text stringlengths 54 60.6k |
|---|
<commit_before>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2019-6-1 23:15:51
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
/*
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
*/
/*
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
*/
// const ll MOD = 1000000007;
const int MAX_SIZE = 1000010;
const long long MOD = 1e6 + 3;
long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD;
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = (i * fact[i - 1]) % MOD;
factinv[i] = (inv[i] * factinv[i - 1]) % MOD;
}
}
long long C(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
}
return 0;
}
long long power(long long x, long long n)
{
if (n == 0)
{
return 1;
}
else if (n % 2 == 1)
{
return (x * power(x, n - 1)) % MOD;
}
else
{
long long half = power(x, n / 2);
return (half * half) % MOD;
}
}
long long gcd(long long x, long long y)
{
return y ? gcd(y, x % y) : x;
}
ll exe(ll x, ll y)
{
if (x == 0)
{
return 0;
}
ll n = y / MOD - (x - 1) / MOD;
if (n == 0)
{
return 0;
}
return (factinv[(x - 1) % MOD] * fact[y % MOD]) % MOD;
}
int main()
{
init();
int Q;
cin >> Q;
while (Q--)
{
ll N, X, D;
cin >> N >> X >> D;
if (D == 0)
{
cout << power(X, N) << endl;
}
else
{
X = (X * inv[D]) % MOD;
cout << (power(D, N) * exe(X, X + N - 1)) % MOD << endl;
}
}
}<commit_msg>submit E.cpp to 'E - Product of Arithmetic Progression' (m-solutions2019) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
* File : E.cpp
* Author : Kazune Takahashi
* Created : 2019-6-1 23:15:51
* Powered by Visual Studio Code
*/
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef long long ll;
/*
void Yes()
{
cout << "Yes" << endl;
exit(0);
}
void No()
{
cout << "No" << endl;
exit(0);
}
*/
/*
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
*/
// const ll MOD = 1000000007;
const int MAX_SIZE = 1000010;
const long long MOD = 1e6 + 3;
long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];
void init()
{
inv[1] = 1;
for (int i = 2; i < MAX_SIZE; i++)
{
inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD;
}
fact[0] = factinv[0] = 1;
for (int i = 1; i < MAX_SIZE; i++)
{
fact[i] = (i * fact[i - 1]) % MOD;
factinv[i] = (inv[i] * factinv[i - 1]) % MOD;
}
}
long long C(int n, int k)
{
if (n >= 0 && k >= 0 && n - k >= 0)
{
return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
}
return 0;
}
long long power(long long x, long long n)
{
if (n == 0)
{
return 1;
}
else if (n % 2 == 1)
{
return (x * power(x, n - 1)) % MOD;
}
else
{
long long half = power(x, n / 2);
return (half * half) % MOD;
}
}
long long gcd(long long x, long long y)
{
return y ? gcd(y, x % y) : x;
}
int main()
{
init();
int Q;
cin >> Q;
while (Q--)
{
ll x, d, n;
cin >> x >> d >> n;
if (d == 0)
{
cout << power(x, n) << endl;
continue;
}
else
{
x = (x * inv[d]) % MOD;
if (x + n - 1 >= MOD)
{
cout << 0 << endl;
continue;
}
ll ans = power(d, n);
ans *= (fact[x + n - 1] * factinv[x - 1]) % MOD;
ans %= MOD;
cout << ans << endl;
}
}
}<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
/*
* This file was originally written in pure C99, but later it had to be migrated to C++.
* In its current state it's kinda written in C99 with C++ features.
*
* This is not proper C++.
*/
#include <hal.h>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <cerrno>
#ifdef STM32F10X_XL
# error "Add support for XL devices"
#endif
/*
* The code below assumes that HSI oscillator is up and running,
* otherwise the Flash controller (FPEC) may misbehave.
* Any FPEC issues will be detected at run time during write/erase verification.
*/
#if !defined(RDP_KEY)
# define RDP_KEY 0x00A5
#endif
#if !defined(FLASH_KEY1)
# define FLASH_KEY1 0x45670123
# define FLASH_KEY2 0xCDEF89AB
#endif
#if !defined(FLASH_SR_WRPRTERR) // Compatibility
# define FLASH_SR_WRPRTERR FLASH_SR_WRPERR
#endif
#if !defined(FLASH_SR_PGERR)
# define FLASH_SR_PGERR (FLASH_SR_WRPERR | FLASH_SR_PGAERR | FLASH_SR_PGPERR | FLASH_SR_PGSERR)
#endif
#if defined(STM32F10X_HD) || defined(STM32F10X_HD_VL) || defined(STM32F10X_CL) || defined(STM32F10X_XL)
# define FLASH_SIZE (*((uint16_t*)0x1FFFF7E0))
# define FLASH_PAGE_SIZE 0x800
#elif defined(STM32F042x6) || defined(STM32F072xB)
# define FLASH_SIZE (*((uint16_t*)0x1FFFF7CC))
# define FLASH_PAGE_SIZE 0x400
#elif defined(STM32F373xC)
# define FLASH_SIZE (*((uint16_t*)0x1FFFF7CC))
# define FLASH_PAGE_SIZE 0x800
#elif defined(STM32F446xx)
/*
* TODO: This is wildly unoptimal - we're dedicating the entire 128k last sector for settings.
* Probably it's better to use one of the smaller 16K sectors for that!
*/
# define LAST_FLASH_PAGE_SIZE (128 * 1024)
# define FLASH_PAGE_ADR (FLASH_END - LAST_FLASH_PAGE_SIZE)
# define FLASH_PAGE_SNB_MASK (FLASH_CR_SNB_0 | FLASH_CR_SNB_1 | FLASH_CR_SNB_2)
# define DATA_SIZE_MAX LAST_FLASH_PAGE_SIZE
#else
# error Unknown device.
#endif
#if defined(FLASH_PAGE_SIZE) && defined(FLASH_SIZE) && !defined(FLASH_PAGE_ADR)
# define FLASH_END ((FLASH_SIZE * 1024) + FLASH_BASE)
# define FLASH_PAGE_ADR (FLASH_END - FLASH_PAGE_SIZE)
# define DATA_SIZE_MAX FLASH_PAGE_SIZE
#endif
static void waitReady(void)
{
do
{
assert(!(FLASH->SR & FLASH_SR_PGERR));
assert(!(FLASH->SR & FLASH_SR_WRPRTERR));
}
while (FLASH->SR & FLASH_SR_BSY);
FLASH->SR |= FLASH_SR_EOP;
}
static void prologue(void)
{
chSysLock();
waitReady();
if (FLASH->CR & FLASH_CR_LOCK)
{
FLASH->KEYR = FLASH_KEY1;
FLASH->KEYR = FLASH_KEY2;
}
FLASH->SR |= FLASH_SR_EOP | FLASH_SR_PGERR | FLASH_SR_WRPRTERR; // Reset flags
FLASH->CR = 0;
}
static void epilogue(void)
{
FLASH->CR = FLASH_CR_LOCK; // Reset the FPEC configuration and lock
chSysUnlock();
}
int configStorageRead(unsigned offset, void* data, unsigned len)
{
if (!data || (offset + len) > DATA_SIZE_MAX)
{
assert(0);
return -EINVAL;
}
/*
* Read directly, FPEC is not involved
*/
std::memcpy(data, (void*)(FLASH_PAGE_ADR + offset), len);
return 0;
}
int configStorageWrite(unsigned offset, const void* data, unsigned len)
{
if (!data || (offset + len) > DATA_SIZE_MAX)
{
assert(0);
return -EINVAL;
}
/*
* Data alignment
*/
if (((size_t)data) % 2)
{
assert(0);
return -EIO;
}
unsigned num_data_halfwords = len / 2;
if (num_data_halfwords * 2 < len)
{
num_data_halfwords += 1;
}
/*
* Write
*/
prologue();
FLASH->CR = FLASH_CR_PG;
volatile uint16_t* flashptr16 = (uint16_t*)(FLASH_PAGE_ADR + offset);
const uint16_t* ramptr16 = (const uint16_t*)data;
for (unsigned i = 0; i < num_data_halfwords; i++)
{
*flashptr16++ = *ramptr16++;
waitReady();
}
waitReady();
FLASH->CR = 0;
epilogue();
/*
* Verify
*/
const int cmpres = memcmp(data, (void*)(FLASH_PAGE_ADR + offset), len);
return cmpres ? -EIO : 0;
}
int configStorageErase(void)
{
/*
* Erase
*/
prologue();
#ifdef FLASH_CR_PER
FLASH->CR = FLASH_CR_PER;
FLASH->AR = FLASH_PAGE_ADR;
#else
FLASH->CR = FLASH_CR_SER | FLASH_PAGE_SNB_MASK;
#endif
FLASH->CR |= FLASH_CR_STRT;
waitReady();
FLASH->CR = 0;
epilogue();
/*
* Verify
*/
for (int i = 0; i < DATA_SIZE_MAX; i++)
{
uint8_t* ptr = (uint8_t*)(FLASH_PAGE_ADR + i);
if (*ptr != 0xFF)
{
return -EIO;
}
}
return 0;
}
<commit_msg>Refactored configuration storage<commit_after>/*
* Copyright (c) 2014 Zubax, zubax.com
* Distributed under the MIT License, available in the file LICENSE.
* Author: Pavel Kirienko <pavel.kirienko@zubax.com>
*/
/*
* This file was originally written in pure C99, but later it had to be migrated to C++.
* In its current state it's kinda written in C99 with C++ features.
*
* This is not proper C++.
*/
#include <hal.h>
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <cerrno>
/*
* The code below assumes that HSI oscillator is up and running,
* otherwise the Flash controller (FPEC) may misbehave.
* Any FPEC issues will be detected at run time during write/erase verification.
*/
#if !defined(RDP_KEY)
# define RDP_KEY 0x00A5
#endif
#if !defined(FLASH_KEY1)
# define FLASH_KEY1 0x45670123
# define FLASH_KEY2 0xCDEF89AB
#endif
#if !defined(FLASH_SR_WRPRTERR) // Compatibility
# define FLASH_SR_WRPRTERR FLASH_SR_WRPERR
#endif
namespace os
{
namespace config
{
/**
* These values should be defined elsewhere in the application.
* @{
*/
extern const unsigned StorageAddress;
extern const unsigned StorageSize;
extern const unsigned StorageSectorNumber;
/**
* @}
*/
}
}
using namespace os::config;
static void checkInvariants(void)
{
assert(StorageAddress % 256 == 0);
assert(StorageSize % 256 == 0);
assert(StorageAddress > 0);
assert(StorageSize > 0);
assert(StorageSectorNumber > 0);
}
static void waitReady(void)
{
do
{
assert(!(FLASH->SR & FLASH_SR_WRPRTERR));
assert(!(FLASH->SR & FLASH_SR_PGAERR));
assert(!(FLASH->SR & FLASH_SR_PGPERR));
assert(!(FLASH->SR & FLASH_SR_PGSERR));
}
while (FLASH->SR & FLASH_SR_BSY);
FLASH->SR |= FLASH_SR_EOP;
}
static void prologue(void)
{
checkInvariants();
chSysLock();
waitReady();
if (FLASH->CR & FLASH_CR_LOCK)
{
FLASH->KEYR = FLASH_KEY1;
FLASH->KEYR = FLASH_KEY2;
}
FLASH->SR |= FLASH_SR_EOP | FLASH_SR_WRPRTERR | FLASH_SR_PGAERR | FLASH_SR_PGPERR | FLASH_SR_PGSERR;
FLASH->CR = 0;
}
static void epilogue(void)
{
FLASH->CR = FLASH_CR_LOCK; // Reset the FPEC configuration and lock
chSysUnlock();
}
int configStorageRead(unsigned offset, void* data, unsigned len)
{
checkInvariants();
if (!data || (offset + len) > StorageSize)
{
assert(0);
return -EINVAL;
}
/*
* Read directly, FPEC is not involved
*/
std::memcpy(data, (void*)(StorageAddress + offset), len);
return 0;
}
int configStorageWrite(unsigned offset, const void* data, unsigned len)
{
if (!data || (offset + len) > StorageSize)
{
assert(0);
return -EINVAL;
}
/*
* Data alignment
*/
if (((size_t)data) % 2)
{
assert(0);
return -EIO;
}
unsigned num_data_halfwords = len / 2;
if (num_data_halfwords * 2 < len)
{
num_data_halfwords += 1;
}
/*
* Write
*/
prologue();
#ifdef FLASH_CR_PSIZE_0
FLASH->CR = FLASH_CR_PG | FLASH_CR_PSIZE_0;
#else
FLASH->CR = FLASH_CR_PG;
#endif
volatile uint16_t* flashptr16 = (uint16_t*)(StorageAddress + offset);
const uint16_t* ramptr16 = (const uint16_t*)data;
for (unsigned i = 0; i < num_data_halfwords; i++)
{
*flashptr16++ = *ramptr16++;
waitReady();
}
waitReady();
FLASH->CR = 0;
epilogue();
/*
* Verify
*/
const int cmpres = memcmp(data, (void*)(StorageAddress + offset), len);
return cmpres ? -EIO : 0;
}
int configStorageErase(void)
{
/*
* Erase
*/
prologue();
#ifdef FLASH_CR_PER
FLASH->CR = FLASH_CR_PER;
FLASH->AR = StorageAddress;
#else
FLASH->CR = FLASH_CR_SER | ((StorageSectorNumber) << 3);
#endif
FLASH->CR |= FLASH_CR_STRT;
waitReady();
FLASH->CR = 0;
epilogue();
/*
* Verify
*/
for (unsigned i = 0; i < StorageSize; i++)
{
uint8_t* ptr = (uint8_t*)(StorageAddress + i);
if (*ptr != 0xFF)
{
return -EIO;
}
}
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright 2009 University of Helsinki
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This is a toy commandline utility for testing spellers on standard io.
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#if HAVE_GETOPT_H
# include <getopt.h>
#endif
#ifdef WINDOWS
# include <windows.h>
#endif
#include "ol-exceptions.h"
#include "ospell.h"
#include "ZHfstOspeller.h"
using hfst_ol::ZHfstOspeller;
using hfst_ol::Transducer;
static bool quiet = false;
static bool verbose = false;
static bool analyse = false;
static unsigned long suggs = 0;
#ifdef WINDOWS
static bool output_to_console = false;
#endif
#ifdef WINDOWS
static std::string wide_string_to_string(const std::wstring & wstr)
{
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)§wstr.size(), NULL, 0, NULL, NULL);
std::string str( size_needed, 0 );
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &str[0], size_needed, NULL, NULL);
return str;
}
#endif
static int hfst_fprintf(FILE * stream, const char * format, ...)
{
va_list args;
va_start(args, format);
#ifdef WINDOWS
if (output_to_console && (stream == stdout || stream == stderr))
{
char buffer [1024];
int r = vsprintf(buffer, format, args);
va_end(args);
if (r < 0)
return r;
HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if (stream == stderr)
stdHandle = GetStdHandle(STD_ERROR_HANDLE);
std::string pstr(buffer);
DWORD numWritten = 0;
int wchars_num =
MultiByteToWideChar(CP_UTF8 , 0 , pstr.c_str() , -1, NULL , 0 );
wchar_t* wstr = new wchar_t[wchars_num];
MultiByteToWideChar(CP_UTF8 , 0 ,
pstr.c_str() , -1, wstr , wchars_num );
int retval = WriteConsoleW(stdHandle, wstr, wchars_num-1, &numWritten, NULL);
delete[] wstr;
return retval;
}
else
{
int retval = vfprintf(stream, format, args);
va_end(args);
return retval;
}
#else
int retval = vfprintf(stream, format, args);
va_end(args);
return retval;
#endif
}
bool print_usage(void)
{
std::cout <<
"\n" <<
"Usage: " << PACKAGE_NAME << " [OPTIONS] ZHFST-ARCHIVE\n" <<
"Use automata in ZHFST-ARCHIVE to check and correct\n"
"\n" <<
" -h, --help Print this help message\n" <<
" -V, --version Print version information\n" <<
" -v, --verbose Be verbose\n" <<
" -q, --quiet Don't be verbose (default)\n" <<
" -s, --silent Same as quiet\n" <<
" -a, --analyse Analyse strings and corrections\n" <<
#ifdef WINDOWS
" -k, --output-to-console Print output to console (Windows-specific)" <<
#endif
"\n" <<
"\n" <<
"Report bugs to " << PACKAGE_BUGREPORT << "\n" <<
"\n";
return true;
}
bool print_version(void)
{
std::cout <<
"\n" <<
PACKAGE_STRING << std::endl <<
__DATE__ << " " __TIME__ << std::endl <<
"copyright (C) 2009 - 2014 University of Helsinki\n";
return true;
}
bool print_short_help(void)
{
print_usage();
return true;
}
void
do_spell(ZHfstOspeller& speller, const std::string& str)
{
if (speller.spell(str))
{
(void)hfst_fprintf(stdout, "\"%s\" is in the lexicon... ",
str.c_str());
if (analyse)
{
(void)hfst_fprintf(stdout, "analysing:\n");
hfst_ol::AnalysisQueue anals = speller.analyse(str, false);
bool all_no_spell = true;
while (anals.size() > 0)
{
if (anals.top().first.find("Use/-Spell") != std::string::npos)
{
(void)hfst_fprintf(stdout,
"%s %f [DISCARDED AS -Spell]\n",
anals.top().first.c_str(),
anals.top().second);
}
else
{
all_no_spell = false;
(void)hfst_fprintf(stdout, "%s %f\n",
anals.top().first.c_str(),
anals.top().second);
}
anals.pop();
}
if (all_no_spell)
{
hfst_fprintf(stdout,
"All spellings were invalidated by analysis! "
".:. Not in lexicon!\n");
}
}
(void)hfst_fprintf(stdout, "(but correcting anyways)\n", str.c_str());
}
else
{
(void)hfst_fprintf(stdout, "\"%s\" is NOT in the lexicon:\n",
str.c_str());
}
hfst_ol::CorrectionQueue corrections = speller.suggest(str);
if (corrections.size() > 0)
{
(void)hfst_fprintf(stdout, "Corrections for \"%s\":\n", str.c_str());
while (corrections.size() > 0)
{
const std::string& corr = corrections.top().first;
if (analyse)
{
hfst_ol::AnalysisQueue anals = speller.analyse(corr, true);
bool all_discarded = true;
while (anals.size() > 0)
{
if (anals.top().first.find("Use/SpellNoSugg") !=
std::string::npos)
{
(void)hfst_fprintf(stdout, "%s %f %s "
"[DISCARDED BY ANALYSES]\n",
corr.c_str(), corrections.top().second,
anals.top().first.c_str());
}
else
{
all_discarded = false;
(void)hfst_fprintf(stdout, "%s %f %s\n",
corr.c_str(), corrections.top().second,
anals.top().first.c_str());
}
anals.pop();
}
if (all_discarded)
{
(void)hfst_fprintf(stdout, "All corrections were "
"invalidated by analysis! "
"No score!\n");
}
}
else
{
(void)hfst_fprintf(stdout, "%s %f\n",
corr.c_str(),
corrections.top().second);
}
corrections.pop();
}
(void)hfst_fprintf(stdout, "\n");
}
else
{
(void)hfst_fprintf(stdout,
"Unable to correct \"%s\"!\n\n", str.c_str());
}
}
int
zhfst_spell(char* zhfst_filename)
{
ZHfstOspeller speller;
try
{
speller.read_zhfst(zhfst_filename);
}
catch (hfst_ol::ZHfstMetaDataParsingError zhmdpe)
{
(void)hfst_fprintf(stderr, "cannot finish reading zhfst archive %s:\n%s.\n",
zhfst_filename, zhmdpe.what());
//std::cerr << "cannot finish reading zhfst archive " << zhfst_filename <<
// ":\n" << zhmdpe.what() << "." << std::endl;
return EXIT_FAILURE;
}
catch (hfst_ol::ZHfstZipReadingError zhzre)
{
//std::cerr << "cannot read zhfst archive " << zhfst_filename << ":\n"
// << zhzre.what() << "." << std::endl
// << "trying to read as legacy automata directory" << std::endl;
(void)hfst_fprintf(stderr,
"cannot read zhfst archive %s:\n"
"%s.\n",
zhfst_filename, zhzre.what());
return EXIT_FAILURE;
}
catch (hfst_ol::ZHfstXmlParsingError zhxpe)
{
//std::cerr << "Cannot finish reading index.xml from "
// << zhfst_filename << ":" << std::endl
// << zhxpe.what() << "." << std::endl;
(void)hfst_fprintf(stderr,
"Cannot finish reading index.xml from %s:\n"
"%s.\n",
zhfst_filename, zhxpe.what());
return EXIT_FAILURE;
}
if (verbose)
{
//std::cout << "Following metadata was read from ZHFST archive:" << std::endl
// << speller.metadata_dump() << std::endl;
(void)hfst_fprintf(stdout,
"Following metadata was read from ZHFST archive:\n"
"%s\n",
speller.metadata_dump().c_str());
}
speller.set_queue_limit(suggs);
if (verbose)
{
hfst_fprintf(stdout, "Printing only %lu top suggestions per line\n", suggs);
}
char * str = (char*) malloc(2000);
#ifdef WINDOWS
SetConsoleCP(65001);
const HANDLE stdIn = GetStdHandle(STD_INPUT_HANDLE);
WCHAR buffer[0x1000];
DWORD numRead = 0;
while (ReadConsoleW(stdIn, buffer, sizeof buffer, &numRead, NULL))
{
std::wstring wstr(buffer, numRead-1); // skip the newline
std::string linestr = wide_string_to_string(wstr);
free(str);
str = strdup(linestr.c_str());
#else
while (!std::cin.eof()) {
std::cin.getline(str, 2000);
#endif
if (str[0] == '\0') {
continue;
}
if (str[strlen(str) - 1] == '\r')
{
#ifdef WINDOWS
str[strlen(str) - 1] = '\0';
#else
(void)hfst_fprintf(stderr, "There is a WINDOWS linebreak in this file\n"
"Please convert with dos2unix or fromdos\n");
exit(1);
#endif
}
do_spell(speller, str);
}
free(str);
return EXIT_SUCCESS;
}
int main(int argc, char **argv)
{
int c;
//std::locale::global(std::locale(""));
#if HAVE_GETOPT_H
while (true) {
static struct option long_options[] =
{
// first the hfst-mandated options
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{"quiet", no_argument, 0, 'q'},
{"silent", no_argument, 0, 's'},
{"analyse", no_argument, 0, 'a'},
{"limit", required_argument, 0, 'n'},
#ifdef WINDOWS
{"output-to-console", no_argument, 0, 'k'},
#endif
{0, 0, 0, 0 }
};
int option_index = 0;
c = getopt_long(argc, argv, "hVvqskan:", long_options, &option_index);
char* endptr = 0;
if (c == -1) // no more options to look at
break;
switch (c) {
case 'h':
print_usage();
return EXIT_SUCCESS;
break;
case 'V':
print_version();
return EXIT_SUCCESS;
break;
case 'v':
verbose = true;
quiet = false;
break;
case 'q': // fallthrough
case 's':
quiet = true;
verbose = false;
break;
case 'a':
analyse = true;
break;
case 'n':
suggs = strtoul(optarg, &endptr, 10);
if (endptr == optarg)
{
fprintf(stderr, "%s not a strtoul number\n", optarg);
exit(1);
}
else if (*endptr != '\0')
{
fprintf(stderr, "%s truncated from limit parameter\n", endptr);
}
break;
#ifdef WINDOWS
case 'k':
output_to_console = true;
break;
#endif
default:
std::cerr << "Invalid option\n\n";
print_short_help();
return EXIT_FAILURE;
break;
}
}
#else
int optind = 1;
#endif
// no more options, we should now be at the input filenames
if (optind == (argc - 1))
{
return zhfst_spell(argv[optind]);
}
else if (optind < (argc - 1))
{
std::cerr << "Too many file parameters" << std::endl;
print_short_help();
return EXIT_FAILURE;
}
else if (optind >= argc)
{
std::cerr << "Give full path to a zhfst speller"
<< std::endl;
print_short_help();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Missing stdarg reqd in >gcc 4.8 or somesuch<commit_after>/*
Copyright 2009 University of Helsinki
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/*
This is a toy commandline utility for testing spellers on standard io.
*/
#if HAVE_CONFIG_H
# include <config.h>
#endif
#if HAVE_GETOPT_H
# include <getopt.h>
#endif
#ifdef WINDOWS
# include <windows.h>
#endif
#include <stdarg.h>
#include "ol-exceptions.h"
#include "ospell.h"
#include "ZHfstOspeller.h"
using hfst_ol::ZHfstOspeller;
using hfst_ol::Transducer;
static bool quiet = false;
static bool verbose = false;
static bool analyse = false;
static unsigned long suggs = 0;
#ifdef WINDOWS
static bool output_to_console = false;
#endif
#ifdef WINDOWS
static std::string wide_string_to_string(const std::wstring & wstr)
{
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)§wstr.size(), NULL, 0, NULL, NULL);
std::string str( size_needed, 0 );
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &str[0], size_needed, NULL, NULL);
return str;
}
#endif
static int hfst_fprintf(FILE * stream, const char * format, ...)
{
va_list args;
va_start(args, format);
#ifdef WINDOWS
if (output_to_console && (stream == stdout || stream == stderr))
{
char buffer [1024];
int r = vsprintf(buffer, format, args);
va_end(args);
if (r < 0)
return r;
HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);
if (stream == stderr)
stdHandle = GetStdHandle(STD_ERROR_HANDLE);
std::string pstr(buffer);
DWORD numWritten = 0;
int wchars_num =
MultiByteToWideChar(CP_UTF8 , 0 , pstr.c_str() , -1, NULL , 0 );
wchar_t* wstr = new wchar_t[wchars_num];
MultiByteToWideChar(CP_UTF8 , 0 ,
pstr.c_str() , -1, wstr , wchars_num );
int retval = WriteConsoleW(stdHandle, wstr, wchars_num-1, &numWritten, NULL);
delete[] wstr;
return retval;
}
else
{
int retval = vfprintf(stream, format, args);
va_end(args);
return retval;
}
#else
int retval = vfprintf(stream, format, args);
va_end(args);
return retval;
#endif
}
bool print_usage(void)
{
std::cout <<
"\n" <<
"Usage: " << PACKAGE_NAME << " [OPTIONS] ZHFST-ARCHIVE\n" <<
"Use automata in ZHFST-ARCHIVE to check and correct\n"
"\n" <<
" -h, --help Print this help message\n" <<
" -V, --version Print version information\n" <<
" -v, --verbose Be verbose\n" <<
" -q, --quiet Don't be verbose (default)\n" <<
" -s, --silent Same as quiet\n" <<
" -a, --analyse Analyse strings and corrections\n" <<
#ifdef WINDOWS
" -k, --output-to-console Print output to console (Windows-specific)" <<
#endif
"\n" <<
"\n" <<
"Report bugs to " << PACKAGE_BUGREPORT << "\n" <<
"\n";
return true;
}
bool print_version(void)
{
std::cout <<
"\n" <<
PACKAGE_STRING << std::endl <<
__DATE__ << " " __TIME__ << std::endl <<
"copyright (C) 2009 - 2014 University of Helsinki\n";
return true;
}
bool print_short_help(void)
{
print_usage();
return true;
}
void
do_spell(ZHfstOspeller& speller, const std::string& str)
{
if (speller.spell(str))
{
(void)hfst_fprintf(stdout, "\"%s\" is in the lexicon... ",
str.c_str());
if (analyse)
{
(void)hfst_fprintf(stdout, "analysing:\n");
hfst_ol::AnalysisQueue anals = speller.analyse(str, false);
bool all_no_spell = true;
while (anals.size() > 0)
{
if (anals.top().first.find("Use/-Spell") != std::string::npos)
{
(void)hfst_fprintf(stdout,
"%s %f [DISCARDED AS -Spell]\n",
anals.top().first.c_str(),
anals.top().second);
}
else
{
all_no_spell = false;
(void)hfst_fprintf(stdout, "%s %f\n",
anals.top().first.c_str(),
anals.top().second);
}
anals.pop();
}
if (all_no_spell)
{
hfst_fprintf(stdout,
"All spellings were invalidated by analysis! "
".:. Not in lexicon!\n");
}
}
(void)hfst_fprintf(stdout, "(but correcting anyways)\n", str.c_str());
}
else
{
(void)hfst_fprintf(stdout, "\"%s\" is NOT in the lexicon:\n",
str.c_str());
}
hfst_ol::CorrectionQueue corrections = speller.suggest(str);
if (corrections.size() > 0)
{
(void)hfst_fprintf(stdout, "Corrections for \"%s\":\n", str.c_str());
while (corrections.size() > 0)
{
const std::string& corr = corrections.top().first;
if (analyse)
{
hfst_ol::AnalysisQueue anals = speller.analyse(corr, true);
bool all_discarded = true;
while (anals.size() > 0)
{
if (anals.top().first.find("Use/SpellNoSugg") !=
std::string::npos)
{
(void)hfst_fprintf(stdout, "%s %f %s "
"[DISCARDED BY ANALYSES]\n",
corr.c_str(), corrections.top().second,
anals.top().first.c_str());
}
else
{
all_discarded = false;
(void)hfst_fprintf(stdout, "%s %f %s\n",
corr.c_str(), corrections.top().second,
anals.top().first.c_str());
}
anals.pop();
}
if (all_discarded)
{
(void)hfst_fprintf(stdout, "All corrections were "
"invalidated by analysis! "
"No score!\n");
}
}
else
{
(void)hfst_fprintf(stdout, "%s %f\n",
corr.c_str(),
corrections.top().second);
}
corrections.pop();
}
(void)hfst_fprintf(stdout, "\n");
}
else
{
(void)hfst_fprintf(stdout,
"Unable to correct \"%s\"!\n\n", str.c_str());
}
}
int
zhfst_spell(char* zhfst_filename)
{
ZHfstOspeller speller;
try
{
speller.read_zhfst(zhfst_filename);
}
catch (hfst_ol::ZHfstMetaDataParsingError zhmdpe)
{
(void)hfst_fprintf(stderr, "cannot finish reading zhfst archive %s:\n%s.\n",
zhfst_filename, zhmdpe.what());
//std::cerr << "cannot finish reading zhfst archive " << zhfst_filename <<
// ":\n" << zhmdpe.what() << "." << std::endl;
return EXIT_FAILURE;
}
catch (hfst_ol::ZHfstZipReadingError zhzre)
{
//std::cerr << "cannot read zhfst archive " << zhfst_filename << ":\n"
// << zhzre.what() << "." << std::endl
// << "trying to read as legacy automata directory" << std::endl;
(void)hfst_fprintf(stderr,
"cannot read zhfst archive %s:\n"
"%s.\n",
zhfst_filename, zhzre.what());
return EXIT_FAILURE;
}
catch (hfst_ol::ZHfstXmlParsingError zhxpe)
{
//std::cerr << "Cannot finish reading index.xml from "
// << zhfst_filename << ":" << std::endl
// << zhxpe.what() << "." << std::endl;
(void)hfst_fprintf(stderr,
"Cannot finish reading index.xml from %s:\n"
"%s.\n",
zhfst_filename, zhxpe.what());
return EXIT_FAILURE;
}
if (verbose)
{
//std::cout << "Following metadata was read from ZHFST archive:" << std::endl
// << speller.metadata_dump() << std::endl;
(void)hfst_fprintf(stdout,
"Following metadata was read from ZHFST archive:\n"
"%s\n",
speller.metadata_dump().c_str());
}
speller.set_queue_limit(suggs);
if (verbose)
{
hfst_fprintf(stdout, "Printing only %lu top suggestions per line\n", suggs);
}
char * str = (char*) malloc(2000);
#ifdef WINDOWS
SetConsoleCP(65001);
const HANDLE stdIn = GetStdHandle(STD_INPUT_HANDLE);
WCHAR buffer[0x1000];
DWORD numRead = 0;
while (ReadConsoleW(stdIn, buffer, sizeof buffer, &numRead, NULL))
{
std::wstring wstr(buffer, numRead-1); // skip the newline
std::string linestr = wide_string_to_string(wstr);
free(str);
str = strdup(linestr.c_str());
#else
while (!std::cin.eof()) {
std::cin.getline(str, 2000);
#endif
if (str[0] == '\0') {
continue;
}
if (str[strlen(str) - 1] == '\r')
{
#ifdef WINDOWS
str[strlen(str) - 1] = '\0';
#else
(void)hfst_fprintf(stderr, "There is a WINDOWS linebreak in this file\n"
"Please convert with dos2unix or fromdos\n");
exit(1);
#endif
}
do_spell(speller, str);
}
free(str);
return EXIT_SUCCESS;
}
int main(int argc, char **argv)
{
int c;
//std::locale::global(std::locale(""));
#if HAVE_GETOPT_H
while (true) {
static struct option long_options[] =
{
// first the hfst-mandated options
{"help", no_argument, 0, 'h'},
{"version", no_argument, 0, 'V'},
{"verbose", no_argument, 0, 'v'},
{"quiet", no_argument, 0, 'q'},
{"silent", no_argument, 0, 's'},
{"analyse", no_argument, 0, 'a'},
{"limit", required_argument, 0, 'n'},
#ifdef WINDOWS
{"output-to-console", no_argument, 0, 'k'},
#endif
{0, 0, 0, 0 }
};
int option_index = 0;
c = getopt_long(argc, argv, "hVvqskan:", long_options, &option_index);
char* endptr = 0;
if (c == -1) // no more options to look at
break;
switch (c) {
case 'h':
print_usage();
return EXIT_SUCCESS;
break;
case 'V':
print_version();
return EXIT_SUCCESS;
break;
case 'v':
verbose = true;
quiet = false;
break;
case 'q': // fallthrough
case 's':
quiet = true;
verbose = false;
break;
case 'a':
analyse = true;
break;
case 'n':
suggs = strtoul(optarg, &endptr, 10);
if (endptr == optarg)
{
fprintf(stderr, "%s not a strtoul number\n", optarg);
exit(1);
}
else if (*endptr != '\0')
{
fprintf(stderr, "%s truncated from limit parameter\n", endptr);
}
break;
#ifdef WINDOWS
case 'k':
output_to_console = true;
break;
#endif
default:
std::cerr << "Invalid option\n\n";
print_short_help();
return EXIT_FAILURE;
break;
}
}
#else
int optind = 1;
#endif
// no more options, we should now be at the input filenames
if (optind == (argc - 1))
{
return zhfst_spell(argv[optind]);
}
else if (optind < (argc - 1))
{
std::cerr << "Too many file parameters" << std::endl;
print_short_help();
return EXIT_FAILURE;
}
else if (optind >= argc)
{
std::cerr << "Give full path to a zhfst speller"
<< std::endl;
print_short_help();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// MIT License
//
// Copyright (c) 2016-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <tacopie/error.hpp>
#include <tacopie/logger.hpp>
#include <tacopie/network/io_service.hpp>
#include <fcntl.h>
#include <io.h>
namespace tacopie {
//!
//! default io_service getter & setter
//!
static std::shared_ptr<io_service> io_service_default_instance = nullptr;
const std::shared_ptr<io_service>&
get_default_io_service(void) {
if (io_service_default_instance == nullptr) { io_service_default_instance = std::make_shared<io_service>(); }
return io_service_default_instance;
}
void
set_default_io_service(const std::shared_ptr<io_service>& service) {
if (service) {
__TACOPIE_LOG(debug, "setting new default_io_service");
io_service_default_instance = service;
}
else {
__TACOPIE_LOG(warn, "setting new default_io_service failed because the service is null");
}
}
//!
//! ctor & dtor
//!
io_service::io_service(void)
: m_should_stop(ATOMIC_VAR_INIT(false))
, m_callback_workers(__TACOPIE_IO_SERVICE_NB_WORKERS) {
__TACOPIE_LOG(debug, "create io_service");
//! Start worker after everything has been initialized
m_poll_worker = std::thread(std::bind(&io_service::poll, this));
}
io_service::~io_service(void) {
__TACOPIE_LOG(debug, "destroy io_service");
m_should_stop = true;
m_notifier.notify();
m_poll_worker.join();
m_callback_workers.stop();
}
//!
//! poll worker function
//!
void
io_service::poll(void) {
__TACOPIE_LOG(debug, "starting poll() worker");
while (!m_should_stop) {
int ndfs = init_poll_fds_info();
__TACOPIE_LOG(debug, "polling fds");
if (select(ndfs, &m_rd_set, &m_wr_set, NULL, NULL) > 0) { process_events(); }
else {
__TACOPIE_LOG(debug, "poll woke up, but nothing to process");
}
}
__TACOPIE_LOG(debug, "stop poll() worker");
}
//!
//! process poll detected events
//!
void
io_service::process_events(void) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
__TACOPIE_LOG(debug, "processing events");
for (const auto& fd : m_polled_fds) {
if (fd == m_notifier.get_read_fd() && FD_ISSET(fd, &m_rd_set)) {
m_notifier.clr_buffer();
continue;
}
auto it = m_tracked_sockets.find(fd);
if (it == m_tracked_sockets.end()) { continue; }
auto& socket = it->second;
if (FD_ISSET(fd, &m_rd_set) && socket.rd_callback && !socket.is_executing_rd_callback) { process_rd_event(fd, socket); }
if (FD_ISSET(fd, &m_wr_set) && socket.wr_callback && !socket.is_executing_wr_callback) { process_wr_event(fd, socket); }
if (socket.marked_for_untrack && !socket.is_executing_rd_callback && !socket.is_executing_wr_callback) {
__TACOPIE_LOG(debug, "untrack socket");
m_tracked_sockets.erase(it);
m_wait_for_removal_condvar.notify_all();
}
}
}
void
io_service::process_rd_event(const fd_t& fd, tracked_socket& socket) {
__TACOPIE_LOG(debug, "processing read event");
auto rd_callback = socket.rd_callback;
socket.is_executing_rd_callback = true;
m_callback_workers << [=] {
__TACOPIE_LOG(debug, "execute read callback");
rd_callback(fd);
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
auto it = m_tracked_sockets.find(fd);
if (it == m_tracked_sockets.end()) { return; }
auto& socket = it->second;
socket.is_executing_rd_callback = false;
if (socket.marked_for_untrack && !socket.is_executing_wr_callback) {
__TACOPIE_LOG(debug, "untrack socket");
m_tracked_sockets.erase(it);
m_wait_for_removal_condvar.notify_all();
}
m_notifier.notify();
};
}
void
io_service::process_wr_event(const fd_t& fd, tracked_socket& socket) {
__TACOPIE_LOG(debug, "processing write event");
auto wr_callback = socket.wr_callback;
socket.is_executing_wr_callback = true;
m_callback_workers << [=] {
__TACOPIE_LOG(debug, "execute write callback");
wr_callback(fd);
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
auto it = m_tracked_sockets.find(fd);
if (it == m_tracked_sockets.end()) { return; }
auto& socket = it->second;
socket.is_executing_wr_callback = false;
if (socket.marked_for_untrack && !socket.is_executing_rd_callback) {
__TACOPIE_LOG(debug, "untrack socket");
m_tracked_sockets.erase(it);
m_wait_for_removal_condvar.notify_all();
}
m_notifier.notify();
};
}
//!
//! init m_poll_fds_info
//!
int
io_service::init_poll_fds_info(void) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
m_polled_fds.clear();
FD_ZERO(&m_rd_set);
FD_ZERO(&m_wr_set);
int ndfs = m_notifier.get_read_fd();
FD_SET(m_notifier.get_read_fd(), &m_rd_set);
m_polled_fds.push_back(m_notifier.get_read_fd());
for (const auto& socket : m_tracked_sockets) {
const auto& fd = socket.first;
const auto& socket_info = socket.second;
bool should_rd = socket_info.rd_callback && !socket_info.is_executing_rd_callback;
if (should_rd) { FD_SET(fd, &m_rd_set); }
bool should_wr = socket_info.wr_callback && !socket_info.is_executing_wr_callback;
if (should_wr) { FD_SET(fd, &m_wr_set); }
if (should_rd || should_wr || socket_info.marked_for_untrack) { m_polled_fds.push_back(fd); }
if ((should_rd || should_wr) && (int) fd > ndfs) { ndfs = fd; }
}
return ndfs + 1;
}
//!
//! track & untrack socket
//!
void
io_service::track(const tcp_socket& socket, const event_callback_t& rd_callback, const event_callback_t& wr_callback) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
__TACOPIE_LOG(debug, "track new socket");
auto& track_info = m_tracked_sockets[socket.get_fd()];
track_info.rd_callback = rd_callback;
track_info.wr_callback = wr_callback;
track_info.marked_for_untrack = false;
m_notifier.notify();
}
void
io_service::set_rd_callback(const tcp_socket& socket, const event_callback_t& event_callback) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
__TACOPIE_LOG(debug, "update read socket tracking callback");
auto& track_info = m_tracked_sockets[socket.get_fd()];
track_info.rd_callback = event_callback;
m_notifier.notify();
}
void
io_service::set_wr_callback(const tcp_socket& socket, const event_callback_t& event_callback) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
__TACOPIE_LOG(debug, "update write socket tracking callback");
auto& track_info = m_tracked_sockets[socket.get_fd()];
track_info.wr_callback = event_callback;
m_notifier.notify();
}
void
io_service::untrack(const tcp_socket& socket) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
auto it = m_tracked_sockets.find(socket.get_fd());
if (it == m_tracked_sockets.end()) { return; }
if (it->second.is_executing_rd_callback || it->second.is_executing_wr_callback) {
__TACOPIE_LOG(debug, "mark socket for untracking");
it->second.marked_for_untrack = true;
}
else {
__TACOPIE_LOG(debug, "untrack socket");
m_tracked_sockets.erase(it);
m_wait_for_removal_condvar.notify_all();
}
m_notifier.notify();
}
//!
//! wait until the socket has been effectively removed
//! basically wait until all pending callbacks are executed
//!
void
io_service::wait_for_removal(const tcp_socket& socket) {
std::unique_lock<std::mutex> lock(m_tracked_sockets_mtx);
m_wait_for_removal_condvar.wait(lock, [&]() {
return m_tracked_sockets.find(socket.get_fd()) == m_tracked_sockets.end();
});
}
} //! tacopie
<commit_msg>[2.4.3] port fixes to windows<commit_after>// MIT License
//
// Copyright (c) 2016-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <tacopie/error.hpp>
#include <tacopie/logger.hpp>
#include <tacopie/network/io_service.hpp>
#include <fcntl.h>
#include <io.h>
namespace tacopie {
//!
//! default io_service getter & setter
//!
static std::shared_ptr<io_service> io_service_default_instance = nullptr;
const std::shared_ptr<io_service>&
get_default_io_service(void) {
if (io_service_default_instance == nullptr) { io_service_default_instance = std::make_shared<io_service>(); }
return io_service_default_instance;
}
void
set_default_io_service(const std::shared_ptr<io_service>& service) {
if (service) {
__TACOPIE_LOG(debug, "setting new default_io_service");
io_service_default_instance = service;
}
else {
__TACOPIE_LOG(warn, "setting new default_io_service failed because the service is null");
}
}
//!
//! ctor & dtor
//!
io_service::io_service(void)
: m_should_stop(ATOMIC_VAR_INIT(false))
, m_callback_workers(__TACOPIE_IO_SERVICE_NB_WORKERS) {
__TACOPIE_LOG(debug, "create io_service");
//! Start worker after everything has been initialized
m_poll_worker = std::thread(std::bind(&io_service::poll, this));
}
io_service::~io_service(void) {
__TACOPIE_LOG(debug, "destroy io_service");
m_should_stop = true;
m_notifier.notify();
m_poll_worker.join();
m_callback_workers.stop();
}
//!
//! poll worker function
//!
void
io_service::poll(void) {
__TACOPIE_LOG(debug, "starting poll() worker");
while (!m_should_stop) {
int ndfs = init_poll_fds_info();
//! setup timeout
struct timeval* timeout_ptr = NULL;
#ifdef __TACOPIE_TIMEOUT
struct timeval timeout;
timeout.tv_usec = __TACOPIE_TIMEOUT;
timeout_ptr = &timeout;
#endif /* __TACOPIE_TIMEOUT */
__TACOPIE_LOG(debug, "polling fds");
if (select(ndfs, &m_rd_set, &m_wr_set, NULL, timeout_ptr) > 0) { process_events(); }
else {
__TACOPIE_LOG(debug, "poll woke up, but nothing to process");
}
}
__TACOPIE_LOG(debug, "stop poll() worker");
}
//!
//! process poll detected events
//!
void
io_service::process_events(void) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
__TACOPIE_LOG(debug, "processing events");
for (const auto& fd : m_polled_fds) {
if (fd == m_notifier.get_read_fd() && FD_ISSET(fd, &m_rd_set)) {
m_notifier.clr_buffer();
continue;
}
auto it = m_tracked_sockets.find(fd);
if (it == m_tracked_sockets.end()) { continue; }
auto& socket = it->second;
if (FD_ISSET(fd, &m_rd_set) && socket.rd_callback && !socket.is_executing_rd_callback) { process_rd_event(fd, socket); }
if (FD_ISSET(fd, &m_wr_set) && socket.wr_callback && !socket.is_executing_wr_callback) { process_wr_event(fd, socket); }
if (socket.marked_for_untrack && !socket.is_executing_rd_callback && !socket.is_executing_wr_callback) {
__TACOPIE_LOG(debug, "untrack socket");
m_tracked_sockets.erase(it);
m_wait_for_removal_condvar.notify_all();
}
}
}
void
io_service::process_rd_event(const fd_t& fd, tracked_socket& socket) {
__TACOPIE_LOG(debug, "processing read event");
auto rd_callback = socket.rd_callback;
socket.is_executing_rd_callback = true;
m_callback_workers << [=] {
__TACOPIE_LOG(debug, "execute read callback");
rd_callback(fd);
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
auto it = m_tracked_sockets.find(fd);
if (it == m_tracked_sockets.end()) { return; }
auto& socket = it->second;
socket.is_executing_rd_callback = false;
if (socket.marked_for_untrack && !socket.is_executing_wr_callback) {
__TACOPIE_LOG(debug, "untrack socket");
m_tracked_sockets.erase(it);
m_wait_for_removal_condvar.notify_all();
}
};
}
void
io_service::process_wr_event(const fd_t& fd, tracked_socket& socket) {
__TACOPIE_LOG(debug, "processing write event");
auto wr_callback = socket.wr_callback;
socket.is_executing_wr_callback = true;
m_callback_workers << [=] {
__TACOPIE_LOG(debug, "execute write callback");
wr_callback(fd);
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
auto it = m_tracked_sockets.find(fd);
if (it == m_tracked_sockets.end()) { return; }
auto& socket = it->second;
socket.is_executing_wr_callback = false;
if (socket.marked_for_untrack && !socket.is_executing_rd_callback) {
__TACOPIE_LOG(debug, "untrack socket");
m_tracked_sockets.erase(it);
m_wait_for_removal_condvar.notify_all();
}
};
}
//!
//! init m_poll_fds_info
//!
int
io_service::init_poll_fds_info(void) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
m_polled_fds.clear();
FD_ZERO(&m_rd_set);
FD_ZERO(&m_wr_set);
int ndfs = m_notifier.get_read_fd();
FD_SET(m_notifier.get_read_fd(), &m_rd_set);
m_polled_fds.push_back(m_notifier.get_read_fd());
for (const auto& socket : m_tracked_sockets) {
const auto& fd = socket.first;
const auto& socket_info = socket.second;
bool should_rd = socket_info.rd_callback && !socket_info.is_executing_rd_callback;
if (should_rd) { FD_SET(fd, &m_rd_set); }
bool should_wr = socket_info.wr_callback && !socket_info.is_executing_wr_callback;
if (should_wr) { FD_SET(fd, &m_wr_set); }
if (should_rd || should_wr || socket_info.marked_for_untrack) { m_polled_fds.push_back(fd); }
if ((should_rd || should_wr) && (int) fd > ndfs) { ndfs = fd; }
}
return ndfs + 1;
}
//!
//! track & untrack socket
//!
void
io_service::track(const tcp_socket& socket, const event_callback_t& rd_callback, const event_callback_t& wr_callback) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
__TACOPIE_LOG(debug, "track new socket");
auto& track_info = m_tracked_sockets[socket.get_fd()];
track_info.rd_callback = rd_callback;
track_info.wr_callback = wr_callback;
track_info.marked_for_untrack = false;
m_notifier.notify();
}
void
io_service::set_rd_callback(const tcp_socket& socket, const event_callback_t& event_callback) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
__TACOPIE_LOG(debug, "update read socket tracking callback");
auto& track_info = m_tracked_sockets[socket.get_fd()];
track_info.rd_callback = event_callback;
m_notifier.notify();
}
void
io_service::set_wr_callback(const tcp_socket& socket, const event_callback_t& event_callback) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
__TACOPIE_LOG(debug, "update write socket tracking callback");
auto& track_info = m_tracked_sockets[socket.get_fd()];
track_info.wr_callback = event_callback;
m_notifier.notify();
}
void
io_service::untrack(const tcp_socket& socket) {
std::lock_guard<std::mutex> lock(m_tracked_sockets_mtx);
auto it = m_tracked_sockets.find(socket.get_fd());
if (it == m_tracked_sockets.end()) { return; }
if (it->second.is_executing_rd_callback || it->second.is_executing_wr_callback) {
__TACOPIE_LOG(debug, "mark socket for untracking");
it->second.marked_for_untrack = true;
}
else {
__TACOPIE_LOG(debug, "untrack socket");
m_tracked_sockets.erase(it);
m_wait_for_removal_condvar.notify_all();
}
m_notifier.notify();
}
//!
//! wait until the socket has been effectively removed
//! basically wait until all pending callbacks are executed
//!
void
io_service::wait_for_removal(const tcp_socket& socket) {
std::unique_lock<std::mutex> lock(m_tracked_sockets_mtx);
m_wait_for_removal_condvar.wait(lock, [&]() {
return m_tracked_sockets.find(socket.get_fd()) == m_tracked_sockets.end();
});
}
} // namespace tacopie
<|endoftext|> |
<commit_before>// main.cpp
// euler
//
// Created by Duncan Smith on 19/10/2013.
// Copyright (c) 2013 Duncan Smith. All rights reserved.
//
#include <iostream>
#include "projects.h"
int main(int argc, const char * argv[])
{
const int max_multiple = 1e6;
project_1(max_multiple);
project_1_s(max_multiple);
}
<commit_msg>rename project<commit_after>// main.cpp
// numbers
//
// Created by Duncan Smith on 19/10/2013.
// Copyright (c) 2013 Duncan Smith. All rights reserved.
//
#include <iostream>
#include "projects.h"
int main(int argc, const char * argv[])
{
const int max_multiple = 1e6;
project_1(max_multiple);
project_1_s(max_multiple);
}
<|endoftext|> |
<commit_before>/**
* @file
*
* @brief Source for yamlcpp plugin
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
// -- Imports ------------------------------------------------------------------------------------------------------------------------------
#include "yamlcpp.hpp"
#include "log.hpp"
#include "read.hpp"
#include "write.hpp"
#include <kdb.hpp>
#include <kdberrors.h>
#include <kdblogger.h>
#include "yaml-cpp/yaml.h"
using std::exception;
using std::overflow_error;
using YAML::BadFile;
using YAML::EmitterException;
using YAML::ParserException;
using YAML::RepresentationException;
using ckdb::Key;
using ckdb::keyNew;
using ckdb::KeySet;
using ckdb::Plugin;
using yamlcpp::yamlRead;
using yamlcpp::yamlWrite;
// -- Functions ----------------------------------------------------------------------------------------------------------------------------
namespace
{
/**
* @brief This function returns a key set containing the contract of this plugin.
*
* @return A contract describing the functionality of this plugin.
*/
kdb::KeySet contractYamlCpp (void)
{
return kdb::KeySet{ 30,
keyNew ("system/elektra/modules/yamlcpp", KEY_VALUE, "yamlcpp plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports/get", KEY_FUNC, elektraYamlcppGet, KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports/set", KEY_FUNC, elektraYamlcppSet, KEY_END),
#include ELEKTRA_README
keyNew ("system/elektra/modules/yamlcpp/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END),
keyNew ("system/elektra/modules/yamlcpp/config/needs/binary/meta", KEY_VALUE, "true", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/config/needs/boolean/restore", KEY_VALUE, "#1", KEY_END),
KS_END };
}
}
// ====================
// = Plugin Interface =
// ====================
/** @see elektraDocGet */
int elektraYamlcppGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
#ifdef __llvm__
__attribute__ ((annotate ("oclint:suppress[high ncss method]")))
#endif
{
kdb::Key parent = kdb::Key (parentKey);
kdb::KeySet keys = kdb::KeySet (returned);
if (parent.getName () == "system/elektra/modules/yamlcpp")
{
keys.append (contractYamlCpp ());
parent.release ();
keys.release ();
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
int status = ELEKTRA_PLUGIN_STATUS_ERROR;
try
{
yamlRead (keys, parent);
status = ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
catch (ParserException const & exception)
{
ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (parent.getKey (), "Unable to parse file '%s'. Reason: %s",
parent.getString ().c_str (), exception.what ());
}
catch (overflow_error const & exception)
{
ELEKTRA_SET_RESOURCE_ERRORF (parent.getKey (), "Unable to read data from file '%s'. Reason: %s",
parent.getString ().c_str (), exception.what ());
}
catch (RepresentationException const & exception)
{
ELEKTRA_SET_RESOURCE_ERRORF (parent.getKey (), "Unable to read data from file '%s'. Reason: %s",
parent.getString ().c_str (), exception.what ());
}
catch (exception const & exception)
{
ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (*parent, "Uncaught Exception: '%s'", exception.what ());
}
parent.release ();
keys.release ();
return status;
}
/** @see elektraDocSet */
int elektraYamlcppSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
kdb::Key parent = kdb::Key (parentKey);
kdb::KeySet keys = kdb::KeySet (returned);
#ifdef HAVE_LOGGER
ELEKTRA_LOG_DEBUG ("Write keys:");
logKeySet (keys);
#endif
int status = ELEKTRA_PLUGIN_STATUS_ERROR;
try
{
yamlWrite (keys, parent);
status = ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
catch (BadFile const & exception)
{
ELEKTRA_SET_RESOURCE_ERRORF (parent.getKey (), "Unable to write to file '%s'. Reason: %s.", parent.getString ().c_str (),
exception.what ());
}
catch (EmitterException const & exception)
{
ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (parent.getKey (),
"Something went wrong while emitting YAML data to file '%s'. Reason: %s.",
parent.getString ().c_str (), exception.what ());
}
catch (exception const & exception)
{
ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (*parent, "Uncaught Exception: '%s'", exception.what ());
}
parent.release ();
keys.release ();
return status;
}
Plugin * ELEKTRA_PLUGIN_EXPORT
{
return elektraPluginExport ("yamlcpp", ELEKTRA_PLUGIN_GET, &elektraYamlcppGet, ELEKTRA_PLUGIN_SET, &elektraYamlcppSet,
ELEKTRA_PLUGIN_END);
}
<commit_msg>YAML CPP: Disable boolean value conversion<commit_after>/**
* @file
*
* @brief Source for yamlcpp plugin
*
* @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
*
*/
// -- Imports ------------------------------------------------------------------------------------------------------------------------------
#include "yamlcpp.hpp"
#include "log.hpp"
#include "read.hpp"
#include "write.hpp"
#include <kdb.hpp>
#include <kdberrors.h>
#include <kdblogger.h>
#include "yaml-cpp/yaml.h"
using std::exception;
using std::overflow_error;
using YAML::BadFile;
using YAML::EmitterException;
using YAML::ParserException;
using YAML::RepresentationException;
using ckdb::Key;
using ckdb::keyNew;
using ckdb::KeySet;
using ckdb::Plugin;
using yamlcpp::yamlRead;
using yamlcpp::yamlWrite;
// -- Functions ----------------------------------------------------------------------------------------------------------------------------
namespace
{
/**
* @brief This function returns a key set containing the contract of this plugin.
*
* @return A contract describing the functionality of this plugin.
*/
kdb::KeySet contractYamlCpp (void)
{
return kdb::KeySet{ 30,
keyNew ("system/elektra/modules/yamlcpp", KEY_VALUE, "yamlcpp plugin waits for your orders", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports/get", KEY_FUNC, elektraYamlcppGet, KEY_END),
keyNew ("system/elektra/modules/yamlcpp/exports/set", KEY_FUNC, elektraYamlcppSet, KEY_END),
#include ELEKTRA_README
keyNew ("system/elektra/modules/yamlcpp/infos/version", KEY_VALUE, PLUGINVERSION, KEY_END),
keyNew ("system/elektra/modules/yamlcpp/config/needs/binary/meta", KEY_VALUE, "true", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/config/needs/boolean/restore", KEY_VALUE, "#1", KEY_END),
keyNew ("system/elektra/modules/yamlcpp/config/needs/boolean/restoreas", KEY_VALUE, "none", KEY_END),
KS_END };
}
}
// ====================
// = Plugin Interface =
// ====================
/** @see elektraDocGet */
int elektraYamlcppGet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
#ifdef __llvm__
__attribute__ ((annotate ("oclint:suppress[high ncss method]")))
#endif
{
kdb::Key parent = kdb::Key (parentKey);
kdb::KeySet keys = kdb::KeySet (returned);
if (parent.getName () == "system/elektra/modules/yamlcpp")
{
keys.append (contractYamlCpp ());
parent.release ();
keys.release ();
return ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
int status = ELEKTRA_PLUGIN_STATUS_ERROR;
try
{
yamlRead (keys, parent);
status = ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
catch (ParserException const & exception)
{
ELEKTRA_SET_VALIDATION_SYNTACTIC_ERRORF (parent.getKey (), "Unable to parse file '%s'. Reason: %s",
parent.getString ().c_str (), exception.what ());
}
catch (overflow_error const & exception)
{
ELEKTRA_SET_RESOURCE_ERRORF (parent.getKey (), "Unable to read data from file '%s'. Reason: %s",
parent.getString ().c_str (), exception.what ());
}
catch (RepresentationException const & exception)
{
ELEKTRA_SET_RESOURCE_ERRORF (parent.getKey (), "Unable to read data from file '%s'. Reason: %s",
parent.getString ().c_str (), exception.what ());
}
catch (exception const & exception)
{
ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (*parent, "Uncaught Exception: '%s'", exception.what ());
}
parent.release ();
keys.release ();
return status;
}
/** @see elektraDocSet */
int elektraYamlcppSet (Plugin * handle ELEKTRA_UNUSED, KeySet * returned, Key * parentKey)
{
kdb::Key parent = kdb::Key (parentKey);
kdb::KeySet keys = kdb::KeySet (returned);
#ifdef HAVE_LOGGER
ELEKTRA_LOG_DEBUG ("Write keys:");
logKeySet (keys);
#endif
int status = ELEKTRA_PLUGIN_STATUS_ERROR;
try
{
yamlWrite (keys, parent);
status = ELEKTRA_PLUGIN_STATUS_SUCCESS;
}
catch (BadFile const & exception)
{
ELEKTRA_SET_RESOURCE_ERRORF (parent.getKey (), "Unable to write to file '%s'. Reason: %s.", parent.getString ().c_str (),
exception.what ());
}
catch (EmitterException const & exception)
{
ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (parent.getKey (),
"Something went wrong while emitting YAML data to file '%s'. Reason: %s.",
parent.getString ().c_str (), exception.what ());
}
catch (exception const & exception)
{
ELEKTRA_SET_PLUGIN_MISBEHAVIOR_ERRORF (*parent, "Uncaught Exception: '%s'", exception.what ());
}
parent.release ();
keys.release ();
return status;
}
Plugin * ELEKTRA_PLUGIN_EXPORT
{
return elektraPluginExport ("yamlcpp", ELEKTRA_PLUGIN_GET, &elektraYamlcppGet, ELEKTRA_PLUGIN_SET, &elektraYamlcppSet,
ELEKTRA_PLUGIN_END);
}
<|endoftext|> |
<commit_before>
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkMovie.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkCGUtils.h"
#ifdef SK_BUILD_FOR_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif
#ifdef SK_BUILD_FOR_IOS
#include <CoreGraphics/CoreGraphics.h>
#endif
static void malloc_release_proc(void* info, const void* data, size_t size) {
sk_free(info);
}
static CGDataProviderRef SkStreamToDataProvider(SkStream* stream) {
// TODO: use callbacks, so we don't have to load all the data into RAM
size_t len = stream->getLength();
void* data = sk_malloc_throw(len);
stream->read(data, len);
return CGDataProviderCreateWithData(data, data, len, malloc_release_proc);
}
static CGImageSourceRef SkStreamToCGImageSource(SkStream* stream) {
CGDataProviderRef data = SkStreamToDataProvider(stream);
CGImageSourceRef imageSrc = CGImageSourceCreateWithDataProvider(data, 0);
CGDataProviderRelease(data);
return imageSrc;
}
class SkImageDecoder_CG : public SkImageDecoder {
protected:
virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode);
};
#define BITMAP_INFO (kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast)
bool SkImageDecoder_CG::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) {
CGImageSourceRef imageSrc = SkStreamToCGImageSource(stream);
if (NULL == imageSrc) {
return false;
}
SkAutoTCallVProc<const void, CFRelease> arsrc(imageSrc);
CGImageRef image = CGImageSourceCreateImageAtIndex(imageSrc, 0, NULL);
if (NULL == image) {
return false;
}
SkAutoTCallVProc<CGImage, CGImageRelease> arimage(image);
const int width = CGImageGetWidth(image);
const int height = CGImageGetHeight(image);
bm->setConfig(SkBitmap::kARGB_8888_Config, width, height);
if (SkImageDecoder::kDecodeBounds_Mode == mode) {
return true;
}
if (!this->allocPixelRef(bm, NULL)) {
return false;
}
bm->lockPixels();
bm->eraseColor(0);
// use the same colorspace, so we don't change the pixels at all
CGColorSpaceRef cs = CGImageGetColorSpace(image);
CGContextRef cg = CGBitmapContextCreate(bm->getPixels(), width, height,
8, bm->rowBytes(), cs, BITMAP_INFO);
CGContextDrawImage(cg, CGRectMake(0, 0, width, height), image);
CGContextRelease(cg);
bm->unlockPixels();
return true;
}
///////////////////////////////////////////////////////////////////////////////
SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) {
return SkNEW(SkImageDecoder_CG);
}
/////////////////////////////////////////////////////////////////////////
SkMovie* SkMovie::DecodeStream(SkStream* stream) {
return NULL;
}
/////////////////////////////////////////////////////////////////////////
static size_t consumer_put(void* info, const void* buffer, size_t count) {
SkWStream* stream = reinterpret_cast<SkWStream*>(info);
return stream->write(buffer, count) ? count : 0;
}
static void consumer_release(void* info) {
// we do nothing, since by design we don't "own" the stream (i.e. info)
}
static CGDataConsumerRef SkStreamToCGDataConsumer(SkWStream* stream) {
CGDataConsumerCallbacks procs;
procs.putBytes = consumer_put;
procs.releaseConsumer = consumer_release;
// we don't own/reference the stream, so it our consumer must not live
// longer that our caller's ownership of the stream
return CGDataConsumerCreate(stream, &procs);
}
static CGImageDestinationRef SkStreamToImageDestination(SkWStream* stream,
CFStringRef type) {
CGDataConsumerRef consumer = SkStreamToCGDataConsumer(stream);
if (NULL == consumer) {
return NULL;
}
SkAutoTCallVProc<const void, CFRelease> arconsumer(consumer);
return CGImageDestinationCreateWithDataConsumer(consumer, type, 1, NULL);
}
class SkImageEncoder_CG : public SkImageEncoder {
public:
SkImageEncoder_CG(Type t) : fType(t) {}
protected:
virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality);
private:
Type fType;
};
/* Encode bitmaps via CGImageDestination. We setup a DataConsumer which writes
to our SkWStream. Since we don't reference/own the SkWStream, our consumer
must only live for the duration of the onEncode() method.
*/
bool SkImageEncoder_CG::onEncode(SkWStream* stream, const SkBitmap& bm,
int quality) {
CFStringRef type;
switch (fType) {
case kJPEG_Type:
type = kUTTypeJPEG;
break;
case kPNG_Type:
type = kUTTypePNG;
break;
default:
return false;
}
CGImageDestinationRef dst = SkStreamToImageDestination(stream, type);
if (NULL == dst) {
return false;
}
SkAutoTCallVProc<const void, CFRelease> ardst(dst);
CGImageRef image = SkCreateCGImageRef(bm);
if (NULL == image) {
return false;
}
SkAutoTCallVProc<CGImage, CGImageRelease> agimage(image);
CGImageDestinationAddImage(dst, image, NULL);
CGImageDestinationFinalize(dst);
return true;
}
SkImageEncoder* SkImageEncoder::Create(Type t) {
switch (t) {
case kJPEG_Type:
case kPNG_Type:
break;
default:
return NULL;
}
return SkNEW_ARGS(SkImageEncoder_CG, (t));
}
<commit_msg>Make SkImageEncoder_CG report more failures to its caller. Review URL: https://codereview.appspot.com/5580052<commit_after>
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkImageDecoder.h"
#include "SkImageEncoder.h"
#include "SkMovie.h"
#include "SkStream.h"
#include "SkTemplates.h"
#include "SkCGUtils.h"
#ifdef SK_BUILD_FOR_MAC
#include <ApplicationServices/ApplicationServices.h>
#endif
#ifdef SK_BUILD_FOR_IOS
#include <CoreGraphics/CoreGraphics.h>
#endif
static void malloc_release_proc(void* info, const void* data, size_t size) {
sk_free(info);
}
static CGDataProviderRef SkStreamToDataProvider(SkStream* stream) {
// TODO: use callbacks, so we don't have to load all the data into RAM
size_t len = stream->getLength();
void* data = sk_malloc_throw(len);
stream->read(data, len);
return CGDataProviderCreateWithData(data, data, len, malloc_release_proc);
}
static CGImageSourceRef SkStreamToCGImageSource(SkStream* stream) {
CGDataProviderRef data = SkStreamToDataProvider(stream);
CGImageSourceRef imageSrc = CGImageSourceCreateWithDataProvider(data, 0);
CGDataProviderRelease(data);
return imageSrc;
}
class SkImageDecoder_CG : public SkImageDecoder {
protected:
virtual bool onDecode(SkStream* stream, SkBitmap* bm, Mode);
};
#define BITMAP_INFO (kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast)
bool SkImageDecoder_CG::onDecode(SkStream* stream, SkBitmap* bm, Mode mode) {
CGImageSourceRef imageSrc = SkStreamToCGImageSource(stream);
if (NULL == imageSrc) {
return false;
}
SkAutoTCallVProc<const void, CFRelease> arsrc(imageSrc);
CGImageRef image = CGImageSourceCreateImageAtIndex(imageSrc, 0, NULL);
if (NULL == image) {
return false;
}
SkAutoTCallVProc<CGImage, CGImageRelease> arimage(image);
const int width = CGImageGetWidth(image);
const int height = CGImageGetHeight(image);
bm->setConfig(SkBitmap::kARGB_8888_Config, width, height);
if (SkImageDecoder::kDecodeBounds_Mode == mode) {
return true;
}
if (!this->allocPixelRef(bm, NULL)) {
return false;
}
bm->lockPixels();
bm->eraseColor(0);
// use the same colorspace, so we don't change the pixels at all
CGColorSpaceRef cs = CGImageGetColorSpace(image);
CGContextRef cg = CGBitmapContextCreate(bm->getPixels(), width, height,
8, bm->rowBytes(), cs, BITMAP_INFO);
CGContextDrawImage(cg, CGRectMake(0, 0, width, height), image);
CGContextRelease(cg);
bm->unlockPixels();
return true;
}
///////////////////////////////////////////////////////////////////////////////
SkImageDecoder* SkImageDecoder::Factory(SkStream* stream) {
return SkNEW(SkImageDecoder_CG);
}
/////////////////////////////////////////////////////////////////////////
SkMovie* SkMovie::DecodeStream(SkStream* stream) {
return NULL;
}
/////////////////////////////////////////////////////////////////////////
static size_t consumer_put(void* info, const void* buffer, size_t count) {
SkWStream* stream = reinterpret_cast<SkWStream*>(info);
return stream->write(buffer, count) ? count : 0;
}
static void consumer_release(void* info) {
// we do nothing, since by design we don't "own" the stream (i.e. info)
}
static CGDataConsumerRef SkStreamToCGDataConsumer(SkWStream* stream) {
CGDataConsumerCallbacks procs;
procs.putBytes = consumer_put;
procs.releaseConsumer = consumer_release;
// we don't own/reference the stream, so it our consumer must not live
// longer that our caller's ownership of the stream
return CGDataConsumerCreate(stream, &procs);
}
static CGImageDestinationRef SkStreamToImageDestination(SkWStream* stream,
CFStringRef type) {
CGDataConsumerRef consumer = SkStreamToCGDataConsumer(stream);
if (NULL == consumer) {
return NULL;
}
SkAutoTCallVProc<const void, CFRelease> arconsumer(consumer);
return CGImageDestinationCreateWithDataConsumer(consumer, type, 1, NULL);
}
class SkImageEncoder_CG : public SkImageEncoder {
public:
SkImageEncoder_CG(Type t) : fType(t) {}
protected:
virtual bool onEncode(SkWStream* stream, const SkBitmap& bm, int quality);
private:
Type fType;
};
/* Encode bitmaps via CGImageDestination. We setup a DataConsumer which writes
to our SkWStream. Since we don't reference/own the SkWStream, our consumer
must only live for the duration of the onEncode() method.
*/
bool SkImageEncoder_CG::onEncode(SkWStream* stream, const SkBitmap& bm,
int quality) {
CFStringRef type;
switch (fType) {
case kJPEG_Type:
type = kUTTypeJPEG;
break;
case kPNG_Type:
type = kUTTypePNG;
break;
default:
return false;
}
CGImageDestinationRef dst = SkStreamToImageDestination(stream, type);
if (NULL == dst) {
return false;
}
SkAutoTCallVProc<const void, CFRelease> ardst(dst);
CGImageRef image = SkCreateCGImageRef(bm);
if (NULL == image) {
return false;
}
SkAutoTCallVProc<CGImage, CGImageRelease> agimage(image);
CGImageDestinationAddImage(dst, image, NULL);
return CGImageDestinationFinalize(dst);
}
SkImageEncoder* SkImageEncoder::Create(Type t) {
switch (t) {
case kJPEG_Type:
case kPNG_Type:
break;
default:
return NULL;
}
return SkNEW_ARGS(SkImageEncoder_CG, (t));
}
<|endoftext|> |
<commit_before>/*
MIT License
Copyright (c) 2017
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <iostream>
#include <vector>
#include <utility>
#include <map>
#include <algorithm>
#include <string>
#include <cstring>
#include <sstream>
#include <fstream>
/*
Program defines
To be moved to a separate header file
*/
#define ARGC_VAL_MIN (1+4)
/*
Custom structs
To be moved to spearate header file
*/
typedef struct {
std::pair<int,int> id;
std::pair<int,int> l;
std::pair<int,int> start;
std::pair<int,int> end;
std::pair<int,int> rc;
double jaccardScore;
int smm;
} mhapRead_t;
typedef struct {
std::vector<mhapRead_t*> lOvlp;
std::vector<mhapRead_t*> rOvlp;
} BOGNode_t;
/*
Global variables
*/
std::map<int,BOGNode_t> nodes;
std::vector<mhapRead_t> mhapReads;
/*
local function declarations
*/
int isDoveTail(mhapRead_t* mRead);
int isLeftAligned(mhapRead_t* mRead);
int main(int argc, char** argv) {
/*
int main() variables
*/
int defaultOutput = 1;
std::string mhapPath;
std::string fastaPath;
std::string outputPath = "output.fasta";
/*
parse input arguments
*/
if (argc < ARGC_VAL_MIN) {
std::cout << "Too few parameters! Expected at least " << ARGC_VAL_MIN-1 << ", got " << argc-1 << ".\r\nTerminating." << std::endl;
return 1;
} else {
// std::cout << "Input parameters OK" << std::endl;
}
for (int i=1; i<argc; ++i) {
if (strcmp(argv[i],"-mhap") == 0) {
mhapPath.assign(argv[++i]);
// accept only *.mhap for now
std::string inputExtension;
std::string::size_type idx = mhapPath.rfind('.');
if (idx != std::string::npos) {
inputExtension = mhapPath.substr(idx);
if (strcmp(inputExtension.c_str(),".mhap")) {
std::cout << "Please provide a *.mhap file. (got " << inputExtension << ")" << std::endl << "Terminating." << std::endl;
return 1;
}
} else {
std::cout << "Provide input file extension!" << std::endl << "Terminating." << std::endl;
return 1;
}
// std::cout << "Input path: " << inputPath << std::endl;
// std::cout << "Input extension " << inputExtension << std::endl;
} else if (strcmp(argv[i],"-fasta") == 0) {
fastaPath.assign(argv[++i]);
// accept only *.mhap for now
std::string inputExtension;
std::string::size_type idx = fastaPath.rfind('.');
if (idx != std::string::npos) {
inputExtension = fastaPath.substr(idx);
if (strcmp(inputExtension.c_str(),".fasta")) {
std::cout << "Please provide a *.fasta file. (got " << inputExtension << ")" << std::endl << "Terminating." << std::endl;
return 1;
}
} else {
std::cout << "Provide input file extension!" << std::endl << "Terminating." << std::endl;
return 1;
}
} else if (strcmp(argv[i],"-o") == 0) {
outputPath.assign(argv[++i]);
defaultOutput = 0;
std::ofstream outputFile (outputPath.c_str());
if (!outputFile) {
std::cout << "Cannot generate output file!" << std::endl << "Terminating." << std::endl;
} else {
outputFile.close();
}
// std::cout << "Output path: " << outputPath << std::endl;
} else {
std::cout << "invalid cli options" << std::endl << "Terminating" << std::endl;
return 1;
}
}
if (fastaPath.empty() || mhapPath.empty()) {
std::cout << "Please provide both *.fasta and *.mhap files!" << std::endl;
return 1;
}
/*
open input file (fasta or mhap)
mhap is better, because conversion of ecoli_corrected.fasta to mhap (graphmap) takes about 70 minutes on 4 cores and 10 GB RAM
*/
// only mhap for now :)
std::ifstream inputFile(mhapPath.c_str(),std::ifstream::in);
if (!inputFile) {
std::cout << mhapPath <<": No such file" << std::endl;
return 1;
}
/*
parse input file
*/
std::string line;
while (std::getline(inputFile,line)) {
std::istringstream inStream(line);
int ix1,ix2,smm,rc1,rc2,s1,e1,l1,s2,e2,l2;
double js;
mhapRead_t cRead;
inStream >> ix1 >> ix2;
inStream >> cRead.jaccardScore;
inStream >> cRead.smm;
inStream >> rc1 >> s1 >> e1 >> l1;
inStream >> rc2 >> s2 >> e2 >> l2;
cRead.id = std::make_pair(ix1,ix2);
cRead.l = std::make_pair(l1,l2);
cRead.start = std::make_pair(s1,s2);
cRead.end = std::make_pair(e1,e2);
cRead.rc = std::make_pair(rc1,rc2);
// std::cout << ix1 << " " << ix2 << " " << js << " " << smm << " " << rc1 << " " << s1 << " " << e1 << " " << l1 << " " << rc2 << " " << s2 << " " << e2 << " " << l2 << std::endl;
// push_back to a vector of reads
mhapReads.push_back(cRead);
}
/*
generate read and overlap contexts
build the complete OVERLAP GRAPH
*/
for (int i = 0; i<mhapReads.size(); ++i) {
mhapRead_t* cRead = &mhapReads[i];
BOGNode_t bNodeF,bNodeS;
int ixf = cRead->id.first;
int ixs = cRead->id.second;
// load existing map record
std::map<int,BOGNode_t>::iterator it = nodes.find(ixf);
if (it != nodes.end()) {
bNodeF = nodes[ixf];
}
it = nodes.find(ixs);
if (it != nodes.end()) {
bNodeS = nodes[ixs];
}
// ignore non-dovetail overlaps
if (isDoveTail(cRead)) {
if (isLeftAligned(cRead)) {
// add to left overlaps
bNodeF.lOvlp.push_back(cRead);
bNodeS.rOvlp.push_back(cRead);
} else {
// add to right overlaps
bNodeF.rOvlp.push_back(cRead);
bNodeS.lOvlp.push_back(cRead);
}
}
nodes[ixf] = bNodeF;
nodes[ixs] = bNodeS;
}
/*
THE ALGORITHM
Travel through the overlap graph, remove contained reads, remove cycles, pick best overlaps
Create the best overlap graph
1 fasta read per chromosome is optimum
*/
/*
Take the BOG and write i in FASTA format
*/
/*
Notify about success, return 0
*/
if (defaultOutput) {
std::cout << "Output to default: " << outputPath << std::endl;
} else {
std::cout << "Output to custom: " << outputPath << std::endl;
}
std::ofstream outputFile (outputPath.c_str());
outputFile << ">The result of the BOG goes here" << std::endl;
outputFile.close();
return 0;
}
// not definitive
int isDoveTail(mhapRead_t* mRead) {
if (mRead->start.first != 0 && mRead->end.first != (mRead->l.first-1)) {
// doesnt start at the beginning nor does it end at the end, this is a pratial overlap
return 0;
}
if (mRead->start.second != 0 && mRead->end.second != (mRead->l.second-1)) {
// doesnt start at the beginning nor does it end at the end, this is a pratial overlap
return 0;
}
return 1;
}
// a left aligned overlap is the one where the first index overlaps form 0 to x, x<l-1
// the end of the second read overlaps with the beginning of the first read
// not definitive
int isLeftAligned(mhapRead_t* mRead) {
return mRead->start.first == 0;
}
<commit_msg>Buildable version before testing what is done so far and before implementing the BOG<commit_after>/*
MIT License
Copyright (c) 2017
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <iostream>
#include <vector>
#include <utility>
#include <map>
#include <set>
#include <algorithm>
#include <string>
#include <cstring>
#include <sstream>
#include <fstream>
/*
Program defines
To be moved to a separate header file
*/
#define ARGC_VAL_MIN (1+4)
/*
Custom structs
To be moved to spearate header file
*/
typedef struct {
std::pair<int,int> id;
std::pair<int,int> l;
std::pair<int,int> start;
std::pair<int,int> end;
std::pair<int,int> rc;
double jaccardScore;
int smm;
} mhapRead_t;
typedef struct {
std::vector<mhapRead_t*> lOvlp;
std::vector<mhapRead_t*> rOvlp;
} BOGNode_t;
bool cmpNodes(mhapRead_t* a, mhapRead_t* b) {
if (a->jaccardScore != b->jaccardScore) {
return a->jaccardScore < b->jaccardScore;
}
return a->smm > b->smm;
}
/*
Global variables
*/
std::map<int,BOGNode_t> nodes;
std::vector<mhapRead_t> mhapReads;
std::set<int> readIxs;
std::vector<int> result;
/*
local function declarations
*/
int isDoveTail(mhapRead_t* mRead);
int isLeftAligned(mhapRead_t* mRead);
int main(int argc, char** argv) {
/*
int main() variables
*/
int defaultOutput = 1;
std::string mhapPath;
std::string fastaPath;
std::string outputPath = "output.fasta";
double minJaccardScore = 1.0;
int minJaccardIx;
/*
parse input arguments
*/
if (argc < ARGC_VAL_MIN) {
std::cout << "Too few parameters! Expected at least " << ARGC_VAL_MIN-1 << ", got " << argc-1 << ".\r\nTerminating." << std::endl;
return 1;
} else {
// std::cout << "Input parameters OK" << std::endl;
}
for (int i=1; i<argc; ++i) {
if (strcmp(argv[i],"-mhap") == 0) {
mhapPath.assign(argv[++i]);
// accept only *.mhap for now
std::string inputExtension;
std::string::size_type idx = mhapPath.rfind('.');
if (idx != std::string::npos) {
inputExtension = mhapPath.substr(idx);
if (strcmp(inputExtension.c_str(),".mhap")) {
std::cout << "Please provide a *.mhap file. (got " << inputExtension << ")" << std::endl << "Terminating." << std::endl;
return 1;
}
} else {
std::cout << "Provide input file extension!" << std::endl << "Terminating." << std::endl;
return 1;
}
// std::cout << "Input path: " << inputPath << std::endl;
// std::cout << "Input extension " << inputExtension << std::endl;
} else if (strcmp(argv[i],"-fasta") == 0) {
fastaPath.assign(argv[++i]);
// accept only *.mhap for now
std::string inputExtension;
std::string::size_type idx = fastaPath.rfind('.');
if (idx != std::string::npos) {
inputExtension = fastaPath.substr(idx);
if (strcmp(inputExtension.c_str(),".fasta")) {
std::cout << "Please provide a *.fasta file. (got " << inputExtension << ")" << std::endl << "Terminating." << std::endl;
return 1;
}
} else {
std::cout << "Provide input file extension!" << std::endl << "Terminating." << std::endl;
return 1;
}
} else if (strcmp(argv[i],"-o") == 0) {
outputPath.assign(argv[++i]);
defaultOutput = 0;
std::ofstream outputFile (outputPath.c_str());
if (!outputFile) {
std::cout << "Cannot generate output file!" << std::endl << "Terminating." << std::endl;
} else {
outputFile.close();
}
// std::cout << "Output path: " << outputPath << std::endl;
} else {
std::cout << "invalid cli options" << std::endl << "Terminating" << std::endl;
return 1;
}
}
if (fastaPath.empty() || mhapPath.empty()) {
std::cout << "Please provide both *.fasta and *.mhap files!" << std::endl;
return 1;
}
/*
open input file (fasta or mhap)
mhap is better, because conversion of ecoli_corrected.fasta to mhap (graphmap) takes about 70 minutes on 4 cores and 10 GB RAM
*/
// only mhap for now :)
std::ifstream inputFile(mhapPath.c_str(),std::ifstream::in);
if (!inputFile) {
std::cout << mhapPath <<": No such file" << std::endl;
return 1;
}
/*
parse input file
*/
std::string line;
while (std::getline(inputFile,line)) {
std::istringstream inStream(line);
int ix1,ix2,smm,rc1,rc2,s1,e1,l1,s2,e2,l2;
double js;
mhapRead_t cRead;
inStream >> ix1 >> ix2;
inStream >> cRead.jaccardScore;
inStream >> cRead.smm;
inStream >> rc1 >> s1 >> e1 >> l1;
inStream >> rc2 >> s2 >> e2 >> l2;
cRead.id = std::make_pair(ix1,ix2);
cRead.l = std::make_pair(l1,l2);
cRead.start = std::make_pair(s1,s2);
cRead.end = std::make_pair(e1,e2);
cRead.rc = std::make_pair(rc1,rc2);
// std::cout << ix1 << " " << ix2 << " " << js << " " << smm << " " << rc1 << " " << s1 << " " << e1 << " " << l1 << " " << rc2 << " " << s2 << " " << e2 << " " << l2 << std::endl;
// push_back to a vector of reads
mhapReads.push_back(cRead);
}
/*
generate read and overlap contexts
build the complete OVERLAP GRAPH
*/
for (int i = 0; i<mhapReads.size(); ++i) {
mhapRead_t* cRead = &mhapReads[i];
BOGNode_t bNodeF,bNodeS;
int ixf = cRead->id.first;
int ixs = cRead->id.second;
// load existing map record
std::map<int,BOGNode_t>::iterator it = nodes.find(ixf);
if (it != nodes.end()) {
bNodeF = nodes[ixf];
} else {
readIxs.insert(ixf);
}
it = nodes.find(ixs);
if (it != nodes.end()) {
bNodeS = nodes[ixs];
} else {
readIxs.insert(ixs);
}
// ignore non-dovetail overlaps
if (isDoveTail(cRead)) {
if (isLeftAligned(cRead)) {
// add to left overlaps
bNodeF.lOvlp.push_back(cRead);
bNodeS.rOvlp.push_back(cRead);
} else {
// add to right overlaps
bNodeF.rOvlp.push_back(cRead);
bNodeS.lOvlp.push_back(cRead);
}
}
nodes[ixf] = bNodeF;
nodes[ixs] = bNodeS;
}
for (int i=0; i<nodes.size(); ++i) {
// sort by Jaccard score which is not exactly Jaccard score when mhap comes from graphmap but ok
std::sort(nodes[i].lOvlp.begin(),nodes[i].lOvlp.end(),cmpNodes);
std::sort(nodes[i].rOvlp.begin(),nodes[i].rOvlp.end(),cmpNodes);
if (minJaccardScore > nodes[i].rOvlp[0]->jaccardScore) {
minJaccardScore > nodes[i].rOvlp[0]->jaccardScore;
minJaccardIx = i;
}
}
// thats it, we have our densely populated overlap graph
/*
THE ALGORITHM
Travel through the overlap graph, remove contained reads, remove cycles, pick best overlaps
Create the best overlap graph
1 fasta read per chromosome is optimum
*/
// pick the node with the worst left overlap Jaccard score - this will be our starting node
result.push_back(minJaccardIx);
readIxs.erase(minJaccardIx);
/*
Take the BOG and write i in FASTA format
*/
/*
Notify about success, return 0
*/
if (defaultOutput) {
std::cout << "Output to default: " << outputPath << std::endl;
} else {
std::cout << "Output to custom: " << outputPath << std::endl;
}
std::ofstream outputFile (outputPath.c_str());
outputFile << ">The result of the BOG goes here" << std::endl;
outputFile.close();
return 0;
}
// not definitive
int isDoveTail(mhapRead_t* mRead) {
if (mRead->start.first != 0 && mRead->end.first != (mRead->l.first-1)) {
// doesnt start at the beginning nor does it end at the end, this is a pratial overlap
return 0;
}
if (mRead->start.second != 0 && mRead->end.second != (mRead->l.second-1)) {
// doesnt start at the beginning nor does it end at the end, this is a pratial overlap
return 0;
}
return 1;
}
// a left aligned overlap is the one where the first index overlaps form 0 to x, x<l-1
// the end of the second read overlaps with the beginning of the first read
// not definitive
int isLeftAligned(mhapRead_t* mRead) {
return mRead->start.first == 0;
}
<|endoftext|> |
<commit_before>#include "PositionModule.hpp"
#include <assert.h>
#include <sys/stat.h>
#include <errno.h>
#include <string>
#include <ros/console.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include "sensor_msgs/Image.h"
#include "api_application/Ping.h"
#include "api_application/Announce.h"
PositionModule::PositionModule(IPositionReceiver* receiver)
{
assert(receiver != 0);
this->receiver = receiver;
_isInitialized = true;
isCalibrating = false;
isRunning = false;
ros::NodeHandle n;
this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4);
this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4);
this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this);
this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this);
this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this);
this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this);
// Advertise myself to API
ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("Announce");
api_application::Announce announce;
announce.request.type = 3; // 3 means position module
announce.request.initializeServiceName = std::string("InitializePositionModule");
if (announceClient.call(announce))
{
rosId = announce.response.ID;
if (rosId == ~0 /* -1 */)
{
ROS_ERROR("Error! Got id -1");
_isInitialized = false;
}
else
{
ROS_INFO("Position module successfully announced. Got id %d", rosId);
}
}
else
{
ROS_ERROR("Error! Could not announce myself to API!");
_isInitialized = false;
}
msg = new KitrokopterMessages(rosId);
if (_isInitialized)
{
ROS_DEBUG("PositionModule initialized.");
}
}
PositionModule::~PositionModule()
{
msg->~KitrokopterMessages();
// TODO: Free picture cache.
ROS_DEBUG("PositionModule destroyed.");
}
// Service
bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res)
{
res.ok = !isCalibrating;
if (!isCalibrating)
{
setPictureSendingActivated(true);
calibrationPictureCount = 0;
boardSize = cv::Size(req.chessboardWidth, req.chessboardHeight);
}
isCalibrating = true;
return true;
}
// Service
bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res)
{
int id = 0;
for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++, id++)
{
if (*it != 0)
{
// TODO: check if image is "good"
std::vector<cv::Point2f> corners;
bool foundAllCorners = cv::findChessboardCorners(**it, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);
if (!foundAllCorners)
{
ROS_INFO("Took bad picture (id %d)", id);
continue;
}
else
{
ROS_INFO("Took good picture (id %d)", id);
}
// Create directory for images.
int error = mkdir("~/calibrationImages", 770);
if (error != 0 && error != EEXIST)
{
ROS_ERROR("Could not create directory for calibration images: %d", error);
return false;
}
std::stringstream ss;
ss << "~/calibrationImages/cam" << id << "_image" << calibrationPictureCount << ".png";
cv::imwrite(ss.str(), **it);
sensor_msgs::Image img;
img.width = 640;
img.height = 480;
img.step = 3 * 640;
for (int i = 0; i < 640 * 480 * 3; i++)
{
img.data[i] = (*it)->data[i];
}
res.images.push_back(img);
delete *it;
*it = 0;
}
}
calibrationPictureCount++;
return true;
}
// Service
bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res)
{
// TODO: Do stuff with danis code...
return true;
}
// Topic
void PositionModule::pictureCallback(const camera_application::Picture &msg)
{
if (isCalibrating)
{
// Don't know if it works that way and I really can randomly insert now...
pictureCache.reserve(msg.ID + 1);
pictureTimes.reserve(msg.ID + 1);
if (pictureCache[msg.ID] != 0)
{
delete pictureCache[msg.ID];
pictureCache[msg.ID] = 0;
}
cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3);
for (int i = 0; i < 640 * 480 * 3; i++)
{
image->data[i] = msg.image[i];
}
pictureCache[msg.ID] = image;
pictureTimes[msg.ID] = msg.timestamp;
}
}
// Topic
void PositionModule::systemCallback(const api_application::System &msg)
{
isRunning = msg.command == 1;
}
void PositionModule::setPictureSendingActivated(bool activated)
{
camera_application::PictureSendingActivation msg;
msg.ID = 0;
msg.active = activated;
pictureSendingActivationPublisher.publish(msg);
}
void PositionModule::sendPing()
{
api_application::Ping msg;
msg.ID = rosId;
pingPublisher.publish(msg);
}
bool PositionModule::isInitialized()
{
return _isInitialized;
}<commit_msg>Don't send bad pictures.<commit_after>#include "PositionModule.hpp"
#include <assert.h>
#include <sys/stat.h>
#include <errno.h>
#include <string>
#include <ros/console.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include "sensor_msgs/Image.h"
#include "api_application/Ping.h"
#include "api_application/Announce.h"
PositionModule::PositionModule(IPositionReceiver* receiver)
{
assert(receiver != 0);
this->receiver = receiver;
_isInitialized = true;
isCalibrating = false;
isRunning = false;
ros::NodeHandle n;
this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4);
this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4);
this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this);
this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this);
this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this);
this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this);
// Advertise myself to API
ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("Announce");
api_application::Announce announce;
announce.request.type = 3; // 3 means position module
announce.request.initializeServiceName = std::string("InitializePositionModule");
if (announceClient.call(announce))
{
rosId = announce.response.ID;
if (rosId == ~0 /* -1 */)
{
ROS_ERROR("Error! Got id -1");
_isInitialized = false;
}
else
{
ROS_INFO("Position module successfully announced. Got id %d", rosId);
}
}
else
{
ROS_ERROR("Error! Could not announce myself to API!");
_isInitialized = false;
}
msg = new KitrokopterMessages(rosId);
if (_isInitialized)
{
ROS_DEBUG("PositionModule initialized.");
}
}
PositionModule::~PositionModule()
{
msg->~KitrokopterMessages();
// TODO: Free picture cache.
ROS_DEBUG("PositionModule destroyed.");
}
// Service
bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res)
{
res.ok = !isCalibrating;
if (!isCalibrating)
{
setPictureSendingActivated(true);
calibrationPictureCount = 0;
boardSize = cv::Size(req.chessboardWidth, req.chessboardHeight);
}
isCalibrating = true;
return true;
}
// Service
bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res)
{
int id = 0;
for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++, id++)
{
if (*it != 0)
{
// TODO: check if image is "good"
std::vector<cv::Point2f> corners;
bool foundAllCorners = cv::findChessboardCorners(**it, boardSize, corners, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE);
if (!foundAllCorners)
{
ROS_INFO("Took bad picture (id %d)", id);
continue;
}
else
{
ROS_INFO("Took good picture (id %d)", id);
// Create directory for images.
int error = mkdir("~/calibrationImages", 770);
if (error != 0 && error != EEXIST)
{
ROS_ERROR("Could not create directory for calibration images: %d", error);
return false;
}
std::stringstream ss;
ss << "~/calibrationImages/cam" << id << "_image" << calibrationPictureCount << ".png";
cv::imwrite(ss.str(), **it);
sensor_msgs::Image img;
img.width = 640;
img.height = 480;
img.step = 3 * 640;
for (int i = 0; i < 640 * 480 * 3; i++)
{
img.data[i] = (*it)->data[i];
}
res.images.push_back(img);
}
delete *it;
*it = 0;
}
}
calibrationPictureCount++;
return true;
}
// Service
bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res)
{
// TODO: Do stuff with danis code...
return true;
}
// Topic
void PositionModule::pictureCallback(const camera_application::Picture &msg)
{
if (isCalibrating)
{
// Don't know if it works that way and I really can randomly insert now...
pictureCache.reserve(msg.ID + 1);
pictureTimes.reserve(msg.ID + 1);
if (pictureCache[msg.ID] != 0)
{
delete pictureCache[msg.ID];
pictureCache[msg.ID] = 0;
}
cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3);
for (int i = 0; i < 640 * 480 * 3; i++)
{
image->data[i] = msg.image[i];
}
pictureCache[msg.ID] = image;
pictureTimes[msg.ID] = msg.timestamp;
}
}
// Topic
void PositionModule::systemCallback(const api_application::System &msg)
{
isRunning = msg.command == 1;
}
void PositionModule::setPictureSendingActivated(bool activated)
{
camera_application::PictureSendingActivation msg;
msg.ID = 0;
msg.active = activated;
pictureSendingActivationPublisher.publish(msg);
}
void PositionModule::sendPing()
{
api_application::Ping msg;
msg.ID = rosId;
pingPublisher.publish(msg);
}
bool PositionModule::isInitialized()
{
return _isInitialized;
}<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_basic.hxx"
#include "sbmodule.hxx"
/** === begin UNO includes === **/
/** === end UNO includes === **/
//........................................................................
namespace basic
{
//........................................................................
//--------------------------------------------------------------------
extern void createRegistryInfo_SfxDialogLibraryContainer();
extern void createRegistryInfo_SfxScriptLibraryContainer();
static void initializeModule()
{
static bool bInitialized( false );
if ( !bInitialized )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !bInitialized )
{
createRegistryInfo_SfxDialogLibraryContainer();
createRegistryInfo_SfxScriptLibraryContainer();
}
}
}
//........................................................................
} // namespace basic
//........................................................................
IMPLEMENT_COMPONENT_LIBRARY_API( ::basic::BasicModule, ::basic::initializeModule )
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>maybe temporary fix for crash when accessing basic uno services<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* 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_basic.hxx"
#include "sbmodule.hxx"
/** === begin UNO includes === **/
/** === end UNO includes === **/
//........................................................................
namespace basic
{
//........................................................................
//--------------------------------------------------------------------
extern void createRegistryInfo_SfxDialogLibraryContainer();
extern void createRegistryInfo_SfxScriptLibraryContainer();
static void initializeModule()
{
static bool bInitialized( false );
if ( !bInitialized )
{
::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );
if ( !bInitialized )
{
static BasicModuleClient aClient;
createRegistryInfo_SfxDialogLibraryContainer();
createRegistryInfo_SfxScriptLibraryContainer();
}
}
}
//........................................................................
} // namespace basic
//........................................................................
IMPLEMENT_COMPONENT_LIBRARY_API( ::basic::BasicModule, ::basic::initializeModule )
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "variable.h"
#include "abstractlocalizer.h"
#include "context.h"
#include "exception.h"
#include "metaenumvariable_p.h"
#include "metatype.h"
#include "util.h"
#include <QtCore/QMetaEnum>
#include <QtCore/QStringList>
using namespace Grantlee;
namespace Grantlee
{
class VariablePrivate
{
public:
VariablePrivate( Variable *variable )
: q_ptr( variable ),
m_localize( false )
{
}
Q_DECLARE_PUBLIC( Variable )
Variable * const q_ptr;
QString m_varString;
QVariant m_literal;
QStringList m_lookups;
bool m_localize;
};
}
Variable::Variable( const Variable &other )
: d_ptr( new VariablePrivate( this ) )
{
d_ptr->m_varString = other.d_ptr->m_varString;
d_ptr->m_literal = other.d_ptr->m_literal;
d_ptr->m_lookups = other.d_ptr->m_lookups;
d_ptr->m_localize = other.d_ptr->m_localize;
}
Variable::Variable()
: d_ptr( new VariablePrivate( this ) )
{
}
Variable::~Variable()
{
delete d_ptr;
}
Variable &Variable::operator=( const Variable & other )
{
d_ptr->m_varString = other.d_ptr->m_varString;
d_ptr->m_literal = other.d_ptr->m_literal;
d_ptr->m_lookups = other.d_ptr->m_lookups;
d_ptr->m_localize = other.d_ptr->m_localize;
return *this;
}
Variable::Variable( const QString &var )
: d_ptr( new VariablePrivate( this ) )
{
Q_D( Variable );
d->m_varString = var;
QVariant v( var );
QString localVar = var;
if ( var.startsWith( QLatin1String( "_(" ) ) && var.endsWith( QLatin1Char( ')' ) ) ) {
d->m_localize = true;
localVar = var.mid( 2, var.size() - 3 );
v = localVar;
}
if ( v.convert( QVariant::Double ) ) {
d->m_literal = v;
if ( !var.contains( QLatin1Char( '.' ) ) && !var.contains( QLatin1Char( 'e' ) ) ) {
if ( var.endsWith( QLatin1Char( '.' ) ) ) {
// throw Grantlee::Exception( VariableSyntaxError, QString( "Variable may not end with a dot: %1" ).arg( v.toString() ) );
}
d->m_literal = v.toInt();
}
} else {
if (( localVar.startsWith( QLatin1Char( '"' ) ) && localVar.endsWith( QLatin1Char( '"' ) ) )
|| ( localVar.startsWith( QLatin1Char( '\'' ) ) && localVar.endsWith( QLatin1Char( '\'' ) ) ) ) {
const QString unesc = unescapeStringLiteral( localVar );
const Grantlee::SafeString ss = markSafe( unesc );
d->m_literal = QVariant::fromValue<Grantlee::SafeString>( ss );
} else {
if ( localVar.contains( QLatin1String( "._" ) ) || ( localVar.startsWith( QLatin1Char( '_' ) ) ) ) {
throw Grantlee::Exception( TagSyntaxError,
QString::fromLatin1( "Variables and attributes may not begin with underscores: %1" ).arg( localVar ) );
}
d->m_lookups = localVar.split( QLatin1Char( '.' ) );
}
}
}
bool Variable::isValid() const
{
Q_D( const Variable );
return !d->m_varString.isEmpty();
}
bool Variable::isConstant() const
{
Q_D( const Variable );
return !d->m_literal.isNull();
}
bool Variable::isTrue( Context *c ) const
{
return variantIsTrue( resolve( c ) );
}
bool Variable::isLocalized() const
{
Q_D( const Variable );
return d->m_localize;
}
QVariant Variable::literal() const
{
Q_D( const Variable );
return d->m_literal;
}
QStringList Variable::lookups() const
{
Q_D( const Variable );
return d->m_lookups;
}
class StaticQtMetaObject : public QObject
{
public:
static const QMetaObject* _smo() { return &QObject::staticQtMetaObject; }
};
QVariant Variable::resolve( Context *c ) const
{
Q_D( const Variable );
QVariant var;
if ( !d->m_lookups.isEmpty() ) {
int i = 0;
if ( d->m_lookups.at( i ) == QLatin1String( "Qt" ) ) {
++i;
const QString nextPart = d->m_lookups.at( i );
++i;
static const QMetaObject *globalMetaObject = StaticQtMetaObject::_smo();
bool breakout = false;
for ( int j = 0; j < globalMetaObject->enumeratorCount(); ++j ) {
const QMetaEnum me = globalMetaObject->enumerator( j );
if ( QLatin1String( me.name() ) == nextPart ) {
const MetaEnumVariable mev( me );
var = QVariant::fromValue( mev );
break;
}
for ( int k = 0; k < me.keyCount(); ++k ) {
if ( QLatin1String( me.key( k ) ) == nextPart ) {
const MetaEnumVariable mev( me, k );
var = QVariant::fromValue( mev );
breakout = true;
break;
}
}
if ( breakout )
break;
}
if ( !var.isValid() )
return QVariant();
} else {
var = c->lookup( d->m_lookups.at( i++ ) );
}
while ( i < d->m_lookups.size() ) {
var = MetaType::lookup( var, d->m_lookups.at( i++ ) );
if ( !var.isValid() )
return QVariant();
}
} else {
if ( isSafeString( var ) )
var = QVariant::fromValue( getSafeString( d->m_literal ) );
else
var = d->m_literal;
}
if ( supportedOutputType( var ) ) {
if ( d->m_localize ) {
return c->localizer()->localize( var );
}
return var;
}
// QStringList with size == 1 is special cased to be convertible to QString.
// We make sure we don't accidentally invoke that.
if ( var.type() != QVariant::StringList && var.canConvert( QVariant::String ) ) {
if ( var.convert( QVariant::String ) ) {
if ( d->m_localize ) {
return QVariant::fromValue<Grantlee::SafeString>( c->localizer()->localize( var ) );
}
return QVariant::fromValue<Grantlee::SafeString>( var.toString() );
}
return QVariant();
}
// Could be a list, hash or enum.
return var;
}
<commit_msg>Actually use the literal value instead of the (empty) var.<commit_after>/*
This file is part of the Grantlee template system.
Copyright (c) 2009,2010 Stephen Kelly <steveire@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either version
2.1 of the Licence, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library. If not, see <http://www.gnu.org/licenses/>.
*/
#include "variable.h"
#include "abstractlocalizer.h"
#include "context.h"
#include "exception.h"
#include "metaenumvariable_p.h"
#include "metatype.h"
#include "util.h"
#include <QtCore/QMetaEnum>
#include <QtCore/QStringList>
using namespace Grantlee;
namespace Grantlee
{
class VariablePrivate
{
public:
VariablePrivate( Variable *variable )
: q_ptr( variable ),
m_localize( false )
{
}
Q_DECLARE_PUBLIC( Variable )
Variable * const q_ptr;
QString m_varString;
QVariant m_literal;
QStringList m_lookups;
bool m_localize;
};
}
Variable::Variable( const Variable &other )
: d_ptr( new VariablePrivate( this ) )
{
d_ptr->m_varString = other.d_ptr->m_varString;
d_ptr->m_literal = other.d_ptr->m_literal;
d_ptr->m_lookups = other.d_ptr->m_lookups;
d_ptr->m_localize = other.d_ptr->m_localize;
}
Variable::Variable()
: d_ptr( new VariablePrivate( this ) )
{
}
Variable::~Variable()
{
delete d_ptr;
}
Variable &Variable::operator=( const Variable & other )
{
d_ptr->m_varString = other.d_ptr->m_varString;
d_ptr->m_literal = other.d_ptr->m_literal;
d_ptr->m_lookups = other.d_ptr->m_lookups;
d_ptr->m_localize = other.d_ptr->m_localize;
return *this;
}
Variable::Variable( const QString &var )
: d_ptr( new VariablePrivate( this ) )
{
Q_D( Variable );
d->m_varString = var;
QVariant v( var );
QString localVar = var;
if ( var.startsWith( QLatin1String( "_(" ) ) && var.endsWith( QLatin1Char( ')' ) ) ) {
d->m_localize = true;
localVar = var.mid( 2, var.size() - 3 );
v = localVar;
}
if ( v.convert( QVariant::Double ) ) {
d->m_literal = v;
if ( !var.contains( QLatin1Char( '.' ) ) && !var.contains( QLatin1Char( 'e' ) ) ) {
if ( var.endsWith( QLatin1Char( '.' ) ) ) {
// throw Grantlee::Exception( VariableSyntaxError, QString( "Variable may not end with a dot: %1" ).arg( v.toString() ) );
}
d->m_literal = v.toInt();
}
} else {
if (( localVar.startsWith( QLatin1Char( '"' ) ) && localVar.endsWith( QLatin1Char( '"' ) ) )
|| ( localVar.startsWith( QLatin1Char( '\'' ) ) && localVar.endsWith( QLatin1Char( '\'' ) ) ) ) {
const QString unesc = unescapeStringLiteral( localVar );
const Grantlee::SafeString ss = markSafe( unesc );
d->m_literal = QVariant::fromValue<Grantlee::SafeString>( ss );
} else {
if ( localVar.contains( QLatin1String( "._" ) ) || ( localVar.startsWith( QLatin1Char( '_' ) ) ) ) {
throw Grantlee::Exception( TagSyntaxError,
QString::fromLatin1( "Variables and attributes may not begin with underscores: %1" ).arg( localVar ) );
}
d->m_lookups = localVar.split( QLatin1Char( '.' ) );
}
}
}
bool Variable::isValid() const
{
Q_D( const Variable );
return !d->m_varString.isEmpty();
}
bool Variable::isConstant() const
{
Q_D( const Variable );
return !d->m_literal.isNull();
}
bool Variable::isTrue( Context *c ) const
{
return variantIsTrue( resolve( c ) );
}
bool Variable::isLocalized() const
{
Q_D( const Variable );
return d->m_localize;
}
QVariant Variable::literal() const
{
Q_D( const Variable );
return d->m_literal;
}
QStringList Variable::lookups() const
{
Q_D( const Variable );
return d->m_lookups;
}
class StaticQtMetaObject : public QObject
{
public:
static const QMetaObject* _smo() { return &QObject::staticQtMetaObject; }
};
QVariant Variable::resolve( Context *c ) const
{
Q_D( const Variable );
QVariant var;
if ( !d->m_lookups.isEmpty() ) {
int i = 0;
if ( d->m_lookups.at( i ) == QLatin1String( "Qt" ) ) {
++i;
const QString nextPart = d->m_lookups.at( i );
++i;
static const QMetaObject *globalMetaObject = StaticQtMetaObject::_smo();
bool breakout = false;
for ( int j = 0; j < globalMetaObject->enumeratorCount(); ++j ) {
const QMetaEnum me = globalMetaObject->enumerator( j );
if ( QLatin1String( me.name() ) == nextPart ) {
const MetaEnumVariable mev( me );
var = QVariant::fromValue( mev );
break;
}
for ( int k = 0; k < me.keyCount(); ++k ) {
if ( QLatin1String( me.key( k ) ) == nextPart ) {
const MetaEnumVariable mev( me, k );
var = QVariant::fromValue( mev );
breakout = true;
break;
}
}
if ( breakout )
break;
}
if ( !var.isValid() )
return QVariant();
} else {
var = c->lookup( d->m_lookups.at( i++ ) );
}
while ( i < d->m_lookups.size() ) {
var = MetaType::lookup( var, d->m_lookups.at( i++ ) );
if ( !var.isValid() )
return QVariant();
}
} else {
if ( isSafeString( d->m_literal ) )
var = QVariant::fromValue( getSafeString( d->m_literal ) );
else
var = d->m_literal;
}
if ( supportedOutputType( var ) ) {
if ( d->m_localize ) {
return c->localizer()->localize( var );
}
return var;
}
// QStringList with size == 1 is special cased to be convertible to QString.
// We make sure we don't accidentally invoke that.
if ( var.type() != QVariant::StringList && var.canConvert( QVariant::String ) ) {
if ( var.convert( QVariant::String ) ) {
if ( d->m_localize ) {
return QVariant::fromValue<Grantlee::SafeString>( c->localizer()->localize( var ) );
}
return QVariant::fromValue<Grantlee::SafeString>( var.toString() );
}
return QVariant();
}
// Could be a list, hash or enum.
return var;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <iostream>
#include <sstream>
#include "metaScene.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"
#include "tubeMacro.h"
#include "FillGapsInTubeTreeCLP.h"
#include "itkGroupSpatialObject.h"
#include "itkSpatialObjectReader.h"
#include "itkSpatialObjectWriter.h"
#include "itkVesselTubeSpatialObject.h"
#include "itkNumericTraits.h"
#include <itkTimeProbesCollectorBase.h>
template< unsigned int VDimension >
int DoIt( int argc, char * argv[] );
template< unsigned int VDimension >
int FillGap( typename itk::GroupSpatialObject< VDimension >::Pointer &pTubeGroup,
std::string InterpolationMethod )
{
//typedefs
typedef itk::GroupSpatialObject< VDimension > TubeGroupType;
typedef typename TubeGroupType::ChildrenListPointer TubeListPointerType;
typedef itk::VesselTubeSpatialObject< VDimension > TubeType;
typedef typename TubeType::Pointer TubePointerType;
typedef typename TubeType::TubePointType TubePointType;
typedef typename TubeType::PointType PositionType;
typedef itk::IndexValueType TubeIdType;
typedef typename TubeType::PointListType TubePointListType;
char tubeName[] = "Tube";
TubeListPointerType pTubeList
= pTubeGroup->GetChildren(
pTubeGroup->GetMaximumDepth(), tubeName );
for( typename TubeGroupType::ChildrenListType::iterator
itSourceTubes = pTubeList->begin();
itSourceTubes != pTubeList->end(); ++itSourceTubes )
{
TubePointerType pCurTube
= dynamic_cast< TubeType * >( itSourceTubes->GetPointer() );
TubeIdType curTubeId = pCurTube->GetId();
TubeIdType curParentTubeId = pCurTube->GetParentId();
TubePointType* parentNearestPoint;
if( pCurTube->GetRoot() == false && curParentTubeId != pTubeGroup->GetId() )
{
//find parent target tube
for( typename TubeGroupType::ChildrenListType::iterator
itTubes = pTubeList->begin();
itTubes != pTubeList->end(); ++itTubes )
{
TubePointerType pTube
= dynamic_cast< TubeType * >( itTubes->GetPointer() );
if( pTube->GetId() == curParentTubeId )
{
double minDistance = itk::NumericTraits<double>::max();
int flag =-1;
for ( int index = 0; index < pTube->GetNumberOfPoints(); index++ )
{
TubePointType* tubePoint =
dynamic_cast< TubePointType* >( pTube->GetPoint( index ) );
PositionType tubePointPosition = tubePoint->GetPosition();
double distance = tubePointPosition.SquaredEuclideanDistanceTo
( pCurTube->GetPoint( 0 )->GetPosition() );
if ( minDistance > distance )
{
minDistance = distance;
parentNearestPoint = tubePoint;
flag = 1;
}
distance = tubePointPosition.SquaredEuclideanDistanceTo
( pCurTube->GetPoint( pCurTube->GetNumberOfPoints() - 1 )->GetPosition() );
if ( minDistance > distance )
{
minDistance = distance;
parentNearestPoint = tubePoint;
flag = 2;
}
}
if( InterpolationMethod == "Straight_Line" )
{
if( flag == 1 )//add as the starting point
{
TubePointListType targetTubePoints = pCurTube->GetPoints();
pCurTube->Clear();
pCurTube->GetPoints().push_back(*parentNearestPoint);
for( int i=0; i < targetTubePoints.size(); i++ )
{
pCurTube->GetPoints().push_back( targetTubePoints[i] );
}
}
if( flag == 2 )// add as an end point
{
pCurTube->GetPoints().push_back( *parentNearestPoint );
}
}
break;
}
}
}
}
return EXIT_SUCCESS;
}
template< unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
// Ensure that the input image dimension is valid
// We only support 2D and 3D Images due to the
// limitation of itkTubeSpatialObject
if ( VDimension != 2 && VDimension != 3 )
{
tube::ErrorMessage(
"Error: Only 2D and 3D data is currently supported.");
return EXIT_FAILURE;
}
// The timeCollector to perform basic profiling of algorithmic components
itk::TimeProbesCollectorBase timeCollector;
// CLIProgressReporter is used to communicate progress with the Slicer GUI
tube::CLIProgressReporter progressReporter( "FillGapsInTubeTree",
CLPProcessInformation );
progressReporter.Start();
float progress = 0;
timeCollector.Start( "Loading Input TRE File" );
// Load TRE File
tubeStandardOutputMacro( << "\n>> Loading TRE File" );
typedef itk::SpatialObjectReader< VDimension > TubesReaderType;
typename TubesReaderType::Pointer tubeFileReader = TubesReaderType::New();
try
{
tubeFileReader->SetFileName( inputTree.c_str() );
tubeFileReader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Error loading TRE File: "
+ std::string( err.GetDescription() ) );
timeCollector.Report();
return EXIT_FAILURE;
}
timeCollector.Stop( "Loading Input TRE File" );
progress = 0.25;
timeCollector.Start( "Filling gaps in input tree" );
tubeStandardOutputMacro( << "\n>> Filling gaps in input tree" );
FillGap< VDimension >( tubeFileReader->GetGroup(), InterpolationMethod );
timeCollector.Stop( "Filling gaps in input tree" );
progress = 0.75;
timeCollector.Start( "Writing the updates TRE file." );
typedef itk::SpatialObjectWriter< VDimension > TubeWriterType;
typename TubeWriterType::Pointer tubeWriter = TubeWriterType::New();
try
{
tubeWriter->SetFileName( outputTree.c_str() );
tubeWriter->SetInput( tubeFileReader->GetGroup() );
tubeWriter->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Error writing TRE file: "
+ std::string( err.GetDescription() ) );
timeCollector.Report();
return EXIT_FAILURE;
}
timeCollector.Stop( "Writing the updates TRE file." );
progress = 1.0;
progressReporter.Report( progress );
progressReporter.End();
timeCollector.Report();
return EXIT_SUCCESS;
}
int main( int argc, char * argv[] )
{
try
{
PARSE_ARGS;
}
catch ( const std::exception & err )
{
tube::ErrorMessage( err.what() );
return EXIT_FAILURE;
}
PARSE_ARGS;
MetaScene *mScene = new MetaScene;
mScene->Read( inputTree.c_str() );
if( mScene->GetObjectList()->empty() )
{
tubeWarningMacro( << "Input TRE file has no spatial objects" );
return EXIT_SUCCESS;
}
switch( mScene->GetObjectList()->front()->NDims() )
{
case 2:
return DoIt<2>( argc, argv );
break;
case 3:
return DoIt<3>( argc, argv );
break;
default:
tubeErrorMacro(<< "Error: Only 2D and 3D data is currently supported.");
return EXIT_FAILURE;
}
}
<commit_msg>COMP: Fixed compilation error.<commit_after>/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#include <iostream>
#include <sstream>
#include "metaScene.h"
#include "tubeCLIProgressReporter.h"
#include "tubeMessage.h"
#include "tubeMacro.h"
#include "FillGapsInTubeTreeCLP.h"
#include "itkGroupSpatialObject.h"
#include "itkSpatialObjectReader.h"
#include "itkSpatialObjectWriter.h"
#include "itkVesselTubeSpatialObject.h"
#include "itkNumericTraits.h"
#include <itkTimeProbesCollectorBase.h>
template< unsigned int VDimension >
int DoIt( int argc, char * argv[] );
template< unsigned int VDimension >
int FillGap( typename itk::GroupSpatialObject< VDimension >::Pointer &pTubeGroup,
std::string InterpolationMethod )
{
//typedefs
typedef itk::GroupSpatialObject< VDimension > TubeGroupType;
typedef typename TubeGroupType::ChildrenListPointer TubeListPointerType;
typedef itk::VesselTubeSpatialObject< VDimension > TubeType;
typedef typename TubeType::Pointer TubePointerType;
typedef typename TubeType::TubePointType TubePointType;
typedef typename TubeType::PointType PositionType;
typedef itk::IndexValueType TubeIdType;
typedef typename TubeType::PointListType TubePointListType;
char tubeName[] = "Tube";
TubeListPointerType pTubeList
= pTubeGroup->GetChildren(
pTubeGroup->GetMaximumDepth(), tubeName );
for( typename TubeGroupType::ChildrenListType::iterator
itSourceTubes = pTubeList->begin();
itSourceTubes != pTubeList->end(); ++itSourceTubes )
{
TubePointerType pCurTube
= dynamic_cast< TubeType * >( itSourceTubes->GetPointer() );
TubeIdType curTubeId = pCurTube->GetId();
TubeIdType curParentTubeId = pCurTube->GetParentId();
TubePointType* parentNearestPoint;
if( pCurTube->GetRoot() == false && curParentTubeId != pTubeGroup->GetId() )
{
//find parent target tube
for( typename TubeGroupType::ChildrenListType::iterator
itTubes = pTubeList->begin();
itTubes != pTubeList->end(); ++itTubes )
{
TubePointerType pTube
= dynamic_cast< TubeType * >( itTubes->GetPointer() );
if( pTube->GetId() == curParentTubeId )
{
double minDistance = itk::NumericTraits<double>::max();
int flag =-1;
for ( int index = 0; index < pTube->GetNumberOfPoints(); index++ )
{
TubePointType* tubePoint =
dynamic_cast< TubePointType* >( pTube->GetPoint( index ) );
PositionType tubePointPosition = tubePoint->GetPosition();
double distance = tubePointPosition.SquaredEuclideanDistanceTo
( pCurTube->GetPoint( 0 )->GetPosition() );
if ( minDistance > distance )
{
minDistance = distance;
parentNearestPoint = tubePoint;
flag = 1;
}
distance = tubePointPosition.SquaredEuclideanDistanceTo
( pCurTube->GetPoint( pCurTube->GetNumberOfPoints() - 1 )->GetPosition() );
if ( minDistance > distance )
{
minDistance = distance;
parentNearestPoint = tubePoint;
flag = 2;
}
}
if( InterpolationMethod == "Straight_Line" )
{
if( flag == 1 )//add as the starting point
{
TubePointListType targetTubePoints = pCurTube->GetPoints();
pCurTube->Clear();
pCurTube->GetPoints().push_back(*parentNearestPoint);
for( int i=0; i < targetTubePoints.size(); i++ )
{
pCurTube->GetPoints().push_back( targetTubePoints[i] );
}
}
if( flag == 2 )// add as an end point
{
pCurTube->GetPoints().push_back( *parentNearestPoint );
}
}
break;
}
}
}
}
return EXIT_SUCCESS;
}
template< unsigned int VDimension >
int DoIt( int argc, char * argv[] )
{
PARSE_ARGS;
// Ensure that the input image dimension is valid
// We only support 2D and 3D Images due to the
// limitation of itkTubeSpatialObject
if ( VDimension != 2 && VDimension != 3 )
{
tube::ErrorMessage(
"Error: Only 2D and 3D data is currently supported.");
return EXIT_FAILURE;
}
// The timeCollector to perform basic profiling of algorithmic components
itk::TimeProbesCollectorBase timeCollector;
// CLIProgressReporter is used to communicate progress with the Slicer GUI
tube::CLIProgressReporter progressReporter( "FillGapsInTubeTree",
CLPProcessInformation );
progressReporter.Start();
float progress = 0;
timeCollector.Start( "Loading Input TRE File" );
// Load TRE File
tubeStandardOutputMacro( << "\n>> Loading TRE File" );
typedef itk::SpatialObjectReader< VDimension > TubesReaderType;
typename TubesReaderType::Pointer tubeFileReader = TubesReaderType::New();
try
{
tubeFileReader->SetFileName( inputTree.c_str() );
tubeFileReader->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Error loading TRE File: "
+ std::string( err.GetDescription() ) );
timeCollector.Report();
return EXIT_FAILURE;
}
timeCollector.Stop( "Loading Input TRE File" );
progress = 0.25;
timeCollector.Start( "Filling gaps in input tree" );
tubeStandardOutputMacro( << "\n>> Filling gaps in input tree" );
typename itk::GroupSpatialObject< VDimension >::Pointer inputTubes;
inputTubes = tubeFileReader->GetGroup();
FillGap< VDimension >( inputTubes, InterpolationMethod );
timeCollector.Stop( "Filling gaps in input tree" );
progress = 0.75;
timeCollector.Start( "Writing the updates TRE file." );
typedef itk::SpatialObjectWriter< VDimension > TubeWriterType;
typename TubeWriterType::Pointer tubeWriter = TubeWriterType::New();
try
{
tubeWriter->SetFileName( outputTree.c_str() );
tubeWriter->SetInput( tubeFileReader->GetGroup() );
tubeWriter->Update();
}
catch( itk::ExceptionObject & err )
{
tube::ErrorMessage( "Error writing TRE file: "
+ std::string( err.GetDescription() ) );
timeCollector.Report();
return EXIT_FAILURE;
}
timeCollector.Stop( "Writing the updates TRE file." );
progress = 1.0;
progressReporter.Report( progress );
progressReporter.End();
timeCollector.Report();
return EXIT_SUCCESS;
}
int main( int argc, char * argv[] )
{
try
{
PARSE_ARGS;
}
catch ( const std::exception & err )
{
tube::ErrorMessage( err.what() );
return EXIT_FAILURE;
}
PARSE_ARGS;
MetaScene *mScene = new MetaScene;
mScene->Read( inputTree.c_str() );
if( mScene->GetObjectList()->empty() )
{
tubeWarningMacro( << "Input TRE file has no spatial objects" );
return EXIT_SUCCESS;
}
switch( mScene->GetObjectList()->front()->NDims() )
{
case 2:
return DoIt<2>( argc, argv );
break;
case 3:
return DoIt<3>( argc, argv );
break;
default:
tubeErrorMacro(<< "Error: Only 2D and 3D data is currently supported.");
return EXIT_FAILURE;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace {
DEF_SEM(DoCLD) {
FLAG_DF = false;
return memory;
}
DEF_SEM(DoSTD) {
FLAG_DF = true;
return memory;
}
DEF_SEM(DoCLC) {
FLAG_CF = false;
return memory;
}
DEF_SEM(DoCMC) {
FLAG_CF = BNot(FLAG_CF);
return memory;
}
DEF_SEM(DoSTC) {
FLAG_CF = BNot(FLAG_CF);
return memory;
}
DEF_SEM(DoSALC) {
Write(REG_AL, Unsigned(FLAG_CF));
return memory;
}
DEF_SEM(DoSAHF) {
Flags flags = {ZExtTo<uint64_t>(Read(REG_AH))};
FLAG_CF = UCmpEq(1, flags.cf);
FLAG_PF = UCmpEq(1, flags.pf);
FLAG_AF = UCmpEq(1, flags.af);
FLAG_SF = UCmpEq(1, flags.sf);
FLAG_ZF = UCmpEq(1, flags.zf);
return memory;
}
DEF_SEM(DoLAHF) {
Flags flags = {0};
flags.cf = Unsigned(FLAG_CF);
flags.must_be_1 = 1;
flags.pf = Unsigned(FLAG_PF);
flags.must_be_0a = 0;
flags.af = Unsigned(FLAG_AF);
flags.must_be_0b = 0;
flags.zf = Unsigned(FLAG_ZF);
flags.sf = Unsigned(FLAG_SF);
Write(REG_AH, TruncTo<uint8_t>(flags.flat));
return memory;
}
DEF_SEM(DoCLAC) {
memory = __remill_sync_hyper_call(
state, memory, SyncHyperCall::kAssertPrivileged);
state.rflag.ac = false;
return memory;
}
DEF_SEM(DoSTAC) {
memory = __remill_sync_hyper_call(
state, memory, SyncHyperCall::kAssertPrivileged);
state.rflag.ac = true;
return memory;
}
DEF_SEM(DoCLI) {
memory = __remill_sync_hyper_call(
state, memory, SyncHyperCall::kAssertPrivileged);
state.rflag._if = false;
return memory;
}
DEF_SEM(DoSTI) {
memory = __remill_sync_hyper_call(
state, memory, SyncHyperCall::kAssertPrivileged);
state.rflag._if = true;
return memory;
}
} // namespace
DEF_ISEL(CLD) = DoCLD;
DEF_ISEL(STD) = DoSTD;
DEF_ISEL(CLC) = DoCLC;
DEF_ISEL(CMC) = DoCMC;
DEF_ISEL(STC) = DoSTC;
DEF_ISEL(SALC) = DoSALC;
DEF_ISEL(SAHF) = DoSAHF;
DEF_ISEL(LAHF) = DoLAHF;
DEF_ISEL(CLAC) = DoCLAC;
DEF_ISEL(STAC) = DoSTAC;
DEF_ISEL(CLI) = DoCLI;
DEF_ISEL(STI) = DoSTI;
<commit_msg>Fix semantics of STC.<commit_after>/*
* Copyright (c) 2017 Trail of Bits, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
namespace {
DEF_SEM(DoCLD) {
FLAG_DF = false;
return memory;
}
DEF_SEM(DoSTD) {
FLAG_DF = true;
return memory;
}
DEF_SEM(DoCLC) {
FLAG_CF = false;
return memory;
}
DEF_SEM(DoCMC) {
FLAG_CF = BNot(FLAG_CF);
return memory;
}
DEF_SEM(DoSTC) {
FLAG_CF = true;
return memory;
}
DEF_SEM(DoSALC) {
Write(REG_AL, Unsigned(FLAG_CF));
return memory;
}
DEF_SEM(DoSAHF) {
Flags flags = {ZExtTo<uint64_t>(Read(REG_AH))};
FLAG_CF = UCmpEq(1, flags.cf);
FLAG_PF = UCmpEq(1, flags.pf);
FLAG_AF = UCmpEq(1, flags.af);
FLAG_SF = UCmpEq(1, flags.sf);
FLAG_ZF = UCmpEq(1, flags.zf);
return memory;
}
DEF_SEM(DoLAHF) {
Flags flags = {0};
flags.cf = Unsigned(FLAG_CF);
flags.must_be_1 = 1;
flags.pf = Unsigned(FLAG_PF);
flags.must_be_0a = 0;
flags.af = Unsigned(FLAG_AF);
flags.must_be_0b = 0;
flags.zf = Unsigned(FLAG_ZF);
flags.sf = Unsigned(FLAG_SF);
Write(REG_AH, TruncTo<uint8_t>(flags.flat));
return memory;
}
DEF_SEM(DoCLAC) {
memory = __remill_sync_hyper_call(
state, memory, SyncHyperCall::kAssertPrivileged);
state.rflag.ac = false;
return memory;
}
DEF_SEM(DoSTAC) {
memory = __remill_sync_hyper_call(
state, memory, SyncHyperCall::kAssertPrivileged);
state.rflag.ac = true;
return memory;
}
DEF_SEM(DoCLI) {
memory = __remill_sync_hyper_call(
state, memory, SyncHyperCall::kAssertPrivileged);
state.rflag._if = false;
return memory;
}
DEF_SEM(DoSTI) {
memory = __remill_sync_hyper_call(
state, memory, SyncHyperCall::kAssertPrivileged);
state.rflag._if = true;
return memory;
}
} // namespace
DEF_ISEL(CLD) = DoCLD;
DEF_ISEL(STD) = DoSTD;
DEF_ISEL(CLC) = DoCLC;
DEF_ISEL(CMC) = DoCMC;
DEF_ISEL(STC) = DoSTC;
DEF_ISEL(SALC) = DoSALC;
DEF_ISEL(SAHF) = DoSAHF;
DEF_ISEL(LAHF) = DoLAHF;
DEF_ISEL(CLAC) = DoCLAC;
DEF_ISEL(STAC) = DoSTAC;
DEF_ISEL(CLI) = DoCLI;
DEF_ISEL(STI) = DoSTI;
<|endoftext|> |
<commit_before>#include "LARA1GUN.H"
#include "CONTROL.H"
#include "SPECIFIC.H"
#ifdef PC_VERSION
#include "GAME.H"
#else
#include "SETUP.H"
#endif
#include "TOMB4FX.H"
#include "DRAW.H"
#include "LARA.H"
#include "LARAFIRE.H"
#include "MISC.H"
#include "OBJECTS.H"
#include "ITEMS.H"
char HKTimer = 0;
char HKShotsFired = 0;
void TriggerGrapplingEffect(long x, long y, long z)//44138(<), ? (F)
{
long size;
long lp;
struct SMOKE_SPARKS* sptr;
//loc_4416C
for(lp = 0; lp < 24; lp++)
{
sptr = &smoke_spark[GetFreeSmokeSpark()];
sptr->On = 1;
sptr->sShade = (GetRandomControl() & 0xF) + 40;
sptr->dShade = (GetRandomControl() & 0xF) + 64;
sptr->ColFadeSpeed = 4;
sptr->FadeToBlack = 16;
sptr->Life = sptr->sLife = (GetRandomControl() & 3) + 40;
sptr->TransType = 2;
sptr->x = x + (GetRandomControl() & 0x1F) - 16;
sptr->y = y + (GetRandomControl() & 0x1F) - 16;
sptr->z = z + (GetRandomControl() & 0x1F) - 16;
sptr->Xvel = (GetRandomControl() & 0x1FF) - 256 << 1;
sptr->Zvel = (GetRandomControl() & 0x1FF) - 256 << 1;
if (lp < 12)
{
sptr->Yvel = (GetRandomControl() & 0x1F);
sptr->Friction = 64;
}
else
{
//loc_4426C
sptr->Yvel = (GetRandomControl() & 0x1FF) + 256;
sptr->Friction = 82;
}
//loc_44284
sptr->Flags = 16;
sptr->RotAng = (GetRandomControl() & 0xFFF);
sptr->RotAdd = (GetRandomControl() & 0x40) - 32;
sptr->MaxYvel = 0;
sptr->Gravity = 0;
size = (GetRandomControl() & 0xF) + 48;
sptr->dSize = size << 1;
sptr->sSize = size >> 2;
sptr->Size = size >> 2;
sptr->mirror = 0;
}
}
void DoGrenadeDamageOnBaddie(struct ITEM_INFO* baddie, struct ITEM_INFO* item)
{
UNIMPLEMENTED();
}
void AnimateShotgun(int weapon_type)
{
UNIMPLEMENTED();
}
void undraw_shotgun(int weapon_type)//436B0(<), 43B14(<) (F)
{
struct ITEM_INFO* item = &items[lara.weapon_item];
AnimateItem(item);
if (item->status == ITEM_DEACTIVATED)
{
lara.gun_status = LG_NO_ARMS;
lara.target = NULL;
lara.right_arm.lock = 0;
lara.left_arm.lock = 0;
KillItem(lara.weapon_item);
lara.weapon_item = -1;
lara.right_arm.frame_number = 0;
lara.left_arm.frame_number = 0;
}//loc_43750
else
{
if (item->current_anim_state == STATE_LARA_JUMP_FORWARD)
{
if (anims[item->anim_number].frame_base == item->frame_number - 21)
{
undraw_shotgun_meshes(weapon_type);
}
}//loc_43798
}
lara.right_arm.frame_base = anims[item->frame_number].frame_ptr;
lara.left_arm.frame_base = anims[item->frame_number].frame_ptr;
lara.right_arm.frame_number = item->frame_number - anims[item->anim_number].frame_base;
lara.left_arm.frame_number = item->frame_number - anims[item->anim_number].frame_base;
lara.right_arm.anim_number = item->anim_number;
lara.left_arm.anim_number = item->anim_number;
}
void draw_shotgun(int weapon_type)// (F)
{
struct ITEM_INFO* item;
if (lara.weapon_item == -1)
{
lara.weapon_item = CreateItem();
item = &items[lara.weapon_item];
item->object_number = WeaponObject(weapon_type);
item->anim_number = objects[item->object_number].anim_index;
item->frame_number = anims[item->anim_number].frame_base;
item->status = ITEM_ACTIVE;
item->goal_anim_state = STATE_LARA_RUN_FORWARD;
item->current_anim_state = STATE_LARA_RUN_FORWARD;
item->room_number = NO_ROOM;
lara.left_arm.frame_base = lara.right_arm.frame_base = objects[item->object_number].frame_base;
}
else
{
item = &items[lara.weapon_item];
}
AnimateItem(item);
if (item->current_anim_state != STATE_LARA_WALK_FORWARD &&
item->current_anim_state != STATE_LARA_TURN_RIGHT_SLOW)
{
if (item->frame_number - anims[item->anim_number].frame_base == weapons[weapon_type].draw_frame)
{
draw_shotgun_meshes(weapon_type);
}
else if (lara.water_status == LW_UNDERWATER)
{
item->goal_anim_state = STATE_LARA_TURN_RIGHT_SLOW;
}
}
else
{
ready_shotgun(weapon_type);
}
lara.left_arm.frame_base = lara.right_arm.frame_base = anims[item->anim_number].frame_ptr;
lara.left_arm.frame_number = lara.right_arm.frame_number = item->frame_number - anims[item->anim_number].frame_base;
lara.left_arm.anim_number = lara.right_arm.anim_number = item->anim_number;
}
void ControlCrossbow(short item_number)
{
UNIMPLEMENTED();
}
void CrossbowHitSwitchType78(struct ITEM_INFO* item, struct ITEM_INFO* target, int MustHitLastNode)
{
UNIMPLEMENTED();
}
void FireCrossbow(struct PHD_3DPOS* Start)
{
UNIMPLEMENTED();
}
void FireHK(int running)
{
UNIMPLEMENTED();
}
void FireShotgun()
{
UNIMPLEMENTED();
}
void RifleHandler(int weapon_type)
{
UNIMPLEMENTED();
}
void ready_shotgun(int weapon_type)//424E0(<), 42934(<) (F)
{
struct object_info* object;
lara.gun_status = LG_READY;
lara.left_arm.z_rot = 0;
lara.left_arm.y_rot = 0;
lara.left_arm.x_rot = 0;
lara.right_arm.z_rot = 0;
lara.right_arm.x_rot = 0;
lara.right_arm.y_rot = 0;
lara.right_arm.frame_number = 0;
lara.left_arm.frame_number = 0;
lara.right_arm.lock = 0;
lara.left_arm.lock = 0;
lara.target = NULL;
object = &objects[WeaponObject(weapon_type)];//v1
lara.right_arm.frame_base = object->frame_base;
lara.left_arm.frame_base = object->frame_base;
return;
}
void undraw_shotgun_meshes(int weapon_type)//42498(<), 428EC(<) (F)
{
lara.back_gun = WeaponObject(weapon_type);
lara.mesh_ptrs[LM_RHAND] = meshes[objects[LARA].mesh_index + 2 * LM_RHAND];
}
void draw_shotgun_meshes(int weapon_type)//42444(<), 42898(<) (F)
{
lara.back_gun = WEAPON_NONE;
lara.mesh_ptrs[LM_RHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_RHAND];
}<commit_msg>Add DoGrenadeDamageOnBaddie<commit_after>#include "LARA1GUN.H"
#include "BOX.H"
#include "CONTROL.H"
#include "SAVEGAME.H"
#include "SPECIFIC.H"
#ifdef PC_VERSION
#include "GAME.H"
#else
#include "SETUP.H"
#endif
#include "TOMB4FX.H"
#include "TRAPS.H"
#include "DRAW.H"
#include "LARA.H"
#include "LARAFIRE.H"
#include "MISC.H"
#include "OBJECTS.H"
#include "ITEMS.H"
char HKTimer = 0;
char HKShotsFired = 0;
void TriggerGrapplingEffect(long x, long y, long z)//44138(<), ? (F)
{
long size;
long lp;
struct SMOKE_SPARKS* sptr;
//loc_4416C
for(lp = 0; lp < 24; lp++)
{
sptr = &smoke_spark[GetFreeSmokeSpark()];
sptr->On = 1;
sptr->sShade = (GetRandomControl() & 0xF) + 40;
sptr->dShade = (GetRandomControl() & 0xF) + 64;
sptr->ColFadeSpeed = 4;
sptr->FadeToBlack = 16;
sptr->Life = sptr->sLife = (GetRandomControl() & 3) + 40;
sptr->TransType = 2;
sptr->x = x + (GetRandomControl() & 0x1F) - 16;
sptr->y = y + (GetRandomControl() & 0x1F) - 16;
sptr->z = z + (GetRandomControl() & 0x1F) - 16;
sptr->Xvel = ((GetRandomControl() & 0x1FF) - 256) << 1;
sptr->Zvel = ((GetRandomControl() & 0x1FF) - 256) << 1;
if (lp < 12)
{
sptr->Yvel = (GetRandomControl() & 0x1F);
sptr->Friction = 64;
}
else
{
//loc_4426C
sptr->Yvel = (GetRandomControl() & 0x1FF) + 256;
sptr->Friction = 82;
}
//loc_44284
sptr->Flags = 16;
sptr->RotAng = (GetRandomControl() & 0xFFF);
sptr->RotAdd = (GetRandomControl() & 0x40) - 32;
sptr->MaxYvel = 0;
sptr->Gravity = 0;
size = (GetRandomControl() & 0xF) + 48;
sptr->dSize = size << 1;
sptr->sSize = size >> 2;
sptr->Size = size >> 2;
sptr->mirror = 0;
}
}
void DoGrenadeDamageOnBaddie(struct ITEM_INFO* baddie, struct ITEM_INFO* item)//43FB0(<), ? (F)
{
if (!(baddie->flags & 0x8000))
{
if (baddie == lara_item && baddie->hit_points > 0)
{
baddie->hit_points -= 50;
if (!(room[item->room_number].flags & RF_FILL_WATER) && baddie->hit_points < 51)
{
LaraBurn();
}//loc_44128
}
else
{
//loc_4404C
if (item->item_flags[2] == 0)
{
baddie->hit_status = 1;
if (!objects[baddie->object_number].undead)
{
HitTarget(baddie, NULL, 30, 1);
if (baddie != lara_item)
{
savegame.Game.AmmoHits++;
if (baddie->hit_points <= 0)
{
savegame.Level.Kills++;
CreatureDie((baddie - items), 1);
}//loc_44128
}//loc_44128
}//loc_44128
}//loc_44128
}
}//loc_44128
}
void AnimateShotgun(int weapon_type)
{
UNIMPLEMENTED();
}
void undraw_shotgun(int weapon_type)//436B0(<), 43B14(<) (F)
{
struct ITEM_INFO* item = &items[lara.weapon_item];
AnimateItem(item);
if (item->status == ITEM_DEACTIVATED)
{
lara.gun_status = LG_NO_ARMS;
lara.target = NULL;
lara.right_arm.lock = 0;
lara.left_arm.lock = 0;
KillItem(lara.weapon_item);
lara.weapon_item = -1;
lara.right_arm.frame_number = 0;
lara.left_arm.frame_number = 0;
}//loc_43750
else
{
if (item->current_anim_state == STATE_LARA_JUMP_FORWARD)
{
if (anims[item->anim_number].frame_base == item->frame_number - 21)
{
undraw_shotgun_meshes(weapon_type);
}
}//loc_43798
}
lara.right_arm.frame_base = anims[item->frame_number].frame_ptr;
lara.left_arm.frame_base = anims[item->frame_number].frame_ptr;
lara.right_arm.frame_number = item->frame_number - anims[item->anim_number].frame_base;
lara.left_arm.frame_number = item->frame_number - anims[item->anim_number].frame_base;
lara.right_arm.anim_number = item->anim_number;
lara.left_arm.anim_number = item->anim_number;
}
void draw_shotgun(int weapon_type)// (F)
{
struct ITEM_INFO* item;
if (lara.weapon_item == -1)
{
lara.weapon_item = CreateItem();
item = &items[lara.weapon_item];
item->object_number = WeaponObject(weapon_type);
item->anim_number = objects[item->object_number].anim_index;
item->frame_number = anims[item->anim_number].frame_base;
item->status = ITEM_ACTIVE;
item->goal_anim_state = STATE_LARA_RUN_FORWARD;
item->current_anim_state = STATE_LARA_RUN_FORWARD;
item->room_number = NO_ROOM;
lara.left_arm.frame_base = lara.right_arm.frame_base = objects[item->object_number].frame_base;
}
else
{
item = &items[lara.weapon_item];
}
AnimateItem(item);
if (item->current_anim_state != STATE_LARA_WALK_FORWARD &&
item->current_anim_state != STATE_LARA_TURN_RIGHT_SLOW)
{
if (item->frame_number - anims[item->anim_number].frame_base == weapons[weapon_type].draw_frame)
{
draw_shotgun_meshes(weapon_type);
}
else if (lara.water_status == LW_UNDERWATER)
{
item->goal_anim_state = STATE_LARA_TURN_RIGHT_SLOW;
}
}
else
{
ready_shotgun(weapon_type);
}
lara.left_arm.frame_base = lara.right_arm.frame_base = anims[item->anim_number].frame_ptr;
lara.left_arm.frame_number = lara.right_arm.frame_number = item->frame_number - anims[item->anim_number].frame_base;
lara.left_arm.anim_number = lara.right_arm.anim_number = item->anim_number;
}
void ControlCrossbow(short item_number)
{
UNIMPLEMENTED();
}
void CrossbowHitSwitchType78(struct ITEM_INFO* item, struct ITEM_INFO* target, int MustHitLastNode)
{
UNIMPLEMENTED();
}
void FireCrossbow(struct PHD_3DPOS* Start)
{
UNIMPLEMENTED();
}
void FireHK(int running)
{
UNIMPLEMENTED();
}
void FireShotgun()
{
UNIMPLEMENTED();
}
void RifleHandler(int weapon_type)
{
UNIMPLEMENTED();
}
void ready_shotgun(int weapon_type)//424E0(<), 42934(<) (F)
{
struct object_info* object;
lara.gun_status = LG_READY;
lara.left_arm.z_rot = 0;
lara.left_arm.y_rot = 0;
lara.left_arm.x_rot = 0;
lara.right_arm.z_rot = 0;
lara.right_arm.x_rot = 0;
lara.right_arm.y_rot = 0;
lara.right_arm.frame_number = 0;
lara.left_arm.frame_number = 0;
lara.right_arm.lock = 0;
lara.left_arm.lock = 0;
lara.target = NULL;
object = &objects[WeaponObject(weapon_type)];//v1
lara.right_arm.frame_base = object->frame_base;
lara.left_arm.frame_base = object->frame_base;
return;
}
void undraw_shotgun_meshes(int weapon_type)//42498(<), 428EC(<) (F)
{
lara.back_gun = WeaponObject(weapon_type);
lara.mesh_ptrs[LM_RHAND] = meshes[objects[LARA].mesh_index + 2 * LM_RHAND];
}
void draw_shotgun_meshes(int weapon_type)//42444(<), 42898(<) (F)
{
lara.back_gun = WEAPON_NONE;
lara.mesh_ptrs[LM_RHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_RHAND];
}<|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "os/os_specific.h"
#include "api/app/renderdoc_app.h"
#include "api/replay/capture_options.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dlfcn.h>
#include <string.h>
#include <libgen.h>
#include "serialise/string_utils.h"
static vector<Process::EnvironmentModification> &GetEnvModifications()
{
static vector<Process::EnvironmentModification> envCallbacks;
return envCallbacks;
}
static map<string, string> EnvStringToEnvMap(const char **envstring)
{
map<string, string> ret;
const char **e = envstring;
while(*e)
{
const char *equals = strchr(*e, '=');
string name;
string value;
name.assign(*e, equals);
value = equals+1;
ret[name] = value;
e++;
}
return ret;
}
void Process::RegisterEnvironmentModification(Process::EnvironmentModification modif)
{
GetEnvModifications().push_back(modif);
}
// on linux we apply environment changes before launching the program, as
// there is no support for injecting/loading renderdoc into a running program
// in any way, and we also have some environment changes that we *have* to make
// for correct hooking (LD_LIBRARY_PATH/LD_PRELOAD)
void Process::ApplyEnvironmentModification()
{
}
static pid_t RunProcess(const char *app, const char *workingDir, const char *cmdLine, char *const *envp)
{
if(!app) return (pid_t)0;
// it is safe to use app directly as execve never modifies argv
char *emptyargv[] = { (char *) app, NULL };
char **argv = emptyargv;
const char *c = cmdLine;
// parse command line into argv[], similar to how bash would
if(cmdLine)
{
int argc = 1;
// get a rough upper bound on the number of arguments
while(*c)
{
if(*c == ' ' || *c == '\t') argc++;
c++;
}
argv = new char*[argc+2];
c = cmdLine;
string a;
argc = 0; // current argument we're fetching
// argv[0] is the application name, by convention
size_t len = strlen(app)+1;
argv[argc] = new char[len];
strcpy(argv[argc], app);
argc++;
bool dquot = false, squot = false; // are we inside ''s or ""s
while(*c)
{
if(!dquot && !squot && (*c == ' ' || *c == '\t'))
{
if(!a.empty())
{
// if we've fetched some number of non-space characters
argv[argc] = new char[a.length()+1];
memcpy(argv[argc], a.c_str(), a.length()+1);
argc++;
}
a = "";
}
else if(!dquot && *c == '"')
{
dquot = true;
}
else if(!squot && *c == '\'')
{
squot = true;
}
else if(dquot && *c == '"')
{
dquot = false;
}
else if(squot && *c == '\'')
{
squot = false;
}
else if(squot)
{
// single quotes don't escape, just copy literally until we leave single quote mode
a.push_back(*c);
}
else if(dquot)
{
// handle escaping
if(*c == '\\')
{
c++;
if(*c)
{
a.push_back(*c);
}
else
{
RDCERR("Malformed command line:\n%s", cmdLine);
return 0;
}
}
else
{
a.push_back(*c);
}
}
else
{
a.push_back(*c);
}
c++;
}
if(!a.empty())
{
// if we've fetched some number of non-space characters
argv[argc] = new char[a.length()+1];
memcpy(argv[argc], a.c_str(), a.length()+1);
argc++;
}
argv[argc] = NULL;
if(squot || dquot)
{
RDCERR("Malformed command line\n%s", cmdLine);
return 0;
}
}
pid_t childPid = fork();
if(childPid == 0)
{
if(workingDir)
{
chdir(workingDir);
}
else
{
string exedir = app;
chdir(dirname((char *)exedir.c_str()));
}
execve(app, argv, envp);
RDCERR("Failed to execute %s: %s", app, strerror(errno));
exit(0);
}
char **argv_delete = argv;
if(argv != emptyargv)
{
while(*argv)
{
delete[] *argv;
argv++;
}
delete[] argv_delete;
}
return childPid;
}
uint32_t Process::InjectIntoProcess(uint32_t pid, const char *logfile, const CaptureOptions *opts, bool waitForExit)
{
RDCUNIMPLEMENTED("Injecting into already running processes on linux");
return 0;
}
uint32_t Process::LaunchProcess(const char *app, const char *workingDir, const char *cmdLine)
{
if(app == NULL || app[0] == 0)
{
RDCERR("Invalid empty 'app'");
return 0;
}
return (uint32_t)RunProcess(app, workingDir, cmdLine, environ);
}
uint32_t Process::LaunchAndInjectIntoProcess(const char *app, const char *workingDir, const char *cmdLine,
const char *logfile, const CaptureOptions *opts, bool waitForExit)
{
if(app == NULL || app[0] == 0)
{
RDCERR("Invalid empty 'app'");
return 0;
}
// turn environment string to a UTF-8 map
map<string, string> env = EnvStringToEnvMap((const char **)environ);
vector<EnvironmentModification> &modifications = GetEnvModifications();
if (logfile == NULL)
logfile = "";
string libpath;
{
FileIO::GetExecutableFilename(libpath);
libpath = dirname(libpath);
}
string optstr;
{
optstr.reserve(sizeof(CaptureOptions)*2+1);
byte *b = (byte *)opts;
for(size_t i=0; i < sizeof(CaptureOptions); i++)
{
optstr.push_back(char( 'a' + ((b[i] >> 4)&0xf) ));
optstr.push_back(char( 'a' + ((b[i] )&0xf) ));
}
}
modifications.push_back(EnvironmentModification(eEnvModification_AppendPlatform, "LD_LIBRARY_PATH", libpath.c_str()));
modifications.push_back(EnvironmentModification(eEnvModification_AppendPlatform, "LD_PRELOAD", "librenderdoc.so"));
modifications.push_back(EnvironmentModification(eEnvModification_Replace, "RENDERDOC_LOGFILE", logfile));
modifications.push_back(EnvironmentModification(eEnvModification_Replace, "RENDERDOC_CAPTUREOPTS", optstr.c_str()));
for(size_t i=0; i < modifications.size(); i++)
{
EnvironmentModification &m = modifications[i];
string &value = env[m.name];
switch(m.type)
{
case eEnvModification_Replace:
value = m.value;
break;
case eEnvModification_Append:
value += m.value;
break;
case eEnvModification_AppendPlatform:
case eEnvModification_AppendColon:
if(!value.empty())
value += ":";
value += m.value;
break;
case eEnvModification_AppendSemiColon:
if(!value.empty())
value += ";";
value += m.value;
break;
case eEnvModification_Prepend:
value = m.value + value;
break;
case eEnvModification_PrependColon:
if(!value.empty())
value = m.value + ":" + value;
else
value = m.value;
break;
case eEnvModification_PrependPlatform:
case eEnvModification_PrependSemiColon:
if(!value.empty())
value = m.value + ";" + value;
else
value = m.value;
break;
default:
RDCERR("Unexpected environment modification type");
}
}
char **envp = new char *[env.size()+1];
envp[env.size()] = NULL;
int i=0;
for(auto it=env.begin(); it != env.end(); it++)
{
string envline = it->first + "=" + it->second;
envp[i] = new char[envline.size()+1];
memcpy(envp[i], envline.c_str(), envline.size()+1);
i++;
}
pid_t childPid = RunProcess(app, workingDir, cmdLine, envp);
int ret = 0;
if(childPid != (pid_t)0)
{
// wait for child to have /proc/<pid> and read out tcp socket
usleep(1000);
string procfile = StringFormat::Fmt("/proc/%d/net/tcp", (int)childPid);
// try for a little while for the /proc entry to appear
for(int retry=0; retry < 10; retry++)
{
// back-off for each retry
usleep(1000 + 500 * retry);
FILE *f = FileIO::fopen(procfile.c_str(), "r");
if(f == NULL)
{
// try again in a bit
continue;
}
// read through the proc file to check for an open listen socket
while(ret == 0 && !feof(f))
{
const size_t sz = 512;
char line[sz];line[sz-1] = 0;
fgets(line, sz-1, f);
int socketnum = 0, hexip = 0, hexport = 0;
int num = sscanf(line, " %d: %x:%x", &socketnum, &hexip, &hexport);
// find open listen socket on 0.0.0.0:port
if(num == 3 && hexip == 0 &&
hexport >= RenderDoc_FirstCaptureNetworkPort &&
hexport <= RenderDoc_LastCaptureNetworkPort)
{
ret = hexport;
}
}
FileIO::fclose(f);
}
if(waitForExit)
{
int dummy = 0;
waitpid(childPid, &dummy, 0);
}
}
char **envp_delete = envp;
while(*envp)
{
delete[] *envp;
envp++;
}
delete[] envp_delete;
return ret;
}
void Process::StartGlobalHook(const char *pathmatch, const char *logfile, const CaptureOptions *opts)
{
RDCUNIMPLEMENTED("Global hooking of all processes on linux");
}
void *Process::LoadModule(const char *module)
{
return dlopen(module, RTLD_NOW);
}
void *Process::GetFunctionAddress(void *module, const char *function)
{
if(module == NULL) return NULL;
return dlsym(module, function);
}
uint32_t Process::GetCurrentPID()
{
return (uint32_t)getpid();
}
<commit_msg>Use our version of dirname on Linux<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2016 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "os/os_specific.h"
#include "api/app/renderdoc_app.h"
#include "api/replay/capture_options.h"
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <dlfcn.h>
#include <string.h>
#include "serialise/string_utils.h"
static vector<Process::EnvironmentModification> &GetEnvModifications()
{
static vector<Process::EnvironmentModification> envCallbacks;
return envCallbacks;
}
static map<string, string> EnvStringToEnvMap(const char **envstring)
{
map<string, string> ret;
const char **e = envstring;
while(*e)
{
const char *equals = strchr(*e, '=');
string name;
string value;
name.assign(*e, equals);
value = equals+1;
ret[name] = value;
e++;
}
return ret;
}
void Process::RegisterEnvironmentModification(Process::EnvironmentModification modif)
{
GetEnvModifications().push_back(modif);
}
// on linux we apply environment changes before launching the program, as
// there is no support for injecting/loading renderdoc into a running program
// in any way, and we also have some environment changes that we *have* to make
// for correct hooking (LD_LIBRARY_PATH/LD_PRELOAD)
void Process::ApplyEnvironmentModification()
{
}
static pid_t RunProcess(const char *app, const char *workingDir, const char *cmdLine, char *const *envp)
{
if(!app) return (pid_t)0;
// it is safe to use app directly as execve never modifies argv
char *emptyargv[] = { (char *) app, NULL };
char **argv = emptyargv;
const char *c = cmdLine;
// parse command line into argv[], similar to how bash would
if(cmdLine)
{
int argc = 1;
// get a rough upper bound on the number of arguments
while(*c)
{
if(*c == ' ' || *c == '\t') argc++;
c++;
}
argv = new char*[argc+2];
c = cmdLine;
string a;
argc = 0; // current argument we're fetching
// argv[0] is the application name, by convention
size_t len = strlen(app)+1;
argv[argc] = new char[len];
strcpy(argv[argc], app);
argc++;
bool dquot = false, squot = false; // are we inside ''s or ""s
while(*c)
{
if(!dquot && !squot && (*c == ' ' || *c == '\t'))
{
if(!a.empty())
{
// if we've fetched some number of non-space characters
argv[argc] = new char[a.length()+1];
memcpy(argv[argc], a.c_str(), a.length()+1);
argc++;
}
a = "";
}
else if(!dquot && *c == '"')
{
dquot = true;
}
else if(!squot && *c == '\'')
{
squot = true;
}
else if(dquot && *c == '"')
{
dquot = false;
}
else if(squot && *c == '\'')
{
squot = false;
}
else if(squot)
{
// single quotes don't escape, just copy literally until we leave single quote mode
a.push_back(*c);
}
else if(dquot)
{
// handle escaping
if(*c == '\\')
{
c++;
if(*c)
{
a.push_back(*c);
}
else
{
RDCERR("Malformed command line:\n%s", cmdLine);
return 0;
}
}
else
{
a.push_back(*c);
}
}
else
{
a.push_back(*c);
}
c++;
}
if(!a.empty())
{
// if we've fetched some number of non-space characters
argv[argc] = new char[a.length()+1];
memcpy(argv[argc], a.c_str(), a.length()+1);
argc++;
}
argv[argc] = NULL;
if(squot || dquot)
{
RDCERR("Malformed command line\n%s", cmdLine);
return 0;
}
}
pid_t childPid = fork();
if(childPid == 0)
{
if(workingDir)
{
chdir(workingDir);
}
else
{
string exedir = app;
chdir(dirname(exedir).c_str());
}
execve(app, argv, envp);
RDCERR("Failed to execute %s: %s", app, strerror(errno));
exit(0);
}
char **argv_delete = argv;
if(argv != emptyargv)
{
while(*argv)
{
delete[] *argv;
argv++;
}
delete[] argv_delete;
}
return childPid;
}
uint32_t Process::InjectIntoProcess(uint32_t pid, const char *logfile, const CaptureOptions *opts, bool waitForExit)
{
RDCUNIMPLEMENTED("Injecting into already running processes on linux");
return 0;
}
uint32_t Process::LaunchProcess(const char *app, const char *workingDir, const char *cmdLine)
{
if(app == NULL || app[0] == 0)
{
RDCERR("Invalid empty 'app'");
return 0;
}
return (uint32_t)RunProcess(app, workingDir, cmdLine, environ);
}
uint32_t Process::LaunchAndInjectIntoProcess(const char *app, const char *workingDir, const char *cmdLine,
const char *logfile, const CaptureOptions *opts, bool waitForExit)
{
if(app == NULL || app[0] == 0)
{
RDCERR("Invalid empty 'app'");
return 0;
}
// turn environment string to a UTF-8 map
map<string, string> env = EnvStringToEnvMap((const char **)environ);
vector<EnvironmentModification> &modifications = GetEnvModifications();
if (logfile == NULL)
logfile = "";
string libpath;
{
FileIO::GetExecutableFilename(libpath);
libpath = dirname(libpath);
}
string optstr;
{
optstr.reserve(sizeof(CaptureOptions)*2+1);
byte *b = (byte *)opts;
for(size_t i=0; i < sizeof(CaptureOptions); i++)
{
optstr.push_back(char( 'a' + ((b[i] >> 4)&0xf) ));
optstr.push_back(char( 'a' + ((b[i] )&0xf) ));
}
}
modifications.push_back(EnvironmentModification(eEnvModification_AppendPlatform, "LD_LIBRARY_PATH", libpath.c_str()));
modifications.push_back(EnvironmentModification(eEnvModification_AppendPlatform, "LD_PRELOAD", "librenderdoc.so"));
modifications.push_back(EnvironmentModification(eEnvModification_Replace, "RENDERDOC_LOGFILE", logfile));
modifications.push_back(EnvironmentModification(eEnvModification_Replace, "RENDERDOC_CAPTUREOPTS", optstr.c_str()));
for(size_t i=0; i < modifications.size(); i++)
{
EnvironmentModification &m = modifications[i];
string &value = env[m.name];
switch(m.type)
{
case eEnvModification_Replace:
value = m.value;
break;
case eEnvModification_Append:
value += m.value;
break;
case eEnvModification_AppendPlatform:
case eEnvModification_AppendColon:
if(!value.empty())
value += ":";
value += m.value;
break;
case eEnvModification_AppendSemiColon:
if(!value.empty())
value += ";";
value += m.value;
break;
case eEnvModification_Prepend:
value = m.value + value;
break;
case eEnvModification_PrependColon:
if(!value.empty())
value = m.value + ":" + value;
else
value = m.value;
break;
case eEnvModification_PrependPlatform:
case eEnvModification_PrependSemiColon:
if(!value.empty())
value = m.value + ";" + value;
else
value = m.value;
break;
default:
RDCERR("Unexpected environment modification type");
}
}
char **envp = new char *[env.size()+1];
envp[env.size()] = NULL;
int i=0;
for(auto it=env.begin(); it != env.end(); it++)
{
string envline = it->first + "=" + it->second;
envp[i] = new char[envline.size()+1];
memcpy(envp[i], envline.c_str(), envline.size()+1);
i++;
}
pid_t childPid = RunProcess(app, workingDir, cmdLine, envp);
int ret = 0;
if(childPid != (pid_t)0)
{
// wait for child to have /proc/<pid> and read out tcp socket
usleep(1000);
string procfile = StringFormat::Fmt("/proc/%d/net/tcp", (int)childPid);
// try for a little while for the /proc entry to appear
for(int retry=0; retry < 10; retry++)
{
// back-off for each retry
usleep(1000 + 500 * retry);
FILE *f = FileIO::fopen(procfile.c_str(), "r");
if(f == NULL)
{
// try again in a bit
continue;
}
// read through the proc file to check for an open listen socket
while(ret == 0 && !feof(f))
{
const size_t sz = 512;
char line[sz];line[sz-1] = 0;
fgets(line, sz-1, f);
int socketnum = 0, hexip = 0, hexport = 0;
int num = sscanf(line, " %d: %x:%x", &socketnum, &hexip, &hexport);
// find open listen socket on 0.0.0.0:port
if(num == 3 && hexip == 0 &&
hexport >= RenderDoc_FirstCaptureNetworkPort &&
hexport <= RenderDoc_LastCaptureNetworkPort)
{
ret = hexport;
}
}
FileIO::fclose(f);
}
if(waitForExit)
{
int dummy = 0;
waitpid(childPid, &dummy, 0);
}
}
char **envp_delete = envp;
while(*envp)
{
delete[] *envp;
envp++;
}
delete[] envp_delete;
return ret;
}
void Process::StartGlobalHook(const char *pathmatch, const char *logfile, const CaptureOptions *opts)
{
RDCUNIMPLEMENTED("Global hooking of all processes on linux");
}
void *Process::LoadModule(const char *module)
{
return dlopen(module, RTLD_NOW);
}
void *Process::GetFunctionAddress(void *module, const char *function)
{
if(module == NULL) return NULL;
return dlsym(module, function);
}
uint32_t Process::GetCurrentPID()
{
return (uint32_t)getpid();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009 Ian Monroe <imonroe@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "QtScriptSmokeBinding.h"
#include <QtDebug>
#include <QtScript/QScriptValue>
#include "global.h"
#include "virtualmethodcall.h"
#include "SmokeQtScriptUtils.h"
namespace QtScriptSmoke {
Binding::Binding(Smoke* s)
: SmokeBinding(s) { }
char* Binding::className(Smoke::Index classId)
{
qDebug() << "QtScriptSmoke::Binding::className " << smoke->className(classId);
// Convert '::' to '.' here
return (char *) smoke->className(classId);
}
//!method called when a virtual method of a smoke-owned object is called. eg QWidget::mousePressEvent
bool Binding::callMethod(Smoke::Index method, void* ptr, Smoke::Stack args, bool isAbstract)
{
QScriptValue * obj = Global::getScriptValue(ptr);
if (obj == 0) {
if ((Debug::DoDebug & Debug::Virtual) != 0) {
qWarning("Cannot find object for virtual method %p -> %p", ptr, obj);
}
return false;
}
QByteArray methodName(smoke->methodNames[smoke->methods[method].name]);
if ( methodName == "metaObject"
|| methodName == "qt_metacast"
|| methodName == "qt_metacall"
|| methodName == "minimumSizeHint"
|| methodName == "maximumSizeHint"
|| methodName == "x11Event"
|| methodName == "sizeHint" )
{
return false;
}
if ((Debug::DoDebug & Debug::Virtual) != 0) {
Smoke::ModuleIndex methodId = { smoke, method };
qWarning( "module: %s virtual %p->%s::%s called",
smoke->moduleName(),
ptr,
smoke->classes[smoke->methods[method].classId].className,
methodToString(methodId).toLatin1().constData() );
}
Object::Instance * instance = Object::Instance::get(*obj);
if (instance == 0) {
if ((Debug::DoDebug & Debug::Virtual) != 0) {
qWarning("Cannot find instance for virtual method %p -> %p", ptr, obj);
}
return false;
}
// If the virtual method hasn't been overriden, return false and just call the C++ one.
if (obj->propertyFlags(methodName) != 0) {
return false;
}
if ((Debug::DoDebug & Debug::Virtual) != 0) {
qWarning("Method '%s' overriden", methodName.constData());
}
QScriptValue function = obj->property(QString(methodName));
VirtualMethodCall methodCall(smoke, method, args, *obj, function);
methodCall.next();
return true;
}
void Binding::deleted(Smoke::Index classId, void* ptr)
{
QScriptValue * obj = Global::getScriptValue(ptr);
Object::Instance * instance = Object::Instance::get(*obj);
if ((Debug::DoDebug & Debug::GC) != 0) {
qWarning("%p->~%s()", ptr, smoke->className(classId));
}
if (instance == 0 || instance->value == 0) {
return;
}
Global::unmapPointer(instance, instance->classId.index, 0);
instance->value = 0;
return;
}
}
<commit_msg>* Special case the 'contentsMargins' virtual method, and don't allow it to be overriden<commit_after>/*
* Copyright 2009 Ian Monroe <imonroe@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) version 3, or any
* later version accepted by the membership of KDE e.V. (or its
* successor approved by the membership of KDE e.V.), which shall
* act as a proxy defined in Section 6 of version 3 of the license.
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "QtScriptSmokeBinding.h"
#include <QtDebug>
#include <QtScript/QScriptValue>
#include "global.h"
#include "virtualmethodcall.h"
#include "SmokeQtScriptUtils.h"
namespace QtScriptSmoke {
Binding::Binding(Smoke* s)
: SmokeBinding(s) { }
char* Binding::className(Smoke::Index classId)
{
qDebug() << "QtScriptSmoke::Binding::className " << smoke->className(classId);
// Convert '::' to '.' here
return (char *) smoke->className(classId);
}
//!method called when a virtual method of a smoke-owned object is called. eg QWidget::mousePressEvent
bool Binding::callMethod(Smoke::Index method, void* ptr, Smoke::Stack args, bool isAbstract)
{
QScriptValue * obj = Global::getScriptValue(ptr);
if (obj == 0) {
if ((Debug::DoDebug & Debug::Virtual) != 0) {
qWarning("Cannot find object for virtual method %p -> %p", ptr, obj);
}
return false;
}
QByteArray methodName(smoke->methodNames[smoke->methods[method].name]);
if ( methodName == "metaObject"
|| methodName == "qt_metacast"
|| methodName == "qt_metacall"
|| methodName == "minimumSizeHint"
|| methodName == "maximumSizeHint"
|| methodName == "x11Event"
|| methodName == "contentsMargins"
|| methodName == "sizeHint" )
{
return false;
}
if ((Debug::DoDebug & Debug::Virtual) != 0) {
Smoke::ModuleIndex methodId = { smoke, method };
qWarning( "module: %s virtual %p->%s::%s called",
smoke->moduleName(),
ptr,
smoke->classes[smoke->methods[method].classId].className,
methodToString(methodId).toLatin1().constData() );
}
Object::Instance * instance = Object::Instance::get(*obj);
if (instance == 0) {
if ((Debug::DoDebug & Debug::Virtual) != 0) {
qWarning("Cannot find instance for virtual method %p -> %p", ptr, obj);
}
return false;
}
// If the virtual method hasn't been overriden, return false and just call the C++ one.
if (obj->propertyFlags(methodName) != 0) {
return false;
}
if ((Debug::DoDebug & Debug::Virtual) != 0) {
qWarning("Method '%s' overriden", methodName.constData());
}
QScriptValue function = obj->property(QString(methodName));
VirtualMethodCall methodCall(smoke, method, args, *obj, function);
methodCall.next();
return true;
}
void Binding::deleted(Smoke::Index classId, void* ptr)
{
QScriptValue * obj = Global::getScriptValue(ptr);
Object::Instance * instance = Object::Instance::get(*obj);
if ((Debug::DoDebug & Debug::GC) != 0) {
qWarning("%p->~%s()", ptr, smoke->className(classId));
}
if (instance == 0 || instance->value == 0) {
return;
}
Global::unmapPointer(instance, instance->classId.index, 0);
instance->value = 0;
return;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <string>
#include "os/os_specific.h"
#include "strings/string_utils.h"
#include "posix_network.h"
using std::string;
// because strerror_r is a complete mess...
static std::string errno_string(int err)
{
switch(err)
{
#if EAGAIN != EWOULDBLOCK
case EAGAIN:
#endif
case EWOULDBLOCK: return "EWOULDBLOCK: Operation would block.";
case EINVAL: return "EINVAL: Invalid argument.";
case EADDRINUSE: return "EADDRINUSE: Address already in use.";
case ECONNRESET: return "ECONNRESET: A connection was forcibly closed by a peer.";
case EINPROGRESS: return "EINPROGRESS: Operation now in progress.";
case EINTR:
return "EINTR: The function was interrupted by a signal that was caught, before any data was "
"available.";
case ETIMEDOUT: return "ETIMEDOUT: A socket operation timed out.";
case ECONNABORTED: return "ECONNABORTED: A connection has been aborted.";
case ECONNREFUSED: return "ECONNREFUSED: A connection was refused.";
case EHOSTDOWN: return "EHOSTDOWN: Host is down.";
case EHOSTUNREACH: return "EHOSTUNREACH: No route to host.";
default: break;
}
return StringFormat::Fmt("Unknown error %d", err);
}
namespace Network
{
void Init()
{
}
void Shutdown()
{
}
Socket::~Socket()
{
Shutdown();
}
void Socket::Shutdown()
{
if(Connected())
{
shutdown((int)socket, SHUT_RDWR);
close((int)socket);
socket = -1;
}
}
bool Socket::Connected() const
{
return (int)socket != -1;
}
Socket *Socket::AcceptClient(bool wait)
{
do
{
int s = accept(socket, NULL, NULL);
if(s != -1)
{
int flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
int nodelay = 1;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));
return new Socket((ptrdiff_t)s);
}
int err = errno;
if(err != EWOULDBLOCK && err != EAGAIN)
{
RDCWARN("accept: %s", errno_string(err).c_str());
Shutdown();
}
Threading::Sleep(4);
} while(wait);
return NULL;
}
bool Socket::SendDataBlocking(const void *buf, uint32_t length)
{
if(length == 0)
return true;
uint32_t sent = 0;
char *src = (char *)buf;
int flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);
timeval oldtimeout = {0};
socklen_t len = sizeof(oldtimeout);
getsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&oldtimeout, &len);
timeval timeout = {0};
timeout.tv_sec = (timeoutMS / 1000);
timeout.tv_usec = (timeoutMS % 1000) * 1000;
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout, sizeof(timeout));
while(sent < length)
{
int ret = send(socket, src, length - sent, 0);
if(ret <= 0)
{
int err = errno;
if(err == EWOULDBLOCK || err == EAGAIN)
{
RDCWARN("Timeout in send");
Shutdown();
return false;
}
else
{
RDCWARN("send: %s", errno_string(err).c_str());
Shutdown();
return false;
}
}
sent += ret;
src += ret;
}
flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags | O_NONBLOCK);
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (const char *)&oldtimeout, sizeof(oldtimeout));
RDCASSERT(sent == length);
return true;
}
bool Socket::IsRecvDataWaiting()
{
char dummy;
int ret = recv(socket, &dummy, 1, MSG_PEEK);
if(ret == 0)
{
Shutdown();
return false;
}
else if(ret <= 0)
{
int err = errno;
if(err == EWOULDBLOCK || err == EAGAIN)
{
ret = 0;
}
else
{
RDCWARN("recv: %s", errno_string(err).c_str());
Shutdown();
return false;
}
}
return ret > 0;
}
bool Socket::RecvDataNonBlocking(void *buf, uint32_t &length)
{
if(length == 0)
return true;
// socket is already blocking, don't have to change anything
int ret = recv(socket, (char *)buf, length, 0);
if(ret > 0)
{
length = (uint32_t)ret;
}
else
{
length = 0;
int err = errno;
if(err == EWOULDBLOCK || err == EAGAIN)
{
return true;
}
else
{
RDCWARN("recv: %s", errno_string(err).c_str());
Shutdown();
return false;
}
}
return true;
}
bool Socket::RecvDataBlocking(void *buf, uint32_t length)
{
if(length == 0)
return true;
uint32_t received = 0;
char *dst = (char *)buf;
int flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);
timeval oldtimeout = {0};
socklen_t len = sizeof(oldtimeout);
getsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&oldtimeout, &len);
timeval timeout = {0};
timeout.tv_sec = (timeoutMS / 1000);
timeout.tv_usec = (timeoutMS % 1000) * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout));
while(received < length)
{
int ret = recv(socket, dst, length - received, 0);
if(ret == 0)
{
Shutdown();
return false;
}
else if(ret <= 0)
{
int err = errno;
if(err == EWOULDBLOCK || err == EAGAIN)
{
RDCWARN("Timeout in recv");
Shutdown();
return false;
}
else
{
RDCWARN("recv: %s", errno_string(err).c_str());
Shutdown();
return false;
}
}
received += ret;
dst += ret;
}
flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags | O_NONBLOCK);
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&oldtimeout, sizeof(oldtimeout));
RDCASSERT(received == length);
return true;
}
uint32_t GetIPFromTCPSocket(int socket)
{
sockaddr_in addr = {};
socklen_t len = sizeof(addr);
getpeername(socket, (sockaddr *)&addr, &len);
return ntohl(addr.sin_addr.s_addr);
}
Socket *CreateTCPServerSocket(const char *bindaddr, uint16_t port, int queuesize)
{
int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int yes = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if(s == -1)
return NULL;
sockaddr_in addr;
RDCEraseEl(addr);
hostent *hp = gethostbyname(bindaddr);
addr.sin_family = AF_INET;
memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
addr.sin_port = htons(port);
int result = bind(s, (sockaddr *)&addr, sizeof(addr));
if(result == -1)
{
RDCWARN("Failed to bind to %s:%d - %d", bindaddr, port, errno);
close(s);
return NULL;
}
result = listen(s, queuesize);
if(result == -1)
{
RDCWARN("Failed to listen on %s:%d - %d", bindaddr, port, errno);
close(s);
return NULL;
}
int flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
return new Socket((ptrdiff_t)s);
}
Socket *CreateAbstractServerSocket(uint16_t port, int queuesize)
{
char socketName[17] = {0};
StringFormat::snprintf(socketName, 16, "renderdoc_%d", port);
int socketNameLength = strlen(socketName);
int s = socket(AF_UNIX, SOCK_STREAM, 0);
if(s == -1)
{
RDCWARN("Unable to create unix socket");
return NULL;
}
sockaddr_un addr;
RDCEraseEl(addr);
addr.sun_family = AF_UNIX;
// first char is '\0'
addr.sun_path[0] = '\0';
strncpy(addr.sun_path + 1, socketName, socketNameLength);
int result = bind(s, (sockaddr *)&addr, offsetof(sockaddr_un, sun_path) + 1 + socketNameLength);
if(result == -1)
{
RDCWARN("Failed to create abstract socket: %s", socketName);
close(s);
return NULL;
}
RDCLOG("Created and bind socket: %d", s);
result = listen(s, queuesize);
if(result == -1)
{
RDCWARN("Failed to listen on %s", socketName);
close(s);
return NULL;
}
int flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
return new Socket((ptrdiff_t)s);
}
Socket *CreateClientSocket(const char *host, uint16_t port, int timeoutMS)
{
char portstr[7] = {0};
StringFormat::snprintf(portstr, 6, "%d", port);
addrinfo hints;
RDCEraseEl(hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addrinfo *result = NULL;
getaddrinfo(host, portstr, &hints, &result);
for(addrinfo *ptr = result; ptr != NULL; ptr = ptr->ai_next)
{
int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(s == -1)
return NULL;
int flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
int result = connect(s, ptr->ai_addr, (int)ptr->ai_addrlen);
if(result == -1)
{
fd_set set;
FD_ZERO(&set);
FD_SET(s, &set);
int err = errno;
if(err == EWOULDBLOCK || err == EINPROGRESS)
{
timeval timeout;
timeout.tv_sec = (timeoutMS / 1000);
timeout.tv_usec = (timeoutMS % 1000) * 1000;
result = select(s + 1, NULL, &set, NULL, &timeout);
if(result <= 0)
{
RDCDEBUG("Timed out");
close(s);
continue;
}
socklen_t len = sizeof(err);
getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &len);
}
if(err != 0)
{
RDCDEBUG("%s", errno_string(err).c_str());
close(s);
continue;
}
}
int nodelay = 1;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));
return new Socket((ptrdiff_t)s);
}
RDCDEBUG("Failed to connect to %s:%d", host, port);
return NULL;
}
bool ParseIPRangeCIDR(const char *str, uint32_t &ip, uint32_t &mask)
{
uint32_t a = 0, b = 0, c = 0, d = 0, num = 0;
int ret = sscanf(str, "%u.%u.%u.%u/%u", &a, &b, &c, &d, &num);
if(ret != 5 || a > 255 || b > 255 || c > 255 || d > 255 || num > 32)
{
ip = 0;
mask = 0;
return false;
}
ip = MakeIP(a, b, c, d);
if(num == 0)
{
mask = 0;
}
else
{
num = 32 - num;
mask = ((~0U) >> num) << num;
}
return true;
}
};
<commit_msg>Copy trailing null byte to keep GCC warnings happy. Closes #1028<commit_after>/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2016-2018 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <string>
#include "os/os_specific.h"
#include "strings/string_utils.h"
#include "posix_network.h"
using std::string;
// because strerror_r is a complete mess...
static std::string errno_string(int err)
{
switch(err)
{
#if EAGAIN != EWOULDBLOCK
case EAGAIN:
#endif
case EWOULDBLOCK: return "EWOULDBLOCK: Operation would block.";
case EINVAL: return "EINVAL: Invalid argument.";
case EADDRINUSE: return "EADDRINUSE: Address already in use.";
case ECONNRESET: return "ECONNRESET: A connection was forcibly closed by a peer.";
case EINPROGRESS: return "EINPROGRESS: Operation now in progress.";
case EINTR:
return "EINTR: The function was interrupted by a signal that was caught, before any data was "
"available.";
case ETIMEDOUT: return "ETIMEDOUT: A socket operation timed out.";
case ECONNABORTED: return "ECONNABORTED: A connection has been aborted.";
case ECONNREFUSED: return "ECONNREFUSED: A connection was refused.";
case EHOSTDOWN: return "EHOSTDOWN: Host is down.";
case EHOSTUNREACH: return "EHOSTUNREACH: No route to host.";
default: break;
}
return StringFormat::Fmt("Unknown error %d", err);
}
namespace Network
{
void Init()
{
}
void Shutdown()
{
}
Socket::~Socket()
{
Shutdown();
}
void Socket::Shutdown()
{
if(Connected())
{
shutdown((int)socket, SHUT_RDWR);
close((int)socket);
socket = -1;
}
}
bool Socket::Connected() const
{
return (int)socket != -1;
}
Socket *Socket::AcceptClient(bool wait)
{
do
{
int s = accept(socket, NULL, NULL);
if(s != -1)
{
int flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
int nodelay = 1;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));
return new Socket((ptrdiff_t)s);
}
int err = errno;
if(err != EWOULDBLOCK && err != EAGAIN)
{
RDCWARN("accept: %s", errno_string(err).c_str());
Shutdown();
}
Threading::Sleep(4);
} while(wait);
return NULL;
}
bool Socket::SendDataBlocking(const void *buf, uint32_t length)
{
if(length == 0)
return true;
uint32_t sent = 0;
char *src = (char *)buf;
int flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);
timeval oldtimeout = {0};
socklen_t len = sizeof(oldtimeout);
getsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&oldtimeout, &len);
timeval timeout = {0};
timeout.tv_sec = (timeoutMS / 1000);
timeout.tv_usec = (timeoutMS % 1000) * 1000;
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (const char *)&timeout, sizeof(timeout));
while(sent < length)
{
int ret = send(socket, src, length - sent, 0);
if(ret <= 0)
{
int err = errno;
if(err == EWOULDBLOCK || err == EAGAIN)
{
RDCWARN("Timeout in send");
Shutdown();
return false;
}
else
{
RDCWARN("send: %s", errno_string(err).c_str());
Shutdown();
return false;
}
}
sent += ret;
src += ret;
}
flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags | O_NONBLOCK);
setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, (const char *)&oldtimeout, sizeof(oldtimeout));
RDCASSERT(sent == length);
return true;
}
bool Socket::IsRecvDataWaiting()
{
char dummy;
int ret = recv(socket, &dummy, 1, MSG_PEEK);
if(ret == 0)
{
Shutdown();
return false;
}
else if(ret <= 0)
{
int err = errno;
if(err == EWOULDBLOCK || err == EAGAIN)
{
ret = 0;
}
else
{
RDCWARN("recv: %s", errno_string(err).c_str());
Shutdown();
return false;
}
}
return ret > 0;
}
bool Socket::RecvDataNonBlocking(void *buf, uint32_t &length)
{
if(length == 0)
return true;
// socket is already blocking, don't have to change anything
int ret = recv(socket, (char *)buf, length, 0);
if(ret > 0)
{
length = (uint32_t)ret;
}
else
{
length = 0;
int err = errno;
if(err == EWOULDBLOCK || err == EAGAIN)
{
return true;
}
else
{
RDCWARN("recv: %s", errno_string(err).c_str());
Shutdown();
return false;
}
}
return true;
}
bool Socket::RecvDataBlocking(void *buf, uint32_t length)
{
if(length == 0)
return true;
uint32_t received = 0;
char *dst = (char *)buf;
int flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags & ~O_NONBLOCK);
timeval oldtimeout = {0};
socklen_t len = sizeof(oldtimeout);
getsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&oldtimeout, &len);
timeval timeout = {0};
timeout.tv_sec = (timeoutMS / 1000);
timeout.tv_usec = (timeoutMS % 1000) * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&timeout, sizeof(timeout));
while(received < length)
{
int ret = recv(socket, dst, length - received, 0);
if(ret == 0)
{
Shutdown();
return false;
}
else if(ret <= 0)
{
int err = errno;
if(err == EWOULDBLOCK || err == EAGAIN)
{
RDCWARN("Timeout in recv");
Shutdown();
return false;
}
else
{
RDCWARN("recv: %s", errno_string(err).c_str());
Shutdown();
return false;
}
}
received += ret;
dst += ret;
}
flags = fcntl(socket, F_GETFL, 0);
fcntl(socket, F_SETFL, flags | O_NONBLOCK);
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char *)&oldtimeout, sizeof(oldtimeout));
RDCASSERT(received == length);
return true;
}
uint32_t GetIPFromTCPSocket(int socket)
{
sockaddr_in addr = {};
socklen_t len = sizeof(addr);
getpeername(socket, (sockaddr *)&addr, &len);
return ntohl(addr.sin_addr.s_addr);
}
Socket *CreateTCPServerSocket(const char *bindaddr, uint16_t port, int queuesize)
{
int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
int yes = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
if(s == -1)
return NULL;
sockaddr_in addr;
RDCEraseEl(addr);
hostent *hp = gethostbyname(bindaddr);
addr.sin_family = AF_INET;
memcpy(&addr.sin_addr, hp->h_addr, hp->h_length);
addr.sin_port = htons(port);
int result = bind(s, (sockaddr *)&addr, sizeof(addr));
if(result == -1)
{
RDCWARN("Failed to bind to %s:%d - %d", bindaddr, port, errno);
close(s);
return NULL;
}
result = listen(s, queuesize);
if(result == -1)
{
RDCWARN("Failed to listen on %s:%d - %d", bindaddr, port, errno);
close(s);
return NULL;
}
int flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
return new Socket((ptrdiff_t)s);
}
Socket *CreateAbstractServerSocket(uint16_t port, int queuesize)
{
char socketName[17] = {0};
StringFormat::snprintf(socketName, 16, "renderdoc_%d", port);
int socketNameLength = strlen(socketName);
int s = socket(AF_UNIX, SOCK_STREAM, 0);
if(s == -1)
{
RDCWARN("Unable to create unix socket");
return NULL;
}
sockaddr_un addr;
RDCEraseEl(addr);
addr.sun_family = AF_UNIX;
// first char is '\0'
addr.sun_path[0] = '\0';
strncpy(addr.sun_path + 1, socketName, socketNameLength + 1);
int result = bind(s, (sockaddr *)&addr, offsetof(sockaddr_un, sun_path) + 1 + socketNameLength);
if(result == -1)
{
RDCWARN("Failed to create abstract socket: %s", socketName);
close(s);
return NULL;
}
RDCLOG("Created and bind socket: %d", s);
result = listen(s, queuesize);
if(result == -1)
{
RDCWARN("Failed to listen on %s", socketName);
close(s);
return NULL;
}
int flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
return new Socket((ptrdiff_t)s);
}
Socket *CreateClientSocket(const char *host, uint16_t port, int timeoutMS)
{
char portstr[7] = {0};
StringFormat::snprintf(portstr, 6, "%d", port);
addrinfo hints;
RDCEraseEl(hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addrinfo *result = NULL;
getaddrinfo(host, portstr, &hints, &result);
for(addrinfo *ptr = result; ptr != NULL; ptr = ptr->ai_next)
{
int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(s == -1)
return NULL;
int flags = fcntl(s, F_GETFL, 0);
fcntl(s, F_SETFL, flags | O_NONBLOCK);
int result = connect(s, ptr->ai_addr, (int)ptr->ai_addrlen);
if(result == -1)
{
fd_set set;
FD_ZERO(&set);
FD_SET(s, &set);
int err = errno;
if(err == EWOULDBLOCK || err == EINPROGRESS)
{
timeval timeout;
timeout.tv_sec = (timeoutMS / 1000);
timeout.tv_usec = (timeoutMS % 1000) * 1000;
result = select(s + 1, NULL, &set, NULL, &timeout);
if(result <= 0)
{
RDCDEBUG("Timed out");
close(s);
continue;
}
socklen_t len = sizeof(err);
getsockopt(s, SOL_SOCKET, SO_ERROR, &err, &len);
}
if(err != 0)
{
RDCDEBUG("%s", errno_string(err).c_str());
close(s);
continue;
}
}
int nodelay = 1;
setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (char *)&nodelay, sizeof(nodelay));
return new Socket((ptrdiff_t)s);
}
RDCDEBUG("Failed to connect to %s:%d", host, port);
return NULL;
}
bool ParseIPRangeCIDR(const char *str, uint32_t &ip, uint32_t &mask)
{
uint32_t a = 0, b = 0, c = 0, d = 0, num = 0;
int ret = sscanf(str, "%u.%u.%u.%u/%u", &a, &b, &c, &d, &num);
if(ret != 5 || a > 255 || b > 255 || c > 255 || d > 255 || num > 32)
{
ip = 0;
mask = 0;
return false;
}
ip = MakeIP(a, b, c, d);
if(num == 0)
{
mask = 0;
}
else
{
num = 32 - num;
mask = ((~0U) >> num) << num;
}
return true;
}
};
<|endoftext|> |
<commit_before>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);
m_pRole = new CFPSRoleLocal();
m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ
m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3
m_pSkillSystem = new CSkillSystem(this);
m_pCameraBase = new CCameraBase();
m_pCameraBase->SetEnabled(1);
g_pSysControl->SetMouseGrab(1);
m_pStarControl = new CStarControl();
m_pRayControl = new CRayControl();
return 1;
}
int CGameProcess::ShutDown() //رϷ
{
delete m_pRole;
delete m_pSkillSystem;
delete m_pCameraBase;
delete m_pStarControl;
delete m_pRayControl;
DelAllListen();
return 0;
}
int CGameProcess::Update()
{
float ifps = g_Engine.pGame->GetIFps();
if (g_Engine.pInput->IsKeyDown('1'))
{
CAction* pAction = m_pRole->OrceAction("attack02");
if (pAction)
{
pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('2'))
{
CAction* pAction = m_pRole->OrceAction("skill01");
if (pAction)
{
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('3'))
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CRoleBase* pTarget = NULL;
}
}
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 15.0f)
{
pTarget = m_vAIList[i];
break;
}
}
if (pTarget)
{
CVector<int> vTarget;
vTarget.Append(pTarget->GetRoleID());
}
return 0;
}
<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h"
#include "Object.h"
#include "Engine.h"
#include "World.h"
#include "App.h"
#include "ToolsCamera.h"
#include "ControlsApp.h"
#include "MathLib.h"
#include "Game.h"
#include "Editor.h"
#include "Input.h"
#include "BlueRayUtils.h"
using namespace MathLib;
CGameProcess::CGameProcess(void)
{
}
CGameProcess::~CGameProcess(void)
{
}
int CGameProcess::Init()
{
g_Engine.pFileSystem->CacheFilesFormExt("char");
g_Engine.pFileSystem->CacheFilesFormExt("node");
g_Engine.pFileSystem->CacheFilesFormExt("smesh");
g_Engine.pFileSystem->CacheFilesFormExt("sanim");
g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world");
//g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world");
g_Engine.pControls->SetKeyPressFunc(KeyPress);
g_Engine.pControls->SetKeyReleaseFunc(KeyRelease);
m_pRole = new CFPSRoleLocal();
m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); //ؽɫԴ
m_pRole->SetActorPosition(vec3(0, 0, 0)); //ýɫʼλáŴΪԭ㣬άϵvec3
m_pSkillSystem = new CSkillSystem(this);
m_pCameraBase = new CCameraBase();
m_pCameraBase->SetEnabled(1);
g_pSysControl->SetMouseGrab(1);
m_pStarControl = new CStarControl();
m_pRayControl = new CRayControl();
return 1;
}
int CGameProcess::ShutDown() //رϷ
{
delete m_pRole;
delete m_pSkillSystem;
delete m_pCameraBase;
delete m_pStarControl;
delete m_pRayControl;
DelAllListen();
return 0;
}
int CGameProcess::Update()
{
float ifps = g_Engine.pGame->GetIFps();
if (g_Engine.pInput->IsKeyDown('1'))
{
CAction* pAction = m_pRole->OrceAction("attack02");
if (pAction)
{
pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f);
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('2'))
{
CAction* pAction = m_pRole->OrceAction("skill01");
if (pAction)
{
m_pRole->StopMove();
}
}
else if (g_Engine.pInput->IsKeyDown('3'))
{
CAction* pAction = m_pRole->OrceAction("skill02");
if (pAction)
{
m_pRole->StopMove();
CRoleBase* pTarget = NULL;
}
}
for (int i = 0; i < 20; i++)
{
float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length();
if (l > 5.0f && l < 15.0f)
{
pTarget = m_vAIList[i];
break;
}
}
if (pTarget)
{
CVector<int> vTarget;
vTarget.Append(pTarget->GetRoleID());
pAction->SetupSkillBulletTarget(vTarget);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "Application.h"
#include "DefaultSettings.h"
#include "Database.h"
#include "Player.h"
#include "SmartmontoolsNotifier.h"
#include "CdromManager.h"
#include "OnlineDBPluginManager.h"
#include "Database.h"
#include "Player.h"
/*
* Derived form QCoreApplication
* Set Organization name, domain and application name
*
* Create Websocket server for API
* Create DiscoveryServer for autodetection of clients
*
*/
Application::Application(int & argc, char ** argv) :
QCoreApplication(argc, argv)
{
QCoreApplication::setOrganizationName("Enna");
QCoreApplication::setOrganizationDomain("enna.me");
QCoreApplication::setApplicationName("EnnaMediaServer");
QSettings settings;
/* Read value for websocket port */
m_websocketPort = settings.value("main/websocket_port", EMS_WEBSOCKET_PORT).toInt();
/* Save websocket back if it's not found in initial config file */
settings.setValue("main/websocket_port", m_websocketPort);
/* Read locations path in config and add them to the scanner object */
int size = settings.beginReadArray("locations");
for (int i = 0; i < size; ++i) {
settings.setArrayIndex(i);
m_scanner.locationAdd(settings.value("path").toString());
}
settings.endArray();
/* Add online database plugins */
OnlineDBPluginManager::instance()->registerAllPlugins();
/* Open Database */
Database::instance()->open();
/* Start the CDROM manager */
CdromManager::instance()->moveToThread(&m_cdromManagerWorker);
connect(&m_cdromManagerWorker, &QThread::started, CdromManager::instance(), &CdromManager::startMonitor);
connect(&m_cdromManagerWorker, &QThread::finished, CdromManager::instance(), &CdromManager::stopMonitor);
m_cdromManagerWorker.start();
/* Start the player */
Player::instance()->start();
/* Create Websocket server */
m_webSocketServer = new WebSocketServer(m_websocketPort, this);
/* Create Discovery Server */
m_discoveryServer = new DiscoveryServer(BCAST_UDP_PORT, this);
m_smartmontools = new SmartmontoolsNotifier(this);
}
Application::~Application()
{
/* Stop the CDROM manager */
m_cdromManagerWorker.quit();
m_cdromManagerWorker.wait();
/* Stop the player thread */
Player::instance()->kill();
Player::instance()->wait(1000);
/* Close properly the database */
Database::instance()->close();
}
<commit_msg>Load websocket port from seting file<commit_after>#include "Application.h"
#include "DefaultSettings.h"
#include "Database.h"
#include "Player.h"
#include "SmartmontoolsNotifier.h"
#include "CdromManager.h"
#include "OnlineDBPluginManager.h"
#include "Database.h"
#include "Player.h"
/*
* Derived form QCoreApplication
* Set Organization name, domain and application name
*
* Create Websocket server for API
* Create DiscoveryServer for autodetection of clients
*
*/
Application::Application(int & argc, char ** argv) :
QCoreApplication(argc, argv)
{
QCoreApplication::setOrganizationName("Enna");
QCoreApplication::setOrganizationDomain("enna.me");
QCoreApplication::setApplicationName("EnnaMediaServer");
QSettings settings(QCoreApplication::organizationName(), QCoreApplication::applicationName());
/* Read value for websocket port */
if (settings.contains("main/websocket_port"))
m_websocketPort = settings.value("main/websocket_port").toInt();
/* Save websocket back if it's not found in initial config file */
else
{
m_websocketPort = EMS_WEBSOCKET_PORT;
settings.setValue("main/websocket_port", m_websocketPort);
}
/* Read locations path in config and add them to the scanner object */
int size = settings.beginReadArray("locations");
for (int i = 0; i < size; ++i) {
settings.setArrayIndex(i);
m_scanner.locationAdd(settings.value("path").toString());
}
settings.endArray();
/* Add online database plugins */
OnlineDBPluginManager::instance()->registerAllPlugins();
/* Open Database */
Database::instance()->open();
/* Start the CDROM manager */
CdromManager::instance()->moveToThread(&m_cdromManagerWorker);
connect(&m_cdromManagerWorker, &QThread::started, CdromManager::instance(), &CdromManager::startMonitor);
connect(&m_cdromManagerWorker, &QThread::finished, CdromManager::instance(), &CdromManager::stopMonitor);
m_cdromManagerWorker.start();
/* Start the player */
Player::instance()->start();
/* Create Websocket server */
m_webSocketServer = new WebSocketServer(m_websocketPort, this);
/* Create Discovery Server */
m_discoveryServer = new DiscoveryServer(BCAST_UDP_PORT, this);
m_smartmontools = new SmartmontoolsNotifier(this);
}
Application::~Application()
{
/* Stop the CDROM manager */
m_cdromManagerWorker.quit();
m_cdromManagerWorker.wait();
/* Stop the player thread */
Player::instance()->kill();
Player::instance()->wait(1000);
/* Close properly the database */
Database::instance()->close();
}
<|endoftext|> |
<commit_before>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2012-06-05 GONG Chen <chen.sst@gmail.com>
//
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/config.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/schema.h>
#include <rime/gear/chord_composer.h>
// U+FEFF works better with MacType
static const char* kZeroWidthSpace = "\xef\xbb\xbf"; //"\xe2\x80\x8b";
namespace rime {
ChordComposer::ChordComposer(const Ticket& ticket) : Processor(ticket) {
if (!engine_)
return;
if (Config* config = engine_->schema()->config()) {
string alphabet;
config->GetString("chord_composer/alphabet", &alphabet);
chording_keys_.Parse(alphabet);
config->GetBool("chord_composer/use_control", &use_control_);
config->GetBool("chord_composer/use_alt", &use_alt_);
config->GetBool("chord_composer/use_shift", &use_shift_);
config->GetString("speller/delimiter", &delimiter_);
algebra_.Load(config->GetList("chord_composer/algebra"));
output_format_.Load(config->GetList("chord_composer/output_format"));
prompt_format_.Load(config->GetList("chord_composer/prompt_format"));
}
Context* ctx = engine_->context();
ctx->set_option("_chord_typing", true);
update_connection_ = ctx->update_notifier().connect(
[this](Context* ctx) { OnContextUpdate(ctx); });
unhandled_key_connection_ = ctx->unhandled_key_notifier().connect(
[this](Context* ctx, const KeyEvent& key) { OnUnhandledKey(ctx, key); });
}
ChordComposer::~ChordComposer() {
update_connection_.disconnect();
unhandled_key_connection_.disconnect();
}
ProcessResult ChordComposer::ProcessFunctionKey(const KeyEvent& key_event) {
if (key_event.release()) {
return kNoop;
}
int ch = key_event.keycode();
if (ch == XK_Return) {
if (!raw_sequence_.empty()) {
// commit raw input
engine_->context()->set_input(raw_sequence_);
// then the sequence should not be used again
raw_sequence_.clear();
}
ClearChord();
} else if (ch == XK_BackSpace || ch == XK_Escape) {
// clear the raw sequence
raw_sequence_.clear();
ClearChord();
}
return kNoop;
}
// Note: QWERTY layout only.
static const char map_to_base_layer[] = {
" 1'3457'908=,-./"
"0123456789;;,=./"
"2abcdefghijklmno"
"pqrstuvwxyz[\\]6-"
"`abcdefghijklmno"
"pqrstuvwxyz[\\]`"
};
inline static int get_base_layer_key_code(const KeyEvent& key_event) {
int ch = key_event.keycode();
bool is_shift = key_event.shift();
return (is_shift && ch >= 0x20 && ch <= 0x7e)
? map_to_base_layer[ch - 0x20] : ch;
}
ProcessResult ChordComposer::ProcessChordingKey(const KeyEvent& key_event) {
if (key_event.ctrl() || key_event.alt()) {
raw_sequence_.clear();
}
if (key_event.ctrl() && !use_control_ ||
key_event.alt() && !use_alt_ ||
key_event.shift() && !use_shift_) {
ClearChord();
return kNoop;
}
int ch = get_base_layer_key_code(key_event);
// non chording key
if (std::find(chording_keys_.begin(),
chording_keys_.end(),
KeyEvent{ch, 0}) == chording_keys_.end()) {
ClearChord();
return kNoop;
}
// chording key
bool is_key_up = key_event.release();
if (is_key_up) {
if (pressed_.erase(ch) != 0 && pressed_.empty()) {
FinishChord();
}
}
else { // key down
pressed_.insert(ch);
bool updated = chord_.insert(ch).second;
if (updated)
UpdateChord();
}
return kAccepted;
}
inline static bool is_composing_text(Context* ctx) {
return ctx->IsComposing() && ctx->input() != kZeroWidthSpace;
}
ProcessResult ChordComposer::ProcessKeyEvent(const KeyEvent& key_event) {
if (engine_->context()->get_option("ascii_mode")) {
return kNoop;
}
if (pass_thru_) {
return ProcessFunctionKey(key_event);
}
bool is_key_up = key_event.release();
int ch = key_event.keycode();
if (!is_key_up && ch >= 0x20 && ch <= 0x7e) {
// save raw input
if (!is_composing_text(engine_->context()) || !raw_sequence_.empty()) {
raw_sequence_.push_back(ch);
DLOG(INFO) << "update raw sequence: " << raw_sequence_;
}
}
auto result = ProcessChordingKey(key_event);
if (result != kNoop) {
return result;
}
return ProcessFunctionKey(key_event);
}
string ChordComposer::SerializeChord() {
KeySequence key_sequence;
for (KeyEvent key : chording_keys_) {
if (chord_.find(key.keycode()) != chord_.end())
key_sequence.push_back(key);
}
string code = key_sequence.repr();
algebra_.Apply(&code);
return code;
}
void ChordComposer::UpdateChord() {
if (!engine_)
return;
Context* ctx = engine_->context();
Composition& comp = ctx->composition();
string code = SerializeChord();
prompt_format_.Apply(&code);
if (comp.empty()) {
// add an invisbile place holder segment
// 1. to cheat ctx->IsComposing() == true
// 2. to attach chord prompt to while chording
ctx->PushInput(kZeroWidthSpace);
if (comp.empty()) {
LOG(ERROR) << "failed to update chord.";
return;
}
comp.back().tags.insert("phony");
}
comp.back().tags.insert("chord_prompt");
comp.back().prompt = code;
}
void ChordComposer::FinishChord() {
if (!engine_)
return;
string code = SerializeChord();
output_format_.Apply(&code);
ClearChord();
KeySequence key_sequence;
if (key_sequence.Parse(code) && !key_sequence.empty()) {
pass_thru_ = true;
for (const KeyEvent& key : key_sequence) {
if (!engine_->ProcessKey(key)) {
// direct commit
engine_->CommitText(string(1, key.keycode()));
// exclude the character (eg. space) from the raw sequence
raw_sequence_.clear();
}
}
pass_thru_ = false;
}
}
void ChordComposer::ClearChord() {
pressed_.clear();
chord_.clear();
if (!engine_)
return;
Context* ctx = engine_->context();
Composition& comp = ctx->composition();
if (comp.empty()) {
return;
}
if (comp.input().substr(comp.back().start) == kZeroWidthSpace) {
ctx->PopInput(ctx->caret_pos() - comp.back().start);
}
else if (comp.back().HasTag("chord_prompt")) {
comp.back().prompt.clear();
comp.back().tags.erase("chord_prompt");
}
}
void ChordComposer::OnContextUpdate(Context* ctx) {
if (is_composing_text(ctx)) {
composing_ = true;
}
else if (composing_) {
composing_ = false;
raw_sequence_.clear();
DLOG(INFO) << "clear raw sequence.";
}
}
void ChordComposer::OnUnhandledKey(Context* ctx, const KeyEvent& key) {
// directly committed ascii should not be captured into the raw sequence
// test case:
// 3.14{Return} should not commit an extra sequence '14'
if ((key.modifier() & ~kShiftMask) == 0 &&
key.keycode() >= 0x20 && key.keycode() <= 0x7e) {
raw_sequence_.clear();
DLOG(INFO) << "clear raw sequence.";
}
}
} // namespace rime
<commit_msg>fix(chord_composer): more safely handle the placeholder ZWSP<commit_after>//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2012-06-05 GONG Chen <chen.sst@gmail.com>
//
#include <rime/common.h>
#include <rime/composition.h>
#include <rime/config.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/key_event.h>
#include <rime/schema.h>
#include <rime/gear/chord_composer.h>
static const char* kZeroWidthSpace = "\xe2\x80\x8b"; // U+200B
namespace rime {
ChordComposer::ChordComposer(const Ticket& ticket) : Processor(ticket) {
if (!engine_)
return;
if (Config* config = engine_->schema()->config()) {
string alphabet;
config->GetString("chord_composer/alphabet", &alphabet);
chording_keys_.Parse(alphabet);
config->GetBool("chord_composer/use_control", &use_control_);
config->GetBool("chord_composer/use_alt", &use_alt_);
config->GetBool("chord_composer/use_shift", &use_shift_);
config->GetString("speller/delimiter", &delimiter_);
algebra_.Load(config->GetList("chord_composer/algebra"));
output_format_.Load(config->GetList("chord_composer/output_format"));
prompt_format_.Load(config->GetList("chord_composer/prompt_format"));
}
Context* ctx = engine_->context();
ctx->set_option("_chord_typing", true);
update_connection_ = ctx->update_notifier().connect(
[this](Context* ctx) { OnContextUpdate(ctx); });
unhandled_key_connection_ = ctx->unhandled_key_notifier().connect(
[this](Context* ctx, const KeyEvent& key) { OnUnhandledKey(ctx, key); });
}
ChordComposer::~ChordComposer() {
update_connection_.disconnect();
unhandled_key_connection_.disconnect();
}
ProcessResult ChordComposer::ProcessFunctionKey(const KeyEvent& key_event) {
if (key_event.release()) {
return kNoop;
}
int ch = key_event.keycode();
if (ch == XK_Return) {
if (!raw_sequence_.empty()) {
// commit raw input
engine_->context()->set_input(raw_sequence_);
// then the sequence should not be used again
raw_sequence_.clear();
}
ClearChord();
} else if (ch == XK_BackSpace || ch == XK_Escape) {
// clear the raw sequence
raw_sequence_.clear();
ClearChord();
}
return kNoop;
}
// Note: QWERTY layout only.
static const char map_to_base_layer[] = {
" 1'3457'908=,-./"
"0123456789;;,=./"
"2abcdefghijklmno"
"pqrstuvwxyz[\\]6-"
"`abcdefghijklmno"
"pqrstuvwxyz[\\]`"
};
inline static int get_base_layer_key_code(const KeyEvent& key_event) {
int ch = key_event.keycode();
bool is_shift = key_event.shift();
return (is_shift && ch >= 0x20 && ch <= 0x7e)
? map_to_base_layer[ch - 0x20] : ch;
}
ProcessResult ChordComposer::ProcessChordingKey(const KeyEvent& key_event) {
if (key_event.ctrl() || key_event.alt()) {
raw_sequence_.clear();
}
if (key_event.ctrl() && !use_control_ ||
key_event.alt() && !use_alt_ ||
key_event.shift() && !use_shift_) {
ClearChord();
return kNoop;
}
int ch = get_base_layer_key_code(key_event);
// non chording key
if (std::find(chording_keys_.begin(),
chording_keys_.end(),
KeyEvent{ch, 0}) == chording_keys_.end()) {
ClearChord();
return kNoop;
}
// chording key
bool is_key_up = key_event.release();
if (is_key_up) {
if (pressed_.erase(ch) != 0 && pressed_.empty()) {
FinishChord();
}
}
else { // key down
pressed_.insert(ch);
bool updated = chord_.insert(ch).second;
if (updated)
UpdateChord();
}
return kAccepted;
}
inline static bool is_composing(Context* ctx) {
return !ctx->composition().empty() &&
!ctx->composition().back().HasTag("phony");
}
ProcessResult ChordComposer::ProcessKeyEvent(const KeyEvent& key_event) {
if (engine_->context()->get_option("ascii_mode")) {
return kNoop;
}
if (pass_thru_) {
return ProcessFunctionKey(key_event);
}
bool is_key_up = key_event.release();
int ch = key_event.keycode();
if (!is_key_up && ch >= 0x20 && ch <= 0x7e) {
// save raw input
if (!is_composing(engine_->context()) || !raw_sequence_.empty()) {
raw_sequence_.push_back(ch);
DLOG(INFO) << "update raw sequence: " << raw_sequence_;
}
}
auto result = ProcessChordingKey(key_event);
if (result != kNoop) {
return result;
}
return ProcessFunctionKey(key_event);
}
string ChordComposer::SerializeChord() {
KeySequence key_sequence;
for (KeyEvent key : chording_keys_) {
if (chord_.find(key.keycode()) != chord_.end())
key_sequence.push_back(key);
}
string code = key_sequence.repr();
algebra_.Apply(&code);
return code;
}
void ChordComposer::UpdateChord() {
if (!engine_)
return;
Context* ctx = engine_->context();
Composition& comp = ctx->composition();
string code = SerializeChord();
prompt_format_.Apply(&code);
if (comp.empty()) {
// add a placeholder segment
// 1. to cheat ctx->IsComposing() == true
// 2. to attach chord prompt to while chording
ctx->set_input(kZeroWidthSpace);
Segment placeholder(0, ctx->input().length());
placeholder.tags.insert("phony");
ctx->composition().AddSegment(placeholder);
}
auto& last_segment = comp.back();
last_segment.tags.insert("chord_prompt");
last_segment.prompt = code;
}
void ChordComposer::FinishChord() {
if (!engine_)
return;
string code = SerializeChord();
output_format_.Apply(&code);
ClearChord();
KeySequence key_sequence;
if (key_sequence.Parse(code) && !key_sequence.empty()) {
pass_thru_ = true;
for (const KeyEvent& key : key_sequence) {
if (!engine_->ProcessKey(key)) {
// direct commit
engine_->CommitText(string(1, key.keycode()));
// exclude the character (eg. space) from the raw sequence
raw_sequence_.clear();
}
}
pass_thru_ = false;
}
}
void ChordComposer::ClearChord() {
pressed_.clear();
chord_.clear();
if (!engine_)
return;
Context* ctx = engine_->context();
Composition& comp = ctx->composition();
if (comp.empty())
return;
auto& last_segment = comp.back();
if (comp.size() == 1 && last_segment.HasTag("phony")) {
ctx->Clear();
}
else if (last_segment.HasTag("chord_prompt")) {
last_segment.prompt.clear();
last_segment.tags.erase("chord_prompt");
}
}
void ChordComposer::OnContextUpdate(Context* ctx) {
if (is_composing(ctx)) {
composing_ = true;
}
else if (composing_) {
composing_ = false;
raw_sequence_.clear();
DLOG(INFO) << "clear raw sequence.";
}
}
void ChordComposer::OnUnhandledKey(Context* ctx, const KeyEvent& key) {
// directly committed ascii should not be captured into the raw sequence
// test case:
// 3.14{Return} should not commit an extra sequence '14'
if ((key.modifier() & ~kShiftMask) == 0 &&
key.keycode() >= 0x20 && key.keycode() <= 0x7e) {
raw_sequence_.clear();
DLOG(INFO) << "clear raw sequence.";
}
}
} // namespace rime
<|endoftext|> |
<commit_before>// Day18.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
const static size_t FieldSize = 100;
typedef std::array<bool, FieldSize> Row;
typedef std::array<Row, FieldSize> Field;
typedef std::shared_ptr<Field> PField;
static PField CreateField(const std::string & InputFile);
static size_t GetTurnedOnLights(PField Lights, size_t Steps);
static bool GetNewLightSate(PField Lights, size_t X, size_t Y);
static size_t GetTurnedOnNeighbors(PField Lights, size_t X, size_t Y);
int main()
{
PField Lights = CreateField("Input.txt");
size_t LightsOn = GetTurnedOnLights(Lights, 100);
std::cout << "Lights on: " << LightsOn << std::endl;
system("pause");
return 0;
}
static PField CreateField(const std::string & InputFile)
{
PField Lights = std::make_shared<Field>();
StringVector InputLines = GetFileLines(InputFile);
Field::iterator RowIter = Lights->begin();
for (const std::string & Line : InputLines)
{
Row::iterator LightIter = (RowIter++)->begin();
for (const char & Char : Line)
{
(*(LightIter++)) = (Char == '#');
}
}
return Lights;
}
static size_t GetTurnedOnLights(PField Lights, size_t Steps)
{
PField Buffer = std::make_shared<Field>();
size_t LightsOn = 0;
for (size_t i = 0; i < Steps; i++)
{
LightsOn = 0;
for (size_t x = 0; x < FieldSize; x++)
for (size_t y = 0; y < FieldSize; y++)
{
bool NewState = GetNewLightSate(Lights, x, y);
(*Buffer)[x][y] = NewState;
if (NewState)
{
++LightsOn;
}
}
Buffer.swap(Lights);
}
return LightsOn;
}
static bool GetNewLightSate(PField Lights, size_t X, size_t Y)
{
size_t TurnedOnNeighbors = GetTurnedOnNeighbors(Lights, X, Y);
if ((*Lights)[X][Y])
{
return ((TurnedOnNeighbors == 2) || (TurnedOnNeighbors == 3));
}
else
{
return (TurnedOnNeighbors == 3);
}
}
static size_t GetTurnedOnNeighbors(PField Lights, size_t X, size_t Y)
{
size_t LightsOn = 0;
for (size_t TX = (X > 0) ? X - 1 : X; TX <= std::min(X + 1, FieldSize - 1); ++TX)
for (size_t TY = (Y > 0) ? Y - 1 : Y; TY <= std::min(Y + 1, FieldSize - 1); ++TY)
{
if ((TX == X) && (TY == Y))
{
continue;
}
LightsOn += ((*Lights)[TX][TY]) ? 1 : 0;
}
return LightsOn;
}<commit_msg>Add solution for Day 18 part two<commit_after>// Day18.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
const static size_t FieldSize = 100;
typedef std::array<bool, FieldSize> Row;
typedef std::array<Row, FieldSize> Field;
typedef std::shared_ptr<Field> PField;
typedef std::pair<size_t, size_t> FieldCoord;
typedef std::vector<FieldCoord> CoordVector;
static PField CreateField(const std::string & InputFile);
static size_t GetTurnedOnLights(PField Lights, size_t Steps, const CoordVector & StuckedLights = CoordVector());
static bool GetNewLightSate(PField Lights, size_t X, size_t Y);
static size_t GetTurnedOnNeighbors(PField Lights, size_t X, size_t Y);
static void TurnOnStuckedLights(PField Lights, const CoordVector & StuckedLights, size_t & LightsOnCount);
int main()
{
PField Lights = CreateField("Input.txt");
size_t LightsOn = GetTurnedOnLights(Lights, 100);
std::cout << "Lights on (non-stucked): " << LightsOn << std::endl;
Lights = CreateField("Input.txt");
LightsOn = GetTurnedOnLights(Lights, 100, { {0,0},{ 0,FieldSize - 1 },{ FieldSize - 1,0 },{ FieldSize - 1,FieldSize - 1 } });
std::cout << "Lights on (stucked): " << LightsOn << std::endl;
system("pause");
return 0;
}
static PField CreateField(const std::string & InputFile)
{
PField Lights = std::make_shared<Field>();
StringVector InputLines = GetFileLines(InputFile);
Field::iterator RowIter = Lights->begin();
for (const std::string & Line : InputLines)
{
Row::iterator LightIter = (RowIter++)->begin();
for (const char & Char : Line)
{
(*(LightIter++)) = (Char == '#');
}
}
return Lights;
}
static size_t GetTurnedOnLights(PField Lights, size_t Steps, const CoordVector & StuckedLights)
{
PField Buffer = std::make_shared<Field>();
size_t LightsOn = 0;
TurnOnStuckedLights(Lights, StuckedLights, LightsOn);
for (size_t i = 0; i < Steps; i++)
{
LightsOn = 0;
for (size_t x = 0; x < FieldSize; x++)
for (size_t y = 0; y < FieldSize; y++)
{
bool NewState = GetNewLightSate(Lights, x, y);
(*Buffer)[x][y] = NewState;
if (NewState)
{
++LightsOn;
}
}
TurnOnStuckedLights(Buffer, StuckedLights, LightsOn);
Buffer.swap(Lights);
}
return LightsOn;
}
static bool GetNewLightSate(PField Lights, size_t X, size_t Y)
{
size_t TurnedOnNeighbors = GetTurnedOnNeighbors(Lights, X, Y);
if ((*Lights)[X][Y])
{
return ((TurnedOnNeighbors == 2) || (TurnedOnNeighbors == 3));
}
else
{
return (TurnedOnNeighbors == 3);
}
}
static size_t GetTurnedOnNeighbors(PField Lights, size_t X, size_t Y)
{
size_t LightsOn = 0;
for (size_t TX = (X > 0) ? X - 1 : X; TX <= std::min(X + 1, FieldSize - 1); ++TX)
for (size_t TY = (Y > 0) ? Y - 1 : Y; TY <= std::min(Y + 1, FieldSize - 1); ++TY)
{
if ((TX == X) && (TY == Y))
{
continue;
}
LightsOn += ((*Lights)[TX][TY]) ? 1 : 0;
}
return LightsOn;
}
static void TurnOnStuckedLights(PField Lights, const CoordVector & StuckedLights, size_t & LightsOnCount)
{
for (const FieldCoord & StuckedLight : StuckedLights)
{
bool & Light = (*Lights)[StuckedLight.first][StuckedLight.second];
if (!Light)
{
Light = true;
++LightsOnCount;
}
}
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2012, Oliver Woodford
Copyright (c) 2014, Florian Franzen
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
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.
*/
#ifndef __MEX_HPP__
#define __MEX_HPP__
#include "mex.h"
#include <stdint.h>
#include <string>
#include <cstring>
#include <typeinfo>
#include <iostream>
#include <sstream>
#include <exception>
#include "Eigen/Core"
using Eigen::Map;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::ColMajor;
#define MEX_CLASS_HANDLE_SIGNATURE 0x434d544d
template<class BaseClass> class MEXClassHandle {
public:
static mxArray* wrap(BaseClass* ptr) {
mexLock();
mxArray *out = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
*((uint64_t *)mxGetData(out)) = reinterpret_cast<uint64_t>(new MEXClassHandle<BaseClass>(ptr));
return out;
}
static BaseClass* unwrap(const mxArray *in) {
return fromMxArray(in)->getPointer();
}
static void free(const mxArray *in) {
delete fromMxArray(in);
mexUnlock();
}
private:
MEXClassHandle(BaseClass* pointer) : mPointer(pointer), mName(typeid(BaseClass).name()), mSignature(MEX_CLASS_HANDLE_SIGNATURE) {}
~MEXClassHandle() {
mSignature = 0;
delete mPointer;
}
bool isValid() {
return ((mSignature == MEX_CLASS_HANDLE_SIGNATURE) &&
!strcmp(mName.c_str(), typeid(BaseClass).name()));
}
BaseClass* getPointer() {
return mPointer;
}
static MEXClassHandle* fromMxArray(const mxArray *in) {
if (mxGetNumberOfElements(in) != 1 || !mxIsUint64(in) || mxIsComplex(in))
mexErrMsgIdAndTxt("MEXClassHandle:notAHandle", "Handle must be a real uint64 scalar.");
MEXClassHandle<BaseClass> *handle = reinterpret_cast<MEXClassHandle<BaseClass> *>(*((uint64_t*) mxGetData(in)));
if (!handle->isValid())
mexErrMsgIdAndTxt("MEXClassHandle:invalidHandle", "Handle is not valid.");
return handle;
}
uint32_t mSignature;
std::string mName;
BaseClass* mPointer;
};
class MEXInput {
public:
MEXInput(int size, const mxArray** data) : mSize(size), mData(data) {}
int size() const {
return mSize;
}
bool has(int i) const {
return i >= 0 && i < mSize;
}
enum Type { // ToDo: Decide if you want to add vectors
Unknown,
BoolScalar,
IntScalar,
FloatScalar,
BoolMatrix,
IntMatrix,
FloatMatrix,
String,
Struct,
Cell
};
class Converter {
public:
Converter(const mxArray* data, int index) : mData(data), mIndex(index) {}
bool isEmpty() {
return mxIsEmpty(mData);
}
MEXInput::Type getType() {
switch (mxGetClassID(mData)) {
case mxCHAR_CLASS:
return MEXInput::String;
case mxSTRUCT_CLASS:
return MEXInput::Struct;
case mxCELL_CLASS:
return MEXInput::Cell;
case mxLOGICAL_CLASS:
return (mxGetNumberOfElements(mData) == 1) ? MEXInput::BoolScalar : MEXInput::BoolMatrix;
case mxINT8_CLASS:
case mxUINT8_CLASS:
case mxINT16_CLASS:
case mxUINT16_CLASS:
case mxINT32_CLASS:
case mxUINT32_CLASS:
case mxINT64_CLASS:
case mxUINT64_CLASS:
return (mxGetNumberOfElements(mData) == 1) ? MEXInput::IntScalar : MEXInput::IntMatrix;
case mxSINGLE_CLASS:
case mxDOUBLE_CLASS:
return (mxGetNumberOfElements(mData) == 1) ? MEXInput::FloatScalar : MEXInput::FloatMatrix;
case mxUNKNOWN_CLASS:
mexErrMsgTxt("Unknown class.");
default:
mexErrMsgTxt("Unidentified class.");
}
return MEXInput::Unknown;
}
bool isType(MEXInput::Type t) {
return (getType() == t);
}
template<class BaseClass> BaseClass* unwrap() {
return MEXClassHandle<BaseClass>::unwrap(mData);
}
operator MatrixXd () {
if(!isType(MEXInput::FloatMatrix)){
mexErrMsgIdAndTxt("MEXInput:typeMismatch", "Argument #%d should be a single or double matrix.", mIndex + 1);
}
if(mxIsSparse(mData)) {
mexErrMsgIdAndTxt("MEXInput:sparseMatrixNotSupported", "Sparse matrix are not supported (argument #%d).", mIndex + 1); // ToDo: Add sparse matrix support.
}
if(mxGetNumberOfDimensions(mData) > 2) {
mexErrMsgIdAndTxt("MEXInput:moreThenTwoDimensions", "3D matrix are not supported (argument #%d).", mIndex + 1); // ToDo: Add 3d matrix support.
}
return Map<MatrixXd,ColMajor>(mxGetPr(mData), mxGetM(mData), mxGetN(mData));
}
operator VectorXd () {
if(!isType(MEXInput::FloatMatrix) or mxGetN(mData) != 1) {
mexErrMsgIdAndTxt("MEXInput:typeMismatch", "Argument #%d should be a single or double column vector.", mIndex + 1);
}
if(mxIsSparse(mData)) {
mexErrMsgIdAndTxt("MEXInput:sparseMatrixNotSupported", "Sparse matrix are not supported (argument #%d).", mIndex + 1); // ToDo: Add sparse matrix support.
}
if(mxGetNumberOfDimensions(mData) > 2) {
mexErrMsgIdAndTxt("MEXInput:moreThenTwoDimensions", "3D matrix are not supported (argument #%d).", mIndex + 1); // ToDo: Add 3d matrix support.
}
return Map<VectorXd,ColMajor>(mxGetPr(mData), mxGetM(mData));
}
operator double () {
if(!isType(MEXInput::FloatScalar)){
mexErrMsgIdAndTxt("MEXInput:typeMismatch", "Argument #%d should be a single or double scalar.", mIndex + 1);
}
return mxGetScalar(mData);
}
operator int () {
if(!isType(MEXInput::IntScalar)){
mexErrMsgIdAndTxt("MEXInput:typeMismatch", "Argument #%d should be a integer scalar.", mIndex + 1);
}
return static_cast<int>(round(mxGetScalar(mData)));
}
operator bool () {
if(!isType(MEXInput::BoolScalar)){
mexErrMsgTxt("This should be a boolean scalar!");
}
return mxGetScalar(mData) != 0;
}
private:
const mxArray* mData;
int mIndex; // Only needed for error messages
};
MEXInput::Converter operator[](int i) const {
if(!has(i)) {
mexErrMsgIdAndTxt("MEXInput:missingArgument", "Not enough argument supplied! Could not access argument #%d.", i + 1);
}
return Converter(mData[i], i);
}
private:
int mSize;
const mxArray** mData;
};
class MEXOutput {
public:
MEXOutput(int size, mxArray** data) : mSize(size), mData(data) {}
int size() {
return mSize;
}
int has(int index) {
return index >= 0 && index < mSize;
}
class Converter {
public:
Converter(mxArray** data) : mData(data) {}
Converter& operator=(const MatrixXd& output) {
(*mData) = mxCreateDoubleMatrix(output.rows(), output.cols(), mxREAL);
Map<MatrixXd,ColMajor> data_wrapper(mxGetPr(*mData), output.rows(), output.cols());
data_wrapper = output;
return *this;
}
// Converter& operator=(const MatrixXb& output) {
// (*mData) = mxCreateLogicalMatrix(output.rows(), output.cols());
// Map<MatrixXb,ColMajor> data_wrapper(mxGetPr(*mData), output.rows(), output.cols());
// data_wrapper = output;
// return *this;
// }
Converter& operator=(const bool& b) {
std::cout << "Bool: " << b << std::endl;
(*mData) = mxCreateLogicalScalar(b);
return *this;
}
Converter& operator=(const int& i) {
const mwSize dims = 1;
(*mData) = mxCreateNumericArray(1, &dims, mxINT32_CLASS, mxREAL);
(*mxGetPr(*mData)) = i;
return *this;
}
Converter& operator=(const double& d) {
std::cout << "Double: " << d << std::endl;
(*mData) = mxCreateDoubleScalar(d);
return *this;
}
Converter& operator=(const std::string& s) {
(*mData) = mxCreateString(s.c_str());
return *this;
}
private:
mxArray** mData;
};
MEXOutput::Converter operator[](int index) {
if(!has(index)) {
mexErrMsgIdAndTxt("MEXOutput:missingArgument", "Not enough ouput argument required! Could not access argument #%d.", index + 1);
}
return Converter(mData + index);
}
private:
int mSize;
mxArray** mData;
};
// streambuffer that writes everything to mexPrintf. Usefull to reroute cout.
class mexstreambuf : public std::streambuf {
protected:
std::streamsize xsputn(const char *s, std::streamsize n) {
mexPrintf("%.*s",n,s);
return n;
}
int overflow(int c = EOF) {
if (c != EOF) {
mexPrintf("%.1s",&c);
}
return 1;
}
};
/**
* Mex wrapper function, that takes care of object creation, storage and deletion and passes everything else onto parser function.
*
* @param creator function that parses matlab data to call class constructor
* @param parser function that parses matlab data and forwards the appropiate function
*/
template<class BaseClass> inline void mexWrapper(BaseClass* (*creator)(MEXInput), bool (*parser)(BaseClass*, std::string, MEXOutput, MEXInput), int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Redirect cout
mexstreambuf mexoutbuf;
std::streambuf* coutbuf = std::cout.rdbuf(&mexoutbuf);
// Get the command string
char cmd[64];
if (nrhs < 1 || mxGetString(prhs[0], cmd, sizeof(cmd)))
mexErrMsgIdAndTxt("mexWrapper:invalidCommandstring", "First input should be a command string less than 64 characters long.");
std::cout << "+++ DEBUG: Call to '" << cmd << "' with " << nrhs << " inputs and " << nlhs << " ouput value(s). +++" << std::endl;
// New
if (!strcmp("new", cmd)) {
// Check parameters
if (nlhs != 1)
mexErrMsgIdAndTxt("mexWrapper:invalidOutput", "New: One output expected.");
try {
BaseClass* ptr = creator(MEXInput(nrhs - 1, prhs + 1));
// Return a handle to a new C++ instance
plhs[0] = MEXClassHandle<BaseClass>::wrap(ptr);
return;
} catch (std::exception& e) {
mexErrMsgIdAndTxt("mexWrapper:constructor:exceptionCaught", "Exception in constructor: \n\t%s", e.what());
}
}
// Check there is a second input, which should be the class instance handle
if (nrhs < 2)
mexErrMsgIdAndTxt("mexWrapper:missingClassHandle", "Second input should be a class instance handle.");
// Delete
if (!strcmp("delete", cmd)) {
// Destroy the C++ object
MEXClassHandle<BaseClass>::free(prhs[1]);
// Warn if other commands were ignored
if (nlhs != 0 || nrhs != 2)
mexWarnMsgIdAndTxt("mexWrapper:ignoredArgurments", "Delete: Unexpected arguments ignored.");
return;
}
// Get the class instance pointer from the second input
BaseClass* instance = MEXClassHandle<BaseClass>::unwrap(prhs[1]);
try {
if(!parser(instance, cmd, MEXOutput(nlhs, plhs), MEXInput(nrhs - 2, prhs + 2)))
mexErrMsgIdAndTxt("mexParse:unknownCommand", "Command '%s' not recognized!", cmd);
} catch (std::exception& e) {
mexErrMsgIdAndTxt("mexWrapper:methodAndPropertyParser:exceptionCaught", "Exception in method and property parser: \n\t%s", e.what());
}
// Reset cout
std::cout.rdbuf(coutbuf);
}
#endif // __MEX_HPP__
<commit_msg>Removes debugging.<commit_after>/*
Copyright (c) 2012, Oliver Woodford
Copyright (c) 2014, Florian Franzen
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
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.
*/
#ifndef __MEX_HPP__
#define __MEX_HPP__
#include "mex.h"
#include <stdint.h>
#include <string>
#include <cstring>
#include <typeinfo>
#include <iostream>
#include <sstream>
#include <exception>
#include "Eigen/Core"
using Eigen::Map;
using Eigen::MatrixXd;
using Eigen::VectorXd;
using Eigen::ColMajor;
#define MEX_CLASS_HANDLE_SIGNATURE 0x434d544d
template<class BaseClass> class MEXClassHandle {
public:
static mxArray* wrap(BaseClass* ptr) {
mexLock();
mxArray *out = mxCreateNumericMatrix(1, 1, mxUINT64_CLASS, mxREAL);
*((uint64_t *)mxGetData(out)) = reinterpret_cast<uint64_t>(new MEXClassHandle<BaseClass>(ptr));
return out;
}
static BaseClass* unwrap(const mxArray *in) {
return fromMxArray(in)->getPointer();
}
static void free(const mxArray *in) {
delete fromMxArray(in);
mexUnlock();
}
private:
MEXClassHandle(BaseClass* pointer) : mPointer(pointer), mName(typeid(BaseClass).name()), mSignature(MEX_CLASS_HANDLE_SIGNATURE) {}
~MEXClassHandle() {
mSignature = 0;
delete mPointer;
}
bool isValid() {
return ((mSignature == MEX_CLASS_HANDLE_SIGNATURE) &&
!strcmp(mName.c_str(), typeid(BaseClass).name()));
}
BaseClass* getPointer() {
return mPointer;
}
static MEXClassHandle* fromMxArray(const mxArray *in) {
if (mxGetNumberOfElements(in) != 1 || !mxIsUint64(in) || mxIsComplex(in))
mexErrMsgIdAndTxt("MEXClassHandle:notAHandle", "Handle must be a real uint64 scalar.");
MEXClassHandle<BaseClass> *handle = reinterpret_cast<MEXClassHandle<BaseClass> *>(*((uint64_t*) mxGetData(in)));
if (!handle->isValid())
mexErrMsgIdAndTxt("MEXClassHandle:invalidHandle", "Handle is not valid.");
return handle;
}
uint32_t mSignature;
std::string mName;
BaseClass* mPointer;
};
class MEXInput {
public:
MEXInput(int size, const mxArray** data) : mSize(size), mData(data) {}
int size() const {
return mSize;
}
bool has(int i) const {
return i >= 0 && i < mSize;
}
enum Type { // ToDo: Decide if you want to add vectors
Unknown,
BoolScalar,
IntScalar,
FloatScalar,
BoolMatrix,
IntMatrix,
FloatMatrix,
String,
Struct,
Cell
};
class Converter {
public:
Converter(const mxArray* data, int index) : mData(data), mIndex(index) {}
bool isEmpty() {
return mxIsEmpty(mData);
}
MEXInput::Type getType() {
switch (mxGetClassID(mData)) {
case mxCHAR_CLASS:
return MEXInput::String;
case mxSTRUCT_CLASS:
return MEXInput::Struct;
case mxCELL_CLASS:
return MEXInput::Cell;
case mxLOGICAL_CLASS:
return (mxGetNumberOfElements(mData) == 1) ? MEXInput::BoolScalar : MEXInput::BoolMatrix;
case mxINT8_CLASS:
case mxUINT8_CLASS:
case mxINT16_CLASS:
case mxUINT16_CLASS:
case mxINT32_CLASS:
case mxUINT32_CLASS:
case mxINT64_CLASS:
case mxUINT64_CLASS:
return (mxGetNumberOfElements(mData) == 1) ? MEXInput::IntScalar : MEXInput::IntMatrix;
case mxSINGLE_CLASS:
case mxDOUBLE_CLASS:
return (mxGetNumberOfElements(mData) == 1) ? MEXInput::FloatScalar : MEXInput::FloatMatrix;
case mxUNKNOWN_CLASS:
mexErrMsgTxt("Unknown class.");
default:
mexErrMsgTxt("Unidentified class.");
}
return MEXInput::Unknown;
}
bool isType(MEXInput::Type t) {
return (getType() == t);
}
template<class BaseClass> BaseClass* unwrap() {
return MEXClassHandle<BaseClass>::unwrap(mData);
}
operator MatrixXd () {
if(!isType(MEXInput::FloatMatrix)){
mexErrMsgIdAndTxt("MEXInput:typeMismatch", "Argument #%d should be a single or double matrix.", mIndex + 1);
}
if(mxIsSparse(mData)) {
mexErrMsgIdAndTxt("MEXInput:sparseMatrixNotSupported", "Sparse matrix are not supported (argument #%d).", mIndex + 1); // ToDo: Add sparse matrix support.
}
if(mxGetNumberOfDimensions(mData) > 2) {
mexErrMsgIdAndTxt("MEXInput:moreThenTwoDimensions", "3D matrix are not supported (argument #%d).", mIndex + 1); // ToDo: Add 3d matrix support.
}
return Map<MatrixXd,ColMajor>(mxGetPr(mData), mxGetM(mData), mxGetN(mData));
}
operator VectorXd () {
if(!isType(MEXInput::FloatMatrix) or mxGetN(mData) != 1) {
mexErrMsgIdAndTxt("MEXInput:typeMismatch", "Argument #%d should be a single or double column vector.", mIndex + 1);
}
if(mxIsSparse(mData)) {
mexErrMsgIdAndTxt("MEXInput:sparseMatrixNotSupported", "Sparse matrix are not supported (argument #%d).", mIndex + 1); // ToDo: Add sparse matrix support.
}
if(mxGetNumberOfDimensions(mData) > 2) {
mexErrMsgIdAndTxt("MEXInput:moreThenTwoDimensions", "3D matrix are not supported (argument #%d).", mIndex + 1); // ToDo: Add 3d matrix support.
}
return Map<VectorXd,ColMajor>(mxGetPr(mData), mxGetM(mData));
}
operator double () {
if(!isType(MEXInput::FloatScalar)){
mexErrMsgIdAndTxt("MEXInput:typeMismatch", "Argument #%d should be a single or double scalar.", mIndex + 1);
}
return mxGetScalar(mData);
}
operator int () {
if(!isType(MEXInput::IntScalar)){
mexErrMsgIdAndTxt("MEXInput:typeMismatch", "Argument #%d should be a integer scalar.", mIndex + 1);
}
return static_cast<int>(round(mxGetScalar(mData)));
}
operator bool () {
if(!isType(MEXInput::BoolScalar)){
mexErrMsgTxt("This should be a boolean scalar!");
}
return mxGetScalar(mData) != 0;
}
private:
const mxArray* mData;
int mIndex; // Only needed for error messages
};
MEXInput::Converter operator[](int i) const {
if(!has(i)) {
mexErrMsgIdAndTxt("MEXInput:missingArgument", "Not enough argument supplied! Could not access argument #%d.", i + 1);
}
return Converter(mData[i], i);
}
private:
int mSize;
const mxArray** mData;
};
class MEXOutput {
public:
MEXOutput(int size, mxArray** data) : mSize(size), mData(data) {}
int size() {
return mSize;
}
int has(int index) {
return index >= 0 && index < mSize;
}
class Converter {
public:
Converter(mxArray** data) : mData(data) {}
Converter& operator=(const MatrixXd& output) {
(*mData) = mxCreateDoubleMatrix(output.rows(), output.cols(), mxREAL);
Map<MatrixXd,ColMajor> data_wrapper(mxGetPr(*mData), output.rows(), output.cols());
data_wrapper = output;
return *this;
}
// Converter& operator=(const MatrixXb& output) {
// (*mData) = mxCreateLogicalMatrix(output.rows(), output.cols());
// Map<MatrixXb,ColMajor> data_wrapper(mxGetPr(*mData), output.rows(), output.cols());
// data_wrapper = output;
// return *this;
// }
Converter& operator=(const bool& b) {
(*mData) = mxCreateLogicalScalar(b);
return *this;
}
Converter& operator=(const int& i) {
const mwSize dims = 1;
(*mData) = mxCreateNumericArray(1, &dims, mxINT32_CLASS, mxREAL);
(*mxGetPr(*mData)) = i;
return *this;
}
Converter& operator=(const double& d) {
std::cout << "Double: " << d << std::endl;
(*mData) = mxCreateDoubleScalar(d);
return *this;
}
Converter& operator=(const std::string& s) {
(*mData) = mxCreateString(s.c_str());
return *this;
}
private:
mxArray** mData;
};
MEXOutput::Converter operator[](int index) {
if(!has(index)) {
mexErrMsgIdAndTxt("MEXOutput:missingArgument", "Not enough ouput argument required! Could not access argument #%d.", index + 1);
}
return Converter(mData + index);
}
private:
int mSize;
mxArray** mData;
};
// streambuffer that writes everything to mexPrintf. Usefull to reroute cout.
class mexstreambuf : public std::streambuf {
protected:
std::streamsize xsputn(const char *s, std::streamsize n) {
mexPrintf("%.*s",n,s);
return n;
}
int overflow(int c = EOF) {
if (c != EOF) {
mexPrintf("%.1s",&c);
}
return 1;
}
};
/**
* Mex wrapper function, that takes care of object creation, storage and deletion and passes everything else onto parser function.
*
* @param creator function that parses matlab data to call class constructor
* @param parser function that parses matlab data and forwards the appropiate function
*/
template<class BaseClass> inline void mexWrapper(BaseClass* (*creator)(MEXInput), bool (*parser)(BaseClass*, std::string, MEXOutput, MEXInput), int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Redirect cout
mexstreambuf mexoutbuf;
std::streambuf* coutbuf = std::cout.rdbuf(&mexoutbuf);
// Get the command string
char cmd[64];
if (nrhs < 1 || mxGetString(prhs[0], cmd, sizeof(cmd)))
mexErrMsgIdAndTxt("mexWrapper:invalidCommandstring", "First input should be a command string less than 64 characters long.");
std::cout << "+++ DEBUG: Call to '" << cmd << "' with " << nrhs << " inputs and " << nlhs << " ouput value(s). +++" << std::endl;
// New
if (!strcmp("new", cmd)) {
// Check parameters
if (nlhs != 1)
mexErrMsgIdAndTxt("mexWrapper:invalidOutput", "New: One output expected.");
try {
BaseClass* ptr = creator(MEXInput(nrhs - 1, prhs + 1));
// Return a handle to a new C++ instance
plhs[0] = MEXClassHandle<BaseClass>::wrap(ptr);
return;
} catch (std::exception& e) {
mexErrMsgIdAndTxt("mexWrapper:constructor:exceptionCaught", "Exception in constructor: \n\t%s", e.what());
}
}
// Check there is a second input, which should be the class instance handle
if (nrhs < 2)
mexErrMsgIdAndTxt("mexWrapper:missingClassHandle", "Second input should be a class instance handle.");
// Delete
if (!strcmp("delete", cmd)) {
// Destroy the C++ object
MEXClassHandle<BaseClass>::free(prhs[1]);
// Warn if other commands were ignored
if (nlhs != 0 || nrhs != 2)
mexWarnMsgIdAndTxt("mexWrapper:ignoredArgurments", "Delete: Unexpected arguments ignored.");
return;
}
// Get the class instance pointer from the second input
BaseClass* instance = MEXClassHandle<BaseClass>::unwrap(prhs[1]);
try {
if(!parser(instance, cmd, MEXOutput(nlhs, plhs), MEXInput(nrhs - 2, prhs + 2)))
mexErrMsgIdAndTxt("mexParse:unknownCommand", "Command '%s' not recognized!", cmd);
} catch (std::exception& e) {
mexErrMsgIdAndTxt("mexWrapper:methodAndPropertyParser:exceptionCaught", "Exception in method and property parser: \n\t%s", e.what());
}
// Reset cout
std::cout.rdbuf(coutbuf);
}
#endif // __MEX_HPP__
<|endoftext|> |
<commit_before>/*
* VariableList.hpp
*
* Created on: 18.04.2016
* Author: Marc Hartung
*/
#ifndef INCLUDE_VARIABLELIST_HPP_
#define INCLUDE_VARIABLELIST_HPP_
#include "AdditionalTypes.hpp"
#include <iostream>
#include <vector>
namespace NetOff
{
/*! \brief
*
* todo Marc!
*/
class VariableList : public SharedDataAccessable
{
public:
VariableList();
VariableList(const std::vector<std::string> & realVars, const std::vector<std::string> & intVars, const std::vector<std::string> & boolVars);
/*! \brief Adds a real variable to the container.
*
* @param varName Name of the variable.
*/
void addReal(const std::string & varName);
/*! \brief Adds a integer variable to the container.
*
* @param varName Name of the variable.
*/
void addInt(const std::string & varName);
/*! \brief Adds a boolean variable to the container.
*
* @param varName Name of the variable.
*/
void addBool(const std::string & varName);
/*! \brief Adds a vector of real variables to the container.
*
* @param varNames Vector of the variable names.
*/
void addReals(const std::vector<std::string> & varNames);
/*! \brief Adds a vector of integer variables to the container.
*
* @param varNames Vector of the variable names.
*/
void addInts(const std::vector<std::string> & varNames);
/*! \brief Adds a vector of boolean variables to the container.
*
* @param varNames Vector of the variable names.
*/
void addBools(const std::vector<std::string> & varNames);
const std::vector<std::string> & getReals() const;
const std::vector<std::string> & getInts() const;
const std::vector<std::string> & getBools() const;
/*! Returns size of real container, i.e., number of stored real variable names. */
size_t sizeReals() const;
size_t sizeInts() const;
size_t sizeBools() const;
/*! \brief Returns true, if the container is empty. */
bool empty() const;
size_t dataSize() const;
std::shared_ptr<const char> data() const;
std::shared_ptr<char> data();
void saveVariablesTo(char * data) const;
static VariableList getVariableListFromData(const char * data);
friend std::ostream & operator<<(std::ostream & out, const VariableList & in);
bool isSubsetOf(const VariableList & in) const;
size_t findRealVariableNameIndex(const std::string & varName) const;
private:
/*! _vars[0] = Vector containing names of real variables.
* _vars[1] = Vector containing names of integer variables.
* _vars[2] = Vector containing names of boolean variables.
*/
std::vector<std::vector<std::string>> _vars;
VariableList(const std::shared_ptr<char> & data);
};
}
#endif /* INCLUDE_VARIABLELIST_HPP_ */
<commit_msg>Add some comments for documentary<commit_after>/*
* VariableList.hpp
*
* Created on: 18.04.2016
* Author: Marc Hartung
*/
#ifndef INCLUDE_VARIABLELIST_HPP_
#define INCLUDE_VARIABLELIST_HPP_
#include "AdditionalTypes.hpp"
#include <iostream>
#include <vector>
namespace NetOff
{
/*! \brief
*
* todo Marc!
*/
class VariableList : public SharedDataAccessable
{
public:
VariableList();
VariableList(const std::vector<std::string> & realVars, const std::vector<std::string> & intVars, const std::vector<std::string> & boolVars);
/*! \brief Adds a real variable to the container.
*
* @param varName Name of the variable.
*/
void addReal(const std::string & varName);
/*! \brief Adds a integer variable to the container.
*
* @param varName Name of the variable.
*/
void addInt(const std::string & varName);
/*! \brief Adds a boolean variable to the container.
*
* @param varName Name of the variable.
*/
void addBool(const std::string & varName);
/*! \brief Adds a vector of real variables to the container.
*
* @param varNames Vector of the variable names.
*/
void addReals(const std::vector<std::string> & varNames);
/*! \brief Adds a vector of integer variables to the container.
*
* @param varNames Vector of the variable names.
*/
void addInts(const std::vector<std::string> & varNames);
/*! \brief Adds a vector of boolean variables to the container.
*
* @param varNames Vector of the variable names.
*/
void addBools(const std::vector<std::string> & varNames);
const std::vector<std::string> & getReals() const;
const std::vector<std::string> & getInts() const;
const std::vector<std::string> & getBools() const;
/*! Returns size of real container, i.e., number of stored real variable names. */
size_t sizeReals() const;
/*! Returns size of integer container, i.e., number of stored integer variable names. */
size_t sizeInts() const;
/*! Returns size of boolean container, i.e., number of stored boolean variable names. */
size_t sizeBools() const;
/*! \brief Returns true, if the container is empty. */
bool empty() const;
size_t dataSize() const;
std::shared_ptr<const char> data() const;
std::shared_ptr<char> data();
void saveVariablesTo(char * data) const;
static VariableList getVariableListFromData(const char * data);
friend std::ostream & operator<<(std::ostream & out, const VariableList & in);
bool isSubsetOf(const VariableList & in) const;
size_t findRealVariableNameIndex(const std::string & varName) const;
private:
/*! _vars[0] = Vector containing names of real variables.
* _vars[1] = Vector containing names of integer variables.
* _vars[2] = Vector containing names of boolean variables.
*/
std::vector<std::vector<std::string>> _vars;
VariableList(const std::shared_ptr<char> & data);
};
}
#endif /* INCLUDE_VARIABLELIST_HPP_ */
<|endoftext|> |
<commit_before>#include "ouroboros_server.h"
#include <server/data/data_store.hpp>
#include <server/device_tree.hpp>
#include <mongoose/mongoose.h>
#include <server/rest.h>
#include <sstream>
#include <cassert>
#include <slre/slre.h>
namespace ouroboros
{
namespace detail
{
std::string bad_JSON(mg_connection* aConn)
{
mg_send_status(aConn, 400);
return std::string("{ \"status\" : \"Bad JSON request.\"}");
}
std::string good_JSON()
{
return std::string("{ \"status\" : \"OK.\"}");
}
}
std::string url_regex("(.+://)?(.+)");
ouroboros_server::ouroboros_server()
:mpServer(NULL),
mStore(device_tree<var_field>::get_device_tree().get_data_store())
{
//The following line is a hack workaround to trying to avoid using
//functional support in c++03
if (!mpSendServer)
{
//HACK
mpSendServer = this;
}
mpServer = mg_create_server(this, ouroboros_server::event_handler);
mg_set_option(mpServer, "document_root", "."); // Serve current directory
mg_set_option(mpServer, "listening_port", "8080"); // Open port 8080
}
ouroboros_server::~ouroboros_server()
{
mg_destroy_server(&mpServer);
}
const var_field *ouroboros_server::get(const std::string& aGroup, const std::string& aField) const
{
return mStore.get(normalize_group(aGroup), aField);
}
var_field *ouroboros_server::get(const std::string& aGroup, const std::string& aField)
{
return const_cast<var_field *>(static_cast<const ouroboros_server&>(*this).get(aGroup, aField));
}
const group<var_field> *ouroboros_server::get(const std::string& aGroup) const
{
return mStore.get(normalize_group(aGroup));
}
group<var_field> *ouroboros_server::get(const std::string& aGroup)
{
return const_cast<group<var_field> *>(static_cast<const ouroboros_server&>(*this).get(aGroup));
}
bool ouroboros_server::set(const std::string& aGroup, const std::string& aField, const var_field& aFieldData)
{
var_field *result = mStore.get(normalize_group(aGroup), aField);
if (!result)
{
return false;
}
result->setJSON(aFieldData.getJSON());
handle_notification(aGroup, aField);
return true;
}
bool ouroboros_server::set(const std::string& , const group<var_field>& )
{
return false;
}
void ouroboros_server::run()
{
mg_poll_server(mpServer, 1000);
}
mg_result ouroboros_server::handle_rest(const rest_request& aRequest)
{
switch (aRequest.getRestRequestType())
{
case FIELDS:
handle_name_rest(aRequest);
break;
case GROUPS:
handle_group_rest(aRequest);
break;
case CALLBACK:
handle_callback_rest(aRequest);
break;
case NONE:
break;
default:
return MG_FALSE;
}
return MG_TRUE;
}
void ouroboros_server::handle_name_rest(const rest_request& aRequest)
{
//get reference to named thing
var_field *named = mStore.get(normalize_group(aRequest.getGroups()), aRequest.getFields());
std::string sjson;
mg_connection *conn = aRequest.getConnection();
if (named)
{
switch (aRequest.getHttpRequestType())
{
case PUT:
{
std::string data(conn->content, conn->content_len);
JSON json(data);
if (named->setJSON(json))
{
handle_notification(aRequest.getGroups(), aRequest.getFields());
sjson = detail::good_JSON();
}
else
{
sjson = detail::bad_JSON(conn);
}
}
break;
case GET:
//Send JSON describing named item
sjson = named->getJSON();
break;
default:
sjson = detail::bad_JSON(conn);
}
}
else
{
sjson = detail::bad_JSON(conn);
}
mg_send_data(conn, sjson.c_str(), sjson.length());
}
void ouroboros_server::handle_group_rest(const rest_request& aRequest)
{
//get reference to named thing
group<var_field> *pgroup = mStore.get(normalize_group(aRequest.getGroups()));
std::string sjson;
mg_connection *conn = aRequest.getConnection();
if (pgroup)
{
switch (aRequest.getHttpRequestType())
{
case GET:
//Send JSON describing named item
sjson = pgroup->getJSON();
break;
default:
sjson = detail::bad_JSON(conn);
}
}
else
{
sjson = detail::bad_JSON(conn);
}
mg_send_data(conn, sjson.c_str(), sjson.length());
}
void ouroboros_server::handle_callback_rest(const rest_request& aRequest)
{
//get reference to named thing
std::string resource = normalize_group(aRequest.getGroups()) + '/' + aRequest.getFields();
var_field *named = mStore.get(normalize_group(aRequest.getGroups()), aRequest.getFields());
std::string response;
mg_connection *conn = aRequest.getConnection();
if (named)
{
switch (aRequest.getHttpRequestType())
{
case POST:
{
std::string data(conn->content, conn->content_len);
JSON json(data);
std::string response_url = json.get("callback");
//create callback
//Due to a limitation of C++03, use a semi-global map
//to track response URLs
mResponseUrls[named] = response_url;
std::string callback_id = register_callback(aRequest.getGroups(), aRequest.getFields(), establish_connection);
std::stringstream ss;
ss << "{ \"id\" : \"" << callback_id << "\" }";
mg_send_status(aConn, 201);
response = ss.str();
}
break;
case DELETE:
{
//Send JSON describing named item
std::string data(conn->content, conn->content_len);
JSON json(data);
std::string id = json.get("id");
unregister_callback(id);
response = detail::good_JSON();
}
break;
default:
response = detail::bad_JSON(conn);
}
}
else
{
response = detail::bad_JSON(conn);
}
mg_send_data(conn, response.c_str(), response.length());
}
void ouroboros_server::establish_connection(var_field* aResponse)
{
if (mpSendServer->mResponseUrls.count(aResponse))
{
std::string url = mpSendServer->mResponseUrls[aResponse];
mg_connection *client;
client = mg_connect(mpSendServer->mpServer, url.c_str());
client->connection_param = aResponse;
}
}
void ouroboros_server::send_response(mg_connection *aConn)
{
var_field *aResponse = reinterpret_cast<var_field*>(aConn->connection_param);
if (mResponseUrls.count(aResponse))
{
std::string url = mResponseUrls[aResponse];
size_t delim = url.find("://");
if (delim != std::string::npos)
{
url = url.substr(delim + 3);
}
delim = url.find("/");
std::string host = url.substr(0, delim);
std::string res;
if (delim != std::string::npos)
{
res = url.substr(delim);
}
else
{
res = "/";
}
mg_printf(aConn, "PUT %s HTTP/1.1\r\nHost: %s\r\n"
"Content-Type: application/json\r\n\r\n%s",
res.c_str(),
host.c_str(),
aResponse->getJSON().c_str());
}
}
std::string ouroboros_server::normalize_group(const std::string& aGroup)
{
std::string result = "server";
if(!aGroup.empty())
{
result += group_delimiter + aGroup;
}
return result;
}
void ouroboros_server::handle_notification(const std::string& aGroup, const std::string& aField)
{
std::string key(aGroup+'/'+aField);
if (mCallbackSubjects.count(key))
{
mCallbackSubjects[key].notify();
}
}
mg_result ouroboros_server::handle_uri(mg_connection *conn, const std::string& uri)
{
rest_request request(conn, uri);
if (request.getRestRequestType() != NONE)
{
std::string output;
return handle_rest(request);
}
return MG_FALSE;
}
int ouroboros_server::event_handler(mg_connection *conn, mg_event ev)
{
ouroboros_server *this_server = reinterpret_cast<ouroboros_server*>(conn->server_param);
switch (ev)
{
case MG_AUTH:
return MG_TRUE;
break;
case MG_REQUEST:
return this_server->handle_uri(conn, conn->uri);
break;
case MG_CONNECT:
this_server->send_response(conn);
return MG_TRUE;
default:
return MG_FALSE;
}
}
std::string ouroboros_server::register_callback(
const std::string& aGroup,
const std::string& aField,
callback_function aCallback)
{
std::string result;
var_field *named = mStore.get(normalize_group(aGroup), aField);
if (named)
{
std::string key(aGroup + "/" + aField);
result = mCallbackManager.register_callback(key);
if (!mCallbackSubjects.count(key))
{
mCallbackSubjects[key] = subject<id_callback<var_field*, callback_function> >();
}
id_callback<var_field*, callback_function> cb(result, named, aCallback);
mCallbackSubjects[key].registerObserver(cb);
}
return result;
}
void ouroboros_server::unregister_callback(const std::string& aID)
{
//TODO
}
const std::string ouroboros_server::group_delimiter(data_store<var_field>::group_delimiter);
ouroboros_server *ouroboros_server::mpSendServer = NULL;
}
<commit_msg>Update ouroboros_server.cpp<commit_after>#include "ouroboros_server.h"
#include <server/data/data_store.hpp>
#include <server/device_tree.hpp>
#include <mongoose/mongoose.h>
#include <server/rest.h>
#include <sstream>
#include <cassert>
#include <slre/slre.h>
namespace ouroboros
{
namespace detail
{
std::string bad_JSON(mg_connection* aConn)
{
mg_send_status(aConn, 400);
return std::string("{ \"status\" : \"Bad JSON request.\"}");
}
std::string good_JSON()
{
return std::string("{ \"status\" : \"OK.\"}");
}
}
std::string url_regex("(.+://)?(.+)");
ouroboros_server::ouroboros_server()
:mpServer(NULL),
mStore(device_tree<var_field>::get_device_tree().get_data_store())
{
//The following line is a hack workaround to trying to avoid using
//functional support in c++03
if (!mpSendServer)
{
//HACK
mpSendServer = this;
}
mpServer = mg_create_server(this, ouroboros_server::event_handler);
mg_set_option(mpServer, "document_root", "."); // Serve current directory
mg_set_option(mpServer, "listening_port", "8080"); // Open port 8080
}
ouroboros_server::~ouroboros_server()
{
mg_destroy_server(&mpServer);
}
const var_field *ouroboros_server::get(const std::string& aGroup, const std::string& aField) const
{
return mStore.get(normalize_group(aGroup), aField);
}
var_field *ouroboros_server::get(const std::string& aGroup, const std::string& aField)
{
return const_cast<var_field *>(static_cast<const ouroboros_server&>(*this).get(aGroup, aField));
}
const group<var_field> *ouroboros_server::get(const std::string& aGroup) const
{
return mStore.get(normalize_group(aGroup));
}
group<var_field> *ouroboros_server::get(const std::string& aGroup)
{
return const_cast<group<var_field> *>(static_cast<const ouroboros_server&>(*this).get(aGroup));
}
bool ouroboros_server::set(const std::string& aGroup, const std::string& aField, const var_field& aFieldData)
{
var_field *result = mStore.get(normalize_group(aGroup), aField);
if (!result)
{
return false;
}
result->setJSON(aFieldData.getJSON());
handle_notification(aGroup, aField);
return true;
}
bool ouroboros_server::set(const std::string& , const group<var_field>& )
{
return false;
}
void ouroboros_server::run()
{
mg_poll_server(mpServer, 1000);
}
mg_result ouroboros_server::handle_rest(const rest_request& aRequest)
{
switch (aRequest.getRestRequestType())
{
case FIELDS:
handle_name_rest(aRequest);
break;
case GROUPS:
handle_group_rest(aRequest);
break;
case CALLBACK:
handle_callback_rest(aRequest);
break;
case NONE:
break;
default:
return MG_FALSE;
}
return MG_TRUE;
}
void ouroboros_server::handle_name_rest(const rest_request& aRequest)
{
//get reference to named thing
var_field *named = mStore.get(normalize_group(aRequest.getGroups()), aRequest.getFields());
std::string sjson;
mg_connection *conn = aRequest.getConnection();
if (named)
{
switch (aRequest.getHttpRequestType())
{
case PUT:
{
std::string data(conn->content, conn->content_len);
JSON json(data);
if (named->setJSON(json))
{
handle_notification(aRequest.getGroups(), aRequest.getFields());
sjson = detail::good_JSON();
}
else
{
sjson = detail::bad_JSON(conn);
}
}
break;
case GET:
//Send JSON describing named item
sjson = named->getJSON();
break;
default:
sjson = detail::bad_JSON(conn);
}
}
else
{
sjson = detail::bad_JSON(conn);
}
mg_send_data(conn, sjson.c_str(), sjson.length());
}
void ouroboros_server::handle_group_rest(const rest_request& aRequest)
{
//get reference to named thing
group<var_field> *pgroup = mStore.get(normalize_group(aRequest.getGroups()));
std::string sjson;
mg_connection *conn = aRequest.getConnection();
if (pgroup)
{
switch (aRequest.getHttpRequestType())
{
case GET:
//Send JSON describing named item
sjson = pgroup->getJSON();
break;
default:
sjson = detail::bad_JSON(conn);
}
}
else
{
sjson = detail::bad_JSON(conn);
}
mg_send_data(conn, sjson.c_str(), sjson.length());
}
void ouroboros_server::handle_callback_rest(const rest_request& aRequest)
{
//get reference to named thing
std::string resource = normalize_group(aRequest.getGroups()) + '/' + aRequest.getFields();
var_field *named = mStore.get(normalize_group(aRequest.getGroups()), aRequest.getFields());
std::string response;
mg_connection *conn = aRequest.getConnection();
if (named)
{
switch (aRequest.getHttpRequestType())
{
case POST:
{
std::string data(conn->content, conn->content_len);
JSON json(data);
std::string response_url = json.get("callback");
//create callback
//Due to a limitation of C++03, use a semi-global map
//to track response URLs
mResponseUrls[named] = response_url;
std::string callback_id = register_callback(aRequest.getGroups(), aRequest.getFields(), establish_connection);
std::stringstream ss;
ss << "{ \"id\" : \"" << callback_id << "\" }";
mg_send_status(conn, 201);
response = ss.str();
}
break;
case DELETE:
{
//Send JSON describing named item
std::string data(conn->content, conn->content_len);
JSON json(data);
std::string id = json.get("id");
unregister_callback(id);
response = detail::good_JSON();
}
break;
default:
response = detail::bad_JSON(conn);
}
}
else
{
response = detail::bad_JSON(conn);
}
mg_send_data(conn, response.c_str(), response.length());
}
void ouroboros_server::establish_connection(var_field* aResponse)
{
if (mpSendServer->mResponseUrls.count(aResponse))
{
std::string url = mpSendServer->mResponseUrls[aResponse];
mg_connection *client;
client = mg_connect(mpSendServer->mpServer, url.c_str());
client->connection_param = aResponse;
}
}
void ouroboros_server::send_response(mg_connection *aConn)
{
var_field *aResponse = reinterpret_cast<var_field*>(aConn->connection_param);
if (mResponseUrls.count(aResponse))
{
std::string url = mResponseUrls[aResponse];
size_t delim = url.find("://");
if (delim != std::string::npos)
{
url = url.substr(delim + 3);
}
delim = url.find("/");
std::string host = url.substr(0, delim);
std::string res;
if (delim != std::string::npos)
{
res = url.substr(delim);
}
else
{
res = "/";
}
mg_printf(aConn, "PUT %s HTTP/1.1\r\nHost: %s\r\n"
"Content-Type: application/json\r\n\r\n%s",
res.c_str(),
host.c_str(),
aResponse->getJSON().c_str());
}
}
std::string ouroboros_server::normalize_group(const std::string& aGroup)
{
std::string result = "server";
if(!aGroup.empty())
{
result += group_delimiter + aGroup;
}
return result;
}
void ouroboros_server::handle_notification(const std::string& aGroup, const std::string& aField)
{
std::string key(aGroup+'/'+aField);
if (mCallbackSubjects.count(key))
{
mCallbackSubjects[key].notify();
}
}
mg_result ouroboros_server::handle_uri(mg_connection *conn, const std::string& uri)
{
rest_request request(conn, uri);
if (request.getRestRequestType() != NONE)
{
std::string output;
return handle_rest(request);
}
return MG_FALSE;
}
int ouroboros_server::event_handler(mg_connection *conn, mg_event ev)
{
ouroboros_server *this_server = reinterpret_cast<ouroboros_server*>(conn->server_param);
switch (ev)
{
case MG_AUTH:
return MG_TRUE;
break;
case MG_REQUEST:
return this_server->handle_uri(conn, conn->uri);
break;
case MG_CONNECT:
this_server->send_response(conn);
return MG_TRUE;
default:
return MG_FALSE;
}
}
std::string ouroboros_server::register_callback(
const std::string& aGroup,
const std::string& aField,
callback_function aCallback)
{
std::string result;
var_field *named = mStore.get(normalize_group(aGroup), aField);
if (named)
{
std::string key(aGroup + "/" + aField);
result = mCallbackManager.register_callback(key);
if (!mCallbackSubjects.count(key))
{
mCallbackSubjects[key] = subject<id_callback<var_field*, callback_function> >();
}
id_callback<var_field*, callback_function> cb(result, named, aCallback);
mCallbackSubjects[key].registerObserver(cb);
}
return result;
}
void ouroboros_server::unregister_callback(const std::string& aID)
{
//TODO
}
const std::string ouroboros_server::group_delimiter(data_store<var_field>::group_delimiter);
ouroboros_server *ouroboros_server::mpSendServer = NULL;
}
<|endoftext|> |
<commit_before>//===- MapFile.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the -Map option. It shows lists in order and
// hierarchically the output sections, input sections, input files and
// symbol:
//
// Address Size Align Out In Symbol
// 00201000 00000015 4 .text
// 00201000 0000000e 4 test.o:(.text)
// 0020100e 00000000 0 local
// 00201005 00000000 0 f(int)
//
//===----------------------------------------------------------------------===//
#include "MapFile.h"
#include "InputFiles.h"
#include "LinkerScript.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SymbolTable.h"
#include "SyntheticSections.h"
#include "lld/Common/Threads.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;
typedef DenseMap<const SectionBase *, SmallVector<Defined *, 4>> SymbolMapTy;
// Print out the first three columns of a line.
static void writeHeader(raw_ostream &OS, uint64_t Addr, uint64_t Size,
uint64_t Align) {
int W = Config->Is64 ? 16 : 8;
OS << format("%0*llx %0*llx %5lld ", W, Addr, W, Size, Align);
}
static std::string indent(int Depth) { return std::string(Depth * 8, ' '); }
// Returns a list of all symbols that we want to print out.
static std::vector<Defined *> getSymbols() {
std::vector<Defined *> V;
for (InputFile *File : ObjectFiles)
for (Symbol *B : File->getSymbols())
if (auto *DR = dyn_cast<Defined>(B))
if (DR->getFile() == File && !DR->isSection() && DR->Section &&
DR->Section->Live)
V.push_back(DR);
return V;
}
// Returns a map from sections to their symbols.
static SymbolMapTy getSectionSyms(ArrayRef<Defined *> Syms) {
SymbolMapTy Ret;
for (Defined *S : Syms)
if (auto *DR = dyn_cast<Defined>(S))
Ret[DR->Section].push_back(S);
// Sort symbols by address. We want to print out symbols in the
// order in the output file rather than the order they appeared
// in the input files.
for (auto &It : Ret) {
SmallVectorImpl<Defined *> &V = It.second;
std::sort(V.begin(), V.end(),
[](Defined *A, Defined *B) { return A->getVA() < B->getVA(); });
}
return Ret;
}
// Construct a map from symbols to their stringified representations.
// Demangling symbols (which is what toString() does) is slow, so
// we do that in batch using parallel-for.
static DenseMap<Defined *, std::string>
getSymbolStrings(ArrayRef<Defined *> Syms) {
std::vector<std::string> Str(Syms.size());
parallelForEachN(0, Syms.size(), [&](size_t I) {
raw_string_ostream OS(Str[I]);
writeHeader(OS, Syms[I]->getVA(), Syms[I]->getSize(), 0);
OS << indent(2) << toString(*Syms[I]);
});
DenseMap<Defined *, std::string> Ret;
for (size_t I = 0, E = Syms.size(); I < E; ++I)
Ret[Syms[I]] = std::move(Str[I]);
return Ret;
}
void elf::writeMapFile() {
if (Config->MapFile.empty())
return;
// Open a map file for writing.
std::error_code EC;
raw_fd_ostream OS(Config->MapFile, EC, sys::fs::F_None);
if (EC) {
error("cannot open " + Config->MapFile + ": " + EC.message());
return;
}
// Collect symbol info that we want to print out.
std::vector<Defined *> Syms = getSymbols();
SymbolMapTy SectionSyms = getSectionSyms(Syms);
DenseMap<Defined *, std::string> SymStr = getSymbolStrings(Syms);
// Print out the header line.
int W = Config->Is64 ? 16 : 8;
OS << left_justify("Address", W) << ' ' << left_justify("Size", W)
<< " Align Out In Symbol\n";
// Print out file contents.
for (OutputSection *OSec : OutputSections) {
writeHeader(OS, OSec->Addr, OSec->Size, OSec->Alignment);
OS << OSec->Name << '\n';
// Dump symbols for each input section.
for (BaseCommand *Base : OSec->SectionCommands) {
auto *ISD = dyn_cast<InputSectionDescription>(Base);
if (!ISD)
continue;
for (InputSection *IS : ISD->Sections) {
writeHeader(OS, OSec->Addr + IS->OutSecOff, IS->getSize(),
IS->Alignment);
OS << indent(1) << toString(IS) << '\n';
for (Defined *Sym : SectionSyms[IS])
OS << SymStr[Sym] << '\n';
}
}
}
}
<commit_msg>Simplify. NFC.<commit_after>//===- MapFile.cpp --------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements the -Map option. It shows lists in order and
// hierarchically the output sections, input sections, input files and
// symbol:
//
// Address Size Align Out In Symbol
// 00201000 00000015 4 .text
// 00201000 0000000e 4 test.o:(.text)
// 0020100e 00000000 0 local
// 00201005 00000000 0 f(int)
//
//===----------------------------------------------------------------------===//
#include "MapFile.h"
#include "InputFiles.h"
#include "LinkerScript.h"
#include "OutputSections.h"
#include "Strings.h"
#include "SymbolTable.h"
#include "SyntheticSections.h"
#include "lld/Common/Threads.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using namespace llvm::object;
using namespace lld;
using namespace lld::elf;
typedef DenseMap<const SectionBase *, SmallVector<Defined *, 4>> SymbolMapTy;
// Print out the first three columns of a line.
static void writeHeader(raw_ostream &OS, uint64_t Addr, uint64_t Size,
uint64_t Align) {
int W = Config->Is64 ? 16 : 8;
OS << format("%0*llx %0*llx %5lld ", W, Addr, W, Size, Align);
}
static std::string indent(int Depth) { return std::string(Depth * 8, ' '); }
// Returns a list of all symbols that we want to print out.
static std::vector<Defined *> getSymbols() {
std::vector<Defined *> V;
for (InputFile *File : ObjectFiles)
for (Symbol *B : File->getSymbols())
if (auto *DR = dyn_cast<Defined>(B))
if (DR->getFile() == File && !DR->isSection() && DR->Section &&
DR->Section->Live)
V.push_back(DR);
return V;
}
// Returns a map from sections to their symbols.
static SymbolMapTy getSectionSyms(ArrayRef<Defined *> Syms) {
SymbolMapTy Ret;
for (Defined *S : Syms)
Ret[S->Section].push_back(S);
// Sort symbols by address. We want to print out symbols in the
// order in the output file rather than the order they appeared
// in the input files.
for (auto &It : Ret) {
SmallVectorImpl<Defined *> &V = It.second;
std::sort(V.begin(), V.end(),
[](Defined *A, Defined *B) { return A->getVA() < B->getVA(); });
}
return Ret;
}
// Construct a map from symbols to their stringified representations.
// Demangling symbols (which is what toString() does) is slow, so
// we do that in batch using parallel-for.
static DenseMap<Defined *, std::string>
getSymbolStrings(ArrayRef<Defined *> Syms) {
std::vector<std::string> Str(Syms.size());
parallelForEachN(0, Syms.size(), [&](size_t I) {
raw_string_ostream OS(Str[I]);
writeHeader(OS, Syms[I]->getVA(), Syms[I]->getSize(), 0);
OS << indent(2) << toString(*Syms[I]);
});
DenseMap<Defined *, std::string> Ret;
for (size_t I = 0, E = Syms.size(); I < E; ++I)
Ret[Syms[I]] = std::move(Str[I]);
return Ret;
}
void elf::writeMapFile() {
if (Config->MapFile.empty())
return;
// Open a map file for writing.
std::error_code EC;
raw_fd_ostream OS(Config->MapFile, EC, sys::fs::F_None);
if (EC) {
error("cannot open " + Config->MapFile + ": " + EC.message());
return;
}
// Collect symbol info that we want to print out.
std::vector<Defined *> Syms = getSymbols();
SymbolMapTy SectionSyms = getSectionSyms(Syms);
DenseMap<Defined *, std::string> SymStr = getSymbolStrings(Syms);
// Print out the header line.
int W = Config->Is64 ? 16 : 8;
OS << left_justify("Address", W) << ' ' << left_justify("Size", W)
<< " Align Out In Symbol\n";
// Print out file contents.
for (OutputSection *OSec : OutputSections) {
writeHeader(OS, OSec->Addr, OSec->Size, OSec->Alignment);
OS << OSec->Name << '\n';
// Dump symbols for each input section.
for (BaseCommand *Base : OSec->SectionCommands) {
auto *ISD = dyn_cast<InputSectionDescription>(Base);
if (!ISD)
continue;
for (InputSection *IS : ISD->Sections) {
writeHeader(OS, OSec->Addr + IS->OutSecOff, IS->getSize(),
IS->Alignment);
OS << indent(1) << toString(IS) << '\n';
for (Defined *Sym : SectionSyms[IS])
OS << SymStr[Sym] << '\n';
}
}
}
}
<|endoftext|> |
<commit_before>/* cbr
* main.cpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 cbr 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 "Timer.hpp"
#include "TimeSync.hpp"
#include "TimeProfiler.hpp"
#include "Network.hpp"
#include "Forwarder.hpp"
#include "LocationService.hpp"
#include "Proximity.hpp"
#include "Server.hpp"
#include "Options.hpp"
#include "Statistics.hpp"
#include "StandardLocationService.hpp"
#include "Test.hpp"
#include "SSTNetwork.hpp"
#include "TCPNetwork.hpp"
#include "FIFOServerMessageQueue.hpp"
#include "FairServerMessageQueue.hpp"
#include "TabularServerIDMap.hpp"
#include "ExpIntegral.hpp"
#include "SqrIntegral.hpp"
#include "UniformCoordinateSegmentation.hpp"
#include "CoordinateSegmentationClient.hpp"
#include "LoadMonitor.hpp"
#include "CraqObjectSegmentation.hpp"
#include "ServerWeightCalculator.hpp"
#include "SpaceContext.hpp"
namespace {
CBR::Network* gNetwork = NULL;
CBR::Trace* gTrace = NULL;
CBR::SpaceContext* gSpaceContext = NULL;
CBR::Time g_start_time( CBR::Time::null() );
}
void *main_loop(void *);
int main(int argc, char** argv) {
using namespace CBR;
InitOptions();
ParseOptions(argc, argv);
std::string time_server=GetOption("time-server")->as<String>();
TimeSync sync;
sync.start(time_server);
ServerID server_id = GetOption("id")->as<ServerID>();
String trace_file = GetPerServerFile(STATS_TRACE_FILE, server_id);
gTrace = new Trace(trace_file);
// Compute the starting date/time
String start_time_str = GetOption("wait-until")->as<String>();
g_start_time = start_time_str.empty() ? Timer::now() : Timer::getSpecifiedDate( start_time_str );
Time start_time = g_start_time;
start_time += GetOption("wait-additional")->as<Duration>();
Duration duration = GetOption("duration")->as<Duration>();
IOService* ios = IOServiceFactory::makeIOService();
IOStrand* mainStrand = ios->createStrand();
Time init_space_ctx_time = Time::null() + (Timer::now() - start_time);
SpaceContext* space_context = new SpaceContext(server_id, ios, mainStrand, start_time, init_space_ctx_time, gTrace, duration);
gSpaceContext = space_context;
String network_type = GetOption(NETWORK_TYPE)->as<String>();
if (network_type == "sst")
gNetwork = new SSTNetwork(space_context);
else if (network_type == "tcp")
gNetwork = new TCPNetwork(space_context,GetOption("space-to-space-receive-buffer")->as<size_t>(),GetOption(RECEIVE_BANDWIDTH)->as<uint32>(),GetOption(SEND_BANDWIDTH)->as<uint32>());
gNetwork->init(&main_loop);
sync.stop();
return 0;
}
void *main_loop(void *) {
using namespace CBR;
ServerID server_id = GetOption("id")->as<ServerID>();
String test_mode = GetOption("test")->as<String>();
if (test_mode != "none") {
String server_port = GetOption("server-port")->as<String>();
String client_port = GetOption("client-port")->as<String>();
String host = GetOption("host")->as<String>();
if (test_mode == "server")
CBR::testServer(server_port.c_str(), host.c_str(), client_port.c_str());
else if (test_mode == "client")
CBR::testClient(client_port.c_str(), host.c_str(), server_port.c_str());
return 0;
}
BoundingBox3f region = GetOption("region")->as<BoundingBox3f>();
Vector3ui32 layout = GetOption("layout")->as<Vector3ui32>();
uint32 max_space_servers = GetOption("max-servers")->as<uint32>();
if (max_space_servers == 0)
max_space_servers = layout.x * layout.y * layout.z;
uint32 num_oh_servers = GetOption("num-oh")->as<uint32>();
uint32 nservers = max_space_servers + num_oh_servers;
Duration duration = GetOption("duration")->as<Duration>();
srand( GetOption("rand-seed")->as<uint32>() );
SpaceContext* space_context = gSpaceContext;
Forwarder* forwarder = new Forwarder(space_context);
LocationService* loc_service = NULL;
String loc_service_type = GetOption(LOC)->as<String>();
if (loc_service_type == "standard")
loc_service = new StandardLocationService(space_context);
else
assert(false);
String filehandle = GetOption("serverips")->as<String>();
std::ifstream ipConfigFileHandle(filehandle.c_str());
ServerIDMap * server_id_map = new TabularServerIDMap(ipConfigFileHandle);
gTrace->setServerIDMap(server_id_map);
gNetwork->setServerIDMap(server_id_map);
ServerMessageQueue* sq = NULL;
String server_queue_type = GetOption(SERVER_QUEUE)->as<String>();
if (server_queue_type == "fifo")
sq = new FIFOServerMessageQueue(space_context, gNetwork, server_id_map, GetOption(SEND_BANDWIDTH)->as<uint32>(),GetOption(RECEIVE_BANDWIDTH)->as<uint32>());
else if (server_queue_type == "fair")
sq = new FairServerMessageQueue(space_context, gNetwork, server_id_map, GetOption(SEND_BANDWIDTH)->as<uint32>(),GetOption(RECEIVE_BANDWIDTH)->as<uint32>());
else {
assert(false);
exit(-1);
}
String cseg_type = GetOption(CSEG)->as<String>();
CoordinateSegmentation* cseg = NULL;
if (cseg_type == "uniform")
cseg = new UniformCoordinateSegmentation(space_context, region, layout);
else if (cseg_type == "client") {
cseg = new CoordinateSegmentationClient(space_context, region, layout, server_id_map);
}
else {
assert(false);
exit(-1);
}
LoadMonitor* loadMonitor = new LoadMonitor(space_context, sq, cseg);
//Create OSeg
std::string oseg_type=GetOption(OSEG)->as<String>();
IOStrand* osegStrand = space_context->ioService->createStrand();
ObjectSegmentation* oseg = NULL;
if (oseg_type == OSEG_OPTION_CRAQ)
{
//using craq approach
std::vector<UUID> initServObjVec;
std::vector<CraqInitializeArgs> craqArgsGet;
CraqInitializeArgs cInitArgs1;
cInitArgs1.ipAdd = "localhost";
cInitArgs1.port = "10298";
craqArgsGet.push_back(cInitArgs1);
std::vector<CraqInitializeArgs> craqArgsSet;
CraqInitializeArgs cInitArgs2;
cInitArgs2.ipAdd = "localhost";
cInitArgs2.port = "10299";
craqArgsSet.push_back(cInitArgs2);
std::string oseg_craq_prefix=GetOption(OSEG_UNIQUE_CRAQ_PREFIX)->as<String>();
if (oseg_type.size() ==0)
{
std::cout<<"\n\nERROR: Incorrect craq prefix for oseg. String must be at least one letter long. (And be between G and Z.) Please try again.\n\n";
assert(false);
}
std::cout<<"\n\nUniquely appending "<<oseg_craq_prefix[0]<<"\n\n";
oseg = new CraqObjectSegmentation (space_context, cseg, initServObjVec, craqArgsGet, craqArgsSet, oseg_craq_prefix[0],osegStrand,space_context->mainStrand);
} //end craq approach
//end create oseg
ServerWeightCalculator* weight_calc = NULL;
if (GetOption("gaussian")->as<bool>()) {
weight_calc =
new ServerWeightCalculator(
server_id,
cseg,
std::tr1::bind(&integralExpFunction,GetOption("flatness")->as<double>(),
std::tr1::placeholders::_1,
std::tr1::placeholders::_2,
std::tr1::placeholders::_3,
std::tr1::placeholders::_4),
sq
);
}else {
weight_calc =
new ServerWeightCalculator(
server_id,
cseg,
std::tr1::bind(SqrIntegral(false),GetOption("const-cutoff")->as<double>(),GetOption("flatness")->as<double>(),
std::tr1::placeholders::_1,
std::tr1::placeholders::_2,
std::tr1::placeholders::_3,
std::tr1::placeholders::_4),
sq);
}
// We have all the info to initialize the forwarder now
forwarder->initialize(oseg, sq);
Proximity* prox = new Proximity(space_context, loc_service);
Server* server = new Server(space_context, forwarder, loc_service, cseg, prox, oseg, server_id_map->lookupExternal(space_context->id()));
prox->initialize(cseg);
Time start_time = g_start_time;
// If we're one of the initial nodes, we'll have to wait until we hit the start time
{
Time now_time = Timer::now();
if (start_time > now_time) {
Duration sleep_time = start_time - now_time;
printf("Waiting %f seconds\n", sleep_time.toSeconds() ); fflush(stdout);
usleep( sleep_time.toMicroseconds() );
}
}
///////////Go go go!! start of simulation/////////////////////
gNetwork->begin();
space_context->add(space_context);
space_context->add(gNetwork);
space_context->add(cseg);
space_context->add(loc_service);
space_context->add(prox);
space_context->add(server);
space_context->add(oseg);
space_context->add(forwarder);
space_context->add(loadMonitor);
space_context->run(2);
if (GetOption(PROFILE)->as<bool>()) {
space_context->profiler->report();
}
gTrace->prepareShutdown();
prox->shutdown();
delete server;
delete sq;
delete prox;
delete server_id_map;
if (weight_calc != NULL)
delete weight_calc;
delete cseg;
delete oseg;
delete loc_service;
delete forwarder;
delete gNetwork;
gNetwork=NULL;
gTrace->shutdown();
delete gTrace;
gTrace = NULL;
IOStrand* mainStrand = space_context->mainStrand;
IOService* ios = space_context->ioService;
delete osegStrand;
delete space_context;
space_context = NULL;
delete mainStrand;
delete osegStrand;
IOServiceFactory::destroyIOService(ios);
return 0;
}
<commit_msg>Oooops. Deleting somethign twice.<commit_after>/* cbr
* main.cpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 cbr 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 "Timer.hpp"
#include "TimeSync.hpp"
#include "TimeProfiler.hpp"
#include "Network.hpp"
#include "Forwarder.hpp"
#include "LocationService.hpp"
#include "Proximity.hpp"
#include "Server.hpp"
#include "Options.hpp"
#include "Statistics.hpp"
#include "StandardLocationService.hpp"
#include "Test.hpp"
#include "SSTNetwork.hpp"
#include "TCPNetwork.hpp"
#include "FIFOServerMessageQueue.hpp"
#include "FairServerMessageQueue.hpp"
#include "TabularServerIDMap.hpp"
#include "ExpIntegral.hpp"
#include "SqrIntegral.hpp"
#include "UniformCoordinateSegmentation.hpp"
#include "CoordinateSegmentationClient.hpp"
#include "LoadMonitor.hpp"
#include "CraqObjectSegmentation.hpp"
#include "ServerWeightCalculator.hpp"
#include "SpaceContext.hpp"
namespace {
CBR::Network* gNetwork = NULL;
CBR::Trace* gTrace = NULL;
CBR::SpaceContext* gSpaceContext = NULL;
CBR::Time g_start_time( CBR::Time::null() );
}
void *main_loop(void *);
int main(int argc, char** argv) {
using namespace CBR;
InitOptions();
ParseOptions(argc, argv);
std::string time_server=GetOption("time-server")->as<String>();
TimeSync sync;
sync.start(time_server);
ServerID server_id = GetOption("id")->as<ServerID>();
String trace_file = GetPerServerFile(STATS_TRACE_FILE, server_id);
gTrace = new Trace(trace_file);
// Compute the starting date/time
String start_time_str = GetOption("wait-until")->as<String>();
g_start_time = start_time_str.empty() ? Timer::now() : Timer::getSpecifiedDate( start_time_str );
Time start_time = g_start_time;
start_time += GetOption("wait-additional")->as<Duration>();
Duration duration = GetOption("duration")->as<Duration>();
IOService* ios = IOServiceFactory::makeIOService();
IOStrand* mainStrand = ios->createStrand();
Time init_space_ctx_time = Time::null() + (Timer::now() - start_time);
SpaceContext* space_context = new SpaceContext(server_id, ios, mainStrand, start_time, init_space_ctx_time, gTrace, duration);
gSpaceContext = space_context;
String network_type = GetOption(NETWORK_TYPE)->as<String>();
if (network_type == "sst")
gNetwork = new SSTNetwork(space_context);
else if (network_type == "tcp")
gNetwork = new TCPNetwork(space_context,GetOption("space-to-space-receive-buffer")->as<size_t>(),GetOption(RECEIVE_BANDWIDTH)->as<uint32>(),GetOption(SEND_BANDWIDTH)->as<uint32>());
gNetwork->init(&main_loop);
sync.stop();
return 0;
}
void *main_loop(void *) {
using namespace CBR;
ServerID server_id = GetOption("id")->as<ServerID>();
String test_mode = GetOption("test")->as<String>();
if (test_mode != "none") {
String server_port = GetOption("server-port")->as<String>();
String client_port = GetOption("client-port")->as<String>();
String host = GetOption("host")->as<String>();
if (test_mode == "server")
CBR::testServer(server_port.c_str(), host.c_str(), client_port.c_str());
else if (test_mode == "client")
CBR::testClient(client_port.c_str(), host.c_str(), server_port.c_str());
return 0;
}
BoundingBox3f region = GetOption("region")->as<BoundingBox3f>();
Vector3ui32 layout = GetOption("layout")->as<Vector3ui32>();
uint32 max_space_servers = GetOption("max-servers")->as<uint32>();
if (max_space_servers == 0)
max_space_servers = layout.x * layout.y * layout.z;
uint32 num_oh_servers = GetOption("num-oh")->as<uint32>();
uint32 nservers = max_space_servers + num_oh_servers;
Duration duration = GetOption("duration")->as<Duration>();
srand( GetOption("rand-seed")->as<uint32>() );
SpaceContext* space_context = gSpaceContext;
Forwarder* forwarder = new Forwarder(space_context);
LocationService* loc_service = NULL;
String loc_service_type = GetOption(LOC)->as<String>();
if (loc_service_type == "standard")
loc_service = new StandardLocationService(space_context);
else
assert(false);
String filehandle = GetOption("serverips")->as<String>();
std::ifstream ipConfigFileHandle(filehandle.c_str());
ServerIDMap * server_id_map = new TabularServerIDMap(ipConfigFileHandle);
gTrace->setServerIDMap(server_id_map);
gNetwork->setServerIDMap(server_id_map);
ServerMessageQueue* sq = NULL;
String server_queue_type = GetOption(SERVER_QUEUE)->as<String>();
if (server_queue_type == "fifo")
sq = new FIFOServerMessageQueue(space_context, gNetwork, server_id_map, GetOption(SEND_BANDWIDTH)->as<uint32>(),GetOption(RECEIVE_BANDWIDTH)->as<uint32>());
else if (server_queue_type == "fair")
sq = new FairServerMessageQueue(space_context, gNetwork, server_id_map, GetOption(SEND_BANDWIDTH)->as<uint32>(),GetOption(RECEIVE_BANDWIDTH)->as<uint32>());
else {
assert(false);
exit(-1);
}
String cseg_type = GetOption(CSEG)->as<String>();
CoordinateSegmentation* cseg = NULL;
if (cseg_type == "uniform")
cseg = new UniformCoordinateSegmentation(space_context, region, layout);
else if (cseg_type == "client") {
cseg = new CoordinateSegmentationClient(space_context, region, layout, server_id_map);
}
else {
assert(false);
exit(-1);
}
LoadMonitor* loadMonitor = new LoadMonitor(space_context, sq, cseg);
//Create OSeg
std::string oseg_type=GetOption(OSEG)->as<String>();
IOStrand* osegStrand = space_context->ioService->createStrand();
ObjectSegmentation* oseg = NULL;
if (oseg_type == OSEG_OPTION_CRAQ)
{
//using craq approach
std::vector<UUID> initServObjVec;
std::vector<CraqInitializeArgs> craqArgsGet;
CraqInitializeArgs cInitArgs1;
cInitArgs1.ipAdd = "localhost";
cInitArgs1.port = "10298";
craqArgsGet.push_back(cInitArgs1);
std::vector<CraqInitializeArgs> craqArgsSet;
CraqInitializeArgs cInitArgs2;
cInitArgs2.ipAdd = "localhost";
cInitArgs2.port = "10299";
craqArgsSet.push_back(cInitArgs2);
std::string oseg_craq_prefix=GetOption(OSEG_UNIQUE_CRAQ_PREFIX)->as<String>();
if (oseg_type.size() ==0)
{
std::cout<<"\n\nERROR: Incorrect craq prefix for oseg. String must be at least one letter long. (And be between G and Z.) Please try again.\n\n";
assert(false);
}
std::cout<<"\n\nUniquely appending "<<oseg_craq_prefix[0]<<"\n\n";
oseg = new CraqObjectSegmentation (space_context, cseg, initServObjVec, craqArgsGet, craqArgsSet, oseg_craq_prefix[0],osegStrand,space_context->mainStrand);
} //end craq approach
//end create oseg
ServerWeightCalculator* weight_calc = NULL;
if (GetOption("gaussian")->as<bool>()) {
weight_calc =
new ServerWeightCalculator(
server_id,
cseg,
std::tr1::bind(&integralExpFunction,GetOption("flatness")->as<double>(),
std::tr1::placeholders::_1,
std::tr1::placeholders::_2,
std::tr1::placeholders::_3,
std::tr1::placeholders::_4),
sq
);
}else {
weight_calc =
new ServerWeightCalculator(
server_id,
cseg,
std::tr1::bind(SqrIntegral(false),GetOption("const-cutoff")->as<double>(),GetOption("flatness")->as<double>(),
std::tr1::placeholders::_1,
std::tr1::placeholders::_2,
std::tr1::placeholders::_3,
std::tr1::placeholders::_4),
sq);
}
// We have all the info to initialize the forwarder now
forwarder->initialize(oseg, sq);
Proximity* prox = new Proximity(space_context, loc_service);
Server* server = new Server(space_context, forwarder, loc_service, cseg, prox, oseg, server_id_map->lookupExternal(space_context->id()));
prox->initialize(cseg);
Time start_time = g_start_time;
// If we're one of the initial nodes, we'll have to wait until we hit the start time
{
Time now_time = Timer::now();
if (start_time > now_time) {
Duration sleep_time = start_time - now_time;
printf("Waiting %f seconds\n", sleep_time.toSeconds() ); fflush(stdout);
usleep( sleep_time.toMicroseconds() );
}
}
///////////Go go go!! start of simulation/////////////////////
gNetwork->begin();
space_context->add(space_context);
space_context->add(gNetwork);
space_context->add(cseg);
space_context->add(loc_service);
space_context->add(prox);
space_context->add(server);
space_context->add(oseg);
space_context->add(forwarder);
space_context->add(loadMonitor);
space_context->run(2);
if (GetOption(PROFILE)->as<bool>()) {
space_context->profiler->report();
}
gTrace->prepareShutdown();
prox->shutdown();
delete server;
delete sq;
delete prox;
delete server_id_map;
if (weight_calc != NULL)
delete weight_calc;
delete cseg;
delete oseg;
delete loc_service;
delete forwarder;
delete gNetwork;
gNetwork=NULL;
gTrace->shutdown();
delete gTrace;
gTrace = NULL;
IOStrand* mainStrand = space_context->mainStrand;
IOService* ios = space_context->ioService;
delete space_context;
space_context = NULL;
delete mainStrand;
delete osegStrand;
IOServiceFactory::destroyIOService(ios);
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <time.h>
#include <unistd.h>
#include <sys/shm.h>
#include "bcm_host.h"
#include "GLES2/gl2.h"
#include "EGL/egl.h"
#include "EGL/eglext.h"
#include "shader.h"
// #define INOTIFY_THREAD_SAFE
#include "inotify-cxx.h"
typedef struct {
uint32_t screen_width;
uint32_t screen_height;
// OpenGL|ES objects
EGLDisplay display;
EGLSurface surface;
EGLContext context;
GLuint buf;
Shader shader;
} CUBE_STATE_T;
bool* fragHasChanged;
std::string fragFile;
std::string vertSource =
"attribute vec4 a_position;"
"varying vec2 v_texcoord;"
"void main(void) {"
" gl_Position = a_position;"
" v_texcoord = a_position.xy*0.5+0.5;"
"}";
static CUBE_STATE_T _state, *state=&_state;
static void init_ogl(CUBE_STATE_T *state){
int32_t success = 0;
EGLBoolean result;
EGLint num_config;
static EGL_DISPMANX_WINDOW_T nativewindow;
DISPMANX_ELEMENT_HANDLE_T dispman_element;
DISPMANX_DISPLAY_HANDLE_T dispman_display;
DISPMANX_UPDATE_HANDLE_T dispman_update;
VC_RECT_T dst_rect;
VC_RECT_T src_rect;
static const EGLint attribute_list[] = {
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
static const EGLint context_attributes[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
EGLConfig config;
// get an EGL display connection
state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
assert(state->display!=EGL_NO_DISPLAY);
// initialize the EGL display connection
result = eglInitialize(state->display, NULL, NULL);
assert(EGL_FALSE != result);
// get an appropriate EGL frame buffer configuration
result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config);
assert(EGL_FALSE != result);
// get an appropriate EGL frame buffer configuration
result = eglBindAPI(EGL_OPENGL_ES_API);
assert(EGL_FALSE != result);
// create an EGL rendering context
state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes);
assert(state->context!=EGL_NO_CONTEXT);
// create an EGL window surface
success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height);
assert( success >= 0 );
dst_rect.x = 0;
dst_rect.y = 0;
dst_rect.width = state->screen_width;
dst_rect.height = state->screen_height;
src_rect.x = 0;
src_rect.y = 0;
src_rect.width = state->screen_width << 16;
src_rect.height = state->screen_height << 16;
dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
dispman_update = vc_dispmanx_update_start( 0 );
dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
0/*layer*/, &dst_rect, 0/*src*/,
&src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/);
nativewindow.element = dispman_element;
nativewindow.width = state->screen_width;
nativewindow.height = state->screen_height;
vc_dispmanx_update_submit_sync( dispman_update );
state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL );
assert(state->surface != EGL_NO_SURFACE);
// connect the context to the surface
result = eglMakeCurrent(state->display, state->surface, state->surface, state->context);
assert(EGL_FALSE != result);
// Set background color and clear buffers
glClearColor(0.15f, 0.25f, 0.35f, 1.0f);
glClear( GL_COLOR_BUFFER_BIT );
}
static bool loadFromPath(const std::string& path, std::string* into) {
std::ifstream file;
std::string buffer;
file.open(path.c_str());
if(!file.is_open()) return false;
while(!file.eof()) {
getline(file, buffer);
(*into) += buffer + "\n";
}
file.close();
return true;
}
static void draw(CUBE_STATE_T *state, GLfloat cx, GLfloat cy){
if(*fragHasChanged) {
std::string fragSource;
if(loadFromPath(fragFile, &fragSource)){
state->shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER);
state->shader.build(fragSource,vertSource);
*fragHasChanged = false;
std::cout << "Parent: reloading shader" << std::endl;
}
}
// Now render to the main frame buffer
glBindFramebuffer(GL_FRAMEBUFFER,0);
// Clear the background (not really necessary I suppose)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glBindBuffer(GL_ARRAY_BUFFER, state->buf);
state->shader.use();
state->shader.sendUniform("u_time",((float)clock())/CLOCKS_PER_SEC);
state->shader.sendUniform("u_mouse",cx, cy);
state->shader.sendUniform("u_resolution",state->screen_width, state->screen_height);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glFlush();
glFinish();
eglSwapBuffers(state->display, state->surface);
}
static int get_mouse(CUBE_STATE_T *state, int *outx, int *outy){
static int fd = -1;
const int width=state->screen_width, height=state->screen_height;
static int x=800, y=400;
const int XSIGN = 1<<4, YSIGN = 1<<5;
if (fd<0) {
fd = open("/dev/input/mouse0",O_RDONLY|O_NONBLOCK);
}
if (fd>=0) {
struct {char buttons, dx, dy; } m;
while (1) {
int bytes = read(fd, &m, sizeof m);
if (bytes < (int)sizeof m) goto _exit;
if (m.buttons&8) {
break; // This bit should always be set
}
read(fd, &m, 1); // Try to sync up again
}
if (m.buttons&3)
return m.buttons&3;
x+=m.dx;
y+=m.dy;
if (m.buttons&XSIGN)
x-=256;
if (m.buttons&YSIGN)
y-=256;
if (x<0) x=0;
if (y<0) y=0;
if (x>width) x=width;
if (y>height) y=height;
}
_exit:
if (outx) *outx = x;
if (outy) *outy = y;
return 0;
}
void drawThread() {
while (1) {
int x, y, b;
b = get_mouse(state, &x, &y);
if (b) break;
draw(state, x, y);
}
}
void watchThread(const std::string& file) {
Inotify notify;
InotifyWatch watch(file, IN_MODIFY);//IN_ALL_EVENTS);
notify.Add(watch);
for (;;) {
if(!(*fragHasChanged)){
std::cout << "Child: Watching again" << std::endl;
notify.WaitForEvents();
size_t count = notify.GetEventCount();
while(count-- > 0) {
InotifyEvent event;
bool got_event = notify.GetEvent(&event);
if(got_event){
std::string mask_str;
event.DumpTypes(mask_str);
*fragHasChanged = true;
std::cout << "Child: Something have change " << mask_str << std::endl;
}
}
}
}
}
void init(const std::string& fragFile) {
GLfloat cx, cy;
bcm_host_init();
// Clear application state
memset( state, 0, sizeof( *state ) );
// Start OGLES
init_ogl(state);
// Build shader;
//
std::string fragSource;
if(!loadFromPath(fragFile, &fragSource)) {
return;
}
state->shader.build(fragSource,vertSource);
// Make Quad
//
static const GLfloat vertex_data[] = {
-1.0,-1.0,1.0,1.0,
1.0,-1.0,1.0,1.0,
1.0,1.0,1.0,1.0,
-1.0,1.0,1.0,1.0
};
GLint posAttribut = state->shader.getAttribLocation("a_position");
glClearColor ( 0.0, 1.0, 1.0, 1.0 );
glGenBuffers(1, &state->buf);
// Prepare viewport
glViewport ( 0, 0, state->screen_width, state->screen_height );
// Upload vertex data to a buffer
glBindBuffer(GL_ARRAY_BUFFER, state->buf);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data),
vertex_data, GL_STATIC_DRAW);
glVertexAttribPointer(posAttribut, 4, GL_FLOAT, 0, 16, 0);
glEnableVertexAttribArray(posAttribut);
}
//==============================================================================
int main(int argc, char **argv){
fragFile = std::string(argv[1]);
int shmId = shmget(IPC_PRIVATE, sizeof(bool), 0666);
pid_t pid = fork();
fragHasChanged = (bool *) shmat(shmId, NULL, 0);
switch(pid) {
case -1: //error
break;
case 0: // child
{
*fragHasChanged = false;
watchThread(fragFile);
}
break;
default:
{
init(fragFile);
drawThread();
kill(pid, SIGKILL);
}
break;
}
shmctl(shmId, IPC_RMID, NULL);
return 0;
}
<commit_msg>watching folder<commit_after>#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <time.h>
#include <unistd.h>
#include <sys/shm.h>
#include "bcm_host.h"
#include "GLES2/gl2.h"
#include "EGL/egl.h"
#include "EGL/eglext.h"
#include "shader.h"
#include "inotify-cxx.h"
typedef struct {
uint32_t screen_width;
uint32_t screen_height;
// OpenGL|ES objects
EGLDisplay display;
EGLSurface surface;
EGLContext context;
GLuint buf;
Shader shader;
} CUBE_STATE_T;
bool* fragHasChanged;
std::string fragFile;
std::string vertSource =
"attribute vec4 a_position;"
"varying vec2 v_texcoord;"
"void main(void) {"
" gl_Position = a_position;"
" v_texcoord = a_position.xy*0.5+0.5;"
"}";
static CUBE_STATE_T _state, *state=&_state;
static void init_ogl(CUBE_STATE_T *state){
int32_t success = 0;
EGLBoolean result;
EGLint num_config;
static EGL_DISPMANX_WINDOW_T nativewindow;
DISPMANX_ELEMENT_HANDLE_T dispman_element;
DISPMANX_DISPLAY_HANDLE_T dispman_display;
DISPMANX_UPDATE_HANDLE_T dispman_update;
VC_RECT_T dst_rect;
VC_RECT_T src_rect;
static const EGLint attribute_list[] = {
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_NONE
};
static const EGLint context_attributes[] = {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL_NONE
};
EGLConfig config;
// get an EGL display connection
state->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
assert(state->display!=EGL_NO_DISPLAY);
// initialize the EGL display connection
result = eglInitialize(state->display, NULL, NULL);
assert(EGL_FALSE != result);
// get an appropriate EGL frame buffer configuration
result = eglChooseConfig(state->display, attribute_list, &config, 1, &num_config);
assert(EGL_FALSE != result);
// get an appropriate EGL frame buffer configuration
result = eglBindAPI(EGL_OPENGL_ES_API);
assert(EGL_FALSE != result);
// create an EGL rendering context
state->context = eglCreateContext(state->display, config, EGL_NO_CONTEXT, context_attributes);
assert(state->context!=EGL_NO_CONTEXT);
// create an EGL window surface
success = graphics_get_display_size(0 /* LCD */, &state->screen_width, &state->screen_height);
assert( success >= 0 );
dst_rect.x = 0;
dst_rect.y = 0;
dst_rect.width = state->screen_width;
dst_rect.height = state->screen_height;
src_rect.x = 0;
src_rect.y = 0;
src_rect.width = state->screen_width << 16;
src_rect.height = state->screen_height << 16;
dispman_display = vc_dispmanx_display_open( 0 /* LCD */);
dispman_update = vc_dispmanx_update_start( 0 );
dispman_element = vc_dispmanx_element_add ( dispman_update, dispman_display,
0/*layer*/, &dst_rect, 0/*src*/,
&src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, 0/*transform*/);
nativewindow.element = dispman_element;
nativewindow.width = state->screen_width;
nativewindow.height = state->screen_height;
vc_dispmanx_update_submit_sync( dispman_update );
state->surface = eglCreateWindowSurface( state->display, config, &nativewindow, NULL );
assert(state->surface != EGL_NO_SURFACE);
// connect the context to the surface
result = eglMakeCurrent(state->display, state->surface, state->surface, state->context);
assert(EGL_FALSE != result);
// Set background color and clear buffers
glClearColor(0.15f, 0.25f, 0.35f, 1.0f);
glClear( GL_COLOR_BUFFER_BIT );
}
static bool loadFromPath(const std::string& path, std::string* into) {
std::ifstream file;
std::string buffer;
file.open(path.c_str());
if(!file.is_open()) return false;
while(!file.eof()) {
getline(file, buffer);
(*into) += buffer + "\n";
}
file.close();
return true;
}
static void draw(CUBE_STATE_T *state, GLfloat cx, GLfloat cy){
if(*fragHasChanged) {
std::string fragSource;
if(loadFromPath(fragFile, &fragSource)){
state->shader.detach(GL_FRAGMENT_SHADER | GL_VERTEX_SHADER);
state->shader.build(fragSource,vertSource);
*fragHasChanged = false;
std::cout << "Parent: reloading shader" << std::endl;
}
}
// Now render to the main frame buffer
glBindFramebuffer(GL_FRAMEBUFFER,0);
// Clear the background (not really necessary I suppose)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glBindBuffer(GL_ARRAY_BUFFER, state->buf);
state->shader.use();
state->shader.sendUniform("u_time",((float)clock())/CLOCKS_PER_SEC);
state->shader.sendUniform("u_mouse",cx, cy);
state->shader.sendUniform("u_resolution",state->screen_width, state->screen_height);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glFlush();
glFinish();
eglSwapBuffers(state->display, state->surface);
}
static int get_mouse(CUBE_STATE_T *state, int *outx, int *outy){
static int fd = -1;
const int width=state->screen_width, height=state->screen_height;
static int x=800, y=400;
const int XSIGN = 1<<4, YSIGN = 1<<5;
if (fd<0) {
fd = open("/dev/input/mouse0",O_RDONLY|O_NONBLOCK);
}
if (fd>=0) {
struct {char buttons, dx, dy; } m;
while (1) {
int bytes = read(fd, &m, sizeof m);
if (bytes < (int)sizeof m) goto _exit;
if (m.buttons&8) {
break; // This bit should always be set
}
read(fd, &m, 1); // Try to sync up again
}
if (m.buttons&3)
return m.buttons&3;
x+=m.dx;
y+=m.dy;
if (m.buttons&XSIGN)
x-=256;
if (m.buttons&YSIGN)
y-=256;
if (x<0) x=0;
if (y<0) y=0;
if (x>width) x=width;
if (y>height) y=height;
}
_exit:
if (outx) *outx = x;
if (outy) *outy = y;
return 0;
}
void drawThread() {
while (1) {
int x, y, b;
b = get_mouse(state, &x, &y);
if (b) break;
draw(state, x, y);
}
}
void watchThread(const std::string& _file) {
Inotify notify;
InotifyWatch watch(".", IN_MODIFY);//IN_ALL_EVENTS);
notify.Add(watch);
for (;;) {
if(!(*fragHasChanged)){
notify.WaitForEvents();
size_t count = notify.GetEventCount();
while(count-- > 0) {
InotifyEvent event;
bool got_event = notify.GetEvent(&event);
if(got_event){
std::string mask_str;
event.DumpTypes(mask_str);
std::string filename = event.GetName();
std::cout << "Child: " << filename << " have change " << mask_str << std::endl;
if (filename == _file){
*fragHasChanged = true;
}
}
}
}
}
}
void init(const std::string& fragFile) {
GLfloat cx, cy;
bcm_host_init();
// Clear application state
memset( state, 0, sizeof( *state ) );
// Start OGLES
init_ogl(state);
// Build shader;
//
std::string fragSource;
if(!loadFromPath(fragFile, &fragSource)) {
return;
}
state->shader.build(fragSource,vertSource);
// Make Quad
//
static const GLfloat vertex_data[] = {
-1.0,-1.0,1.0,1.0,
1.0,-1.0,1.0,1.0,
1.0,1.0,1.0,1.0,
-1.0,1.0,1.0,1.0
};
GLint posAttribut = state->shader.getAttribLocation("a_position");
glClearColor ( 0.0, 1.0, 1.0, 1.0 );
glGenBuffers(1, &state->buf);
// Prepare viewport
glViewport ( 0, 0, state->screen_width, state->screen_height );
// Upload vertex data to a buffer
glBindBuffer(GL_ARRAY_BUFFER, state->buf);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertex_data),
vertex_data, GL_STATIC_DRAW);
glVertexAttribPointer(posAttribut, 4, GL_FLOAT, 0, 16, 0);
glEnableVertexAttribArray(posAttribut);
}
//==============================================================================
int main(int argc, char **argv){
fragFile = std::string(argv[1]);
int shmId = shmget(IPC_PRIVATE, sizeof(bool), 0666);
pid_t pid = fork();
fragHasChanged = (bool *) shmat(shmId, NULL, 0);
switch(pid) {
case -1: //error
break;
case 0: // child
{
*fragHasChanged = false;
watchThread(fragFile);
}
break;
default:
{
init(fragFile);
drawThread();
kill(pid, SIGKILL);
}
break;
}
shmctl(shmId, IPC_RMID, NULL);
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "macro.hpp"
#include <utility>
namespace bh
{
namespace impl
{
template<typename ... T> class ScopeFuncImpl;
template<> class ScopeFuncImpl<> {};
template<typename First_T, typename ... Rest_T>
class ScopeFuncImpl<First_T, Rest_T...>
: private ScopeFuncImpl<Rest_T...>
{
private:
using BaseType = ScopeFuncImpl<Rest_T...>;
First_T m_Functor;
public:
ScopeFuncImpl(First_T && p_Functor, Rest_T && ... p_Functors)
: BaseType(std::forward<Rest_T>(p_Functors)...), m_Functor(p_Functor) {}
~ScopeFuncImpl(void) { m_Functor(); }
}; // ScopeFuncImpl
} // impl ns
/**
* \class ScopeFunc
* A RAII class that takes an arbitrary number of functor objects, executing the objects' operator()
* in the ScopeFunc object's destructor when the ScopeFunc object is destroyed.
*/
template<typename ... Functor_T>
class ScopeFunc
: private impl::ScopeFuncImpl<Functor_T...>
{
private:
using BaseType = impl::ScopeFuncImpl<Functor_T...>;
public:
ScopeFunc(Functor_T && ... p_Functors)
: BaseType(std::forward<Functor_T>(p_Functors)...) {}
};
template<typename ... Functor_T>
ScopeFunc<Functor_T...> makeScopeFunc(Functor_T && ... p_rrFunctor)
{
return ScopeFunc<Functor_T...>(std::forward<Functor_T>(p_rrFunctor) ... );
}
} // BH ns
/**
* Create a named ScopeFunc object.
*/
#define MakeNamedScopeFunc(...) auto MAKE_UNIQUE_NAME() = bh::makeScopeFunc(__VA_ARGS__);
/**
* Create a named ScopeFunc object.
* \see MakeNamedScopeFunc.
*/
#define BH_MakeNamedScopeFunc(...) MakeNamedScopeFunc(__VA_ARGS__);
<commit_msg>Update ScopeFunc.hpp<commit_after>#pragma once
#include "macro.hpp"
#include <utility>
namespace bh
{
namespace impl
{
/** @brief ScopeFunc implementation impl. */
template<typename ... T> class ScopeFuncImpl;
/** @brief ScopeFunc implementation impl. */
template<> class ScopeFuncImpl<> {};
/** @brief ScopeFunc implementation impl. */
template<typename First_T, typename ... Rest_T>
class ScopeFuncImpl<First_T, Rest_T...>
: private ScopeFuncImpl<Rest_T...>
{
private:
using BaseType = ScopeFuncImpl<Rest_T...>;
First_T m_Functor;
public:
ScopeFuncImpl(First_T && p_Functor, Rest_T && ... p_Functors)
: BaseType(std::forward<Rest_T>(p_Functors)...), m_Functor(p_Functor) {}
~ScopeFuncImpl(void) { m_Functor(); }
}; // ScopeFuncImpl
} // impl ns
/**
* @class ScopeFunc
* @brief A RAII class that takes a single functor object, executing the object's operator()
* in the ScopeFunc object's destructor when the ScopeFunc object is destroyed.
*/
template<typename ... Functor_T>
class ScopeFunc
: private impl::ScopeFuncImpl<Functor_T...>
{
private:
using BaseType = impl::ScopeFuncImpl<Functor_T...>;
public:
ScopeFunc(Functor_T && ... p_Functors)
: BaseType(std::forward<Functor_T>(p_Functors)...) {}
};
/**
* Utility function for creating a ScopeFunc object with an arbitrary amount of functors.
*
* Sample usuage:
* @code
* auto scope_func = makeScopeFunc([](void){ std::cout << "end of scope" << std::endl; });
* @endcode
* @return a ScopeFunc object.
*/
template<typename ... Functor_T>
ScopeFunc<Functor_T...> makeScopeFunc(Functor_T && ... p_rrFunctor)
{
return ScopeFunc<Functor_T...>(std::forward<Functor_T>(p_rrFunctor) ... );
}
} // bh ns
/**
* Utility macro function for creating a ScopeFunc object with an arbitrary amount of functors.
* This function takes care of creating the ScopeFunc object for you so you don't declare one.
* makeScopeFunc is used internally.
*
* Sample usuage:
* @code
* MakeScopeFunc([](void){ std::cout << "end of scope" << std::endl; });
* @endcode
* @return a ScopeFunc object.
*/
#define MakeScopeFunc(...) auto MAKE_UNIQUE_NAME() = bh::makeScopeFunc(__VA_ARGS__);
#define BH_MakeScopeFunc(...) auto BH_MAKE_UNIQUE_NAME() = bh::makeScopeFunc(__VA_ARGS__);
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <string.h>
#include "../include/Suffix.h"
#include "../include/Constants.h"
#include "../include/Functions.h"
using std::cout;
using std::cin;
using std::cerr;
using std::setw;
using std::flush;
using std::endl;
int main() {
cout << "Enter sample string: " << flush;
cin.getline(T, MAX_LENGTH - 1);
N = (int) (strlen(T) - 1);
Suffix active(0, 0, -1);
for (int i = 0; i <= N; i++) {
AddPrefix(active, i);
}
dump_edges(N);
cout << "Would you like to validate the tree?" << flush;
std::string s;
getline(cin, s);
if (s.size() > 0 && s[0] == 'Y' || s[0] == 'y') {
validate();
}
return 1;
}<commit_msg>Fixed main program namespaces.<commit_after>#include <iostream>
#include <iomanip>
#include <string.h>
#include "../include/Suffix.h"
#include "../include/Constants.h"
#include "../include/Functions.h"
using std::cout;
using std::cin;
using std::flush;
int main() {
cout << "Enter sample string: " << flush;
cin.getline(T, MAX_LENGTH - 1);
N = (int) (strlen(T) - 1);
Suffix active(0, 0, -1);
for (int i = 0; i <= N; i++) {
AddPrefix(active, i);
}
dump_edges(N);
cout << "Would you like to validate the tree?" << flush;
std::string s;
getline(cin, s);
if (s.size() > 0 && s[0] == 'Y' || s[0] == 'y') {
validate();
}
return 1;
}<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <string>
#include "args.hpp"
#include "code.hpp"
#include "error.hpp"
#include "parser.hpp"
#ifndef VERSION
#error No version was defined during the compilation process
#endif
int main(int argc, char **argv)
{
// @TODO: Make it possible through a flag to one day be able to generate a binary file.
if (argc == 1) {
// @TODO Print out proper usage information
std::cerr << Error() << "Invalid number of arguments" << std::endl;
return 1;
} else {
// Before anything, check if this is a version invocation
// @TODO Also add license when there is a license
if (std::string(argv[1]) == "version") {
std::cout << "DTVM version " << VERSION << "\n" <<
"by Victhor S. Sartório" << std::endl;
return 0;
}
// Parse possible flags
// @TODO Pass over the handling of flags to the `args` translation unit
for (int i = 3; i < argc; i++) {
std::string arg(argv[i]);
if (arg == "-no-ansi-color-codes" || arg == "-no-acc")
dtvm_args::no_ansi_color_codes = true;
else if (arg == "-parse-and-print")
dtvm_args::parse_and_print = true;
else
std::cout << Warn() << "Unknown option '" << argv[i] << "'" << std::endl;
}
// Attempt to open file
std::string file_path(argv[2]);
std::ifstream file(file_path);
if (!file.is_open()) {
std::cerr << Error() << "Could not open file '" << file_path << "'" << std::endl;
return 1;
}
// Parse code
auto code = parse(file, file_path);
if (code.curr_index == 0) {
std::cerr << Error() << "Got invalid code from parser" << std::endl;
return 1;
}
// If the program was called with -parse-and-print, just pretty print the parsed bytecode.
if (dtvm_args::parse_and_print) {
code.display();
return 0;
}
// Run the code in the VM.
std::cout << Error() << "The VM is not yet implemented" << std::endl;
}
return 0;
}
<commit_msg>Fixed bug where you'd still need the 'c' in invocation<commit_after>#include <fstream>
#include <iostream>
#include <string>
#include "args.hpp"
#include "code.hpp"
#include "error.hpp"
#include "parser.hpp"
#ifndef VERSION
#error No version was defined during the compilation process
#endif
int main(int argc, char **argv)
{
// @TODO: Make it possible through a flag to one day be able to generate a binary file.
if (argc == 1) {
// @TODO Print out proper usage information
std::cerr << Error() << "Invalid number of arguments" << std::endl;
return 1;
} else {
// Before anything, check if this is a version invocation
// @TODO Also add license when there is a license
if (std::string(argv[1]) == "version") {
std::cout << "DTVM version " << VERSION << "\n" <<
"by Victhor S. Sartório" << std::endl;
return 0;
}
// Parse possible flags
// @TODO Pass over the handling of flags to the `args` translation unit
for (int i = 2; i < argc; i++) {
std::string arg(argv[i]);
if (arg == "-no-ansi-color-codes" || arg == "-no-acc")
dtvm_args::no_ansi_color_codes = true;
else if (arg == "-parse-and-print")
dtvm_args::parse_and_print = true;
else
std::cout << Warn() << "Unknown option '" << argv[i] << "'" << std::endl;
}
// Attempt to open file
std::string file_path(argv[1]);
std::ifstream file(file_path);
if (!file.is_open()) {
std::cerr << Error() << "Could not open file '" << file_path << "'" << std::endl;
return 1;
}
// Parse code
auto code = parse(file, file_path);
if (code.curr_index == 0) {
std::cerr << Error() << "Got invalid code from parser" << std::endl;
return 1;
}
// If the program was called with -parse-and-print, just pretty print the parsed bytecode.
if (dtvm_args::parse_and_print) {
code.display();
return 0;
}
// Run the code in the VM.
std::cout << Error() << "The VM is not yet implemented" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************
main.cpp
-------------------
A brewing recipe calculator
-------------------
Copyright (c) 1999-2007 David Johnson <david@usermode.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
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 <cstdlib>
#include <QApplication>
#include <QLibraryInfo>
#include <QLocale>
#include <QMainWindow>
#include <QStringList>
#include <QTextStream>
#include <QTranslator>
#if defined(Q_WS_MACX)
extern void qt_mac_set_menubar_icons(bool enable);
#endif
#include "qbrew.h"
#include "resource.h"
using namespace std;
using namespace Resource;
//////////////////////////////////////////////////////////////////////////////
// doversion()
// -----------
// Print out copyright and version info to stdout
void doversion(QTextStream &stream)
{
stream << PACKAGE << ' ' << VERSION << '\n';
stream << QObject::tr(DESCRIPTION) << '\n';
stream << QObject::tr(COPYRIGHT);
stream << ' ' << AUTHOR;
stream << " <" << AUTHOR_EMAIL << ">";
stream << endl;
}
//////////////////////////////////////////////////////////////////////////////
// dohelp()
// --------
// Print out help info to stdout
void dohelp(QTextStream &stream)
{
stream << QObject::tr("Usage: %1 [options] [file]\n").arg(PACKAGE);
stream << QObject::tr(DESCRIPTION) << "\n\n";
// arguments
stream << QObject::tr("Arguments\n");
stream << QObject::tr(" file File to open") << "\n\n";
// general options
stream << QObject::tr("Options\n");
stream << QObject::tr(" --help Print the command line options.\n");
stream << QObject::tr(" --version Print the application version.\n");
stream << endl;
}
//////////////////////////////////////////////////////////////////////////////
// doargs()
// --------
// Process the arguments that QApplication doesn't take care of
QString doargs(QStringList arguments, QTextStream &stream)
{
QString arg;
for (int n=1; n<arguments.count(); ++n) {
arg = arguments.at(n);
if ((arg == "-h") || (arg == "-help") ||
(arg == "--help")) {
dohelp(stream);
exit(0);
} else if ((arg == "-v") || (arg == "-version") ||
(arg == "--version")) {
doversion(stream);
exit(0);
} else if (arg[0] == '-') {
// no other valid options
stream << QObject::tr("Invalid parameter \"%1\"\n") .arg(arg);
dohelp(stream);
exit(1);
} else {
// it must be a filename
return arg;
}
}
return (QObject::tr(DEFAULT_FILE));
}
//////////////////////////////////////////////////////////////////////////////
// main()
// ------
// Entry point of application
int main(int argc, char **argv)
{
Q_INIT_RESOURCE(qbrew);
QApplication app(argc, argv);
#if defined(Q_WS_MACX)
// disable icons on Mac menus (as is customary)
qt_mac_set_menubar_icons(false);
#endif
// load qbrew translations
QString transdir = QBrew::instance()->dataBase() + "translations";
QTranslator translator;
translator.load("qbrew_" + QLocale::system().name(), transdir);
app.installTranslator(&translator);
// load qt translations
QString qttransdir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
QTranslator qttranslator;
qttranslator.load("qt_" + QLocale::system().name(), qttransdir);
app.installTranslator(&qttranslator);
// check for additional command line arguments
QTextStream stream(stdout);
QString filename = doargs(app.arguments(), stream);
QBrew* mainwindow = QBrew::instance();
mainwindow->initialize(filename);
mainwindow->show();
app.installEventFilter(mainwindow); // for handling file open events
return app.exec();
}
<commit_msg>check loading of translations<commit_after>/***************************************************************************
main.cpp
-------------------
A brewing recipe calculator
-------------------
Copyright (c) 1999-2007 David Johnson <david@usermode.org>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
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 <cstdlib>
#include <QApplication>
#include <QLibraryInfo>
#include <QLocale>
#include <QMainWindow>
#include <QStringList>
#include <QTextStream>
#include <QTranslator>
#if defined(Q_WS_MACX)
extern void qt_mac_set_menubar_icons(bool enable);
#endif
#include "qbrew.h"
#include "resource.h"
using namespace std;
using namespace Resource;
//////////////////////////////////////////////////////////////////////////////
// doversion()
// -----------
// Print out copyright and version info to stdout
void doversion(QTextStream &stream)
{
stream << PACKAGE << ' ' << VERSION << '\n';
stream << QObject::tr(DESCRIPTION) << '\n';
stream << QObject::tr(COPYRIGHT);
stream << ' ' << AUTHOR;
stream << " <" << AUTHOR_EMAIL << ">";
stream << endl;
}
//////////////////////////////////////////////////////////////////////////////
// dohelp()
// --------
// Print out help info to stdout
void dohelp(QTextStream &stream)
{
stream << QObject::tr("Usage: %1 [options] [file]\n").arg(PACKAGE);
stream << QObject::tr(DESCRIPTION) << "\n\n";
// arguments
stream << QObject::tr("Arguments\n");
stream << QObject::tr(" file File to open") << "\n\n";
// general options
stream << QObject::tr("Options\n");
stream << QObject::tr(" --help Print the command line options.\n");
stream << QObject::tr(" --version Print the application version.\n");
stream << endl;
}
//////////////////////////////////////////////////////////////////////////////
// doargs()
// --------
// Process the arguments that QApplication doesn't take care of
QString doargs(QStringList arguments, QTextStream &stream)
{
QString arg;
for (int n=1; n<arguments.count(); ++n) {
arg = arguments.at(n);
if ((arg == "-h") || (arg == "-help") ||
(arg == "--help")) {
dohelp(stream);
exit(0);
} else if ((arg == "-v") || (arg == "-version") ||
(arg == "--version")) {
doversion(stream);
exit(0);
} else if (arg[0] == '-') {
// no other valid options
stream << QObject::tr("Invalid parameter \"%1\"\n") .arg(arg);
dohelp(stream);
exit(1);
} else {
// it must be a filename
return arg;
}
}
return (QObject::tr(DEFAULT_FILE));
}
//////////////////////////////////////////////////////////////////////////////
// main()
// ------
// Entry point of application
int main(int argc, char **argv)
{
Q_INIT_RESOURCE(qbrew);
QApplication app(argc, argv);
#if defined(Q_WS_MACX)
// disable icons on Mac menus (as is customary)
qt_mac_set_menubar_icons(false);
#endif
// load qbrew translations
QString transdir = QBrew::instance()->dataBase() + "translations";
QTranslator translator;
if (translator.load("qbrew_" + QLocale::system().name(), transdir)) {
app.installTranslator(&translator);
}
// load qt translations
QString qttransdir = QLibraryInfo::location(QLibraryInfo::TranslationsPath);
QTranslator qttranslator;
if (qttranslator.load("qt_" + QLocale::system().name(), qttransdir)) {
app.installTranslator(&qttranslator);
}
// check for additional command line arguments
QTextStream stream(stdout);
QString filename = doargs(app.arguments(), stream);
QBrew* mainwindow = QBrew::instance();
mainwindow->initialize(filename);
mainwindow->show();
app.installEventFilter(mainwindow); // for handling file open events
return app.exec();
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>
* Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>
* Copyright (c) 2005 Ryan Nickell <p0z3r@earthlink.net>
*
* This file is part of SuperKaramba.
*
* SuperKaramba is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* SuperKaramba 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SuperKaramba; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
****************************************************************************/
#include <karambaapp.h>
#include <qobject.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kconfig.h>
#include <kmainwindow.h>
#include <qfileinfo.h>
#include <qstringlist.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kdeversion.h>
#include "karamba.h"
#include "karambasessionmanaged.h"
#include "karambainterface.h"
#include "karamba_python.h"
static const char *description =
I18N_NOOP("A KDE Eye-candy Application");
static const char *version = "0.38";
static KCmdLineOptions options[] =
{
// { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
// { "!nosystray", I18N_NOOP("Disable systray icon"), 0 },
{ "+file", I18N_NOOP("A required argument 'file'"), 0 },
{ 0, 0, 0 }
};
// This is for redirecting all qWarning, qDebug,... messages to file.
// Usefull when testing session management issues etc.
// #define KARAMBA_LOG 1
#ifdef KARAMBA_LOG
void karambaMessageOutput(QtMsgType type, const char *msg)
{
FILE* fp = fopen("/tmp/karamba.log", "a");
if(fp)
{
pid_t pid = getpid();
switch ( type )
{
case QtDebugMsg:
fprintf( fp, "Debug (%d): %s\n", pid, msg );
break;
case QtWarningMsg:
if (strncmp(msg, "X Error", 7) != 0)
fprintf( fp, "Warning (%d): %s\n", pid, msg );
break;
case QtFatalMsg:
fprintf( fp, "Fatal (%d): %s\n", pid, msg );
abort(); // deliberately core dump
}
fclose(fp);
}
}
#endif
int main(int argc, char **argv)
{
#ifdef KARAMBA_LOG
qInstallMsgHandler(karambaMessageOutput);
#endif
KAboutData about("superkaramba", I18N_NOOP("SuperKaramba"),
version, description,
KAboutData::License_GPL,
"(c) 2003-2006 The SuperKaramba developers");
about.addAuthor("Adam Geitgey", 0, "adam@rootnode.org");
about.addAuthor("Hans Karlsson", 0, "karlsson.h@home.se");
about.addAuthor("Ryan Nickell", 0, "p0z3r@earthlink.net");
about.addAuthor("Petri Damstén", 0, "petri.damsten@iki.fi");
about.addAuthor("Alexander Wiedenbruch", 0, "mail@wiedenbruch.de");
about.addAuthor("Luke Kenneth Casson Leighton", 0, "lkcl@lkcl.net");
KCmdLineArgs::init(argc, argv, &about);
KCmdLineArgs::addCmdLineOptions(options);
KSessionManaged ksm;
//karamba *mainWin = 0;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
QStringList lst;
int ret = 0;
// Create ~/.superkaramba if necessary
KarambaApplication::checkSuperKarambaDir();
KarambaApplication::lockKaramba();
KarambaApplication app;
QString mainAppId = app.getMainKaramba();
if(!mainAppId.isEmpty())
{
app.initDcopStub(mainAppId.ascii());
}
else
{
//Set up systray icon
app.setUpSysTray(&about);
app.initDcopStub();
}
KarambaApplication::unlockKaramba();
app.connect(qApp,SIGNAL(lastWindowClosed()),qApp,SLOT(quit()));
// Try to restore a previous session if applicable.
app.checkPreviousSession(app, lst);
if( (lst.size() == 0) && !app.isRestored() )
{
//Not a saved session - check for themes given on command line
app.checkCommandLine(args, lst);
if(lst.size() == 0)
{
//No themes given on command line and no saved session.
//Show welcome dialog.
app.globalShowThemeDialog();
}
}
args->clear();
KarambaPython::initPython();
//qDebug("startThemes");
if(app.startThemes(lst) || mainAppId.isEmpty())
ret = app.exec();
KarambaPython::shutdownPython();
return ret;
}
<commit_msg>Bump up the version to 0.39 before the 3.5.2 tagging occurs.<commit_after>/*
* Copyright (C) 2003 Hans Karlsson <karlsson.h@home.se>
* Copyright (C) 2003-2004 Adam Geitgey <adam@rootnode.org>
* Copyright (c) 2005 Ryan Nickell <p0z3r@earthlink.net>
*
* This file is part of SuperKaramba.
*
* SuperKaramba is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* SuperKaramba 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with SuperKaramba; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
****************************************************************************/
#include <karambaapp.h>
#include <qobject.h>
#include <kaboutdata.h>
#include <kcmdlineargs.h>
#include <klocale.h>
#include <kconfig.h>
#include <kmainwindow.h>
#include <qfileinfo.h>
#include <qstringlist.h>
#include <kconfig.h>
#include <kstandarddirs.h>
#include <kdeversion.h>
#include "karamba.h"
#include "karambasessionmanaged.h"
#include "karambainterface.h"
#include "karamba_python.h"
static const char *description =
I18N_NOOP("A KDE Eye-candy Application");
static const char *version = "0.39";
static KCmdLineOptions options[] =
{
// { "+[URL]", I18N_NOOP( "Document to open" ), 0 },
// { "!nosystray", I18N_NOOP("Disable systray icon"), 0 },
{ "+file", I18N_NOOP("A required argument 'file'"), 0 },
{ 0, 0, 0 }
};
// This is for redirecting all qWarning, qDebug,... messages to file.
// Usefull when testing session management issues etc.
// #define KARAMBA_LOG 1
#ifdef KARAMBA_LOG
void karambaMessageOutput(QtMsgType type, const char *msg)
{
FILE* fp = fopen("/tmp/karamba.log", "a");
if(fp)
{
pid_t pid = getpid();
switch ( type )
{
case QtDebugMsg:
fprintf( fp, "Debug (%d): %s\n", pid, msg );
break;
case QtWarningMsg:
if (strncmp(msg, "X Error", 7) != 0)
fprintf( fp, "Warning (%d): %s\n", pid, msg );
break;
case QtFatalMsg:
fprintf( fp, "Fatal (%d): %s\n", pid, msg );
abort(); // deliberately core dump
}
fclose(fp);
}
}
#endif
int main(int argc, char **argv)
{
#ifdef KARAMBA_LOG
qInstallMsgHandler(karambaMessageOutput);
#endif
KAboutData about("superkaramba", I18N_NOOP("SuperKaramba"),
version, description,
KAboutData::License_GPL,
"(c) 2003-2006 The SuperKaramba developers");
about.addAuthor("Adam Geitgey", 0, "adam@rootnode.org");
about.addAuthor("Hans Karlsson", 0, "karlsson.h@home.se");
about.addAuthor("Ryan Nickell", 0, "p0z3r@earthlink.net");
about.addAuthor("Petri Damstén", 0, "petri.damsten@iki.fi");
about.addAuthor("Alexander Wiedenbruch", 0, "mail@wiedenbruch.de");
about.addAuthor("Luke Kenneth Casson Leighton", 0, "lkcl@lkcl.net");
KCmdLineArgs::init(argc, argv, &about);
KCmdLineArgs::addCmdLineOptions(options);
KSessionManaged ksm;
//karamba *mainWin = 0;
KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
QStringList lst;
int ret = 0;
// Create ~/.superkaramba if necessary
KarambaApplication::checkSuperKarambaDir();
KarambaApplication::lockKaramba();
KarambaApplication app;
QString mainAppId = app.getMainKaramba();
if(!mainAppId.isEmpty())
{
app.initDcopStub(mainAppId.ascii());
}
else
{
//Set up systray icon
app.setUpSysTray(&about);
app.initDcopStub();
}
KarambaApplication::unlockKaramba();
app.connect(qApp,SIGNAL(lastWindowClosed()),qApp,SLOT(quit()));
// Try to restore a previous session if applicable.
app.checkPreviousSession(app, lst);
if( (lst.size() == 0) && !app.isRestored() )
{
//Not a saved session - check for themes given on command line
app.checkCommandLine(args, lst);
if(lst.size() == 0)
{
//No themes given on command line and no saved session.
//Show welcome dialog.
app.globalShowThemeDialog();
}
}
args->clear();
KarambaPython::initPython();
//qDebug("startThemes");
if(app.startThemes(lst) || mainAppId.isEmpty())
ret = app.exec();
KarambaPython::shutdownPython();
return ret;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <cstdlib>
#include <signal.h>
#include <unistd.h>
#include "logger.hpp"
#include "server.hpp"
#include "parser.hpp"
#include "config.hpp"
#include "requestHandler.hpp"
void handler(int sig)
{
RequestHandler::stop();
exit(0);
}
int main(int argc, char **argv)
{
std::ios_base::sync_with_stdio(false);
signal(SIGINT, handler);
signal(SIGTERM, handler);
std::string configFile = "liquid.conf";
unsigned int logLevel = Logger::Level::INFO;
int opt;
while ((opt = getopt(argc, argv, "c:v:")) != -1) {
switch (opt) {
case 'c':
configFile = optarg;
break;
case 'v':
try {
logLevel = std::stoul(optarg);
if (logLevel <= Logger::Level::ERROR)
break;
}
catch (const std::exception& e) {}
default:
std::cerr << "Usage: " << argv0 << " [-c configFile] [-v <0,1,2>]\n";
return 1;
}
}
try {
LOG_INIT(static_cast<Logger::Level>(logLevel));
Config::load("liquid.conf");
int port = Config::getInt("port");
Server server(port);
Parser::init();
if (Config::get("type") == "private")
RequestHandler::init();
LOG_INFO("Starting " + Config::get("type") + " server on port " + std::to_string(port));
server.run();
}
catch (const std::exception& e) {
LOG_ERROR(e.what());
}
return 0;
}
<commit_msg>fix build error<commit_after>#include <iostream>
#include <cstdlib>
#include <signal.h>
#include <unistd.h>
#include "logger.hpp"
#include "server.hpp"
#include "parser.hpp"
#include "config.hpp"
#include "requestHandler.hpp"
void handler(int sig)
{
RequestHandler::stop();
exit(0);
}
int main(int argc, char **argv)
{
std::ios_base::sync_with_stdio(false);
signal(SIGINT, handler);
signal(SIGTERM, handler);
std::string configFile = "liquid.conf";
unsigned int logLevel = Logger::Level::INFO;
int opt;
while ((opt = getopt(argc, argv, "c:v:")) != -1) {
switch (opt) {
case 'c':
configFile = optarg;
break;
case 'v':
try {
logLevel = std::stoul(optarg);
if (logLevel <= Logger::Level::ERROR)
break;
}
catch (const std::exception& e) {}
default:
std::cerr << "Usage: " << argv[0] << " [-c configFile] [-v <0,1,2>]\n";
return 1;
}
}
try {
LOG_INIT(static_cast<Logger::Level>(logLevel));
Config::load("liquid.conf");
int port = Config::getInt("port");
Server server(port);
Parser::init();
if (Config::get("type") == "private")
RequestHandler::init();
LOG_INFO("Starting " + Config::get("type") + " server on port " + std::to_string(port));
server.run();
}
catch (const std::exception& e) {
LOG_ERROR(e.what());
}
return 0;
}
<|endoftext|> |
<commit_before>#include <SPI.h>
#include "RF24.h"
#include <ArduinoHardware.h>
/* Definições */
#define NUMBER_OF_ROBOTS 5
/* Declaração das funções */
void radioSetup();
void enviaMensagem();
void atualizaVelocidades();
/* Pinos para o rádio */
int CE = 3;
int CS = 2;
/* Objeto que gerencia o rádio */
RF24 radio(CE,CS);
/* Endereços */
uint64_t txPipeAddress = 0xABCDABCD71L;
uint64_t rxPipeAddress = 0x744d52687CL;
/* Estrutura para a mensagem a ser transmitida */
struct Velocidade{
int16_t motorA[5];
int16_t motorB[5];
};
/* Estrutura para a mensagem a ser recebida do USB */
struct VelocidadeSerial {
Velocidade data;
int16_t checksum;
};
/* Mensagem a ser transmitida */
Velocidade velocidades;
/* Contagem de erros de transmissão via USB detectados */
uint32_t erros = 0;
uint32_t lastOK = 0;
/* Loop de setup */
void setup(void) {
Serial.begin(115200);
//radioSetup();
pinMode(LED_BUILTIN, OUTPUT);
}
/* Loop que é executado continuamente */
void loop(){
atualizaVelocidades();
//enviaMensagem();
//recebeDadosDebug();
//enviaDebugSerial();
if(millis()-lastOK < 5){
digitalWrite(LED_BUILTIN, HIGH);
}
else{
digitalWrite(LED_BUILTIN, LOW);
}
}
/* Envia a mensagem pelo rádio */
void enviaMensagem(){
// Garante que o rádio não está escutando
radio.stopListening();
// Permite chamadas de write sem ACK
radio.enableDynamicAck();
// Abre um pipe para escrita
radio.openWritingPipe(txPipeAddress);
// Envia a mensagem
radio.write(&velocidades,sizeof(velocidades), 1);
}
/* Configura o rádio */
void radioSetup(){
// inicializa radio
radio.begin();
// muda para um canal de frequencia diferente de 2.4Ghz
radio.setChannel(108);
// usa potencia maxima
radio.setPALevel(RF24_PA_MAX);
// usa velocidade maxima
radio.setDataRate(RF24_2MBPS);
// escuta pelo pipe1
radio.openReadingPipe(1,rxPipeAddress);
// ativa payloads dinamicos(pacote tamamhos diferentes do padrao)
radio.enableDynamicPayloads();
// ajusta o tamanho dos pacotes ao tamanho da mensagem
radio.setPayloadSize(sizeof(velocidades));
// Start listening
radio.startListening();
}
/* Lê do serial novas velocidades */
void atualizaVelocidades(){
int initCounter = 0;
while(Serial.available()){
/* Lê um caracter da mensagem */
char character = Serial.read();
/* Incrementa o contador se for 'B' */
if(character == 'B') initCounter++;
/* Se os três primeiros caracteres são 'B' então de fato é o início da mensagem */
if(initCounter >= 3){
VelocidadeSerial receber;
/* Lê a mensagem até o caracter de terminação e a decodifica */
Serial.readBytes((char*)(&receber), (size_t)sizeof(VelocidadeSerial));
/* Faz o checksum */
int16_t checksum = 0;
for(int i=0 ; i<5 ; i++){
checksum += receber.data.motorA[i] + receber.data.motorB[i];
}
/* Verifica o checksum */
if(checksum == receber.checksum){
/* Copia para o buffer global de velocidades */
velocidades = receber.data;
/* Reporta que deu certo */
Serial.printf("%d\t%d\t%d\n", checksum, velocidades.motorA[0], velocidades.motorB[0]);
lastOK = millis();
}
else {
/* Devolve o checksum calculado se deu errado */
Serial.printf("%d\t%d\t%d\n", checksum, velocidades.motorA[0], velocidades.motorB[0]);
}
/* Zera o contador */
initCounter = 0;
}
}
}
<commit_msg>Versao testada com o radio no ESP32 e os pinos 12 para CE e 13 para CS alem dos pinos de SCK (18), MOSI (23) e MISO (19)<commit_after>#include <SPI.h>
#include "RF24.h"
#include <ArduinoHardware.h>
/* Definições */
#define NUMBER_OF_ROBOTS 5
/* Declaração das funções */
void radioSetup();
void enviaMensagem();
void atualizaVelocidades();
/* Pinos para o rádio */
int CE = 12;
int CS = 13;
/* Objeto que gerencia o rádio */
RF24 radio(CE,CS);
/* Endereços */
uint64_t txPipeAddress = 0xABCDABCD71L;
uint64_t rxPipeAddress = 0x744d52687CL;
/* Estrutura para a mensagem a ser transmitida */
struct Velocidade{
int16_t motorA[5];
int16_t motorB[5];
};
/* Estrutura para a mensagem a ser recebida do USB */
struct VelocidadeSerial {
Velocidade data;
int16_t checksum;
};
/* Mensagem a ser transmitida */
Velocidade velocidades;
/* Contagem de erros de transmissão via USB detectados */
uint32_t erros = 0;
uint32_t lastOK = 0;
/* Loop de setup */
void setup(void) {
Serial.begin(115200);
while(!Serial);
radioSetup();
pinMode(LED_BUILTIN, OUTPUT);
}
/* Loop que é executado continuamente */
void loop(){
atualizaVelocidades();
enviaMensagem();
//recebeDadosDebug();
//enviaDebugSerial();
if(millis()-lastOK < 5){
digitalWrite(LED_BUILTIN, HIGH);
}
else{
digitalWrite(LED_BUILTIN, LOW);
}
//delay(5);
/*digitalWrite(LED_BUILTIN, HIGH);
sleep(1);
digitalWrite(LED_BUILTIN, LOW);
sleep(1);*/
}
/* Envia a mensagem pelo rádio */
void enviaMensagem(){
// Garante que o rádio não está escutando
//radio.stopListening();
// Permite chamadas de write sem ACK
radio.enableDynamicAck();
// Abre um pipe para escrita
radio.openWritingPipe(txPipeAddress);
// Envia a mensagem
radio.write(&velocidades,sizeof(velocidades), 1);
}
/* Configura o rádio */
void radioSetup(){
// inicializa radio
radio.begin();
// muda para um canal de frequencia diferente de 2.4Ghz
radio.setChannel(108);
// usa potencia maxima
radio.setPALevel(RF24_PA_MAX);
// usa velocidade maxima
radio.setDataRate(RF24_2MBPS);
// escuta pelo pipe1
radio.openReadingPipe(1,rxPipeAddress);
// ativa payloads dinamicos(pacote tamamhos diferentes do padrao)
radio.enableDynamicPayloads();
// ajusta o tamanho dos pacotes ao tamanho da mensagem
radio.setPayloadSize(sizeof(velocidades));
// Start listening
radio.startListening();
radio.stopListening();
}
/* Lê do serial novas velocidades */
void atualizaVelocidades(){
int initCounter = 0;
while(Serial.available()){
/* Lê um caracter da mensagem */
char character = Serial.read();
/* Incrementa o contador se for 'B' */
if(character == 'B') initCounter++;
/* Se os três primeiros caracteres são 'B' então de fato é o início da mensagem */
if(initCounter >= 3){
VelocidadeSerial receber;
/* Lê a mensagem até o caracter de terminação e a decodifica */
Serial.readBytes((char*)(&receber), (size_t)sizeof(VelocidadeSerial));
/* Faz o checksum */
int16_t checksum = 0;
for(int i=0 ; i<5 ; i++){
checksum += receber.data.motorA[i] + receber.data.motorB[i];
}
/* Verifica o checksum */
if(checksum == receber.checksum){
/* Copia para o buffer global de velocidades */
velocidades = receber.data;
/* Reporta que deu certo */
Serial.printf("%d\t%d\t%d\n", checksum, velocidades.motorA[0], velocidades.motorB[0]);
lastOK = millis();
}
else {
/* Devolve o checksum calculado se deu errado */
Serial.printf("%d\t%d\t%d\n", checksum, velocidades.motorA[0], velocidades.motorB[0]);
}
/* Zera o contador */
initCounter = 0;
}
}
}
<|endoftext|> |
<commit_before>#include <stdexcept>
#include <limits>
#include <algorithm>
#include <array>
#include <memory>
#include <iomanip>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/
#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif
#if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H)
#include "win_error_string.hpp"
#endif
const std::string version("0.1.0");
const std::string listing("http://nwn.efupw.com/rootdir/index.dat");
const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/");
const std::string file_checksum(const std::string &path);
std::vector<std::string> &split(const std::string &s, char delim,
std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim)
{
std::vector<std::string> elems;
return split(s, delim, elems);
}
void make_dir(const std::string &path)
{
#ifdef _WIN32
unsigned file_start = path.find_last_of("/\\");
if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr))
{
WinErrorString wes;
if (wes.code() != ERROR_ALREADY_EXISTS)
{
throw std::ios_base::failure("sdf" + wes.str());
}
}
#else
auto elems = split(path, '/');
std::string descend;
for (size_t i = 0, k = elems.size() - 1; i < k; ++i)
{
const std::string &s(elems[i]);
if (s.size() && s != ".")
{
descend.append((i > 0 ? "/" : "") + s);
auto status = mkdir(descend.c_str(), S_IRWXU);
if (status == -1)
{
std::error_code err(errno, std::generic_category());
if (err != std::errc::file_exists)
{
std::cout << "error making dir: "
<< descend << ": "
<< err.message() << std::endl;
}
}
}
}
#endif
}
// TODO
#ifdef CPP11_ENUM_CLASS
#define ENUM_CLASS enum class
#else
#define ENUM_CLASS enum
#endif
class Target
{
public:
ENUM_CLASS Status {
Nonexistent,
Outdated,
Current
};
explicit Target(const std::string &name, const std::string &checksum):
m_name(name.find_first_of('/') == std::string::npos ? name :
name, name.find_first_of('/') + 1, name.size() - 1),
m_checksum(checksum)
{}
std::string name() const { return m_name; }
const std::string checksum() const { return m_checksum; }
void fetch() const
{
std::cout << "Statting target " << name() << "...";
std::fstream fs(name(), std::ios_base::in);
if (!fs.good())
{
fs.close();
std::cout << " doesn't exist, creating new." << std::endl;
make_dir(name());
fs.open(name(), std::ios_base::out);
if (!fs.good())
{
fs.close();
std::cout << "Failed to create file: " << name() << std::endl;
}
else
{
fs.close();
do_fetch();
return;
}
}
if (fs.good())
{
fs.close();
if (status() == Status::Current)
{
std::cout << " already up to date." << std::endl;
}
else
{
std::cout << " outdated, downloading new." << std::endl;
do_fetch();
}
}
}
Status status() const
{
std::ifstream is(name());
if (!is.good())
{
return Status::Nonexistent;
}
is.close();
auto calcsum(file_checksum(name()));
if (calcsum == checksum())
{
return Status::Current;
}
else
{
return Status::Outdated;
}
}
private:
void do_fetch() const
{
std::ofstream ofs(name(), std::ios::binary);
if (ofs.good())
{
std::string s;
std::string url(patch_dir + name());
CurlEasy curl(url);
curl.write_to(s);
curl.progressbar(true);
curl.perform();
ofs << s;
ofs.close();
std::cout << "Finished downloading " << name() << std::endl;
}
else
{
std::cout << "Couldn't write to " << name() << std::endl;
}
}
std::string m_name;
std::string m_checksum;
};
std::ostream& operator<<(std::ostream &os, const Target &t)
{
return os << "name: " << t.name() << ", checksum: " << t.checksum();
}
const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
auto md = EVP_md5();
const int md_len = MD5_DIGEST_LENGTH;
#else
auto md = EVP_sha1();
const int md_len = SHA_DIGEST_LENGTH;
#endif
std::array<unsigned char, md_len> result;
EVP_MD_CTX *mdctx = nullptr;
std::ifstream is(path, std::ios::binary);
if (!is.good())
{
std::cout << "Couldn't open file " << path
<< " for checksumming." << std::endl;
return std::string();
}
const int length = 8192;
std::array<unsigned char, length> buffer;
auto buf = reinterpret_cast<char *>(buffer.data());
mdctx = EVP_MD_CTX_create();
int status = EVP_DigestInit_ex(mdctx, md, nullptr);
while (status && is)
{
is.read(buf, length);
status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount());
}
status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
EVP_MD_CTX_destroy(mdctx);
std::stringstream calcsum;
calcsum << std::setfill('0');
#ifdef CPP11_FOR_EACH
for (const unsigned char c : result)
#else
std::for_each(std::begin(result), std::end(result),
[&calcsum](const unsigned char c)
#endif
{
calcsum << std::hex << std::setw(2)
<< static_cast<unsigned int>(c);
}
#ifndef CPP11_FOR_EACH
);
#endif
return calcsum.str();
}
namespace Options
{
bool version(const std::string &val)
{
return val == "version";
}
bool update_path(const std::string &val)
{
return val == "update path";
}
};
bool confirm()
{
char c;
do
{
std::cin >> c;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
c = static_cast<char>(tolower(c));
} while (c != 'y' && c != 'n');
return c == 'y';
}
class EfuLauncher
{
public:
// TODO: assignment, copy operator
explicit EfuLauncher(const std::string path,
const std::string update_check):
m_path(path),
m_update_check(update_check),
m_has_update(false)
{}
bool has_update()
{
if (m_has_update)
{
return m_has_update;
}
std::string fetch;
CurlEasy curl(m_update_check.c_str());
curl.write_to(fetch);
//TODO
try
{
curl.perform();
}
catch (CurlEasyException &e)
{
std::cout << e.what() << std::endl;
}
std::vector<std::string> lines(split(fetch, '\n'));
fetch.clear();
for (auto beg = std::begin(lines), end = std::end(lines);
beg != end; ++beg)
{
auto keyvals(split(*beg, '='));
if (keyvals.size() != 2)
{
std::cerr << "Malformed option: " + *beg +
", aborting launcher update check." << std::endl;
return m_has_update = false;
}
if (Options::version(keyvals[0]))
{
const std::string version_test(keyvals[1]);
m_has_update = version_test != version;
}
else if (Options::update_path(keyvals[0]))
{
m_update_path = keyvals[1];
}
}
return m_has_update;
}
bool get_update()
{
if (!m_has_update || m_update_path.empty())
{
return m_has_update = false;
}
return !(m_has_update = false);
}
void stat_targets()
{
std::string fetch;
CurlEasy curl(listing);
curl.write_to(fetch);
curl.perform();
auto lines(split(fetch, '\n'));
std::vector<Target> new_targets, old_targets;
for (auto beg = std::begin(lines), end = std::end(lines);
beg != end; ++beg)
{
auto data(split(*beg, '@'));
Target t(data[0], data[data.size() - 1]);
auto status = t.status();
// TODO
#ifdef CPP11_ENUM_CLASS
if (status == Target::Status::Nonexistent)
#else
if (status == Target::Nonexistent)
#endif
{
new_targets.push_back(std::move(t));
}
// TODO
#ifdef CPP11_ENUM_CLASS
else if (status == Target::Status::Outdated)
#else
else if (status == Target::Outdated)
#endif
{
old_targets.push_back(std::move(t));
}
}
if (new_targets.size())
{
std::cout << "New targets: " << new_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
for (auto &t : new_targets)
#else
std::for_each(new_targets.cbegin(), new_targets.cend(),
[](const Target &t)
#endif
{
std::cout << "- " << t.name() << std::endl;
}
#ifndef CPP11_FOR_EACH
);
#endif
}
else
{
std::cout << "No new targets." << std::endl;
}
if (old_targets.size())
{
std::cout << "Outdated targets: " << old_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
for (auto &t : old_targets)
#else
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](const Target &t)
#endif
{
std::cout << "- " << t.name() << std::endl;
}
#ifndef CPP11_FOR_EACH
);
#endif
}
else
{
std::cout << "No targets out of date." << std::endl;
}
#ifndef DEBUG
#ifdef CPP11_FOR_EACH
for (auto &t : new_targets)
#else
std::for_each(new_targets.cbegin(), new_targets.cend(),
[](const Target &t)
#endif
{
t.fetch();
}
#ifndef CPP11_FOR_EACH
);
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](const Target &t)
#else
for (auto &t : old_targets)
#endif
{
t.fetch();
}
#ifndef CPP11_FOR_EACH
);
#endif
#endif
}
private:
const std::string path() const { return m_path; }
const std::string m_path;
const std::string m_update_check;
std::string m_update_path;
bool m_has_update;
};
int main(int argc, char *argv[])
{
CurlGlobalInit curl_global;
EfuLauncher l(argv[0],
"https://raw.github.com/commonquail/efulauncher/"\
"master/versioncheck");
if (l.has_update())
{
std::cout << "A new version of the launcher is available."\
" Would you like to download it (y/n)?" << std::endl;
bool download(confirm());
if (!download)
{
std::cout << "It is strongly recommended to always use"\
" the latest launcher. Would you like to download it (y/n)?"
<< std::endl;
download = confirm();
}
if (download)
{
// Download.
std::cout << "Downloading new launcher..." << std::endl;
if (l.get_update())
{
std::cout << "Done. Please extract and run the new launcher." << std::endl;
}
return 0;
}
}
try
{
l.stat_targets();
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
<commit_msg>Use more readable numbers and rely on constant folding.<commit_after>#include <stdexcept>
#include <limits>
#include <algorithm>
#include <array>
#include <memory>
#include <iomanip>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/
#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif
#if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H)
#include "win_error_string.hpp"
#endif
const std::string version("0.1.0");
const std::string listing("http://nwn.efupw.com/rootdir/index.dat");
const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/");
const std::string file_checksum(const std::string &path);
std::vector<std::string> &split(const std::string &s, char delim,
std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim)
{
std::vector<std::string> elems;
return split(s, delim, elems);
}
void make_dir(const std::string &path)
{
#ifdef _WIN32
unsigned file_start = path.find_last_of("/\\");
if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr))
{
WinErrorString wes;
if (wes.code() != ERROR_ALREADY_EXISTS)
{
throw std::ios_base::failure("sdf" + wes.str());
}
}
#else
auto elems = split(path, '/');
std::string descend;
for (size_t i = 0, k = elems.size() - 1; i < k; ++i)
{
const std::string &s(elems[i]);
if (s.size() && s != ".")
{
descend.append((i > 0 ? "/" : "") + s);
auto status = mkdir(descend.c_str(), S_IRWXU);
if (status == -1)
{
std::error_code err(errno, std::generic_category());
if (err != std::errc::file_exists)
{
std::cout << "error making dir: "
<< descend << ": "
<< err.message() << std::endl;
}
}
}
}
#endif
}
// TODO
#ifdef CPP11_ENUM_CLASS
#define ENUM_CLASS enum class
#else
#define ENUM_CLASS enum
#endif
class Target
{
public:
ENUM_CLASS Status {
Nonexistent,
Outdated,
Current
};
explicit Target(const std::string &name, const std::string &checksum):
m_name(name.find_first_of('/') == std::string::npos ? name :
name, name.find_first_of('/') + 1, name.size() - 1),
m_checksum(checksum)
{}
std::string name() const { return m_name; }
const std::string checksum() const { return m_checksum; }
void fetch() const
{
std::cout << "Statting target " << name() << "...";
std::fstream fs(name(), std::ios_base::in);
if (!fs.good())
{
fs.close();
std::cout << " doesn't exist, creating new." << std::endl;
make_dir(name());
fs.open(name(), std::ios_base::out);
if (!fs.good())
{
fs.close();
std::cout << "Failed to create file: " << name() << std::endl;
}
else
{
fs.close();
do_fetch();
return;
}
}
if (fs.good())
{
fs.close();
if (status() == Status::Current)
{
std::cout << " already up to date." << std::endl;
}
else
{
std::cout << " outdated, downloading new." << std::endl;
do_fetch();
}
}
}
Status status() const
{
std::ifstream is(name());
if (!is.good())
{
return Status::Nonexistent;
}
is.close();
auto calcsum(file_checksum(name()));
if (calcsum == checksum())
{
return Status::Current;
}
else
{
return Status::Outdated;
}
}
private:
void do_fetch() const
{
std::ofstream ofs(name(), std::ios::binary);
if (ofs.good())
{
std::string s;
std::string url(patch_dir + name());
CurlEasy curl(url);
curl.write_to(s);
curl.progressbar(true);
curl.perform();
ofs << s;
ofs.close();
std::cout << "Finished downloading " << name() << std::endl;
}
else
{
std::cout << "Couldn't write to " << name() << std::endl;
}
}
std::string m_name;
std::string m_checksum;
};
std::ostream& operator<<(std::ostream &os, const Target &t)
{
return os << "name: " << t.name() << ", checksum: " << t.checksum();
}
const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
auto md = EVP_md5();
const int md_len = MD5_DIGEST_LENGTH;
#else
auto md = EVP_sha1();
const int md_len = SHA_DIGEST_LENGTH;
#endif
std::array<unsigned char, md_len> result;
EVP_MD_CTX *mdctx = nullptr;
std::ifstream is(path, std::ios::binary);
if (!is.good())
{
std::cout << "Couldn't open file " << path
<< " for checksumming." << std::endl;
return std::string();
}
const int length = 8 * 1024;
std::array<unsigned char, length> buffer;
auto buf = reinterpret_cast<char *>(buffer.data());
mdctx = EVP_MD_CTX_create();
int status = EVP_DigestInit_ex(mdctx, md, nullptr);
while (status && is)
{
is.read(buf, length);
status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount());
}
status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
EVP_MD_CTX_destroy(mdctx);
std::stringstream calcsum;
calcsum << std::setfill('0');
#ifdef CPP11_FOR_EACH
for (const unsigned char c : result)
#else
std::for_each(std::begin(result), std::end(result),
[&calcsum](const unsigned char c)
#endif
{
calcsum << std::hex << std::setw(2)
<< static_cast<unsigned int>(c);
}
#ifndef CPP11_FOR_EACH
);
#endif
return calcsum.str();
}
namespace Options
{
bool version(const std::string &val)
{
return val == "version";
}
bool update_path(const std::string &val)
{
return val == "update path";
}
};
bool confirm()
{
char c;
do
{
std::cin >> c;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
c = static_cast<char>(tolower(c));
} while (c != 'y' && c != 'n');
return c == 'y';
}
class EfuLauncher
{
public:
// TODO: assignment, copy operator
explicit EfuLauncher(const std::string path,
const std::string update_check):
m_path(path),
m_update_check(update_check),
m_has_update(false)
{}
bool has_update()
{
if (m_has_update)
{
return m_has_update;
}
std::string fetch;
CurlEasy curl(m_update_check.c_str());
curl.write_to(fetch);
//TODO
try
{
curl.perform();
}
catch (CurlEasyException &e)
{
std::cout << e.what() << std::endl;
}
std::vector<std::string> lines(split(fetch, '\n'));
fetch.clear();
for (auto beg = std::begin(lines), end = std::end(lines);
beg != end; ++beg)
{
auto keyvals(split(*beg, '='));
if (keyvals.size() != 2)
{
std::cerr << "Malformed option: " + *beg +
", aborting launcher update check." << std::endl;
return m_has_update = false;
}
if (Options::version(keyvals[0]))
{
const std::string version_test(keyvals[1]);
m_has_update = version_test != version;
}
else if (Options::update_path(keyvals[0]))
{
m_update_path = keyvals[1];
}
}
return m_has_update;
}
bool get_update()
{
if (!m_has_update || m_update_path.empty())
{
return m_has_update = false;
}
return !(m_has_update = false);
}
void stat_targets()
{
std::string fetch;
CurlEasy curl(listing);
curl.write_to(fetch);
curl.perform();
auto lines(split(fetch, '\n'));
std::vector<Target> new_targets, old_targets;
for (auto beg = std::begin(lines), end = std::end(lines);
beg != end; ++beg)
{
auto data(split(*beg, '@'));
Target t(data[0], data[data.size() - 1]);
auto status = t.status();
// TODO
#ifdef CPP11_ENUM_CLASS
if (status == Target::Status::Nonexistent)
#else
if (status == Target::Nonexistent)
#endif
{
new_targets.push_back(std::move(t));
}
// TODO
#ifdef CPP11_ENUM_CLASS
else if (status == Target::Status::Outdated)
#else
else if (status == Target::Outdated)
#endif
{
old_targets.push_back(std::move(t));
}
}
if (new_targets.size())
{
std::cout << "New targets: " << new_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
for (auto &t : new_targets)
#else
std::for_each(new_targets.cbegin(), new_targets.cend(),
[](const Target &t)
#endif
{
std::cout << "- " << t.name() << std::endl;
}
#ifndef CPP11_FOR_EACH
);
#endif
}
else
{
std::cout << "No new targets." << std::endl;
}
if (old_targets.size())
{
std::cout << "Outdated targets: " << old_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
for (auto &t : old_targets)
#else
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](const Target &t)
#endif
{
std::cout << "- " << t.name() << std::endl;
}
#ifndef CPP11_FOR_EACH
);
#endif
}
else
{
std::cout << "No targets out of date." << std::endl;
}
#ifndef DEBUG
#ifdef CPP11_FOR_EACH
for (auto &t : new_targets)
#else
std::for_each(new_targets.cbegin(), new_targets.cend(),
[](const Target &t)
#endif
{
t.fetch();
}
#ifndef CPP11_FOR_EACH
);
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](const Target &t)
#else
for (auto &t : old_targets)
#endif
{
t.fetch();
}
#ifndef CPP11_FOR_EACH
);
#endif
#endif
}
private:
const std::string path() const { return m_path; }
const std::string m_path;
const std::string m_update_check;
std::string m_update_path;
bool m_has_update;
};
int main(int argc, char *argv[])
{
CurlGlobalInit curl_global;
EfuLauncher l(argv[0],
"https://raw.github.com/commonquail/efulauncher/"\
"master/versioncheck");
if (l.has_update())
{
std::cout << "A new version of the launcher is available."\
" Would you like to download it (y/n)?" << std::endl;
bool download(confirm());
if (!download)
{
std::cout << "It is strongly recommended to always use"\
" the latest launcher. Would you like to download it (y/n)?"
<< std::endl;
download = confirm();
}
if (download)
{
// Download.
std::cout << "Downloading new launcher..." << std::endl;
if (l.get_update())
{
std::cout << "Done. Please extract and run the new launcher." << std::endl;
}
return 0;
}
}
try
{
l.stat_targets();
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <thread>
#include <future>
#include "common/log.h"
#include "gfx/gl/driver.h"
#include "gfx/camera.h"
#include "gfx/mesh_chunk.h"
#include "gfx/idriver_ui_adapter.h"
#include "gfx/support/load_wavefront.h"
#include "gfx/support/mesh_conversion.h"
#include "gfx/support/generate_aabb.h"
#include "gfx/support/write_data_to_mesh.h"
#include "gfx/support/texture_load.h"
#include "gfx/support/software_texture.h"
#include "ui/load.h"
#include "ui/freetype_renderer.h"
#include "ui/mouse_logic.h"
#include "ui/simple_controller.h"
#include "map/map.h"
#include "map/water.h"
#include "map/terrain.h"
#include "stratlib/player_state.h"
#include "glad/glad.h"
#include "glfw3.h"
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "uv.h"
#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"
glm::vec4 project_point(glm::vec4 pt,
glm::mat4 const& model,
glm::mat4 const& view,
glm::mat4 const& proj) noexcept
{
pt = proj * view * model * pt;
pt /= pt.w;
return pt;
}
void scroll_callback(GLFWwindow* window, double, double deltay)
{
auto cam_ptr = glfwGetWindowUserPointer(window);
auto& camera = *((game::gfx::Camera*) cam_ptr);
camera.fp.pos += -deltay;
}
game::ui::Mouse_State gen_mouse_state(GLFWwindow* w)
{
game::ui::Mouse_State ret;
ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
game::Vec<double> pos;
glfwGetCursorPos(w, &pos.x, &pos.y);
ret.position = game::vec_cast<int>(pos);
return ret;
}
void log_gl_limits(game::Log_Severity s) noexcept
{
GLint i = 0;
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i);
log(s, "GL_MAX_ELEMENTS_VERTICES: %", i);
}
struct Command_Options
{
};
Command_Options parse_command_line(int argc, char**)
{
Command_Options opt;
for(int i = 0; i < argc; ++i)
{
//auto option = argv[i];
}
return opt;
}
int main(int argc, char** argv)
{
using namespace game;
set_log_level(Log_Severity::Debug);
uv_chdir("assets/");
// Initialize logger.
Scoped_Log_Init log_init_raii_lock{};
// Parse command line arguments.
auto options = parse_command_line(argc - 1, argv+1);
// Init glfw.
if(!glfwInit())
return EXIT_FAILURE;
auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
if(!window)
{
glfwTerminate();
return EXIT_FAILURE;
}
// Init context + load gl functions.
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
// Log glfw version.
log_i("Initialized GLFW %", glfwGetVersionString());
int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
// Log GL profile.
log_i("OpenGL core profile %.%.%", maj, min, rev);
{
// Make an OpenGL driver.
gfx::gl::Driver driver{Vec<int>{1000, 1000}};
// Load our default shader.
auto default_shader = driver.make_shader_repr();
default_shader->load_vertex_part("shader/basic/v");
default_shader->load_fragment_part("shader/basic/f");
default_shader->set_projection_name("proj");
default_shader->set_view_name("view");
default_shader->set_model_name("model");
default_shader->set_sampler_name("tex");
default_shader->set_diffuse_name("dif");
driver.use_shader(*default_shader);
default_shader->set_sampler(0);
// Load our textures.
auto grass_tex = driver.make_texture_repr();
load_png("tex/grass.png", *grass_tex);
// Make an isometric camera.
auto cam = gfx::make_isometric_camera();
// Load the image
Software_Texture terrain_image;
load_png("map/default.png", terrain_image);
// Convert it into a heightmap
Maybe_Owned<Mesh> terrain = driver.make_mesh_repr();
auto terrain_heightmap = make_heightmap_from_image(terrain_image);
auto terrain_data =
make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01);
auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f));
gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain);
gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain));
gfx::format_mesh_buffers(*terrain);
terrain->set_primitive_type(Primitive_Type::Triangle);
// Map + structures.
Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr();
Map map({1000, 1000}); // <-- Map size for now
strat::Player_State player_state{strat::Player_State_Type::Nothing};
auto structures_future =
std::async(std::launch::async, load_structures,"structure/structures.json",
ref_mo(structure_mesh));
int fps = 0;
int time = glfwGetTime();
// Set up some pre-rendering state.
driver.clear_color_value(Color{0x55, 0x66, 0x77});
driver.clear_depth_value(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
// Our quick hack to avoid splitting into multiple functions and dealing
// either with global variables or like a bound struct or something.
bool has_clicked_down = false;
// Load our ui
gfx::IDriver_UI_Adapter ui_adapter{driver};
ui::Freetype_Renderer freetype_font;
auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter};
auto hud = ui::load("ui/hud.json", ui_load_params);
auto controller = ui::Simple_Controller{};
auto structures = structures_future.get();
hud->find_child_r("build_house")->add_click_listener([&](auto const& pt)
{
player_state.type = strat::Player_State_Type::Building;
player_state.building.to_build = &structures[0];
});
hud->find_child_r("build_gvn_build")->add_click_listener([&](auto const& pt)
{
player_state.type = strat::Player_State_Type::Building;
player_state.building.to_build = &structures[1];
});
hud->layout(driver.window_extents());
controller.add_drag_listener([&](auto const& np, auto const& op)
{
// pan
auto movement = vec_cast<float>(np - op);
movement /= -75;
glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f);
move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec;
cam.fp.pos.x += move_vec.x;
cam.fp.pos.z += move_vec.z;
});
glfwSetWindowUserPointer(window, &cam);
glfwSetScrollCallback(window, scroll_callback);
//water_obj.material->diffuse_color = Color{0xaa, 0xaa, 0xff};
while(!glfwWindowShouldClose(window))
{
++fps;
glfwPollEvents();
// Clear the screen and render the terrain.
driver.clear();
use_camera(driver, cam);
driver.bind_texture(*grass_tex, 0);
default_shader->set_diffuse(colors::white);
default_shader->set_model(terrain_model);
terrain->draw_elements(0, terrain_data.mesh.elements.size());
// Render the terrain before we calculate the depth of the mouse position.
auto mouse_state = gen_mouse_state(window);
controller.step(hud, mouse_state);
{
ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter};
hud->render(ui_adapter);
}
glfwSwapBuffers(window);
if(int(glfwGetTime()) != time)
{
time = glfwGetTime();
log_d("fps: %", fps);
fps = 0;
}
flush_log();
}
}
glfwTerminate();
return 0;
}
<commit_msg>We are now using the map mouse-unprojecting function in our main loop.<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <thread>
#include <future>
#include "common/log.h"
#include "gfx/gl/driver.h"
#include "gfx/camera.h"
#include "gfx/mesh_chunk.h"
#include "gfx/idriver_ui_adapter.h"
#include "gfx/support/load_wavefront.h"
#include "gfx/support/mesh_conversion.h"
#include "gfx/support/generate_aabb.h"
#include "gfx/support/write_data_to_mesh.h"
#include "gfx/support/texture_load.h"
#include "gfx/support/software_texture.h"
#include "ui/load.h"
#include "ui/freetype_renderer.h"
#include "ui/mouse_logic.h"
#include "ui/simple_controller.h"
#include "map/map.h"
#include "map/water.h"
#include "map/terrain.h"
#include "stratlib/player_state.h"
#include "glad/glad.h"
#include "glfw3.h"
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "uv.h"
#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"
glm::vec4 project_point(glm::vec4 pt,
glm::mat4 const& model,
glm::mat4 const& view,
glm::mat4 const& proj) noexcept
{
pt = proj * view * model * pt;
pt /= pt.w;
return pt;
}
void scroll_callback(GLFWwindow* window, double, double deltay)
{
auto cam_ptr = glfwGetWindowUserPointer(window);
auto& camera = *((game::gfx::Camera*) cam_ptr);
camera.fp.pos += -deltay;
}
game::ui::Mouse_State gen_mouse_state(GLFWwindow* w)
{
game::ui::Mouse_State ret;
ret.button_down =glfwGetMouseButton(w, GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS;
game::Vec<double> pos;
glfwGetCursorPos(w, &pos.x, &pos.y);
ret.position = game::vec_cast<int>(pos);
return ret;
}
void log_gl_limits(game::Log_Severity s) noexcept
{
GLint i = 0;
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i);
log(s, "GL_MAX_ELEMENTS_VERTICES: %", i);
}
struct Command_Options
{
};
Command_Options parse_command_line(int argc, char**)
{
Command_Options opt;
for(int i = 0; i < argc; ++i)
{
//auto option = argv[i];
}
return opt;
}
int main(int argc, char** argv)
{
using namespace game;
set_log_level(Log_Severity::Debug);
uv_chdir("assets/");
// Initialize logger.
Scoped_Log_Init log_init_raii_lock{};
// Parse command line arguments.
auto options = parse_command_line(argc - 1, argv+1);
// Init glfw.
if(!glfwInit())
return EXIT_FAILURE;
auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
if(!window)
{
glfwTerminate();
return EXIT_FAILURE;
}
// Init context + load gl functions.
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
// Log glfw version.
log_i("Initialized GLFW %", glfwGetVersionString());
int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
// Log GL profile.
log_i("OpenGL core profile %.%.%", maj, min, rev);
{
// Make an OpenGL driver.
gfx::gl::Driver driver{Vec<int>{1000, 1000}};
// Load our default shader.
auto default_shader = driver.make_shader_repr();
default_shader->load_vertex_part("shader/basic/v");
default_shader->load_fragment_part("shader/basic/f");
default_shader->set_projection_name("proj");
default_shader->set_view_name("view");
default_shader->set_model_name("model");
default_shader->set_sampler_name("tex");
default_shader->set_diffuse_name("dif");
driver.use_shader(*default_shader);
default_shader->set_sampler(0);
// Load our textures.
auto grass_tex = driver.make_texture_repr();
load_png("tex/grass.png", *grass_tex);
// Make an isometric camera.
auto cam = gfx::make_isometric_camera();
// Load the image
Software_Texture terrain_image;
load_png("map/default.png", terrain_image);
// Convert it into a heightmap
Maybe_Owned<Mesh> terrain = driver.make_mesh_repr();
auto terrain_heightmap = make_heightmap_from_image(terrain_image);
auto terrain_data =
make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01);
auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f));
gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain);
gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain));
gfx::format_mesh_buffers(*terrain);
terrain->set_primitive_type(Primitive_Type::Triangle);
// Map + structures.
Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr();
Map map({1000, 1000}); // <-- Map size for now
strat::Player_State player_state{strat::Player_State_Type::Nothing};
auto structures_future =
std::async(std::launch::async, load_structures,"structure/structures.json",
ref_mo(structure_mesh));
int fps = 0;
int time = glfwGetTime();
// Set up some pre-rendering state.
driver.clear_color_value(Color{0x55, 0x66, 0x77});
driver.clear_depth_value(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
// Our quick hack to avoid splitting into multiple functions and dealing
// either with global variables or like a bound struct or something.
bool has_clicked_down = false;
// Load our ui
gfx::IDriver_UI_Adapter ui_adapter{driver};
ui::Freetype_Renderer freetype_font;
auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter};
auto hud = ui::load("ui/hud.json", ui_load_params);
auto controller = ui::Simple_Controller{};
auto structures = structures_future.get();
hud->find_child_r("build_house")->add_click_listener([&](auto const& pt)
{
player_state.type = strat::Player_State_Type::Building;
player_state.building.to_build = &structures[0];
});
hud->find_child_r("build_gvn_build")->add_click_listener([&](auto const& pt)
{
player_state.type = strat::Player_State_Type::Building;
player_state.building.to_build = &structures[1];
});
hud->layout(driver.window_extents());
controller.add_drag_listener([&](auto const& np, auto const& op)
{
// pan
auto movement = vec_cast<float>(np - op);
movement /= -75;
glm::vec4 move_vec(movement.x, 0.0f, movement.y, 0.0f);
move_vec = glm::inverse(camera_view_matrix(cam)) * move_vec;
cam.fp.pos.x += move_vec.x;
cam.fp.pos.z += move_vec.z;
});
glfwSetWindowUserPointer(window, &cam);
glfwSetScrollCallback(window, scroll_callback);
//water_obj.material->diffuse_color = Color{0xaa, 0xaa, 0xff};
while(!glfwWindowShouldClose(window))
{
++fps;
glfwPollEvents();
// Clear the screen and render the terrain.
driver.clear();
use_camera(driver, cam);
driver.bind_texture(*grass_tex, 0);
default_shader->set_diffuse(colors::white);
default_shader->set_model(terrain_model);
// Render the terrain before we calculate the depth of the mouse position.
terrain->draw_elements(0, terrain_data.mesh.elements.size());
auto mouse_state = gen_mouse_state(window);
auto map_coord = unproject_mouse_coordinates(driver, cam, terrain_model,
mouse_state.position);
log_i("% %", map_coord.x, map_coord.y);
controller.step(hud, mouse_state);
{
ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter};
hud->render(ui_adapter);
}
glfwSwapBuffers(window);
if(int(glfwGetTime()) != time)
{
time = glfwGetTime();
log_d("fps: %", fps);
fps = 0;
}
flush_log();
}
}
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>// Minimal main example (with truss sdl)
#include "truss.h"
#include "truss_sdl.h"
#include "addons/bgfx_nanovg/nanovg_addon.h"
#include "addons/websocket_client/wsclient_addon.h"
#include <iostream>
#include <sstream>
#if defined(WIN32)
// On Windows, manually construct an RPATH to the `./lib` subdirectory.
#include "windows.h"
void setWindowsRPath() {
char exe_filepath[MAX_PATH], exe_drive[MAX_PATH], exe_path[MAX_PATH];
GetModuleFileName(NULL, exe_filepath, MAX_PATH);
_splitpath_s(exe_filepath, exe_drive, MAX_PATH, exe_path, MAX_PATH, NULL, 0, NULL, 0);
std::stringstream ss;
ss << exe_drive << exe_path << "\\lib";
SetDllDirectory(ss.str().c_str());
}
#endif
void storeArgs(int argc, char** argv) {
for (int i = 0; i < argc; ++i) {
std::stringstream ss;
ss << "arg" << i;
std::string val(argv[i]);
trss::core()->setStoreValue(ss.str(), val);
}
}
int main(int argc, char** argv) {
# if defined(WIN32)
setWindowsRPath();
# endif
trss_test();
trss_log(0, "Entered main!");
storeArgs(argc, argv);
// set up physFS filesystem
trss::core()->initFS(argv[0], true); // mount the base directory
trss::core()->setWriteDir("save"); // write into basedir/save/
trss::Interpreter* interpreter = trss::core()->spawnInterpreter("interpreter_0");
interpreter->setDebug(0); // want most verbose debugging output
// interpreter->attachAddon(new SDLAddon);
interpreter->attachAddon(new NanoVGAddon);
interpreter->attachAddon(new WSClientAddon);
trss_log(0, "Starting interpreter!");
// startUnthreaded starts the interpreter in the current thread,
// which means the call will block until the interpreter is stopped
//interpreter->startUnthreaded("examples/dart_gui_test.t");
if (argc > 1) {
interpreter->startUnthreaded(argv[1]);
}
else {
interpreter->startUnthreaded("examples/dart_gui_test.t");
}
return 0;
}<commit_msg>Fixed issue with forced loading of windows libraries.<commit_after>// Minimal main example (with truss sdl)
#include "truss.h"
#include "truss_sdl.h"
#include "addons/bgfx_nanovg/nanovg_addon.h"
#include "addons/websocket_client/wsclient_addon.h"
#include <iostream>
#include <sstream>
#if defined(WIN32)
// On Windows, manually construct an RPATH to the `./lib` subdirectory.
// TODO: refactor this into a config.in
#include "windows.h"
void setWindowsRPath() {
// Get path to current executable.
char exe_filepath[MAX_PATH], exe_drive[MAX_PATH], exe_path[MAX_PATH];
GetModuleFileName(NULL, exe_filepath, MAX_PATH);
_splitpath_s(exe_filepath, exe_drive, MAX_PATH, exe_path, MAX_PATH, NULL, 0, NULL, 0);
// Add absolute path to "./lib" directory to "RPATH".
std::stringstream ss;
ss << exe_drive << exe_path << "\\lib";
SetDllDirectory(ss.str().c_str());
// Manually force loading of DELAYLOAD-ed libraries.
LoadLibrary("bgfx-shared-libRelease.dll");
}
#endif
void storeArgs(int argc, char** argv) {
for (int i = 0; i < argc; ++i) {
std::stringstream ss;
ss << "arg" << i;
std::string val(argv[i]);
trss::core()->setStoreValue(ss.str(), val);
}
}
int main(int argc, char** argv) {
# if defined(WIN32)
setWindowsRPath();
# endif
trss_test();
trss_log(0, "Entered main!");
storeArgs(argc, argv);
// set up physFS filesystem
trss::core()->initFS(argv[0], true); // mount the base directory
trss::core()->setWriteDir("save"); // write into basedir/save/
trss::Interpreter* interpreter = trss::core()->spawnInterpreter("interpreter_0");
interpreter->setDebug(0); // want most verbose debugging output
interpreter->attachAddon(new SDLAddon);
interpreter->attachAddon(new NanoVGAddon);
interpreter->attachAddon(new WSClientAddon);
trss_log(0, "Starting interpreter!");
// startUnthreaded starts the interpreter in the current thread,
// which means the call will block until the interpreter is stopped
//interpreter->startUnthreaded("examples/dart_gui_test.t");
if (argc > 1) {
interpreter->startUnthreaded(argv[1]);
}
else {
interpreter->startUnthreaded("examples/dart_gui_test.t");
}
return 0;
}<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <thread>
#include <future>
#include "common/log.h"
#include "gfx/gl/driver.h"
#include "gfx/camera.h"
#include "gfx/mesh_chunk.h"
#include "gfx/idriver_ui_adapter.h"
#include "gfx/support/load_wavefront.h"
#include "gfx/support/mesh_conversion.h"
#include "gfx/support/generate_aabb.h"
#include "gfx/support/write_data_to_mesh.h"
#include "gfx/support/texture_load.h"
#include "gfx/support/software_texture.h"
#include "gfx/support/unproject.h"
#include "gfx/immediate_renderer.h"
#include "ui/load.h"
#include "ui/freetype_renderer.h"
#include "ui/mouse_logic.h"
#include "ui/simple_controller.h"
#include "ui/pie_menu.h"
#include "map/map.h"
#include "map/water.h"
#include "map/terrain.h"
#include "stratlib/player_state.h"
#include "glad/glad.h"
#include "glfw3.h"
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "uv.h"
#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"
glm::vec4 project_point(glm::vec4 pt,
glm::mat4 const& model,
glm::mat4 const& view,
glm::mat4 const& proj) noexcept
{
pt = proj * view * model * pt;
pt /= pt.w;
return pt;
}
struct Glfw_User_Data
{
game::gfx::IDriver& driver;
game::gfx::Camera& cam;
game::ui::Mouse_State mouse_state;
};
void scroll_callback(GLFWwindow* window, double, double deltay)
{
auto ptr = glfwGetWindowUserPointer(window);
auto& data = *((Glfw_User_Data*) ptr);
namespace gfx = game::gfx;
gfx::apply_zoom(data.cam, deltay, data.mouse_state.position, data.driver);
}
game::ui::Mouse_State gen_mouse_state(GLFWwindow* w)
{
game::ui::Mouse_State ret;
if(glfwGetMouseButton(w,GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
{
ret.buttons = game::ui::Mouse_Button_Left;
}
else
{
ret.buttons = 0x00;
}
game::Vec<double> pos;
glfwGetCursorPos(w, &pos.x, &pos.y);
ret.position = game::vec_cast<int>(pos);
return ret;
}
void log_gl_limits(game::Log_Severity s) noexcept
{
GLint i = 0;
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i);
log(s, "GL_MAX_ELEMENTS_VERTICES: %", i);
}
int main(int argc, char** argv)
{
using namespace game;
set_log_level(Log_Severity::Debug);
uv_chdir("assets/");
// Initialize logger.
Scoped_Log_Init log_init_raii_lock{};
// Init glfw.
if(!glfwInit())
return EXIT_FAILURE;
auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
if(!window)
{
glfwTerminate();
return EXIT_FAILURE;
}
// Init context + load gl functions.
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
// Log glfw version.
log_i("Initialized GLFW %", glfwGetVersionString());
int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
// Log GL profile.
log_i("OpenGL core profile %.%.%", maj, min, rev);
{
// Make an OpenGL driver.
gfx::gl::Driver driver{Vec<int>{1000, 1000}};
// Load our default shader.
auto default_shader = driver.make_shader_repr();
default_shader->load_vertex_part("shader/basic/v");
default_shader->load_fragment_part("shader/basic/f");
default_shader->set_projection_name("proj");
default_shader->set_view_name("view");
default_shader->set_model_name("model");
default_shader->set_sampler_name("tex");
default_shader->set_diffuse_name("dif");
driver.use_shader(*default_shader);
default_shader->set_sampler(0);
// Load our textures.
auto grass_tex = driver.make_texture_repr();
load_png("tex/grass.png", *grass_tex);
// Make an isometric camera.
auto cam = gfx::make_isometric_camera();
// Load the image
Software_Texture terrain_image;
load_png("map/default.png", terrain_image);
// Convert it into a heightmap
Maybe_Owned<Mesh> terrain = driver.make_mesh_repr();
auto terrain_heightmap = make_heightmap_from_image(terrain_image);
auto terrain_data =
make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01);
auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f));
gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain);
gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain));
gfx::format_mesh_buffers(*terrain);
terrain->set_primitive_type(Primitive_Type::Triangle);
// Map + structures.
Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr();
Map map({1000, 1000}); // <-- Map size for now
strat::Player_State player_state{strat::Player_State_Type::Nothing};
auto structures = load_structures("structure/structures.json",
ref_mo(structure_mesh),
driver);
int fps = 0;
int time = glfwGetTime();
// Set up some pre-rendering state.
driver.clear_color_value(Color{0x55, 0x66, 0x77});
driver.clear_depth_value(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
// Our quick hack to avoid splitting into multiple functions and dealing
// either with global variables or like a bound struct or something.
bool has_clicked_down = false;
// Load our ui
gfx::IDriver_UI_Adapter ui_adapter{driver};
ui::Freetype_Renderer freetype_font;
auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter};
auto hud = ui::load("ui/hud.json", ui_load_params);
auto controller = ui::Simple_Controller{};
hud->find_child_r("build_house")->add_click_listener([&](auto const& pt)
{
player_state.type = strat::Player_State_Type::Building;
player_state.building.to_build = &structures[0];
});
hud->find_child_r("build_gvn_build")->add_click_listener([&](auto const& pt)
{
player_state.type = strat::Player_State_Type::Building;
player_state.building.to_build = &structures[1];
});
hud->layout(driver.window_extents());
controller.add_drag_listener([&](auto const& np, auto const& op)
{
// Only drag if we don't have anything else to do.
if(player_state.type != strat::Player_State_Type::Nothing) return;
gfx::apply_pan(cam, np, op, driver);
});
Glfw_User_Data data{driver, cam};
glfwSetWindowUserPointer(window, &data);
glfwSetScrollCallback(window, scroll_callback);
//water_obj.material->diffuse_color = Color{0xaa, 0xaa, 0xff};
ui::Mouse_State old_mouse = gen_mouse_state(window);
ui::Pie_Menu pie_menu;
pie_menu.radius(200);
pie_menu.font_renderer(freetype_font);
pie_menu.num_buttons(3);
pie_menu.center_button("Place");
pie_menu.radial_button(0, "Analyze");
pie_menu.radial_button(1, "Rotate");
pie_menu.radial_button(2, "Cancel");
bool render_pie = false;
int action_countdown = 0;
gfx::Immediate_Renderer ir{driver};
while(!glfwWindowShouldClose(window))
{
action_countdown = std::max(action_countdown - 1, 0);
// TODO: Combine button and mouse state or something, this is terrible.
auto mouse_state = gen_mouse_state(window);
data.mouse_state = mouse_state;
++fps;
glfwPollEvents();
// Clear the screen and render the terrain.
driver.clear();
use_camera(driver, cam);
driver.bind_texture(*grass_tex, 0);
default_shader->set_diffuse(colors::white);
default_shader->set_model(terrain_model);
// Render the terrain before we calculate the depth of the mouse position.
terrain->draw_elements(0, terrain_data.mesh.elements.size());
// Render any structures.
// Maybe the mouse?
// We only want to be able to pan the terrain for now. That's why we need
// to do this before any structure rendering.
auto mouse_world = gfx::unproject_screen(driver, cam, glm::mat4(1.0f),
mouse_state.position);
controller.step(hud, mouse_state);
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS &&
player_state.type == strat::Player_State_Type::Building &&
action_countdown == 0)
{
player_state.type = strat::Player_State_Type::Nothing;
action_countdown = 500;
}
else if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS &&
player_state.type == strat::Player_State_Type::Nothing &&
action_countdown == 0)
{
glfwSetWindowShouldClose(window, true);
}
if(player_state.type == strat::Player_State_Type::Building)
{
auto& st = *player_state.building.to_build;
// TODO: Put this stuff somewhere to access it a bunch
auto mouse_map = Vec<float>{mouse_world.x, mouse_world.z};
//auto new_pos = st.on_snap(mouse_map);
render_structure(driver, st, mouse_map);
}
// Render all the other structures.
for(auto const& st : map.structures)
{
// TODO: Find/store correct y somehow?
render_structure_instance(driver, st);
}
// If we release the mouse find the item of the pie menu the user selected.
if(ui::is_click(mouse_state, old_mouse, true) &&
player_state.type == strat::Player_State_Type::Building)
{
// Enable viewing of the pie menu
render_pie = true;
pie_menu.center(mouse_state.position);
// Make sure we don't pan or build or whatever
player_state.type = strat::Player_State_Type::Pie_Menu;
// But place the object down.
auto st_pos = Vec<float>{};
st_pos.x = mouse_world.x;
st_pos.y = mouse_world.z;
ir.reset();
if(!try_structure_place(map, *player_state.building.to_build,st_pos,&ir))
{
// Tell the user!
}
}
else if(ui::is_release(mouse_state, old_mouse, true) &&
player_state.type == strat::Player_State_Type::Pie_Menu)
{
// Disable viewing of the pie menu
render_pie = false;
// Get current button
auto cur_radial = pie_menu.current_radial_button();
// It was either the center button
if(pie_menu.active_center_button())
{
// For now we know the center button places the object. Also, since the
// map already has it as a structure, we can just let things be.
}
// Or a radial button.
else if(cur_radial)
{
// For now brute force it.
switch(cur_radial.value())
{
case 0:
break;
case 1:
break;
case 2:
// Cancel
map.structures.erase(map.structures.end() - 1);
break;
default: break;
}
}
else
{
// No button, reverse the initial placement.
map.structures.erase(map.structures.end() - 1);
}
player_state.type = strat::Player_State_Type::Building;
}
ir.render(cam);
if(render_pie) pie_menu.handle_event(mouse_state);
{
ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter};
if(render_pie) pie_menu.render(ui_adapter);
hud->render(ui_adapter);
}
glfwSwapBuffers(window);
if(int(glfwGetTime()) != time)
{
time = glfwGetTime();
log_d("fps: %", fps);
fps = 0;
}
flush_log();
old_mouse = mouse_state;
}
}
glfwTerminate();
return 0;
}
<commit_msg>Remove some unnecesarily code in the main function<commit_after>/*
* Copyright (C) 2015 Luke San Antonio
* All rights reserved.
*/
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include <thread>
#include <future>
#include "common/log.h"
#include "gfx/gl/driver.h"
#include "gfx/camera.h"
#include "gfx/mesh_chunk.h"
#include "gfx/idriver_ui_adapter.h"
#include "gfx/support/load_wavefront.h"
#include "gfx/support/mesh_conversion.h"
#include "gfx/support/generate_aabb.h"
#include "gfx/support/write_data_to_mesh.h"
#include "gfx/support/texture_load.h"
#include "gfx/support/software_texture.h"
#include "gfx/support/unproject.h"
#include "gfx/immediate_renderer.h"
#include "ui/load.h"
#include "ui/freetype_renderer.h"
#include "ui/mouse_logic.h"
#include "ui/simple_controller.h"
#include "ui/pie_menu.h"
#include "map/map.h"
#include "map/water.h"
#include "map/terrain.h"
#include "stratlib/player_state.h"
#include "glad/glad.h"
#include "glfw3.h"
#define GLM_FORCE_RADIANS
#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "uv.h"
#define CATCH_CONFIG_RUNNER
#include "catch/catch.hpp"
glm::vec4 project_point(glm::vec4 pt,
glm::mat4 const& model,
glm::mat4 const& view,
glm::mat4 const& proj) noexcept
{
pt = proj * view * model * pt;
pt /= pt.w;
return pt;
}
struct Glfw_User_Data
{
game::gfx::IDriver& driver;
game::gfx::Camera& cam;
game::ui::Mouse_State mouse_state;
};
void scroll_callback(GLFWwindow* window, double, double deltay)
{
auto ptr = glfwGetWindowUserPointer(window);
auto& data = *((Glfw_User_Data*) ptr);
namespace gfx = game::gfx;
gfx::apply_zoom(data.cam, deltay, data.mouse_state.position, data.driver);
}
game::ui::Mouse_State gen_mouse_state(GLFWwindow* w)
{
game::ui::Mouse_State ret;
if(glfwGetMouseButton(w,GLFW_MOUSE_BUTTON_LEFT) == GLFW_PRESS)
{
ret.buttons = game::ui::Mouse_Button_Left;
}
else
{
ret.buttons = 0x00;
}
game::Vec<double> pos;
glfwGetCursorPos(w, &pos.x, &pos.y);
ret.position = game::vec_cast<int>(pos);
return ret;
}
void log_gl_limits(game::Log_Severity s) noexcept
{
GLint i = 0;
glGetIntegerv(GL_MAX_ELEMENTS_VERTICES, &i);
log(s, "GL_MAX_ELEMENTS_VERTICES: %", i);
}
int main(int argc, char** argv)
{
using namespace game;
set_log_level(Log_Severity::Debug);
uv_chdir("assets/");
// Initialize logger.
Scoped_Log_Init log_init_raii_lock{};
// Init glfw.
if(!glfwInit())
return EXIT_FAILURE;
auto window = glfwCreateWindow(1000, 1000, "Hello World", NULL, NULL);
if(!window)
{
glfwTerminate();
return EXIT_FAILURE;
}
// Init context + load gl functions.
glfwMakeContextCurrent(window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
// Log glfw version.
log_i("Initialized GLFW %", glfwGetVersionString());
int maj = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MAJOR);
int min = glfwGetWindowAttrib(window, GLFW_CONTEXT_VERSION_MINOR);
int rev = glfwGetWindowAttrib(window, GLFW_CONTEXT_REVISION);
// Log GL profile.
log_i("OpenGL core profile %.%.%", maj, min, rev);
{
// Make an OpenGL driver.
gfx::gl::Driver driver{Vec<int>{1000, 1000}};
// Load our default shader.
auto default_shader = driver.make_shader_repr();
default_shader->load_vertex_part("shader/basic/v");
default_shader->load_fragment_part("shader/basic/f");
default_shader->set_projection_name("proj");
default_shader->set_view_name("view");
default_shader->set_model_name("model");
default_shader->set_sampler_name("tex");
default_shader->set_diffuse_name("dif");
driver.use_shader(*default_shader);
default_shader->set_sampler(0);
// Load our textures.
auto grass_tex = driver.make_texture_repr();
load_png("tex/grass.png", *grass_tex);
// Make an isometric camera.
auto cam = gfx::make_isometric_camera();
// Load the image
Software_Texture terrain_image;
load_png("map/default.png", terrain_image);
// Convert it into a heightmap
Maybe_Owned<Mesh> terrain = driver.make_mesh_repr();
auto terrain_heightmap = make_heightmap_from_image(terrain_image);
auto terrain_data =
make_terrain_mesh(terrain_heightmap, {20, 20}, .001f, .01);
auto terrain_model = glm::scale(glm::mat4(1.0f),glm::vec3(5.0f, 1.0f, 5.0f));
gfx::allocate_mesh_buffers(terrain_data.mesh, *terrain);
gfx::write_data_to_mesh(terrain_data.mesh, ref_mo(terrain));
gfx::format_mesh_buffers(*terrain);
terrain->set_primitive_type(Primitive_Type::Triangle);
// Map + structures.
Maybe_Owned<Mesh> structure_mesh = driver.make_mesh_repr();
Map map({1000, 1000}); // <-- Map size for now
strat::Player_State player_state{strat::Player_State_Type::Nothing};
auto structures = load_structures("structure/structures.json",
ref_mo(structure_mesh),
driver);
int fps = 0;
int time = glfwGetTime();
// Set up some pre-rendering state.
driver.clear_color_value(Color{0x55, 0x66, 0x77});
driver.clear_depth_value(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glEnable(GL_CULL_FACE);
// Load our ui
gfx::IDriver_UI_Adapter ui_adapter{driver};
ui::Freetype_Renderer freetype_font;
auto ui_load_params = ui::Load_Params{freetype_font, ui_adapter};
auto hud = ui::load("ui/hud.json", ui_load_params);
auto controller = ui::Simple_Controller{};
hud->find_child_r("build_house")->add_click_listener([&](auto const& pt)
{
player_state.type = strat::Player_State_Type::Building;
player_state.building.to_build = &structures[0];
});
hud->find_child_r("build_gvn_build")->add_click_listener([&](auto const& pt)
{
player_state.type = strat::Player_State_Type::Building;
player_state.building.to_build = &structures[1];
});
hud->layout(driver.window_extents());
controller.add_drag_listener([&](auto const& np, auto const& op)
{
// Only drag if we don't have anything else to do.
if(player_state.type != strat::Player_State_Type::Nothing) return;
gfx::apply_pan(cam, np, op, driver);
});
Glfw_User_Data data{driver, cam};
glfwSetWindowUserPointer(window, &data);
glfwSetScrollCallback(window, scroll_callback);
//water_obj.material->diffuse_color = Color{0xaa, 0xaa, 0xff};
ui::Mouse_State old_mouse = gen_mouse_state(window);
ui::Pie_Menu pie_menu;
pie_menu.radius(200);
pie_menu.font_renderer(freetype_font);
pie_menu.num_buttons(3);
pie_menu.center_button("Place");
pie_menu.radial_button(0, "Analyze");
pie_menu.radial_button(1, "Rotate");
pie_menu.radial_button(2, "Cancel");
bool render_pie = false;
int action_countdown = 0;
gfx::Immediate_Renderer ir{driver};
while(!glfwWindowShouldClose(window))
{
action_countdown = std::max(action_countdown - 1, 0);
// TODO: Combine button and mouse state or something, this is terrible.
auto mouse_state = gen_mouse_state(window);
data.mouse_state = mouse_state;
++fps;
glfwPollEvents();
// Clear the screen and render the terrain.
driver.clear();
use_camera(driver, cam);
driver.bind_texture(*grass_tex, 0);
default_shader->set_diffuse(colors::white);
default_shader->set_model(terrain_model);
// Render the terrain before we calculate the depth of the mouse position.
terrain->draw_elements(0, terrain_data.mesh.elements.size());
// Render any structures.
// Maybe the mouse?
// We only want to be able to pan the terrain for now. That's why we need
// to do this before any structure rendering.
auto mouse_world = gfx::unproject_screen(driver, cam, glm::mat4(1.0f),
mouse_state.position);
controller.step(hud, mouse_state);
if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS &&
player_state.type == strat::Player_State_Type::Building &&
action_countdown == 0)
{
player_state.type = strat::Player_State_Type::Nothing;
action_countdown = 500;
}
else if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS &&
player_state.type == strat::Player_State_Type::Nothing &&
action_countdown == 0)
{
glfwSetWindowShouldClose(window, true);
}
if(player_state.type == strat::Player_State_Type::Building)
{
auto& st = *player_state.building.to_build;
// TODO: Put this stuff somewhere to access it a bunch
auto mouse_map = Vec<float>{mouse_world.x, mouse_world.z};
//auto new_pos = st.on_snap(mouse_map);
render_structure(driver, st, mouse_map);
}
// Render all the other structures.
for(auto const& st : map.structures)
{
// TODO: Find/store correct y somehow?
render_structure_instance(driver, st);
}
// If we release the mouse find the item of the pie menu the user selected.
if(ui::is_click(mouse_state, old_mouse, true) &&
player_state.type == strat::Player_State_Type::Building)
{
// Enable viewing of the pie menu
render_pie = true;
pie_menu.center(mouse_state.position);
// Make sure we don't pan or build or whatever
player_state.type = strat::Player_State_Type::Pie_Menu;
// But place the object down.
auto st_pos = Vec<float>{};
st_pos.x = mouse_world.x;
st_pos.y = mouse_world.z;
ir.reset();
if(!try_structure_place(map, *player_state.building.to_build,st_pos,&ir))
{
// Tell the user!
}
}
else if(ui::is_release(mouse_state, old_mouse, true) &&
player_state.type == strat::Player_State_Type::Pie_Menu)
{
// Disable viewing of the pie menu
render_pie = false;
// Get current button
auto cur_radial = pie_menu.current_radial_button();
// It was either the center button
if(pie_menu.active_center_button())
{
// For now we know the center button places the object. Also, since the
// map already has it as a structure, we can just let things be.
}
// Or a radial button.
else if(cur_radial)
{
// For now brute force it.
switch(cur_radial.value())
{
case 0:
break;
case 1:
break;
case 2:
// Cancel
map.structures.erase(map.structures.end() - 1);
break;
default: break;
}
}
else
{
// No button, reverse the initial placement.
map.structures.erase(map.structures.end() - 1);
}
player_state.type = strat::Player_State_Type::Building;
}
ir.render(cam);
if(render_pie) pie_menu.handle_event(mouse_state);
{
ui::Draw_Scoped_Lock scoped_draw_lock{ui_adapter};
if(render_pie) pie_menu.render(ui_adapter);
hud->render(ui_adapter);
}
glfwSwapBuffers(window);
if(int(glfwGetTime()) != time)
{
time = glfwGetTime();
log_d("fps: %", fps);
fps = 0;
}
flush_log();
old_mouse = mouse_state;
}
}
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>#include "compiler.h"
#include "mswin.h"
#include "glinit.h"
#include "model.h"
#include "cmdline.h"
#include <windowsx.h>
// #include "tinyscheme-config.h"
// #include <scheme-private.h>
// #include <scheme.h>
#include <cstdint>
namespace usr {
// Program name.
static const TCHAR * const program_name = TEXT ("Polymorph");
static const TCHAR * const message =
TEXT ("And the ratios of their numbers, motions, and ")
TEXT ("other properties, everywhere God, as far as ")
TEXT ("necessity allowed or gave consent, has exactly ")
TEXT ("perfected, and harmonised in due proportion.");
// TEXT ("\n\nThis screensaver includes TinyScheme, developed by Dimitrios ")
// TEXT ("Souflis and licensed under the Modified BSD License. ")
// TEXT ("See \"tinyscheme/COPYING.txt\" for details.");
}
inline std::uint64_t qpc ()
{
LARGE_INTEGER t;
::QueryPerformanceCounter (& t);
return t.QuadPart;
}
struct window_struct_t
{
model_t model;
POINT initial_cursor_position;
run_mode_t mode;
};
LRESULT CALLBACK InitWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
HGLRC setup_opengl_context (HWND hwnd);
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
// Read command line arguments.
HWND parent = NULL;
run_mode_t mode = parse_command_line (::GetCommandLine (), & parent);
if (mode == configure) {
::MessageBox (NULL, usr::message, usr::program_name, MB_OK | MB_ICONASTERISK);
return 0;
}
// Placement and window style of the main window.
RECT rect;
DWORD style;
DWORD ex_style = 0;
if (mode == embedded) {
style = WS_CHILD | WS_VISIBLE;
::GetClientRect (parent, & rect); // 0, 0, width, height
}
else {
style = WS_POPUP | WS_VISIBLE;
if (mode == fullscreen) ex_style = WS_EX_TOPMOST;
rect.left = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
rect.top = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
rect.right = ::GetSystemMetrics (SM_CXVIRTUALSCREEN); // actually width, not right
rect.bottom = ::GetSystemMetrics (SM_CYVIRTUALSCREEN); // actually height, not bottom
}
window_struct_t ws ALIGNED16;
ws.mode = mode;
// Create a window with an OpenGL rendering context.
// To obtain a proper OpenGL pixel format, we need to call wglChoosePixelFormatARB, but
// first we must obtain the address of that function by calling using wglGetProcAddress,
// which requires that an OpenGL rendering context is current, which requires a device
// context that supports OpenGL, which requires a window with an OpenGL pixel format.
// Bootstrap the process with a legacy OpenGL pixel format. According to MSDN,
// "Once a window's pixel format is set, it cannot be changed", so the window
// and associated resources are of no further use and are destroyed here.
// Create the dummy window. See InitWndProc.
// Note this window does not survive creation.
WNDCLASS init_wc = { 0, & InitWndProc, 0, 0, hInstance, NULL, NULL, NULL, NULL, TEXT ("GLinit") };
ATOM init_wc_atom = ::RegisterClass (& init_wc);
::CreateWindowEx (0, MAKEINTATOM (init_wc_atom), TEXT (""), 0,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
::UnregisterClass (MAKEINTATOM (init_wc_atom), hInstance);
// Exit if we failed to get the function pointers.
if (! wglChoosePixelFormatARB) return -1;
// Create the main window. See MainWndProc.
HICON icon = ::LoadIcon (hInstance, MAKEINTRESOURCE (257));
WNDCLASS main_wc = { 0, & MainWndProc, 0, 0, hInstance, icon, NULL, NULL, NULL, usr::program_name };
ATOM main_wc_atom = ::RegisterClass (& main_wc);
HWND hwnd = ::CreateWindowEx (ex_style, MAKEINTATOM (main_wc_atom), usr::program_name, style,
rect.left, rect.top, rect.right, rect.bottom,
parent, NULL, hInstance, & ws);
// Exit if we failed to create the window.
if (! hwnd) return 1;
// Enter the main loop.
MSG msg;
while (::GetMessage (& msg, NULL, 0, 0)) {
::TranslateMessage (& msg);
::DispatchMessage (& msg);
}
::UnregisterClass (MAKEINTATOM (main_wc_atom), hInstance);
return msg.wParam;
}
LRESULT CALLBACK InitWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_NCCREATE) {
// Set up a legacy rendering context to get the OpenGL function pointers.
PIXELFORMATDESCRIPTOR pfd = { sizeof pfd, 1, PFD_SUPPORT_OPENGL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
if (HDC hdc = ::GetDC (hwnd)) {
int pf = ::ChoosePixelFormat (hdc, & pfd);
::SetPixelFormat (hdc, pf, & pfd);
if (HGLRC hglrc = ::wglCreateContext (hdc)) {
::wglMakeCurrent (hdc, hglrc);
// Get the function pointers.
get_glprocs ();
::wglMakeCurrent (NULL, NULL);
::wglDeleteContext (hglrc);
}
::ReleaseDC (hwnd, hdc);
}
return FALSE; // Abort window creation.
}
else {
return ::DefWindowProc (hwnd, msg, wParam, lParam);
}
}
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool call_def_window_proc = false, close_window = false;
// Retrieve the window-struct pointer from the window userdata.
window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA));
switch (msg) {
case WM_CREATE: {
result = -1; // Abort window creation.
// Stash the window-struct pointer in the window userdata.
CREATESTRUCT * cs = reinterpret_cast <CREATESTRUCT *> (lParam);
ws = reinterpret_cast <window_struct_t *> (cs->lpCreateParams);
::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws));
// Remember initial mouse-pointer position to detect mouse movement.
::GetCursorPos (& ws->initial_cursor_position);
// Set up OpenGL rendering context.
HGLRC hglrc = setup_opengl_context (hwnd);
if (hglrc) {
ws->model.initialize (qpc (), cs->cx, cs->cy);
::PostMessage (hwnd, WM_APP, 0, 0); // Start the simulation.
result = 0; // Allow window creation to continue.
}
break;
}
case WM_APP: {
ws->model.draw_next ();
::InvalidateRect (hwnd, NULL, FALSE);
break;
}
case WM_PAINT: {
PAINTSTRUCT ps;
::BeginPaint (hwnd, & ps);
::SwapBuffers (ps.hdc);
::EndPaint (hwnd, & ps);
::PostMessage (hwnd, WM_APP, 0, 0);
break;
}
case WM_SETCURSOR:
::SetCursor (ws->mode == fullscreen ? NULL : (::LoadCursor (NULL, IDC_ARROW)));
break;
case WM_MOUSEMOVE:
if (ws->mode == fullscreen) {
// Compare the current mouse position with the one stored in the window struct.
POINT current = { GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam) };
::ClientToScreen (hwnd, & current);
SHORT dx = current.x - ws->initial_cursor_position.x;
SHORT dy = current.y - ws->initial_cursor_position.y;
close_window = dx > 10 || dy > 10 || dx * dx + dy * dy > 100;
}
break;
case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN:
close_window = ws->mode == fullscreen || ws->mode == special;
break;
case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE:
close_window = ws->mode == fullscreen && LOWORD (wParam) == WA_INACTIVE;
call_def_window_proc = true;
break;
case WM_SYSCOMMAND:
call_def_window_proc = ! (ws->mode == fullscreen && wParam == SC_SCREENSAVE);
break;
case WM_DESTROY:
::wglMakeCurrent (NULL, NULL);
//::wglDeleteContext (ws->hglrc);
::PostQuitMessage (0);
break;
default:
call_def_window_proc = true;
break;
}
if (close_window) {
::PostMessage (hwnd, WM_CLOSE, 0, 0);
}
if (call_def_window_proc) {
result = ::DefWindowProc (hwnd, msg, wParam, lParam);
}
return result;
}
// Set up a proper pixel format and rendering context for the main window.
HGLRC setup_opengl_context (HWND hwnd)
{
const int pf_attribs [] = {
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_DEPTH_BITS_ARB, 4,
WGL_SAMPLE_BUFFERS_ARB, GL_FALSE,
//WGL_SAMPLES_ARB, 5,
0, 0,
};
const int context_attribs [] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 2,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0, 0,
};
HGLRC hglrc = NULL;
int pf;
UINT pfcount;
if (HDC hdc = ::GetDC (hwnd)) {
if (wglChoosePixelFormatARB (hdc, pf_attribs, NULL, 1, & pf, & pfcount)) {
if (::SetPixelFormat (hdc, pf, NULL)) {
hglrc = wglCreateContextAttribsARB (hdc, NULL, context_attribs);
if (hglrc) {
::wglMakeCurrent (hdc, hglrc);
}
}
}
::ReleaseDC (hwnd, hdc);
}
return hglrc;
}
#ifdef TINY
// Tiny startup.
// No standard handles, window placement, environment variables,
// command-line transformation, global constructors and destructors,
// atexit functions, stack realignment, thread-local storage,
// runtime relocation fixups, 387 floating-point initialization,
// signal handlers or exceptions.
extern "C"
{
// This symbol is provided by all recent GCC and MSVC linkers.
IMAGE_DOS_HEADER __ImageBase;
// This entry point must be specified in the linker command line.
void custom_startup ()
{
HINSTANCE hInstance = reinterpret_cast <HINSTANCE> (& __ImageBase);
int status = WinMain (hInstance, NULL, NULL, 0);
::ExitProcess (static_cast <UINT> (status));
}
}
#endif
<commit_msg>main.cpp: fix and simplify mouse position comparison.<commit_after>#include "compiler.h"
#include "mswin.h"
#include "glinit.h"
#include "model.h"
#include "cmdline.h"
#include <windowsx.h>
// #include "tinyscheme-config.h"
// #include <scheme-private.h>
// #include <scheme.h>
#include <cstdint>
namespace usr {
// Program name.
static const TCHAR * const program_name = TEXT ("Polymorph");
static const TCHAR * const message =
TEXT ("And the ratios of their numbers, motions, and ")
TEXT ("other properties, everywhere God, as far as ")
TEXT ("necessity allowed or gave consent, has exactly ")
TEXT ("perfected, and harmonised in due proportion.");
// TEXT ("\n\nThis screensaver includes TinyScheme, developed by Dimitrios ")
// TEXT ("Souflis and licensed under the Modified BSD License. ")
// TEXT ("See \"tinyscheme/COPYING.txt\" for details.");
}
inline std::uint64_t qpc ()
{
LARGE_INTEGER t;
::QueryPerformanceCounter (& t);
return t.QuadPart;
}
struct window_struct_t
{
model_t model;
POINT initial_cursor_position;
run_mode_t mode;
};
LRESULT CALLBACK InitWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
HGLRC setup_opengl_context (HWND hwnd);
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
// Read command line arguments.
HWND parent = NULL;
run_mode_t mode = parse_command_line (::GetCommandLine (), & parent);
if (mode == configure) {
::MessageBox (NULL, usr::message, usr::program_name, MB_OK | MB_ICONASTERISK);
return 0;
}
// Placement and window style of the main window.
RECT rect;
DWORD style;
DWORD ex_style = 0;
if (mode == embedded) {
style = WS_CHILD | WS_VISIBLE;
::GetClientRect (parent, & rect); // 0, 0, width, height
}
else {
style = WS_POPUP | WS_VISIBLE;
if (mode == fullscreen) ex_style = WS_EX_TOPMOST;
rect.left = ::GetSystemMetrics (SM_XVIRTUALSCREEN);
rect.top = ::GetSystemMetrics (SM_YVIRTUALSCREEN);
rect.right = ::GetSystemMetrics (SM_CXVIRTUALSCREEN); // actually width, not right
rect.bottom = ::GetSystemMetrics (SM_CYVIRTUALSCREEN); // actually height, not bottom
}
window_struct_t ws ALIGNED16;
ws.mode = mode;
// Create a window with an OpenGL rendering context.
// To obtain a proper OpenGL pixel format, we need to call wglChoosePixelFormatARB, but
// first we must obtain the address of that function by calling using wglGetProcAddress,
// which requires that an OpenGL rendering context is current, which requires a device
// context that supports OpenGL, which requires a window with an OpenGL pixel format.
// Bootstrap the process with a legacy OpenGL pixel format. According to MSDN,
// "Once a window's pixel format is set, it cannot be changed", so the window
// and associated resources are of no further use and are destroyed here.
// Create the dummy window. See InitWndProc.
// Note this window does not survive creation.
WNDCLASS init_wc = { 0, & InitWndProc, 0, 0, hInstance, NULL, NULL, NULL, NULL, TEXT ("GLinit") };
ATOM init_wc_atom = ::RegisterClass (& init_wc);
::CreateWindowEx (0, MAKEINTATOM (init_wc_atom), TEXT (""), 0,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
NULL, NULL, hInstance, NULL);
::UnregisterClass (MAKEINTATOM (init_wc_atom), hInstance);
// Exit if we failed to get the function pointers.
if (! wglChoosePixelFormatARB) return -1;
// Create the main window. See MainWndProc.
HICON icon = ::LoadIcon (hInstance, MAKEINTRESOURCE (257));
WNDCLASS main_wc = { 0, & MainWndProc, 0, 0, hInstance, icon, NULL, NULL, NULL, usr::program_name };
ATOM main_wc_atom = ::RegisterClass (& main_wc);
HWND hwnd = ::CreateWindowEx (ex_style, MAKEINTATOM (main_wc_atom), usr::program_name, style,
rect.left, rect.top, rect.right, rect.bottom,
parent, NULL, hInstance, & ws);
// Exit if we failed to create the window.
if (! hwnd) return 1;
// Enter the main loop.
MSG msg;
while (::GetMessage (& msg, NULL, 0, 0)) {
::TranslateMessage (& msg);
::DispatchMessage (& msg);
}
::UnregisterClass (MAKEINTATOM (main_wc_atom), hInstance);
return msg.wParam;
}
LRESULT CALLBACK InitWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (msg == WM_NCCREATE) {
// Set up a legacy rendering context to get the OpenGL function pointers.
PIXELFORMATDESCRIPTOR pfd = { sizeof pfd, 1, PFD_SUPPORT_OPENGL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
if (HDC hdc = ::GetDC (hwnd)) {
int pf = ::ChoosePixelFormat (hdc, & pfd);
::SetPixelFormat (hdc, pf, & pfd);
if (HGLRC hglrc = ::wglCreateContext (hdc)) {
::wglMakeCurrent (hdc, hglrc);
// Get the function pointers.
get_glprocs ();
::wglMakeCurrent (NULL, NULL);
::wglDeleteContext (hglrc);
}
::ReleaseDC (hwnd, hdc);
}
return FALSE; // Abort window creation.
}
else {
return ::DefWindowProc (hwnd, msg, wParam, lParam);
}
}
LRESULT CALLBACK MainWndProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool call_def_window_proc = false, close_window = false;
// Retrieve the window-struct pointer from the window userdata.
window_struct_t * ws = reinterpret_cast <window_struct_t *> (::GetWindowLongPtr (hwnd, GWLP_USERDATA));
switch (msg) {
case WM_CREATE: {
result = -1; // Abort window creation.
// Stash the window-struct pointer in the window userdata.
CREATESTRUCT * cs = reinterpret_cast <CREATESTRUCT *> (lParam);
ws = reinterpret_cast <window_struct_t *> (cs->lpCreateParams);
::SetWindowLongPtr (hwnd, GWLP_USERDATA, reinterpret_cast <LONG_PTR> (ws));
// Remember initial mouse-pointer position to detect mouse movement.
POINT cursor;
::GetCursorPos (& cursor);
::ScreenToClient (hwnd, & cursor);
ws->initial_cursor_position = cursor;
// Set up OpenGL rendering context.
HGLRC hglrc = setup_opengl_context (hwnd);
if (hglrc) {
ws->model.initialize (qpc (), cs->cx, cs->cy);
::PostMessage (hwnd, WM_APP, 0, 0); // Start the simulation.
result = 0; // Allow window creation to continue.
}
break;
}
case WM_APP: {
ws->model.draw_next ();
::InvalidateRect (hwnd, NULL, FALSE);
break;
}
case WM_PAINT: {
PAINTSTRUCT ps;
::BeginPaint (hwnd, & ps);
::SwapBuffers (ps.hdc);
::EndPaint (hwnd, & ps);
::PostMessage (hwnd, WM_APP, 0, 0);
break;
}
case WM_SETCURSOR:
::SetCursor (ws->mode == fullscreen ? NULL : (::LoadCursor (NULL, IDC_ARROW)));
break;
case WM_MOUSEMOVE:
if (ws->mode == fullscreen) {
// Compare the current mouse position with the one stored in the window struct.
DWORD cursor = (DWORD) lParam;
int dx = GET_X_LPARAM (cursor) - ws->initial_cursor_position.x;
int dy = GET_Y_LPARAM (cursor) - ws->initial_cursor_position.y;
close_window = (dx < -10 || dx > 10) || (dy < -10 || dy > 10);
}
break;
case WM_KEYDOWN: case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN:
close_window = ws->mode == fullscreen || ws->mode == special;
break;
case WM_ACTIVATE: case WM_ACTIVATEAPP: case WM_NCACTIVATE:
close_window = ws->mode == fullscreen && LOWORD (wParam) == WA_INACTIVE;
call_def_window_proc = true;
break;
case WM_SYSCOMMAND:
call_def_window_proc = ! (ws->mode == fullscreen && wParam == SC_SCREENSAVE);
break;
case WM_DESTROY:
::wglMakeCurrent (NULL, NULL);
//::wglDeleteContext (ws->hglrc);
::PostQuitMessage (0);
break;
default:
call_def_window_proc = true;
break;
}
if (close_window) {
::PostMessage (hwnd, WM_CLOSE, 0, 0);
}
if (call_def_window_proc) {
result = ::DefWindowProc (hwnd, msg, wParam, lParam);
}
return result;
}
// Set up a proper pixel format and rendering context for the main window.
HGLRC setup_opengl_context (HWND hwnd)
{
const int pf_attribs [] = {
WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
WGL_SWAP_METHOD_ARB, WGL_SWAP_EXCHANGE_ARB,
WGL_COLOR_BITS_ARB, 32,
WGL_DEPTH_BITS_ARB, 4,
WGL_SAMPLE_BUFFERS_ARB, GL_FALSE,
//WGL_SAMPLES_ARB, 5,
0, 0,
};
const int context_attribs [] = {
WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
WGL_CONTEXT_MINOR_VERSION_ARB, 2,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0, 0,
};
HGLRC hglrc = NULL;
int pf;
UINT pfcount;
if (HDC hdc = ::GetDC (hwnd)) {
if (wglChoosePixelFormatARB (hdc, pf_attribs, NULL, 1, & pf, & pfcount)) {
if (::SetPixelFormat (hdc, pf, NULL)) {
hglrc = wglCreateContextAttribsARB (hdc, NULL, context_attribs);
if (hglrc) {
::wglMakeCurrent (hdc, hglrc);
}
}
}
::ReleaseDC (hwnd, hdc);
}
return hglrc;
}
#ifdef TINY
// Tiny startup.
// No standard handles, window placement, environment variables,
// command-line transformation, global constructors and destructors,
// atexit functions, stack realignment, thread-local storage,
// runtime relocation fixups, 387 floating-point initialization,
// signal handlers or exceptions.
extern "C"
{
// This symbol is provided by all recent GCC and MSVC linkers.
IMAGE_DOS_HEADER __ImageBase;
// This entry point must be specified in the linker command line.
void custom_startup ()
{
HINSTANCE hInstance = reinterpret_cast <HINSTANCE> (& __ImageBase);
int status = WinMain (hInstance, NULL, NULL, 0);
::ExitProcess (static_cast <UINT> (status));
}
}
#endif
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <iostream>
/// The main function
int main () {
std::cout << "Hello !" << std::endl;
return 0;
}<commit_msg>Include headers for GLEW and glfw3<commit_after>#include <GL/glew.h> // to load OpenGL extensions at runtime
#include <GLFW/glfw3.h> // to set up the OpenGL context and manage window lifecycle and inputs
#include <stdio.h>
#include <iostream>
/// The main function
int main () {
std::cout << "Hello !" << std::endl;
return 0;
}<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <cstdlib>
using namespace std;
using namespace boost;
int main(int argc, char** argv) {
string input = "";
/*for(int i = 1; i < argc; i++) {//comment out if using user input
input += argv[i];//comment out if using user input
}*///comment out for user input
//cout << "$ " << input << endl;
pid_t pid;
while(1) {//use this for user input
cout << "$ ";//use this for user input
getline(cin, input);//use this for user input instead of command line
typedef tokenizer<char_separator<char> > tokenizer;
char_separator<char> sep(";");
tokenizer tkn(input, sep);
for(tokenizer::iterator tok = tkn.begin(); tok != tkn.end(); tok++) {
char **ptr;
vector<char *> v;
if(v.empty() && (tok->compare("exit") == 0)) {
return 1;
}
if((tok->compare("&") == 0) && (tok->compare("|") == 0)) {
} else if(tok->compare("&") == 0) {
} else if(tok->compare("|") == 0) {
} else {
string temp = *tok;
if(temp.find(" ") == 0) {
temp.erase(0,1);
}
if(temp.find("#") != string::npos) {
int index = temp.find("#");
temp = temp.substr(0, index);
}
if(temp.find(" ") != string::npos) {
char_separator<char> sep_2(" ");
tokenizer tkn_2(temp, sep_2);
for(tokenizer::iterator tok_2 = tkn_2.begin(); tok_2 != tkn_2.end(); tok_2++) {
string temp_2 = *tok_2;
char *temp_1 = new char[temp_2.size()];
copy(temp_2.begin(), temp_2.end(), temp_1);
v.push_back(temp_1);
}
v.push_back('\0');
ptr = &v[0];
} else {
char *temp_1 = new char[temp.size() + 1];
copy(temp.begin(), temp.end(), temp_1);
temp_1[temp.size()] = '\0';
v.push_back(temp_1);
ptr = &v[0];
}
pid = fork();
if(pid == -1) {
return -1;
}
if(pid == 0) {
if(execvp(ptr[0], ptr) == -1) {
perror("Execvp Failed");
}
exit(1);
}
if(pid > 0) {
if(wait(0) == -1) {
perror("Wait");
exit(1);
}
}
ptr = NULL;
v.clear();
}
}
}
}<commit_msg>modified main.cpp<commit_after>#include <iostream>
#include <boost/foreach.hpp>
#include <boost/tokenizer.hpp>
#include <string>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <cstdlib>
using namespace std;
using namespace boost;
bool execute(string);
bool test(string);
bool run(string);
int main(int argc, char** argv) {
//finding user login info
string user, info;
char hostInfo[256];
struct passwd *u = getpwuid(getuid());
int h = gethostname(hostInfo, 256);
if(u != 0 && h != -1) {
user = u->pw_name;
info = hostInfo;
info.append("@");
info.append(user);
info.append("$ ");
} else {
info = "user@host_name$ ";
}
//string input = "";
/*for(int i = 1; i < argc; i++) {//comment out if using user input
input += argv[i];//comment out if using user input
}//comment out for user input
cout << "$ " << input << endl;*/
while(1) {//use this for user input
string input = "";
cout << info;//use this for user input
getline(cin, input);//use this for user input instead of command line
typedef tokenizer<char_separator<char> > tokenizer;
char_separator<char> sep(";");
tokenizer tkn(input, sep);
for(tokenizer::iterator tok = tkn.begin(); tok != tkn.end(); tok++) {
string currTok = *tok;
if(currTok.find("&") != string::npos) { //else if
bool passed = true;
char_separator<char> sep1("&");
tokenizer tkn1(currTok, sep1);
for(tokenizer::iterator tok1 = tkn1.begin(); tok1 != tkn1.end(); tok1++) {
if(passed == true) {
string temp_and = *tok1;
if(temp_and.find("exit") != string::npos) {
return 1;
}
passed = run(temp_and);
}
}
} else if(currTok.find("|") != string::npos) {
bool passed = false;
char_separator<char> sep2("|");
tokenizer tkn2(currTok, sep2);
for(tokenizer::iterator tok2 = tkn2.begin(); tok2 != tkn2.end(); tok2++) {
if(passed == false) {
string temp_or = *tok2;
if(temp_or.find("exit") != string::npos) {
return 1;
}
passed = run(temp_or);
}
}
} else {
if(currTok == "exit") { //|| currTok.find("exit") != string::npos) {
return 1;
}
run(currTok);
}
}
}
}
bool run(string temp) {
bool ret;
string temp2 = temp;
if( temp2.find("test") != string::npos ) {
while(temp2.at(temp2.size() - 1) == ' ') {
temp2 = temp2.substr(0, temp2.size() - 1);
}
ret = test(temp2);
} else if( temp2.find("[") != string::npos && temp2.find("]") != string::npos ) {
temp2 = temp2.substr(0, temp2.find("]") - 1);
ret = test(temp2);
} else {
while(temp2.at(temp2.size() - 1) == ' ') {
temp2 = temp2.substr(0, temp2.size() - 1);
}
ret = execute(temp2);
}
return ret;
}
bool execute(string temp) {
bool ret = true;
pid_t pid;
typedef tokenizer<char_separator<char> > tokenizer;
char **ptr;
string temp1 = temp;
vector<char *> v;
while(temp1.find(" ") == 0) {
temp1.erase(0,1);
}
if(temp1.find("#") != string::npos) {
int index = temp1.find("#");
temp1 = temp1.substr(0, index);
}
if(temp1.find(" ") != string::npos) {
int i = 0;
string temp_last;
char_separator<char> sep_2(" ");
tokenizer tkn_2(temp1, sep_2);
for(tokenizer::iterator tok_2 = tkn_2.begin(); tok_2 != tkn_2.end(); tok_2++) {
string temp_2 = *tok_2;
char *temp_1 = new char[temp_2.size()];
copy(temp_2.begin(), temp_2.end(), temp_1);
v.push_back(temp_1);
i++;
temp_last = temp_2;
}
//v.push_back('\0');
char *temp_3 = new char[temp_last.size() + 1];
copy(temp_last.begin(), temp_last.end(), temp_3);
temp_3[temp_last.size()] = '\0';
v.pop_back();
v.push_back(temp_3);
ptr = &v[0];
} else {
char *temp_1 = new char[temp1.size() + 1];
copy(temp1.begin(), temp1.end(), temp_1);
temp_1[temp1.size()] = '\0';
v.push_back(temp_1);
ptr = &v[0];
}
pid = fork();
if(pid == -1) {
return false;
}
if(pid == 0) {
if(execvp(ptr[0], ptr) == -1) {
perror("Execvp Failed");
}
exit(1);
}
if(pid > 0) {
if(wait(0) == -1) {
perror("Wait");
exit(1);
}
}
ptr = NULL;
v.clear();
return ret;
}
bool test(string temp) {
struct stat buf;
if(temp.find("-e") != string::npos) {
string temp2 = temp.substr(temp.find("-e") + 3);
if(stat(temp2.c_str(), &buf) == 0) {
cout << "(TRUE)" << endl;
return true;
} else {
cout << "(FALSE)" << endl;
return false;
}
}
if(temp.find("-f") != string::npos) {
string temp2 = temp.substr(temp.find("-f") + 3);
if(stat(temp2.c_str(), &buf) == 0) {
if(S_ISREG(buf.st_mode)) {
cout << "(TRUE)" << endl;
return true;
} else {
cout << "(FALSE)" << endl;
return false;
}
} else {
cout << "(FALSE)" << endl;
return false;
}
}
if(temp.find("-d") != string::npos) {
string temp2 = temp.substr(temp.find("-d") + 3);
if(stat(temp2.c_str(), &buf) == 0) {
if(S_ISDIR(buf.st_mode)) {
cout << "(TRUE)" << endl;
return true;
} else {
cout << "(FALSE)" << endl;
return false;
}
} else {
cout << "(FALSE)" << endl;
return false;
}
}
if(temp.find("-e") == string::npos && temp.find("-f") == string::npos && temp.find("-d") == string::npos) {
string temp2 = temp;
if(temp2.find("[") != string::npos) {
temp2 = temp2.substr(temp2.find("[") + 2);
}
if(temp2.find("test") != string::npos) {
temp2 = temp2.substr(temp2.find("test") + 5);
}
if(stat(temp2.c_str(), &buf) == 0) {
cout << "(TRUE)" << endl;
return true;
} else {
cout << "(FALSE)" << endl;
return false;
}
}
}<|endoftext|> |
<commit_before>#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <boost/log/trivial.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <hadouken/application.hpp>
#include <hadouken/logging.hpp>
#include <hadouken/platform.hpp>
#include <hadouken/hosting/host.hpp>
#include <hadouken/hosting/console_host.hpp>
#ifdef WIN32
#include <hadouken/hosting/service_host.hpp>
#endif
namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace pt = boost::property_tree;
po::variables_map load_options(int argc,char *argv[])
{
po::options_description desc("Allowed options");
desc.add_options()
("config", po::value<std::string>(), "Set path to a JSON configuration file. The default is %appdir%/hadouken.json")
("daemon", "Start Hadouken in daemon/service mode.")
#ifdef WIN32
("install-service", "Install Hadouken in the SCM.")
("uninstall-service", "Uninstall Hadouken from the SCM.")
#endif
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
return vm;
}
fs::path get_config_path(const po::variables_map& options)
{
if (options.count("config"))
{
return options["config"].as<std::string>();
}
else if (options.count("daemon"))
{
return (hadouken::platform::data_path() / "hadouken.json");
}
else
{
return (hadouken::platform::get_current_directory() / "hadouken.json");
}
}
std::unique_ptr<hadouken::hosting::host> get_host(const po::variables_map& options)
{
if (options.count("daemon"))
{
#ifdef WIN32
return std::unique_ptr<hadouken::hosting::host>(new hadouken::hosting::service_host());
#endif
}
return std::unique_ptr<hadouken::hosting::host>(new hadouken::hosting::console_host());
}
int main(int argc, char *argv[])
{
po::variables_map vm = load_options(argc, argv);
hadouken::logging::setup(vm);
// Do platform-specific initialization as early as possible.
hadouken::platform::init();
#ifdef WIN32
if (vm.count("install-service"))
{
hadouken::platform::install_service();
return 0;
}
else if (vm.count("uninstall-service"))
{
hadouken::platform::uninstall_service();
return 0;
}
#endif
fs::path config_file = get_config_path(vm);
pt::ptree config;
if (!fs::exists(config_file))
{
BOOST_LOG_TRIVIAL(warning) << "Could not find config file at " << config_file;
}
else
{
try
{
pt::read_json(config_file.string(), config);
BOOST_LOG_TRIVIAL(info) << "Loaded config file " << config_file;
}
catch (const std::exception& ex)
{
// To meet expectations, fail if the configuration file cannot be parsed. Otherwise,
// we will revert to the default config which might be totally wrong.
BOOST_LOG_TRIVIAL(fatal) << "Error when loading config file " << config_file << ": " << ex.what();
return EXIT_FAILURE;
}
}
boost::shared_ptr<boost::asio::io_service> io(new boost::asio::io_service());
hadouken::application app(io, config);
app.script_host().define_global("__CONFIG__", config_file.string());
app.script_host().define_global("__CONFIG_PATH__", config_file.parent_path().string());
app.start();
int result = get_host(vm)->wait_for_exit(io);
app.stop();
return result;
}
<commit_msg>Add quick and dirty --help option.<commit_after>#include <boost/asio.hpp>
#include <boost/filesystem.hpp>
#include <boost/log/trivial.hpp>
#include <boost/program_options.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <hadouken/application.hpp>
#include <hadouken/logging.hpp>
#include <hadouken/platform.hpp>
#include <hadouken/hosting/host.hpp>
#include <hadouken/hosting/console_host.hpp>
#ifdef WIN32
#include <hadouken/hosting/service_host.hpp>
#endif
namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace pt = boost::property_tree;
po::variables_map load_options(int argc,char *argv[])
{
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Display available commandline options")
("config", po::value<std::string>(), "Set path to a JSON configuration file. The default is %appdir%/hadouken.json")
("daemon", "Start Hadouken in daemon/service mode.")
#ifdef WIN32
("install-service", "Install Hadouken in the SCM.")
("uninstall-service", "Uninstall Hadouken from the SCM.")
#endif
;
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
return vm;
}
fs::path get_config_path(const po::variables_map& options)
{
if (options.count("config"))
{
return options["config"].as<std::string>();
}
else if (options.count("daemon"))
{
return (hadouken::platform::data_path() / "hadouken.json");
}
else
{
return (hadouken::platform::get_current_directory() / "hadouken.json");
}
}
std::unique_ptr<hadouken::hosting::host> get_host(const po::variables_map& options)
{
if (options.count("daemon"))
{
#ifdef WIN32
return std::unique_ptr<hadouken::hosting::host>(new hadouken::hosting::service_host());
#endif
}
return std::unique_ptr<hadouken::hosting::host>(new hadouken::hosting::console_host());
}
int main(int argc, char *argv[])
{
po::variables_map vm = load_options(argc, argv);
hadouken::logging::setup(vm);
// Do platform-specific initialization as early as possible.
hadouken::platform::init();
#ifdef WIN32
if (vm.count("install-service"))
{
hadouken::platform::install_service();
return 0;
}
else if (vm.count("uninstall-service"))
{
hadouken::platform::uninstall_service();
return 0;
}
#endif
fs::path config_file = get_config_path(vm);
pt::ptree config;
if (!fs::exists(config_file))
{
BOOST_LOG_TRIVIAL(warning) << "Could not find config file at " << config_file;
}
else
{
try
{
pt::read_json(config_file.string(), config);
BOOST_LOG_TRIVIAL(info) << "Loaded config file " << config_file;
}
catch (const std::exception& ex)
{
// To meet expectations, fail if the configuration file cannot be parsed. Otherwise,
// we will revert to the default config which might be totally wrong.
BOOST_LOG_TRIVIAL(fatal) << "Error when loading config file " << config_file << ": " << ex.what();
return EXIT_FAILURE;
}
}
boost::shared_ptr<boost::asio::io_service> io(new boost::asio::io_service());
hadouken::application app(io, config);
app.script_host().define_global("__CONFIG__", config_file.string());
app.script_host().define_global("__CONFIG_PATH__", config_file.parent_path().string());
app.start();
int result = get_host(vm)->wait_for_exit(io);
app.stop();
return result;
}
<|endoftext|> |
<commit_before>#include <algorithm>
#include <iostream>
#include <iomanip>
#include <ios>
#include <stan/mcmc/chains.hpp>
#include <cmdstan/stansummary_helper.hpp>
#include <fstream>
void diagnose_usage() {
std::cout << "USAGE: diagnose <filename 1> [<filename 2> ... <filename N>]"
<< std::endl
<< std::endl;
}
/**
* The Stan print function.
*
* @param argc Number of arguments
* @param argv Arguments
*
* @return 0 for success,
* non-zero otherwise
*/
int main(int argc, const char* argv[]) {
if (argc == 1) {
diagnose_usage();
return 0;
}
// Parse any arguments specifying filenames
std::ifstream ifstream;
std::vector<std::string> filenames;
for (int i = 1; i < argc; ++i) {
ifstream.open(argv[i]);
if (ifstream.good()) {
filenames.push_back(argv[i]);
ifstream.close();
} else {
std::cout << "File " << argv[i] << " not found" << std::endl;
}
}
if (!filenames.size()) {
std::cout << "No valid input files, exiting." << std::endl;
return 0;
}
// Parse specified files
ifstream.open(filenames[0].c_str());
stan::io::stan_csv stan_csv
= stan::io::stan_csv_reader::parse(ifstream, &std::cout);
stan::mcmc::chains<> chains(stan_csv);
ifstream.close();
for (std::vector<std::string>::size_type chain = 1;
chain < filenames.size(); ++chain) {
ifstream.open(filenames[chain].c_str());
stan_csv = stan::io::stan_csv_reader::parse(ifstream, &std::cout);
chains.add(stan_csv);
ifstream.close();
}
int num_samples = chains.num_samples();
std::vector<std::string> bad_n_eff_names;
std::vector<std::string> bad_rhat_names;
for (int i = 0; i < chains.num_params(); ++i) {
int max_limit = 10;
if (chains.param_name(i) == std::string("treedepth__")) {
int max = chains.samples(i).maxCoeff();
if (max >= max_limit) {
int n_max = 0;
Eigen::VectorXd t_samples = chains.samples(i);
for (size_t n = 0; n < t_samples.size(); ++n)
if (t_samples(n) == max) ++n_max;
std::cout << n_max << " of " << num_samples << " ("
<< std::setprecision(2)
<< 100 * static_cast<double>(n_max) / num_samples
<< "%) transitions hit the maximum treedepth limit of "
<< max << ", or 2^" << max << " leapfrog steps."
<< " Trajectories that are prematurely terminated due to this"
<< " limit will result in slow exploration and you should"
<< " increase the limit to ensure optimal performance."
<< std::endl << std::endl;
}
} else if (chains.param_name(i) == std::string("divergent__")) {
int n_divergent = chains.samples(i).sum();
if (n_divergent > 0)
std::cout << n_divergent << " of " << num_samples << " ("
<< std::setprecision(2)
<< 100 * static_cast<double>(n_divergent) / num_samples
<< "%) transitions ended with a divergence. These divergent"
<< " transitions indicate that HMC is not fully able to"
<< " explore the posterior distribution. Try rerunning with"
<< " adapt delta set to a larger value and see if the"
<< " divergences vanish. If increasing adapt delta towards"
<< " 1 does not remove the divergences then you will likely"
<< " need to reparameterize your model."
<< std::endl << std::endl;
} else if (chains.param_name(i) == std::string("energy__")) {
Eigen::VectorXd e_samples = chains.samples(i);
double delta_e_sq_mean = 0;
double e_mean = 0;
double e_var = 0;
e_mean += e_samples(0);
e_var += e_samples(0) * (e_samples(0) - e_mean);
for (size_t n = 1; n < e_samples.size(); ++n) {
double e = e_samples(n);
double delta_e_sq = (e - e_samples(n - 1)) * (e - e_samples(n - 1));
double d = delta_e_sq - delta_e_sq_mean;
delta_e_sq_mean += d / n;
d = e - e_mean;
e_mean += d / (n + 1);
e_var += d * (e - e_mean);
}
e_var /= static_cast<double>(e_samples.size() - 1);
double e_bfmi = delta_e_sq_mean / e_var;
double e_bfmi_threshold = 0.3;
if (e_bfmi < e_bfmi_threshold)
std::cout << "The E-BFMI, " << e_bfmi << ", is below the nominal"
<< " threshold of " << e_bfmi_threshold << " which suggests"
<< " that HMC may have trouble exploring the target"
<< " distribution. You should consider any"
<< " reparameterizations if possible."
<< std::endl << std::endl;
} else if (chains.param_name(i).find("__") == std::string::npos) {
double n_eff = chains.effective_sample_size(i);
if (n_eff / num_samples < 0.001)
bad_n_eff_names.push_back(chains.param_name(i));
double split_rhat = chains.split_potential_scale_reduction(i);
if (split_rhat > 1.1)
bad_rhat_names.push_back(chains.param_name(i));
}
}
if (bad_n_eff_names.size() > 0) {
std::cout << "The following parameters had fewer than 0.001 effective"
<< " samples per transition:" << std::endl;
std::cout << " ";
for (int n = 0; n < bad_n_eff_names.size() - 1; ++n)
std::cout << bad_n_eff_names.at(n) << ", ";
std::cout << bad_n_eff_names.back() << std::endl;
std::cout << "Such low values indicate that the effective sample size"
<< " estimators may be biased high and actual performance"
<< " may be substantially lower than quoted."
<< std::endl << std::endl;
}
if (bad_rhat_names.size() > 0) {
std::cout << "The following parameters had split R-hat less than 1.1:"
<< std::endl;
std::cout << " ";
for (int n = 0; n < bad_rhat_names.size() - 1; ++n)
std::cout << bad_rhat_names.at(n) << ", ";
std::cout << bad_rhat_names.back() << std::endl;
std::cout << "Such high values indicate incomplete mixing and biased"
<< "estimation. You should consider regularization your model"
<< " with additional prior information or looking for a more"
<< " effective parameterization."
<< std::endl << std::endl;
}
return 0;
}
<commit_msg>fixed types in diagnose to remove warnings<commit_after>#include <algorithm>
#include <iostream>
#include <iomanip>
#include <ios>
#include <stan/mcmc/chains.hpp>
#include <cmdstan/stansummary_helper.hpp>
#include <fstream>
void diagnose_usage() {
std::cout << "USAGE: diagnose <filename 1> [<filename 2> ... <filename N>]"
<< std::endl
<< std::endl;
}
/**
* The Stan print function.
*
* @param argc Number of arguments
* @param argv Arguments
*
* @return 0 for success,
* non-zero otherwise
*/
int main(int argc, const char* argv[]) {
if (argc == 1) {
diagnose_usage();
return 0;
}
// Parse any arguments specifying filenames
std::ifstream ifstream;
std::vector<std::string> filenames;
for (int i = 1; i < argc; ++i) {
ifstream.open(argv[i]);
if (ifstream.good()) {
filenames.push_back(argv[i]);
ifstream.close();
} else {
std::cout << "File " << argv[i] << " not found" << std::endl;
}
}
if (!filenames.size()) {
std::cout << "No valid input files, exiting." << std::endl;
return 0;
}
// Parse specified files
ifstream.open(filenames[0].c_str());
stan::io::stan_csv stan_csv
= stan::io::stan_csv_reader::parse(ifstream, &std::cout);
stan::mcmc::chains<> chains(stan_csv);
ifstream.close();
for (std::vector<std::string>::size_type chain = 1;
chain < filenames.size(); ++chain) {
ifstream.open(filenames[chain].c_str());
stan_csv = stan::io::stan_csv_reader::parse(ifstream, &std::cout);
chains.add(stan_csv);
ifstream.close();
}
int num_samples = chains.num_samples();
std::vector<std::string> bad_n_eff_names;
std::vector<std::string> bad_rhat_names;
for (int i = 0; i < chains.num_params(); ++i) {
int max_limit = 10;
if (chains.param_name(i) == std::string("treedepth__")) {
int max = chains.samples(i).maxCoeff();
if (max >= max_limit) {
int n_max = 0;
Eigen::VectorXd t_samples = chains.samples(i);
for (long n = 0; n < t_samples.size(); ++n)
if (t_samples(n) == max) ++n_max;
std::cout << n_max << " of " << num_samples << " ("
<< std::setprecision(2)
<< 100 * static_cast<double>(n_max) / num_samples
<< "%) transitions hit the maximum treedepth limit of "
<< max << ", or 2^" << max << " leapfrog steps."
<< " Trajectories that are prematurely terminated due to this"
<< " limit will result in slow exploration and you should"
<< " increase the limit to ensure optimal performance."
<< std::endl << std::endl;
}
} else if (chains.param_name(i) == std::string("divergent__")) {
int n_divergent = chains.samples(i).sum();
if (n_divergent > 0)
std::cout << n_divergent << " of " << num_samples << " ("
<< std::setprecision(2)
<< 100 * static_cast<double>(n_divergent) / num_samples
<< "%) transitions ended with a divergence. These divergent"
<< " transitions indicate that HMC is not fully able to"
<< " explore the posterior distribution. Try rerunning with"
<< " adapt delta set to a larger value and see if the"
<< " divergences vanish. If increasing adapt delta towards"
<< " 1 does not remove the divergences then you will likely"
<< " need to reparameterize your model."
<< std::endl << std::endl;
} else if (chains.param_name(i) == std::string("energy__")) {
Eigen::VectorXd e_samples = chains.samples(i);
double delta_e_sq_mean = 0;
double e_mean = 0;
double e_var = 0;
e_mean += e_samples(0);
e_var += e_samples(0) * (e_samples(0) - e_mean);
for (long n = 1; n < e_samples.size(); ++n) {
double e = e_samples(n);
double delta_e_sq = (e - e_samples(n - 1)) * (e - e_samples(n - 1));
double d = delta_e_sq - delta_e_sq_mean;
delta_e_sq_mean += d / n;
d = e - e_mean;
e_mean += d / (n + 1);
e_var += d * (e - e_mean);
}
e_var /= static_cast<double>(e_samples.size() - 1);
double e_bfmi = delta_e_sq_mean / e_var;
double e_bfmi_threshold = 0.3;
if (e_bfmi < e_bfmi_threshold)
std::cout << "The E-BFMI, " << e_bfmi << ", is below the nominal"
<< " threshold of " << e_bfmi_threshold << " which suggests"
<< " that HMC may have trouble exploring the target"
<< " distribution. You should consider any"
<< " reparameterizations if possible."
<< std::endl << std::endl;
} else if (chains.param_name(i).find("__") == std::string::npos) {
double n_eff = chains.effective_sample_size(i);
if (n_eff / num_samples < 0.001)
bad_n_eff_names.push_back(chains.param_name(i));
double split_rhat = chains.split_potential_scale_reduction(i);
if (split_rhat > 1.1)
bad_rhat_names.push_back(chains.param_name(i));
}
}
if (bad_n_eff_names.size() > 0) {
std::cout << "The following parameters had fewer than 0.001 effective"
<< " samples per transition:" << std::endl;
std::cout << " ";
for (size_t n = 0; n < bad_n_eff_names.size() - 1; ++n)
std::cout << bad_n_eff_names.at(n) << ", ";
std::cout << bad_n_eff_names.back() << std::endl;
std::cout << "Such low values indicate that the effective sample size"
<< " estimators may be biased high and actual performance"
<< " may be substantially lower than quoted."
<< std::endl << std::endl;
}
if (bad_rhat_names.size() > 0) {
std::cout << "The following parameters had split R-hat less than 1.1:"
<< std::endl;
std::cout << " ";
for (size_t n = 0; n < bad_rhat_names.size() - 1; ++n)
std::cout << bad_rhat_names.at(n) << ", ";
std::cout << bad_rhat_names.back() << std::endl;
std::cout << "Such high values indicate incomplete mixing and biased"
<< "estimation. You should consider regularization your model"
<< " with additional prior information or looking for a more"
<< " effective parameterization."
<< std::endl << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* main.cpp
*
*/
#include "Robot.h"
#include "Behaviour.h"
#include "Action.h"
#include <player-3.0/libplayerc++/playerc++.h>
#include <iostream>
#include <cstdlib>
#define _GXX_EXPERIMENTAL_CXX0X__
#include <chrono>
using namespace PlayerCc;
using namespace std;
int main(int argc, char **argv) {
PlayerClient robot("localhost", 6665);
Position2dProxy pp(&robot);
LaserProxy lp(&robot);
RobotDescriptor descriptor;
Robot r(&pp, &lp, &descriptor);
srand(time(0));
/*
BehaviourOnObstacleDistance bClose(&r, 180, 0, 1.5);
for (int i = 0; i < 10; i++) {
bClose.addAction(
new Action(rand() % 2 ? ACTION_LINEAR_VEL : ACTION_ANGLUAR_VEL,
-1 + (rand() % 200) / 100.0, rand() % 2));
}
BehaviourOnObstacleDistance bFar(&r, 180, 1.5, 100);
for (int i = 0; i < 10; i++) {
bFar.addAction(
new Action(rand() % 2 ? ACTION_LINEAR_VEL : ACTION_ANGLUAR_VEL,
-1 + (rand() % 200) / 100.0, rand() % 2));
}
*/
BehaviourOnObstacleDistance bClose(&r, 180, 0, 1);
BehaviourOnObstacleDistance bCloseL(&r, 270, 0, 0.7);
BehaviourOnObstacleDistance bCloseR(&r, 90, 0, 0.7);
BehaviourOnObstacleDistance bCloseL2(&r, 360, 0, 0.3);
BehaviourOnObstacleDistance bCloseR2(&r, 0, 0, 0.3);
BehaviourOnObstacleDistance bFar(&r, 180, 1, 100);
bClose.addAction(new Action(ACTION_ANGLUAR_VEL, 0.5, 0.1));
bCloseL.addAction(new Action(ACTION_ANGLUAR_VEL, -0.5, 0.2));
bCloseR.addAction(new Action(ACTION_ANGLUAR_VEL, 0.5, 0.2));
bCloseL2.addAction(new Action(ACTION_ANGLUAR_VEL, -0.5, 0.2));
bCloseR2.addAction(new Action(ACTION_ANGLUAR_VEL, 0.5, 0.2));
bFar.addAction(new Action(ACTION_LINEAR_VEL, 1, 0.1));
descriptor.addBehavior(&bClose);
descriptor.addBehavior(&bCloseL);
descriptor.addBehavior(&bCloseR);
descriptor.addBehavior(&bCloseL2);
descriptor.addBehavior(&bCloseR2);
descriptor.addBehavior(&bFar);
while (true) {
robot.Read();
r.update();
}
}
<commit_msg>Coisas aleatórias<commit_after>/*
* main.cpp
*
*/
#include "Robot.h"
#include "Behaviour.h"
#include "Action.h"
#include <player-3.0/libplayerc++/playerc++.h>
#include <iostream>
#include <cstdlib>
#define _GXX_EXPERIMENTAL_CXX0X__
#include <chrono>
using namespace PlayerCc;
using namespace std;
int main(int argc, char **argv) {
PlayerClient robot("localhost", 6665);
Position2dProxy pp(&robot);
LaserProxy lp(&robot);
RobotDescriptor descriptor;
Robot r(&pp, &lp, &descriptor);
srand(time(0));
// criar comportamentos
int rb = rand()%5 + 2;
for(int i = 0; i < rb; i++){
double minDist = (rand() % 100)/100.0;
Behaviour *b = new BehaviourOnObstacleDistance(&r, rand()%360, minDist, minDist + (rand() % 400)/100.0);
int ra = rand() % 10 + 1;
for(int i = 0; i < ra; i++){
Action *act;
if(rand()%2){
act = new Action(ACTION_LINEAR_VEL, (rand()%200)/100.0 - 1, (rand()%100)/100.0);
}else{
act = new Action(ACTION_ANGLUAR_VEL, (rand()%200)/100.0 - 1, (rand()%100)/100.0);
}
b->addAction(act);
}
descriptor.addBehavior(b);
}
BehaviourOnObstacleDistance far(&r, 180, 0, 100);
far.addAction(new Action(ACTION_LINEAR_VEL, 1, 0.1));
// senão tem uma grande chance dele ficar parado
descriptor.addBehavior(&far);
while (true) {
robot.Read();
r.update();
}
}
<|endoftext|> |
<commit_before>#include "circuit.h"
#include "docopt.h"
#include "evaluate_circuit.h"
#include "global.h"
#include "grid.h"
#include "input.h"
#include "memory.h"
#include "ordering.h"
static const char VERSION[] = "qFlex v0.1";
static const char USAGE[] =
R"(Flexible Quantum Circuit Simulator (qFlex) implements an efficient
tensor network, CPU-based simulator of large quantum circuits.
Usage:
qflex <circuit_filename> <ordering_filename> <grid_filename> [<initial_conf> <final_conf> <verbosity_level> <memory_limit> <track_memory_milliseconds>]
qflex -c <circuit_filename> -o <ordering_filename> -g <grid_filename> [--initial-conf=<initial_conf> --final-conf=<final_conf> --verbosity=<verbosity_level> --memory=<memory_limit> --track-memory=<milliseconds>]
qflex (-h | --help)
qflex --version
Options:
-h,--help Show this help.
-c,--circuit=<circuit_filename> Circuit filename.
-o,--ordering=<ordering_filename> Ordering filename.
-g,--grid=<grid_filename> Grid filename.
-v,--verbosity=<verbosity_level> Verbosity level [default: 0].
-m,--memory=<memory_limit> Memory limit [default: 1GB].)"
#ifdef __linux__
"\n" R"( -t,--track-memory=<milliseconds> If <verbosity_level> > 0, track memory usage [default: 0].)"
#endif
"\n" R"( --initial-conf=<initial_conf> Initial configuration.
--final-conf=<final_conf> Final configuration.
--version Show version.
)";
/*
* Example:
* $ src/qflex.x config/circuits/bristlecone_48_1-24-1_0.txt \
* config/ordering/bristlecone_48.txt \
* config/grid/bristlecone_48.txt
*
*/
int main(int argc, char** argv) {
try {
std::map<std::string, docopt::value> args =
docopt::docopt(USAGE, {argv + 1, argv + argc}, true, VERSION);
// Reading input
qflex::QflexInput input;
// Update global qflex::global::verbose
if (static_cast<bool>(args["--verbosity"]))
qflex::global::verbose = args["--verbosity"].asLong();
else if (static_cast<bool>(args["<verbosity_level>"]))
qflex::global::verbose = args["<verbosity_level>"].asLong();
// Update global qflex::global::memory_limit
if (static_cast<bool>(args["--memory"]))
qflex::global::memory_limit = qflex::utils::from_readable_memory_string(
args["--memory"].asString());
else if (static_cast<bool>(args["<memory_limit>"]))
qflex::global::memory_limit = qflex::utils::from_readable_memory_string(
args["<memory_limit>"].asString());
#ifdef __linux__
if (static_cast<bool>(args["--track-memory"]))
qflex::global::track_memory = args["--track-memory"].asLong();
else if (static_cast<bool>(args["<track_memory_milliseconds>"]))
qflex::global::track_memory =
args["<track_memory_milliseconds>"].asLong();
// Alarms can interfere with the flow of the program if called to often in a
// short period of time
if (qflex::global::track_memory > 0 && qflex::global::track_memory < 100) {
std::cerr << "WARNING! Minimum allowed tracking time is 100ms. Setting "
"to 100ms."
<< std::endl;
qflex::global::track_memory = 100;
}
#endif
// Get initial/final configurations
if (static_cast<bool>(args["--initial-conf"]))
input.initial_state = args["--initial-conf"].asString();
else if (static_cast<bool>(args["<initial_conf>"]))
input.initial_state = args["<initial_conf>"].asString();
if (static_cast<bool>(args["--final-conf"]))
input.final_state = args["--final-conf"].asString();
else if (static_cast<bool>(args["<final_conf>"]))
input.final_state = args["<final_conf>"].asString();
// Getting filenames
std::string circuit_filename = static_cast<bool>(args["--circuit"])
? args["--circuit"].asString()
: args["<circuit_filename>"].asString();
std::string ordering_filename =
static_cast<bool>(args["--ordering"])
? args["--ordering"].asString()
: args["<ordering_filename>"].asString();
std::string grid_filename = static_cast<bool>(args["--grid"])
? args["--grid"].asString()
: args["<grid_filename>"].asString();
// Print info on maximum memory
#ifdef __linux__
if (qflex::global::verbose > 0)
std::cerr << "Maximum allowed memory: "
<< qflex::utils::readable_memory_string(
qflex::global::memory_limit)
<< std::endl;
// set alarms to get memory usage in real time
if (qflex::global::verbose > 0 && qflex::global::track_memory > 0) {
signal(SIGALRM, qflex::memory::print_memory_usage);
ualarm(qflex::global::track_memory * 1e3,
qflex::global::track_memory * 1e3);
}
#endif
// Load circuit
input.circuit.load(std::ifstream(circuit_filename));
// Load ordering
input.ordering.load(std::ifstream(ordering_filename));
// Load grid
input.grid.load(grid_filename);
// Evaluating circuit.
std::vector<std::pair<std::string, std::complex<double>>> amplitudes;
try {
amplitudes = qflex::EvaluateCircuit(&input);
} catch (const std::string& err_msg) {
throw ERROR_MSG("Failed to call EvaluateCircuit(). Error:\n\t[", err_msg,
"]");
}
// If no error is caught, amplitudes will be initialized.
#ifdef __linux__
if (qflex::global::verbose > 0 && qflex::global::track_memory > 0)
qflex::memory::print_memory_usage();
#endif
// Printing output.
for (std::size_t c = 0; c < amplitudes.size(); ++c) {
const auto& state = amplitudes[c].first;
const auto& amplitude = amplitudes[c].second;
std::cout << input.initial_state << " --> " << state << ": "
<< std::real(amplitude) << " " << std::imag(amplitude)
<< std::endl;
}
} catch (const std::exception& ex) {
std::cerr << ex.what() << std::endl;
return 1;
} catch (const std::string& msg) {
std::cerr << msg << std::endl;
return 2;
}
return 0;
}
<commit_msg>Fix format.<commit_after>#include "circuit.h"
#include "docopt.h"
#include "evaluate_circuit.h"
#include "global.h"
#include "grid.h"
#include "input.h"
#include "memory.h"
#include "ordering.h"
static const char VERSION[] = "qFlex v0.1";
static const char USAGE[] =
R"(Flexible Quantum Circuit Simulator (qFlex) implements an efficient
tensor network, CPU-based simulator of large quantum circuits.
Usage:
qflex <circuit_filename> <ordering_filename> <grid_filename> [<initial_conf> <final_conf> <verbosity_level> <memory_limit> <track_memory_milliseconds>]
qflex -c <circuit_filename> -o <ordering_filename> -g <grid_filename> [--initial-conf=<initial_conf> --final-conf=<final_conf> --verbosity=<verbosity_level> --memory=<memory_limit> --track-memory=<milliseconds>]
qflex (-h | --help)
qflex --version
Options:
-h,--help Show this help.
-c,--circuit=<circuit_filename> Circuit filename.
-o,--ordering=<ordering_filename> Ordering filename.
-g,--grid=<grid_filename> Grid filename.
-v,--verbosity=<verbosity_level> Verbosity level [default: 0].
-m,--memory=<memory_limit> Memory limit [default: 1GB].)"
#ifdef __linux__
"\n"
R"( -t,--track-memory=<milliseconds> If <verbosity_level> > 0, track memory usage [default: 0].)"
#endif
"\n"
R"( --initial-conf=<initial_conf> Initial configuration.
--final-conf=<final_conf> Final configuration.
--version Show version.
)";
/*
* Example:
* $ src/qflex.x config/circuits/bristlecone_48_1-24-1_0.txt \
* config/ordering/bristlecone_48.txt \
* config/grid/bristlecone_48.txt
*
*/
int main(int argc, char** argv) {
try {
std::map<std::string, docopt::value> args =
docopt::docopt(USAGE, {argv + 1, argv + argc}, true, VERSION);
// Reading input
qflex::QflexInput input;
// Update global qflex::global::verbose
if (static_cast<bool>(args["--verbosity"]))
qflex::global::verbose = args["--verbosity"].asLong();
else if (static_cast<bool>(args["<verbosity_level>"]))
qflex::global::verbose = args["<verbosity_level>"].asLong();
// Update global qflex::global::memory_limit
if (static_cast<bool>(args["--memory"]))
qflex::global::memory_limit = qflex::utils::from_readable_memory_string(
args["--memory"].asString());
else if (static_cast<bool>(args["<memory_limit>"]))
qflex::global::memory_limit = qflex::utils::from_readable_memory_string(
args["<memory_limit>"].asString());
#ifdef __linux__
if (static_cast<bool>(args["--track-memory"]))
qflex::global::track_memory = args["--track-memory"].asLong();
else if (static_cast<bool>(args["<track_memory_milliseconds>"]))
qflex::global::track_memory =
args["<track_memory_milliseconds>"].asLong();
// Alarms can interfere with the flow of the program if called to often in a
// short period of time
if (qflex::global::track_memory > 0 && qflex::global::track_memory < 100) {
std::cerr << "WARNING! Minimum allowed tracking time is 100ms. Setting "
"to 100ms."
<< std::endl;
qflex::global::track_memory = 100;
}
#endif
// Get initial/final configurations
if (static_cast<bool>(args["--initial-conf"]))
input.initial_state = args["--initial-conf"].asString();
else if (static_cast<bool>(args["<initial_conf>"]))
input.initial_state = args["<initial_conf>"].asString();
if (static_cast<bool>(args["--final-conf"]))
input.final_state = args["--final-conf"].asString();
else if (static_cast<bool>(args["<final_conf>"]))
input.final_state = args["<final_conf>"].asString();
// Getting filenames
std::string circuit_filename = static_cast<bool>(args["--circuit"])
? args["--circuit"].asString()
: args["<circuit_filename>"].asString();
std::string ordering_filename =
static_cast<bool>(args["--ordering"])
? args["--ordering"].asString()
: args["<ordering_filename>"].asString();
std::string grid_filename = static_cast<bool>(args["--grid"])
? args["--grid"].asString()
: args["<grid_filename>"].asString();
// Print info on maximum memory
#ifdef __linux__
if (qflex::global::verbose > 0)
std::cerr << "Maximum allowed memory: "
<< qflex::utils::readable_memory_string(
qflex::global::memory_limit)
<< std::endl;
// set alarms to get memory usage in real time
if (qflex::global::verbose > 0 && qflex::global::track_memory > 0) {
signal(SIGALRM, qflex::memory::print_memory_usage);
ualarm(qflex::global::track_memory * 1e3,
qflex::global::track_memory * 1e3);
}
#endif
// Load circuit
input.circuit.load(std::ifstream(circuit_filename));
// Load ordering
input.ordering.load(std::ifstream(ordering_filename));
// Load grid
input.grid.load(grid_filename);
// Evaluating circuit.
std::vector<std::pair<std::string, std::complex<double>>> amplitudes;
try {
amplitudes = qflex::EvaluateCircuit(&input);
} catch (const std::string& err_msg) {
throw ERROR_MSG("Failed to call EvaluateCircuit(). Error:\n\t[", err_msg,
"]");
}
// If no error is caught, amplitudes will be initialized.
#ifdef __linux__
if (qflex::global::verbose > 0 && qflex::global::track_memory > 0)
qflex::memory::print_memory_usage();
#endif
// Printing output.
for (std::size_t c = 0; c < amplitudes.size(); ++c) {
const auto& state = amplitudes[c].first;
const auto& amplitude = amplitudes[c].second;
std::cout << input.initial_state << " --> " << state << ": "
<< std::real(amplitude) << " " << std::imag(amplitude)
<< std::endl;
}
} catch (const std::exception& ex) {
std::cerr << ex.what() << std::endl;
return 1;
} catch (const std::string& msg) {
std::cerr << msg << std::endl;
return 2;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "configure.hpp"
#include "parsers/md_parser.hpp"
#include "display_drivers/ncurses_display_driver.hpp"
using namespace std;
int main(int argc, char ** argv) {
cout << "mdl v" << MDL_VERSION_STRING << endl;
if (argc < 2) {
cerr << "mdl: missing at least one argument" << endl;
return 1;
}
MdParser parser(argv[1]);
NcursesDisplayDriver drv;
drv.display(parser.get_document());
return 0;
}
<commit_msg>Make program usable for all locales<commit_after>#include "configure.hpp"
#include "parsers/md_parser.hpp"
#include "display_drivers/ncurses_display_driver.hpp"
#include <iostream>
#include <locale.h>
using namespace std;
int main(int argc, char ** argv) {
setlocale(LC_ALL, "");
cout << "mdl v" << MDL_VERSION_STRING << endl;
if (argc < 2) {
cerr << "mdl: missing at least one argument" << endl;
return 1;
}
MdParser parser(argv[1]);
NcursesDisplayDriver drv;
drv.display(parser.get_document());
return 0;
}
<|endoftext|> |
<commit_before>#include <string>
#include <iostream>
#include <fstream>
using namespace std;
#include "options.hpp"
#include "version.h"
int main(int argc, char * argv[]) {
ifstream theFile;
CmdLineOptions parsedOptions(argc, argv);
cout << "awg20400-lattice-gen " << GIT_VERSION << endl;
cout << "\nRunning via command: `" << argv[0] << "'" << endl;
if ( parsedOptions.getHelp() ) {
parsedOptions.printUsage();
return -1;
}
return 0;
}
<commit_msg>Main program: reads in file, processes<commit_after>#include <string>
#include <iostream>
#include <fstream>
using namespace std;
#include "options.hpp"
#include "version.h"
#include "latticePair.hpp"
int main(int argc, char * argv[]) {
ifstream theFile;
CmdLineOptions parsedOptions(argc, argv);
cout << "awg20400-lattice-gen " << GIT_VERSION << endl;
if ( parsedOptions.getDebug() ) {
cout << "Command invoked as: `" << argv[0];
for(int arg=1; arg<argc; arg++) {
cout << ' ' << argv[arg];
}
cout << "'\n";
}
if ( parsedOptions.getHelp() ) {
parsedOptions.printUsage();
return -1;
}
string inputFilePath("AWGSpec.csv");
if ( parsedOptions.getInputPath().size() > 0 ) inputFilePath = parsedOptions.getInputPath();
cout << "\nReading file from: " << inputFilePath << endl;
theFile.open(inputFilePath.c_str());
if (!theFile.is_open() || !theFile.good()) {
cerr << "Problem opening data file!" << endl;
theFile.close();
return -1;
}
string theLine;
unsigned int linesRead=0;
latticePair ourPair;
while( theFile.good() ) {
std::getline(theFile, theLine);
theFile.peek();
linesRead++;
ourPair.processLine(theLine);
if ( parsedOptions.getDebug() ) cout << linesRead << "\t| " << theLine << endl;
}
cout << "Done!" << endl;
string master, slave;
cout << "Getting master string" << endl;
master = ourPair.masterProgrammingString();
cout << "Getting slave string" << endl;
slave = ourPair.slaveProgrammingString();
cout << "Master Programming String:" << endl;
cout << master;
cout << endl << endl;
cout << "Slave Programming String:" << endl;
cout << slave;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright 2014 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_RCLCPP_UTILITIES_HPP_
#define RCLCPP_RCLCPP_UTILITIES_HPP_
// TODO(wjwwood): remove
#include <iostream>
#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <csignal>
#include <cstring>
#include <mutex>
#include <string.h>
#include <thread>
#include <rmw/error_handling.h>
#include <rmw/macros.h>
#include <rmw/rmw.h>
// Determine if sigaction is available
#if __APPLE__ || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#define HAS_SIGACTION
#endif
namespace
{
/// Represent the status of the global interrupt signal.
volatile sig_atomic_t g_signal_status = 0;
/// Guard condition for interrupting the rmw implementation when the global interrupt signal fired.
rmw_guard_condition_t * g_sigint_guard_cond_handle = \
rmw_create_guard_condition();
/// Condition variable for timed sleep (see sleep_for).
std::condition_variable g_interrupt_condition_variable;
std::atomic<bool> g_is_interrupted = false;
/// Mutex for protecting the global condition variable.
std::mutex g_interrupt_mutex;
#ifdef HAS_SIGACTION
struct sigaction old_action;
#else
void (* old_signal_handler)(int) = 0;
#endif
/// Handle the interrupt signal.
/** When the interrupt signal fires, the signal handler notifies the condition variable to wake up
* and triggers the interrupt guard condition, so that all global threads managed by rclcpp
* are interrupted.
*/
void
#ifdef HAS_SIGACTION
signal_handler(int signal_value, siginfo_t * siginfo, void * context)
#else
signal_handler(int signal_value)
#endif
{
// TODO(wjwwood): remove
std::cout << "signal_handler(" << signal_value << ")" << std::endl;
#ifdef HAS_SIGACTION
if (old_action.sa_flags & SA_SIGINFO) {
if (old_action.sa_sigaction != NULL) {
old_action.sa_sigaction(signal_value, siginfo, context);
}
} else {
// *INDENT-OFF*
if (
old_action.sa_handler != NULL && // Is set
old_action.sa_handler != SIG_DFL && // Is not default
old_action.sa_handler != SIG_IGN) // Is not ignored
// *INDENT-ON*
{
old_action.sa_handler(signal_value);
}
}
#else
if (old_signal_handler) {
old_signal_handler(signal_value);
}
#endif
g_signal_status = signal_value;
rmw_ret_t status = rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
if (status != RMW_RET_OK) {
fprintf(stderr,
"[rclcpp::error] failed to trigger guard condition: %s\n", rmw_get_error_string_safe());
}
g_is_interrupted.store(true);
g_interrupt_condition_variable.notify_all();
}
} // namespace
namespace rclcpp
{
RMW_THREAD_LOCAL size_t thread_id = 0;
namespace utilities
{
/// Initialize communications via the rmw implementation and set up a global signal handler.
/**
* \param[in] argc Number of arguments.
* \param[in] argv Argument vector. Will eventually be used for passing options to rclcpp.
*/
void
init(int argc, char * argv[])
{
(void)argc;
(void)argv;
g_is_interrupted.store(false);
rmw_ret_t status = rmw_init();
if (status != RMW_RET_OK) {
// *INDENT-OFF* (prevent uncrustify from making unecessary indents here)
throw std::runtime_error(
std::string("failed to initialize rmw implementation: ") + rmw_get_error_string_safe());
// *INDENT-ON*
}
#ifdef HAS_SIGACTION
struct sigaction action;
memset(&action, 0, sizeof(action));
sigemptyset(&action.sa_mask);
action.sa_sigaction = ::signal_handler;
action.sa_flags = SA_SIGINFO;
ssize_t ret = sigaction(SIGINT, &action, &old_action);
if (ret == -1)
#else
::old_signal_handler = std::signal(SIGINT, ::signal_handler);
if (::old_signal_handler == SIG_ERR)
#endif
{
const size_t error_length = 1024;
char error_string[error_length];
#ifndef _WIN32
strerror_r(errno, error_string, error_length);
#else
strerror_s(error_string, error_length, errno);
#endif
// *INDENT-OFF*
throw std::runtime_error(
std::string("Failed to set SIGINT signal handler: (" + std::to_string(errno) + ")") +
error_string);
// *INDENT-ON*
}
}
/// Check rclcpp's status.
// \return True if SIGINT hasn't fired yet, false otherwise.
bool
ok()
{
return ::g_signal_status == 0;
}
/// Notify the signal handler and rmw that rclcpp is shutting down.
void
shutdown()
{
g_signal_status = SIGINT;
rmw_ret_t status = rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
if (status != RMW_RET_OK) {
fprintf(stderr,
"[rclcpp::error] failed to trigger guard condition: %s\n", rmw_get_error_string_safe());
}
g_is_interrupted.store(true);
g_interrupt_condition_variable.notify_all();
}
/// Get a handle to the rmw guard condition that manages the signal handler.
rmw_guard_condition_t *
get_global_sigint_guard_condition()
{
return ::g_sigint_guard_cond_handle;
}
/// Use the global condition variable to block for the specified amount of time.
/**
* \param[in] nanoseconds A std::chrono::duration representing how long to sleep for.
* \return True if the condition variable did not timeout.
*/
bool
sleep_for(const std::chrono::nanoseconds & nanoseconds)
{
// TODO: determine if posix's nanosleep(2) is more efficient here
std::chrono::nanoseconds time_left = nanoseconds;
{
std::unique_lock<std::mutex> lock(::g_interrupt_mutex);
auto start = std::chrono::steady_clock::now();
::g_interrupt_condition_variable.wait_for(lock, nanoseconds);
time_left -= std::chrono::steady_clock::now() - start;
}
if (time_left > std::chrono::nanoseconds::zero() && !g_is_interrupted) {
return sleep_for(time_left);
}
// Return true if the timeout elapsed successfully, otherwise false.
return !g_is_interrupted;
}
} /* namespace utilities */
} /* namespace rclcpp */
#ifdef HAS_SIGACTION
#undef HAS_SIGACTION
#endif
#endif /* RCLCPP_RCLCPP_UTILITIES_HPP_ */
<commit_msg>fix deleted invocation of copy constructor on Linux<commit_after>// Copyright 2014 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef RCLCPP_RCLCPP_UTILITIES_HPP_
#define RCLCPP_RCLCPP_UTILITIES_HPP_
// TODO(wjwwood): remove
#include <iostream>
#include <cerrno>
#include <chrono>
#include <condition_variable>
#include <csignal>
#include <cstring>
#include <mutex>
#include <string.h>
#include <thread>
#include <rmw/error_handling.h>
#include <rmw/macros.h>
#include <rmw/rmw.h>
// Determine if sigaction is available
#if __APPLE__ || _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE
#define HAS_SIGACTION
#endif
namespace
{
/// Represent the status of the global interrupt signal.
volatile sig_atomic_t g_signal_status = 0;
/// Guard condition for interrupting the rmw implementation when the global interrupt signal fired.
rmw_guard_condition_t * g_sigint_guard_cond_handle = \
rmw_create_guard_condition();
/// Condition variable for timed sleep (see sleep_for).
std::condition_variable g_interrupt_condition_variable;
std::atomic<bool> g_is_interrupted(false);
/// Mutex for protecting the global condition variable.
std::mutex g_interrupt_mutex;
#ifdef HAS_SIGACTION
struct sigaction old_action;
#else
void (* old_signal_handler)(int) = 0;
#endif
/// Handle the interrupt signal.
/** When the interrupt signal fires, the signal handler notifies the condition variable to wake up
* and triggers the interrupt guard condition, so that all global threads managed by rclcpp
* are interrupted.
*/
void
#ifdef HAS_SIGACTION
signal_handler(int signal_value, siginfo_t * siginfo, void * context)
#else
signal_handler(int signal_value)
#endif
{
// TODO(wjwwood): remove
std::cout << "signal_handler(" << signal_value << ")" << std::endl;
#ifdef HAS_SIGACTION
if (old_action.sa_flags & SA_SIGINFO) {
if (old_action.sa_sigaction != NULL) {
old_action.sa_sigaction(signal_value, siginfo, context);
}
} else {
// *INDENT-OFF*
if (
old_action.sa_handler != NULL && // Is set
old_action.sa_handler != SIG_DFL && // Is not default
old_action.sa_handler != SIG_IGN) // Is not ignored
// *INDENT-ON*
{
old_action.sa_handler(signal_value);
}
}
#else
if (old_signal_handler) {
old_signal_handler(signal_value);
}
#endif
g_signal_status = signal_value;
rmw_ret_t status = rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
if (status != RMW_RET_OK) {
fprintf(stderr,
"[rclcpp::error] failed to trigger guard condition: %s\n", rmw_get_error_string_safe());
}
g_is_interrupted.store(true);
g_interrupt_condition_variable.notify_all();
}
} // namespace
namespace rclcpp
{
RMW_THREAD_LOCAL size_t thread_id = 0;
namespace utilities
{
/// Initialize communications via the rmw implementation and set up a global signal handler.
/**
* \param[in] argc Number of arguments.
* \param[in] argv Argument vector. Will eventually be used for passing options to rclcpp.
*/
void
init(int argc, char * argv[])
{
(void)argc;
(void)argv;
g_is_interrupted.store(false);
rmw_ret_t status = rmw_init();
if (status != RMW_RET_OK) {
// *INDENT-OFF* (prevent uncrustify from making unecessary indents here)
throw std::runtime_error(
std::string("failed to initialize rmw implementation: ") + rmw_get_error_string_safe());
// *INDENT-ON*
}
#ifdef HAS_SIGACTION
struct sigaction action;
memset(&action, 0, sizeof(action));
sigemptyset(&action.sa_mask);
action.sa_sigaction = ::signal_handler;
action.sa_flags = SA_SIGINFO;
ssize_t ret = sigaction(SIGINT, &action, &old_action);
if (ret == -1)
#else
::old_signal_handler = std::signal(SIGINT, ::signal_handler);
if (::old_signal_handler == SIG_ERR)
#endif
{
const size_t error_length = 1024;
char error_string[error_length];
#ifndef _WIN32
strerror_r(errno, error_string, error_length);
#else
strerror_s(error_string, error_length, errno);
#endif
// *INDENT-OFF*
throw std::runtime_error(
std::string("Failed to set SIGINT signal handler: (" + std::to_string(errno) + ")") +
error_string);
// *INDENT-ON*
}
}
/// Check rclcpp's status.
// \return True if SIGINT hasn't fired yet, false otherwise.
bool
ok()
{
return ::g_signal_status == 0;
}
/// Notify the signal handler and rmw that rclcpp is shutting down.
void
shutdown()
{
g_signal_status = SIGINT;
rmw_ret_t status = rmw_trigger_guard_condition(g_sigint_guard_cond_handle);
if (status != RMW_RET_OK) {
fprintf(stderr,
"[rclcpp::error] failed to trigger guard condition: %s\n", rmw_get_error_string_safe());
}
g_is_interrupted.store(true);
g_interrupt_condition_variable.notify_all();
}
/// Get a handle to the rmw guard condition that manages the signal handler.
rmw_guard_condition_t *
get_global_sigint_guard_condition()
{
return ::g_sigint_guard_cond_handle;
}
/// Use the global condition variable to block for the specified amount of time.
/**
* \param[in] nanoseconds A std::chrono::duration representing how long to sleep for.
* \return True if the condition variable did not timeout.
*/
bool
sleep_for(const std::chrono::nanoseconds & nanoseconds)
{
// TODO: determine if posix's nanosleep(2) is more efficient here
std::chrono::nanoseconds time_left = nanoseconds;
{
std::unique_lock<std::mutex> lock(::g_interrupt_mutex);
auto start = std::chrono::steady_clock::now();
::g_interrupt_condition_variable.wait_for(lock, nanoseconds);
time_left -= std::chrono::steady_clock::now() - start;
}
if (time_left > std::chrono::nanoseconds::zero() && !g_is_interrupted) {
return sleep_for(time_left);
}
// Return true if the timeout elapsed successfully, otherwise false.
return !g_is_interrupted;
}
} /* namespace utilities */
} /* namespace rclcpp */
#ifdef HAS_SIGACTION
#undef HAS_SIGACTION
#endif
#endif /* RCLCPP_RCLCPP_UTILITIES_HPP_ */
<|endoftext|> |
<commit_before>/*
This file is part of the PhantomJS project from Ofi Labs.
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
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 <organization> 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 <COPYRIGHT HOLDER> 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 "consts.h"
#include "utils.h"
#include "env.h"
#include "phantom.h"
#ifdef Q_OS_LINUX
#include "client/linux/handler/exception_handler.h"
#endif
#ifdef Q_OS_MAC
#include "client/mac/handler/exception_handler.h"
#endif
#include <QApplication>
#ifdef Q_OS_WIN32
#if !defined(QT_SHARED) && !defined(QT_DLL)
#include <QtPlugin>
// HACK: When linking a static PhantomJS + MSVC agains the
// static Qt included in PhantomJS, we get linker errors.
// This noop function can cure them.
#include <QUuid>
#include <QPainter>
#include <QXmlStreamAttributes>
void makeLinkerHappy()
{
QWidget().colorCount();
QUuid().createUuid();
QPainter().drawImage(QPointF(), QImage(), QRect());
const QXmlStreamAttributes foo;
foo[0];
}
// End of linker hack.
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
#endif
#endif
#if QT_VERSION != QT_VERSION_CHECK(4, 8, 2)
#error Something is wrong with the setup. Please report to the mailing list!
#endif
int main(int argc, char** argv, const char** envp)
{
// Setup Google Breakpad exception handler
#ifdef Q_OS_LINUX
google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true);
#endif
#ifdef Q_OS_MAC
google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true, NULL);
#endif
QApplication app(argc, argv);
app.setWindowIcon(QIcon(":/phantomjs-icon.png"));
app.setApplicationName("PhantomJS");
app.setOrganizationName("Ofi Labs");
app.setOrganizationDomain("www.ofilabs.com");
app.setApplicationVersion(PHANTOMJS_VERSION_STRING);
// Prepare the "env" singleton using the environment variables
Env::instance()->parse(envp);
// Get the Phantom singleton
Phantom *phantom = Phantom::instance();
// Registering an alternative Message Handler
Utils::printDebugMessages = phantom->printDebugMessages();
qInstallMsgHandler(Utils::messageHandler);
// Start script execution
if (phantom->execute()) {
app.exec();
}
// End script execution: delete the phantom singleton and set execution return value
int retVal = phantom->returnValue();
delete phantom;
return retVal;
}
<commit_msg>Make the msvc linker happy again.<commit_after>/*
This file is part of the PhantomJS project from Ofi Labs.
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
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 <organization> 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 <COPYRIGHT HOLDER> 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 "consts.h"
#include "utils.h"
#include "env.h"
#include "phantom.h"
#ifdef Q_OS_LINUX
#include "client/linux/handler/exception_handler.h"
#endif
#ifdef Q_OS_MAC
#include "client/mac/handler/exception_handler.h"
#endif
#include <QApplication>
#ifdef Q_OS_WIN32
#if !defined(QT_SHARED) && !defined(QT_DLL)
#include <QtPlugin>
// HACK: When linking a static PhantomJS + MSVC agains the
// static Qt included in PhantomJS, we get linker errors.
// This noop function can cure them.
#include <QUuid>
#include <QPainter>
#include <QXmlStreamAttributes>
#include <QFileDialog>
#include <QPainter>
#include <QToolTip>
#include <QStandardItem>
void makeLinkerHappy()
{
QWidget().colorCount();
QUuid().createUuid();
QPainter().drawImage(QPointF(), QImage(), QRect());
const QXmlStreamAttributes foo;
foo[0];
QFileDialog().getOpenFileName();
QPainter::staticMetaObject.indexOfMethod(0);
QToolTip::hideText();
QStandardItem standardItem;
standardItem.setForeground(QBrush());
standardItem.setBackground(QBrush());
standardItem.setToolTip(QString());
}
// End of linker hack.
Q_IMPORT_PLUGIN(qcncodecs)
Q_IMPORT_PLUGIN(qjpcodecs)
Q_IMPORT_PLUGIN(qkrcodecs)
Q_IMPORT_PLUGIN(qtwcodecs)
#endif
#endif
#if QT_VERSION != QT_VERSION_CHECK(4, 8, 2)
#error Something is wrong with the setup. Please report to the mailing list!
#endif
int main(int argc, char** argv, const char** envp)
{
// Setup Google Breakpad exception handler
#ifdef Q_OS_LINUX
google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true);
#endif
#ifdef Q_OS_MAC
google_breakpad::ExceptionHandler eh("/tmp", NULL, Utils::exceptionHandler, NULL, true, NULL);
#endif
QApplication app(argc, argv);
app.setWindowIcon(QIcon(":/phantomjs-icon.png"));
app.setApplicationName("PhantomJS");
app.setOrganizationName("Ofi Labs");
app.setOrganizationDomain("www.ofilabs.com");
app.setApplicationVersion(PHANTOMJS_VERSION_STRING);
// Prepare the "env" singleton using the environment variables
Env::instance()->parse(envp);
// Get the Phantom singleton
Phantom *phantom = Phantom::instance();
// Registering an alternative Message Handler
Utils::printDebugMessages = phantom->printDebugMessages();
qInstallMsgHandler(Utils::messageHandler);
// Start script execution
if (phantom->execute()) {
app.exec();
}
// End script execution: delete the phantom singleton and set execution return value
int retVal = phantom->returnValue();
delete phantom;
return retVal;
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <atomic>
#include <chrono>
#include <iostream>
#include "dll/rbm/rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
namespace {
constexpr const size_t K = 3;
template <typename C>
float distance_knn(const C& lhs, const C& rhs) {
return etl::sum((lhs - rhs) >> (lhs - rhs));
}
struct distance_t {
float dist;
uint32_t label;
};
size_t vote_knn(const std::vector<distance_t>& distances) {
size_t votes[10]{};
for (size_t k = 0; k < K; ++k) {
++votes[distances[k].label];
}
size_t label = 0;
for (size_t k = 1; k < 10; ++k) {
if (votes[k] > votes[label]) {
label = k;
}
}
return label;
}
template <typename C, typename L>
double evaluate_knn(const C& training, const C& test, const L& training_labels, const L& test_labels) {
std::atomic<size_t> correct;
correct = 0;
cpp::default_thread_pool<> pool(8);
cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
std::vector<distance_t> distances(training.size());
for (size_t j = 0; j < training.size(); ++j) {
float d = distance_knn(test[i], training[j]);
distances[j] = {d, training_labels[j]};
}
std::sort(distances.begin(), distances.end(), [](const distance_t& lhs, const distance_t& rhs) {
return lhs.dist < rhs.dist;
});
if (vote_knn(distances) == test_labels[i]) {
++correct;
}
});
return correct / double(test.size());
}
template <size_t I, typename N, typename D>
double evaluate_knn_net(const N& net, const D& dataset) {
std::vector<etl::dyn_vector<float>> training(dataset.training_images.size());
std::vector<etl::dyn_vector<float>> test(dataset.test_images.size());
cpp::default_thread_pool<> pool(8);
cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) {
training[i] = net->template features_sub<I>(dataset.training_images[i]);
});
cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
test[i] = net->template features_sub<I>(dataset.test_images[i]);
});
return evaluate_knn(training, test, dataset.training_labels, dataset.test_labels);
}
template <size_t I, typename Net, typename D>
void evaluate_net(size_t N, const Net& net, const D& dataset) {
std::cout << "__result__(KNN): dense_ae_" << N << ":" << evaluate_knn_net<I>(net, dataset) << std::endl;
}
template <typename R, typename D>
double evaluate_knn_rbm(const R& rbm, const D& dataset) {
std::vector<etl::dyn_vector<float>> training(dataset.training_images.size());
std::vector<etl::dyn_vector<float>> test(dataset.test_images.size());
cpp::default_thread_pool<> pool(8);
cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) {
training[i] = rbm->features(dataset.training_images[i]);
});
cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
test[i] = rbm->features(dataset.test_images[i]);
});
return evaluate_knn(training, test, dataset.training_labels, dataset.test_labels);
}
template <typename R, typename D>
void evaluate_rbm(size_t N, const R& rbm, const D& dataset) {
std::cout << "__result__: dense_rbm_" << N << ":" << evaluate_knn_rbm(rbm, dataset) << std::endl;
}
} // end of anonymous
int main(int argc, char* argv[]) {
std::string model = "raw";
if (argc > 1) {
model = argv[1];
}
auto dataset = mnist::read_dataset_direct<std::vector, etl::dyn_vector<float>>();
if (model == "raw") {
double accuracy = evaluate_knn(dataset.training_images, dataset.test_images, dataset.training_labels, dataset.test_labels);
std::cout << "Raw: " << accuracy << std::endl;
} else if (model == "dense") {
mnist::binarize_dataset(dataset);
static constexpr size_t epochs = 100;
static constexpr size_t batch_size = 100;
#define SINGLE_RBM(N) \
{ \
using rbm_t = dll::rbm_desc< \
28 * 28, N, \
dll::batch_size<batch_size>, \
dll::momentum>::layer_t; \
auto rbm = std::make_unique<rbm_t>(); \
rbm->learning_rate = 0.1; \
rbm->initial_momentum = 0.9; \
rbm->final_momentum = 0.9; \
auto error = rbm->train(dataset.training_images, epochs); \
std::cout << "pretrain_error:" << error << std::endl; \
evaluate_rbm(N, rbm, dataset); \
}
#define SINGLE_AE(N) \
{ \
using network_t = \
dll::dbn_desc<dll::dbn_layers<dll::dense_desc<28 * 28, N>::layer_t, \
dll::dense_desc<N, 28 * 28>::layer_t>, \
dll::momentum, dll::trainer<dll::sgd_trainer>, \
dll::batch_size<batch_size>>::dbn_t; \
auto ae = std::make_unique<network_t>(); \
ae->learning_rate = 0.1; \
ae->initial_momentum = 0.9; \
ae->final_momentum = 0.9; \
auto ft_error = ae->fine_tune_ae(dataset.training_images, epochs); \
std::cout << "ft_error:" << ft_error << std::endl; \
evaluate_net<1>(N, ae, dataset); \
}
SINGLE_RBM(50);
SINGLE_RBM(100);
SINGLE_RBM(200);
SINGLE_RBM(400);
SINGLE_RBM(600);
SINGLE_RBM(800);
SINGLE_RBM(1000);
SINGLE_AE(50);
SINGLE_AE(100);
SINGLE_AE(200);
SINGLE_AE(400);
SINGLE_AE(600);
SINGLE_AE(800);
SINGLE_AE(1000);
}
return 0;
}
<commit_msg>Cleanup<commit_after>//=======================================================================
// Copyright (c) 2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <atomic>
#include <chrono>
#include <iostream>
#include "dll/rbm/rbm.hpp"
#include "dll/dbn.hpp"
#include "dll/neural/dense_layer.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"
#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"
namespace {
constexpr const size_t K = 3;
template <typename C>
float distance_knn(const C& lhs, const C& rhs) {
return etl::sum((lhs - rhs) >> (lhs - rhs));
}
struct distance_t {
float dist;
uint32_t label;
};
size_t vote_knn(const std::vector<distance_t>& distances) {
size_t votes[10]{};
for (size_t k = 0; k < K; ++k) {
++votes[distances[k].label];
}
size_t label = 0;
for (size_t k = 1; k < 10; ++k) {
if (votes[k] > votes[label]) {
label = k;
}
}
return label;
}
template <typename C, typename L>
double evaluate_knn(const C& training, const C& test, const L& training_labels, const L& test_labels) {
std::atomic<size_t> correct;
correct = 0;
cpp::default_thread_pool<> pool(8);
cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
std::vector<distance_t> distances(training.size());
for (size_t j = 0; j < training.size(); ++j) {
float d = distance_knn(test[i], training[j]);
distances[j] = {d, training_labels[j]};
}
std::sort(distances.begin(), distances.end(), [](const distance_t& lhs, const distance_t& rhs) {
return lhs.dist < rhs.dist;
});
if (vote_knn(distances) == test_labels[i]) {
++correct;
}
});
return correct / double(test.size());
}
template <size_t I, typename N, typename D>
double evaluate_knn_net(const N& net, const D& ds) {
std::vector<etl::dyn_vector<float>> training(ds.training_images.size());
std::vector<etl::dyn_vector<float>> test(ds.test_images.size());
cpp::default_thread_pool<> pool(8);
cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) {
training[i] = net->template features_sub<I>(ds.training_images[i]);
});
cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
test[i] = net->template features_sub<I>(ds.test_images[i]);
});
return evaluate_knn(training, test, ds.training_labels, ds.test_labels);
}
template <size_t I, typename Net, typename D>
void evaluate_net(size_t N, const Net& net, const D& ds) {
std::cout << "__result__(KNN): dense_ae_" << N << ":" << evaluate_knn_net<I>(net, ds) << std::endl;
}
template <typename R, typename D>
double evaluate_knn_rbm(const R& rbm, const D& ds) {
std::vector<etl::dyn_vector<float>> training(ds.training_images.size());
std::vector<etl::dyn_vector<float>> test(ds.test_images.size());
cpp::default_thread_pool<> pool(8);
cpp::parallel_foreach_n(pool, 0, training.size(), [&](const size_t i) {
training[i] = rbm->features(ds.training_images[i]);
});
cpp::parallel_foreach_n(pool, 0, test.size(), [&](const size_t i) {
test[i] = rbm->features(ds.test_images[i]);
});
return evaluate_knn(training, test, ds.training_labels, ds.test_labels);
}
template <typename R, typename D>
void evaluate_rbm(size_t N, const R& rbm, const D& ds) {
std::cout << "__result__: dense_rbm_" << N << ":" << evaluate_knn_rbm(rbm, ds) << std::endl;
}
} // end of anonymous
int main(int argc, char* argv[]) {
std::string model = "raw";
if (argc > 1) {
model = argv[1];
}
auto ds = mnist::read_dataset_direct<std::vector, etl::dyn_vector<float>>();
if (model == "raw") {
std::cout << "Raw(KNN): " << evaluate_knn(ds.training_images, ds.test_images, ds.training_labels, ds.test_labels) << std::endl;
} else if (model == "dense") {
mnist::binarize_dataset(ds);
static constexpr size_t epochs = 100;
static constexpr size_t batch_size = 100;
#define SINGLE_RBM(N) \
{ \
using rbm_t = dll::rbm_desc< \
28 * 28, N, \
dll::batch_size<batch_size>, \
dll::momentum>::layer_t; \
auto rbm = std::make_unique<rbm_t>(); \
rbm->learning_rate = 0.1; \
rbm->initial_momentum = 0.9; \
rbm->final_momentum = 0.9; \
auto error = rbm->train(ds.training_images, epochs); \
std::cout << "pretrain_error:" << error << std::endl; \
evaluate_rbm(N, rbm, ds); \
}
#define SINGLE_AE(N) \
{ \
using network_t = \
dll::dbn_desc<dll::dbn_layers<dll::dense_desc<28 * 28, N>::layer_t, \
dll::dense_desc<N, 28 * 28>::layer_t>, \
dll::momentum, dll::trainer<dll::sgd_trainer>, \
dll::batch_size<batch_size>>::dbn_t; \
auto ae = std::make_unique<network_t>(); \
ae->learning_rate = 0.1; \
ae->initial_momentum = 0.9; \
ae->final_momentum = 0.9; \
auto ft_error = ae->fine_tune_ae(ds.training_images, epochs); \
std::cout << "ft_error:" << ft_error << std::endl; \
evaluate_net<1>(N, ae, ds); \
}
SINGLE_RBM(50);
SINGLE_RBM(100);
SINGLE_RBM(200);
SINGLE_RBM(400);
SINGLE_RBM(600);
SINGLE_RBM(800);
SINGLE_RBM(1000);
SINGLE_AE(50);
SINGLE_AE(100);
SINGLE_AE(200);
SINGLE_AE(400);
SINGLE_AE(600);
SINGLE_AE(800);
SINGLE_AE(1000);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <Arduino.h>
#include <avr/wdt.h>
#include <TinyGPS++.h>
#include <idDHT11.h>
#include <SDCard.h>
#include <Utils.h>
#include <PinMap.h>
#ifdef DEBUG
#include <MemoryFree.h>
#include <SoftwareSerial.h>
SoftwareSerial gpsSerial(8, 9);
#endif
SDCard sd(SD_PIN);
TinyGPSPlus gps;
Utils utils;
bool firstEntry = true;
char fileName [11];
int ledState = LOW;
/**
* initialize dht as on library documentation
* @see https://github.com/niesteszeck/idDHT11/blob/master/examples/idDHT11_Lib_example/idDHT11_Lib_example.ino
* @see https://www.arduino.cc/en/Reference/AttachInterrupt
*/
void dht11_wrapper();
idDHT11 dht(DHT_PIN, 1, dht11_wrapper);
void dht11_wrapper() {
dht.isrCallback();
}
/**
* wrap all data together to be appended to csv log file
*/
void serialize(char* entry) {
while(dht.acquiring());
int result = dht.getStatus();
if (result != IDDHTLIB_OK) {
#ifdef DEBUG
dht.printError(result);
#endif
} else {
// save new values
dht.saveLastValidData();
}
sprintf(
entry,
"%i,%i,%i,%i,%0.6f,%0.6f,%0.2f",
utils.readMQ(MQ2_PIN), utils.readMQ(MQ135_PIN),
(int)dht.getLastValidCelsius(), (int)dht.getLastValidHumidity(),
gps.location.lat(), gps.location.lng(), gps.altitude.meters()
);
}
void createFileName(char *str) {
// limited to 8.3 file format https://en.wikipedia.org/wiki/8.3_filename
// so .csv was removed
sprintf(str, "%d-%d-%d", gps.date.day(), gps.time.hour(), gps.time.minute());
}
/**
* delay while keep reading gps data
*/
void smartDelay(const unsigned long &delay) {
unsigned long initialTime = millis();
unsigned long currentTime;
do {
#ifdef DEBUG
if (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
#else
if (Serial.available() > 0) {
gps.encode(Serial.read());
#endif
}
currentTime = millis();
} while (currentTime - initialTime < delay);
}
void setup() {
Serial.begin(9600);
#ifdef DEBUG
Serial.println(F("setup: initializing sensor platform..."));
gpsSerial.begin(9600);
#endif
// setup control led
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// enable watchdog with 2 seconds timer
wdt_enable(WDTO_2S);
if(!sd.begin()) {
utils.error("setup: sd could not begin!");
}
// start acquiring first value, result is interrupt driven
// the dht sensor is having issues since the soldering on the board,
// this is a tmeporary work around to get valid values
if (dht.acquireAndWait() != IDDHTLIB_OK) {
utils.error("setup: dht could not acquire proper data!");
} else {
dht.saveLastValidData();
}
#ifdef DEBUG
Serial.println(F("setup: initialization went okay!"));
#endif
}
void loop() {
smartDelay(255);
if (firstEntry && gps.date.isValid() && gps.location.isValid()) {
// if valid state is entered, led is on
digitalWrite(LED_PIN, HIGH);
createFileName(fileName);
if (sd.exists(fileName)) {
#ifdef DEBUG
Serial.print(F("appending to file "));
Serial.println(fileName);
#endif
firstEntry = false;
} else {
#ifdef DEBUG
Serial.print(F("new log file "));
Serial.println(fileName);
#endif
firstEntry = false;
}
}
if (!firstEntry && gps.location.isValid()) {
// if valid state is entered, led is on
digitalWrite(LED_PIN, HIGH);
if (gps.location.isUpdated()) {
// get new dht value
dht.acquire();
char entry [40];
serialize(entry);
#ifdef DEBUG
Serial.println(entry);
#endif
if (!sd.writeToFile(fileName, entry)) {
utils.error("could not write data to file");
}
}
} else {
// blink for invalid gps data
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_PIN, ledState);
}
// reset watchdog timer
wdt_reset();
}
<commit_msg>add time to file entries, save data whenever location is valid<commit_after>#include <Arduino.h>
#include <avr/wdt.h>
#include <TinyGPS++.h>
#include <idDHT11.h>
#include <SDCard.h>
#include <Utils.h>
#include <PinMap.h>
#ifdef DEBUG
#include <MemoryFree.h>
#include <SoftwareSerial.h>
SoftwareSerial gpsSerial(8, 9);
#endif
SDCard sd(SD_PIN);
TinyGPSPlus gps;
Utils utils;
bool firstEntry = true;
char fileName [11];
int ledState = LOW;
/**
* initialize dht as on library documentation
* @see https://github.com/niesteszeck/idDHT11/blob/master/examples/idDHT11_Lib_example/idDHT11_Lib_example.ino
* @see https://www.arduino.cc/en/Reference/AttachInterrupt
*/
void dht11_wrapper();
idDHT11 dht(DHT_PIN, 1, dht11_wrapper);
void dht11_wrapper() {
dht.isrCallback();
}
/**
* wrap all data together to be appended to csv log file
*/
void serialize(char* entry) {
while(dht.acquiring());
int result = dht.getStatus();
if (result != IDDHTLIB_OK) {
#ifdef DEBUG
dht.printError(result);
#endif
} else {
// save new values
dht.saveLastValidData();
}
sprintf(
entry,
"%i,%i,%i,%i,%0.6f,%0.6f,%0.2f,%lu",
utils.readMQ(MQ2_PIN), utils.readMQ(MQ135_PIN),
(int)dht.getLastValidCelsius(), (int)dht.getLastValidHumidity(),
gps.location.lat(), gps.location.lng(), gps.altitude.meters(),
gps.time.value()
);
}
void createFileName(char *str) {
// limited to 8.3 file format https://en.wikipedia.org/wiki/8.3_filename
// so .csv was removed
sprintf(str, "%d-%d-%d", gps.date.day(), gps.time.hour(), gps.time.minute());
}
/**
* delay while keep reading gps data
*/
void smartDelay(const unsigned long &delay) {
unsigned long initialTime = millis();
unsigned long currentTime;
do {
#ifdef DEBUG
if (gpsSerial.available() > 0) {
gps.encode(gpsSerial.read());
#else
if (Serial.available() > 0) {
gps.encode(Serial.read());
#endif
}
currentTime = millis();
} while (currentTime - initialTime < delay);
}
void setup() {
Serial.begin(9600);
#ifdef DEBUG
Serial.println(F("setup: initializing sensor platform..."));
gpsSerial.begin(9600);
#endif
// setup control led
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// enable watchdog with 2 seconds timer
wdt_enable(WDTO_2S);
if(!sd.begin()) {
utils.error("setup: sd could not begin!");
}
// start acquiring first value, result is interrupt driven
// the dht sensor is having issues since the soldering on the board,
// this is a tmeporary work around to get valid values
if (dht.acquireAndWait() != IDDHTLIB_OK) {
utils.error("setup: dht could not acquire proper data!");
} else {
dht.saveLastValidData();
}
#ifdef DEBUG
Serial.println(F("setup: initialization went okay!"));
#endif
}
void loop() {
smartDelay(255);
if (firstEntry && gps.date.isValid() && gps.location.isValid()) {
// if valid state is entered, led is on
digitalWrite(LED_PIN, HIGH);
createFileName(fileName);
if (sd.exists(fileName)) {
#ifdef DEBUG
Serial.print(F("appending to file "));
Serial.println(fileName);
#endif
firstEntry = false;
} else {
#ifdef DEBUG
Serial.print(F("new log file "));
Serial.println(fileName);
#endif
firstEntry = false;
}
}
if (!firstEntry && gps.location.isValid()) {
// if valid state is entered, led is on
digitalWrite(LED_PIN, HIGH);
// get new dht value
dht.acquire();
char entry [40];
serialize(entry);
#ifdef DEBUG
Serial.println(entry);
#endif
if (!sd.writeToFile(fileName, entry)) {
utils.error("could not write data to file");
}
} else {
// blink for invalid gps data
if (ledState == LOW) {
ledState = HIGH;
} else {
ledState = LOW;
}
digitalWrite(LED_PIN, ledState);
}
// reset watchdog timer
wdt_reset();
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016, Mike Tzou
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 foo_xspf_1 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 HOLDER 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 "stdafx.h"
#include "main.h"
#include "helper.h"
#define PLUGIN_NAME "XSPF Playlist"
#define PLUGIN_VERSION "2.6.2"
DECLARE_COMPONENT_VERSION
(
PLUGIN_NAME , PLUGIN_VERSION ,
PLUGIN_NAME"\n"
"Compiled on: "__DATE__"\n"
"https://github.com/Chocobo1/foo_xspf_1\n"
"This plugin is released under BSD 3-Clause license\n"
"\n"
"Mike Tzou (Chocobo1)\n"
"\n"
"This plugin links statically with the following open source library:\n"
"TinyXML-2, http://www.grinninglizard.com/tinyxml2/\n"
);
const char *xspf::get_extension()
{
return "xspf";
}
bool xspf::is_our_content_type( const char *p_content_type )
{
const char mime[] = "application/xspf+xml";
if( strcmp( p_content_type , mime ) != 0 )
return false;
return true;
}
bool xspf::is_associatable()
{
return true;
}
bool xspf::can_write()
{
return true;
}
void xspf::open( const char *p_path , const service_ptr_t<file> &p_file , playlist_loader_callback::ptr p_callback , abort_callback &p_abort )
{
// avoid file open loop
if( file_list.find( p_path ) != file_list.cend() )
return;
file_list.emplace( p_path );
pfc::hires_timer t;
t.start();
try
{
p_callback->on_progress( p_path );
open_helper( p_path , p_file , p_callback , p_abort );
}
catch( ... )
{
file_list.erase( p_path );
throw;
}
console::printf( CONSOLE_HEADER"Read time: %s, %s" , t.queryString().toString() , p_path );
file_list.erase( p_path );
return;
}
void xspf::write( const char *p_path , const service_ptr_t<file> &p_file , metadb_handle_list_cref p_data , abort_callback &p_abort )
{
pfc::hires_timer t;
t.start();
write_helper( p_path , p_file , p_data , p_abort );
console::printf( CONSOLE_HEADER"Write time: %s, %s" , t.queryString().toString() , p_path );
return;
}
<commit_msg>bump version<commit_after>/*
Copyright (c) 2016, Mike Tzou
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 foo_xspf_1 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 HOLDER 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 "stdafx.h"
#include "main.h"
#include "helper.h"
#define PLUGIN_NAME "XSPF Playlist"
#define PLUGIN_VERSION "2.6.3"
DECLARE_COMPONENT_VERSION
(
PLUGIN_NAME , PLUGIN_VERSION ,
PLUGIN_NAME"\n"
"Compiled on: "__DATE__"\n"
"https://github.com/Chocobo1/foo_xspf_1\n"
"This plugin is released under BSD 3-Clause license\n"
"\n"
"Mike Tzou (Chocobo1)\n"
"\n"
"This plugin links statically with the following open source library:\n"
"TinyXML-2, http://www.grinninglizard.com/tinyxml2/\n"
);
const char *xspf::get_extension()
{
return "xspf";
}
bool xspf::is_our_content_type( const char *p_content_type )
{
const char mime[] = "application/xspf+xml";
if( strcmp( p_content_type , mime ) != 0 )
return false;
return true;
}
bool xspf::is_associatable()
{
return true;
}
bool xspf::can_write()
{
return true;
}
void xspf::open( const char *p_path , const service_ptr_t<file> &p_file , playlist_loader_callback::ptr p_callback , abort_callback &p_abort )
{
// avoid file open loop
if( file_list.find( p_path ) != file_list.cend() )
return;
file_list.emplace( p_path );
pfc::hires_timer t;
t.start();
try
{
p_callback->on_progress( p_path );
open_helper( p_path , p_file , p_callback , p_abort );
}
catch( ... )
{
file_list.erase( p_path );
throw;
}
console::printf( CONSOLE_HEADER"Read time: %s, %s" , t.queryString().toString() , p_path );
file_list.erase( p_path );
return;
}
void xspf::write( const char *p_path , const service_ptr_t<file> &p_file , metadb_handle_list_cref p_data , abort_callback &p_abort )
{
pfc::hires_timer t;
t.start();
write_helper( p_path , p_file , p_data , p_abort );
console::printf( CONSOLE_HEADER"Write time: %s, %s" , t.queryString().toString() , p_path );
return;
}
<|endoftext|> |
<commit_before>#define DISTANCECMCRITICAL 20
#define DISTANCECMWARNING 30
#define PUBLSIHINTERVAL 1000
#define TRYFOLLOWLINEINTERVAL 3000
#define WAITINTERVAL 5000
#define MOVESPEED 100
#include <Arduino.h>
#include <Streaming.h>
#include <ArduinoJson.h>
#include <MeMCore.h>
enum direction { STOP, FORWARD, BACKWARD, LEFT, RIGHT } moveDirection = STOP;
MeDCMotor motorL(M1);
MeDCMotor motorR(M2);
MeLineFollower lineFollower(PORT_2);
MeTemperature temperature(PORT_4, SLOT2);
MeUltrasonicSensor ultrasonicSensor(PORT_3);
MeLightSensor lightSensor(PORT_6);
MeIR ir;
MeRGBLed rgbLed(PORT_7, 2);
MeBuzzer buzzer;
int moveSpeed = 100;
int lineFollowFlag = 0;
bool start = false;
bool makeNoise = false;
bool obstacle = false;
unsigned long publishTimer = millis();
bool wait = false;
unsigned long waitTimer = millis();
bool tryFollowLine = true;
unsigned long tryFollowLineTimer = millis();
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
void forward() {
motorL.run(-MOVESPEED);
motorR.run(MOVESPEED);
}
void backward() {
motorL.run(MOVESPEED);
motorR.run(-MOVESPEED);
}
void turnLeft() {
motorL.run(-MOVESPEED / 10);
motorR.run(MOVESPEED);
}
void turnRight() {
motorL.run(-MOVESPEED);
motorR.run(MOVESPEED / 10);
}
void stop() {
moveDirection = STOP;
motorL.run(0);
motorR.run(0);
}
bool distanceWarning(double distanceCmLimit) {
if (ultrasonicSensor.distanceCm() < distanceCmLimit) {
return true;
} else {
return false;
}
}
void move() {
if (distanceWarning(DISTANCECMCRITICAL)) {
if (moveDirection == BACKWARD) {
backward();
} else {
stop();
}
} else {
switch (moveDirection) {
case FORWARD:
forward();
break;
case BACKWARD:
backward();
break;
case LEFT:
turnLeft();
break;
case RIGHT:
turnRight();
break;
case STOP:
stop();
break;
}
}
}
void toggleStart() {
start = !start;
if (start) {
rgbLed.setColor(1, 0, 10, 0);
rgbLed.show();
} else {
rgbLed.setColor(1, 0, 0, 0);
rgbLed.show();
moveDirection = STOP;
}
delay(250);
}
void bottomCheck() {
if (analogRead(A7) == 0) {
toggleStart();
}
}
void irCheck() {
unsigned long value;
if (ir.decode()) {
value = ir.value;
switch (value >> 16 & 0xff) {
case IR_BUTTON_LEFT:
moveDirection = LEFT;
break;
case IR_BUTTON_RIGHT:
moveDirection = RIGHT;
break;
case IR_BUTTON_DOWN:
moveDirection = BACKWARD;
break;
case IR_BUTTON_UP:
moveDirection = FORWARD;
break;
case IR_BUTTON_SETTING:
moveDirection = STOP;
break;
case IR_BUTTON_A:
toggleStart();
break;
}
}
}
void silent() {
buzzer.noTone();
rgbLed.setColor(2, 0, 0, 0);
rgbLed.show();
}
void warning() {
rgbLed.setColor(2, 0, 0, 10);
rgbLed.show();
}
void alarm() {
//buzzer.tone(262, 100);
rgbLed.setColor(2, 10, 0, 0);
rgbLed.show();
}
void noiseCheck() {
if (start and distanceWarning(DISTANCECMCRITICAL)) {
if (wait == false) {
wait = true;
waitTimer = millis();
}
if (wait and millis() - waitTimer > WAITINTERVAL) {
makeNoise = true;
alarm();
} else {
warning();
}
} else {
wait = false;
makeNoise = false;
silent();
}
}
void autonomous() {
byte randNumber;
randomSeed(analogRead(6));
randNumber = random(2);
if (!distanceWarning(DISTANCECMCRITICAL) and !obstacle) {
moveDirection = FORWARD;
} else {
obstacle = true;
}
if (obstacle) {
if (distanceWarning(DISTANCECMWARNING)) {
moveDirection = BACKWARD;
} else {
switch (randNumber) {
case 0:
moveDirection = LEFT;
turnLeft();
delay(400);
break;
case 1:
moveDirection = RIGHT;
turnRight();
delay(400);
break;
}
obstacle = false;
}
}
}
void sendData() {
if (millis() - publishTimer > PUBLSIHINTERVAL) {
publishTimer = millis();
root["start"] = start;
root["moveDirection"] = moveDirection;
root["wait"] = wait;
root["makeNoise"] = makeNoise;
root["distanceCm"] = ultrasonicSensor.distanceCm();
root["lightSensor"] = lightSensor.read();
root["temperature"] = temperature.temperature();
root.prettyPrintTo(Serial);
Serial << endl;
}
}
void setup() {
Serial.begin(115200);
Serial << endl << endl;
pinMode(A7, INPUT);
ir.begin();
rgbLed.setColor(0, 0, 0, 0);
rgbLed.show();
}
void loop() {
bottomCheck();
irCheck();
noiseCheck();
sendData();
move();
if (start) {
switch (lineFollower.readSensors()) {
case S1_IN_S2_IN:
tryFollowLine = true;
moveDirection = FORWARD;
lineFollowFlag = 10;
break;
case S1_IN_S2_OUT:
tryFollowLine = true;
moveDirection = FORWARD;
if (lineFollowFlag > 1) lineFollowFlag--;
break;
case S1_OUT_S2_IN:
tryFollowLine = true;
moveDirection = FORWARD;
if (lineFollowFlag < 20) lineFollowFlag++;
break;
case S1_OUT_S2_OUT:
if (tryFollowLine) {
tryFollowLine = !tryFollowLine;
tryFollowLineTimer = millis();
}
if (millis() - tryFollowLineTimer < TRYFOLLOWLINEINTERVAL) {
if (lineFollowFlag == 10) moveDirection = BACKWARD;
if (lineFollowFlag < 10) moveDirection = LEFT;
if (lineFollowFlag > 10) moveDirection = RIGHT;
} else {
autonomous();
}
break;
}
}
}
<commit_msg>started pir support<commit_after>#define DISTANCECMCRITICAL 20
#define DISTANCECMWARNING 30
#define PUBLSIHINTERVAL 1000
#define TRYFOLLOWLINEINTERVAL 3000
#define WAITINTERVAL 5000
#define MOVESPEED 100
#include <Arduino.h>
#include <Streaming.h>
#include <ArduinoJson.h>
#include <MeMCore.h>
enum direction { STOP, FORWARD, BACKWARD, LEFT, RIGHT } moveDirection = STOP;
MeDCMotor motorL(M1);
MeDCMotor motorR(M2);
MeLineFollower lineFollower(PORT_2);
MeTemperature temperature(PORT_4, SLOT2);
MeUltrasonicSensor ultrasonicSensor(PORT_3);
MeLightSensor lightSensor(PORT_6);
MeIR ir;
MeRGBLed rgbLed(PORT_7, 2);
MeBuzzer buzzer;
MePIRMotionSensor pirMotionSensor(PORT_1);
int moveSpeed = 100;
int lineFollowFlag = 0;
bool start = false;
bool makeNoise = false;
bool obstacle = false;
unsigned long publishTimer = millis();
bool wait = false;
unsigned long waitTimer = millis();
bool tryFollowLine = true;
unsigned long tryFollowLineTimer = millis();
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
void forward() {
motorL.run(-MOVESPEED);
motorR.run(MOVESPEED);
}
void backward() {
motorL.run(MOVESPEED);
motorR.run(-MOVESPEED);
}
void turnLeft() {
motorL.run(-MOVESPEED / 10);
motorR.run(MOVESPEED);
}
void turnRight() {
motorL.run(-MOVESPEED);
motorR.run(MOVESPEED / 10);
}
void stop() {
moveDirection = STOP;
motorL.run(0);
motorR.run(0);
}
bool distanceWarning(double distanceCmLimit) {
if (ultrasonicSensor.distanceCm() < distanceCmLimit) {
return true;
} else {
return false;
}
}
void move() {
if (distanceWarning(DISTANCECMCRITICAL)) {
if (moveDirection == BACKWARD) {
backward();
} else {
stop();
}
} else {
switch (moveDirection) {
case FORWARD:
forward();
break;
case BACKWARD:
backward();
break;
case LEFT:
turnLeft();
break;
case RIGHT:
turnRight();
break;
case STOP:
stop();
break;
}
}
}
void toggleStart() {
start = !start;
if (start) {
rgbLed.setColor(1, 0, 10, 0);
rgbLed.show();
} else {
rgbLed.setColor(1, 0, 0, 0);
rgbLed.show();
moveDirection = STOP;
}
delay(250);
}
void bottomCheck() {
if (analogRead(A7) == 0) {
toggleStart();
}
}
void irCheck() {
unsigned long value;
if (ir.decode()) {
value = ir.value;
switch (value >> 16 & 0xff) {
case IR_BUTTON_LEFT:
moveDirection = LEFT;
break;
case IR_BUTTON_RIGHT:
moveDirection = RIGHT;
break;
case IR_BUTTON_DOWN:
moveDirection = BACKWARD;
break;
case IR_BUTTON_UP:
moveDirection = FORWARD;
break;
case IR_BUTTON_SETTING:
moveDirection = STOP;
break;
case IR_BUTTON_A:
toggleStart();
break;
}
}
}
void silent() {
buzzer.noTone();
rgbLed.setColor(2, 0, 0, 0);
rgbLed.show();
}
void warning() {
rgbLed.setColor(2, 0, 0, 10);
rgbLed.show();
}
void alarm() {
//buzzer.tone(262, 100);
rgbLed.setColor(2, 10, 0, 0);
rgbLed.show();
}
void noiseCheck() {
if (start and distanceWarning(DISTANCECMCRITICAL)) {
if (wait == false) {
wait = true;
waitTimer = millis();
}
if (wait and millis() - waitTimer > WAITINTERVAL) {
makeNoise = true;
alarm();
} else {
warning();
}
} else {
wait = false;
makeNoise = false;
silent();
}
}
void autonomous() {
byte randNumber;
randomSeed(analogRead(6));
randNumber = random(2);
if (!distanceWarning(DISTANCECMCRITICAL) and !obstacle) {
moveDirection = FORWARD;
} else {
obstacle = true;
}
if (obstacle) {
if (distanceWarning(DISTANCECMWARNING)) {
moveDirection = BACKWARD;
} else {
switch (randNumber) {
case 0:
moveDirection = LEFT;
turnLeft();
delay(400);
break;
case 1:
moveDirection = RIGHT;
turnRight();
delay(400);
break;
}
obstacle = false;
}
}
}
void sendData() {
if (millis() - publishTimer > PUBLSIHINTERVAL) {
publishTimer = millis();
root["start"] = start;
root["moveDirection"] = moveDirection;
root["wait"] = wait;
root["makeNoise"] = makeNoise;
root["distanceCm"] = ultrasonicSensor.distanceCm();
root["lightSensor"] = lightSensor.read();
root["temperature"] = temperature.temperature();
root["isHumanDetected"] = pirMotionSensor.isHumanDetected();
root.prettyPrintTo(Serial);
Serial << endl;
}
}
void setup() {
Serial.begin(115200);
Serial << endl << endl;
pinMode(A7, INPUT);
ir.begin();
pirMotionSensor.SetPirMotionMode(1);
rgbLed.setColor(0, 0, 0, 0);
rgbLed.show();
}
void loop() {
bottomCheck();
irCheck();
noiseCheck();
sendData();
move();
if (start) {
switch (lineFollower.readSensors()) {
case S1_IN_S2_IN:
tryFollowLine = true;
moveDirection = FORWARD;
lineFollowFlag = 10;
break;
case S1_IN_S2_OUT:
tryFollowLine = true;
moveDirection = FORWARD;
if (lineFollowFlag > 1) lineFollowFlag--;
break;
case S1_OUT_S2_IN:
tryFollowLine = true;
moveDirection = FORWARD;
if (lineFollowFlag < 20) lineFollowFlag++;
break;
case S1_OUT_S2_OUT:
if (tryFollowLine) {
tryFollowLine = !tryFollowLine;
tryFollowLineTimer = millis();
}
if (millis() - tryFollowLineTimer < TRYFOLLOWLINEINTERVAL) {
if (lineFollowFlag == 10) moveDirection = BACKWARD;
if (lineFollowFlag < 10) moveDirection = LEFT;
if (lineFollowFlag > 10) moveDirection = RIGHT;
} else {
autonomous();
}
break;
}
}
}
<|endoftext|> |
<commit_before>/*
* main.cpp
* FaffoCue
*
* Copyright (C) Simon Harris 2010-2013.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// This is very rough-and-ready main.cpp, until we can get the mainloop
// integrated with Cocoa and Winforms/WPF.
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <math.h>
#include <iostream>
#include <TCLAP/CmdLine.h>
#include <sstream>
////////////////////////////////////////////////////////////
// FaffoCue headers
////////////////////////////////////////////////////////////
#include "Text.hpp"
#include "Keys.hpp"
#include "Resources.hpp"
#include "App.hpp"
namespace fcmain
{
unsigned int resWidth, resHeight;
bool fullscreen;
std::string script_file, font_file;
double font_size;
////////////////////////////////////////////////////////////
// Command-line argument parsing
//
// -t --font: font name
// -z --font-size
// -r --resolution: screen resolution
// -f --fullscreen: overrides resolution
// -w --windowed: in case fullscreen is somehow the default
// unlabeled: autocue script (extension .fcx for xml, .fct for text)
////////////////////////////////////////////////////////////
void parse_cmdline(int argc, char *argv[])
{
try {
TCLAP::CmdLine cmd("These command-line arguments are not recommended for production setups.", ' ', "3.0");
TCLAP::ValueArg<std::string>
resolution("r", "resolution", "Screen resolution", true, "!", "<number>x<number>", cmd),
font_file("t", "font", "Font names", true, "!", "string", cmd);
TCLAP::ValueArg<float>
font_size("z", "font-size", "Font size", false, 48.f, "positive number", cmd);
TCLAP::SwitchArg
fullscreen("f", "fullscreen", "Fullscreen", cmd),
windowed("w", "windowed", "Windowed", cmd, true);
TCLAP::UnlabeledValueArg<std::string>
script_file("script-file", "Autocue script to load", false, "", "file path");
cmd.parse(argc, argv);
// fc-specific parsing time
fcmain::fullscreen = fullscreen.getValue() && !windowed.getValue();
fcmain::font_file = font_file.getValue();
fcmain::font_size = font_size.getValue();
fcmain::script_file = script_file.getValue();
{
std::stringstream ss(resolution.getValue());
char dummy;
/* try: */ ss >> fcmain::resWidth >> dummy >> fcmain::resHeight;
if (!ss) throw TCLAP::ArgException("Bad resolution format (should be <number>x<number>)", "resolution");
}
}
catch (TCLAP::ArgException& e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
exit(1);
}
}
}; // ns
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
//fcmain::parse_cmdline(argc, argv);
// @HACK@
fcmain::resWidth = 800; fcmain::resHeight = 600;
fcmain::font_size = 14.f;
fcmain::fullscreen = false;
//sf::RenderWindow App(sf::VideoMode(640, 480), "FaffoCue");
FaffoCue::App app(sf::VideoMode(fcmain::resWidth, fcmain::resHeight), false, false, fcmain::font_size);
//App.SetFramerateLimit(60);
//App.UseVerticalSync(true);
// sf::Font fnt;
fcmain::font_file = FaffoCue::_impl::resources_location() + "/AurulentSans-Bold.otf"; // @HACK@
app.font().loadFromFile(fcmain::font_file);
app.text().add_line("The quick brown fox jumps over the lazy dog. And here's another sentence because the last one wasn't really long enough to test the word wrap thoroughly. But this should be okay.");
app.text().add_line("And now, for a limited time only, a second line of text!");
// sf::View &cxView = app.cx().GetDefaultView();
// const sf::Input &cxInput = app.cx().GetInput();
double x = 0;
bool fullscreen = false;
app.main();
return EXIT_SUCCESS;
}
<commit_msg>Added extra line to sample text<commit_after>/*
* main.cpp
* FaffoCue
*
* Copyright (C) Simon Harris 2010-2013.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
// This is very rough-and-ready main.cpp, until we can get the mainloop
// integrated with Cocoa and Winforms/WPF.
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics.hpp>
#include <math.h>
#include <iostream>
#include <TCLAP/CmdLine.h>
#include <sstream>
////////////////////////////////////////////////////////////
// FaffoCue headers
////////////////////////////////////////////////////////////
#include "Text.hpp"
#include "Keys.hpp"
#include "Resources.hpp"
#include "App.hpp"
namespace fcmain
{
unsigned int resWidth, resHeight;
bool fullscreen;
std::string script_file, font_file;
double font_size;
////////////////////////////////////////////////////////////
// Command-line argument parsing
//
// -t --font: font name
// -z --font-size
// -r --resolution: screen resolution
// -f --fullscreen: overrides resolution
// -w --windowed: in case fullscreen is somehow the default
// unlabeled: autocue script (extension .fcx for xml, .fct for text)
////////////////////////////////////////////////////////////
void parse_cmdline(int argc, char *argv[])
{
try {
TCLAP::CmdLine cmd("These command-line arguments are not recommended for production setups.", ' ', "3.0");
TCLAP::ValueArg<std::string>
resolution("r", "resolution", "Screen resolution", true, "!", "<number>x<number>", cmd),
font_file("t", "font", "Font names", true, "!", "string", cmd);
TCLAP::ValueArg<float>
font_size("z", "font-size", "Font size", false, 48.f, "positive number", cmd);
TCLAP::SwitchArg
fullscreen("f", "fullscreen", "Fullscreen", cmd),
windowed("w", "windowed", "Windowed", cmd, true);
TCLAP::UnlabeledValueArg<std::string>
script_file("script-file", "Autocue script to load", false, "", "file path");
cmd.parse(argc, argv);
// fc-specific parsing time
fcmain::fullscreen = fullscreen.getValue() && !windowed.getValue();
fcmain::font_file = font_file.getValue();
fcmain::font_size = font_size.getValue();
fcmain::script_file = script_file.getValue();
{
std::stringstream ss(resolution.getValue());
char dummy;
/* try: */ ss >> fcmain::resWidth >> dummy >> fcmain::resHeight;
if (!ss) throw TCLAP::ArgException("Bad resolution format (should be <number>x<number>)", "resolution");
}
}
catch (TCLAP::ArgException& e) {
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
exit(1);
}
}
}; // ns
////////////////////////////////////////////////////////////
/// Entry point of application
///
/// \return Application exit code
///
////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
//fcmain::parse_cmdline(argc, argv);
// @HACK@
fcmain::resWidth = 800; fcmain::resHeight = 600;
fcmain::font_size = 14.f;
fcmain::fullscreen = false;
//sf::RenderWindow App(sf::VideoMode(640, 480), "FaffoCue");
FaffoCue::App app(sf::VideoMode(fcmain::resWidth, fcmain::resHeight), false, false, fcmain::font_size);
//App.SetFramerateLimit(60);
//App.UseVerticalSync(true);
// sf::Font fnt;
fcmain::font_file = FaffoCue::_impl::resources_location() + "/AurulentSans-Bold.otf"; // @HACK@
app.font().loadFromFile(fcmain::font_file);
app.text().add_line("The quick brown fox jumps over the lazy dog. And here's another sentence because the last one wasn't really long enough to test the word wrap thoroughly. But this should be okay.");
app.text().add_line("And now, for a limited time only, a second line of text!");
app.text().add_line("0 1 2 3 4 5 6 7 8 9");
// sf::View &cxView = app.cx().GetDefaultView();
// const sf::Input &cxInput = app.cx().GetInput();
double x = 0;
bool fullscreen = false;
app.main();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include <fstream>
#include <iostream>
#include <sstream>
#include <unistd.h>
#if USE_LIBOSRM
#include "osrm/exception.hpp"
#endif
#include "problems/vrp.h"
#include "structures/cl_args.h"
#include "structures/typedefs.h"
#include "structures/vroom/input/input.h"
#include "utils/exception.h"
#include "utils/input_parser.h"
#include "utils/output_json.h"
#include "utils/version.h"
void display_usage() {
std::string usage = "VROOM Copyright (C) 2015-2018, Julien Coupey\n";
usage += "Version: " + vroom::get_version() + "\n";
usage += "Usage:\n\tvroom [OPTION]... \"INPUT\"";
usage += "\n\tvroom [OPTION]... -i FILE\n";
usage += "Options:\n";
usage += "\t-a PROFILE:HOST (=" + vroom::DEFAULT_PROFILE +
":0.0.0.0)\t Routing server\n";
usage += "\t-p PROFILE:PORT (=" + vroom::DEFAULT_PROFILE +
":5000),\t Routing server port\n";
usage += "\t-g,\t\t\t add detailed route geometry and indicators\n";
usage += "\t-i FILE,\t\t read input from FILE rather than from stdin\n";
usage += "\t-o OUTPUT,\t\t output file name\n";
usage += "\t-r ROUTER (=osrm),\t osrm or libosrm\n";
usage += "\t-t THREADS (=4),\t number of threads to use\n";
usage += "\t-x EXPLORE (=5),\t exploration level to use (0..5)";
std::cout << usage << std::endl;
exit(0);
}
int main(int argc, char** argv) {
// Load default command-line options.
vroom::io::CLArgs cl_args;
// Parsing command-line arguments.
const char* optString = "a:gi:o:p:r:t:x:h?";
int opt = getopt(argc, argv, optString);
std::string router_arg;
std::string nb_threads_arg = std::to_string(cl_args.nb_threads);
std::string exploration_level_arg = std::to_string(cl_args.exploration_level);
while (opt != -1) {
switch (opt) {
case 'a':
vroom::io::update_host(cl_args.servers, optarg);
break;
case 'g':
cl_args.geometry = true;
break;
case 'h':
display_usage();
break;
case 'i':
cl_args.input_file = optarg;
break;
case 'o':
cl_args.output_file = optarg;
break;
case 'p':
vroom::io::update_port(cl_args.servers, optarg);
break;
case 'r':
router_arg = optarg;
break;
case 't':
nb_threads_arg = optarg;
break;
case 'x':
exploration_level_arg = optarg;
break;
default:
break;
}
opt = getopt(argc, argv, optString);
}
try {
// Needs to be done after previous switch to make sure the
// appropriate output file is set.
cl_args.nb_threads = std::stoul(nb_threads_arg);
cl_args.exploration_level = std::stoul(exploration_level_arg);
cl_args.exploration_level =
std::min(cl_args.exploration_level, cl_args.max_exploration_level);
} catch (const std::exception& e) {
std::string message = "Invalid numerical value.";
std::cerr << "[Error] " << message << std::endl;
vroom::io::write_to_json({1, message}, false, cl_args.output_file);
exit(1);
}
// Determine routing engine (defaults to ROUTER::OSRM).
if (router_arg == "libosrm") {
cl_args.router = vroom::ROUTER::LIBOSRM;
} else if (!router_arg.empty() and router_arg != "osrm") {
std::string message = "Invalid routing engine: " + router_arg;
std::cerr << "[Error] " << message << std::endl;
vroom::io::write_to_json({1, message}, false, cl_args.output_file);
exit(1);
}
// Add default server if none provided in input.
if (cl_args.servers.empty()) {
cl_args.servers.emplace(vroom::DEFAULT_PROFILE, vroom::Server());
}
if (cl_args.input_file.empty()) {
// Getting input from command-line.
if (argc == optind) {
// Missing argument!
display_usage();
}
cl_args.input = argv[optind];
} else {
// Getting input from provided file.
std::ifstream ifs(cl_args.input_file);
std::stringstream buffer;
buffer << ifs.rdbuf();
cl_args.input = buffer.str();
}
try {
// Build problem.
vroom::Input problem_instance = vroom::io::parse(cl_args);
vroom::Solution sol =
problem_instance.solve(cl_args.exploration_level, cl_args.nb_threads);
// Write solution.
vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file);
} catch (const vroom::Exception& e) {
std::cerr << "[Error] " << e.get_message() << std::endl;
vroom::io::write_to_json({1, e.get_message()}, false, cl_args.output_file);
exit(1);
}
#if USE_LIBOSRM
catch (const osrm::exception& e) {
// In case of an unhandled routing error.
auto message = "Routing problem: " + std::string(e.what());
std::cerr << "[Error] " << message << std::endl;
vroom::io::write_to_json({1, message}, false, cl_args.output_file);
exit(1);
}
#endif
catch (const std::exception& e) {
// In case of an unhandled internal error.
std::cerr << "[Error] " << e.what() << std::endl;
vroom::io::write_to_json({1, e.what()}, false, cl_args.output_file);
exit(1);
}
return 0;
}
<commit_msg>Cleanup usage output.<commit_after>/*
This file is part of VROOM.
Copyright (c) 2015-2018, Julien Coupey.
All rights reserved (see LICENSE).
*/
#include <fstream>
#include <iostream>
#include <sstream>
#include <unistd.h>
#if USE_LIBOSRM
#include "osrm/exception.hpp"
#endif
#include "problems/vrp.h"
#include "structures/cl_args.h"
#include "structures/typedefs.h"
#include "structures/vroom/input/input.h"
#include "utils/exception.h"
#include "utils/input_parser.h"
#include "utils/output_json.h"
#include "utils/version.h"
void display_usage() {
std::string usage = "VROOM Copyright (C) 2015-2018, Julien Coupey\n";
usage += "Version: " + vroom::get_version() + "\n";
usage += "Usage:\n\tvroom [OPTION]... \"INPUT\"";
usage += "\n\tvroom [OPTION]... -i FILE\n";
usage += "Options:\n";
usage += "\t-a PROFILE:HOST (=" + vroom::DEFAULT_PROFILE +
":0.0.0.0)\t routing server\n";
usage += "\t-p PROFILE:PORT (=" + vroom::DEFAULT_PROFILE +
":5000),\t routing server port\n";
usage += "\t-g,\t\t\t\t add detailed route geometry and indicators\n";
usage += "\t-i FILE,\t\t\t read input from FILE rather than from stdin\n";
usage += "\t-o OUTPUT,\t\t\t output file name\n";
usage += "\t-r ROUTER (=osrm),\t\t osrm or libosrm\n";
usage += "\t-t THREADS (=4),\t\t number of threads to use\n";
usage += "\t-x EXPLORE (=5),\t\t exploration level to use (0..5)";
std::cout << usage << std::endl;
exit(0);
}
int main(int argc, char** argv) {
// Load default command-line options.
vroom::io::CLArgs cl_args;
// Parsing command-line arguments.
const char* optString = "a:gi:o:p:r:t:x:h?";
int opt = getopt(argc, argv, optString);
std::string router_arg;
std::string nb_threads_arg = std::to_string(cl_args.nb_threads);
std::string exploration_level_arg = std::to_string(cl_args.exploration_level);
while (opt != -1) {
switch (opt) {
case 'a':
vroom::io::update_host(cl_args.servers, optarg);
break;
case 'g':
cl_args.geometry = true;
break;
case 'h':
display_usage();
break;
case 'i':
cl_args.input_file = optarg;
break;
case 'o':
cl_args.output_file = optarg;
break;
case 'p':
vroom::io::update_port(cl_args.servers, optarg);
break;
case 'r':
router_arg = optarg;
break;
case 't':
nb_threads_arg = optarg;
break;
case 'x':
exploration_level_arg = optarg;
break;
default:
break;
}
opt = getopt(argc, argv, optString);
}
try {
// Needs to be done after previous switch to make sure the
// appropriate output file is set.
cl_args.nb_threads = std::stoul(nb_threads_arg);
cl_args.exploration_level = std::stoul(exploration_level_arg);
cl_args.exploration_level =
std::min(cl_args.exploration_level, cl_args.max_exploration_level);
} catch (const std::exception& e) {
std::string message = "Invalid numerical value.";
std::cerr << "[Error] " << message << std::endl;
vroom::io::write_to_json({1, message}, false, cl_args.output_file);
exit(1);
}
// Determine routing engine (defaults to ROUTER::OSRM).
if (router_arg == "libosrm") {
cl_args.router = vroom::ROUTER::LIBOSRM;
} else if (!router_arg.empty() and router_arg != "osrm") {
std::string message = "Invalid routing engine: " + router_arg;
std::cerr << "[Error] " << message << std::endl;
vroom::io::write_to_json({1, message}, false, cl_args.output_file);
exit(1);
}
// Add default server if none provided in input.
if (cl_args.servers.empty()) {
cl_args.servers.emplace(vroom::DEFAULT_PROFILE, vroom::Server());
}
if (cl_args.input_file.empty()) {
// Getting input from command-line.
if (argc == optind) {
// Missing argument!
display_usage();
}
cl_args.input = argv[optind];
} else {
// Getting input from provided file.
std::ifstream ifs(cl_args.input_file);
std::stringstream buffer;
buffer << ifs.rdbuf();
cl_args.input = buffer.str();
}
try {
// Build problem.
vroom::Input problem_instance = vroom::io::parse(cl_args);
vroom::Solution sol =
problem_instance.solve(cl_args.exploration_level, cl_args.nb_threads);
// Write solution.
vroom::io::write_to_json(sol, cl_args.geometry, cl_args.output_file);
} catch (const vroom::Exception& e) {
std::cerr << "[Error] " << e.get_message() << std::endl;
vroom::io::write_to_json({1, e.get_message()}, false, cl_args.output_file);
exit(1);
}
#if USE_LIBOSRM
catch (const osrm::exception& e) {
// In case of an unhandled routing error.
auto message = "Routing problem: " + std::string(e.what());
std::cerr << "[Error] " << message << std::endl;
vroom::io::write_to_json({1, message}, false, cl_args.output_file);
exit(1);
}
#endif
catch (const std::exception& e) {
// In case of an unhandled internal error.
std::cerr << "[Error] " << e.what() << std::endl;
vroom::io::write_to_json({1, e.what()}, false, cl_args.output_file);
exit(1);
}
return 0;
}
<|endoftext|> |
<commit_before>#include "libtg.hpp"
using namespace std;
// argv[0]
string exe;
void usage() {
cerr << "Usage mode: " << exe << " [options...] \n";
cerr << endl;
cerr << "I/O options:\n";
cerr << "\t-i\t<file path>\tRead formula from file.\n";
cerr << "\t-oinfo\t<file path>\tAppend formula information to file.\n";
cerr << "\t-ocnf\t<file path>\tWrite CNF to file.\n";
cerr << "\t-oproof\t<file path>\tWrite proof formula to file.\n";
cerr << endl;
cerr << "Pipeline options:\n";
cerr << "\t-f\tFlat ((p|(q|r)|s) ---> (p|q|r|s)). Before DAG.\n";
cerr << "\t-m\tMinimize DAG edges ((p&q)|(p&r&q) ---> (p&q)|((p&q)&r)).\n";
cerr << "\t-a\t<algorithm number>\tSelect renaming algorithm.\n";
cerr << "\t-s\tSimplify CNF. (see note 1)\n";
cerr << "\t-ionly\tOnly compute formula information.\n";
cerr << endl;
cerr << "Additional options:\n";
cerr << "\t-h\tDisplay usage mode.\n";
cerr << "\t-syntax\tDisplay formula syntax.\n";
cerr << endl;
cerr << "Renaming algorithms (see note 2):\n";
cerr << "\t1\tKnapsack 0-1 based algorithm.\n";
cerr << "\t2\tBoy de la Tour's algorithm.\n";
cerr << endl;
cerr << "Notes:\n";
cerr << "\t1) CNF simplification removes tautologies, repeated literals\n";
cerr << "\tand repeated clauses.\n";
cerr << "\t2) If option -a is not set or an invalid algorithm is passed,\n";
cerr << "\tthen no renaming will happen at all.\n";
cerr << "\t3) Formula information format:\n";
cerr << "\t<file path>,<size>,<number of clauses>,<number of symbols>,\\n\n";
cerr << endl;
exit(-1);
}
void syntax() {
cerr << exe << ": Formula syntax.\n";
cerr << endl;
cerr << "Propositional symbols are strings of one or more of the following\n";
cerr << "ASCII characters:\n";
cerr << "\t_\t(underscore)\n";
cerr << "\t0 to 9\t(decimal digits)\n";
cerr << "\ta to z\t(lowercase letters)\n";
cerr << "\tA to Z\t(uppercase letters)\n";
cerr << endl;
cerr << "Logic connectives are the following strings of ASCII characters:\n";
cerr << "\t~\t(tilde)\t\t\t\t\t\tNegation.\n";
cerr << "\t&\t(ampersand)\t\t\t\t\tConjunction.\n";
cerr << "\t|\t(pipe)\t\t\t\t\t\tDisjunction.\n";
cerr << "\t=>\t(equals and greater than signs)\t\t\tImplication.\n";
cerr << "\t<=>\t(less than, equals and greater than signs)\tEquivalence.\n";
cerr << endl;
cerr << "Notes:\n";
cerr << "\t1) Only one line is read by the parser.\n";
cerr << "\t2) Whitespaces and multiple parentheses are completely ignored.\n";
cerr << "\tExample:\n";
cerr << "\t\t(((p => q)))\tis the same as\t\tp=>q\n";
cerr << endl;
exit(-1);
}
class Args {
private:
int argc;
char** argv;
unordered_map<string,int> idx;
public:
void init(int argc, char** argv) {
this->argc = argc;
this->argv = argv;
for (int i = argc-1; 1 <= i; i--) idx[argv[i]] = i;
}
bool find(const string& str) const {
return idx.find(str) != idx.end();
}
template <typename T>
T opt(const string& name) const {
auto it = idx.find(name);
if (it == idx.end()) usage();
int i = it->second+1;
if (argc <= i) usage();
stringstream ss;
ss << argv[i];
T ret;
ss >> ret;
if (ss.fail()) usage();
return ret;
}
void checkflag(const string& name) const {
if (!find(name)) usage();
}
template <typename T>
void checkopt(const string& name, bool required = false) const {
if (find(name)) opt<T>(name);
else if (required) usage();
}
} args;
// files
unordered_map<string,fstream*> files;
ostream& get_output_stream(const string& name, bool append = false) {
if (!args.find("-o"+name)) return cout;
string fn = args.opt<string>("-o"+name);
auto it = files.find(fn);
if (it != files.end()) return (ostream&)*it->second;
fstream::openmode md = fstream::out;
if (append) md = md | fstream::app;
fstream* file = new fstream(fn,md);
if (!file->is_open()) {
cerr << exe << ": ";
cerr << "error opening `" << fn << "' for " << name << " output.\n";
exit(-1);
}
files[fn] = file;
return (ostream&)*file;
}
void close_files() {
for (auto& kv : files) {
kv.second->close();
delete kv.second;
}
}
int main(int argc, char** argv) {
// init args
exe = argv[0];
args.init(argc,argv);
// display help
if (args.find("-h")) usage();
if (args.find("-syntax")) syntax();
// init input stream
string in_fn = "stdin";
if (args.find("-i")) {
in_fn = args.opt<string>("-i");
if (!freopen(in_fn.c_str(),"r",stdin)) {
cerr << exe << ": `" << in_fn << "' not found.\n";
return -1;
}
reverse(in_fn.begin(),in_fn.end());
auto pos = in_fn.find("/");
if (pos != string::npos) in_fn = in_fn.substr(0,pos);
reverse(in_fn.begin(),in_fn.end());
}
// init output streams
ostream& info_stream = get_output_stream("info", true);
ostream& cnf_stream = get_output_stream("cnf");
ostream& proof_stream = get_output_stream("proof");
// additional argument checks
args.checkopt<int>("-a");
// input
getline(cin,raw);
parse();
// info only
if (args.find("-ionly")) {
info_stream << in_fn << ",";
info_stream << size(T) << ",";
info_stream << clauses(T) << ",";
info_stream << symbols(T) << ",\n";
close_files();
return 0;
}
// pipeline
nnf();
if (args.find("-f")) flat();
dag();
if (args.find("-m")) mindag();
if (args.find("-a")) switch (args.opt<int>("-a")) {
case 1: knapsack(); break;
case 2: boydelatour(); break;
}
rename();
if (args.find("-s")) simplecnf();
else cnf();
// output
info_stream << in_fn << ",";
info_stream << CNF.size() << ",";
info_stream << CNF.clauses() << ",";
info_stream << CNF.symbols() << ",\n";
cnf_stream << CNF << endl;
proof_stream << "(" << raw << ") <=> (" << CNF << ")\n";
close_files();
return 0;
}
<commit_msg>Update usage mode<commit_after>#include "libtg.hpp"
using namespace std;
// argv[0]
string exe;
void usage() {
cerr << "Usage mode: " << exe << " [options...] \n";
cerr << endl;
cerr << "I/O options:\n";
cerr << "\t-i\t<file path>\tRead formula from file.\n";
cerr << "\t-oinfo\t<file path>\tAppend formula information to file.\n";
cerr << "\t-ocnf\t<file path>\tWrite CNF to file.\n";
cerr << "\t-oproof\t<file path>\tWrite proof formula to file.\n";
cerr << endl;
cerr << "Pipeline options:\n";
cerr << "\t-f\tFlat ((p|(q|r)|s) ---> (p|q|r|s)). Before DAG.\n";
cerr << "\t-m\tMinimize DAG edges ((p&q)|(p&r&q) ---> (p&q)|((p&q)&r)).\n";
cerr << "\t-a\t<algorithm number>\tSelect renaming algorithm.\n";
cerr << "\t-s\tSimplify CNF. (see note 1)\n";
cerr << "\t-ionly\tOnly compute formula information.\n";
cerr << endl;
cerr << "Additional options:\n";
cerr << "\t-h\tDisplay usage mode.\n";
cerr << "\t-syntax\tDisplay formula syntax.\n";
cerr << endl;
cerr << "Renaming algorithms (see note 2):\n";
cerr << "\t1\tKnapsack 0-1 based algorithm.\n";
cerr << "\t2\tBoy de la Tour's algorithm.\n";
cerr << endl;
cerr << "Notes:\n";
cerr << "\t1) CNF simplification removes tautologies, repeated literals\n";
cerr << "\tand repeated clauses.\n";
cerr << "\t2) If option -a is not set or an invalid algorithm is passed,\n";
cerr << "\tthen no renaming will happen at all.\n";
cerr << "\t3) Formula information format:\n";
cerr << "\t<file path>,<size>,<number of clauses>,<number of symbols>,\n";
cerr << endl;
exit(-1);
}
void syntax() {
cerr << exe << ": Formula syntax.\n";
cerr << endl;
cerr << "Propositional symbols are strings of one or more of the following\n";
cerr << "ASCII characters:\n";
cerr << "\t_\t(underscore)\n";
cerr << "\t0 to 9\t(decimal digits)\n";
cerr << "\ta to z\t(lowercase letters)\n";
cerr << "\tA to Z\t(uppercase letters)\n";
cerr << endl;
cerr << "Logic connectives are the following strings of ASCII characters:\n";
cerr << "\t~\t(tilde)\t\t\t\t\t\tNegation.\n";
cerr << "\t&\t(ampersand)\t\t\t\t\tConjunction.\n";
cerr << "\t|\t(pipe)\t\t\t\t\t\tDisjunction.\n";
cerr << "\t=>\t(equals and greater than signs)\t\t\tImplication.\n";
cerr << "\t<=>\t(less than, equals and greater than signs)\tEquivalence.\n";
cerr << endl;
cerr << "Notes:\n";
cerr << "\t1) Only one line is read by the parser.\n";
cerr << "\t2) Whitespaces and multiple parentheses are completely ignored.\n";
cerr << "\tExample:\n";
cerr << "\t\t(((p => q)))\tis the same as\t\tp=>q\n";
cerr << endl;
exit(-1);
}
class Args {
private:
int argc;
char** argv;
unordered_map<string,int> idx;
public:
void init(int argc, char** argv) {
this->argc = argc;
this->argv = argv;
for (int i = argc-1; 1 <= i; i--) idx[argv[i]] = i;
}
bool find(const string& str) const {
return idx.find(str) != idx.end();
}
template <typename T>
T opt(const string& name) const {
auto it = idx.find(name);
if (it == idx.end()) usage();
int i = it->second+1;
if (argc <= i) usage();
stringstream ss;
ss << argv[i];
T ret;
ss >> ret;
if (ss.fail()) usage();
return ret;
}
void checkflag(const string& name) const {
if (!find(name)) usage();
}
template <typename T>
void checkopt(const string& name, bool required = false) const {
if (find(name)) opt<T>(name);
else if (required) usage();
}
} args;
// files
unordered_map<string,fstream*> files;
ostream& get_output_stream(const string& name, bool append = false) {
if (!args.find("-o"+name)) return cout;
string fn = args.opt<string>("-o"+name);
auto it = files.find(fn);
if (it != files.end()) return (ostream&)*it->second;
fstream::openmode md = fstream::out;
if (append) md = md | fstream::app;
fstream* file = new fstream(fn,md);
if (!file->is_open()) {
cerr << exe << ": ";
cerr << "error opening `" << fn << "' for " << name << " output.\n";
exit(-1);
}
files[fn] = file;
return (ostream&)*file;
}
void close_files() {
for (auto& kv : files) {
kv.second->close();
delete kv.second;
}
}
int main(int argc, char** argv) {
// init args
exe = argv[0];
args.init(argc,argv);
// display help
if (args.find("-h")) usage();
if (args.find("-syntax")) syntax();
// init input stream
string in_fn = "stdin";
if (args.find("-i")) {
in_fn = args.opt<string>("-i");
if (!freopen(in_fn.c_str(),"r",stdin)) {
cerr << exe << ": `" << in_fn << "' not found.\n";
return -1;
}
reverse(in_fn.begin(),in_fn.end());
auto pos = in_fn.find("/");
if (pos != string::npos) in_fn = in_fn.substr(0,pos);
reverse(in_fn.begin(),in_fn.end());
}
// init output streams
ostream& info_stream = get_output_stream("info", true);
ostream& cnf_stream = get_output_stream("cnf");
ostream& proof_stream = get_output_stream("proof");
// additional argument checks
args.checkopt<int>("-a");
// input
getline(cin,raw);
parse();
// info only
if (args.find("-ionly")) {
info_stream << in_fn << ",";
info_stream << size(T) << ",";
info_stream << clauses(T) << ",";
info_stream << symbols(T) << ",\n";
close_files();
return 0;
}
// pipeline
nnf();
if (args.find("-f")) flat();
dag();
if (args.find("-m")) mindag();
if (args.find("-a")) switch (args.opt<int>("-a")) {
case 1: knapsack(); break;
case 2: boydelatour(); break;
}
rename();
if (args.find("-s")) simplecnf();
else cnf();
// output
info_stream << in_fn << ",";
info_stream << CNF.size() << ",";
info_stream << CNF.clauses() << ",";
info_stream << CNF.symbols() << ",\n";
cnf_stream << CNF << endl;
proof_stream << "(" << raw << ") <=> (" << CNF << ")\n";
close_files();
return 0;
}
<|endoftext|> |
<commit_before>/*
*
* Copyright 2016 Carmine Dodaro.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "EnumerationSolver.h"
#include "glucose-syrup/core/Dimacs.h"
int main(int argc, char** argv)
{
EnumerationSolver s;
gzFile in = (argc == 1) ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
if (in == NULL)
printf("ERROR! Could not open file: %s\n", argc == 1 ? "<stdin>" : argv[1]), exit(1);
parse_DIMACS(in, s);
gzclose(in);
s.enumerate();
}
<commit_msg>Removed main.<commit_after><|endoftext|> |
<commit_before>/*
* main.cpp
* Copyright (c) 2015 Markus Himmel. All rights reserved.
* Distributed under the terms of the MIT license.
*/
#include <algorithm>
#include <iostream>
#include <limits>
#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <NodeInfo.h>
#include <Path.h>
#include <String.h>
#include <fs_attr.h>
BString handleAttribute(BString name, const void *data)
{
if (name == "META:url") {
std::cout << " HREF=\"" << (const char*)data << "\"";
} else if (name == "META:title") {
return BString((const char *)data);
}
return NULL;
}
status_t doFile(BFile& file, int indent)
{
size_t bufferSize = std::max(B_MIME_TYPE_LENGTH, B_ATTR_NAME_LENGTH);
BNodeInfo nodeInfo(&file);
char* buffer = new (std::nothrow) char[bufferSize];
if (buffer == NULL)
return B_NO_MEMORY;
nodeInfo.GetType(buffer);
if (BString(buffer) != "application/x-vnd.Be-bookmark") {
delete[] buffer;
return B_BAD_VALUE;
}
BString ind;
ind.Append(' ', indent);
std::cout << ind << "<DT><A";
BString title;
struct attr_info info;
while (file.GetNextAttrName(buffer) == B_OK) {
if (file.GetAttrInfo(buffer, &info) != B_OK)
continue;
uint8_t* data = new (std::nothrow) uint8_t[info.size];
if (data == NULL)
continue;
if (file.ReadAttr(buffer, info.type, 0, data, info.size) ==
info.size) {
BString maybeTitle = handleAttribute(BString(buffer),
data);
if (maybeTitle != NULL)
title = maybeTitle;
}
delete[] data;
}
delete[] buffer;
if (title == NULL)
title = "Unknown";
std::cout << ">" << title << "</A>" << std::endl;
return B_OK;
}
status_t getLastChanged(BDirectory* dir, time_t* out)
{
if (dir == NULL || out == NULL)
return B_BAD_VALUE;
time_t latest = std::numeric_limits<time_t>::min(), cTime;
BEntry current;
bool any = false;
while (dir->GetNextEntry(¤t) == B_OK) {
if (current.GetCreationTime(&cTime) == B_OK && cTime > latest) {
any = true;
latest = cTime;
}
}
if (any) {
*out = latest;
return B_OK;
}
return B_ERROR;
}
status_t doDirectory(BDirectory& dir, const char* name, int indent)
{
BString ind;
ind.Append(' ', indent);
if (indent > 0) {
std::cout << ind << "<DT><H3";
time_t addDate;
if (dir.GetCreationTime(&addDate) == B_OK) {
std::cout << " ADD_DATE=\"" << addDate << "\" ";
time_t lastModified = addDate;
getLastChanged(&dir, &lastModified);
std::cout << "LAST_MODIFIED=\"" << lastModified << "\"";
}
std::cout << ">" << name << "</H3>" << std::endl << ind << "<DL><p>"
<< std::endl;
}
BEntry current;
dir.Rewind();
while (dir.GetNextEntry(¤t) == B_OK) {
if (current.IsDirectory()) {
BDirectory subdir(¤t);
char buffer[B_FILE_NAME_LENGTH];
if (current.GetName(buffer) == B_OK)
doDirectory(subdir, buffer, indent + 4);
else
doDirectory(subdir, "Unknown", indent + 4);
}
else if (current.IsFile()) {
BFile subfile(¤t, B_READ_ONLY);
doFile(subfile, indent + 4);
}
}
if (indent > 0)
std::cout << ind << "</DL><p>" << std::endl;
return B_OK;
}
status_t extract(const char* path)
{
std::cout << "<!DOCTYPE NETSCAPE-Bookmark-file-1>" << std::endl
<< "<!-- This is an automatically generated file." << std::endl
<< " It will be read and overwritten." << std::endl
<< " DO NOT EDIT! -->" << std::endl
<< "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;"
<< " charset=UTF-8\">" << std::endl
<< "<TITLE>Bookmarks</TITLE>" << std::endl
<< "<H1>Bookmarks</H1>" << std::endl
<< "<DL><p>" << std::endl;
BDirectory parent(path);
if (parent.InitCheck() != B_OK)
return B_ERROR;
doDirectory(parent, NULL, 0);
std::cout << "</DL><p>" << std::endl;
}
int main(int argc, char* argv[])
{
BPath dir;
switch (argc) {
case 1:
if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK) {
BString dest(dir.Path());
dest << "/WebPositive/Bookmarks/";
extract(dest.String());
break;
}
std::cerr << "Could not find settings directory." << std::endl;
break;
case 2:
extract(argv[1]);
break;
default:
std::cerr << "Too many arguments." << std::endl;
return 1;
}
return 0;
}
<commit_msg>Revert changes regarding data buffers<commit_after>/*
* main.cpp
* Copyright (c) 2015 Markus Himmel. All rights reserved.
* Distributed under the terms of the MIT license.
*/
#include <algorithm>
#include <iostream>
#include <limits>
#include <Directory.h>
#include <Entry.h>
#include <File.h>
#include <FindDirectory.h>
#include <NodeInfo.h>
#include <Path.h>
#include <String.h>
#include <fs_attr.h>
BString handleAttribute(BString name, const void *data)
{
if (name == "META:url") {
std::cout << " HREF=\"" << (const char*)data << "\"";
} else if (name == "META:title") {
return BString((const char *)data);
}
return NULL;
}
status_t doFile(BFile& file, int indent)
{
BNodeInfo nodeInfo(&file);
char buffer[B_MIME_TYPE_LENGTH];
nodeInfo.GetType(buffer);
if (BString(buffer) != "application/x-vnd.Be-bookmark")
return B_BAD_VALUE;
BString ind;
ind.Append(' ', indent);
std::cout << ind << "<DT><A";
BString title;
struct attr_info info;
char attrBuffer[B_ATTR_NAME_LENGTH];
while (file.GetNextAttrName(attrBuffer) == B_OK) {
if (file.GetAttrInfo(attrBuffer, &info) != B_OK)
continue;
uint8_t* data = new (std::nothrow) uint8_t[info.size];
if (data == NULL)
continue;
if (file.ReadAttr(attrBuffer, info.type, 0, data, info.size) ==
info.size) {
BString maybeTitle = handleAttribute(BString(attrBuffer),
data);
if (maybeTitle != NULL)
title = maybeTitle;
}
delete[] data;
}
if (title == NULL)
title = "Unknown";
std::cout << ">" << title << "</A>" << std::endl;
return B_OK;
}
status_t getLastChanged(BDirectory* dir, time_t* out)
{
if (dir == NULL || out == NULL)
return B_BAD_VALUE;
time_t latest = std::numeric_limits<time_t>::min(), cTime;
BEntry current;
bool any = false;
while (dir->GetNextEntry(¤t) == B_OK) {
if (current.GetCreationTime(&cTime) == B_OK && cTime > latest) {
any = true;
latest = cTime;
}
}
if (any) {
*out = latest;
return B_OK;
}
return B_ERROR;
}
status_t doDirectory(BDirectory& dir, const char* name, int indent)
{
BString ind;
ind.Append(' ', indent);
if (indent > 0) {
std::cout << ind << "<DT><H3";
time_t addDate;
if (dir.GetCreationTime(&addDate) == B_OK) {
std::cout << " ADD_DATE=\"" << addDate << "\" ";
time_t lastModified = addDate;
getLastChanged(&dir, &lastModified);
std::cout << "LAST_MODIFIED=\"" << lastModified << "\"";
}
std::cout << ">" << name << "</H3>" << std::endl << ind << "<DL><p>"
<< std::endl;
}
BEntry current;
dir.Rewind();
while (dir.GetNextEntry(¤t) == B_OK) {
if (current.IsDirectory()) {
BDirectory subdir(¤t);
char buffer[B_FILE_NAME_LENGTH];
if (current.GetName(buffer) == B_OK)
doDirectory(subdir, buffer, indent + 4);
else
doDirectory(subdir, "Unknown", indent + 4);
}
else if (current.IsFile()) {
BFile subfile(¤t, B_READ_ONLY);
doFile(subfile, indent + 4);
}
}
if (indent > 0)
std::cout << ind << "</DL><p>" << std::endl;
return B_OK;
}
status_t extract(const char* path)
{
std::cout << "<!DOCTYPE NETSCAPE-Bookmark-file-1>" << std::endl
<< "<!-- This is an automatically generated file." << std::endl
<< " It will be read and overwritten." << std::endl
<< " DO NOT EDIT! -->" << std::endl
<< "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html;"
<< " charset=UTF-8\">" << std::endl
<< "<TITLE>Bookmarks</TITLE>" << std::endl
<< "<H1>Bookmarks</H1>" << std::endl
<< "<DL><p>" << std::endl;
BDirectory parent(path);
if (parent.InitCheck() != B_OK)
return B_ERROR;
doDirectory(parent, NULL, 0);
std::cout << "</DL><p>" << std::endl;
}
int main(int argc, char* argv[])
{
BPath dir;
switch (argc) {
case 1:
if (find_directory(B_USER_SETTINGS_DIRECTORY, &dir) == B_OK) {
BString dest(dir.Path());
dest << "/WebPositive/Bookmarks/";
extract(dest.String());
break;
}
std::cerr << "Could not find settings directory." << std::endl;
break;
case 2:
extract(argv[1]);
break;
default:
std::cerr << "Too many arguments." << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <thread>
#include <time.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "../sdk/stb/stb_image_write.h"
#include "renderer.h"
// おおよそ30秒毎に、レンダリングの途中経過をbmpかpngで連番(000.png, 001.png, ...) で出力してください。
// 4分33秒以内に自動で終了してください。
#define WIDTH 256
#define HEIGHT 256
#define OUTPUT_INTERVAL 30
#define FINISH_TIME (4 * 60 + 33)
#define FINISH_MARGIN 2
void save(const double *data, unsigned char *buf, const char *filename, int steps)
{
const double coeff = 1.0 / (10.1 * (double)steps);
#pragma omp parallel for
for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) {
double tmp = 1.0 - exp(-data[i] * coeff);// tone mapping
buf[i] = (unsigned char)(pow(tmp, 1.0/2.2) * 255.999);// gamma correct
}
// save
int w = WIDTH;
int h = HEIGHT;
int comp = 3; // RGB
int stride_in_bytes = 3 * w;
int result = stbi_write_png(filename, w, h, comp, buf, stride_in_bytes);
}
int main()
{
time_t t0 = time(NULL);
time_t t_last = 0;
int count = 0;
unsigned char *image = new unsigned char[3 * WIDTH * HEIGHT];
// frame buffer の初期化
int current = 0;
double *fb[2];
fb[0] = new double[3 * WIDTH * HEIGHT];
fb[1] = new double[3 * WIDTH * HEIGHT];
double *fb0 = fb[0], *fb1 = fb[1];
#pragma omp parallel for
for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) {
fb0[i] = fb1[i] = 0;
}
renderer *pRenderer = new renderer(WIDTH, HEIGHT);
do
{
// fb[1-current] を読み込んで fb[current]にレンダリング
std::this_thread::sleep_for(std::chrono::seconds(1));
int steps = pRenderer->update(fb[1 - current], fb[current]);
// swap
current = 1 - current;
// 30 秒ごとに出力
time_t t = time(NULL) - t0;
int c = (int)(t / OUTPUT_INTERVAL);
if (count < c) {
char filename[256];
snprintf(filename, 256, "%d.png", c);
save(fb[1 - current], image, filename, steps);
count++;
}
// 4分33秒以内に終了なので、前のフレームを考えてオーバーしそうならば終了する
if (FINISH_TIME - FINISH_MARGIN <= t + (t - t_last)) break;
t_last = t;
}while (true);
delete pRenderer;
delete[] image;
delete[] fb[0];
delete[] fb[1];
return 0;
}
<commit_msg>full hd<commit_after>#include <iostream>
#include <thread>
#include <time.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "../sdk/stb/stb_image_write.h"
#include "renderer.h"
// おおよそ30秒毎に、レンダリングの途中経過をbmpかpngで連番(000.png, 001.png, ...) で出力してください。
// 4分33秒以内に自動で終了してください。
#define WIDTH 1980
#define HEIGHT 1080
#define OUTPUT_INTERVAL 30
#define FINISH_TIME (4 * 60 + 33)
#define FINISH_MARGIN 2
void save(const double *data, unsigned char *buf, const char *filename, int steps)
{
const double coeff = 1.0 / (10.1 * (double)steps);
#pragma omp parallel for
for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) {
double tmp = 1.0 - exp(-data[i] * coeff);// tone mapping
buf[i] = (unsigned char)(pow(tmp, 1.0/2.2) * 255.999);// gamma correct
}
// save
int w = WIDTH;
int h = HEIGHT;
int comp = 3; // RGB
int stride_in_bytes = 3 * w;
int result = stbi_write_png(filename, w, h, comp, buf, stride_in_bytes);
}
int main()
{
time_t t0 = time(NULL);
time_t t_last = 0;
int count = 0;
unsigned char *image = new unsigned char[3 * WIDTH * HEIGHT];
// frame buffer の初期化
int current = 0;
double *fb[2];
fb[0] = new double[3 * WIDTH * HEIGHT];
fb[1] = new double[3 * WIDTH * HEIGHT];
double *fb0 = fb[0], *fb1 = fb[1];
#pragma omp parallel for
for (int i = 0; i < 3 * WIDTH * HEIGHT; i++) {
fb0[i] = fb1[i] = 0;
}
renderer *pRenderer = new renderer(WIDTH, HEIGHT);
do
{
// fb[1-current] を読み込んで fb[current]にレンダリング
std::this_thread::sleep_for(std::chrono::seconds(1));
int steps = pRenderer->update(fb[1 - current], fb[current]);
// swap
current = 1 - current;
// 30 秒ごとに出力
time_t t = time(NULL) - t0;
int c = (int)(t / OUTPUT_INTERVAL);
if (count < c) {
char filename[256];
snprintf(filename, 256, "%d.png", c);
save(fb[1 - current], image, filename, steps);
count++;
}
// 4分33秒以内に終了なので、前のフレームを考えてオーバーしそうならば終了する
if (FINISH_TIME - FINISH_MARGIN <= t + (t - t_last)) break;
t_last = t;
}while (true);
delete pRenderer;
delete[] image;
delete[] fb[0];
delete[] fb[1];
return 0;
}
<|endoftext|> |
<commit_before>/**
* main.cpp
* This file is part of MultitouchPadOsc
*
*
* The MIT License
* Copyright (c) 2012 Paul Vollmer, http://www.wrong-entertainment.com
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
* @plattform MacOs 10.6+
* Win XXX
* Linux XXX
* @openFrameworks 0071
* @dependencies
* @modified 2012.07.15
* @version 0.1.2
*/
#include "ofMain.h"
#include "MultitouchPadOscApp.h"
#include "ofAppGlutWindow.h"
#include "Cocoa/Cocoa.h"
int main() {
ofAppGlutWindow window;
ofSetupOpenGL(&window, 500, 400, OF_WINDOW); // setup the GL context
if (NSApp){
NSMenu *menu;
NSMenuItem *menuItem;
[NSApp setMainMenu:[[NSMenu alloc] init]];
// Appname menu
menu = [[NSMenu alloc] initWithTitle:@""];
[menu addItemWithTitle:@"About MultitouchPadOsc" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Hide MultitouchPadOsc" action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Quit MultitouchPadOsc" action:@selector(terminate:) keyEquivalent:@"q"];
// Put menu into the menubar
menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
[menuItem setSubmenu:menu];
[[NSApp mainMenu] addItem:menuItem];
// Tell the application object that this is now the application menu
//[NSApp setMainMenu:menu];
}
// this kicks off the running of my app can be
// OF_WINDOW or OF_FULLSCREEN pass in width and height too:
ofRunApp(new MultitouchPadOscApp());
}
<commit_msg>clean up code<commit_after>/**
* main.cpp
* This file is part of MultitouchPadOsc
*
*
* The MIT License
* Copyright (c) 2012 Paul Vollmer, http://www.wrong-entertainment.com
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
* @plattform MacOs 10.6+
* Win XXX
* Linux XXX
* @openFrameworks 0071
* @dependencies
* @modified 2012.07.15
* @version 0.1.2
*/
#include "ofMain.h"
#include "MultitouchPadOscApp.h"
#include "ofAppGlutWindow.h"
#include "Cocoa/Cocoa.h"
int main() {
ofAppGlutWindow window;
ofSetupOpenGL(&window, 500, 400, OF_WINDOW); // setup the GL context
if (NSApp){
NSMenu *menu;
NSMenuItem *menuItem;
[NSApp setMainMenu:[[NSMenu alloc] init]];
// Appname menu
menu = [[NSMenu alloc] initWithTitle:@""];
[menu addItemWithTitle:@"About MultitouchPadOsc" action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Hide MultitouchPadOsc" action:@selector(hide:) keyEquivalent:@"h"];
menuItem = (NSMenuItem *)[menu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
[menuItem setKeyEquivalentModifierMask:(NSAlternateKeyMask|NSCommandKeyMask)];
[menu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];
[menu addItem:[NSMenuItem separatorItem]];
[menu addItemWithTitle:@"Quit MultitouchPadOsc" action:@selector(terminate:) keyEquivalent:@"q"];
// Put menu into the menubar
menuItem = [[NSMenuItem alloc] initWithTitle:@"Apple" action:nil keyEquivalent:@""];
[menuItem setSubmenu:menu];
[[NSApp mainMenu] addItem:menuItem];
}
// this kicks off the running of my app can be
// OF_WINDOW or OF_FULLSCREEN pass in width and height too:
ofRunApp(new MultitouchPadOscApp());
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"
const char * game_name = "Game Of Life On Surface";
int screen_width = 640;
int screen_height = 640;
float R = 200;
int px, py;
vec3s delta = { 0, 0, 0 };
vec3s view_direction = {1, M_PI / 4, 0 };
field f(16, 32);
bool quit_flag = false;
bool button_set = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;
void game_send_error( int code ) {
printf( "[error]: %s\n", SDL_GetError() );
exit( code );
}
void game_event( SDL_Event * event ) {
SDL_PollEvent( event );
switch ( event->type ) {
case SDL_QUIT:
quit_flag = true;
break;
case SDL_WINDOWEVENT:
if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) {
screen_width = event->window.data1;
screen_height = event->window.data2;
}
break;
case SDL_KEYDOWN:
switch ( event->key.keysym.sym ) {
case SDLK_ESCAPE:
quit_flag = true;
break;
case SDLK_UP:
view_direction.theta -= 0.01f;
break;
case SDLK_DOWN:
view_direction.theta += 0.01f;
break;
case SDLK_LEFT:
view_direction.phi -= 0.01f;
break;
case SDLK_RIGHT:
view_direction.phi += 0.01f;
break;
default:
break;
}
case SDL_MOUSEMOTION:
if ( button_set ) {
delta.phi = -( event->button.x - px ) / 100.0f;
delta.theta = ( event->button.y - py ) / 100.0f;
px = event->button.x;
py = event->button.y;
view_direction += delta;
}
break;
case SDL_MOUSEBUTTONDOWN:
switch ( event->button.button ) {
case SDL_BUTTON_LEFT:
if ( button_set == false ) {
px = event->button.x;
py = event->button.y;
}
break;
default:
break;
}
button_set = true;
break;
case SDL_MOUSEBUTTONUP:
button_set = false;
break;
default:
break;
}
}
void game_loop( void ) {
// insert code
}
void game_render( void ) {
SDL_RenderClear( render );
set_coloru( COLOR_WHITE );
draw_sphere( view_direction, {screen_width / 2, screen_height / 2}, R, f );
set_coloru( COLOR_BLACK );
SDL_RenderPresent( render );
}
void game_destroy( void ) {
SDL_DestroyRenderer( render );
SDL_DestroyWindow( window );
SDL_Quit();
}
void game_init( void ) {
SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
if ( window == NULL ) {
game_send_error( EXIT_FAILURE );
}
render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
SDL_RENDERER_TARGETTEXTURE );
if ( render == NULL ) {
game_send_error( EXIT_FAILURE );
}
SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND );
draw_init( render );
}
int main( int argc, char * argv[] ) {
game_init();
while ( quit_flag == false ) {
game_event( &event );
game_loop();
game_render();
}
game_destroy();
return EXIT_SUCCESS;
}
<commit_msg>[add] get_fps(), font; [upd] scroll<commit_after>#include <cstdio>
#include <SDL2/SDL.h>
#include "draw.hpp"
#include "font.hpp"
const char * game_name = "Game Of Life On Surface";
const wchar_t tmp_str[] = L"FPS: %.2f";
int screen_width = 640;
int screen_height = 640;
float R = 200;
int px, py;
vec3s delta = { 0, 0, 0 };
vec3s view_direction = {1, M_PI / 4, 0 };
field f(16, 32);
bool quit_flag = false;
bool button_set = false;
SDL_Window * window = NULL;
SDL_Renderer * render = NULL;
SDL_Event event;
font_table_t * ft = NULL;
void game_send_error( int code ) {
printf( "[error]: %s\n", SDL_GetError() );
exit( code );
}
float get_fps( void ) {
static float NewCount = 0.0f, LastCount = 0.0f, FpsRate = 0.0f;
static int FrameCount = 0;
NewCount = (float) SDL_GetTicks();
if ( ( NewCount - LastCount ) > 1000.0f ) {
FpsRate = ( FrameCount * 1000.0f ) / ( NewCount - LastCount );
LastCount = NewCount;
FrameCount = 0;
}
FrameCount++;
return FpsRate;
}
void game_event( SDL_Event * event ) {
SDL_PollEvent( event );
switch ( event->type ) {
case SDL_QUIT:
quit_flag = true;
break;
case SDL_WINDOWEVENT:
if ( event->window.event == SDL_WINDOWEVENT_RESIZED ) {
screen_width = event->window.data1;
screen_height = event->window.data2;
}
break;
case SDL_KEYDOWN:
switch ( event->key.keysym.sym ) {
case SDLK_ESCAPE:
quit_flag = true;
break;
case SDLK_UP:
view_direction.theta -= 0.01f;
break;
case SDLK_DOWN:
view_direction.theta += 0.01f;
break;
case SDLK_LEFT:
view_direction.phi -= 0.01f;
break;
case SDLK_RIGHT:
view_direction.phi += 0.01f;
break;
default:
break;
}
case SDL_MOUSEMOTION:
if ( button_set ) {
delta.phi = ( event->button.x - px ) / 100.0f;
delta.theta = ( event->button.y - py ) / 100.0f;
px = event->button.x;
py = event->button.y;
view_direction -= delta;
}
break;
case SDL_MOUSEBUTTONDOWN:
switch ( event->button.button ) {
case SDL_BUTTON_LEFT:
if ( button_set == false ) {
px = event->button.x;
py = event->button.y;
}
break;
default:
break;
}
button_set = true;
break;
case SDL_MOUSEBUTTONUP:
button_set = false;
break;
default:
break;
}
}
void game_loop( void ) {
// insert code
}
void game_render( void ) {
const size_t BUFFER_SIZE = 128;
wchar_t buffer[BUFFER_SIZE];
SDL_RenderClear( render );
set_coloru( COLOR_WHITE );
draw_sphere( view_direction, {screen_width / 2, screen_height / 2}, R, f );
swprintf( buffer, BUFFER_SIZE, tmp_str, get_fps() );
font_draw( render, ft, buffer, 5, screen_height - 16 );
set_coloru( COLOR_BLACK );
SDL_RenderPresent( render );
}
void game_destroy( void ) {
font_destroy( ft );
SDL_DestroyRenderer( render );
SDL_DestroyWindow( window );
SDL_Quit();
}
void game_init( void ) {
SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS );
window = SDL_CreateWindow( game_name, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
screen_width, screen_height, SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE );
if ( window == NULL ) {
game_send_error( EXIT_FAILURE );
}
render = SDL_CreateRenderer( window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC |
SDL_RENDERER_TARGETTEXTURE );
if ( render == NULL ) {
game_send_error( EXIT_FAILURE );
}
SDL_SetRenderDrawBlendMode( render, SDL_BLENDMODE_BLEND );
draw_init( render );
font_load( render, &ft, "./data/font.cfg" );
}
int main( int argc, char * argv[] ) {
game_init();
while ( quit_flag == false ) {
game_event( &event );
game_loop();
game_render();
}
game_destroy();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include "ftdi.hpp"
#include "dionysus.hpp"
#define PROGRAM_NAME "dionysus-ftdi"
using namespace Ftdi;
#define DEFAULT_ARGUMENTS \
{ \
.vendor = DIONYSUS_VID, \
.product = DIONYSUS_PID, \
.debug = false \
}
struct arguments {
int vendor;
int product;
bool debug;
};
static double TimevalDiff(const struct timeval *a, const struct timeval *b)
{
return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec);
}
static void usage (int exit_status){
fprintf (exit_status == EXIT_SUCCESS ? stdout : stderr,
"\n"
"USAGE: %s [-v <vendor>] [-p <product>] [-d]\n"
"\n"
"Options:\n"
" -h, --help\n"
"\tPrints this helpful message\n"
" -d, --debug\n"
"\tEnable Debug output\n"
" -v, --vendor\n"
"\tSpecify an alternate vendor ID (in hex) to use (Default: %04X)\n"
" -p, --product\n"
"\tSpecify an alternate product ID (in hex) to use (Default: %04X)\n"
,
PROGRAM_NAME, DIONYSUS_VID, DIONYSUS_PID);
exit(exit_status);
}
static void parse_args(struct arguments* args, int argc, char *const argv[]){
int print_usage = 0;
const char shortopts[] = "hdv:p:";
struct option longopts[5];
longopts[0].name = "help";
longopts[0].has_arg = no_argument;
longopts[0].flag = NULL;
longopts[0].val = 'h';
longopts[1].name = "debug";
longopts[1].has_arg = no_argument;
longopts[1].flag = NULL;
longopts[1].val = 'd';
longopts[2].name = "vendor";
longopts[2].has_arg = required_argument;
longopts[2].flag = NULL;
longopts[2].val = 'v';
longopts[3].name = "help";
longopts[3].has_arg = required_argument;
longopts[3].flag = NULL;
longopts[3].val = 'p';
longopts[4].name = 0;
longopts[4].has_arg = 0;
longopts[4].flag = 0;
longopts[4].val = 0;
while (1) {
int option_idx = 0;
int c = getopt_long(argc, argv, shortopts, longopts, &option_idx);
if (c == -1){
break;
}
switch (c){
case 0:
/* no arguments */
if (print_usage){
usage(EXIT_SUCCESS);
}
break;
case 'h':
usage(EXIT_SUCCESS);
break;
case 'd':
printf ("debug enabled\n");
args->debug = true;
break;
case 'v':
args->vendor = strtol(optarg, (char**)0, 16);
break;
case 'p':
args->product = strtol(optarg, (char**)0, 16);
break;
case '?': /* Fall through */
default:
printf ("Unknown Command\n");
usage (EXIT_FAILURE);
break;
}
}
}
int main(int argc, char **argv){
struct arguments args;
args.vendor = DIONYSUS_VID;
args.product = DIONYSUS_PID;
args.debug = false;
uint8_t* buffer = new uint8_t [8196];
uint32_t num_devices;
uint32_t device_type = 0;
uint32_t device_addres = 0;
uint32_t device_size = 0;
bool memory_device = false;
bool fail = false;
uint32_t fail_count = 0;
struct timeval start;
struct timeval end;
double interval = 1.0;
double mem_size;
double rate = 0;
uint32_t memory_device_index = 0;
parse_args(&args, argc, argv);
//Dionysus dionysus = Dionysus((uint32_t)DEFAULT_BUFFER_SIZE, args.debug);
Dionysus dionysus = Dionysus(args.debug);
dionysus.open(args.vendor, args.product);
if (dionysus.is_open()){
dionysus.reset();
//dionysus.program_fpga();
//dionysus.soft_reset();
gettimeofday(&start, NULL);
dionysus.ping();
gettimeofday(&end, NULL);
interval = TimevalDiff(&end, &start);
rate = 9 / interval; //Megabytes/Sec
printf ("Time difference: %f\n", interval);
printf ("Ping Rate: %.2f Bytes/Sec\n", rate);
printf ("Reading from the DRT\n");
//dionysus.read_periph_data(0, 0, buffer, 32);
dionysus.read_drt();
for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
printf ("Device %d:\n", i);
printf ("\tType:\t\t0x%08X\n", dionysus.get_drt_device_type(i));
printf ("\tSize:\t\t0x%08X (32-bit values)\n", dionysus.get_drt_device_size(i));
printf ("\tAddress:\t0x%08X\n", dionysus.get_drt_device_addr(i));
if (dionysus.is_memory_device(i)){
printf ("\t\tOn the memory bus\n");
}
}
//Buffer Data:
//for (int i = 0; i < 32; i++){
// printf ("%02X ", buffer[i]);
//}
printf ("\n");
//dionysus.read_periph_data(0, 0, buffer, 4096);
printf ("Peripheral Write Test. read a lot of data from the DRT\n");
printf ("\t(DRT will just ignore this data)\n");
dionysus.write_periph_data(0, 0, buffer, 8192);
printf ("Peripheral Read Test. Read a lot of data from the DRT\n");
printf ("\t(Data from the DRT will just loop)\n");
dionysus.read_periph_data(0, 0, buffer, 8192);
delete(buffer);
printf ("Look for a memory device\n");
for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
if (dionysus.get_drt_device_type(i) == 5){
memory_device_index = i;
}
}
if (memory_device_index > 0){
printf ("Found a memory device at position: %d\n", memory_device_index);
printf ("Memory Test! Read and write: 0x%08X Bytes\n", dionysus.get_drt_device_size(memory_device_index));
buffer = new uint8_t[dionysus.get_drt_device_size(memory_device_index)];
for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
buffer[i] = i;
}
printf ("Testing Full Memory Write Time...\n");
gettimeofday(&start, NULL);
dionysus.write_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index));
gettimeofday(&end, NULL);
interval = TimevalDiff(&end, &start);
mem_size = dionysus.get_drt_device_size(memory_device_index);
rate = mem_size/ interval / 1e6; //Megabytes/Sec
printf ("Time difference: %f\n", interval);
printf ("Write Rate: %.2f MB/Sec\n", rate);
for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
buffer[i] = 0;
}
gettimeofday(&start, NULL);
dionysus.read_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index));
gettimeofday(&end, NULL);
interval = TimevalDiff(&end, &start);
mem_size = dionysus.get_drt_device_size(memory_device_index);
rate = mem_size/ interval / 1e6; //Megabytes/Sec
printf ("Time difference: %f\n", interval);
printf ("Read Rate: %.2f MB/Sec\n", rate);
for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
if (buffer[i] != i % 256){
if (!fail){
if (fail_count > 16){
fail = true;
}
fail_count += 1;
printf ("Failed @ 0x%08X\n", i);
printf ("Value should be: 0x%08X but is: 0x%08X\n", i, buffer[i]);
}
}
}
if (!fail){
printf ("Memory Test Passed!\n");
}
delete (buffer);
}
dionysus.close();
}
return 0;
}
<commit_msg>Added support for testing the GPIO driver<commit_after>#include <stdio.h>
#include <getopt.h>
#include <string.h>
#include <unistd.h>
#include "ftdi.hpp"
#include "dionysus.hpp"
#include "gpio.hpp"
#include "arduino.hpp"
#define PROGRAM_NAME "dionysus-ftdi"
#define MEMORY_TEST false
//5 seconds
#define GPIO_TEST_WAIT 10
using namespace Ftdi;
#define DEFAULT_ARGUMENTS \
{ \
.vendor = DIONYSUS_VID, \
.product = DIONYSUS_PID, \
.debug = false \
}
struct arguments {
int vendor;
int product;
bool debug;
};
static double TimevalDiff(const struct timeval *a, const struct timeval *b)
{
return (a->tv_sec - b->tv_sec) + 1e-6 * (a->tv_usec - b->tv_usec);
}
static void usage (int exit_status){
fprintf (exit_status == EXIT_SUCCESS ? stdout : stderr,
"\n"
"USAGE: %s [-v <vendor>] [-p <product>] [-d]\n"
"\n"
"Options:\n"
" -h, --help\n"
"\tPrints this helpful message\n"
" -d, --debug\n"
"\tEnable Debug output\n"
" -v, --vendor\n"
"\tSpecify an alternate vendor ID (in hex) to use (Default: %04X)\n"
" -p, --product\n"
"\tSpecify an alternate product ID (in hex) to use (Default: %04X)\n"
,
PROGRAM_NAME, DIONYSUS_VID, DIONYSUS_PID);
exit(exit_status);
}
static void parse_args(struct arguments* args, int argc, char *const argv[]){
int print_usage = 0;
const char shortopts[] = "hdv:p:";
struct option longopts[5];
longopts[0].name = "help";
longopts[0].has_arg = no_argument;
longopts[0].flag = NULL;
longopts[0].val = 'h';
longopts[1].name = "debug";
longopts[1].has_arg = no_argument;
longopts[1].flag = NULL;
longopts[1].val = 'd';
longopts[2].name = "vendor";
longopts[2].has_arg = required_argument;
longopts[2].flag = NULL;
longopts[2].val = 'v';
longopts[3].name = "help";
longopts[3].has_arg = required_argument;
longopts[3].flag = NULL;
longopts[3].val = 'p';
longopts[4].name = 0;
longopts[4].has_arg = 0;
longopts[4].flag = 0;
longopts[4].val = 0;
while (1) {
int option_idx = 0;
int c = getopt_long(argc, argv, shortopts, longopts, &option_idx);
if (c == -1){
break;
}
switch (c){
case 0:
/* no arguments */
if (print_usage){
usage(EXIT_SUCCESS);
}
break;
case 'h':
usage(EXIT_SUCCESS);
break;
case 'd':
printf ("debug enabled\n");
args->debug = true;
break;
case 'v':
args->vendor = strtol(optarg, (char**)0, 16);
break;
case 'p':
args->product = strtol(optarg, (char**)0, 16);
break;
case '?': /* Fall through */
default:
printf ("Unknown Command\n");
usage (EXIT_FAILURE);
break;
}
}
}
void breath(GPIO *g, uint32_t timeout){
struct timeval test_start;
struct timeval test_now;
double interval = 1.0;
gettimeofday(&test_start, NULL);
gettimeofday(&test_now, NULL);
uint32_t period;
uint32_t max_val = 10;
uint32_t current = 0;
uint32_t position = 0;
uint32_t delay_count = 0;
uint32_t delay = 0;
uint8_t direction = 1;
printf ("Breath\n");
printf ("Max value: %d\n", max_val);
while (interval < GPIO_TEST_WAIT){
if (direction){
if (current < max_val){
if (position < max_val) {
//printf ("pos++\n");
position++;
}
else {
//printf ("position = 0\n");
position = 0;
if (delay_count < delay){
delay_count++;
}
else {
//printf ("increment count\n");
delay_count = 0;
current++;
}
}
}
else {
//printf ("go down\n");
direction = 0;
}
}
else {
if (current > 0){
if (position < max_val){
position++;
}
else {
position = 0;
if (delay_count < delay){
delay_count++;
}
else {
delay_count = 0;
current--;
}
}
}
else {
//printf ("go up\n");
direction = 1;
}
}
if (position < current){
//printf ("HI\n");
//g->digitalWrite(0, LOW);
g->set_gpios(0x00000002);
}
else {
//printf ("LOW\n");
g->set_gpios(0x00000001);
//g->digitalWrite(0, HIGH);
}
gettimeofday(&test_now, NULL);
interval = TimevalDiff(&test_now, &test_start);
}
};
void test_gpios(Nysa *nysa, uint32_t dev_index, bool debug){
if (dev_index == 0){
printf ("Device index == 0!, this is the DRT!");
}
struct timeval test_start;
struct timeval test_now;
double interval = 1.0;
double led_interval = 1.0;
printf ("Setting up new gpio device\n");
//Setup GPIO
GPIO *gpio = new GPIO(nysa, dev_index, debug);
printf ("Got new GPIO Device\n");
try {
gpio->pinMode(0, OUTPUT); //LED 0
gpio->pinMode(1, OUTPUT); //LED 1
gpio->pinMode(2, INPUT); //Button 0
gpio->pinMode(3, INPUT); //Button 1
}
catch (int e) {
printf ("Error while setting pinMode: Error: %d\n", e);
}
printf ("set pin modes!\n");
//Length of GPIO tests
gettimeofday(&test_start, NULL);
gettimeofday(&test_now, NULL);
//Pulse width of the LED
interval = TimevalDiff(&test_now, &test_start);
printf ("Interval: %f\n", interval);
breath(gpio, GPIO_TEST_WAIT);
/*
while (interval < GPIO_TEST_WAIT){
gpio->toggle(0);
usleep(1000000);
gettimeofday(&test_now, NULL);
interval = TimevalDiff(&test_now, &test_start);
//printf ("Interval: %f\n", interval);
}
*/
//Loop for about two seconds
printf ("Set 0 to high\n");
gpio->digitalWrite(0, LOW);
gpio->digitalWrite(1, LOW);
}
int main(int argc, char **argv){
struct arguments args;
args.vendor = DIONYSUS_VID;
args.product = DIONYSUS_PID;
args.debug = false;
uint8_t* buffer = new uint8_t [8196];
uint32_t num_devices;
uint32_t device_type = 0;
uint32_t device_addres = 0;
uint32_t device_size = 0;
bool memory_device = false;
bool fail = false;
uint32_t fail_count = 0;
struct timeval start;
struct timeval end;
double interval = 1.0;
double mem_size;
double rate = 0;
uint32_t memory_device_index = 0;
parse_args(&args, argc, argv);
//Dionysus dionysus = Dionysus((uint32_t)DEFAULT_BUFFER_SIZE, args.debug);
Dionysus dionysus = Dionysus(args.debug);
dionysus.open(args.vendor, args.product);
if (dionysus.is_open()){
dionysus.reset();
//dionysus.program_fpga();
//dionysus.soft_reset();
gettimeofday(&start, NULL);
dionysus.ping();
gettimeofday(&end, NULL);
interval = TimevalDiff(&end, &start);
rate = 9 / interval; //Megabytes/Sec
printf ("Time difference: %f\n", interval);
printf ("Ping Rate: %.2f Bytes/Sec\n", rate);
printf ("Reading from the DRT\n");
//dionysus.read_periph_data(0, 0, buffer, 32);
dionysus.read_drt();
for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
printf ("Device %d:\n", i);
printf ("\tType:\t\t0x%08X\n", dionysus.get_drt_device_type(i));
printf ("\tSize:\t\t0x%08X (32-bit values)\n", dionysus.get_drt_device_size(i));
printf ("\tAddress:\t0x%08X\n", dionysus.get_drt_device_addr(i));
if (dionysus.is_memory_device(i)){
printf ("\t\tOn the memory bus\n");
}
}
//Buffer Data:
//for (int i = 0; i < 32; i++){
// printf ("%02X ", buffer[i]);
//}
printf ("\n");
//dionysus.read_periph_data(0, 0, buffer, 4096);
printf ("Peripheral Write Test. read a lot of data from the DRT\n");
printf ("\t(DRT will just ignore this data)\n");
dionysus.write_periph_data(0, 0, buffer, 8192);
printf ("Peripheral Read Test. Read a lot of data from the DRT\n");
printf ("\t(Data from the DRT will just loop)\n");
dionysus.read_periph_data(0, 0, buffer, 8192);
delete(buffer);
printf ("Look for a memory device\n");
if (MEMORY_TEST){
for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
if (dionysus.get_drt_device_type(i) == 5){
memory_device_index = i;
}
}
}
if (memory_device_index > 0){
printf ("Found a memory device at position: %d\n", memory_device_index);
printf ("Memory Test! Read and write: 0x%08X Bytes\n", dionysus.get_drt_device_size(memory_device_index));
buffer = new uint8_t[dionysus.get_drt_device_size(memory_device_index)];
for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
buffer[i] = i;
}
printf ("Testing Full Memory Write Time...\n");
gettimeofday(&start, NULL);
dionysus.write_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index));
gettimeofday(&end, NULL);
interval = TimevalDiff(&end, &start);
mem_size = dionysus.get_drt_device_size(memory_device_index);
rate = mem_size/ interval / 1e6; //Megabytes/Sec
printf ("Time difference: %f\n", interval);
printf ("Write Rate: %.2f MB/Sec\n", rate);
for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
buffer[i] = 0;
}
gettimeofday(&start, NULL);
dionysus.read_memory(0x00000000, buffer, dionysus.get_drt_device_size(memory_device_index));
gettimeofday(&end, NULL);
interval = TimevalDiff(&end, &start);
mem_size = dionysus.get_drt_device_size(memory_device_index);
rate = mem_size/ interval / 1e6; //Megabytes/Sec
printf ("Time difference: %f\n", interval);
printf ("Read Rate: %.2f MB/Sec\n", rate);
for (int i = 0; i < dionysus.get_drt_device_size(memory_device_index); i++){
if (buffer[i] != i % 256){
if (!fail){
if (fail_count > 16){
fail = true;
}
fail_count += 1;
printf ("Failed @ 0x%08X\n", i);
printf ("Value should be: 0x%08X but is: 0x%08X\n", i, buffer[i]);
}
}
}
if (!fail){
printf ("Memory Test Passed!\n");
}
delete (buffer);
}
uint32_t gpio_device = 0;
for (int i = 1; i < dionysus.get_drt_device_count() + 1; i++){
if (dionysus.get_drt_device_type(i) == get_gpio_device_type()){
gpio_device = i;
}
}
if (gpio_device > 0){
test_gpios(&dionysus, gpio_device, args.debug);
}
dionysus.close();
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "DFA.h"
using namespace std;
int main()
{
DFA DFA_each;
DFA_each.InputRegex();//
DFA_each.InsertNode();//
DFA_each.RegextoPost();//תΪʽ
DFA_each.GetEdgeNumber();//ɨ沨ʽгַĿ
DFA_each.Thompson();//Thompson취NFA
DFA_each.NFAtoDFA();//Ӽ취 NFADFA
DFA_each.Hopcroft();//СDFA㷨
DFA_each.InputString();//Ҫƥַ
DFA_each.Match();//ƥ
system("pause");
return 0;
}
<commit_msg>update<commit_after>#include <iostream>
#include "DFA.h"
using namespace std;
int main()
{
DFA DFA_each;
DFA_each.InputRegex();//
DFA_each.InsertNode();//
DFA_each.RegextoPost();//תΪʽ
DFA_each.GetEdgeNumber();//ɨ沨ʽгַĿ
DFA_each.Thompson();//Thompson취NFA
DFA_each.NFAtoDFA();//Ӽ취 NFADFA
DFA_each.Hopcroft();//СDFA㷨
DFA_each.InputString();//Ҫƥַ
DFA_each.Match();//ƥ
cout<<"quit! "<<endl;
return 0;
}
<|endoftext|> |
<commit_before>/*! \file main.cpp
* \brief Program to run the grid code. */
#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"
int main(int argc, char *argv[])
{
// timing variables
double start_total, stop_total, start_step, stop_step;
#ifdef CPU_TIME
double stop_init, init_min, init_max, init_avg;
double start_bound, stop_bound, bound_min, bound_max, bound_avg;
double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
double init, bound, hydro;
init = bound = hydro = 0;
#endif //CPU_TIME
// start the total time
start_total = get_time();
/* Initialize MPI communication */
#ifdef MPI_CHOLLA
InitializeChollaMPI(&argc, &argv);
#endif /*MPI_CHOLLA*/
Real dti = 0; // inverse time step, 1.0 / dt
// input parameter variables
char *param_file;
struct parameters P;
int nfile = 0; // number of output files
Real outtime = 0; // current output time
// read in command line arguments
if (argc != 2)
{
chprintf("usage: %s <parameter_file>\n", argv[0]);
chexit(-1);
} else {
param_file = argv[1];
}
// create the grid
Grid3D G;
// read in the parameters
parse_params (param_file, &P);
// and output to screen
chprintf ("Parameter values: nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
if (strcmp(P.init, "Read_Grid") == 0 ) chprintf ("Input directory: %s\n", P.indir);
chprintf ("Output directory: %s\n", P.outdir);
//Create a Log file to output run-time messages
Create_Log_File(P);
// initialize the grid
G.Initialize(&P);
chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);
char *message = (char*)malloc(50 * sizeof(char));
sprintf(message, "Initializing Simulation" );
Write_Message_To_Log_File( message );
// Set initial conditions and calculate first dt
chprintf("Setting initial conditions...\n");
G.Set_Initial_Conditions(P);
chprintf("Initial conditions set.\n");
// set main variables for Read_Grid initial conditions
if (strcmp(P.init, "Read_Grid") == 0) {
dti = C_cfl / G.H.dt;
outtime += G.H.t;
nfile = P.nfile;
}
#ifdef DE
chprintf("\nUsing Dual Energy Formalism:\n eta_1: %0.3f eta_2: %0.4f\n", DE_ETA_1, DE_ETA_2 );
sprintf(message, " eta_1: %0.3f eta_2: %0.3f ", DE_ETA_1, DE_ETA_2 );
Write_Message_To_Log_File( message );
#endif
#ifdef CPU_TIME
G.Timer.Initialize();
#endif
#ifdef GRAVITY
G.Initialize_Gravity(&P);
#endif
#ifdef PARTICLES
G.Initialize_Particles(&P);
#endif
#ifdef COSMOLOGY
G.Initialize_Cosmology(&P);
#endif
#ifdef COOLING_GRACKLE
G.Initialize_Grackle(&P);
#endif
#ifdef ANALYSIS
G.Initialize_Analysis_Module(&P);
if ( G.Analysis.Output_Now ) G.Compute_and_Output_Analysis(&P);
#endif
#ifdef GRAVITY
// Get the gravitaional potential for the first timestep
G.Compute_Gravitational_Potential( &P);
#endif
// Set boundary conditions (assign appropriate values to ghost cells) for hydro and potential
chprintf("Setting boundary conditions...\n");
G.Set_Boundary_Conditions_Grid(P);
chprintf("Boundary conditions set.\n");
#ifdef GRAVITY_ANALYTIC_COMP
// add analytic component to gravity potential.
G.Add_Analytic_Potential(&P);
#endif
#ifdef PARTICLES
// Get the particles acceleration for the first timestep
G.Get_Particles_Acceleration();
#endif
chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
chprintf("Ratio of specific heats gamma = %f\n",gama);
chprintf("Nstep = %d Timestep = %f Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);
#ifdef OUTPUT
if (strcmp(P.init, "Read_Grid") != 0 || G.H.Output_Now ) {
// write the initial conditions to file
chprintf("Writing initial conditions to file...\n");
#ifdef MPI_GPU
cudaMemcpy(G.C.density, G.C.device,
G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
#endif
WriteData(G, P, nfile);
}
// add one to the output file count
nfile++;
#endif //OUTPUT
// increment the next output time
outtime += P.outstep;
#ifdef CPU_TIME
stop_init = get_time();
init = stop_init - start_total;
#ifdef MPI_CHOLLA
init_min = ReduceRealMin(init);
init_max = ReduceRealMax(init);
init_avg = ReduceRealAvg(init);
chprintf("Init min: %9.4f max: %9.4f avg: %9.4f\n", init_min, init_max, init_avg);
#else
printf("Init %9.4f\n", init);
#endif //MPI_CHOLLA
#endif //CPU_TIME
// Evolve the grid, one timestep at a time
chprintf("Starting calculations.\n");
sprintf(message, "Starting calculations." );
Write_Message_To_Log_File( message );
while (G.H.t < P.tout)
{
// get the start time
start_step = get_time();
// calculate the timestep
G.set_dt(dti);
if (G.H.t + G.H.dt > outtime) G.H.dt = outtime - G.H.t;
#ifdef PARTICLES
//Advance the particles KDK( first step ): Velocities are updated by 0.5*dt and positions are updated by dt
G.Advance_Particles( 1 );
//Transfer the particles that moved outside the local domain
G.Transfer_Particles_Boundaries(P);
#endif
// Advance the grid by one timestep
dti = G.Update_Hydro_Grid();
// update the simulation time ( t += dt )
G.Update_Time();
#ifdef GRAVITY
//Compute Gravitational potential for next step
G.Compute_Gravitational_Potential( &P);
#endif
// add one to the timestep count
G.H.n_step++;
//Set the Grid boundary conditions for next time step
G.Set_Boundary_Conditions_Grid(P);
#ifdef GRAVITY_ANALYTIC_COMP
// add analytic component to gravity potential.
G.Add_Analytic_Potential(&P);
#endif
#ifdef PARTICLES
///Advance the particles KDK( second step ): Velocities are updated by 0.5*dt using the Accelerations at the new positions
G.Advance_Particles( 2 );
#endif
#ifdef PARTICLE_AGE
//G.Cluster_Feedback();
#endif
#ifdef CPU_TIME
G.Timer.Print_Times();
#endif
// get the time to compute the total timestep
stop_step = get_time();
stop_total = get_time();
G.H.t_wall = stop_total-start_total;
#ifdef MPI_CHOLLA
G.H.t_wall = ReduceRealMax(G.H.t_wall);
#endif
chprintf("n_step: %d sim time: %10.7f sim timestep: %7.4e timestep time = %9.3f ms total time = %9.4f s\n\n",
G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);
#ifdef OUTPUT_ALWAYS
G.H.Output_Now = true;
#endif
#ifdef ANALYSIS
if ( G.Analysis.Output_Now ) G.Compute_and_Output_Analysis(&P);
#endif
// if ( P.n_steps_output > 0 && G.H.n_step % P.n_steps_output == 0) G.H.Output_Now = true;
if (G.H.t == outtime || G.H.Output_Now )
{
#ifdef OUTPUT
/*output the grid data*/
#ifdef MPI_GPU
cudaMemcpy(G.C.density, G.C.device,
G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
#endif
WriteData(G, P, nfile);
// add one to the output file count
nfile++;
#endif //OUTPUT
// update to the next output time
outtime += P.outstep;
}
#ifdef CPU_TIME
G.Timer.n_steps += 1;
#endif
#ifdef N_STEPS_LIMIT
// Exit the loop when reached the limit number of steps (optional)
if ( G.H.n_step == N_STEPS_LIMIT) {
#ifdef MPI_GPU
cudaMemcpy(G.C.density, G.C.device,
G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
#endif
WriteData(G, P, nfile);
break;
}
#endif
#ifdef COSMOLOGY
// Exit the loop when reached the last scale_factor output
if ( G.Cosmo.exit_now ) {
chprintf( "\nReached Last Cosmological Output: Ending Simulation\n");
break;
}
#endif
} /*end loop over timesteps*/
#ifdef CPU_TIME
// Print timing statistics
G.Timer.Get_Average_Times();
G.Timer.Print_Average_Times( P );
#endif
sprintf(message, "Simulation completed successfully." );
Write_Message_To_Log_File( message );
// free the grid
G.Reset();
#ifdef MPI_CHOLLA
MPI_Finalize();
#endif /*MPI_CHOLLA*/
return 0;
}
<commit_msg>don't save when reaching last step<commit_after>/*! \file main.cpp
* \brief Program to run the grid code. */
#ifdef MPI_CHOLLA
#include <mpi.h>
#include "mpi_routines.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "global.h"
#include "grid3D.h"
#include "io.h"
#include "error_handling.h"
int main(int argc, char *argv[])
{
// timing variables
double start_total, stop_total, start_step, stop_step;
#ifdef CPU_TIME
double stop_init, init_min, init_max, init_avg;
double start_bound, stop_bound, bound_min, bound_max, bound_avg;
double start_hydro, stop_hydro, hydro_min, hydro_max, hydro_avg;
double init, bound, hydro;
init = bound = hydro = 0;
#endif //CPU_TIME
// start the total time
start_total = get_time();
/* Initialize MPI communication */
#ifdef MPI_CHOLLA
InitializeChollaMPI(&argc, &argv);
#endif /*MPI_CHOLLA*/
Real dti = 0; // inverse time step, 1.0 / dt
// input parameter variables
char *param_file;
struct parameters P;
int nfile = 0; // number of output files
Real outtime = 0; // current output time
// read in command line arguments
if (argc != 2)
{
chprintf("usage: %s <parameter_file>\n", argv[0]);
chexit(-1);
} else {
param_file = argv[1];
}
// create the grid
Grid3D G;
// read in the parameters
parse_params (param_file, &P);
// and output to screen
chprintf ("Parameter values: nx = %d, ny = %d, nz = %d, tout = %f, init = %s, boundaries = %d %d %d %d %d %d\n",
P.nx, P.ny, P.nz, P.tout, P.init, P.xl_bcnd, P.xu_bcnd, P.yl_bcnd, P.yu_bcnd, P.zl_bcnd, P.zu_bcnd);
if (strcmp(P.init, "Read_Grid") == 0 ) chprintf ("Input directory: %s\n", P.indir);
chprintf ("Output directory: %s\n", P.outdir);
//Create a Log file to output run-time messages
Create_Log_File(P);
// initialize the grid
G.Initialize(&P);
chprintf("Local number of grid cells: %d %d %d %d\n", G.H.nx_real, G.H.ny_real, G.H.nz_real, G.H.n_cells);
char *message = (char*)malloc(50 * sizeof(char));
sprintf(message, "Initializing Simulation" );
Write_Message_To_Log_File( message );
// Set initial conditions and calculate first dt
chprintf("Setting initial conditions...\n");
G.Set_Initial_Conditions(P);
chprintf("Initial conditions set.\n");
// set main variables for Read_Grid initial conditions
if (strcmp(P.init, "Read_Grid") == 0) {
dti = C_cfl / G.H.dt;
outtime += G.H.t;
nfile = P.nfile;
}
#ifdef DE
chprintf("\nUsing Dual Energy Formalism:\n eta_1: %0.3f eta_2: %0.4f\n", DE_ETA_1, DE_ETA_2 );
sprintf(message, " eta_1: %0.3f eta_2: %0.3f ", DE_ETA_1, DE_ETA_2 );
Write_Message_To_Log_File( message );
#endif
#ifdef CPU_TIME
G.Timer.Initialize();
#endif
#ifdef GRAVITY
G.Initialize_Gravity(&P);
#endif
#ifdef PARTICLES
G.Initialize_Particles(&P);
#endif
#ifdef COSMOLOGY
G.Initialize_Cosmology(&P);
#endif
#ifdef COOLING_GRACKLE
G.Initialize_Grackle(&P);
#endif
#ifdef ANALYSIS
G.Initialize_Analysis_Module(&P);
if ( G.Analysis.Output_Now ) G.Compute_and_Output_Analysis(&P);
#endif
#ifdef GRAVITY
// Get the gravitaional potential for the first timestep
G.Compute_Gravitational_Potential( &P);
#endif
// Set boundary conditions (assign appropriate values to ghost cells) for hydro and potential
chprintf("Setting boundary conditions...\n");
G.Set_Boundary_Conditions_Grid(P);
chprintf("Boundary conditions set.\n");
#ifdef GRAVITY_ANALYTIC_COMP
// add analytic component to gravity potential.
G.Add_Analytic_Potential(&P);
#endif
#ifdef PARTICLES
// Get the particles acceleration for the first timestep
G.Get_Particles_Acceleration();
#endif
chprintf("Dimensions of each cell: dx = %f dy = %f dz = %f\n", G.H.dx, G.H.dy, G.H.dz);
chprintf("Ratio of specific heats gamma = %f\n",gama);
chprintf("Nstep = %d Timestep = %f Simulation time = %f\n", G.H.n_step, G.H.dt, G.H.t);
#ifdef OUTPUT
if (strcmp(P.init, "Read_Grid") != 0 || G.H.Output_Now ) {
// write the initial conditions to file
chprintf("Writing initial conditions to file...\n");
#ifdef MPI_GPU
cudaMemcpy(G.C.density, G.C.device,
G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
#endif
WriteData(G, P, nfile);
}
// add one to the output file count
nfile++;
#endif //OUTPUT
// increment the next output time
outtime += P.outstep;
#ifdef CPU_TIME
stop_init = get_time();
init = stop_init - start_total;
#ifdef MPI_CHOLLA
init_min = ReduceRealMin(init);
init_max = ReduceRealMax(init);
init_avg = ReduceRealAvg(init);
chprintf("Init min: %9.4f max: %9.4f avg: %9.4f\n", init_min, init_max, init_avg);
#else
printf("Init %9.4f\n", init);
#endif //MPI_CHOLLA
#endif //CPU_TIME
// Evolve the grid, one timestep at a time
chprintf("Starting calculations.\n");
sprintf(message, "Starting calculations." );
Write_Message_To_Log_File( message );
while (G.H.t < P.tout)
{
// get the start time
start_step = get_time();
// calculate the timestep
G.set_dt(dti);
if (G.H.t + G.H.dt > outtime) G.H.dt = outtime - G.H.t;
#ifdef PARTICLES
//Advance the particles KDK( first step ): Velocities are updated by 0.5*dt and positions are updated by dt
G.Advance_Particles( 1 );
//Transfer the particles that moved outside the local domain
G.Transfer_Particles_Boundaries(P);
#endif
// Advance the grid by one timestep
dti = G.Update_Hydro_Grid();
// update the simulation time ( t += dt )
G.Update_Time();
#ifdef GRAVITY
//Compute Gravitational potential for next step
G.Compute_Gravitational_Potential( &P);
#endif
// add one to the timestep count
G.H.n_step++;
//Set the Grid boundary conditions for next time step
G.Set_Boundary_Conditions_Grid(P);
#ifdef GRAVITY_ANALYTIC_COMP
// add analytic component to gravity potential.
G.Add_Analytic_Potential(&P);
#endif
#ifdef PARTICLES
///Advance the particles KDK( second step ): Velocities are updated by 0.5*dt using the Accelerations at the new positions
G.Advance_Particles( 2 );
#endif
#ifdef PARTICLE_AGE
//G.Cluster_Feedback();
#endif
#ifdef CPU_TIME
G.Timer.Print_Times();
#endif
// get the time to compute the total timestep
stop_step = get_time();
stop_total = get_time();
G.H.t_wall = stop_total-start_total;
#ifdef MPI_CHOLLA
G.H.t_wall = ReduceRealMax(G.H.t_wall);
#endif
chprintf("n_step: %d sim time: %10.7f sim timestep: %7.4e timestep time = %9.3f ms total time = %9.4f s\n\n",
G.H.n_step, G.H.t, G.H.dt, (stop_step-start_step)*1000, G.H.t_wall);
#ifdef OUTPUT_ALWAYS
G.H.Output_Now = true;
#endif
#ifdef ANALYSIS
if ( G.Analysis.Output_Now ) G.Compute_and_Output_Analysis(&P);
#endif
// if ( P.n_steps_output > 0 && G.H.n_step % P.n_steps_output == 0) G.H.Output_Now = true;
if (G.H.t == outtime || G.H.Output_Now )
{
#ifdef OUTPUT
/*output the grid data*/
#ifdef MPI_GPU
cudaMemcpy(G.C.density, G.C.device,
G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
#endif
WriteData(G, P, nfile);
// add one to the output file count
nfile++;
#endif //OUTPUT
// update to the next output time
outtime += P.outstep;
}
#ifdef CPU_TIME
G.Timer.n_steps += 1;
#endif
#ifdef N_STEPS_LIMIT
// Exit the loop when reached the limit number of steps (optional)
if ( G.H.n_step == N_STEPS_LIMIT) {
#ifndef COSMOLOGY
#ifdef MPI_GPU
cudaMemcpy(G.C.density, G.C.device,
G.H.n_fields*G.H.n_cells*sizeof(Real), cudaMemcpyDeviceToHost);
#endif
WriteData(G, P, nfile);
#endif //COSMOLOGY
break;
}
#endif
#ifdef COSMOLOGY
// Exit the loop when reached the last scale_factor output
if ( G.Cosmo.exit_now ) {
chprintf( "\nReached Last Cosmological Output: Ending Simulation\n");
break;
}
#endif
} /*end loop over timesteps*/
#ifdef CPU_TIME
// Print timing statistics
G.Timer.Get_Average_Times();
G.Timer.Print_Average_Times( P );
#endif
sprintf(message, "Simulation completed successfully." );
Write_Message_To_Log_File( message );
// free the grid
G.Reset();
#ifdef MPI_CHOLLA
MPI_Finalize();
#endif /*MPI_CHOLLA*/
return 0;
}
<|endoftext|> |
<commit_before>#include <fstream>
#include <iostream>
#include <Refal2.h>
using namespace Refal2;
class CMyClass :
public IVariablesBuilderListener,
public IFunctionBuilderListener,
public IScannerListener,
public IParserListener
{
public:
virtual void OnScannerError(const TScannerErrorCodes errorCode, char c);
virtual void OnParserError(const TParserErrorCodes errorCode);
virtual void OnFunctionBuilderError(const TFunctionBuilderErrorCodes errorCode);
virtual void OnVariablesBuilderError(const TVariablesBuilderErrorCodes errorCode);
};
void CMyClass::OnScannerError(const TScannerErrorCodes errorCode, char c)
{
static const char* errorText[] = {
"SEC_UnexpectedControlSequence",
"SEC_SymbolAfterPlus",
"SEC_UnexpectedCharacter",
"SEC_IllegalCharacterInLabelOrNumberBegin",
"SEC_IllegalCharacterInLabel",
"SEC_IllegalCharacterInNumber",
"SEC_IllegalCharacterInQualifierNameBegin",
"SEC_IllegalCharacterInQualifierName",
"SEC_IllegalCharacterInStringAfterBackslash",
"SEC_IllegalCharacterInStringInHexadecimal",
"SEC_TryingAppendNullByteToString",
"SEC_IllegalCharacterInStringInOctal",
"SEC_UnclosedStringConstantAtTheEndOfFile",
"SEC_UnclosedStringConstant",
"SEC_UnclosedLabelOrNumberAtTheEndOfFile",
"SEC_UnclosedLabelOrNumber",
"SEC_UnclosedLabelAtTheEndOfFile",
"SEC_UnclosedLabel",
"SEC_UnclosedNumberAtTheEndOfFile",
"SEC_UnclosedNumber",
"SEC_UnclosedQualifierAtTheEndOfFile",
"SEC_UnclosedQualifier",
"SEC_UnexpectedEndOfFil"
};
std::cout << "ScannerError: " /*<< line << ": " << localOffset << ": "*/;
/*if( c != '\0' ) {
std::cout << c << ": ";
}*/
std::cout << errorText[errorCode] << "\n";
}
void CMyClass::OnParserError(const TParserErrorCodes errorCode)
{
static const char* errorText[] = {
"PEC_LineShouldBeginWithIdentifierOrSpace",
"PEC_NewLineExpected",
"PEC_UnexpectedLexemeAfterIdentifierInTheBeginningOfLine",
"PEC_STUB"
};
std::cout << errorText[errorCode] << "\n";
}
void CMyClass::OnFunctionBuilderError(const Refal2::TFunctionBuilderErrorCodes errorCode)
{
static const char* errorText[] = {
"FBEC_ThereAreNoRulesInFunction",
"FBEC_IllegalLeftBracketInLeftPart",
"FBEC_IllegalRightBracketInLeftPart",
"FBEC_RightParenDoesNotMatchLeftParen",
"FBEC_RightBracketDoesNotMatchLeftBracket",
"FBEC_UnclosedLeftParenInLeftPart",
"FBEC_UnclosedLeftParenInRightPart",
"FBEC_UnclosedLeftBracketInRightPart",
"FBEC_IllegalQualifierInRightPart"
};
printf("CFunctionBuilder error: %s\n", errorText[errorCode]);
}
void CMyClass::OnVariablesBuilderError(const Refal2::TVariablesBuilderErrorCodes errorCode)
{
static const char* errorText[] = {
"VBEC_InvalidVatiableName",
"VBEC_NoSuchTypeOfVariable",
"VBEC_TypeOfVariableDoesNotMatch",
"VBEC_NoSuchVariableInLeftPart"
};
printf("CVariablesBuilder error: %s\n", errorText[errorCode]);
}
int main(int argc, const char* argv[])
{
try {
const char* filename = "../tests/btest.ref";
//const char* filename = "../tests/PROGRAM.REF";
if( argc == 2 ) {
filename = argv[1];
}
CMyClass ca;
CParser parser( &ca );
std::ifstream f( filename );
if( !f.good() ) {
std::cerr << "Can't open file\n";
return 1;
}
while( true ) {
int c = f.get();
if( c == -1 ) {
parser.AddEndOfFile();
break;
} else {
parser.AddChar(c);
}
}
std::cout << "\n--------------------------------------------------\n\n";
if( parser.HasErrors() ) {
std::cout << "Errors!\n\n";
return 0;
}
COperationList program;
for( int i = LabelTable.GetFirstLabel(); i != InvalidLabel;
i = LabelTable.GetNextLabel( i ) )
{
CFunction& function = LabelTable.GetLabelFunction( i );
if( function.IsParsed() ) {
std::cout << "{START:" << LabelTable.GetLabelText( i ) << "}\n";
PrintFunction( function );
CFunctionCompiler compiler;
compiler.Compile( &function );
std::cout << "{END:" << LabelTable.GetLabelText( i ) << "}\n";
COperationNode* operation = program.GetLast();
compiler.Export( program );
operation = operation == 0 ? program.GetFirst() : operation->Next();
function.SetCompiled( operation );
}
}
std::cout << "\n--------------------------------------------------\n\n";
TLabel entryLabel = parser.GetEntryLabel();
if( entryLabel == InvalidLabel ) {
entryLabel = LabelTable.AddLabel( "go" );
}
assert( LabelTable.GetLabelFunction( entryLabel ).IsCompiled() );
CUnitList fieldOfView;
CUnitNode* errorCall = 0;
TExecutionResult executionResult = COperationsExecuter::Run( entryLabel,
fieldOfView, errorCall );
std::cout << "\n--------------------------------------------------\n\n";
switch( executionResult ) {
case ER_OK:
std::cout << "OK!\nFieldOfView: ";
break;
case ER_RecognitionImpossible:
std::cout << "RecognitionImpossible!\nFieldOfView: ";
break;
case ER_CallEmptyFunction:
std::cout << "CallEmptyFunction!\nFieldOfView: ";
break;
case ER_LostFunctionLabel:
std::cout << "LostFunctionLabel!\nFieldOfView: ";
break;
case ER_WrongArgumentOfExternalFunction:
std::cout << "WrongArgumentOfExternalFunction!\nFieldOfView: ";
break;
default:
assert( false );
break;
}
HandyPrintFieldOfView( fieldOfView );
} catch( bool ) {
return 1;
}
return 0;
}
<commit_msg>small changes in main.cpp<commit_after>#include <fstream>
#include <iostream>
#include <Refal2.h>
using namespace Refal2;
class CErrorProcessor :
public IVariablesBuilderListener,
public IFunctionBuilderListener,
public IScannerListener,
public IParserListener
{
public:
virtual void OnScannerError( const TScannerErrorCodes errorCode, char c );
virtual void OnParserError( const TParserErrorCodes errorCode );
virtual void OnFunctionBuilderError(
const TFunctionBuilderErrorCodes errorCode );
virtual void OnVariablesBuilderError(
const TVariablesBuilderErrorCodes errorCode );
};
void CErrorProcessor::OnScannerError( const TScannerErrorCodes errorCode,
char c )
{
static const char* errorText[] = {
"SEC_UnexpectedControlSequence",
"SEC_SymbolAfterPlus",
"SEC_UnexpectedCharacter",
"SEC_IllegalCharacterInLabelOrNumberBegin",
"SEC_IllegalCharacterInLabel",
"SEC_IllegalCharacterInNumber",
"SEC_IllegalCharacterInQualifierNameBegin",
"SEC_IllegalCharacterInQualifierName",
"SEC_IllegalCharacterInStringAfterBackslash",
"SEC_IllegalCharacterInStringInHexadecimal",
"SEC_TryingAppendNullByteToString",
"SEC_IllegalCharacterInStringInOctal",
"SEC_UnclosedStringConstantAtTheEndOfFile",
"SEC_UnclosedStringConstant",
"SEC_UnclosedLabelOrNumberAtTheEndOfFile",
"SEC_UnclosedLabelOrNumber",
"SEC_UnclosedLabelAtTheEndOfFile",
"SEC_UnclosedLabel",
"SEC_UnclosedNumberAtTheEndOfFile",
"SEC_UnclosedNumber",
"SEC_UnclosedQualifierAtTheEndOfFile",
"SEC_UnclosedQualifier",
"SEC_UnexpectedEndOfFil"
};
/*std::cout << "ScannerError: " << line << ": " << localOffset << ": ";
if( c != '\0' ) {
std::cout << c << ": ";
}*/
std::cout << errorText[errorCode] << std::endl;
}
void CErrorProcessor::OnParserError( const TParserErrorCodes errorCode )
{
static const char* errorText[] = {
"PEC_LineShouldBeginWithIdentifierOrSpace",
"PEC_NewLineExpected",
"PEC_UnexpectedLexemeAfterIdentifierInTheBeginningOfLine",
"PEC_STUB"
};
std::cout << errorText[errorCode] << std::endl;
}
void CErrorProcessor::OnFunctionBuilderError(
const Refal2::TFunctionBuilderErrorCodes errorCode )
{
static const char* errorText[] = {
"FBEC_ThereAreNoRulesInFunction",
"FBEC_IllegalLeftBracketInLeftPart",
"FBEC_IllegalRightBracketInLeftPart",
"FBEC_RightParenDoesNotMatchLeftParen",
"FBEC_RightBracketDoesNotMatchLeftBracket",
"FBEC_UnclosedLeftParenInLeftPart",
"FBEC_UnclosedLeftParenInRightPart",
"FBEC_UnclosedLeftBracketInRightPart",
"FBEC_IllegalQualifierInRightPart"
};
std::cout << errorText[errorCode] << std::endl;
}
void CErrorProcessor::OnVariablesBuilderError(
const Refal2::TVariablesBuilderErrorCodes errorCode )
{
static const char* errorText[] = {
"VBEC_InvalidVatiableName",
"VBEC_NoSuchTypeOfVariable",
"VBEC_TypeOfVariableDoesNotMatch",
"VBEC_NoSuchVariableInLeftPart"
};
std::cout << errorText[errorCode] << std::endl;
}
int main( int argc, const char* argv[] )
{
try {
const char* filename = "../tests/btest.ref";
if( argc == 2 ) {
filename = argv[1];
}
CErrorProcessor errorProcessor;
CParser parser( &errorProcessor );
std::ifstream f( filename );
if( !f.good() ) {
std::cerr << "Can't open file\n";
return 1;
}
while( true ) {
int c = f.get();
if( c == -1 ) {
parser.AddEndOfFile();
break;
} else {
parser.AddChar(c);
}
}
std::cout << "\n--------------------------------------------------\n\n";
if( parser.HasErrors() ) {
std::cout << "Errors!\n\n";
return 0;
}
COperationList program;
for( int i = LabelTable.GetFirstLabel(); i != InvalidLabel;
i = LabelTable.GetNextLabel( i ) )
{
CFunction& function = LabelTable.GetLabelFunction( i );
if( function.IsParsed() ) {
std::cout << "{START:" << LabelTable.GetLabelText( i ) << "}\n";
PrintFunction( function );
CFunctionCompiler compiler;
compiler.Compile( &function );
std::cout << "{END:" << LabelTable.GetLabelText( i ) << "}\n";
COperationNode* operation = program.GetLast();
compiler.Export( program );
operation = operation == 0 ? program.GetFirst() : operation->Next();
function.SetCompiled( operation );
}
}
std::cout << "\n--------------------------------------------------\n\n";
TLabel entryLabel = parser.GetEntryLabel();
if( entryLabel == InvalidLabel ) {
entryLabel = LabelTable.AddLabel( "go" );
}
assert( LabelTable.GetLabelFunction( entryLabel ).IsCompiled() );
CUnitList fieldOfView;
CUnitNode* errorCall = 0;
TExecutionResult executionResult = COperationsExecuter::Run( entryLabel,
fieldOfView, errorCall );
std::cout << "\n--------------------------------------------------\n\n";
switch( executionResult ) {
case ER_OK:
std::cout << "OK!\nFieldOfView: ";
break;
case ER_RecognitionImpossible:
std::cout << "RecognitionImpossible!\nFieldOfView: ";
break;
case ER_CallEmptyFunction:
std::cout << "CallEmptyFunction!\nFieldOfView: ";
break;
case ER_LostFunctionLabel:
std::cout << "LostFunctionLabel!\nFieldOfView: ";
break;
case ER_WrongArgumentOfExternalFunction:
std::cout << "WrongArgumentOfExternalFunction!\nFieldOfView: ";
break;
default:
assert( false );
break;
}
HandyPrintFieldOfView( fieldOfView );
} catch( bool ) {
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "readimage.h"
#include "gpudm.h"
#include "parseconfig.h"
#include "hyperspectral.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
if (argc < 3){
cout << "Usage: " << argv[0] << " infilename outfilename" << endl;
exit(1);
}
readConfigFile("configfile.xml");
//read image to BIL-interleaved float-array
char *filename = argv[1];
size_t offset;
HyspexHeader header;
readHeader(filename, &header);
ImageSubset subset;
subset.startSamp = 0;
subset.endSamp = header.samples;
subset.startLine = 0;
subset.endLine = header.lines;
float *data = new float[header.lines*header.samples*header.bands];
readImage(filename, &header, subset, data);
float *wlens = new float[header.bands];
for (int i=0; i < header.bands; i++){
wlens[i] = header.wlens[i];
}
int lines = header.lines;
int bands = bands;
int samples = header.samples;
//prepare gpudm arrays
GPUDMParams params;
gpudm_initialize(¶ms, samples, bands, wlens);
//prepare output arrays
float *res_530 = new float[samples*lines*params.lsq_w530->fitting_numEndmembers];
float *res_700 = new float[samples*lines*params.lsq_w700->fitting_numEndmembers];
for (int i=0; i < lines; i++){
float *lineRefl = data + i*samples*bands;
gpudm_fit_reflectance(¶ms, lineRefl);
//result from interval around 500 nm
float *res_line_530 = res_530 + samples*params.lsq_w530->fitting_numEndmembers*i;
gpudm_download_530res(¶ms, res_line_530);
//result from interval around 700 nm
float *res_line_700 = res_700 + samples*params.lsq_w700->fitting_numEndmembers*i;
gpudm_download_700res(¶ms, res_line_700);
}
//write results to hyperspectral files
Hyperspectral *hyp530res = new Hyperspectral(res_530, lines, samples, params.lsq_w530->fitting_numEndmembers, BIL);
hyp530res->writeToFile(string(argv[2]) + "_530res");
Hyperspectral *hyp700res = new Hyperspectral(res_700, lines, samples, params.lsq_w700->fitting_numEndmembers, BIL);
hyp700res->writeToFile(string(argv[2]) + "_700res");
delete [] res_530;
delete [] res_700;
delete [] data;
delete hyp530res;
delete hyp700res;
gpudm_free(¶ms);
}
<commit_msg>Changed main.cpp example to be slightly saner.<commit_after>#include "readimage.h"
#include "gpudm.h"
#include "parseconfig.h"
#include "hyperspectral.h"
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
if (argc < 3){
cout << "Usage: " << argv[0] << " infilename outfilename" << endl;
exit(1);
}
readConfigFile("configfile.xml");
//read image to BIL-interleaved float-array
char *filename = argv[1];
size_t offset;
HyspexHeader header;
readHeader(filename, &header);
ImageSubset subset;
subset.startSamp = 0;
subset.endSamp = header.samples;
subset.startLine = 0;
subset.endLine = header.lines;
float *data = new float[header.lines*header.samples*header.bands];
readImage(filename, &header, subset, data);
float *wlens = new float[header.bands];
for (int i=0; i < header.bands; i++){
wlens[i] = header.wlens[i];
}
int lines = header.lines;
int bands = header.bands;
int samples = 1600;
//prepare gpudm arrays
GPUDMParams params;
gpudm_initialize(¶ms, samples, bands, wlens);
//prepare output arrays
float *res_530 = new float[samples*lines*params.lsq_w530->fitting_numEndmembers];
float *res_700 = new float[samples*lines*params.lsq_w700->fitting_numEndmembers];
for (int i=0; i < lines; i++){
float *lineReflOrig = data + i*header.samples*bands;
float *lineRefl = new float[samples*bands]();
for (int j=0; j < samples; j++){
for (int k=0; k < bands; k++){
lineRefl[k*samples + j] = lineReflOrig[k*header.samples + j];
}
}
gpudm_fit_reflectance(¶ms, lineRefl);
//result from interval around 500 nm
float *res_line_530 = res_530 + samples*params.lsq_w530->fitting_numEndmembers*i;
gpudm_download_530res(¶ms, res_line_530);
//result from interval around 700 nm
float *res_line_700 = res_700 + samples*params.lsq_w700->fitting_numEndmembers*i;
gpudm_download_700res(¶ms, res_line_700);
delete [] lineRefl;
}
//write results to hyperspectral files
Hyperspectral *hyp530res = new Hyperspectral(res_530, lines, samples, params.lsq_w530->fitting_numEndmembers, BIL);
hyp530res->writeToFile(string(argv[2]) + "_530res");
Hyperspectral *hyp700res = new Hyperspectral(res_700, lines, samples, params.lsq_w700->fitting_numEndmembers, BIL);
hyp700res->writeToFile(string(argv[2]) + "_700res");
delete [] res_530;
delete [] res_700;
delete [] data;
delete hyp530res;
delete hyp700res;
gpudm_free(¶ms);
}
<|endoftext|> |
<commit_before>#include "particle.hpp"
#include "scene.hpp"
#include <SFML/Graphics.hpp>
#include <string>
#include <iostream>
#include <sstream>
int main()
{
SmokeShape shape_ref;
shape_ref.m_Shape.setRadius(10.f);
Scene scene;
sf::Font font;
font.loadFromFile("menu_font.ttf");
sf::Text text;
text.setPosition({50.f,90.f});
text.setFont(font);
SceneNode &node1 =scene.getRootNode();
ParticleEmitter<SmokeShape> p(shape_ref, node1, 1000);
p.setFrequency(60);
// p.setPosition({400.f, 300.f});
sf::RenderWindow window({800,600}, "toto");
sf::Clock clock;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed) window.close();
}
std::ostringstream stream;
stream << p.getNumberOfParticles();
text.setString("Particules : " + stream.str());
node1.setPosition(window.mapPixelToCoords(sf::Mouse::getPosition(window)));
p.update(clock.getElapsedTime());
clock.restart();
window.clear(sf::Color::Cyan);
window.draw(scene);
window.draw(text);
window.display();
}
return 0;
}
//#include "cpp_std_11.hpp"
//
//#include <SFML/Graphics.hpp>
//#include <iostream>
//#include "gamescreenstate.hpp"
//#include "menuscreenstate.hpp"
//#include "screenstack.hpp"
//#include "resourcemanager.hpp"
//
//
//int main(int argc, char** argv)
//{
// sf::RenderWindow window;
// sf::String window_title = "Ludum Dare 35";
// sf::VideoMode window_mode (800,600);
//
// window.create(window_mode, window_title);
// window.setFramerateLimit(60);
//
//
// ScreenStack screenStack;
// screenStack.registerState(ScreenState::Menu, make_unique<MenuScreenState>());
//// screenStack.registerState(ScreenState::Game, make_unique<GameScreenState>());
//
//// screenStack.pushState(ScreenState::Game);
// screenStack.pushState(ScreenState::Menu);
// sf::Event event;
// sf::Clock clock;
//
// while (window.isOpen()) {
// while (window.pollEvent(event)) {
// if (event.type == sf::Event::Closed)
// window.close();
// else
// //menu_screen_state.event(window, event);
// screenStack.onEvent(window, event);
// }
//
// window.clear();
// screenStack.onDraw(window);
// //menu_screen_state.render(window);
// window.display();
// //screenStack.window_update(window);
// screenStack.onUpdate(clock.getElapsedTime());
// //menu_screen_state.update(clock.getElapsedTime());
// clock.restart();
//
// }
//}
<commit_msg>Restore previous main.cpp.<commit_after>#include "cpp_std_11.hpp"
#include <SFML/Graphics.hpp>
#include <iostream>
#include "gamescreenstate.hpp"
#include "menuscreenstate.hpp"
#include "screenstack.hpp"
#include "resourcemanager.hpp"
int main(int argc, char** argv)
{
sf::RenderWindow window;
sf::String window_title = "Ludum Dare 35";
sf::VideoMode window_mode (800,600);
window.create(window_mode, window_title);
window.setFramerateLimit(60);
ScreenStack screenStack;
screenStack.registerState(ScreenState::Menu, make_unique<MenuScreenState>());
// screenStack.registerState(ScreenState::Game, make_unique<GameScreenState>());
// screenStack.pushState(ScreenState::Game);
screenStack.pushState(ScreenState::Menu);
sf::Event event;
sf::Clock clock;
while (window.isOpen()) {
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
else
//menu_screen_state.event(window, event);
screenStack.onEvent(window, event);
}
window.clear();
screenStack.onDraw(window);
//menu_screen_state.render(window);
window.display();
//screenStack.window_update(window);
screenStack.onUpdate(clock.getElapsedTime());
//menu_screen_state.update(clock.getElapsedTime());
clock.restart();
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <memory>
#include "DataLoader.h"
int test0 () {
DataLoader *loader = new DataLoader();
loader->e = 10;
int e = loader->e;
int r = loader->loadCSV();
cout << e + r << endl;
return 0;
}
int test1 () {
std::unique_ptr <DataLoader> loader(new DataLoader());
loader->e = 100;
int r = loader->loadCSV();
cout << loader->e + r << endl;
return 0;
}
int test2 () {
std::unique_ptr <DataLoader> loader(new DataLoader());
std::unique_ptr <string> fname(new string("/Users/daiki/GitHubRepos/sandbox/hellocpp/android_names.txt"));
// &fname: アドレス番地が見れる
// *fname: 格納されているものが見れる
cout << &fname << endl;
cout << *fname << endl;
loader->loadText(fname->c_str());
return 0;
}
int main() {
cout << "Hello, World!\n" << endl;
test2();
return 0;
}<commit_msg>こうやっても書ける<commit_after>#include <iostream>
#include <memory>
#include "DataLoader.h"
int test0 () {
DataLoader *loader = new DataLoader();
loader->e = 10;
int e = loader->e;
int r = loader->loadCSV();
cout << e + r << endl;
return 0;
}
int test1 () {
std::unique_ptr <DataLoader> loader(new DataLoader());
loader->e = 100;
int r = loader->loadCSV();
cout << loader->e + r << endl;
return 0;
}
int test2 () {
std::unique_ptr <DataLoader> loader(new DataLoader());
std::unique_ptr <string> fname(new string("/Users/daiki/GitHubRepos/sandbox/hellocpp/android_names.txt"));
std::string fn = "/Users/daiki/GitHubRepos/sandbox/hellocpp/android_names.txt";
// &fname: アドレス番地が見れる
// *fname: 格納されているものが見れる
cout << &fn << endl;
cout << fn << endl;
//loader->loadText(fname->c_str());
loader->loadText(fn);
return 0;
}
int main() {
cout << "Hello, World!\n" << endl;
test2();
return 0;
}<|endoftext|> |
<commit_before>// BUG: this whole thing depends on the specifics of how the clang version I
// am using emits llvm bitcode for the hacky RMC protocol.
// We rely on how basic blocks get named, on the labels forcing things
// into their own basic blocks, and probably will rely on this block
// having one predecessor and one successor. We could probably even
// force those to be empty without too much work by adding more labels...
#include <llvm/Pass.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/CFG.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/raw_ostream.h>
#include <ostream>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
using namespace llvm;
namespace {
#if 0 // I hate you, emacs. Is there a better way to work around this?
}
#endif
/* To do bogus data dependencies, we will emit inline assembly
instructions. This is sort of tasteless; we should add an intrinsic;
but it means we don't need to modify llvm. This is what the
instruction should look like (probably the constraints aren't
right?):
%2 = call i32 asm sideeffect "eor $0, $0;", "=r,0"(i32 %1) #2, !srcloc !11
Also for ctrlisb we do:
call void asm sideeffect "cmp $0, $0;beq 1f;1: isb", "r,~{memory}"(i32 %1) #2, !srcloc !4
And for dmb:
call void asm sideeffect "dmb", "~{memory}"() #2, !srcloc !5
We can probably do a bogus inline asm on x86 to prevent reordering:
%2 = call i32 asm sideeffect "", "=r,r,0,~{dirflag},~{fpsr},~{flags}"(i32 %1, i32 %0) #3, !srcloc !9
What about this makes the right value come out:
=r specifies an output parameter and the 0 says that that input parameter
is paired with param 0.
Hm. Does this *actually* work?? What does "sideeffect" actually mean
for asm and do we need it.
--
Should we emit dmb directly, or try to use llvm's fences?
*/
//// Some auxillary data structures
enum RMCEdgeType {
VisbilityEdge,
ExecutionEdge
};
raw_ostream& operator<<(raw_ostream& os, const RMCEdgeType& t) {
switch (t) {
case VisbilityEdge:
os << "v";
break;
case ExecutionEdge:
os << "x";
break;
default:
os << "?";
break;
}
return os;
}
// Info about an RMC edge
struct RMCEdge {
RMCEdgeType edgeType;
BasicBlock *src;
BasicBlock *dst;
bool operator<(const RMCEdge& rhs) const {
return std::tie(edgeType, src, dst)
< std::tie(rhs.edgeType, rhs.src, rhs.dst);
}
void print(raw_ostream &os) const {
// substr(5) is to drop "_rmc_" from the front
os << src->getName().substr(5) << " -" << edgeType <<
"-> " << dst->getName().substr(5);
}
};
raw_ostream& operator<<(raw_ostream& os, const RMCEdge& e) {
e.print(os);
return os;
}
// Information for a node in the RMC graph.
struct Block {
Block(BasicBlock *p_bb) : bb(p_bb), stores(0), loads(0), RMWs(0), calls(0) {}
void operator=(const Block &) LLVM_DELETED_FUNCTION;
Block(const Block &) LLVM_DELETED_FUNCTION;
Block(Block &&) = default; // move constructor!
BasicBlock *bb;
// Some basic info about what sort of instructions live in the block
int stores;
int loads;
int RMWs;
int calls;
// Edges in the graph.
// XXX: Would we be better off storing this some other way?
// a <ptr, type> pair?
// And should we store v edges in x
SmallPtrSet<Block *, 2> execEdges;
SmallPtrSet<Block *, 2> visEdges;
};
// Code to find all simple paths between two basic blocks.
// Could generalize more to graphs if we wanted, but I don't right
// now.
typedef std::vector<BasicBlock *> Path;
typedef SmallVector<Path, 2> PathList;
typedef SmallPtrSet<BasicBlock *, 8> GreySet;
PathList findAllSimplePaths_(GreySet *grey, BasicBlock *src, BasicBlock *dst) {
PathList paths;
if (grey->count(src)) return paths;
if (src == dst) {
Path path;
path.push_back(dst);
paths.push_back(std::move(path));
return paths;
}
grey->insert(src);
// Go search all the successors
for (auto i = succ_begin(src), e = succ_end(src); i != e; i++) {
PathList subpaths = findAllSimplePaths_(grey, *i, dst);
std::move(subpaths.begin(), subpaths.end(), back_inserter(paths));
}
// Add our step to all of the vectors
for (auto & path : paths) {
path.push_back(src);
}
// Remove it from the set of things we've seen. We might come
// through here again.
// We can't really do any sort of memoization, since in a cyclic
// graph the possible simple paths depend not just on what node we
// are on, but our previous path (to avoid looping).
grey->erase(src);
return paths;
}
PathList findAllSimplePaths(BasicBlock *src, BasicBlock *dst) {
GreySet grey;
return findAllSimplePaths_(&grey, src, dst);
}
void dumpPaths(const PathList &paths) {
for (auto & path : paths) {
for (auto block : path) {
errs() << block->getName() << " <- ";
}
errs() << "\n";
}
}
// XXX: This is the wrong way to do this!
bool targetARM = true;
bool targetx86 = false;
// Some llvm nonsense. I should probably find a way to clean this up.
// do we put ~{dirflag},~{fpsr},~{flags} for the x86 ones? don't think so.
Instruction *makeSync(Value *dummy) {
LLVMContext &C = dummy->getContext();
FunctionType *f_ty = FunctionType::get(FunctionType::getVoidTy(C), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "dmb", "~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "msync", "~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "sync");
}
Instruction *makeLwsync(Value *dummy) {
LLVMContext &C = dummy->getContext();
FunctionType *f_ty = FunctionType::get(FunctionType::getVoidTy(C), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "dmb", "~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "", "~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "lwsync");
}
Instruction *makeCtrlIsync(Value *v) {
LLVMContext &C = v->getContext();
FunctionType *f_ty =
FunctionType::get(FunctionType::getVoidTy(C), v->getType(), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "cmp $0, $0;beq 1f;1: isb", "r,~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "", "r,~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "ctrlisync");
}
// We also need to add a thing for fake data deps, which is more annoying.
//// Actual code for the pass
class RMCPass : public FunctionPass {
private:
std::vector<Block> blocks_;
DenseMap<BasicBlock *, Block *> bb2block_;
public:
static char ID;
RMCPass() : FunctionPass(ID) {
}
~RMCPass() { }
std::vector<RMCEdge> findEdges(Function &F);
void buildGraph(std::vector<RMCEdge> &edges, Function &F);
virtual bool runOnFunction(Function &F);
};
bool nameMatches(StringRef blockName, StringRef target) {
StringRef name = "_rmc_" + target.str() + "_";
if (!blockName.startswith(name)) return false;
// Now make sure the rest is an int
APInt dummy;
return !blockName.drop_front(name.size()).getAsInteger(10, dummy);
}
StringRef getStringArg(Value *v) {
const Value *g = cast<Constant>(v)->stripPointerCasts();
const Constant *ptr = cast<GlobalVariable>(g)->getInitializer();
StringRef str = cast<ConstantDataSequential>(ptr)->getAsString();
// Drop the '\0' at the end
return str.drop_back();
}
std::vector<RMCEdge> RMCPass::findEdges(Function &F) {
std::vector<RMCEdge> edges;
for (inst_iterator is = inst_begin(F), ie = inst_end(F); is != ie;) {
// Grab the instruction and advance the iterator at the start, since
// we might delete the instruction.
Instruction *i = &*is;
is++;
CallInst *load = dyn_cast<CallInst>(i);
if (!load) continue;
Function *target = load->getCalledFunction();
// We look for calls to the bogus function
// __rmc_edge_register, pull out the information about them,
// and delete the calls.
if (!target || target->getName() != "__rmc_edge_register") continue;
// Pull out what the operands have to be.
// We just assert if something is wrong, which is not great UX.
bool isVisibility = cast<ConstantInt>(load->getOperand(0))
->getValue().getBoolValue();
RMCEdgeType edgeType = isVisibility ? VisbilityEdge : ExecutionEdge;
StringRef srcName = getStringArg(load->getOperand(1));
StringRef dstName = getStringArg(load->getOperand(2));
// Since multiple blocks can have the same tag, we search for
// them by name.
// We could make this more efficient by building maps but I don't think
// it is going to matter.
for (auto & src : F) {
if (!nameMatches(src.getName(), srcName)) continue;
for (auto & dst : F) {
if (!nameMatches(dst.getName(), dstName)) continue;
edges.push_back({edgeType, &src, &dst});
}
}
// Delete the bogus call.
i->eraseFromParent();
}
return edges;
}
void analyzeBlock(Block &info) {
for (auto & i : *info.bb) {
if (isa<LoadInst>(i)) {
info.loads++;
} else if (isa<StoreInst>(i)) {
info.stores++;
// What else counts as a call? I'm counting fences I guess.
} else if (isa<CallInst>(i) || isa<FenceInst>(i)) {
info.calls++;
} else if (isa<AtomicCmpXchgInst>(i) || isa<AtomicRMWInst>(i)) {
info.RMWs++;
}
}
}
void RMCPass::buildGraph(std::vector<RMCEdge> &edges, Function &F) {
// First, collect all the basic blocks with edges attached to them
SmallPtrSet<BasicBlock *, 8> basicBlocks;
for (auto & edge : edges) {
basicBlocks.insert(edge.src);
basicBlocks.insert(edge.dst);
}
// Now, make the vector of blocks and a mapping from BasicBlock *.
blocks_.reserve(basicBlocks.size());
for (auto bb : basicBlocks) {
blocks_.emplace_back(bb);
bb2block_[bb] = &blocks_.back();
}
// Analyze the instructions in blocks to see what sort of actions
// they peform.
for (auto & block : blocks_) {
analyzeBlock(block);
}
// Build our list of edges into a more explicit graph
for (auto & edge : edges) {
Block *src = bb2block_[edge.src];
Block *dst = bb2block_[edge.dst];
if (edge.edgeType == VisbilityEdge) {
src->visEdges.insert(dst);
} else {
src->execEdges.insert(dst);
}
}
}
bool RMCPass::runOnFunction(Function &F) {
auto edges = findEdges(F);
for (auto & edge : edges) {
errs() << "Found an edge: " << edge << "\n";
}
buildGraph(edges, F);
bool changed = !edges.empty();
// Clear our data structures to save memory, make things clean for
// future runs.
blocks_.clear();
bb2block_.clear();
return changed;
}
char RMCPass::ID = 0;
RegisterPass<RMCPass> X("rmc-pass", "RMC");
}
<commit_msg>Add a data structure to track cuts that we add.<commit_after>// BUG: this whole thing depends on the specifics of how the clang version I
// am using emits llvm bitcode for the hacky RMC protocol.
// We rely on how basic blocks get named, on the labels forcing things
// into their own basic blocks, and probably will rely on this block
// having one predecessor and one successor. We could probably even
// force those to be empty without too much work by adding more labels...
#include <llvm/Pass.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/InlineAsm.h>
#include <llvm/IR/CFG.h>
#include <llvm/IR/InstIterator.h>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/raw_ostream.h>
#include <ostream>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
using namespace llvm;
namespace {
#if 0 // I hate you, emacs. Is there a better way to work around this?
}
#endif
/* To do bogus data dependencies, we will emit inline assembly
instructions. This is sort of tasteless; we should add an intrinsic;
but it means we don't need to modify llvm. This is what the
instruction should look like (probably the constraints aren't
right?):
%2 = call i32 asm sideeffect "eor $0, $0;", "=r,0"(i32 %1) #2, !srcloc !11
Also for ctrlisb we do:
call void asm sideeffect "cmp $0, $0;beq 1f;1: isb", "r,~{memory}"(i32 %1) #2, !srcloc !4
And for dmb:
call void asm sideeffect "dmb", "~{memory}"() #2, !srcloc !5
We can probably do a bogus inline asm on x86 to prevent reordering:
%2 = call i32 asm sideeffect "", "=r,r,0,~{dirflag},~{fpsr},~{flags}"(i32 %1, i32 %0) #3, !srcloc !9
What about this makes the right value come out:
=r specifies an output parameter and the 0 says that that input parameter
is paired with param 0.
Hm. Does this *actually* work?? What does "sideeffect" actually mean
for asm and do we need it.
--
Should we emit dmb directly, or try to use llvm's fences?
*/
//// Some auxillary data structures
enum RMCEdgeType {
VisbilityEdge,
ExecutionEdge
};
raw_ostream& operator<<(raw_ostream& os, const RMCEdgeType& t) {
switch (t) {
case VisbilityEdge:
os << "v";
break;
case ExecutionEdge:
os << "x";
break;
default:
os << "?";
break;
}
return os;
}
// Info about an RMC edge
struct RMCEdge {
RMCEdgeType edgeType;
BasicBlock *src;
BasicBlock *dst;
bool operator<(const RMCEdge& rhs) const {
return std::tie(edgeType, src, dst)
< std::tie(rhs.edgeType, rhs.src, rhs.dst);
}
void print(raw_ostream &os) const {
// substr(5) is to drop "_rmc_" from the front
os << src->getName().substr(5) << " -" << edgeType <<
"-> " << dst->getName().substr(5);
}
};
raw_ostream& operator<<(raw_ostream& os, const RMCEdge& e) {
e.print(os);
return os;
}
// Information for a node in the RMC graph.
struct Block {
Block(BasicBlock *p_bb) : bb(p_bb), stores(0), loads(0), RMWs(0), calls(0) {}
void operator=(const Block &) LLVM_DELETED_FUNCTION;
Block(const Block &) LLVM_DELETED_FUNCTION;
Block(Block &&) = default; // move constructor!
BasicBlock *bb;
// Some basic info about what sort of instructions live in the block
int stores;
int loads;
int RMWs;
int calls;
// Edges in the graph.
// XXX: Would we be better off storing this some other way?
// a <ptr, type> pair?
// And should we store v edges in x
SmallPtrSet<Block *, 2> execEdges;
SmallPtrSet<Block *, 2> visEdges;
};
enum CutType {
CutNone,
CutCtrlIsync, // needs to be paired with a dep
CutLwsync,
CutSync
};
struct EdgeCut {
EdgeCut() : type(CutNone), front(false), read(nullptr) {}
CutType type;
bool front;
Value *read;
};
// Code to find all simple paths between two basic blocks.
// Could generalize more to graphs if we wanted, but I don't right
// now.
typedef std::vector<BasicBlock *> Path;
typedef SmallVector<Path, 2> PathList;
typedef SmallPtrSet<BasicBlock *, 8> GreySet;
PathList findAllSimplePaths_(GreySet *grey, BasicBlock *src, BasicBlock *dst) {
PathList paths;
if (grey->count(src)) return paths;
if (src == dst) {
Path path;
path.push_back(dst);
paths.push_back(std::move(path));
return paths;
}
grey->insert(src);
// Go search all the successors
for (auto i = succ_begin(src), e = succ_end(src); i != e; i++) {
PathList subpaths = findAllSimplePaths_(grey, *i, dst);
std::move(subpaths.begin(), subpaths.end(), back_inserter(paths));
}
// Add our step to all of the vectors
for (auto & path : paths) {
path.push_back(src);
}
// Remove it from the set of things we've seen. We might come
// through here again.
// We can't really do any sort of memoization, since in a cyclic
// graph the possible simple paths depend not just on what node we
// are on, but our previous path (to avoid looping).
grey->erase(src);
return paths;
}
PathList findAllSimplePaths(BasicBlock *src, BasicBlock *dst) {
GreySet grey;
return findAllSimplePaths_(&grey, src, dst);
}
void dumpPaths(const PathList &paths) {
for (auto & path : paths) {
for (auto block : path) {
errs() << block->getName() << " <- ";
}
errs() << "\n";
}
}
// XXX: This is the wrong way to do this!
bool targetARM = true;
bool targetx86 = false;
// Some llvm nonsense. I should probably find a way to clean this up.
// do we put ~{dirflag},~{fpsr},~{flags} for the x86 ones? don't think so.
Instruction *makeSync(Value *dummy) {
LLVMContext &C = dummy->getContext();
FunctionType *f_ty = FunctionType::get(FunctionType::getVoidTy(C), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "dmb", "~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "msync", "~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "sync");
}
Instruction *makeLwsync(Value *dummy) {
LLVMContext &C = dummy->getContext();
FunctionType *f_ty = FunctionType::get(FunctionType::getVoidTy(C), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "dmb", "~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "", "~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "lwsync");
}
Instruction *makeCtrlIsync(Value *v) {
LLVMContext &C = v->getContext();
FunctionType *f_ty =
FunctionType::get(FunctionType::getVoidTy(C), v->getType(), false);
InlineAsm *a;
if (targetARM) {
a = InlineAsm::get(f_ty, "cmp $0, $0;beq 1f;1: isb", "r,~{memory}", true);
} else if (targetx86) {
a = InlineAsm::get(f_ty, "", "r,~{memory}", true);
} else {
assert(false && "invalid target");
}
return CallInst::Create(a, None, "ctrlisync");
}
// We also need to add a thing for fake data deps, which is more annoying.
//// Actual code for the pass
class RMCPass : public FunctionPass {
private:
std::vector<Block> blocks_;
DenseMap<BasicBlock *, Block *> bb2block_;
DenseMap<BasicBlock *, EdgeCut> cuts_;
public:
static char ID;
RMCPass() : FunctionPass(ID) {
}
~RMCPass() { }
std::vector<RMCEdge> findEdges(Function &F);
void buildGraph(std::vector<RMCEdge> &edges, Function &F);
virtual bool runOnFunction(Function &F);
};
bool nameMatches(StringRef blockName, StringRef target) {
StringRef name = "_rmc_" + target.str() + "_";
if (!blockName.startswith(name)) return false;
// Now make sure the rest is an int
APInt dummy;
return !blockName.drop_front(name.size()).getAsInteger(10, dummy);
}
StringRef getStringArg(Value *v) {
const Value *g = cast<Constant>(v)->stripPointerCasts();
const Constant *ptr = cast<GlobalVariable>(g)->getInitializer();
StringRef str = cast<ConstantDataSequential>(ptr)->getAsString();
// Drop the '\0' at the end
return str.drop_back();
}
std::vector<RMCEdge> RMCPass::findEdges(Function &F) {
std::vector<RMCEdge> edges;
for (inst_iterator is = inst_begin(F), ie = inst_end(F); is != ie;) {
// Grab the instruction and advance the iterator at the start, since
// we might delete the instruction.
Instruction *i = &*is;
is++;
CallInst *load = dyn_cast<CallInst>(i);
if (!load) continue;
Function *target = load->getCalledFunction();
// We look for calls to the bogus function
// __rmc_edge_register, pull out the information about them,
// and delete the calls.
if (!target || target->getName() != "__rmc_edge_register") continue;
// Pull out what the operands have to be.
// We just assert if something is wrong, which is not great UX.
bool isVisibility = cast<ConstantInt>(load->getOperand(0))
->getValue().getBoolValue();
RMCEdgeType edgeType = isVisibility ? VisbilityEdge : ExecutionEdge;
StringRef srcName = getStringArg(load->getOperand(1));
StringRef dstName = getStringArg(load->getOperand(2));
// Since multiple blocks can have the same tag, we search for
// them by name.
// We could make this more efficient by building maps but I don't think
// it is going to matter.
for (auto & src : F) {
if (!nameMatches(src.getName(), srcName)) continue;
for (auto & dst : F) {
if (!nameMatches(dst.getName(), dstName)) continue;
edges.push_back({edgeType, &src, &dst});
}
}
// Delete the bogus call.
i->eraseFromParent();
}
return edges;
}
void analyzeBlock(Block &info) {
for (auto & i : *info.bb) {
if (isa<LoadInst>(i)) {
info.loads++;
} else if (isa<StoreInst>(i)) {
info.stores++;
// What else counts as a call? I'm counting fences I guess.
} else if (isa<CallInst>(i) || isa<FenceInst>(i)) {
info.calls++;
} else if (isa<AtomicCmpXchgInst>(i) || isa<AtomicRMWInst>(i)) {
info.RMWs++;
}
}
}
void RMCPass::buildGraph(std::vector<RMCEdge> &edges, Function &F) {
// First, collect all the basic blocks with edges attached to them
SmallPtrSet<BasicBlock *, 8> basicBlocks;
for (auto & edge : edges) {
basicBlocks.insert(edge.src);
basicBlocks.insert(edge.dst);
}
// Now, make the vector of blocks and a mapping from BasicBlock *.
blocks_.reserve(basicBlocks.size());
for (auto bb : basicBlocks) {
blocks_.emplace_back(bb);
bb2block_[bb] = &blocks_.back();
}
// Analyze the instructions in blocks to see what sort of actions
// they peform.
for (auto & block : blocks_) {
analyzeBlock(block);
}
// Build our list of edges into a more explicit graph
for (auto & edge : edges) {
Block *src = bb2block_[edge.src];
Block *dst = bb2block_[edge.dst];
if (edge.edgeType == VisbilityEdge) {
src->visEdges.insert(dst);
} else {
src->execEdges.insert(dst);
}
}
}
bool RMCPass::runOnFunction(Function &F) {
auto edges = findEdges(F);
for (auto & edge : edges) {
errs() << "Found an edge: " << edge << "\n";
}
buildGraph(edges, F);
bool changed = !edges.empty();
// Clear our data structures to save memory, make things clean for
// future runs.
blocks_.clear();
bb2block_.clear();
cuts_.clear();
return changed;
}
char RMCPass::ID = 0;
RegisterPass<RMCPass> X("rmc-pass", "RMC");
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2013 Teragon Audio. 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.
*
* 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 HOLDER 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 "TestRunner.h"
#include "PluginParameters.h"
using namespace teragon;
////////////////////////////////////////////////////////////////////////////////
// Observers
////////////////////////////////////////////////////////////////////////////////
class TestAsyncObserver : public PluginParameterObserver {
public:
TestAsyncObserver() {}
#if ENABLE_MULTITHREADED
bool isRealtimePriority() const { return true; }
#endif
void onParameterUpdated(const PluginParameter* parameter) {
}
private:
};
static bool testUpdatesReceivedOnBothThreads() {
return true;
}
int runMultithreadedTests();
int runMultithreadedTests() {
ADD_TEST("UpdatesReceivedOnBothThreads", testUpdatesReceivedOnBothThreads());
return 0;
}
<commit_msg>Add basic multithreading test observers<commit_after>/*
* Copyright (c) 2013 Teragon Audio. 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.
*
* 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 HOLDER 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 "TestRunner.h"
#include "PluginParameters.h"
#if ENABLE_MULTITHREADED
using namespace teragon;
////////////////////////////////////////////////////////////////////////////////
// Observers
////////////////////////////////////////////////////////////////////////////////
class TestCounterObserver : public PluginParameterObserver {
public:
TestCounterObserver(bool isRealtime) : PluginParameterObserver(),
realtime(isRealtime), count(0) {}
virtual ~TestCounterObserver() {}
int getCount() const { return count; }
virtual bool isRealtimePriority() const { return realtime; }
void onParameterUpdated(const PluginParameter* parameter) {
count++;
}
private:
const bool realtime;
int count;
};
class TestAsyncObserver : public TestCounterObserver {
public:
TestAsyncObserver() : TestCounterObserver(false) {}
virtual ~TestAsyncObserver() {}
};
class TestRealtimeObserver : public TestCounterObserver {
public:
TestRealtimeObserver() : TestCounterObserver(true) {}
virtual ~TestRealtimeObserver() {}
};
////////////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////////////
static bool testUpdatesReceivedOnBothThreads() {
PluginParameterSet p;
return true;
}
////////////////////////////////////////////////////////////////////////////////
// Run test suite
////////////////////////////////////////////////////////////////////////////////
void runMultithreadedTests();
void runMultithreadedTests() {
ADD_TEST("UpdatesReceivedOnBothThreads", testUpdatesReceivedOnBothThreads());
}
#endif // #if ENABLE_MULTITHREADED
<|endoftext|> |
<commit_before>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include <iostream>
#include <vector>
#include <cstring>
#include <dlfcn.h>
#include <string>
#import <Cocoa/Cocoa.h>
#include "host.h"
#include "log.h"
namespace kroll
{
OSXHost::OSXHost(int _argc, const char **_argv) : Host(_argc,_argv)
{
SetupLog(_argc,_argv,[NSString stringWithFormat:@"%s/run.log",this->GetApplicationHome().c_str()]);
char *p = getenv("KR_PLUGINS");
if (p)
{
FileUtils::Tokenize(p, this->module_paths, ":");
}
}
OSXHost::~OSXHost()
{
CloseLog();
}
int OSXHost::Run()
{
TRACE(@PRODUCT_NAME" Kroll Running (OSX)...");
this->AddModuleProvider(this);
this->LoadModules();
[NSApp run];
return 0;
}
Module* OSXHost::CreateModule(std::string& path)
{
std::cout << "Creating module " << path << std::endl;
void* lib_handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (!lib_handle)
{
std::cerr << "Error load module: " << path << std::endl;
return 0;
}
// get the module factory
ModuleCreator* create = (ModuleCreator*)dlsym(lib_handle, "CreateModule");
if (!create)
{
std::cerr << "Error load create entry from module: " << path << std::endl;
return 0;
}
return create(this,FileUtils::GetDirectory(path));
}
}
@interface KrollMainThreadCaller : NSObject
{
SharedPtr<kroll::BoundMethod> method;
SharedPtr<kroll::Value> result;
kroll::ValueList args;
}
- (id)initWithBoundMethod:(SharedPtr<kroll::BoundMethod>)method args:(SharedPtr<ValueList>)args;
- (void)call;
- (SharedPtr<kroll::Value>)getResult;
@end
@implementation KrollMainThreadCaller
- (id)initWithBoundMethod:(SharedPtr<kroll::BoundMethod>)m args:(SharedPtr<ValueList>)a
{
self = [super init];
if (self)
{
method = m;
args = a;
result = NULL;
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (SharedPtr<kroll::Value>)getResult
{
return result;
}
- (void)call
{
result->assign(method->Call(args));
}
@end
namespace ti
{
SharedValue OSXHost::InvokeMethodOnMainThread(SharedBoundMethod method,
const ValueList& args)
{
KrollMainThreadCaller *caller = [[KrollMainThreadCaller alloc] initWithBoundMethod:method args:args];
[caller performSelectorOnMainThread:@selector(call) withObject:nil waitUntilDone:YES];
SharedValue result = [caller getResult];
[caller release];
return result;
}
}
<commit_msg>Build fixes for osx<commit_after>/**
* Appcelerator Kroll - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
*/
#include <iostream>
#include <vector>
#include <cstring>
#include <dlfcn.h>
#include <string>
#import <Cocoa/Cocoa.h>
#include "host.h"
#include "log.h"
namespace kroll
{
OSXHost::OSXHost(int _argc, const char **_argv) : Host(_argc,_argv)
{
SetupLog(_argc,_argv,[NSString stringWithFormat:@"%s/run.log",this->GetApplicationHome().c_str()]);
char *p = getenv("KR_PLUGINS");
if (p)
{
FileUtils::Tokenize(p, this->module_paths, ":");
}
}
OSXHost::~OSXHost()
{
CloseLog();
}
int OSXHost::Run()
{
TRACE(@PRODUCT_NAME" Kroll Running (OSX)...");
this->AddModuleProvider(this);
this->LoadModules();
[NSApp run];
return 0;
}
Module* OSXHost::CreateModule(std::string& path)
{
std::cout << "Creating module " << path << std::endl;
void* lib_handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
if (!lib_handle)
{
std::cerr << "Error load module: " << path << std::endl;
return 0;
}
// get the module factory
ModuleCreator* create = (ModuleCreator*)dlsym(lib_handle, "CreateModule");
if (!create)
{
std::cerr << "Error load create entry from module: " << path << std::endl;
return 0;
}
return create(this,FileUtils::GetDirectory(path));
}
}
@interface KrollMainThreadCaller : NSObject
{
SharedPtr<kroll::BoundMethod> *method;
SharedPtr<kroll::Value> *result;
const kroll::ValueList* args;
}
- (id)initWithBoundMethod:(SharedPtr<kroll::BoundMethod>)method args:(const ValueList*)args;
- (void)call;
- (SharedPtr<kroll::Value>)getResult;
@end
@implementation KrollMainThreadCaller
- (id)initWithBoundMethod:(SharedPtr<kroll::BoundMethod>)m args:(const ValueList*)a
{
self = [super init];
if (self)
{
method = new SharedPtr<kroll::BoundMethod>(m);
args = a;
result = new SharedPtr<kroll::Value>();
}
return self;
}
- (void)dealloc
{
delete method;
delete result;
[super dealloc];
}
- (SharedPtr<kroll::Value>)getResult
{
return *result;
}
- (void)call
{
result->assign((*method)->Call(*args));
}
@end
namespace ti
{
SharedValue OSXHost::InvokeMethodOnMainThread(SharedBoundMethod method,
const ValueList& args)
{
KrollMainThreadCaller *caller = [[KrollMainThreadCaller alloc] initWithBoundMethod:method args:&args];
[caller performSelectorOnMainThread:@selector(call) withObject:nil waitUntilDone:YES];
SharedValue result = [caller getResult];
[caller release];
return result;
}
}
<|endoftext|> |
<commit_before>
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Tests for the Solidity optimizer.
*/
#include <string>
#include <tuple>
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <test/solidityExecutionFramework.h>
using namespace std;
namespace dev
{
namespace solidity
{
namespace test
{
class OptimizerTestFramework: public ExecutionFramework
{
public:
OptimizerTestFramework() { }
/// Compiles the source code with and without optimizing.
void compileBothVersions(unsigned _expectedSizeDecrease, std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "") {
m_optimize = false;
bytes nonOptimizedBytecode = compileAndRun(_sourceCode, _value, _contractName);
m_nonOptimizedContract = m_contractAddress;
m_optimize = true;
bytes optimizedBytecode = compileAndRun(_sourceCode, _value, _contractName);
int sizeDiff = nonOptimizedBytecode.size() - optimizedBytecode.size();
BOOST_CHECK_MESSAGE(sizeDiff == int(_expectedSizeDecrease), "Bytecode shrank by "
+ boost::lexical_cast<string>(sizeDiff) + " bytes, expected: "
+ boost::lexical_cast<string>(_expectedSizeDecrease));
m_optimizedContract = m_contractAddress;
}
template <class... Args>
void compareVersions(std::string _sig, Args const&... _arguments)
{
m_contractAddress = m_nonOptimizedContract;
bytes nonOptimizedOutput = callContractFunction(_sig, _arguments...);
m_contractAddress = m_optimizedContract;
bytes optimizedOutput = callContractFunction(_sig, _arguments...);
BOOST_CHECK_MESSAGE(nonOptimizedOutput == optimizedOutput, "Computed values do not match."
"\nNon-Optimized: " + toHex(nonOptimizedOutput) +
"\nOptimized: " + toHex(optimizedOutput));
}
protected:
Address m_optimizedContract;
Address m_nonOptimizedContract;
};
BOOST_FIXTURE_TEST_SUITE(SolidityOptimizer, OptimizerTestFramework)
BOOST_AUTO_TEST_CASE(smoke_test)
{
char const* sourceCode = R"(
contract test {
function f(uint a) returns (uint b) {
return a;
}
})";
compileBothVersions(29, sourceCode);
compareVersions("f(uint256)", u256(7));
}
BOOST_AUTO_TEST_CASE(large_integers)
{
char const* sourceCode = R"(
contract test {
function f() returns (uint a, uint b) {
a = 0x234234872642837426347000000;
b = 0x10000000000000000000000002;
}
})";
compileBothVersions(53, sourceCode);
compareVersions("f()");
}
BOOST_AUTO_TEST_CASE(invariants)
{
char const* sourceCode = R"(
contract test {
function f(int a) returns (int b) {
return int(0) | (int(1) * (int(0) ^ (0 + a)));
}
})";
compileBothVersions(53, sourceCode);
compareVersions("f(uint256)", u256(0x12334664));
}
BOOST_AUTO_TEST_CASE(unused_expressions)
{
char const* sourceCode = R"(
contract test {
uint data;
function f() returns (uint a, uint b) {
10 + 20;
data;
}
})";
compileBothVersions(36, sourceCode);
compareVersions("f()");
}
BOOST_AUTO_TEST_CASE(constant_folding_both_sides)
{
// if constants involving the same associative and commutative operator are applied from both
// sides, the operator should be applied only once, because the expression compiler pushes
// literals as late as possible
char const* sourceCode = R"(
contract test {
function f(uint x) returns (uint y) {
return 98 ^ (7 * ((1 | (x | 1000)) * 40) ^ 102);
}
})";
compileBothVersions(56, sourceCode);
compareVersions("f(uint256)");
}
BOOST_AUTO_TEST_SUITE_END()
}
}
} // end namespaces
<commit_msg>adjusting byte difference in optimizer large integers test<commit_after>
/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Tests for the Solidity optimizer.
*/
#include <string>
#include <tuple>
#include <boost/test/unit_test.hpp>
#include <boost/lexical_cast.hpp>
#include <test/solidityExecutionFramework.h>
using namespace std;
namespace dev
{
namespace solidity
{
namespace test
{
class OptimizerTestFramework: public ExecutionFramework
{
public:
OptimizerTestFramework() { }
/// Compiles the source code with and without optimizing.
void compileBothVersions(unsigned _expectedSizeDecrease, std::string const& _sourceCode, u256 const& _value = 0, std::string const& _contractName = "") {
m_optimize = false;
bytes nonOptimizedBytecode = compileAndRun(_sourceCode, _value, _contractName);
m_nonOptimizedContract = m_contractAddress;
m_optimize = true;
bytes optimizedBytecode = compileAndRun(_sourceCode, _value, _contractName);
int sizeDiff = nonOptimizedBytecode.size() - optimizedBytecode.size();
BOOST_CHECK_MESSAGE(sizeDiff == int(_expectedSizeDecrease), "Bytecode shrank by "
+ boost::lexical_cast<string>(sizeDiff) + " bytes, expected: "
+ boost::lexical_cast<string>(_expectedSizeDecrease));
m_optimizedContract = m_contractAddress;
}
template <class... Args>
void compareVersions(std::string _sig, Args const&... _arguments)
{
m_contractAddress = m_nonOptimizedContract;
bytes nonOptimizedOutput = callContractFunction(_sig, _arguments...);
m_contractAddress = m_optimizedContract;
bytes optimizedOutput = callContractFunction(_sig, _arguments...);
BOOST_CHECK_MESSAGE(nonOptimizedOutput == optimizedOutput, "Computed values do not match."
"\nNon-Optimized: " + toHex(nonOptimizedOutput) +
"\nOptimized: " + toHex(optimizedOutput));
}
protected:
Address m_optimizedContract;
Address m_nonOptimizedContract;
};
BOOST_FIXTURE_TEST_SUITE(SolidityOptimizer, OptimizerTestFramework)
BOOST_AUTO_TEST_CASE(smoke_test)
{
char const* sourceCode = R"(
contract test {
function f(uint a) returns (uint b) {
return a;
}
})";
compileBothVersions(29, sourceCode);
compareVersions("f(uint256)", u256(7));
}
BOOST_AUTO_TEST_CASE(large_integers)
{
char const* sourceCode = R"(
contract test {
function f() returns (uint a, uint b) {
a = 0x234234872642837426347000000;
b = 0x10000000000000000000000002;
}
})";
compileBothVersions(58, sourceCode);
compareVersions("f()");
}
BOOST_AUTO_TEST_CASE(invariants)
{
char const* sourceCode = R"(
contract test {
function f(int a) returns (int b) {
return int(0) | (int(1) * (int(0) ^ (0 + a)));
}
})";
compileBothVersions(53, sourceCode);
compareVersions("f(uint256)", u256(0x12334664));
}
BOOST_AUTO_TEST_CASE(unused_expressions)
{
char const* sourceCode = R"(
contract test {
uint data;
function f() returns (uint a, uint b) {
10 + 20;
data;
}
})";
compileBothVersions(36, sourceCode);
compareVersions("f()");
}
BOOST_AUTO_TEST_CASE(constant_folding_both_sides)
{
// if constants involving the same associative and commutative operator are applied from both
// sides, the operator should be applied only once, because the expression compiler pushes
// literals as late as possible
char const* sourceCode = R"(
contract test {
function f(uint x) returns (uint y) {
return 98 ^ (7 * ((1 | (x | 1000)) * 40) ^ 102);
}
})";
compileBothVersions(56, sourceCode);
compareVersions("f(uint256)");
}
BOOST_AUTO_TEST_SUITE_END()
}
}
} // end namespaces
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef FS_COMMON_HPP
#define FS_COMMON_HPP
#include <memory>
#include <string>
#include <delegate>
#include <vector>
#include "path.hpp"
#include <hw/block_device.hpp>
namespace fs {
// Generic structure for directory entries
struct Dirent;
/**
* @brief Type used as a building block to represent buffers
* within the filesystem subsystem
*/
using buffer_t = std::shared_ptr<uint8_t>;
/** Container types **/
using dirvector = std::vector<Dirent>;
using dirvec_t = std::shared_ptr<dirvector>;
/** Pointer types **/
using Path_ptr = std::shared_ptr<Path>;
/** ID types **/
using Device_id = hw::Block_device::Device_id;
/** Entity types for dirents **/
enum Enttype {
FILE,
DIR,
/** FAT puts disk labels in the root directory, hence: */
VOLUME_ID,
SYM_LINK,
INVALID_ENTITY
};
/** Error type **/
struct error_t
{
enum token_t {
NO_ERR = 0,
E_IO, // general I/O error
E_MNT,
E_NOENT,
E_NOTDIR,
E_NOTFILE
}; //< enum token_t
/**
* @brief Constructor
*
* @param tk: An error token
* @param rsn: The reason for the error
*/
error_t(const token_t tk, const std::string& rsn)
: token_{tk}
, reason_{rsn}
{}
/**
* @brief Get a human-readable description of the token
*
* @return Description of the token as a {std::string}
*/
const std::string& token() const noexcept;
/**
* @brief Get an explanation for error
*/
const std::string& reason() const noexcept
{ return reason_; }
/**
* @brief Get a {std::string} representation of this type
*
* Format "description: reason"
*
* @return {std::string} representation of this type
*/
std::string to_string() const
{ return token() + ": " + reason(); }
/**
* @brief Check if the object of this type represents
* an error
*
* @return true if its an error, false otherwise
*/
operator bool () const noexcept
{ return token_ not_eq NO_ERR; }
private:
token_t token_;
std::string reason_;
}; //< struct error_t
/**
* @brief Type used for buffers within the filesystem
* subsystem
*/
struct Buffer
{
Buffer(const error_t& e, buffer_t b, const uint64_t l)
: err_ {e}
, buffer_ {b}
, len_ {l}
{}
/**
* @brief Check if an object of this type is in a valid
* state
*
* @return true if valid, false otherwise
*/
bool is_valid() const noexcept
{ return (buffer_ not_eq nullptr) and (not err_); }
/**
* @brief Coerce an object of this type to a bool
*/
operator bool () const noexcept
{ return is_valid(); }
/// retrieve error status
error_t error() const noexcept
{ return err_; }
/**
* @brief Get the starting address of the underlying data buffer
*
* @return The starting address of the underlying data buffer
*/
uint8_t* data() noexcept
{ return buffer_.get(); }
/**
* @brief Get the size/length of the buffer
*
* @return The size/length of the buffer
*/
size_t size() const noexcept
{ return len_; }
/**
* @brief Get a {std::string} representation of this type
*
* @return A {std::string} representation of this type
*/
std::string to_string() const noexcept
{ return std::string{reinterpret_cast<char*>(buffer_.get()), size()}; }
private:
error_t err_;
buffer_t buffer_;
uint64_t len_;
}; //< struct Buffer
/** @var no_error: Always returns boolean false when used in expressions */
extern error_t no_error;
/** Async function types **/
using on_init_func = delegate<void(error_t)>;
using on_ls_func = delegate<void(error_t, dirvec_t)>;
using on_read_func = delegate<void(error_t, buffer_t, uint64_t)>;
using on_stat_func = delegate<void(error_t, const Dirent&)>;
struct List {
error_t error;
dirvec_t entries;
auto begin() { return entries->begin(); }
auto end() { return entries->end(); }
auto cbegin() { return entries->cbegin(); }
auto cend() { return entries->cend(); }
};
} //< namespace fs
#endif //< FS_ERROR_HPP
<commit_msg>fs: corrected #endif comment<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef FS_COMMON_HPP
#define FS_COMMON_HPP
#include <memory>
#include <string>
#include <delegate>
#include <vector>
#include "path.hpp"
#include <hw/block_device.hpp>
namespace fs {
// Generic structure for directory entries
struct Dirent;
/**
* @brief Type used as a building block to represent buffers
* within the filesystem subsystem
*/
using buffer_t = std::shared_ptr<uint8_t>;
/** Container types **/
using dirvector = std::vector<Dirent>;
using dirvec_t = std::shared_ptr<dirvector>;
/** Pointer types **/
using Path_ptr = std::shared_ptr<Path>;
/** ID types **/
using Device_id = hw::Block_device::Device_id;
/** Entity types for dirents **/
enum Enttype {
FILE,
DIR,
/** FAT puts disk labels in the root directory, hence: */
VOLUME_ID,
SYM_LINK,
INVALID_ENTITY
};
/** Error type **/
struct error_t
{
enum token_t {
NO_ERR = 0,
E_IO, // general I/O error
E_MNT,
E_NOENT,
E_NOTDIR,
E_NOTFILE
}; //< enum token_t
/**
* @brief Constructor
*
* @param tk: An error token
* @param rsn: The reason for the error
*/
error_t(const token_t tk, const std::string& rsn)
: token_{tk}
, reason_{rsn}
{}
/**
* @brief Get a human-readable description of the token
*
* @return Description of the token as a {std::string}
*/
const std::string& token() const noexcept;
/**
* @brief Get an explanation for error
*/
const std::string& reason() const noexcept
{ return reason_; }
/**
* @brief Get a {std::string} representation of this type
*
* Format "description: reason"
*
* @return {std::string} representation of this type
*/
std::string to_string() const
{ return token() + ": " + reason(); }
/**
* @brief Check if the object of this type represents
* an error
*
* @return true if its an error, false otherwise
*/
operator bool () const noexcept
{ return token_ not_eq NO_ERR; }
private:
token_t token_;
std::string reason_;
}; //< struct error_t
/**
* @brief Type used for buffers within the filesystem
* subsystem
*/
struct Buffer
{
Buffer(const error_t& e, buffer_t b, const uint64_t l)
: err_ {e}
, buffer_ {b}
, len_ {l}
{}
/**
* @brief Check if an object of this type is in a valid
* state
*
* @return true if valid, false otherwise
*/
bool is_valid() const noexcept
{ return (buffer_ not_eq nullptr) and (not err_); }
/**
* @brief Coerce an object of this type to a bool
*/
operator bool () const noexcept
{ return is_valid(); }
/// retrieve error status
error_t error() const noexcept
{ return err_; }
/**
* @brief Get the starting address of the underlying data buffer
*
* @return The starting address of the underlying data buffer
*/
uint8_t* data() noexcept
{ return buffer_.get(); }
/**
* @brief Get the size/length of the buffer
*
* @return The size/length of the buffer
*/
size_t size() const noexcept
{ return len_; }
/**
* @brief Get a {std::string} representation of this type
*
* @return A {std::string} representation of this type
*/
std::string to_string() const noexcept
{ return std::string{reinterpret_cast<char*>(buffer_.get()), size()}; }
private:
error_t err_;
buffer_t buffer_;
uint64_t len_;
}; //< struct Buffer
/** @var no_error: Always returns boolean false when used in expressions */
extern error_t no_error;
/** Async function types **/
using on_init_func = delegate<void(error_t)>;
using on_ls_func = delegate<void(error_t, dirvec_t)>;
using on_read_func = delegate<void(error_t, buffer_t, uint64_t)>;
using on_stat_func = delegate<void(error_t, const Dirent&)>;
struct List {
error_t error;
dirvec_t entries;
auto begin() { return entries->begin(); }
auto end() { return entries->end(); }
auto cbegin() { return entries->cbegin(); }
auto cend() { return entries->cend(); }
};
} //< namespace fs
#endif //< FS_COMMON_HPP
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string>
#include <vector>
#include <limits>
#include "Halide.h"
using namespace Halide;
std::vector<std::string> messages;
extern "C" void halide_print(void *user_context, const char *message) {
//printf("%s", message);
messages.push_back(message);
}
#ifdef _MSC_VER
#define snprintf _snprintf
#endif
int main(int argc, char **argv) {
Var x;
{
Func f;
f(x) = print(x * x, "the answer is", 42.0f, "unsigned", cast<uint32_t>(145));
f.set_custom_print(halide_print);
Image<int32_t> result = f.realize(10);
for (int32_t i = 0; i < 10; i++) {
if (result(i) != i * i) {
return -1;
}
}
assert(messages.size() == 10);
for (size_t i = 0; i < messages.size(); i++) {
long long square;
float forty_two;
unsigned long long one_forty_five;
int scan_count = sscanf(messages[i].c_str(), "%lld the answer is %f unsigned %llu",
&square, &forty_two, &one_forty_five);
assert(scan_count == 3);
assert(square == static_cast<long long>(i * i));
assert(forty_two == 42.0f);
assert(one_forty_five == 145);
}
}
messages.clear();
{
Func f;
Param<int> param;
param.set(127);
// Test a string containing a printf format specifier (It should print it as-is).
f(x) = print_when(x == 3, x * x, "g", 42.0f, "%s", param);
f.set_custom_print(halide_print);
Image<int32_t> result = f.realize(10);
for (int32_t i = 0; i < 10; i++) {
if (result(i) != i * i) {
return -1;
}
}
assert(messages.size() == 1);
long long nine;
float forty_two;
long long p;
int scan_count = sscanf(messages[0].c_str(), "%lld g %f %%s %lld",
&nine, &forty_two, &p);
assert(scan_count == 3);
assert(nine == 9);
assert(forty_two == 42.0f);
assert(p == 127);
}
messages.clear();
{
Func f;
// Test a single message longer than 8K.
std::vector<Expr> args;
for (int i = 0; i < 500; i++) {
uint64_t n = i;
n *= n;
n *= n;
n *= n;
n *= n;
n += 100;
int32_t hi = n >> 32;
int32_t lo = n & 0xffffffff;
args.push_back((cast<uint64_t>(hi) << 32) | lo);
Expr dn = cast<double>((float)(n));
args.push_back(dn);
}
f(x) = print(args);
f.set_custom_print(halide_print);
Image<uint64_t> result = f.realize(1);
if (result(0) != 100) {
return -1;
}
assert(messages.back().size() == 8191);
}
messages.clear();
// Check that Halide's stringification of floats and doubles
// matches %f and %e respectively.
#ifndef _MSC_VER
// msvc's library has different ideas about how %f and %e should come out.
{
Func f, g;
const int N = 1000000;
Expr e = reinterpret(Float(32), random_int());
// Make sure we cover some special values.
e = select(x == 0, 0.0f,
x == 1, -0.0f,
x == 2, std::numeric_limits<float>::infinity(),
x == 3, -std::numeric_limits<float>::infinity(),
x == 4, std::numeric_limits<float>::quiet_NaN(),
x == 5, -std::numeric_limits<float>::quiet_NaN(),
e);
e = select(x == 5, std::numeric_limits<float>::denorm_min(),
x == 6, -std::numeric_limits<float>::denorm_min(),
x == 7, std::numeric_limits<float>::min(),
x == 8, -std::numeric_limits<float>::min(),
x == 9, std::numeric_limits<float>::max(),
x == 10, -std::numeric_limits<float>::max(),
e);
f(x) = print(e);
f.set_custom_print(halide_print);
Image<float> imf = f.realize(N);
assert(messages.size() == N);
char correct[1024];
for (int i = 0; i < N; i++) {
snprintf(correct, sizeof(correct), "%f\n", imf(i));
// OS X prints -nan as nan
#ifdef __APPLE__
if (messages[i] == "-nan\n") messages[i] = "nan\n";
#endif
if (messages[i] != correct) {
printf("float %d: %s vs %s for %10.20e\n", i, messages[i].c_str(), correct, imf(i));
return -1;
}
}
messages.clear();
g(x) = print(reinterpret(Float(64), (cast<uint64_t>(random_int()) << 32) | random_int()));
g.set_custom_print(halide_print);
Image<double> img = g.realize(N);
assert(messages.size() == N);
for (int i = 0; i < N; i++) {
snprintf(correct, sizeof(correct), "%e\n", img(i));
#ifdef __APPLE__
if (messages[i] == "-nan\n") messages[i] = "nan\n";
#endif
if (messages[i] != correct) {
printf("double %d: %s vs %s for %10.20e\n", i, messages[i].c_str(), correct, img(i));
return -1;
}
}
}
#endif
printf("Success!\n");
return 0;
}
<commit_msg>Fix warning<commit_after>#include <stdio.h>
#include <string>
#include <vector>
#include <limits>
#include "Halide.h"
using namespace Halide;
std::vector<std::string> messages;
extern "C" void halide_print(void *user_context, const char *message) {
//printf("%s", message);
messages.push_back(message);
}
#ifdef _MSC_VER
#define snprintf _snprintf
#endif
int main(int argc, char **argv) {
Var x;
{
Func f;
f(x) = print(x * x, "the answer is", 42.0f, "unsigned", cast<uint32_t>(145));
f.set_custom_print(halide_print);
Image<int32_t> result = f.realize(10);
for (int32_t i = 0; i < 10; i++) {
if (result(i) != i * i) {
return -1;
}
}
assert(messages.size() == 10);
for (size_t i = 0; i < messages.size(); i++) {
long long square;
float forty_two;
unsigned long long one_forty_five;
int scan_count = sscanf(messages[i].c_str(), "%lld the answer is %f unsigned %llu",
&square, &forty_two, &one_forty_five);
assert(scan_count == 3);
assert(square == static_cast<long long>(i * i));
assert(forty_two == 42.0f);
assert(one_forty_five == 145);
}
}
messages.clear();
{
Func f;
Param<int> param;
param.set(127);
// Test a string containing a printf format specifier (It should print it as-is).
f(x) = print_when(x == 3, x * x, "g", 42.0f, "%s", param);
f.set_custom_print(halide_print);
Image<int32_t> result = f.realize(10);
for (int32_t i = 0; i < 10; i++) {
if (result(i) != i * i) {
return -1;
}
}
assert(messages.size() == 1);
long long nine;
float forty_two;
long long p;
int scan_count = sscanf(messages[0].c_str(), "%lld g %f %%s %lld",
&nine, &forty_two, &p);
assert(scan_count == 3);
assert(nine == 9);
assert(forty_two == 42.0f);
assert(p == 127);
}
messages.clear();
{
Func f;
// Test a single message longer than 8K.
std::vector<Expr> args;
for (int i = 0; i < 500; i++) {
uint64_t n = i;
n *= n;
n *= n;
n *= n;
n *= n;
n += 100;
int32_t hi = n >> 32;
int32_t lo = n & 0xffffffff;
args.push_back((cast<uint64_t>(hi) << 32) | lo);
Expr dn = cast<double>((float)(n));
args.push_back(dn);
}
f(x) = print(args);
f.set_custom_print(halide_print);
Image<uint64_t> result = f.realize(1);
if (result(0) != 100) {
return -1;
}
assert(messages.back().size() == 8191);
}
messages.clear();
// Check that Halide's stringification of floats and doubles
// matches %f and %e respectively.
#ifndef _MSC_VER
// msvc's library has different ideas about how %f and %e should come out.
{
Func f, g;
const int N = 1000000;
Expr e = reinterpret(Float(32), random_int());
// Make sure we cover some special values.
e = select(x == 0, 0.0f,
x == 1, -0.0f,
x == 2, std::numeric_limits<float>::infinity(),
x == 3, -std::numeric_limits<float>::infinity(),
x == 4, std::numeric_limits<float>::quiet_NaN(),
x == 5, -std::numeric_limits<float>::quiet_NaN(),
e);
e = select(x == 5, std::numeric_limits<float>::denorm_min(),
x == 6, -std::numeric_limits<float>::denorm_min(),
x == 7, std::numeric_limits<float>::min(),
x == 8, -std::numeric_limits<float>::min(),
x == 9, std::numeric_limits<float>::max(),
x == 10, -std::numeric_limits<float>::max(),
e);
f(x) = print(e);
f.set_custom_print(halide_print);
Image<float> imf = f.realize(N);
assert(messages.size() == (size_t)N);
char correct[1024];
for (int i = 0; i < N; i++) {
snprintf(correct, sizeof(correct), "%f\n", imf(i));
// OS X prints -nan as nan
#ifdef __APPLE__
if (messages[i] == "-nan\n") messages[i] = "nan\n";
#endif
if (messages[i] != correct) {
printf("float %d: %s vs %s for %10.20e\n", i, messages[i].c_str(), correct, imf(i));
return -1;
}
}
messages.clear();
g(x) = print(reinterpret(Float(64), (cast<uint64_t>(random_int()) << 32) | random_int()));
g.set_custom_print(halide_print);
Image<double> img = g.realize(N);
assert(messages.size() == (size_t)N);
for (int i = 0; i < N; i++) {
snprintf(correct, sizeof(correct), "%e\n", img(i));
#ifdef __APPLE__
if (messages[i] == "-nan\n") messages[i] = "nan\n";
#endif
if (messages[i] != correct) {
printf("double %d: %s vs %s for %10.20e\n", i, messages[i].c_str(), correct, img(i));
return -1;
}
}
}
#endif
printf("Success!\n");
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "pch.h"
#include "Util.h"
#include <Windows.h>
#include <filesystem>
#include <sstream>
#include "unzip.h"
#include <direct.h>
#define WRITEBUFFERSIZE 8192
#define NODE_MODULE_MAX_PATH 1024
#define MD5HASHSIZE 16
using namespace Platform;
using namespace std::tr2::sys;
using namespace concurrency;
namespace nodeuwputil
{
shared_ptr<char> WCharToChar(const wchar_t* str, int strSize)
{
// Calculate the needed buffer size
DWORD bufferSize = WideCharToMultiByte(CP_UTF8,
0,
str,
strSize,
nullptr,
0,
nullptr,
nullptr);
if (bufferSize == 0)
{
throw ref new ::Platform::Exception(GetLastError(), L"nodeuwputil::WCharToChar failed");
}
shared_ptr<char> buffer(new char[bufferSize + 1], [](char* ptr) { delete[] ptr; });
buffer.get()[bufferSize] = '\0';
// Do the actual conversion
WideCharToMultiByte(CP_UTF8,
0,
str,
strSize,
buffer.get(),
bufferSize,
nullptr,
nullptr);
return buffer;
}
shared_ptr<wchar_t> CharToWChar(const char* str, int strSize)
{
// Calculate the needed buffer size
DWORD bufferSize = MultiByteToWideChar(CP_UTF8,
0,
str,
strSize,
nullptr,
0);
if (bufferSize == 0)
{
throw ref new ::Platform::Exception(GetLastError(), L"nodeuwputil::CharToWChar failed");
}
shared_ptr<wchar_t> buffer(new wchar_t[bufferSize + 1], [](wchar_t* ptr) { delete[] ptr; });
buffer.get()[bufferSize] = '\0';
// Do the actual conversion
MultiByteToWideChar(CP_UTF8,
0,
str,
strSize,
buffer.get(),
bufferSize);
return buffer;
}
void PopulateArgsVector(vector<shared_ptr<char>> &argVector,
String^ startStr, bool &useLogger)
{
if (startStr != nullptr)
{
wstring localFolder(ApplicationData::Current->LocalFolder->Path->Data());
localFolder.append(L"\\");
wstring args(startStr->Data());
args.erase(0, args.find_first_not_of(L" \n\r\t")); // Trim leading whitespace
wstring arg;
shared_ptr<char> in;
bool insert = false;
bool scriptFound = false;
for (size_t i = 0; i < args.length(); i++) {
wchar_t c = args[i];
if (c == ' ')
{
insert = true;
}
else if (c == '\"')
{
i++;
while (args[i] != '\"' && i < args.size())
{
arg += args[i];
i++;
}
i++;
insert = true;
}
else
{
arg += args[i];
}
// We insert an argument into the vector if we see a space or we've reached the
// end of the string.
if ((insert == true || args.size() - 1 == i) && arg.size() != 0)
{
insert = false;
// 'node' will usually be the first argument if the package.json file is also
// used with the console version of node. We'll ignore it if it exists.
if (_wcsicmp(arg.c_str(), L"node") == 0 && argVector.size() == 1)
{
arg.clear();
continue;
}
// Update the script path.
// The script to start will be the first argument that doesn't start with '-'.
// Node usage: node [options] [v8 options] [script.js | -e "script"] [arguments]
// 'options' and 'v8 options' start with '-'
if (arg[0] != '-' && scriptFound == false)
{
scriptFound = true;
arg = localFolder + arg;
}
if (arg.compare(L"--use-logger") == 0)
{
useLogger = true;
arg.clear();
continue;
}
in = WCharToChar(arg.c_str(), arg.size());
argVector.push_back(in);
arg.clear();
}
}
}
}
void CopyFolderSync(StorageFolder^ source, StorageFolder^ destination)
{
path from(source->Path->Data());
path to(destination->Path->Data());
copy_options opts = copy_options::recursive | copy_options::overwrite_existing;
copy(from, to, opts);
}
int MakePath(String^ newDir)
{
wstring newdir(newDir->Data());
vector<String^> subdirs;
wchar_t *nextTok = NULL;
StorageFolder^ storagefolder;
wchar_t* tok = wcstok_s((wchar_t*)newDir->Data(), L"\\", &nextTok);
while (tok != NULL)
{
subdirs.push_back(ref new String(tok));
tok = wcstok_s(NULL, L"\\", &nextTok);
}
// Walk the path until we get a valid StorageFolder object.
// This function will fail if path provided isn't abosolute.
// In future if needed this can be modified.
newDir = subdirs.at(0);
subdirs.erase(subdirs.begin());
vector<String^>::iterator it = subdirs.begin();
for (; it != subdirs.end(); ++it)
{
newDir = newDir + "\\" + *it;
try
{
storagefolder = create_task(StorageFolder::GetFolderFromPathAsync(newDir)).get();
break;
}
catch (Exception^ e)
{
if (e->HResult != HRESULT_FROM_WIN32(ERROR_ACCESS_DENIED))
{
throw;
}
else
{
continue;
}
}
}
if (storagefolder == nullptr)
{
return UNZ_INTERNALERROR;
}
// Create the folders that don't exist
advance(it, 1);
for (; it != subdirs.end(); ++it)
{
String^ temp = *it;
try
{
storagefolder = create_task(storagefolder->CreateFolderAsync(*it)).get();
}
catch (Exception^ e)
{
if (e->HResult != HRESULT_FROM_WIN32(ERROR_ALREADY_EXISTS))
{
throw;
}
else
{
storagefolder = create_task(storagefolder->GetFolderAsync(*it)).get();
}
}
}
}
// Based on https://github.com/ms-iot/node/blob/chakra-uwp/deps/zlib/contrib/minizip/miniunz.c#L312
int DoExtractCurrentfile(unzFile uf, String^ dest)
{
char filename_inzip[NODE_MODULE_MAX_PATH];
char* filename_withoutpath;
char* p;
FILE *fout = NULL;
unz_file_info64 file_info;
uLong ratio = 0;
int err = unzGetCurrentFileInfo64(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK)
{
return err;
}
// Prepend the destination to the path (filename_inzip)
char temp[NODE_MODULE_MAX_PATH];
strcpy_s(temp, NODE_MODULE_MAX_PATH, filename_inzip);
strcpy_s(filename_inzip, NODE_MODULE_MAX_PATH, WCharToChar(dest->Data(), dest->Length()).get());
strcat_s(filename_inzip, NODE_MODULE_MAX_PATH, "\\");
strcat_s(filename_inzip, NODE_MODULE_MAX_PATH, temp);
p = filename_withoutpath = filename_inzip;
while ((*p) != '\0')
{
if (((*p) == '/') || ((*p) == '\\'))
{
filename_withoutpath = p + 1;
}
p++;
}
if ((*filename_withoutpath) == '\0')
{
err = _mkdir(filename_inzip);
if (0 != err)
{
return err;
}
}
else
{
const char* write_filename = filename_inzip;
// Needs to be called even when zip has no password
err = unzOpenCurrentFilePassword(uf, 0);
if (err == UNZ_OK)
{
fopen_s(&fout, write_filename, "wb");
/* some zipfile don't contain directory alone before file */
if ((fout == NULL) && (filename_withoutpath != (char*)filename_inzip))
{
char c = *(filename_withoutpath - 1);
*(filename_withoutpath - 1) = '\0';
MakePath(ref new String(CharToWChar(write_filename, sizeof(filename_inzip)).get()));
*(filename_withoutpath - 1) = c;
fopen_s(&fout, write_filename, "wb");
}
}
if (fout != NULL)
{
shared_ptr<byte> buf(new byte[WRITEBUFFERSIZE], [](byte* ptr) { delete[] ptr; });
do
{
err = unzReadCurrentFile(uf, buf.get(), WRITEBUFFERSIZE);
if (err < 0)
{
break;
}
if (err > 0)
{
if (fwrite(buf.get(), err, 1, fout) != 1)
{
err = UNZ_ERRNO;
break;
}
}
}
while (err > 0);
if (fout)
{
fclose(fout);
}
}
if (err == UNZ_OK)
{
err = unzCloseCurrentFile(uf);
}
else
{
unzCloseCurrentFile(uf); /* don't lose the error */
}
}
return err;
}
// Based on https://github.com/ms-iot/node/blob/chakra-uwp/deps/zlib/contrib/minizip/miniunz.c#L475
int DoExtract(unzFile uf, String^ dest)
{
unz_global_info64 gi;
int err = unzGetGlobalInfo64(uf, &gi);
if (err != UNZ_OK)
{
throw ref new ::Platform::Exception(err, L"nodeuwputil::DoExtract unzGetGlobalInfo failed");
}
for (uLong i = 0; i < gi.number_entry; i++)
{
err = DoExtractCurrentfile(uf, dest);
if (err != UNZ_OK)
{
return err;
}
if ((i + 1) < gi.number_entry)
{
err = unzGoToNextFile(uf);
if (err != UNZ_OK)
{
return err;
}
}
}
return err;
}
int CompareHashFiles(char* file1, int file1Size, char* file2, int file2Size, bool& isEqual)
{
FILE* f1 = NULL;
FILE* f2 = NULL;
int err;
isEqual = false;
err = fopen_s(&f1, file1, "r");
if (err != 0)
{
return err;
}
err = fopen_s(&f2, file2, "r");
if (err != 0)
{
if (f1)
{
fclose(f1);
}
return err;
}
char b1[MD5HASHSIZE];
char b2[MD5HASHSIZE];
int bytesRead = fread(b1, 1, MD5HASHSIZE, f1);
if (bytesRead != MD5HASHSIZE)
{
err = UNZ_INTERNALERROR;
}
else
{
bytesRead = fread(b2, 1, MD5HASHSIZE, f2);
if (bytesRead != MD5HASHSIZE)
{
err = UNZ_INTERNALERROR;
}
else
{
if (0 == memcmp(b1, b2, MD5HASHSIZE))
{
isEqual = true;
}
}
}
if (f1)
{
fclose(f1);
}
if (f2)
{
fclose(f2);
}
return err;
}
bool ModuleUpdateRequired()
{
StorageFolder^ appFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
String^ currHashFile;
bool hashesAreEqual;
int err;
try
{
currHashFile = create_task(localFolder->GetFileAsync("node_modules.hash")).get()->Path;
}
catch (Exception^ e)
{
if (e->HResult != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
throw;
}
else
{
return true;
}
}
String^ newHashFile = create_task(appFolder->GetFileAsync("node_modules.hash")).get()->Path;
err = CompareHashFiles(WCharToChar(newHashFile->Data(), newHashFile->Length()).get(), newHashFile->Length(),
WCharToChar(currHashFile->Data(), currHashFile->Length()).get(), currHashFile->Length(), hashesAreEqual);
if (err != UNZ_OK)
{
return false;
}
else
{
if (hashesAreEqual)
{
// No update required if the hashes match
return false;
}
else
{
return true;
}
}
}
void Extract(StorageFile^ zipFile, String^ destination)
{
shared_ptr<char> zipFileCharStr = WCharToChar(zipFile->Path->Data(), zipFile->Path->Length());
unzFile uf = unzOpen64(zipFileCharStr.get());
int err;
if (uf)
{
err = DoExtract(uf, destination);
unzClose(uf);
if (err != UNZ_OK)
{
throw ref new ::Platform::Exception(err, L"nodeuwputil::Extract error");
}
}
else
{
throw ref new ::Platform::Exception(ERROR_INVALID_PARAMETER, L"nodeuwputil::Extract Invalid zip file");
}
}
}
<commit_msg>Rolling back to win32 implementation of MakePath<commit_after>/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "pch.h"
#include "Util.h"
#include <Windows.h>
#include <filesystem>
#include <sstream>
#include "unzip.h"
#include <direct.h>
#define WRITEBUFFERSIZE 8192
#define NODE_MODULE_MAX_PATH 1024
#define MD5HASHSIZE 16
using namespace Platform;
using namespace std::tr2::sys;
using namespace concurrency;
namespace nodeuwputil
{
shared_ptr<char> WCharToChar(const wchar_t* str, int strSize)
{
// Calculate the needed buffer size
DWORD bufferSize = WideCharToMultiByte(CP_UTF8,
0,
str,
strSize,
nullptr,
0,
nullptr,
nullptr);
if (bufferSize == 0)
{
throw ref new ::Platform::Exception(GetLastError(), L"nodeuwputil::WCharToChar failed");
}
shared_ptr<char> buffer(new char[bufferSize + 1], [](char* ptr) { delete[] ptr; });
buffer.get()[bufferSize] = '\0';
// Do the actual conversion
WideCharToMultiByte(CP_UTF8,
0,
str,
strSize,
buffer.get(),
bufferSize,
nullptr,
nullptr);
return buffer;
}
shared_ptr<wchar_t> CharToWChar(const char* str, int strSize)
{
// Calculate the needed buffer size
DWORD bufferSize = MultiByteToWideChar(CP_UTF8,
0,
str,
strSize,
nullptr,
0);
if (bufferSize == 0)
{
throw ref new ::Platform::Exception(GetLastError(), L"nodeuwputil::CharToWChar failed");
}
shared_ptr<wchar_t> buffer(new wchar_t[bufferSize + 1], [](wchar_t* ptr) { delete[] ptr; });
buffer.get()[bufferSize] = '\0';
// Do the actual conversion
MultiByteToWideChar(CP_UTF8,
0,
str,
strSize,
buffer.get(),
bufferSize);
return buffer;
}
void PopulateArgsVector(vector<shared_ptr<char>> &argVector,
String^ startStr, bool &useLogger)
{
if (startStr != nullptr)
{
wstring localFolder(ApplicationData::Current->LocalFolder->Path->Data());
localFolder.append(L"\\");
wstring args(startStr->Data());
args.erase(0, args.find_first_not_of(L" \n\r\t")); // Trim leading whitespace
wstring arg;
shared_ptr<char> in;
bool insert = false;
bool scriptFound = false;
for (size_t i = 0; i < args.length(); i++) {
wchar_t c = args[i];
if (c == ' ')
{
insert = true;
}
else if (c == '\"')
{
i++;
while (args[i] != '\"' && i < args.size())
{
arg += args[i];
i++;
}
i++;
insert = true;
}
else
{
arg += args[i];
}
// We insert an argument into the vector if we see a space or we've reached the
// end of the string.
if ((insert == true || args.size() - 1 == i) && arg.size() != 0)
{
insert = false;
// 'node' will usually be the first argument if the package.json file is also
// used with the console version of node. We'll ignore it if it exists.
if (_wcsicmp(arg.c_str(), L"node") == 0 && argVector.size() == 1)
{
arg.clear();
continue;
}
// Update the script path.
// The script to start will be the first argument that doesn't start with '-'.
// Node usage: node [options] [v8 options] [script.js | -e "script"] [arguments]
// 'options' and 'v8 options' start with '-'
if (arg[0] != '-' && scriptFound == false)
{
scriptFound = true;
arg = localFolder + arg;
}
if (arg.compare(L"--use-logger") == 0)
{
useLogger = true;
arg.clear();
continue;
}
in = WCharToChar(arg.c_str(), arg.size());
argVector.push_back(in);
arg.clear();
}
}
}
}
void CopyFolderSync(StorageFolder^ source, StorageFolder^ destination)
{
path from(source->Path->Data());
path to(destination->Path->Data());
copy_options opts = copy_options::recursive | copy_options::overwrite_existing;
copy(from, to, opts);
}
// Based on https://github.com/ms-iot/node/blob/chakra-uwp/deps/zlib/contrib/minizip/miniunz.c#L138
int MakePath(char* newdir, int len)
{
char *buffer;
char *p;
if (len <= 0)
{
return 0;
}
buffer = (char*)malloc(len + 1);
if (buffer == NULL)
{
return UNZ_INTERNALERROR;
}
strcpy_s(buffer, len, newdir);
if (buffer[len - 1] == '/') {
buffer[len - 1] = '\0';
}
if (_mkdir(buffer) == 0)
{
free(buffer);
return 1;
}
p = buffer + 1;
while (1)
{
char hold;
while (*p && *p != '\\' && *p != '/')
p++;
hold = *p;
*p = 0;
if ((_mkdir(buffer) == -1) && (errno == ENOENT))
{
free(buffer);
return 0;
}
if (hold == 0)
break;
*p++ = hold;
}
free(buffer);
return 1;
}
// Based on https://github.com/ms-iot/node/blob/chakra-uwp/deps/zlib/contrib/minizip/miniunz.c#L312
int DoExtractCurrentfile(unzFile uf, String^ dest)
{
char filename_inzip[NODE_MODULE_MAX_PATH];
char* filename_withoutpath;
char* p;
FILE *fout = NULL;
unz_file_info64 file_info;
uLong ratio = 0;
int err = unzGetCurrentFileInfo64(uf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0);
if (err != UNZ_OK)
{
return err;
}
// Prepend the destination to the path (filename_inzip)
char temp[NODE_MODULE_MAX_PATH];
strcpy_s(temp, NODE_MODULE_MAX_PATH, filename_inzip);
strcpy_s(filename_inzip, NODE_MODULE_MAX_PATH, WCharToChar(dest->Data(), dest->Length()).get());
strcat_s(filename_inzip, NODE_MODULE_MAX_PATH, "\\");
strcat_s(filename_inzip, NODE_MODULE_MAX_PATH, temp);
p = filename_withoutpath = filename_inzip;
while ((*p) != '\0')
{
if (((*p) == '/') || ((*p) == '\\'))
{
filename_withoutpath = p + 1;
}
p++;
}
if ((*filename_withoutpath) == '\0')
{
_mkdir(filename_inzip);
}
else
{
const char* write_filename = filename_inzip;
// Needs to be called even when zip has no password
err = unzOpenCurrentFilePassword(uf, 0);
if (err == UNZ_OK)
{
fopen_s(&fout, write_filename, "wb");
/* some zipfile don't contain directory alone before file */
if ((fout == NULL) && (filename_withoutpath != (char*)filename_inzip))
{
char c = *(filename_withoutpath - 1);
*(filename_withoutpath - 1) = '\0';
MakePath(filename_inzip, sizeof(filename_inzip));
*(filename_withoutpath - 1) = c;
fopen_s(&fout, write_filename, "wb");
}
}
if (fout != NULL)
{
shared_ptr<byte> buf(new byte[WRITEBUFFERSIZE], [](byte* ptr) { delete[] ptr; });
do
{
err = unzReadCurrentFile(uf, buf.get(), WRITEBUFFERSIZE);
if (err < 0)
{
break;
}
if (err > 0)
{
if (fwrite(buf.get(), err, 1, fout) != 1)
{
err = UNZ_ERRNO;
break;
}
}
}
while (err > 0);
if (fout)
{
fclose(fout);
}
}
if (err == UNZ_OK)
{
err = unzCloseCurrentFile(uf);
}
else
{
unzCloseCurrentFile(uf); /* don't lose the error */
}
}
return err;
}
// Based on https://github.com/ms-iot/node/blob/chakra-uwp/deps/zlib/contrib/minizip/miniunz.c#L475
int DoExtract(unzFile uf, String^ dest)
{
unz_global_info64 gi;
int err = unzGetGlobalInfo64(uf, &gi);
if (err != UNZ_OK)
{
throw ref new ::Platform::Exception(err, L"nodeuwputil::DoExtract unzGetGlobalInfo failed");
}
for (uLong i = 0; i < gi.number_entry; i++)
{
if (DoExtractCurrentfile(uf, dest) != UNZ_OK)
{
break;
}
if ((i + 1) < gi.number_entry)
{
if (unzGoToNextFile(uf) != UNZ_OK)
{
break;
}
}
}
return 0;
}
int CompareHashFiles(char* file1, int file1Size, char* file2, int file2Size, bool& isEqual)
{
FILE* f1 = NULL;
FILE* f2 = NULL;
int err;
isEqual = false;
err = fopen_s(&f1, file1, "r");
if (err != 0)
{
return err;
}
err = fopen_s(&f2, file2, "r");
if (err != 0)
{
if (f1)
{
fclose(f1);
}
return err;
}
char b1[MD5HASHSIZE];
char b2[MD5HASHSIZE];
int bytesRead = fread(b1, 1, MD5HASHSIZE, f1);
if (bytesRead != MD5HASHSIZE)
{
err = UNZ_INTERNALERROR;
}
else
{
bytesRead = fread(b2, 1, MD5HASHSIZE, f2);
if (bytesRead != MD5HASHSIZE)
{
err = UNZ_INTERNALERROR;
}
else
{
if (0 == memcmp(b1, b2, MD5HASHSIZE))
{
isEqual = true;
}
}
}
if (f1)
{
fclose(f1);
}
if (f2)
{
fclose(f2);
}
return err;
}
bool ModuleUpdateRequired()
{
StorageFolder^ appFolder = Windows::ApplicationModel::Package::Current->InstalledLocation;
StorageFolder^ localFolder = ApplicationData::Current->LocalFolder;
String^ currHashFile;
bool hashesAreEqual;
int err;
try
{
currHashFile = create_task(localFolder->GetFileAsync("node_modules.hash")).get()->Path;
}
catch (Exception^ e)
{
if (e->HResult != HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND))
{
throw;
}
else
{
return true;
}
}
String^ newHashFile = create_task(appFolder->GetFileAsync("node_modules.hash")).get()->Path;
err = CompareHashFiles(WCharToChar(newHashFile->Data(), newHashFile->Length()).get(), newHashFile->Length(),
WCharToChar(currHashFile->Data(), currHashFile->Length()).get(), currHashFile->Length(), hashesAreEqual);
if (err != UNZ_OK)
{
return false;
}
else
{
if (hashesAreEqual)
{
// No update required if the hashes match
return false;
}
else
{
return true;
}
}
}
void Extract(StorageFile^ zipFile, String^ destination)
{
shared_ptr<char> zipFileCharStr = WCharToChar(zipFile->Path->Data(), zipFile->Path->Length());
unzFile uf = unzOpen64(zipFileCharStr.get());
int err;
if (uf)
{
err = DoExtract(uf, destination);
unzClose(uf);
if (err != UNZ_OK)
{
throw ref new ::Platform::Exception(err, L"nodeuwputil::Extract error");
}
}
else
{
throw ref new ::Platform::Exception(ERROR_INVALID_PARAMETER, L"nodeuwputil::Extract Invalid zip file");
}
}
}
<|endoftext|> |
<commit_before>#include<iostream>
using namespace std;
// Creating a NODE Structure
struct node
{
int data;
struct node *next;
};
// Creating a class STACK
class stack
{
struct node *top;
public:
stack() // constructure
{
top=NULL;
}
void push(); // to insert an element
void pop(); // to delete an element
void show(); // to show the stack
};
// PUSH Operation
void stack::push()
{
int value;
struct node *ptr;
cout<<"\nPUSH Operationn";
cout<<"Enter a number to insert: ";
cin>>value;
ptr=new node;
ptr->data=value;
ptr->next=NULL;
if(top!=NULL)
ptr->next=top;
top=ptr;
cout<<"\nNew item is inserted to the stack!!!";
}
// POP Operation
void stack::pop()
{
struct node *temp;
if(top==NULL)
{
cout<<"\nThe stack is empty!!!";
}
temp=top;
top=top->next;
cout<<"\nPOP Operation........nPoped value is "<<temp->data;
delete temp;
}
// Show stack
void stack::show()
{
struct node *ptr1=top;
cout<<"\nThe stack is\n";
while(ptr1!=NULL)
{
cout<<ptr1->data<<" ->";
ptr1=ptr1->next;
}
cout<<"NULL\n";
}
// Main function
int main()
{
stack s;
int choice;
while(1)
{
cout<<"\n-----------------------------------------------------------";
cout<<"\n\t\tSTACK USING LINKED LIST\n\n";
cout<<"1:PUSH\n2:POP\n3:DISPLAY STACK\n4:EXIT";
cout<<"\nEnter your choice(1-4): ";
cin>>choice;
switch(choice)
{
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.show();
break;
case 4:
return 0;
break;
default:
cout<<"\nPlease enter correct choice(1-4)!!";
break;
}
}
return 0;
}<commit_msg>fixes #1 core dump in pop operation<commit_after>#include<iostream>
using namespace std;
// Creating a NODE Structure
struct node
{
int data;
struct node *next;
};
// Creating a class STACK
class stack
{
struct node *top;
public:
stack() // constructure
{
top=NULL;
}
void push(); // to insert an element
void pop(); // to delete an element
void show(); // to show the stack
};
// PUSH Operation
void stack::push()
{
int value;
struct node *ptr;
cout<<"\nPUSH Operation\n";
cout<<"Enter a number to insert: ";
cin>>value;
ptr=new node;
ptr->data=value;
ptr->next=NULL;
if(top!=NULL)
ptr->next=top;
top=ptr;
cout<<"\nNew item is inserted to the stack!!!";
}
// POP Operation
void stack::pop()
{
struct node *temp;
if(top==NULL)
{
cout<<"\nThe stack is empty!!!";
}else{
temp=top;
top=top->next;
cout<<"\nPOP Operation........nPoped value is "<<temp->data;
delete temp;
}
}
// Show stack
void stack::show()
{
struct node *ptr1=top;
cout<<"\nThe stack is\n";
while(ptr1!=NULL)
{
cout<<ptr1->data<<" ->";
ptr1=ptr1->next;
}
cout<<"NULL\n";
}
// Main function
int main()
{
stack s;
int choice;
while(1)
{
cout<<"\n-----------------------------------------------------------";
cout<<"\n\t\tSTACK USING LINKED LIST\n\n";
cout<<"1:PUSH\n2:POP\n3:DISPLAY STACK\n4:EXIT";
cout<<"\nEnter your choice(1-4): ";
cin>>choice;
switch(choice)
{
case 1:
s.push();
break;
case 2:
s.pop();
break;
case 3:
s.show();
break;
case 4:
return 0;
break;
default:
cout<<"\nPlease enter correct choice(1-4)!!";
break;
}
}
return 0;
}<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
$Log: AliT0Preprocessor.cxx,v $
Revision 1.8 2007/12/07 15:22:51 alla
bug fixed by Alberto
Revision 1.7 2007/12/06 16:35:24 alla
new bugs fixed by Tomek
Revision 1.5 2007/11/23 19:28:52 alla
bug fixed
Version 2.1 2007/11/21
Preprocessor storing data to OCDB (T.Malkiewicz)
Version 1.1 2006/10
Preliminary test version (T.Malkiewicz)
*/
// T0 preprocessor:
// 1) takes data from DCS and passes it to the class AliTOFDataDCS
// for processing and writes the result to the Reference DB.
// 2) takes data form DAQ (both from Laser Calibration and Physics runs),
// processes it, and stores either to OCDB or to Reference DB.
#include "AliT0Preprocessor.h"
#include "AliT0DataDCS.h"
#include "AliT0CalibWalk.h"
#include "AliT0CalibTimeEq.h"
#include "AliCDBMetaData.h"
#include "AliDCSValue.h"
#include "AliLog.h"
#include <TTimeStamp.h>
#include <TFile.h>
#include <TObjString.h>
#include <TNamed.h>
#include "AliT0Dqclass.h"
ClassImp(AliT0Preprocessor)
//____________________________________________________
AliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) :
AliPreprocessor("T00", shuttle),
fData(0)
{
//constructor
AddRunType("PHYSICS");
AddRunType("STANDALONE");
}
//____________________________________________________
AliT0Preprocessor::~AliT0Preprocessor()
{
//destructor
delete fData;
fData = 0;
}
//____________________________________________________
void AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)
{
// Creates AliT0DataDCS object
AliPreprocessor::Initialize(run, startTime, endTime);
AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString()));
fData = new AliT0DataDCS(fRun, fStartTime, fEndTime);
}
//____________________________________________________
Bool_t AliT0Preprocessor::ProcessDCS(){
// Check whether DCS should be processed or not...
TString runType = GetRunType();
Log(Form("ProcessDCS - RunType: %s",runType.Data()));
if((runType == "STANDALONE")||(runType == "PHYSICS")){
// return kFALSE;
return kTRUE;
}else{
return kFALSE;
}
}
//____________________________________________________
UInt_t AliT0Preprocessor::ProcessDCSDataPoints(TMap* dcsAliasMap){
// Fills data into AliT0DataDCS object
Log("Processing DCS DP");
Bool_t resultDCSMap=kFALSE;
Bool_t resultDCSStore=kFALSE;
if(!dcsAliasMap)
{
Log("No DCS input data");
return 1;
}
else
{
resultDCSMap=fData->ProcessData(*dcsAliasMap);
if(!resultDCSMap)
{
Log("Error when processing DCS data");
return 2;// return error Code for processed DCS data not stored
}
else
{
AliCDBMetaData metaDataDCS;
metaDataDCS.SetBeamPeriod(0);
metaDataDCS.SetResponsible("Tomasz Malkiewicz");
metaDataDCS.SetComment("This preprocessor fills an AliTODataDCS object.");
AliInfo("Storing DCS Data");
resultDCSStore = StoreReferenceData("Calib","DCSData",fData, &metaDataDCS);
if (!resultDCSStore)
{
Log("Some problems occurred while storing DCS data results in ReferenceDB");
return 2;// return error Code for processed DCS data not stored
}
}
}
return 0;
}
//____________________________________________________
UInt_t AliT0Preprocessor::ProcessLaser(){
// Processing data from DAQ Standalone run
Log("Processing Laser calibration - Walk Correction");
Bool_t resultLaser=kFALSE;
//processing DAQ
TList* list = GetFileSources(kDAQ, "LASER");
if (list)
{
TIter iter(list);
TObjString *source;
while ((source = dynamic_cast<TObjString *> (iter.Next())))
{
const char *laserFile = GetFile(kDAQ, "LASER", source->GetName());
if (laserFile)
{
Log(Form("File with Id LASER found in source %s!", source->GetName()));
AliT0CalibWalk *laser = new AliT0CalibWalk();
laser->MakeWalkCorrGraph(laserFile);
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Tomek&Michal");
metaData.SetComment("Walk correction from laser runs.");
resultLaser=Store("Calib","Slewing_Walk", laser, &metaData, 0, 1);
delete laser;
Log(Form("resultLaser = %d",resultLaser));
}
else
{
Log(Form("Could not find file with Id LASER in source %s!", source->GetName()));
return 1;
}
}
if (!resultLaser)
{
Log("No Laser Data stored");
return 3;//return error code for failure in storing Laser Data
}
} else {
Log("No sources found for id LASER!");
return 1;
}
return 0;
}
//____________________________________________________
UInt_t AliT0Preprocessor::ProcessPhysics(){
//Processing data from DAQ Physics run
Log("Processing Physics");
Bool_t resultOnline=kFALSE;
//processing DAQ
TList* listPhys = GetFileSources(kDAQ, "PHYSICS");
if (listPhys)
{
TIter iter(listPhys);
TObjString *sourcePhys;
while ((sourcePhys = dynamic_cast<TObjString *> (iter.Next())))
{
const char *filePhys = GetFile(kDAQ, "PHYSICS", sourcePhys->GetName());
if (filePhys)
{
AliT0CalibTimeEq *online = new AliT0CalibTimeEq();
online->Reset();
online->ComputeOnlineParams(filePhys);
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Tomek&Michal");
metaData.SetComment("Time equalizing result.");
resultOnline = Store("Calib","TimeDelay", online, &metaData, 0, 1);
Log(Form("resultOnline = %d",resultOnline));
delete online;
}
else
{
Log(Form("Could not find file with Id PHYSICS in source %s!", sourcePhys->GetName()));
return 1;
}
}
if (!resultOnline)
{
Log("No Data stored");
return 4;//return error code for failure in storing OCDB Data
}
} else {
Log("No sources found for id PHYSICS!");
return 1;
}
return 0;
}
//____________________________________________________
UInt_t AliT0Preprocessor::ProcessCosmic(){
//Processing data from DAQ Physics run
Log("Processing Laser Physics");
Bool_t resultLaserOnline=kFALSE;
//processing DAQ
TList* listLaser = GetFileSources(kDAQ, "COSMIC");
if (listLaser)
{
TIter iter(listLaser);
TObjString *sourceLaser;
while ((sourceLaser = dynamic_cast<TObjString *> (iter.Next())))
{
const char *fileLaser = GetFile(kDAQ, "COSMIC", sourceLaser->GetName());
if (fileLaser)
{
AliT0CalibTimeEq *onlineLaser = new AliT0CalibTimeEq();
onlineLaser->Reset();
onlineLaser->ComputeOnlineParams(fileLaser);
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Tomek&Michal");
metaData.SetComment("Time equalizing result.");
resultLaserOnline = Store("Calib","LaserTimeDelay", onlineLaser, &metaData, 0, 1);
Log(Form("resultLaserOnline = %d",resultLaserOnline));
delete onlineLaser;
}
else
{
Log(Form("Could not find file with Id COSMIC in source %s!", sourceLaser->GetName()));
return 0;
}
}
if (!resultLaserOnline)
{
Log("No Laser Data stored");
return 0;//return error code for failure in storing OCDB Data
}
} else {
Log("No sources found for id COSMIC!");
return 0;
}
return 0;
}
//____________________________________________________
UInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap )
{
// T0 preprocessor return codes:
// return=0 : all ok
// return=1 : no DCS input data
// return=2 : failed to store DCS data
// return=3 : no Laser data (Walk correction)
// return=4 : failed to store OCDB time equalized data
// return=5 : no DAQ input for OCDB
// return=6 : failed to retrieve DAQ data from OCDB
// return=7 : failed to store T0 OCDB data
Bool_t dcsDP = ProcessDCS();
Log(Form("dcsDP = %d",dcsDP));
TString runType = GetRunType();
Log(Form("RunType: %s",runType.Data()));
//processing
if(runType == "STANDALONE"){
Int_t iresultLaser = ProcessLaser();
if(dcsDP==1){
Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
return iresultDCS;
}
Log(Form("iresultLaser = %d",iresultLaser));
return iresultLaser;
}
else if(runType == "PHYSICS"){
Int_t iresultPhysics = ProcessPhysics();
// Int_t iresultCosmic = ProcessCosmic();
if(dcsDP==1){
Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
return iresultDCS;
}
Log(Form("iresultPhysics = %d",iresultPhysics));
return iresultPhysics;
// Log(Form("iresultPhysics =iresultCosmic %d",iresultCosmic));
// return iresultCosmic;
}
return 0;
}
<commit_msg> new run type LASER implemented<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/*
$Log: AliT0Preprocessor.cxx,v $
Revision 1.8 2007/12/07 15:22:51 alla
bug fixed by Alberto
Revision 1.7 2007/12/06 16:35:24 alla
new bugs fixed by Tomek
Revision 1.5 2007/11/23 19:28:52 alla
bug fixed
Version 2.1 2007/11/21
Preprocessor storing data to OCDB (T.Malkiewicz)
Version 1.1 2006/10
Preliminary test version (T.Malkiewicz)
*/
// T0 preprocessor:
// 1) takes data from DCS and passes it to the class AliTOFDataDCS
// for processing and writes the result to the Reference DB.
// 2) takes data form DAQ (both from Laser Calibration and Physics runs),
// processes it, and stores either to OCDB or to Reference DB.
#include "AliT0Preprocessor.h"
#include "AliT0DataDCS.h"
#include "AliT0CalibWalk.h"
#include "AliT0CalibTimeEq.h"
#include "AliCDBMetaData.h"
#include "AliDCSValue.h"
#include "AliLog.h"
#include <TTimeStamp.h>
#include <TFile.h>
#include <TObjString.h>
#include <TNamed.h>
#include "AliT0Dqclass.h"
ClassImp(AliT0Preprocessor)
//____________________________________________________
AliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) :
AliPreprocessor("T00", shuttle),
fData(0)
{
//constructor
AddRunType("PHYSICS");
AddRunType("STANDALONE");
AddRunType("LASER");
}
//____________________________________________________
AliT0Preprocessor::~AliT0Preprocessor()
{
//destructor
delete fData;
fData = 0;
}
//____________________________________________________
void AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)
{
// Creates AliT0DataDCS object
AliPreprocessor::Initialize(run, startTime, endTime);
AliInfo(Form("\n\tRun %d \n\tStartTime %s \n\tEndTime %s", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString()));
fData = new AliT0DataDCS(fRun, fStartTime, fEndTime);
}
//____________________________________________________
Bool_t AliT0Preprocessor::ProcessDCS(){
// Check whether DCS should be processed or not...
TString runType = GetRunType();
Log(Form("ProcessDCS - RunType: %s",runType.Data()));
if((runType == "STANDALONE")||(runType == "PHYSICS")){
// return kFALSE;
return kTRUE;
}else{
return kFALSE;
}
}
//____________________________________________________
UInt_t AliT0Preprocessor::ProcessDCSDataPoints(TMap* dcsAliasMap){
// Fills data into AliT0DataDCS object
Log("Processing DCS DP");
Bool_t resultDCSMap=kFALSE;
Bool_t resultDCSStore=kFALSE;
if(!dcsAliasMap)
{
Log("No DCS input data");
return 1;
}
else
{
resultDCSMap=fData->ProcessData(*dcsAliasMap);
if(!resultDCSMap)
{
Log("Error when processing DCS data");
return 2;// return error Code for processed DCS data not stored
}
else
{
AliCDBMetaData metaDataDCS;
metaDataDCS.SetBeamPeriod(0);
metaDataDCS.SetResponsible("Tomasz Malkiewicz");
metaDataDCS.SetComment("This preprocessor fills an AliTODataDCS object.");
AliInfo("Storing DCS Data");
resultDCSStore = StoreReferenceData("Calib","DCSData",fData, &metaDataDCS);
if (!resultDCSStore)
{
Log("Some problems occurred while storing DCS data results in ReferenceDB");
return 2;// return error Code for processed DCS data not stored
}
}
}
return 0;
}
//____________________________________________________
UInt_t AliT0Preprocessor::ProcessLaser(){
// Processing data from DAQ Standalone run
Log("Processing Laser calibration - Walk Correction");
Bool_t resultLaser=kFALSE;
//processing DAQ
TList* list = GetFileSources(kDAQ, "LASER");
if (list)
{
TIter iter(list);
TObjString *source;
while ((source = dynamic_cast<TObjString *> (iter.Next())))
{
const char *laserFile = GetFile(kDAQ, "LASER", source->GetName());
if (laserFile)
{
Log(Form("File with Id LASER found in source %s!", source->GetName()));
AliT0CalibWalk *laser = new AliT0CalibWalk();
laser->MakeWalkCorrGraph(laserFile);
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Tomek&Michal");
metaData.SetComment("Walk correction from laser runs.");
resultLaser=Store("Calib","Slewing_Walk", laser, &metaData, 0, 1);
delete laser;
Log(Form("resultLaser = %d",resultLaser));
}
else
{
Log(Form("Could not find file with Id LASER in source %s!", source->GetName()));
return 1;
}
}
if (!resultLaser)
{
Log("No Laser Data stored");
return 3;//return error code for failure in storing Laser Data
}
} else {
Log("No sources found for id LASER!");
return 1;
}
return 0;
}
//____________________________________________________
UInt_t AliT0Preprocessor::ProcessPhysics(){
//Processing data from DAQ Physics run
Log("Processing Physics");
Bool_t resultOnline=kFALSE;
//processing DAQ
TList* listPhys = GetFileSources(kDAQ, "PHYSICS");
if (listPhys)
{
TIter iter(listPhys);
TObjString *sourcePhys;
while ((sourcePhys = dynamic_cast<TObjString *> (iter.Next())))
{
const char *filePhys = GetFile(kDAQ, "PHYSICS", sourcePhys->GetName());
if (filePhys)
{
AliT0CalibTimeEq *online = new AliT0CalibTimeEq();
online->Reset();
online->ComputeOnlineParams(filePhys);
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Tomek&Michal");
metaData.SetComment("Time equalizing result.");
resultOnline = Store("Calib","TimeDelay", online, &metaData, 0, 1);
Log(Form("resultOnline = %d",resultOnline));
delete online;
}
else
{
Log(Form("Could not find file with Id PHYSICS in source %s!", sourcePhys->GetName()));
return 1;
}
}
if (!resultOnline)
{
Log("No Data stored");
return 4;//return error code for failure in storing OCDB Data
}
} else {
Log("No sources found for id PHYSICS!");
return 1;
}
return 0;
}
//____________________________________________________
UInt_t AliT0Preprocessor::ProcessCosmic(){
//Processing data from DAQ Physics run
Log("Processing Laser Physics");
Bool_t resultLaserOnline=kFALSE;
//processing DAQ
TList* listLaser = GetFileSources(kDAQ, "COSMIC");
if (listLaser)
{
TIter iter(listLaser);
TObjString *sourceLaser;
while ((sourceLaser = dynamic_cast<TObjString *> (iter.Next())))
{
const char *fileLaser = GetFile(kDAQ, "COSMIC", sourceLaser->GetName());
if (fileLaser)
{
AliT0CalibTimeEq *onlineLaser = new AliT0CalibTimeEq();
onlineLaser->Reset();
onlineLaser->ComputeOnlineParams(fileLaser);
AliCDBMetaData metaData;
metaData.SetBeamPeriod(0);
metaData.SetResponsible("Tomek&Michal");
metaData.SetComment("Time equalizing result.");
resultLaserOnline = Store("Calib","LaserTimeDelay", onlineLaser, &metaData, 0, 1);
Log(Form("resultLaserOnline = %d",resultLaserOnline));
delete onlineLaser;
}
else
{
Log(Form("Could not find file with Id COSMIC in source %s!", sourceLaser->GetName()));
return 0;
}
}
if (!resultLaserOnline)
{
Log("No Laser Data stored");
return 0;//return error code for failure in storing OCDB Data
}
} else {
Log("No sources found for id COSMIC!");
return 0;
}
return 0;
}
//____________________________________________________
UInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap )
{
// T0 preprocessor return codes:
// return=0 : all ok
// return=1 : no DCS input data
// return=2 : failed to store DCS data
// return=3 : no Laser data (Walk correction)
// return=4 : failed to store OCDB time equalized data
// return=5 : no DAQ input for OCDB
// return=6 : failed to retrieve DAQ data from OCDB
// return=7 : failed to store T0 OCDB data
Bool_t dcsDP = ProcessDCS();
Log(Form("dcsDP = %d",dcsDP));
TString runType = GetRunType();
Log(Form("RunType: %s",runType.Data()));
//processing
if(runType == "STANDALONE"){
if(dcsDP==1){
Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
return iresultDCS;
}
}
if(runType == "LASER"){
Int_t iresultLaser = ProcessLaser();
Log(Form("iresultLaser = %d",iresultLaser));
return iresultLaser;
}
else if(runType == "PHYSICS"){
Int_t iresultPhysics = ProcessPhysics();
// Int_t iresultCosmic = ProcessCosmic();
if(dcsDP==1){
Int_t iresultDCS = ProcessDCSDataPoints(dcsAliasMap);
return iresultDCS;
}
Log(Form("iresultPhysics = %d",iresultPhysics));
return iresultPhysics;
// Log(Form("iresultPhysics =iresultCosmic %d",iresultCosmic));
// return iresultCosmic;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 "ros/init.h"
#include "ros/names.h"
#include "ros/xmlrpc_manager.h"
#include "ros/poll_manager.h"
#include "ros/connection_manager.h"
#include "ros/topic_manager.h"
#include "ros/service_manager.h"
#include "ros/this_node.h"
#include "ros/network.h"
#include "ros/file_log.h"
#include "ros/callback_queue.h"
#include "ros/param.h"
#include "ros/rosout_appender.h"
#include "roscpp/GetLoggers.h"
#include "roscpp/SetLoggerLevel.h"
#include <ros/console.h>
#include <ros/time.h>
#include <roslib/Time.h>
#include <roslib/Clock.h>
#include <algorithm>
#include <signal.h>
#include <cstdlib>
namespace ros
{
namespace master
{
void init(const M_string& remappings);
}
namespace this_node
{
void init(const std::string& names, const M_string& remappings, uint32_t options);
}
namespace network
{
void init(const M_string& remappings);
}
namespace param
{
void init(const M_string& remappings);
}
namespace file_log
{
void init(const M_string& remappings);
}
CallbackQueue g_global_queue;
ROSOutAppenderPtr g_rosout_appender;
static bool g_initialized = false;
static bool g_started = false;
static bool g_atexit_registered = false;
static boost::mutex g_start_mutex;
static bool g_ok = false;
static uint32_t g_init_options = 0;
static bool g_shutdown_requested = false;
static volatile bool g_shutting_down = false;
static boost::mutex g_shutting_down_mutex;
static boost::thread g_internal_queue_thread;
bool isInitialized()
{
return g_initialized;
}
bool isShuttingDown()
{
return g_shutting_down;
}
void checkForShutdown()
{
if (g_shutdown_requested)
{
shutdown();
}
}
void requestShutdown()
{
g_shutdown_requested = true;
}
void atexitCallback()
{
if (ok() && !isShuttingDown())
{
ROS_INFO("shutting down due to exit() or end of main() without cleanup of all NodeHandles");
shutdown();
}
}
void shutdownCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result)
{
int num_params = 0;
if (params.getType() == XmlRpc::XmlRpcValue::TypeArray)
num_params = params.size();
if (num_params > 1)
{
std::string reason = params[1];
ROS_WARN("Shutdown request received.");
ROS_WARN("Reason given for shutdown: [%s]", reason.c_str());
requestShutdown();
}
result = xmlrpc::responseInt(1, "", 0);
}
bool getLoggers(roscpp::GetLoggers::Request&, roscpp::GetLoggers::Response& resp)
{
log4cxx::spi::LoggerRepositoryPtr repo = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME)->getLoggerRepository();
log4cxx::LoggerList loggers = repo->getCurrentLoggers();
log4cxx::LoggerList::iterator it = loggers.begin();
log4cxx::LoggerList::iterator end = loggers.end();
for (; it != end; ++it)
{
roscpp::Logger logger;
logger.name = (*it)->getName();
const log4cxx::LevelPtr& level = (*it)->getEffectiveLevel();
if (level)
{
logger.level = level->toString();
}
resp.loggers.push_back(logger);
}
return true;
}
bool setLoggerLevel(roscpp::SetLoggerLevel::Request& req, roscpp::SetLoggerLevel::Response&)
{
log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(req.logger);
log4cxx::LevelPtr level;
std::transform(req.level.begin(), req.level.end(), req.level.begin(), (int(*)(int))std::toupper);
if (req.level == "DEBUG")
{
level = log4cxx::Level::getDebug();
}
else if (req.level == "INFO")
{
level = log4cxx::Level::getInfo();
}
else if (req.level == "WARN")
{
level = log4cxx::Level::getWarn();
}
else if (req.level == "ERROR")
{
level = log4cxx::Level::getError();
}
else if (req.level == "FATAL")
{
level = log4cxx::Level::getFatal();
}
if (level)
{
logger->setLevel(level);
console::notifyLoggerLevelsChanged();
return true;
}
return false;
}
void timeCallback(const roslib::Time::ConstPtr& msg)
{
Time::setNow(msg->rostime);
}
void clockCallback(const roslib::Clock::ConstPtr& msg)
{
Time::setNow(msg->clock);
}
CallbackQueuePtr getInternalCallbackQueue()
{
static CallbackQueuePtr queue;
if (!queue)
{
queue.reset(new CallbackQueue);
}
return queue;
}
void basicSigintHandler(int sig)
{
ros::requestShutdown();
}
void internalCallbackQueueThreadFunc()
{
disableAllSignalsInThisThread();
CallbackQueuePtr queue = getInternalCallbackQueue();
while (!g_shutting_down)
{
queue->callAvailable(WallDuration(0.05));
}
}
bool isStarted()
{
return g_started;
}
void start()
{
boost::mutex::scoped_lock lock(g_start_mutex);
if (g_started)
{
return;
}
g_shutdown_requested = false;
g_shutting_down = false;
g_started = true;
g_ok = true;
PollManager::instance()->addPollThreadListener(checkForShutdown);
XMLRPCManager::instance()->bind("shutdown", shutdownCallback);
TopicManager::instance()->start();
ServiceManager::instance()->start();
ConnectionManager::instance()->start();
PollManager::instance()->start();
XMLRPCManager::instance()->start();
if (!(g_init_options & init_options::NoSigintHandler))
{
signal(SIGINT, basicSigintHandler);
}
if (!(g_init_options & init_options::NoRosout))
{
g_rosout_appender = new ROSOutAppender;
const log4cxx::LoggerPtr& logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME);
logger->addAppender(g_rosout_appender);
}
if (!g_shutting_down)
{
{
ros::AdvertiseServiceOptions ops;
ops.init<roscpp::GetLoggers>(names::resolve("~get_loggers"), getLoggers);
ops.callback_queue = getInternalCallbackQueue().get();
ServiceManager::instance()->advertiseService(ops);
}
if (!g_shutting_down)
{
{
ros::AdvertiseServiceOptions ops;
ops.init<roscpp::SetLoggerLevel>(names::resolve("~set_logger_level"), setLoggerLevel);
ops.callback_queue = getInternalCallbackQueue().get();
ServiceManager::instance()->advertiseService(ops);
}
if (!g_shutting_down)
{
bool use_sim_time = false;
param::param("/use_sim_time", use_sim_time, use_sim_time);
if (use_sim_time)
{
Time::setNow(ros::Time());
}
if (!g_shutting_down)
{
{
ros::SubscribeOptions ops;
ops.init<roslib::Time>("/time", 1, timeCallback);
ops.callback_queue = getInternalCallbackQueue().get();
TopicManager::instance()->subscribe(ops);
}
{
ros::SubscribeOptions ops;
ops.init<roslib::Clock>("/clock", 1, clockCallback);
ops.callback_queue = getInternalCallbackQueue().get();
TopicManager::instance()->subscribe(ops);
}
g_internal_queue_thread = boost::thread(internalCallbackQueueThreadFunc);
g_global_queue.enable();
getGlobalCallbackQueue()->enable();
ROS_DEBUG("Started node [%s], pid [%d], bound on [%s], xmlrpc port [%d], tcpros port [%d], logging to [%s], using [%s] time", this_node::getName().c_str(), getpid(), network::getHost().c_str(), XMLRPCManager::instance()->getServerPort(), ConnectionManager::instance()->getTCPPort(), file_log::getLogFilename().c_str(), Time::useSystemTime() ? "real" : "sim");
}
}
}
}
// If we received a shutdown request while initializing, wait until we've shutdown to continue
if (g_shutting_down)
{
boost::mutex::scoped_lock lock(g_shutting_down_mutex);
}
}
void init(const M_string& remappings, const std::string& name, uint32_t options)
{
if (!g_atexit_registered)
{
g_atexit_registered = true;
atexit(atexitCallback);
}
if (!g_initialized)
{
g_init_options = options;
g_ok = true;
ROSCONSOLE_AUTOINIT;
ros::Time::init();
network::init(remappings);
master::init(remappings);
// names:: namespace is initialized by this_node
this_node::init(name, remappings, options);
param::init(remappings);
file_log::init(remappings);
g_initialized = true;
}
}
void init(int& argc, char** argv, const std::string& name, uint32_t options)
{
M_string remappings;
int full_argc = argc;
// now, move the remapping argv's to the end, and decrement argc as needed
for (int i = 0; i < argc; )
{
std::string arg = argv[i];
size_t pos = arg.find(":=");
if (pos != std::string::npos)
{
std::string local_name = arg.substr(0, pos);
std::string external_name = arg.substr(pos + 2);
remappings[local_name] = external_name;
// shuffle everybody down and stuff this guy at the end of argv
char *tmp = argv[i];
for (int j = i; j < full_argc - 1; j++)
argv[j] = argv[j+1];
argv[argc-1] = tmp;
argc--;
}
else
{
i++; // move on, since we didn't shuffle anybody here to replace it
}
}
init(remappings, name, options);
}
void init(const VP_string& remappings, const std::string& name, uint32_t options)
{
M_string remappings_map;
VP_string::const_iterator it = remappings.begin();
VP_string::const_iterator end = remappings.end();
for (; it != end; ++it)
{
remappings_map[it->first] = it->second;
}
init(remappings_map, name, options);
}
void spin()
{
SingleThreadedSpinner s;
spin(s);
}
void spin(Spinner& s)
{
s.spin();
}
void spinOnce()
{
g_global_queue.callAvailable(ros::WallDuration());
}
CallbackQueue* getGlobalCallbackQueue()
{
return &g_global_queue;
}
bool ok()
{
return g_ok;
}
void shutdown()
{
boost::mutex::scoped_lock lock(g_shutting_down_mutex);
if (g_shutting_down)
{
return;
}
g_shutting_down = true;
g_global_queue.disable();
g_global_queue.clear();
getGlobalCallbackQueue()->disable();
getGlobalCallbackQueue()->clear();
if (g_internal_queue_thread.get_id() != boost::this_thread::get_id())
{
g_internal_queue_thread.join();
ROS_DEBUG("internal callback queue thread shut down");
}
const log4cxx::LoggerPtr& logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME);
logger->removeAppender(g_rosout_appender);
g_rosout_appender = 0;
if (g_started)
{
XMLRPCManager::instance()->shutdown();
TopicManager::instance()->shutdown();
ServiceManager::instance()->shutdown();
ConnectionManager::instance()->shutdown();
PollManager::instance()->shutdown();
}
g_started = false;
g_ok = false;
Time::shutdown();
}
}
<commit_msg>info->debug<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* 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 Willow Garage, Inc. 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 "ros/init.h"
#include "ros/names.h"
#include "ros/xmlrpc_manager.h"
#include "ros/poll_manager.h"
#include "ros/connection_manager.h"
#include "ros/topic_manager.h"
#include "ros/service_manager.h"
#include "ros/this_node.h"
#include "ros/network.h"
#include "ros/file_log.h"
#include "ros/callback_queue.h"
#include "ros/param.h"
#include "ros/rosout_appender.h"
#include "roscpp/GetLoggers.h"
#include "roscpp/SetLoggerLevel.h"
#include <ros/console.h>
#include <ros/time.h>
#include <roslib/Time.h>
#include <roslib/Clock.h>
#include <algorithm>
#include <signal.h>
#include <cstdlib>
namespace ros
{
namespace master
{
void init(const M_string& remappings);
}
namespace this_node
{
void init(const std::string& names, const M_string& remappings, uint32_t options);
}
namespace network
{
void init(const M_string& remappings);
}
namespace param
{
void init(const M_string& remappings);
}
namespace file_log
{
void init(const M_string& remappings);
}
CallbackQueue g_global_queue;
ROSOutAppenderPtr g_rosout_appender;
static bool g_initialized = false;
static bool g_started = false;
static bool g_atexit_registered = false;
static boost::mutex g_start_mutex;
static bool g_ok = false;
static uint32_t g_init_options = 0;
static bool g_shutdown_requested = false;
static volatile bool g_shutting_down = false;
static boost::mutex g_shutting_down_mutex;
static boost::thread g_internal_queue_thread;
bool isInitialized()
{
return g_initialized;
}
bool isShuttingDown()
{
return g_shutting_down;
}
void checkForShutdown()
{
if (g_shutdown_requested)
{
shutdown();
}
}
void requestShutdown()
{
g_shutdown_requested = true;
}
void atexitCallback()
{
if (ok() && !isShuttingDown())
{
ROS_DEBUG("shutting down due to exit() or end of main() without cleanup of all NodeHandles");
shutdown();
}
}
void shutdownCallback(XmlRpc::XmlRpcValue& params, XmlRpc::XmlRpcValue& result)
{
int num_params = 0;
if (params.getType() == XmlRpc::XmlRpcValue::TypeArray)
num_params = params.size();
if (num_params > 1)
{
std::string reason = params[1];
ROS_WARN("Shutdown request received.");
ROS_WARN("Reason given for shutdown: [%s]", reason.c_str());
requestShutdown();
}
result = xmlrpc::responseInt(1, "", 0);
}
bool getLoggers(roscpp::GetLoggers::Request&, roscpp::GetLoggers::Response& resp)
{
log4cxx::spi::LoggerRepositoryPtr repo = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME)->getLoggerRepository();
log4cxx::LoggerList loggers = repo->getCurrentLoggers();
log4cxx::LoggerList::iterator it = loggers.begin();
log4cxx::LoggerList::iterator end = loggers.end();
for (; it != end; ++it)
{
roscpp::Logger logger;
logger.name = (*it)->getName();
const log4cxx::LevelPtr& level = (*it)->getEffectiveLevel();
if (level)
{
logger.level = level->toString();
}
resp.loggers.push_back(logger);
}
return true;
}
bool setLoggerLevel(roscpp::SetLoggerLevel::Request& req, roscpp::SetLoggerLevel::Response&)
{
log4cxx::LoggerPtr logger = log4cxx::Logger::getLogger(req.logger);
log4cxx::LevelPtr level;
std::transform(req.level.begin(), req.level.end(), req.level.begin(), (int(*)(int))std::toupper);
if (req.level == "DEBUG")
{
level = log4cxx::Level::getDebug();
}
else if (req.level == "INFO")
{
level = log4cxx::Level::getInfo();
}
else if (req.level == "WARN")
{
level = log4cxx::Level::getWarn();
}
else if (req.level == "ERROR")
{
level = log4cxx::Level::getError();
}
else if (req.level == "FATAL")
{
level = log4cxx::Level::getFatal();
}
if (level)
{
logger->setLevel(level);
console::notifyLoggerLevelsChanged();
return true;
}
return false;
}
void timeCallback(const roslib::Time::ConstPtr& msg)
{
Time::setNow(msg->rostime);
}
void clockCallback(const roslib::Clock::ConstPtr& msg)
{
Time::setNow(msg->clock);
}
CallbackQueuePtr getInternalCallbackQueue()
{
static CallbackQueuePtr queue;
if (!queue)
{
queue.reset(new CallbackQueue);
}
return queue;
}
void basicSigintHandler(int sig)
{
ros::requestShutdown();
}
void internalCallbackQueueThreadFunc()
{
disableAllSignalsInThisThread();
CallbackQueuePtr queue = getInternalCallbackQueue();
while (!g_shutting_down)
{
queue->callAvailable(WallDuration(0.05));
}
}
bool isStarted()
{
return g_started;
}
void start()
{
boost::mutex::scoped_lock lock(g_start_mutex);
if (g_started)
{
return;
}
g_shutdown_requested = false;
g_shutting_down = false;
g_started = true;
g_ok = true;
PollManager::instance()->addPollThreadListener(checkForShutdown);
XMLRPCManager::instance()->bind("shutdown", shutdownCallback);
TopicManager::instance()->start();
ServiceManager::instance()->start();
ConnectionManager::instance()->start();
PollManager::instance()->start();
XMLRPCManager::instance()->start();
if (!(g_init_options & init_options::NoSigintHandler))
{
signal(SIGINT, basicSigintHandler);
}
if (!(g_init_options & init_options::NoRosout))
{
g_rosout_appender = new ROSOutAppender;
const log4cxx::LoggerPtr& logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME);
logger->addAppender(g_rosout_appender);
}
if (!g_shutting_down)
{
{
ros::AdvertiseServiceOptions ops;
ops.init<roscpp::GetLoggers>(names::resolve("~get_loggers"), getLoggers);
ops.callback_queue = getInternalCallbackQueue().get();
ServiceManager::instance()->advertiseService(ops);
}
if (!g_shutting_down)
{
{
ros::AdvertiseServiceOptions ops;
ops.init<roscpp::SetLoggerLevel>(names::resolve("~set_logger_level"), setLoggerLevel);
ops.callback_queue = getInternalCallbackQueue().get();
ServiceManager::instance()->advertiseService(ops);
}
if (!g_shutting_down)
{
bool use_sim_time = false;
param::param("/use_sim_time", use_sim_time, use_sim_time);
if (use_sim_time)
{
Time::setNow(ros::Time());
}
if (!g_shutting_down)
{
{
ros::SubscribeOptions ops;
ops.init<roslib::Time>("/time", 1, timeCallback);
ops.callback_queue = getInternalCallbackQueue().get();
TopicManager::instance()->subscribe(ops);
}
{
ros::SubscribeOptions ops;
ops.init<roslib::Clock>("/clock", 1, clockCallback);
ops.callback_queue = getInternalCallbackQueue().get();
TopicManager::instance()->subscribe(ops);
}
g_internal_queue_thread = boost::thread(internalCallbackQueueThreadFunc);
g_global_queue.enable();
getGlobalCallbackQueue()->enable();
ROS_DEBUG("Started node [%s], pid [%d], bound on [%s], xmlrpc port [%d], tcpros port [%d], logging to [%s], using [%s] time", this_node::getName().c_str(), getpid(), network::getHost().c_str(), XMLRPCManager::instance()->getServerPort(), ConnectionManager::instance()->getTCPPort(), file_log::getLogFilename().c_str(), Time::useSystemTime() ? "real" : "sim");
}
}
}
}
// If we received a shutdown request while initializing, wait until we've shutdown to continue
if (g_shutting_down)
{
boost::mutex::scoped_lock lock(g_shutting_down_mutex);
}
}
void init(const M_string& remappings, const std::string& name, uint32_t options)
{
if (!g_atexit_registered)
{
g_atexit_registered = true;
atexit(atexitCallback);
}
if (!g_initialized)
{
g_init_options = options;
g_ok = true;
ROSCONSOLE_AUTOINIT;
ros::Time::init();
network::init(remappings);
master::init(remappings);
// names:: namespace is initialized by this_node
this_node::init(name, remappings, options);
param::init(remappings);
file_log::init(remappings);
g_initialized = true;
}
}
void init(int& argc, char** argv, const std::string& name, uint32_t options)
{
M_string remappings;
int full_argc = argc;
// now, move the remapping argv's to the end, and decrement argc as needed
for (int i = 0; i < argc; )
{
std::string arg = argv[i];
size_t pos = arg.find(":=");
if (pos != std::string::npos)
{
std::string local_name = arg.substr(0, pos);
std::string external_name = arg.substr(pos + 2);
remappings[local_name] = external_name;
// shuffle everybody down and stuff this guy at the end of argv
char *tmp = argv[i];
for (int j = i; j < full_argc - 1; j++)
argv[j] = argv[j+1];
argv[argc-1] = tmp;
argc--;
}
else
{
i++; // move on, since we didn't shuffle anybody here to replace it
}
}
init(remappings, name, options);
}
void init(const VP_string& remappings, const std::string& name, uint32_t options)
{
M_string remappings_map;
VP_string::const_iterator it = remappings.begin();
VP_string::const_iterator end = remappings.end();
for (; it != end; ++it)
{
remappings_map[it->first] = it->second;
}
init(remappings_map, name, options);
}
void spin()
{
SingleThreadedSpinner s;
spin(s);
}
void spin(Spinner& s)
{
s.spin();
}
void spinOnce()
{
g_global_queue.callAvailable(ros::WallDuration());
}
CallbackQueue* getGlobalCallbackQueue()
{
return &g_global_queue;
}
bool ok()
{
return g_ok;
}
void shutdown()
{
boost::mutex::scoped_lock lock(g_shutting_down_mutex);
if (g_shutting_down)
{
return;
}
g_shutting_down = true;
g_global_queue.disable();
g_global_queue.clear();
getGlobalCallbackQueue()->disable();
getGlobalCallbackQueue()->clear();
if (g_internal_queue_thread.get_id() != boost::this_thread::get_id())
{
g_internal_queue_thread.join();
ROS_DEBUG("internal callback queue thread shut down");
}
const log4cxx::LoggerPtr& logger = log4cxx::Logger::getLogger(ROSCONSOLE_ROOT_LOGGER_NAME);
logger->removeAppender(g_rosout_appender);
g_rosout_appender = 0;
if (g_started)
{
XMLRPCManager::instance()->shutdown();
TopicManager::instance()->shutdown();
ServiceManager::instance()->shutdown();
ConnectionManager::instance()->shutdown();
PollManager::instance()->shutdown();
}
g_started = false;
g_ok = false;
Time::shutdown();
}
}
<|endoftext|> |
<commit_before>/***************************************************************************//**
* context.cpp
*
* The main root structure of cmgui.
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cmgui.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "zinc/fieldgroup.h"
#include "zinc/graphicsmodule.h"
#include "context/context.h"
#include "curve/curve.h"
#include "general/debug.h"
#include "general/mystring.h"
#include "general/object.h"
#include "graphics/scene_viewer.h"
#include "graphics/graphics_module.h"
#include "graphics/rendition.h"
#include "selection/any_object_selection.h"
#include "region/cmiss_region.h"
#include "time/time_keeper.h"
//-- #include "user_interface/event_dispatcher.h"
/* following is temporary until circular references are removed for Cmiss_region */
#include "region/cmiss_region_private.h"
struct Context *Cmiss_context_create(const char *id)
{
struct Context *context = NULL;
if (ALLOCATE(context, struct Context, 1))
{
context->graphics_module = NULL;
context->root_region = NULL;
context->id = duplicate_string(id);
context->any_object_selection = NULL;
context->element_point_ranges_selection = NULL;
context->scene_viewer_package = NULL;
context->io_stream_package = NULL;
context->curve_manager = NULL;
context->time_keeper = 0;
context->access_count = 1;
}
return context;
}
int Cmiss_context_destroy(struct Context **context_address)
{
int return_code = 0;
struct Context *context = NULL;
if (context_address && NULL != (context = *context_address))
{
context->access_count--;
if (0 == context->access_count)
{
if (context->id)
DEALLOCATE(context->id);
if (context->graphics_module)
Cmiss_graphics_module_destroy(&context->graphics_module);
if (context->root_region)
{
/* need the following due to circular references where field owned by region references region itself;
* when following removed also remove #include "region/cmiss_region_private.h". Also rendition
* has a computed_field manager callback so it must be deleted before detaching fields hierarchical */
Cmiss_region_detach_fields_hierarchical(context->root_region);
DEACCESS(Cmiss_region)(&context->root_region);
}
if (context->scene_viewer_package)
{
Cmiss_scene_viewer_package_destroy(&context->scene_viewer_package);
}
if (context->any_object_selection)
{
DESTROY(Any_object_selection)(&context->any_object_selection);
}
if (context->element_point_ranges_selection)
{
DESTROY(Element_point_ranges_selection)(&context->element_point_ranges_selection);
}
if (context->curve_manager)
{
DESTROY(MANAGER(Curve))(&context->curve_manager);
}
if (context->io_stream_package)
{
DESTROY(IO_stream_package)(&context->io_stream_package);
}
if (context->time_keeper)
{
Cmiss_time_keeper_destroy(&context->time_keeper);
}
DEALLOCATE(*context_address);
}
*context_address = NULL;
return_code = 1;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_destroy. Missing context address");
return_code = 0;
}
/* Write out any memory blocks still ALLOCATED when MEMORY_CHECKING is
on. When MEMORY_CHECKING is off this function does nothing */
list_memory(/*count_number*/0, /*show_pointers*/0, /*increment_counter*/0,
/*show_structures*/1);
return return_code;
}
struct Context *Cmiss_context_access(struct Context *context)
{
if (context)
{
context->access_count++;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_access. Missing context");
}
return context;
}
struct Cmiss_region *Cmiss_context_get_default_region(struct Context *context)
{
struct Cmiss_region *root_region = 0;
if (context)
{
if (!context->root_region)
{
context->root_region = Cmiss_region_create_internal();
}
root_region = ACCESS(Cmiss_region)(context->root_region);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_region. Missing context");
}
return root_region;
}
struct Cmiss_graphics_module *Cmiss_context_get_default_graphics_module(struct Context *context)
{
struct Cmiss_graphics_module *graphics_module = 0;
if (context)
{
if (!context->graphics_module)
{
context->graphics_module = Cmiss_graphics_module_create(context);
}
graphics_module = Cmiss_graphics_module_access(context->graphics_module);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_graphics_module. Missing context");
}
return graphics_module;
}
struct Cmiss_region *Cmiss_context_create_region(struct Context *context)
{
Cmiss_region *region = NULL;
if (context)
{
// all regions share the element shapes and bases from the default_region
if (!context->root_region)
{
Cmiss_region *default_region = Cmiss_context_get_default_region(context);
Cmiss_region_destroy(&default_region);
}
region = Cmiss_region_create_region(context->root_region);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_create_region. Missing context");
}
return region;
}
struct Any_object_selection *Cmiss_context_get_any_object_selection(
struct Context *context)
{
struct Any_object_selection *any_object_selection = NULL;
if (context)
{
if (!context->any_object_selection)
{
context->any_object_selection = CREATE(Any_object_selection)();
}
any_object_selection = context->any_object_selection;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_any_object_selection. Missing context.");
}
return any_object_selection;
}
struct Element_point_ranges_selection *Cmiss_context_get_element_point_ranges_selection(
struct Context *context)
{
struct Element_point_ranges_selection *element_point_ranges_selection = NULL;
if (context)
{
if (!context->element_point_ranges_selection)
{
context->element_point_ranges_selection = CREATE(Element_point_ranges_selection)();
}
element_point_ranges_selection = context->element_point_ranges_selection;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_element_point_ranges_selection. Missing context.");
}
return element_point_ranges_selection;
}
struct IO_stream_package *Cmiss_context_get_default_IO_stream_package(
struct Context *context)
{
struct IO_stream_package *io_stream_package = NULL;
if (context)
{
if (!context->io_stream_package)
{
context->io_stream_package = CREATE(IO_stream_package)();
}
io_stream_package = context->io_stream_package;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_IO_stream_package. Missing context.");
}
return io_stream_package;
}
Cmiss_time_keeper_id Cmiss_context_get_default_time_keeper(Cmiss_context_id context)
{
Cmiss_time_keeper_id time_keeper = 0;
if (context)
{
if (!context->time_keeper)
{
context->time_keeper = CREATE(Time_keeper)("default", 0);
}
time_keeper = context->time_keeper;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_time_keeper. Missing context.");
}
return time_keeper;
}
Cmiss_scene_viewer_package_id Cmiss_context_get_default_scene_viewer_package(
Cmiss_context_id context)
{
Cmiss_scene_viewer_package *scene_viewer_package = NULL;
if (context)
{
if (!context->scene_viewer_package)
{
Cmiss_graphics_module_id graphics_module = Cmiss_context_get_default_graphics_module(context);
if (graphics_module)
{
struct Light *default_light =
Cmiss_graphics_module_get_default_light(graphics_module);
struct Light_model *default_light_model =
Cmiss_graphics_module_get_default_light_model(graphics_module);
struct Scene *default_scene =
Cmiss_graphics_module_get_default_scene(graphics_module);
Colour default_background_colour;
default_background_colour.red = 0.0;
default_background_colour.green = 0.0;
default_background_colour.blue = 0.0;
context->scene_viewer_package = CREATE(Cmiss_scene_viewer_package)
(&default_background_colour,
/* interactive_tool_manager */0,
Cmiss_graphics_module_get_light_manager(graphics_module), default_light,
Cmiss_graphics_module_get_light_model_manager(graphics_module), default_light_model,
Cmiss_graphics_module_get_scene_manager(graphics_module), default_scene);
DEACCESS(Light_model)(&default_light_model);
DEACCESS(Light)(&default_light);
Cmiss_scene_destroy(&default_scene);
}
}
scene_viewer_package = Cmiss_scene_viewer_package_access(context->scene_viewer_package);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_scene_viewer_package. "
"Missing context");
}
return scene_viewer_package;
}
struct MANAGER(Curve) *Cmiss_context_get_default_curve_manager(
Cmiss_context_id context)
{
MANAGER(Curve) *curve_manager = NULL;
if (context)
{
if (!context->curve_manager)
{
context->curve_manager = CREATE(MANAGER(Curve))();
}
curve_manager = context->curve_manager;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_curve_manager. "
"Missing context");
}
return curve_manager;
}
<commit_msg>Adding access to returned time_keeper in Cmiss_context_get_default_time_keeper. https://tracker.physiomeproject.org/show_bug.cgi?id=3528<commit_after>/***************************************************************************//**
* context.cpp
*
* The main root structure of cmgui.
*/
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is cmgui.
*
* The Initial Developer of the Original Code is
* Auckland Uniservices Ltd, Auckland, New Zealand.
* Portions created by the Initial Developer are Copyright (C) 2005
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "zinc/fieldgroup.h"
#include "zinc/graphicsmodule.h"
#include "context/context.h"
#include "curve/curve.h"
#include "general/debug.h"
#include "general/mystring.h"
#include "general/object.h"
#include "graphics/scene_viewer.h"
#include "graphics/graphics_module.h"
#include "graphics/rendition.h"
#include "selection/any_object_selection.h"
#include "region/cmiss_region.h"
#include "time/time_keeper.h"
//-- #include "user_interface/event_dispatcher.h"
/* following is temporary until circular references are removed for Cmiss_region */
#include "region/cmiss_region_private.h"
struct Context *Cmiss_context_create(const char *id)
{
struct Context *context = NULL;
if (ALLOCATE(context, struct Context, 1))
{
context->graphics_module = NULL;
context->root_region = NULL;
context->id = duplicate_string(id);
context->any_object_selection = NULL;
context->element_point_ranges_selection = NULL;
context->scene_viewer_package = NULL;
context->io_stream_package = NULL;
context->curve_manager = NULL;
context->time_keeper = 0;
context->access_count = 1;
}
return context;
}
int Cmiss_context_destroy(struct Context **context_address)
{
int return_code = 0;
struct Context *context = NULL;
if (context_address && NULL != (context = *context_address))
{
context->access_count--;
if (0 == context->access_count)
{
if (context->id)
DEALLOCATE(context->id);
if (context->graphics_module)
Cmiss_graphics_module_destroy(&context->graphics_module);
if (context->root_region)
{
/* need the following due to circular references where field owned by region references region itself;
* when following removed also remove #include "region/cmiss_region_private.h". Also rendition
* has a computed_field manager callback so it must be deleted before detaching fields hierarchical */
Cmiss_region_detach_fields_hierarchical(context->root_region);
DEACCESS(Cmiss_region)(&context->root_region);
}
if (context->scene_viewer_package)
{
Cmiss_scene_viewer_package_destroy(&context->scene_viewer_package);
}
if (context->any_object_selection)
{
DESTROY(Any_object_selection)(&context->any_object_selection);
}
if (context->element_point_ranges_selection)
{
DESTROY(Element_point_ranges_selection)(&context->element_point_ranges_selection);
}
if (context->curve_manager)
{
DESTROY(MANAGER(Curve))(&context->curve_manager);
}
if (context->io_stream_package)
{
DESTROY(IO_stream_package)(&context->io_stream_package);
}
if (context->time_keeper)
{
Cmiss_time_keeper_destroy(&context->time_keeper);
}
DEALLOCATE(*context_address);
}
*context_address = NULL;
return_code = 1;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_destroy. Missing context address");
return_code = 0;
}
/* Write out any memory blocks still ALLOCATED when MEMORY_CHECKING is
on. When MEMORY_CHECKING is off this function does nothing */
list_memory(/*count_number*/0, /*show_pointers*/0, /*increment_counter*/0,
/*show_structures*/1);
return return_code;
}
struct Context *Cmiss_context_access(struct Context *context)
{
if (context)
{
context->access_count++;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_access. Missing context");
}
return context;
}
struct Cmiss_region *Cmiss_context_get_default_region(struct Context *context)
{
struct Cmiss_region *root_region = 0;
if (context)
{
if (!context->root_region)
{
context->root_region = Cmiss_region_create_internal();
}
root_region = ACCESS(Cmiss_region)(context->root_region);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_region. Missing context");
}
return root_region;
}
struct Cmiss_graphics_module *Cmiss_context_get_default_graphics_module(struct Context *context)
{
struct Cmiss_graphics_module *graphics_module = 0;
if (context)
{
if (!context->graphics_module)
{
context->graphics_module = Cmiss_graphics_module_create(context);
}
graphics_module = Cmiss_graphics_module_access(context->graphics_module);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_graphics_module. Missing context");
}
return graphics_module;
}
struct Cmiss_region *Cmiss_context_create_region(struct Context *context)
{
Cmiss_region *region = NULL;
if (context)
{
// all regions share the element shapes and bases from the default_region
if (!context->root_region)
{
Cmiss_region *default_region = Cmiss_context_get_default_region(context);
Cmiss_region_destroy(&default_region);
}
region = Cmiss_region_create_region(context->root_region);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_create_region. Missing context");
}
return region;
}
struct Any_object_selection *Cmiss_context_get_any_object_selection(
struct Context *context)
{
struct Any_object_selection *any_object_selection = NULL;
if (context)
{
if (!context->any_object_selection)
{
context->any_object_selection = CREATE(Any_object_selection)();
}
any_object_selection = context->any_object_selection;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_any_object_selection. Missing context.");
}
return any_object_selection;
}
struct Element_point_ranges_selection *Cmiss_context_get_element_point_ranges_selection(
struct Context *context)
{
struct Element_point_ranges_selection *element_point_ranges_selection = NULL;
if (context)
{
if (!context->element_point_ranges_selection)
{
context->element_point_ranges_selection = CREATE(Element_point_ranges_selection)();
}
element_point_ranges_selection = context->element_point_ranges_selection;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_element_point_ranges_selection. Missing context.");
}
return element_point_ranges_selection;
}
struct IO_stream_package *Cmiss_context_get_default_IO_stream_package(
struct Context *context)
{
struct IO_stream_package *io_stream_package = NULL;
if (context)
{
if (!context->io_stream_package)
{
context->io_stream_package = CREATE(IO_stream_package)();
}
io_stream_package = context->io_stream_package;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_IO_stream_package. Missing context.");
}
return io_stream_package;
}
Cmiss_time_keeper_id Cmiss_context_get_default_time_keeper(Cmiss_context_id context)
{
Cmiss_time_keeper_id time_keeper = 0;
if (context)
{
if (!context->time_keeper)
{
context->time_keeper = CREATE(Time_keeper)("default", 0);
}
time_keeper = Cmiss_time_keeper_access(context->time_keeper);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_time_keeper. Missing context.");
}
return time_keeper;
}
Cmiss_scene_viewer_package_id Cmiss_context_get_default_scene_viewer_package(
Cmiss_context_id context)
{
Cmiss_scene_viewer_package *scene_viewer_package = NULL;
if (context)
{
if (!context->scene_viewer_package)
{
Cmiss_graphics_module_id graphics_module = Cmiss_context_get_default_graphics_module(context);
if (graphics_module)
{
struct Light *default_light =
Cmiss_graphics_module_get_default_light(graphics_module);
struct Light_model *default_light_model =
Cmiss_graphics_module_get_default_light_model(graphics_module);
struct Scene *default_scene =
Cmiss_graphics_module_get_default_scene(graphics_module);
Colour default_background_colour;
default_background_colour.red = 0.0;
default_background_colour.green = 0.0;
default_background_colour.blue = 0.0;
context->scene_viewer_package = CREATE(Cmiss_scene_viewer_package)
(&default_background_colour,
/* interactive_tool_manager */0,
Cmiss_graphics_module_get_light_manager(graphics_module), default_light,
Cmiss_graphics_module_get_light_model_manager(graphics_module), default_light_model,
Cmiss_graphics_module_get_scene_manager(graphics_module), default_scene);
DEACCESS(Light_model)(&default_light_model);
DEACCESS(Light)(&default_light);
Cmiss_scene_destroy(&default_scene);
}
}
scene_viewer_package = Cmiss_scene_viewer_package_access(context->scene_viewer_package);
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_scene_viewer_package. "
"Missing context");
}
return scene_viewer_package;
}
struct MANAGER(Curve) *Cmiss_context_get_default_curve_manager(
Cmiss_context_id context)
{
MANAGER(Curve) *curve_manager = NULL;
if (context)
{
if (!context->curve_manager)
{
context->curve_manager = CREATE(MANAGER(Curve))();
}
curve_manager = context->curve_manager;
}
else
{
display_message(ERROR_MESSAGE,
"Cmiss_context_get_default_curve_manager. "
"Missing context");
}
return curve_manager;
}
<|endoftext|> |
<commit_before>// @(#)root/thread:$Id$
// Authors: Enric Tejedor CERN 12/09/2016
// Philippe Canal FNAL 12/09/2016
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TRWSpinLock
\brief An implementation of a read-write lock with an internal spin lock.
This class provides an implementation of a read-write lock that uses an
internal spin lock and a condition variable to synchronize readers and
writers when necessary.
The implementation tries to make faster the scenario when readers come
and go but there is no writer. In that case, readers will not pay the
price of taking the internal spin lock.
Moreover, this RW lock tries to be fair with writers, giving them the
possibility to claim the lock and wait for only the remaining readers,
thus preventing starvation.
*/
#include "TRWSpinLock.h"
using namespace ROOT;
////////////////////////////////////////////////////////////////////////////
/// Acquire the lock in read mode.
void TRWSpinLock::ReadLock()
{
++fReaderReservation;
if (!fWriter) {
// There is no writer, go freely to the critical section
++fReaders;
--fReaderReservation;
} else {
// A writer claimed the RW lock, we will need to wait on the
// internal lock
--fReaderReservation;
std::unique_lock<ROOT::TSpinMutex> lock(fMutex);
// Wait for writers, if any
fCond.wait(lock, [this]{ return !fWriter; });
// This RW lock now belongs to the readers
++fReaders;
lock.unlock();
}
}
//////////////////////////////////////////////////////////////////////////
/// Release the lock in read mode.
void TRWSpinLock::ReadUnLock()
{
--fReaders;
if (fWriterReservation && fReaders == 0) {
// We still need to lock here to prevent interleaving with a writer
std::lock_guard<ROOT::TSpinMutex> lock(fMutex);
// Make sure you wake up a writer, if any
// Note: spurrious wakeups are okay, fReaders
// will be checked again in WriteLock
fCond.notify_all();
}
}
//////////////////////////////////////////////////////////////////////////
/// Acquire the lock in write mode.
void TRWSpinLock::WriteLock()
{
++fWriterReservation;
std::unique_lock<ROOT::TSpinMutex> lock(fMutex);
// Wait for other writers, if any
fCond.wait(lock, [this]{ return !fWriter; });
// Claim the lock for this writer
fWriter = true;
// Wait until all reader reservations finish
while(fReaderReservation) {};
// Wait for remaining readers
fCond.wait(lock, [this]{ return fReaders == 0; });
--fWriterReservation;
lock.unlock();
}
//////////////////////////////////////////////////////////////////////////
/// Release the lock in write mode.
void TRWSpinLock::WriteUnLock()
{
// We need to lock here to prevent interleaving with a reader
std::lock_guard<ROOT::TSpinMutex> lock(fMutex);
fWriter = false;
// Notify all potential readers/writers that are waiting
fCond.notify_all();
}
<commit_msg>Get TRWSpinLock header from the ROOT subdir<commit_after>// @(#)root/thread:$Id$
// Authors: Enric Tejedor CERN 12/09/2016
// Philippe Canal FNAL 12/09/2016
/*************************************************************************
* Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/** \class TRWSpinLock
\brief An implementation of a read-write lock with an internal spin lock.
This class provides an implementation of a read-write lock that uses an
internal spin lock and a condition variable to synchronize readers and
writers when necessary.
The implementation tries to make faster the scenario when readers come
and go but there is no writer. In that case, readers will not pay the
price of taking the internal spin lock.
Moreover, this RW lock tries to be fair with writers, giving them the
possibility to claim the lock and wait for only the remaining readers,
thus preventing starvation.
*/
#include "ROOT/TRWSpinLock.h"
using namespace ROOT;
////////////////////////////////////////////////////////////////////////////
/// Acquire the lock in read mode.
void TRWSpinLock::ReadLock()
{
++fReaderReservation;
if (!fWriter) {
// There is no writer, go freely to the critical section
++fReaders;
--fReaderReservation;
} else {
// A writer claimed the RW lock, we will need to wait on the
// internal lock
--fReaderReservation;
std::unique_lock<ROOT::TSpinMutex> lock(fMutex);
// Wait for writers, if any
fCond.wait(lock, [this]{ return !fWriter; });
// This RW lock now belongs to the readers
++fReaders;
lock.unlock();
}
}
//////////////////////////////////////////////////////////////////////////
/// Release the lock in read mode.
void TRWSpinLock::ReadUnLock()
{
--fReaders;
if (fWriterReservation && fReaders == 0) {
// We still need to lock here to prevent interleaving with a writer
std::lock_guard<ROOT::TSpinMutex> lock(fMutex);
// Make sure you wake up a writer, if any
// Note: spurrious wakeups are okay, fReaders
// will be checked again in WriteLock
fCond.notify_all();
}
}
//////////////////////////////////////////////////////////////////////////
/// Acquire the lock in write mode.
void TRWSpinLock::WriteLock()
{
++fWriterReservation;
std::unique_lock<ROOT::TSpinMutex> lock(fMutex);
// Wait for other writers, if any
fCond.wait(lock, [this]{ return !fWriter; });
// Claim the lock for this writer
fWriter = true;
// Wait until all reader reservations finish
while(fReaderReservation) {};
// Wait for remaining readers
fCond.wait(lock, [this]{ return fReaders == 0; });
--fWriterReservation;
lock.unlock();
}
//////////////////////////////////////////////////////////////////////////
/// Release the lock in write mode.
void TRWSpinLock::WriteUnLock()
{
// We need to lock here to prevent interleaving with a reader
std::lock_guard<ROOT::TSpinMutex> lock(fMutex);
fWriter = false;
// Notify all potential readers/writers that are waiting
fCond.notify_all();
}
<|endoftext|> |
<commit_before>// Copyright 2016 Samuel Austin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Windows.h>
// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>
// Generated JSON header file
#include "com_samaust_trackerv2_osvr_json.h"
// Standard includes
#include <iostream>
#include <cmath>
#include "trackir.h"
#define DEGTORADDIV2 0.00872664625997165
trackir::trackir(OSVR_PluginRegContext ctx, CameraLibrary::Camera *camera)
{
std::cout << "[TrackerV2-OSVR] Initializing TrackIR..." << std::endl;
m_camera = camera;
// Set Video Mode
// TrackIR 4 only supports segment mode
// TrackIR 5 supports segment mode, Interleaved grayscale mode - non-realtime and Bit Packed Precision mode
m_camera->SetVideoType(Core::SegmentMode);
// Start camera output
m_camera->Start();
// CameraLibrary objects
m_vec = CameraLibrary::cModuleVector::Create(); //new cModuleVector();
m_vecprocessor = new CameraLibrary::cModuleVectorProcessing();
CameraLibrary::cVectorProcessingSettings vectorProcessorSettings;
CameraLibrary::cVectorSettings vectorSettings;
// Get Vector arrangement from settings (currently hardcoded to TrackClipPro)
//CameraLibrary::cVectorSettings::Arrangements selectedArrangement = CameraLibrary::cVectorSettings::VectorClip;
CameraLibrary::cVectorSettings::Arrangements selectedArrangement = CameraLibrary::cVectorSettings::TrackClipPro;
// Configure vectorProcessorSettings
vectorProcessorSettings = *m_vecprocessor->Settings();
vectorProcessorSettings.Arrangement = selectedArrangement;
vectorProcessorSettings.ShowPivotPoint = false;
vectorProcessorSettings.ShowProcessed = false;
m_vecprocessor->SetSettings(vectorProcessorSettings);
// Get camera lens distortion
m_camera->GetDistortionModel(m_lensDistortion);
// Configure vector settings
vectorSettings = *m_vec->Settings();
vectorSettings.Arrangement = selectedArrangement;
vectorSettings.Enabled = true;
// Plug in focal length in (mm) by converting it from pixels -> mm
vectorSettings.ImagerFocalLength = (m_lensDistortion.HorizontalFocalLength / ((float)m_camera->PhysicalPixelWidth()))*m_camera->ImagerWidth();
vectorSettings.ImagerHeight = m_camera->ImagerHeight();
vectorSettings.ImagerWidth = m_camera->ImagerWidth();
vectorSettings.PrincipalX = m_camera->PhysicalPixelWidth() / 2;
vectorSettings.PrincipalY = m_camera->PhysicalPixelHeight() / 2;
vectorSettings.PixelWidth = m_camera->PhysicalPixelWidth();
vectorSettings.PixelHeight = m_camera->PhysicalPixelHeight();
m_vec->SetSettings(vectorSettings);
// Turn off TrackIR illumination LEDs (not necessary for TrackClip PRO)
m_camera->SetLED(CameraLibrary::eStatusLEDs::IlluminationLED, false);
std::cout << "[TrackerV2-OSVR] TrackIR initialized" << std::endl;
// Create the initialization options
OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);
// configure our tracker
osvrDeviceTrackerConfigure(opts, &m_tracker);
// Create the device token with the options
m_dev.initAsync(ctx, "Tracker", opts);
// Send JSON descriptor
m_dev.sendJsonDescriptor(com_samaust_trackerv2_osvr_json);
// Register update callback
m_dev.registerUpdateCallback(this);
}
trackir::~trackir(void)
{
// Release camera
m_camera->Release();
// Shutdown Camera Library
CameraLibrary::CameraManager::X().Shutdown();
}
OSVR_ReturnCode trackir::update() {
// Fetch a new frame from the camera
CameraLibrary::Frame *frame = m_camera->GetFrame();
if (frame)
{
m_vec->BeginFrame();
for (int i = 0; i<frame->ObjectCount(); i++)
{
CameraLibrary::cObject *obj = frame->Object(i);
float x = obj->X();
float y = obj->Y();
Core::Undistort2DPoint(m_lensDistortion, x, y);
m_vec->PushMarkerData(x, y, obj->Area(), obj->Width(), obj->Height());
}
m_vec->Calculate();
m_vecprocessor->PushData(m_vec);
// Recenter if CTRL + F12 is pressed
if (GetAsyncKeyState(VK_CONTROL) & 0x8000)
{
if (GetAsyncKeyState(VK_F12) & 0x8000)
m_vecprocessor->Recenter();
}
// Get position and orientation
m_vecprocessor->GetPosition(m_x, m_y, m_z);
m_vecprocessor->GetOrientation(m_yaw, m_pitch, m_roll);
// Release frame
frame->Release();
}
// Euler to quaternion
// Source : http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/
double c1 = cos(m_yaw * DEGTORADDIV2);
double s1 = sin(m_yaw * DEGTORADDIV2);
double c2 = cos(m_pitch * DEGTORADDIV2);
double s2 = sin(m_pitch * DEGTORADDIV2);
double c3 = cos(-m_roll * DEGTORADDIV2);
double s3 = sin(-m_roll * DEGTORADDIV2);
double c1c2 = c1*c2;
double s1s2 = s1*s2;
// Report pose
OSVR_Pose3 pose;
pose.translation.data[0] = m_x;
pose.translation.data[1] = m_y;
pose.translation.data[2] = m_z;
pose.rotation.data[0] = c1c2*c3 - s1s2*s3;
pose.rotation.data[1] = c1c2*s3 + s1s2*c3;
pose.rotation.data[2] = s1*c2*c3 + c1*s2*s3;
pose.rotation.data[3] = c1*s2*c3 - s1*c2*s3;
osvrDeviceTrackerSendPose(m_dev, m_tracker, &pose, 0);
return OSVR_RETURN_SUCCESS;
}
<commit_msg>Turn on green LED if three or more targets are detected by the camera<commit_after>// Copyright 2016 Samuel Austin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http ://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <Windows.h>
// Internal Includes
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/PluginKit/TrackerInterfaceC.h>
// Generated JSON header file
#include "com_samaust_trackerv2_osvr_json.h"
// Standard includes
#include <iostream>
#include <cmath>
#include "trackir.h"
#define DEGTORADDIV2 0.00872664625997165
trackir::trackir(OSVR_PluginRegContext ctx, CameraLibrary::Camera *camera)
{
std::cout << "[TrackerV2-OSVR] Initializing TrackIR..." << std::endl;
m_camera = camera;
// Set Video Mode
// TrackIR 4 only supports segment mode
// TrackIR 5 supports segment mode, Interleaved grayscale mode - non-realtime and Bit Packed Precision mode
m_camera->SetVideoType(Core::SegmentMode);
// Start camera output
m_camera->Start();
// CameraLibrary objects
m_vec = CameraLibrary::cModuleVector::Create(); //new cModuleVector();
m_vecprocessor = new CameraLibrary::cModuleVectorProcessing();
CameraLibrary::cVectorProcessingSettings vectorProcessorSettings;
CameraLibrary::cVectorSettings vectorSettings;
// Get Vector arrangement from settings (currently hardcoded to TrackClipPro)
//CameraLibrary::cVectorSettings::Arrangements selectedArrangement = CameraLibrary::cVectorSettings::VectorClip;
CameraLibrary::cVectorSettings::Arrangements selectedArrangement = CameraLibrary::cVectorSettings::TrackClipPro;
// Configure vectorProcessorSettings
vectorProcessorSettings = *m_vecprocessor->Settings();
vectorProcessorSettings.Arrangement = selectedArrangement;
vectorProcessorSettings.ShowPivotPoint = false;
vectorProcessorSettings.ShowProcessed = false;
m_vecprocessor->SetSettings(vectorProcessorSettings);
// Get camera lens distortion
m_camera->GetDistortionModel(m_lensDistortion);
// Configure vector settings
vectorSettings = *m_vec->Settings();
vectorSettings.Arrangement = selectedArrangement;
vectorSettings.Enabled = true;
// Plug in focal length in (mm) by converting it from pixels -> mm
vectorSettings.ImagerFocalLength = (m_lensDistortion.HorizontalFocalLength / ((float)m_camera->PhysicalPixelWidth()))*m_camera->ImagerWidth();
vectorSettings.ImagerHeight = m_camera->ImagerHeight();
vectorSettings.ImagerWidth = m_camera->ImagerWidth();
vectorSettings.PrincipalX = m_camera->PhysicalPixelWidth() / 2;
vectorSettings.PrincipalY = m_camera->PhysicalPixelHeight() / 2;
vectorSettings.PixelWidth = m_camera->PhysicalPixelWidth();
vectorSettings.PixelHeight = m_camera->PhysicalPixelHeight();
m_vec->SetSettings(vectorSettings);
// Turn off TrackIR illumination LEDs (not necessary for TrackClip PRO)
m_camera->SetLED(CameraLibrary::eStatusLEDs::IlluminationLED, false);
std::cout << "[TrackerV2-OSVR] TrackIR initialized" << std::endl;
// Create the initialization options
OSVR_DeviceInitOptions opts = osvrDeviceCreateInitOptions(ctx);
// configure our tracker
osvrDeviceTrackerConfigure(opts, &m_tracker);
// Create the device token with the options
m_dev.initAsync(ctx, "Tracker", opts);
// Send JSON descriptor
m_dev.sendJsonDescriptor(com_samaust_trackerv2_osvr_json);
// Register update callback
m_dev.registerUpdateCallback(this);
}
trackir::~trackir(void)
{
// Release camera
m_camera->Release();
// Shutdown Camera Library
CameraLibrary::CameraManager::X().Shutdown();
}
OSVR_ReturnCode trackir::update() {
// Fetch a new frame from the camera
CameraLibrary::Frame *frame = m_camera->GetFrame();
if (frame)
{
m_vec->BeginFrame();
int frameObjectCount = frame->ObjectCount();
// Light green LED if TracClip PRO is detected
if (frameObjectCount >= 3)
m_camera->SetLED(CameraLibrary::eStatusLEDs::GreenStatusLED, true);
else
m_camera->SetLED(CameraLibrary::eStatusLEDs::GreenStatusLED, false);
for (int i = 0; i<frameObjectCount; i++)
{
CameraLibrary::cObject *obj = frame->Object(i);
float x = obj->X();
float y = obj->Y();
Core::Undistort2DPoint(m_lensDistortion, x, y);
m_vec->PushMarkerData(x, y, obj->Area(), obj->Width(), obj->Height());
}
m_vec->Calculate();
m_vecprocessor->PushData(m_vec);
// Recenter if CTRL + F12 is pressed
if (GetAsyncKeyState(VK_CONTROL) & 0x8000)
{
if (GetAsyncKeyState(VK_F12) & 0x8000)
m_vecprocessor->Recenter();
}
// Get position and orientation
m_vecprocessor->GetPosition(m_x, m_y, m_z);
m_vecprocessor->GetOrientation(m_yaw, m_pitch, m_roll);
// Release frame
frame->Release();
}
// Euler to quaternion
// Source : http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/
double c1 = cos(m_yaw * DEGTORADDIV2);
double s1 = sin(m_yaw * DEGTORADDIV2);
double c2 = cos(m_pitch * DEGTORADDIV2);
double s2 = sin(m_pitch * DEGTORADDIV2);
double c3 = cos(-m_roll * DEGTORADDIV2);
double s3 = sin(-m_roll * DEGTORADDIV2);
double c1c2 = c1*c2;
double s1s2 = s1*s2;
// Report pose
OSVR_Pose3 pose;
pose.translation.data[0] = m_x;
pose.translation.data[1] = m_y;
pose.translation.data[2] = m_z;
pose.rotation.data[0] = c1c2*c3 - s1s2*s3;
pose.rotation.data[1] = c1c2*s3 + s1s2*c3;
pose.rotation.data[2] = s1*c2*c3 + c1*s2*s3;
pose.rotation.data[3] = c1*s2*c3 - s1*c2*s3;
osvrDeviceTrackerSendPose(m_dev, m_tracker, &pose, 0);
return OSVR_RETURN_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "ajokki_callbacks.hpp"
#include "cpp/ylikuutio/callback/callback_parameter.hpp"
#include "cpp/ylikuutio/callback/callback_object.hpp"
#include "cpp/ylikuutio/callback/callback_engine.hpp"
#include "cpp/ylikuutio/common/any_value.hpp"
#include "cpp/ylikuutio/ontology/text2D.hpp"
#include "cpp/ylikuutio/ontology/object.hpp"
#include "cpp/ylikuutio/ontology/species.hpp"
#include "cpp/ylikuutio/ontology/material.hpp"
#include "cpp/ylikuutio/ontology/universe.hpp"
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <vector> // std::vector
namespace ajokki
{
datatypes::AnyValue* glfwTerminate_cleanup(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
glfwTerminate();
return nullptr;
}
datatypes::AnyValue* full_cleanup(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
std::cout << "Cleaning up.\n";
if (input_parameters.size() != 1)
{
std::cerr << "Invalid size of input_parameters: " << input_parameters.size() << ", should be 1.\n";
}
else
{
datatypes::AnyValue* any_value = input_parameters.at(0)->get_any_value();
if (any_value->type == datatypes::VOID_POINTER)
{
delete static_cast<ontology::Universe*>(any_value->void_pointer);
}
else
{
std::cerr << "Invalid datatype: " << any_value->type << ", should be " << datatypes::VOID_POINTER << "\n";
}
}
// Delete the text's VBO, the shader and the texture
text2D::cleanupText2D();
// Close OpenGL window and terminate GLFW
glfwTerminate();
return nullptr;
}
datatypes::AnyValue* delete_suzanne_species(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
datatypes::AnyValue* any_value = input_parameters.at(1)->get_any_value();
if (any_value->type != datatypes::BOOL_POINTER)
{
// `any_value` was not `bool*`.
return nullptr;
}
// OK, `any_value` is a `bool*`.
bool* does_suzanne_species_exist = any_value->bool_pointer;
if (*does_suzanne_species_exist)
{
ontology::Species* species = static_cast<ontology::Species*>(input_parameters.at(0)->get_any_value()->void_pointer);
delete species;
*does_suzanne_species_exist = false;
}
return nullptr;
}
datatypes::AnyValue* switch_to_new_material(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
bool* does_suzanne_species_exist = static_cast<bool*>(input_parameters.at(2)->get_any_value()->void_pointer);
bool* does_suzanne_species_have_original_texture = static_cast<bool*>(input_parameters.at(3)->get_any_value()->void_pointer);
bool* does_suzanne_species_have_new_texture = static_cast<bool*>(input_parameters.at(4)->get_any_value()->void_pointer);
if (*does_suzanne_species_exist && *does_suzanne_species_have_original_texture)
{
ontology::Species* species = static_cast<ontology::Species*>(input_parameters.at(0)->get_any_value()->void_pointer);
ontology::Material* material = static_cast<ontology::Material*>(input_parameters.at(1)->get_any_value()->void_pointer);
species->bind_to_new_parent(material);
*does_suzanne_species_have_original_texture = false;
*does_suzanne_species_have_new_texture = true;
}
return nullptr;
}
datatypes::AnyValue* transform_into_new_species(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
bool* does_suzanne_species_exist = static_cast<bool*>(input_parameters.at(2)->get_any_value()->void_pointer);
bool* does_suzanne_species_belong_to_original_species = static_cast<bool*>(input_parameters.at(3)->get_any_value()->void_pointer);
bool* does_suzanne_species_belong_to_new_species = static_cast<bool*>(input_parameters.at(4)->get_any_value()->void_pointer);
if (*does_suzanne_species_exist && *does_suzanne_species_belong_to_original_species)
{
ontology::Object* object = static_cast<ontology::Object*>(input_parameters.at(0)->get_any_value()->void_pointer);
ontology::Species* species = static_cast<ontology::Species*>(input_parameters.at(1)->get_any_value()->void_pointer);
object->bind_to_new_parent(species);
*does_suzanne_species_belong_to_original_species = false;
*does_suzanne_species_belong_to_new_species = true;
}
return nullptr;
}
}
<commit_msg>Renamed variables.<commit_after>#include "ajokki_callbacks.hpp"
#include "cpp/ylikuutio/callback/callback_parameter.hpp"
#include "cpp/ylikuutio/callback/callback_object.hpp"
#include "cpp/ylikuutio/callback/callback_engine.hpp"
#include "cpp/ylikuutio/common/any_value.hpp"
#include "cpp/ylikuutio/ontology/text2D.hpp"
#include "cpp/ylikuutio/ontology/object.hpp"
#include "cpp/ylikuutio/ontology/species.hpp"
#include "cpp/ylikuutio/ontology/material.hpp"
#include "cpp/ylikuutio/ontology/universe.hpp"
// Include GLFW
#ifndef __GLFW3_H_INCLUDED
#define __GLFW3_H_INCLUDED
#include <glfw3.h>
#endif
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <vector> // std::vector
namespace ajokki
{
datatypes::AnyValue* glfwTerminate_cleanup(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
glfwTerminate();
return nullptr;
}
datatypes::AnyValue* full_cleanup(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
std::cout << "Cleaning up.\n";
if (input_parameters.size() != 1)
{
std::cerr << "Invalid size of input_parameters: " << input_parameters.size() << ", should be 1.\n";
}
else
{
datatypes::AnyValue* any_value_void_pointer = input_parameters.at(0)->get_any_value();
if (any_value_void_pointer->type == datatypes::VOID_POINTER)
{
delete static_cast<ontology::Universe*>(any_value_void_pointer->void_pointer);
}
else
{
std::cerr << "Invalid datatype: " << any_value_void_pointer->type << ", should be " << datatypes::VOID_POINTER << "\n";
}
}
// Delete the text's VBO, the shader and the texture
text2D::cleanupText2D();
// Close OpenGL window and terminate GLFW
glfwTerminate();
return nullptr;
}
datatypes::AnyValue* delete_suzanne_species(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
datatypes::AnyValue* any_value_bool_pointer = input_parameters.at(1)->get_any_value();
if (any_value_bool_pointer->type != datatypes::BOOL_POINTER)
{
// `any_value_bool_pointer` was not `bool*`.
return nullptr;
}
// OK, `any_value_bool_pointer` is a `bool*`.
bool* does_suzanne_species_exist = any_value_bool_pointer->bool_pointer;
if (*does_suzanne_species_exist)
{
ontology::Species* species = static_cast<ontology::Species*>(input_parameters.at(0)->get_any_value()->void_pointer);
delete species;
*does_suzanne_species_exist = false;
}
return nullptr;
}
datatypes::AnyValue* switch_to_new_material(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
bool* does_suzanne_species_exist = static_cast<bool*>(input_parameters.at(2)->get_any_value()->void_pointer);
bool* does_suzanne_species_have_original_texture = static_cast<bool*>(input_parameters.at(3)->get_any_value()->void_pointer);
bool* does_suzanne_species_have_new_texture = static_cast<bool*>(input_parameters.at(4)->get_any_value()->void_pointer);
if (*does_suzanne_species_exist && *does_suzanne_species_have_original_texture)
{
ontology::Species* species = static_cast<ontology::Species*>(input_parameters.at(0)->get_any_value()->void_pointer);
ontology::Material* material = static_cast<ontology::Material*>(input_parameters.at(1)->get_any_value()->void_pointer);
species->bind_to_new_parent(material);
*does_suzanne_species_have_original_texture = false;
*does_suzanne_species_have_new_texture = true;
}
return nullptr;
}
datatypes::AnyValue* transform_into_new_species(
callback_system::CallbackEngine*,
callback_system::CallbackObject*,
std::vector<callback_system::CallbackParameter*> input_parameters)
{
bool* does_suzanne_species_exist = static_cast<bool*>(input_parameters.at(2)->get_any_value()->void_pointer);
bool* does_suzanne_species_belong_to_original_species = static_cast<bool*>(input_parameters.at(3)->get_any_value()->void_pointer);
bool* does_suzanne_species_belong_to_new_species = static_cast<bool*>(input_parameters.at(4)->get_any_value()->void_pointer);
if (*does_suzanne_species_exist && *does_suzanne_species_belong_to_original_species)
{
ontology::Object* object = static_cast<ontology::Object*>(input_parameters.at(0)->get_any_value()->void_pointer);
ontology::Species* species = static_cast<ontology::Species*>(input_parameters.at(1)->get_any_value()->void_pointer);
object->bind_to_new_parent(species);
*does_suzanne_species_belong_to_original_species = false;
*does_suzanne_species_belong_to_new_species = true;
}
return nullptr;
}
}
<|endoftext|> |
<commit_before>#ifndef FMO_RETAINER_HPP
#define FMO_RETAINER_HPP
#include <array>
#include <vector>
namespace fmo {
/// A container for objects of type T, which must be default constructible and also must have a
/// method named clear() which reverts the object to a state equivalent to that after default
/// construction.
///
/// The first Count elements are never destroyed, clear() is called on them instead.
template <typename T, size_t Count>
struct Retainer {
Retainer() = default;
Retainer(const Retainer&) = default;
Retainer(Retainer&&) = default;
Retainer& operator=(const Retainer&) = default;
Retainer& operator=(Retainer&&) = default;
void swap(Retainer& rhs) {
std::swap(mSz, rhs.mSz);
mArr.swap(rhs.mArr);
mVec.swap(rhs.mVec);
}
friend void swap(Retainer& lhs, Retainer& rhs) { lhs.swap(rhs); }
bool empty() const { return mSz == 0; }
size_t size() const { return mSz; }
void emplace_back() {
if (++mSz > Count) { mVec.emplace_back(); }
}
void pop_back() {
if (mSz-- > Count) {
mVec.pop_back();
} else {
mArr[mSz].clear();
}
}
T& back() {
if (mSz > Count) return mVec.back();
return mArr[mSz - 1];
}
const T& back() const {
if (mSz > Count) return mVec.back();
return mArr[mSz - 1];
}
void clear() {
if (mSz > Count) {
mVec.clear();
mSz = Count;
}
while (!empty()) pop_back();
}
private:
std::array<T, Count> mArr;
std::vector<T> mVec;
size_t mSz = 0;
};
}
#endif // FMO_RETAINER_HPP
<commit_msg>Keep the data order in swap()<commit_after>#ifndef FMO_RETAINER_HPP
#define FMO_RETAINER_HPP
#include <array>
#include <vector>
namespace fmo {
/// A container for objects of type T, which must be default constructible and also must have a
/// method named clear() which reverts the object to a state equivalent to that after default
/// construction.
///
/// The first Count elements are never destroyed, clear() is called on them instead.
template <typename T, size_t Count>
struct Retainer {
Retainer() = default;
Retainer(const Retainer&) = default;
Retainer(Retainer&&) = default;
Retainer& operator=(const Retainer&) = default;
Retainer& operator=(Retainer&&) = default;
void swap(Retainer& rhs) {
mArr.swap(rhs.mArr);
mVec.swap(rhs.mVec);
std::swap(mSz, rhs.mSz);
}
friend void swap(Retainer& lhs, Retainer& rhs) { lhs.swap(rhs); }
bool empty() const { return mSz == 0; }
size_t size() const { return mSz; }
void emplace_back() {
if (++mSz > Count) { mVec.emplace_back(); }
}
void pop_back() {
if (mSz-- > Count) {
mVec.pop_back();
} else {
mArr[mSz].clear();
}
}
T& back() {
if (mSz > Count) return mVec.back();
return mArr[mSz - 1];
}
const T& back() const {
if (mSz > Count) return mVec.back();
return mArr[mSz - 1];
}
void clear() {
if (mSz > Count) {
mVec.clear();
mSz = Count;
}
while (!empty()) pop_back();
}
private:
std::array<T, Count> mArr;
std::vector<T> mVec;
size_t mSz = 0;
};
}
#endif // FMO_RETAINER_HPP
<|endoftext|> |
<commit_before>// Copyright 2017 Global Phasing Ltd.
#ifndef GEMMI_TO_CIF_HPP_
#define GEMMI_TO_CIF_HPP_
#include <fstream>
#include "cifdoc.hpp"
namespace gemmi {
namespace cif {
enum class Style {
Simple,
NoBlankLines,
PreferPairs, // write single-row loops as pairs
Pdbx, // PreferPairs + put '#' (empty comments) between categories
Indent35, // start values in pairs from 35th column
};
// CIF files are read in binary mode. It makes difference only for text fields.
// If the text field with \r\n would be written as is in text mode on Windows
// \r would get duplicated. As a workaround, here we convert \r\n to \n.
// Hopefully \r that gets removed here is never meaningful.
inline void write_text_field(std::ostream& os, const std::string& value) {
for (size_t pos = 0, end = 0; end != std::string::npos; pos = end + 1) {
end = value.find("\r\n", pos);
size_t len = (end == std::string::npos ? value.size() : end) - pos;
os.write(value.c_str() + pos, len);
}
}
inline void write_out_pair(std::ostream& os, const std::string& name,
const std::string& value, Style style) {
os << name;
if (is_text_field(value)) {
os.put('\n');
write_text_field(os, value);
} else {
if (name.size() + value.size() > 120)
os.put('\n');
else if (style == Style::Indent35 && name.size() < 34)
os.write(" ", 34 - name.size());
else
os.put(' ');
os << value;
}
os.put('\n');
}
inline void write_out_loop(std::ostream& os, const Loop& loop, Style style) {
if (loop.values.empty())
return;
if ((style == Style::PreferPairs || style == Style::Pdbx) &&
loop.length() == 1) {
for (size_t i = 0; i != loop.tags.size(); ++i)
write_out_pair(os, loop.tags[i], loop.values[i], style);
return;
}
os << "loop_";
for (const std::string& tag : loop.tags)
os << '\n' << tag;
size_t ncol = loop.tags.size();
size_t col = 0;
for (const std::string& val : loop.values) {
bool text_field = is_text_field(val);
os.put(col++ == 0 || text_field ? '\n' : ' ');
if (text_field)
write_text_field(os, val);
else
os << val;
if (col == ncol)
col = 0;
}
os.put('\n');
}
inline void write_out_item(std::ostream& os, const Item& item, Style style) {
switch (item.type) {
case ItemType::Pair:
write_out_pair(os, item.pair[0], item.pair[1], style);
break;
case ItemType::Loop:
write_out_loop(os, item.loop, style);
break;
case ItemType::Frame:
os << "save_" << item.frame.name << '\n';
for (const Item& inner_item : item.frame.items)
write_out_item(os, inner_item, style);
os << "save_\n";
break;
case ItemType::Comment:
os << item.pair[1] << '\n';
break;
case ItemType::Erased:
break;
}
}
inline bool should_be_separted_(const Item& a, const Item& b) {
if (a.type == ItemType::Comment || b.type == ItemType::Comment)
return false;
if (a.type != ItemType::Pair || b.type != ItemType::Pair)
return true;
// check if we have mmcif-like tags from different categories
auto adot = a.pair[0].find('.');
if (adot == std::string::npos)
return false;
auto bdot = b.pair[0].find('.');
return adot != bdot || a.pair[0].compare(0, adot, b.pair[0], 0, adot) != 0;
}
inline void write_cif_to_stream(std::ostream& os, const Document& doc,
Style s=Style::Simple) {
bool first = true;
for (const Block& block : doc.blocks) {
if (!first)
os.put('\n'); // extra blank line for readability
os << "data_" << block.name << '\n';
if (s == Style::Pdbx)
os << "#\n";
const Item* prev = nullptr;
for (const Item& item : block.items)
if (item.type != ItemType::Erased) {
if (prev && s != Style::NoBlankLines &&
should_be_separted_(*prev, item))
os << (s == Style::Pdbx ? "#\n" : "\n");
write_out_item(os, item, s);
prev = &item;
}
first = false;
if (s == Style::Pdbx)
os << "#\n";
}
}
inline void write_cif_to_file(const Document& doc, const std::string& filename,
Style s=Style::Simple) {
std::ofstream of(filename);
if (!of)
throw std::runtime_error("Failed to open " + filename);
write_cif_to_stream(of, doc, s);
of.close();
}
} // namespace cif
} // namespace gemmi
#endif
<commit_msg>write_cif_to_file(): support non-ascii filenames on Windows (MSVC only)<commit_after>// Copyright 2017 Global Phasing Ltd.
#ifndef GEMMI_TO_CIF_HPP_
#define GEMMI_TO_CIF_HPP_
#include <fstream>
#include "cifdoc.hpp"
#if defined(_MSC_VER) && !defined(GEMMI_USE_FOPEN)
#include <locale>
#include <codecvt>
#endif
namespace gemmi {
namespace cif {
enum class Style {
Simple,
NoBlankLines,
PreferPairs, // write single-row loops as pairs
Pdbx, // PreferPairs + put '#' (empty comments) between categories
Indent35, // start values in pairs from 35th column
};
// CIF files are read in binary mode. It makes difference only for text fields.
// If the text field with \r\n would be written as is in text mode on Windows
// \r would get duplicated. As a workaround, here we convert \r\n to \n.
// Hopefully \r that gets removed here is never meaningful.
inline void write_text_field(std::ostream& os, const std::string& value) {
for (size_t pos = 0, end = 0; end != std::string::npos; pos = end + 1) {
end = value.find("\r\n", pos);
size_t len = (end == std::string::npos ? value.size() : end) - pos;
os.write(value.c_str() + pos, len);
}
}
inline void write_out_pair(std::ostream& os, const std::string& name,
const std::string& value, Style style) {
os << name;
if (is_text_field(value)) {
os.put('\n');
write_text_field(os, value);
} else {
if (name.size() + value.size() > 120)
os.put('\n');
else if (style == Style::Indent35 && name.size() < 34)
os.write(" ", 34 - name.size());
else
os.put(' ');
os << value;
}
os.put('\n');
}
inline void write_out_loop(std::ostream& os, const Loop& loop, Style style) {
if (loop.values.empty())
return;
if ((style == Style::PreferPairs || style == Style::Pdbx) &&
loop.length() == 1) {
for (size_t i = 0; i != loop.tags.size(); ++i)
write_out_pair(os, loop.tags[i], loop.values[i], style);
return;
}
os << "loop_";
for (const std::string& tag : loop.tags)
os << '\n' << tag;
size_t ncol = loop.tags.size();
size_t col = 0;
for (const std::string& val : loop.values) {
bool text_field = is_text_field(val);
os.put(col++ == 0 || text_field ? '\n' : ' ');
if (text_field)
write_text_field(os, val);
else
os << val;
if (col == ncol)
col = 0;
}
os.put('\n');
}
inline void write_out_item(std::ostream& os, const Item& item, Style style) {
switch (item.type) {
case ItemType::Pair:
write_out_pair(os, item.pair[0], item.pair[1], style);
break;
case ItemType::Loop:
write_out_loop(os, item.loop, style);
break;
case ItemType::Frame:
os << "save_" << item.frame.name << '\n';
for (const Item& inner_item : item.frame.items)
write_out_item(os, inner_item, style);
os << "save_\n";
break;
case ItemType::Comment:
os << item.pair[1] << '\n';
break;
case ItemType::Erased:
break;
}
}
inline bool should_be_separted_(const Item& a, const Item& b) {
if (a.type == ItemType::Comment || b.type == ItemType::Comment)
return false;
if (a.type != ItemType::Pair || b.type != ItemType::Pair)
return true;
// check if we have mmcif-like tags from different categories
auto adot = a.pair[0].find('.');
if (adot == std::string::npos)
return false;
auto bdot = b.pair[0].find('.');
return adot != bdot || a.pair[0].compare(0, adot, b.pair[0], 0, adot) != 0;
}
inline void write_cif_to_stream(std::ostream& os, const Document& doc,
Style s=Style::Simple) {
bool first = true;
for (const Block& block : doc.blocks) {
if (!first)
os.put('\n'); // extra blank line for readability
os << "data_" << block.name << '\n';
if (s == Style::Pdbx)
os << "#\n";
const Item* prev = nullptr;
for (const Item& item : block.items)
if (item.type != ItemType::Erased) {
if (prev && s != Style::NoBlankLines &&
should_be_separted_(*prev, item))
os << (s == Style::Pdbx ? "#\n" : "\n");
write_out_item(os, item, s);
prev = &item;
}
first = false;
if (s == Style::Pdbx)
os << "#\n";
}
}
inline void write_cif_to_file(const Document& doc, const std::string& filename,
Style s=Style::Simple) {
#if defined(_MSC_VER) && !defined(GEMMI_USE_FOPEN)
std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> convert;
std::wstring wfilename = convert.from_bytes(filename.c_str());
std::ofstream of(wfilename.c_str());
#else
std::ofstream of(filename);
#endif
if (!of)
throw std::runtime_error("Failed to open " + filename);
write_cif_to_stream(of, doc, s);
of.close();
}
} // namespace cif
} // namespace gemmi
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/units/unit_base.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
class TestUnit final : public rtc_units_impl::RelativeUnit<TestUnit> {
public:
TestUnit() = delete;
using UnitBase::FromValue;
using UnitBase::ToValue;
using UnitBase::ToValueOr;
template <typename T>
static constexpr TestUnit FromKilo(T kilo) {
return FromFraction(1000, kilo);
}
template <typename T = int64_t>
T ToKilo() const {
return UnitBase::ToFraction<1000, T>();
}
constexpr int64_t ToKiloOr(int64_t fallback) const {
return UnitBase::ToFractionOr<1000>(fallback);
}
template <typename T>
constexpr T ToMilli() const {
return UnitBase::ToMultiple<1000, T>();
}
private:
friend class UnitBase<TestUnit>;
static constexpr bool one_sided = false;
using RelativeUnit<TestUnit>::RelativeUnit;
};
constexpr TestUnit TestUnitAddKilo(TestUnit value, int add_kilo) {
value += TestUnit::FromKilo(add_kilo);
return value;
}
} // namespace
namespace test {
TEST(UnitBaseTest, ConstExpr) {
constexpr int64_t kValue = -12345;
constexpr TestUnit kTestUnitZero = TestUnit::Zero();
constexpr TestUnit kTestUnitPlusInf = TestUnit::PlusInfinity();
constexpr TestUnit kTestUnitMinusInf = TestUnit::MinusInfinity();
static_assert(kTestUnitZero.IsZero(), "");
static_assert(kTestUnitPlusInf.IsPlusInfinity(), "");
static_assert(kTestUnitMinusInf.IsMinusInfinity(), "");
static_assert(kTestUnitPlusInf.ToKiloOr(-1) == -1, "");
static_assert(kTestUnitPlusInf > kTestUnitZero, "");
constexpr TestUnit kTestUnitKilo = TestUnit::FromKilo(kValue);
constexpr TestUnit kTestUnitValue = TestUnit::FromValue(kValue);
static_assert(kTestUnitKilo.ToKiloOr(0) == kValue, "");
static_assert(kTestUnitValue.ToValueOr(0) == kValue, "");
static_assert(TestUnitAddKilo(kTestUnitValue, 2).ToValue() == kValue + 2000,
"");
}
TEST(UnitBaseTest, GetBackSameValues) {
const int64_t kValue = 499;
for (int sign = -1; sign <= 1; ++sign) {
int64_t value = kValue * sign;
EXPECT_EQ(TestUnit::FromKilo(value).ToKilo(), value);
EXPECT_EQ(TestUnit::FromValue(value).ToValue<int64_t>(), value);
}
EXPECT_EQ(TestUnit::Zero().ToValue<int64_t>(), 0);
}
TEST(UnitBaseTest, GetDifferentPrefix) {
const int64_t kValue = 3000000;
EXPECT_EQ(TestUnit::FromValue(kValue).ToKilo(), kValue / 1000);
EXPECT_EQ(TestUnit::FromKilo(kValue).ToValue<int64_t>(), kValue * 1000);
}
TEST(UnitBaseTest, IdentityChecks) {
const int64_t kValue = 3000;
EXPECT_TRUE(TestUnit::Zero().IsZero());
EXPECT_FALSE(TestUnit::FromKilo(kValue).IsZero());
EXPECT_TRUE(TestUnit::PlusInfinity().IsInfinite());
EXPECT_TRUE(TestUnit::MinusInfinity().IsInfinite());
EXPECT_FALSE(TestUnit::Zero().IsInfinite());
EXPECT_FALSE(TestUnit::FromKilo(-kValue).IsInfinite());
EXPECT_FALSE(TestUnit::FromKilo(kValue).IsInfinite());
EXPECT_FALSE(TestUnit::PlusInfinity().IsFinite());
EXPECT_FALSE(TestUnit::MinusInfinity().IsFinite());
EXPECT_TRUE(TestUnit::FromKilo(-kValue).IsFinite());
EXPECT_TRUE(TestUnit::FromKilo(kValue).IsFinite());
EXPECT_TRUE(TestUnit::Zero().IsFinite());
EXPECT_TRUE(TestUnit::PlusInfinity().IsPlusInfinity());
EXPECT_FALSE(TestUnit::MinusInfinity().IsPlusInfinity());
EXPECT_TRUE(TestUnit::MinusInfinity().IsMinusInfinity());
EXPECT_FALSE(TestUnit::PlusInfinity().IsMinusInfinity());
}
TEST(UnitBaseTest, ComparisonOperators) {
const int64_t kSmall = 450;
const int64_t kLarge = 451;
const TestUnit small = TestUnit::FromKilo(kSmall);
const TestUnit large = TestUnit::FromKilo(kLarge);
EXPECT_EQ(TestUnit::Zero(), TestUnit::FromKilo(0));
EXPECT_EQ(TestUnit::PlusInfinity(), TestUnit::PlusInfinity());
EXPECT_EQ(small, TestUnit::FromKilo(kSmall));
EXPECT_LE(small, TestUnit::FromKilo(kSmall));
EXPECT_GE(small, TestUnit::FromKilo(kSmall));
EXPECT_NE(small, TestUnit::FromKilo(kLarge));
EXPECT_LE(small, TestUnit::FromKilo(kLarge));
EXPECT_LT(small, TestUnit::FromKilo(kLarge));
EXPECT_GE(large, TestUnit::FromKilo(kSmall));
EXPECT_GT(large, TestUnit::FromKilo(kSmall));
EXPECT_LT(TestUnit::Zero(), small);
EXPECT_GT(TestUnit::Zero(), TestUnit::FromKilo(-kSmall));
EXPECT_GT(TestUnit::Zero(), TestUnit::FromKilo(-kSmall));
EXPECT_GT(TestUnit::PlusInfinity(), large);
EXPECT_LT(TestUnit::MinusInfinity(), TestUnit::Zero());
}
TEST(UnitBaseTest, Clamping) {
const TestUnit upper = TestUnit::FromKilo(800);
const TestUnit lower = TestUnit::FromKilo(100);
const TestUnit under = TestUnit::FromKilo(100);
const TestUnit inside = TestUnit::FromKilo(500);
const TestUnit over = TestUnit::FromKilo(1000);
EXPECT_EQ(under.Clamped(lower, upper), lower);
EXPECT_EQ(inside.Clamped(lower, upper), inside);
EXPECT_EQ(over.Clamped(lower, upper), upper);
TestUnit mutable_delta = lower;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, lower);
mutable_delta = inside;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, inside);
mutable_delta = over;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, upper);
}
TEST(UnitBaseTest, CanBeInititializedFromLargeInt) {
const int kMaxInt = std::numeric_limits<int>::max();
EXPECT_EQ(TestUnit::FromKilo(kMaxInt).ToValue<int64_t>(),
static_cast<int64_t>(kMaxInt) * 1000);
}
TEST(UnitBaseTest, ConvertsToAndFromDouble) {
const int64_t kValue = 17017;
const double kMilliDouble = kValue * 1e3;
const double kValueDouble = kValue;
const double kKiloDouble = kValue * 1e-3;
EXPECT_EQ(TestUnit::FromValue(kValue).ToKilo<double>(), kKiloDouble);
EXPECT_EQ(TestUnit::FromKilo(kKiloDouble).ToValue<int64_t>(), kValue);
EXPECT_EQ(TestUnit::FromValue(kValue).ToValue<double>(), kValueDouble);
EXPECT_EQ(TestUnit::FromValue(kValueDouble).ToValue<int64_t>(), kValue);
EXPECT_NEAR(TestUnit::FromValue(kValue).ToMilli<double>(), kMilliDouble, 1);
const double kPlusInfinity = std::numeric_limits<double>::infinity();
const double kMinusInfinity = -kPlusInfinity;
EXPECT_EQ(TestUnit::PlusInfinity().ToKilo<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToKilo<double>(), kMinusInfinity);
EXPECT_EQ(TestUnit::PlusInfinity().ToValue<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToValue<double>(), kMinusInfinity);
EXPECT_EQ(TestUnit::PlusInfinity().ToMilli<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToMilli<double>(), kMinusInfinity);
EXPECT_TRUE(TestUnit::FromKilo(kPlusInfinity).IsPlusInfinity());
EXPECT_TRUE(TestUnit::FromKilo(kMinusInfinity).IsMinusInfinity());
EXPECT_TRUE(TestUnit::FromValue(kPlusInfinity).IsPlusInfinity());
EXPECT_TRUE(TestUnit::FromValue(kMinusInfinity).IsMinusInfinity());
}
TEST(UnitBaseTest, MathOperations) {
const int64_t kValueA = 267;
const int64_t kValueB = 450;
const TestUnit delta_a = TestUnit::FromKilo(kValueA);
const TestUnit delta_b = TestUnit::FromKilo(kValueB);
EXPECT_EQ((delta_a + delta_b).ToKilo(), kValueA + kValueB);
EXPECT_EQ((delta_a - delta_b).ToKilo(), kValueA - kValueB);
const int32_t kInt32Value = 123;
const double kFloatValue = 123.0;
EXPECT_EQ((TestUnit::FromValue(kValueA) * kValueB).ToValue<int64_t>(),
kValueA * kValueB);
EXPECT_EQ((TestUnit::FromValue(kValueA) * kInt32Value).ToValue<int64_t>(),
kValueA * kInt32Value);
EXPECT_EQ((TestUnit::FromValue(kValueA) * kFloatValue).ToValue<int64_t>(),
kValueA * kFloatValue);
EXPECT_EQ((delta_b / 10).ToKilo(), kValueB / 10);
EXPECT_EQ(delta_b / delta_a, static_cast<double>(kValueB) / kValueA);
TestUnit mutable_delta = TestUnit::FromKilo(kValueA);
mutable_delta += TestUnit::FromKilo(kValueB);
EXPECT_EQ(mutable_delta, TestUnit::FromKilo(kValueA + kValueB));
mutable_delta -= TestUnit::FromKilo(kValueB);
EXPECT_EQ(mutable_delta, TestUnit::FromKilo(kValueA));
}
TEST(UnitBaseTest, InfinityOperations) {
const int64_t kValue = 267;
const TestUnit finite = TestUnit::FromKilo(kValue);
EXPECT_TRUE((TestUnit::PlusInfinity() + finite).IsPlusInfinity());
EXPECT_TRUE((TestUnit::PlusInfinity() - finite).IsPlusInfinity());
EXPECT_TRUE((finite + TestUnit::PlusInfinity()).IsPlusInfinity());
EXPECT_TRUE((finite - TestUnit::MinusInfinity()).IsPlusInfinity());
EXPECT_TRUE((TestUnit::MinusInfinity() + finite).IsMinusInfinity());
EXPECT_TRUE((TestUnit::MinusInfinity() - finite).IsMinusInfinity());
EXPECT_TRUE((finite + TestUnit::MinusInfinity()).IsMinusInfinity());
EXPECT_TRUE((finite - TestUnit::PlusInfinity()).IsMinusInfinity());
}
} // namespace test
} // namespace webrtc
<commit_msg>Fix errors C2238, C2248 and C2059 on MSVC bots.<commit_after>/*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "rtc_base/units/unit_base.h"
#include "test/gtest.h"
namespace webrtc {
namespace {
class TestUnit final : public rtc_units_impl::RelativeUnit<TestUnit> {
public:
TestUnit() = delete;
using UnitBase::FromValue;
using UnitBase::ToValue;
using UnitBase::ToValueOr;
template <typename T>
static constexpr TestUnit FromKilo(T kilo) {
return FromFraction(1000, kilo);
}
template <typename T = int64_t>
T ToKilo() const {
return UnitBase::ToFraction<1000, T>();
}
constexpr int64_t ToKiloOr(int64_t fallback) const {
return UnitBase::ToFractionOr<1000>(fallback);
}
template <typename T>
constexpr T ToMilli() const {
return UnitBase::ToMultiple<1000, T>();
}
private:
friend class rtc_units_impl::UnitBase<TestUnit>;
static constexpr bool one_sided = false;
using RelativeUnit<TestUnit>::RelativeUnit;
};
constexpr TestUnit TestUnitAddKilo(TestUnit value, int add_kilo) {
value += TestUnit::FromKilo(add_kilo);
return value;
}
} // namespace
namespace test {
TEST(UnitBaseTest, ConstExpr) {
constexpr int64_t kValue = -12345;
constexpr TestUnit kTestUnitZero = TestUnit::Zero();
constexpr TestUnit kTestUnitPlusInf = TestUnit::PlusInfinity();
constexpr TestUnit kTestUnitMinusInf = TestUnit::MinusInfinity();
static_assert(kTestUnitZero.IsZero(), "");
static_assert(kTestUnitPlusInf.IsPlusInfinity(), "");
static_assert(kTestUnitMinusInf.IsMinusInfinity(), "");
static_assert(kTestUnitPlusInf.ToKiloOr(-1) == -1, "");
static_assert(kTestUnitPlusInf > kTestUnitZero, "");
constexpr TestUnit kTestUnitKilo = TestUnit::FromKilo(kValue);
constexpr TestUnit kTestUnitValue = TestUnit::FromValue(kValue);
static_assert(kTestUnitKilo.ToKiloOr(0) == kValue, "");
static_assert(kTestUnitValue.ToValueOr(0) == kValue, "");
static_assert(TestUnitAddKilo(kTestUnitValue, 2).ToValue() == kValue + 2000,
"");
}
TEST(UnitBaseTest, GetBackSameValues) {
const int64_t kValue = 499;
for (int sign = -1; sign <= 1; ++sign) {
int64_t value = kValue * sign;
EXPECT_EQ(TestUnit::FromKilo(value).ToKilo(), value);
EXPECT_EQ(TestUnit::FromValue(value).ToValue<int64_t>(), value);
}
EXPECT_EQ(TestUnit::Zero().ToValue<int64_t>(), 0);
}
TEST(UnitBaseTest, GetDifferentPrefix) {
const int64_t kValue = 3000000;
EXPECT_EQ(TestUnit::FromValue(kValue).ToKilo(), kValue / 1000);
EXPECT_EQ(TestUnit::FromKilo(kValue).ToValue<int64_t>(), kValue * 1000);
}
TEST(UnitBaseTest, IdentityChecks) {
const int64_t kValue = 3000;
EXPECT_TRUE(TestUnit::Zero().IsZero());
EXPECT_FALSE(TestUnit::FromKilo(kValue).IsZero());
EXPECT_TRUE(TestUnit::PlusInfinity().IsInfinite());
EXPECT_TRUE(TestUnit::MinusInfinity().IsInfinite());
EXPECT_FALSE(TestUnit::Zero().IsInfinite());
EXPECT_FALSE(TestUnit::FromKilo(-kValue).IsInfinite());
EXPECT_FALSE(TestUnit::FromKilo(kValue).IsInfinite());
EXPECT_FALSE(TestUnit::PlusInfinity().IsFinite());
EXPECT_FALSE(TestUnit::MinusInfinity().IsFinite());
EXPECT_TRUE(TestUnit::FromKilo(-kValue).IsFinite());
EXPECT_TRUE(TestUnit::FromKilo(kValue).IsFinite());
EXPECT_TRUE(TestUnit::Zero().IsFinite());
EXPECT_TRUE(TestUnit::PlusInfinity().IsPlusInfinity());
EXPECT_FALSE(TestUnit::MinusInfinity().IsPlusInfinity());
EXPECT_TRUE(TestUnit::MinusInfinity().IsMinusInfinity());
EXPECT_FALSE(TestUnit::PlusInfinity().IsMinusInfinity());
}
TEST(UnitBaseTest, ComparisonOperators) {
const int64_t kSmall = 450;
const int64_t kLarge = 451;
const TestUnit small = TestUnit::FromKilo(kSmall);
const TestUnit large = TestUnit::FromKilo(kLarge);
EXPECT_EQ(TestUnit::Zero(), TestUnit::FromKilo(0));
EXPECT_EQ(TestUnit::PlusInfinity(), TestUnit::PlusInfinity());
EXPECT_EQ(small, TestUnit::FromKilo(kSmall));
EXPECT_LE(small, TestUnit::FromKilo(kSmall));
EXPECT_GE(small, TestUnit::FromKilo(kSmall));
EXPECT_NE(small, TestUnit::FromKilo(kLarge));
EXPECT_LE(small, TestUnit::FromKilo(kLarge));
EXPECT_LT(small, TestUnit::FromKilo(kLarge));
EXPECT_GE(large, TestUnit::FromKilo(kSmall));
EXPECT_GT(large, TestUnit::FromKilo(kSmall));
EXPECT_LT(TestUnit::Zero(), small);
EXPECT_GT(TestUnit::Zero(), TestUnit::FromKilo(-kSmall));
EXPECT_GT(TestUnit::Zero(), TestUnit::FromKilo(-kSmall));
EXPECT_GT(TestUnit::PlusInfinity(), large);
EXPECT_LT(TestUnit::MinusInfinity(), TestUnit::Zero());
}
TEST(UnitBaseTest, Clamping) {
const TestUnit upper = TestUnit::FromKilo(800);
const TestUnit lower = TestUnit::FromKilo(100);
const TestUnit under = TestUnit::FromKilo(100);
const TestUnit inside = TestUnit::FromKilo(500);
const TestUnit over = TestUnit::FromKilo(1000);
EXPECT_EQ(under.Clamped(lower, upper), lower);
EXPECT_EQ(inside.Clamped(lower, upper), inside);
EXPECT_EQ(over.Clamped(lower, upper), upper);
TestUnit mutable_delta = lower;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, lower);
mutable_delta = inside;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, inside);
mutable_delta = over;
mutable_delta.Clamp(lower, upper);
EXPECT_EQ(mutable_delta, upper);
}
TEST(UnitBaseTest, CanBeInititializedFromLargeInt) {
const int kMaxInt = std::numeric_limits<int>::max();
EXPECT_EQ(TestUnit::FromKilo(kMaxInt).ToValue<int64_t>(),
static_cast<int64_t>(kMaxInt) * 1000);
}
TEST(UnitBaseTest, ConvertsToAndFromDouble) {
const int64_t kValue = 17017;
const double kMilliDouble = kValue * 1e3;
const double kValueDouble = kValue;
const double kKiloDouble = kValue * 1e-3;
EXPECT_EQ(TestUnit::FromValue(kValue).ToKilo<double>(), kKiloDouble);
EXPECT_EQ(TestUnit::FromKilo(kKiloDouble).ToValue<int64_t>(), kValue);
EXPECT_EQ(TestUnit::FromValue(kValue).ToValue<double>(), kValueDouble);
EXPECT_EQ(TestUnit::FromValue(kValueDouble).ToValue<int64_t>(), kValue);
EXPECT_NEAR(TestUnit::FromValue(kValue).ToMilli<double>(), kMilliDouble, 1);
const double kPlusInfinity = std::numeric_limits<double>::infinity();
const double kMinusInfinity = -kPlusInfinity;
EXPECT_EQ(TestUnit::PlusInfinity().ToKilo<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToKilo<double>(), kMinusInfinity);
EXPECT_EQ(TestUnit::PlusInfinity().ToValue<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToValue<double>(), kMinusInfinity);
EXPECT_EQ(TestUnit::PlusInfinity().ToMilli<double>(), kPlusInfinity);
EXPECT_EQ(TestUnit::MinusInfinity().ToMilli<double>(), kMinusInfinity);
EXPECT_TRUE(TestUnit::FromKilo(kPlusInfinity).IsPlusInfinity());
EXPECT_TRUE(TestUnit::FromKilo(kMinusInfinity).IsMinusInfinity());
EXPECT_TRUE(TestUnit::FromValue(kPlusInfinity).IsPlusInfinity());
EXPECT_TRUE(TestUnit::FromValue(kMinusInfinity).IsMinusInfinity());
}
TEST(UnitBaseTest, MathOperations) {
const int64_t kValueA = 267;
const int64_t kValueB = 450;
const TestUnit delta_a = TestUnit::FromKilo(kValueA);
const TestUnit delta_b = TestUnit::FromKilo(kValueB);
EXPECT_EQ((delta_a + delta_b).ToKilo(), kValueA + kValueB);
EXPECT_EQ((delta_a - delta_b).ToKilo(), kValueA - kValueB);
const int32_t kInt32Value = 123;
const double kFloatValue = 123.0;
EXPECT_EQ((TestUnit::FromValue(kValueA) * kValueB).ToValue<int64_t>(),
kValueA * kValueB);
EXPECT_EQ((TestUnit::FromValue(kValueA) * kInt32Value).ToValue<int64_t>(),
kValueA * kInt32Value);
EXPECT_EQ((TestUnit::FromValue(kValueA) * kFloatValue).ToValue<int64_t>(),
kValueA * kFloatValue);
EXPECT_EQ((delta_b / 10).ToKilo(), kValueB / 10);
EXPECT_EQ(delta_b / delta_a, static_cast<double>(kValueB) / kValueA);
TestUnit mutable_delta = TestUnit::FromKilo(kValueA);
mutable_delta += TestUnit::FromKilo(kValueB);
EXPECT_EQ(mutable_delta, TestUnit::FromKilo(kValueA + kValueB));
mutable_delta -= TestUnit::FromKilo(kValueB);
EXPECT_EQ(mutable_delta, TestUnit::FromKilo(kValueA));
}
TEST(UnitBaseTest, InfinityOperations) {
const int64_t kValue = 267;
const TestUnit finite = TestUnit::FromKilo(kValue);
EXPECT_TRUE((TestUnit::PlusInfinity() + finite).IsPlusInfinity());
EXPECT_TRUE((TestUnit::PlusInfinity() - finite).IsPlusInfinity());
EXPECT_TRUE((finite + TestUnit::PlusInfinity()).IsPlusInfinity());
EXPECT_TRUE((finite - TestUnit::MinusInfinity()).IsPlusInfinity());
EXPECT_TRUE((TestUnit::MinusInfinity() + finite).IsMinusInfinity());
EXPECT_TRUE((TestUnit::MinusInfinity() - finite).IsMinusInfinity());
EXPECT_TRUE((finite + TestUnit::MinusInfinity()).IsMinusInfinity());
EXPECT_TRUE((finite - TestUnit::PlusInfinity()).IsMinusInfinity());
}
} // namespace test
} // namespace webrtc
<|endoftext|> |
<commit_before>// Copyright 2014-2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <ccpp_dds_dcps.h>
#include <dds_dcps.h>
#include "rmw/allocators.h"
#include "rmw/error_handling.h"
#include "rmw/impl/cpp/macros.hpp"
#include "rmw/rmw.h"
#include "rmw/types.h"
#include "identifier.hpp"
#include "types.hpp"
// The extern "C" here enforces that overloading is not used.
extern "C"
{
rmw_ret_t check_attach_condition_error(DDS::ReturnCode_t retcode)
{
if (retcode == DDS::RETCODE_OK) {
return RMW_RET_OK;
}
if (retcode == DDS::RETCODE_OUT_OF_RESOURCES) {
RMW_SET_ERROR_MSG("failed to attach condition to waitset: out of resources");
} else if (retcode == DDS::RETCODE_BAD_PARAMETER) {
RMW_SET_ERROR_MSG("failed to attach condition to waitset: condition pointer was invalid");
} else {
RMW_SET_ERROR_MSG("failed to attach condition to waitset");
}
return RMW_RET_ERROR;
}
rmw_ret_t
rmw_wait(
rmw_subscriptions_t * subscriptions,
rmw_guard_conditions_t * guard_conditions,
rmw_services_t * services,
rmw_clients_t * clients,
rmw_waitset_t * waitset,
const rmw_time_t * wait_timeout)
{
// To ensure that we properly clean up the wait set, we declare an
// object whose destructor will detach what we attached (this was previously
// being done inside the destructor of the wait set.
struct atexit_t
{
~atexit_t()
{
// Manually detach conditions and clear sequences, to ensure a clean wait set for next time.
if (!waitset) {
RMW_SET_ERROR_MSG("waitset handle is null");
return;
}
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
waitset handle,
waitset->implementation_identifier, opensplice_cpp_identifier,
return )
OpenSpliceWaitSetInfo * waitset_info = static_cast<OpenSpliceWaitSetInfo *>(waitset->data);
if (!waitset_info) {
RMW_SET_ERROR_MSG("WaitSet implementation struct is null");
return;
}
DDS::WaitSet * dds_waitset = static_cast<DDS::WaitSet *>(waitset_info->waitset);
if (!dds_waitset) {
RMW_SET_ERROR_MSG("DDS waitset handle is null");
return;
}
DDS::ConditionSeq * attached_conditions =
static_cast<DDS::ConditionSeq *>(waitset_info->attached_conditions);
if (!attached_conditions) {
RMW_SET_ERROR_MSG("DDS condition sequence handle is null");
return;
}
DDS::ReturnCode_t retcode;
retcode = dds_waitset->get_conditions(*attached_conditions);
if (retcode != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("Failed to get attached conditions for waitset");
return;
}
for (uint32_t i = 0; i < attached_conditions->length(); ++i) {
retcode = dds_waitset->detach_condition((*attached_conditions)[i]);
if (retcode != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("Failed to get detach condition from waitset");
}
}
DDS::ConditionSeq * active_conditions =
static_cast<DDS::ConditionSeq *>(waitset_info->active_conditions);
if (!active_conditions) {
RMW_SET_ERROR_MSG("DDS condition sequence handle is null");
return;
}
// Disassociate conditions left in active_conditions so that when the
// waitset (and therefore the active_conditions sequence) are destroyed
// they do not try to free the entities to which they point.
// These entities are already being deleted (are owned) by other entities
// like rmw_guard_conditions_t and rmw_node_t.
// Without this step, sporadic bad memory accesses could occur when the
// items added to the waitset were destroyed before the waitset.
// The items in active_conditions are not being leaked though because
// other entities own them and are responsible for removing them.
for (uint32_t i = 0; i < active_conditions->length(); ++i) {
active_conditions->get_buffer()[i] = nullptr;
}
}
rmw_waitset_t * waitset = NULL;
} atexit;
atexit.waitset = waitset;
if (!waitset) {
RMW_SET_ERROR_MSG("waitset handle is null");
return RMW_RET_ERROR;
}
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
waitset,
waitset->implementation_identifier, opensplice_cpp_identifier,
return RMW_RET_ERROR);
OpenSpliceWaitSetInfo * waitset_info = static_cast<OpenSpliceWaitSetInfo *>(waitset->data);
if (!waitset_info) {
RMW_SET_ERROR_MSG("WaitSet implementation struct is null");
return RMW_RET_ERROR;
}
DDS::WaitSet * dds_waitset = static_cast<DDS::WaitSet *>(waitset_info->waitset);
if (!dds_waitset) {
RMW_SET_ERROR_MSG("DDS waitset handle is null");
return RMW_RET_ERROR;
}
DDS::ConditionSeq * active_conditions =
static_cast<DDS::ConditionSeq *>(waitset_info->active_conditions);
if (!active_conditions) {
RMW_SET_ERROR_MSG("DDS condition sequence handle is null");
return RMW_RET_ERROR;
}
DDS::ConditionSeq * attached_conditions =
static_cast<DDS::ConditionSeq *>(waitset_info->attached_conditions);
if (!attached_conditions) {
RMW_SET_ERROR_MSG("DDS condition sequence handle is null");
return RMW_RET_ERROR;
}
// add a condition for each subscriber
for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {
OpenSpliceStaticSubscriberInfo * subscriber_info =
static_cast<OpenSpliceStaticSubscriberInfo *>(subscriptions->subscribers[i]);
if (!subscriber_info) {
RMW_SET_ERROR_MSG("subscriber info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = subscriber_info->read_condition;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
rmw_ret_t status = check_attach_condition_error(
dds_waitset->attach_condition(read_condition));
if (status != RMW_RET_OK) {
return status;
}
}
// add a condition for each guard condition
if (guard_conditions) {
for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {
DDS::GuardCondition * guard_condition =
static_cast<DDS::GuardCondition *>(guard_conditions->guard_conditions[i]);
if (!guard_condition) {
RMW_SET_ERROR_MSG("guard condition handle is null");
return RMW_RET_ERROR;
}
rmw_ret_t status = check_attach_condition_error(
dds_waitset->attach_condition(guard_condition));
if (status != RMW_RET_OK) {
return status;
}
}
}
// add a condition for each service
for (size_t i = 0; i < services->service_count; ++i) {
OpenSpliceStaticServiceInfo * service_info =
static_cast<OpenSpliceStaticServiceInfo *>(services->services[i]);
if (!service_info) {
RMW_SET_ERROR_MSG("service info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = service_info->read_condition_;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
rmw_ret_t status = check_attach_condition_error(
dds_waitset->attach_condition(read_condition));
if (status != RMW_RET_OK) {
return status;
}
}
// add a condition for each client
for (size_t i = 0; i < clients->client_count; ++i) {
OpenSpliceStaticClientInfo * client_info =
static_cast<OpenSpliceStaticClientInfo *>(clients->clients[i]);
if (!client_info) {
RMW_SET_ERROR_MSG("client info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = client_info->read_condition_;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
rmw_ret_t status = check_attach_condition_error(
dds_waitset->attach_condition(read_condition));
if (status != RMW_RET_OK) {
return status;
}
}
// invoke wait until one of the conditions triggers
DDS::Duration_t timeout;
if (!wait_timeout) {
timeout = DDS::DURATION_INFINITE;
} else {
timeout.sec = static_cast<DDS::Long>(wait_timeout->sec);
timeout.nanosec = static_cast<DDS::Long>(wait_timeout->nsec);
}
DDS::ReturnCode_t status = dds_waitset->wait(*active_conditions, timeout);
if (status != DDS::RETCODE_OK && status != DDS::RETCODE_TIMEOUT) {
RMW_SET_ERROR_MSG("failed to wait on waitset");
return RMW_RET_ERROR;
}
// set subscriber handles to zero for all not triggered status conditions
for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {
OpenSpliceStaticSubscriberInfo * subscriber_info =
static_cast<OpenSpliceStaticSubscriberInfo *>(subscriptions->subscribers[i]);
if (!subscriber_info) {
RMW_SET_ERROR_MSG("subscriber info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = subscriber_info->read_condition;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
if (!read_condition->get_trigger_value()) {
// if the status condition was not triggered
// reset the subscriber handle
subscriptions->subscribers[i] = 0;
}
if (dds_waitset->detach_condition(read_condition) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to detach guard condition");
return RMW_RET_ERROR;
}
}
if (guard_conditions) {
for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {
DDS::GuardCondition * guard_condition =
static_cast<DDS::GuardCondition *>(guard_conditions->guard_conditions[i]);
if (!guard_condition) {
RMW_SET_ERROR_MSG("guard condition handle is null");
return RMW_RET_ERROR;
}
if (!guard_condition->get_trigger_value()) {
guard_conditions->guard_conditions[i] = 0;
} else {
// reset the trigger value for triggered guard conditions
if (guard_condition->set_trigger_value(false) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to set trigger value to false");
return RMW_RET_ERROR;
}
}
if (dds_waitset->detach_condition(guard_condition) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to detach guard condition");
return RMW_RET_ERROR;
}
}
}
// set service handles to zero for all not triggered conditions
for (size_t i = 0; i < services->service_count; ++i) {
OpenSpliceStaticServiceInfo * service_info =
static_cast<OpenSpliceStaticServiceInfo *>(services->services[i]);
if (!service_info) {
RMW_SET_ERROR_MSG("service info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = service_info->read_condition_;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
// search for service condition in active set
uint32_t j = 0;
for (; j < active_conditions->length(); ++j) {
if ((*active_conditions)[j] == read_condition) {
break;
}
}
// if service condition is not found in the active set
// reset the service handle
if (!(j < active_conditions->length())) {
services->services[i] = 0;
}
if (dds_waitset->detach_condition(read_condition) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to detach guard condition");
return RMW_RET_ERROR;
}
}
// set client handles to zero for all not triggered conditions
for (size_t i = 0; i < clients->client_count; ++i) {
OpenSpliceStaticClientInfo * client_info =
static_cast<OpenSpliceStaticClientInfo *>(clients->clients[i]);
if (!client_info) {
RMW_SET_ERROR_MSG("client info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = client_info->read_condition_;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
// search for service condition in active set
uint32_t j = 0;
for (; j < active_conditions->length(); ++j) {
if ((*active_conditions)[j] == read_condition) {
break;
}
}
// if client condition is not found in the active set
// reset the client handle
if (!(j < active_conditions->length())) {
clients->clients[i] = 0;
}
if (dds_waitset->detach_condition(read_condition) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to detach guard condition");
return RMW_RET_ERROR;
}
}
if (status == DDS::RETCODE_TIMEOUT) {
return RMW_RET_TIMEOUT;
}
return RMW_RET_OK;
}
} // extern "C"
<commit_msg>pointers are checked for null<commit_after>// Copyright 2014-2015 Open Source Robotics Foundation, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <ccpp_dds_dcps.h>
#include <dds_dcps.h>
#include "rmw/allocators.h"
#include "rmw/error_handling.h"
#include "rmw/impl/cpp/macros.hpp"
#include "rmw/rmw.h"
#include "rmw/types.h"
#include "identifier.hpp"
#include "types.hpp"
// The extern "C" here enforces that overloading is not used.
extern "C"
{
rmw_ret_t check_attach_condition_error(DDS::ReturnCode_t retcode)
{
if (retcode == DDS::RETCODE_OK) {
return RMW_RET_OK;
}
if (retcode == DDS::RETCODE_OUT_OF_RESOURCES) {
RMW_SET_ERROR_MSG("failed to attach condition to waitset: out of resources");
} else if (retcode == DDS::RETCODE_BAD_PARAMETER) {
RMW_SET_ERROR_MSG("failed to attach condition to waitset: condition pointer was invalid");
} else {
RMW_SET_ERROR_MSG("failed to attach condition to waitset");
}
return RMW_RET_ERROR;
}
rmw_ret_t
rmw_wait(
rmw_subscriptions_t * subscriptions,
rmw_guard_conditions_t * guard_conditions,
rmw_services_t * services,
rmw_clients_t * clients,
rmw_waitset_t * waitset,
const rmw_time_t * wait_timeout)
{
// To ensure that we properly clean up the wait set, we declare an
// object whose destructor will detach what we attached (this was previously
// being done inside the destructor of the wait set.
struct atexit_t
{
~atexit_t()
{
// Manually detach conditions and clear sequences, to ensure a clean wait set for next time.
if (!waitset) {
RMW_SET_ERROR_MSG("waitset handle is null");
return;
}
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
waitset handle,
waitset->implementation_identifier, opensplice_cpp_identifier,
return )
OpenSpliceWaitSetInfo * waitset_info = static_cast<OpenSpliceWaitSetInfo *>(waitset->data);
if (!waitset_info) {
RMW_SET_ERROR_MSG("WaitSet implementation struct is null");
return;
}
DDS::WaitSet * dds_waitset = static_cast<DDS::WaitSet *>(waitset_info->waitset);
if (!dds_waitset) {
RMW_SET_ERROR_MSG("DDS waitset handle is null");
return;
}
DDS::ConditionSeq * attached_conditions =
static_cast<DDS::ConditionSeq *>(waitset_info->attached_conditions);
if (!attached_conditions) {
RMW_SET_ERROR_MSG("DDS condition sequence handle is null");
return;
}
DDS::ReturnCode_t retcode;
retcode = dds_waitset->get_conditions(*attached_conditions);
if (retcode != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("Failed to get attached conditions for waitset");
return;
}
for (uint32_t i = 0; i < attached_conditions->length(); ++i) {
retcode = dds_waitset->detach_condition((*attached_conditions)[i]);
if (retcode != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("Failed to get detach condition from waitset");
}
}
DDS::ConditionSeq * active_conditions =
static_cast<DDS::ConditionSeq *>(waitset_info->active_conditions);
if (!active_conditions) {
RMW_SET_ERROR_MSG("DDS condition sequence handle is null");
return;
}
// Disassociate conditions left in active_conditions so that when the
// waitset (and therefore the active_conditions sequence) are destroyed
// they do not try to free the entities to which they point.
// These entities are already being deleted (are owned) by other entities
// like rmw_guard_conditions_t and rmw_node_t.
// Without this step, sporadic bad memory accesses could occur when the
// items added to the waitset were destroyed before the waitset.
// The items in active_conditions are not being leaked though because
// other entities own them and are responsible for removing them.
for (uint32_t i = 0; i < active_conditions->length(); ++i) {
active_conditions->get_buffer()[i] = nullptr;
}
}
rmw_waitset_t * waitset = NULL;
} atexit;
atexit.waitset = waitset;
if (!waitset) {
RMW_SET_ERROR_MSG("waitset handle is null");
return RMW_RET_ERROR;
}
RMW_CHECK_TYPE_IDENTIFIERS_MATCH(
waitset,
waitset->implementation_identifier, opensplice_cpp_identifier,
return RMW_RET_ERROR);
OpenSpliceWaitSetInfo * waitset_info = static_cast<OpenSpliceWaitSetInfo *>(waitset->data);
if (!waitset_info) {
RMW_SET_ERROR_MSG("WaitSet implementation struct is null");
return RMW_RET_ERROR;
}
DDS::WaitSet * dds_waitset = static_cast<DDS::WaitSet *>(waitset_info->waitset);
if (!dds_waitset) {
RMW_SET_ERROR_MSG("DDS waitset handle is null");
return RMW_RET_ERROR;
}
DDS::ConditionSeq * active_conditions =
static_cast<DDS::ConditionSeq *>(waitset_info->active_conditions);
if (!active_conditions) {
RMW_SET_ERROR_MSG("DDS condition sequence handle is null");
return RMW_RET_ERROR;
}
DDS::ConditionSeq * attached_conditions =
static_cast<DDS::ConditionSeq *>(waitset_info->attached_conditions);
if (!attached_conditions) {
RMW_SET_ERROR_MSG("DDS condition sequence handle is null");
return RMW_RET_ERROR;
}
// add a condition for each subscriber
if (subscriptions) {
for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {
OpenSpliceStaticSubscriberInfo * subscriber_info =
static_cast<OpenSpliceStaticSubscriberInfo *>(subscriptions->subscribers[i]);
if (!subscriber_info) {
RMW_SET_ERROR_MSG("subscriber info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = subscriber_info->read_condition;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
rmw_ret_t status = check_attach_condition_error(
dds_waitset->attach_condition(read_condition));
if (status != RMW_RET_OK) {
return status;
}
}
}
// add a condition for each guard condition
if (guard_conditions) {
for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {
DDS::GuardCondition * guard_condition =
static_cast<DDS::GuardCondition *>(guard_conditions->guard_conditions[i]);
if (!guard_condition) {
RMW_SET_ERROR_MSG("guard condition handle is null");
return RMW_RET_ERROR;
}
rmw_ret_t status = check_attach_condition_error(
dds_waitset->attach_condition(guard_condition));
if (status != RMW_RET_OK) {
return status;
}
}
}
// add a condition for each service
if (services) {
for (size_t i = 0; i < services->service_count; ++i) {
OpenSpliceStaticServiceInfo * service_info =
static_cast<OpenSpliceStaticServiceInfo *>(services->services[i]);
if (!service_info) {
RMW_SET_ERROR_MSG("service info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = service_info->read_condition_;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
rmw_ret_t status = check_attach_condition_error(
dds_waitset->attach_condition(read_condition));
if (status != RMW_RET_OK) {
return status;
}
}
}
// add a condition for each client
if (clients) {
for (size_t i = 0; i < clients->client_count; ++i) {
OpenSpliceStaticClientInfo * client_info =
static_cast<OpenSpliceStaticClientInfo *>(clients->clients[i]);
if (!client_info) {
RMW_SET_ERROR_MSG("client info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = client_info->read_condition_;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
rmw_ret_t status = check_attach_condition_error(
dds_waitset->attach_condition(read_condition));
if (status != RMW_RET_OK) {
return status;
}
}
}
// invoke wait until one of the conditions triggers
DDS::Duration_t timeout;
if (!wait_timeout) {
timeout = DDS::DURATION_INFINITE;
} else {
timeout.sec = static_cast<DDS::Long>(wait_timeout->sec);
timeout.nanosec = static_cast<DDS::Long>(wait_timeout->nsec);
}
DDS::ReturnCode_t status = dds_waitset->wait(*active_conditions, timeout);
if (status != DDS::RETCODE_OK && status != DDS::RETCODE_TIMEOUT) {
RMW_SET_ERROR_MSG("failed to wait on waitset");
return RMW_RET_ERROR;
}
// set subscriber handles to zero for all not triggered status conditions
if (subscriptions) {
for (size_t i = 0; i < subscriptions->subscriber_count; ++i) {
OpenSpliceStaticSubscriberInfo * subscriber_info =
static_cast<OpenSpliceStaticSubscriberInfo *>(subscriptions->subscribers[i]);
if (!subscriber_info) {
RMW_SET_ERROR_MSG("subscriber info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = subscriber_info->read_condition;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
if (!read_condition->get_trigger_value()) {
// if the status condition was not triggered
// reset the subscriber handle
subscriptions->subscribers[i] = 0;
}
if (dds_waitset->detach_condition(read_condition) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to detach guard condition");
return RMW_RET_ERROR;
}
}
}
if (guard_conditions) {
for (size_t i = 0; i < guard_conditions->guard_condition_count; ++i) {
DDS::GuardCondition * guard_condition =
static_cast<DDS::GuardCondition *>(guard_conditions->guard_conditions[i]);
if (!guard_condition) {
RMW_SET_ERROR_MSG("guard condition handle is null");
return RMW_RET_ERROR;
}
if (!guard_condition->get_trigger_value()) {
guard_conditions->guard_conditions[i] = 0;
} else {
// reset the trigger value for triggered guard conditions
if (guard_condition->set_trigger_value(false) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to set trigger value to false");
return RMW_RET_ERROR;
}
}
if (dds_waitset->detach_condition(guard_condition) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to detach guard condition");
return RMW_RET_ERROR;
}
}
}
// set service handles to zero for all not triggered conditions
if (services) {
for (size_t i = 0; i < services->service_count; ++i) {
OpenSpliceStaticServiceInfo * service_info =
static_cast<OpenSpliceStaticServiceInfo *>(services->services[i]);
if (!service_info) {
RMW_SET_ERROR_MSG("service info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = service_info->read_condition_;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
// search for service condition in active set
uint32_t j = 0;
for (; j < active_conditions->length(); ++j) {
if ((*active_conditions)[j] == read_condition) {
break;
}
}
// if service condition is not found in the active set
// reset the service handle
if (!(j < active_conditions->length())) {
services->services[i] = 0;
}
if (dds_waitset->detach_condition(read_condition) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to detach guard condition");
return RMW_RET_ERROR;
}
}
}
// set client handles to zero for all not triggered conditions
if (clients) {
for (size_t i = 0; i < clients->client_count; ++i) {
OpenSpliceStaticClientInfo * client_info =
static_cast<OpenSpliceStaticClientInfo *>(clients->clients[i]);
if (!client_info) {
RMW_SET_ERROR_MSG("client info handle is null");
return RMW_RET_ERROR;
}
DDS::ReadCondition * read_condition = client_info->read_condition_;
if (!read_condition) {
RMW_SET_ERROR_MSG("read condition handle is null");
return RMW_RET_ERROR;
}
// search for service condition in active set
uint32_t j = 0;
for (; j < active_conditions->length(); ++j) {
if ((*active_conditions)[j] == read_condition) {
break;
}
}
// if client condition is not found in the active set
// reset the client handle
if (!(j < active_conditions->length())) {
clients->clients[i] = 0;
}
if (dds_waitset->detach_condition(read_condition) != DDS::RETCODE_OK) {
RMW_SET_ERROR_MSG("failed to detach guard condition");
return RMW_RET_ERROR;
}
}
}
if (status == DDS::RETCODE_TIMEOUT) {
return RMW_RET_TIMEOUT;
}
return RMW_RET_OK;
}
} // extern "C"
<|endoftext|> |
<commit_before>#include "readDMAT.h"
#include "verbose.h"
#include <cstdio>
#include <Eigen/Dense>
// Static helper method reads the first to elements in the given file
// Inputs:
// fp file pointer of .dmat file that was just opened
// Outputs:
// num_rows number of rows
// num_cols number of columns
// Returns true on success, false on failure
static inline bool readDMAT_read_header(FILE * fp, int & num_rows, int & num_cols)
{
// first line contains number of rows and number of columns
int res = fscanf(fp,"%d %d\n",&num_cols,&num_rows);
if(res != 2)
{
fprintf(stderr,"IOError: readDMAT() first row should be [num cols] [num rows]...\n");
return false;
}
// check that number of columns and rows are sane
if(num_cols < 0)
{
fprintf(stderr,"IOError: readDMAT() number of columns %d < 0\n",num_cols);
return false;
}
if(num_rows < 0)
{
fprintf(stderr,"IOError: readDMAT() number of rows %d < 0\n",num_rows);
return false;
}
return true;
}
#ifndef IGL_NO_EIGEN
template <typename DerivedW>
IGL_INLINE bool igl::readDMAT(const std::string file_name,
Eigen::PlainObjectBase<DerivedW> & W)
{
FILE * fp = fopen(file_name.c_str(),"r");
if(fp == NULL)
{
fprintf(stderr,"IOError: readDMAT() could not open %s...\n",file_name.c_str());
return false;
}
int num_rows,num_cols;
bool head_success = readDMAT_read_header(fp,num_rows,num_cols);
if(!head_success)
{
fclose(fp);
return false;
}
// Resize output to fit matrix
W.resize(num_rows,num_cols);
// Loop over columns slowly
for(int j = 0;j < num_cols;j++)
{
// loop over rows (down columns) quickly
for(int i = 0;i < num_rows;i++)
{
double d;
if(fscanf(fp," %lg",&d) != 1)
{
fclose(fp);
fprintf(
stderr,
"IOError: readDMAT() bad format after reading %d entries\n",
j*num_rows + i);
return false;
}
W(i,j) = d;
}
}
fclose(fp);
return true;
}
#endif
template <typename Scalar>
IGL_INLINE bool igl::readDMAT(
const std::string file_name,
std::vector<std::vector<Scalar> > & W)
{
FILE * fp = fopen(file_name.c_str(),"r");
if(fp == NULL)
{
fprintf(stderr,"IOError: readDMAT() could not open %s...\n",file_name.c_str());
return false;
}
int num_rows,num_cols;
bool head_success = readDMAT_read_header(fp,num_rows,num_cols);
if(!head_success)
{
fclose(fp);
return false;
}
// Resize for output
W.resize(num_rows,typename std::vector<Scalar>(num_cols));
// Loop over columns slowly
for(int j = 0;j < num_cols;j++)
{
// loop over rows (down columns) quickly
for(int i = 0;i < num_rows;i++)
{
double d;
if(fscanf(fp," %lg",&d) != 1)
{
fclose(fp);
fprintf(
stderr,
"IOError: readDMAT() bad format after reading %d entries\n",
j*num_rows + i);
return false;
}
W[i][j] = (Scalar)d;
}
}
fclose(fp);
return true;
}
#ifndef IGL_HEADER_ONLY
// Explicit template specialization
template bool igl::readDMAT<Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
#endif
<commit_msg>no eigen in readDmat<commit_after>#include "readDMAT.h"
#include "verbose.h"
#include <cstdio>
#include <iostream>
// Static helper method reads the first to elements in the given file
// Inputs:
// fp file pointer of .dmat file that was just opened
// Outputs:
// num_rows number of rows
// num_cols number of columns
// Returns true on success, false on failure
static inline bool readDMAT_read_header(FILE * fp, int & num_rows, int & num_cols)
{
// first line contains number of rows and number of columns
int res = fscanf(fp,"%d %d\n",&num_cols,&num_rows);
if(res != 2)
{
fprintf(stderr,"IOError: readDMAT() first row should be [num cols] [num rows]...\n");
return false;
}
// check that number of columns and rows are sane
if(num_cols < 0)
{
fprintf(stderr,"IOError: readDMAT() number of columns %d < 0\n",num_cols);
return false;
}
if(num_rows < 0)
{
fprintf(stderr,"IOError: readDMAT() number of rows %d < 0\n",num_rows);
return false;
}
return true;
}
#ifndef IGL_NO_EIGEN
template <typename DerivedW>
IGL_INLINE bool igl::readDMAT(const std::string file_name,
Eigen::PlainObjectBase<DerivedW> & W)
{
FILE * fp = fopen(file_name.c_str(),"r");
if(fp == NULL)
{
fprintf(stderr,"IOError: readDMAT() could not open %s...\n",file_name.c_str());
return false;
}
int num_rows,num_cols;
bool head_success = readDMAT_read_header(fp,num_rows,num_cols);
if(!head_success)
{
fclose(fp);
return false;
}
// Resize output to fit matrix
W.resize(num_rows,num_cols);
// Loop over columns slowly
for(int j = 0;j < num_cols;j++)
{
// loop over rows (down columns) quickly
for(int i = 0;i < num_rows;i++)
{
double d;
if(fscanf(fp," %lg",&d) != 1)
{
fclose(fp);
fprintf(
stderr,
"IOError: readDMAT() bad format after reading %d entries\n",
j*num_rows + i);
return false;
}
W(i,j) = d;
}
}
fclose(fp);
return true;
}
#endif
template <typename Scalar>
IGL_INLINE bool igl::readDMAT(
const std::string file_name,
std::vector<std::vector<Scalar> > & W)
{
FILE * fp = fopen(file_name.c_str(),"r");
if(fp == NULL)
{
fprintf(stderr,"IOError: readDMAT() could not open %s...\n",file_name.c_str());
return false;
}
int num_rows,num_cols;
bool head_success = readDMAT_read_header(fp,num_rows,num_cols);
if(!head_success)
{
fclose(fp);
return false;
}
// Resize for output
W.resize(num_rows,typename std::vector<Scalar>(num_cols));
// Loop over columns slowly
for(int j = 0;j < num_cols;j++)
{
// loop over rows (down columns) quickly
for(int i = 0;i < num_rows;i++)
{
double d;
if(fscanf(fp," %lg",&d) != 1)
{
fclose(fp);
fprintf(
stderr,
"IOError: readDMAT() bad format after reading %d entries\n",
j*num_rows + i);
return false;
}
W[i][j] = (Scalar)d;
}
}
fclose(fp);
return true;
}
#ifndef IGL_HEADER_ONLY
// Explicit template specialization
template bool igl::readDMAT<Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&);
#endif
<|endoftext|> |
<commit_before>#include "command.h"
#include "image.h"
#include "algo/loop.h"
#include "math/math.h"
#include "image/average_space.h"
#include "interp/linear.h"
#include "interp/nearest.h"
#include "interp/cubic.h"
#include "interp/sinc.h"
#include "filter/reslice.h"
using namespace MR;
using namespace App;
const char* interp_choices[] = { "nearest", "linear", "cubic", "sinc", NULL }; // TODO
const char* space_choices[] = { "voxel", "image1", "image2", "average", NULL };
template <class ValueType>
inline void meansquared (const ValueType& value1,
const ValueType& value2,
Eigen::Matrix<ValueType, Eigen::Dynamic, 1>& cost){
cost.array() += Math::pow2 (value1 - value2);
}
template <class ValueType>
inline void meansquared (const Eigen::Matrix<ValueType,Eigen::Dynamic, 1>& value1,
const Eigen::Matrix<ValueType,Eigen::Dynamic, 1>& value2,
Eigen::Matrix<ValueType, Eigen::Dynamic, 1>& cost) {
cost.array() += (value1 - value2).array().square();
}
// TODO: there must be a better way of doing this?
template <class ImageType1, class ImageType2, class TransformType, class OversampleType, class ValueType>
void reslice(size_t interp, ImageType1& input, ImageType2& output, const TransformType& trafo = Adapter::NoTransform, const OversampleType& oversample = Adapter::AutoOverSample, const ValueType out_of_bounds_value = 0.f){
switch(interp){
case 0:
Filter::reslice<Interp::Nearest> (input, output, trafo, Adapter::AutoOverSample, out_of_bounds_value);
DEBUG("Nearest");
break;
case 1:
Filter::reslice<Interp::Linear> (input, output, trafo, Adapter::AutoOverSample, out_of_bounds_value);
DEBUG("Linear");
break;
case 2:
Filter::reslice<Interp::Cubic> (input, output, trafo, Adapter::AutoOverSample, out_of_bounds_value);
DEBUG("Cubic");
break;
case 3:
Filter::reslice<Interp::Sinc> (input, output, trafo, Adapter::AutoOverSample, out_of_bounds_value);
DEBUG("Sinc");
break;
default:
throw Exception ("Fixme: interpolation value invalid");
}
}
void usage ()
{
AUTHOR = "David Raffelt (david.raffelt@florey.edu.au)";
DESCRIPTION
+ "computes a dissimilarity metric between two images. Currently only the mean squared difference is implemented";
ARGUMENTS
+ Argument ("image1", "the first input image.").type_image_in ()
+ Argument ("image2", "the second input image.").type_image_in ();
OPTIONS
+ Option ("space",
"voxel (default): per voxel "
"image1: scanner space of image 1 "
"image2: scanner space of image 2 "
"average: scanner space of the average affine transformation of image 1 and 2 ")
+ Argument ("iteration method").type_choice (space_choices)
+ Option ("interp",
"set the interpolation method to use when reslicing (choices: nearest, linear, cubic, sinc. Default: cubic).")
+ Argument ("method").type_choice (interp_choices)
+ Option ("mask1", "mask for image 1")
+ Argument ("image").type_image_in ()
+ Option ("mask2", "mask for image 2")
+ Argument ("image").type_image_in ()
+ Option ("nonormalisation",
"do not normalise the dissimilarity metric to the number of voxels.")
+ Option ("overlap",
"output number of voxels that were used.");
}
typedef double value_type;
typedef Image<bool> MaskType;
void run ()
{
auto input1 = Image<value_type>::open (argument[0]).with_direct_io (Stride::contiguous_along_axis (3));;
auto input2 = Image<value_type>::open (argument[1]).with_direct_io (Stride::contiguous_along_axis (3));;
const size_t dimensions = input1.ndim();
if (input1.ndim() != input2.ndim())
throw Exception ("both images have to have the same number of dimensions");
DEBUG("dimensions: " + str(dimensions));
if (dimensions > 4) throw Exception ("images have to be 3D or 4D");
size_t volumes(1);
if (dimensions == 4) {
volumes = input1.size(3);
if (input1.size(3) != input2.size(3)){
throw Exception ("both images have to have the same number of volumes");
}
}
DEBUG("volumes: " + str(volumes));
int space = 0; // voxel
auto opt = get_options ("space");
if (opt.size())
space = opt[0][0];
MaskType mask1;
bool use_mask1 = get_options ("mask1").size()==1;
if (use_mask1) {
mask1 = Image<bool>::open(get_options ("mask1")[0][0]);
if (mask1.ndim() != 3) throw Exception ("mask has to be 3D");
}
MaskType mask2;
bool use_mask2 = get_options ("mask2").size()==1;
if (use_mask2){
mask2 = Image<bool>::open(get_options ("mask2")[0][0]);
if (mask2.ndim() != 3) throw Exception ("mask has to be 3D");
}
bool nonormalisation = false;
if (get_options ("nonormalisation").size())
nonormalisation = true;
ssize_t n_voxels = input1.size(0) * input1.size(1) * input1.size(2);
value_type out_of_bounds_value = 0.0;
Eigen::Matrix<value_type, Eigen::Dynamic, 1> sos = Eigen::Matrix<value_type, Eigen::Dynamic, 1>::Zero (volumes);
if (space==0){
DEBUG("per-voxel");
check_dimensions (input1, input2);
if (use_mask1 or use_mask2)
n_voxels = 0;
if (use_mask1 and use_mask2) {
if (dimensions == 3) {
for (auto i = Loop() (input1, input2, mask1, mask2); i ;++i)
if (mask1.value() and mask2.value()){
++n_voxels;
meansquared<value_type>(input1.value(), input2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (input1, input2, mask1, mask2); i ;++i) {
if (mask1.value() and mask2.value()){
++n_voxels;
meansquared<value_type>(input1.row(3), input2.row(3), sos);
}
}
}
} else if (use_mask1) {
if (dimensions == 3) {
for (auto i = Loop() (input1, input2, mask1); i ;++i)
if (mask1.value()){
++n_voxels;
meansquared<value_type>(input1.value(), input2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (input1, input2, mask1); i ;++i) {
if (mask1.value()){
++n_voxels;
meansquared<value_type>(input1.row(3), input2.row(3), sos);
}
}
}
} else if (use_mask2){
if (dimensions == 3) {
for (auto i = Loop() (input1, input2, mask2); i ;++i)
if (mask2.value()){
++n_voxels;
meansquared<value_type>(input1.value(), input2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (input1, input2, mask2); i ;++i) {
if (mask2.value()){
++n_voxels;
meansquared<value_type>(input1.row(3), input2.row(3), sos);
}
}
}
} else {
for (auto i = Loop() (input1, input2); i ;++i)
meansquared<value_type>(input1.value(), input2.value(), sos);
}
} else {
DEBUG("scanner space");
int interp = 2; // cubic
opt = get_options ("interp");
if (opt.size())
interp = opt[0][0];
auto output1 = Header::scratch(input1.original_header(),"-").get_image<value_type>();
auto output2 = Header::scratch(input2.original_header(),"-").get_image<value_type>();
MaskType output1mask;
MaskType output2mask;
if (space == 1){
DEBUG("image 1");
output1 = input1;
output1mask = mask1;
output2 = Header::scratch(input1.original_header(),"-").get_image<value_type>();
output2mask = Header::scratch(input1.original_header(),"-").get_image<bool>();
{
LogLevelLatch log_level (0);
reslice(interp,input2, output2, Adapter::NoTransform, Adapter::AutoOverSample, out_of_bounds_value);
if (use_mask2)
Filter::reslice<Interp::Nearest> (mask2, output2mask, Adapter::NoTransform, Adapter::AutoOverSample, 0);
}
}
if (space == 2) {
DEBUG("image 2");
output1 = Header::scratch(input2.original_header(),"-").get_image<value_type>();
output1mask = Header::scratch(input2.original_header(),"-").get_image<bool>();
output2 = input2;
output2mask = mask2;
{
LogLevelLatch log_level (0);
reslice(interp, input1, output1, Adapter::NoTransform, Adapter::AutoOverSample, out_of_bounds_value);
if (use_mask1)
Filter::reslice<Interp::Nearest> (mask1, output1mask, Adapter::NoTransform, Adapter::AutoOverSample, 0);
}
n_voxels = input2.size(0) * input2.size(1) * input2.size(2);
}
if (space == 3) {
DEBUG("average space");
std::vector<Header> headers;
headers.push_back (input1.original_header());
headers.push_back (input2.original_header());
default_type template_res = 1.0;
auto padding = Eigen::Matrix<default_type, 4, 1>(0, 0, 0, 1.0);
std::vector<Eigen::Transform<double, 3, Eigen::Projective>> transform_header_with;
auto template_header = compute_minimum_average_header<double,Eigen::Transform<double, 3, Eigen::Projective>>(headers, template_res, padding, transform_header_with);
template_header.set_ndim(input1.ndim());
output1 = Image<value_type>::scratch(input1.original_header(),"-");
output2 = Image<value_type>::scratch(input1.original_header(),"-");
output1mask = Header::scratch(template_header,"-").get_image<bool>();
output2mask = Header::scratch(template_header,"-").get_image<bool>();
{
LogLevelLatch log_level (0);
reslice(interp, input1, output1, Adapter::NoTransform, Adapter::AutoOverSample, out_of_bounds_value);
reslice(interp, input2, output2, Adapter::NoTransform, Adapter::AutoOverSample, out_of_bounds_value);
if (use_mask1)
Filter::reslice<Interp::Nearest> (mask1, output1mask, Adapter::NoTransform, Adapter::AutoOverSample, 0);
if (use_mask2)
Filter::reslice<Interp::Nearest> (mask2, output2mask, Adapter::NoTransform, Adapter::AutoOverSample, 0);
}
n_voxels = output1.size(0) * output1.size(1) * output1.size(2);
}
if (use_mask1 or use_mask2)
n_voxels = 0;
if (use_mask1 and use_mask2){
if (dimensions == 3) {
for (auto i = Loop() (output1, output2, output1mask, output2mask); i ;++i)
if (output1mask.value() and output2mask.value()){
++n_voxels;
meansquared<value_type>(output1.value(), output2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (output1, output2, output1mask, output2mask); i ;++i) {
if (output1mask.value() and output2mask.value()){
++n_voxels;
meansquared<value_type>(output1.row(3), output2.row(3), sos);
}
}
}
} else if (use_mask1){
if (dimensions == 3) {
for (auto i = Loop() (output1, output2, output1mask); i ;++i)
if (output1mask.value()){
++n_voxels;
meansquared<value_type>(output1.value(), output2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (output1, output2, output1mask); i ;++i) {
if (output1mask.value()){
++n_voxels;
meansquared<value_type>(output1.row(3), output2.row(3), sos);
}
}
}
} else if (use_mask2){
if (dimensions == 3) {
for (auto i = Loop() (output1, output2, output2mask); i ;++i)
if (output2mask.value()){
++n_voxels;
meansquared<value_type>(output1.value(), output2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (output1, output2, output2mask); i ;++i) {
if (output2mask.value()){
++n_voxels;
meansquared<value_type>(output1.row(3), output2.row(3), sos);
}
}
}
} else {
if (dimensions == 3) {
for (auto i = Loop() (output1, output2); i ;++i)
meansquared<value_type>(output1.value(), output2.value(), sos);
} else { // 4D
for (auto i = Loop(0, 3) (output1, output2); i ;++i)
meansquared<value_type>(output1.row(3), output2.row(3), sos);
}
}
}
DEBUG ("n_voxels:" + str(n_voxels));
if (n_voxels==0)
WARN("number of overlapping voxels is zero");
if (!nonormalisation)
sos.array() /= static_cast<value_type>(n_voxels);
std::cout << str(sos.transpose()) << std::endl;
if (get_options ("overlap").size())
std::cout << str(n_voxels) << std::endl;
}
<commit_msg>mrmetric: fixed goof up introduced in previous commit<commit_after>#include "command.h"
#include "image.h"
#include "algo/loop.h"
#include "math/math.h"
#include "image/average_space.h"
#include "interp/linear.h"
#include "interp/nearest.h"
#include "interp/cubic.h"
#include "interp/sinc.h"
#include "filter/reslice.h"
using namespace MR;
using namespace App;
const char* interp_choices[] = { "nearest", "linear", "cubic", "sinc", NULL }; // TODO
const char* space_choices[] = { "voxel", "image1", "image2", "average", NULL };
template <class ValueType>
inline void meansquared (const ValueType& value1,
const ValueType& value2,
Eigen::Matrix<ValueType, Eigen::Dynamic, 1>& cost){
cost.array() += Math::pow2 (value1 - value2);
}
template <class ValueType>
inline void meansquared (const Eigen::Matrix<ValueType,Eigen::Dynamic, 1>& value1,
const Eigen::Matrix<ValueType,Eigen::Dynamic, 1>& value2,
Eigen::Matrix<ValueType, Eigen::Dynamic, 1>& cost) {
cost.array() += (value1 - value2).array().square();
}
// TODO: there must be a better way of doing this?
template <class ImageType1, class ImageType2, class TransformType, class OversampleType, class ValueType>
void reslice(size_t interp, ImageType1& input, ImageType2& output, const TransformType& trafo = Adapter::NoTransform, const OversampleType& oversample = Adapter::AutoOverSample, const ValueType out_of_bounds_value = 0.f){
switch(interp){
case 0:
Filter::reslice<Interp::Nearest> (input, output, trafo, Adapter::AutoOverSample, out_of_bounds_value);
DEBUG("Nearest");
break;
case 1:
Filter::reslice<Interp::Linear> (input, output, trafo, Adapter::AutoOverSample, out_of_bounds_value);
DEBUG("Linear");
break;
case 2:
Filter::reslice<Interp::Cubic> (input, output, trafo, Adapter::AutoOverSample, out_of_bounds_value);
DEBUG("Cubic");
break;
case 3:
Filter::reslice<Interp::Sinc> (input, output, trafo, Adapter::AutoOverSample, out_of_bounds_value);
DEBUG("Sinc");
break;
default:
throw Exception ("Fixme: interpolation value invalid");
}
}
void usage ()
{
AUTHOR = "David Raffelt (david.raffelt@florey.edu.au)";
DESCRIPTION
+ "computes a dissimilarity metric between two images. Currently only the mean squared difference is implemented";
ARGUMENTS
+ Argument ("image1", "the first input image.").type_image_in ()
+ Argument ("image2", "the second input image.").type_image_in ();
OPTIONS
+ Option ("space",
"voxel (default): per voxel "
"image1: scanner space of image 1 "
"image2: scanner space of image 2 "
"average: scanner space of the average affine transformation of image 1 and 2 ")
+ Argument ("iteration method").type_choice (space_choices)
+ Option ("interp",
"set the interpolation method to use when reslicing (choices: nearest, linear, cubic, sinc. Default: cubic).")
+ Argument ("method").type_choice (interp_choices)
+ Option ("mask1", "mask for image 1")
+ Argument ("image").type_image_in ()
+ Option ("mask2", "mask for image 2")
+ Argument ("image").type_image_in ()
+ Option ("nonormalisation",
"do not normalise the dissimilarity metric to the number of voxels.")
+ Option ("overlap",
"output number of voxels that were used.");
}
typedef double value_type;
typedef Image<bool> MaskType;
void run ()
{
auto input1 = Image<value_type>::open (argument[0]).with_direct_io (Stride::contiguous_along_axis (3));;
auto input2 = Image<value_type>::open (argument[1]).with_direct_io (Stride::contiguous_along_axis (3));;
const size_t dimensions = input1.ndim();
if (input1.ndim() != input2.ndim())
throw Exception ("both images have to have the same number of dimensions");
DEBUG("dimensions: " + str(dimensions));
if (dimensions > 4) throw Exception ("images have to be 3D or 4D");
size_t volumes(1);
if (dimensions == 4) {
volumes = input1.size(3);
if (input1.size(3) != input2.size(3)){
throw Exception ("both images have to have the same number of volumes");
}
}
DEBUG("volumes: " + str(volumes));
int space = 0; // voxel
auto opt = get_options ("space");
if (opt.size())
space = opt[0][0];
MaskType mask1;
bool use_mask1 = get_options ("mask1").size()==1;
if (use_mask1) {
mask1 = Image<bool>::open(get_options ("mask1")[0][0]);
if (mask1.ndim() != 3) throw Exception ("mask has to be 3D");
}
MaskType mask2;
bool use_mask2 = get_options ("mask2").size()==1;
if (use_mask2){
mask2 = Image<bool>::open(get_options ("mask2")[0][0]);
if (mask2.ndim() != 3) throw Exception ("mask has to be 3D");
}
bool nonormalisation = false;
if (get_options ("nonormalisation").size())
nonormalisation = true;
ssize_t n_voxels = input1.size(0) * input1.size(1) * input1.size(2);
value_type out_of_bounds_value = 0.0;
Eigen::Matrix<value_type, Eigen::Dynamic, 1> sos = Eigen::Matrix<value_type, Eigen::Dynamic, 1>::Zero (volumes);
if (space==0){
DEBUG("per-voxel");
check_dimensions (input1, input2);
if (use_mask1 or use_mask2)
n_voxels = 0;
if (use_mask1 and use_mask2) {
if (dimensions == 3) {
for (auto i = Loop() (input1, input2, mask1, mask2); i ;++i)
if (mask1.value() and mask2.value()){
++n_voxels;
meansquared<value_type>(input1.value(), input2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (input1, input2, mask1, mask2); i ;++i) {
if (mask1.value() and mask2.value()){
++n_voxels;
meansquared<value_type>(input1.row(3), input2.row(3), sos);
}
}
}
} else if (use_mask1) {
if (dimensions == 3) {
for (auto i = Loop() (input1, input2, mask1); i ;++i)
if (mask1.value()){
++n_voxels;
meansquared<value_type>(input1.value(), input2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (input1, input2, mask1); i ;++i) {
if (mask1.value()){
++n_voxels;
meansquared<value_type>(input1.row(3), input2.row(3), sos);
}
}
}
} else if (use_mask2){
if (dimensions == 3) {
for (auto i = Loop() (input1, input2, mask2); i ;++i)
if (mask2.value()){
++n_voxels;
meansquared<value_type>(input1.value(), input2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (input1, input2, mask2); i ;++i) {
if (mask2.value()){
++n_voxels;
meansquared<value_type>(input1.row(3), input2.row(3), sos);
}
}
}
} else {
for (auto i = Loop() (input1, input2); i ;++i)
meansquared<value_type>(input1.value(), input2.value(), sos);
}
} else {
DEBUG("scanner space");
int interp = 2; // cubic
opt = get_options ("interp");
if (opt.size())
interp = opt[0][0];
auto output1 = Header::scratch(input1.original_header(),"-").get_image<value_type>();
auto output2 = Header::scratch(input2.original_header(),"-").get_image<value_type>();
MaskType output1mask;
MaskType output2mask;
if (space == 1){
DEBUG("image 1");
output1 = input1;
output1mask = mask1;
output2 = Header::scratch(input1.original_header(),"-").get_image<value_type>();
output2mask = Header::scratch(input1.original_header(),"-").get_image<bool>();
{
LogLevelLatch log_level (0);
reslice(interp,input2, output2, Adapter::NoTransform, Adapter::AutoOverSample, out_of_bounds_value);
if (use_mask2)
Filter::reslice<Interp::Nearest> (mask2, output2mask, Adapter::NoTransform, Adapter::AutoOverSample, 0);
}
}
if (space == 2) {
DEBUG("image 2");
output1 = Header::scratch(input2.original_header(),"-").get_image<value_type>();
output1mask = Header::scratch(input2.original_header(),"-").get_image<bool>();
output2 = input2;
output2mask = mask2;
{
LogLevelLatch log_level (0);
reslice(interp, input1, output1, Adapter::NoTransform, Adapter::AutoOverSample, out_of_bounds_value);
if (use_mask1)
Filter::reslice<Interp::Nearest> (mask1, output1mask, Adapter::NoTransform, Adapter::AutoOverSample, 0);
}
n_voxels = input2.size(0) * input2.size(1) * input2.size(2);
}
if (space == 3) {
DEBUG("average space");
std::vector<Header> headers;
headers.push_back (input1.original_header());
headers.push_back (input2.original_header());
default_type template_res = 1.0;
auto padding = Eigen::Matrix<default_type, 4, 1>(0, 0, 0, 1.0);
std::vector<Eigen::Transform<double, 3, Eigen::Projective>> transform_header_with;
auto template_header = compute_minimum_average_header<double,Eigen::Transform<double, 3, Eigen::Projective>>(headers, template_res, padding, transform_header_with);
template_header.set_ndim(input1.ndim());
output1 = Image<value_type>::scratch(template_header,"-");
output2 = Image<value_type>::scratch(template_header,"-");
output1mask = Header::scratch(template_header,"-").get_image<bool>();
output2mask = Header::scratch(template_header,"-").get_image<bool>();
{
LogLevelLatch log_level (0);
reslice(interp, input1, output1, Adapter::NoTransform, Adapter::AutoOverSample, out_of_bounds_value);
reslice(interp, input2, output2, Adapter::NoTransform, Adapter::AutoOverSample, out_of_bounds_value);
if (use_mask1)
Filter::reslice<Interp::Nearest> (mask1, output1mask, Adapter::NoTransform, Adapter::AutoOverSample, 0);
if (use_mask2)
Filter::reslice<Interp::Nearest> (mask2, output2mask, Adapter::NoTransform, Adapter::AutoOverSample, 0);
}
n_voxels = output1.size(0) * output1.size(1) * output1.size(2);
}
if (use_mask1 or use_mask2)
n_voxels = 0;
if (use_mask1 and use_mask2){
if (dimensions == 3) {
for (auto i = Loop() (output1, output2, output1mask, output2mask); i ;++i)
if (output1mask.value() and output2mask.value()){
++n_voxels;
meansquared<value_type>(output1.value(), output2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (output1, output2, output1mask, output2mask); i ;++i) {
if (output1mask.value() and output2mask.value()){
++n_voxels;
meansquared<value_type>(output1.row(3), output2.row(3), sos);
}
}
}
} else if (use_mask1){
if (dimensions == 3) {
for (auto i = Loop() (output1, output2, output1mask); i ;++i)
if (output1mask.value()){
++n_voxels;
meansquared<value_type>(output1.value(), output2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (output1, output2, output1mask); i ;++i) {
if (output1mask.value()){
++n_voxels;
meansquared<value_type>(output1.row(3), output2.row(3), sos);
}
}
}
} else if (use_mask2){
if (dimensions == 3) {
for (auto i = Loop() (output1, output2, output2mask); i ;++i)
if (output2mask.value()){
++n_voxels;
meansquared<value_type>(output1.value(), output2.value(), sos);
}
} else { // 4D
for (auto i = Loop(0, 3) (output1, output2, output2mask); i ;++i) {
if (output2mask.value()){
++n_voxels;
meansquared<value_type>(output1.row(3), output2.row(3), sos);
}
}
}
} else {
if (dimensions == 3) {
for (auto i = Loop() (output1, output2); i ;++i)
meansquared<value_type>(output1.value(), output2.value(), sos);
} else { // 4D
for (auto i = Loop(0, 3) (output1, output2); i ;++i)
meansquared<value_type>(output1.row(3), output2.row(3), sos);
}
}
}
DEBUG ("n_voxels:" + str(n_voxels));
if (n_voxels==0)
WARN("number of overlapping voxels is zero");
if (!nonormalisation)
sos.array() /= static_cast<value_type>(n_voxels);
std::cout << str(sos.transpose()) << std::endl;
if (get_options ("overlap").size())
std::cout << str(n_voxels) << std::endl;
}
<|endoftext|> |
<commit_before>#pragma once
/**
@file
@brief operator class
@author MITSUNARI Shigeo(@herumi)
@license modified new BSD license
http://opensource.org/licenses/BSD-3-Clause
*/
#include <mcl/op.hpp>
#include <mcl/util.hpp>
#include <mcl/array_iterator.hpp>
#ifdef _MSC_VER
#ifndef MCL_FORCE_INLINE
#define MCL_FORCE_INLINE __forceinline
#endif
#pragma warning(push)
#pragma warning(disable : 4714)
#else
#ifndef MCL_FORCE_INLINE
#define MCL_FORCE_INLINE __attribute__((always_inline))
#endif
#endif
namespace mcl { namespace fp {
template<class T>
struct Empty {};
/*
T must have add, sub, mul, inv, neg
*/
template<class T, class E = Empty<T> >
struct Operator : public E {
template<class S> MCL_FORCE_INLINE T& operator+=(const S& rhs) { T::add(static_cast<T&>(*this), static_cast<const T&>(*this), rhs); return static_cast<T&>(*this); }
template<class S> MCL_FORCE_INLINE T& operator-=(const S& rhs) { T::sub(static_cast<T&>(*this), static_cast<const T&>(*this), rhs); return static_cast<T&>(*this); }
template<class S> friend MCL_FORCE_INLINE T operator+(const T& a, const S& b) { T c; T::add(c, a, b); return c; }
template<class S> friend MCL_FORCE_INLINE T operator-(const T& a, const S& b) { T c; T::sub(c, a, b); return c; }
template<class S> MCL_FORCE_INLINE T& operator*=(const S& rhs) { T::mul(static_cast<T&>(*this), static_cast<const T&>(*this), rhs); return static_cast<T&>(*this); }
template<class S> friend MCL_FORCE_INLINE T operator*(const T& a, const S& b) { T c; T::mul(c, a, b); return c; }
MCL_FORCE_INLINE T& operator/=(const T& rhs) { T c; T::inv(c, rhs); T::mul(static_cast<T&>(*this), static_cast<const T&>(*this), c); return static_cast<T&>(*this); }
static MCL_FORCE_INLINE void div(T& c, const T& a, const T& b) { T t; T::inv(t, b); T::mul(c, a, t); }
friend MCL_FORCE_INLINE T operator/(const T& a, const T& b) { T c; T::inv(c, b); c *= a; return c; }
MCL_FORCE_INLINE T operator-() const { T c; T::neg(c, static_cast<const T&>(*this)); return c; }
/*
powGeneric = pow if T = Fp, Fp2, Fp6
pow is for GT (use GLV method and unitaryInv)
powGeneric is for Fp12
*/
static void pow(T& z, const T& x, const Unit *y, size_t yn, bool isNegative = false)
{
if (powArrayGLV && yn > 1) {
powArrayGLV(z, x, y, yn, isNegative, false);
return;
}
powArrayBase(z, x, y, yn, isNegative, false);
}
template<class tag2, size_t maxBitSize2, template<class _tag, size_t _maxBitSize> class FpT>
static void pow(T& z, const T& x, const FpT<tag2, maxBitSize2>& y)
{
fp::Block b;
y.getBlock(b);
pow(z, x, b.p, b.n);
}
static void pow(T& z, const T& x, int64_t y)
{
const uint64_t u = fp::abs_(y);
#if MCL_SIZEOF_UNIT == 8
pow(z, x, &u, 1, y < 0);
#else
uint32_t ua[2] = { uint32_t(u), uint32_t(u >> 32) };
size_t un = ua[1] ? 2 : 1;
pow(z, x, ua, un, y < 0);
#endif
}
static void pow(T& z, const T& x, const mpz_class& y)
{
pow(z, x, gmp::getUnit(y), gmp::getUnitSize(y), y < 0);
}
template<class tag2, size_t maxBitSize2, template<class _tag, size_t _maxBitSize> class FpT>
static void powGeneric(T& z, const T& x, const FpT<tag2, maxBitSize2>& y)
{
fp::Block b;
y.getBlock(b);
powArrayBase(z, x, b.p, b.n, false, false);
}
static void powGeneric(T& z, const T& x, const mpz_class& y)
{
powArrayBase(z, x, gmp::getUnit(y), gmp::getUnitSize(y), y < 0, false);
}
static void setPowArrayGLV(void f(T& z, const T& x, const Unit *y, size_t yn, bool isNegative, bool constTime), size_t g(T& z, const T *xVec, const mpz_class *yVec, size_t n) = 0)
{
powArrayGLV = f;
powVecNGLV = g;
}
static const size_t powVecMaxN = 16;
template<class tag, size_t maxBitSize, template<class _tag, size_t _maxBitSize>class FpT>
static void powVec(T& z, const T* xVec, const FpT<tag, maxBitSize> *yVec, size_t n)
{
assert(powVecNGLV);
T r;
r.setOne();
const size_t N = mcl::fp::maxMulVecNGLV;
mpz_class myVec[N];
while (n > 0) {
T t;
size_t tn = fp::min_(n, N);
for (size_t i = 0; i < tn; i++) {
bool b;
yVec[i].getMpz(&b, myVec[i]);
assert(b); (void)b;
}
size_t done = powVecNGLV(t, xVec, myVec, tn);
r *= t;
xVec += done;
yVec += done;
n -= done;
}
z = r;
}
private:
static void (*powArrayGLV)(T& z, const T& x, const Unit *y, size_t yn, bool isNegative, bool constTime);
static size_t (*powVecNGLV)(T& z, const T* xVec, const mpz_class *yVec, size_t n);
static void powArrayBase(T& z, const T& x, const Unit *y, size_t yn, bool isNegative, bool)
{
while (yn > 0 && y[yn - 1] == 0) {
yn--;
}
if (yn == 0 || (yn == 1 && y[0] == 1)) {
z = 1;
return;
}
const size_t w = 4;
const size_t N = 1 << w;
uint8_t idxTbl[sizeof(T) * 8 / w];
mcl::fp::ArrayIterator<Unit> iter(y, sizeof(Unit) * 8 * yn, w);
size_t idxN = 0;
while (iter.hasNext()) {
assert(idxN < sizeof(idxTbl));
idxTbl[idxN++] = iter.getNext();
}
assert(idxN > 0);
T tbl[N];
tbl[1] = x;
for (size_t i = 2; i < N; i++) {
tbl[i] = tbl[i-1] * x;
}
uint32_t idx = idxTbl[idxN - 1];
z = idx == 0 ? 1 : tbl[idx];
for (size_t i = 1; i < idxN; i++) {
for (size_t j = 0; j < w; j++) {
T::sqr(z, z);
}
idx = idxTbl[idxN - 1 - i];
if (idx) {
z *= tbl[idx];
}
}
if (isNegative) {
T::inv(z, z);
}
}
};
template<class T, class E>
void (*Operator<T, E>::powArrayGLV)(T& z, const T& x, const Unit *y, size_t yn, bool isNegative, bool constTime);
template<class T, class E>
size_t (*Operator<T, E>::powVecNGLV)(T& z, const T* xVec, const mpz_class *yVec, size_t n);
/*
T must have save and load
*/
template<class T, class E = Empty<T> >
struct Serializable : public E {
// may set *pb = false if the size of str is too large.
void setStr(bool *pb, const char *str, int ioMode = 0)
{
size_t len = strlen(str);
size_t n = deserialize(str, len, ioMode);
*pb = n > 0 && n == len;
}
// return strlen(buf) if success else 0
size_t getStr(char *buf, size_t maxBufSize, int ioMode = 0) const
{
size_t n = serialize(buf, maxBufSize, ioMode);
if (n == 0 || n == maxBufSize - 1) return 0;
buf[n] = '\0';
return n;
}
#ifndef CYBOZU_DONT_USE_STRING
// may throw exception if the size of str is too large.
void setStr(const std::string& str, int ioMode = 0)
{
cybozu::StringInputStream is(str);
static_cast<T&>(*this).load(is, ioMode);
}
void getStr(std::string& str, int ioMode = 0) const
{
str.clear();
cybozu::StringOutputStream os(str);
static_cast<const T&>(*this).save(os, ioMode);
}
std::string getStr(int ioMode = 0) const
{
std::string str;
getStr(str, ioMode);
return str;
}
std::string serializeToHexStr() const
{
std::string str(sizeof(T) * 2, 0);
size_t n = serialize(&str[0], str.size(), IoSerializeHexStr);
str.resize(n);
return str;
}
#ifndef CYBOZU_DONT_USE_EXCEPTION
void deserializeHexStr(const std::string& str)
{
size_t n = deserialize(str.c_str(), str.size(), IoSerializeHexStr);
if (n == 0) throw cybozu::Exception("bad str") << str;
}
#endif
#endif
// return written bytes
size_t serialize(void *buf, size_t maxBufSize, int ioMode = IoSerialize) const
{
cybozu::MemoryOutputStream os(buf, maxBufSize);
bool b;
static_cast<const T&>(*this).save(&b, os, ioMode);
return b ? os.getPos() : 0;
}
// return read bytes
size_t deserialize(const void *buf, size_t bufSize, int ioMode = IoSerialize)
{
cybozu::MemoryInputStream is(buf, bufSize);
bool b;
static_cast<T&>(*this).load(&b, is, ioMode);
return b ? is.getPos() : 0;
}
};
} } // mcl::fp
<commit_msg>fix condition of zero<commit_after>#pragma once
/**
@file
@brief operator class
@author MITSUNARI Shigeo(@herumi)
@license modified new BSD license
http://opensource.org/licenses/BSD-3-Clause
*/
#include <mcl/op.hpp>
#include <mcl/util.hpp>
#include <mcl/array_iterator.hpp>
#ifdef _MSC_VER
#ifndef MCL_FORCE_INLINE
#define MCL_FORCE_INLINE __forceinline
#endif
#pragma warning(push)
#pragma warning(disable : 4714)
#else
#ifndef MCL_FORCE_INLINE
#define MCL_FORCE_INLINE __attribute__((always_inline))
#endif
#endif
namespace mcl { namespace fp {
template<class T>
struct Empty {};
/*
T must have add, sub, mul, inv, neg
*/
template<class T, class E = Empty<T> >
struct Operator : public E {
template<class S> MCL_FORCE_INLINE T& operator+=(const S& rhs) { T::add(static_cast<T&>(*this), static_cast<const T&>(*this), rhs); return static_cast<T&>(*this); }
template<class S> MCL_FORCE_INLINE T& operator-=(const S& rhs) { T::sub(static_cast<T&>(*this), static_cast<const T&>(*this), rhs); return static_cast<T&>(*this); }
template<class S> friend MCL_FORCE_INLINE T operator+(const T& a, const S& b) { T c; T::add(c, a, b); return c; }
template<class S> friend MCL_FORCE_INLINE T operator-(const T& a, const S& b) { T c; T::sub(c, a, b); return c; }
template<class S> MCL_FORCE_INLINE T& operator*=(const S& rhs) { T::mul(static_cast<T&>(*this), static_cast<const T&>(*this), rhs); return static_cast<T&>(*this); }
template<class S> friend MCL_FORCE_INLINE T operator*(const T& a, const S& b) { T c; T::mul(c, a, b); return c; }
MCL_FORCE_INLINE T& operator/=(const T& rhs) { T c; T::inv(c, rhs); T::mul(static_cast<T&>(*this), static_cast<const T&>(*this), c); return static_cast<T&>(*this); }
static MCL_FORCE_INLINE void div(T& c, const T& a, const T& b) { T t; T::inv(t, b); T::mul(c, a, t); }
friend MCL_FORCE_INLINE T operator/(const T& a, const T& b) { T c; T::inv(c, b); c *= a; return c; }
MCL_FORCE_INLINE T operator-() const { T c; T::neg(c, static_cast<const T&>(*this)); return c; }
/*
powGeneric = pow if T = Fp, Fp2, Fp6
pow is for GT (use GLV method and unitaryInv)
powGeneric is for Fp12
*/
static void pow(T& z, const T& x, const Unit *y, size_t yn, bool isNegative = false)
{
if (powArrayGLV && yn > 1) {
powArrayGLV(z, x, y, yn, isNegative, false);
return;
}
powArrayBase(z, x, y, yn, isNegative, false);
}
template<class tag2, size_t maxBitSize2, template<class _tag, size_t _maxBitSize> class FpT>
static void pow(T& z, const T& x, const FpT<tag2, maxBitSize2>& y)
{
fp::Block b;
y.getBlock(b);
pow(z, x, b.p, b.n);
}
static void pow(T& z, const T& x, int64_t y)
{
const uint64_t u = fp::abs_(y);
#if MCL_SIZEOF_UNIT == 8
pow(z, x, &u, 1, y < 0);
#else
uint32_t ua[2] = { uint32_t(u), uint32_t(u >> 32) };
size_t un = ua[1] ? 2 : 1;
pow(z, x, ua, un, y < 0);
#endif
}
static void pow(T& z, const T& x, const mpz_class& y)
{
pow(z, x, gmp::getUnit(y), gmp::getUnitSize(y), y < 0);
}
template<class tag2, size_t maxBitSize2, template<class _tag, size_t _maxBitSize> class FpT>
static void powGeneric(T& z, const T& x, const FpT<tag2, maxBitSize2>& y)
{
fp::Block b;
y.getBlock(b);
powArrayBase(z, x, b.p, b.n, false, false);
}
static void powGeneric(T& z, const T& x, const mpz_class& y)
{
powArrayBase(z, x, gmp::getUnit(y), gmp::getUnitSize(y), y < 0, false);
}
static void setPowArrayGLV(void f(T& z, const T& x, const Unit *y, size_t yn, bool isNegative, bool constTime), size_t g(T& z, const T *xVec, const mpz_class *yVec, size_t n) = 0)
{
powArrayGLV = f;
powVecNGLV = g;
}
static const size_t powVecMaxN = 16;
template<class tag, size_t maxBitSize, template<class _tag, size_t _maxBitSize>class FpT>
static void powVec(T& z, const T* xVec, const FpT<tag, maxBitSize> *yVec, size_t n)
{
assert(powVecNGLV);
T r;
r.setOne();
const size_t N = mcl::fp::maxMulVecNGLV;
mpz_class myVec[N];
while (n > 0) {
T t;
size_t tn = fp::min_(n, N);
for (size_t i = 0; i < tn; i++) {
bool b;
yVec[i].getMpz(&b, myVec[i]);
assert(b); (void)b;
}
size_t done = powVecNGLV(t, xVec, myVec, tn);
r *= t;
xVec += done;
yVec += done;
n -= done;
}
z = r;
}
private:
static void (*powArrayGLV)(T& z, const T& x, const Unit *y, size_t yn, bool isNegative, bool constTime);
static size_t (*powVecNGLV)(T& z, const T* xVec, const mpz_class *yVec, size_t n);
static void powArrayBase(T& z, const T& x, const Unit *y, size_t yn, bool isNegative, bool)
{
while (yn > 0 && y[yn - 1] == 0) {
yn--;
}
if (yn == 0) {
z = 1;
return;
}
const size_t w = 4;
const size_t N = 1 << w;
uint8_t idxTbl[sizeof(T) * 8 / w];
mcl::fp::ArrayIterator<Unit> iter(y, sizeof(Unit) * 8 * yn, w);
size_t idxN = 0;
while (iter.hasNext()) {
assert(idxN < sizeof(idxTbl));
idxTbl[idxN++] = iter.getNext();
}
assert(idxN > 0);
T tbl[N];
tbl[1] = x;
for (size_t i = 2; i < N; i++) {
tbl[i] = tbl[i-1] * x;
}
uint32_t idx = idxTbl[idxN - 1];
z = idx == 0 ? 1 : tbl[idx];
for (size_t i = 1; i < idxN; i++) {
for (size_t j = 0; j < w; j++) {
T::sqr(z, z);
}
idx = idxTbl[idxN - 1 - i];
if (idx) {
z *= tbl[idx];
}
}
if (isNegative) {
T::inv(z, z);
}
}
};
template<class T, class E>
void (*Operator<T, E>::powArrayGLV)(T& z, const T& x, const Unit *y, size_t yn, bool isNegative, bool constTime);
template<class T, class E>
size_t (*Operator<T, E>::powVecNGLV)(T& z, const T* xVec, const mpz_class *yVec, size_t n);
/*
T must have save and load
*/
template<class T, class E = Empty<T> >
struct Serializable : public E {
// may set *pb = false if the size of str is too large.
void setStr(bool *pb, const char *str, int ioMode = 0)
{
size_t len = strlen(str);
size_t n = deserialize(str, len, ioMode);
*pb = n > 0 && n == len;
}
// return strlen(buf) if success else 0
size_t getStr(char *buf, size_t maxBufSize, int ioMode = 0) const
{
size_t n = serialize(buf, maxBufSize, ioMode);
if (n == 0 || n == maxBufSize - 1) return 0;
buf[n] = '\0';
return n;
}
#ifndef CYBOZU_DONT_USE_STRING
// may throw exception if the size of str is too large.
void setStr(const std::string& str, int ioMode = 0)
{
cybozu::StringInputStream is(str);
static_cast<T&>(*this).load(is, ioMode);
}
void getStr(std::string& str, int ioMode = 0) const
{
str.clear();
cybozu::StringOutputStream os(str);
static_cast<const T&>(*this).save(os, ioMode);
}
std::string getStr(int ioMode = 0) const
{
std::string str;
getStr(str, ioMode);
return str;
}
std::string serializeToHexStr() const
{
std::string str(sizeof(T) * 2, 0);
size_t n = serialize(&str[0], str.size(), IoSerializeHexStr);
str.resize(n);
return str;
}
#ifndef CYBOZU_DONT_USE_EXCEPTION
void deserializeHexStr(const std::string& str)
{
size_t n = deserialize(str.c_str(), str.size(), IoSerializeHexStr);
if (n == 0) throw cybozu::Exception("bad str") << str;
}
#endif
#endif
// return written bytes
size_t serialize(void *buf, size_t maxBufSize, int ioMode = IoSerialize) const
{
cybozu::MemoryOutputStream os(buf, maxBufSize);
bool b;
static_cast<const T&>(*this).save(&b, os, ioMode);
return b ? os.getPos() : 0;
}
// return read bytes
size_t deserialize(const void *buf, size_t bufSize, int ioMode = IoSerialize)
{
cybozu::MemoryInputStream is(buf, bufSize);
bool b;
static_cast<T&>(*this).load(&b, is, ioMode);
return b ? is.getPos() : 0;
}
};
} } // mcl::fp
<|endoftext|> |
<commit_before>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// checkParsed.cpp
#include "passes.h"
#include "stmt.h"
#include "expr.h"
#include "astutil.h"
#include "stlUtil.h"
static void checkNamedArguments(CallExpr* call);
static void checkPrivateDecls(DefExpr* def);
static void checkParsedVar(VarSymbol* var);
static void checkFunction(FnSymbol* fn);
static void checkExportedNames();
static void checkModule(ModuleSymbol* mod);
void
checkParsed() {
forv_Vec(CallExpr, call, gCallExprs) {
checkNamedArguments(call);
}
forv_Vec(DefExpr, def, gDefExprs) {
if (toVarSymbol(def->sym))
// The test for FLAG_TEMP allows compiler-generated (temporary) variables
// to be declared without an explicit type or initializer expression.
if ((!def->init || def->init->isNoInitExpr())
&& !def->exprType && !def->sym->hasFlag(FLAG_TEMP))
if (isBlockStmt(def->parentExpr) && !isArgSymbol(def->parentSymbol))
if (def->parentExpr != rootModule->block)
if (!def->sym->hasFlag(FLAG_INDEX_VAR))
USR_FATAL_CONT(def->sym,
"Variable '%s' is not initialized or has no type",
def->sym->name);
checkPrivateDecls(def);
}
forv_Vec(VarSymbol, var, gVarSymbols) {
checkParsedVar(var);
}
forv_Vec(FnSymbol, fn, gFnSymbols) {
checkFunction(fn);
}
forv_Vec(ModuleSymbol, mod, gModuleSymbols) {
checkModule(mod);
}
checkExportedNames();
}
static void
checkNamedArguments(CallExpr* call) {
Vec<const char*> names;
for_actuals(expr, call) {
if (NamedExpr* named = toNamedExpr(expr)) {
forv_Vec(const char, name, names) {
if (!strcmp(name, named->name))
USR_FATAL_CONT(named,
"The named argument '%s' is used more "
"than once in the same function call.",
name);
}
names.add(named->name);
}
}
}
static void checkPrivateDecls(DefExpr* def) {
if (def->sym->hasFlag(FLAG_PRIVATE)) {
// The symbol has been declared private.
if (def->parentSymbol) {
if (toFnSymbol(def->parentSymbol)) {
// The parent symbol of this definition is a FnSymbol. Private
// symbols at the function scope are meaningless because there is no
// way for anything outside the function to access its locals, so warn
// the user.
USR_WARN(def,
"Private declarations within function bodies are meaningless");
// Don't want to waste time treating this symbol as if it could be
// accessed from an outer scope, so remove the flag.
def->sym->removeFlag(FLAG_PRIVATE);
} else if (ModuleSymbol *mod = toModuleSymbol(def->parentSymbol)) {
// The parent symbol is a module symbol. Could still be invalid.
if (mod->block != def->parentExpr) {
// The block in which we are defined is not the top level module
// block. Private symbols at this scope are meaningless, so warn
// the user.
USR_WARN(def,
"Private declarations within nested blocks are meaningless");
def->sym->removeFlag(FLAG_PRIVATE);
}
} else if (TypeSymbol *t = toTypeSymbol(def->parentSymbol)) {
if (toAggregateType(t->type)) {
USR_FATAL_CONT(def, "Can't apply private to the fields or methods of a class or record yet");
// Private fields and methods require further discussion before they
// are implemented.
}
}
}
}
}
static void
checkParsedVar(VarSymbol* var) {
if (var->isParameter() && !var->immediate)
if (!var->defPoint->init &&
(toFnSymbol(var->defPoint->parentSymbol) ||
toModuleSymbol(var->defPoint->parentSymbol)))
USR_FATAL_CONT(var, "Top-level params must be initialized.");
if (var->defPoint->init && var->defPoint->init->isNoInitExpr()) {
if (var->hasFlag(FLAG_CONST))
USR_FATAL_CONT(var, "const variables specified with noinit must be explicitly initialized.");
}
//
// Verify that config variables are only at Module scope i.e. it is
// an error if any config variable is not an immediate child of a
// module
if (var->hasFlag(FLAG_CONFIG) &&
isModuleSymbol(var->defPoint->parentSymbol) == false) {
const char* varType = NULL;
if (var->hasFlag(FLAG_PARAM))
varType = "parameters";
else if (var->hasFlag(FLAG_CONST))
varType = "constants";
else
varType = "variables";
USR_FATAL_CONT(var->defPoint,
"Configuration %s are allowed only at module scope.", varType);
}
}
static void
checkFunction(FnSymbol* fn) {
// Ensure that the lhs of "=" and "<op>=" is passed by ref.
if (fn->hasFlag(FLAG_ASSIGNOP))
if (fn->getFormal(1)->intent != INTENT_REF)
USR_WARN(fn, "The left operand of '=' and '<op>=' should have 'ref' intent.");
if (!strcmp(fn->name, "this") && fn->hasFlag(FLAG_NO_PARENS))
USR_FATAL_CONT(fn, "method 'this' must have parentheses");
if (!strcmp(fn->name, "these") && fn->hasFlag(FLAG_NO_PARENS))
USR_FATAL_CONT(fn, "method 'these' must have parentheses");
if (fn->retTag == RET_PARAM && fn->retExprType != NULL)
USR_WARN(fn, "providing an explicit return type on a 'param' function currently leads to incorrect results; as a workaround, remove the return type specification in function '%s'", fn->name);
std::vector<CallExpr*> calls;
collectMyCallExprs(fn, calls, fn);
bool isIterator = fn->isIterator();
bool notInAFunction = !isIterator && (fn->getModule()->initFn == fn);
int numVoidReturns = 0, numNonVoidReturns = 0, numYields = 0;
for_vector(CallExpr, call, calls) {
if (call->isPrimitive(PRIM_RETURN)) {
if (notInAFunction)
USR_FATAL_CONT(call, "return statement is not in a function or iterator");
else {
SymExpr* sym = toSymExpr(call->get(1));
if (sym && sym->var == gVoid)
numVoidReturns++;
else {
if (isIterator)
USR_FATAL_CONT(call, "returning a value in an iterator");
else
numNonVoidReturns++;
}
}
}
else if (call->isPrimitive(PRIM_YIELD)) {
if (notInAFunction)
USR_FATAL_CONT(call, "yield statement is outside an iterator");
else if (!isIterator)
USR_FATAL_CONT(call, "yield statement is in a non-iterator function");
else
numYields++;
}
}
if (numVoidReturns != 0 && numNonVoidReturns != 0)
USR_FATAL_CONT(fn, "Not all returns in this function return a value");
if (isIterator && numYields == 0)
USR_FATAL_CONT(fn, "iterator does not yield a value");
if (!isIterator &&
fn->retTag == RET_REF &&
numNonVoidReturns == 0) {
USR_FATAL_CONT(fn, "function declared 'var' but does not return anything");
}
}
//
// This is a special test to ensure that there are no instances of a return
// or yield statement at the top level of a module. This "special" semantic
// check is needed to resolve 4 test applications that failed once the
// insertion of a Module init function was moved to a later pass.
//
// Those tests have historically relied on the matching call in checkFunction
// which was executed when scanning the module initFunction.
//
// This is probably a good anchor for a family of tests of this form.
//
static void
checkModule(ModuleSymbol* mod) {
for_alist(stmt, mod->block->body) {
if (CallExpr* call = toCallExpr(stmt)) {
if (call->isPrimitive(PRIM_RETURN)) {
USR_FATAL_CONT(call, "return statement is not in a function or iterator");
} else if (call->isPrimitive(PRIM_YIELD)) {
USR_FATAL_CONT(call, "yield statement is outside an iterator");
}
}
}
}
static void
checkExportedNames()
{
// The right side of the map is a dummy Boolean.
// We are just using the map to implement a set.
HashMap<const char*, StringHashFns, bool> names;
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (!fn->hasFlag(FLAG_EXPORT))
continue;
const char* name = fn->cname;
if (names.get(name))
USR_FATAL_CONT(fn, "The name %s cannot be exported twice from the same compilation unit.", name);
names.put(name, true);
}
}
<commit_msg>Fix errors with warning message insertion for invalid private declarations<commit_after>/*
* Copyright 2004-2015 Cray Inc.
* Other additional copyright holders may be indicated within.
*
* The entirety of this work is licensed under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// checkParsed.cpp
#include "passes.h"
#include "stmt.h"
#include "expr.h"
#include "astutil.h"
#include "stlUtil.h"
static void checkNamedArguments(CallExpr* call);
static void checkPrivateDecls(DefExpr* def);
static void checkParsedVar(VarSymbol* var);
static void checkFunction(FnSymbol* fn);
static void checkExportedNames();
static void checkModule(ModuleSymbol* mod);
void
checkParsed() {
forv_Vec(CallExpr, call, gCallExprs) {
checkNamedArguments(call);
}
forv_Vec(DefExpr, def, gDefExprs) {
if (toVarSymbol(def->sym))
// The test for FLAG_TEMP allows compiler-generated (temporary) variables
// to be declared without an explicit type or initializer expression.
if ((!def->init || def->init->isNoInitExpr())
&& !def->exprType && !def->sym->hasFlag(FLAG_TEMP))
if (isBlockStmt(def->parentExpr) && !isArgSymbol(def->parentSymbol))
if (def->parentExpr != rootModule->block)
if (!def->sym->hasFlag(FLAG_INDEX_VAR))
USR_FATAL_CONT(def->sym,
"Variable '%s' is not initialized or has no type",
def->sym->name);
checkPrivateDecls(def);
}
forv_Vec(VarSymbol, var, gVarSymbols) {
checkParsedVar(var);
}
forv_Vec(FnSymbol, fn, gFnSymbols) {
checkFunction(fn);
}
forv_Vec(ModuleSymbol, mod, gModuleSymbols) {
checkModule(mod);
}
checkExportedNames();
}
static void
checkNamedArguments(CallExpr* call) {
Vec<const char*> names;
for_actuals(expr, call) {
if (NamedExpr* named = toNamedExpr(expr)) {
forv_Vec(const char, name, names) {
if (!strcmp(name, named->name))
USR_FATAL_CONT(named,
"The named argument '%s' is used more "
"than once in the same function call.",
name);
}
names.add(named->name);
}
}
}
static void checkPrivateDecls(DefExpr* def) {
if (def->sym->hasFlag(FLAG_PRIVATE)) {
// The symbol has been declared private.
if (def->parentSymbol) {
if (toFnSymbol(def->parentSymbol)) {
// The parent symbol of this definition is a FnSymbol. Private
// symbols at the function scope are meaningless because there is no
// way for anything outside the function to access its locals, so warn
// the user.
USR_WARN(def,
"Private declarations within function bodies are meaningless");
// Don't want to waste time treating this symbol as if it could be
// accessed from an outer scope, so remove the flag.
def->sym->removeFlag(FLAG_PRIVATE);
} else if (ModuleSymbol *mod = toModuleSymbol(def->parentSymbol)) {
// The parent symbol is a module symbol. Could still be invalid.
if (mod->block != def->parentExpr) {
if (BlockStmt* block = toBlockStmt(def->parentExpr)) {
// Scopeless blocks are used to define multiple symbols, for
// instance. Those are valid "nested" blocks for private symbols.
if (block->blockTag != BLOCK_SCOPELESS) {
// The block in which we are defined is not the top level module
// block. Private symbols at this scope are meaningless, so warn
// the user.
USR_WARN(def,
"Private declarations within nested blocks are meaningless");
def->sym->removeFlag(FLAG_PRIVATE);
}
} else {
// There are many situations which could lead to this else branch.
// Most of them will not reach here due to being banned at parse
// time. However, those that aren't excluded by syntax errors will
// be caught here.
USR_WARN(def, "Private declarations are meaningless outside of module level declarations");
def->sym->removeFlag(FLAG_PRIVATE);
}
}
} else if (TypeSymbol *t = toTypeSymbol(def->parentSymbol)) {
if (toAggregateType(t->type)) {
USR_FATAL_CONT(def, "Can't apply private to the fields or methods of a class or record yet");
// Private fields and methods require further discussion before they
// are implemented.
}
}
}
}
}
static void
checkParsedVar(VarSymbol* var) {
if (var->isParameter() && !var->immediate)
if (!var->defPoint->init &&
(toFnSymbol(var->defPoint->parentSymbol) ||
toModuleSymbol(var->defPoint->parentSymbol)))
USR_FATAL_CONT(var, "Top-level params must be initialized.");
if (var->defPoint->init && var->defPoint->init->isNoInitExpr()) {
if (var->hasFlag(FLAG_CONST))
USR_FATAL_CONT(var, "const variables specified with noinit must be explicitly initialized.");
}
//
// Verify that config variables are only at Module scope i.e. it is
// an error if any config variable is not an immediate child of a
// module
if (var->hasFlag(FLAG_CONFIG) &&
isModuleSymbol(var->defPoint->parentSymbol) == false) {
const char* varType = NULL;
if (var->hasFlag(FLAG_PARAM))
varType = "parameters";
else if (var->hasFlag(FLAG_CONST))
varType = "constants";
else
varType = "variables";
USR_FATAL_CONT(var->defPoint,
"Configuration %s are allowed only at module scope.", varType);
}
}
static void
checkFunction(FnSymbol* fn) {
// Ensure that the lhs of "=" and "<op>=" is passed by ref.
if (fn->hasFlag(FLAG_ASSIGNOP))
if (fn->getFormal(1)->intent != INTENT_REF)
USR_WARN(fn, "The left operand of '=' and '<op>=' should have 'ref' intent.");
if (!strcmp(fn->name, "this") && fn->hasFlag(FLAG_NO_PARENS))
USR_FATAL_CONT(fn, "method 'this' must have parentheses");
if (!strcmp(fn->name, "these") && fn->hasFlag(FLAG_NO_PARENS))
USR_FATAL_CONT(fn, "method 'these' must have parentheses");
if (fn->retTag == RET_PARAM && fn->retExprType != NULL)
USR_WARN(fn, "providing an explicit return type on a 'param' function currently leads to incorrect results; as a workaround, remove the return type specification in function '%s'", fn->name);
std::vector<CallExpr*> calls;
collectMyCallExprs(fn, calls, fn);
bool isIterator = fn->isIterator();
bool notInAFunction = !isIterator && (fn->getModule()->initFn == fn);
int numVoidReturns = 0, numNonVoidReturns = 0, numYields = 0;
for_vector(CallExpr, call, calls) {
if (call->isPrimitive(PRIM_RETURN)) {
if (notInAFunction)
USR_FATAL_CONT(call, "return statement is not in a function or iterator");
else {
SymExpr* sym = toSymExpr(call->get(1));
if (sym && sym->var == gVoid)
numVoidReturns++;
else {
if (isIterator)
USR_FATAL_CONT(call, "returning a value in an iterator");
else
numNonVoidReturns++;
}
}
}
else if (call->isPrimitive(PRIM_YIELD)) {
if (notInAFunction)
USR_FATAL_CONT(call, "yield statement is outside an iterator");
else if (!isIterator)
USR_FATAL_CONT(call, "yield statement is in a non-iterator function");
else
numYields++;
}
}
if (numVoidReturns != 0 && numNonVoidReturns != 0)
USR_FATAL_CONT(fn, "Not all returns in this function return a value");
if (isIterator && numYields == 0)
USR_FATAL_CONT(fn, "iterator does not yield a value");
if (!isIterator &&
fn->retTag == RET_REF &&
numNonVoidReturns == 0) {
USR_FATAL_CONT(fn, "function declared 'var' but does not return anything");
}
}
//
// This is a special test to ensure that there are no instances of a return
// or yield statement at the top level of a module. This "special" semantic
// check is needed to resolve 4 test applications that failed once the
// insertion of a Module init function was moved to a later pass.
//
// Those tests have historically relied on the matching call in checkFunction
// which was executed when scanning the module initFunction.
//
// This is probably a good anchor for a family of tests of this form.
//
static void
checkModule(ModuleSymbol* mod) {
for_alist(stmt, mod->block->body) {
if (CallExpr* call = toCallExpr(stmt)) {
if (call->isPrimitive(PRIM_RETURN)) {
USR_FATAL_CONT(call, "return statement is not in a function or iterator");
} else if (call->isPrimitive(PRIM_YIELD)) {
USR_FATAL_CONT(call, "yield statement is outside an iterator");
}
}
}
}
static void
checkExportedNames()
{
// The right side of the map is a dummy Boolean.
// We are just using the map to implement a set.
HashMap<const char*, StringHashFns, bool> names;
forv_Vec(FnSymbol, fn, gFnSymbols) {
if (!fn->hasFlag(FLAG_EXPORT))
continue;
const char* name = fn->cname;
if (names.get(name))
USR_FATAL_CONT(fn, "The name %s cannot be exported twice from the same compilation unit.", name);
names.put(name, true);
}
}
<|endoftext|> |
<commit_before>// Catch
#include <catch.hpp>
// C++ Standard Library
#include <cstdlib>
#include <cmath>
// Armadillo
#include <armadillo>
// HOP
#include <hop>
TEST_CASE("Random rotation matrix", "") {
SECTION("2-dimensional rotation") {
arma::Col<double>::fixed<10000> angles;
for (std::size_t n = 0; n < angles.n_elem; ++n) {
arma::Col<double>::fixed<2> rotatedUnitVector = hop::getRandomRotationMatrix(2) * arma::Col<double>::fixed<2>({-2, 1});
angles.at(n) = std::atan2(rotatedUnitVector.at(1), rotatedUnitVector.at(0));
}
arma::Col<arma::uword> histogram = arma::hist(angles);
CHECK(0.05 > static_cast<double>(histogram.max() - histogram.min()) / angles.n_elem);
}
SECTION("3-dimensional rotation") {
arma::Col<double>::fixed<10000> rollAngles;
arma::Col<double>::fixed<10000> pitchAngles;
arma::Col<double>::fixed<10000> yawAngles;
for (std::size_t n = 0; n < rollAngles.n_elem; ++n) {
arma::Col<double>::fixed<3> rotatedUnitVector = hop::getRandomRotationMatrix(3) * arma::Col<double>::fixed<3>({-2, 1, 3});
rollAngles.at(n) = std::atan2(rotatedUnitVector.at(1), rotatedUnitVector.at(0));
pitchAngles.at(n) = std::atan2(rotatedUnitVector.at(2), rotatedUnitVector.at(1));
yawAngles.at(n) = std::atan2(rotatedUnitVector.at(0), rotatedUnitVector.at(2));
}
arma::Col<arma::uword> histogram;
histogram = arma::hist(rollAngles);
CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / rollAngles.n_elem);
histogram = arma::hist(pitchAngles);
CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / pitchAngles.n_elem);
histogram = arma::hist(yawAngles);
CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / yawAngles.n_elem);
}
}
TEST_CASE("Random permutation", "") {
SECTION("Full permutation") {
arma::Mat<arma::uword>::fixed<10, 10000> permutations;
for (std::size_t n = 0; n < permutations.n_cols; ++n) {
permutations.col(n) = hop::getRandomPermutation(permutations.n_rows);
}
arma::Col<arma::uword> centers(permutations.n_rows);
for (std::size_t n = 0; n < permutations.n_rows; ++n) {
centers.at(n) = n;
}
for (std::size_t n = 0; n < permutations.n_rows; ++n) {
arma::Row<arma::uword> histogram = arma::hist(permutations.row(n), centers);
CHECK(0.05 > static_cast<double>(histogram.max() - histogram.min()) / permutations.n_cols);
}
}
SECTION("Partial permutation") {
arma::Mat<arma::uword>::fixed<10, 20000> permutations;
for (std::size_t n = 0; n < permutations.n_cols; ++n) {
permutations.col(n) = hop::getRandomPermutation(permutations.n_rows + 1, permutations.n_rows);
}
arma::Col<arma::uword> centers(permutations.n_rows);
for (std::size_t n = 0; n < permutations.n_rows; ++n) {
centers.at(n) = n;
}
for (std::size_t n = 0; n < permutations.n_rows; ++n) {
arma::Row<arma::uword> histogram = arma::hist(permutations.row(n), centers);
CHECK(0.1 > static_cast<double>(histogram.max() - histogram.min()) / permutations.n_cols);
}
}
}
<commit_msg>test: Increased sample size for permutation tests<commit_after>// Catch
#include <catch.hpp>
// C++ Standard Library
#include <cstdlib>
#include <cmath>
// Armadillo
#include <armadillo>
// HOP
#include <hop>
TEST_CASE("Random rotation matrix", "") {
SECTION("2-dimensional rotation") {
arma::Col<double>::fixed<10000> angles;
for (std::size_t n = 0; n < angles.n_elem; ++n) {
arma::Col<double>::fixed<2> rotatedUnitVector = hop::getRandomRotationMatrix(2) * arma::Col<double>::fixed<2>({-2, 1});
angles.at(n) = std::atan2(rotatedUnitVector.at(1), rotatedUnitVector.at(0));
}
arma::Col<arma::uword> histogram = arma::hist(angles);
CHECK(0.05 > static_cast<double>(histogram.max() - histogram.min()) / angles.n_elem);
}
SECTION("3-dimensional rotation") {
arma::Col<double>::fixed<10000> rollAngles;
arma::Col<double>::fixed<10000> pitchAngles;
arma::Col<double>::fixed<10000> yawAngles;
for (std::size_t n = 0; n < rollAngles.n_elem; ++n) {
arma::Col<double>::fixed<3> rotatedUnitVector = hop::getRandomRotationMatrix(3) * arma::Col<double>::fixed<3>({-2, 1, 3});
rollAngles.at(n) = std::atan2(rotatedUnitVector.at(1), rotatedUnitVector.at(0));
pitchAngles.at(n) = std::atan2(rotatedUnitVector.at(2), rotatedUnitVector.at(1));
yawAngles.at(n) = std::atan2(rotatedUnitVector.at(0), rotatedUnitVector.at(2));
}
arma::Col<arma::uword> histogram;
histogram = arma::hist(rollAngles);
CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / rollAngles.n_elem);
histogram = arma::hist(pitchAngles);
CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / pitchAngles.n_elem);
histogram = arma::hist(yawAngles);
CHECK(0.02 > static_cast<double>(histogram.max() - histogram.min()) / yawAngles.n_elem);
}
}
TEST_CASE("Random permutation", "") {
SECTION("Full permutation") {
arma::Mat<arma::uword>::fixed<10, 10000> permutations;
for (std::size_t n = 0; n < permutations.n_cols; ++n) {
permutations.col(n) = hop::getRandomPermutation(permutations.n_rows);
}
arma::Col<arma::uword> centers(permutations.n_rows);
for (std::size_t n = 0; n < permutations.n_rows; ++n) {
centers.at(n) = n;
}
for (std::size_t n = 0; n < permutations.n_rows; ++n) {
arma::Row<arma::uword> histogram = arma::hist(permutations.row(n), centers);
CHECK(0.05 > static_cast<double>(histogram.max() - histogram.min()) / permutations.n_cols);
}
}
SECTION("Partial permutation") {
arma::Mat<arma::uword>::fixed<10, 40000> permutations;
for (std::size_t n = 0; n < permutations.n_cols; ++n) {
permutations.col(n) = hop::getRandomPermutation(permutations.n_rows + 1, permutations.n_rows);
}
arma::Col<arma::uword> centers(permutations.n_rows);
for (std::size_t n = 0; n < permutations.n_rows; ++n) {
centers.at(n) = n;
}
for (std::size_t n = 0; n < permutations.n_rows; ++n) {
arma::Row<arma::uword> histogram = arma::hist(permutations.row(n), centers);
CHECK(0.1 > static_cast<double>(histogram.max() - histogram.min()) / permutations.n_cols);
}
}
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef WITHOUT_GPU_BACKEND
#include "top.hpp"
#include "os/os.hpp"
#include "device/device.hpp"
#include "rocsettings.hpp"
#include "device/rocm/rocglinterop.hpp"
namespace roc {
Settings::Settings() {
// Initialize the HSA device default settings
// Set this to true when we drop the flag
doublePrecision_ = ::CL_KHR_FP64;
pollCompletion_ = ENVVAR_HSA_POLL_KERNEL_COMPLETION;
enableLocalMemory_ = HSA_LOCAL_MEMORY_ENABLE;
enableImageHandle_ = true;
maxWorkGroupSize_ = 1024;
preferredWorkGroupSize_ = 256;
maxWorkGroupSize2DX_ = 16;
maxWorkGroupSize2DY_ = 16;
maxWorkGroupSize3DX_ = 4;
maxWorkGroupSize3DY_ = 4;
maxWorkGroupSize3DZ_ = 4;
kernargPoolSize_ = HSA_KERNARG_POOL_SIZE;
signalPoolSize_ = HSA_SIGNAL_POOL_SIZE;
// Determine if user is requesting Non-Coherent mode
// for system memory. By default system memory is
// operates or is programmed to be in Coherent mode.
// Users can turn it off for hardware that does not
// support this feature naturally
char* nonCoherentMode = nullptr;
nonCoherentMode = getenv("OPENCL_USE_NC_MEMORY_POLICY");
enableNCMode_ = (nonCoherentMode) ? true : false;
// Determine if user wishes to disable support for
// partial dispatch. By default support for partial
// dispatch is enabled. Users can turn it off for
// devices that do not support this feature.
//
// @note Update appropriate field of device::Settings
char* partialDispatch = nullptr;
partialDispatch = getenv("OPENCL_DISABLE_PARTIAL_DISPATCH");
enablePartialDispatch_ = (partialDispatch) ? false : true;
partialDispatch_ = (partialDispatch) ? false : true;
commandQueues_ = 100; //!< Field value set to maximum number
//!< concurrent Virtual GPUs for ROCm backend
// Disable image DMA by default (ROCM runtime doesn't support it)
imageDMA_ = false;
stagedXferRead_ = true;
stagedXferWrite_ = true;
stagedXferSize_ = GPU_STAGING_BUFFER_SIZE * Ki;
// Initialize transfer buffer size to 1MB by default
xferBufSize_ = 1024 * Ki;
const static size_t MaxPinnedXferSize = 32;
pinnedXferSize_ = std::min(GPU_PINNED_XFER_SIZE, MaxPinnedXferSize) * Mi;
pinnedMinXferSize_ = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_);
// Don't support Denormals for single precision by default
singleFpDenorm_ = false;
}
bool Settings::create(bool fullProfile, int gfxipVersion) {
customHostAllocator_ = false;
if (fullProfile) {
pinnedXferSize_ = 0;
stagedXferSize_ = 0;
xferBufSize_ = 0;
} else {
pinnedXferSize_ = std::max(pinnedXferSize_, pinnedMinXferSize_);
stagedXferSize_ = std::max(stagedXferSize_, pinnedMinXferSize_ + 4 * Ki);
}
// Enable extensions
enableExtension(ClKhrByteAddressableStore);
enableExtension(ClKhrGlobalInt32BaseAtomics);
enableExtension(ClKhrGlobalInt32ExtendedAtomics);
enableExtension(ClKhrLocalInt32BaseAtomics);
enableExtension(ClKhrLocalInt32ExtendedAtomics);
enableExtension(ClKhrInt64BaseAtomics);
enableExtension(ClKhrInt64ExtendedAtomics);
enableExtension(ClKhr3DImageWrites);
enableExtension(ClAmdMediaOps);
enableExtension(ClAmdMediaOps2);
enableExtension(ClAMDLiquidFlash);
if (MesaInterop::Supported()) {
enableExtension(ClKhrGlSharing);
}
// Enable platform extension
enableExtension(ClAmdDeviceAttributeQuery);
// Enable KHR double precision extension
enableExtension(ClKhrFp64);
#if !defined(WITH_LIGHTNING_COMPILER)
// Also enable AMD double precision extension?
enableExtension(ClAmdFp64);
#endif // !defined(WITH_LIGHTNING_COMPILER)
enableExtension(ClKhrSubGroups);
enableExtension(ClKhrDepthImages);
enableExtension(ClAmdCopyBufferP2P);
enableExtension(ClKhrFp16);
supportDepthsRGB_ = true;
#if defined(WITH_LIGHTNING_COMPILER)
switch (gfxipVersion) {
case 900:
singleFpDenorm_ = true;
break;
}
#endif // WITH_LIGHTNING_COMPILER
// Override current device settings
override();
return true;
}
void Settings::override() {
// Limit reported workgroup size
if (GPU_MAX_WORKGROUP_SIZE != 0) {
preferredWorkGroupSize_ = GPU_MAX_WORKGROUP_SIZE;
}
if (!flagIsDefault(GPU_MAX_COMMAND_QUEUES)) {
commandQueues_ = GPU_MAX_COMMAND_QUEUES;
}
if (!flagIsDefault(GPU_IMAGE_DMA)) {
commandQueues_ = GPU_IMAGE_DMA;
}
if (!flagIsDefault(GPU_XFER_BUFFER_SIZE)) {
xferBufSize_ = GPU_XFER_BUFFER_SIZE * Ki;
}
if (!flagIsDefault(GPU_PINNED_MIN_XFER_SIZE)) {
pinnedMinXferSize_ = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_);
}
if (!flagIsDefault(AMD_GPU_FORCE_SINGLE_FP_DENORM)) {
switch (AMD_GPU_FORCE_SINGLE_FP_DENORM) {
case 0:
singleFpDenorm_ = false;
break;
case 1:
singleFpDenorm_ = true;
break;
default:
break;
}
}
}
} // namespace roc
#endif // WITHOUT_GPU_BACKEND
<commit_msg>P4 to Git Change 1479658 by gandryey@gera-w8 on 2017/11/07 13:52:17<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//
#ifndef WITHOUT_GPU_BACKEND
#include "top.hpp"
#include "os/os.hpp"
#include "device/device.hpp"
#include "rocsettings.hpp"
#include "device/rocm/rocglinterop.hpp"
namespace roc {
Settings::Settings() {
// Initialize the HSA device default settings
// Set this to true when we drop the flag
doublePrecision_ = ::CL_KHR_FP64;
pollCompletion_ = ENVVAR_HSA_POLL_KERNEL_COMPLETION;
enableLocalMemory_ = HSA_LOCAL_MEMORY_ENABLE;
enableImageHandle_ = true;
maxWorkGroupSize_ = 1024;
preferredWorkGroupSize_ = 256;
maxWorkGroupSize2DX_ = 16;
maxWorkGroupSize2DY_ = 16;
maxWorkGroupSize3DX_ = 4;
maxWorkGroupSize3DY_ = 4;
maxWorkGroupSize3DZ_ = 4;
kernargPoolSize_ = HSA_KERNARG_POOL_SIZE;
signalPoolSize_ = HSA_SIGNAL_POOL_SIZE;
// Determine if user is requesting Non-Coherent mode
// for system memory. By default system memory is
// operates or is programmed to be in Coherent mode.
// Users can turn it off for hardware that does not
// support this feature naturally
char* nonCoherentMode = nullptr;
nonCoherentMode = getenv("OPENCL_USE_NC_MEMORY_POLICY");
enableNCMode_ = (nonCoherentMode) ? true : false;
// Determine if user wishes to disable support for
// partial dispatch. By default support for partial
// dispatch is enabled. Users can turn it off for
// devices that do not support this feature.
//
// @note Update appropriate field of device::Settings
char* partialDispatch = nullptr;
partialDispatch = getenv("OPENCL_DISABLE_PARTIAL_DISPATCH");
enablePartialDispatch_ = (partialDispatch) ? false : true;
partialDispatch_ = (partialDispatch) ? false : true;
commandQueues_ = 100; //!< Field value set to maximum number
//!< concurrent Virtual GPUs for ROCm backend
// Disable image DMA by default (ROCM runtime doesn't support it)
imageDMA_ = false;
stagedXferRead_ = true;
stagedXferWrite_ = true;
stagedXferSize_ = GPU_STAGING_BUFFER_SIZE * Ki;
// Initialize transfer buffer size to 1MB by default
xferBufSize_ = 1024 * Ki;
const static size_t MaxPinnedXferSize = 32;
pinnedXferSize_ = std::min(GPU_PINNED_XFER_SIZE, MaxPinnedXferSize) * Mi;
pinnedMinXferSize_ = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_);
// Don't support Denormals for single precision by default
singleFpDenorm_ = false;
}
bool Settings::create(bool fullProfile, int gfxipVersion) {
customHostAllocator_ = false;
if (fullProfile) {
pinnedXferSize_ = 0;
stagedXferSize_ = 0;
xferBufSize_ = 0;
} else {
pinnedXferSize_ = std::max(pinnedXferSize_, pinnedMinXferSize_);
stagedXferSize_ = std::max(stagedXferSize_, pinnedMinXferSize_ + 4 * Ki);
}
// Enable extensions
enableExtension(ClKhrByteAddressableStore);
enableExtension(ClKhrGlobalInt32BaseAtomics);
enableExtension(ClKhrGlobalInt32ExtendedAtomics);
enableExtension(ClKhrLocalInt32BaseAtomics);
enableExtension(ClKhrLocalInt32ExtendedAtomics);
enableExtension(ClKhrInt64BaseAtomics);
enableExtension(ClKhrInt64ExtendedAtomics);
enableExtension(ClKhr3DImageWrites);
enableExtension(ClAmdMediaOps);
enableExtension(ClAmdMediaOps2);
if (MesaInterop::Supported()) {
enableExtension(ClKhrGlSharing);
}
// Enable platform extension
enableExtension(ClAmdDeviceAttributeQuery);
// Enable KHR double precision extension
enableExtension(ClKhrFp64);
#if !defined(WITH_LIGHTNING_COMPILER)
// Also enable AMD double precision extension?
enableExtension(ClAmdFp64);
#endif // !defined(WITH_LIGHTNING_COMPILER)
enableExtension(ClKhrSubGroups);
enableExtension(ClKhrDepthImages);
enableExtension(ClAmdCopyBufferP2P);
enableExtension(ClKhrFp16);
supportDepthsRGB_ = true;
#if defined(WITH_LIGHTNING_COMPILER)
switch (gfxipVersion) {
case 900:
singleFpDenorm_ = true;
break;
}
#endif // WITH_LIGHTNING_COMPILER
// Override current device settings
override();
return true;
}
void Settings::override() {
// Limit reported workgroup size
if (GPU_MAX_WORKGROUP_SIZE != 0) {
preferredWorkGroupSize_ = GPU_MAX_WORKGROUP_SIZE;
}
if (!flagIsDefault(GPU_MAX_COMMAND_QUEUES)) {
commandQueues_ = GPU_MAX_COMMAND_QUEUES;
}
if (!flagIsDefault(GPU_IMAGE_DMA)) {
commandQueues_ = GPU_IMAGE_DMA;
}
if (!flagIsDefault(GPU_XFER_BUFFER_SIZE)) {
xferBufSize_ = GPU_XFER_BUFFER_SIZE * Ki;
}
if (!flagIsDefault(GPU_PINNED_MIN_XFER_SIZE)) {
pinnedMinXferSize_ = std::min(GPU_PINNED_MIN_XFER_SIZE * Ki, pinnedXferSize_);
}
if (!flagIsDefault(AMD_GPU_FORCE_SINGLE_FP_DENORM)) {
switch (AMD_GPU_FORCE_SINGLE_FP_DENORM) {
case 0:
singleFpDenorm_ = false;
break;
case 1:
singleFpDenorm_ = true;
break;
default:
break;
}
}
}
} // namespace roc
#endif // WITHOUT_GPU_BACKEND
<|endoftext|> |
<commit_before>// Copyright © 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#ifndef NIX_DATATYPE_H
#define NIX_DATATYPE_H
#include <cstdint>
#include <ostream>
#include <nix/Platform.hpp>
namespace nix {
/**
* @brief Enumeration providing constants for all valid data types.
*
* Those data types are used by {@link nix::DataArray} and {@link nix::Property}
* in order to indicate of what type the stored data of value is.
*/
NIXAPI enum class DataType {
Bool,
Char,
Float,
Double,
Int8,
Int16,
Int32,
Int64,
UInt8,
UInt16,
UInt32,
UInt64,
String,
Date,
DateTime,
Nothing = -1
};
/**
* @brief Determine if a type is a valid data type.
*/
template<typename T>
struct to_data_type {
static const bool is_valid = false;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<bool> {
static const bool is_valid = true;
static const DataType value = DataType::Bool;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<char> {
static const bool is_valid = true;
static const DataType value = DataType::Char;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<float> {
static const bool is_valid = true;
static const DataType value = DataType::Float;
};
/**
* @brief Determine if a type is a valid data type.
*
* @internal
*/
template<>
struct to_data_type<double> {
static const bool is_valid = true;
static const DataType value = DataType::Double;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int8_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int8;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint8_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt8;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int16_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int16;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint16_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt16;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int32_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int32;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint32_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt32;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int64_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int64;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint64_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt64;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<std::string> {
static const bool is_valid = true;
static const DataType value = DataType::String;
};
/**
* @brief Determine the size of a data type.
*
* @param dtype The data type.
*
* @return The size of the type.
*/
NIXAPI size_t data_type_to_size(DataType dtype);
/**
* @brief Convert a data type into string representation.
*
* @param dtype The data type.
*
* @return A human readable name for the given type.
*/
NIXAPI std::string data_type_to_string(DataType dtype);
/**
* @brief Output operator for data type.
*
* Prints a human readable string representation of the
* data type to an output stream.
*
* @param out The output stream.
* @param dtype The data type to print.
*
* @return The output stream.
*/
NIXAPI std::ostream& operator<<(std::ostream &out, const DataType dtype);
} // nix::
#endif
<commit_msg>DataType: Add "Opaque" type<commit_after>// Copyright © 2014, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
//
// Author: Christian Kellner <kellner@bio.lmu.de>
#ifndef NIX_DATATYPE_H
#define NIX_DATATYPE_H
#include <cstdint>
#include <ostream>
#include <nix/Platform.hpp>
namespace nix {
/**
* @brief Enumeration providing constants for all valid data types.
*
* Those data types are used by {@link nix::DataArray} and {@link nix::Property}
* in order to indicate of what type the stored data of value is.
*/
NIXAPI enum class DataType {
Bool,
Char,
Float,
Double,
Int8,
Int16,
Int32,
Int64,
UInt8,
UInt16,
UInt32,
UInt64,
String,
Date,
DateTime,
Opaque,
Nothing = -1
};
/**
* @brief Determine if a type is a valid data type.
*/
template<typename T>
struct to_data_type {
static const bool is_valid = false;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<bool> {
static const bool is_valid = true;
static const DataType value = DataType::Bool;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<char> {
static const bool is_valid = true;
static const DataType value = DataType::Char;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<float> {
static const bool is_valid = true;
static const DataType value = DataType::Float;
};
/**
* @brief Determine if a type is a valid data type.
*
* @internal
*/
template<>
struct to_data_type<double> {
static const bool is_valid = true;
static const DataType value = DataType::Double;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int8_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int8;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint8_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt8;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int16_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int16;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint16_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt16;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int32_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int32;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint32_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt32;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<int64_t> {
static const bool is_valid = true;
static const DataType value = DataType::Int64;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<uint64_t> {
static const bool is_valid = true;
static const DataType value = DataType::UInt64;
};
/**
* @brief Determine if a type is a valid data type.
*/
template<>
struct to_data_type<std::string> {
static const bool is_valid = true;
static const DataType value = DataType::String;
};
/**
* @brief Determine the size of a data type.
*
* @param dtype The data type.
*
* @return The size of the type.
*/
NIXAPI size_t data_type_to_size(DataType dtype);
/**
* @brief Convert a data type into string representation.
*
* @param dtype The data type.
*
* @return A human readable name for the given type.
*/
NIXAPI std::string data_type_to_string(DataType dtype);
/**
* @brief Output operator for data type.
*
* Prints a human readable string representation of the
* data type to an output stream.
*
* @param out The output stream.
* @param dtype The data type to print.
*
* @return The output stream.
*/
NIXAPI std::ostream& operator<<(std::ostream &out, const DataType dtype);
} // nix::
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_SVL_ITEMPROP_HXX
#define INCLUDED_SVL_ITEMPROP_HXX
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <com/sun/star/beans/PropertyState.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <cppuhelper/implbase1.hxx>
#include <svl/itemset.hxx>
#include <svl/svldllapi.h>
#include <vector>
struct SfxItemPropertyMapEntry
{
OUString aName;
sal_uInt16 nWID;
com::sun::star::uno::Type aType;
long nFlags;
sal_uInt8 nMemberId;
};
struct SfxItemPropertySimpleEntry
{
sal_uInt16 nWID;
com::sun::star::uno::Type aType;
long nFlags;
sal_uInt8 nMemberId;
SfxItemPropertySimpleEntry()
: nWID( 0 )
, nFlags( 0 )
, nMemberId( 0 )
{
}
SfxItemPropertySimpleEntry(sal_uInt16 _nWID, com::sun::star::uno::Type const & _rType,
long _nFlags, sal_uInt8 _nMemberId)
: nWID( _nWID )
, aType( _rType )
, nFlags( _nFlags )
, nMemberId( _nMemberId )
{
}
SfxItemPropertySimpleEntry( const SfxItemPropertyMapEntry* pMapEntry )
: nWID( pMapEntry->nWID )
, aType( pMapEntry->aType )
, nFlags( pMapEntry->nFlags )
, nMemberId( pMapEntry->nMemberId )
{
}
};
struct SfxItemPropertyNamedEntry : public SfxItemPropertySimpleEntry
{
OUString sName;
SfxItemPropertyNamedEntry( const OUString& rName, const SfxItemPropertySimpleEntry& rSimpleEntry)
: SfxItemPropertySimpleEntry( rSimpleEntry )
, sName( rName )
{
}
};
typedef std::vector< SfxItemPropertyNamedEntry > PropertyEntryVector_t;
class SfxItemPropertyMap_Impl;
class SVL_DLLPUBLIC SfxItemPropertyMap
{
SfxItemPropertyMap_Impl* m_pImpl;
public:
SfxItemPropertyMap( const SfxItemPropertyMapEntry* pEntries );
SfxItemPropertyMap( const SfxItemPropertyMap& rSource );
~SfxItemPropertyMap();
const SfxItemPropertySimpleEntry* getByName( const OUString &rName ) const;
com::sun::star::uno::Sequence< com::sun::star::beans::Property > getProperties() const;
com::sun::star::beans::Property getPropertyByName( const OUString & rName ) const
throw( ::com::sun::star::beans::UnknownPropertyException );
bool hasPropertyByName( const OUString& rName ) const;
void mergeProperties( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& rPropSeq );
PropertyEntryVector_t getPropertyEntries() const;
sal_uInt32 getSize() const;
};
class SVL_DLLPUBLIC SfxItemPropertySet
{
SfxItemPropertyMap m_aMap;
mutable com::sun::star::uno::Reference<com::sun::star::beans::XPropertySetInfo> m_xInfo;
public:
SfxItemPropertySet( const SfxItemPropertyMapEntry *pMap ) :
m_aMap(pMap) {}
virtual ~SfxItemPropertySet();
void getPropertyValue( const SfxItemPropertySimpleEntry& rEntry,
const SfxItemSet& rSet,
com::sun::star::uno::Any& rAny) const
throw(::com::sun::star::uno::RuntimeException);
void getPropertyValue( const OUString &rName,
const SfxItemSet& rSet,
com::sun::star::uno::Any& rAny) const
throw(::com::sun::star::uno::RuntimeException,
::com::sun::star::beans::UnknownPropertyException);
com::sun::star::uno::Any
getPropertyValue( const OUString &rName,
const SfxItemSet& rSet ) const
throw(::com::sun::star::uno::RuntimeException,
::com::sun::star::beans::UnknownPropertyException);
void setPropertyValue( const SfxItemPropertySimpleEntry& rEntry,
const com::sun::star::uno::Any& aVal,
SfxItemSet& rSet ) const
throw(::com::sun::star::uno::RuntimeException,
com::sun::star::lang::IllegalArgumentException);
void setPropertyValue( const OUString& rPropertyName,
const com::sun::star::uno::Any& aVal,
SfxItemSet& rSet ) const
throw(::com::sun::star::uno::RuntimeException,
com::sun::star::lang::IllegalArgumentException,
::com::sun::star::beans::UnknownPropertyException);
com::sun::star::beans::PropertyState
getPropertyState(const OUString& rName, const SfxItemSet& rSet)const
throw(com::sun::star::beans::UnknownPropertyException);
com::sun::star::beans::PropertyState
getPropertyState(const SfxItemPropertySimpleEntry& rEntry, const SfxItemSet& rSet) const
throw();
com::sun::star::uno::Reference<com::sun::star::beans::XPropertySetInfo>
getPropertySetInfo() const;
const SfxItemPropertyMap& getPropertyMap() const {return m_aMap;}
};
struct SfxItemPropertySetInfo_Impl;
class SVL_DLLPUBLIC SfxItemPropertySetInfo : public
cppu::WeakImplHelper1<com::sun::star::beans::XPropertySetInfo>
{
SfxItemPropertySetInfo_Impl* m_pImpl;
public:
SfxItemPropertySetInfo(const SfxItemPropertyMap &rMap );
SfxItemPropertySetInfo(const SfxItemPropertyMapEntry *pEntries );
virtual ~SfxItemPropertySetInfo();
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL
getProperties( )
throw(::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual ::com::sun::star::beans::Property SAL_CALL
getPropertyByName( const OUString& aName )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual sal_Bool SAL_CALL
hasPropertyByName( const OUString& Name )
throw(::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
};
class SVL_DLLPUBLIC SfxExtItemPropertySetInfo: public cppu::WeakImplHelper1<com::sun::star::beans::XPropertySetInfo >
{
SfxItemPropertyMap aExtMap;
public:
SfxExtItemPropertySetInfo(
const SfxItemPropertyMapEntry *pMap,
const com::sun::star::uno::Sequence<com::sun::star::beans::Property>& rPropSeq );
virtual ~SfxExtItemPropertySetInfo();
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL
getProperties( )
throw(::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual ::com::sun::star::beans::Property SAL_CALL
getPropertyByName( const OUString& aName )
throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual sal_Bool SAL_CALL
hasPropertyByName( const OUString& Name )
throw(::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>svl: document SfxItemPropertyMapEntry<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_SVL_ITEMPROP_HXX
#define INCLUDED_SVL_ITEMPROP_HXX
#include <com/sun/star/beans/XPropertySetInfo.hpp>
#include <com/sun/star/beans/PropertyState.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <cppuhelper/implbase1.hxx>
#include <svl/itemset.hxx>
#include <svl/svldllapi.h>
#include <vector>
/// map a property between beans::XPropertySet and SfxPoolItem
struct SfxItemPropertyMapEntry
{
OUString aName; ///< name of property
sal_uInt16 nWID; ///< WhichId of SfxPoolItem
com::sun::star::uno::Type aType; ///< UNO type of property
/// flag bitmap, @see com::sun::star::beans::PropertyAttribute
long nFlags;
/// "member ID" to tell QueryValue/PutValue which property it is
/// (when multiple properties map to the same nWID)
sal_uInt8 nMemberId;
};
struct SfxItemPropertySimpleEntry
{
sal_uInt16 nWID;
com::sun::star::uno::Type aType;
long nFlags;
sal_uInt8 nMemberId;
SfxItemPropertySimpleEntry()
: nWID( 0 )
, nFlags( 0 )
, nMemberId( 0 )
{
}
SfxItemPropertySimpleEntry(sal_uInt16 _nWID, com::sun::star::uno::Type const & _rType,
long _nFlags, sal_uInt8 _nMemberId)
: nWID( _nWID )
, aType( _rType )
, nFlags( _nFlags )
, nMemberId( _nMemberId )
{
}
SfxItemPropertySimpleEntry( const SfxItemPropertyMapEntry* pMapEntry )
: nWID( pMapEntry->nWID )
, aType( pMapEntry->aType )
, nFlags( pMapEntry->nFlags )
, nMemberId( pMapEntry->nMemberId )
{
}
};
struct SfxItemPropertyNamedEntry : public SfxItemPropertySimpleEntry
{
OUString sName;
SfxItemPropertyNamedEntry( const OUString& rName, const SfxItemPropertySimpleEntry& rSimpleEntry)
: SfxItemPropertySimpleEntry( rSimpleEntry )
, sName( rName )
{
}
};
typedef std::vector< SfxItemPropertyNamedEntry > PropertyEntryVector_t;
class SfxItemPropertyMap_Impl;
class SVL_DLLPUBLIC SfxItemPropertyMap
{
SfxItemPropertyMap_Impl* m_pImpl;
public:
SfxItemPropertyMap( const SfxItemPropertyMapEntry* pEntries );
SfxItemPropertyMap( const SfxItemPropertyMap& rSource );
~SfxItemPropertyMap();
const SfxItemPropertySimpleEntry* getByName( const OUString &rName ) const;
com::sun::star::uno::Sequence< com::sun::star::beans::Property > getProperties() const;
com::sun::star::beans::Property getPropertyByName( const OUString & rName ) const
throw( ::com::sun::star::beans::UnknownPropertyException );
bool hasPropertyByName( const OUString& rName ) const;
void mergeProperties( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& rPropSeq );
PropertyEntryVector_t getPropertyEntries() const;
sal_uInt32 getSize() const;
};
class SVL_DLLPUBLIC SfxItemPropertySet
{
SfxItemPropertyMap m_aMap;
mutable com::sun::star::uno::Reference<com::sun::star::beans::XPropertySetInfo> m_xInfo;
public:
SfxItemPropertySet( const SfxItemPropertyMapEntry *pMap ) :
m_aMap(pMap) {}
virtual ~SfxItemPropertySet();
void getPropertyValue( const SfxItemPropertySimpleEntry& rEntry,
const SfxItemSet& rSet,
com::sun::star::uno::Any& rAny) const
throw(::com::sun::star::uno::RuntimeException);
void getPropertyValue( const OUString &rName,
const SfxItemSet& rSet,
com::sun::star::uno::Any& rAny) const
throw(::com::sun::star::uno::RuntimeException,
::com::sun::star::beans::UnknownPropertyException);
com::sun::star::uno::Any
getPropertyValue( const OUString &rName,
const SfxItemSet& rSet ) const
throw(::com::sun::star::uno::RuntimeException,
::com::sun::star::beans::UnknownPropertyException);
void setPropertyValue( const SfxItemPropertySimpleEntry& rEntry,
const com::sun::star::uno::Any& aVal,
SfxItemSet& rSet ) const
throw(::com::sun::star::uno::RuntimeException,
com::sun::star::lang::IllegalArgumentException);
void setPropertyValue( const OUString& rPropertyName,
const com::sun::star::uno::Any& aVal,
SfxItemSet& rSet ) const
throw(::com::sun::star::uno::RuntimeException,
com::sun::star::lang::IllegalArgumentException,
::com::sun::star::beans::UnknownPropertyException);
com::sun::star::beans::PropertyState
getPropertyState(const OUString& rName, const SfxItemSet& rSet)const
throw(com::sun::star::beans::UnknownPropertyException);
com::sun::star::beans::PropertyState
getPropertyState(const SfxItemPropertySimpleEntry& rEntry, const SfxItemSet& rSet) const
throw();
com::sun::star::uno::Reference<com::sun::star::beans::XPropertySetInfo>
getPropertySetInfo() const;
const SfxItemPropertyMap& getPropertyMap() const {return m_aMap;}
};
struct SfxItemPropertySetInfo_Impl;
class SVL_DLLPUBLIC SfxItemPropertySetInfo : public
cppu::WeakImplHelper1<com::sun::star::beans::XPropertySetInfo>
{
SfxItemPropertySetInfo_Impl* m_pImpl;
public:
SfxItemPropertySetInfo(const SfxItemPropertyMap &rMap );
SfxItemPropertySetInfo(const SfxItemPropertyMapEntry *pEntries );
virtual ~SfxItemPropertySetInfo();
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL
getProperties( )
throw(::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual ::com::sun::star::beans::Property SAL_CALL
getPropertyByName( const OUString& aName )
throw(::com::sun::star::beans::UnknownPropertyException,
::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual sal_Bool SAL_CALL
hasPropertyByName( const OUString& Name )
throw(::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
};
class SVL_DLLPUBLIC SfxExtItemPropertySetInfo: public cppu::WeakImplHelper1<com::sun::star::beans::XPropertySetInfo >
{
SfxItemPropertyMap aExtMap;
public:
SfxExtItemPropertySetInfo(
const SfxItemPropertyMapEntry *pMap,
const com::sun::star::uno::Sequence<com::sun::star::beans::Property>& rPropSeq );
virtual ~SfxExtItemPropertySetInfo();
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > SAL_CALL
getProperties( )
throw(::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual ::com::sun::star::beans::Property SAL_CALL
getPropertyByName( const OUString& aName )
throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
virtual sal_Bool SAL_CALL
hasPropertyByName( const OUString& Name )
throw(::com::sun::star::uno::RuntimeException, std::exception) SAL_OVERRIDE;
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>// Copyright (c) 2015-2018 Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/sequences/
#ifndef TAOCPP_SEQUENCES_INCLUDE_FOLD_HPP
#define TAOCPP_SEQUENCES_INCLUDE_FOLD_HPP
#include <type_traits>
#include "integer_sequence.hpp"
#include "make_integer_sequence.hpp"
#include "select.hpp"
namespace tao
{
namespace seq
{
namespace impl
{
template< template< typename U, U, U > class, typename, bool, typename T, T... >
struct folder;
template< template< typename U, U, U > class OP, std::size_t... Is, typename T, T... Ns >
struct folder< OP, index_sequence< Is... >, false, T, Ns... >
{
using type = integer_sequence< T, OP< T, seq::select< 2 * Is, T, Ns... >::value, seq::select< 2 * Is + 1, T, Ns... >::value >::value... >;
};
template< template< typename U, U, U > class OP, std::size_t... Is, typename T, T N, T... Ns >
struct folder< OP, index_sequence< Is... >, true, T, N, Ns... >
{
using type = integer_sequence< T, N, OP< T, seq::select< 2 * Is, T, Ns... >::value, seq::select< 2 * Is + 1, T, Ns... >::value >::value... >;
};
} // namespace impl
template< template< typename U, U, U > class, typename T, T... >
struct fold;
template< template< typename U, U, U > class OP, typename T, T N >
struct fold< OP, T, N >
: std::integral_constant< T, N >
{
};
template< template< typename U, U, U > class OP, typename T, T... Ns >
struct fold
: fold< OP, typename impl::folder< OP, make_index_sequence< sizeof...( Ns ) / 2 >, sizeof...( Ns ) % 2 == 1, T, Ns... >::type >
{
};
template< template< typename U, U, U > class OP, typename T, T... Ns >
struct fold< OP, integer_sequence< T, Ns... > >
: fold< OP, T, Ns... >
{
};
} // namespace seq
} // namespace tao
#endif
<commit_msg>Add a layer to fix Clang problems<commit_after>// Copyright (c) 2015-2018 Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/sequences/
#ifndef TAOCPP_SEQUENCES_INCLUDE_FOLD_HPP
#define TAOCPP_SEQUENCES_INCLUDE_FOLD_HPP
#include <type_traits>
#include "integer_sequence.hpp"
#include "make_integer_sequence.hpp"
#include "select.hpp"
namespace tao
{
namespace seq
{
namespace impl
{
template< template< typename U, U, U > class OP >
struct folder
{
template< bool, typename, typename T, T... >
struct sub;
template< std::size_t... Is, typename T, T... Ns >
struct sub< false, index_sequence< Is... >, T, Ns... >
{
using type = integer_sequence< T, OP< T, seq::select< 2 * Is, T, Ns... >::value, seq::select< 2 * Is + 1, T, Ns... >::value >::value... >;
};
template< std::size_t... Is, typename T, T N, T... Ns >
struct sub< true, index_sequence< Is... >, T, N, Ns... >
{
using type = integer_sequence< T, N, OP< T, seq::select< 2 * Is, T, Ns... >::value, seq::select< 2 * Is + 1, T, Ns... >::value >::value... >;
};
};
} // namespace impl
template< template< typename U, U, U > class, typename T, T... >
struct fold;
template< template< typename U, U, U > class OP, typename T, T N >
struct fold< OP, T, N >
: std::integral_constant< T, N >
{
};
template< template< typename U, U, U > class OP, typename T, T... Ns >
struct fold
: fold< OP, typename impl::folder< OP >::template sub< sizeof...( Ns ) % 2 == 1, make_index_sequence< sizeof...( Ns ) / 2 >, T, Ns... >::type >
{
};
template< template< typename U, U, U > class OP, typename T, T... Ns >
struct fold< OP, integer_sequence< T, Ns... > >
: fold< OP, T, Ns... >
{
};
} // namespace seq
} // namespace tao
#endif
<|endoftext|> |
<commit_before>#include "keilo.hpp"
namespace keilo {
table::table(std::string table_name, std::string key) : name(std::move(table_name)), key(std::move(key)) { }
table::table(std::string table_name, std::string key, std::list<record> instances) : name(std::move(table_name)),
key(std::move(key)),
records(std::move(instances)) {
}
table::table(const table& other) { *this = other; }
table& table::operator=(const table& other) {
this->name = other.name;
this->key = other.key;
for (const auto& record : other.records)
this->records.emplace_back(record);
return *this;
}
table table::join(table& other) {
std::unique_lock<std::mutex> lock(this->mutex);
auto joined_table{records};
auto other_table{other.records};
for (auto& origin_record : joined_table)
for (auto& other_record : other_table)
for (auto& other_instance : other_record.instances)
if (key != other_instance.identifier &&
other_record.key.value == origin_record.key.value)
origin_record.instances.emplace_back(other_instance);
return {get_name() + '+' + other.get_name(), key, joined_table};
}
std::list<record> table::select_record(const std::list<instance>& conditions) const {
auto dump = records;
auto selected = std::list<record>();
for (;;) {
auto it = std::find_if(dump.cbegin(), dump.cend(),
[conditions](const record& record) {
auto found = true;
for (const auto& condition : conditions) {
if (record.instances.cend() == std::find_if(
record.instances.cbegin(), record.instances.cend(),
[condition](const instance& instance) {
return instance == condition;
})
) {
found = false;
break;
}
}
return found;
}
);
if (it != dump.cend()) {
selected.emplace_back(*it);
dump.erase(it);
}
else
break;
}
return selected;
}
result_t table::insert_record(const record& record) {
std::unique_lock<std::mutex> lock(this->mutex);
if (record.key.identifier != this->key)
return result_t::key_not_exist;
const auto val = record.key.value;
const auto pos = std::find_if(records.cbegin(), records.cend(), [this, val](const keilo::record& record) {
return record.instances.cend() != std::find_if(record.instances.cbegin(), record.instances.cend(),
[this, val](const instance& instance) {
return instance.identifier == key && instance.value ==
val;
});
});
if (pos != records.cend())
return result_t::key_overlapped;
records.insert(pos, record);
return result_t::success;
}
result_t table::update_record(const std::list<instance>& conditions, const std::list<instance>& replacements) {
std::unique_lock<std::mutex> lock(mutex);
// find suitable records
const auto to_update = select_record(conditions);
if (to_update.empty())
return result_t::cannot_find;
// check duplication of instance of key if there is modifying of key
const auto dup = std::find_if(replacements.cbegin(), replacements.cend(),
[this](const instance& instance) { return instance.identifier == key; }
);
if (dup != replacements.cend())
if (records.cend() != std::find_if(records.cbegin(), records.cend(),
[&dup](const record& record) { return record.key == *dup; })
)
return result_t::key_overlapped;
for (const auto& replacement : replacements) {
for (const auto& be_update : to_update) {
auto rt = std::find_if(records.begin(), records.end(),
[&be_update](const record& record) { return be_update.key == record.key; }
);
auto it = std::find_if(rt->instances.begin(), rt->instances.end(),
[replacement](const instance& instance) {
return replacement.identifier == instance.identifier;
}
);
it->value = replacement.value;
}
}
return result_t::success;
}
result_t table::remove_record(const std::list<instance>& conditions) {
std::unique_lock<std::mutex> lock(mutex);
const auto selected_records = this->select_record(conditions);
// when program cannot find suitable records
if (selected_records.empty())
return result_t::cannot_find;
for (const auto& selected_record : selected_records) {
auto it = std::find_if(this->records.cbegin(), this->records.cend(),
[&selected_record](const record& origin_record) {
return selected_record.key.value == origin_record.key.value;
}
);
if (it != this->records.cend()) {
auto tmp = it;
++tmp;
records.erase(it);
it = tmp;
}
}
return result_t::success;
}
std::list<record> table::get_records() {
std::unique_lock<std::mutex> lock(mutex);
return records;
}
size_t table::count() {
std::unique_lock<std::mutex> lock(mutex);
return records.size();
}
std::string table::get_key() const { return key; }
void table::sort(const bool& order) {
records.sort([order](const record& a, const record& b) {
return order ? a.key.value < b.key.value : a.key.value > b.key.value;
});
}
void table::sort(const char* sort_key, const bool& order) {
records.sort([sort_key, order](const record& a, const record& b) {
const auto a_key = std::find_if(a.instances.begin(), a.instances.end(),
[sort_key](const instance& instance) {
return sort_key == instance.identifier;
});
const auto b_key = std::find_if(b.instances.begin(), b.instances.end(),
[sort_key](const instance& instance) {
return sort_key == instance.identifier;
});
return order ? a_key->value < b_key->value : a_key->value > b_key->value;
});
}
std::string table::get_name() const { return name; }
void table::set_name(std::string name) { this->name = std::move(name); }
}
<commit_msg>Update table.cpp<commit_after>#include "keilo.hpp"
namespace keilo {
table::table(std::string table_name, std::string key) : name(std::move(table_name)), key(std::move(key)) { }
table::table(std::string table_name, std::string key, std::list<record> instances) : name(std::move(table_name)),
key(std::move(key)),
records(std::move(instances)) {
}
table::table(const table& other) { *this = other; }
table& table::operator=(const table& other) {
this->name = other.name;
this->key = other.key;
for (const auto& record : other.records)
this->records.emplace_back(record);
return *this;
}
table table::join(table& other) {
std::unique_lock<std::mutex> lock(this->mutex);
auto joined_table{records};
auto other_table{other.records};
for (auto& origin_record : joined_table)
for (auto& other_record : other_table)
for (auto& other_instance : other_record.instances)
if (key != other_instance.identifier &&
other_record.key.value == origin_record.key.value)
origin_record.instances.emplace_back(other_instance);
return {get_name() + '+' + other.get_name(), key, joined_table};
}
std::list<record> table::select_record(const std::list<instance>& conditions) const {
auto dump = records;
auto selected = std::list<record>();
for (;;) {
auto it = std::find_if(dump.cbegin(), dump.cend(),
[conditions](const record& record) {
auto found = true;
for (const auto& condition : conditions) {
if (record.instances.cend() == std::find_if(
record.instances.cbegin(), record.instances.cend(),
[condition](const instance& instance) {
return instance == condition;
})
) {
found = false;
break;
}
}
return found;
}
);
if (it != dump.cend()) {
selected.emplace_back(*it);
dump.erase(it);
}
else
break;
}
return selected;
}
result_t table::insert_record(const record& record) {
std::unique_lock<std::mutex> lock(this->mutex);
if (record.key.identifier != this->key)
return result_t::key_not_exist;
const auto val = record.key.value;
const auto pos = std::find_if(records.cbegin(), records.cend(), [this, val](const keilo::record& record) {
return record.instances.cend() != std::find_if(record.instances.cbegin(), record.instances.cend(),
[this, val](const instance& instance) {
return instance.identifier == key && instance.value ==
val;
});
});
if (pos != records.cend())
return result_t::key_overlapped;
records.insert(pos, record);
return result_t::success;
}
result_t table::update_record(const std::list<instance>& conditions, const std::list<instance>& replacements) {
std::unique_lock<std::mutex> lock(mutex);
// find suitable records
const auto to_update = select_record(conditions);
if (to_update.empty())
return result_t::cannot_find;
// check duplication of instance of key if there is modifying of key
const auto dup = std::find_if(replacements.cbegin(), replacements.cend(),
[this](const instance& instance) { return instance.identifier == key; }
);
if (dup != replacements.cend())
if (records.cend() != std::find_if(records.cbegin(), records.cend(),
[&dup](const record& record) { return record.key == *dup; })
)
return result_t::key_overlapped;
for (const auto& replacement : replacements) {
for (const auto& be_update : to_update) {
auto rt = std::find_if(records.begin(), records.end(),
[&be_update](const record& record) { return be_update.key == record.key; }
);
auto it = std::find_if(rt->instances.begin(), rt->instances.end(),
[replacement](const instance& instance) {
return replacement.identifier == instance.identifier;
}
);
it->value = replacement.value;
}
}
return result_t::success;
}
result_t table::remove_record(const std::list<instance>& conditions) {
std::unique_lock<std::mutex> lock(mutex);
const auto selected_records = this->select_record(conditions);
// when program cannot find suitable records
if (selected_records.empty())
return result_t::cannot_find;
for (const auto& selected_record : selected_records) {
auto it = std::find_if(this->records.cbegin(), this->records.cend(),
[&selected_record](const record& origin_record) {
return selected_record.key.value == origin_record.key.value;
}
);
if (it != this->records.cend()) {
auto tmp = it;
++tmp;
records.erase(it);
it = tmp;
}
}
return result_t::success;
}
std::list<record> table::get_records() {
std::unique_lock<std::mutex> lock(mutex);
return records;
}
size_t table::count() {
std::unique_lock<std::mutex> lock(mutex);
return records.size();
}
std::string table::get_key() const { return key; }
void table::sort(const bool& order) {
records.sort([order](const record& a, const record& b) {
return order ? a.key.value < b.key.value : a.key.value > b.key.value;
});
}
void table::sort(const char* sort_key, const bool& order) {
records.sort([sort_key, order](const record& a, const record& b) {
const auto a_key = std::find_if(a.instances.begin(), a.instances.end(),
[sort_key](const instance& instance) {
return sort_key == instance.identifier;
});
const auto b_key = std::find_if(b.instances.begin(), b.instances.end(),
[sort_key](const instance& instance) {
return sort_key == instance.identifier;
});
return order ? a_key->value < b_key->value : a_key->value > b_key->value;
});
}
std::string table::get_name() const { return name; }
}
<|endoftext|> |
<commit_before><commit_msg>Reverted "Leak TypeDescriptor_Init_Impl to avoid problems at exit."<commit_after><|endoftext|> |
<commit_before>#include "GAMEFLOW.H"
//#include "DRAW.H"
#include "../SPEC_PSX/FILE.H"
#include "../SPEC_PSX/MALLOC.H"
#include <stdint.h>
#include <string.h>
//Temp
#include <assert.h>
unsigned char gfGameMode;
unsigned char gfNumMips;
int scroll_pos;
char DEL_playingamefmv;
char num_fmvs;
char fmv_to_play[2];
unsigned short dels_cutseq_selector_flag;
unsigned short dels_cutseq_player;
char Chris_Menu;
unsigned char gfLegendTime;
unsigned char bDoCredits;
static unsigned char gfCutNumber;
unsigned char gfInitialiseGame;
long nframes;
unsigned char gfNumPickups;
unsigned char gfNumTakeaways;
char CanLoad;
struct GAMEFLOW* Gameflow;
unsigned short* gfStringOffset;
char* gfStringWad;
unsigned short* gfFilenameOffset;
char* gfFilenameWad;
unsigned char gfCurrentLevel;
unsigned char gfLevelComplete;
unsigned char gfRequiredStartPos;
unsigned short gfLevelFlags;
unsigned char gfLevelNames[40];
unsigned char gfResidentCut[4];
unsigned char gfResetHubDest;
char gfUVRotate;
char gfLayer1Vel;
char gfLayer2Vel;
struct CVECTOR gfLayer1Col;
struct CVECTOR gfLayer2Col;
unsigned long GameTimer;
//struct PHD_VECTOR gfLensFlare;
struct CVECTOR gfLensFlareColour;
unsigned char gfMirrorRoom;
unsigned char gfMips[8];
char title_controls_locked_out;
long gfScriptLen = 0;
unsigned char gfLegend;
unsigned char gfWadNames[40];
static unsigned short *gfScriptOffset;
static unsigned char *gfScriptWad;
static char* gfExtensions;
static int gfStatus;
static unsigned long OldSP;
unsigned char gfPickups[16];
unsigned char gfTakeaways[16];
void DoGameflow()//10F5C, 10FD8
{
unsigned char *gf;
unsigned char n;
LoadGameflow();
#ifndef _DEBUG
//0 = Eidos Logo FMV
//1 = TRC Intro FMV
S_PlayFMV(0);
S_PlayFMV(1);
#endif
#if 1
struct GAMEFLOW* v1 = Gameflow;
num_fmvs = 0;
fmv_to_play[0] = 0;
fmv_to_play[1] = 0;
//? Since when did gf flags store the current level?
//FIXME!
int v0 = *(int*)v1;
v0 >>= 2;
v0 &= 1;
v0 = v0 < 1 ? 1 : 0;
gfCurrentLevel = v0;
//Current level's script offset
unsigned short* scriptOffsetPtr = gfScriptOffset + (gfCurrentLevel & 0xFF);
unsigned int s0 = 0x000A0000;//?
unsigned char* sequenceCommand = gfScriptWad + *scriptOffsetPtr;
while (1)//?
{
int op = *sequenceCommand - 0x80;
sequenceCommand++;
switch (op)
{
case 2://IB = 113D8, 11488
gfLevelFlags = (sequenceCommand[0] | (sequenceCommand[1] << 8));
DoTitle(sequenceCommand[2], sequenceCommand[3]);//a3[2]unconfirmed
break;
case 3://11048
break;
case 5://112B8
gfResidentCut[0] = *sequenceCommand;
sequenceCommand += 1;
break;
case 6://112CC
gfResidentCut[1] = *sequenceCommand;
sequenceCommand += 1;
break;
case 7:
gfResidentCut[2] = *sequenceCommand;
sequenceCommand += 1;
break;
case 8://112F4
gfResidentCut[3] = *sequenceCommand;
sequenceCommand += 1;
break;
case 9://1107C
{
int a2 = 10;//?
int a1 = 10;//?
///LightningRGB[0] = *sequenceCommand;
///LightningRGBs[0] = *sequenceCommand;
gfLayer2Col.r = *sequenceCommand;
sequenceCommand += 1;
#ifdef _DEBUG
//internal beta is 0x2E
//GameTimer = 0x2E;
#endif
///LightningRGB[1] = *sequenceCommand;//*a3++;?
///LightningRGBs[1] = *sequenceCommand;//*a3++;?
gfLayer2Col.g = *sequenceCommand;//*a3++;?
sequenceCommand += 1;
GameTimer = 44;
///GlobalRoomNumber = *sequenceCommand;
///GLOBAL_gunflash_meshptr = *sequenceCommand;
gfLayer1Col.cd = *sequenceCommand;
sequenceCommand += 1;
gfLayer1Vel = *sequenceCommand;
sequenceCommand += 1;
break;
}
default://11550
assert(1);
break;
}
}
#endif
dump_game_malloc();
}
void LoadGameflow()//102E0, 102B0
{
int len = FILE_Length("SCRIPT.DAT");
unsigned char* s = game_malloc(len);
FILE_Load("SCRIPT.DAT", s);
Gameflow = (struct GAMEFLOW*)s;
s += sizeof(struct GAMEFLOW);
gfExtensions = s;
s += 0x28;
gfFilenameOffset = s;
s += Gameflow->nFileNames * sizeof(unsigned short);
gfFilenameWad = s;
s += Gameflow->FileNameLen;
gfScriptOffset = s;
s += Gameflow->nLevels * sizeof(unsigned short);
gfScriptLen = len;
gfScriptWad = s;
s += Gameflow->ScriptLen;
//Align
gfStringOffset = (char*)((uintptr_t)(s + 3) & (uintptr_t)-4);
int i = 0;
#ifdef CORE_UNSAFE
//This is original code, unsafe (if no lang loc files exist on disk)
while (FILE_Length(s) == -1)
{
//Null terminated
s += strlen(s) + 1;
i++;
}
#else
//Safer code (no inf loop).
for (i = 0; i < 8; i++)
{
if (FILE_Length(s) != -1)
{
break;
}
//Null terminated
s += strlen(s) + 1;
}
#endif
Gameflow->Language = i;
FILE_Load(s, gfStringOffset);
struct STRINGHEADER sh;
memcpy(&sh, gfStringOffset, sizeof(struct STRINGHEADER));
memcpy(gfStringOffset, gfStringOffset + (sizeof(struct STRINGHEADER) / sizeof(unsigned short)), (sh.nStrings + sh.nPSXStrings) * sizeof(unsigned short));
#ifdef _DEBUG
//Internal Beta
//memcpy(gfStringOffset + (sh.nStrings + sh.nPSXStrings), gfStringOffset + 317, sh.StringWadLen + sh.PSXStringWadLen);
memcpy(gfStringOffset + (sh.nStrings + sh.nPSXStrings), gfStringOffset + 315, sh.StringWadLen + sh.PSXStringWadLen);
#else
memcpy(gfStringOffset + (sh.nStrings + sh.nPSXStrings), gfStringOffset + 315, sh.StringWadLen + sh.PSXStringWadLen);
#endif
if (sh.nStrings + sh.nPSXStrings != 0)
{
unsigned char* stringPtr = gfStringOffset + sh.nStrings + sh.nPSXStrings;
for (i = 0; i < sh.nStrings + sh.nPSXStrings; i++)
{
int stringLength = (gfStringOffset[i + 1] - gfStringOffset[i]) - 1;
if (stringLength > 0)
{
for (int j = 0; j < stringLength; j++)
{
stringPtr[j] ^= 0xA5;
}
}
stringPtr += stringLength + 1;
}
}
if (Gameflow->nLevels != 0)
{
unsigned char* sequenceCommand = gfScriptWad;
for (i = 0; i < Gameflow->nLevels; i++)
{
int endOfSequence = 0;
while (!endOfSequence)
{
unsigned char op = *sequenceCommand - 0x80;
sequenceCommand++;
switch (op)
{
case 0:
sequenceCommand += 1;
break;
case 1:
gfLevelNames[i] = *sequenceCommand;
sequenceCommand += 5;
break;
case 2:
case 9:
case 10:
sequenceCommand += 4;
break;
case 3:
endOfSequence = 1;
break;
case 4:
case 5:
case 6:
case 7:
case 8:
case 11:
case 12:
case 16:
case 17:
sequenceCommand += 1;
break;
case 13:
sequenceCommand += 9;
break;
case 14:
sequenceCommand += 5;
break;
case 15:
sequenceCommand += 3;
break;
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
case 38:
case 39:
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
case 58:
case 59:
case 60:
case 61:
case 62:
case 63:
case 64:
case 65:
case 66:
case 67:
case 68:
case 69:
case 70:
case 71:
case 72:
case 73:
case 74:
case 75:
case 76:
case 77:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 86:
case 87:
case 88:
case 89:
case 90:
sequenceCommand += 2;
break;
default:
sequenceCommand += 2;
break;
}
}
}
}
}
void QuickControlPhase()
{
}
void DoTitle(unsigned char Name, unsigned char Audio)//10604, 105C4
{
}
void DoLevel(unsigned char Name, unsigned char Audio)
{
}<commit_msg>Fix: type mis-match errors. GAMEFLOW.C<commit_after>#include "GAMEFLOW.H"
//#include "DRAW.H"
//#include "NEWINV2.H"
//#include "SAVEGAME.H"
//#include "TOMB4FX.H"
//#include "../SPEC_PSX/CD.H"
#include "../SPEC_PSX/FILE.H"
#include "../SPEC_PSX/MALLOC.H"
#//include "../SPEC_PSX/ROOMLOAD.H"
#include <stdint.h>
#include <string.h>
//Temp
#include "../SPEC_PSX/LOAD_LEV.H"
#include <assert.h>
unsigned char gfGameMode;
unsigned char gfNumMips;
int scroll_pos;
char DEL_playingamefmv;
char num_fmvs;
char fmv_to_play[2];
unsigned short dels_cutseq_selector_flag;
unsigned short dels_cutseq_player;
char Chris_Menu;
unsigned char gfLegendTime;
unsigned char bDoCredits;
static unsigned char gfCutNumber;
unsigned char gfInitialiseGame;
long nframes;
unsigned char gfNumPickups;
unsigned char gfNumTakeaways;
char CanLoad;
struct GAMEFLOW* Gameflow;
unsigned short* gfStringOffset;
char* gfStringWad;
unsigned short* gfFilenameOffset;
char* gfFilenameWad;
unsigned char gfCurrentLevel;
unsigned char gfLevelComplete;
unsigned char gfRequiredStartPos;
unsigned short gfLevelFlags;
unsigned char gfLevelNames[40];
unsigned char gfResidentCut[4];
unsigned char gfResetHubDest;
char gfUVRotate;
char gfLayer1Vel;
char gfLayer2Vel;
struct CVECTOR gfLayer1Col;
struct CVECTOR gfLayer2Col;
unsigned long GameTimer;
//struct PHD_VECTOR gfLensFlare;
struct CVECTOR gfLensFlareColour;
unsigned char gfMirrorRoom;
unsigned char gfMips[8];
char title_controls_locked_out;
long gfScriptLen = 0;
unsigned char gfLegend;
unsigned char gfWadNames[40];
static unsigned short *gfScriptOffset;
static unsigned char *gfScriptWad;
static char* gfExtensions;
static int gfStatus;
static unsigned long OldSP;
unsigned char gfPickups[16];
unsigned char gfTakeaways[16];
void DoGameflow()//10F5C, 10FD8
{
unsigned char *gf;
unsigned char n;
LoadGameflow();
#ifdef PSX
//0 = Eidos Logo FMV
//1 = TRC Intro FMV
S_PlayFMV(0);
S_PlayFMV(1);
#endif
#if 1
struct GAMEFLOW* v1 = Gameflow;
num_fmvs = 0;
fmv_to_play[0] = 0;
fmv_to_play[1] = 0;
//? Since when did gf flags store the current level?
//FIXME!
int v0 = *(int*)v1;
v0 >>= 2;
v0 &= 1;
v0 = v0 < 1 ? 1 : 0;
gfCurrentLevel = v0;
//Current level's script offset
unsigned short* scriptOffsetPtr = gfScriptOffset + (gfCurrentLevel & 0xFF);
unsigned int s0 = 0x000A0000;//?
unsigned char* sequenceCommand = gfScriptWad + *scriptOffsetPtr;
while (1)//?
{
int op = *sequenceCommand - 0x80;
sequenceCommand++;
switch (op)
{
case 2://IB = 113D8, 11488
gfLevelFlags = (sequenceCommand[0] | (sequenceCommand[1] << 8));
DoTitle(sequenceCommand[2], sequenceCommand[3]);//a3[2]unconfirmed
break;
case 3://11048
break;
case 5://112B8
gfResidentCut[0] = *sequenceCommand;
sequenceCommand += 1;
break;
case 6://112CC
gfResidentCut[1] = *sequenceCommand;
sequenceCommand += 1;
break;
case 7:
gfResidentCut[2] = *sequenceCommand;
sequenceCommand += 1;
break;
case 8://112F4
gfResidentCut[3] = *sequenceCommand;
sequenceCommand += 1;
break;
case 9://1107C
{
int a2 = 10;//?
int a1 = 10;//?
/// LightningRGB[0] = *sequenceCommand;
/// LightningRGBs[0] = *sequenceCommand;
gfLayer2Col.r = *sequenceCommand;
sequenceCommand += 1;
#ifdef _DEBUG
//internal beta is 0x2E
//GameTimer = 0x2E;
#endif
/// LightningRGB[1] = *sequenceCommand;//*a3++;?
/// LightningRGBs[1] = *sequenceCommand;//*a3++;?
gfLayer2Col.g = *sequenceCommand;//*a3++;?
sequenceCommand += 1;
GameTimer = 44;
/// GlobalRoomNumber = *sequenceCommand;
// GLOBAL_gunflash_meshptr = *sequenceCommand;
gfLayer1Col.cd = *sequenceCommand;
sequenceCommand += 1;
gfLayer1Vel = *sequenceCommand;
sequenceCommand += 1;
break;
}
default://11550
assert(1);
break;
}
}
#endif
dump_game_malloc();
}
void LoadGameflow()//102E0, 102B0
{
int len = FILE_Length("SCRIPT.DAT");
char* s = game_malloc(len);
FILE_Load("SCRIPT.DAT", s);
Gameflow = (struct GAMEFLOW*)s;
s += sizeof(struct GAMEFLOW);
gfExtensions = s;
s += 0x28;
gfFilenameOffset = (unsigned short*)s;
s += Gameflow->nFileNames * sizeof(unsigned short);
gfFilenameWad = s;
s += Gameflow->FileNameLen;
gfScriptOffset = (unsigned short*)s;
s += Gameflow->nLevels * sizeof(unsigned short);
gfScriptLen = len;
gfScriptWad = (unsigned char*)s;
s += Gameflow->ScriptLen;
//Align
gfStringOffset = (unsigned short*)(char*)((uintptr_t)(s + 3) & (uintptr_t)-4);
int i = 0;
#ifdef CORE_UNSAFE
//This is original code, unsafe (if no lang loc files exist on disk)
while (FILE_Length(s) == -1)
{
//Null terminated
s += strlen(s) + 1;
i++;
}
#else
//Safer code (no inf loop).
for (i = 0; i < 8; i++)
{
if (FILE_Length((char*)s) != -1)
{
break;
}
//Null terminated
s += strlen((char*)s) + 1;
}
#endif
Gameflow->Language = i;
FILE_Load((char*)s, gfStringOffset);
struct STRINGHEADER sh;
memcpy(&sh, gfStringOffset, sizeof(struct STRINGHEADER));
memcpy(gfStringOffset, gfStringOffset + (sizeof(struct STRINGHEADER) / sizeof(unsigned short)), (sh.nStrings + sh.nPSXStrings) * sizeof(unsigned short));
#ifdef _DEBUG
//Internal Beta
//memcpy(gfStringOffset + (sh.nStrings + sh.nPSXStrings), gfStringOffset + 317, sh.StringWadLen + sh.PSXStringWadLen);
memcpy(gfStringOffset + (sh.nStrings + sh.nPSXStrings), gfStringOffset + 315, sh.StringWadLen + sh.PSXStringWadLen);
#else
memcpy(gfStringOffset + (sh.nStrings + sh.nPSXStrings), gfStringOffset + 315, sh.StringWadLen + sh.PSXStringWadLen);
#endif
if (sh.nStrings + sh.nPSXStrings != 0)
{
unsigned char* stringPtr = (unsigned char*)(gfStringOffset + sh.nStrings + sh.nPSXStrings);//s?
for (i = 0; i < sh.nStrings + sh.nPSXStrings; i++)
{
int stringLength = (gfStringOffset[i + 1] - gfStringOffset[i]) - 1;
if (stringLength > 0)
{
for (int j = 0; j < stringLength; j++)
{
stringPtr[j] ^= 0xA5;
}
}
stringPtr += stringLength + 1;
}
}
if (Gameflow->nLevels != 0)
{
unsigned char* sequenceCommand = gfScriptWad;
for (i = 0; i < Gameflow->nLevels; i++)
{
int endOfSequence = 0;
while (!endOfSequence)
{
unsigned char op = *sequenceCommand - 0x80;
sequenceCommand++;
switch (op)
{
case 0:
sequenceCommand += 1;
break;
case 1:
gfLevelNames[i] = *sequenceCommand;
sequenceCommand += 5;
break;
case 2:
case 9:
case 10:
sequenceCommand += 4;
break;
case 3:
endOfSequence = 1;
break;
case 4:
case 5:
case 6:
case 7:
case 8:
case 11:
case 12:
case 16:
case 17:
sequenceCommand += 1;
break;
case 13:
sequenceCommand += 9;
break;
case 14:
sequenceCommand += 5;
break;
case 15:
sequenceCommand += 3;
break;
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
case 38:
case 39:
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
case 48:
case 49:
case 50:
case 51:
case 52:
case 53:
case 54:
case 55:
case 56:
case 57:
case 58:
case 59:
case 60:
case 61:
case 62:
case 63:
case 64:
case 65:
case 66:
case 67:
case 68:
case 69:
case 70:
case 71:
case 72:
case 73:
case 74:
case 75:
case 76:
case 77:
case 78:
case 79:
case 80:
case 81:
case 82:
case 83:
case 84:
case 85:
case 86:
case 87:
case 88:
case 89:
case 90:
sequenceCommand += 2;
break;
default:
sequenceCommand += 2;
break;
}
}
}
}
}
void QuickControlPhase()
{
}
void DoTitle(unsigned char Name, unsigned char Audio)//10604, 105C4
{
}
void DoLevel(unsigned char Name, unsigned char Audio)
{
}
<|endoftext|> |
<commit_before>#include "LARA2GUN.H"
#include "SPECIFIC.H"
#include "LARA.H"
#include "LARAFIRE.H"
#ifdef PC_VERSION
#include "GAME.H"
#else
#include "SETUP.H"
#endif
#include "DRAW.H"
#include "OBJECTS.H"
#include "EFFECTS.H"
#include "SOUND.H"
static struct PISTOL_DEF PistolTable[4] =
{
{ LARA, 0, 0, 0, 0 },
{ PISTOLS_ANIM, 4, 5, 0xD, 0x18 },
{ REVOLVER_ANIM , 7, 8, 0xF, 0x1D },
{ UZI_ANIM, 4, 5, 0xD, 0x18 }
};
void AnimatePistols(int weapon_type)
{
UNIMPLEMENTED();
}
void PistolHandler(int weapon_type)
{
UNIMPLEMENTED();
}
void undraw_pistol_mesh_right(int weapon_type)//44968(<), 44DCC(<) (F)
{
WeaponObject(weapon_type);
lara.mesh_ptrs[LM_RHAND] = meshes[objects[LARA].mesh_index + 2 * LM_RHAND];
switch (weapon_type)
{
case WEAPON_PISTOLS:
lara.holster = LARA_HOLSTERS_PISTOLS;
break;
case WEAPON_REVOLVER:
lara.holster = LARA_HOLSTERS_REVOLVER;
break;
case WEAPON_UZI:
lara.holster = LARA_HOLSTERS_UZIS;
break;
}
}
void undraw_pistol_mesh_left(int weapon_type)//448F0(<), 44D54(<) (F)
{
if(weapon_type != WEAPON_REVOLVER)
{
WeaponObject(weapon_type);
lara.mesh_ptrs[LM_LHAND] = meshes[objects[LARA].mesh_index + 2 * LM_LHAND];
switch (weapon_type)
{
case WEAPON_PISTOLS:
lara.holster = LARA_HOLSTERS_PISTOLS;
break;
case WEAPON_UZI:
lara.holster = LARA_HOLSTERS_UZIS;
break;
}
}
}
void draw_pistol_meshes(int weapon_type)// (F)
{
lara.holster = LARA_HOLSTERS;
lara.mesh_ptrs[LM_RHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_RHAND];
if (weapon_type != WEAPON_REVOLVER)
{
lara.mesh_ptrs[LM_LHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_LHAND];
}
}
void ready_pistols(int weapon_type)// (F)
{
lara.gun_status = LG_READY;
lara.left_arm.z_rot = 0;
lara.left_arm.y_rot = 0;
lara.left_arm.x_rot = 0;
lara.right_arm.z_rot = 0;
lara.right_arm.y_rot = 0;
lara.right_arm.x_rot = 0;
lara.right_arm.frame_number = 0;
lara.left_arm.frame_number = 0;
lara.target = 0;
lara.right_arm.lock = 0;
lara.left_arm.lock = 0;
lara.right_arm.frame_base = lara.left_arm.frame_base = objects[WeaponObject(weapon_type)].frame_base;
}
void undraw_pistols(int weapon_type)//
{
UNIMPLEMENTED();
}
void draw_pistols(int weapon_type)//443B4, 44818 (F)
{
struct PISTOL_DEF* p = &PistolTable[lara.gun_type];//$a1
short ani = lara.left_arm.frame_number + 1;//$s1
//a3 = p->Draw1Anim
//v0 = p->RecoilAnim
if (ani < p->Draw1Anim || p->RecoilAnim - 1 < ani)
{
//loc_44420
ani = p->Draw1Anim;
}
else
{
//loc_44428
if (ani == p->Draw2Anim)
{
draw_pistol_meshes(weapon_type);
//a1 = lara_item
//a0 = 6
//a2 = 0;
SoundEffect(SFX_LARA_HOLSTER_DRAW, &lara_item->pos, 0);
//s0 = &lara.right_arm.frame_base
}//loc_44460
else if (ani == p->RecoilAnim - 1)
{
ready_pistols(weapon_type);
ani = 0;
}
}
set_arm_info(&lara.right_arm, ani);
set_arm_info(&lara.left_arm, ani);
}
void set_arm_info(struct lara_arm* arm/*a3*/, int frame/*a1*/)//44308 (F)
{
struct PISTOL_DEF* def = &PistolTable[lara.gun_type];//$a2
int anim_base = objects[def->ObjectNum].anim_index;//$a0
if (def->Draw1Anim != 0)
{
arm->anim_number = anim_base;
//j loc_44388
}
else
{
//loc_44358
if (frame >= def->Draw2Anim)
{
if (frame >= def->RecoilAnim)
{
//loc_44384
arm->anim_number = anim_base + 3;
}
else
{
//loc_44384
arm->anim_number = anim_base + 2;
}
}
else
{
//loc_44384
arm->anim_number = anim_base + 1;
}
}
arm->frame_number = frame;
arm->frame_base = anims[arm->anim_number].frame_ptr;
}
<commit_msg>[Game]: Correct set_arm_info.<commit_after>#include "LARA2GUN.H"
#include "SPECIFIC.H"
#include "LARA.H"
#include "LARAFIRE.H"
#ifdef PC_VERSION
#include "GAME.H"
#else
#include "SETUP.H"
#endif
#include "DRAW.H"
#include "OBJECTS.H"
#include "EFFECTS.H"
#include "SOUND.H"
static struct PISTOL_DEF PistolTable[4] =
{
{ LARA, 0, 0, 0, 0 },
{ PISTOLS_ANIM, 4, 5, 0xD, 0x18 },
{ REVOLVER_ANIM , 7, 8, 0xF, 0x1D },
{ UZI_ANIM, 4, 5, 0xD, 0x18 }
};
void AnimatePistols(int weapon_type)
{
UNIMPLEMENTED();
}
void PistolHandler(int weapon_type)
{
UNIMPLEMENTED();
}
void undraw_pistol_mesh_right(int weapon_type)//44968(<), 44DCC(<) (F)
{
WeaponObject(weapon_type);
lara.mesh_ptrs[LM_RHAND] = meshes[objects[LARA].mesh_index + 2 * LM_RHAND];
switch (weapon_type)
{
case WEAPON_PISTOLS:
lara.holster = LARA_HOLSTERS_PISTOLS;
break;
case WEAPON_REVOLVER:
lara.holster = LARA_HOLSTERS_REVOLVER;
break;
case WEAPON_UZI:
lara.holster = LARA_HOLSTERS_UZIS;
break;
}
}
void undraw_pistol_mesh_left(int weapon_type)//448F0(<), 44D54(<) (F)
{
if(weapon_type != WEAPON_REVOLVER)
{
WeaponObject(weapon_type);
lara.mesh_ptrs[LM_LHAND] = meshes[objects[LARA].mesh_index + 2 * LM_LHAND];
switch (weapon_type)
{
case WEAPON_PISTOLS:
lara.holster = LARA_HOLSTERS_PISTOLS;
break;
case WEAPON_UZI:
lara.holster = LARA_HOLSTERS_UZIS;
break;
}
}
}
void draw_pistol_meshes(int weapon_type)// (F)
{
lara.holster = LARA_HOLSTERS;
lara.mesh_ptrs[LM_RHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_RHAND];
if (weapon_type != WEAPON_REVOLVER)
{
lara.mesh_ptrs[LM_LHAND] = meshes[objects[WeaponObjectMesh(weapon_type)].mesh_index + 2 * LM_LHAND];
}
}
void ready_pistols(int weapon_type)// (F)
{
lara.gun_status = LG_READY;
lara.left_arm.z_rot = 0;
lara.left_arm.y_rot = 0;
lara.left_arm.x_rot = 0;
lara.right_arm.z_rot = 0;
lara.right_arm.y_rot = 0;
lara.right_arm.x_rot = 0;
lara.right_arm.frame_number = 0;
lara.left_arm.frame_number = 0;
lara.target = 0;
lara.right_arm.lock = 0;
lara.left_arm.lock = 0;
lara.right_arm.frame_base = lara.left_arm.frame_base = objects[WeaponObject(weapon_type)].frame_base;
}
void undraw_pistols(int weapon_type)//
{
UNIMPLEMENTED();
}
void draw_pistols(int weapon_type)//443B4, 44818 (F)
{
struct PISTOL_DEF* p = &PistolTable[lara.gun_type];//$a1
short ani = lara.left_arm.frame_number + 1;//$s1
//a3 = p->Draw1Anim
//v0 = p->RecoilAnim
if (ani < p->Draw1Anim || p->RecoilAnim - 1 < ani)
{
//loc_44420
ani = p->Draw1Anim;
}
else
{
//loc_44428
if (ani == p->Draw2Anim)
{
draw_pistol_meshes(weapon_type);
//a1 = lara_item
//a0 = 6
//a2 = 0;
SoundEffect(SFX_LARA_HOLSTER_DRAW, &lara_item->pos, 0);
//s0 = &lara.right_arm.frame_base
}//loc_44460
else if (ani == p->RecoilAnim - 1)
{
ready_pistols(weapon_type);
ani = 0;
}
}
set_arm_info(&lara.right_arm, ani);
set_arm_info(&lara.left_arm, ani);
}
void set_arm_info(struct lara_arm* arm/*a3*/, int frame/*a1*/)//44308, 4476C (F)
{
struct PISTOL_DEF* def = &PistolTable[lara.gun_type];//$a2
int anim_base = objects[def->ObjectNum].anim_index;//$a0
if (frame < def->Draw1Anim)
{
arm->anim_number = anim_base;
//j loc_44388
}
else
{
//loc_44358
if (frame >= def->Draw2Anim)
{
if (frame >= def->RecoilAnim)
{
//loc_44384
arm->anim_number = anim_base + 3;
}
else
{
//loc_44384
arm->anim_number = anim_base + 2;
}
}
else
{
//loc_44384
arm->anim_number = anim_base + 1;
}
}
arm->frame_number = frame;
arm->frame_base = anims[arm->anim_number].frame_ptr;
}
<|endoftext|> |
<commit_before><commit_msg>Crasher fix. Check for NULL.<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.