<commit_before>/* snesasm

nicklausw's attempt at a portable
snes assembler

licensed under the isc license. you
should have gotten a copy with snesasm,
if not then visit http://nicklausw.github.io/isc.txt

enjoy. */

#include <iostream> // basics
#include <fstream> // io
#include <string> // string
#include <sstream> // file streams
#include <vector> // vectors
#include <cctype> // char checks
#include <cstdlib> // exit
using namespace std; // print

// definitions
#define success 0
#define fail 1

// default to lorom
#define lorom 0
#define hirom 1

// current pass defines
#define p1 0
#define p2 1

// function declarations
void help(string prog_name); // help message
int snesasm(string in, string out); // the true main function
bool file_existent(string name); // file existence check
void file_to_string(string file); // speaks for itself
int lexer(); // the wonderful lexer magic
int append_token(unsigned int counter, int current_token); // add token to string
int pass(string out); // pass function
int hint_next_token_type(unsigned int counter, string cur); // speaks for itself
string hint_next_token_dat(unsigned int counter, string cur); // same
int one_numeric_arg(string str, unsigned int counter, int range); // directives with one number arg
long parse_num(string num); // number parse
string str_tolower(string str); // lower all caps in string

// token struct
typedef struct {
    int token_type; // type
    string token_i; // internals
} token;

// tokens vector
vector<token> tokens;

// token types
int tkUNDEF = 0; // fail
int tkNUM = 1; // number
int tkDIR = 2; // directive
int tkOP = 3; // opcode

// ranges
int rNONE = 0;
int r8 = 1;
int r16 = 2;
int r24 = 3;

string ins; // universal file string

// snes variables
bool compcheck_flag = false;
bool autoromsize_flag = false;
int romsize = 0;
int carttype = 0;
int licenseecode = 0;
int version = 0;
int lohirom = lorom;
int rombanks = 0;
long banksize = 0;

// temporary transfer variable
long tr = 0;

// pass variable
int cur_pass = p1;

int main(int argc, char **argv)
{
    // args!
    if (argc != 3) {
        help(argv[0]);
        return fail;
    }

    // hand it all off to snesasm()
    if (snesasm(string(argv[1]), string(argv[2])) == fail) return fail;
    return success;
}

void help(string prog_name)
{
    cerr << "snesasm by nicklausw\n";
    cerr << "args: " << prog_name << " [in file] [out file]\n";
}

int snesasm(string in, string out)
{
    if (file_existent(in) == false) {
        cerr << "error: file " << in << " doesn't exist\n";
        return fail;
    }

    file_to_string(in); // read file
    if (lexer() == fail) return fail; // lexer magic
    if (pass(out) == fail) return fail; // pass 1
    cur_pass = p2; if (pass(out) == fail) return fail; // pass 2

    return success;
}

bool file_existent(string name)
{
    ifstream file(name.c_str());
    return file.good();
}

void file_to_string(string file)
{
    ifstream in(file.c_str()); // file stream
    string str; // temporary build-up string
    char in_c; // char for comparison
    unsigned int counter = 0; // basic counter

    // clear ins
    ins.clear();

    // read into new_str converting tabs to spaces
    while (!in.eof()) {
        in.get(in_c);
        if (in_c == '\t') {
            ins.append(" ");
        } else {
            ins.append(string(1, in_c));
        }
    }

    str = ins;

    // simplify multiple spaces to one space
    ins.clear();

    while (counter <= str.length()) {
        if (str[counter] == ' ') {
            ins.append(" ");
            while (str[counter] == ' ') {
                counter++;
                if (counter == str.length())
                    break;
            }
        } else {
            ins.append(string(1, str[counter]));
            counter++;
        }
    }

    // do same to remove comments
    ins.clear();
    counter = 0;

    while (counter <= str.length()) {
        if (str[counter] == ';') {
            ins.append("\n");
            while (str[counter] != '\n') {
                counter++;
                if (counter == str.length())
                    break;
            }
        } else {
            ins.append(string(1, str[counter]));
            counter++;
        }
    }
}

int lexer()
{
    // the crazy part, tokens
    unsigned int counter = 0; // counter again
    int current_token = 0; // vector location value
    bool ct_used = false; // current token usage

    // we need the token vector big enough
    // for the first token, obviously
    tokens.resize(1);

    while (counter < ins.length()) {
        // handle newlines
        if (ins[counter] == '\n' || ins[counter] == ' ') {
            if (ct_used == false) {
                counter++;
                continue;
            } else {
                // handle vector size
                tokens.resize((current_token+1)*sizeof(token));

                // get ready for another loop
                ct_used = false;
                counter++;
                current_token++;
                continue;
            }
        }

        // no newline means do a token

        if (ins[counter] == '.') {
            // directive
            ct_used = true;
            tokens[current_token].token_type = tkDIR;
            counter++; // skip period

            counter = append_token(counter, current_token);

            // no case sensitivity
            tokens[current_token].token_i = str_tolower(tokens[current_token].token_i);

            // no need for a counter++ here, it's handled above.
            continue;
        } else if (isalpha(ins[counter])) {
            // opcode
            ct_used = true;
            tokens[current_token].token_type = tkOP;

            counter = append_token(counter, current_token);

            // no need for a counter++ here, it's handled above.
            continue;
        } else if (isdigit(ins[counter]) || ins[counter] == '$' || ins[counter] == '%') {
            // number
            ct_used = true;
            tokens[current_token].token_type = tkNUM;

            counter = append_token(counter, current_token);

            // no case sensitivity
            tokens[current_token].token_i = str_tolower(tokens[current_token].token_i);

            // no need for a counter++ here, it's handled above.
            continue;
        } else {
            // unknown
            ct_used = true;
            tokens[current_token].token_type = tkUNDEF;

            counter = append_token(counter, current_token);

            // no need for a counter++ here, it's handled above.
            continue;
        }

        // be sure to move on to next symbol.
        counter++;
    }

    return success;
}

int append_token(unsigned int counter, int current_token)
{
    while (ins[counter] != ' ' && ins[counter] != '\n') {
                if (counter == ins.length())
                    break; // no overflows please!
                tokens[current_token].token_i.append(string(1, ins[counter]));
                counter++;
    }

    return counter;
}

int pass(string out)
{
    if (cur_pass == p2) {
        // file stuff, yay
        ofstream outs;
        outs.open(out);
    }

    for (unsigned int counter = 0; counter < (tokens.size())/sizeof(token); counter++) {
        if (tokens[counter].token_type == tkDIR) {
            if (tokens[counter].token_i == "compcheck") {
                compcheck_flag = true;
            } else if (tokens[counter].token_i == "autoromsize") {
                autoromsize_flag = true;
            } else if (tokens[counter].token_i == "romsize") {
                counter = one_numeric_arg("romsize", counter, r8); romsize = tr;
            } else if (tokens[counter].token_i == "carttype") {
                counter = one_numeric_arg("carttype", counter, r8); carttype = tr;
            } else if (tokens[counter].token_i == "licenseecode") {
                counter = one_numeric_arg("licenseecode", counter, r8); licenseecode = tr;
            } else if (tokens[counter].token_i == "version") {
                counter = one_numeric_arg("version", counter, r8); version = tr;
            } else if (tokens[counter].token_i == "banksize") {
                counter = one_numeric_arg("banksize", counter, r16); banksize = tr;
            } else if (tokens[counter].token_i == "rombanks") {
                // not sure about rombanks limit
                counter = one_numeric_arg("banksize", counter, rNONE); rombanks = tr;
            } else if (tokens[counter].token_i == "lorom") {
                lohirom = lorom;
            } else if (tokens[counter].token_i == "hirom") {
                lohirom = hirom;
            } else {
                cout << "error: unknown directive \"" << tokens[counter].token_i << "\"\n";
                return fail;
            }
        } else if (tokens[counter].token_type == tkNUM) {
            cerr << "error: loose num " << tokens[counter].token_i << '\n';
            return fail;
        } else if (tokens[counter].token_type == tkOP) {
            cerr << "error: opcodes aren't implemented yet, sorry.\n";
            return fail;
        } else {
            cerr << "error: unknown symbol \"" << tokens[counter].token_i << "\"\n";
            return fail;
        }
    }

    return success;
}

int hint_next_token_type(unsigned int counter, string cur)
{
    if (counter >= tokens.size()) {
        cerr << "error: " << cur << " requires args\n";
        exit(fail);
    }

    return tokens[counter+1].token_type;
}

string hint_next_token_dat(unsigned int counter, string cur)
{
    if (counter >= tokens.size()) {
        cerr << "error: " << cur << " requires args\n";
        exit(fail);
    }

    return tokens[counter+1].token_i;
}

int one_numeric_arg(string str, unsigned int counter, int range)
{
    if (hint_next_token_type(counter, tokens[counter].token_i) != tkNUM) {
        cerr << "error: " << str << " expects numeric args\n";
        exit(fail);
    } else {
        tr = parse_num(hint_next_token_dat(counter, tokens[counter].token_i));

        if (range == r8) {
            if (tr > 0xFF) {
                cerr << "error: " << str << " requires 8-bit args\n";
                exit(fail);
            }
        } else if (range == r16) {
            if (tr > 0xFFFF) {
                cerr << "error: " << str << " requires 16-bit args\n";
                exit(fail);
            }
        }

        counter++;
    }

    return counter;
}

long parse_num(string num)
{
    string without_sym = num; // declare without symbol

    // make 'without symbol' true
    if (!isdigit(without_sym[0])) {
        without_sym.erase(without_sym.begin());
    }

    // check for invalid symbols
    for (unsigned int checkn = 0; checkn < without_sym.length(); checkn++) {
        if (isdigit(without_sym[checkn])) continue;

        // not a digit...
        if (num[0] != '$') {
            cerr << "error: invalid symbol in number\n";
            exit(fail);
        } else {
            switch (without_sym[checkn]) {
                case 'a': continue;
                case 'b': continue;
                case 'c': continue;
                case 'd': continue;
                case 'e': continue;
                case 'f': continue;
                default:
                    // invalid symbol
                    cerr << "error: invalid symbol in number\n";
                    exit(fail);
            }
        }
    }

    char *chararray = const_cast<char*>(without_sym.c_str()); // turn without_sym into char array

    switch (num[0]) {
        case '%':
            // binary
            return strtol(chararray, &chararray, 2);
        case '$':
            // hex
            return strtol(chararray, &chararray, 16);
    }

    return strtol(chararray, &chararray, 10);
}

string str_tolower(string str)
{
    for (unsigned int counter = 0; counter < str.length(); counter++) {
        if (isalpha(str[counter])) {
            str[counter] = tolower(str[counter]);
        }
    }

    return str;
}
<commit_msg>single-pass, fill up rom<commit_after>/* snesasm

nicklausw's attempt at a portable
snes assembler

licensed under the isc license. you
should have gotten a copy with snesasm,
if not then visit http://nicklausw.github.io/isc.txt

enjoy. */

#include <iostream> // basics
#include <fstream> // io
#include <string> // string
#include <sstream> // file streams
#include <vector> // vectors
#include <cctype> // char checks
#include <cstdlib> // exit
using namespace std; // print

// definitions
#define success 0
#define fail 1

// default to lorom
#define lorom 0
#define hirom 1

// function declarations
void help(string prog_name); // help message
int snesasm(string in, string out); // the true main function
bool file_existent(string name); // file existence check
void file_to_string(string file); // speaks for itself
int lexer(); // the wonderful lexer magic
int append_token(unsigned int counter, int current_token); // add token to string
int pass(string out); // pass function
int hint_next_token_type(unsigned int counter, string cur); // speaks for itself
string hint_next_token_dat(unsigned int counter, string cur); // same
int one_numeric_arg(string str, unsigned int counter, int range); // directives with one number arg
long parse_num(string num); // number parse
string str_tolower(string str); // lower all caps in string

// token struct
typedef struct {
    int token_type; // type
    string token_i; // internals
} token;

// tokens vector
vector<token> tokens;

// token types
int tkUNDEF = 0; // fail
int tkNUM = 1; // number
int tkDIR = 2; // directive
int tkOP = 3; // opcode

// ranges
int rNONE = 0;
int r8 = 1;
int r16 = 2;
int r24 = 3;

string ins; // universal file string

// snes variables
bool compcheck_flag = false;
bool autoromsize_flag = false;
int romsize = 0;
int carttype = 0;
int licenseecode = 0;
int version = 0;
int lohirom = lorom;
int rombanks = 0;
long banksize = 0;

// temporary transfer variable
long tr = 0;

int main(int argc, char **argv)
{
    // args!
    if (argc != 3) {
        help(argv[0]);
        return fail;
    }

    // hand it all off to snesasm()
    if (snesasm(string(argv[1]), string(argv[2])) == fail) return fail;
    return success;
}

void help(string prog_name)
{
    cerr << "snesasm by nicklausw\n";
    cerr << "args: " << prog_name << " [in file] [out file]\n";
}

int snesasm(string in, string out)
{
    if (file_existent(in) == false) {
        cerr << "error: file " << in << " doesn't exist\n";
        return fail;
    }

    file_to_string(in); // read file
    if (lexer() == fail) return fail; // lexer magic
    if (pass(out) == fail) return fail; // pass

    return success;
}

bool file_existent(string name)
{
    ifstream file(name.c_str());
    return file.good();
}

void file_to_string(string file)
{
    ifstream in(file.c_str()); // file stream
    string str; // temporary build-up string
    char in_c; // char for comparison
    unsigned int counter = 0; // basic counter

    // clear ins
    ins.clear();

    // read into new_str converting tabs to spaces
    while (!in.eof()) {
        in.get(in_c);
        if (in_c == '\t') {
            ins.append(" ");
        } else {
            ins.append(string(1, in_c));
        }
    }

    str = ins;

    // simplify multiple spaces to one space
    ins.clear();

    while (counter <= str.length()) {
        if (str[counter] == ' ') {
            ins.append(" ");
            while (str[counter] == ' ') {
                counter++;
                if (counter == str.length())
                    break;
            }
        } else {
            ins.append(string(1, str[counter]));
            counter++;
        }
    }

    // do same to remove comments
    ins.clear();
    counter = 0;

    while (counter <= str.length()) {
        if (str[counter] == ';') {
            ins.append("\n");
            while (str[counter] != '\n') {
                counter++;
                if (counter == str.length())
                    break;
            }
        } else {
            ins.append(string(1, str[counter]));
            counter++;
        }
    }
}

int lexer()
{
    // the crazy part, tokens
    unsigned int counter = 0; // counter again
    int current_token = 0; // vector location value
    bool ct_used = false; // current token usage

    // we need the token vector big enough
    // for the first token, obviously
    tokens.resize(1);

    while (counter < ins.length()) {
        // handle newlines
        if (ins[counter] == '\n' || ins[counter] == ' ') {
            if (ct_used == false) {
                counter++;
                continue;
            } else {
                // handle vector size
                tokens.resize((current_token+1)*sizeof(token));

                // get ready for another loop
                ct_used = false;
                counter++;
                current_token++;
                continue;
            }
        }

        // no newline means do a token

        if (ins[counter] == '.') {
            // directive
            ct_used = true;
            tokens[current_token].token_type = tkDIR;
            counter++; // skip period

            counter = append_token(counter, current_token);

            // no case sensitivity
            tokens[current_token].token_i = str_tolower(tokens[current_token].token_i);

            // no need for a counter++ here, it's handled above.
            continue;
        } else if (isalpha(ins[counter])) {
            // opcode
            ct_used = true;
            tokens[current_token].token_type = tkOP;

            counter = append_token(counter, current_token);

            // no need for a counter++ here, it's handled above.
            continue;
        } else if (isdigit(ins[counter]) || ins[counter] == '$' || ins[counter] == '%') {
            // number
            ct_used = true;
            tokens[current_token].token_type = tkNUM;

            counter = append_token(counter, current_token);

            // no case sensitivity
            tokens[current_token].token_i = str_tolower(tokens[current_token].token_i);

            // no need for a counter++ here, it's handled above.
            continue;
        } else {
            // unknown
            ct_used = true;
            tokens[current_token].token_type = tkUNDEF;

            counter = append_token(counter, current_token);

            // no need for a counter++ here, it's handled above.
            continue;
        }

        // be sure to move on to next symbol.
        counter++;
    }

    return success;
}

int append_token(unsigned int counter, int current_token)
{
    while (ins[counter] != ' ' && ins[counter] != '\n') {
                if (counter == ins.length())
                    break; // no overflows please!
                tokens[current_token].token_i.append(string(1, ins[counter]));
                counter++;
    }

    return counter;
}

int pass(string out)
{
    // file stuff, yay
    ofstream outs;
    outs.open(out);

    for (unsigned int counter = 0; counter < (tokens.size())/sizeof(token); counter++) {
        if (tokens[counter].token_type == tkDIR) {
            if (tokens[counter].token_i == "compcheck") {
                compcheck_flag = true;
            } else if (tokens[counter].token_i == "autoromsize") {
                autoromsize_flag = true;
            } else if (tokens[counter].token_i == "romsize") {
                counter = one_numeric_arg("romsize", counter, r8); romsize = tr;
            } else if (tokens[counter].token_i == "carttype") {
                counter = one_numeric_arg("carttype", counter, r8); carttype = tr;
            } else if (tokens[counter].token_i == "licenseecode") {
                counter = one_numeric_arg("licenseecode", counter, r8); licenseecode = tr;
            } else if (tokens[counter].token_i == "version") {
                counter = one_numeric_arg("version", counter, r8); version = tr;
            } else if (tokens[counter].token_i == "banksize") {
                counter = one_numeric_arg("banksize", counter, r16); banksize = tr;

                if (rombanks != 0) {
                    // go ahead and set size of output
                    char *fill_array = new char[rombanks*banksize];
                    outs.write(fill_array, rombanks*banksize);
                }
            } else if (tokens[counter].token_i == "rombanks") {
                // not sure about rombanks limit
                counter = one_numeric_arg("rombanks", counter, rNONE); rombanks = tr;

                if (banksize != 0) {
                    // go ahead and set size of output
                    char *fill_array = new char[rombanks*banksize];
                    outs.write(fill_array, rombanks*banksize);
                }
            } else if (tokens[counter].token_i == "lorom") {
                lohirom = lorom;
            } else if (tokens[counter].token_i == "hirom") {
                lohirom = hirom;
            } else {
                cout << "error: unknown directive \"" << tokens[counter].token_i << "\"\n";
                return fail;
            }
        } else if (tokens[counter].token_type == tkNUM) {
            cerr << "error: loose num " << tokens[counter].token_i << '\n';
            return fail;
        } else if (tokens[counter].token_type == tkOP) {
            cerr << "error: opcodes aren't implemented yet, sorry.\n";
            return fail;
        } else {
            cerr << "error: unknown symbol \"" << tokens[counter].token_i << "\"\n";
            return fail;
        }
    }

    return success;
}

int hint_next_token_type(unsigned int counter, string cur)
{
    if (counter >= tokens.size()) {
        cerr << "error: " << cur << " requires args\n";
        exit(fail);
    }

    return tokens[counter+1].token_type;
}

string hint_next_token_dat(unsigned int counter, string cur)
{
    if (counter >= tokens.size()) {
        cerr << "error: " << cur << " requires args\n";
        exit(fail);
    }

    return tokens[counter+1].token_i;
}

int one_numeric_arg(string str, unsigned int counter, int range)
{
    if (hint_next_token_type(counter, tokens[counter].token_i) != tkNUM) {
        cerr << "error: " << str << " expects numeric args\n";
        exit(fail);
    } else {
        tr = parse_num(hint_next_token_dat(counter, tokens[counter].token_i));

        if (range == r8) {
            if (tr > 0xFF) {
                cerr << "error: " << str << " requires 8-bit args\n";
                exit(fail);
            }
        } else if (range == r16) {
            if (tr > 0xFFFF) {
                cerr << "error: " << str << " requires 16-bit args\n";
                exit(fail);
            }
        }

        counter++;
    }

    return counter;
}

long parse_num(string num)
{
    string without_sym = num; // declare without symbol

    // make 'without symbol' true
    if (!isdigit(without_sym[0])) {
        without_sym.erase(without_sym.begin());
    }

    // check for invalid symbols
    for (unsigned int checkn = 0; checkn < without_sym.length(); checkn++) {
        if (isdigit(without_sym[checkn])) continue;

        // not a digit...
        if (num[0] != '$') {
            cerr << "error: invalid symbol in number\n";
            exit(fail);
        } else {
            switch (without_sym[checkn]) {
                case 'a': continue;
                case 'b': continue;
                case 'c': continue;
                case 'd': continue;
                case 'e': continue;
                case 'f': continue;
                default:
                    // invalid symbol
                    cerr << "error: invalid symbol in number\n";
                    exit(fail);
            }
        }
    }

    char *chararray = const_cast<char*>(without_sym.c_str()); // turn without_sym into char array

    switch (num[0]) {
        case '%':
            // binary
            return strtol(chararray, &chararray, 2);
        case '$':
            // hex
            return strtol(chararray, &chararray, 16);
    }

    return strtol(chararray, &chararray, 10);
}

string str_tolower(string str)
{
    for (unsigned int counter = 0; counter < str.length(); counter++) {
        if (isalpha(str[counter])) {
            str[counter] = tolower(str[counter]);
        }
    }

    return str;
}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <iostream>

namespace {

class OpenMeshVectorTest : public testing::Test {

    protected:

        // This function is called before each test is run
        virtual void SetUp() {

            // Do some initial stuff with the member data here...
        }

        // This function is called after all tests are through
        virtual void TearDown() {

            // Do some final stuff with the member data here...
        }

};

/*
 * ====================================================================
 * Define tests below
 * ====================================================================
 */

/* Compute surface area via cross product
 */
TEST_F(OpenMeshVectorTest, ComputeTriangleSurfaceWithCrossProduct) {

  //
  // vec1
  //  x
  //  |
  //  |
  //  |
  //  x------>x vec2
  //

  OpenMesh::Vec3d vec1(0.0,1.0,0.0);
  OpenMesh::Vec3d vec2(1.0,0.0,0.0);

  double area = 0.5 * cross(vec1,vec2).norm();
  EXPECT_EQ(0.5f , area ) << "Wrong area in cross product function";

  area = 0.5 * ( vec1 % vec2 ).norm();
  EXPECT_EQ(0.5f , area ) << "Wrong area in cross product operator";

}

/* Check OpenMesh Vector type abs function
 */
TEST_F(OpenMeshVectorTest, AbsTest) {

  OpenMesh::Vec3d vec1(0.5,0.5,-0.5);

  EXPECT_EQ( vec1.l8_norm() , 0.5f ) << "Wrong l8norm computation";

}

/* Compute surface area via cross product
 */
TEST_F(OpenMeshVectorTest, VectorCasting) {

  OpenMesh::Vec3d vecd(1.0,2.0,3.0);
  OpenMesh::Vec3f vecf = OpenMesh::vector_cast<OpenMesh::Vec3f>(vecd);
  EXPECT_EQ(1.f, vecf[0]) << "vector type cast failed on component 0";
  EXPECT_EQ(2.f, vecf[1]) << "vector type cast failed on component 1";
  EXPECT_EQ(3.f, vecf[2]) << "vector type cast failed on component 2";

  OpenMesh::Vec4d vecd4(40.0,30.0,20.0,10.0);
  vecd = OpenMesh::vector_cast<OpenMesh::Vec3d>(vecd4);
  EXPECT_EQ(40.0, vecd[0]) << "vector dimension cast failed on component 0";
  EXPECT_EQ(30.0, vecd[1]) << "vector dimension cast failed on component 1";
  EXPECT_EQ(20.0, vecd[2]) << "vector dimension cast failed on component 2";

}

#if __cplusplus > 199711L || defined(__GXX_EXPERIMENTAL_CXX0X__)
TEST_F(OpenMeshVectorTest, cpp11_constructors) {
    OpenMesh::Vec3d vec1 { 1.2, 2.0, 3.0 };

    EXPECT_EQ(1.2, vec1[0]);
    EXPECT_EQ(2.0, vec1[1]);
    EXPECT_EQ(3.0, vec1[2]);

    OpenMesh::Vec4f vec2 { 1.2f, 3.5f, 1.0f, 0.0f };

    EXPECT_EQ(1.2f, vec2[0]);
    EXPECT_EQ(3.5f, vec2[1]);
    EXPECT_EQ(1.0f, vec2[2]);
    EXPECT_EQ(0.0f, vec2[3]);

    OpenMesh::Vec4f vec2b { vec2 };

    EXPECT_EQ(1.2f, vec2b[0]);
    EXPECT_EQ(3.5f, vec2b[1]);
    EXPECT_EQ(1.0f, vec2b[2]);
    EXPECT_EQ(0.0f, vec2b[3]);

    OpenMesh::Vec4d vec4d { 1.23 };
    EXPECT_EQ(1.23, vec4d[0]);
    EXPECT_EQ(1.23, vec4d[1]);
    EXPECT_EQ(1.23, vec4d[2]);
    EXPECT_EQ(1.23, vec4d[3]);
}

TEST_F(OpenMeshVectorTest, cpp11_htmlColorLiteral) {
    static constexpr OpenMesh::Vec4f rose = 0xFFC7F1FF_htmlColor;

    const OpenMesh::Vec4f light_blue = 0x1FCFFFFF_htmlColor;
    EXPECT_LE((OpenMesh::Vec4f(0.1215686274f, 0.8117647058f, 1.0f, 1.0f)
        - light_blue).sqrnorm(), 1e-10);

    const auto light_blue_2 = 0x1FCFFFFF_htmlColor;
    // Check whether auto type deduction works as expected.
    static_assert(std::is_same<decltype(light_blue_2), decltype(light_blue)>
        ::value, "Bad type deduced from _htmlColor literal.");
    EXPECT_EQ(light_blue, light_blue_2);
}
#endif

TEST_F(OpenMeshVectorTest, BasicLinearAlgebra) {
    OpenMesh::Vec3d v(1, 2, 3);
    EXPECT_EQ(v[0], 1.0);
    EXPECT_EQ(v[1], 2.0);
    EXPECT_EQ(v[2], 3.0);

    EXPECT_EQ(OpenMesh::Vec3d(-1, -2, -3), -v);
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, 2).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 2, 3).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, -4).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(-4, 2, 3).max());
    EXPECT_EQ(4, OpenMesh::Vec3d(1, 3, -4).max_abs());
    EXPECT_EQ(4, OpenMesh::Vec3d(-4, 2, 3).max_abs());

    EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, 2).min());
    EXPECT_EQ(1, OpenMesh::Vec3d(1, 2, 3).min());
    EXPECT_EQ(-4, OpenMesh::Vec3d(1, 3, -4).min());
    EXPECT_EQ(-4, OpenMesh::Vec3d(-4, 2, 3).min());
    EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, -4).min_abs());
    EXPECT_EQ(2, OpenMesh::Vec3d(-4, 2, 3).min_abs());

    EXPECT_NEAR(14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(1, 2, 3), 1e-6);
    EXPECT_NEAR(-14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6);
    EXPECT_NEAR(14, OpenMesh::Vec3d(-1, -2, -3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6);
}

TEST_F(OpenMeshVectorTest, normalized_cond) {
    OpenMesh::Vec3d v1(1, -2, 3), v2(0, 0, 0);
    EXPECT_EQ(OpenMesh::Vec3d(0, 0, 0), v2.normalize_cond());
    const auto r1 = OpenMesh::Vec3d(0.2672612419124244, -0.5345224838248488, 0.8017837257372732) - v1.normalize_cond();
    EXPECT_NEAR(r1[0], 0.0, 1e-12);
    EXPECT_NEAR(r1[1], 0.0, 1e-12);
    EXPECT_NEAR(r1[2], 0.0, 1e-12);
}

TEST_F(OpenMeshVectorTest, size_dim) {
    OpenMesh::Vec3d v3d(1, 2, 3);
    OpenMesh::Vec3f v3f(1, 2, 3);
    OpenMesh::Vec2i v2i(1, 2);

    EXPECT_EQ(3u, v3d.size());
    EXPECT_EQ(3, v3d.dim());
    EXPECT_EQ(3u, v3f.size());
    EXPECT_EQ(3, v3f.dim());
    EXPECT_EQ(2u, v2i.size());
    EXPECT_EQ(2, v2i.dim());
}

namespace {
class C {
    public:
        C() {}
        C(const C &rhs) { ADD_FAILURE() << "Copy constructor used."; }
        C(C &&rhs) { ++copy_con; }
        C &operator= (const C &rhs) {
            ADD_FAILURE() << "Copy assignemnt used.";
            return *this;
        }
        C &operator= (C &&rhs) { ++copy_ass; return *this; }

        static int copy_con;
        static int copy_ass;
};

int C::copy_con = 0;
int C::copy_ass = 0;
}

/**
 * Checks two things:
 *   1) Whether VectorT works with a non-arithmetic type.
 *   2) Whether move construction and assignment works.
 */
TEST_F(OpenMeshVectorTest, move_constructor_assignment) {

    C::copy_con = 0;
    C::copy_ass = 0;

    // Test move assigning.
    OpenMesh::VectorT<C, 3> x, y;
    x = std::move(y);
    EXPECT_EQ(3, C::copy_ass);
    EXPECT_EQ(0, C::copy_con);

    // Test move constructing.
    OpenMesh::VectorT<C, 3> z(std::move(x));
    EXPECT_EQ(3, C::copy_ass);
    EXPECT_EQ(3, C::copy_con);
}

}
<commit_msg>Purged another warning in unit tests.<commit_after>#include <gtest/gtest.h>
#include <Unittests/unittests_common.hh>
#include <iostream>

namespace {

class OpenMeshVectorTest : public testing::Test {

    protected:

        // This function is called before each test is run
        virtual void SetUp() {

            // Do some initial stuff with the member data here...
        }

        // This function is called after all tests are through
        virtual void TearDown() {

            // Do some final stuff with the member data here...
        }

};

/*
 * ====================================================================
 * Define tests below
 * ====================================================================
 */

/* Compute surface area via cross product
 */
TEST_F(OpenMeshVectorTest, ComputeTriangleSurfaceWithCrossProduct) {

  //
  // vec1
  //  x
  //  |
  //  |
  //  |
  //  x------>x vec2
  //

  OpenMesh::Vec3d vec1(0.0,1.0,0.0);
  OpenMesh::Vec3d vec2(1.0,0.0,0.0);

  double area = 0.5 * cross(vec1,vec2).norm();
  EXPECT_EQ(0.5f , area ) << "Wrong area in cross product function";

  area = 0.5 * ( vec1 % vec2 ).norm();
  EXPECT_EQ(0.5f , area ) << "Wrong area in cross product operator";

}

/* Check OpenMesh Vector type abs function
 */
TEST_F(OpenMeshVectorTest, AbsTest) {

  OpenMesh::Vec3d vec1(0.5,0.5,-0.5);

  EXPECT_EQ( vec1.l8_norm() , 0.5f ) << "Wrong l8norm computation";

}

/* Compute surface area via cross product
 */
TEST_F(OpenMeshVectorTest, VectorCasting) {

  OpenMesh::Vec3d vecd(1.0,2.0,3.0);
  OpenMesh::Vec3f vecf = OpenMesh::vector_cast<OpenMesh::Vec3f>(vecd);
  EXPECT_EQ(1.f, vecf[0]) << "vector type cast failed on component 0";
  EXPECT_EQ(2.f, vecf[1]) << "vector type cast failed on component 1";
  EXPECT_EQ(3.f, vecf[2]) << "vector type cast failed on component 2";

  OpenMesh::Vec4d vecd4(40.0,30.0,20.0,10.0);
  vecd = OpenMesh::vector_cast<OpenMesh::Vec3d>(vecd4);
  EXPECT_EQ(40.0, vecd[0]) << "vector dimension cast failed on component 0";
  EXPECT_EQ(30.0, vecd[1]) << "vector dimension cast failed on component 1";
  EXPECT_EQ(20.0, vecd[2]) << "vector dimension cast failed on component 2";

}

#if __cplusplus > 199711L || defined(__GXX_EXPERIMENTAL_CXX0X__)
TEST_F(OpenMeshVectorTest, cpp11_constructors) {
    OpenMesh::Vec3d vec1 { 1.2, 2.0, 3.0 };

    EXPECT_EQ(1.2, vec1[0]);
    EXPECT_EQ(2.0, vec1[1]);
    EXPECT_EQ(3.0, vec1[2]);

    OpenMesh::Vec4f vec2 { 1.2f, 3.5f, 1.0f, 0.0f };

    EXPECT_EQ(1.2f, vec2[0]);
    EXPECT_EQ(3.5f, vec2[1]);
    EXPECT_EQ(1.0f, vec2[2]);
    EXPECT_EQ(0.0f, vec2[3]);

    OpenMesh::Vec4f vec2b { vec2 };

    EXPECT_EQ(1.2f, vec2b[0]);
    EXPECT_EQ(3.5f, vec2b[1]);
    EXPECT_EQ(1.0f, vec2b[2]);
    EXPECT_EQ(0.0f, vec2b[3]);

    OpenMesh::Vec4d vec4d { 1.23 };
    EXPECT_EQ(1.23, vec4d[0]);
    EXPECT_EQ(1.23, vec4d[1]);
    EXPECT_EQ(1.23, vec4d[2]);
    EXPECT_EQ(1.23, vec4d[3]);
}

TEST_F(OpenMeshVectorTest, cpp11_htmlColorLiteral) {
    static constexpr OpenMesh::Vec4f rose = 0xFFC7F1FF_htmlColor;

    EXPECT_EQ(0xFFC7F1FF_htmlColor, rose);

    const OpenMesh::Vec4f light_blue = 0x1FCFFFFF_htmlColor;
    EXPECT_LE((OpenMesh::Vec4f(0.1215686274f, 0.8117647058f, 1.0f, 1.0f)
        - light_blue).sqrnorm(), 1e-10);

    const auto light_blue_2 = 0x1FCFFFFF_htmlColor;
    // Check whether auto type deduction works as expected.
    static_assert(std::is_same<decltype(light_blue_2), decltype(light_blue)>
        ::value, "Bad type deduced from _htmlColor literal.");
    EXPECT_EQ(light_blue, light_blue_2);
}
#endif

TEST_F(OpenMeshVectorTest, BasicLinearAlgebra) {
    OpenMesh::Vec3d v(1, 2, 3);
    EXPECT_EQ(v[0], 1.0);
    EXPECT_EQ(v[1], 2.0);
    EXPECT_EQ(v[2], 3.0);

    EXPECT_EQ(OpenMesh::Vec3d(-1, -2, -3), -v);
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, 2).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 2, 3).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(1, 3, -4).max());
    EXPECT_EQ(3, OpenMesh::Vec3d(-4, 2, 3).max());
    EXPECT_EQ(4, OpenMesh::Vec3d(1, 3, -4).max_abs());
    EXPECT_EQ(4, OpenMesh::Vec3d(-4, 2, 3).max_abs());

    EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, 2).min());
    EXPECT_EQ(1, OpenMesh::Vec3d(1, 2, 3).min());
    EXPECT_EQ(-4, OpenMesh::Vec3d(1, 3, -4).min());
    EXPECT_EQ(-4, OpenMesh::Vec3d(-4, 2, 3).min());
    EXPECT_EQ(1, OpenMesh::Vec3d(1, 3, -4).min_abs());
    EXPECT_EQ(2, OpenMesh::Vec3d(-4, 2, 3).min_abs());

    EXPECT_NEAR(14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(1, 2, 3), 1e-6);
    EXPECT_NEAR(-14, OpenMesh::Vec3d(1, 2, 3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6);
    EXPECT_NEAR(14, OpenMesh::Vec3d(-1, -2, -3) | OpenMesh::Vec3d(-1, -2, -3), 1e-6);
}

TEST_F(OpenMeshVectorTest, normalized_cond) {
    OpenMesh::Vec3d v1(1, -2, 3), v2(0, 0, 0);
    EXPECT_EQ(OpenMesh::Vec3d(0, 0, 0), v2.normalize_cond());
    const auto r1 = OpenMesh::Vec3d(0.2672612419124244, -0.5345224838248488, 0.8017837257372732) - v1.normalize_cond();
    EXPECT_NEAR(r1[0], 0.0, 1e-12);
    EXPECT_NEAR(r1[1], 0.0, 1e-12);
    EXPECT_NEAR(r1[2], 0.0, 1e-12);
}

TEST_F(OpenMeshVectorTest, size_dim) {
    OpenMesh::Vec3d v3d(1, 2, 3);
    OpenMesh::Vec3f v3f(1, 2, 3);
    OpenMesh::Vec2i v2i(1, 2);

    EXPECT_EQ(3u, v3d.size());
    EXPECT_EQ(3, v3d.dim());
    EXPECT_EQ(3u, v3f.size());
    EXPECT_EQ(3, v3f.dim());
    EXPECT_EQ(2u, v2i.size());
    EXPECT_EQ(2, v2i.dim());
}

namespace {
class C {
    public:
        C() {}
        C(const C &rhs) { ADD_FAILURE() << "Copy constructor used."; }
        C(C &&rhs) { ++copy_con; }
        C &operator= (const C &rhs) {
            ADD_FAILURE() << "Copy assignemnt used.";
            return *this;
        }
        C &operator= (C &&rhs) { ++copy_ass; return *this; }

        static int copy_con;
        static int copy_ass;
};

int C::copy_con = 0;
int C::copy_ass = 0;
}

/**
 * Checks two things:
 *   1) Whether VectorT works with a non-arithmetic type.
 *   2) Whether move construction and assignment works.
 */
TEST_F(OpenMeshVectorTest, move_constructor_assignment) {

    C::copy_con = 0;
    C::copy_ass = 0;

    // Test move assigning.
    OpenMesh::VectorT<C, 3> x, y;
    x = std::move(y);
    EXPECT_EQ(3, C::copy_ass);
    EXPECT_EQ(0, C::copy_con);

    // Test move constructing.
    OpenMesh::VectorT<C, 3> z(std::move(x));
    EXPECT_EQ(3, C::copy_ass);
    EXPECT_EQ(3, C::copy_con);
}

}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>

#include <fstream>
#include <iostream>
#include <memory>
#include <string>

#include <boost/algorithm/hex.hpp>
#include <boost/filesystem.hpp>

#include "config/config.h"
#include "package_manager/ostreemanager.h"
#include "storage/invstorage.h"
#include "utilities/types.h"
#include "utilities/utils.h"

boost::filesystem::path test_sysroot;

/* Reject bad OSTree server URIs. */
TEST(OstreeManager, PullBadUriNoCreds) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.ostree_server = "bad-url";
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  KeyManager keys(storage, config.keymanagerConfig());
  keys.loadKeys();
  Json::Value target_json_test;
  target_json_test["hashes"]["sha256"] = "some_hash";
  target_json_test["length"] = 0;
  Uptane::Target target_test("test.deb", target_json_test);
  data::InstallationResult result =
      OstreeManager::pull(config.pacman.sysroot, config.pacman.ostree_server, keys, target_test);

  EXPECT_EQ(result.result_code.num_code, data::ResultCode::Numeric::kInstallFailed);
  EXPECT_EQ(result.description, "Failed to parse uri: bad-url");
}

/* Reject bad OSTree server URIs. */
TEST(OstreeManager, PullBadUriWithCreds) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.ostree_server = "bad-url";
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  std::string ca = Utils::readFile("tests/test_data/prov/root.crt");
  std::string pkey = Utils::readFile("tests/test_data/prov/pkey.pem");
  std::string cert = Utils::readFile("tests/test_data/prov/client.pem");
  storage->storeTlsCa(ca);
  storage->storeTlsPkey(pkey);
  storage->storeTlsCert(cert);
  KeyManager keys(storage, config.keymanagerConfig());
  keys.loadKeys();
  Json::Value target_json_test;
  target_json_test["hashes"]["sha256"] = "some_hash";
  target_json_test["length"] = 0;
  Uptane::Target target_test("test.deb", target_json_test);
  data::InstallationResult result =
      OstreeManager::pull(config.pacman.sysroot, config.pacman.ostree_server, keys, target_test);

  EXPECT_EQ(result.result_code.num_code, data::ResultCode::Numeric::kInstallFailed);
  EXPECT_EQ(result.description, "Failed to parse uri: bad-url");
}

/* Reject bad OSTree server URIs. */
TEST(OstreeManager, InstallBadUri) {
  Json::Value target_json;
  target_json["hashes"]["sha256"] = "hash";
  target_json["length"] = 0;
  Uptane::Target target("branch-name-hash", target_json);
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  OstreeManager ostree(config.pacman, storage, nullptr);
  data::InstallationResult result = ostree.install(target);
  EXPECT_EQ(result.result_code.num_code, data::ResultCode::Numeric::kInstallFailed);
  EXPECT_EQ(result.description, "Refspec 'hash' not found");
}

/* Abort if the OSTree sysroot is invalid. */
TEST(OstreeManager, BadSysroot) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = "sysroot-that-is-missing";
  config.storage.path = temp_dir.Path();
  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  EXPECT_THROW(OstreeManager ostree(config.pacman, storage, nullptr), std::runtime_error);
}

/* Parse a provided list of installed packages. */
TEST(OstreeManager, ParseInstalledPackages) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.pacman.packages_file = "tests/test_data/package.manifest";
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  OstreeManager ostree(config.pacman, storage, nullptr);
  Json::Value packages = ostree.getInstalledPackages();
  EXPECT_EQ(packages[0]["name"].asString(), "vim");
  EXPECT_EQ(packages[0]["version"].asString(), "1.0");
  EXPECT_EQ(packages[1]["name"].asString(), "emacs");
  EXPECT_EQ(packages[1]["version"].asString(), "2.0");
  EXPECT_EQ(packages[2]["name"].asString(), "bash");
  EXPECT_EQ(packages[2]["version"].asString(), "1.1");
}

/* Communicate with a remote OSTree server without credentials. */
TEST(OstreeManager, AddRemoteNoCreds) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  KeyManager keys(storage, config.keymanagerConfig());
  keys.loadKeys();

  OstreeRepo *repo = nullptr;
  GError *error = nullptr;
  std::shared_ptr<OstreeSysroot> sysroot = OstreeManager::LoadSysroot(config.pacman.sysroot);
  EXPECT_TRUE(ostree_sysroot_get_repo(sysroot.get(), &repo, nullptr, &error));
  EXPECT_TRUE(OstreeManager::addRemote(repo, config.pacman.ostree_server, keys));

  g_autofree char *url = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "url", nullptr, &url, &error));
  EXPECT_EQ(url, config.pacman.ostree_server);

  gboolean out_gpg_verify;
  EXPECT_TRUE(ostree_repo_get_remote_boolean_option(repo, remote, "gpg-verify", FALSE, &out_gpg_verify, &error));

  g_autofree char *ostree_cert = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-client-cert-path", nullptr, &ostree_cert, &error));
  EXPECT_EQ(ostree_cert, nullptr);

  g_autofree char *ostree_key = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-client-key-path", nullptr, &ostree_key, &error));
  EXPECT_EQ(ostree_key, nullptr);

  g_autofree char *ostree_ca = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-ca-path", nullptr, &ostree_ca, &error));
  EXPECT_EQ(ostree_ca, nullptr);

  g_object_unref(repo);
}

/* Communicate with a remote OSTree server with credentials. */
TEST(OstreeManager, AddRemoteWithCreds) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  std::string ca = Utils::readFile("tests/test_data/prov/root.crt");
  std::string pkey = Utils::readFile("tests/test_data/prov/pkey.pem");
  std::string cert = Utils::readFile("tests/test_data/prov/client.pem");
  storage->storeTlsCa(ca);
  storage->storeTlsPkey(pkey);
  storage->storeTlsCert(cert);
  KeyManager keys(storage, config.keymanagerConfig());
  keys.loadKeys();

  OstreeRepo *repo = nullptr;
  GError *error = nullptr;
  std::shared_ptr<OstreeSysroot> sysroot = OstreeManager::LoadSysroot(config.pacman.sysroot);
  EXPECT_TRUE(ostree_sysroot_get_repo(sysroot.get(), &repo, nullptr, &error));
  EXPECT_TRUE(OstreeManager::addRemote(repo, config.pacman.ostree_server, keys));

  g_autofree char *url = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "url", nullptr, &url, &error));
  EXPECT_EQ(url, config.pacman.ostree_server);

  gboolean out_gpg_verify;
  EXPECT_TRUE(ostree_repo_get_remote_boolean_option(repo, remote, "gpg-verify", FALSE, &out_gpg_verify, &error));

  g_autofree char *ostree_cert = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-client-cert-path", nullptr, &ostree_cert, &error));
  EXPECT_EQ(ostree_cert, keys.getCertFile());

  g_autofree char *ostree_key = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-client-key-path", nullptr, &ostree_key, &error));
  EXPECT_EQ(ostree_key, keys.getPkeyFile());

  g_autofree char *ostree_ca = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-ca-path", nullptr, &ostree_ca, &error));
  EXPECT_EQ(ostree_ca, keys.getCaFile());

  g_object_unref(repo);
}

#ifndef __NO_MAIN__
int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);

  if (argc != 2) {
    std::cerr << "Error: " << argv[0] << " requires the path to an OSTree sysroot as an input argument.\n";
    return EXIT_FAILURE;
  }
  test_sysroot = argv[1];
  return RUN_ALL_TESTS();
}
#endif
<commit_msg>Use a temp copy of sysroot to test ostree<commit_after>#include <gtest/gtest.h>

#include <fstream>
#include <iostream>
#include <memory>
#include <string>

#include <boost/algorithm/hex.hpp>
#include <boost/filesystem.hpp>

#include "config/config.h"
#include "package_manager/ostreemanager.h"
#include "storage/invstorage.h"
#include "utilities/types.h"
#include "utilities/utils.h"

boost::filesystem::path test_sysroot;

/* Reject bad OSTree server URIs. */
TEST(OstreeManager, PullBadUriNoCreds) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.ostree_server = "bad-url";
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  KeyManager keys(storage, config.keymanagerConfig());
  keys.loadKeys();
  Json::Value target_json_test;
  target_json_test["hashes"]["sha256"] = "some_hash";
  target_json_test["length"] = 0;
  Uptane::Target target_test("test.deb", target_json_test);
  data::InstallationResult result =
      OstreeManager::pull(config.pacman.sysroot, config.pacman.ostree_server, keys, target_test);

  EXPECT_EQ(result.result_code.num_code, data::ResultCode::Numeric::kInstallFailed);
  EXPECT_EQ(result.description, "Failed to parse uri: bad-url");
}

/* Reject bad OSTree server URIs. */
TEST(OstreeManager, PullBadUriWithCreds) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.ostree_server = "bad-url";
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  std::string ca = Utils::readFile("tests/test_data/prov/root.crt");
  std::string pkey = Utils::readFile("tests/test_data/prov/pkey.pem");
  std::string cert = Utils::readFile("tests/test_data/prov/client.pem");
  storage->storeTlsCa(ca);
  storage->storeTlsPkey(pkey);
  storage->storeTlsCert(cert);
  KeyManager keys(storage, config.keymanagerConfig());
  keys.loadKeys();
  Json::Value target_json_test;
  target_json_test["hashes"]["sha256"] = "some_hash";
  target_json_test["length"] = 0;
  Uptane::Target target_test("test.deb", target_json_test);
  data::InstallationResult result =
      OstreeManager::pull(config.pacman.sysroot, config.pacman.ostree_server, keys, target_test);

  EXPECT_EQ(result.result_code.num_code, data::ResultCode::Numeric::kInstallFailed);
  EXPECT_EQ(result.description, "Failed to parse uri: bad-url");
}

/* Reject bad OSTree server URIs. */
TEST(OstreeManager, InstallBadUri) {
  Json::Value target_json;
  target_json["hashes"]["sha256"] = "hash";
  target_json["length"] = 0;
  Uptane::Target target("branch-name-hash", target_json);
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  OstreeManager ostree(config.pacman, storage, nullptr);
  data::InstallationResult result = ostree.install(target);
  EXPECT_EQ(result.result_code.num_code, data::ResultCode::Numeric::kInstallFailed);
  EXPECT_EQ(result.description, "Refspec 'hash' not found");
}

/* Abort if the OSTree sysroot is invalid. */
TEST(OstreeManager, BadSysroot) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = "sysroot-that-is-missing";
  config.storage.path = temp_dir.Path();
  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  EXPECT_THROW(OstreeManager ostree(config.pacman, storage, nullptr), std::runtime_error);
}

/* Parse a provided list of installed packages. */
TEST(OstreeManager, ParseInstalledPackages) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.pacman.packages_file = "tests/test_data/package.manifest";
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  OstreeManager ostree(config.pacman, storage, nullptr);
  Json::Value packages = ostree.getInstalledPackages();
  EXPECT_EQ(packages[0]["name"].asString(), "vim");
  EXPECT_EQ(packages[0]["version"].asString(), "1.0");
  EXPECT_EQ(packages[1]["name"].asString(), "emacs");
  EXPECT_EQ(packages[1]["version"].asString(), "2.0");
  EXPECT_EQ(packages[2]["name"].asString(), "bash");
  EXPECT_EQ(packages[2]["version"].asString(), "1.1");
}

/* Communicate with a remote OSTree server without credentials. */
TEST(OstreeManager, AddRemoteNoCreds) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  KeyManager keys(storage, config.keymanagerConfig());
  keys.loadKeys();

  OstreeRepo *repo = nullptr;
  GError *error = nullptr;
  std::shared_ptr<OstreeSysroot> sysroot = OstreeManager::LoadSysroot(config.pacman.sysroot);
  EXPECT_TRUE(ostree_sysroot_get_repo(sysroot.get(), &repo, nullptr, &error));
  EXPECT_TRUE(OstreeManager::addRemote(repo, config.pacman.ostree_server, keys));

  g_autofree char *url = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "url", nullptr, &url, &error));
  EXPECT_EQ(url, config.pacman.ostree_server);

  gboolean out_gpg_verify;
  EXPECT_TRUE(ostree_repo_get_remote_boolean_option(repo, remote, "gpg-verify", FALSE, &out_gpg_verify, &error));

  g_autofree char *ostree_cert = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-client-cert-path", nullptr, &ostree_cert, &error));
  EXPECT_EQ(ostree_cert, nullptr);

  g_autofree char *ostree_key = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-client-key-path", nullptr, &ostree_key, &error));
  EXPECT_EQ(ostree_key, nullptr);

  g_autofree char *ostree_ca = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-ca-path", nullptr, &ostree_ca, &error));
  EXPECT_EQ(ostree_ca, nullptr);

  g_object_unref(repo);
}

/* Communicate with a remote OSTree server with credentials. */
TEST(OstreeManager, AddRemoteWithCreds) {
  TemporaryDirectory temp_dir;
  Config config;
  config.pacman.type = PackageManager::kOstree;
  config.pacman.sysroot = test_sysroot;
  config.storage.path = temp_dir.Path();

  std::shared_ptr<INvStorage> storage = INvStorage::newStorage(config.storage);
  std::string ca = Utils::readFile("tests/test_data/prov/root.crt");
  std::string pkey = Utils::readFile("tests/test_data/prov/pkey.pem");
  std::string cert = Utils::readFile("tests/test_data/prov/client.pem");
  storage->storeTlsCa(ca);
  storage->storeTlsPkey(pkey);
  storage->storeTlsCert(cert);
  KeyManager keys(storage, config.keymanagerConfig());
  keys.loadKeys();

  OstreeRepo *repo = nullptr;
  GError *error = nullptr;
  std::shared_ptr<OstreeSysroot> sysroot = OstreeManager::LoadSysroot(config.pacman.sysroot);
  EXPECT_TRUE(ostree_sysroot_get_repo(sysroot.get(), &repo, nullptr, &error));
  EXPECT_TRUE(OstreeManager::addRemote(repo, config.pacman.ostree_server, keys));

  g_autofree char *url = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "url", nullptr, &url, &error));
  EXPECT_EQ(url, config.pacman.ostree_server);

  gboolean out_gpg_verify;
  EXPECT_TRUE(ostree_repo_get_remote_boolean_option(repo, remote, "gpg-verify", FALSE, &out_gpg_verify, &error));

  g_autofree char *ostree_cert = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-client-cert-path", nullptr, &ostree_cert, &error));
  EXPECT_EQ(ostree_cert, keys.getCertFile());

  g_autofree char *ostree_key = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-client-key-path", nullptr, &ostree_key, &error));
  EXPECT_EQ(ostree_key, keys.getPkeyFile());

  g_autofree char *ostree_ca = nullptr;
  EXPECT_TRUE(ostree_repo_get_remote_option(repo, remote, "tls-ca-path", nullptr, &ostree_ca, &error));
  EXPECT_EQ(ostree_ca, keys.getCaFile());

  g_object_unref(repo);
}

#ifndef __NO_MAIN__
int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);

  if (argc != 2) {
    std::cerr << "Error: " << argv[0] << " requires the path to an OSTree sysroot as an input argument.\n";
    return EXIT_FAILURE;
  }

  TemporaryDirectory temp_sysroot;
  test_sysroot = temp_sysroot / "sysroot";
  // uses cp, as boost doesn't like to copy bad symlinks
  int r = system((std::string("cp -r ") + argv[1] + std::string(" ") + test_sysroot.string()).c_str());
  if (r != 0) {
    return -1;
  }

  return RUN_ALL_TESTS();
}
#endif
<|endoftext|>


<commit_before>//
// C++ Interface: BuiltinFuncs
//
// Description:
//
//
// Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//

#ifndef _BUILTIN_FUNCS_HPP
#define _BUILTIN_FUNCS_HPP

#include "Common.hpp"
#include "Func.hpp"
#include <cmath>
#include <cstdlib>
#include <cassert>

#include "RandomNumberGenerators.hpp"

/* Wrappers for all the builtin functions
   The arg_list pointer is a list of floats. Its
   size is equal to the number of arguments the parameter
   takes */
class FuncWrappers {

/* Values to optimize the sigmoid function */
static const int R =  32767;
static const int RR = 65534;

public:

static inline float int_wrapper(float * arg_list) {

return floor(arg_list[0]);

}

static inline float sqr_wrapper(float * arg_list) {
	return pow(arg_list[0], 2);
}

static inline float sigmoid_wrapper(float * arg_list)
{
	const double t = (1+exp(-arg_list[0]*arg_list[1]));
	return (fabs(t) > 0.00001) ? 1.0/t : 0;
}

static inline float sign_wrapper(float * arg_list) {

return -arg_list[0];
}

static inline float min_wrapper(float * arg_list) {

if (arg_list[0] > arg_list[1])
return arg_list[1];

return arg_list[0];
}

static inline float max_wrapper(float * arg_list) {

if (arg_list[0] > arg_list[1])
return arg_list[0];

return arg_list[1];
}

static inline float bor_wrapper(float * arg_list) {

return (float)((int)arg_list[0] || (int)arg_list[1]);
}

static inline float band_wrapper(float * arg_list) {
return (float)((int)arg_list[0] && (int)arg_list[1]);
}

static inline float bnot_wrapper(float * arg_list) {
return (float)(!(int)arg_list[0]);
}

static inline float if_wrapper(float * arg_list) {

if ((int)arg_list[0] == 0)
	return arg_list[2];
return arg_list[1];
}

static inline float rand_wrapper(float * arg_list) {
float l=1;

//  printf("RAND ARG:(%d)\n", (int)arg_list[0]);
if ((int)arg_list[0] > 0)
	l  = (float) RandomNumberGenerators::uniformInteger((int)arg_list[0]);

return l;
}

static inline float equal_wrapper(float * arg_list) {
	return (arg_list[0] == arg_list[1]);
}

static inline float above_wrapper(float * arg_list) {

return (arg_list[0] > arg_list[1]);
}

static inline float below_wrapper(float * arg_list) {

return (arg_list[0] < arg_list[1]);
}

static float sin_wrapper(float * arg_list) {
	const float d = sinf(*arg_list);
	return d;
}

static inline float cos_wrapper(float * arg_list) {
return (cos (arg_list[0]));
}

static inline float tan_wrapper(float * arg_list) {
return (tan(arg_list[0]));
}

static inline float asin_wrapper(float * arg_list) {
return (asin (arg_list[0]));
}

static inline float acos_wrapper(float * arg_list) {
return (acos (arg_list[0]));
}

static inline float atan_wrapper(float * arg_list) {
return (atan (arg_list[0]));
}

static inline float atan2_wrapper(float * arg_list) {
return (atan2 (arg_list[0], arg_list[1]));
}

static inline float pow_wrapper(float * arg_list) {
return (pow (arg_list[0], arg_list[1]));
}

static inline float exp_wrapper(float * arg_list) {
return (exp(arg_list[0]));
}

static inline float abs_wrapper(float * arg_list) {
return (fabs(arg_list[0]));
}

static inline float log_wrapper(float* arg_list) {
return (log (arg_list[0]));
}

static inline float log10_wrapper(float * arg_list) {
return (log10 (arg_list[0]));
}

static inline float sqrt_wrapper(float * arg_list) {
return (sqrt (arg_list[0]));
}

static inline float print_wrapper(float * arg_list) {

	std::cout << arg_list[0] << std::endl;
	return 0;
}

static inline float nchoosek_wrapper(float * arg_list) {
unsigned long cnm = 1UL;
int i, f;
int n, m;

n = (int)arg_list[0];
m = (int)arg_list[1];

if (m*2 >n) m = n-m;
for (i=1 ; i <= m; n--, i++)
{
if ((f=n) % i == 0)
f   /= i;
else  cnm /= i;
cnm *= f;
}
return (float)cnm;
}

static inline float fact_wrapper(float * arg_list) {

int result = 1;

int n = (int)arg_list[0];

while (n > 1) {
result = result * n;
n--;
}
return (float)result;
}
};

#include <map>
class BuiltinFuncs {

public:

    static int init_builtin_func_db();
    static int destroy_builtin_func_db();
    static int load_all_builtin_func();
    static int load_builtin_func( const std::string & name, float (*func_ptr)(float*), int num_args );

    static int insert_func( Func *func );
    static int remove_func( Func *func );
    static Func *find_func( const std::string & name );
private:
     static std::map<std::string, Func*> builtin_func_tree;
     static volatile bool initialized;
};

#endif
<commit_msg>return what you're printing<commit_after>//
// C++ Interface: BuiltinFuncs
//
// Description:
//
//
// Author: Carmelo Piccione <carmelo.piccione@gmail.com>, (C) 2007
//
// Copyright: See COPYING file that comes with this distribution
//
//

#ifndef _BUILTIN_FUNCS_HPP
#define _BUILTIN_FUNCS_HPP

#include "Common.hpp"
#include "Func.hpp"
#include <cmath>
#include <cstdlib>
#include <cassert>

#include "RandomNumberGenerators.hpp"

/* Wrappers for all the builtin functions
   The arg_list pointer is a list of floats. Its
   size is equal to the number of arguments the parameter
   takes */
class FuncWrappers {

/* Values to optimize the sigmoid function */
static const int R =  32767;
static const int RR = 65534;

public:

static inline float int_wrapper(float * arg_list) {

return floor(arg_list[0]);

}

static inline float sqr_wrapper(float * arg_list) {
	return pow(arg_list[0], 2);
}

static inline float sigmoid_wrapper(float * arg_list)
{
	const double t = (1+exp(-arg_list[0]*arg_list[1]));
	return (fabs(t) > 0.00001) ? 1.0/t : 0;
}

static inline float sign_wrapper(float * arg_list) {

return -arg_list[0];
}

static inline float min_wrapper(float * arg_list) {

if (arg_list[0] > arg_list[1])
return arg_list[1];

return arg_list[0];
}

static inline float max_wrapper(float * arg_list) {

if (arg_list[0] > arg_list[1])
return arg_list[0];

return arg_list[1];
}

static inline float bor_wrapper(float * arg_list) {

return (float)((int)arg_list[0] || (int)arg_list[1]);
}

static inline float band_wrapper(float * arg_list) {
return (float)((int)arg_list[0] && (int)arg_list[1]);
}

static inline float bnot_wrapper(float * arg_list) {
return (float)(!(int)arg_list[0]);
}

static inline float if_wrapper(float * arg_list) {

	if ((int)arg_list[0] == 0)
		return arg_list[2];
	//std::cout <<"NOT ZERO: " << arg_list[0] << std::endl;
	return arg_list[1];
}

static inline float rand_wrapper(float * arg_list) {
float l=1;

//  printf("RAND ARG:(%d)\n", (int)arg_list[0]);
if ((int)arg_list[0] > 0)
	l  = (float) RandomNumberGenerators::uniformInteger((int)arg_list[0]);

return l;
}

static inline float equal_wrapper(float * arg_list) {
	return (arg_list[0] == arg_list[1]);
}

static inline float above_wrapper(float * arg_list) {

return (arg_list[0] > arg_list[1]);
}

static inline float below_wrapper(float * arg_list) {

return (arg_list[0] < arg_list[1]);
}

static float sin_wrapper(float * arg_list) {
	const float d = sinf(*arg_list);
	return d;
}

static inline float cos_wrapper(float * arg_list) {
return (cos (arg_list[0]));
}

static inline float tan_wrapper(float * arg_list) {
return (tan(arg_list[0]));
}

static inline float asin_wrapper(float * arg_list) {
return (asin (arg_list[0]));
}

static inline float acos_wrapper(float * arg_list) {
return (acos (arg_list[0]));
}

static inline float atan_wrapper(float * arg_list) {
return (atan (arg_list[0]));
}

static inline float atan2_wrapper(float * arg_list) {
return (atan2 (arg_list[0], arg_list[1]));
}

static inline float pow_wrapper(float * arg_list) {
return (pow (arg_list[0], arg_list[1]));
}

static inline float exp_wrapper(float * arg_list) {
return (exp(arg_list[0]));
}

static inline float abs_wrapper(float * arg_list) {
return (fabs(arg_list[0]));
}

static inline float log_wrapper(float* arg_list) {
return (log (arg_list[0]));
}

static inline float log10_wrapper(float * arg_list) {
return (log10 (arg_list[0]));
}

static inline float sqrt_wrapper(float * arg_list) {
return (sqrt (arg_list[0]));
}

static inline float print_wrapper(float * arg_list) {

	std::cout << arg_list[0] << std::endl;
	return arg_list[0];
}

static inline float nchoosek_wrapper(float * arg_list) {
unsigned long cnm = 1UL;
int i, f;
int n, m;

n = (int)arg_list[0];
m = (int)arg_list[1];

if (m*2 >n) m = n-m;
for (i=1 ; i <= m; n--, i++)
{
if ((f=n) % i == 0)
f   /= i;
else  cnm /= i;
cnm *= f;
}
return (float)cnm;
}

static inline float fact_wrapper(float * arg_list) {

int result = 1;

int n = (int)arg_list[0];

while (n > 1) {
result = result * n;
n--;
}
return (float)result;
}
};

#include <map>
class BuiltinFuncs {

public:

    static int init_builtin_func_db();
    static int destroy_builtin_func_db();
    static int load_all_builtin_func();
    static int load_builtin_func( const std::string & name, float (*func_ptr)(float*), int num_args );

    static int insert_func( Func *func );
    static int remove_func( Func *func );
    static Func *find_func( const std::string & name );
private:
     static std::map<std::string, Func*> builtin_func_tree;
     static volatile bool initialized;
};

#endif
<|endoftext|>


<commit_before>// Copyright (c) 2015, Tiaan Louw
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include "universe/camera.h"

#include <SFML/Graphics/RenderTarget.hpp>

Camera::Camera() {
#if SHOW_CAMERA_TARGET
  // Adjust some values on the camera target shape.
  m_cameraTargetShape.setRadius(10.f);
  sf::FloatRect bounds{m_cameraTargetShape.getGlobalBounds()};
  m_cameraTargetShape.setOrigin(bounds.width / 2.f, bounds.height / 2.f);
  m_cameraTargetShape.setFillColor(sf::Color(255, 0, 0));
#endif  // SHOW_CAMERA_TARGET
}

Camera::~Camera() {
}

sf::Vector2f Camera::mousePosToUniversePos(const sf::Vector2i& mousePos) const {
  const float width = static_cast<float>(m_viewportSize.x);
  const float height = static_cast<float>(m_viewportSize.y);
  const sf::FloatRect& viewport = m_view.getViewport();

  const sf::IntRect adjViewport{
      static_cast<int>(0.5f + width * viewport.left),
      static_cast<int>(0.5f + height * viewport.top),
      static_cast<int>(0.5f + width * viewport.width),
      static_cast<int>(0.5f + height * viewport.height)};

  const sf::Vector2f normalized{
      -1.f + 2.f * (mousePos.x - adjViewport.left) / adjViewport.width,
      1.f - 2.f * (mousePos.y - adjViewport.top) / adjViewport.height};

  // Then transform by the inverse of the view matrix
  return m_view.getInverseTransform().transformPoint(normalized);
}

sf::Vector2i Camera::universePosToMousePos(
    const sf::Vector2f& universePos) const {
  const float width = static_cast<float>(m_viewportSize.x);
  const float height = static_cast<float>(m_viewportSize.y);

  // Transform the point by the vie matrix.
  const sf::Vector2f normalized =
      m_view.getTransform().transformPoint(universePos);

  // Convert the point to viewport coordinates.
  const sf::FloatRect& viewport = m_view.getViewport();
  const sf::IntRect adjViewport{static_cast<int>(width * viewport.left),
                                static_cast<int>(height * viewport.top),
                                static_cast<int>(width * viewport.width),
                                static_cast<int>(height * viewport.height)};

  const sf::Vector2i result{
      static_cast<int>((normalized.x + 1.f) / 2.f * adjViewport.width +
                       adjViewport.left),
      static_cast<int>((-normalized.y + 1.f) / 2.f * adjViewport.height +
                       adjViewport.top)};

  return result;
}

void Camera::onMousePressed(sf::Event& event) {
  switch (event.mouseButton.button) {
    case sf::Mouse::Right:
      m_isDraggingView = true;
      m_startDragViewPos =
          sf::Vector2f{static_cast<float>(event.mouseButton.x),
                       static_cast<float>(event.mouseButton.y)};
      break;
  }
}

void Camera::onMouseDragged(sf::Event& event) {
  // Adjust the camera if we are dragging the view around.
  if (m_isDraggingView) {
    // Get the amount that the mouse moved from the last position.
    sf::Vector2f delta = sf::Vector2f(static_cast<float>(event.mouseMove.x),
                                      static_cast<float>(event.mouseMove.y)) -
                         m_startDragViewPos;

    // Update the position of the camera.
    m_cameraTarget -= delta * m_zoomLevel;
#if SHOW_CAMERA_TARGET
    m_cameraTargetShape.setPosition(m_cameraTarget);
#endif

    // Set the last view position to the current position for the next drag
    // event.
    m_startDragViewPos = sf::Vector2f(static_cast<float>(event.mouseMove.x),
                                      static_cast<float>(event.mouseMove.y));
  }
}

void Camera::onMouseReleased(sf::Event& event) {
  switch (event.mouseButton.button) {
    case sf::Mouse::Right:
      m_isDraggingView = false;
      break;
  }
}

void Camera::onMouseWheel(sf::Event& event) {
  m_targetZoomLevel -= static_cast<float>(event.mouseWheel.delta);
  if (m_targetZoomLevel < 1.f)
    m_targetZoomLevel = 1.f;
  if (m_targetZoomLevel > 5.f)
    m_targetZoomLevel = 5.f;

  // We also move the camera target to where we scrolled the mouse wheel.
  // NOTE: We only do it half way between the current camera target and the
  // mouse position so that movements aren't so sudden.
  sf::Vector2f uniPos{mousePosToUniversePos(
      sf::Vector2i{event.mouseWheel.x, event.mouseWheel.y})};

  m_cameraTarget = uniPos;

#if SHOW_CAMERA_TARGET
  m_cameraTargetShape.setPosition(m_cameraTarget);
#endif
}

void Camera::layout(const sf::IntRect& rect) {
  m_viewportSize.x = static_cast<float>(rect.width);
  m_viewportSize.y = static_cast<float>(rect.height);

  updateView();
}

void Camera::tick(float adjustment) {
  // Adjust the current camera position towards the camera target position.
  m_cameraPos.x =
      m_cameraPos.x + (m_cameraTarget.x - m_cameraPos.x) / 10.f * adjustment;
  m_cameraPos.y =
      m_cameraPos.y + (m_cameraTarget.y - m_cameraPos.y) / 10.f * adjustment;

  // Adjust the zoom level towards the target zoom level.
  m_zoomLevel =
      m_zoomLevel + (m_targetZoomLevel - m_zoomLevel) / 7.5f * adjustment;

  // If we changed the zoom level of the camera position, we have to update the
  // view.
  updateView();
}

void Camera::draw(sf::RenderTarget& target, sf::RenderStates states) const {
#if SHOW_CAMERA_TARGET
  target.draw(m_cameraTargetShape);
#endif
}

void Camera::updateView() {
  // Adjust the viewport size.
  float ratio = 1080.f / m_viewportSize.y;

  sf::Vector2f size{m_viewportSize.x * ratio, m_viewportSize.y * ratio};

  sf::View result{m_cameraPos, size};
  result.zoom(m_zoomLevel);

  m_view = result;
}
<commit_msg>Change mouse button to left for camera interaction.<commit_after>// Copyright (c) 2015, Tiaan Louw
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.

#include "universe/camera.h"

#include <SFML/Graphics/RenderTarget.hpp>

Camera::Camera() {
#if SHOW_CAMERA_TARGET
  // Adjust some values on the camera target shape.
  m_cameraTargetShape.setRadius(10.f);
  sf::FloatRect bounds{m_cameraTargetShape.getGlobalBounds()};
  m_cameraTargetShape.setOrigin(bounds.width / 2.f, bounds.height / 2.f);
  m_cameraTargetShape.setFillColor(sf::Color(255, 0, 0));
#endif  // SHOW_CAMERA_TARGET
}

Camera::~Camera() {
}

sf::Vector2f Camera::mousePosToUniversePos(const sf::Vector2i& mousePos) const {
  const float width = static_cast<float>(m_viewportSize.x);
  const float height = static_cast<float>(m_viewportSize.y);
  const sf::FloatRect& viewport = m_view.getViewport();

  const sf::IntRect adjViewport{
      static_cast<int>(0.5f + width * viewport.left),
      static_cast<int>(0.5f + height * viewport.top),
      static_cast<int>(0.5f + width * viewport.width),
      static_cast<int>(0.5f + height * viewport.height)};

  const sf::Vector2f normalized{
      -1.f + 2.f * (mousePos.x - adjViewport.left) / adjViewport.width,
      1.f - 2.f * (mousePos.y - adjViewport.top) / adjViewport.height};

  // Then transform by the inverse of the view matrix
  return m_view.getInverseTransform().transformPoint(normalized);
}

sf::Vector2i Camera::universePosToMousePos(
    const sf::Vector2f& universePos) const {
  const float width = static_cast<float>(m_viewportSize.x);
  const float height = static_cast<float>(m_viewportSize.y);

  // Transform the point by the vie matrix.
  const sf::Vector2f normalized =
      m_view.getTransform().transformPoint(universePos);

  // Convert the point to viewport coordinates.
  const sf::FloatRect& viewport = m_view.getViewport();
  const sf::IntRect adjViewport{static_cast<int>(width * viewport.left),
                                static_cast<int>(height * viewport.top),
                                static_cast<int>(width * viewport.width),
                                static_cast<int>(height * viewport.height)};

  const sf::Vector2i result{
      static_cast<int>((normalized.x + 1.f) / 2.f * adjViewport.width +
                       adjViewport.left),
      static_cast<int>((-normalized.y + 1.f) / 2.f * adjViewport.height +
                       adjViewport.top)};

  return result;
}

void Camera::onMousePressed(sf::Event& event) {
  switch (event.mouseButton.button) {
    case sf::Mouse::Left:
      m_isDraggingView = true;
      m_startDragViewPos =
          sf::Vector2f{static_cast<float>(event.mouseButton.x),
                       static_cast<float>(event.mouseButton.y)};
      break;
  }
}

void Camera::onMouseDragged(sf::Event& event) {
  // Adjust the camera if we are dragging the view around.
  if (m_isDraggingView) {
    // Get the amount that the mouse moved from the last position.
    sf::Vector2f delta = sf::Vector2f(static_cast<float>(event.mouseMove.x),
                                      static_cast<float>(event.mouseMove.y)) -
                         m_startDragViewPos;

    // Update the position of the camera.
    m_cameraTarget -= delta * m_zoomLevel;
#if SHOW_CAMERA_TARGET
    m_cameraTargetShape.setPosition(m_cameraTarget);
#endif

    // Set the last view position to the current position for the next drag
    // event.
    m_startDragViewPos = sf::Vector2f(static_cast<float>(event.mouseMove.x),
                                      static_cast<float>(event.mouseMove.y));
  }
}

void Camera::onMouseReleased(sf::Event& event) {
  switch (event.mouseButton.button) {
    case sf::Mouse::Left:
      m_isDraggingView = false;
      break;
  }
}

void Camera::onMouseWheel(sf::Event& event) {
  m_targetZoomLevel -= static_cast<float>(event.mouseWheel.delta);
  if (m_targetZoomLevel < 1.f)
    m_targetZoomLevel = 1.f;
  if (m_targetZoomLevel > 5.f)
    m_targetZoomLevel = 5.f;

  // We also move the camera target to where we scrolled the mouse wheel.
  // NOTE: We only do it half way between the current camera target and the
  // mouse position so that movements aren't so sudden.
  sf::Vector2f uniPos{mousePosToUniversePos(
      sf::Vector2i{event.mouseWheel.x, event.mouseWheel.y})};

  m_cameraTarget = uniPos;

#if SHOW_CAMERA_TARGET
  m_cameraTargetShape.setPosition(m_cameraTarget);
#endif
}

void Camera::layout(const sf::IntRect& rect) {
  m_viewportSize.x = static_cast<float>(rect.width);
  m_viewportSize.y = static_cast<float>(rect.height);

  updateView();
}

void Camera::tick(float adjustment) {
  // Adjust the current camera position towards the camera target position.
  m_cameraPos.x =
      m_cameraPos.x + (m_cameraTarget.x - m_cameraPos.x) / 10.f * adjustment;
  m_cameraPos.y =
      m_cameraPos.y + (m_cameraTarget.y - m_cameraPos.y) / 10.f * adjustment;

  // Adjust the zoom level towards the target zoom level.
  m_zoomLevel =
      m_zoomLevel + (m_targetZoomLevel - m_zoomLevel) / 7.5f * adjustment;

  // If we changed the zoom level of the camera position, we have to update the
  // view.
  updateView();
}

void Camera::draw(sf::RenderTarget& target, sf::RenderStates states) const {
#if SHOW_CAMERA_TARGET
  target.draw(m_cameraTargetShape);
#endif
}

void Camera::updateView() {
  // Adjust the viewport size.
  float ratio = 1080.f / m_viewportSize.y;

  sf::Vector2f size{m_viewportSize.x * ratio, m_viewportSize.y * ratio};

  sf::View result{m_cameraPos, size};
  result.zoom(m_zoomLevel);

  m_view = result;
}
<|endoftext|>


<commit_before>/**
 *  TEM.cpp
 *  main program for running DVM-DOS-TEM
 *
 *  It runs at 3 run-mods:
 *      (1) site-specific
 *      (2) regional - time series
 * 		(3) regional - spatially (not yet available)
 *
 * Authors: Shuhua Yi - the original codes
 * 		    Fengming Yuan - re-designing and re-coding for (1) easily code managing;
 *                                        (2) java interface developing for calibration;
 *                                        (3) stand-alone application of TEM (java-c++)
 *                                        (4) inputs/outputs using netcdf format, have to be modified
 *                                        to fix memory-leaks
 *                                        (5) fix the snow/soil thermal/hydraulic algorithms
 *                                        (6) DVM coupled
 * 			Tobey Carman - modifications and maintenance
 *            1) update application entry point with boost command line arg. handling.
 *
 * Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
 *
 * started: 11/01/2010
 * last modified: 09/18/2012
*/

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <exception>
#include <map>

#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>

#include "ArgHandler.h"
#include "TEMLogger.h"
#include "assembler/Runner.h"

BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_general_logger, severity_channel_logger_t) {
  return severity_channel_logger_t(keywords::channel = "GENER");
}
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_cal_logger, severity_channel_logger_t) {
  return severity_channel_logger_t(keywords::channel = "CALIB");
}

// forward declaration of various free fucntions...
void quit_handler(const boost::system::error_code&,
                  boost::shared_ptr< boost::asio::io_service >);

void pause_handler(const boost::system::error_code&,
                      boost::shared_ptr< boost::asio::io_service >);

void calibration_worker( boost::shared_ptr< boost::asio::io_service > );

// DEFINE FREE FUNCTIIONS...
void quit_handler(const boost::system::error_code& error,
                  boost::shared_ptr< boost::asio::io_service > io_service ){
  severity_channel_logger_t& clg = my_cal_logger::get();
  BOOST_LOG_SEV(clg, info) << "Running the quit signal handler...";
  BOOST_LOG_SEV(clg, info) << "Stopping the io_service.";
  io_service->stop();

  BOOST_LOG_SEV(clg, debug) << "Quitting. Exit with -1.";
  exit(-1);
}

/** The signal handler that will pause the calibration */
void pause_handler( const boost::system::error_code& error,
                    boost::shared_ptr< boost::asio::io_service > io_service ){

  severity_channel_logger_t& clg = my_cal_logger::get();
  BOOST_LOG_SEV(clg, info) << "Caught signal!";
  BOOST_LOG_SEV(clg, info) << "Running pause handler."; ;

  BOOST_LOG_SEV(clg, info) << "Run blocking cin.get()";
  std::cin.get();
//   std::string ui;
//   std::getline(std::cin, ui);
//   BOOST_LOG_SEV(clg, info) << "You entered: " << ui;

  BOOST_LOG_SEV(clg, info) << "  Stop the service.";
  io_service->stop();

  BOOST_LOG_SEV(clg, info) << "  Reset the service.";
  io_service->reset();

  BOOST_LOG_SEV(clg, info) << "  Define a signal set...";
  boost::asio::signal_set signals(*io_service, SIGINT, SIGTERM);

  BOOST_LOG_SEV(clg, info) <<   "  Set another async wait on signals to PAUSE handler.";
  signals.async_wait(
      boost::bind(pause_handler, boost::asio::placeholders::error, io_service) );

  BOOST_LOG_SEV(clg, info) << "Done in Handler...";

  /* print menu, collect input
   * while input != 'q'
   *   execute input request
   */

}

/** A seperate function to run the model. */
void calibration_worker( boost::shared_ptr< boost::asio::io_service > io_service ) {

  // get handles for each of global loggers
  severity_channel_logger_t& clg = my_cal_logger::get();

  BOOST_LOG_SEV(clg, info) << "Start loop over cohorts, years, months.";

  for(int cohort = 0; cohort < 1; cohort++){
    for(int yr = 0; yr < 100; ++yr){

      int handlers_run = 0;
      boost::system::error_code ec;

      BOOST_LOG_SEV(clg, info) << "poll one handler from the io_service...";
      handlers_run = io_service->poll_one(ec);

      for(int m = 0; m < 12; ++m) {
        int sleeptime = 300;
        BOOST_LOG_SEV(clg, info) << "(cht, yr, m):" << "(" << cohort <<", "<< yr <<", "<< m << ") "
                                 << "Thinking for " << sleeptime << " milliseconds...";
        boost::posix_time::milliseconds workTime(sleeptime);
        boost::this_thread::sleep(workTime);

      } // end month loop
    } // end yr loop
  } // end cht loop

  BOOST_LOG_SEV(clg, info)  << "Done working. This simulation loops have exited.";
}

ArgHandler* args = new ArgHandler();

int main(int argc, char* argv[]){
  args->parse(argc, argv);
	if (args->getHelp()){
		args->showHelp();
		return 0;
	}
  args->verify();

  std::cout << "Setting up Logging...\n";

  setup_console_log_sink();

  set_log_severity_level(args->getLogLevel());

  // get handles for each of global loggers...
  severity_channel_logger_t& glg = my_general_logger::get();
  severity_channel_logger_t& clg = my_cal_logger::get();

  if (args->getCalibrationMode() == "on") {
    BOOST_LOG_SEV(glg, info) << "Running in Calibration Mode";

    BOOST_LOG_SEV(glg, info) << "Make shared pointers to an io_service";
    boost::shared_ptr< boost::asio::io_service > io_service(
      new boost::asio::io_service
    );

    BOOST_LOG_SEV(glg, info) << "Add some work to the service so it won't die.";
    boost::shared_ptr< boost::asio::io_service::work > work(
      new boost::asio::io_service::work( *io_service )
    );

    BOOST_LOG_SEV(clg, debug) << "  Define a signal set...";
    boost::asio::signal_set signals(*io_service, SIGINT, SIGTERM);

    BOOST_LOG_SEV(clg, debug) <<   "  Set async wait on signals to PAUSE handler.";
    signals.async_wait(
        boost::bind(pause_handler, boost::asio::placeholders::error, io_service) );

    calibration_worker(io_service);

  } else {
    BOOST_LOG_SEV(glg, info) << "Running in extrapolation mode.";
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);

    if (args->getMode() == "siterun") {
      time_t stime;
      time_t etime;
      stime=time(0);
      BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in siterun mode. Start @ "
                               << ctime(&stime);

      string controlfile = args->getCtrlfile();
      string chtid = args->getChtid();

      Runner siter;

      siter.chtid = atoi(chtid.c_str());

      siter.initInput(controlfile, "siter");

      siter.initOutput();

      siter.setupData();

      siter.setupIDs();

      siter.runmode1();

      etime=time(0);

    } else if (args->getMode() == "regnrun") {

      time_t stime;
      time_t etime;
      stime=time(0);
      BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in regional mode. Start @ "
                               << ctime(&stime);

      string controlfile = args->getCtrlfile();
      string runmode = args->getRegrunmode();

      Runner regner;

      regner.initInput(controlfile, runmode);

      regner.initOutput();

      regner.setupData();

      regner.setupIDs();

      if (runmode.compare("regner1")==0) {
        BOOST_LOG_SEV(glg, debug) << "Running in regner1...(runmode2)";
        regner.runmode2();
      } else if (runmode.compare("regner2")==0){
        BOOST_LOG_SEV(glg, debug) << "Running in regner2...(runmode3)";
        regner.runmode3();
      } else {
        BOOST_LOG_SEV(glg, fatal) << "Invalid runmode...quitting.";
        exit(-1);
      }

      etime = time(0);
      BOOST_LOG_SEV(glg, info) << "Done running dvm-dos-tem regionally "
                               << "(" << ctime(&etime) << ").";
      BOOST_LOG_SEV(glg, info) << "total seconds: " << difftime(etime, stime);
    }

    return 0;
  }
};
<commit_msg>maybe closer? moved the service re-setting out of the handler.<commit_after>/**
 *  TEM.cpp
 *  main program for running DVM-DOS-TEM
 *
 *  It runs at 3 run-mods:
 *      (1) site-specific
 *      (2) regional - time series
 * 		(3) regional - spatially (not yet available)
 *
 * Authors: Shuhua Yi - the original codes
 * 		    Fengming Yuan - re-designing and re-coding for (1) easily code managing;
 *                                        (2) java interface developing for calibration;
 *                                        (3) stand-alone application of TEM (java-c++)
 *                                        (4) inputs/outputs using netcdf format, have to be modified
 *                                        to fix memory-leaks
 *                                        (5) fix the snow/soil thermal/hydraulic algorithms
 *                                        (6) DVM coupled
 * 			Tobey Carman - modifications and maintenance
 *            1) update application entry point with boost command line arg. handling.
 *
 * Affilation: Spatial Ecology Lab, University of Alaska Fairbanks
 *
 * started: 11/01/2010
 * last modified: 09/18/2012
*/

#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <ctime>
#include <cstdlib>
#include <exception>
#include <map>

#include <boost/asio/signal_set.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>

#include "ArgHandler.h"
#include "TEMLogger.h"
#include "assembler/Runner.h"

BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_general_logger, severity_channel_logger_t) {
  return severity_channel_logger_t(keywords::channel = "GENER");
}
BOOST_LOG_INLINE_GLOBAL_LOGGER_INIT(my_cal_logger, severity_channel_logger_t) {
  return severity_channel_logger_t(keywords::channel = "CALIB");
}

// forward declaration of various free fucntions...
void quit_handler(const boost::system::error_code&,
                  boost::shared_ptr< boost::asio::io_service >);

void pause_handler(const boost::system::error_code&,
                      boost::shared_ptr< boost::asio::io_service >);

void calibration_worker( boost::shared_ptr< boost::asio::io_service > );

// DEFINE FREE FUNCTIIONS...
void quit_handler(const boost::system::error_code& error,
                  boost::shared_ptr< boost::asio::io_service > io_service ){
  severity_channel_logger_t& clg = my_cal_logger::get();
  BOOST_LOG_SEV(clg, info) << "Running the quit signal handler...";
  BOOST_LOG_SEV(clg, info) << "Stopping the io_service.";
  io_service->stop();

  BOOST_LOG_SEV(clg, debug) << "Quitting. Exit with -1.";
  exit(-1);
}

/** The signal handler that will pause the calibration */
void pause_handler( const boost::system::error_code& error,
                    boost::shared_ptr< boost::asio::io_service > io_service ){

  severity_channel_logger_t& clg = my_cal_logger::get();
  BOOST_LOG_SEV(clg, info) << "Caught signal!";
  BOOST_LOG_SEV(clg, info) << "Running pause handler."; ;

  BOOST_LOG_SEV(clg, info) << "Run blocking cin.get()";
  std::cin.get();
//   std::string ui;
//   std::getline(std::cin, ui);
//   BOOST_LOG_SEV(clg, info) << "You entered: " << ui;

  BOOST_LOG_SEV(clg, info) << "Done in Handler...";
}

/** A seperate function to run the model. */
void calibration_worker( ) {

  // get handles for each of global loggers
  severity_channel_logger_t& clg = my_cal_logger::get();

  BOOST_LOG_SEV(clg, info) << "Start loop over cohorts, years, months.";

  BOOST_LOG_SEV(clg, info) << "Make shared pointers to an io_service";
  boost::shared_ptr< boost::asio::io_service > io_service(
    new boost::asio::io_service
  );

  BOOST_LOG_SEV(clg, debug) << "Define a signal set...";
  boost::asio::signal_set signals(*io_service, SIGINT, SIGTERM);

  BOOST_LOG_SEV(clg, debug) <<   "Set async wait on signals to PAUSE handler.";
  signals.async_wait(
    boost::bind(pause_handler, boost::asio::placeholders::error, io_service) );

  for(int cohort = 0; cohort < 1; cohort++){
    for(int yr = 0; yr < 100; ++yr){

      int handlers_run = 0;
      boost::system::error_code ec;

      BOOST_LOG_SEV(clg, info) << "poll the io_service...";
      handlers_run = io_service->poll(ec);
      BOOST_LOG_SEV(clg, info) << handlers_run << "handlers run.";

      if (handlers_run > 0) {

        BOOST_LOG_SEV(clg, debug) <<   "Reset the io_service object.";
        io_service->reset();

        BOOST_LOG_SEV(clg, debug) <<   "Set async wait on signals to PAUSE handler.";
        signals.async_wait(
          boost::bind(pause_handler, boost::asio::placeholders::error, io_service) );

      }

      for(int m = 0; m < 12; ++m) {
        int sleeptime = 300;
        BOOST_LOG_SEV(clg, info) << "(cht, yr, m):" << "(" << cohort <<", "<< yr <<", "<< m << ") "
                                 << "Thinking for " << sleeptime << " milliseconds...";
        boost::posix_time::milliseconds workTime(sleeptime);
        boost::this_thread::sleep(workTime);

      } // end month loop
    } // end yr loop
  } // end cht loop

  BOOST_LOG_SEV(clg, info)  << "Done working. This simulation loops have exited.";
}

ArgHandler* args = new ArgHandler();

int main(int argc, char* argv[]){
  args->parse(argc, argv);
	if (args->getHelp()){
		args->showHelp();
		return 0;
	}
  args->verify();

  std::cout << "Setting up Logging...\n";

  setup_console_log_sink();

  set_log_severity_level(args->getLogLevel());

  // get handles for each of global loggers...
  severity_channel_logger_t& glg = my_general_logger::get();
  severity_channel_logger_t& clg = my_cal_logger::get();

  if (args->getCalibrationMode() == "on") {
    BOOST_LOG_SEV(glg, info) << "Running in Calibration Mode";

    calibration_worker();

  } else {
    BOOST_LOG_SEV(glg, info) << "Running in extrapolation mode.";
    setvbuf(stdout, NULL, _IONBF, 0);
    setvbuf(stderr, NULL, _IONBF, 0);

    if (args->getMode() == "siterun") {
      time_t stime;
      time_t etime;
      stime=time(0);
      BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in siterun mode. Start @ "
                               << ctime(&stime);

      string controlfile = args->getCtrlfile();
      string chtid = args->getChtid();

      Runner siter;

      siter.chtid = atoi(chtid.c_str());

      siter.initInput(controlfile, "siter");

      siter.initOutput();

      siter.setupData();

      siter.setupIDs();

      siter.runmode1();

      etime=time(0);

    } else if (args->getMode() == "regnrun") {

      time_t stime;
      time_t etime;
      stime=time(0);
      BOOST_LOG_SEV(glg, info) << "Running dvm-dos-tem in regional mode. Start @ "
                               << ctime(&stime);

      string controlfile = args->getCtrlfile();
      string runmode = args->getRegrunmode();

      Runner regner;

      regner.initInput(controlfile, runmode);

      regner.initOutput();

      regner.setupData();

      regner.setupIDs();

      if (runmode.compare("regner1")==0) {
        BOOST_LOG_SEV(glg, debug) << "Running in regner1...(runmode2)";
        regner.runmode2();
      } else if (runmode.compare("regner2")==0){
        BOOST_LOG_SEV(glg, debug) << "Running in regner2...(runmode3)";
        regner.runmode3();
      } else {
        BOOST_LOG_SEV(glg, fatal) << "Invalid runmode...quitting.";
        exit(-1);
      }

      etime = time(0);
      BOOST_LOG_SEV(glg, info) << "Done running dvm-dos-tem regionally "
                               << "(" << ctime(&etime) << ").";
      BOOST_LOG_SEV(glg, info) << "total seconds: " << difftime(etime, stime);
    }

    return 0;
  }
};
<|endoftext|>


<commit_before>/*
** SelfPortrait API
** See Copyright Notice in lua_utils.h
*/
#include "lua_utils.h"
#include <stdexcept>
#include "str_conversion.h"
using namespace std;

namespace {
	void handleUserdata(lua_State* L, int index) {

		void* p = lua_touserdata(L, index);

		if (p != nullptr) {
			if (lua_getmetatable(L, index)) {
				lua_pushvalue(L, LUA_REGISTRYINDEX);

				/* table is in the stack at index 't' */
				bool found = false;
				lua_pushnil(L);
				while (lua_next(L, -2) != 0) {
					if (lua_istable(L, -1)) {
						if (lua_rawequal(L, -1, -4)) {
							printf("%d: lua_user_data, metatable: %s\n", index, lua_tostring(L, -2));
							lua_pop(L, 4); // pop the key-value pair, the registry and the metatable
							return;
						}
					}
					lua_pop(L, 1); // pop the value
				}
				lua_pop(L, 2); // pop the registry and the metatable
			}
		}

		printf("%d: lua_user_data\n", index);
	}
}

namespace LuaUtils {

	bool found = false;
	// modified version of luaL_checkudata
	bool isudata (lua_State *L, int ud, const char *tname) {
	  void *p = lua_touserdata(L, ud);
	  if (p != NULL) {  /* value is a userdata? */
		if (lua_getmetatable(L, ud)) {  /* does it have a metatable? */
		  lua_getfield(L, LUA_REGISTRYINDEX, tname);  /* get correct metatable */
		  if (lua_rawequal(L, -1, -2)) {  /* does it have the correct mt? */
			found = true;
		  }
		  lua_pop(L, 2);  /* remove both metatables */
		}
	  }
	  return found;
	}

    void printType(lua_State* L, int i) {
        int t = lua_type(L, i);
        switch (t) {
            case LUA_TSTRING:
                printf("%d: lua_string: %s\n", i, lua_tostring(L, i));
                break;
            case LUA_TBOOLEAN:
                printf("%d: lua_boolean: %d\n", i, lua_toboolean(L, i));
                break;
            case LUA_TNUMBER:
                printf("%d: lua_number: %f\n", i, lua_tonumber(L, i));
                break;
            case LUA_TNIL:
                printf("%d: lua_nil\n", i);
                break;
            case LUA_TTABLE:
                printf("%d: lua_table\n", i);
                break;
            case LUA_TFUNCTION:
                printf("%d: lua_function\n", i);
                break;
            case LUA_TUSERDATA:
                handleUserdata(L, i);
                break;
            case LUA_TTHREAD:
                printf("%d: lua_thread\n", i);
                break;
            default:
                printf("%d: unkonwn type\n", i);
                break;
        }
    }

    int stackDump(lua_State *L)
	{
		int top = lua_gettop(L);
		for (int i = 1; i <= top; i++) {
            printType(L, i);
		}
        return 0;
	}

    LuaStateHolder::LuaStateHolder(lua_State* L, const string& addLuaPath, const string& addCPath)
        : m_L(L)
    {

        luaL_openlibs(L);

        if (!addLuaPath.empty()) {
            lua_getglobal(L, "package");
            luaL_checktype(L, 1, LUA_TTABLE);
            lua_getfield(L, 1, "path");
            lua_pushstring(L, ";");
            lua_pushstring(L, addLuaPath.c_str());
            lua_concat(L, 3);
            lua_setfield(L, 1, "path");

            lua_settop(L, 0);
        }

        if (!addCPath.empty()) {
            lua_getglobal(L, "package");
            luaL_checktype(L, 1, LUA_TTABLE);
            lua_getfield(L, 1, "cpath");
            lua_pushstring(L, ";");
            lua_pushstring(L, addCPath.c_str());
            lua_concat(L, 3);
            lua_setfield(L, 1, "cpath");
            lua_settop(L, 0);
        }
    }

    LuaStateHolder::LuaStateHolder(const string& addLuaPath, const string& addCPath)
        : LuaStateHolder(luaL_newstate(), addLuaPath, addCPath) {}

}
<commit_msg>Fix accidentally global variable<commit_after>/*
** SelfPortrait API
** See Copyright Notice in lua_utils.h
*/
#include "lua_utils.h"
#include <stdexcept>
#include "str_conversion.h"
using namespace std;

namespace {
	void handleUserdata(lua_State* L, int index) {

		void* p = lua_touserdata(L, index);

		if (p != nullptr) {
			if (lua_getmetatable(L, index)) {
				lua_pushvalue(L, LUA_REGISTRYINDEX);

				/* table is in the stack at index 't' */
				bool found = false;
				lua_pushnil(L);
				while (lua_next(L, -2) != 0) {
					if (lua_istable(L, -1)) {
						if (lua_rawequal(L, -1, -4)) {
							printf("%d: lua_user_data, metatable: %s\n", index, lua_tostring(L, -2));
							lua_pop(L, 4); // pop the key-value pair, the registry and the metatable
							return;
						}
					}
					lua_pop(L, 1); // pop the value
				}
				lua_pop(L, 2); // pop the registry and the metatable
			}
		}

		printf("%d: lua_user_data\n", index);
	}
}

namespace LuaUtils {

	// modified version of luaL_checkudata
	bool isudata (lua_State *L, int ud, const char *tname) {
      bool found = false;
	  void *p = lua_touserdata(L, ud);
	  if (p != NULL) {  /* value is a userdata? */
		if (lua_getmetatable(L, ud)) {  /* does it have a metatable? */
		  lua_getfield(L, LUA_REGISTRYINDEX, tname);  /* get correct metatable */
		  if (lua_rawequal(L, -1, -2)) {  /* does it have the correct mt? */
			found = true;
		  }
		  lua_pop(L, 2);  /* remove both metatables */
		}
	  }
	  return found;
	}

    void printType(lua_State* L, int i) {
        int t = lua_type(L, i);
        switch (t) {
            case LUA_TSTRING:
                printf("%d: lua_string: %s\n", i, lua_tostring(L, i));
                break;
            case LUA_TBOOLEAN:
                printf("%d: lua_boolean: %d\n", i, lua_toboolean(L, i));
                break;
            case LUA_TNUMBER:
                printf("%d: lua_number: %f\n", i, lua_tonumber(L, i));
                break;
            case LUA_TNIL:
                printf("%d: lua_nil\n", i);
                break;
            case LUA_TTABLE:
                printf("%d: lua_table\n", i);
                break;
            case LUA_TFUNCTION:
                printf("%d: lua_function\n", i);
                break;
            case LUA_TUSERDATA:
                handleUserdata(L, i);
                break;
            case LUA_TTHREAD:
                printf("%d: lua_thread\n", i);
                break;
            default:
                printf("%d: unkonwn type\n", i);
                break;
        }
    }

    int stackDump(lua_State *L)
	{
		int top = lua_gettop(L);
		for (int i = 1; i <= top; i++) {
            printType(L, i);
		}
        return 0;
	}

    LuaStateHolder::LuaStateHolder(lua_State* L, const string& addLuaPath, const string& addCPath)
        : m_L(L)
    {

        luaL_openlibs(L);

        if (!addLuaPath.empty()) {
            lua_getglobal(L, "package");
            luaL_checktype(L, 1, LUA_TTABLE);
            lua_getfield(L, 1, "path");
            lua_pushstring(L, ";");
            lua_pushstring(L, addLuaPath.c_str());
            lua_concat(L, 3);
            lua_setfield(L, 1, "path");

            lua_settop(L, 0);
        }

        if (!addCPath.empty()) {
            lua_getglobal(L, "package");
            luaL_checktype(L, 1, LUA_TTABLE);
            lua_getfield(L, 1, "cpath");
            lua_pushstring(L, ";");
            lua_pushstring(L, addCPath.c_str());
            lua_concat(L, 3);
            lua_setfield(L, 1, "cpath");
            lua_settop(L, 0);
        }
    }

    LuaStateHolder::LuaStateHolder(const string& addLuaPath, const string& addCPath)
        : LuaStateHolder(luaL_newstate(), addLuaPath, addCPath) {}

}
<|endoftext|>