<commit_before>/*
 *  caosVM.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Tue May 25 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#include "caosVM.h"
#include "openc2e.h"
#include "World.h"
#include "bytecode.h"
#include "caosScript.h"
#include <iostream>

#include <boost/format.hpp>

using std::cout;
using std::cerr;
using std::endl;

void dumpStack(caosVM *vm) {
	std::cerr << "\tvalueStack: ";
	int i, c = 0;
	for (i = vm->valueStack.size() - 1; i >= 0 && c++ < 5; i--)
		std::cerr << vm->valueStack[i].dump() << " | ";
	if (i >= 0)
		std::cerr << "...";
	else
		std::cerr << "END";
	std::cerr << std::endl;
}

caosVM::caosVM(const AgentRef &o)
	: vm(this)
{
	owner = o;
	currentscript.reset();
	cip = nip = 0;
	blocking = NULL;
	inputstream = 0; outputstream = 0;
	resetCore();
	trace = false;
}

caosVM::~caosVM() {
	resetCore(); // delete blocking, close streams
}

bool caosVM::isBlocking() {
	if (!blocking) return false;
	bool bl = (*blocking)();
	if (!bl) {
		delete blocking;
		blocking = NULL;
	}
	return bl;
}

void caosVM::startBlocking(blockCond *whileWhat) {
	if (!owner)
		// TODO: should this just fail to block?
		throw creaturesException("trying to block in a non-blockable script");
	inst = false;
	if (blocking)
		throw creaturesException("trying to block with a block condition in-place");
	blocking = whileWhat;
}

inline void caosVM::safeJMP(int dest) {
//	std::cerr << "jmp from " << cip << " to " << dest << "(old nip = " << nip << ") in script of length " << currentscript->scriptLength() << std::endl;
	if (dest < 0) {
		std::cerr << currentscript->dump();
		throw caosException(boost::str(boost::format("Internal error: Unrelocated jump at %08x") % cip));
	}
	if (dest >= currentscript->scriptLength()) {
		std::cerr << currentscript->dump();
		throw creaturesException(boost::str(boost::format("Internal error: Jump out of bounds at %08x") % cip));
	}
	nip = dest;
}

inline void caosVM::invoke_cmd(script *s, bool is_saver, int opidx) {
	const cmdinfo *ci = s->dialect->getcmd(opidx);
	// We subtract two here to account for a) the missing return, and b)
	// consuming the new value.
	int stackdelta = ci->stackdelta - (is_saver ? 2 : 0);
	unsigned int stackstart = valueStack.size();
	assert(result.isNull());
#ifndef VCPP_BROKENNESS
	if (is_saver)
		(this->*(ci->savehandler))();
	else
		(this->*(ci->handler))();
#else
	if (is_saver)
		dispatchCAOS(this, ci->savehandler_idx);
	else
		dispatchCAOS(this, ci->handler_idx);
#endif
	if (!is_saver && !result.isNull()) {
		valueStack.push_back(result);
		result.reset();
	} else {
		assert(result.isNull());
	}
	if (stackdelta < INT_MAX - 1) {
		if ((int)stackstart + stackdelta != (int)valueStack.size()) {
			dumpStack(this);
			throw caosException("Stack imbalance detected");
		}
	}
}

inline void caosVM::runOpCore(script *s, caosOp op) {
	switch (op.opcode) {
		case CAOS_NOP: break;
		case CAOS_DIE:
			{
				int idx = op.argument;
				std::string err = "aborted";
				caosVar constVal = s->getConstant(idx);
				if (constVal.hasString())
					err = constVal.getString();
				throw creaturesException(err);
			}
		case CAOS_STOP:
			{
				stop();
				break;
			}
		case CAOS_SAVE_CMD:
			{
				invoke_cmd(s, true, op.argument);
				break;
			}
		case CAOS_CMD:
			{
				invoke_cmd(s, false, op.argument);
				break;
			}
		case CAOS_YIELD:
			{
#ifndef NDEBUG
				// This condition can arise as a result of bad save data,
				// so an assert is not appropriate... or is it?
				//
				// In any case, it is mostly harmless but should never occur,
				// as it indicates a bug in the CAOS compiler.
				caos_assert(auxStack.size() == 0);
#endif
				if (!inst)
					timeslice -= op.argument;
				break;
			}
		case CAOS_COND:
			{
				VM_PARAM_VALUE(v2);
				VM_PARAM_VALUE(v1);
				VM_PARAM_INTEGER(condaccum);
				assert(!v1.isEmpty());
				assert(!v2.isEmpty());
				int condition = op.argument;
				if (condition & CAND) condition -= CAND;
				if (condition & COR) condition -= COR;
				int result = 0;
				if (condition == CEQ)
					result = (v1 == v2);
				if (condition == CNE)
					result = !(v1 == v2);

				if (condition == CLT)
					result = (v1 < v2);
				if (condition == CGE)
					result = !(v1 < v2);
				if (condition == CGT)
					result = (v1 > v2);
				if (condition == CLE)
					result = !(v1 > v2);

				if (condition == CBT) {
					caos_assert(v1.hasInt() && v2.hasInt());
					result = (v2.getInt() == v1.getInt() & v2.getInt());
				}
				if (condition == CBF) {
					caos_assert(v1.hasInt() && v2.hasInt());
					result = (0           == v1.getInt() & v2.getInt());
				}
				if (op.argument & CAND)
					result = (condaccum && result);
				else
					result = (condaccum || result);
				valueStack.push_back(caosVar(result));
				break;
			}
		case CAOS_CONST:
			{
				valueStack.push_back(vmStackItem(s->getConstant(op.argument)));
				break;
			}
		case CAOS_CONSTINT:
			{
				valueStack.push_back(vmStackItem(caosVar(op.argument)));
				break;
			}
		case CAOS_BYTESTR:
			{
				valueStack.push_back(vmStackItem(s->getBytestr(op.argument)));
				break;
			}
		case CAOS_PUSH_AUX:
			{
				caos_assert(op.argument >= 0);
				caos_assert(op.argument < (int)valueStack.size());
				auxStack.push_back(valueStack[valueStack.size() - op.argument - 1]);
				break;
			}
		case CAOS_RESTORE_AUX:
			{
				caos_assert(op.argument >= 0);
				caos_assert(op.argument <= (int)auxStack.size());
				for (int i = 0; i < op.argument; i++) {
					valueStack.push_back(auxStack.back());
					auxStack.pop_back();
				}
				break;
			}
		case CAOS_STACK_ROT:
			{
				caos_assert(op.argument >= 0);
				caos_assert(op.argument < (int)valueStack.size());
				for (int i = 0; i < op.argument; i++) {
					int top = valueStack.size() - 1;
					std::swap(valueStack[top - i], valueStack[top - i - 1]);
				}
				break;
			}
		case CAOS_CJMP:
			{
				VM_PARAM_VALUE(v);
				if (v.getInt() != 0)
					safeJMP(op.argument);
				break;
			}
		case CAOS_JMP:
			{
				safeJMP(op.argument);
				break;
			}
		case CAOS_DECJNZ:
			{
				VM_PARAM_INTEGER(counter);
				counter--;
				if (counter) {
					safeJMP(op.argument);
					valueStack.push_back(caosVar(counter));
				}
				break;
			}
		case CAOS_GSUB:
			{
				callStack.push_back(callStackItem());
				callStack.back().nip = nip;
				callStack.back().valueStack.swap(valueStack);
				safeJMP(op.argument);
				break;
			}
		case CAOS_ENUMPOP:
			{
				VM_PARAM_VALUE(v);
				if (v.isEmpty())
					break;
				if (!v.hasAgent()) {
					dumpStack(this);
					throw caosException(std::string("Stack item type mismatch: ") + v.dump());
				}
				targ = v.getAgentRef();
				safeJMP(op.argument);
				break;
			}
		default:
			throw creaturesException(boost::str(boost::format("Illegal opcode %d") % (int)op.opcode));
	}
}

inline void caosVM::runOp() {
	cip = nip;
	nip++;

	runops++;
	if (runops > 1000000) throw creaturesException("script exceeded 1m ops");

	shared_ptr<script> scr = currentscript;
	caosOp op = currentscript->getOp(cip);

	try {
		if (trace) {
			std::cerr
				<< boost::str(boost::format("optrace(%s): INST=%d TS=%d %p @%08d top=%s depth=%d ") % scr->filename.c_str() % (int)inst % (int)timeslice % (void *)this % cip % (valueStack.empty() ? std::string("(empty)") : valueStack.back().dump()) % valueStack.size())
				<< dumpOp(currentscript->dialect, op) << std::endl;
			if (trace >= 2) {
				dumpStack(this);
			}
		}
		runOpCore(scr.get(), op);
	} catch (caosException &e) {
		e.trace(currentscript, op.traceindex);
		stop();
		throw;
	} catch (creaturesException &e) {
		stop();
		throw;
	}

}

void caosVM::stop() {
	lock = false;
	currentscript.reset();
}

void caosVM::runEntirely(shared_ptr<script> s) {
	// caller is responsible for resetting/setting *all* state!
	cip = nip = runops = 0;
	currentscript = s;

	while (true) {
		runOp();
		if (!currentscript) break;
		if (blocking) {
			delete blocking;
			blocking = NULL;
			throw creaturesException("blocking in an installation script");
		}
	}
}

bool caosVM::fireScript(shared_ptr<script> s, bool nointerrupt, Agent *frm) {
	assert(owner);
	assert(s);
	if (lock) return false; // can't interrupt scripts which called LOCK
	if (currentscript && nointerrupt) return false; // don't interrupt scripts with a timer script

	resetScriptState();
	currentscript = s;
	targ = owner;
	from.setAgent(frm);
	timeslice = 1;
	return true;
}

void caosVM::resetScriptState() {
	stop();
	resetCore();
}

void caosVM::resetCore() {
	if (blocking)
		delete blocking;
	blocking = NULL;
	result.reset();

	valueStack.clear();
	auxStack.clear();
	callStack.clear();

	inst = lock = 0;
	timeslice = 0;

	c_FILE_ICLO(); // make sure input stream is freed
	inputstream = 0; // .. possibly not strictly necessary, when all is bugfree
	c_FILE_OCLO(); // make sure output stream is freed
	outputstream = 0;

	_it_ = NULL;
	from.setAgent(NULL);
	setTarg(owner);
	part = 0;

	_p_[0].reset(); _p_[0].setInt(0); _p_[1].reset(); _p_[1].setInt(0);
	for (unsigned int i = 0; i < 100; i++) { var[i].reset(); var[i].setInt(0); }

	camera.reset();

	trace = 0;
	cip = nip = runops = 0;
}

void caosVM::tick() {
	stop_loop = false;
	runops = 0;
	while (currentscript && !stop_loop && (timeslice > 0 || inst)) {
		if (isBlocking()) return;
		runOp();
	}
}

void caosVM::dummy_cmd() {
	// no-op
}
/* vim: set noet: */
<commit_msg>make the VM stack imbalance error a bit more informative<commit_after>/*
 *  caosVM.cpp
 *  openc2e
 *
 *  Created by Alyssa Milburn on Tue May 25 2004.
 *  Copyright (c) 2004 Alyssa Milburn. All rights reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 */

#include "caosVM.h"
#include "openc2e.h"
#include "World.h"
#include "bytecode.h"
#include "caosScript.h"
#include <iostream>

#include <boost/format.hpp>

using std::cout;
using std::cerr;
using std::endl;

void dumpStack(caosVM *vm) {
	std::cerr << "\tvalueStack: ";
	int i, c = 0;
	for (i = vm->valueStack.size() - 1; i >= 0 && c++ < 5; i--)
		std::cerr << vm->valueStack[i].dump() << " | ";
	if (i >= 0)
		std::cerr << "...";
	else
		std::cerr << "END";
	std::cerr << std::endl;
}

caosVM::caosVM(const AgentRef &o)
	: vm(this)
{
	owner = o;
	currentscript.reset();
	cip = nip = 0;
	blocking = NULL;
	inputstream = 0; outputstream = 0;
	resetCore();
	trace = false;
}

caosVM::~caosVM() {
	resetCore(); // delete blocking, close streams
}

bool caosVM::isBlocking() {
	if (!blocking) return false;
	bool bl = (*blocking)();
	if (!bl) {
		delete blocking;
		blocking = NULL;
	}
	return bl;
}

void caosVM::startBlocking(blockCond *whileWhat) {
	if (!owner)
		// TODO: should this just fail to block?
		throw creaturesException("trying to block in a non-blockable script");
	inst = false;
	if (blocking)
		throw creaturesException("trying to block with a block condition in-place");
	blocking = whileWhat;
}

inline void caosVM::safeJMP(int dest) {
//	std::cerr << "jmp from " << cip << " to " << dest << "(old nip = " << nip << ") in script of length " << currentscript->scriptLength() << std::endl;
	if (dest < 0) {
		std::cerr << currentscript->dump();
		throw caosException(boost::str(boost::format("Internal error: Unrelocated jump at %08x") % cip));
	}
	if (dest >= currentscript->scriptLength()) {
		std::cerr << currentscript->dump();
		throw creaturesException(boost::str(boost::format("Internal error: Jump out of bounds at %08x") % cip));
	}
	nip = dest;
}

inline void caosVM::invoke_cmd(script *s, bool is_saver, int opidx) {
	const cmdinfo *ci = s->dialect->getcmd(opidx);
	// We subtract two here to account for a) the missing return, and b)
	// consuming the new value.
	int stackdelta = ci->stackdelta - (is_saver ? 2 : 0);
	unsigned int stackstart = valueStack.size();
	assert(result.isNull());
#ifndef VCPP_BROKENNESS
	if (is_saver)
		(this->*(ci->savehandler))();
	else
		(this->*(ci->handler))();
#else
	if (is_saver)
		dispatchCAOS(this, ci->savehandler_idx);
	else
		dispatchCAOS(this, ci->handler_idx);
#endif
	if (!is_saver && !result.isNull()) {
		valueStack.push_back(result);
		result.reset();
	} else {
		assert(result.isNull());
	}
	if (stackdelta < INT_MAX - 1) {
		if ((int)stackstart + stackdelta != (int)valueStack.size()) {
			dumpStack(this);
			throw caosException(boost::str(boost::format("Internal error: Stack imbalance detected: expected to be %d after start of %d, but stack size is now %d") % stackdelta % (int)stackstart % (int)valueStack.size()));
		}
	}
}

inline void caosVM::runOpCore(script *s, caosOp op) {
	switch (op.opcode) {
		case CAOS_NOP: break;
		case CAOS_DIE:
			{
				int idx = op.argument;
				std::string err = "aborted";
				caosVar constVal = s->getConstant(idx);
				if (constVal.hasString())
					err = constVal.getString();
				throw creaturesException(err);
			}
		case CAOS_STOP:
			{
				stop();
				break;
			}
		case CAOS_SAVE_CMD:
			{
				invoke_cmd(s, true, op.argument);
				break;
			}
		case CAOS_CMD:
			{
				invoke_cmd(s, false, op.argument);
				break;
			}
		case CAOS_YIELD:
			{
#ifndef NDEBUG
				// This condition can arise as a result of bad save data,
				// so an assert is not appropriate... or is it?
				//
				// In any case, it is mostly harmless but should never occur,
				// as it indicates a bug in the CAOS compiler.
				caos_assert(auxStack.size() == 0);
#endif
				if (!inst)
					timeslice -= op.argument;
				break;
			}
		case CAOS_COND:
			{
				VM_PARAM_VALUE(v2);
				VM_PARAM_VALUE(v1);
				VM_PARAM_INTEGER(condaccum);
				assert(!v1.isEmpty());
				assert(!v2.isEmpty());
				int condition = op.argument;
				if (condition & CAND) condition -= CAND;
				if (condition & COR) condition -= COR;
				int result = 0;
				if (condition == CEQ)
					result = (v1 == v2);
				if (condition == CNE)
					result = !(v1 == v2);

				if (condition == CLT)
					result = (v1 < v2);
				if (condition == CGE)
					result = !(v1 < v2);
				if (condition == CGT)
					result = (v1 > v2);
				if (condition == CLE)
					result = !(v1 > v2);

				if (condition == CBT) {
					caos_assert(v1.hasInt() && v2.hasInt());
					result = (v2.getInt() == v1.getInt() & v2.getInt());
				}
				if (condition == CBF) {
					caos_assert(v1.hasInt() && v2.hasInt());
					result = (0           == v1.getInt() & v2.getInt());
				}
				if (op.argument & CAND)
					result = (condaccum && result);
				else
					result = (condaccum || result);
				valueStack.push_back(caosVar(result));
				break;
			}
		case CAOS_CONST:
			{
				valueStack.push_back(vmStackItem(s->getConstant(op.argument)));
				break;
			}
		case CAOS_CONSTINT:
			{
				valueStack.push_back(vmStackItem(caosVar(op.argument)));
				break;
			}
		case CAOS_BYTESTR:
			{
				valueStack.push_back(vmStackItem(s->getBytestr(op.argument)));
				break;
			}
		case CAOS_PUSH_AUX:
			{
				caos_assert(op.argument >= 0);
				caos_assert(op.argument < (int)valueStack.size());
				auxStack.push_back(valueStack[valueStack.size() - op.argument - 1]);
				break;
			}
		case CAOS_RESTORE_AUX:
			{
				caos_assert(op.argument >= 0);
				caos_assert(op.argument <= (int)auxStack.size());
				for (int i = 0; i < op.argument; i++) {
					valueStack.push_back(auxStack.back());
					auxStack.pop_back();
				}
				break;
			}
		case CAOS_STACK_ROT:
			{
				caos_assert(op.argument >= 0);
				caos_assert(op.argument < (int)valueStack.size());
				for (int i = 0; i < op.argument; i++) {
					int top = valueStack.size() - 1;
					std::swap(valueStack[top - i], valueStack[top - i - 1]);
				}
				break;
			}
		case CAOS_CJMP:
			{
				VM_PARAM_VALUE(v);
				if (v.getInt() != 0)
					safeJMP(op.argument);
				break;
			}
		case CAOS_JMP:
			{
				safeJMP(op.argument);
				break;
			}
		case CAOS_DECJNZ:
			{
				VM_PARAM_INTEGER(counter);
				counter--;
				if (counter) {
					safeJMP(op.argument);
					valueStack.push_back(caosVar(counter));
				}
				break;
			}
		case CAOS_GSUB:
			{
				callStack.push_back(callStackItem());
				callStack.back().nip = nip;
				callStack.back().valueStack.swap(valueStack);
				safeJMP(op.argument);
				break;
			}
		case CAOS_ENUMPOP:
			{
				VM_PARAM_VALUE(v);
				if (v.isEmpty())
					break;
				if (!v.hasAgent()) {
					dumpStack(this);
					throw caosException(std::string("Stack item type mismatch: ") + v.dump());
				}
				targ = v.getAgentRef();
				safeJMP(op.argument);
				break;
			}
		default:
			throw creaturesException(boost::str(boost::format("Illegal opcode %d") % (int)op.opcode));
	}
}

inline void caosVM::runOp() {
	cip = nip;
	nip++;

	runops++;
	if (runops > 1000000) throw creaturesException("script exceeded 1m ops");

	shared_ptr<script> scr = currentscript;
	caosOp op = currentscript->getOp(cip);

	try {
		if (trace) {
			std::cerr
				<< boost::str(boost::format("optrace(%s): INST=%d TS=%d %p @%08d top=%s depth=%d ") % scr->filename.c_str() % (int)inst % (int)timeslice % (void *)this % cip % (valueStack.empty() ? std::string("(empty)") : valueStack.back().dump()) % valueStack.size())
				<< dumpOp(currentscript->dialect, op) << std::endl;
			if (trace >= 2) {
				dumpStack(this);
			}
		}
		runOpCore(scr.get(), op);
	} catch (caosException &e) {
		e.trace(currentscript, op.traceindex);
		stop();
		throw;
	} catch (creaturesException &e) {
		stop();
		throw;
	}

}

void caosVM::stop() {
	lock = false;
	currentscript.reset();
}

void caosVM::runEntirely(shared_ptr<script> s) {
	// caller is responsible for resetting/setting *all* state!
	cip = nip = runops = 0;
	currentscript = s;

	while (true) {
		runOp();
		if (!currentscript) break;
		if (blocking) {
			delete blocking;
			blocking = NULL;
			throw creaturesException("blocking in an installation script");
		}
	}
}

bool caosVM::fireScript(shared_ptr<script> s, bool nointerrupt, Agent *frm) {
	assert(owner);
	assert(s);
	if (lock) return false; // can't interrupt scripts which called LOCK
	if (currentscript && nointerrupt) return false; // don't interrupt scripts with a timer script

	resetScriptState();
	currentscript = s;
	targ = owner;
	from.setAgent(frm);
	timeslice = 1;
	return true;
}

void caosVM::resetScriptState() {
	stop();
	resetCore();
}

void caosVM::resetCore() {
	if (blocking)
		delete blocking;
	blocking = NULL;
	result.reset();

	valueStack.clear();
	auxStack.clear();
	callStack.clear();

	inst = lock = 0;
	timeslice = 0;

	c_FILE_ICLO(); // make sure input stream is freed
	inputstream = 0; // .. possibly not strictly necessary, when all is bugfree
	c_FILE_OCLO(); // make sure output stream is freed
	outputstream = 0;

	_it_ = NULL;
	from.setAgent(NULL);
	setTarg(owner);
	part = 0;

	_p_[0].reset(); _p_[0].setInt(0); _p_[1].reset(); _p_[1].setInt(0);
	for (unsigned int i = 0; i < 100; i++) { var[i].reset(); var[i].setInt(0); }

	camera.reset();

	trace = 0;
	cip = nip = runops = 0;
}

void caosVM::tick() {
	stop_loop = false;
	runops = 0;
	while (currentscript && !stop_loop && (timeslice > 0 || inst)) {
		if (isBlocking()) return;
		runOp();
	}
}

void caosVM::dummy_cmd() {
	// no-op
}
/* vim: set noet: */
<|endoftext|>


<commit_before>// Test for "sancov.py missing ...".

// First case: coverage from executable. main() is called on every code path.
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %t -DFOOBAR -DMAIN
// RUN: rm -rf %T/coverage-missing
// RUN: mkdir -p %T/coverage-missing
// RUN: cd %T/coverage-missing
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t
// RUN: %sancov print *.sancov > main.txt
// RUN: rm *.sancov
// RUN: count 1 < main.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t x
// RUN: %sancov print *.sancov > foo.txt
// RUN: rm *.sancov
// RUN: count 3 < foo.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t x x
// RUN: %sancov print *.sancov > bar.txt
// RUN: rm *.sancov
// RUN: count 4 < bar.txt
// RUN: %sancov missing %t < foo.txt > foo-missing.txt
// RUN: sort main.txt foo-missing.txt -o foo-missing-with-main.txt
// The "missing from foo" set may contain a few bogus PCs from the sanitizer
// runtime, but it must include the entire "bar" code path as a subset. Sorted
// lists can be tested for set inclusion with diff + grep.
// RUN: ( diff bar.txt foo-missing-with-main.txt || true ) | not grep "^<"

// Second case: coverage from DSO.
// cd %T
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %dynamiclib -DFOOBAR -shared -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=func %s %dynamiclib -o %t -DMAIN
// RUN: export LIBNAME=`basename %dynamiclib`
// RUN: rm -rf %T/coverage-missing
// RUN: mkdir -p %T/coverage-missing
// RUN: cd %T/coverage-missing
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t x
// RUN: %sancov print $LIBNAME.*.sancov > foo.txt
// RUN: rm *.sancov
// RUN: count 2 < foo.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t x x
// RUN: %sancov print $LIBNAME.*.sancov > bar.txt
// RUN: rm *.sancov
// RUN: count 3 < bar.txt
// RUN: %sancov missing %dynamiclib < foo.txt > foo-missing.txt
// RUN: ( diff bar.txt foo-missing.txt || true ) | not grep "^<"

// REQUIRES: x86-target-arch
// XFAIL: android

#include <stdio.h>

void foo1();
void foo2();
void bar1();
void bar2();
void bar3();

#if defined(FOOBAR)
void foo1() { fprintf(stderr, "foo1\n"); }
void foo2() { fprintf(stderr, "foo2\n"); }

void bar1() { fprintf(stderr, "bar1\n"); }
void bar2() { fprintf(stderr, "bar2\n"); }
void bar3() { fprintf(stderr, "bar3\n"); }
#endif

#if defined(MAIN)
int main(int argc, char **argv) {
  switch (argc) {
    case 1:
      break;
    case 2:
      foo1();
      foo2();
      break;
    case 3:
      bar1();
      bar2();
      bar3();
      break;
  }
}
#endif
<commit_msg>Avoid sub shell.<commit_after>// Test for "sancov.py missing ...".

// First case: coverage from executable. main() is called on every code path.
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %t -DFOOBAR -DMAIN
// RUN: rm -rf %T/coverage-missing
// RUN: mkdir -p %T/coverage-missing
// RUN: cd %T/coverage-missing
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t
// RUN: %sancov print *.sancov > main.txt
// RUN: rm *.sancov
// RUN: count 1 < main.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t x
// RUN: %sancov print *.sancov > foo.txt
// RUN: rm *.sancov
// RUN: count 3 < foo.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t x x
// RUN: %sancov print *.sancov > bar.txt
// RUN: rm *.sancov
// RUN: count 4 < bar.txt
// RUN: %sancov missing %t < foo.txt > foo-missing.txt
// RUN: sort main.txt foo-missing.txt -o foo-missing-with-main.txt
// The "missing from foo" set may contain a few bogus PCs from the sanitizer
// runtime, but it must include the entire "bar" code path as a subset. Sorted
// lists can be tested for set inclusion with diff + grep.
// RUN: diff bar.txt foo-missing-with-main.txt > %t.log || true
// RUN: not grep "^<" %t.log

// Second case: coverage from DSO.
// cd %T
// RUN: %clangxx_asan -fsanitize-coverage=func %s -o %dynamiclib -DFOOBAR -shared -fPIC
// RUN: %clangxx_asan -fsanitize-coverage=func %s %dynamiclib -o %t -DMAIN
// RUN: export LIBNAME=`basename %dynamiclib`
// RUN: rm -rf %T/coverage-missing
// RUN: mkdir -p %T/coverage-missing
// RUN: cd %T/coverage-missing
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t x
// RUN: %sancov print $LIBNAME.*.sancov > foo.txt
// RUN: rm *.sancov
// RUN: count 2 < foo.txt
// RUN: %env_asan_opts=coverage=1:coverage_dir=%T/coverage-missing %run %t x x
// RUN: %sancov print $LIBNAME.*.sancov > bar.txt
// RUN: rm *.sancov
// RUN: count 3 < bar.txt
// RUN: %sancov missing %dynamiclib < foo.txt > foo-missing.txt
// RUN: diff bar.txt foo-missing.txt > %t.log || true
// RUN: not grep "^<" %t.log

// REQUIRES: x86-target-arch
// XFAIL: android

#include <stdio.h>

void foo1();
void foo2();
void bar1();
void bar2();
void bar3();

#if defined(FOOBAR)
void foo1() { fprintf(stderr, "foo1\n"); }
void foo2() { fprintf(stderr, "foo2\n"); }

void bar1() { fprintf(stderr, "bar1\n"); }
void bar2() { fprintf(stderr, "bar2\n"); }
void bar3() { fprintf(stderr, "bar3\n"); }
#endif

#if defined(MAIN)
int main(int argc, char **argv) {
  switch (argc) {
    case 1:
      break;
    case 2:
      foo1();
      foo2();
      break;
    case 3:
      bar1();
      bar2();
      bar3();
      break;
  }
}
#endif
<|endoftext|>


<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/codegen/passes/weight_layout/weight_layout.h"

#include "core/codegen/common/common.h"
#include "core/codegen/common/utils.h"
#include "core/codegen/mti/mti_tvm_utils.h"
#include "core/codegen/passes/utils/ort_tvm_utils.h"

namespace onnxruntime {
namespace tvm_codegen {

static tvm::Tensor CreateTVMPlaceholder(
    const std::string& name,
    HalideIR::Type type,
    int dim) {
  tvm::Array<tvm::Expr> shape;
  if (dim > 0) {
    for (int i = 0; i < dim; ++i) {
      shape.push_back(tvm::Var(name + "_v" + std::to_string(i)));
    }
  } else {
    shape.push_back(1);
  }
  return tvm::placeholder(shape, type, name + "_placeholder");
}

const std::string WeightLayout::GetKey(
    const std::string& name,
    ONNX_NAMESPACE::TensorProto_DataType proto_type,
    int input_dim,
    float pad_zero) {
  std::string key = name;
  key += "_type_" + std::to_string(static_cast<int>(proto_type));
  key += "_dim_" + input_dim;
  key += "_pad_zero_" + std::to_string(pad_zero);
  key = NormalizeCppName(key);
  return key;
}

WeightLayout::WeightLayout(
    const std::string& name,
    ONNX_NAMESPACE::TensorProto_DataType proto_type,
    int input_dim,
    float pad_zero)
    : name_(GetKey(name, proto_type, input_dim, pad_zero)),
      proto_type_(proto_type),
      input_dim_(input_dim),
      pad_zero_(pad_zero) {}

const std::string& WeightLayout::Name() const {
  return name_;
}

void WeightLayout::CreateLayoutMarshallingTVMOp(tvm::Array<tvm::Tensor>& inputs,
                                                tvm::Array<tvm::Tensor>& outputs) const {
  HalideIR::Type halide_type = ToTvmType(proto_type_);

  tvm::Tensor placeholder = CreateTVMPlaceholder(name_, halide_type, input_dim_);
  inputs.push_back(placeholder);

  tvm::Array<tvm::Expr> new_shape = ToActualShape(placeholder);
  CoordTransFunc new_coord_to_old_coord_func = ToNominal(placeholder);
  tvm::Expr pad_zero_expr = tvm::make_const(halide_type, pad_zero_);

  tvm::Tensor output = tvm::compute(
      new_shape,
      [&](const tvm::Array<tvm::Var>& output_coord) {
        tvm::Array<tvm::Expr> output_coord1;
        for (const auto& coord : output_coord)
          output_coord1.push_back(coord);
        auto input_coord = new_coord_to_old_coord_func(output_coord1);
        ORT_ENFORCE(input_coord.size() == placeholder->shape.size());

        if (input_coord.size() > 0) {
          auto in_range = (input_coord[0] >= 0) && (input_coord[0] < placeholder->shape[0]);
          for (size_t dim = 1; dim < input_coord.size(); ++dim)
            in_range = in_range && (input_coord[dim] >= 0) && (input_coord[dim] < placeholder->shape[dim]);

          return tvm::ir::Select::make(in_range, placeholder(input_coord), pad_zero_expr);
        } else {
          // scalar
          return placeholder(input_coord);
        }
      });

  outputs.push_back(output);
}

}  // namespace tvm_codegen
}  // namespace onnxruntime
<commit_msg>Nuphar: Fix a bug in weight layout where read may go out of bound (#2129)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

#include "core/codegen/passes/weight_layout/weight_layout.h"

#include "core/codegen/common/common.h"
#include "core/codegen/common/utils.h"
#include "core/codegen/mti/mti_tvm_utils.h"
#include "core/codegen/passes/utils/ort_tvm_utils.h"

namespace onnxruntime {
namespace tvm_codegen {

static tvm::Tensor CreateTVMPlaceholder(
    const std::string& name,
    HalideIR::Type type,
    int dim) {
  tvm::Array<tvm::Expr> shape;
  if (dim > 0) {
    for (int i = 0; i < dim; ++i) {
      shape.push_back(tvm::Var(name + "_v" + std::to_string(i)));
    }
  } else {
    shape.push_back(1);
  }
  return tvm::placeholder(shape, type, name + "_placeholder");
}

const std::string WeightLayout::GetKey(
    const std::string& name,
    ONNX_NAMESPACE::TensorProto_DataType proto_type,
    int input_dim,
    float pad_zero) {
  std::string key = name;
  key += "_type_" + std::to_string(static_cast<int>(proto_type));
  key += "_dim_" + input_dim;
  key += "_pad_zero_" + std::to_string(pad_zero);
  key = NormalizeCppName(key);
  return key;
}

WeightLayout::WeightLayout(
    const std::string& name,
    ONNX_NAMESPACE::TensorProto_DataType proto_type,
    int input_dim,
    float pad_zero)
    : name_(GetKey(name, proto_type, input_dim, pad_zero)),
      proto_type_(proto_type),
      input_dim_(input_dim),
      pad_zero_(pad_zero) {}

const std::string& WeightLayout::Name() const {
  return name_;
}

void WeightLayout::CreateLayoutMarshallingTVMOp(tvm::Array<tvm::Tensor>& inputs,
                                                tvm::Array<tvm::Tensor>& outputs) const {
  HalideIR::Type halide_type = ToTvmType(proto_type_);

  tvm::Tensor placeholder = CreateTVMPlaceholder(name_, halide_type, input_dim_);
  inputs.push_back(placeholder);

  tvm::Array<tvm::Expr> new_shape = ToActualShape(placeholder);
  CoordTransFunc new_coord_to_old_coord_func = ToNominal(placeholder);
  tvm::Expr pad_zero_expr = tvm::make_const(halide_type, pad_zero_);

  tvm::Tensor output = tvm::compute(
      new_shape,
      [&](const tvm::Array<tvm::Var>& output_coord) {
        tvm::Array<tvm::Expr> output_coord1;
        for (const auto& coord : output_coord)
          output_coord1.push_back(coord);
        auto input_coord = new_coord_to_old_coord_func(output_coord1);
        ORT_ENFORCE(input_coord.size() == placeholder->shape.size());

        if (input_coord.size() > 0) {
          auto in_range = (input_coord[0] >= 0) && (input_coord[0] < placeholder->shape[0]);
          for (size_t dim = 1; dim < input_coord.size(); ++dim)
            in_range = in_range && (input_coord[dim] >= 0) && (input_coord[dim] < placeholder->shape[dim]);

          return tvm::if_then_else(in_range, placeholder(input_coord), pad_zero_expr);
        } else {
          // scalar
          return placeholder(input_coord);
        }
      });

  outputs.push_back(output);
}

}  // namespace tvm_codegen
}  // namespace onnxruntime
<|endoftext|>


<commit_before>/*
 * Instruction.cpp
 *
 *  Created on: 28 oct. 2017
 *      Author: Matthieu
 */

#include <Instruction.h>

float defaultTemperature = 13.0;
float instructedTemperature = 16.0;
const float Instruction::T_DIFF = 0.1;
time_t blimit = 0;
Timer* Instruction::timer;

Instruction::Instruction(Timer* timer, float defaultTemperature,
		float instructedTemperature, time_t limit) {
	this->init(timer, defaultTemperature, instructedTemperature, limit);

}
Instruction::Instruction() {
}

Instruction::~Instruction() {
	// TODO Auto-generated destructor stub
}

void Instruction::init(Timer* timer, float defaultTemperature,
		float instructedTemperature, time_t limit) {
	this->setDefaultTemperature(defaultTemperature);
	Instruction::setTimer(timer);
	this->setInstructedTemperature(instructedTemperature);
	this->setLimit(limit);
}

void Instruction::setTimer(Timer* timer) {
	Instruction::timer = timer;
}

float Instruction::getDefaultTemperature() {
	return defaultTemperature;
}
float Instruction::getInstructedTemperature() {
	return instructedTemperature;
}
time_t Instruction::getLimit() {
	return limit;
}
void Instruction::setLimit(time_t limit_) {
	limit = limit_;
}

void Instruction::setInstructedTemperature(float instructedTemperature_) {
	instructedTemperature = instructedTemperature_;
}
void Instruction::setDefaultTemperature(float defaultTemperature_) {
	defaultTemperature = defaultTemperature_;
}

/*
 * Return a int between 0 and 5 included telling how much power we should give, in %, 5 being 100%, 0 being no heat needed.
 * see *_POWER static variables in Instruction class.
 */

int Instruction::shouldHeat(DHTSmoother* dht) {
	//handle two kind of instructions : cold and hot ones
	//TODO the thinking is not done yet
	if (Instruction::timer->getEpochTime() <= getLimit()) {
		return Instruction::compare(instructedTemperature,
				dht->readTemperature());
	} else {
		return Instruction::compare(defaultTemperature, dht->readTemperature());
	}

}

int Instruction::compare(float instructed, float current) {
	if (current > instructed + Instruction::T_DIFF) {
		return Instruction::NO_POWER;
	} else if (current > instructed) {
		return Instruction::VERY_LOW_POWER;
	} else if (current > instructed - Instruction::T_DIFF) {
		return Instruction::LOW_POWER;
	} else if (current > instructed - Instruction::T_DIFF * 2) {
		return Instruction::MEDIUM_POWER;
	} else if (current > instructed - Instruction::T_DIFF * 3) {
		return Instruction::HIGH_POWER;
	} else {
		return Instruction::FULL_POWER;
	}
	//SHould not happen
	return Instruction::NO_POWER;
}
bool Instruction::parseInstruction(const char*) {
	return false;
}

<commit_msg>working, had an issue after several minutes of runningm need to investigate why<commit_after>/*
 * Instruction.cpp
 *
 *  Created on: 28 oct. 2017
 *      Author: Matthieu
 */

#include <Instruction.h>

float defaultTemperature = 13.0;
float instructedTemperature = 16.0;
const float Instruction::T_DIFF = 0.1;
time_t blimit = 0;
Timer* Instruction::timer;

Instruction::Instruction(Timer* timer, float defaultTemperature,
		float instructedTemperature, time_t limit) {
	this->init(timer, defaultTemperature, instructedTemperature, limit);

}
Instruction::Instruction() {
}

Instruction::~Instruction() {
	// TODO Auto-generated destructor stub
}

void Instruction::init(Timer* timer, float defaultTemperature,
		float instructedTemperature, time_t limit) {
	this->setDefaultTemperature(defaultTemperature);
	Instruction::setTimer(timer);
	this->setInstructedTemperature(instructedTemperature);
	this->setLimit(limit);
}

void Instruction::setTimer(Timer* timer) {
	Instruction::timer = timer;
}

float Instruction::getDefaultTemperature() {
	return defaultTemperature;
}
float Instruction::getInstructedTemperature() {
	return instructedTemperature;
}
time_t Instruction::getLimit() {
	return limit;
}
void Instruction::setLimit(time_t limit_) {
	limit = limit_;
}

void Instruction::setInstructedTemperature(float instructedTemperature_) {
	instructedTemperature = instructedTemperature_;
}
void Instruction::setDefaultTemperature(float defaultTemperature_) {
	defaultTemperature = defaultTemperature_;
}

/*
 * Return a int between 0 and 5 included telling how much power we should give, in %, 5 being 100%, 0 being no heat needed.
 * see *_POWER static variables in Instruction class.
 */

int Instruction::shouldHeat(DHTSmoother* dht) {
	//handle two kind of instructions : cold and hot ones
	//TODO let it run several minutes on COM port to check if no error.
	if (Instruction::timer->getEpochTime() <= getLimit()) {
		return Instruction::compare(instructedTemperature,
				dht->readTemperature());
	} else {
		return Instruction::compare(defaultTemperature, dht->readTemperature());
	}

}

int Instruction::compare(float instructed, float current) {
	if (current > instructed + Instruction::T_DIFF) {
		return Instruction::NO_POWER;
	} else if (current > instructed) {
		return Instruction::VERY_LOW_POWER;
	} else if (current > instructed - Instruction::T_DIFF) {
		return Instruction::LOW_POWER;
	} else if (current > instructed - Instruction::T_DIFF * 2) {
		return Instruction::MEDIUM_POWER;
	} else if (current > instructed - Instruction::T_DIFF * 3) {
		return Instruction::HIGH_POWER;
	} else {
		return Instruction::FULL_POWER;
	}
	//SHould not happen
	return Instruction::NO_POWER;
}
bool Instruction::parseInstruction(const char*) {
	return false;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <seqan/arg_parse.h>
#include <seqan/seq_io.h>

using namespace seqan;
using namespace std;

const char *PROGRAM_NAME = "biotool";
const char *HEADER = "FILENAME\tNUMSEQ\tTOTAL\tMIN\tAVG\tMAX";
const unsigned DEFAULT_MIN_LEN = 0;

typedef enum {Success=0, Error_command_line=1, Error_open_file=2, Error_parse_file=3} exit_status;

struct BiotoolOptions
{
    unsigned minlen;
    bool verbose;
    bool version;
    vector<string> fasta_files;

    BiotoolOptions() :
    minlen(DEFAULT_MIN_LEN), verbose(false), version(false), fasta_files({})
    {}
};

void print_error(const char *message)
{
    cerr << PROGRAM_NAME << " ERROR: " << message << endl;
}

BiotoolOptions parse_options(int argc, char const **argv)
{
    ArgumentParser parser(PROGRAM_NAME);
    addArgument(parser, ArgParseArgument(
        ArgParseArgument::STRING, "FASTA_FILE", true));
    addOption(parser, ArgParseOption(
        "m", "minlen", "Minimum length sequence to include in stats (default " + to_string(DEFAULT_MIN_LEN) + ")",
        ArgParseArgument::INTEGER, "INT"));
    addOption(parser, ArgParseOption(
        "v", "version", "Display program version and exit"));
    addOption(parser, ArgParseOption(
        "b", "verbose", "Print more stuff about what's happening"));
    ArgumentParser::ParseResult res = parse(parser, argc, argv);

    //if (res == ArgumentParser::PARSE_ERROR)
    if (res != ArgumentParser::PARSE_OK)
    {
	if (res == ArgumentParser::PARSE_ERROR) {
           exit(Error_command_line);
	}
	else {
           exit(Success);
        }
    }

    BiotoolOptions options;
    getOptionValue(options.minlen, parser, "minlen");
    options.verbose = isSet(parser, "verbose");
    options.version = isSet(parser, "version");
    options.fasta_files = getArgumentValues(parser, 0);
    return options;
}

void process_files(BiotoolOptions options)
{
    CharString id;
    CharString seq;

    cout << HEADER << endl;

    for (string filename : options.fasta_files) {
	SeqFileIn seqFileIn;

        if (!open(seqFileIn, toCString(filename)))
        {
	    print_error("Could not open the file.");
            exit(Error_open_file);
        }

        int max_len = 0;
        int min_len = -1;
	int this_len;
        unsigned total_len = 0;
        unsigned num_seqs = 0;
	unsigned int average;

        while(!atEnd(seqFileIn))
        {
	    try
	    {
	        readRecord(id, seq, seqFileIn);
	    }
            catch (Exception const & e)
            {
	        print_error(e.what());
                exit(Error_parse_file);
            }
	    this_len = length(seq);
	    if (this_len > options.minlen)
            {
	        num_seqs++;
	        total_len += this_len;
	        max_len = max(max_len, this_len);
	        if (min_len < 0 || this_len < min_len)
                {
                    min_len = this_len;
                }
	    }
        }
	if (num_seqs > 0)
        {
            average = (unsigned int) floor((double) total_len / (double) num_seqs);
	    cout << filename << '\t' << num_seqs << '\t' \
		 << min_len << '\t' << average << '\t' << max_len << endl;
        }
	else
        {
	    cout << filename << "\t0\t0\t-\t-\t-" << endl;
        }
    }
}

int main(int argc, char const **argv)
{
    BiotoolOptions options = parse_options(argc, argv);
    process_files(options);

    return 0;
}
<commit_msg>Include total sequence length in output<commit_after>#include <iostream>
#include <seqan/arg_parse.h>
#include <seqan/seq_io.h>

using namespace seqan;
using namespace std;

const char *PROGRAM_NAME = "biotool";
const char *HEADER = "FILENAME\tNUMSEQ\tTOTAL\tMIN\tAVG\tMAX";
const unsigned DEFAULT_MIN_LEN = 0;

typedef enum {Success=0, Error_command_line=1, Error_open_file=2, Error_parse_file=3} exit_status;

struct BiotoolOptions
{
    unsigned minlen;
    bool verbose;
    bool version;
    vector<string> fasta_files;

    BiotoolOptions() :
    minlen(DEFAULT_MIN_LEN), verbose(false), version(false), fasta_files({})
    {}
};

void print_error(const char *message)
{
    cerr << PROGRAM_NAME << " ERROR: " << message << endl;
}

BiotoolOptions parse_options(int argc, char const **argv)
{
    ArgumentParser parser(PROGRAM_NAME);
    addArgument(parser, ArgParseArgument(
        ArgParseArgument::STRING, "FASTA_FILE", true));
    addOption(parser, ArgParseOption(
        "m", "minlen", "Minimum length sequence to include in stats (default " + to_string(DEFAULT_MIN_LEN) + ")",
        ArgParseArgument::INTEGER, "INT"));
    addOption(parser, ArgParseOption(
        "v", "version", "Display program version and exit"));
    addOption(parser, ArgParseOption(
        "b", "verbose", "Print more stuff about what's happening"));
    ArgumentParser::ParseResult res = parse(parser, argc, argv);

    //if (res == ArgumentParser::PARSE_ERROR)
    if (res != ArgumentParser::PARSE_OK)
    {
	if (res == ArgumentParser::PARSE_ERROR) {
           exit(Error_command_line);
	}
	else {
           exit(Success);
        }
    }

    BiotoolOptions options;
    getOptionValue(options.minlen, parser, "minlen");
    options.verbose = isSet(parser, "verbose");
    options.version = isSet(parser, "version");
    options.fasta_files = getArgumentValues(parser, 0);
    return options;
}

void process_files(BiotoolOptions options)
{
    CharString id;
    CharString seq;

    cout << HEADER << endl;

    for (string filename : options.fasta_files) {
	SeqFileIn seqFileIn;

        if (!open(seqFileIn, toCString(filename)))
        {
	    print_error("Could not open the file.");
            exit(Error_open_file);
        }

        int max_len = 0;
        int min_len = -1;
	int this_len;
        unsigned total_len = 0;
        unsigned num_seqs = 0;
	unsigned int average;

        while(!atEnd(seqFileIn))
        {
	    try
	    {
	        readRecord(id, seq, seqFileIn);
	    }
            catch (Exception const & e)
            {
	        print_error(e.what());
                exit(Error_parse_file);
            }
	    this_len = length(seq);
	    if (this_len > options.minlen)
            {
	        num_seqs++;
	        total_len += this_len;
	        max_len = max(max_len, this_len);
	        if (min_len < 0 || this_len < min_len)
                {
                    min_len = this_len;
                }
	    }
        }
	if (num_seqs > 0)
        {
            average = (unsigned int) floor((double) total_len / (double) num_seqs);
	    cout << filename << '\t' << num_seqs << '\t' << total_len << '\t' \
		 << min_len << '\t' << average << '\t' << max_len << endl;
        }
	else
        {
	    cout << filename << "\t0\t0\t-\t-\t-" << endl;
        }
    }
}

int main(int argc, char const **argv)
{
    BiotoolOptions options = parse_options(argc, argv);
    process_files(options);

    return 0;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/file.hpp"

#include <boost/bind.hpp>

using namespace libtorrent;

// do not include files and folders whose
// name starts with a .
bool file_filter(std::string const& f)
{
	if (filename(f)[0] == '.') return false;
	fprintf(stderr, "%s\n", f.c_str());
	return true;
}

void print_progress(int i, int num)
{
	fprintf(stderr, "\r%d/%d", i+1, num);
}

void print_usage()
{
	fputs("usage: make_torrent FILE [OPTIONS]\n"
		"\n"
		"Generates a torrent file from the specified file\n"
		"or directory and writes it to standard out\n\n"
		"OPTIONS:\n"
		"-m          generate a merkle hash tree torrent.\n"
		"            merkle torrents require client support\n"
		"-w url      adds a web seed to the torrent with\n"
		"            the specified url\n"
		"-t url      adds the specified tracker to the\n"
		"            torrent\n"
		"-p bytes    enables padding files. Files larger\n"
		"            than bytes will be piece-aligned\n"
		"-s bytes    specifies a piece size for the torrent\n"
		"            This has to be a multiple of 16 kiB\n"
		, stderr);
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	char const* creator_str = "libtorrent";

	if (argc < 2)
	{
		print_usage();
		return 1;
	}

#ifndef BOOST_NO_EXCEPTIONS
	try
	{
#endif
		std::vector<std::string> web_seeds;
		std::vector<std::string> trackers;
		int pad_file_limit = -1;
		int piece_size = 0;
		int flags = 0;

		for (int i = 2; i < argc; ++i)
		{
			if (argv[i][0] != '-')
			{
				print_usage();
				return 1;
			}

			switch (argv[i][1])
			{
				case 'w':
					++i;
					web_seeds.push_back(argv[i]);
					break;
				case 't':
					++i;
					trackers.push_back(argv[i]);
					break;
				case 'p':
					++i;
					pad_file_limit = atoi(argv[i]);
					flags |= create_torrent::optimize;
					break;
				case 's':
					++i;
					piece_size = atoi(argv[i]);
					break;
				case 'm':
					flags |= create_torrent::merkle;
					break;
				default:
					print_usage();
					return 1;
			}
		}

		file_storage fs;
		file_pool fp;
		std::string full_path = libtorrent::complete(argv[1]);

		add_files(fs, full_path, file_filter);

		create_torrent t(fs, piece_size, pad_file_limit, flags);
		for (std::vector<std::string>::iterator i = trackers.begin()
			, end(trackers.end()); i != end; ++i)
			t.add_tracker(*i);

		for (std::vector<std::string>::iterator i = web_seeds.begin()
			, end(web_seeds.end()); i != end; ++i)
			t.add_url_seed(*i);

		error_code ec;
		set_piece_hashes(t, parent_path(full_path)
			, boost::bind(&print_progress, _1, t.num_pieces()), ec);
		if (ec)
		{
			fprintf(stderr, "%s\n", ec.message().c_str());
			return 1;
		}

		fprintf(stderr, "\n");
		t.set_creator(creator_str);

		// create the torrent and print it to stdout
		std::vector<char> torrent;
		bencode(back_inserter(torrent), t.generate());
		fwrite(&torrent[0], 1, torrent.size(), stdout);

#ifndef BOOST_NO_EXCEPTIONS
	}
	catch (std::exception& e)
	{
		fprintf(stderr, "%s\n", e.what());
	}
#endif

	return 0;
}

<commit_msg>error handling in make_torrent<commit_after>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/create_torrent.hpp"
#include "libtorrent/file.hpp"

#include <boost/bind.hpp>

using namespace libtorrent;

// do not include files and folders whose
// name starts with a .
bool file_filter(std::string const& f)
{
	if (filename(f)[0] == '.') return false;
	fprintf(stderr, "%s\n", f.c_str());
	return true;
}

void print_progress(int i, int num)
{
	fprintf(stderr, "\r%d/%d", i+1, num);
}

void print_usage()
{
	fputs("usage: make_torrent FILE [OPTIONS]\n"
		"\n"
		"Generates a torrent file from the specified file\n"
		"or directory and writes it to standard out\n\n"
		"OPTIONS:\n"
		"-m          generate a merkle hash tree torrent.\n"
		"            merkle torrents require client support\n"
		"-w url      adds a web seed to the torrent with\n"
		"            the specified url\n"
		"-t url      adds the specified tracker to the\n"
		"            torrent\n"
		"-p bytes    enables padding files. Files larger\n"
		"            than bytes will be piece-aligned\n"
		"-s bytes    specifies a piece size for the torrent\n"
		"            This has to be a multiple of 16 kiB\n"
		, stderr);
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;

	char const* creator_str = "libtorrent";

	if (argc < 2)
	{
		print_usage();
		return 1;
	}

#ifndef BOOST_NO_EXCEPTIONS
	try
	{
#endif
		std::vector<std::string> web_seeds;
		std::vector<std::string> trackers;
		int pad_file_limit = -1;
		int piece_size = 0;
		int flags = 0;

		for (int i = 2; i < argc; ++i)
		{
			if (argv[i][0] != '-')
			{
				print_usage();
				return 1;
			}

			switch (argv[i][1])
			{
				case 'w':
					++i;
					web_seeds.push_back(argv[i]);
					break;
				case 't':
					++i;
					trackers.push_back(argv[i]);
					break;
				case 'p':
					++i;
					pad_file_limit = atoi(argv[i]);
					flags |= create_torrent::optimize;
					break;
				case 's':
					++i;
					piece_size = atoi(argv[i]);
					break;
				case 'm':
					flags |= create_torrent::merkle;
					break;
				default:
					print_usage();
					return 1;
			}
		}

		file_storage fs;
		file_pool fp;
		std::string full_path = libtorrent::complete(argv[1]);

		add_files(fs, full_path, file_filter);
		if (fs.num_files() == 0)
		{
			fputs("no files specified.\n", stderr);
			return 1;
		}

		create_torrent t(fs, piece_size, pad_file_limit, flags);
		for (std::vector<std::string>::iterator i = trackers.begin()
			, end(trackers.end()); i != end; ++i)
			t.add_tracker(*i);

		for (std::vector<std::string>::iterator i = web_seeds.begin()
			, end(web_seeds.end()); i != end; ++i)
			t.add_url_seed(*i);

		error_code ec;
		set_piece_hashes(t, parent_path(full_path)
			, boost::bind(&print_progress, _1, t.num_pieces()), ec);
		if (ec)
		{
			fprintf(stderr, "%s\n", ec.message().c_str());
			return 1;
		}

		fprintf(stderr, "\n");
		t.set_creator(creator_str);

		// create the torrent and print it to stdout
		std::vector<char> torrent;
		bencode(back_inserter(torrent), t.generate());
		fwrite(&torrent[0], 1, torrent.size(), stdout);

#ifndef BOOST_NO_EXCEPTIONS
	}
	catch (std::exception& e)
	{
		fprintf(stderr, "%s\n", e.what());
	}
#endif

	return 0;
}

<|endoftext|>


<commit_before>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <iostream>
#include <fstream>
#include <iterator>
#include <iomanip>

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/file_pool.hpp"

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>

using namespace boost::filesystem;
using namespace libtorrent;

void add_files(
	torrent_info& t
	, path const& p
	, path const& l)
{
	path f(p / l);
	if (is_directory(f))
	{
		for (directory_iterator i(f), end; i != end; ++i)
			add_files(t, p, l / i->leaf());
	}
	else
	{
		std::cerr << "adding \"" << l.string() << "\"\n";
		t.add_file(l, file_size(f));
	}
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;
	using namespace boost::filesystem;

	path::default_name_check(no_check);

	if (argc != 4)
	{
		std::cerr << "usage: make_torrent <output torrent-file> "
			"<announce url> <file or directory to create torrent from>\n";
		return 1;
	}

	try
	{
		torrent_info t;
		path full_path = complete(path(argv[3]));
		ofstream out(complete(path(argv[1])), std::ios_base::binary);

		int piece_size = 256 * 1024;
		char const* creator_str = "libtorrent";

		add_files(t, full_path.branch_path(), full_path.leaf());
		t.set_piece_size(piece_size);

		file_pool fp;
		storage st(t, full_path.branch_path(), fp);
		t.add_tracker(argv[2]);

		// calculate the hash for all pieces
		int num = t.num_pieces();
		std::vector<char> buf(piece_size);
		for (int i = 0; i < num; ++i)
		{
			st.read(&buf[0], i, 0, t.piece_size(i));
			hasher h(&buf[0], t.piece_size(i));
			t.set_hash(i, h.final());
			std::cerr << (i+1) << "/" << num << "\r";
		}

		t.set_creator(creator_str);

		// create the torrent and print it to out
		entry e = t.create_torrent();
		libtorrent::bencode(std::ostream_iterator<char>(out), e);
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << "\n";
	}

	return 0;
}

<commit_msg>the torrent maker now skips hidden files<commit_after>/*

Copyright (c) 2006, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#include <iostream>
#include <fstream>
#include <iterator>
#include <iomanip>

#include "libtorrent/entry.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent_info.hpp"
#include "libtorrent/file.hpp"
#include "libtorrent/storage.hpp"
#include "libtorrent/hasher.hpp"
#include "libtorrent/file_pool.hpp"

#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/fstream.hpp>

using namespace boost::filesystem;
using namespace libtorrent;

void add_files(
	torrent_info& t
	, path const& p
	, path const& l)
{
	if (l.leaf()[0] == '.') return;
	path f(p / l);
	if (is_directory(f))
	{
		for (directory_iterator i(f), end; i != end; ++i)
			add_files(t, p, l / i->leaf());
	}
	else
	{
		std::cerr << "adding \"" << l.string() << "\"\n";
		t.add_file(l, file_size(f));
	}
}

int main(int argc, char* argv[])
{
	using namespace libtorrent;
	using namespace boost::filesystem;

	path::default_name_check(no_check);

	if (argc != 4)
	{
		std::cerr << "usage: make_torrent <output torrent-file> "
			"<announce url> <file or directory to create torrent from>\n";
		return 1;
	}

	try
	{
		torrent_info t;
		path full_path = complete(path(argv[3]));
		ofstream out(complete(path(argv[1])), std::ios_base::binary);

		int piece_size = 256 * 1024;
		char const* creator_str = "libtorrent";

		add_files(t, full_path.branch_path(), full_path.leaf());
		t.set_piece_size(piece_size);

		file_pool fp;
		storage st(t, full_path.branch_path(), fp);
		t.add_tracker(argv[2]);

		// calculate the hash for all pieces
		int num = t.num_pieces();
		std::vector<char> buf(piece_size);
		for (int i = 0; i < num; ++i)
		{
			st.read(&buf[0], i, 0, t.piece_size(i));
			hasher h(&buf[0], t.piece_size(i));
			t.set_hash(i, h.final());
			std::cerr << (i+1) << "/" << num << "\r";
		}

		t.set_creator(creator_str);

		// create the torrent and print it to out
		entry e = t.create_torrent();
		libtorrent::bencode(std::ostream_iterator<char>(out), e);
	}
	catch (std::exception& e)
	{
		std::cerr << e.what() << "\n";
	}

	return 0;
}

<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// This file is part of Swift2D.                                              //
//                                                                            //
// Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer                    //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include <swift2d/swift2d.hpp>
#include "SpaceScene.hpp"
#include "Player.hpp"

#include <steam/steam_api.h>

using namespace swift;

// main ------------------------------------------------------------------------
int main(int argc, char** argv) {

  // initialize Swift2D
  Application::get().init(argc, argv);
  Network::get().connect("TestGame");

  if (!Steam::get().init()) {
    Application::get().clean_up();
    return 1;
  }

  Steam::get().update_room_list();

  Steam::get().on_updated_room_list.connect(
    [](std::unordered_map<uint64_t, Steam::RoomData> const& rooms) {
      for (auto const& room : rooms) {
        if (room.second.name == "ichmachemaleinfachnureinenraumauf") {
          Steam::get().join_room(room.first);
          return;
        }
      }

      Steam::get().create_room("ichmachemaleinfachnureinenraumauf");
  });

  Steam::get().on_message.connect(
    [](Steam::MessageType type, uint64_t user_id, std::string const& join_message) {
      std::cout << join_message << std::endl;

      std::string huhu("huhu");
      SteamNetworking()->SendP2PPacket(user_id, huhu.c_str(), huhu.length(), k_EP2PSendReliable);
  });

  // scene ---------------------------------------------------------------------
  auto scene = SpaceScene::create();
  auto camera = scene->add<CameraComponent>();
  camera->Size = math::vec2(2.f, 2.f);

  // player --------------------------------------------------------------------
  Player::init();
  Player player(true);

  // rendering pipeline --------------------------------------------------------
  auto window = WindowManager::get().get_default();

  // main loop -----------------------------------------------------------------
  Timer timer;
  timer.start();
  Application::get().on_frame.connect([&]() {
    Steam::get().update();

    uint32 size;
    if (SteamNetworking()->IsP2PPacketAvailable(&size)) {
      std::string result(size, ' ');
      uint32 actual_size;
      CSteamID sender;
      SteamNetworking()->ReadP2PPacket(&(*result.begin()), size, &actual_size, &sender);
      std::cout << "Got message: " << result << " from " << Steam::get().get_user_name(sender.ConvertToUint64()) << std::endl;
    }

    double time(timer.get_elapsed());
    timer.reset();

    window->process_input();
    Network::get().update();
    scene->update(time);
    Application::get().display(scene, camera);
  });

  window->on_close.connect([&](){
    Application::get().stop();
  });

  window->on_key_press.connect([&](Key key, int scancode, int action, int mods) {
    if (action != 1) {
      switch(key) {
        case Key::ESCAPE:
          Application::get().stop();
          break;
      }
    }
  });

  Application::get().start();
  Application::get().clean_up();

  return 0;
}
<commit_msg>added package on enter<commit_after>////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// This file is part of Swift2D.                                              //
//                                                                            //
// Copyright: (c) 2011-2014 Simon Schneegans & Felix Lauer                    //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////

#include <swift2d/swift2d.hpp>
#include "SpaceScene.hpp"
#include "Player.hpp"

#include <steam/steam_api.h>

using namespace swift;

// main ------------------------------------------------------------------------
int main(int argc, char** argv) {

  // initialize Swift2D
  Application::get().init(argc, argv);
  Network::get().connect("TestGame");

  if (!Steam::get().init()) {
    Application::get().clean_up();
    return 1;
  }

  Steam::get().update_room_list();

  Steam::get().on_updated_room_list.connect(
    [](std::unordered_map<uint64_t, Steam::RoomData> const& rooms) {
      for (auto const& room : rooms) {
        if (room.second.name == "ichmachemaleinfachnureinenraumauf") {
          Steam::get().join_room(room.first);
          return;
        }
      }

      Steam::get().create_room("ichmachemaleinfachnureinenraumauf");
  });

  std::set<uint64_t> user_ids;

  Steam::get().on_message.connect(
    [&](Steam::MessageType type, uint64_t user_id, std::string const& join_message) {
      std::cout << join_message << std::endl;
      user_ids.insert(user_id);
      std::string huhu("huhu");
      SteamNetworking()->SendP2PPacket(user_id, huhu.c_str(), huhu.length(), k_EP2PSendReliable);
  });

  // scene ---------------------------------------------------------------------
  auto scene = SpaceScene::create();
  auto camera = scene->add<CameraComponent>();
  camera->Size = math::vec2(2.f, 2.f);

  // player --------------------------------------------------------------------
  Player::init();
  Player player(true);

  // rendering pipeline --------------------------------------------------------
  auto window = WindowManager::get().get_default();

  // main loop -----------------------------------------------------------------
  Timer timer;
  timer.start();
  Application::get().on_frame.connect([&]() {
    Steam::get().update();

    uint32 size;
    if (SteamNetworking()->IsP2PPacketAvailable(&size)) {
      std::string result(size, ' ');
      uint32 actual_size;
      CSteamID sender;
      SteamNetworking()->ReadP2PPacket(&(*result.begin()), size, &actual_size, &sender);
      std::cout << "Got message: " << result << " from " << Steam::get().get_user_name(sender.ConvertToUint64()) << std::endl;
    }

    double time(timer.get_elapsed());
    timer.reset();

    window->process_input();
    Network::get().update();
    scene->update(time);
    Application::get().display(scene, camera);
  });

  window->on_close.connect([&](){
    Application::get().stop();
  });

  window->on_key_press.connect([&](Key key, int scancode, int action, int mods) {
    if (action != 1) {
      switch(key) {
        case Key::ESCAPE:
          Application::get().stop();
          break;
        case Key::ENTER:
          for (auto user_id : user_ids) {
            std::string msg("Huhu, ich habe Enter gedrückt!");
            SteamNetworking()->SendP2PPacket(user_id, msg.c_str(), msg.length(), k_EP2PSendReliable);
          }
          break;
      }
    }
  });

  Application::get().start();
  Application::get().clean_up();

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: b3drange.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:05:24 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"

#ifndef _BGFX_RANGE_B3DRANGE_HXX
#include <basegfx/range/b3drange.hxx>
#endif

#ifndef _BGFX_RANGE_B3IRANGE_HXX
#include <basegfx/range/b3irange.hxx>
#endif

#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif

namespace basegfx
{
    B3DRange::B3DRange(const B3IRange& rRange) :
        maRangeX(),
        maRangeY(),
        maRangeZ()
    {
        if( !rRange.isEmpty() )
        {
            maRangeX = rRange.getMinX();
            maRangeY = rRange.getMinY();
            maRangeZ = rRange.getMinZ();

            maRangeX.expand( rRange.getMaxX() );
            maRangeY.expand( rRange.getMaxY() );
            maRangeZ.expand( rRange.getMaxZ() );
        }
    }

    B3IRange fround(const B3DRange& rRange )
    {
        return rRange.isEmpty() ?
            B3IRange() :
            B3IRange(fround(rRange.getMinX()),
                     fround(rRange.getMinY()),
                     fround(rRange.getMinZ()),
                     fround(rRange.getMaxX()),
                     fround(rRange.getMaxY()),
                     fround(rRange.getMaxZ()));
    }

} // end of namespace basegfx

// eof
<commit_msg>INTEGRATION: CWS changefileheader (1.8.58); FILE MERGED 2008/04/01 10:48:15 thb 1.8.58.2: #i85898# Stripping all external header guards 2008/03/28 16:05:56 rt 1.8.58.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: b3drange.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"
#include <basegfx/range/b3drange.hxx>
#include <basegfx/range/b3irange.hxx>
#include <basegfx/numeric/ftools.hxx>

namespace basegfx
{
    B3DRange::B3DRange(const B3IRange& rRange) :
        maRangeX(),
        maRangeY(),
        maRangeZ()
    {
        if( !rRange.isEmpty() )
        {
            maRangeX = rRange.getMinX();
            maRangeY = rRange.getMinY();
            maRangeZ = rRange.getMinZ();

            maRangeX.expand( rRange.getMaxX() );
            maRangeY.expand( rRange.getMaxY() );
            maRangeZ.expand( rRange.getMaxZ() );
        }
    }

    B3IRange fround(const B3DRange& rRange )
    {
        return rRange.isEmpty() ?
            B3IRange() :
            B3IRange(fround(rRange.getMinX()),
                     fround(rRange.getMinY()),
                     fround(rRange.getMinZ()),
                     fround(rRange.getMaxX()),
                     fround(rRange.getMaxY()),
                     fround(rRange.getMaxZ()));
    }

} // end of namespace basegfx

// eof
<|endoftext|>


<commit_before><commit_msg>coverity#735397 dead code<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <pcl/io/pcd_io.h>
#include <pcl/io/ply_io.h>
#include <pcl/point_types.h>
#include <pcl/io/vtk_lib_io.h>
#include <pcl/impl/point_types.hpp>
#include <pcl/registration/icp.h>
#include <pcl/visualization/cloud_viewer.h>
#include <fstream>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/features/normal_3d.h>
#include <pcl/surface/gp3.h>
#include <pcl/surface/organized_fast_mesh.h>
#include <sstream>
#include <sensor_msgs/PointCloud2.h>
#include <pcl/filters/voxel_grid.h>
//#include <pcl/PCLPointCloud2.h>//1.7 only

using namespace std;

void ShowCloud (pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, int index)
{
	stringstream title;
       	title << "Cloud "<<index;
	pcl::visualization::CloudViewer viewer (title.str());
	viewer.showCloud (cloud);
	while (!viewer.wasStopped ())
	{
	}
}

void ReadCloud (pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, ifstream& file, int index, bool useBGR)
{
	char dsize[4];
	file.read (dsize, 4);
	cout<<"READ: "<<(int)(dsize[0])<<" "<<(int)(dsize[1])<<" "<<(int)(dsize[2])<<" "<<(int)(dsize[3])<<endl;
	ifstream::pos_type size = (unsigned char)dsize[0];
	size = size<<8;
	size += (unsigned char)dsize[1];
	size = size<<8;
	size += (unsigned char)dsize[2];
	size = size<<8;
	size += (unsigned char)dsize[3];
	cout<<"Got Size: "<<size<<" "<<endl;
	char* memblock = new char [10*size];
	file.read (memblock, 10*size);
	unsigned char* umem = reinterpret_cast<unsigned char*>(memblock);

	cloud->width    = size;
	cloud->height   = 1;
	cloud->is_dense = false;
	cloud->points.resize (cloud->width * cloud->height);
	for (size_t i = 0; i < cloud->points.size (); ++i)
	{
			cloud->points[i].x = (signed short)(((umem[i*10+0])<<8) + umem[i*10+1]);
			cloud->points[i].y = (signed short)(((umem[i*10+2])<<8) + umem[i*10+3]);
			cloud->points[i].z = -(signed short)(((umem[i*10+4])<<8) + umem[i*10+5]);
			cloud->points[i].x/=1000;
			cloud->points[i].y/=1000;
			cloud->points[i].z/=1000;

			if(i<5 || i+5>=cloud->points.size())
			{
				cout<<"Point: "<<i<<" "<<cloud->points[i].x<<" "<<cloud->points[i].y<<" "<<cloud->points[i].z<<endl;
			}
		if(!useBGR)
		{

			cloud->points[i].b = memblock[i*10+6];
			cloud->points[i].g = memblock[i*10+7];
			cloud->points[i].r = memblock[i*10+8];
			cloud->points[i].a = memblock[i*10+9];
		}
		else
		{
			if(index%3==0)
			{
				cloud->points[i].b = 255;
				cloud->points[i].g = 0;
				cloud->points[i].r = 0;
				cloud->points[i].a = 0;
			}
			else if (index%3==1)
			{
				cloud->points[i].b = 0;
				cloud->points[i].g = 255;
				cloud->points[i].r = 0;
				cloud->points[i].a = 0;

			}
			else
			{
				cloud->points[i].b = 0;
				cloud->points[i].g = 0;
				cloud->points[i].r = 255;
				cloud->points[i].a = 0;
			}
		}
	}

	cout<<"Set cloud"<<endl;

	delete[] memblock;
}

void SaveToPly(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud, string name)
{
	pcl::PLYWriter plyWriter;
	plyWriter.write(name, *cloud);
}

void MakePolygons(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud)
{
	pcl::OrganizedFastMesh<pcl::PointXYZRGBA> ofm;
	ofm.setInputCloud(cloud);
	pcl::PolygonMesh polymesh;
	ofm.reconstruct(polymesh);
	cout<<"Done constructing mesh"<<endl;

	//pcl::io::savePolygonFileSTL("sample2.stl",polymesh);
/*
	pcl::PLYWriter plyWriter;
	plyWriter.writeASCII("sample.ply",cloud);*/
	/*
	// Normal estimation*
	pcl::NormalEstimation<pcl::PointXYZRGBA, pcl::Normal> n;
	pcl::PointCloud<pcl::Normal>::Ptr normals (new pcl::PointCloud<pcl::Normal>);
	pcl::search::KdTree<pcl::PointXYZRGBA>::Ptr tree (new pcl::search::KdTree<pcl::PointXYZRGBA>);
	tree->setInputCloud (cloud);
	n.setInputCloud (cloud);n.setSearchMethod (tree);
	n.setKSearch (20);
	n.compute (*normals);
	// normals should not contain the point normals + surface curvatures

	// Concatenate the XYZ and normal fields*
	pcl::PointCloud<pcl::PointNormal>::Ptr cloud_with_normals (new pcl::PointCloud<pcl::PointNormal>);
	pcl::concatenateFields (*cloud, *normals, *cloud_with_normals);
	// cloud_with_normals = cloud + normals

	// Create search tree*
	pcl::search::KdTree<pcl::PointNormal>::Ptr tree2 (new pcl::search::KdTree<pcl::PointNormal>);
	tree2->setInputCloud (cloud_with_normals);

	// Initialize objects
	pcl::GreedyProjectionTriangulation<pcl::PointNormal> gp3;
	pcl::PolygonMesh triangles;

	// Set the maximum distance between connected points (maximum edge length)
	gp3.setSearchRadius (0.025);

	// Set typical values for the parameters
	gp3.setMu (2.5);
	gp3.setMaximumNearestNeighbors (100);
	gp3.setMaximumSurfaceAngle(M_PI/4); // 45 degrees
	gp3.setMinimumAngle(M_PI/18); // 10 degrees
	gp3.setMaximumAngle(2*M_PI/3); // 120 degrees
	gp3.setNormalConsistency(false);

	// Get result
	gp3.setInputCloud (cloud_with_normals);
	gp3.setSearchMethod (tree2);
	gp3.reconstruct (triangles);

	// Additional vertex information
	std::vector<int> parts = gp3.getPartIDs();
	std::vector<int> states = gp3.getPointStates();*/
}

void FilterCloud(pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud)
{
	sensor_msgs::PointCloud2::Ptr msg (new sensor_msgs::PointCloud2);
	sensor_msgs::PointCloud2::Ptr cloud_filtered (new sensor_msgs::PointCloud2);
	//pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::toROSMsg (*cloud, *msg);

	std::cerr << "PointCloud before filtering: " << cloud->width * cloud->height
		<< endl;

	// Create the filtering object
	pcl::VoxelGrid<sensor_msgs::PointCloud2> sor;
	sor.setInputCloud (msg);
	sor.setLeafSize (10.0f, 10.0f, 10.0f);
	sor.filter (*cloud_filtered);

	std::cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height
		<< endl;
}

int main (int argc, char** argv)
{
	cout<<"Usage: [# iterations], [Use rgb], [ply file name], [use ICP]"<<endl;

	int iters = 3;
	if(argc>1)
	{
		sscanf(argv[1],"%d",&iters);
		cout<<"Iters: "<<iters<<endl;
	}

	bool useBGR = 1;
	int a;
	if(argc>2)
	{
		sscanf(argv[2],"%d",&a);
		useBGR = a!=0;
	}

	string plyFile = "sample2.ply";
	if(argc>3)
	{
		plyFile = string(argv[3]);
	}

	bool useICP = false;
	if(argc>4)
	{
		sscanf(argv[4],"%d",&a);
		useICP = a!=0;
	}

	bool savePly = true;
	if(argc>5)
	{
		sscanf(argv[5],"%d",&a);
		savePly = a!=0;
	}

	//  pcl::PointCloud<pcl::PointXYZRGBA> cloud, cloud2;
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud2 (new pcl::PointCloud<pcl::PointXYZRGBA>);
	pcl::PointCloud<pcl::PointXYZRGBA>::Ptr cloud3 (new pcl::PointCloud<pcl::PointXYZRGBA>);

	// Fill in the cloud data

	cloud2->width    = 1000;
	cloud2->height   = 1;
	cloud2->is_dense = false;
	cloud2->points.resize (cloud2->width * cloud2->height);

	//ifstream file ("C:\\Users\\Eric\\Documents\\Visual Studio 2013\\Projects\\KinectExplorer-WPF\\bin\\Debug\\KinectDepth2.txt", ios::in|ios::binary|ios::ate);
	ifstream file ("..\\data\\KinectDepth2.txt", ios::in|ios::binary|ios::ate);

	if (file.is_open())
	{
		file.seekg (0, ios::beg);
		for(int  i=0; i <iters; i++)
		{
			if(i==0)
			{
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ShowCloud(cloud,i);
				*cloud3+=*cloud;

			//	FilterCloud(cloud3);
				//MakePolygons(cloud);
			}
			else if(i%2==1)
			{
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ReadCloud(cloud2, file,i, useBGR);
				ShowCloud(cloud2,i);
				if(useICP)
				{
					pcl::IterativeClosestPoint<pcl::PointXYZRGBA, pcl::PointXYZRGBA> icp;

					icp.setInputCloud (cloud2);
					icp.setInputTarget(cloud);
					icp.setMaximumIterations (2);
					icp.setMaxCorrespondenceDistance (1);

					cout<<"Trying to align!"<<endl;
					icp.align(*cloud2);
					Eigen::Matrix4f transformation = icp.getFinalTransformation ();

					cout << "has converged:" << icp.hasConverged() << " score: " << icp.getFitnessScore() << std::endl;

					cout << transformation << endl;
					cout<<"Size afer icp: "<<cloud2->size()<<" "<<cloud3->size()<<endl;
				}

				*cloud3+=*cloud2;
			}
			else if(i%2==0)
			{
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ReadCloud(cloud, file,i, useBGR);
				ShowCloud(cloud,i);

				if(useICP)
				{
					pcl::IterativeClosestPoint<pcl::PointXYZRGBA, pcl::PointXYZRGBA> icp;

					icp.setInputCloud (cloud);
					icp.setInputTarget(cloud2);
					icp.setMaximumIterations (2);
					icp.setMaxCorrespondenceDistance (1);

					cout<<"Trying to align!"<<endl;
					icp.align(*cloud);
					Eigen::Matrix4f transformation = icp.getFinalTransformation ();

					cout << "has converged:" << icp.hasConverged() << " score: " << icp.getFitnessScore() << std::endl;

					cout << transformation << endl;
					cout<<"Size afer icp: "<<cloud->size()<<" "<<cloud3->size()<<endl;
				}

				*cloud3+=*cloud;
			}
		}

		cout<<"FINAL CLOUD!"<<endl;
		ShowCloud(cloud3,-1);
		cout<<"Saving to ply file..."<<endl;
		if(savePly)
			SaveToPly(cloud3, plyFile);
		//MakePolygons(cloud3);
	}
	else cout << "Unable to open file";

	std::cout<<"DONE!\n";
	/*
	   pcl::io::savePCDFileASCII ("test_pcd.pcd", cloud);
	   std::cerr << "Saved " << cloud.points.size () << " data points to test_pcd.pcd." << std::endl;

	   for (size_t i = 0; i < cloud.points.size (); ++i)
	   std::cerr << "    " << cloud.points[i].x << " " << cloud.points[i].y << " " << cloud.points[i].z << std::endl;
	   */
	return (0);
}

<commit_msg>remove kinect2mesh<commit_after><|endoftext|>