<commit_before>#include "../cshared/shared.h"
#include "../cshared/opcodes.h"
#include "../cshared/opcodes_format.h"
#include "../cshared/opcodes_debug.h"
#include "../cshared/asm_stream.h"
#include "../cshared/stream.h"

struct Arg
{
    uint64_t    fixnum = 0;
    std::string string;

    Arg(uint64_t fixnum) : fixnum(fixnum)
    {
    }
    Arg(dab_register_t reg) : fixnum(reg.value())
    {
    }
    Arg(std::vector<dab_register_t> regs)
    {
        (void)regs;
    }
    Arg(std::string string) : string(string)
    {
    }
};

struct Op
{
    size_t           code;
    std::vector<Arg> data;

    uint16_t arg_uint16(size_t index)
    {
        return data[index].fixnum;
    }

    std::string arg_string(size_t index)
    {
        return data[index].string;
    }
};

void parse_asm(bool raw, std::function<void(Op)> func)
{
    if (!raw)
    {
        // skip header
        const auto    header_size = 3 + 4 * 8;
        unsigned char header[header_size];
        fread(header, 1, header_size, stdin);
    }

    Stream stream;
    byte   buffer[1024];
    while (!feof(stdin))
    {
        size_t bytes = fread(buffer, 1, 1024, stdin);
        if (bytes)
        {
            stream.append(buffer, bytes);
        }
    }

    while (!stream.eof())
    {
        auto opcode = stream.read_uint8();
        assert(opcode < countof(g_opcodes));
        const auto &data = g_opcodes[opcode];
        Op          op;
        op.code = opcode;
        for (const auto &arg : data.args)
        {
            switch (arg)
            {
            case OpcodeArg::ARG_UINT8:
                op.data.push_back(stream.read_uint8());
                break;
            case OpcodeArg::ARG_UINT16:
                op.data.push_back(stream.read_uint16());
                break;
            case OpcodeArg::ARG_UINT64:
                op.data.push_back(stream.read_uint64());
                break;
            case OpcodeArg::ARG_INT16:
                op.data.push_back(stream.read_int16());
                break;
            case OpcodeArg::ARG_VLC:
                op.data.push_back(stream.read_vlc_string());
                break;
            case OpcodeArg::ARG_UINT32:
                op.data.push_back(stream.read_uint32());
                break;
            case OpcodeArg::ARG_INT32:
                op.data.push_back(stream.read_int32());
                break;
            case OpcodeArg::ARG_REG:
                op.data.push_back(stream.read_reg());
                break;
            case OpcodeArg::ARG_SYMBOL:
                op.data.push_back(stream.read_symbol());
                break;
            case OpcodeArg::ARG_REGLIST:
                op.data.push_back(stream.read_reglist());
                break;
            case OpcodeArg::ARG_STRING4:
                op.data.push_back(stream.read_string4());
                break;
            case OpcodeArg::ARG_CSTRING:
                op.data.push_back(stream.read_cstring());
                break;
            }
        }
        func(op);
    }
};

int main(int argc, char **argv)
{
    bool raw = (argc == 2) && (std::string(argv[1]) == "--raw");

    std::map<uint64_t, std::string>        files;
    std::map<uint64_t, std::set<uint64_t>> lines;

    parse_asm(raw, [&files, &lines](Op op) {
        if (op.code == OP_COV_FILE)
        {
            files[op.arg_uint16(0)] = op.arg_string(1);
        }
        if (op.code == OP_COV)
        {
            lines[op.arg_uint16(0)].insert(op.arg_uint16(1));
        }
    });

    printf("[");
    int j = 0;
    for (auto f : files)
    {
        if (j++ > 0)
            printf(",");
        printf("{\"file\": \"%s\", \"lines\": [", f.second.c_str());
        auto &file_lines = lines[f.first];
        int   i          = 0;
        for (auto line : file_lines)
        {
            if (i++ > 0)
                printf(", ");
            printf("%d", (int)line);
        }
        printf("]}");
    }
    printf("]\n");

    return 0;
}
<commit_msg>cdumpcov: extract read_stream<commit_after>#include "../cshared/shared.h"
#include "../cshared/opcodes.h"
#include "../cshared/opcodes_format.h"
#include "../cshared/opcodes_debug.h"
#include "../cshared/asm_stream.h"
#include "../cshared/stream.h"

struct Arg
{
    uint64_t    fixnum = 0;
    std::string string;

    Arg(uint64_t fixnum) : fixnum(fixnum)
    {
    }
    Arg(dab_register_t reg) : fixnum(reg.value())
    {
    }
    Arg(std::vector<dab_register_t> regs)
    {
        (void)regs;
    }
    Arg(std::string string) : string(string)
    {
    }
};

struct Op
{
    size_t           code;
    std::vector<Arg> data;

    uint16_t arg_uint16(size_t index)
    {
        return data[index].fixnum;
    }

    std::string arg_string(size_t index)
    {
        return data[index].string;
    }
};

void read_stream(Stream &stream)
{
    byte buffer[1024];
    while (!feof(stdin))
    {
        size_t bytes = fread(buffer, 1, 1024, stdin);
        if (bytes)
        {
            stream.append(buffer, bytes);
        }
    }
}

void parse_asm(bool raw, std::function<void(Op)> func)
{
    if (!raw)
    {
        // skip header
        const auto    header_size = 3 + 4 * 8;
        unsigned char header[header_size];
        fread(header, 1, header_size, stdin);
    }

    Stream stream;
    read_stream(stream);

    while (!stream.eof())
    {
        auto opcode = stream.read_uint8();
        assert(opcode < countof(g_opcodes));
        const auto &data = g_opcodes[opcode];
        Op          op;
        op.code = opcode;
        for (const auto &arg : data.args)
        {
            switch (arg)
            {
            case OpcodeArg::ARG_UINT8:
                op.data.push_back(stream.read_uint8());
                break;
            case OpcodeArg::ARG_UINT16:
                op.data.push_back(stream.read_uint16());
                break;
            case OpcodeArg::ARG_UINT64:
                op.data.push_back(stream.read_uint64());
                break;
            case OpcodeArg::ARG_INT16:
                op.data.push_back(stream.read_int16());
                break;
            case OpcodeArg::ARG_VLC:
                op.data.push_back(stream.read_vlc_string());
                break;
            case OpcodeArg::ARG_UINT32:
                op.data.push_back(stream.read_uint32());
                break;
            case OpcodeArg::ARG_INT32:
                op.data.push_back(stream.read_int32());
                break;
            case OpcodeArg::ARG_REG:
                op.data.push_back(stream.read_reg());
                break;
            case OpcodeArg::ARG_SYMBOL:
                op.data.push_back(stream.read_symbol());
                break;
            case OpcodeArg::ARG_REGLIST:
                op.data.push_back(stream.read_reglist());
                break;
            case OpcodeArg::ARG_STRING4:
                op.data.push_back(stream.read_string4());
                break;
            case OpcodeArg::ARG_CSTRING:
                op.data.push_back(stream.read_cstring());
                break;
            }
        }
        func(op);
    }
};

int main(int argc, char **argv)
{
    bool raw = (argc == 2) && (std::string(argv[1]) == "--raw");

    std::map<uint64_t, std::string>        files;
    std::map<uint64_t, std::set<uint64_t>> lines;

    parse_asm(raw, [&files, &lines](Op op) {
        if (op.code == OP_COV_FILE)
        {
            files[op.arg_uint16(0)] = op.arg_string(1);
        }
        if (op.code == OP_COV)
        {
            lines[op.arg_uint16(0)].insert(op.arg_uint16(1));
        }
    });

    printf("[");
    int j = 0;
    for (auto f : files)
    {
        if (j++ > 0)
            printf(",");
        printf("{\"file\": \"%s\", \"lines\": [", f.second.c_str());
        auto &file_lines = lines[f.first];
        int   i          = 0;
        for (auto line : file_lines)
        {
            if (i++ > 0)
                printf(", ");
            printf("%d", (int)line);
        }
        printf("]}");
    }
    printf("]\n");

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <gflags/gflags.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "gen-cpp/PointStore.h"

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

using namespace core;

DEFINE_int32(port1, 8000, "Server1 port to connect to");
DEFINE_int32(port2, 8001, "Server2 port to connect to");

Point makePoint(int x, int y) {
  Point p;
  p.xCord = x;
  p.yCord = y;
  return p;
}

Data makeData(int id, Point p, string value = "") {
  Data d;
  d.id = id;
  d.point = p;
  d.value = value;
  return d;
}

class Client {
 public:
  Client(string ip, int port) {
    socket.reset(new TSocket(ip, port));
    transport.reset(new TBufferedTransport(socket));
    protocol.reset(new TBinaryProtocol(transport));
    client = new PointStoreClient(protocol);
    transport->open();
  }

  ~Client() {
    transport->close();
    delete client;
  }

  PointStoreClient& get() {
    return *client;
  }

  boost::shared_ptr<TTransport> socket;
  boost::shared_ptr<TTransport> transport;
  boost::shared_ptr<TProtocol> protocol;
  PointStoreClient* client;
};

int main(int argc, char **argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);

  Client client1 ("localhost", FLAGS_port1);
  Client client2 ("localhost", FLAGS_port2);
  try {
    // Create 3 points
    Data d1 = makeData(1, makePoint(10, 10), "Point1");
    Data d2 = makeData(2, makePoint(20, 20), "Point2");
    Data d3 = makeData(3, makePoint(10, 20), "Point3");
    try {
      printf("Creating d1\n");
      client1.get().createData(d1.id, d1.point, time(nullptr), d1.value);
      printf("Creating d2\n");
      client1.get().createData(d2.id, d2.point, time(nullptr), d2.value);
      printf("Creating d3\n");
      client1.get().createData(d3.id, d3.point, time(nullptr), d3.value);
    } catch (ZeonException const& ze) {
      printf("Create failed: %d %s\n", ze.what, ze.why.c_str());
    }

    // Create 3 points
    Data d4 = makeData(4, makePoint(110, 10), "Point4");
    Data d5 = makeData(5, makePoint(120, 20), "Point5");
    Data d6 = makeData(6, makePoint(110, 20), "Point6");
    try {
      printf("Creating d4\n");
      client2.get().createData(d4.id, d4.point, time(nullptr), d4.value);
      printf("Creating d5\n");
      client2.get().createData(d5.id, d5.point, time(nullptr), d5.value);
      printf("Creating d6\n");
      client2.get().createData(d6.id, d6.point, time(nullptr), d6.value);
    } catch (ZeonException const& ze) {
      printf("Create failed: %d %s\n", ze.what, ze.why.c_str());
    }

    vector<Data> ret;
    printf("Getting 3 nearest points to (15,15)\n");
    client1.get().getNearestKByPoint(ret, makePoint(15, 15), 3);
    for (auto const& d: ret) {
      cout << "Recv: " << d.id << " (" << d.point.xCord << "," << d.point.yCord << ") " << d.value << "\n";
    }

    printf("Getting 1 nearest points to (15,15)\n");
    client1.get().getNearestKByPoint(ret, makePoint(15, 15), 1);
    for (auto const& d: ret) {
      cout << "Recv: " << d.id << " (" << d.point.xCord << "," << d.point.yCord << ") " << d.value << "\n";
    }

  } catch (ZeonException const& ze) {
    cout << "ZeonException: " << ze.what << " " << ze.why << endl;
  } catch (TException const& tx) {
    cout << "ERROR: " << tx.what() << endl;
  }

}
<commit_msg>Everything works*<commit_after>#include <iostream>
#include <gflags/gflags.h>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>

#include "gen-cpp/PointStore.h"

using namespace std;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;

using namespace core;

DEFINE_int32(port1, 8000, "Server1 port to connect to");
DEFINE_int32(port2, 8001, "Server2 port to connect to");

Point makePoint(int x, int y) {
  Point p;
  p.xCord = x;
  p.yCord = y;
  return p;
}

Data makeData(int id, Point p, string value = "") {
  Data d;
  d.id = id;
  d.point = p;
  d.value = value;
  return d;
}

class Client {
 public:
  Client(string ip, int port) {
    socket.reset(new TSocket(ip, port));
    transport.reset(new TBufferedTransport(socket));
    protocol.reset(new TBinaryProtocol(transport));
    client = new PointStoreClient(protocol);
    transport->open();
  }

  ~Client() {
    transport->close();
    delete client;
  }

  PointStoreClient& get() {
    return *client;
  }

  boost::shared_ptr<TTransport> socket;
  boost::shared_ptr<TTransport> transport;
  boost::shared_ptr<TProtocol> protocol;
  PointStoreClient* client;
};

void printData(Data const& d) {
  cout << "Recv: " << d.id << " (" << d.point.xCord << "," << d.point.yCord << ") " << d.value << "\n";
}

int main(int argc, char **argv) {
  google::ParseCommandLineFlags(&argc, &argv, true);

  Client client1 ("localhost", FLAGS_port1);
  Client client2 ("localhost", FLAGS_port2);
  try {
    // Create 3 points
    Data d1 = makeData(1, makePoint(10, 10), "Point1");
    Data d2 = makeData(2, makePoint(20, 20), "Point2");
    Data d3 = makeData(3, makePoint(10, 20), "Point3");
    try {
      printf("Creating d1\n");
      client1.get().createData(d1.id, d1.point, time(nullptr), d1.value);
      printf("Creating d2\n");
      client1.get().createData(d2.id, d2.point, time(nullptr), d2.value);
      printf("Creating d3\n");
      client1.get().createData(d3.id, d3.point, time(nullptr), d3.value);
    } catch (ZeonException const& ze) {
      printf("Create failed: %d %s\n", ze.what, ze.why.c_str());
    }

    // Create 3 points
    Data d4 = makeData(4, makePoint(110, 10), "Point4");
    Data d5 = makeData(5, makePoint(120, 20), "Point5");
    Data d6 = makeData(6, makePoint(110, 20), "Point6");
    try {
      printf("Creating d4\n");
      client2.get().createData(d4.id, d4.point, time(nullptr), d4.value);
      printf("Creating d5\n");
      client2.get().createData(d5.id, d5.point, time(nullptr), d5.value);
      printf("Creating d6\n");
      client2.get().createData(d6.id, d6.point, time(nullptr), d6.value);
    } catch (ZeonException const& ze) {
      printf("Create failed: %d %s\n", ze.what, ze.why.c_str());
    }

    vector<Data> ret;
    printf("Getting 3 nearest points to (15,15)\n");
    client1.get().getNearestKByPoint(ret, makePoint(15, 15), 3);
    for (auto const& d: ret) {
      cout << "Recv: " << d.id << " (" << d.point.xCord << "," << d.point.yCord << ") " << d.value << "\n";
    }

    printf("Getting 1 nearest points to (15,15)\n");
    client1.get().getNearestKByPoint(ret, makePoint(15, 15), 1);
    for (auto const& d: ret) {
      cout << "Recv: " << d.id << " (" << d.point.xCord << "," << d.point.yCord << ") " << d.value << "\n";
    }

    Data dataToMove = makeData(1, makePoint(115, 10));
    dataToMove.prevPoint = makePoint(10, 10);
    client2.get().setData(dataToMove, false);

    try {
      Data dataRecv;
      printf("Getting data from server1\n");
      client1.get().getData(dataRecv, 1, true);
      printData(dataRecv);
    } catch (ZeonException const& ze) {
      printf("Set failed: %d %s\n", ze.what, ze.why.c_str());
    }

  } catch (ZeonException const& ze) {
    cout << "ZeonException: " << ze.what << " " << ze.why << endl;
  } catch (TException const& tx) {
    cout << "ERROR: " << tx.what() << endl;
  }

}
<|endoftext|>


<commit_before>#include <cmath>
#include <cstdlib>
#include <ctime>
#include "Experience.h"
#include "StateSpace.h"
#include "Action.h"

//utility calculation function
double q();

//reward function based off raw position and velocity
double state_reward(const double theta, const double theta_dot);

int main()
{
	std::srand(std::time(NULL));

	//create the state space
	StateSpace space(100,50);

	//array to hold the current state of the robot
	double current_state[2]={0,0};
	double last_state[2]={0,0};

	//create pointers to the possible actions as well as pointers to hold the chosen action and the previous action
	Action* actions[2],chosen_action;
	actions[0]=new action(FORWARDS);
	actions[1]=new action(BACKWARDS);

	//evaluate state
	current_state[0]=getPosition();//!
	current_state[1]=getVelocity();//!

	while(true)
	{
		//evaluate q of last action
		//current_state>>old_state

		chosen_action=selectAction(/*...*/);

		//>>current_state
	}

	delete actions[0];
	delete actions[1];

	return 1;
}

double q()
{
	return //StateSpace[originalstate[0],originalstate[1]].GetExperience().GetUtility(action) + learningrate(state_reward(newstate[0], newstate[1]) + gamma(StateSpace[newstate[0],newstate[1]].GetExperience().GetHighestUtility()) - StateSpace[originalstate[0],originalstate[1]].GetExperience().GetUtility(action); // Utility calculation pseudocode
}

double state_reward(const double theta, const double theta_dot)
{
	return 180+theta_dot*theta/std::abs(theta_dot);
}
//updates Q value for a state-action
void updateQ(StateSpace * space, Action * action, State * current_state,
                 State * old_state, double alpha, double gamma)
{
    //oldQ value
    double oldQ = (*space).StateSearch(old_state).search(action).second;
    //reward given to current state
    double R = new_state->getReward();
    //optimal Q value for new state i.e. first element
    double maxQ = (*space).StateSearch(current_state)[0].second;

    //new Q value determined by Q learning algorithm
    double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ;

    //updates Q value
    (*space).StateSearch(old_state).search(action).second = newQ;
}

//function is fed with a priority queue of action-values
//generates Boltzmann distribution of these action-values
//and selects an action based on probabilities
Action * selectAction(PriorityQueue<Action *,double> a_queue, double temp)
{
    typedef PriorityQueue<Action *,double> PQ;
    typedef std::vector< std::pair<Action *, double> > Vec_Pair;
    typedef std::pair<Action *, double> Pair;

    double sum= 0;
    int i = 0;

    int size = a_queue.getSize();
    Vec_Pair action_vec(size);
    Pair pear;

    //Calculate partition function by iterating over action-values
	for(PQ::constIter iter = a_queue.begin(); iter < a_queue.end(); iter++)
	{
		sum += std::exp((iter->second)/temp);
	}
	//Calculate boltzmann factors for action-values
	for(Vec_Pair::iterator it = action_vec.begin(); it < action_vec.end(); it++)
	{
	    it->first = a_queue[i].first;
	    it->second = std::exp(a_queue[i].second / temp) / sum;
	    i++;
	}
	//calculate cumulative probability distribution
    for(std::vector< std::pair<int, double> >::iterator it = action_vec.begin()+1; it < action_vec.end(); it++)
	{
	    it->second += (it-1)->second;
	}
    //seed random number generator
	srand(time(NULL));
	//generate RN between 0 and 1
	double rand_num = (double)rand()/ (RAND_MAX);

	//select action based on probability
    for(Vec_Pair::iterator it = action_vec.begin(); it < action_vec.end(); it++)
    {
        //if RN falls within cumulative probability bin return the corresponding action
        if(rand_num < it->second){return it->first};
    }
    return -1;
}
<commit_msg>minor bug fixes<commit_after>#include <cmath>
#include <cstdlib>
#include <ctime>
#include "StateSpace.h"
#include "Action.h"
#include "PriorityQueue.h"

//utility calculation function
double q();

//reward function based off raw position and velocity
double state_reward(const double theta, const double theta_dot);

int main()
{
	std::srand(std::time(NULL));

	//create the state space
	StateSpace space(100,50);

	//array to hold the current state of the robot
//	double current_state[2]={0,0};
//	double last_state[2]={0,0};

	//create pointers to the possible actions as well as pointers to hold the chosen action and the previous action
//	Action* chosen_action;
	Action* actions[2];
	actions[0]=new Action(TORSO_FORWARDS);
	actions[1]=new Action(TORSO_BACK);

	//evaluate state
//	current_state[0]=getPosition();
//	current_state[1]=getVelocity();

	while(true)
	{
		//evaluate q of last action
		//current_state>>old_state

		//chosen_action=selectAction(/*...*/);

		//>>current_state
	}

	delete actions[0];
	delete actions[1];

	return 1;
}

double q()
{
	return 1;//StateSpace[originalstate[0],originalstate[1]].GetExperience().GetUtility(action) + learningrate(state_reward(newstate[0], newstate[1]) + gamma(StateSpace[newstate[0],newstate[1]].GetExperience().GetHighestUtility()) - StateSpace[originalstate[0],originalstate[1]].GetExperience().GetUtility(action); // Utility calculation pseudocode
}

double state_reward(const double theta, const double theta_dot)
{
	return 180+theta_dot*theta/std::abs(theta_dot);
}

//function is fed with a priority queue of action-values
//generates Boltzmann distribution of these action-values
//and selects an action based on probabilities
Action * selectAction(PriorityQueue<Action *,double>& a_queue, double temp)
{
	typedef PriorityQueue<Action *,double> PQ;
	typedef std::vector< std::pair<Action *, double> > Vec_Pair;
	typedef std::pair<Action *, double> Pair;

	double sum= 0;
	int i = 0;

	int size = a_queue.getSize();
	Vec_Pair action_vec(size);
	Pair pear;

	//Calculate partition function by iterating over action-values
	for(auto iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)
	{
		sum += std::exp((iter->second)/temp);
	}
	//Calculate boltzmann factors for action-values
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
	    it->first = a_queue[i].first;
	    it->second = std::exp(a_queue[i].second / temp) / sum;
	    ++i;
	}
	//calculate cumulative probability distribution
	for(std::vector< std::pair<int, double> >::iterator it = action_vec.begin()+1,end=action_vec.end(); it < end; ++it)
	{
	    it->second += (it-1)->second;
	}

	//generate RN between 0 and 1
	double rand_num = (double)rand()/ (RAND_MAX);

	//select action based on probability
	for(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)
	{
		//if RN falls within cumulative probability bin return the corresponding action
		if(rand_num < it->second)return it->first;
	}

	return nullptr; //note that this line should never be reached
}
<|endoftext|>


<commit_before>#include "keyboard-layout-manager.h"

#include <X11/XKBlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/XKBrules.h>
#include <cwctype>
#include <cctype>

void KeyboardLayoutManager::Init(v8::Handle<v8::Object> exports, v8::Handle<v8::Object> module) {
  Nan::HandleScope scope;
  v8::Local<v8::FunctionTemplate> newTemplate = Nan::New<v8::FunctionTemplate>(KeyboardLayoutManager::New);
  newTemplate->SetClassName(Nan::New<v8::String>("KeyboardLayoutManager").ToLocalChecked());
  newTemplate->InstanceTemplate()->SetInternalFieldCount(1);
  v8::Local<v8::ObjectTemplate> proto = newTemplate->PrototypeTemplate();
  Nan::SetMethod(proto, "getCurrentKeyboardLayout", KeyboardLayoutManager::GetCurrentKeyboardLayout);
  Nan::SetMethod(proto, "getCurrentKeyboardLanguage", KeyboardLayoutManager::GetCurrentKeyboardLayout); // NB:  Intentionally mapped to same stub
  Nan::SetMethod(proto, "getInstalledKeyboardLanguages", KeyboardLayoutManager::GetInstalledKeyboardLanguages);
  Nan::SetMethod(proto, "getCurrentKeymap", KeyboardLayoutManager::GetCurrentKeymap);
  module->Set(Nan::New("exports").ToLocalChecked(), newTemplate->GetFunction());
}

NODE_MODULE(keyboard_layout_manager, KeyboardLayoutManager::Init)

NAN_METHOD(KeyboardLayoutManager::New) {
  Nan::HandleScope scope;

  v8::Local<v8::Function> callbackHandle = info[0].As<v8::Function>();
  Nan::Callback *callback = new Nan::Callback(callbackHandle);

  KeyboardLayoutManager *manager = new KeyboardLayoutManager(callback);
  manager->Wrap(info.This());
  return;
}

KeyboardLayoutManager::KeyboardLayoutManager(Nan::Callback *callback) : callback{callback}, xInputContext{nullptr} {
  xDisplay = XOpenDisplay("");
  if (!xDisplay) {
    Nan::ThrowError("Could not connect to X display.");
    return;
  }

  xInputMethod = XOpenIM(xDisplay, 0, 0, 0);
  if (!xInputMethod) {
    return;
  }

  XIMStyles* styles = 0;
  if (XGetIMValues(xInputMethod, XNQueryInputStyle, &styles, NULL) || !styles) {
    return;
  }

  XIMStyle bestMatchStyle = 0;
  for (int i = 0; i < styles->count_styles; i++) {
    XIMStyle thisStyle = styles->supported_styles[i];
    if (thisStyle == (XIMPreeditNothing | XIMStatusNothing))
    {
      bestMatchStyle = thisStyle;
      break;
    }
  }
  XFree(styles);
  if (!bestMatchStyle) {
    return;
  }

  Window window;
  int revert_to;
  XGetInputFocus(xDisplay, &window, &revert_to);
  if (window != BadRequest) {
    xInputContext = XCreateIC(
      xInputMethod, XNInputStyle, bestMatchStyle, XNClientWindow, window,
      XNFocusWindow, window, NULL
    );
  }
}

KeyboardLayoutManager::~KeyboardLayoutManager() {
  XDestroyIC(xInputContext);
  XCloseIM(xInputMethod);
  XCloseDisplay(xDisplay);
  delete callback;
};

void KeyboardLayoutManager::HandleKeyboardLayoutChanged() {
}

NAN_METHOD(KeyboardLayoutManager::GetCurrentKeyboardLayout) {
  Nan::HandleScope scope;
  KeyboardLayoutManager* manager = Nan::ObjectWrap::Unwrap<KeyboardLayoutManager>(info.Holder());
  v8::Handle<v8::Value> result;

  XkbRF_VarDefsRec vdr;
  char *tmp = NULL;
  if (XkbRF_GetNamesProp(manager->xDisplay, &tmp, &vdr) && vdr.layout) {
    XkbStateRec xkbState;
    XkbGetState(manager->xDisplay, XkbUseCoreKbd, &xkbState);
    if (vdr.variant) {
      result = Nan::New<v8::String>(std::string(vdr.layout) + "," + std::string(vdr.variant) + " [" + std::to_string(xkbState.group) + "]").ToLocalChecked();
    } else {
      result = Nan::New<v8::String>(std::string(vdr.layout) + " [" + std::to_string(xkbState.group) + "]").ToLocalChecked();
    }
  } else {
    result = Nan::Null();
  }

  info.GetReturnValue().Set(result);

  return;
}

NAN_METHOD(KeyboardLayoutManager::GetInstalledKeyboardLanguages) {
  Nan::HandleScope scope;
  return;
}

struct KeycodeMapEntry {
  uint xkbKeycode;
  const char *dom3Code;
};

#define USB_KEYMAP_DECLARATION static const KeycodeMapEntry keyCodeMap[] =
#define USB_KEYMAP(usb, evdev, xkb, win, mac, code, id) {xkb, code}

#include "keycode_converter_data.inc"

v8::Local<v8::Value> CharacterForNativeCode(XIC xInputContext, XKeyEvent *keyEvent, uint xkbKeycode, uint state) {
  keyEvent->keycode = xkbKeycode;
  keyEvent->state = state;

  if (xInputContext) {
    wchar_t characters[2];
    int count = XwcLookupString(xInputContext, keyEvent, characters, 2, NULL, NULL);
    if (count > 0 && !std::iswcntrl(characters[0])) {
      return Nan::New<v8::String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
    } else {
      return Nan::Null();
    }
  } else {
    // Graceful fallback for systems where no window is open or no input context
    // can be found.
    char characters[2];
    int count = XLookupString(keyEvent, characters, 2, NULL, NULL);
    if (count > 0 && !std::iscntrl(characters[0])) {
      return Nan::New<v8::String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
    } else {
      return Nan::Null();
    }
  }
}

NAN_METHOD(KeyboardLayoutManager::GetCurrentKeymap) {
  v8::Handle<v8::Object> result = Nan::New<v8::Object>();
  KeyboardLayoutManager* manager = Nan::ObjectWrap::Unwrap<KeyboardLayoutManager>(info.Holder());
  v8::Local<v8::String> unmodifiedKey = Nan::New("unmodified").ToLocalChecked();
  v8::Local<v8::String> withShiftKey = Nan::New("withShift").ToLocalChecked();

  // Clear cached keymap
  XMappingEvent eventMap = {MappingNotify, 0, false, manager->xDisplay, 0, MappingKeyboard, 0, 0};
  XRefreshKeyboardMapping(&eventMap);

  XkbStateRec xkbState;
  XkbGetState(manager->xDisplay, XkbUseCoreKbd, &xkbState);
  uint keyboardBaseState = 0x0000;
  if (xkbState.group == 1) {
    keyboardBaseState = 0x2000;
  } else if (xkbState.group == 2) {
    keyboardBaseState = 0x4000;
  }

  // Set up an event to reuse across CharacterForNativeCode calls
  XEvent event;
  memset(&event, 0, sizeof(XEvent));
  XKeyEvent* keyEvent = &event.xkey;
  keyEvent->display = manager->xDisplay;
  keyEvent->type = KeyPress;

  size_t keyCodeMapSize = sizeof(keyCodeMap) / sizeof(keyCodeMap[0]);
  for (size_t i = 0; i < keyCodeMapSize; i++) {
    const char *dom3Code = keyCodeMap[i].dom3Code;
    uint xkbKeycode = keyCodeMap[i].xkbKeycode;

    if (dom3Code && xkbKeycode > 0x0000) {
      v8::Local<v8::String> dom3CodeKey = Nan::New(dom3Code).ToLocalChecked();
      v8::Local<v8::Value> unmodified = CharacterForNativeCode(manager->xInputContext, keyEvent, xkbKeycode, keyboardBaseState);
      v8::Local<v8::Value> withShift = CharacterForNativeCode(manager->xInputContext, keyEvent, xkbKeycode, keyboardBaseState | ShiftMask);

      if (unmodified->IsString() || withShift->IsString()) {
        v8::Local<v8::Object> entry = Nan::New<v8::Object>();
        entry->Set(unmodifiedKey, unmodified);
        entry->Set(withShiftKey, withShift);
        result->Set(dom3CodeKey, entry);
      }
    }
  }

  info.GetReturnValue().Set(result);
}
<commit_msg>:art: Fix warning<commit_after>#include "keyboard-layout-manager.h"

#include <X11/XKBlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/XKBrules.h>
#include <cwctype>
#include <cctype>

void KeyboardLayoutManager::Init(v8::Handle<v8::Object> exports, v8::Handle<v8::Object> module) {
  Nan::HandleScope scope;
  v8::Local<v8::FunctionTemplate> newTemplate = Nan::New<v8::FunctionTemplate>(KeyboardLayoutManager::New);
  newTemplate->SetClassName(Nan::New<v8::String>("KeyboardLayoutManager").ToLocalChecked());
  newTemplate->InstanceTemplate()->SetInternalFieldCount(1);
  v8::Local<v8::ObjectTemplate> proto = newTemplate->PrototypeTemplate();
  Nan::SetMethod(proto, "getCurrentKeyboardLayout", KeyboardLayoutManager::GetCurrentKeyboardLayout);
  Nan::SetMethod(proto, "getCurrentKeyboardLanguage", KeyboardLayoutManager::GetCurrentKeyboardLayout); // NB:  Intentionally mapped to same stub
  Nan::SetMethod(proto, "getInstalledKeyboardLanguages", KeyboardLayoutManager::GetInstalledKeyboardLanguages);
  Nan::SetMethod(proto, "getCurrentKeymap", KeyboardLayoutManager::GetCurrentKeymap);
  module->Set(Nan::New("exports").ToLocalChecked(), newTemplate->GetFunction());
}

NODE_MODULE(keyboard_layout_manager, KeyboardLayoutManager::Init)

NAN_METHOD(KeyboardLayoutManager::New) {
  Nan::HandleScope scope;

  v8::Local<v8::Function> callbackHandle = info[0].As<v8::Function>();
  Nan::Callback *callback = new Nan::Callback(callbackHandle);

  KeyboardLayoutManager *manager = new KeyboardLayoutManager(callback);
  manager->Wrap(info.This());
  return;
}

KeyboardLayoutManager::KeyboardLayoutManager(Nan::Callback *callback) : xInputContext{nullptr}, callback{callback} {
  xDisplay = XOpenDisplay("");
  if (!xDisplay) {
    Nan::ThrowError("Could not connect to X display.");
    return;
  }

  xInputMethod = XOpenIM(xDisplay, 0, 0, 0);
  if (!xInputMethod) {
    return;
  }

  XIMStyles* styles = 0;
  if (XGetIMValues(xInputMethod, XNQueryInputStyle, &styles, NULL) || !styles) {
    return;
  }

  XIMStyle bestMatchStyle = 0;
  for (int i = 0; i < styles->count_styles; i++) {
    XIMStyle thisStyle = styles->supported_styles[i];
    if (thisStyle == (XIMPreeditNothing | XIMStatusNothing))
    {
      bestMatchStyle = thisStyle;
      break;
    }
  }
  XFree(styles);
  if (!bestMatchStyle) {
    return;
  }

  Window window;
  int revert_to;
  XGetInputFocus(xDisplay, &window, &revert_to);
  if (window != BadRequest) {
    xInputContext = XCreateIC(
      xInputMethod, XNInputStyle, bestMatchStyle, XNClientWindow, window,
      XNFocusWindow, window, NULL
    );
  }
}

KeyboardLayoutManager::~KeyboardLayoutManager() {
  XDestroyIC(xInputContext);
  XCloseIM(xInputMethod);
  XCloseDisplay(xDisplay);
  delete callback;
};

void KeyboardLayoutManager::HandleKeyboardLayoutChanged() {
}

NAN_METHOD(KeyboardLayoutManager::GetCurrentKeyboardLayout) {
  Nan::HandleScope scope;
  KeyboardLayoutManager* manager = Nan::ObjectWrap::Unwrap<KeyboardLayoutManager>(info.Holder());
  v8::Handle<v8::Value> result;

  XkbRF_VarDefsRec vdr;
  char *tmp = NULL;
  if (XkbRF_GetNamesProp(manager->xDisplay, &tmp, &vdr) && vdr.layout) {
    XkbStateRec xkbState;
    XkbGetState(manager->xDisplay, XkbUseCoreKbd, &xkbState);
    if (vdr.variant) {
      result = Nan::New<v8::String>(std::string(vdr.layout) + "," + std::string(vdr.variant) + " [" + std::to_string(xkbState.group) + "]").ToLocalChecked();
    } else {
      result = Nan::New<v8::String>(std::string(vdr.layout) + " [" + std::to_string(xkbState.group) + "]").ToLocalChecked();
    }
  } else {
    result = Nan::Null();
  }

  info.GetReturnValue().Set(result);

  return;
}

NAN_METHOD(KeyboardLayoutManager::GetInstalledKeyboardLanguages) {
  Nan::HandleScope scope;
  return;
}

struct KeycodeMapEntry {
  uint xkbKeycode;
  const char *dom3Code;
};

#define USB_KEYMAP_DECLARATION static const KeycodeMapEntry keyCodeMap[] =
#define USB_KEYMAP(usb, evdev, xkb, win, mac, code, id) {xkb, code}

#include "keycode_converter_data.inc"

v8::Local<v8::Value> CharacterForNativeCode(XIC xInputContext, XKeyEvent *keyEvent, uint xkbKeycode, uint state) {
  keyEvent->keycode = xkbKeycode;
  keyEvent->state = state;

  if (xInputContext) {
    wchar_t characters[2];
    int count = XwcLookupString(xInputContext, keyEvent, characters, 2, NULL, NULL);
    if (count > 0 && !std::iswcntrl(characters[0])) {
      return Nan::New<v8::String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
    } else {
      return Nan::Null();
    }
  } else {
    // Graceful fallback for systems where no window is open or no input context
    // can be found.
    char characters[2];
    int count = XLookupString(keyEvent, characters, 2, NULL, NULL);
    if (count > 0 && !std::iscntrl(characters[0])) {
      return Nan::New<v8::String>(reinterpret_cast<const uint16_t *>(characters), count).ToLocalChecked();
    } else {
      return Nan::Null();
    }
  }
}

NAN_METHOD(KeyboardLayoutManager::GetCurrentKeymap) {
  v8::Handle<v8::Object> result = Nan::New<v8::Object>();
  KeyboardLayoutManager* manager = Nan::ObjectWrap::Unwrap<KeyboardLayoutManager>(info.Holder());
  v8::Local<v8::String> unmodifiedKey = Nan::New("unmodified").ToLocalChecked();
  v8::Local<v8::String> withShiftKey = Nan::New("withShift").ToLocalChecked();

  // Clear cached keymap
  XMappingEvent eventMap = {MappingNotify, 0, false, manager->xDisplay, 0, MappingKeyboard, 0, 0};
  XRefreshKeyboardMapping(&eventMap);

  XkbStateRec xkbState;
  XkbGetState(manager->xDisplay, XkbUseCoreKbd, &xkbState);
  uint keyboardBaseState = 0x0000;
  if (xkbState.group == 1) {
    keyboardBaseState = 0x2000;
  } else if (xkbState.group == 2) {
    keyboardBaseState = 0x4000;
  }

  // Set up an event to reuse across CharacterForNativeCode calls
  XEvent event;
  memset(&event, 0, sizeof(XEvent));
  XKeyEvent* keyEvent = &event.xkey;
  keyEvent->display = manager->xDisplay;
  keyEvent->type = KeyPress;

  size_t keyCodeMapSize = sizeof(keyCodeMap) / sizeof(keyCodeMap[0]);
  for (size_t i = 0; i < keyCodeMapSize; i++) {
    const char *dom3Code = keyCodeMap[i].dom3Code;
    uint xkbKeycode = keyCodeMap[i].xkbKeycode;

    if (dom3Code && xkbKeycode > 0x0000) {
      v8::Local<v8::String> dom3CodeKey = Nan::New(dom3Code).ToLocalChecked();
      v8::Local<v8::Value> unmodified = CharacterForNativeCode(manager->xInputContext, keyEvent, xkbKeycode, keyboardBaseState);
      v8::Local<v8::Value> withShift = CharacterForNativeCode(manager->xInputContext, keyEvent, xkbKeycode, keyboardBaseState | ShiftMask);

      if (unmodified->IsString() || withShift->IsString()) {
        v8::Local<v8::Object> entry = Nan::New<v8::Object>();
        entry->Set(unmodifiedKey, unmodified);
        entry->Set(withShiftKey, withShift);
        result->Set(dom3CodeKey, entry);
      }
    }
  }

  info.GetReturnValue().Set(result);
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
 *
 * Released under the MIT license, see LICENSE.txt
 */

#include <deque>
#include <cassert>
#include "halMafExport.h"

using namespace std;
using namespace hal;

MafExport::MafExport() : _maxRefGap(0), _noDupes(false)
{

}

MafExport::~MafExport()
{

}

void MafExport::setMaxRefGap(hal_size_t maxRefGap)
{
  _maxRefGap = maxRefGap;
}

void MafExport::setNoDupes(bool noDupes)
{
  _noDupes = noDupes;
}

void MafExport::setNoAncestors(bool noAncestors)
{
  _noAncestors = noAncestors;
}

void MafExport::writeHeader()
{
  assert(_mafStream != NULL);
  if (_mafStream->tellp() == streampos(0))
  {
    *_mafStream << "##maf version=1 scoring=N/A\n"
                << "# hal " << _alignment->getNewickTree() << endl << endl;
  }
}

void MafExport::convertSegmentedSequence(ostream& mafStream,
                                         AlignmentConstPtr alignment,
                                         const SegmentedSequence* seq,
                                         hal_index_t startPosition,
                                         hal_size_t length,
                                         const set<const Genome*>& targets)
{
  assert(seq != NULL);
  if (startPosition >= (hal_index_t)seq->getSequenceLength() ||
      (hal_size_t)startPosition + length > seq->getSequenceLength())
  {
    throw hal_exception("Invalid range specified for convertGenome");
  }
  if (length == 0)
  {
    length = seq->getSequenceLength() - startPosition;
  }
  if (length == 0)
  {
    throw hal_exception("Cannot convert zero length sequence");
  }
  hal_index_t lastPosition = startPosition + (hal_index_t)(length - 1);

  _mafStream = &mafStream;
  _alignment = alignment;
  writeHeader();

  ColumnIteratorConstPtr colIt = seq->getColumnIterator(&targets,
                                                        _maxRefGap,
                                                        startPosition,
                                                        lastPosition,
                                                        _noDupes,
                                                        _noAncestors);
  _mafBlock.initBlock(colIt);
  assert(_mafBlock.canAppendColumn(colIt) == true);

  size_t numBlocks = 0;
  do
  {
    if (_mafBlock.canAppendColumn(colIt) == false)
    {
      // erase empty entries from the column.  helps when there are
      // millions of sequences (ie from fastas with lots of scaffolds)
      if (numBlocks++ % 1000 == 0)
      {
        colIt->defragment();
      }

      mafStream << _mafBlock << '\n';
      _mafBlock.initBlock(colIt);
      assert(_mafBlock.canAppendColumn(colIt) == true);
    }
    _mafBlock.appendColumn(colIt);
    colIt->toRight();
  }
  while (colIt->lastColumn() == false);
  mafStream << _mafBlock << endl;
}

<commit_msg>fix loop<commit_after>/*
 * Copyright (C) 2012 by Glenn Hickey (hickey@soe.ucsc.edu)
 *
 * Released under the MIT license, see LICENSE.txt
 */

#include <deque>
#include <cassert>
#include "halMafExport.h"

using namespace std;
using namespace hal;

MafExport::MafExport() : _maxRefGap(0), _noDupes(false)
{

}

MafExport::~MafExport()
{

}

void MafExport::setMaxRefGap(hal_size_t maxRefGap)
{
  _maxRefGap = maxRefGap;
}

void MafExport::setNoDupes(bool noDupes)
{
  _noDupes = noDupes;
}

void MafExport::setNoAncestors(bool noAncestors)
{
  _noAncestors = noAncestors;
}

void MafExport::writeHeader()
{
  assert(_mafStream != NULL);
  if (_mafStream->tellp() == streampos(0))
  {
    *_mafStream << "##maf version=1 scoring=N/A\n"
                << "# hal " << _alignment->getNewickTree() << endl << endl;
  }
}

void MafExport::convertSegmentedSequence(ostream& mafStream,
                                         AlignmentConstPtr alignment,
                                         const SegmentedSequence* seq,
                                         hal_index_t startPosition,
                                         hal_size_t length,
                                         const set<const Genome*>& targets)
{
  assert(seq != NULL);
  if (startPosition >= (hal_index_t)seq->getSequenceLength() ||
      (hal_size_t)startPosition + length > seq->getSequenceLength())
  {
    throw hal_exception("Invalid range specified for convertGenome");
  }
  if (length == 0)
  {
    length = seq->getSequenceLength() - startPosition;
  }
  if (length == 0)
  {
    throw hal_exception("Cannot convert zero length sequence");
  }
  hal_index_t lastPosition = startPosition + (hal_index_t)(length - 1);

  _mafStream = &mafStream;
  _alignment = alignment;
  writeHeader();

  ColumnIteratorConstPtr colIt = seq->getColumnIterator(&targets,
                                                        _maxRefGap,
                                                        startPosition,
                                                        lastPosition,
                                                        _noDupes,
                                                        _noAncestors);
  _mafBlock.initBlock(colIt);
  assert(_mafBlock.canAppendColumn(colIt) == true);
  _mafBlock.appendColumn(colIt);
  size_t numBlocks = 0;
  while (colIt->lastColumn() == false)
  {
    colIt->toRight();
    if (_mafBlock.canAppendColumn(colIt) == false)
    {
      // erase empty entries from the column.  helps when there are
      // millions of sequences (ie from fastas with lots of scaffolds)
      if (numBlocks++ % 1000 == 0)
      {
        colIt->defragment();
      }

      mafStream << _mafBlock << '\n';
      _mafBlock.initBlock(colIt);
      assert(_mafBlock.canAppendColumn(colIt) == true);
    }
    _mafBlock.appendColumn(colIt);
  }
  mafStream << _mafBlock << endl;
}

<|endoftext|>


<commit_before>#ifndef SIGMA_GRAPHICS_OPENGL_FRAME_BUFFER_HPP
#define SIGMA_GRAPHICS_OPENGL_FRAME_BUFFER_HPP

#include <sigma/config.hpp>

#include <sigma/graphics/opengl/util.hpp>

#include <glad/glad.h>

#include <glm/vec2.hpp>

#include <array>

namespace sigma {
namespace opengl {
    class texture;
    class render_buffer;

    class default_frame_buffer {
    public:
        enum class target {
            DRAW = GL_DRAW_FRAMEBUFFER,
            READ = GL_READ_FRAMEBUFFER,
        };

        default_frame_buffer(glm::ivec2 size);

        glm::ivec2 size();

        void bind();

        void bind(target tgt);

    protected:
        glm::ivec2 size_;
        GLuint object_;

    private:
        default_frame_buffer(const default_frame_buffer&) = delete;
        default_frame_buffer& operator=(const default_frame_buffer&) = delete;
    };

    // TODO hold on to bound textures???
    class frame_buffer : public default_frame_buffer {
    public:
        enum class attachment : GLenum {
            COLOR0 = GL_COLOR_ATTACHMENT0,
            COLOR1 = GL_COLOR_ATTACHMENT1,
            COLOR2 = GL_COLOR_ATTACHMENT2,
            COLOR3 = GL_COLOR_ATTACHMENT3,
            COLOR4 = GL_COLOR_ATTACHMENT4,
            COLOR5 = GL_COLOR_ATTACHMENT5,
            COLOR6 = GL_COLOR_ATTACHMENT6,
            COLOR7 = GL_COLOR_ATTACHMENT7,
            COLOR8 = GL_COLOR_ATTACHMENT8,
            COLOR9 = GL_COLOR_ATTACHMENT9,
            DEPTH = GL_DEPTH_ATTACHMENT,
            STENCIL = GL_STENCIL_ATTACHMENT,
            DEPTH_STENCIL = GL_DEPTH_STENCIL_ATTACHMENT,
            NONE = GL_NONE
        };

        frame_buffer(glm::ivec2 size);

        ~frame_buffer();

        void attach(attachment att, const texture& txt);

        void attach(attachment att, const render_buffer& buf);

        void dettach(attachment att, const texture& txt);

        void dettach(attachment att, const render_buffer& txt);

        void read_buffer(attachment att);

        template <class... Args>
        void draw_buffers(Args... atts)
        {
            std::array<attachment, sizeof...(Args)> real = { atts... };
            GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, object_));
            GL_CHECK(glDrawBuffers(sizeof...(Args), (GLenum*)real.data()));
        }

    private:
        frame_buffer(const frame_buffer&) = delete;
        frame_buffer& operator=(const frame_buffer&) = delete;
    };
}
}

#endif // SIGMA_GRAPHICS_OPENGL_FRAME_BUFFER_HPP
<commit_msg>Suppress warning.<commit_after>#ifndef SIGMA_GRAPHICS_OPENGL_FRAME_BUFFER_HPP
#define SIGMA_GRAPHICS_OPENGL_FRAME_BUFFER_HPP

#include <sigma/config.hpp>

#include <sigma/graphics/opengl/util.hpp>

#include <glad/glad.h>

#include <glm/vec2.hpp>

#include <array>

namespace sigma {
namespace opengl {
    class texture;
    class render_buffer;

    class default_frame_buffer {
    public:
        enum class target {
            DRAW = GL_DRAW_FRAMEBUFFER,
            READ = GL_READ_FRAMEBUFFER,
        };

        default_frame_buffer(glm::ivec2 size);

        glm::ivec2 size();

        void bind();

        void bind(target tgt);

    protected:
        glm::ivec2 size_;
        GLuint object_;

    private:
        default_frame_buffer(const default_frame_buffer&) = delete;
        default_frame_buffer& operator=(const default_frame_buffer&) = delete;
    };

    // TODO hold on to bound textures???
    class frame_buffer : public default_frame_buffer {
    public:
        enum class attachment : GLenum {
            COLOR0 = GL_COLOR_ATTACHMENT0,
            COLOR1 = GL_COLOR_ATTACHMENT1,
            COLOR2 = GL_COLOR_ATTACHMENT2,
            COLOR3 = GL_COLOR_ATTACHMENT3,
            COLOR4 = GL_COLOR_ATTACHMENT4,
            COLOR5 = GL_COLOR_ATTACHMENT5,
            COLOR6 = GL_COLOR_ATTACHMENT6,
            COLOR7 = GL_COLOR_ATTACHMENT7,
            COLOR8 = GL_COLOR_ATTACHMENT8,
            COLOR9 = GL_COLOR_ATTACHMENT9,
            DEPTH = GL_DEPTH_ATTACHMENT,
            STENCIL = GL_STENCIL_ATTACHMENT,
            DEPTH_STENCIL = GL_DEPTH_STENCIL_ATTACHMENT,
            NONE = GL_NONE
        };

        frame_buffer(glm::ivec2 size);

        ~frame_buffer();

        void attach(attachment att, const texture& txt);

        void attach(attachment att, const render_buffer& buf);

        void dettach(attachment att, const texture& txt);

        void dettach(attachment att, const render_buffer& txt);

        void read_buffer(attachment att);

        template <class... Args>
        void draw_buffers(Args... atts)
        {
            std::array<attachment, sizeof...(Args)> real = { { atts... } };
            GL_CHECK(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, object_));
            GL_CHECK(glDrawBuffers(sizeof...(Args), (GLenum*)real.data()));
        }

    private:
        frame_buffer(const frame_buffer&) = delete;
        frame_buffer& operator=(const frame_buffer&) = delete;
    };
}
}

#endif // SIGMA_GRAPHICS_OPENGL_FRAME_BUFFER_HPP
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/log/consoleloghandler.hpp>

#ifdef _WIN32
# include <windows.h>
# include <io.h>
# define isatty _isatty
#else
# include <unistd.h>
#endif

#define CATSIZEMAX 16

namespace qi {
  namespace log {

    class PrivateConsoleLogHandler
    {
    public:
#ifndef _WIN32
      enum ConsoleAttr {
        reset      = 0,
        bright,
        dim,
        underline  = 4,
        blink,
        reverse    = 7
      };
#else
      enum ConsoleAttr {
        reset      = 0,
        dim        = 0,
        reverse    = 7,
        bright
      };
#endif

#ifdef _WIN32
      enum ConsoleColor {
        black   = 0,
        darkblue,
        green,
        bluegray,
        brown,
        purple,
        whitegray = 7,
        gray,
        whiteblue,
        whitegreen,
        cyan,
        red,
        magenta,
        yellow,
        white
      };
#else
      enum ConsoleColor {
        black   = 0,
        red,
        green,
        yellow,
        blue,
        magenta,
        cyan,
        white,
        gray
      };
#endif

      void textColorBG(char bg) const;
      void textColorFG(char fg) const;
      void textColorAttr(char attr) const;
      void header(const LogLevel verb) const;

      bool _color;

#ifdef _WIN32
      void* _winScreenHandle;
#endif
    };

#ifndef _WIN32
    void PrivateConsoleLogHandler::textColorAttr(char attr) const
    {
      if (!_color)
        return;

      printf("%c[%dm", 0x1B, attr);
    }

    void PrivateConsoleLogHandler::textColorBG(char bg) const
    {
      if (!_color)
        return;

      printf("%c[%dm", 0x1B, bg + 40);
    }

    void PrivateConsoleLogHandler::textColorFG(char fg) const
    {
      if (!_color)
        return;

      printf("%c[%dm", 0x1B, fg + 30);
    }

#else
    void PrivateConsoleLogHandler::textColorBG(char bg) const
    {
      return;
    }

    void PrivateConsoleLogHandler::textColorAttr(char attr) const
    {
      textColorFG(attr);
      return;
    }

    void PrivateConsoleLogHandler::textColorFG(char fg) const
    {
      if (!_color)
        return;

      if (fg == reset)
      {
        SetConsoleTextAttribute(_winScreenHandle, whitegray);
      }
      else
      {
        SetConsoleTextAttribute(_winScreenHandle, fg);
      }
      return;
    }
#endif

    void PrivateConsoleLogHandler::header(const LogLevel verb) const
    {
      //display log level
      textColorAttr(reset);
      if (verb == fatal)
        textColorFG(magenta);
      if (verb == error)
        textColorFG(red);
      if (verb == warning)
        textColorFG(yellow);
      if (verb == info)
        textColorAttr(reset);
      if (verb == verbose)
        textColorAttr(dim);
      if (verb == debug)
        textColorAttr(dim);
      printf("%s ", logLevelToString(verb));
      textColorAttr(reset);
    }

    ConsoleLogHandler::ConsoleLogHandler()
      : _private(new PrivateConsoleLogHandler)
    {
      const char *color   = std::getenv("CLICOLOR");

#ifdef _WIN32
      _private->_winScreenHandle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
      _private->_color = 1;

      if (color)
        _private->_color = atoi(color) > 0 ? true: false;
      if (!isatty(1))
        _private->_color = 0;
    }

    void cutCat(const char* category, char* res)
    {
      int categorySize = strlen(category);
      if (categorySize < CATSIZEMAX)
      {
        memset(res, ' ', CATSIZEMAX);
        memcpy(res, category, strlen(category));
      }
      else
      {
        memset(res, '.', CATSIZEMAX);
        memcpy(res + 3, category + categorySize - CATSIZEMAX + 3, CATSIZEMAX - 3);
      }
      res[CATSIZEMAX] = '\0';
    }

    void ConsoleLogHandler::log(const LogLevel        verb,
                                const qi::os::timeval date,
                                const char            *category,
                                const char            *msg,
                                const char            *file,
                                const char            *fct,
                                const int             line)
    {
      if (verb > qi::log::verbosity())
      {
        return;
      }
      else
      {
        _private->header(verb);
        char fixedCategory[CATSIZEMAX + 1];
        fixedCategory[CATSIZEMAX] = '\0';
        cutCat(category, fixedCategory);
#ifndef WIN32
        _private->textColorAttr(_private->reset);
        _private->textColorFG(_private->gray);
#endif

        std::stringstream ss;
        ss << date.tv_sec << "." << date.tv_usec;

        int ctx = qi::log::context();
        switch (ctx)
        {
          case 1:
            printf("%s: ", fixedCategory);
            break;
          case 2:
            printf("%s ", ss.str().c_str());
            break;
          case 3:
            if (line == 0)
              printf("");
            else
              printf("%s(%d) ", file, line);
            break;
          case 4:
            printf("%s %s: ", ss.str().c_str(), fixedCategory);
            break;
          case 5:
            if (line == 0)
              printf("%s ", ss.str().c_str());
            else
              printf("%s %s(%d) ", ss.str().c_str(), file, line);
            break;
          case 6:
            if (line == 0)
              printf("%s: ", fixedCategory);
            else
              printf("%s: %s(%d) ", fixedCategory, file, line);
            break;
          case 7:
            if (line == 0)
              printf("%s %s: %s ", ss.str().c_str(), fixedCategory, fct);
            else
              printf("%s %s: %s(%d) %s ", ss.str().c_str(), fixedCategory, file, line, fct);
            break;
          default:
            break;
        }
        printf("%s", msg);
        fflush(stdout);
      }
      fflush(stdout);
    }
  }
}

<commit_msg>consoleloghandler: fix warning<commit_after>/*
 * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the COPYING file.
 */

#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <qi/os.hpp>
#include <qi/log.hpp>
#include <qi/log/consoleloghandler.hpp>

#ifdef _WIN32
# include <windows.h>
# include <io.h>
# define isatty _isatty
#else
# include <unistd.h>
#endif

#define CATSIZEMAX 16

namespace qi {
  namespace log {

    class PrivateConsoleLogHandler
    {
    public:
#ifndef _WIN32
      enum ConsoleAttr {
        reset      = 0,
        bright,
        dim,
        underline  = 4,
        blink,
        reverse    = 7
      };
#else
      enum ConsoleAttr {
        reset      = 0,
        dim        = 0,
        reverse    = 7,
        bright
      };
#endif

#ifdef _WIN32
      enum ConsoleColor {
        black   = 0,
        darkblue,
        green,
        bluegray,
        brown,
        purple,
        whitegray = 7,
        gray,
        whiteblue,
        whitegreen,
        cyan,
        red,
        magenta,
        yellow,
        white
      };
#else
      enum ConsoleColor {
        black   = 0,
        red,
        green,
        yellow,
        blue,
        magenta,
        cyan,
        white,
        gray
      };
#endif

      void textColorBG(char bg) const;
      void textColorFG(char fg) const;
      void textColorAttr(char attr) const;
      void header(const LogLevel verb) const;

      bool _color;

#ifdef _WIN32
      void* _winScreenHandle;
#endif
    };

#ifndef _WIN32
    void PrivateConsoleLogHandler::textColorAttr(char attr) const
    {
      if (!_color)
        return;

      printf("%c[%dm", 0x1B, attr);
    }

    void PrivateConsoleLogHandler::textColorBG(char bg) const
    {
      if (!_color)
        return;

      printf("%c[%dm", 0x1B, bg + 40);
    }

    void PrivateConsoleLogHandler::textColorFG(char fg) const
    {
      if (!_color)
        return;

      printf("%c[%dm", 0x1B, fg + 30);
    }

#else
    void PrivateConsoleLogHandler::textColorBG(char bg) const
    {
      return;
    }

    void PrivateConsoleLogHandler::textColorAttr(char attr) const
    {
      textColorFG(attr);
      return;
    }

    void PrivateConsoleLogHandler::textColorFG(char fg) const
    {
      if (!_color)
        return;

      if (fg == reset)
      {
        SetConsoleTextAttribute(_winScreenHandle, whitegray);
      }
      else
      {
        SetConsoleTextAttribute(_winScreenHandle, fg);
      }
      return;
    }
#endif

    void PrivateConsoleLogHandler::header(const LogLevel verb) const
    {
      //display log level
      textColorAttr(reset);
      if (verb == fatal)
        textColorFG(magenta);
      if (verb == error)
        textColorFG(red);
      if (verb == warning)
        textColorFG(yellow);
      if (verb == info)
        textColorAttr(reset);
      if (verb == verbose)
        textColorAttr(dim);
      if (verb == debug)
        textColorAttr(dim);
      printf("%s ", logLevelToString(verb));
      textColorAttr(reset);
    }

    ConsoleLogHandler::ConsoleLogHandler()
      : _private(new PrivateConsoleLogHandler)
    {
      const char *color   = std::getenv("CLICOLOR");

#ifdef _WIN32
      _private->_winScreenHandle = GetStdHandle(STD_OUTPUT_HANDLE);
#endif
      _private->_color = 1;

      if (color)
        _private->_color = atoi(color) > 0 ? true: false;
      if (!isatty(1))
        _private->_color = 0;
    }

    void cutCat(const char* category, char* res)
    {
      int categorySize = strlen(category);
      if (categorySize < CATSIZEMAX)
      {
        memset(res, ' ', CATSIZEMAX);
        memcpy(res, category, strlen(category));
      }
      else
      {
        memset(res, '.', CATSIZEMAX);
        memcpy(res + 3, category + categorySize - CATSIZEMAX + 3, CATSIZEMAX - 3);
      }
      res[CATSIZEMAX] = '\0';
    }

    void ConsoleLogHandler::log(const LogLevel        verb,
                                const qi::os::timeval date,
                                const char            *category,
                                const char            *msg,
                                const char            *file,
                                const char            *fct,
                                const int             line)
    {
      if (verb > qi::log::verbosity())
      {
        return;
      }
      else
      {
        _private->header(verb);
        char fixedCategory[CATSIZEMAX + 1];
        fixedCategory[CATSIZEMAX] = '\0';
        cutCat(category, fixedCategory);
#ifndef WIN32
        _private->textColorAttr(_private->reset);
        _private->textColorFG(_private->gray);
#endif

        std::stringstream ss;
        ss << date.tv_sec << "." << date.tv_usec;

        int ctx = qi::log::context();
        switch (ctx)
        {
          case 1:
            printf("%s: ", fixedCategory);
            break;
          case 2:
            printf("%s ", ss.str().c_str());
            break;
          case 3:
              printf("%s(%d) ", file, line);
            break;
          case 4:
            printf("%s %s: ", ss.str().c_str(), fixedCategory);
            break;
          case 5:
            if (line == 0)
              printf("%s ", ss.str().c_str());
            else
              printf("%s %s(%d) ", ss.str().c_str(), file, line);
            break;
          case 6:
            if (line == 0)
              printf("%s: ", fixedCategory);
            else
              printf("%s: %s(%d) ", fixedCategory, file, line);
            break;
          case 7:
            if (line == 0)
              printf("%s %s: %s ", ss.str().c_str(), fixedCategory, fct);
            else
              printf("%s %s: %s(%d) %s ", ss.str().c_str(), fixedCategory, file, line, fct);
            break;
          default:
            break;
        }
        printf("%s", msg);
        fflush(stdout);
      }
      fflush(stdout);
    }
  }
}

<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkMatrix4x4.cxx

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

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

=========================================================================*/
#include "vtkMatrix4x4.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"

#include <stdlib.h>
#include <math.h>

vtkCxxRevisionMacro(vtkMatrix4x4, "1.60");
vtkStandardNewMacro(vtkMatrix4x4);

// Useful for viewing a double[16] as a double[4][4]
typedef double (*SqMatPtr)[4];

//----------------------------------------------------------------------------
void vtkMatrix4x4::Zero(double Elements[16])
{
  SqMatPtr elem  = (SqMatPtr)Elements;
  int i,j;
  for (i = 0; i < 4; i++)
    {
    for (j = 0; j < 4; j++)
      {
      elem[i][j] = 0.0;
      }
    }
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::Identity(double Elements[16])
{
  Elements[0] = Elements[5] = Elements[10] = Elements[15] = 1.0;
  Elements[1] = Elements[2] = Elements[3] = Elements[4] =
    Elements[6] = Elements[7] = Elements[8] = Elements[9] =
    Elements[11] = Elements[12] = Elements[13] = Elements[14] = 0.0;
}

//----------------------------------------------------------------------------
template<class T1, class T2, class T3>
void vtkMatrixMultiplyPoint(T1 elem[16], T2 in[4], T3 out[4])
{
  T3 v1 = in[0];
  T3 v2 = in[1];
  T3 v3 = in[2];
  T3 v4 = in[3];

  out[0] = v1*elem[0]  + v2*elem[1]  + v3*elem[2]  + v4*elem[3];
  out[1] = v1*elem[4]  + v2*elem[5]  + v3*elem[6]  + v4*elem[7];
  out[2] = v1*elem[8]  + v2*elem[9]  + v3*elem[10] + v4*elem[11];
  out[3] = v1*elem[12] + v2*elem[13] + v3*elem[14] + v4*elem[15];
}

//----------------------------------------------------------------------------
// Multiply this matrix by a point (in homogeneous coordinates).
// and return the result in result. The in[4] and result[4]
// arrays must both be allocated but they can be the same array.
void vtkMatrix4x4::MultiplyPoint(const double Elements[16],
                                 const float in[4], float result[4])
{
  vtkMatrixMultiplyPoint(Elements,in,result);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::MultiplyPoint(const double Elements[16],
                                 const double in[4], double result[4])
{
  vtkMatrixMultiplyPoint(Elements,in,result);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::PointMultiply(const double Elements[16],
                                 const float in[4], float result[4])
{
  double newElements[16];
  vtkMatrix4x4::Transpose(Elements,newElements);
  vtkMatrix4x4::MultiplyPoint(newElements,in,result);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::PointMultiply(const double Elements[16],
                                 const double in[4], double result[4])
{
  double newElements[16];
  vtkMatrix4x4::Transpose(Elements,newElements);
  vtkMatrix4x4::MultiplyPoint(newElements,in,result);
}

//----------------------------------------------------------------------------
// Multiplies matrices a and b and stores the result in c.
void vtkMatrix4x4::Multiply4x4(const double a[16], const double b[16],
                               double c[16])
{
  SqMatPtr aMat = (SqMatPtr) a;
  SqMatPtr bMat = (SqMatPtr) b;
  SqMatPtr cMat = (SqMatPtr) c;
  int i, k;
  double Accum[4][4];

  for (i = 0; i < 4; i++)
    {
    for (k = 0; k < 4; k++)
      {
      Accum[i][k] = aMat[i][0] * bMat[0][k] +
                    aMat[i][1] * bMat[1][k] +
                    aMat[i][2] * bMat[2][k] +
                    aMat[i][3] * bMat[3][k];
      }
    }

  // Copy to final dest
  for (i = 0; i < 4; i++)
    {
    cMat[i][0] = Accum[i][0];
    cMat[i][1] = Accum[i][1];
    cMat[i][2] = Accum[i][2];
    cMat[i][3] = Accum[i][3];
    }

}

//----------------------------------------------------------------------------
// Matrix Inversion (adapted from Richard Carling in "Graphics Gems,"
// Academic Press, 1990).
void vtkMatrix4x4::Invert(const double inElements[16],
                          double outElements[16])
{
  SqMatPtr outElem = (SqMatPtr)outElements;

  // inverse( original_matrix, inverse_matrix )
  // calculate the inverse of a 4x4 matrix
  //
  //     -1
  //     A  = ___1__ adjoint A
  //         det A
  //

  int i, j;
  double det;

  // calculate the 4x4 determinent
  // if the determinent is zero,
  // then the inverse matrix is not unique.

  det = vtkMatrix4x4::Determinant(inElements);
  if ( det == 0.0 )
    {
    vtkWarningMacro(<< "Singular matrix, no inverse!" );
    return;
    }

  // calculate the adjoint matrix
  vtkMatrix4x4::Adjoint(inElements, outElements );

  // scale the adjoint matrix to get the inverse
  for (i=0; i<4; i++)
    {
    for(j=0; j<4; j++)
      {
      outElem[i][j] = outElem[i][j] / det;
      }
    }
}

//----------------------------------------------------------------------------
double vtkMatrix4x4::Determinant(const double Elements[16])
{
  SqMatPtr elem = (SqMatPtr)Elements;

  double a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4;

  // assign to individual variable names to aid selecting
  //  correct elements

  a1 = elem[0][0]; b1 = elem[0][1];
  c1 = elem[0][2]; d1 = elem[0][3];

  a2 = elem[1][0]; b2 = elem[1][1];
  c2 = elem[1][2]; d2 = elem[1][3];

  a3 = elem[2][0]; b3 = elem[2][1];
  c3 = elem[2][2]; d3 = elem[2][3];

  a4 = elem[3][0]; b4 = elem[3][1];
  c4 = elem[3][2]; d4 = elem[3][3];

  return a1 * vtkMath::Determinant3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4)
       - b1 * vtkMath::Determinant3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4)
       + c1 * vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4)
       - d1 * vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::Adjoint(const double inElements[16], double outElements[16])
{
  SqMatPtr inElem = (SqMatPtr) inElements;
  SqMatPtr outElem = (SqMatPtr) outElements;

  //
  //   adjoint( original_matrix, inverse_matrix )
  //
  //     calculate the adjoint of a 4x4 matrix
  //
  //      Let  a   denote the minor determinant of matrix A obtained by
  //           ij
  //
  //      deleting the ith row and jth column from A.
  //
  //                    i+j
  //     Let  b   = (-1)    a
  //          ij            ji
  //
  //    The matrix B = (b  ) is the adjoint of A
  //                     ij
  //
  double a1, a2, a3, a4, b1, b2, b3, b4;
  double c1, c2, c3, c4, d1, d2, d3, d4;

  // assign to individual variable names to aid
  // selecting correct values

  a1 = inElem[0][0]; b1 = inElem[0][1];
  c1 = inElem[0][2]; d1 = inElem[0][3];

  a2 = inElem[1][0]; b2 = inElem[1][1];
  c2 = inElem[1][2]; d2 = inElem[1][3];

  a3 = inElem[2][0]; b3 = inElem[2][1];
  c3 = inElem[2][2]; d3 = inElem[2][3];

  a4 = inElem[3][0]; b4 = inElem[3][1];
  c4 = inElem[3][2]; d4 = inElem[3][3];

  // row column labeling reversed since we transpose rows & columns

  outElem[0][0]  =
    vtkMath::Determinant3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4);
  outElem[1][0]  =
    - vtkMath::Determinant3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4);
  outElem[2][0]  =
    vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4);
  outElem[3][0]  =
    - vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4);

  outElem[0][1]  =
    - vtkMath::Determinant3x3( b1, b3, b4, c1, c3, c4, d1, d3, d4);
  outElem[1][1]  =
    vtkMath::Determinant3x3( a1, a3, a4, c1, c3, c4, d1, d3, d4);
  outElem[2][1]  =
    - vtkMath::Determinant3x3( a1, a3, a4, b1, b3, b4, d1, d3, d4);
  outElem[3][1]  =
    vtkMath::Determinant3x3( a1, a3, a4, b1, b3, b4, c1, c3, c4);

  outElem[0][2]  =
    vtkMath::Determinant3x3( b1, b2, b4, c1, c2, c4, d1, d2, d4);
  outElem[1][2]  =
    - vtkMath::Determinant3x3( a1, a2, a4, c1, c2, c4, d1, d2, d4);
  outElem[2][2]  =
    vtkMath::Determinant3x3( a1, a2, a4, b1, b2, b4, d1, d2, d4);
  outElem[3][2]  =
    - vtkMath::Determinant3x3( a1, a2, a4, b1, b2, b4, c1, c2, c4);

  outElem[0][3]  =
    - vtkMath::Determinant3x3( b1, b2, b3, c1, c2, c3, d1, d2, d3);
  outElem[1][3]  =
    vtkMath::Determinant3x3( a1, a2, a3, c1, c2, c3, d1, d2, d3);
  outElem[2][3]  =
    - vtkMath::Determinant3x3( a1, a2, a3, b1, b2, b3, d1, d2, d3);
  outElem[3][3]  =
    vtkMath::Determinant3x3( a1, a2, a3, b1, b2, b3, c1, c2, c3);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::DeepCopy(double Elements[16], const double newElements[16])
{
  for (int i = 0; i < 16; i++)
    {
    Elements[i] = newElements[i];
    }
}

//----------------------------------------------------------------------------
// Transpose the matrix and put it into out.
void vtkMatrix4x4::Transpose(const double inElements[16],
                              double outElements[16])
{
  SqMatPtr inElem = (SqMatPtr)inElements;
  SqMatPtr outElem = (SqMatPtr)outElements;
  int i, j;
  double temp;

  for (i=0; i<4; i++)
    {
    for(j=i; j<4; j++)
      {
      temp = inElem[i][j];
      outElem[i][j] = inElem[j][i];
      outElem[j][i] = temp;
      }
    }
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  int i, j;

  os << indent << "Elements:\n";
  for (i = 0; i < 4; i++)
    {
    os << indent << indent;
    for (j = 0; j < 4; j++)
      {
      os << this->Element[i][j] << " ";
      }
    os << "\n";
    }
}
<commit_msg>BUG: Cannot use vtkDebugMacro from non member functions instead use vtkGenericWarningMacro<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkMatrix4x4.cxx

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

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

=========================================================================*/
#include "vtkMatrix4x4.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"

#include <stdlib.h>
#include <math.h>

vtkCxxRevisionMacro(vtkMatrix4x4, "1.61");
vtkStandardNewMacro(vtkMatrix4x4);

// Useful for viewing a double[16] as a double[4][4]
typedef double (*SqMatPtr)[4];

//----------------------------------------------------------------------------
void vtkMatrix4x4::Zero(double Elements[16])
{
  SqMatPtr elem  = (SqMatPtr)Elements;
  int i,j;
  for (i = 0; i < 4; i++)
    {
    for (j = 0; j < 4; j++)
      {
      elem[i][j] = 0.0;
      }
    }
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::Identity(double Elements[16])
{
  Elements[0] = Elements[5] = Elements[10] = Elements[15] = 1.0;
  Elements[1] = Elements[2] = Elements[3] = Elements[4] =
    Elements[6] = Elements[7] = Elements[8] = Elements[9] =
    Elements[11] = Elements[12] = Elements[13] = Elements[14] = 0.0;
}

//----------------------------------------------------------------------------
template<class T1, class T2, class T3>
void vtkMatrixMultiplyPoint(T1 elem[16], T2 in[4], T3 out[4])
{
  T3 v1 = in[0];
  T3 v2 = in[1];
  T3 v3 = in[2];
  T3 v4 = in[3];

  out[0] = v1*elem[0]  + v2*elem[1]  + v3*elem[2]  + v4*elem[3];
  out[1] = v1*elem[4]  + v2*elem[5]  + v3*elem[6]  + v4*elem[7];
  out[2] = v1*elem[8]  + v2*elem[9]  + v3*elem[10] + v4*elem[11];
  out[3] = v1*elem[12] + v2*elem[13] + v3*elem[14] + v4*elem[15];
}

//----------------------------------------------------------------------------
// Multiply this matrix by a point (in homogeneous coordinates).
// and return the result in result. The in[4] and result[4]
// arrays must both be allocated but they can be the same array.
void vtkMatrix4x4::MultiplyPoint(const double Elements[16],
                                 const float in[4], float result[4])
{
  vtkMatrixMultiplyPoint(Elements,in,result);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::MultiplyPoint(const double Elements[16],
                                 const double in[4], double result[4])
{
  vtkMatrixMultiplyPoint(Elements,in,result);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::PointMultiply(const double Elements[16],
                                 const float in[4], float result[4])
{
  double newElements[16];
  vtkMatrix4x4::Transpose(Elements,newElements);
  vtkMatrix4x4::MultiplyPoint(newElements,in,result);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::PointMultiply(const double Elements[16],
                                 const double in[4], double result[4])
{
  double newElements[16];
  vtkMatrix4x4::Transpose(Elements,newElements);
  vtkMatrix4x4::MultiplyPoint(newElements,in,result);
}

//----------------------------------------------------------------------------
// Multiplies matrices a and b and stores the result in c.
void vtkMatrix4x4::Multiply4x4(const double a[16], const double b[16],
                               double c[16])
{
  SqMatPtr aMat = (SqMatPtr) a;
  SqMatPtr bMat = (SqMatPtr) b;
  SqMatPtr cMat = (SqMatPtr) c;
  int i, k;
  double Accum[4][4];

  for (i = 0; i < 4; i++)
    {
    for (k = 0; k < 4; k++)
      {
      Accum[i][k] = aMat[i][0] * bMat[0][k] +
                    aMat[i][1] * bMat[1][k] +
                    aMat[i][2] * bMat[2][k] +
                    aMat[i][3] * bMat[3][k];
      }
    }

  // Copy to final dest
  for (i = 0; i < 4; i++)
    {
    cMat[i][0] = Accum[i][0];
    cMat[i][1] = Accum[i][1];
    cMat[i][2] = Accum[i][2];
    cMat[i][3] = Accum[i][3];
    }

}

//----------------------------------------------------------------------------
// Matrix Inversion (adapted from Richard Carling in "Graphics Gems,"
// Academic Press, 1990).
void vtkMatrix4x4::Invert(const double inElements[16],
                          double outElements[16])
{
  SqMatPtr outElem = (SqMatPtr)outElements;

  // inverse( original_matrix, inverse_matrix )
  // calculate the inverse of a 4x4 matrix
  //
  //     -1
  //     A  = ___1__ adjoint A
  //         det A
  //

  int i, j;
  double det;

  // calculate the 4x4 determinent
  // if the determinent is zero,
  // then the inverse matrix is not unique.

  det = vtkMatrix4x4::Determinant(inElements);
  if ( det == 0.0 )
    {
    vtkGenericWarningMacro(<< "Singular matrix, no inverse!" );
    return;
    }

  // calculate the adjoint matrix
  vtkMatrix4x4::Adjoint(inElements, outElements );

  // scale the adjoint matrix to get the inverse
  for (i=0; i<4; i++)
    {
    for(j=0; j<4; j++)
      {
      outElem[i][j] = outElem[i][j] / det;
      }
    }
}

//----------------------------------------------------------------------------
double vtkMatrix4x4::Determinant(const double Elements[16])
{
  SqMatPtr elem = (SqMatPtr)Elements;

  double a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4;

  // assign to individual variable names to aid selecting
  //  correct elements

  a1 = elem[0][0]; b1 = elem[0][1];
  c1 = elem[0][2]; d1 = elem[0][3];

  a2 = elem[1][0]; b2 = elem[1][1];
  c2 = elem[1][2]; d2 = elem[1][3];

  a3 = elem[2][0]; b3 = elem[2][1];
  c3 = elem[2][2]; d3 = elem[2][3];

  a4 = elem[3][0]; b4 = elem[3][1];
  c4 = elem[3][2]; d4 = elem[3][3];

  return a1 * vtkMath::Determinant3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4)
       - b1 * vtkMath::Determinant3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4)
       + c1 * vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4)
       - d1 * vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::Adjoint(const double inElements[16], double outElements[16])
{
  SqMatPtr inElem = (SqMatPtr) inElements;
  SqMatPtr outElem = (SqMatPtr) outElements;

  //
  //   adjoint( original_matrix, inverse_matrix )
  //
  //     calculate the adjoint of a 4x4 matrix
  //
  //      Let  a   denote the minor determinant of matrix A obtained by
  //           ij
  //
  //      deleting the ith row and jth column from A.
  //
  //                    i+j
  //     Let  b   = (-1)    a
  //          ij            ji
  //
  //    The matrix B = (b  ) is the adjoint of A
  //                     ij
  //
  double a1, a2, a3, a4, b1, b2, b3, b4;
  double c1, c2, c3, c4, d1, d2, d3, d4;

  // assign to individual variable names to aid
  // selecting correct values

  a1 = inElem[0][0]; b1 = inElem[0][1];
  c1 = inElem[0][2]; d1 = inElem[0][3];

  a2 = inElem[1][0]; b2 = inElem[1][1];
  c2 = inElem[1][2]; d2 = inElem[1][3];

  a3 = inElem[2][0]; b3 = inElem[2][1];
  c3 = inElem[2][2]; d3 = inElem[2][3];

  a4 = inElem[3][0]; b4 = inElem[3][1];
  c4 = inElem[3][2]; d4 = inElem[3][3];

  // row column labeling reversed since we transpose rows & columns

  outElem[0][0]  =
    vtkMath::Determinant3x3( b2, b3, b4, c2, c3, c4, d2, d3, d4);
  outElem[1][0]  =
    - vtkMath::Determinant3x3( a2, a3, a4, c2, c3, c4, d2, d3, d4);
  outElem[2][0]  =
    vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, d2, d3, d4);
  outElem[3][0]  =
    - vtkMath::Determinant3x3( a2, a3, a4, b2, b3, b4, c2, c3, c4);

  outElem[0][1]  =
    - vtkMath::Determinant3x3( b1, b3, b4, c1, c3, c4, d1, d3, d4);
  outElem[1][1]  =
    vtkMath::Determinant3x3( a1, a3, a4, c1, c3, c4, d1, d3, d4);
  outElem[2][1]  =
    - vtkMath::Determinant3x3( a1, a3, a4, b1, b3, b4, d1, d3, d4);
  outElem[3][1]  =
    vtkMath::Determinant3x3( a1, a3, a4, b1, b3, b4, c1, c3, c4);

  outElem[0][2]  =
    vtkMath::Determinant3x3( b1, b2, b4, c1, c2, c4, d1, d2, d4);
  outElem[1][2]  =
    - vtkMath::Determinant3x3( a1, a2, a4, c1, c2, c4, d1, d2, d4);
  outElem[2][2]  =
    vtkMath::Determinant3x3( a1, a2, a4, b1, b2, b4, d1, d2, d4);
  outElem[3][2]  =
    - vtkMath::Determinant3x3( a1, a2, a4, b1, b2, b4, c1, c2, c4);

  outElem[0][3]  =
    - vtkMath::Determinant3x3( b1, b2, b3, c1, c2, c3, d1, d2, d3);
  outElem[1][3]  =
    vtkMath::Determinant3x3( a1, a2, a3, c1, c2, c3, d1, d2, d3);
  outElem[2][3]  =
    - vtkMath::Determinant3x3( a1, a2, a3, b1, b2, b3, d1, d2, d3);
  outElem[3][3]  =
    vtkMath::Determinant3x3( a1, a2, a3, b1, b2, b3, c1, c2, c3);
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::DeepCopy(double Elements[16], const double newElements[16])
{
  for (int i = 0; i < 16; i++)
    {
    Elements[i] = newElements[i];
    }
}

//----------------------------------------------------------------------------
// Transpose the matrix and put it into out.
void vtkMatrix4x4::Transpose(const double inElements[16],
                              double outElements[16])
{
  SqMatPtr inElem = (SqMatPtr)inElements;
  SqMatPtr outElem = (SqMatPtr)outElements;
  int i, j;
  double temp;

  for (i=0; i<4; i++)
    {
    for(j=i; j<4; j++)
      {
      temp = inElem[i][j];
      outElem[i][j] = inElem[j][i];
      outElem[j][i] = temp;
      }
    }
}

//----------------------------------------------------------------------------
void vtkMatrix4x4::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  int i, j;

  os << indent << "Elements:\n";
  for (i = 0; i < 4; i++)
    {
    os << indent << indent;
    for (j = 0; j < 4; j++)
      {
      os << this->Element[i][j] << " ";
      }
    os << "\n";
    }
}
<|endoftext|>


<commit_before>#define DEBUG
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>

//for connection to server
#include "../sockets/SocketW.h"
bool ready4data = false;//set to true when streaming starts
bool inited = false;
bool stopparsing = false;
timeval lastrec;

int CONN_fd = 0;
FILE * CONN = 0;
#include "parsechunks.cpp" //chunkstream parsing
#include "handshake.cpp" //handshaking
#include "../util/flv_sock.cpp" //FLV parsing with SocketW
#include "../util/ddv_socket.cpp" //DDVTech Socket wrapper

int main(){

  int server_socket = DDV_Listen(1935);
  int status;
  while (server_socket > 0){
    waitpid((pid_t)-1, &status, WNOHANG);
    CONN_fd = DDV_Accept(server_socket);
    CONN = fdopen(CONN_fd, "r+");
    pid_t myid = fork();
    if (myid == 0){
      break;
    }else{
      printf("Spawned new process %i for incoming client\n", (int)myid);
    }
  }
  if (server_socket <= 0){
    return 0;
  }

  unsigned int ts;
  unsigned int fts = 0;
  unsigned int ftst;
  SWUnixSocket ss;

  //first timestamp set
  firsttime = getNowMS();
  int now = getNowMS();
  int lastcheck = now;

  #ifdef DEBUG
  fprintf(stderr, "Doing handshake...\n");
  #endif
  if (doHandshake()){
    #ifdef DEBUG
    fprintf(stderr, "Handshake succcess!\n");
    #endif
  }else{
    #ifdef DEBUG
    fprintf(stderr, "Handshake fail!\n");
    #endif
    return 0;
  }
  #ifdef DEBUG
  fprintf(stderr, "Starting processing...\n");
  #endif

  int retval;
  int poller = epoll_create(1);
  struct epoll_event ev;
  ev.events = EPOLLIN;
  ev.data.fd = CONN_fd;
  epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);
  struct epoll_event events[1];

  while (!ferror(CONN) && !feof(CONN)){
    //only parse input if available or not yet init'ed
    //rightnow = getNowMS();
    retval = epoll_wait(poller, events, 1, 100);
    now = getNowMS();
    if ((retval > 0) || ((now - lastcheck > 1) && (!ready4data || (snd_cnt - snd_window_at >= snd_window_size)))){
      lastcheck = now;
      parseChunk();
      fflush(CONN);
    }
    if (ready4data){
      if (!inited){
        //we are ready, connect the socket!
        if (!ss.connect(streamname.c_str())){
          #ifdef DEBUG
          fprintf(stderr, "Could not connect to server!\n");
          #endif
          return 0;
        }
        FLV_Readheader(ss);//read the header, we don't want it
        #ifdef DEBUG
        fprintf(stderr, "Header read, starting to send video data...\n");
        #endif
        inited = true;
      }
      //only send data if previous data has been ACK'ed...
      if (snd_cnt - snd_window_at < snd_window_size){
        if (FLV_GetPacket(ss)){//able to read a full packet?
          ts = FLVbuffer[7] * 256*256*256;
          ts += FLVbuffer[4] * 256*256;
          ts += FLVbuffer[5] * 256;
          ts += FLVbuffer[6];
          if (ts != 0){
            if (fts == 0){fts = ts;ftst = getNowMS();}
            ts -= fts;
            FLVbuffer[7] = ts / (256*256*256);
            FLVbuffer[4] = ts / (256*256);
            FLVbuffer[5] = ts / 256;
            FLVbuffer[6] = ts % 256;
            ts += ftst;
          }else{
            ftst = getNowMS();
            FLVbuffer[7] = ftst / (256*256*256);
            FLVbuffer[4] = ftst / (256*256);
            FLVbuffer[5] = ftst / 256;
            FLVbuffer[6] = ftst % 256;
          }
          SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts);
          #ifdef DEBUG
          fprintf(stderr, "Sent a tag.\n");
          #endif
          FLV_Dump();//dump packet and get ready for next
        }
        if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){
          #ifdef DEBUG
          fprintf(stderr, "No more data! :-(  (%s)\n", SWBerr.get_error().c_str());
          #endif
          return 0;//no more input possible! Fail immediately.
        }
      }
    }
    //send ACK if we received a whole window
    if (rec_cnt - rec_window_at > rec_window_size){
      rec_window_at = rec_cnt;
      SendCTL(3, rec_cnt);//send ack (msg 3)
    }
  }
  #ifdef DEBUG
  fprintf(stderr, "User disconnected.\n");
  #endif
  return 0;
}//main
<commit_msg>Nog een poging...<commit_after>#define DEBUG
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/epoll.h>

//for connection to server
#include "../sockets/SocketW.h"
bool ready4data = false;//set to true when streaming starts
bool inited = false;
bool stopparsing = false;
timeval lastrec;

int CONN_fd = 0;
FILE * CONN = 0;
#include "parsechunks.cpp" //chunkstream parsing
#include "handshake.cpp" //handshaking
#include "../util/flv_sock.cpp" //FLV parsing with SocketW
#include "../util/ddv_socket.cpp" //DDVTech Socket wrapper

int main(){

  int server_socket = DDV_Listen(1935);
  int status;
  while (server_socket > 0){
    waitpid((pid_t)-1, &status, WNOHANG);
    CONN_fd = DDV_Accept(server_socket);
    pid_t myid = fork();
    if (myid == 0){
      break;
    }else{
      printf("Spawned new process %i for incoming client\n", (int)myid);
    }
  }
  if (server_socket <= 0){
    return 0;
  }

  CONN = fdopen(CONN_fd, "r+");

  unsigned int ts;
  unsigned int fts = 0;
  unsigned int ftst;
  SWUnixSocket ss;

  //first timestamp set
  firsttime = getNowMS();

  #ifdef DEBUG
  fprintf(stderr, "Doing handshake...\n");
  #endif
  if (doHandshake()){
    #ifdef DEBUG
    fprintf(stderr, "Handshake succcess!\n");
    #endif
  }else{
    #ifdef DEBUG
    fprintf(stderr, "Handshake fail!\n");
    #endif
    return 0;
  }
  #ifdef DEBUG
  fprintf(stderr, "Starting processing...\n");
  #endif

  int retval;
  int poller = epoll_create(1);
  struct epoll_event ev;
  ev.events = EPOLLIN;
  ev.data.fd = CONN_fd;
  epoll_ctl(poller, EPOLL_CTL_ADD, CONN_fd, &ev);
  struct epoll_event events[1];

  while (!ferror(CONN) && !feof(CONN)){
    //only parse input if available or not yet init'ed
    //rightnow = getNowMS();
    retval = epoll_wait(poller, events, 1, 0);
    if ((retval > 0) || (!ready4data || (snd_cnt - snd_window_at >= snd_window_size))){
      parseChunk();
    }
    if (ready4data){
      if (!inited){
        //we are ready, connect the socket!
        if (!ss.connect(streamname.c_str())){
          #ifdef DEBUG
          fprintf(stderr, "Could not connect to server!\n");
          #endif
          return 0;
        }
        FLV_Readheader(ss);//read the header, we don't want it
        #ifdef DEBUG
        fprintf(stderr, "Header read, starting to send video data...\n");
        #endif
        inited = true;
      }
      //only send data if previous data has been ACK'ed...
      if (snd_cnt - snd_window_at < snd_window_size){
        if (FLV_GetPacket(ss)){//able to read a full packet?
          ts = FLVbuffer[7] * 256*256*256;
          ts += FLVbuffer[4] * 256*256;
          ts += FLVbuffer[5] * 256;
          ts += FLVbuffer[6];
          if (ts != 0){
            if (fts == 0){fts = ts;ftst = getNowMS();}
            ts -= fts;
            FLVbuffer[7] = ts / (256*256*256);
            FLVbuffer[4] = ts / (256*256);
            FLVbuffer[5] = ts / 256;
            FLVbuffer[6] = ts % 256;
            ts += ftst;
          }else{
            ftst = getNowMS();
            FLVbuffer[7] = ftst / (256*256*256);
            FLVbuffer[4] = ftst / (256*256);
            FLVbuffer[5] = ftst / 256;
            FLVbuffer[6] = ftst % 256;
          }
          SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts);
          #ifdef DEBUG
          fprintf(stderr, "Sent a tag.\n");
          #endif
          FLV_Dump();//dump packet and get ready for next
        }
        if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){
          #ifdef DEBUG
          fprintf(stderr, "No more data! :-(  (%s)\n", SWBerr.get_error().c_str());
          #endif
          return 0;//no more input possible! Fail immediately.
        }
      }
    }
    //send ACK if we received a whole window
    if (rec_cnt - rec_window_at > rec_window_size){
      rec_window_at = rec_cnt;
      SendCTL(3, rec_cnt);//send ack (msg 3)
    }
  }
  #ifdef DEBUG
  fprintf(stderr, "User disconnected.\n");
  #endif
  return 0;
}//main
<|endoftext|>