<commit_before>#include <stdio.h>
#include <stdlib.h>

#include <string>
#include <iostream>
#include <utility>
#include <unordered_set>
#include <unordered_map>
using namespace std;

#include "scx/Dir.hpp"
#include "scx/FileInfo.hpp"
using namespace scx;

#include "Tools.h"
#include "ConsUnit.h"
#include "Parallel.h"

static const unordered_set<string> C_EXT = { "c" };
static const unordered_set<string> CXX_EXT = { "cc", "cxx", "cpp", "C" };
static const unordered_set<string> ASM_EXT = { "s", "S", "asm", "nas" };

static void Usage(const string& cmd)
{
    const string sp(cmd.size(), ' ');
    cout << ""
        "Usage:\n"
        "\t" + cmd + " [ file1 file1 | dir1 dir2 ]\n"
        "\t" + sp + " cc=?        C compiler.\n"
        "\t" + sp + " cxx=?       C++ compiler.\n"
        "\t" + sp + " flag=?      Compiler flag.\n"
        "\t" + sp + " ld=?        Linker.\n"
        "\t" + sp + " ldflag=?    Linker flag.\n"
        "\t" + sp + " ldfirst=?   First object file.\n"
        "\t" + sp + " as=?        Assembler.\n"
        "\t" + sp + " asflag=?    Assembler flag.\n"
        "\t" + sp + " jobs=?      Parallel build.\n"
        "\t" + sp + " workdir=?   Work direcotry.\n"
        "\t" + sp + " out=?       Binary output file name.\n"
        "\t" + sp + " prefix=?    Search head file and library in.\n"
        "\t" + sp + " nlink       Do not link.\n"
        "\t" + sp + " verbose     Verbose output.\n"
        "\t" + sp + " clean       Clean build output.\n"
        "\t" + sp + " help        Show this help message.\n"
        "\n"
        "\t" + sp + " shared      Generate shared library. (*)\n"
        "\t" + sp + " g           -g (*)\n"
        "\t" + sp + " c++11       -std=c++11 (*)\n"
        "\t" + sp + " c++1y       -std=c++1y (*)\n"
        "\t" + sp + " thread      Link against pthread. (*)\n"
        "\n";

    cout << ""
        "Note:\n"
        "\t* Just for convenient. You may also use flags to approach the function.\n"
        "\n";

    cout << ""
        "Author:\n"
        "\tYanhui Shen <@bsdelf on Twitter>\n";
}

int main(int argc, char** argv)
{
    unordered_map<string, string> ArgTable = {
        {   "cc",       "cc"    },
        {   "cxx",      "c++"   },
        {   "flag",     ""      },
        {   "ld",       "cc"    },
        {   "ldflag",   ""      },
        {   "ldfirst",  ""      },
        {   "as",       "as"    },
        {   "asflag",   ""      },
        {   "jobs",     "0"     },
        {   "workdir",  ""      },
        {   "out",      "b.out" }
    };

    bool clean = false;
    bool nlink = false;
    bool verbose = false;
    vector<string> allsrc;
    vector<string> prefixes;

    // Parse arguments.
    {
        bool useShared = false;
        bool useDebug = false;
        bool usePipe = true;
        bool useCXX11 = false;
        bool useCXX1y = false;
        bool useThread = false;

        for (int i = 1; i < argc; ++i) {
            const string& arg(argv[i]);

            // So obvisously, file name should not contain '='.
            size_t pos = arg.find('=');
            if (pos != string::npos && pos != arg.size()-1) {
                const auto& key = arg.substr(0, pos);
                const auto& val = arg.substr(pos+1);
                // Update key-value.
                auto iter = ArgTable.find(key);
                if (iter != ArgTable.end()) {
                    iter->second = val;
                } else if (key == "prefix") {
                    prefixes.push_back(val);
                } else {
                    cout << "Argument ignored!" << endl;
                    cout << "    Argument: " << arg << endl;
                }
            } else if (arg == "help") {
                Usage(argv[0]);
                return 0;
            } else if (arg == "verbose") {
                verbose = true;
            } else if (arg == "nlink") {
                nlink = true;
            } else if (arg == "clean") {
                clean = true;
            } else if (arg == "g") {
                useDebug = true;
            } else if (arg == "shared") {
                useShared = true;
            } else if (arg == "c++11") {
                useCXX11 = true;
            } else if (arg == "c++1y") {
                useCXX1y = true;
            } else if (arg == "thread") {
                useThread = true;
            } else {
                // Add source files
                switch (FileInfo(arg).Type()) {
                case FileType::Directory:
                    {
                        const auto& files = Dir::ListDir(arg);
                        allsrc.reserve(allsrc.size() + files.size());
                        allsrc.insert(allsrc.end(), files.begin(), files.end());
                    }
                    break;

                case FileType::Regular:
                    {
                        allsrc.push_back(arg);
                    }
                    break;

                default:
                    {
                        cerr << "FATAL: bad argument: " << endl;
                        cerr << "arg: " << arg << endl;
                        return -1;
                    }
                    break;
                }
            }
        }

        if (!ArgTable["flag"].empty())
            ArgTable["flag"].insert(0, 1, ' ');

        if (!ArgTable["ldflag"].empty()) {
            ArgTable["ldflag"].insert(0, 1, ' ');
        }

        for (const auto& prefix: prefixes) {
            ArgTable["flag"] += " -I " + prefix + "/include";
            ArgTable["ldflag"] += " -L " + prefix + "/lib";
        }

        if (!ArgTable["workdir"].empty()) {
            auto& dir = ArgTable["workdir"];
            if (dir[dir.size()-1] != '/')
                dir += "/";
            const auto& info = FileInfo(dir);
            if (!info.Exists()) {
                if (!Dir::MakeDir(dir, 0744)) {
                    cerr << "Failed to create directory!" << endl;
                    cerr << "    Directory: " << dir << endl;
                    return -1;
                }
            } else if (info.Type() != FileType::Directory) {
                cerr << "Bad work directory! " << endl;
                cerr << "    Directory: " << dir << endl;
                cerr << "    File type: " << FileType::ToString(info.Type()) << endl;
                return -1;
            }
        }

        if (useDebug)
            ArgTable["flag"] += " -g";

        if (usePipe) {
            ArgTable["flag"] += " -pipe";
        }

        if (useShared) {
            ArgTable["flag"] += " -fPIC";
            ArgTable["ldflag"] += " -shared";
        }

        if (useThread) {
            ArgTable["ldflag"] += " -pthread";
        }

        if (useCXX11) {
            ArgTable["flag"] += " -std=c++11";
        } else if (useCXX1y) {
            ArgTable["flag"] += " -std=c++1y";
        }

        // By default we'll take all files under current folder
        if (allsrc.empty())
            allsrc = Dir::ListDir(".");

        if (allsrc.empty()) {
            cerr << "FATAL: nothing to build!" << endl;
            return -1;
        }
    }

    // Prepare construct units.
    // Note: "workdir" & "out" should occur together
    bool hasCpp = false;
    bool hasOut = FileInfo(ArgTable["workdir"] + ArgTable["out"]).Exists();
    vector<ConsUnit> newUnits;
    string allObjects;

    for (const auto& file: allsrc) {
        ConsUnit unit(ArgTable["workdir"], file);
        string compiler;
        string compilerFlag;

        // Calculate dependence.
        bool ok = false;
        const string ext(FileInfo(file).Suffix());
        if (C_EXT.find(ext) != C_EXT.end()) {
            compiler = ArgTable["cc"];
            compilerFlag = ArgTable["flag"];
            ok = ConsUnit::InitC(unit, compiler, compilerFlag);
        } else if (CXX_EXT.find(ext) != CXX_EXT.end()) {
            hasCpp = true;
            compiler = ArgTable["cxx"];
            compilerFlag = ArgTable["flag"];
            ok = ConsUnit::InitCpp(unit, compiler, compilerFlag);
        } else if (ASM_EXT.find(ext) != ASM_EXT.end()) {
            compiler = ArgTable["as"];
            compilerFlag = ArgTable["asflag"];
            ok = ConsUnit::InitAsm(unit, compiler, compilerFlag);
        } else {
            continue;
        }

        if (ok) {
            if (unit.out == ArgTable["ldfirst"])
                allObjects = " " + unit.out + allObjects;
            else
                allObjects += " " + unit.out;
            if (!unit.cmd.empty())
                newUnits.push_back(std::move(unit));
        } else {
            cerr << "FATAL: failed to calculate dependence!" << endl;
            cerr << "    file:     " << file << endl;
            cerr << "    compiler: " << compiler << endl;
            cerr << "    flag:     " << ArgTable["flag"] << endl;
            return -1;
        }
    }

    if (hasCpp)
        ArgTable["ld"] = ArgTable["cxx"];

#ifdef DEBUG
    // Debug info.
    {
        auto fn = [](const vector<ConsUnit>& units)->void {
            for (const auto& unit: units) {
                cout << "in: " <<  unit.in << ", " << "out: " << unit.out << endl;
                cout << "\t" << unit.cmd << endl;
                cout << "\t";
                for (const auto& dep: unit.deps)
                    cout << dep << ", ";
                cout << endl;
            }
        };
        cout << "new units: " << endl;
        fn(newUnits);
    }
#endif

    // clean
    if (clean) {
        const string& cmd = "rm -f " + ArgTable["workdir"] + ArgTable["out"] + allObjects;
        cout << cmd << endl;
        ::system(cmd.c_str());
        return 0;
    }

    // compile
    if (!newUnits.empty()) {
        cout << "* Build: ";
        if (!verbose) {
            cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file");
        } else {
            for (size_t i = 0; i < newUnits.size(); ++i) {
                cout << newUnits[i].in << ((i+1 < newUnits.size()) ? ", " : "");
            }
        }
        cout << endl;

        ParallelCompiler pc(newUnits);
        pc.SetVerbose(verbose);
        if (pc.Run(std::stoi(ArgTable["jobs"])) != 0)
            return -1;
    }

    // link
    if ((!hasOut || !newUnits.empty()) && !nlink) {
        string ldCmd = ArgTable["ld"] + ArgTable["ldflag"];
        ldCmd += " -o " + ArgTable["workdir"] + ArgTable["out"] + allObjects;

        if (!verbose)
            cout << "- Link - " << ArgTable["workdir"] + ArgTable["out"] << endl;
        else
            cout << "- Link - " << ldCmd << endl;
        if (::system(ldCmd.c_str()) != 0) {
            cerr << "FATAL: failed to link!" << endl;
            cerr << "    file:   " << allObjects << endl;
            cerr << "    ld:     " << ArgTable["ld"] << endl;
            cerr << "    ldflag: " << ArgTable["ldflag"] << endl;
            return -2;
        }
    }

    return 0;
}
<commit_msg>* introduce ccflag, cppflag, c++14, c++1z<commit_after>#include <stdio.h>
#include <stdlib.h>

#include <string>
#include <iostream>
#include <utility>
#include <unordered_set>
#include <unordered_map>
using namespace std;

#include "scx/Dir.hpp"
#include "scx/FileInfo.hpp"
using namespace scx;

#include "Tools.h"
#include "ConsUnit.h"
#include "Parallel.h"

static const unordered_set<string> C_EXT = { "c" };
static const unordered_set<string> CXX_EXT = { "cc", "cxx", "cpp", "C" };
static const unordered_set<string> ASM_EXT = { "s", "S", "asm", "nas" };

static void Usage(const string& cmd)
{
    const string sp(cmd.size(), ' ');
    cout << ""
        "Usage:\n"
        "\t" + cmd + " [ file1 file2 ... | dir1 dir2 ... ]\n"
        "\t" + sp + " as=?        Assembler.\n"
        "\t" + sp + " asflag=?    Assembler flag.\n"
        "\t" + sp + " cc=?        C compiler.\n"
        "\t" + sp + " ccflag=?    C Compiler flag.\n"
        "\t" + sp + " cpp=?       C++ compiler.\n"
        "\t" + sp + " cppflag=?   C++ Compiler flag.\n"
        "\t" + sp + " flag=?      Compiler Common flag.\n"
        "\t" + sp + " ld=?        Linker.\n"
        "\t" + sp + " ldflag=?    Linker flag.\n"
        "\t" + sp + " ldfirst=?   First object file.\n"
        "\t" + sp + " jobs=?      Parallel build.\n"
        "\t" + sp + " workdir=?   Work direcotry.\n"
        "\t" + sp + " out=?       Binary output file name.\n"
        "\t" + sp + " prefix=?    Search head file and library in.\n"
        "\t" + sp + " nlink       Do not link.\n"
        "\t" + sp + " verbose     Verbose output.\n"
        "\t" + sp + " clean       Clean build output.\n"
        "\t" + sp + " help        Show this help message.\n"
        "\n"
        "\t" + sp + " shared      Generate shared library. (*)\n"
        "\t" + sp + " g           -g (*)\n"
        "\t" + sp + " c++11       -std=c++11 (*)\n"
        "\t" + sp + " c++14       -std=c++14 (*)\n"
        "\t" + sp + " c++1y       -std=c++1y (*)\n"
        "\t" + sp + " c++1z       -std=c++1z (*)\n"
        "\t" + sp + " thread      Link against pthread. (*)\n"
        "\n";

    cout << ""
        "Note:\n"
        "\t* Just for convenient. You may also use flags to approach the function.\n"
        "\n";

    cout << ""
        "Author:\n"
        "\tYanhui Shen <@bsdelf on Twitter>\n";
}

int main(int argc, char** argv)
{
    unordered_map<string, string> ArgTable = {
        {   "as",       "as"    },
        {   "asflag",   ""      },
        {   "cc",       "cc"    },
        {   "ccflag",   ""      },
        {   "cpp",      "c++"   },
        {   "cppflag",  ""      },
        {   "flag",     ""      },
        {   "ld",       "cc"    },
        {   "ldflag",   ""      },
        {   "ldfirst",  ""      },
        {   "jobs",     "0"     },
        {   "workdir",  ""      },
        {   "out",      "b.out" }
    };

    bool clean = false;
    bool nlink = false;
    bool verbose = false;
    vector<string> allsrc;
    vector<string> prefixes;

    // Parse arguments.
    {
        bool useShared = false;
        bool useDebug = false;
        bool usePipe = true;
        bool useC89 = false;
        bool useC99 = true;
        bool useCXX11 = false;
        bool useCXX14 = false;
        bool useCXX1y = false;
        bool useCXX1z = false;
        bool useThread = false;

        for (int i = 1; i < argc; ++i) {
            const string& arg(argv[i]);

            // So obvisously, file name should not contain '='.
            size_t pos = arg.find('=');
            if (pos != string::npos && pos != arg.size()-1) {
                const auto& key = arg.substr(0, pos);
                const auto& val = arg.substr(pos+1);
                // Update key-value.
                auto iter = ArgTable.find(key);
                if (iter != ArgTable.end()) {
                    iter->second = val;
                } else if (key == "prefix") {
                    prefixes.push_back(val);
                } else {
                    cout << "Argument ignored!" << endl;
                    cout << "    Argument: " << arg << endl;
                }
            } else if (arg == "help") {
                Usage(argv[0]);
                return 0;
            } else if (arg == "verbose") {
                verbose = true;
            } else if (arg == "nlink") {
                nlink = true;
            } else if (arg == "clean") {
                clean = true;
            } else if (arg == "g") {
                useDebug = true;
            } else if (arg == "shared") {
                useShared = true;
            } else if (arg == "c89") {
                useC89 = true;
            } else if (arg == "c99") {
                useC99 = true;
            } else if (arg == "c++11") {
                useCXX11 = true;
            } else if (arg == "c++14") {
                useCXX14 = true;
            } else if (arg == "c++1y") {
                useCXX1y = true;
            } else if (arg == "c++1z") {
                useCXX1z = true;
            } else if (arg == "thread") {
                useThread = true;
            } else {
                // Add source files
                switch (FileInfo(arg).Type()) {
                case FileType::Directory:
                    {
                        const auto& files = Dir::ListDir(arg);
                        allsrc.reserve(allsrc.size() + files.size());
                        allsrc.insert(allsrc.end(), files.begin(), files.end());
                    }
                    break;

                case FileType::Regular:
                    {
                        allsrc.push_back(arg);
                    }
                    break;

                default:
                    {
                        cerr << "FATAL: bad argument: " << endl;
                        cerr << "arg: " << arg << endl;
                        return -1;
                    }
                    break;
                }
            }
        }

        if (!ArgTable["workdir"].empty()) {
            auto& dir = ArgTable["workdir"];
            if (dir[dir.size()-1] != '/')
                dir += "/";
            const auto& info = FileInfo(dir);
            if (!info.Exists()) {
                if (!Dir::MakeDir(dir, 0744)) {
                    cerr << "Failed to create directory!" << endl;
                    cerr << "    Directory: " << dir << endl;
                    return -1;
                }
            } else if (info.Type() != FileType::Directory) {
                cerr << "Bad work directory! " << endl;
                cerr << "    Directory: " << dir << endl;
                cerr << "    File type: " << FileType::ToString(info.Type()) << endl;
                return -1;
            }
        }

        //-------------------------------------------------------------
        // additional compiler common flag

        if (!ArgTable["flag"].empty()) {
            ArgTable["flag"].insert(0, 1, ' ');
        }

        for (const auto& prefix: prefixes) {
            ArgTable["flag"] += " -I " + prefix + "/include";
            ArgTable["ldflag"] += " -L " + prefix + "/lib";
        }

        if (useDebug) {
            ArgTable["flag"] += " -g";
        }

        if (usePipe) {
            ArgTable["flag"] += " -pipe";
        }

        if (useShared) {
            ArgTable["flag"] += " -fPIC";
            ArgTable["ldflag"] += " -shared";
        }

        //-------------------------------------------------------------
        // additional link flag

        if (!ArgTable["ldflag"].empty()) {
            ArgTable["ldflag"].insert(0, 1, ' ');
        }

        if (useThread) {
            ArgTable["ldflag"] += " -pthread";
        }

        //-------------------------------------------------------------
        // additional c/c++ compiler flag

        if (ArgTable["ccflag"].empty()) {
            ArgTable["ccflag"] = ArgTable["flag"];
        } else {
            ArgTable["ccflag"].insert(0, ArgTable["flag"] + " ");
        }

        if (useC89) {
            ArgTable["ccflag"] += " -std=c89";
        } else if (useC99) {
            ArgTable["ccflag"] += " -std=c99";
        }

        if (ArgTable["cppflag"].empty()) {
            ArgTable["cppflag"] = ArgTable["flag"];
        } else {
            ArgTable["cppflag"].insert(0, ArgTable["flag"] + " ");
        }

        if (useCXX11) {
            ArgTable["cppflag"] += " -std=c++11";
        } else if (useCXX14) {
            ArgTable["cppflag"] += " -std=c++14";
        } else if (useCXX1y) {
            ArgTable["cppflag"] += " -std=c++1y";
        } else if (useCXX1z) {
            ArgTable["cppflag"] += " -std=c++1z";
        }

        //-------------------------------------------------------------

        // if unspecified, take all files under current folder
        if (allsrc.empty()) {
            allsrc = Dir::ListDir(".");
        }

        if (allsrc.empty()) {
            cerr << "FATAL: nothing to build!" << endl;
            return -1;
        }
    }

    // Prepare construct units.
    // Note: "workdir" & "out" should occur together
    bool hasCpp = false;
    bool hasOut = FileInfo(ArgTable["workdir"] + ArgTable["out"]).Exists();
    vector<ConsUnit> newUnits;
    string allObjects;

    for (const auto& file: allsrc) {
        ConsUnit unit(ArgTable["workdir"], file);
        string compiler;
        string compilerFlag;

        // Calculate dependence.
        bool ok = false;
        const string ext(FileInfo(file).Suffix());
        if (C_EXT.find(ext) != C_EXT.end()) {
            compiler = ArgTable["cc"];
            compilerFlag = ArgTable["ccflag"];
            ok = ConsUnit::InitC(unit, compiler, compilerFlag);
        } else if (CXX_EXT.find(ext) != CXX_EXT.end()) {
            hasCpp = true;
            compiler = ArgTable["cpp"];
            compilerFlag = ArgTable["cppflag"];
            ok = ConsUnit::InitCpp(unit, compiler, compilerFlag);
        } else if (ASM_EXT.find(ext) != ASM_EXT.end()) {
            compiler = ArgTable["as"];
            compilerFlag = ArgTable["asflag"];
            ok = ConsUnit::InitAsm(unit, compiler, compilerFlag);
        } else {
            continue;
        }

        if (ok) {
            if (unit.out == ArgTable["ldfirst"])
                allObjects = " " + unit.out + allObjects;
            else
                allObjects += " " + unit.out;
            if (!unit.cmd.empty())
                newUnits.push_back(std::move(unit));
        } else {
            cerr << "FATAL: failed to calculate dependence!" << endl;
            cerr << "    file:     " << file << endl;
            cerr << "    compiler: " << compiler << endl;
            cerr << "    flag:     " << ArgTable["flag"] << endl;
            cerr << "    ccflag:   " << ArgTable["ccflag"] << endl;
            cerr << "    cppflag:  " << ArgTable["cppflag"] << endl;
            return -1;
        }
    }

    if (hasCpp) {
        ArgTable["ld"] = ArgTable["cpp"];
    }

#ifdef DEBUG
    // Debug info.
    {
        auto fn = [](const vector<ConsUnit>& units)->void {
            for (const auto& unit: units) {
                cout << "in: " <<  unit.in << ", " << "out: " << unit.out << endl;
                cout << "\t" << unit.cmd << endl;
                cout << "\t";
                for (const auto& dep: unit.deps)
                    cout << dep << ", ";
                cout << endl;
            }
        };
        cout << "new units: " << endl;
        fn(newUnits);
    }
#endif

    // clean
    if (clean) {
        const string& cmd = "rm -f " + ArgTable["workdir"] + ArgTable["out"] + allObjects;
        cout << cmd << endl;
        ::system(cmd.c_str());
        return 0;
    }

    // compile
    if (!newUnits.empty()) {
        cout << "* Build: ";
        if (!verbose) {
            cout << newUnits.size() << (newUnits.size() > 1 ? " files" : " file");
        } else {
            for (size_t i = 0; i < newUnits.size(); ++i) {
                cout << newUnits[i].in << ((i+1 < newUnits.size()) ? ", " : "");
            }
        }
        cout << endl;

        ParallelCompiler pc(newUnits);
        pc.SetVerbose(verbose);
        if (pc.Run(std::stoi(ArgTable["jobs"])) != 0)
            return -1;
    }

    // link
    if ((!hasOut || !newUnits.empty()) && !nlink) {
        string ldCmd = ArgTable["ld"] + ArgTable["ldflag"];
        ldCmd += " -o " + ArgTable["workdir"] + ArgTable["out"] + allObjects;

        if (!verbose)
            cout << "- Link - " << ArgTable["workdir"] + ArgTable["out"] << endl;
        else
            cout << "- Link - " << ldCmd << endl;
        if (::system(ldCmd.c_str()) != 0) {
            cerr << "FATAL: failed to link!" << endl;
            cerr << "    file:   " << allObjects << endl;
            cerr << "    ld:     " << ArgTable["ld"] << endl;
            cerr << "    ldflag: " << ArgTable["ldflag"] << endl;
            return -2;
        }
    }

    return 0;
}
<|endoftext|>


<commit_before>#include <string>
#include <fstream>
#include <iostream>
#include "map.h"

using namespace std;

Map::Map() {}

Map::~Map() {}

void Map::LoadMap(string MapFileName){
	string Temp;
	fstream MapFile;
	int X = 0;
	int Y = 0;
	int F = 0;
	int C = 0;

	MapFile.open (MapFileName, fstream::in);
	while ( MapFile >> Temp ){

				cout << Temp << endl << endl << endl << flush;
		for (int i = 0; i < Temp.length(); i++){
			if (Temp[i] == ','){
				C++;
				mapArray[X][Y] = stoi(Temp.substr(F,i-F));
				cout << mapArray[X][Y] << "  " << flush;
				X++;
				F = i + 1;
			}
		}
		cout << "C = " << C << flush;
		Y++;
	}
	MapFile.close();
}

int Map::Point(int X, int Y){
	return (int)mapArray[X][Y];
}

bool Map::Passable(int X, int Y){
	return (mapArray[X][Y] < PassableThreshhold);
}

string Map::GetPlot(int X, int Y){
	//Returns a 20x20 chunk of the map
	string RetVal;
	string Temp;
	for (int i = X; i < X + 20; i++){
		for (int j = Y; j < Y + 20; j++){
			if (i <= MaxX && i > -1 && j <= MaxY && j > -1){
				Temp = to_string(mapArray[i][j]);
				if (Temp.length() == 1) { RetVal += "0";}
				RetVal += Temp;
			} else {
			RetVal += "-1";
			}
		}
	}
	return RetVal;
}<commit_msg>Work in progress<commit_after>#include <string>
#include <fstream>
#include <iostream>
#include "map.h"

using namespace std;

Map::Map() {}

Map::~Map() {}

void Map::LoadMap(string MapFileName){
	string Temp;
	fstream MapFile;
	int X = 0;
	int Y = 0;
	int F = 0;
	int C = 0;

	MapFile.open (MapFileName, fstream::in);
	while ( MapFile >> Temp ){

				cout << Temp << endl << endl << endl << flush;
		for (int i = 0; i < Temp.length(); i++){
			if (Temp[i] == ','){
				C++;
				mapArray[X][Y] = stoi(Temp.substr(F,i-F));
				cout << mapArray[X][Y] << "  " << flush;
				X++;
				F = i + 1;
		cout << "C = " << C << flush;
			}
		}
		Y++;
	}
	MapFile.close();
}

int Map::Point(int X, int Y){
	return (int)mapArray[X][Y];
}

bool Map::Passable(int X, int Y){
	return (mapArray[X][Y] < PassableThreshhold);
}

string Map::GetPlot(int X, int Y){
	//Returns a 20x20 chunk of the map
	string RetVal;
	string Temp;
	for (int i = X; i < X + 20; i++){
		for (int j = Y; j < Y + 20; j++){
			if (i <= MaxX && i > -1 && j <= MaxY && j > -1){
				Temp = to_string(mapArray[i][j]);
				if (Temp.length() == 1) { RetVal += "0";}
				RetVal += Temp;
			} else {
			RetVal += "-1";
			}
		}
	}
	return RetVal;
}<|endoftext|>


<commit_before>#ifndef VXL_ONB_HPP
# define VXL_ONB_HPP
# pragma once

#include "vector.hpp"

namespace vxl
{

// Graphics Tools---The jgt Editors' Choice
// Building an orthonormal basis from a unit vector
// Building an Orthonormal Basis from a 3D Unit Vector Without Normalization
// http://blog.selfshadow.com/2011/10/17/perp-vectors/
// http://lolengine.net/blog/2013/09/21/picking-orthogonal-vector-combing-coconuts
//////////////////////////////////////////////////////////////////////////////
template <typename T>
//__attribute__ ((noinline))
inline constexpr auto ortho(vector<T, 2> const& v,
  default_tag const = {}) noexcept
{
  return vector<T, 2>{-v(1), v(0)};
}

//////////////////////////////////////////////////////////////////////////////
template <typename T>
//__attribute__ ((noinline))
inline constexpr auto ortho(vector<T, 3> const& v) noexcept
{
  using int_value_type = typename vector_traits<float, 3>::int_value_type;

  auto const tmp(abs(v));

/*
  return tmp(0) > tmp(1) ?
    vector<T, 3>{-v(2), T(0), v(0)} ?
    vector<T, 3>{T(0), -v(2), v(1)};
*/

  // if abs(v(0)) > abs(v(1)), then we keep v(0) and v(2), otherwise
  // v(1) and v(2), this way the maximum vector element by abs value is always
  // retained, we negate the comparison to negate 1, as -0 == 0
  return vector<T, 3>{
    select(
      vector_type{-v(2), T(0), v(0)},
      vector_type{T(0), -v(2), v(1)},
      cvector<int_value_type, 3>(-(tmp(0) > tmp(1)))
    )
  };
}

}

#endif // VXL_ONB_HPP
<commit_msg>some fixes<commit_after>#ifndef VXL_ONB_HPP
# define VXL_ONB_HPP
# pragma once

#include "vector.hpp"

namespace vxl
{

// Graphics Tools---The jgt Editors' Choice
// Building an orthonormal basis from a unit vector
// Building an Orthonormal Basis from a 3D Unit Vector Without Normalization
// http://blog.selfshadow.com/2011/10/17/perp-vectors/
// http://lolengine.net/blog/2013/09/21/picking-orthogonal-vector-combing-coconuts
//////////////////////////////////////////////////////////////////////////////
template <typename T>
//__attribute__ ((noinline))
inline constexpr auto ortho(vector<T, 2> const& v,
  default_tag const = {}) noexcept
{
  return vector<T, 2>{-v(1), v(0)};
}

//////////////////////////////////////////////////////////////////////////////
template <typename T>
//__attribute__ ((noinline))
inline constexpr auto ortho(vector<T, 3> const& v) noexcept
{
  using int_value_type = typename vector_traits<float, 3>::int_value_type;
  using vector_type = typename vector_traits<float, 3>::vector_type;

  auto const tmp(abs(v));

/*
  return tmp(0) > tmp(1) ?
    vector<T, 3>{-v(2), T(0), v(0)} ?
    vector<T, 3>{T(0), -v(2), v(1)};
*/

  // if abs(v(0)) > abs(v(1)), then we keep v(0) and v(2), otherwise
  // v(1) and v(2), this way the maximum vector element by abs value is always
  // retained, we negate the comparison to negate 1, as -0 == 0
  return vector<T, 3>{
    select(
      vector_type{-v(2), T(0), v(0)},
      vector_type{T(0), -v(2), v(1)},
      cvector<int_value_type, 3>(-(tmp(0) > tmp(1)))
    )
  };
}

}

#endif // VXL_ONB_HPP
<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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 program 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 program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define SOFA_CORE_OBJECTMODEL_DATA_CPP

#include <sofa/core/objectmodel/Data.h>

namespace sofa
{

namespace core
{

namespace objectmodel
{

/// Specialization for reading strings
template<>
inline
bool SOFA_CORE_API TData<std::string>::read( const std::string& str )
{
    virtualSetValue(str);
    return true;
}

/// Specialization for reading booleans
template<>
inline
bool SOFA_CORE_API TData<bool>::read( const std::string& str )
{
    if (str.empty())
        return false;
    bool val;
    if (str[0] == 'T' || str[0] == 't')
        val = true;
    else if (str[0] == 'F' || str[0] == 'f')
        val = false;
    else if ((str[0] >= '0' && str[0] <= '9') || str[0] == '-')
        val = (atoi(str.c_str()) != 0);
    else
        return false;
    virtualSetValue(val);
    return true;
}

template class SOFA_CORE_API TData< std::string >;
template class SOFA_CORE_API Data< std::string >;
template class SOFA_CORE_API TData< sofa::helper::vector<std::string> >;
template class SOFA_CORE_API Data< sofa::helper::vector<std::string> >;
template class SOFA_CORE_API TData< bool >;
template class SOFA_CORE_API Data< bool >;

} // objectmodel

} // core

} // sofa

<commit_msg>[SofaKernel] FIX don't inline exported functions<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, development version     *
*                (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This program 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 program 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 program. If not, see <http://www.gnu.org/licenses/>.        *
*******************************************************************************
* Authors: The SOFA Team and external contributors (see Authors.txt)          *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/
#define SOFA_CORE_OBJECTMODEL_DATA_CPP

#include <sofa/core/objectmodel/Data.h>

namespace sofa
{

namespace core
{

namespace objectmodel
{

/// Specialization for reading strings
template<>
bool SOFA_CORE_API TData<std::string>::read( const std::string& str )
{
    virtualSetValue(str);
    return true;
}

/// Specialization for reading booleans
template<>
bool SOFA_CORE_API TData<bool>::read( const std::string& str )
{
    if (str.empty())
        return false;
    bool val;
    if (str[0] == 'T' || str[0] == 't')
        val = true;
    else if (str[0] == 'F' || str[0] == 'f')
        val = false;
    else if ((str[0] >= '0' && str[0] <= '9') || str[0] == '-')
        val = (atoi(str.c_str()) != 0);
    else
        return false;
    virtualSetValue(val);
    return true;
}

template class SOFA_CORE_API TData< std::string >;
template class SOFA_CORE_API Data< std::string >;
template class SOFA_CORE_API TData< sofa::helper::vector<std::string> >;
template class SOFA_CORE_API Data< sofa::helper::vector<std::string> >;
template class SOFA_CORE_API TData< bool >;
template class SOFA_CORE_API Data< bool >;

} // objectmodel

} // core

} // sofa

<|endoftext|>


<commit_before>/*****************************************************************************
*                                                                            *
*  OpenNI 2.x Alpha                                                          *
*  Copyright (C) 2012 PrimeSense Ltd.                                        *
*                                                                            *
*  This file is part of OpenNI.                                              *
*                                                                            *
*  Licensed under the Apache License, Version 2.0 (the "License");           *
*  you may not use this file except in compliance with the License.          *
*  You may obtain a copy of the License at                                   *
*                                                                            *
*      http://www.apache.org/licenses/LICENSE-2.0                            *
*                                                                            *
*  Unless required by applicable law or agreed to in writing, software       *
*  distributed under the License is distributed on an "AS IS" BASIS,         *
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
*  See the License for the specific language governing permissions and       *
*  limitations under the License.                                            *
*                                                                            *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include "XnDeviceSensor.h"
#include "XnDeviceSensorInit.h"
#include "XnDeviceSensorProtocol.h"
#include "Bayer.h"
#include "XnHostProtocol.h"
#include <XnLog.h>
#include "XnSensor.h"

#define XN_HOST_PROTOCOL_MUTEX_NAME_PREFIX	"HostProtocolMutex"

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
XnStatus XnDeviceSensorInit(XnDevicePrivateData* pDevicePrivateData)
{
	XnStatus nRetVal = XN_STATUS_OK;

	nRetVal = XnDeviceSensorAllocateBuffers(pDevicePrivateData);
	XN_IS_STATUS_OK(nRetVal);

#if XN_PLATFORM == XN_PLATFORM_ANDROID_ARM
	nRetVal = xnOSCreateMutex(&pDevicePrivateData->hExecuteMutex);
	XN_IS_STATUS_OK(nRetVal);
#else
	XnChar strMutexName[XN_FILE_MAX_PATH];
	XnUInt32 nCharsWritten = 0;
	nRetVal = xnOSStrFormat(strMutexName, XN_FILE_MAX_PATH, &nCharsWritten, "%s%s", XN_HOST_PROTOCOL_MUTEX_NAME_PREFIX, pDevicePrivateData->pSensor->GetUSBPath());
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = xnOSCreateNamedMutex(&pDevicePrivateData->hExecuteMutex, strMutexName);
	XN_IS_STATUS_OK(nRetVal);
#endif

	nRetVal = XnDeviceSensorConfigureVersion(pDevicePrivateData);
	XN_IS_STATUS_OK(nRetVal);

	return (XN_STATUS_OK);
}

XnStatus XnDeviceSensorOpenInputThreads(XnDevicePrivateData* pDevicePrivateData)
{
	XnSensorUsbInterface usbInterface = pDevicePrivateData->pSensor->GetCurrentUsbInterface();

	// common stuff
	pDevicePrivateData->pSpecificDepthUsb = (XnSpecificUsbDevice*)xnOSMallocAligned(sizeof(XnSpecificUsbDevice), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->pSpecificDepthUsb->pDevicePrivateData = pDevicePrivateData;
	pDevicePrivateData->pSpecificDepthUsb->pUsbConnection = &pDevicePrivateData->SensorHandle.DepthConnection;
	pDevicePrivateData->pSpecificDepthUsb->CurrState.State = XN_WAITING_FOR_CONFIGURATION;
	pDevicePrivateData->pSpecificDepthUsb->nIgnoreBytes = (pDevicePrivateData->FWInfo.nFWVer >= XN_SENSOR_FW_VER_5_0) ? 0 : pDevicePrivateData->pSpecificDepthUsb->nChunkReadBytes;

	pDevicePrivateData->pSpecificImageUsb = (XnSpecificUsbDevice*)xnOSMallocAligned(sizeof(XnSpecificUsbDevice), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->pSpecificImageUsb->pDevicePrivateData = pDevicePrivateData;
	pDevicePrivateData->pSpecificImageUsb->pUsbConnection = &pDevicePrivateData->SensorHandle.ImageConnection;
	pDevicePrivateData->pSpecificImageUsb->CurrState.State = XN_WAITING_FOR_CONFIGURATION;
	pDevicePrivateData->pSpecificImageUsb->nIgnoreBytes = (pDevicePrivateData->FWInfo.nFWVer >= XN_SENSOR_FW_VER_5_0) ? 0 : pDevicePrivateData->pSpecificImageUsb->nChunkReadBytes;

	pDevicePrivateData->pSpecificMiscUsb = (XnSpecificUsbDevice*)xnOSMallocAligned(sizeof(XnSpecificUsbDevice), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->pSpecificMiscUsb->pDevicePrivateData = pDevicePrivateData;
	pDevicePrivateData->pSpecificMiscUsb->pUsbConnection = &pDevicePrivateData->SensorHandle.MiscConnection;
	pDevicePrivateData->pSpecificMiscUsb->CurrState.State = XN_WAITING_FOR_CONFIGURATION;
	pDevicePrivateData->pSpecificMiscUsb->nIgnoreBytes = (pDevicePrivateData->FWInfo.nFWVer >= XN_SENSOR_FW_VER_5_0) ? 0 : pDevicePrivateData->pSpecificMiscUsb->nChunkReadBytes;

	// timeout
	if (usbInterface == XN_SENSOR_USB_INTERFACE_ISO_ENDPOINTS || usbInterface == XN_SENSOR_USB_INTERFACE_ISO_ENDPOINTS_LOW_DEPTH)
	{
		pDevicePrivateData->pSpecificDepthUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_ISO;
		pDevicePrivateData->pSpecificImageUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_ISO;
		pDevicePrivateData->pSpecificMiscUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_ISO;
	}
	else
	{
		pDevicePrivateData->pSpecificDepthUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_BULK;
		pDevicePrivateData->pSpecificImageUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_BULK;
		pDevicePrivateData->pSpecificMiscUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_BULK;
	}

	// buffer size
	if (usbInterface == XN_SENSOR_USB_INTERFACE_BULK_ENDPOINTS)
	{
		pDevicePrivateData->pSpecificDepthUsb->nChunkReadBytes = XN_SENSOR_USB_DEPTH_BUFFER_SIZE_MULTIPLIER_BULK * pDevicePrivateData->SensorHandle.DepthConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificImageUsb->nChunkReadBytes = XN_SENSOR_USB_IMAGE_BUFFER_SIZE_MULTIPLIER_BULK * pDevicePrivateData->SensorHandle.ImageConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificMiscUsb->nChunkReadBytes = XN_SENSOR_USB_MISC_BUFFER_SIZE_MULTIPLIER_BULK * pDevicePrivateData->SensorHandle.MiscConnection.nMaxPacketSize;
	}
	else if (pDevicePrivateData->pSensor->IsLowBandwidth())
	{
		pDevicePrivateData->pSpecificDepthUsb->nChunkReadBytes = XN_SENSOR_USB_DEPTH_BUFFER_SIZE_MULTIPLIER_LOWBAND_ISO * pDevicePrivateData->SensorHandle.DepthConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificImageUsb->nChunkReadBytes = XN_SENSOR_USB_IMAGE_BUFFER_SIZE_MULTIPLIER_LOWBAND_ISO * pDevicePrivateData->SensorHandle.ImageConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificMiscUsb->nChunkReadBytes = XN_SENSOR_USB_MISC_BUFFER_SIZE_MULTIPLIER_LOWBAND_ISO * pDevicePrivateData->SensorHandle.MiscConnection.nMaxPacketSize;
	}
	else
	{
		pDevicePrivateData->pSpecificDepthUsb->nChunkReadBytes = XN_SENSOR_USB_DEPTH_BUFFER_SIZE_MULTIPLIER_ISO * pDevicePrivateData->SensorHandle.DepthConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificImageUsb->nChunkReadBytes = XN_SENSOR_USB_IMAGE_BUFFER_SIZE_MULTIPLIER_ISO * pDevicePrivateData->SensorHandle.ImageConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificMiscUsb->nChunkReadBytes = XN_SENSOR_USB_MISC_BUFFER_SIZE_MULTIPLIER_ISO * pDevicePrivateData->SensorHandle.MiscConnection.nMaxPacketSize;
	}

	// number of buffers
	pDevicePrivateData->pSpecificDepthUsb->nNumberOfBuffers = XN_SENSOR_USB_IMAGE_BUFFERS;
	pDevicePrivateData->pSpecificDepthUsb->nNumberOfBuffers = XN_SENSOR_USB_MISC_BUFFERS;
	if (usbInterface == XN_SENSOR_USB_INTERFACE_ISO_ENDPOINTS_LOW_DEPTH)
	{
		pDevicePrivateData->pSpecificDepthUsb->nNumberOfBuffers = XN_SENSOR_USB_DEPTH_BUFFERS_LOW_ISO;
	}
	else
	{
		pDevicePrivateData->pSpecificDepthUsb->nNumberOfBuffers = XN_SENSOR_USB_DEPTH_BUFFERS;
	}

	// Switch depth & image EPs for older FWs
	if (pDevicePrivateData->FWInfo.nFWVer <= XN_SENSOR_FW_VER_5_1)
	{
		XnSpecificUsbDevice* pTempUsbDevice = pDevicePrivateData->pSpecificDepthUsb;
		pDevicePrivateData->pSpecificDepthUsb = pDevicePrivateData->pSpecificImageUsb;
		pDevicePrivateData->pSpecificImageUsb = pTempUsbDevice;
	}

	return XN_STATUS_OK;
}

XnStatus XnDeviceSensorAllocateBuffers(XnDevicePrivateData* pDevicePrivateData)
{
	pDevicePrivateData->SensorHandle.DepthConnection.pUSBBuffer = (XnUInt8*)xnOSCallocAligned(XN_SENSOR_PROTOCOL_USB_BUFFER_SIZE, sizeof(XnUInt8), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->SensorHandle.DepthConnection.nUSBBufferReadOffset = 0;
	pDevicePrivateData->SensorHandle.DepthConnection.nUSBBufferWriteOffset = 0;

	pDevicePrivateData->SensorHandle.ImageConnection.pUSBBuffer = (XnUInt8*)xnOSCallocAligned(XN_SENSOR_PROTOCOL_USB_BUFFER_SIZE, sizeof(XnUInt8), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->SensorHandle.ImageConnection.nUSBBufferReadOffset = 0;
	pDevicePrivateData->SensorHandle.ImageConnection.nUSBBufferWriteOffset = 0;

	if (pDevicePrivateData->pSensor->IsMiscSupported())
	{
		pDevicePrivateData->SensorHandle.MiscConnection.pUSBBuffer = (XnUInt8*)xnOSCallocAligned(XN_SENSOR_PROTOCOL_USB_BUFFER_SIZE, sizeof(XnUInt8), XN_DEFAULT_MEM_ALIGN);
		pDevicePrivateData->SensorHandle.MiscConnection.nUSBBufferReadOffset = 0;
		pDevicePrivateData->SensorHandle.MiscConnection.nUSBBufferWriteOffset = 0;
	}
	else
	{
		pDevicePrivateData->SensorHandle.MiscConnection.pUSBBuffer = NULL;
	}

	return (XN_STATUS_OK);
}

XnStatus XnDeviceSensorFreeBuffers(XnDevicePrivateData* pDevicePrivateData)
{
	if (pDevicePrivateData->SensorHandle.DepthConnection.pUSBBuffer != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->SensorHandle.DepthConnection.pUSBBuffer);
	}

	if (pDevicePrivateData->SensorHandle.ImageConnection.pUSBBuffer != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->SensorHandle.ImageConnection.pUSBBuffer);
	}

	if (pDevicePrivateData->SensorHandle.MiscConnection.pUSBBuffer != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->SensorHandle.MiscConnection.pUSBBuffer);
	}

	if (pDevicePrivateData->pSpecificDepthUsb != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->pSpecificDepthUsb);
	}

	if (pDevicePrivateData->pSpecificImageUsb != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->pSpecificImageUsb);
	}

	if (pDevicePrivateData->pSpecificMiscUsb != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->pSpecificMiscUsb);
	}

	return (XN_STATUS_OK);
}

XnStatus XnDeviceSensorConfigureVersion(XnDevicePrivateData* pDevicePrivateData)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// GetVersion is exactly the same in all versions, except a change that was made in version 5.1.
	// so, we'll start with that, and if doesn't work we'll try previous protocols
	XnHostProtocolUsbCore usb = XN_USB_CORE_JANGO;
	nRetVal = XnHostProtocolInitFWParams(pDevicePrivateData, 5, 1, 0, usb, TRUE);
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = XnHostProtocolGetVersion(pDevicePrivateData, pDevicePrivateData->Version);

	// Strange bug: sometimes, when sending first command to device, no reply is received, so try again
	if (nRetVal == XN_STATUS_USB_TRANSFER_TIMEOUT)
	{
		xnOSSleep(2000);
		nRetVal = XnHostProtocolGetVersion(pDevicePrivateData, pDevicePrivateData->Version);
	}

	// if command failed for any reason, try again with older protocol
	if (nRetVal != XN_STATUS_OK)
	{
		nRetVal = XnHostProtocolInitFWParams(pDevicePrivateData, 5, 0, 0, usb, TRUE);
		XN_IS_STATUS_OK(nRetVal);

		nRetVal = XnHostProtocolGetVersion(pDevicePrivateData, pDevicePrivateData->Version);
	}

	// if it still fails, give up
	XN_IS_STATUS_OK(nRetVal);

	// check which usb core is used (don't check error code. If this fails, assume JANGO
	if (XN_STATUS_OK != XnHostProtocolGetUsbCoreType(pDevicePrivateData, usb))
	{
		usb = XN_USB_CORE_JANGO;
	}

	// Now that we have the actual version, configure protocol accordingly
	nRetVal = XnHostProtocolInitFWParams(pDevicePrivateData, pDevicePrivateData->Version.nMajor, pDevicePrivateData->Version.nMinor, pDevicePrivateData->Version.nBuild, usb, FALSE);
	XN_IS_STATUS_OK(nRetVal);

	pDevicePrivateData->HWInfo.nHWVer = pDevicePrivateData->Version.HWVer;
	pDevicePrivateData->ChipInfo.nChipVer = pDevicePrivateData->Version.ChipVer;

	return (XN_STATUS_OK);
}
<commit_msg>fixed color and IR stream (was mistakenly broken by new interface commit)<commit_after>/*****************************************************************************
*                                                                            *
*  OpenNI 2.x Alpha                                                          *
*  Copyright (C) 2012 PrimeSense Ltd.                                        *
*                                                                            *
*  This file is part of OpenNI.                                              *
*                                                                            *
*  Licensed under the Apache License, Version 2.0 (the "License");           *
*  you may not use this file except in compliance with the License.          *
*  You may obtain a copy of the License at                                   *
*                                                                            *
*      http://www.apache.org/licenses/LICENSE-2.0                            *
*                                                                            *
*  Unless required by applicable law or agreed to in writing, software       *
*  distributed under the License is distributed on an "AS IS" BASIS,         *
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  *
*  See the License for the specific language governing permissions and       *
*  limitations under the License.                                            *
*                                                                            *
*****************************************************************************/
//---------------------------------------------------------------------------
// Includes
//---------------------------------------------------------------------------
#include "XnDeviceSensor.h"
#include "XnDeviceSensorInit.h"
#include "XnDeviceSensorProtocol.h"
#include "Bayer.h"
#include "XnHostProtocol.h"
#include <XnLog.h>
#include "XnSensor.h"

#define XN_HOST_PROTOCOL_MUTEX_NAME_PREFIX	"HostProtocolMutex"

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
XnStatus XnDeviceSensorInit(XnDevicePrivateData* pDevicePrivateData)
{
	XnStatus nRetVal = XN_STATUS_OK;

	nRetVal = XnDeviceSensorAllocateBuffers(pDevicePrivateData);
	XN_IS_STATUS_OK(nRetVal);

#if XN_PLATFORM == XN_PLATFORM_ANDROID_ARM
	nRetVal = xnOSCreateMutex(&pDevicePrivateData->hExecuteMutex);
	XN_IS_STATUS_OK(nRetVal);
#else
	XnChar strMutexName[XN_FILE_MAX_PATH];
	XnUInt32 nCharsWritten = 0;
	nRetVal = xnOSStrFormat(strMutexName, XN_FILE_MAX_PATH, &nCharsWritten, "%s%s", XN_HOST_PROTOCOL_MUTEX_NAME_PREFIX, pDevicePrivateData->pSensor->GetUSBPath());
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = xnOSCreateNamedMutex(&pDevicePrivateData->hExecuteMutex, strMutexName);
	XN_IS_STATUS_OK(nRetVal);
#endif

	nRetVal = XnDeviceSensorConfigureVersion(pDevicePrivateData);
	XN_IS_STATUS_OK(nRetVal);

	return (XN_STATUS_OK);
}

XnStatus XnDeviceSensorOpenInputThreads(XnDevicePrivateData* pDevicePrivateData)
{
	XnSensorUsbInterface usbInterface = pDevicePrivateData->pSensor->GetCurrentUsbInterface();

	// common stuff
	pDevicePrivateData->pSpecificDepthUsb = (XnSpecificUsbDevice*)xnOSMallocAligned(sizeof(XnSpecificUsbDevice), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->pSpecificDepthUsb->pDevicePrivateData = pDevicePrivateData;
	pDevicePrivateData->pSpecificDepthUsb->pUsbConnection = &pDevicePrivateData->SensorHandle.DepthConnection;
	pDevicePrivateData->pSpecificDepthUsb->CurrState.State = XN_WAITING_FOR_CONFIGURATION;
	pDevicePrivateData->pSpecificDepthUsb->nIgnoreBytes = (pDevicePrivateData->FWInfo.nFWVer >= XN_SENSOR_FW_VER_5_0) ? 0 : pDevicePrivateData->pSpecificDepthUsb->nChunkReadBytes;

	pDevicePrivateData->pSpecificImageUsb = (XnSpecificUsbDevice*)xnOSMallocAligned(sizeof(XnSpecificUsbDevice), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->pSpecificImageUsb->pDevicePrivateData = pDevicePrivateData;
	pDevicePrivateData->pSpecificImageUsb->pUsbConnection = &pDevicePrivateData->SensorHandle.ImageConnection;
	pDevicePrivateData->pSpecificImageUsb->CurrState.State = XN_WAITING_FOR_CONFIGURATION;
	pDevicePrivateData->pSpecificImageUsb->nIgnoreBytes = (pDevicePrivateData->FWInfo.nFWVer >= XN_SENSOR_FW_VER_5_0) ? 0 : pDevicePrivateData->pSpecificImageUsb->nChunkReadBytes;

	pDevicePrivateData->pSpecificMiscUsb = (XnSpecificUsbDevice*)xnOSMallocAligned(sizeof(XnSpecificUsbDevice), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->pSpecificMiscUsb->pDevicePrivateData = pDevicePrivateData;
	pDevicePrivateData->pSpecificMiscUsb->pUsbConnection = &pDevicePrivateData->SensorHandle.MiscConnection;
	pDevicePrivateData->pSpecificMiscUsb->CurrState.State = XN_WAITING_FOR_CONFIGURATION;
	pDevicePrivateData->pSpecificMiscUsb->nIgnoreBytes = (pDevicePrivateData->FWInfo.nFWVer >= XN_SENSOR_FW_VER_5_0) ? 0 : pDevicePrivateData->pSpecificMiscUsb->nChunkReadBytes;

	// timeout
	if (usbInterface == XN_SENSOR_USB_INTERFACE_ISO_ENDPOINTS || usbInterface == XN_SENSOR_USB_INTERFACE_ISO_ENDPOINTS_LOW_DEPTH)
	{
		pDevicePrivateData->pSpecificDepthUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_ISO;
		pDevicePrivateData->pSpecificImageUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_ISO;
		pDevicePrivateData->pSpecificMiscUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_ISO;
	}
	else
	{
		pDevicePrivateData->pSpecificDepthUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_BULK;
		pDevicePrivateData->pSpecificImageUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_BULK;
		pDevicePrivateData->pSpecificMiscUsb->nTimeout = XN_SENSOR_READ_THREAD_TIMEOUT_BULK;
	}

	// buffer size
	if (usbInterface == XN_SENSOR_USB_INTERFACE_BULK_ENDPOINTS)
	{
		pDevicePrivateData->pSpecificDepthUsb->nChunkReadBytes = XN_SENSOR_USB_DEPTH_BUFFER_SIZE_MULTIPLIER_BULK * pDevicePrivateData->SensorHandle.DepthConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificImageUsb->nChunkReadBytes = XN_SENSOR_USB_IMAGE_BUFFER_SIZE_MULTIPLIER_BULK * pDevicePrivateData->SensorHandle.ImageConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificMiscUsb->nChunkReadBytes = XN_SENSOR_USB_MISC_BUFFER_SIZE_MULTIPLIER_BULK * pDevicePrivateData->SensorHandle.MiscConnection.nMaxPacketSize;
	}
	else if (pDevicePrivateData->pSensor->IsLowBandwidth())
	{
		pDevicePrivateData->pSpecificDepthUsb->nChunkReadBytes = XN_SENSOR_USB_DEPTH_BUFFER_SIZE_MULTIPLIER_LOWBAND_ISO * pDevicePrivateData->SensorHandle.DepthConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificImageUsb->nChunkReadBytes = XN_SENSOR_USB_IMAGE_BUFFER_SIZE_MULTIPLIER_LOWBAND_ISO * pDevicePrivateData->SensorHandle.ImageConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificMiscUsb->nChunkReadBytes = XN_SENSOR_USB_MISC_BUFFER_SIZE_MULTIPLIER_LOWBAND_ISO * pDevicePrivateData->SensorHandle.MiscConnection.nMaxPacketSize;
	}
	else
	{
		pDevicePrivateData->pSpecificDepthUsb->nChunkReadBytes = XN_SENSOR_USB_DEPTH_BUFFER_SIZE_MULTIPLIER_ISO * pDevicePrivateData->SensorHandle.DepthConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificImageUsb->nChunkReadBytes = XN_SENSOR_USB_IMAGE_BUFFER_SIZE_MULTIPLIER_ISO * pDevicePrivateData->SensorHandle.ImageConnection.nMaxPacketSize;
		pDevicePrivateData->pSpecificMiscUsb->nChunkReadBytes = XN_SENSOR_USB_MISC_BUFFER_SIZE_MULTIPLIER_ISO * pDevicePrivateData->SensorHandle.MiscConnection.nMaxPacketSize;
	}

	// number of buffers
	pDevicePrivateData->pSpecificImageUsb->nNumberOfBuffers = XN_SENSOR_USB_IMAGE_BUFFERS;
	pDevicePrivateData->pSpecificMiscUsb->nNumberOfBuffers = XN_SENSOR_USB_MISC_BUFFERS;
	if (usbInterface == XN_SENSOR_USB_INTERFACE_ISO_ENDPOINTS_LOW_DEPTH)
	{
		pDevicePrivateData->pSpecificDepthUsb->nNumberOfBuffers = XN_SENSOR_USB_DEPTH_BUFFERS_LOW_ISO;
	}
	else
	{
		pDevicePrivateData->pSpecificDepthUsb->nNumberOfBuffers = XN_SENSOR_USB_DEPTH_BUFFERS;
	}

	// Switch depth & image EPs for older FWs
	if (pDevicePrivateData->FWInfo.nFWVer <= XN_SENSOR_FW_VER_5_1)
	{
		XnSpecificUsbDevice* pTempUsbDevice = pDevicePrivateData->pSpecificDepthUsb;
		pDevicePrivateData->pSpecificDepthUsb = pDevicePrivateData->pSpecificImageUsb;
		pDevicePrivateData->pSpecificImageUsb = pTempUsbDevice;
	}

	return XN_STATUS_OK;
}

XnStatus XnDeviceSensorAllocateBuffers(XnDevicePrivateData* pDevicePrivateData)
{
	pDevicePrivateData->SensorHandle.DepthConnection.pUSBBuffer = (XnUInt8*)xnOSCallocAligned(XN_SENSOR_PROTOCOL_USB_BUFFER_SIZE, sizeof(XnUInt8), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->SensorHandle.DepthConnection.nUSBBufferReadOffset = 0;
	pDevicePrivateData->SensorHandle.DepthConnection.nUSBBufferWriteOffset = 0;

	pDevicePrivateData->SensorHandle.ImageConnection.pUSBBuffer = (XnUInt8*)xnOSCallocAligned(XN_SENSOR_PROTOCOL_USB_BUFFER_SIZE, sizeof(XnUInt8), XN_DEFAULT_MEM_ALIGN);
	pDevicePrivateData->SensorHandle.ImageConnection.nUSBBufferReadOffset = 0;
	pDevicePrivateData->SensorHandle.ImageConnection.nUSBBufferWriteOffset = 0;

	if (pDevicePrivateData->pSensor->IsMiscSupported())
	{
		pDevicePrivateData->SensorHandle.MiscConnection.pUSBBuffer = (XnUInt8*)xnOSCallocAligned(XN_SENSOR_PROTOCOL_USB_BUFFER_SIZE, sizeof(XnUInt8), XN_DEFAULT_MEM_ALIGN);
		pDevicePrivateData->SensorHandle.MiscConnection.nUSBBufferReadOffset = 0;
		pDevicePrivateData->SensorHandle.MiscConnection.nUSBBufferWriteOffset = 0;
	}
	else
	{
		pDevicePrivateData->SensorHandle.MiscConnection.pUSBBuffer = NULL;
	}

	return (XN_STATUS_OK);
}

XnStatus XnDeviceSensorFreeBuffers(XnDevicePrivateData* pDevicePrivateData)
{
	if (pDevicePrivateData->SensorHandle.DepthConnection.pUSBBuffer != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->SensorHandle.DepthConnection.pUSBBuffer);
	}

	if (pDevicePrivateData->SensorHandle.ImageConnection.pUSBBuffer != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->SensorHandle.ImageConnection.pUSBBuffer);
	}

	if (pDevicePrivateData->SensorHandle.MiscConnection.pUSBBuffer != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->SensorHandle.MiscConnection.pUSBBuffer);
	}

	if (pDevicePrivateData->pSpecificDepthUsb != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->pSpecificDepthUsb);
	}

	if (pDevicePrivateData->pSpecificImageUsb != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->pSpecificImageUsb);
	}

	if (pDevicePrivateData->pSpecificMiscUsb != NULL)
	{
		XN_ALIGNED_FREE_AND_NULL(pDevicePrivateData->pSpecificMiscUsb);
	}

	return (XN_STATUS_OK);
}

XnStatus XnDeviceSensorConfigureVersion(XnDevicePrivateData* pDevicePrivateData)
{
	XnStatus nRetVal = XN_STATUS_OK;

	// GetVersion is exactly the same in all versions, except a change that was made in version 5.1.
	// so, we'll start with that, and if doesn't work we'll try previous protocols
	XnHostProtocolUsbCore usb = XN_USB_CORE_JANGO;
	nRetVal = XnHostProtocolInitFWParams(pDevicePrivateData, 5, 1, 0, usb, TRUE);
	XN_IS_STATUS_OK(nRetVal);

	nRetVal = XnHostProtocolGetVersion(pDevicePrivateData, pDevicePrivateData->Version);

	// Strange bug: sometimes, when sending first command to device, no reply is received, so try again
	if (nRetVal == XN_STATUS_USB_TRANSFER_TIMEOUT)
	{
		xnOSSleep(2000);
		nRetVal = XnHostProtocolGetVersion(pDevicePrivateData, pDevicePrivateData->Version);
	}

	// if command failed for any reason, try again with older protocol
	if (nRetVal != XN_STATUS_OK)
	{
		nRetVal = XnHostProtocolInitFWParams(pDevicePrivateData, 5, 0, 0, usb, TRUE);
		XN_IS_STATUS_OK(nRetVal);

		nRetVal = XnHostProtocolGetVersion(pDevicePrivateData, pDevicePrivateData->Version);
	}

	// if it still fails, give up
	XN_IS_STATUS_OK(nRetVal);

	// check which usb core is used (don't check error code. If this fails, assume JANGO
	if (XN_STATUS_OK != XnHostProtocolGetUsbCoreType(pDevicePrivateData, usb))
	{
		usb = XN_USB_CORE_JANGO;
	}

	// Now that we have the actual version, configure protocol accordingly
	nRetVal = XnHostProtocolInitFWParams(pDevicePrivateData, pDevicePrivateData->Version.nMajor, pDevicePrivateData->Version.nMinor, pDevicePrivateData->Version.nBuild, usb, FALSE);
	XN_IS_STATUS_OK(nRetVal);

	pDevicePrivateData->HWInfo.nHWVer = pDevicePrivateData->Version.HWVer;
	pDevicePrivateData->ChipInfo.nChipVer = pDevicePrivateData->Version.ChipVer;

	return (XN_STATUS_OK);
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAntiAliasBinaryImageFilter.txx"
#include "itkAutomaticTopologyMeshSource.txx"
#include "itkBalloonForce3DFilter.txx"
#include "itkBalloonForceFilter.txx"
#include "itkBinaryMask3DMeshSource.txx"
#include "itkBinaryMinMaxCurvatureFlowFunction.txx"
#include "itkBinaryMinMaxCurvatureFlowImageFilter.txx"
#include "itkBioGene.h"
#include "itkBioGeneNetwork.h"
#include "itkCannySegmentationLevelSetFunction.txx"
#include "itkCannySegmentationLevelSetImageFilter.txx"
#include "itkClassifierBase.txx"
#include "itkConnectedRegionsMeshFilter.txx"
#include "itkCurvatureFlowFunction.txx"
#include "itkCurvatureFlowImageFilter.txx"
#include "itkDeformableMesh3DFilter.txx"
#include "itkDeformableMeshFilter.txx"
#include "itkDemonsRegistrationFilter.txx"
#include "itkDemonsRegistrationFunction.txx"
#include "itkExtensionVelocitiesImageFilter.txx"
#include "itkFEMRegistrationFilter.txx"
#include "itkFastMarchingExtensionImageFilter.txx"
#include "itkFastMarchingImageFilter.txx"
#include "itkGeodesicActiveContourLevelSetFunction.txx"
#include "itkGeodesicActiveContourLevelSetImageFilter.txx"
#include "itkGradientVectorFlowImageFilter.txx"
#include "itkHistogramMatchingImageFilter.txx"
#include "itkImageClassifierBase.txx"
#include "itkImageGaussianModelEstimator.txx"
#include "itkImageKmeansModelEstimator.txx"
#include "itkImageModelEstimatorBase.txx"
#include "itkImageMomentsCalculator.txx"
#include "itkImageRegistrationMethod.txx"
#include "itkImageToImageMetric.txx"
#include "itkImageToSpatialObjectMetric.txx"
#include "itkImageToSpatialObjectRegistrationMethod.txx"
#include "itkKLMRegionGrowImageFilter.txx"
#include "itkKalmanLinearEstimator.h"
#include "itkLaplacianSegmentationLevelSetFunction.txx"
#include "itkLaplacianSegmentationLevelSetImageFilter.txx"
#include "itkLevelSetNeighborhoodExtractor.txx"
#include "itkLevelSetVelocityNeighborhoodExtractor.txx"
#include "itkMRASlabIdentifier.txx"
#include "itkMRFImageFilter.txx"
#include "itkMRIBiasFieldCorrectionFilter.txx"
#include "itkMattesMutualInformationImageToImageMetric.txx"
#include "itkMeanSquaresImageToImageMetric.txx"
#include "itkMeanSquaresPointSetToImageMetric.txx"
#include "itkMinMaxCurvatureFlowFunction.txx"
#include "itkMinMaxCurvatureFlowImageFilter.txx"
#include "itkMultiResolutionImageRegistrationMethod.txx"
#include "itkMultiResolutionPDEDeformableRegistration.txx"
#include "itkMultiResolutionPyramidImageFilter.txx"
#include "itkMutualInformationImageToImageMetric.txx"
#include "itkNormalizedCorrelationImageToImageMetric.txx"
#include "itkNormalizedCorrelationPointSetToImageMetric.txx"
#include "itkOtsuThresholdImageCalculator.txx"
#include "itkPDEDeformableRegistrationFilter.txx"
#include "itkPDEDeformableRegistrationFunction.h"
#include "itkPatternIntensityImageToImageMetric.txx"
#include "itkPatternIntensityPointSetToImageMetric.txx"
#include "itkPointSetToImageMetric.txx"
#include "itkPointSetToImageRegistrationMethod.txx"
#include "itkRGBGibbsPriorFilter.txx"
#include "itkRecursiveMultiResolutionPyramidImageFilter.txx"
#include "itkRegionGrowImageFilter.txx"
#include "itkRegistrationMethod.txx"
#include "itkReinitializeLevelSetImageFilter.txx"
#include "itkSegmentationLevelSetImageFilter.txx"
#include "itkShapeDetectionLevelSetFunction.txx"
#include "itkShapeDetectionLevelSetImageFilter.txx"
#include "itkSimpleFuzzyConnectednessImageFilterBase.txx"
#include "itkSimpleFuzzyConnectednessRGBImageFilter.txx"
#include "itkSimpleFuzzyConnectednessScalarImageFilter.txx"
#include "itkSphereMeshSource.txx"
#include "itkThresholdSegmentationLevelSetFunction.txx"
#include "itkThresholdSegmentationLevelSetImageFilter.txx"
#include "itkVectorFuzzyConnectednessImageFilter.txx"
#include "itkVoronoiDiagram2D.txx"
#include "itkVoronoiDiagram2DGenerator.txx"
#include "itkVoronoiPartitioningImageFilter.txx"
#include "itkVoronoiSegmentationImageFilter.txx"
#include "itkVoronoiSegmentationImageFilterBase.txx"
#include "itkVoronoiSegmentationRGBImageFilter.txx"
#include "itkWatershedBoundary.txx"
#include "itkWatershedBoundaryResolver.txx"
#include "itkWatershedEquivalenceRelabeler.txx"
#include "itkWatershedEquivalencyTable.txx"
#include "itkWatershedImageFilter.txx"
#include "itkWatershedMiniPipelineProgressCommand.h"
#include "itkWatershedOneWayEquivalencyTable.txx"
#include "itkWatershedRelabeler.txx"
#include "itkWatershedSegmentTable.txx"
#include "itkWatershedSegmentTree.txx"
#include "itkWatershedSegmentTreeGenerator.txx"
#include "itkWatershedSegmenter.txx"

int main ( int , char*  )
{

  return 0;
}

<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit (ITK)
  Module:
  Language:  C++
  Date:
  Version:

Copyright (c) 2000 National Library of Medicine
All rights reserved.

See COPYRIGHT.txt for copyright details.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkAntiAliasBinaryImageFilter.txx"
#include "itkAutomaticTopologyMeshSource.txx"
#include "itkBalloonForce3DFilter.txx"
#include "itkBalloonForceFilter.txx"
#include "itkBinaryMask3DMeshSource.txx"
#include "itkBinaryMinMaxCurvatureFlowFunction.txx"
#include "itkBinaryMinMaxCurvatureFlowImageFilter.txx"
#include "itkBioGene.h"
#include "itkBioGeneNetwork.h"
#include "itkCannySegmentationLevelSetFunction.txx"
#include "itkCannySegmentationLevelSetImageFilter.txx"
#include "itkClassifierBase.txx"
#include "itkConnectedRegionsMeshFilter.txx"
#include "itkCurvatureFlowFunction.txx"
#include "itkCurvatureFlowImageFilter.txx"
#include "itkDeformableMesh3DFilter.txx"
#include "itkDeformableMeshFilter.txx"
#include "itkDemonsRegistrationFilter.txx"
#include "itkDemonsRegistrationFunction.txx"
#include "itkExtensionVelocitiesImageFilter.txx"
#include "itkFEMRegistrationFilter.txx"
#include "itkFastMarchingExtensionImageFilter.txx"
#include "itkFastMarchingImageFilter.txx"
#include "itkGeodesicActiveContourLevelSetFunction.txx"
#include "itkGeodesicActiveContourLevelSetImageFilter.txx"
#include "itkGradientVectorFlowImageFilter.txx"
#include "itkHistogramMatchingImageFilter.txx"
#include "itkImageClassifierBase.txx"
#include "itkImageGaussianModelEstimator.txx"
#include "itkImageKmeansModelEstimator.txx"
#include "itkImageModelEstimatorBase.txx"
#include "itkImageMomentsCalculator.txx"
#include "itkImageRegistrationMethod.txx"
#include "itkImageToImageMetric.txx"
#include "itkImageToSpatialObjectMetric.txx"
#include "itkImageToSpatialObjectRegistrationMethod.txx"
#include "itkKLMRegionGrowImageFilter.txx"
#include "itkKalmanLinearEstimator.h"
#include "itkLaplacianSegmentationLevelSetFunction.txx"
#include "itkLaplacianSegmentationLevelSetImageFilter.txx"
#include "itkLevelSetNeighborhoodExtractor.txx"
#include "itkLevelSetVelocityNeighborhoodExtractor.txx"
#include "itkMRASlabIdentifier.txx"
#include "itkMRFImageFilter.txx"
#include "itkMRIBiasFieldCorrectionFilter.txx"
#include "itkMattesMutualInformationImageToImageMetric.txx"
#include "itkMeanSquaresImageToImageMetric.txx"
#include "itkMeanSquaresPointSetToImageMetric.txx"
#include "itkMinMaxCurvatureFlowFunction.txx"
#include "itkMinMaxCurvatureFlowImageFilter.txx"
#include "itkMultiResolutionImageRegistrationMethod.txx"
#include "itkMultiResolutionPDEDeformableRegistration.txx"
#include "itkMultiResolutionPyramidImageFilter.txx"
#include "itkMutualInformationImageToImageMetric.txx"
#include "itkNormalizedCorrelationImageToImageMetric.txx"
#include "itkNormalizedCorrelationPointSetToImageMetric.txx"
#include "itkOtsuThresholdImageCalculator.txx"
#include "itkPDEDeformableRegistrationFilter.txx"
#include "itkPDEDeformableRegistrationFunction.h"
#include "itkPatternIntensityImageToImageMetric.txx"
#include "itkPatternIntensityPointSetToImageMetric.txx"
#include "itkPointSetToImageMetric.txx"
#include "itkPointSetToImageRegistrationMethod.txx"
#include "itkRGBGibbsPriorFilter.txx"
#include "itkRecursiveMultiResolutionPyramidImageFilter.txx"
#include "itkRegionGrowImageFilter.txx"
#include "itkRegistrationMethod.txx"
#include "itkReinitializeLevelSetImageFilter.txx"
#include "itkSegmentationLevelSetImageFilter.txx"
#include "itkShapeDetectionLevelSetFunction.txx"
#include "itkShapeDetectionLevelSetImageFilter.txx"
#include "itkSimpleFuzzyConnectednessImageFilterBase.txx"
#include "itkSimpleFuzzyConnectednessRGBImageFilter.txx"
#include "itkSimpleFuzzyConnectednessScalarImageFilter.txx"
#include "itkSphereMeshSource.txx"
#include "itkStructHashFunction.h"
#include "itkThresholdSegmentationLevelSetFunction.txx"
#include "itkThresholdSegmentationLevelSetImageFilter.txx"
#include "itkVectorFuzzyConnectednessImageFilter.txx"
#include "itkVoronoiDiagram2D.txx"
#include "itkVoronoiDiagram2DGenerator.txx"
#include "itkVoronoiPartitioningImageFilter.txx"
#include "itkVoronoiSegmentationImageFilter.txx"
#include "itkVoronoiSegmentationImageFilterBase.txx"
#include "itkVoronoiSegmentationRGBImageFilter.txx"
#include "itkWatershedBoundary.txx"
#include "itkWatershedBoundaryResolver.txx"
#include "itkWatershedEquivalenceRelabeler.txx"
#include "itkWatershedEquivalencyTable.txx"
#include "itkWatershedImageFilter.txx"
#include "itkWatershedMiniPipelineProgressCommand.h"
#include "itkWatershedOneWayEquivalencyTable.txx"
#include "itkWatershedRelabeler.txx"
#include "itkWatershedSegmentTable.txx"
#include "itkWatershedSegmentTree.txx"
#include "itkWatershedSegmentTreeGenerator.txx"
#include "itkWatershedSegmenter.txx"

int main ( int , char*  )
{

  return 0;
}

<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "Inject.h"

#include "Util.h"

// Ripped from Oblivion Script Extender
// http://obse.silverlock.org/
// The sordid thread-suspending logic in DoInjectDLL is my own dismal contribution

extern BOOL ToggleProcessThreads(DWORD dwOwnerPID, bool suspend);

Inject::Inject(void)
{
}

Inject::~Inject(void)
{
}

bool Inject::InjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)
{
	bool	result = false;

	// wrap DLL injection in SEH, if it crashes print a message
	__try {
		result = DoInjectDLL(processId, dllPath, processWasLaunched);
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		_injectError = "DLL injection failed. In most cases, this is caused by an overly paranoid software firewall or antivirus package. Disabling either of these may solve the problem.";
		result = false;
	}

	return result;
}

/*** jmp hook layout
 *	E9 ## ## ## ##	jmp LoadLibraryA
 *						offset = LoadLibraryA - (base + 5)
 *	<string>		name of function
 ***/

typedef unsigned int UInt32;
typedef unsigned char UInt8;

bool Inject::DoInjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)
{
	bool result = false; // assume failure

	HANDLE process = OpenProcess(
		PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, processId);
	if(process)
	{
		UInt32	hookBase = (UInt32)VirtualAllocEx(process, NULL, 8192, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
		if(hookBase)
		{
			// safe because kernel32 is loaded at the same address in all processes
			// (can change across restarts)
			UInt32	loadLibraryAAddr = (UInt32)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

			//_MESSAGE("hookBase = %08X", hookBase);
			//_MESSAGE("loadLibraryAAddr = %08X", loadLibraryAAddr);

			SIZE_T	bytesWritten;
			WriteProcessMemory(process, (LPVOID)(hookBase + 5), dllPath, strlen(dllPath) + 1, &bytesWritten);

			UInt8	hookCode[5];

			hookCode[0] = 0xE9;
			*((UInt32 *)&hookCode[1]) = loadLibraryAAddr - (hookBase + 5);

			WriteProcessMemory(process, (LPVOID)(hookBase), hookCode, sizeof(hookCode), &bytesWritten);

			HANDLE hookThread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)hookBase, (void *)(hookBase + 5), 0, NULL);
			if (hookThread && hookThread != INVALID_HANDLE_VALUE)
			{
				ResumeThread(hookThread);
				if(true) // always wait
				{
					// So, if we are attaching to an existing process, all of its threads should have already been suspended by the loader.
					// however, its quite possible that we suspended the threads inside a critical section and now our hook thread will deadlock.
					// so what we'll do is wait for a bit on the hook thread, and if we timeout, resume all threads in the target process for a brief period,
					// then resuspend them.  Then resume our hook thread and try again.  Do this some number of times and hopefully we'll be successful.
					// Its basically a jackhammer, and it can fail (especially if our hook thread does a bunch of slow initialization stuff), but it
					// usually succeeds.

					DWORD waitTimeout;
					int MaxHookAttempts;
					if (processWasLaunched) {
						waitTimeout = INFINITE;
						MaxHookAttempts = 1;
					}
					else {
						waitTimeout = 500;
						MaxHookAttempts = 25;
					}

					int attempt = 0;

					for (attempt = 0; !result && attempt < MaxHookAttempts; ++attempt) {
						switch(WaitForSingleObject(hookThread, waitTimeout))  // g_options.m_threadTimeout
						{
							case WAIT_OBJECT_0:
								Util::Log("Hook Thread complete\n");
								result = true;
								break;

							case WAIT_ABANDONED:
								_injectError = "Hook Thread WAIT_ABANDONED";
								break;

							case WAIT_TIMEOUT:
								// Resume all threads, sleep for a bit, then suspend them all again.  Then resume hook thread and retry.
								Util::Log("timeout, retrying\n");
								ToggleProcessThreads(processId,false);
								Sleep(0);
								ToggleProcessThreads(processId,true);
								ResumeThread(hookThread);
								break;

							case WAIT_FAILED:
								_injectError = "Hook Thread WAIT_FAILED";
								break;
							default:
								_injectError = "Hook Thread Unknown wait state";

						}
					}

					if (!result) {
						_injectError = "Unable to complete hook thread after several attempts";
					}
				}
				else
					result = true;

				CloseHandle(hookThread);
			}
			else {
				//http://stackoverflow.com/questions/3006229/get-a-text-from-the-error-code-returns-from-the-getlasterror-function
				DWORD   dwLastError = ::GetLastError();
				const DWORD BufSize = 256;
				TCHAR   lpBuffer[BufSize] = _T("?");
				if(dwLastError != 0)    // Don't want to see a "operation done successfully" error ;-)
				::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,                 // Its a system error
                     NULL,                                      // No string to be formatted needed
                     dwLastError,                               // Hey Windows: Please explain this error!
                     MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),  // Do it in the standard language
                     lpBuffer,              // Put the message here
                     BufSize-1,                     // Number of bytes to store the message
                     NULL);

				_injectError = string("CreateRemoteThread failed: ") + string(lpBuffer);
			}

			VirtualFreeEx(process, (LPVOID)hookBase, 8192, MEM_RELEASE);
		}
		else
			_injectError = "Process::InstallHook: couldn't allocate memory in target process";

		CloseHandle(process);
	}
	else
		_injectError = "Process::InstallHook: couldn't get process handle.  You may need to run MMLoader as an adminstrator.";

	return result;
}
<commit_msg>Fix(maybe-loader): use a retry loop for CreateRemoteThread<commit_after>#include "StdAfx.h"
#include "Inject.h"

#include "Util.h"

// Ripped from Oblivion Script Extender
// http://obse.silverlock.org/
// The sordid thread-suspending logic in DoInjectDLL is my own dismal contribution

extern BOOL ToggleProcessThreads(DWORD dwOwnerPID, bool suspend);

Inject::Inject(void)
{
}

Inject::~Inject(void)
{
}

bool Inject::InjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)
{
	bool	result = false;

	// wrap DLL injection in SEH, if it crashes print a message
	__try {
		result = DoInjectDLL(processId, dllPath, processWasLaunched);
	}
	__except(EXCEPTION_EXECUTE_HANDLER)
	{
		_injectError = "DLL injection failed. In most cases, this is caused by an overly paranoid software firewall or antivirus package. Disabling either of these may solve the problem.";
		result = false;
	}

	return result;
}

/*** jmp hook layout
 *	E9 ## ## ## ##	jmp LoadLibraryA
 *						offset = LoadLibraryA - (base + 5)
 *	<string>		name of function
 ***/

typedef unsigned int UInt32;
typedef unsigned char UInt8;

bool Inject::DoInjectDLL(DWORD processId, const char * dllPath, bool processWasLaunched)
{
	bool result = false; // assume failure

	HANDLE process = OpenProcess(
		PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ, FALSE, processId);
	if(process)
	{
		UInt32	hookBase = (UInt32)VirtualAllocEx(process, NULL, 8192, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
		if(hookBase)
		{
			// safe because kernel32 is loaded at the same address in all processes
			// (can change across restarts)
			UInt32	loadLibraryAAddr = (UInt32)GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");

			//_MESSAGE("hookBase = %08X", hookBase);
			//_MESSAGE("loadLibraryAAddr = %08X", loadLibraryAAddr);

			SIZE_T	bytesWritten;
			WriteProcessMemory(process, (LPVOID)(hookBase + 5), dllPath, strlen(dllPath) + 1, &bytesWritten);

			UInt8	hookCode[5];

			hookCode[0] = 0xE9;
			*((UInt32 *)&hookCode[1]) = loadLibraryAAddr - (hookBase + 5);

			WriteProcessMemory(process, (LPVOID)(hookBase), hookCode, sizeof(hookCode), &bytesWritten);

			// yet another race...creating this thread sometimes fails, usually when loader is "cold" and hasn't been started
			// recently. not sure a retry loop will help (and may need to sleep here)
			int hook_thread_attempts = 3;
			HANDLE hookThread = NULL;
			bool hookThreadValid = false;
			while (!hookThreadValid && hook_thread_attempts > 0) {
				hook_thread_attempts--;
				hookThread = CreateRemoteThread(process, NULL, 0, (LPTHREAD_START_ROUTINE)hookBase, (void *)(hookBase + 5), 0, NULL);
				hookThreadValid = hookThread && hookThread != INVALID_HANDLE_VALUE;
				if (!hookThreadValid) {
					Util::Log("Failed hook thread (%d more attempts)", hook_thread_attempts);
				}
			}
			if (hookThreadValid)
			{
				ResumeThread(hookThread);
				// So, if we are attaching to an existing process, all of its threads should have already been suspended by the loader.
				// however, its quite possible that we suspended the threads inside a critical section and now our hook thread will deadlock.
				// so what we'll do is wait for a bit on the hook thread, and if we timeout, resume all threads in the target process for a brief period,
				// then resuspend them.  Then resume our hook thread and try again.  Do this some number of times and hopefully we'll be successful.
				// Its basically a jackhammer, and it can fail (especially if our hook thread does a bunch of slow initialization stuff), but it
				// usually succeeds.

				DWORD waitTimeout;
				int MaxHookAttempts;
				if (processWasLaunched) {
					waitTimeout = INFINITE;
					MaxHookAttempts = 1;
				}
				else {
					waitTimeout = 500;
					MaxHookAttempts = 25;
				}

				int attempt = 0;

				for (attempt = 0; !result && attempt < MaxHookAttempts; ++attempt) {
					switch(WaitForSingleObject(hookThread, waitTimeout))  // g_options.m_threadTimeout
					{
						case WAIT_OBJECT_0:
							Util::Log("Hook Thread complete\n");
							result = true;
							break;

						case WAIT_ABANDONED:
							_injectError = "Hook Thread WAIT_ABANDONED";
							break;

						case WAIT_TIMEOUT:
							// Resume all threads, sleep for a bit, then suspend them all again.  Then resume hook thread and retry.
							Util::Log("timeout, retrying\n");
							ToggleProcessThreads(processId,false);
							Sleep(0);
							ToggleProcessThreads(processId,true);
							ResumeThread(hookThread);
							break;

						case WAIT_FAILED:
							_injectError = "Hook Thread WAIT_FAILED";
							break;
						default:
							_injectError = "Hook Thread Unknown wait state";

					}
				}

				if (!result) {
					_injectError = "Unable to complete hook thread after several attempts";
				}

				CloseHandle(hookThread);
			}
			else {
				//http://stackoverflow.com/questions/3006229/get-a-text-from-the-error-code-returns-from-the-getlasterror-function
				DWORD   dwLastError = ::GetLastError();
				const DWORD BufSize = 256;
				TCHAR   lpBuffer[BufSize] = _T("?");
				if(dwLastError != 0)    // Don't want to see a "operation done successfully" error ;-)
				::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,                 // Its a system error
                     NULL,                                      // No string to be formatted needed
                     dwLastError,                               // Hey Windows: Please explain this error!
                     MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),  // Do it in the standard language
                     lpBuffer,              // Put the message here
                     BufSize-1,                     // Number of bytes to store the message
                     NULL);

				_injectError = string("CreateRemoteThread failed: ") + string(lpBuffer);
			}

			VirtualFreeEx(process, (LPVOID)hookBase, 8192, MEM_RELEASE);
		}
		else
			_injectError = "Process::InstallHook: couldn't allocate memory in target process";

		CloseHandle(process);
	}
	else
		_injectError = "Process::InstallHook: couldn't get process handle.  You may need to run MMLoader as an adminstrator.";

	return result;
}
<|endoftext|>