<commit_before>/*
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *   @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <KAboutData>
#include <KCmdLineArgs>
#include <KApplication>
#include <KDebug>

#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/ConnectionFactory>
#include <TelepathyQt/ChannelClassSpec>
#include <TelepathyQt/ChannelFactory>
#include <TelepathyQt/ClientRegistrar>
#include <TelepathyQt/ContactFactory>
#include <TelepathyQt/Debug>
#include <TelepathyQt/Types>

#include "sasl-handler.h"
#include "tls-handler.h"

#include <KTp/telepathy-handler-application.h>

// FIXME: Move this to tp-qt4 itself
#include "types.h"

int main(int argc, char *argv[])
{
    KAboutData aboutData("ktp-auth-handler", 0,
                         ki18n("Telepathy Authentication Handler"),
                         "0.3");
    aboutData.addAuthor(ki18n("David Edmundson"), ki18n("Developer"), "kde@davidedmundson.co.uk");
    aboutData.addAuthor(ki18n("Daniele E. Domenichelli"), ki18n("Developer"), "daniele.domenichelli@gmail.com");
    aboutData.setProductName("telepathy/auth-handler");

    KCmdLineArgs::init(argc, argv, &aboutData);
    KTp::TelepathyHandlerApplication app;

    // FIXME: Move this to tp-qt4 itself
    registerTypes();

    Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(
            QDBusConnection::sessionBus(), Tp::Account::FeatureCore);
    Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(
            QDBusConnection::sessionBus(), Tp::Connection::FeatureCore);
    Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(
            QDBusConnection::sessionBus());
    channelFactory->addCommonFeatures(Tp::Channel::FeatureCore);
    Tp::ClientRegistrarPtr clientRegistrar = Tp::ClientRegistrar::create(
            accountFactory, connectionFactory, channelFactory);

    int handlers = 2;

    Tp::ChannelClassSpecList saslFilter;
    QVariantMap saslOtherProperties;
    saslOtherProperties.insert(
            TP_QT_IFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION + QLatin1String(".AuthenticationMethod"),
            TP_QT_IFACE_CHANNEL_INTERFACE_SASL_AUTHENTICATION);
    saslFilter.append(Tp::ChannelClassSpec(TP_QT_IFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION,
                Tp::HandleTypeNone, false, saslOtherProperties));
    Tp::SharedPtr<SaslHandler> saslHandler = Tp::SharedPtr<SaslHandler>(new SaslHandler(saslFilter));
    if (!clientRegistrar->registerClient(
                Tp::AbstractClientPtr(saslHandler), QLatin1String("KTp.SASLHandler"))) {
        handlers -= 1;
    }

    Tp::ChannelClassSpecList tlsFilter;
    tlsFilter.append(Tp::ChannelClassSpec(TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION,
                Tp::HandleTypeNone, false));
    Tp::SharedPtr<TlsHandler> tlsHandler = Tp::SharedPtr<TlsHandler>(new TlsHandler(tlsFilter));
    if (!clientRegistrar->registerClient(
                Tp::AbstractClientPtr(tlsHandler), QLatin1String("KTp.TLSHandler"))) {
        handlers -= 1;
    }

    if (!handlers) {
        kDebug() << "No handlers registered. Exiting";
        return 1;
    }
    return app.exec();
}
<commit_msg>Disable the TLSHandler registration in main() for now, as it's not working.<commit_after>/*
 * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/>
 *   @author Andre Moreira Magalhaes <andre.magalhaes@collabora.co.uk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include <KAboutData>
#include <KCmdLineArgs>
#include <KApplication>
#include <KDebug>

#include <TelepathyQt/AccountFactory>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/ConnectionFactory>
#include <TelepathyQt/ChannelClassSpec>
#include <TelepathyQt/ChannelFactory>
#include <TelepathyQt/ClientRegistrar>
#include <TelepathyQt/ContactFactory>
#include <TelepathyQt/Debug>
#include <TelepathyQt/Types>

#include "sasl-handler.h"
#include "tls-handler.h"

#include <KTp/telepathy-handler-application.h>

// FIXME: Move this to tp-qt4 itself
#include "types.h"

int main(int argc, char *argv[])
{
    KAboutData aboutData("ktp-auth-handler", 0,
                         ki18n("Telepathy Authentication Handler"),
                         "0.3");
    aboutData.addAuthor(ki18n("David Edmundson"), ki18n("Developer"), "kde@davidedmundson.co.uk");
    aboutData.addAuthor(ki18n("Daniele E. Domenichelli"), ki18n("Developer"), "daniele.domenichelli@gmail.com");
    aboutData.setProductName("telepathy/auth-handler");

    KCmdLineArgs::init(argc, argv, &aboutData);
    KTp::TelepathyHandlerApplication app;

    // FIXME: Move this to tp-qt4 itself
    registerTypes();

    Tp::AccountFactoryPtr accountFactory = Tp::AccountFactory::create(
            QDBusConnection::sessionBus(), Tp::Account::FeatureCore);
    Tp::ConnectionFactoryPtr connectionFactory = Tp::ConnectionFactory::create(
            QDBusConnection::sessionBus(), Tp::Connection::FeatureCore);
    Tp::ChannelFactoryPtr channelFactory = Tp::ChannelFactory::create(
            QDBusConnection::sessionBus());
    channelFactory->addCommonFeatures(Tp::Channel::FeatureCore);
    Tp::ClientRegistrarPtr clientRegistrar = Tp::ClientRegistrar::create(
            accountFactory, connectionFactory, channelFactory);

    int handlers = 1;

    Tp::ChannelClassSpecList saslFilter;
    QVariantMap saslOtherProperties;
    saslOtherProperties.insert(
            TP_QT_IFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION + QLatin1String(".AuthenticationMethod"),
            TP_QT_IFACE_CHANNEL_INTERFACE_SASL_AUTHENTICATION);
    saslFilter.append(Tp::ChannelClassSpec(TP_QT_IFACE_CHANNEL_TYPE_SERVER_AUTHENTICATION,
                Tp::HandleTypeNone, false, saslOtherProperties));
    Tp::SharedPtr<SaslHandler> saslHandler = Tp::SharedPtr<SaslHandler>(new SaslHandler(saslFilter));
    if (!clientRegistrar->registerClient(
                Tp::AbstractClientPtr(saslHandler), QLatin1String("KTp.SASLHandler"))) {
        handlers -= 1;
    }

#if 0
    Tp::ChannelClassSpecList tlsFilter;
    tlsFilter.append(Tp::ChannelClassSpec(TP_QT_IFACE_CHANNEL_TYPE_SERVER_TLS_CONNECTION,
                Tp::HandleTypeNone, false));
    Tp::SharedPtr<TlsHandler> tlsHandler = Tp::SharedPtr<TlsHandler>(new TlsHandler(tlsFilter));
    if (!clientRegistrar->registerClient(
                Tp::AbstractClientPtr(tlsHandler), QLatin1String("KTp.TLSHandler"))) {
        handlers -= 1;
    }
#endif

    if (!handlers) {
        kDebug() << "No handlers registered. Exiting";
        return 1;
    }
    return app.exec();
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <cstring>
#include <string>
#include <vector>

using namespace std;

//TOM: This function removes extra spaces at the head and tail of input
//     and also removes comments followed by #.
void prepareInput(string &input) {
    size_t hasHash = input.find("#");

    if (hasHash != string::npos) {
        input.erase(hasHash);
    }

    while (true) {
        if (input.at(0) == ' ') {
            input.erase(0,1);
        }else {
            break;
        }
    }

    while (true) {
        if (input.at(input.size() - 1) == ' ') {
            input.erase(input.size() - 1);
        }else {
            break;
        }
    }

    return;
}

//TOM: This function returns the initial position of the first delimiter.
//     If no delimiter is found, returns 99999999.
int firstCut(vector<size_t> v) {
    unsigned int min = 99999999;

    for (unsigned int i = 0; i < v.size(); i++) {
        if ((v.at(i) >= 0) && (min > v.at(i))) min = v.at(i);
    }

    return min;
}

//TOM: Pass in an empty vector and get back a vector with tokens
//     (e.g. "ls -a" or "||" or "echo hello") in sequential order.
//     Note that the "exit" command is not handled here, because
//     handling it in the interpretation of these tokens makes
//     way much more sense.
void getInput(vector<string> &tokenz) {
    string input;
    //TOM: 0 for ';', 1 for "&&", 2 for "||"
    vector<size_t> spots(3);
    //TOM: cutPos is the first position to cut our input.
    unsigned int cutPos;
    //TOM: coin stores command substrings temporarily.
    string coin;

    cout << "$ ";
    getline(cin, input);

    prepareInput(input);

    if (input.size() == 0) return;

    //TOM: Asks for more input when an attempt ends with valid connector.
    //     If a connector follows immediately after ';', this loop
    //     will continue to take inputs, and this error will be detected
    //     in the loop where the input is turned into tokens.
    if (input.size() > 2) {
        while (input.substr(input.size() - 2) == "||" ||
               input.substr(input.size() - 2) == "&&") {
            string appendage;

            cout << "> ";
            getline(cin, appendage);

            if (appendage.size() == 0) continue;

            prepareInput(appendage);
            input += appendage;
        }
    }

    //TOM: Removes ending ';' since if an input ends in ';' then
    //     the ';' really has no purpose but complicated codes below.
    if (input.at(input.size() - 1) == ';') {
        input.erase(input.size() - 1);
    }

    while (true) {
        prepareInput(input);
        spots.at(0) = input.find(";");
        spots.at(1) = input.find("&&");
        spots.at(2) = input.find("||");

        cutPos = firstCut(spots);

        //TOM: Connector at the front, syntax must be wrong.
        //     Note that this doesn't check for invalid characters at front.
        //     Also error message is printed manually, as I can't come up
        //     with an alternative method.
        if (cutPos == 0) {
            cout << "-rshell: syntax error with unexpected connector";
            tokenz.clear();
            return;
        }

        if (cutPos == 99999999) {
            tokenz.push_back(input);

            break;

        }else {
            coin = input.substr(0, cutPos);
            prepareInput(coin);
            tokenz.push_back(coin);

            if (input.at(cutPos) == ';') {
                tokenz.push_back(";");
                input.erase(0, cutPos + 1);

            }else if (input.at(cutPos) == '|'){
                tokenz.push_back("||");
                input.erase(0, cutPos + 2);

            }else if (input.at(cutPos) == '&'){
                tokenz.push_back("&&");
                input.erase(0, cutPos + 2);

            }
        }
    }

    return;
}

int main() {
    vector<string> tokens;
    getInput(tokens);

    cout << "tokens content: " << endl;
    for (unsigned int i = 0; i < tokens.size(); i++) {
        cout << tokens[i] << " size " << tokens[i].size() << endl;
    }

    return 0;
}

<commit_msg>Added codes to main.cpp (execute)<commit_after>#include <cstdlib>
#include <stdio.h>
#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>

using namespace std;

//TOM: This function removes extra spaces at the head and tail of input
//     and also removes comments followed by #.
void prepareInput(string &input) {
    size_t hasHash = input.find("#");

    if (hasHash != string::npos) {
        input.erase(hasHash);
    }

    while (true) {
        if (input.at(0) == ' ') {
            input.erase(0,1);
        }else {
            break;
        }
    }

    while (true) {
        if (input.at(input.size() - 1) == ' ') {
            input.erase(input.size() - 1);
        }else {
            break;
        }
    }

    return;
}

//TOM: This function returns the initial position of the first delimiter.
//     If no delimiter is found, returns 99999999.
int firstCut(vector<size_t> v) {
    unsigned int min = 99999999;

    for (unsigned int i = 0; i < v.size(); i++) {
        if ((v.at(i) >= 0) && (min > v.at(i))) min = v.at(i);
    }

    return min;
}

//TOM: Pass in an empty vector and get back a vector with tokens
//     (e.g. "ls -a" or "||" or "echo hello") in sequential order.
//     Note that the "exit" command is not handled here, because
//     handling it in the interpretation of these tokens makes
//     way much more sense.
void getInput(vector<string> &tokenz) {
    string input;
    //TOM: 0 for ';', 1 for "&&", 2 for "||"
    vector<size_t> spots(3);
    //TOM: cutPos is the first position to cut our input.
    unsigned int cutPos;
    //TOM: coin stores command substrings temporarily.
    string coin;

    cout << "$ ";
    getline(cin, input);

    prepareInput(input);

    if (input.size() == 0) return;

    //TOM: Asks for more input when an attempt ends with valid connector.
    //     If a connector follows immediately after ';', this loop
    //     will continue to take inputs, and this error will be detected
    //     in the loop where the input is turned into tokens.
    if (input.size() > 2) {
        while (input.substr(input.size() - 2) == "||" ||
               input.substr(input.size() - 2) == "&&") {
            string appendage;

            cout << "> ";
            getline(cin, appendage);

            if (appendage.size() == 0) continue;

            prepareInput(appendage);
            input += appendage;
        }
    }

    //TOM: Removes ending ';' since if an input ends in ';' then
    //     the ';' really has no purpose but complicated codes below.
    if (input.at(input.size() - 1) == ';') {
        input.erase(input.size() - 1);
    }

    while (true) {
        prepareInput(input);
        spots.at(0) = input.find(";");
        spots.at(1) = input.find("&&");
        spots.at(2) = input.find("||");

        cutPos = firstCut(spots);

        //TOM: Connector at the front, syntax must be wrong.
        //     Note that this doesn't check for invalid characters at front.
        //     Also error message is printed manually, as I can't come up
        //     with an alternative method.
        if (cutPos == 0) {
            cout << "-rshell: syntax error with unexpected connector";
            tokenz.clear();
            return;
        }

        if (cutPos == 99999999) {
            tokenz.push_back(input);

            break;

        }else {
            coin = input.substr(0, cutPos);
            prepareInput(coin);
            tokenz.push_back(coin);

            if (input.at(cutPos) == ';') {
                tokenz.push_back(";");
                input.erase(0, cutPos + 1);

            }else if (input.at(cutPos) == '|'){
                tokenz.push_back("||");
                input.erase(0, cutPos + 2);

            }else if (input.at(cutPos) == '&'){
                tokenz.push_back("&&");
                input.erase(0, cutPos + 2);

            }
        }
    }

    return;
}

//Wangho: This function is for executing command, cmd[0] should contain the
//        main command while anything else is flags, ***NEED a NULL at the
//        end of it.
int execute(char* cmd[]) {
    pid_t pid;
    int status;
    int output = 0;
    int fd[2];    //Wangho: This is a piepe that for passing variable
                  //        (this case: output) between parent and child
                  //        process

    pipe(fd);
    pid = fork();
    if (pid < 0) {
        perror("rshell");
    }else if (pid == 0) {
        //Wangho: Close the read function of pipe
        close(fd[0]);
        //Wangho: This is child process
        output = execvp(cmd[0], cmd);

        //Wangho: Will only be here if the execp() fail, so output fail
        write(fd[1], &output, sizeof(output));
        perror("rshell");
        exit(0);
    }else if (pid > 0) {
        //Wangho: Close the write function of pipe
        close(fd[1]);
        //Wangho: This is parent process
        waitpid(pid, &status, 0);

        //Wangho: When child process is fully returned
        if(WIFEXITED(status)){
            //Wangho: Take the output value, if execvp fail, it returns -1
            read(fd[0], &output, sizeof(output));
            return output;
        }
    }
}

int main() {
    vector<string> tokens;
    getInput(tokens);
    int output = 0;

    cout << "tokens content: " << endl;
    for (unsigned int i = 0; i < tokens.size(); i++) {
        cout << tokens[i] << " size " << tokens[i].size() << endl;
    }

/*Wangho: TEST AREA*/
    string ls = "ls";
    string dash = "-l";
    char* cmd[] = {(char*)ls.c_str(), (char*)dash.c_str(), NULL};

    string ls2 = "ls";
    string dash2 = "-a";
    char* cmd2[] = {(char*)ls2.c_str(), (char*)dash2.c_str(), NULL};

    string connect = ";";

    if (connect == ";" /*Wangho: if connector is ";"*/) {
        execute(cmd);
        execute(cmd2);
    }else if (connect == "&&" /*Wangho: if connecter is "&&"*/) {
        output = execute(cmd);

        if (output == 0) {
            execute(cmd2);
        }
    }else if (connect == "||" /*Wangho: if connecter is "||"*/) {
        output = execute(cmd);

        if (output == -1) {
            execute(cmd2);
        }
    }
/*end TEST AREA*/
    return 0;
}

<|endoftext|>


<commit_before>// main.cpp : Entry point for the console application.
#include<iostream>
#include<fstream>
#include<time.h>
#include<string>
#include<boost/program_options.hpp>
#include<boost/filesystem.hpp>

#include<eap_resources.hpp>
#include<lua_cmds.hpp>
#include<algorithm.hpp>
#include<ga.hpp>
#include<sa.hpp>
#include<es.hpp>
#include<hc.hpp>
#include<exhaust.hpp>

namespace prg_opts = boost::program_options;

std::unique_ptr<algorithm> eap::algo = NULL;

int main(int argc, char* argv[])
{
    try
    {
        std::string lua_file;
        unsigned int runs = 0;

        prg_opts::options_description desc("\nUsage");
        desc.add_options()
            ("help,h", "view valid options")
            ("input,i", prg_opts::value<std::string>(&lua_file), "Input file")
            ("runs,r", prg_opts::value<unsigned int>(&runs), "#of runs");

        prg_opts::variables_map vm;
        prg_opts::store(prg_opts::parse_command_line(argc, argv, desc), vm);
        prg_opts::notify(vm);

        if (vm.count("help") || !vm.count("input") || !vm.count("runs"))
        {
            std::cout << desc << "\n";
            return 0;
        }

        if (!std::ifstream(lua_file.c_str()))
        {
            std::cout << "Can not open input file" << "\n";
            return 0;
        }

        eap::init_lua();
        eap::load_lua_lib(lua_file.c_str());

        switch(eap::get_algorithm())
        {
            case GA:
                std::cout<<"Running GA...\n";
                eap::algo.reset(new ga(lua_file));
                break;
            case SA:
                std::cout<<"Running SA...\n";
                eap::algo.reset(new sa(lua_file));
                break;
            case HC:
                std::cout<<"Running HC...\n";
                eap::algo.reset(new hc(lua_file));
                break;
            case ES:
                std::cout<<"Running ES...\n";
                eap::algo.reset(new es(lua_file));
                break;
            case EX:
                std::cout<<"Running EX...\n";
                eap::algo.reset(new exhaust(lua_file));
                break;
            default:
                std::cout<<"Not a valid algorithm"<<std::endl;
        }

        /* load algorithm run parameters */
        eap::algo->setup_algo_params();

        /* load all possible antenna placements */
        eap::algo->algorithm::setup_ant_placements();

        /* load all wires from nec files */
        eap::algo->algorithm::load_nec_files();

        /*clean up previous output files */
        eap::algo->algorithm::setup_run_context();

        /* create antenna free space patterns */
        eap::algo->algorithm::write_freespace();

        /* run free space pattern files */
        eap::algo->algorithm::run_freespace();

        /* read free space pattern results */
        eap::algo->algorithm::read_freespace();

        for (unsigned int i=0; i<runs; ++i)
        {
            /* run the specific algorithm */
            eap::algo->run(i);
            std::string name = boost::filesystem::basename (lua_file);

            /* save results */
            //std::cout<<"***Archiving results\n";
            //boost::format formatter("cd " + eap::run_directory + "; tar -cjf ../" + name + "_a" + "_i%02d." + "tar.bz2 *");
            //system(str(formatter % i).c_str());
            std::cout<<"***deleting runs directory\n";
            boost::filesystem::remove_all(eap::run_directory);
            boost::filesystem::create_directory(eap::run_directory);
        }
    }
    catch (const std::exception &e)
    {
        std::cerr<<e.what() << "\n";
    }
    eap::close_lua();
    return 0;
}

<commit_msg>debug with run id<commit_after>// main.cpp : Entry point for the console application.
#include<iostream>
#include<fstream>
#include<time.h>
#include<string>
#include<boost/program_options.hpp>
#include<boost/filesystem.hpp>

#include<eap_resources.hpp>
#include<lua_cmds.hpp>
#include<algorithm.hpp>
#include<ga.hpp>
#include<sa.hpp>
#include<es.hpp>
#include<hc.hpp>
#include<exhaust.hpp>

namespace prg_opts = boost::program_options;

std::unique_ptr<algorithm> eap::algo = NULL;

int main(int argc, char* argv[])
{
    try
    {
        std::string lua_file;
        unsigned int runs = 0;

        prg_opts::options_description desc("\nUsage");
        desc.add_options()
            ("help,h", "view valid options")
            ("input,i", prg_opts::value<std::string>(&lua_file), "Input file")
            ("runs,r", prg_opts::value<unsigned int>(&runs), "#of runs");

        prg_opts::variables_map vm;
        prg_opts::store(prg_opts::parse_command_line(argc, argv, desc), vm);
        prg_opts::notify(vm);

        if (vm.count("help") || !vm.count("input") || !vm.count("runs"))
        {
            std::cout << desc << "\n";
            return 0;
        }

        if (!std::ifstream(lua_file.c_str()))
        {
            std::cout << "Can not open input file" << "\n";
            return 0;
        }

        eap::init_lua();
        eap::load_lua_lib(lua_file.c_str());

        switch(eap::get_algorithm())
        {
            case GA:
                std::cout<<"Running GA...\n";
                eap::algo.reset(new ga(lua_file));
                break;
            case SA:
                std::cout<<"Running SA...\n";
                eap::algo.reset(new sa(lua_file));
                break;
            case HC:
                std::cout<<"Running HC...\n";
                eap::algo.reset(new hc(lua_file));
                break;
            case ES:
                std::cout<<"Running ES...\n";
                eap::algo.reset(new es(lua_file));
                break;
            case EX:
                std::cout<<"Running EX...\n";
                eap::algo.reset(new exhaust(lua_file));
                break;
            default:
                std::cout<<"Not a valid algorithm"<<std::endl;
        }

        /* load algorithm run parameters */
        eap::algo->setup_algo_params();

        /* load all possible antenna placements */
        eap::algo->algorithm::setup_ant_placements();

        /* load all wires from nec files */
        eap::algo->algorithm::load_nec_files();

        /*clean up previous output files */
        eap::algo->algorithm::setup_run_context();

        /* create antenna free space patterns */
        eap::algo->algorithm::write_freespace();

        /* run free space pattern files */
        eap::algo->algorithm::run_freespace();

        /* read free space pattern results */
        eap::algo->algorithm::read_freespace();

        for (unsigned int i=0; i<runs; ++i)
        {
            /* run the specific algorithm */
            std::cout<<"***completed run "<<i<<"\n";
            eap::algo->run(i);
            std::string name = boost::filesystem::basename (lua_file);

            /* save results */
            //std::cout<<"***Archiving results\n";
            //boost::format formatter("cd " + eap::run_directory + "; tar -cjf ../" + name + "_a" + "_i%02d." + "tar.bz2 *");
            //system(str(formatter % i).c_str());
            std::cout<<"***deleting runs directory\n";
            boost::filesystem::remove_all(eap::run_directory);
            boost::filesystem::create_directory(eap::run_directory);
            std::cout<<"***completed run "<<i<<"\n";
        }
    }
    catch (const std::exception &e)
    {
        std::cerr<<e.what() << "\n";
    }
    eap::close_lua();
    return 0;
}

<|endoftext|>


<commit_before>//
//  main.cpp
//  ArduinoCommTest
//
//  Created by James Rees on 10/04/2015.
//  Copyright (c) 2015 James Rees. All rights reserved.
//

#include <iostream>

int main(int argc, const char * argv[]) {
    // insert code here...
        std::cout << "Hello, World!\n";

    //const FILE *file;
    FILE* file;
    file = fopen("/dev/cu.usbmodem1411","w");  //Opening device file
    for(int i = 0; i < 10000; i++){
   // std::cout << "The file is: " << file << std::endl;

        fprintf(file,"%d", 9); //Writing to the file

    }
    fclose(file);

}
<commit_msg>Modified test code so that the LED turns on, perhaps flush will be used to have direct communication,  I really don't want to store inside a buffer just directly access the newest incoming bytes.<commit_after>//
//  main.cpp
//  ArduinoCommTest
//
//  Created by James Rees on 10/04/2015.
//  Copyright (c) 2015 James Rees. All rights reserved.
//

#include <iostream>

int main(int argc, const char * argv[]) {
    // insert code here...
        std::cout << "Hello, World!\n";

    //const FILE *file;
    FILE* file;
    file = fopen("/dev/cu.usbmodem1411","w");  //Opening device file
    for(int i = 0; i < 80000000 ; i++){
   // std::cout << "The file is: " << file << std::endl;

        fprintf(file,"%d", 9); //Writing to the file

    }
    std::cout << "Finished sending" << std::endl;
    fclose(file);

}
<|endoftext|>


<commit_before>#include <iostream>
#include <cmath>
#include "solarsystem.h"
#include "euler.h"

using namespace std;

int main(int numArguments, char **arguments)
{
    int numTimesteps = 1000;
    if(numArguments >= 2) numTimesteps = atoi(arguments[1]);

    SolarSystem solarSystem;
    // We create new bodies like this. Note that the createCelestialBody function returns a reference to the newly created body
    // This can then be used to modify properties or print properties of the body if desired
    CelestialBody &sun = solarSystem.createCelestialBody( vec3(0,0,0), vec3(0,0,0), 1.0 );
    CelestialBody &earth = solarSystem.createCelestialBody( vec3(1, 0, 0), vec3(0, 2*M_PI, 0), 3e-6 );

    // To get a list (a reference, not copy) of all the bodies in the solar system, we use the .bodies() function
    vector<CelestialBody> &bodies = solarSystem.bodies();

    for(int i = 0; i<bodies.size(); i++) {
        CelestialBody &body = bodies[i]; // Reference to this body
        cout << "The position of this object is " << body.position << " with velocity " << body.velocity << endl;
    }

    Euler integrator(0.001);
    for(int timestep=0; timestep<numTimesteps; timestep++) {
        integrator.integrateOneStep(solarSystem);
    }

    cout << "I just created my first solar system that has " << solarSystem.bodies().size() << " objects." << endl;
    return 0;
}

<commit_msg>Using dt as variable in main().<commit_after>#include <iostream>
#include <cmath>
#include "solarsystem.h"
#include "euler.h"

using namespace std;

int main(int numArguments, char **arguments)
{
    int numTimesteps = 1000;
    if(numArguments >= 2) numTimesteps = atoi(arguments[1]);

    SolarSystem solarSystem;
    // We create new bodies like this. Note that the createCelestialBody function returns a reference to the newly created body
    // This can then be used to modify properties or print properties of the body if desired
    CelestialBody &sun = solarSystem.createCelestialBody( vec3(0,0,0), vec3(0,0,0), 1.0 );
    CelestialBody &earth = solarSystem.createCelestialBody( vec3(1, 0, 0), vec3(0, 2*M_PI, 0), 3e-6 );

    // To get a list (a reference, not copy) of all the bodies in the solar system, we use the .bodies() function
    vector<CelestialBody> &bodies = solarSystem.bodies();

    for(int i = 0; i<bodies.size(); i++) {
        CelestialBody &body = bodies[i]; // Reference to this body
        cout << "The position of this object is " << body.position << " with velocity " << body.velocity << endl;
    }

    double dt = 0.001;
    Euler integrator(dt);
    for(int timestep=0; timestep<numTimesteps; timestep++) {
        integrator.integrateOneStep(solarSystem);
    }

    cout << "I just created my first solar system that has " << solarSystem.bodies().size() << " objects." << endl;
    return 0;
}

<|endoftext|>


<commit_before>858a6ab5-ad5b-11e7-9846-ac87a332f658<commit_msg>Tuesday, turns out it was tuesday<commit_after>85f0241e-ad5b-11e7-8ed3-ac87a332f658<|endoftext|>


<commit_before>#include<iostream>

#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/highgui/highgui.hpp>

#include <omp.h>

#include "gaussian_kernel.hpp"

#ifndef profile_omp_time__
#define profile_omp_time__(label) for(double blockTime = -1; (blockTime == -1 ? (blockTime = omp_get_wtime()) != -1 : false); cout << label << " " << omp_get_wtime()-blockTime << endl)
#endif

using namespace std;
using namespace cv;

int Reflect(int size, int p)
{
    if (p < 0)
        return -p - 1;
    if (p >= size)
        return 2*size - p - 1;
    return p;
}

bool AreMatsEqual(Mat a, Mat b)
{
    return equal(a.begin<Vec3b>(), a.end<Vec3b>(), b.begin<Vec3b>());
}

uchar* ConvertMatToArray(Mat a)
{
    vector<uchar> tmp;
    tmp.assign((uchar*)a.datastart, (uchar*)a.dataend);
    return &tmp[0];
}

float* Convert2DVectorToArray(vector<vector<float> >* kernel)
{
    int k = (*kernel).size();
    float* tmp = new float[k*k];
    for(int i = 0; i < k; i++)
    {
        for(int j = 0; j < k; j++)
        {
            tmp[j + i*k] = (*kernel)[i][j];
        }
    }
    return tmp;
}

Vec3b Convolution(const Mat src, vector<vector<float> >* kernel, int x, int y)
{
    int k = (*kernel).size() / 2;
    int x_tmp, y_tmp;
    Vec3b sum = 0.0;
    for (int i = -k; i <= k; i++)
    {
        for (int j = -k; j <= k; j++)
        {
            x_tmp = Reflect(src.cols, x-j);
            y_tmp = Reflect(src.rows, y-i);
            sum = sum + (*kernel)[j+k][i+k] * src.at<Vec3b>(y_tmp,x_tmp);
        }
    }
    return sum;
}

Mat ApplyKernelSequential(const Mat src, vector<vector<float> >* kernel)
{
    Mat dst = Mat(src.rows, src.cols, src.type());
    for (int y = 0; y < src.rows; y++)
    {
        for (int x = 0; x < src.cols; x++)
        {
            dst.at<Vec3b>(y,x) = Convolution(src, kernel, x, y);
        }
    }
    return dst;
}

Mat ApplyKernelSequentialFlat(const Mat& src, vector<vector<float> >* kernel)
{
    int kernel_flat_size = (*kernel).size() * (*kernel).size();
    int src_flat_size = src.rows * src.cols * src.elemSize();

    uchar* src_flat = ConvertMatToArray(src);
    float* kernel_flat = Convert2DVectorToArray(kernel);
    uchar* dst_flat = new uchar[src_flat_size];

    uchar sum = 0;
    int i_tmp;

    for(int i = 0; i < src_flat_size; i++)
    {
        for(int j = 0; j < kernel_flat_size; j++)
        {
            i_tmp = i; // TODO compute the right index on flat structures
            sum = sum + kernel_flat[j] * src_flat[i_tmp];
        }
        dst_flat[i] = sum;
    }

    Mat dst = Mat(src.rows, src.cols, src.type(), dst_flat);
    return dst;
}

Mat ApplyKernelParallel(const Mat src, vector<vector<float> >* kernel, int num_threads)
{
    Mat dst = Mat(src.rows, src.cols, src.type());
    omp_set_nested(1);
    int x,y;
    #pragma omp parallel for num_threads(num_threads) collapse(2)
    for (y = 0; y < src.rows; y++)
    {
        for (x = 0; x < src.cols; x++)
        {
            dst.at<Vec3b>(y,x) = Convolution(src, kernel, x, y);
        }
    }
    return dst;
}

int main(int argc, char *argv[])
{
    char* filename = argv[1];

    Mat src = imread(filename, CV_LOAD_IMAGE_COLOR);

    if (!src.data)
    {
        cout << "Image file " << filename << "not found!" << endl;
        return -1;
    }

    cout << "Processing image file " << filename << endl;

    GaussianKernel kernel(5);

    Mat dst_sequential, dst_sequential_flat,
        dst_parallel, dst_parallel_flat;

    profile_omp_time__("*** Sequential version")
    {
        dst_sequential = ApplyKernelSequential(src, &(kernel.values));
    }

    profile_omp_time__("*** Sequential version - Flat")
    {
        dst_sequential_flat = ApplyKernelSequentialFlat(src, &(kernel.values));
    }
    cout << "    Correct: " << AreMatsEqual(dst_sequential, dst_sequential_flat) << endl;

    for(int t = 0; t < 4; t++) {
        int num_threads = pow(2, t);
        ostringstream label;
        label << "*** OpenMP version - " << num_threads << " thread(s)";
        profile_omp_time__(label.str())
        {
            dst_parallel = ApplyKernelParallel(src, &(kernel.values), num_threads);
        }
        cout << "    Correct: " << AreMatsEqual(dst_sequential, dst_parallel) << endl;
    }

    namedWindow("final", WINDOW_NORMAL);
    imshow("final", dst_sequential_flat);

    namedWindow("initial", WINDOW_NORMAL);
    imshow("initial", src);

    waitKey();

    return 0;
}<commit_msg>openmp stable version<commit_after>#include <iostream>
#include <sstream>

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <omp.h>

#include "gaussian_kernel.hpp"

#ifndef profile_omp_time__
#define profile_omp_time__(label) for(double blockTime = -1; (blockTime == -1 ? (blockTime = omp_get_wtime()) != -1 : false); cout << label << " " << omp_get_wtime()-blockTime << endl)
#endif

using namespace std;
using namespace cv;

int Reflect(int size, int p)
{
    if (p < 0)
        return -p - 1;
    if (p >= size)
        return 2*size - p - 1;
    return p;
}

bool AreMatsEqual(Mat a, Mat b)
{
    return equal(a.begin<Vec3b>(), a.end<Vec3b>(), b.begin<Vec3b>());
}

Vec3b Convolution(const Mat& src, vector<vector<float> >* kernel, int x, int y)
{
    int k = (*kernel).size() / 2;
    int x_tmp, y_tmp;
    Vec3b sum = 0;
    for (int i = -k; i <= k; i++)
    {
        for (int j = -k; j <= k; j++)
        {
            x_tmp = Reflect(src.cols, x-j);
            y_tmp = Reflect(src.rows, y-i);
            sum = sum + (*kernel)[j+k][i+k] * src.at<Vec3b>(y_tmp,x_tmp);
        }
    }
    return sum;
}

Mat ApplyKernelSequential(const Mat& src, vector<vector<float> >* kernel)
{
    Mat dst = Mat(src.rows, src.cols, src.type());
    for (int y = 0; y < src.rows; y++)
    {
        for (int x = 0; x < src.cols; x++)
        {
            dst.at<Vec3b>(y,x) = Convolution(src, kernel, x, y);
        }
    }
    return dst;
}

Mat ApplyKernelParallel(const Mat& src, vector<vector<float> >* kernel, int num_threads)
{
    Mat dst = Mat(src.rows, src.cols, src.type());
    omp_set_nested(1);
    int x,y;
    #pragma omp parallel for num_threads(num_threads) collapse(2)
    for (y = 0; y < src.rows; y++)
    {
        for (x = 0; x < src.cols; x++)
        {
            dst.at<Vec3b>(y,x) = Convolution(src, kernel, x, y);
        }
    }
    return dst;
}

void ProcessSingleBlock(const Mat& src, Mat& dst, vector<vector<float> >* kernel, int x_start, int y_start, int block_width)
{
    int x, y;
    for (y = y_start; y < y_start + block_width; y++)
    {
        if(y == src.rows) break;
        for (x = x_start; x < x_start + block_width; x++)
        {
            if(x == src.cols) break;
            dst.at<Vec3b>(y,x) = Convolution(src, kernel, x, y);
        }
    }
}

Mat ApplyKernelParallelBlock(const Mat& src, vector<vector<float> >* kernel, int num_threads)
{
    Mat dst = Mat(src.rows, src.cols, src.type());
    int block_width = 64;
    #pragma omp parallel for num_threads(num_threads) collapse(2)
    for (int y = 0; y < src.rows; y+=block_width)
    {
        for (int x = 0; x < src.cols; x+=block_width)
        {
            ProcessSingleBlock(src, dst, kernel, x, y, block_width);
        }
    }
    return dst;
}

int main(int argc, char *argv[])
{
    if (argc < 5)
    {
        cerr << "Provide following parameters: " << endl;
        cerr << " - Image file path" << endl;
        cerr << " - Number of threads" << endl;
        cerr << " - Image blocks width" << endl;
        cerr << " - Display results (true/false)" << endl;
        return -1;
    }

    char* filename = argv[1];

    istringstream num_threads_ss(argv[2]);
    int num_threads;
    if (!(num_threads_ss >> num_threads))
    {
        cerr << "Invalid number of threads: " << argv[2] << endl;
        return -1;
    }

    istringstream block_width_ss(argv[3]);
    int block_width;
    if (!(block_width_ss >> block_width))
    {
        cerr << "Invalid blocks width: " << argv[3] << endl;
        return -1;
    }

    bool display_images = string(argv[4]) == "true";

    Mat src = imread(filename, CV_LOAD_IMAGE_COLOR);

    if (!src.data)
    {
        cout << "Image file " << filename << "not found!" << endl;
        return -1;
    }

    cout << "Processing image file " << filename << endl;

    GaussianKernel kernel(5);

    Mat dst_sequential, dst_parallel, dst_parallel_blocks;

    profile_omp_time__("*** Sequential version - Elapsed time")
    {
        dst_sequential = ApplyKernelSequential(src, &(kernel.values));
    }

    ostringstream label;
    label << "*** OpenMP version - " << num_threads << " thread(s) - Elapsed time";
    profile_omp_time__(label.str())
    {
        dst_parallel = ApplyKernelParallel(src, &(kernel.values), num_threads);
    }
    cout << "    Correct: " << AreMatsEqual(dst_sequential, dst_parallel) << endl;

    label.str("");
    label << "*** OpenMP version - " << num_threads << " thread(s) - Block width " << block_width << " - Elapsed time";
    profile_omp_time__(label.str())
    {
        dst_parallel_blocks = ApplyKernelParallelBlock(src, &(kernel.values), num_threads);
    }
    cout << "    Correct: " << AreMatsEqual(dst_sequential, dst_parallel_blocks) << endl;

    if(display_images)
    {
        namedWindow("Source", WINDOW_NORMAL);
        imshow("Source", src);

        namedWindow("Result", WINDOW_NORMAL);
        imshow("Result", dst_sequential);

        waitKey();
    }

    return 0;
}<|endoftext|>


<commit_before>1b738da1-2748-11e6-9b5e-e0f84713e7b8<commit_msg>Initial commit.2<commit_after>1b889054-2748-11e6-9dad-e0f84713e7b8<|endoftext|>


<commit_before>0e7693e6-ad59-11e7-8b21-ac87a332f658<commit_msg>Now it no longer crashes if X<commit_after>0f24f6eb-ad59-11e7-bdef-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include <math.h>

using namespace std;

const int n = 9;

bool fun(bool *x)
{
	for (unsigned int j = 0; j < n-2; ++j)
		if ((x[j] != x[j+1]) && (x[j] != x[j+2]))
			return false;
	return true;
}

class Expr
{
public:
	Expr(){}
	virtual operator bool() const = 0;
};
typedef shared_ptr<Expr> PExpr;

class Disjunction: public Expr
{
public:
	Disjunction(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left || *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Conjunction: public Expr
{
public:
	Conjunction(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left && *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Negation: public Expr
{
public:
	Negation(PExpr pExpr)
		: expr(pExpr)
	{}
	operator bool() const
	{
		return !(*expr);
	}

private:
	PExpr expr;
};

class ValueToken: public Expr
{
public:
	ValueToken(bool b)
		: value(b)
	{}
	operator bool() const
	{
		return value;
	}

private:
	bool value;
};

enum Token_value
{
	NAME, NUMBER, END = ';',
	OR = '|', AND = '&', NOT = '!',
	EQV = '=', LP = '(', RP = ')'
};

Token_value curr_tok = END;
bool number_value;
string string_value;
map<string, bool> table;
int no_of_errors;

PExpr expr(bool);

int error(const string& s)
{
	++no_of_errors;
	cerr << "ошибка: " << s << endl;
	return 1;
}

Token_value get_token()
{
	char ch = 0;
	cin >> ch;
	switch(ch)
	{
	case 0:
		return curr_tok = END;
	case ';':
	case '&':
	case '|':
	case '(':
	case ')':
	case '=':
	case '!':
		return curr_tok = Token_value(ch);
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
	case '.':
		cin.putback(ch);
		cin >> number_value;
		return curr_tok = NUMBER;
	default:
		if (isalpha(ch))
		{
			cin.putback(ch);
			cin >> string_value;
			return curr_tok = NAME;
		}
		else
		{
			error("неправильная лексема");
			return curr_tok = END;
		}
	}
}

PExpr prim(bool get)
{
	if (get)
		get_token();

	switch(curr_tok)
	{
	case NUMBER:
	{
		bool v = number_value;
		get_token();
		return make_shared<ValueToken>(v);
	}
	case LP:
	{
		PExpr e = expr(true);
		if (curr_tok != RP)
			error("ожидалась )");
		get_token();
		return e;
	}
	default:
		return PExpr();
	}
}

PExpr term(bool get)
{
	PExpr pLeft = prim(get);
	while (true)
	{
		switch(curr_tok)
		{
		case AND:
		{
			PExpr pRight = prim(true);
			pLeft = make_shared<Conjunction>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

PExpr expr(bool get)
{
	PExpr pLeft = term(get);
	while (true)
	{
		switch(curr_tok)
		{
		case OR:
		{
			PExpr pRight = term(true);
			pLeft = make_shared<Disjunction>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

void compile()
{
	freopen("input.txt", "r", stdin);
	while(cin)
	{
		get_token();
		if (curr_tok == END)
			break;
		cout << *expr(false) << endl;
	}
}

void overrun()
{
	for (unsigned int i = 0; i < pow(2, n); ++i)
	{
		bool x[n];
		unsigned k = i;
		for (unsigned int j = 0; j < n; ++j)
		{
			x[n-j-1] = 0x1 & k;
			k >>= 1;
		}
		if (fun(x))
		{
			for (unsigned int j = 0; j < n; ++j)
				cout << x[j];
			cout << endl;
		}
	}
}

int main(int argc, char* argv[])
{
	switch(argc)
	{
	case 1:
		cout << "запуск без параметров. выбран режим работы по умолчанию." << endl;
		overrun();
		return 0;
	case 2:
		if (!strcmp(argv[1],"-d"))
		{
			cout << "режим работы по умолчанию" << endl;
			overrun();
			return 0;
		}
		if (!strcmp(argv[1],"-i"))
		{
			cout << "интерактивный режим работы" << endl;
			compile();
			return(10);
		}
		cout << "неизвестный параметр" << endl;
		return(1);
	default:
		cout << "слишком много параметров" << endl;
		return(2);
	}
}
<commit_msg>add negative handler<commit_after>#include <iostream>
#include <map>
#include <math.h>

using namespace std;

const int n = 9;

bool fun(bool *x)
{
	for (unsigned int j = 0; j < n-2; ++j)
		if ((x[j] != x[j+1]) && (x[j] != x[j+2]))
			return false;
	return true;
}

class Expr
{
public:
	Expr(){}
	virtual operator bool() const = 0;
};
typedef shared_ptr<Expr> PExpr;

class Disjunction: public Expr
{
public:
	Disjunction(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left || *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Conjunction: public Expr
{
public:
	Conjunction(PExpr pLeft, PExpr pRight)
		: left (pLeft )
		, right(pRight)
	{}
	operator bool() const
	{
		return *left && *right;
	}

private:
	PExpr left;
	PExpr right;
};

class Negation: public Expr
{
public:
	Negation(PExpr pExpr)
		: expr(pExpr)
	{}
	operator bool() const
	{
		return !(*expr);
	}

private:
	PExpr expr;
};

class ValueToken: public Expr
{
public:
	ValueToken(bool b)
		: value(b)
	{}
	operator bool() const
	{
		return value;
	}

private:
	bool value;
};

enum Token_value
{
	NAME, NUMBER, END = ';',
	OR = '|', AND = '&', NOT = '!',
	EQV = '=', LP = '(', RP = ')'
};

Token_value curr_tok = END;
bool number_value;
string string_value;
map<string, bool> table;
int no_of_errors;

PExpr expr(bool);

int error(const string& s)
{
	++no_of_errors;
	cerr << "ошибка: " << s << endl;
	return 1;
}

Token_value get_token()
{
	char ch = 0;
	cin >> ch;
	switch(ch)
	{
	case 0:
		return curr_tok = END;
	case ';':
	case '&':
	case '|':
	case '(':
	case ')':
	case '=':
	case '!':
		return curr_tok = Token_value(ch);
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
	case '.':
		cin.putback(ch);
		cin >> number_value;
		return curr_tok = NUMBER;
	default:
		if (isalpha(ch))
		{
			cin.putback(ch);
			cin >> string_value;
			return curr_tok = NAME;
		}
		else
		{
			error("неправильная лексема");
			return curr_tok = END;
		}
	}
}

PExpr prim(bool get)
{
	if (get)
		get_token();

	switch(curr_tok)
	{
	case NUMBER:
	{
		bool v = number_value;
		get_token();
		return make_shared<ValueToken>(v);
	}
	case LP:
	{
		PExpr e = expr(true);
		if (curr_tok != RP)
			error("ожидалась )");
		get_token();
		return e;
	}
	case NOT:
	{
		PExpr e = expr(true);
		e = make_shared<Negation>(e);
		get_token();
		return e;
	}
	default:
		return PExpr();
	}
}

PExpr term(bool get)
{
	PExpr pLeft = prim(get);
	while (true)
	{
		switch(curr_tok)
		{
		case AND:
		{
			PExpr pRight = prim(true);
			pLeft = make_shared<Conjunction>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

PExpr expr(bool get)
{
	PExpr pLeft = term(get);
	while (true)
	{
		switch(curr_tok)
		{
		case OR:
		{
			PExpr pRight = term(true);
			pLeft = make_shared<Disjunction>(pLeft, pRight);
			break;
		}
		default:
			return pLeft;
		}
	}
}

void compile()
{
	freopen("input.txt", "r", stdin);
	while(cin)
	{
		get_token();
		if (curr_tok == END)
			break;
		cout << *expr(false) << endl;
	}
}

void overrun()
{
	for (unsigned int i = 0; i < pow(2, n); ++i)
	{
		bool x[n];
		unsigned k = i;
		for (unsigned int j = 0; j < n; ++j)
		{
			x[n-j-1] = 0x1 & k;
			k >>= 1;
		}
		if (fun(x))
		{
			for (unsigned int j = 0; j < n; ++j)
				cout << x[j];
			cout << endl;
		}
	}
}

int main(int argc, char* argv[])
{
	switch(argc)
	{
	case 1:
		cout << "запуск без параметров. выбран режим работы по умолчанию." << endl;
		overrun();
		return 0;
	case 2:
		if (!strcmp(argv[1],"-d"))
		{
			cout << "режим работы по умолчанию" << endl;
			overrun();
			return 0;
		}
		if (!strcmp(argv[1],"-i"))
		{
			cout << "интерактивный режим работы" << endl;
			compile();
			return(10);
		}
		cout << "неизвестный параметр" << endl;
		return(1);
	default:
		cout << "слишком много параметров" << endl;
		return(2);
	}
}
<|endoftext|>


<commit_before>7a2ed45c-2749-11e6-8935-e0f84713e7b8<commit_msg>Bug fixes and performance improvements<commit_after>7a387942-2749-11e6-a4e8-e0f84713e7b8<|endoftext|>


<commit_before>81d5b861-2749-11e6-9e27-e0f84713e7b8<commit_msg>Initial commit.13<commit_after>81e7d997-2749-11e6-9aeb-e0f84713e7b8<|endoftext|>


<commit_before>f5eeafb8-ad58-11e7-82e6-ac87a332f658<commit_msg>Too poor for Dropbox<commit_after>f68033d4-ad58-11e7-8bd9-ac87a332f658<|endoftext|>


<commit_before>#include <iostream>
#include <unistd.h>
#include <getopt.h>
#include <cstring>
#include <cstdlib>
#include "util.h"
#include "sniffer.h"

using namespace std;

static int verbose_flag = 0;
static int debug_flag = 0;
static int help_flag = 0;
static char * interface = 0;

int main(int argc, char ** argv) {
  cout << "WiFi Sniffer\n"
          "------------\tBy Jay H. Bosamiya\n"
          "            \t------------------\n\n";

  // Make sure that only root can run this program
  if ( geteuid() ) {
    help_flag = true;
  }

  if ( argc == 1 ) {
    help_flag = true;
  }

  // Option parsing loop
  while (1) {
    int c;

    static struct option long_options[] =
      {
        {"macstat"  , no_argument      , &macstat_flag  ,  1},
        {"time"     , required_argument, NULL           ,'t'},
        {"verbose"  , no_argument      , &verbose_flag  ,  1},
        {"debug"    , no_argument      , &debug_flag    ,  1},
        {"help"     , no_argument      , &help_flag     ,  1},
        {0, 0, 0, 0}
      };
    int option_index = 0;

    c = getopt_long_only (argc, argv, "",
                     long_options, &option_index);

    /* Detect the end of the options. */
    if (c == -1)
      break;

    switch (c)
      {
      case 0:
        break;

      case 't':
        max_time = atoi(optarg);
        break;

      default:
        cerr << "Invalid option. Try " << argv[0] << " -h for help. Quitting.\n";
        return -1;
      }
  }

  if (help_flag) {
    cerr << "Usage: " << argv[0] << " [options] interface\n"
            "  -m, --macstat   : Show number of detections of each MAC and timestamps\n"
            "  -t, --time      : Set time to run sniffer in seconds (default: 60)\n"
            "  -v, --verbose   : Output more information\n"
            "  -d, --debug     : Show debugging information\n"
            "  -h, --help      : Show this help text\n"
            "\n"
            "Note: This program needs to be run as root\n"
    ;
    return 0;
  }

  while (optind < argc) {
    if ( ! interface ) {
      interface = strdup(argv[optind++]);
    } else {
      cerr << "Too many interfaces. Try " << argv[0] << " -h for help. Quitting.\n";
      return -1;
    }
  }

  if ( ! interface ) {
    cerr << "No interface specified. Try " << argv[0] << " -h for help. Quitting.\n";
    return -1;
  }

  if ( verbose_flag ) {
    set_verbose_on();
  }

  if ( debug_flag ) {
    set_debug_on();
  }

  // Do actual work (from sniffer.* files)
  initialize(interface);
  capture_packets();
  print_info();

  return 0;
}
<commit_msg>Improve help message<commit_after>#include <iostream>
#include <unistd.h>
#include <getopt.h>
#include <cstring>
#include <cstdlib>
#include "util.h"
#include "sniffer.h"

using namespace std;

static int verbose_flag = 0;
static int debug_flag = 0;
static int help_flag = 0;
static char * interface = 0;

int main(int argc, char ** argv) {
  cout << "WiFi Sniffer\n"
          "------------\tBy Jay H. Bosamiya\n"
          "            \t------------------\n\n";

  // Make sure that only root can run this program
  if ( geteuid() ) {
    help_flag = true;
  }

  if ( argc == 1 ) {
    help_flag = true;
  }

  // Option parsing loop
  while (1) {
    int c;

    static struct option long_options[] =
      {
        {"macstat"  , no_argument      , &macstat_flag  ,  1},
        {"time"     , required_argument, NULL           ,'t'},
        {"verbose"  , no_argument      , &verbose_flag  ,  1},
        {"debug"    , no_argument      , &debug_flag    ,  1},
        {"help"     , no_argument      , &help_flag     ,  1},
        {0, 0, 0, 0}
      };
    int option_index = 0;

    c = getopt_long_only (argc, argv, "",
                     long_options, &option_index);

    /* Detect the end of the options. */
    if (c == -1)
      break;

    switch (c)
      {
      case 0:
        break;

      case 't':
        max_time = atoi(optarg);
        break;

      default:
        cerr << "Invalid option. Try " << argv[0] << " -h for help. Quitting.\n";
        return -1;
      }
  }

  if (help_flag) {
    cerr << "Usage: " << argv[0] << " [options] interface\n"
            "  -m, --macstat   : Show number of detections of each MAC and timestamps\n"
            "  -t, --time t    : Run sniffer for t seconds (default: 60)\n"
            "  -v, --verbose   : Output more information\n"
            "  -d, --debug     : Show debugging information\n"
            "  -h, --help      : Show this help text\n"
            "\n"
            "Note: This program needs to be run as root\n"
    ;
    return 0;
  }

  while (optind < argc) {
    if ( ! interface ) {
      interface = strdup(argv[optind++]);
    } else {
      cerr << "Too many interfaces. Try " << argv[0] << " -h for help. Quitting.\n";
      return -1;
    }
  }

  if ( ! interface ) {
    cerr << "No interface specified. Try " << argv[0] << " -h for help. Quitting.\n";
    return -1;
  }

  if ( verbose_flag ) {
    set_verbose_on();
  }

  if ( debug_flag ) {
    set_debug_on();
  }

  // Do actual work (from sniffer.* files)
  initialize(interface);
  capture_packets();
  print_info();

  return 0;
}
<|endoftext|>


<commit_before>d21415ab-4b02-11e5-b3ef-28cfe9171a43<commit_msg>The previous fix has been fixed<commit_after>d222648f-4b02-11e5-afb5-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>

 using namespace std;

/**
* The purpose of this function is to displays an equilateral
* triangle based on the user's input.
* The user decides on its size and the character that it may consist of.
* The triangle increases by three characters each time and is based on the
* T(n)=2n+1 equation.
* @param char character The character that the user enters.
* @param int size The size of the triangle.
*/

void generateEquilateralTriangle(char character, int size)
{

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

        for (int j = 0; j < (2*size + 1); j++) {

            cout << (((size + i) >= j && (size - i) <= j) ? character: ' ');

        }

        cout << endl;

     }
}

/**
* The purpose of this function is to validate the user's input.
* @param char character The character that the user enters.
* @param int size The size of the triangle.
* @return True if input is invalid.
*/

bool validateInput(char character,int size)
{
    if (cin.fail()) {

        cin.clear();
        cin.ignore();
    }
    else
        generateEquilateralTriangle(character,size);

}

/**
 * The purpose of this method is to manage user input in order to
 * correctly display the triangle.
 *
 * @author Chad Petersen
 * @return The valid input and display the triangle.
 */

int main()
{
int size;
char character;

    do {

        cout << "Enter a size for your triangle: " << endl;
        cin  >> size;
        cout << "Enter a character for your triangle: " << endl;
        cin  >> character;

    } while(validateInput(character,size)!=0);

    return 0;

 }
<commit_msg>Made changes to clean up the equilateral triangle meme<commit_after>#include <iostream>

using namespace std;

/**
 * The purpose of this function is to generate an equilateral triangle
 *
 * @param char character A triangle character
 * @param int  height    A triangle height
 */
void generateEquilateralTriangle(char character, int height)
{
     for (int i = 0; i < height; i++) {
        for (int j = 0; j < (2*height + 1); j++) {
            cout << (((height + i) >= j && (height - i) <= j) ? character: ' ');
        }

        cout << endl;
     }
}

/**
 * The purpose of this function is to validate the user's input
 *
 * @return bool True if validation is a success
 */
bool validateInput()
{
    if (cin.fail()) {
        cin.clear();
        cin.ignore();

        return false;
    }

    return true;
}

/**
 * The purpose of this method is to capture user input
 *
 * @return int The status code
 */
int main()
{
    char character;
    int height;

    do {
        cout << "Enter a character for your triangle: " << endl;
        cin  >> character;
        cout << "Enter a height for your triangle: " << endl;
        cin  >> height;

        if (validateInput())
            generateEquilateralTriangle(character, height);
        else
            cout << "You entered invalid values, please try again?" << endl;

    } while (height != -1);

    return 0;
}
<|endoftext|>


<commit_before>9a5455c7-4b02-11e5-9af5-28cfe9171a43<commit_msg>update testing<commit_after>9a63538f-4b02-11e5-b6de-28cfe9171a43<|endoftext|>


<commit_before>
#include <iostream>

#include "Command/CommandQueueDefault.h"
#include "Communication/CommunicationJumpropes.h"

OpenALRF::CommandQueue Queue;
OpenALRF::CommunicationJumpropes Comm(&Queue);

int main()
{
   std::cout << "Hello, World!" << std::endl;

   OpenALRF::Command Hello{ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotForward, 2, 0 };
   Queue.Add(Hello);

   OpenALRF::Command World{ OpenALRF::modCamera, OpenALRF::actCameraCapture, 0, 0 };
   Queue.Add(World);

   Queue.Process();
   Queue.Process();

   return 1;
}
<commit_msg>setup main loop with comm, watchdog, cmd processing<commit_after>
#include <iostream>

#include <Groundfloor/Atoms/Defines.h>
#include <Groundfloor/Atoms/Initialize.h>

#include "Command/CommandQueueDefault.h"
#include "Communication/CommunicationJumpropes.h"

#include <Jumpropes/Initialize.h>
#include <Jumpropes/Functions.h>

#include "System/WatchCat.h"

OpenALRF::CommandQueue Queue;
OpenALRF::ISystem *System = Queue.GetSystem();

void RebootSystem()
{
   Queue.Add({ OpenALRF::modSystem, OpenALRF::actSystemReboot });
   Queue.Process();
}

int main()
{
   std::cout << "Hello" << std::endl;

   if (Groundfloor::initGroundfloor())
   {
      std::cout << "World!" << std::endl;

      if (Jumpropes::initJumpropes())
      {
         std::cout << "And Universe!" << std::endl;

         AudacityRover::WatchCat Cat(System, &Queue);
         AudacityRover::CommunicationJumpropes Comm(&Queue);
         try
         {
            while (!System->ShouldQuit())
            {
               Comm.Process();
               Queue.Process();
               Cat.Process();

               GFMillisleep(10);
            }

         }
         catch (std::exception &e)
         {
            std::cout << e.what() << std::endl;
         }

         std::cout << "Goodbye!" << std::endl;

         /*
         OpenALRF::Command Hello{ OpenALRF::modRemotePilot, OpenALRF::actRemotePilotForward, 2, 0 };
         Queue.Add(Hello);

         OpenALRF::Command World{ OpenALRF::modCamera, OpenALRF::actCameraCapture, 0, 0 };
         Queue.Add(World);
         */

         Jumpropes::finiJumpropes();
      }

      Groundfloor::initGroundfloor();
   }

   return 1;
}
<|endoftext|>


<commit_before>177f10b5-2748-11e6-95ab-e0f84713e7b8<commit_msg>The previous fix has been fixed<commit_after>1790ee6b-2748-11e6-b114-e0f84713e7b8<|endoftext|>


<commit_before>afbacf30-4b02-11e5-bed7-28cfe9171a43<commit_msg>updated some files<commit_after>afc9deb3-4b02-11e5-a02c-28cfe9171a43<|endoftext|>


<commit_before>#include <iostream>

int main(){
    std::cout << "hello world!" << std::endl;
    return 0;
}
<commit_msg>test hello<commit_after>#include <iostream>

int main(){
    std::cout << "hello!" << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
int main (void)
        {
            printf ("hw");
        }
<commit_msg>TeamCity test<commit_after>#include <stdio.h>
int main (void)
        {
            printf ("hw");
            printf ("hw");
        }
Попробуем помучать teamcity<|endoftext|>


<commit_before>72763bf8-2749-11e6-a333-e0f84713e7b8<commit_msg>Made changes so it will hopefully compile by the next commit<commit_after>72870b47-2749-11e6-929b-e0f84713e7b8<|endoftext|>


<commit_before>#include <boost/program_options.hpp>
#include <iostream>
#include <execinfo.h>
#include "test/Problem.h"
#include "test/Timer.h"
#include <signal.h>

using namespace std;

struct Args {
    bool debug;
    bool optimized;
    int numThreads;
    int threadsPerQueue;
    int parallelFactor;
    double startParam;
    double endParam;
    int chunkSize;
};

void handler(int sig) {
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

Args parseArguments(int argc, const char *const *argv) {
    Args args;
    namespace po = boost::program_options;
    po::options_description desc("Divide & Conquer Framework demo");
    desc.add_options()
            ("debug,v", po::bool_switch(&args.debug)->default_value(false), "Debug mode")
            ("optimized,o", po::bool_switch(&args.optimized)->default_value(false), "Run optimized version")
            ("numThreads,n", po::value<int>(&args.numThreads)->default_value(1), "Number of threads")
            ("startParam,s", po::value<double>(&args.startParam)->default_value(0), "start param")
            ("endParam,e", po::value<double>(&args.endParam)->default_value(100), "endParam")
            ("threadsPerQueue,q", po::value<int>(&args.threadsPerQueue)->default_value(1),
             "Number of threads per queue for optimized version")
            ("chunkSize,c", po::value<int>(&args.chunkSize)->default_value(1000),
             "Lock free factory chunk size");
    ("parallelFactor,p", po::value<int>(&args.parallelFactor)->default_value(1), "Num task gained at once per thread.");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    return args;
}

/**
 * usage
 * program [base_or_optimized] [numThreads] [threadsPerQueue] [parallelFactor]
 */
int main(int argc, char **argv) {
    signal(SIGSEGV, handler);   // install our handler
    Args config = parseArguments(argc, argv);

    IntProblem p;
    AbstractProblemSolver<IntParam, IntResult> *solver;
    if (!config.optimized) {
        cout << "\nrunning base solver";
        solver = new BaseProblemSolver<IntParam, IntResult>(p, config.numThreads);
    }
    else {
        cout << "\nrunning optimized solver";
        solver = new OptimizedProblemSolver<IntParam, IntResult>(p, config.numThreads, config.threadsPerQueue,
                                                                 config.parallelFactor, config.chunkSize);
    }

    // common config
    solver->debug = config.debug;

    // execution
    Timer timer;
    ThreadStats &threadStats = solver->getThreadStats();
    timer.start();
    IntResult d = solver->process({config.startParam, config.endParam});
    timer.stop();

    threadStats.calculate();
    cout << "\nresult: " << d
    << "\nduration: " << timer.getDurationString()
    << "\naverage load: " << threadStats.getAverage()
    << "\nstd deviation: " << threadStats.getStdDeviation()
    << "\n";

    // cleanup
    delete solver;
    return 0;
}<commit_msg>added help option<commit_after>#include <boost/program_options.hpp>
#include <iostream>
#include <execinfo.h>
#include "test/Problem.h"
#include "test/Timer.h"
#include <signal.h>

using namespace std;

struct Args {
    bool debug;
    bool optimized;
    int numThreads;
    int threadsPerQueue;
    int parallelFactor;
    double startParam;
    double endParam;
    int chunkSize;
};

void handler(int sig) {
    void *array[10];
    size_t size;

    // get void*'s for all entries on the stack
    size = backtrace(array, 10);

    // print out all the frames to stderr
    fprintf(stderr, "Error: signal %d:\n", sig);
    backtrace_symbols_fd(array, size, STDERR_FILENO);
    exit(1);
}

Args parseArguments(int argc, const char *const *argv) {
    Args args;
    namespace po = boost::program_options;
    po::options_description desc("Divide & Conquer Framework demo");
    desc.add_options()
            ("debug,v", po::bool_switch(&args.debug)->default_value(false), "Debug mode")
            ("optimized,o", po::bool_switch(&args.optimized)->default_value(false), "Run optimized version")
            ("numThreads,n", po::value<int>(&args.numThreads)->default_value(1), "Number of threads")
            ("startParam,s", po::value<double>(&args.startParam)->default_value(0), "start param")
            ("endParam,e", po::value<double>(&args.endParam)->default_value(100), "endParam")
            ("threadsPerQueue,q", po::value<int>(&args.threadsPerQueue)->default_value(1),
             "Number of threads per queue for optimized version")
            ("chunkSize,c", po::value<int>(&args.chunkSize)->default_value(1000),
             "Lock free factory chunk size")
            ("help,h", "produce help message");
    ("parallelFactor,p", po::value<int>(&args.parallelFactor)->default_value(1), "Num task gained at once per thread.");
    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);
    if (vm.count("help")) {
        cout << desc << "\n";
        exit (0);
    }
    return args;
}

/**
 * usage
 * program [base_or_optimized] [numThreads] [threadsPerQueue] [parallelFactor]
 */
int main(int argc, char **argv) {
    signal(SIGSEGV, handler);   // install our handler
    Args config = parseArguments(argc, argv);

    IntProblem p;
    AbstractProblemSolver<IntParam, IntResult> *solver;
    if (!config.optimized) {
        cout << "\nrunning base solver";
        solver = new BaseProblemSolver<IntParam, IntResult>(p, config.numThreads);
    }
    else {
        cout << "\nrunning optimized solver";
        solver = new OptimizedProblemSolver<IntParam, IntResult>(p, config.numThreads, config.threadsPerQueue,
                                                                 config.parallelFactor, config.chunkSize);
    }

    // common config
    solver->debug = config.debug;

    // execution
    Timer timer;
    ThreadStats &threadStats = solver->getThreadStats();
    timer.start();
    IntResult d = solver->process({config.startParam, config.endParam});
    timer.stop();

    threadStats.calculate();
    cout << "\nresult: " << d
    << "\nduration: " << timer.getDurationString()
    << "\naverage load: " << threadStats.getAverage()
    << "\nstd deviation: " << threadStats.getStdDeviation()
    << "\n";

    // cleanup
    delete solver;
    return 0;
}<|endoftext|>


<commit_before>c14eccc0-2747-11e6-881f-e0f84713e7b8<commit_msg>Did ANOTHER thing<commit_after>c163d85e-2747-11e6-a276-e0f84713e7b8<|endoftext|>


<commit_before>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>

static const GLfloat globVertexBufferData[] = {
  -1.0f, -1.0f,  0.0f,
   1.0f, -1.0f,  0.0f,
   0.0f,  1.0f,  0.0f,
};

bool checkShaderCompileStatus(GLuint obj) {
  GLint status;
  glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
  if(status == GL_FALSE) {
    GLint length;
    glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &length);
    std::vector<char> log((unsigned long)length);
    glGetShaderInfoLog(obj, length, &length, &log[0]);
    std::cerr << &log[0];
    return true;
  }
  return false;
}

bool checkProgramLinkStatus(GLuint obj) {
  GLint status;
  glGetProgramiv(obj, GL_LINK_STATUS, &status);
  if(status == GL_FALSE) {
    GLint length;
    glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &length);
    std::vector<char> log((unsigned long)length);
    glGetProgramInfoLog(obj, length, &length, &log[0]);
    std::cerr << &log[0];
    return true;
  }
  return false;
}

GLuint prepareProgram(bool *errorFlagPtr) {
  *errorFlagPtr = false;

  std::string vertexShaderSource = ""
          "#version 330 core\n"
          "layout(location = 0) in vec3 vertexPosition_modelspace;\n"
          "void main(){\n"
          "  gl_Position.xyz = vertexPosition_modelspace;\n"
          "  gl_Position.w = 1.0;\n"
          "}";

  GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
  const GLchar * const vertexShaderSourcePtr = vertexShaderSource.c_str();
  glShaderSource(vertexShaderId, 1, &vertexShaderSourcePtr, nullptr);
  glCompileShader(vertexShaderId);

  *errorFlagPtr = checkShaderCompileStatus(vertexShaderId);
  if(*errorFlagPtr) return 0;

  std::string fragmentShaderSource = ""
          "#version 330 core\n"
          "out vec3 color;\n"
          "void main() { color = vec3(1,0,0); }\n";

  GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
  const GLchar * const fragmentShaderSourcePtr = fragmentShaderSource.c_str();
  glShaderSource(fragmentShaderId, 1, &fragmentShaderSourcePtr, nullptr);
  glCompileShader(fragmentShaderId);

  *errorFlagPtr = checkShaderCompileStatus(fragmentShaderId);
  if(*errorFlagPtr) return 0;

  GLuint programId = glCreateProgram();
  glAttachShader(programId, vertexShaderId);
  glAttachShader(programId, fragmentShaderId);
  glLinkProgram(programId);

  *errorFlagPtr = checkProgramLinkStatus(programId);
  if(*errorFlagPtr) return 0;

  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  return programId;
}

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow* window = glfwCreateWindow(300, 300, "VAO and Shaders",
                                        nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    glfwDestroyWindow(window);
    glfwTerminate();
    return 1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  bool errorFlag;
  GLuint programId = prepareProgram(&errorFlag);
  if(errorFlag) {
    glfwDestroyWindow(window);
    glfwTerminate();
    return -1;
  }

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO
  glBindVertexArray(0); // unbind VAO

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    glBindVertexArray(vao);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);
  glDeleteProgram(programId);

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}
<commit_msg>Minor changes<commit_after>#include <GLXW/glxw.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>

static const GLfloat globVertexBufferData[] = {
  -1.0f, -1.0f,  0.0f,
   1.0f, -1.0f,  0.0f,
   0.0f,  1.0f,  0.0f,
};

bool checkShaderCompileStatus(GLuint obj) {
  GLint status;
  glGetShaderiv(obj, GL_COMPILE_STATUS, &status);
  if(status == GL_FALSE) {
    GLint length;
    glGetShaderiv(obj, GL_INFO_LOG_LENGTH, &length);
    std::vector<char> log((unsigned long)length);
    glGetShaderInfoLog(obj, length, &length, &log[0]);
    std::cerr << &log[0];
    return true;
  }
  return false;
}

bool checkProgramLinkStatus(GLuint obj) {
  GLint status;
  glGetProgramiv(obj, GL_LINK_STATUS, &status);
  if(status == GL_FALSE) {
    GLint length;
    glGetProgramiv(obj, GL_INFO_LOG_LENGTH, &length);
    std::vector<char> log((unsigned long)length);
    glGetProgramInfoLog(obj, length, &length, &log[0]);
    std::cerr << &log[0];
    return true;
  }
  return false;
}

GLuint prepareProgram(bool *errorFlagPtr) {
  *errorFlagPtr = false;

  std::string vertexShaderSource = ""
          "#version 330 core\n"
          "layout(location = 0) in vec3 vertexPos;\n"
          "void main(){\n"
          "  gl_Position.xyz = vertexPos;\n"
          "  gl_Position.w = 1.0;\n"
          "}";

  GLuint vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
  const GLchar * const vertexShaderSourcePtr = vertexShaderSource.c_str();
  glShaderSource(vertexShaderId, 1, &vertexShaderSourcePtr, nullptr);
  glCompileShader(vertexShaderId);

  *errorFlagPtr = checkShaderCompileStatus(vertexShaderId);
  if(*errorFlagPtr) return 0;

  std::string fragmentShaderSource = ""
          "#version 330 core\n"
          "out vec3 color;\n"
          "void main() { color = vec3(0,0,1); }\n";

  GLuint fragmentShaderId = glCreateShader(GL_FRAGMENT_SHADER);
  const GLchar * const fragmentShaderSourcePtr = fragmentShaderSource.c_str();
  glShaderSource(fragmentShaderId, 1, &fragmentShaderSourcePtr, nullptr);
  glCompileShader(fragmentShaderId);

  *errorFlagPtr = checkShaderCompileStatus(fragmentShaderId);
  if(*errorFlagPtr) return 0;

  GLuint programId = glCreateProgram();
  glAttachShader(programId, vertexShaderId);
  glAttachShader(programId, fragmentShaderId);
  glLinkProgram(programId);

  *errorFlagPtr = checkProgramLinkStatus(programId);
  if(*errorFlagPtr) return 0;

  glDeleteShader(vertexShaderId);
  glDeleteShader(fragmentShaderId);

  return programId;
}

void windowSizeCallback(GLFWwindow *, int width, int height) {
  glViewport(0, 0, width, height);
}

int main() {
  if(glfwInit() == GL_FALSE) {
    std::cerr << "Failed to initialize GLFW" << std::endl;
    return -1;
  }

  glfwDefaultWindowHints();

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

  GLFWwindow* window = glfwCreateWindow(300, 300, "VAO and Shaders",
                                        nullptr, nullptr);
  if(window == nullptr) {
    std::cerr << "Failed to open GLFW window" << std::endl;
    glfwTerminate();
    return -1;
  }

  glfwMakeContextCurrent(window);

  if(glxwInit()) {
    std::cerr << "Failed to init GLXW" << std::endl;
    glfwDestroyWindow(window);
    glfwTerminate();
    return 1;
  }

  glfwSwapInterval(1);

  glfwSetWindowSizeCallback(window, windowSizeCallback);

  glfwShowWindow(window);

  glEnable(GL_DEPTH_TEST | GL_DOUBLEBUFFER);
  glDepthFunc(GL_LESS);

  glClearColor(0, 0, 0, 1);

  bool errorFlag;
  GLuint programId = prepareProgram(&errorFlag);
  if(errorFlag) {
    glfwDestroyWindow(window);
    glfwTerminate();
    return -1;
  }

  GLuint vbo;
  glGenBuffers(1, &vbo);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(globVertexBufferData), globVertexBufferData, GL_STATIC_DRAW);

  GLuint vao;
  glGenVertexArrays(1, &vao);

  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
  glBindBuffer(GL_ARRAY_BUFFER, 0); // unbind VBO
  glBindVertexArray(0); // unbind VAO

  while(glfwWindowShouldClose(window) == GL_FALSE) {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(programId);

    glBindVertexArray(vao);
    glEnableVertexAttribArray(0);
    glDrawArrays(GL_TRIANGLES, 0, 3);
    glDisableVertexAttribArray(0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glDeleteVertexArrays(1, &vao);
  glDeleteBuffers(1, &vbo);
  glDeleteProgram(programId);

  glfwDestroyWindow(window);
  glfwTerminate();
  return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstdio>

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"

#define WIDTH  640
#define HEIGHT 480

using std::cout;
using std::endl;
using std::vector;

typedef struct {
    float x;
    float y;
    float z;
    bool is_new;
} Point3f;

const float BASE_SIZE = 3.5f;
const float DEPTH = -10.0f;
const int MAX_SUBDIVS = 5;

float disp = 2.5;
float down = 0.4;

int its = 0;
float angle = 0.0f;
bool split = false;

vector<Point3f> tri;

void init() {
    float r3 = 1.73205;

    glClearColor(0.0, 0.0, 1.0, 1.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45, (double) WIDTH/(double) HEIGHT, 1.0, 500.0);
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    float dif[] = {1.0, 1.0, 1.0, 1.0};
    float amb[] = {0.2, 0.2, 0.2, 1.0};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, dif);
    glLightfv(GL_LIGHT0, GL_AMBIENT, amb);

    Point3f p2; p2.x =        0.0; p2.y = BASE_SIZE *  r3 / 2.0; p2.z = 0.0; p2.is_new = false;
    Point3f p0; p0.x = -BASE_SIZE; p0.y = BASE_SIZE * -r3 / 2.0; p0.z = 0.0; p0.is_new = false;
    Point3f p1; p1.x =  BASE_SIZE; p1.y = BASE_SIZE * -r3 / 2.0; p1.z = 0.0; p1.is_new = false;

    tri.push_back(p0);
    tri.push_back(p1);
    tri.push_back(p2);
}

void init_SDL() {
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface* screen = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_SWSURFACE | SDL_OPENGL);
}

void print_point(Point3f p) {
    printf("X %+5.5f, Y %+5.5f, Z %+5.5f, N %d\n", p.x, p.y, p.z, p.is_new);
}

void print_tri() {
    int i;

    printf("TRIANGLE STATE:\n");

    for (i = 0; i < tri.size(); ++i) {
        print_point(tri.at(i));
        if ((i + 1) % 3 == 0) printf("\n");
    }
}

// Calculates 'n' for the triangle, where 'n' is the number of
// points along a side.
int calc_base(int size) {
    int total = 0;
    int base = 0;
    for (int i = 1; total < size; ++i) {
        total += i;
        ++base;
    }
    return base;
}

vector<Point3f> split_triangle(vector<Point3f>* tri) {
    int i;
    int j;

    Point3f p;
    Point3f mp0, mp1, mp2;

    int base = calc_base((*tri).size());
    int nbase = 2*base - 1;

    vector<Point3f> new_points;

    int idx = 0;
    for (i = base; i > 0; --i) {
        // Insert new 'alternating' new-old row of points
        for (j = 0; j < i; j++) {
            // Take 'next' existing point not yet incorporated
            // since the order will be the same in old & new arrays.
            new_points.push_back((*tri).at(idx++));
            if (j+1 != i) {
                Point3f np;
                np.is_new = true;
                new_points.push_back(np);
            }
        }
        // Is an all-new row required?
        // Yes if i-1 != 1
        // Need 2i-2
        if (i > 1) {
            for (j = 0; j < (2*i - 2); ++j) {
                Point3f np;
                np.is_new = true;
                new_points.push_back(np);
            }
        }
    }

    cout << new_points.size() << " vertices" << endl;

    // New points inserted
    // Now initialise them
    int offset = 0;
    for (i = nbase; i > 0; --i) {
        for (j = 0; j < i; ++j) {
            Point3f* p = &new_points.at(offset + j);
            if (i % 2) {
                // p might be new, and is in an
                // alternating old-new point row
                if (p->is_new) {
                    Point3f pl = new_points.at(offset + j - 1);
                    Point3f pr = new_points.at(offset + j + 1);
                    p->x = (pl.x + pr.x) / 2.0;
                    p->y = pl.y;
                    p->z = (pl.z + pr.z) / 2.0;
                }
            } else {
                // p is definitely new, as we're in
                // a brand new point row
                Point3f dl = new_points.at(offset + j - i - 1);
                Point3f dr = new_points.at(offset + j - i    );
                p->x = (dl.x + dr.x) / 2.0;
                if (j % 2) {
                    Point3f ul = new_points.at(offset + j + i - 1);
                    p->y = (dr.y + ul.y) / 2.0;
                    p->z = (dr.z + ul.z) / 2.0;
                } else {
                    Point3f ur = new_points.at(offset + j + i    );
                    p->y = (dl.y + ur.y) / 2.0;;
                    p->z = (dl.z + ur.z) / 2.0;;
                }
            }
            p->is_new = false;
        }
        offset += i;
    }

    // Vertically offset the vertices
    for (i = 0; i < new_points.size(); ++i) {
        new_points.at(i).z += disp * (float(rand()) / float(RAND_MAX)) - (disp / 2.);
        //new_points.at(i).y += 0.5 - 0.25 * (float(rand()) / float(RAND_MAX));
        //new_points.at(i).x += 0.5 - 0.25 * (float(rand()) / float(RAND_MAX));
    }

    disp *= down;
    return new_points;
}

float* cross_product(Point3f a, Point3f b, Point3f c) {
    float* v = new float[3];

    float* ab = new float[3];
    float* ac = new float[3];
    ab[0] = b.x - a.x; ab[1] = b.y - a.y; ab[2] = b.z - a.z;
    ac[0] = c.x - a.x; ac[1] = c.y - a.y; ac[2] = c.z - a.z;

    v[0] = (ab[1] * ac[2]) - (ab[2] * ac[1]);
    v[1] = (ab[2] * ac[0]) - (ab[0] * ac[2]);
    v[2] = (ab[0] * ac[1]) - (ab[1] * ac[0]);

    return v;
}

void display() {
    int i, j;
    int idx0, idx1, idx2;

    float pos[] = {-2.0, 2.0, -3.0, 1.0};
    float difamb[] = {1.0, 0.5, 0.3, 1.0};
    float* normal;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLightfv(GL_LIGHT0, GL_POSITION, pos);

    glLoadIdentity();

    glTranslatef(-0.5, -2.0, DEPTH);
    glRotatef(265, 0.1, 0.0, 0.0);
    glRotatef(angle, 0, 0, 1);
    angle += 0.8;

    int base = calc_base(tri.size());
    int offset = 0;

    glBegin(GL_TRIANGLES);
    for (i = base; i > 0; --i) {
        for (j = 0; j < i - 1; ++j) {
            idx0 = offset + j; idx1 = offset + j + 1; idx2 = offset + j + i;
            normal = cross_product(tri.at(idx0), tri.at(idx1), tri.at(idx2));
            //glColor3f(rand() % 100 / 100.0f, rand() % 100 / 100.0f, rand() % 100 / 100.0f);
            glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, difamb);
            glNormal3f(normal[0], normal[1], normal[2]);

            // Pointy-uppy triangles
            glVertex3f(tri.at(idx0).x, tri.at(idx0).y, tri.at(idx0).z);
            glVertex3f(tri.at(idx1).x, tri.at(idx1).y, tri.at(idx1).z);
            glVertex3f(tri.at(idx2).x, tri.at(idx2).y, tri.at(idx2).z);

            if (j > 0 && (j+1) < i) {
                idx0 = offset + j; idx1 = offset + j + i - 1; idx2 = offset + j + i;
                normal = cross_product(tri.at(idx0), tri.at(idx1), tri.at(idx2));
                glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, difamb);
                glNormal3f(normal[0], normal[1], normal[2]);

                // Pointy-downy triangles
                glVertex3f(tri.at(idx0).x, tri.at(idx0).y, tri.at(idx0).z);
                glVertex3f(tri.at(idx1).x, tri.at(idx1).y, tri.at(idx1).z);
                glVertex3f(tri.at(idx2).x, tri.at(idx2).y, tri.at(idx2).z);
            }
        }
        offset += i;
    }
    glEnd();
    glFlush();

    if /*(its < MAX_SUBDIVS)*/ (split) { ++its; split = false; tri = split_triangle(&tri);}

    //SDL_Delay(1000);
}

int main(void) {
    bool running = true;
    Uint32 start;
    SDL_Event event;

    init_SDL();
    init();

    while (running) {
        start = SDL_GetTicks();
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    running = false;
                    break;
                case SDL_KEYDOWN:
                    switch (event.key.keysym.sym) {
                        case SDLK_s:
                            split = true;
                            break;
                    }
                    break;
            }
        }
        display();
        SDL_GL_SwapBuffers();
        if (1000 / 30 > (SDL_GetTicks() - start)) SDL_Delay(1000 / 30 - (SDL_GetTicks() - start));
    }
}
<commit_msg>[IMP] Comments, improved variable usage.<commit_after>#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstdio>

#include "SDL/SDL.h"
#include "SDL/SDL_opengl.h"

#define WIDTH  640
#define HEIGHT 480

using std::cout;
using std::endl;
using std::vector;

/* The 3D points from which our
 * triangle-based terrain mesh
 * will be built.
 */
typedef struct {
    float x;
    float y;
    float z;
    bool is_new;
} Point3f;

// Parameters for OpenGL rendering
const float BASE_SIZE = 3.5f;
const float DEPTH = -10.f;
const float CAM_PITCH = 265.f;
const float DELTA_ROTATE = 0.8f;

// Subdivision iterations
const int MAX_SUBDIVS = 5;

// Magnitude of vertical vertex
// displacement
float disp = 2.5;

// Damping factor by which 'disp'
// will be multiplied on each
// iteration.
float down = 0.4;

bool split = false;

vector<Point3f> tri;

void init() {
    float r3 = 1.73205;

    glClearColor(0.0, 0.0, 0.2, 1.0); glMatrixMode(GL_PROJECTION); glLoadIdentity();
    gluPerspective(45, (double) WIDTH/(double) HEIGHT, 1.0, 500.0);
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    float dif[] = {1.0, 1.0, 1.0, 1.0};
    float amb[] = {0.2, 0.2, 0.2, 1.0};
    glLightfv(GL_LIGHT0, GL_DIFFUSE, dif);
    glLightfv(GL_LIGHT0, GL_AMBIENT, amb);

    Point3f p2; p2.x =        0.0; p2.y = BASE_SIZE *  r3 / 2.0; p2.z = 0.0; p2.is_new = false;
    Point3f p0; p0.x = -BASE_SIZE; p0.y = BASE_SIZE * -r3 / 2.0; p0.z = 0.0; p0.is_new = false;
    Point3f p1; p1.x =  BASE_SIZE; p1.y = BASE_SIZE * -r3 / 2.0; p1.z = 0.0; p1.is_new = false;

    tri.push_back(p0);
    tri.push_back(p1);
    tri.push_back(p2);
}

void init_SDL() {
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface* screen = SDL_SetVideoMode(WIDTH, HEIGHT, 32, SDL_SWSURFACE | SDL_OPENGL);
}

void print_point(Point3f p) {
    printf("X %+5.5f, Y %+5.5f, Z %+5.5f, N %d\n", p.x, p.y, p.z, p.is_new);
}

void print_tri() {
    int i;

    printf("TRIANGLE STATE:\n");

    for (i = 0; i < tri.size(); ++i) {
        print_point(tri.at(i));
        if ((i + 1) % 3 == 0) printf("\n");
    }
}

/* Calculates 'n' for the triangle, where 'n'
   is the number of points along a side.
*/
int calc_base(int size) {
    int total = 0;
    int base = 0;
    for (int i = 1; total < size; ++i) {
        total += i;
        ++base;
    }
    return base;
}

/* Take a vector of points representing a
 * triangle-based terrain and operate on it
 * such that each triangle in the mesh is
 * split into four smaller triangles.
 */
void subdivide_terrain(vector<Point3f>* tri) {
    int i;
    int j;

    Point3f p;
    Point3f mp0, mp1, mp2;

    int base = calc_base((*tri).size());
    int nbase = 2*base - 1;

    int idx = 0;
    int ins_idx = 0;

    /* Subdivide the triangular terrain by
     * inserting new points into the vector.
     *
     * For each row of vertices, introduce a
     * new vertex in every odd-indexed position
     * remembering that we're zero-indexing).
     * After this, introduce enough points to
     * consitutea whole new row of vertices in
     * the triangle, of length n-1 (where 'n'
     * is the number of vertices now in the row
     * which we just 'inflated'.
     */
    for (i = base; i > 0; --i) {
        // Insert new points in odd-indexed positions
        for (j = 0; j < i; j++) {
            ins_idx++;
            if (j+1 != i) {
                Point3f np;
                np.is_new = true;
                (*tri).insert((*tri).begin() + ins_idx++, np);
            }
        }
        /* Introduce a new row if we haven't
         * yet reached the tip of the triangle.
         * The number of points needed turns out
         * to be 2i-2.
         */
        if (i > 1) {
            for (j = 0; j < (2*i - 2); ++j) {
                Point3f np;
                np.is_new = true;
                (*tri).insert((*tri).begin() + ins_idx++, np);
            }
        }
    }

    /* New points have now been inserted into the
     * triangular terrain, although they have not
     * yet been initialised with co-ordinates.
     *
     * The triangluar terrain can be thought of
     * as rows of vertices. These rows currently
     * consist of two types; those whose points
     * have all just been added to the triangle,
     * and those which contain some pre-existing
     * ('old') points, in which case they will
     * alternate old-new-old-new...
     *
     * Calculation of each new point's initial
     * co-ordinates depends on which 'type' of
     * row the point belongs to. On an alternating
     * old-new row, all co-ordinates can be
     * derived based on the points either side of
     * it in the row. On completely-new rows
     * however, these values must be calculated
     * based on points in the rows below and above
     * (note that these will always exist, since
     * we never insert * a new row below the base
     * edge or above the tip).
     *
     * Moving from a flat edge to the tip, row 0
     * and all other even-numbered rows will
     * alternate old-new, whilst row 1 and all
     * other odd-numbered rows will consist
     * exclusively of new points.
     */
    int offset = 0;
    for (i = nbase; i > 0; --i) {
        for (j = 0; j < i; ++j) {
            Point3f* p = &(*tri).at(offset + j);
            if (i % 2) {
                // p may or may not be new, as it is in
                // an alternating old-new row of points
                if (p->is_new) {
                    Point3f pl = (*tri).at(offset + j - 1);
                    Point3f pr = (*tri).at(offset + j + 1);
                    p->x = (pl.x + pr.x) / 2.0;
                    p->y = pl.y;
                    p->z = (pl.z + pr.z) / 2.0;
                }
            } else {
                // p is definitely new, as we're in
                // a brand new row of points
                Point3f dl = (*tri).at(offset + j - i - 1);
                Point3f dr = (*tri).at(offset + j - i    );
                p->x = (dl.x + dr.x) / 2.0;
                if (j % 2) {
                    Point3f ul = (*tri).at(offset + j + i - 1);
                    p->y = (dr.y + ul.y) / 2.0;
                    p->z = (dr.z + ul.z) / 2.0;
                } else {
                    Point3f ur = (*tri).at(offset + j + i    );
                    p->y = (dl.y + ur.y) / 2.0;;
                    p->z = (dl.z + ur.z) / 2.0;;
                }
            }
            p->is_new = false;
        }
        offset += i;
    }
}

void distort_terrain(vector<Point3f>* tri) {
    // Vertically offset the vertices
    for (int i = 0; i < (*tri).size(); ++i) {
        (*tri).at(i).z += disp * (float(rand()) / float(RAND_MAX)) - (disp / 2.);
        //(*tri).at(i).y += 0.5 - 0.25 * (float(rand()) / float(RAND_MAX));
        //(*tri).at(i).x += 0.5 - 0.25 * (float(rand()) / float(RAND_MAX));
    }

    disp *= down;
}

/* Simple function to calculate the cross-product
 * of three 3D vectors
 */
float* cross_product(Point3f a, Point3f b, Point3f c) {
    float* v = new float[3];

    float* ab = new float[3];
    float* ac = new float[3];
    ab[0] = b.x - a.x; ab[1] = b.y - a.y; ab[2] = b.z - a.z;
    ac[0] = c.x - a.x; ac[1] = c.y - a.y; ac[2] = c.z - a.z;

    v[0] = (ab[1] * ac[2]) - (ab[2] * ac[1]);
    v[1] = (ab[2] * ac[0]) - (ab[0] * ac[2]);
    v[2] = (ab[0] * ac[1]) - (ab[1] * ac[0]);

    return v;
}

/* Using OpenGL, render the terrain.
 */
void display(vector<Point3f>* tri) {
    int i, j;
    int idx0, idx1, idx2;

    float pos[] = {-2.0, 2.0, -3.0, 1.0};
    float difamb[] = {1.0, 0.5, 0.3, 1.0};
    float* normal;

    static float angle = 0.f;

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLightfv(GL_LIGHT0, GL_POSITION, pos);

    glLoadIdentity();

    glTranslatef(-0.5, -2.0, DEPTH);
    glRotatef(CAM_PITCH, 0.1, 0.0, 0.0);
    glRotatef(angle, 0, 0, 1);
    angle += DELTA_ROTATE;

    int base = calc_base((*tri).size());
    int offset = 0;

    glBegin(GL_TRIANGLES);
    for (i = base; i > 0; --i) {
        for (j = 0; j < i - 1; ++j) {
            idx0 = offset + j; idx1 = offset + j + 1; idx2 = offset + j + i;
            normal = cross_product((*tri).at(idx0), (*tri).at(idx1), (*tri).at(idx2));
            glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, difamb);
            glNormal3f(normal[0], normal[1], normal[2]);

            // Pointy-uppy triangles
            glVertex3f((*tri).at(idx0).x, (*tri).at(idx0).y, (*tri).at(idx0).z);
            glVertex3f((*tri).at(idx1).x, (*tri).at(idx1).y, (*tri).at(idx1).z);
            glVertex3f((*tri).at(idx2).x, (*tri).at(idx2).y, (*tri).at(idx2).z);

            if (j > 0 && (j+1) < i) {
                idx0 = offset + j; idx1 = offset + j + i - 1; idx2 = offset + j + i;
                normal = cross_product((*tri).at(idx0), (*tri).at(idx1), (*tri).at(idx2));
                glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, difamb);
                glNormal3f(normal[0], normal[1], normal[2]);

                // Pointy-downy triangles
                glVertex3f((*tri).at(idx0).x, (*tri).at(idx0).y, (*tri).at(idx0).z);
                glVertex3f((*tri).at(idx1).x, (*tri).at(idx1).y, (*tri).at(idx1).z);
                glVertex3f((*tri).at(idx2).x, (*tri).at(idx2).y, (*tri).at(idx2).z);
            }
        }
        offset += i;
    }
    glEnd();
    glFlush();
}

int main(void) {
    bool running = true;
    Uint32 start;
    SDL_Event event;

    init_SDL();
    init();

    for (int i = 0; i < MAX_SUBDIVS; ++i) {
        subdivide_terrain(&tri);
        distort_terrain(&tri);
    }

    while (running) {
        start = SDL_GetTicks();
        while (SDL_PollEvent(&event)) {
            switch (event.type) {
                case SDL_QUIT:
                    running = false;
                    break;
                case SDL_KEYDOWN:
                    switch (event.key.keysym.sym) {
                        case SDLK_s:
                            split = true;
                            break;
                        case SDLK_ESCAPE:
                            running = false;
                            break;
                    }
                    break;
            }
        }
        //if (its < MAX_SUBDIVS || split) {
        //    ++its;
        //    split = false;
        //    subdivide_triangle(&tri);
        //}

        display(&tri);

        SDL_GL_SwapBuffers();

        if (1000 / 60 > (SDL_GetTicks() - start))
            SDL_Delay(1000 / 60 - (SDL_GetTicks() - start));
    }
}
<|endoftext|>