text
stringlengths 54
60.6k
|
---|
<commit_before>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/config.hpp"
#if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
#include <string>
#include <cstring>
#include <stdlib.h>
// uClibc++ doesn't have cxxabi.h
#if defined __GNUC__ && __GNUC__ >= 3 \
&& !defined __UCLIBCXX_MAJOR__
#include <cxxabi.h>
std::string demangle(char const* name)
{
// in case this string comes
// this is needed on linux
char const* start = strchr(name, '(');
if (start != 0)
{
++start;
}
else
{
// this is needed on macos x
start = strstr(name, "0x");
if (start != 0)
{
start = strchr(start, ' ');
if (start != 0) ++start;
else start = name;
}
else start = name;
}
char const* end = strchr(start, '+');
if (end) while (*(end-1) == ' ') --end;
std::string in;
if (end == 0) in.assign(start);
else in.assign(start, end);
size_t len;
int status;
char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status);
if (unmangled == 0) return in;
std::string ret(unmangled);
free(unmangled);
return ret;
}
#elif defined WIN32
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // XP
#include "windows.h"
#include "dbghelp.h"
std::string demangle(char const* name)
{
char demangled_name[256];
if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0)
demangled_name[0] = 0;
return demangled_name;
}
#else
std::string demangle(char const* name) { return name; }
#endif
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include "libtorrent/version.hpp"
// execinfo.h is available in the MacOS X 10.5 SDK.
#if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
#include <execinfo.h>
TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth)
{
void* stack[50];
int size = backtrace(stack, 50);
char** symbols = backtrace_symbols(stack, size);
for (int i = 1; i < size && len > 0; ++i)
{
int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str());
out += ret;
len -= ret;
if (i - 1 == max_depth && max_depth > 0) break;
}
free(symbols);
}
#elif defined WIN32
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // XP
#include "windows.h"
#include "libtorrent/utf8.hpp"
#include "winbase.h"
#include "dbghelp.h"
TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth)
{
typedef USHORT (*RtlCaptureStackBackTrace_t)(
__in ULONG FramesToSkip,
__in ULONG FramesToCapture,
__out PVOID *BackTrace,
__out_opt PULONG BackTraceHash);
static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0;
if (RtlCaptureStackBackTrace == 0)
{
// we don't actually have to free this library, everyone has it loaded
HMODULE lib = LoadLibrary(TEXT("kernel32.dll"));
RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace");
if (RtlCaptureStackBackTrace == 0)
{
out[0] = 0;
return;
}
}
int i;
void* stack[50];
int size = CaptureStackBackTrace(0, 50, stack, 0);
SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1);
symbol->MaxNameLen = MAX_SYM_NAME;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
HANDLE p = GetCurrentProcess();
static bool sym_initialized = false;
if (!sym_initialized)
{
sym_initialized = true;
SymInitialize(p, NULL, true);
}
for (i = 0; i < size && len > 0; ++i)
{
int ret;
if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol))
ret = snprintf(out, len, "%d: %s\n", i, symbol->Name);
else
ret = snprintf(out, len, "%d: <unknown>\n", i);
out += ret;
len -= ret;
if (i == max_depth && max_depth > 0) break;
}
free(symbol);
}
#else
TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) {}
#endif
#if TORRENT_PRODUCTION_ASSERTS
char const* libtorrent_assert_log = "asserts.log";
#endif
TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file
, char const* function, char const* value)
{
#if TORRENT_PRODUCTION_ASSERTS
FILE* out = fopen(libtorrent_assert_log, "a+");
if (out == 0) out = stderr;
#else
FILE* out = stderr;
#endif
char stack[8192];
print_backtrace(stack, sizeof(stack), 0);
fprintf(out, "assertion failed. Please file a bugreport at "
"http://code.rasterbar.com/libtorrent/newticket\n"
"Please include the following information:\n\n"
"version: " LIBTORRENT_VERSION "\n"
"%s\n"
"file: '%s'\n"
"line: %d\n"
"function: %s\n"
"expression: %s\n"
"%s%s\n"
"stack:\n"
"%s\n"
, LIBTORRENT_REVISION, file, line, function, expr
, value ? value : "", value ? "\n" : ""
, stack);
// if production asserts are defined, don't abort, just print the error
#if TORRENT_PRODUCTION_ASSERTS
if (out != stderr) fclose(out);
#else
// send SIGINT to the current process
// to break into the debugger
raise(SIGINT);
abort();
#endif
}
#else
TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file, char const* function) {}
#endif
<commit_msg>fix msvc-8 debug build<commit_after>/*
Copyright (c) 2007, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/config.hpp"
#if defined TORRENT_DEBUG || defined TORRENT_ASIO_DEBUGGING || TORRENT_RELEASE_ASSERTS
#ifdef __APPLE__
#include <AvailabilityMacros.h>
#endif
#include <string>
#include <cstring>
#include <stdlib.h>
// uClibc++ doesn't have cxxabi.h
#if defined __GNUC__ && __GNUC__ >= 3 \
&& !defined __UCLIBCXX_MAJOR__
#include <cxxabi.h>
std::string demangle(char const* name)
{
// in case this string comes
// this is needed on linux
char const* start = strchr(name, '(');
if (start != 0)
{
++start;
}
else
{
// this is needed on macos x
start = strstr(name, "0x");
if (start != 0)
{
start = strchr(start, ' ');
if (start != 0) ++start;
else start = name;
}
else start = name;
}
char const* end = strchr(start, '+');
if (end) while (*(end-1) == ' ') --end;
std::string in;
if (end == 0) in.assign(start);
else in.assign(start, end);
size_t len;
int status;
char* unmangled = ::abi::__cxa_demangle(in.c_str(), 0, &len, &status);
if (unmangled == 0) return in;
std::string ret(unmangled);
free(unmangled);
return ret;
}
#elif defined WIN32
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // XP
#include "windows.h"
#include "dbghelp.h"
std::string demangle(char const* name)
{
char demangled_name[256];
if (UnDecorateSymbolName(name, demangled_name, sizeof(demangled_name), UNDNAME_NO_THROW_SIGNATURES) == 0)
demangled_name[0] = 0;
return demangled_name;
}
#else
std::string demangle(char const* name) { return name; }
#endif
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include "libtorrent/version.hpp"
// execinfo.h is available in the MacOS X 10.5 SDK.
#if (defined __linux__ || (defined __APPLE__ && MAC_OS_X_VERSION_MIN_REQUIRED >= 1050))
#include <execinfo.h>
TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth)
{
void* stack[50];
int size = backtrace(stack, 50);
char** symbols = backtrace_symbols(stack, size);
for (int i = 1; i < size && len > 0; ++i)
{
int ret = snprintf(out, len, "%d: %s\n", i, demangle(symbols[i]).c_str());
out += ret;
len -= ret;
if (i - 1 == max_depth && max_depth > 0) break;
}
free(symbols);
}
// visual studio 9 and up appears to support this
#elif defined WIN32 && _MSC_VER >= 1500
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0501 // XP
#include "windows.h"
#include "libtorrent/utf8.hpp"
#include "winbase.h"
#include "dbghelp.h"
TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth)
{
typedef USHORT (*RtlCaptureStackBackTrace_t)(
__in ULONG FramesToSkip,
__in ULONG FramesToCapture,
__out PVOID *BackTrace,
__out_opt PULONG BackTraceHash);
static RtlCaptureStackBackTrace_t RtlCaptureStackBackTrace = 0;
if (RtlCaptureStackBackTrace == 0)
{
// we don't actually have to free this library, everyone has it loaded
HMODULE lib = LoadLibrary(TEXT("kernel32.dll"));
RtlCaptureStackBackTrace = (RtlCaptureStackBackTrace_t)GetProcAddress(lib, "RtlCaptureStackBackTrace");
if (RtlCaptureStackBackTrace == 0)
{
out[0] = 0;
return;
}
}
int i;
void* stack[50];
int size = CaptureStackBackTrace(0, 50, stack, 0);
SYMBOL_INFO* symbol = (SYMBOL_INFO*)calloc(sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR), 1);
symbol->MaxNameLen = MAX_SYM_NAME;
symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
HANDLE p = GetCurrentProcess();
static bool sym_initialized = false;
if (!sym_initialized)
{
sym_initialized = true;
SymInitialize(p, NULL, true);
}
for (i = 0; i < size && len > 0; ++i)
{
int ret;
if (SymFromAddr(p, uintptr_t(stack[i]), 0, symbol))
ret = snprintf(out, len, "%d: %s\n", i, symbol->Name);
else
ret = snprintf(out, len, "%d: <unknown>\n", i);
out += ret;
len -= ret;
if (i == max_depth && max_depth > 0) break;
}
free(symbol);
}
#else
TORRENT_EXPORT void print_backtrace(char* out, int len, int max_depth) {}
#endif
#if TORRENT_PRODUCTION_ASSERTS
char const* libtorrent_assert_log = "asserts.log";
#endif
TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file
, char const* function, char const* value)
{
#if TORRENT_PRODUCTION_ASSERTS
FILE* out = fopen(libtorrent_assert_log, "a+");
if (out == 0) out = stderr;
#else
FILE* out = stderr;
#endif
char stack[8192];
print_backtrace(stack, sizeof(stack), 0);
fprintf(out, "assertion failed. Please file a bugreport at "
"http://code.rasterbar.com/libtorrent/newticket\n"
"Please include the following information:\n\n"
"version: " LIBTORRENT_VERSION "\n"
"%s\n"
"file: '%s'\n"
"line: %d\n"
"function: %s\n"
"expression: %s\n"
"%s%s\n"
"stack:\n"
"%s\n"
, LIBTORRENT_REVISION, file, line, function, expr
, value ? value : "", value ? "\n" : ""
, stack);
// if production asserts are defined, don't abort, just print the error
#if TORRENT_PRODUCTION_ASSERTS
if (out != stderr) fclose(out);
#else
// send SIGINT to the current process
// to break into the debugger
raise(SIGINT);
abort();
#endif
}
#else
TORRENT_EXPORT void assert_fail(char const* expr, int line, char const* file, char const* function) {}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2011 Vince Durham
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "auxpow.h"
#include "init.h"
using namespace std;
using namespace boost;
unsigned char pchMergedMiningHeader[] = { 0xfa, 0xbe, 'm', 'm' } ;
void RemoveMergedMiningHeader(vector<unsigned char>& vchAux)
{
if (vchAux.begin() != std::search(vchAux.begin(), vchAux.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
throw runtime_error("merged mining aux too short");
vchAux.erase(vchAux.begin(), vchAux.begin() + sizeof(pchMergedMiningHeader));
}
bool CAuxPow::Check(uint256 hashAuxBlock, int nChainID)
{
if (nIndex != 0)
return error("AuxPow is not a generate");
if (!fTestNet && parentBlock.GetChainID() == nChainID)
return error("Aux POW parent has our chain ID");
if (vChainMerkleBranch.size() > 30)
return error("Aux POW chain merkle branch too long");
// Check that the chain merkle root is in the coinbase
uint256 nRootHash = CBlock::CheckMerkleBranch(hashAuxBlock, vChainMerkleBranch, nChainIndex);
vector<unsigned char> vchRootHash(nRootHash.begin(), nRootHash.end());
std::reverse(vchRootHash.begin(), vchRootHash.end()); // correct endian
// Check that we are in the parent block merkle tree
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != parentBlock.hashMerkleRoot)
return error("Aux POW merkle root incorrect");
const CScript script = vin[0].scriptSig;
// Check that the same work is not submitted twice to our chain.
//
CScript::const_iterator pcHead =
std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
CScript::const_iterator pc =
std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());
if (pc == script.end())
return error("Aux POW missing chain merkle root in parent coinbase");
if (pcHead != script.end())
{
// Enforce only one chain merkle root by checking that a single instance of the merged
// mining header exists just before.
if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
return error("Multiple merged mining headers in coinbase");
if (pcHead + sizeof(pchMergedMiningHeader) != pc)
return error("Merged mining header is not just before chain merkle root");
}
else
{
// For backward compatibility.
// Enforce only one chain merkle root by checking that it starts early in the coinbase.
// 8-12 bytes are enough to encode extraNonce and nBits.
if (pc - script.begin() > 20)
return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase");
}
// Ensure we are at a deterministic point in the merkle leaves by hashing
// a nonce and our chain ID and comparing to the index.
pc += vchRootHash.size();
if (script.end() - pc < 8)
return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");
int nSize;
memcpy(&nSize, &pc[0], 4);
if (nSize != (1 << vChainMerkleBranch.size()))
return error("Aux POW merkle branch size does not match parent coinbase");
int nNonce;
memcpy(&nNonce, &pc[4], 4);
// Choose a pseudo-random slot in the chain merkle tree
// but have it be fixed for a size/nonce/chain combination.
//
// This prevents the same work from being used twice for the
// same chain while reducing the chance that two chains clash
// for the same slot.
int rand = nNonce;
rand = rand * 1103515245 + 12345;
rand += nChainID;
rand = rand * 1103515245 + 12345;
if (nChainIndex != (rand % nSize))
return error("Aux POW wrong index");
return true;
}
CScript MakeCoinbaseWithAux(unsigned int nHeight, unsigned int nExtraNonce,
vector<unsigned char>& vchAux) {
vector<unsigned char> vchAuxWithHeader(UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
vchAuxWithHeader.insert(vchAuxWithHeader.end(), vchAux.begin(), vchAux.end());
// Push OP_2 just in case we want versioning later
/* BIP34: v2 coin base must start with nHeight */
return CScript() << nHeight << CBigNum(nExtraNonce) << COINBASE_FLAGS << OP_2 << vchAuxWithHeader;
}
void IncrementExtraNonceWithAux(CBlock* pblock, CBlockIndex* pindexPrev,
unsigned int& nExtraNonce, vector<unsigned char>& vchAux) {
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
pblock->vtx[0].vin[0].scriptSig = MakeCoinbaseWithAux(pindexPrev->nHeight + 1, nExtraNonce, vchAux);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
<commit_msg>MakeCoinbaseWithAux() Fixed<commit_after>// Copyright (c) 2011 Vince Durham
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "script.h"
#include "auxpow.h"
#include "init.h"
using namespace std;
using namespace boost;
unsigned char pchMergedMiningHeader[] = { 0xfa, 0xbe, 'm', 'm' } ;
void RemoveMergedMiningHeader(vector<unsigned char>& vchAux)
{
if (vchAux.begin() != std::search(vchAux.begin(), vchAux.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
throw runtime_error("merged mining aux too short");
vchAux.erase(vchAux.begin(), vchAux.begin() + sizeof(pchMergedMiningHeader));
}
bool CAuxPow::Check(uint256 hashAuxBlock, int nChainID)
{
if (nIndex != 0)
return error("AuxPow is not a generate");
if (!fTestNet && parentBlock.GetChainID() == nChainID)
return error("Aux POW parent has our chain ID");
if (vChainMerkleBranch.size() > 30)
return error("Aux POW chain merkle branch too long");
// Check that the chain merkle root is in the coinbase
uint256 nRootHash = CBlock::CheckMerkleBranch(hashAuxBlock, vChainMerkleBranch, nChainIndex);
vector<unsigned char> vchRootHash(nRootHash.begin(), nRootHash.end());
std::reverse(vchRootHash.begin(), vchRootHash.end()); // correct endian
// Check that we are in the parent block merkle tree
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != parentBlock.hashMerkleRoot)
return error("Aux POW merkle root incorrect");
const CScript script = vin[0].scriptSig;
// Check that the same work is not submitted twice to our chain.
//
CScript::const_iterator pcHead =
std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
CScript::const_iterator pc =
std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());
if (pc == script.end())
return error("Aux POW missing chain merkle root in parent coinbase");
if (pcHead != script.end())
{
// Enforce only one chain merkle root by checking that a single instance of the merged
// mining header exists just before.
if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
return error("Multiple merged mining headers in coinbase");
if (pcHead + sizeof(pchMergedMiningHeader) != pc)
return error("Merged mining header is not just before chain merkle root");
}
else
{
// For backward compatibility.
// Enforce only one chain merkle root by checking that it starts early in the coinbase.
// 8-12 bytes are enough to encode extraNonce and nBits.
if (pc - script.begin() > 20)
return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase");
}
// Ensure we are at a deterministic point in the merkle leaves by hashing
// a nonce and our chain ID and comparing to the index.
pc += vchRootHash.size();
if (script.end() - pc < 8)
return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");
int nSize;
memcpy(&nSize, &pc[0], 4);
if (nSize != (1 << vChainMerkleBranch.size()))
return error("Aux POW merkle branch size does not match parent coinbase");
int nNonce;
memcpy(&nNonce, &pc[4], 4);
// Choose a pseudo-random slot in the chain merkle tree
// but have it be fixed for a size/nonce/chain combination.
//
// This prevents the same work from being used twice for the
// same chain while reducing the chance that two chains clash
// for the same slot.
int rand = nNonce;
rand = rand * 1103515245 + 12345;
rand += nChainID;
rand = rand * 1103515245 + 12345;
if (nChainIndex != (rand % nSize))
return error("Aux POW wrong index");
return true;
}
CScript MakeCoinbaseWithAux(unsigned int nHeight, unsigned int nExtraNonce,
vector<unsigned char>& vchAux) {
vector<unsigned char> vchAuxWithHeader(UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
vchAuxWithHeader.insert(vchAuxWithHeader.end(), vchAux.begin(), vchAux.end());
// Push OP_2 just in case we want versioning later
/* BIP34: v2 coin base must start with nHeight */
return(((CScript() << nHeight << CBigNum(nExtraNonce)) + COINBASE_FLAGS) << OP_2 << vchAuxWithHeader);
}
void IncrementExtraNonceWithAux(CBlock* pblock, CBlockIndex* pindexPrev,
unsigned int& nExtraNonce, vector<unsigned char>& vchAux) {
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
pblock->vtx[0].vin[0].scriptSig = MakeCoinbaseWithAux(pindexPrev->nHeight + 1, nExtraNonce, vchAux);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
<|endoftext|> |
<commit_before><commit_msg>Remove iOS references in chrome_browser_main_extra_parts_profiles.cc<commit_after><|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* A Use Case for In Situ visulization frameworks (Conduit, SENSEI)
*
* Each processor contributes to a subset of all variables
* Each variable is written by a subset of all processes
* The per-writer-blocks in a variable have different sizes
* The variable cannot be nicely defined as a global array
*
* We still define the variables in this writer as global arrays but
* with k+1 dimensions for each variable, where the extra dimension is
* used as an index to the writer blocks. The other dimensions are
* defined as huge numbers to cover all possible dimension sizes on each
* process.
*
* The reader needs to discover the content of each variable block-by-block.
* It cannot rely on the global shape of the variable as most of it is empty.
*
* The global dimensions of a global array MUST NOT change over time.
* The decomposition of the array across the processes, however, can change
* between output steps.
*
* Created on: Jul 11, 2017
* Author: pnorbert
*/
#include <algorithm> // std::transform
#include <iostream>
#include <vector>
#include <adios2.h>
#ifdef ADIOS2_HAVE_MPI
#include <mpi.h>
MPI_Comm writerComm;
#endif
const int NSTEPS = 5;
const int BIGDIM = 1000;
/* Variables:
a: size 8, written by rank 0 (5 elements) and rank 1 (3 elements)
b: size 9, written by rank 0 (5 elements) and rank 2 (4 elements)
c: size 10, written by rank 0 (5 elements) and rank 3 (5 elements)
d: size 7, written by rank 1 (3 elements) and rank 2 (4 elements)
Variables in the output:
2D arrays, 4 x BIGDIM
*/
// Which process writes which variables
std::vector<std::vector<std::string>> VarTree = {
{"a", "b", "c"}, {"a", "d"}, {"b", "d"}, {"c"}};
// What size of data do they write
std::vector<std::vector<size_t>> SizesTree = {
{5, 5, 5}, {3, 3}, {4, 4}, {5, 5}};
std::string argEngine = "BPFile";
adios2::Params engineParams;
void ProcessArgs(int rank, int argc, char *argv[])
{
if (argc > 1)
{
argEngine = argv[1];
}
std::string elc = argEngine;
std::transform(elc.begin(), elc.end(), elc.begin(), ::tolower);
if (elc == "sst")
{
engineParams["MarshalMethod"] = "BP";
}
else if (elc == "insitumpi")
{
engineParams["verbose"] = "3";
}
}
int main(int argc, char *argv[])
{
int rank = 0, nproc = 1;
#ifdef ADIOS2_HAVE_MPI
MPI_Init(&argc, &argv);
int wrank, wnproc;
MPI_Comm_rank(MPI_COMM_WORLD, &wrank);
MPI_Comm_size(MPI_COMM_WORLD, &wnproc);
const unsigned int color = 1;
MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &writerComm);
MPI_Comm_rank(writerComm, &rank);
MPI_Comm_size(writerComm, &nproc);
#endif
const int maxProc = VarTree.size();
if (nproc > maxProc)
{
if (!rank)
{
std::cout
<< "ERROR: Maximum number of processors for this example is "
<< maxProc << std::endl;
}
exit(1);
}
ProcessArgs(rank, argc, argv);
if (!rank)
{
std::cout << "Writer: ADIOS2 Engine set to: " << argEngine
<< " Parameters:";
for (auto &p : engineParams)
{
std::cout << " " << p.first << " = " << p.second;
}
std::cout << std::endl;
}
#ifdef ADIOS2_HAVE_MPI
adios2::ADIOS adios(writerComm);
#else
adios2::ADIOS adios;
#endif
// We have a varying number of vars on each processor
const int nvars = VarTree[rank].size();
// A 1D array for each variable
std::vector<std::vector<double>> Vars(nvars);
for (int i = 0; i < nvars; i++)
{
Vars[i].resize(SizesTree[rank][i]);
}
std::vector<adios2::Variable<double>> ADIOSVars(nvars);
try
{
adios2::IO io = adios.DeclareIO("Output");
io.SetEngine(argEngine);
io.SetParameters(engineParams);
for (int i = 0; i < nvars; i++)
{
size_t nelems = SizesTree[rank][i];
Vars[i].resize(nelems);
ADIOSVars[i] = io.DefineVariable<double>(
VarTree[rank][i], {(unsigned int)nproc, BIGDIM});
}
adios2::Engine writer = io.Open("output.bp", adios2::Mode::Write);
for (int step = 0; step < NSTEPS; step++)
{
writer.BeginStep();
for (int i = 0; i < nvars; i++)
{
size_t nelems = SizesTree[rank][i];
for (int j = 0; j < nelems; j++)
{
Vars[i][j] = (double)step / 100.0 + (double)rank;
}
// Make a 2D selection to describe the local dimensions of the
// variable we write and its offsets in the global spaces
// adios2::SelectionBoundingBox sel();
ADIOSVars[i].SetSelection(adios2::Box<adios2::Dims>(
{static_cast<size_t>(rank), 0},
{1, static_cast<size_t>(nelems)}));
writer.Put<double>(ADIOSVars[i], Vars[i].data());
}
// Indicate we are done for this step.
// Disk I/O will be performed during this call unless
// time aggregation postpones all of that to some later step
writer.EndStep();
}
// Called once: indicate that we are done with this output for the run
writer.Close();
}
catch (std::invalid_argument &e)
{
if (rank == 0)
{
std::cout << "Invalid argument exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
catch (std::ios_base::failure &e)
{
if (rank == 0)
{
std::cout << "System exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
catch (std::exception &e)
{
if (rank == 0)
{
std::cout << "Exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
#ifdef ADIOS2_HAVE_MPI
MPI_Finalize();
#endif
return 0;
}
<commit_msg>fix type conversion warnings<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* A Use Case for In Situ visulization frameworks (Conduit, SENSEI)
*
* Each processor contributes to a subset of all variables
* Each variable is written by a subset of all processes
* The per-writer-blocks in a variable have different sizes
* The variable cannot be nicely defined as a global array
*
* We still define the variables in this writer as global arrays but
* with k+1 dimensions for each variable, where the extra dimension is
* used as an index to the writer blocks. The other dimensions are
* defined as huge numbers to cover all possible dimension sizes on each
* process.
*
* The reader needs to discover the content of each variable block-by-block.
* It cannot rely on the global shape of the variable as most of it is empty.
*
* The global dimensions of a global array MUST NOT change over time.
* The decomposition of the array across the processes, however, can change
* between output steps.
*
* Created on: Jul 11, 2017
* Author: pnorbert
*/
#include <algorithm> // std::transform
#include <iostream>
#include <vector>
#include <adios2.h>
#ifdef ADIOS2_HAVE_MPI
#include <mpi.h>
MPI_Comm writerComm;
#endif
const size_t NSTEPS = 5;
const size_t BIGDIM = 1000;
/* Variables:
a: size 8, written by rank 0 (5 elements) and rank 1 (3 elements)
b: size 9, written by rank 0 (5 elements) and rank 2 (4 elements)
c: size 10, written by rank 0 (5 elements) and rank 3 (5 elements)
d: size 7, written by rank 1 (3 elements) and rank 2 (4 elements)
Variables in the output:
2D arrays, 4 x BIGDIM
*/
// Which process writes which variables
std::vector<std::vector<std::string>> VarTree = {
{"a", "b", "c"}, {"a", "d"}, {"b", "d"}, {"c"}};
// What size of data do they write
std::vector<std::vector<size_t>> SizesTree = {
{5, 5, 5}, {3, 3}, {4, 4}, {5, 5}};
std::string argEngine = "BPFile";
adios2::Params engineParams;
void ProcessArgs(int rank, int argc, char *argv[])
{
if (argc > 1)
{
argEngine = argv[1];
}
std::string elc = argEngine;
std::transform(elc.begin(), elc.end(), elc.begin(), ::tolower);
if (elc == "sst")
{
engineParams["MarshalMethod"] = "BP";
}
else if (elc == "insitumpi")
{
engineParams["verbose"] = "5";
}
}
int main(int argc, char *argv[])
{
int rank = 0, nproc = 1;
#ifdef ADIOS2_HAVE_MPI
MPI_Init(&argc, &argv);
int wrank, wnproc;
MPI_Comm_rank(MPI_COMM_WORLD, &wrank);
MPI_Comm_size(MPI_COMM_WORLD, &wnproc);
const unsigned int color = 1;
MPI_Comm_split(MPI_COMM_WORLD, color, wrank, &writerComm);
MPI_Comm_rank(writerComm, &rank);
MPI_Comm_size(writerComm, &nproc);
#endif
const size_t maxProc = VarTree.size();
if (nproc > maxProc)
{
if (!rank)
{
std::cout
<< "ERROR: Maximum number of processors for this example is "
<< maxProc << std::endl;
}
exit(1);
}
ProcessArgs(rank, argc, argv);
if (!rank)
{
std::cout << "Writer: ADIOS2 Engine set to: " << argEngine
<< " Parameters:";
for (auto &p : engineParams)
{
std::cout << " " << p.first << " = " << p.second;
}
std::cout << std::endl;
}
#ifdef ADIOS2_HAVE_MPI
adios2::ADIOS adios(writerComm);
#else
adios2::ADIOS adios;
#endif
// We have a varying number of vars on each processor
const size_t nvars = VarTree[rank].size();
// A 1D array for each variable
std::vector<std::vector<double>> Vars(nvars);
for (int i = 0; i < nvars; i++)
{
Vars[i].resize(SizesTree[rank][i]);
}
std::vector<adios2::Variable<double>> ADIOSVars(nvars);
try
{
adios2::IO io = adios.DeclareIO("Output");
io.SetEngine(argEngine);
io.SetParameters(engineParams);
for (int i = 0; i < nvars; i++)
{
size_t nelems = SizesTree[rank][i];
Vars[i].resize(nelems);
ADIOSVars[i] = io.DefineVariable<double>(
VarTree[rank][i], {(unsigned int)nproc, BIGDIM});
}
adios2::Engine writer = io.Open("output.bp", adios2::Mode::Write);
for (int step = 0; step < NSTEPS; step++)
{
writer.BeginStep();
for (int i = 0; i < nvars; i++)
{
size_t nelems = SizesTree[rank][i];
for (int j = 0; j < nelems; j++)
{
Vars[i][j] = ((double)step + 1.0) / 100.0 + (double)rank;
}
// Make a 2D selection to describe the local dimensions of the
// variable we write and its offsets in the global spaces
// adios2::SelectionBoundingBox sel();
ADIOSVars[i].SetSelection(adios2::Box<adios2::Dims>(
{static_cast<size_t>(rank), 0},
{1, static_cast<size_t>(nelems)}));
writer.Put<double>(ADIOSVars[i], Vars[i].data());
}
// Indicate we are done for this step.
// Disk I/O will be performed during this call unless
// time aggregation postpones all of that to some later step
writer.EndStep();
}
// Called once: indicate that we are done with this output for the run
writer.Close();
}
catch (std::invalid_argument &e)
{
if (rank == 0)
{
std::cout << "Invalid argument exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
catch (std::ios_base::failure &e)
{
if (rank == 0)
{
std::cout << "System exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
catch (std::exception &e)
{
if (rank == 0)
{
std::cout << "Exception, STOPPING PROGRAM\n";
std::cout << e.what() << "\n";
}
}
#ifdef ADIOS2_HAVE_MPI
MPI_Finalize();
#endif
return 0;
}
<|endoftext|> |
<commit_before>#pragma once
#include "renderer.hpp"
#include "../gl3companion/gldebug.hpp"
#include "../gl3companion/glframebuffers.hpp"
#include "../gl3companion/glresource_types.hpp"
#include "../gl3companion/glshaders.hpp"
#include "../gl3companion/gltexturing.hpp"
#include <vector>
using FramebufferDef = TextureDef;
namespace
{
bool isEqual(TextureDef const& a, TextureDef const& b)
{
return a.data == b.data
&& a.width == b.width
&& a.height == b.height
&& a.depth == b.depth
&& a.pixelFiller == b.pixelFiller;
}
void framebufferPixelFiller(uint32_t* pixels, int width, int height,
int depth, void const* data)
{
printf("data: %p\n", data);
// this function is just an identifier
printf("ERROR: I should not be called, framebuffer: %d\n", *((GLint*)data));
}
}
// persistent datastructure... the core of the infrastructure
class FrameSeries
{
public:
~FrameSeries()
{
printf("summary:\n");
printf("program creations: %ld\n", programCreations);
printf("texture creations: %ld\n", textureCreations);
printf("mesh creations: %ld\n"
"meshes: %ld\n",
meshCreations,
meshes.size());
printf("framebuffer creations: %ld\n"
"framebuffers: %ld\n",
framebufferCreations,
framebuffers.size());
}
void beginFrame()
{
// we should invalidate arrays so as to garbage
// collect / recycle the now un-needed definitions
reset(meshHeap);
reset(textureHeap);
reset(programHeap);
struct FramebufferMaterials {
GLuint framebufferId;
TextureDef textureDef;
};
FramebufferMaterials framebuffer(FramebufferDef framebufferDef)
{
auto fbIndex = findOrCreate<FramebufferDef>
(framebufferHeap,
framebufferDef,
[&framebufferDef](FramebufferDef const& element) {
return isEqual(element, framebufferDef);
},
[=](FramebufferDef const& def, size_t framebufferIndex) {
framebuffers.resize(1 + framebufferIndex);
auto& framebuffer = framebuffers[framebufferIndex];
auto txIndex = findOrCreate<TextureDef>
(textureHeap,
framebufferDef,
[&framebufferDef](TextureDef const& element) {
return isEqual(element, framebufferDef);
},
[=](TextureDef const& def, size_t index) {
textures.resize(index + 1);
},
[=](size_t indexA, size_t indexB) {
std::swap(textures[indexA], textures[indexB]);
}
);
auto& texture = textures[txIndex];
texture.target = GL_TEXTURE_2D;
createImageCaptureFramebuffer(framebuffer.resource, texture.resource,
framebuffer.depthbuffer, { framebufferDef.width, framebufferDef.height });
framebufferCreations++;
auto textureDef = framebufferDef;
textureDef.data.resize(sizeof(GLint));
*((GLint*) &textureDef.data.front()) = framebuffer.resource.id;
textureDef.pixelFiller = framebufferPixelFiller;
textureDefs[txIndex] = textureDef;
framebuffer.textureDef = textureDef;
framebufferDefs[framebufferIndex] = textureDef;
},
[=](size_t indexA, size_t indexB) {
std::swap(framebuffers[indexA], framebuffers[indexB]);
});
auto const& framebuffer = framebuffers[fbIndex];
return { framebuffer.resource.id, framebuffer.textureDef };
}
struct MeshMaterials {
GLuint vertexArray;
size_t indicesCount;
GLuint indicesBuffer;
std::vector<GLuint> vertexBuffers;
};
MeshMaterials mesh(GeometryDef geometryDef)
{
auto meshIndex = findOrCreate<GeometryDef>
(meshHeap,
geometryDef,
[&geometryDef](GeometryDef const& element) {
return element.data == geometryDef.data
&& element.definer == geometryDef.definer
&& element.arrayCount == geometryDef.arrayCount;
},
[=](GeometryDef const& def, size_t meshIndex) {
meshes.resize(1 + meshIndex);
auto& mesh = meshes[meshIndex];
if (def.definer) {
mesh.vertexBuffers.resize(def.arrayCount);
mesh.indicesCount = def.definer
(mesh.indices,
&mesh.vertexBuffers.front(),
&def.data.front());
}
meshCreations++;
},
[=](size_t indexA, size_t indexB) {
std::swap(meshes.at(indexA), meshes.at(indexB));
});
auto const& mesh = meshes.at(meshIndex);
auto vertexBufferIds = std::vector<GLuint> {};
std::transform(std::begin(mesh.vertexBuffers),
std::end(mesh.vertexBuffers),
std::back_inserter(vertexBufferIds),
[](BufferResource const& element) {
return element.id;
});
return {
mesh.vertexArray.id,
mesh.indicesCount,
mesh.indices.id,
vertexBufferIds
};
}
struct TextureMaterials {
GLuint textureId;
GLenum target;
};
TextureMaterials texture(TextureDef textureDef)
{
auto index = findOrCreate<TextureDef>(textureHeap,
textureDef,
[&textureDef](TextureDef const& element) {
return isEqual(element, textureDef);
},
[=](TextureDef const& def, size_t index) {
textures.resize(index + 1);
auto& texture = textures[index];
if (def.width > 0 && def.height > 0 && def.depth > 0) {
texture.target = GL_TEXTURE_3D;
} else if (def.width > 0 && def.height > 0) {
texture.target = GL_TEXTURE_2D;
} else if (def.width > 0) {
texture.target = GL_TEXTURE_1D;
} else {
texture.target = 0;
}
OGL_TRACE;
switch(texture.target) {
case GL_TEXTURE_2D:
glBindTexture(texture.target, texture.resource.id);
defineNonMipmappedARGB32Texture(def.width,
def.height,
[&def](uint32_t* data, int width, int height) {
def.pixelFiller(data, width, height, 0, &def.data.front());
});
break;
case GL_TEXTURE_3D:
glBindTexture(texture.target, texture.resource.id);
defineNonMipmappedARGB32Texture3d(def.width,
def.height,
def.depth,
[&def](uint32_t* data, int width, int height, int depth) {
def.pixelFiller(data, width, height, depth, &def.data.front());
});
break;
};
glBindTexture(texture.target, 0);
OGL_TRACE;
textureCreations++;
},
[=](size_t indexA, size_t indexB) {
std::swap(textures[indexA], textures[indexB]);
});
auto const& texture = textures[index];
return { texture.resource.id, texture.target };
}
struct ShaderProgramMaterials {
GLuint programId;
};
ShaderProgramMaterials program(ProgramDef programDef)
{
auto index = findOrCreate<ProgramDef>
(programHeap,
programDef,
[&programDef](ProgramDef const& element) {
return element.fragmentShader.source
== programDef.fragmentShader.source
&& element.vertexShader.source
== programDef.vertexShader.source;
},
[=](ProgramDef const& def, size_t index) {
programs.resize(index + 1);
vertexShaders.resize(index + 1);
fragmentShaders.resize(index + 1);
auto& program = programs[index];
auto& vertexShader = vertexShaders[index];
auto& fragmentShader = fragmentShaders[index];
compile(vertexShader, programDef.vertexShader.source);
compile(fragmentShader, programDef.fragmentShader.source);
link(program, vertexShader, fragmentShader);
OGL_TRACE;
programCreations++;
},
[=](size_t indexA, size_t indexB) {
std::swap(programs[indexA], programs[indexB]);
std::swap(vertexShaders[indexA], vertexShaders[indexB]);
std::swap(fragmentShaders[indexA], fragmentShaders[indexB]);
});
return { programs[index].id };
}
private:
// returns index to use (and create an entry if missing)
template <typename ResourceDef>
size_t findOrCreateDef(std::vector<ResourceDef>& definitions,
ResourceDef const& def,
std::function<bool(ResourceDef const&)> isDef,
size_t firstRecyclableIndex)
{
auto existing =
std::find_if(std::begin(definitions),
std::end(definitions),
isDef);
if (existing != std::end(definitions)) {
return &(*existing) - &definitions.front();
} else {
auto index = firstRecyclableIndex;
if (index >= definitions.size()) {
definitions.resize(1 + index);
}
definitions[index] = def;
return index;
}
}
template <typename ResourceDef>
struct RecyclingHeap {
size_t firstInactiveIndex;
size_t firstRecyclableIndex;
std::vector<ResourceDef>& definitions;
};
template <typename ResourceDef>
void reset(RecyclingHeap<ResourceDef>& heap)
{
heap.firstRecyclableIndex = heap.firstInactiveIndex;
heap.firstInactiveIndex = 0;
}
template <typename ResourceDef>
size_t findOrCreate(RecyclingHeap<ResourceDef>& heap,
ResourceDef const& def,
std::function<bool(ResourceDef const&)> isDef,
std::function<void(ResourceDef const&,size_t)> createAt,
std::function<void(size_t,size_t)> swap)
{
auto index = findOrCreateDef(heap.definitions,
def,
isDef,
heap.firstRecyclableIndex);
if (index == heap.firstRecyclableIndex) {
heap.firstRecyclableIndex++;
createAt(def, index);
}
auto newIndex = index;
if (heap.firstInactiveIndex < newIndex) {
newIndex = heap.firstInactiveIndex;
std::swap(heap.definitions.at(newIndex), heap.definitions.at(index));
swap(newIndex, index);
}
heap.firstInactiveIndex = newIndex + 1;
return newIndex;
}
struct Mesh {
VertexArrayResource vertexArray;
size_t indicesCount = 0;
BufferResource indices;
std::vector<BufferResource> vertexBuffers;
};
struct Framebuffer {
FramebufferResource resource;
RenderbufferResource depthbuffer;
TextureDef textureDef;
};
std::vector<Framebuffer> framebuffers;
std::vector<FramebufferDef> framebufferDefs;
RecyclingHeap<FramebufferDef> framebufferHeap = { 0, 0, framebufferDefs };
long framebufferCreations = 0;
std::vector<Mesh> meshes;
std::vector<GeometryDef> meshDefs;
RecyclingHeap<GeometryDef> meshHeap = { 0, 0, meshDefs };
long meshCreations = 0;
struct Texture {
TextureResource resource;
GLenum target;
};
std::vector<Texture> textures;
std::vector<TextureDef> textureDefs;
RecyclingHeap<TextureDef> textureHeap = { 0, 0, textureDefs };
long textureCreations = 0;
std::vector<VertexShaderResource> vertexShaders;
std::vector<FragmentShaderResource> fragmentShaders;
std::vector<ShaderProgramResource> programs;
std::vector<ProgramDef> programDefs;
RecyclingHeap<ProgramDef> programHeap = { 0, 0, programDefs };
long programCreations = 0;
};
<commit_msg>reset also the framebuffer heap<commit_after>#pragma once
#include "renderer.hpp"
#include "../gl3companion/gldebug.hpp"
#include "../gl3companion/glframebuffers.hpp"
#include "../gl3companion/glresource_types.hpp"
#include "../gl3companion/glshaders.hpp"
#include "../gl3companion/gltexturing.hpp"
#include <vector>
using FramebufferDef = TextureDef;
namespace
{
bool isEqual(TextureDef const& a, TextureDef const& b)
{
return a.data == b.data
&& a.width == b.width
&& a.height == b.height
&& a.depth == b.depth
&& a.pixelFiller == b.pixelFiller;
}
void framebufferPixelFiller(uint32_t* pixels, int width, int height,
int depth, void const* data)
{
printf("data: %p\n", data);
// this function is just an identifier
printf("ERROR: I should not be called, framebuffer: %d\n", *((GLint*)data));
}
}
// persistent datastructure... the core of the infrastructure
class FrameSeries
{
public:
~FrameSeries()
{
printf("summary:\n");
printf("program creations: %ld\n", programCreations);
printf("texture creations: %ld\n", textureCreations);
printf("mesh creations: %ld\n"
"meshes: %ld\n",
meshCreations,
meshes.size());
printf("framebuffer creations: %ld\n"
"framebuffers: %ld\n",
framebufferCreations,
framebuffers.size());
}
void beginFrame()
{
// we should invalidate arrays so as to garbage
// collect / recycle the now un-needed definitions
reset(framebufferHeap);
reset(meshHeap);
reset(textureHeap);
reset(programHeap);
}
struct FramebufferMaterials {
GLuint framebufferId;
TextureDef textureDef;
};
FramebufferMaterials framebuffer(FramebufferDef framebufferDef)
{
auto fbIndex = findOrCreate<FramebufferDef>
(framebufferHeap,
framebufferDef,
[&framebufferDef](FramebufferDef const& element) {
return isEqual(element, framebufferDef);
},
[=](FramebufferDef const& def, size_t framebufferIndex) {
framebuffers.resize(1 + framebufferIndex);
auto& framebuffer = framebuffers[framebufferIndex];
auto txIndex = findOrCreate<TextureDef>
(textureHeap,
framebufferDef,
[&framebufferDef](TextureDef const& element) {
return isEqual(element, framebufferDef);
},
[=](TextureDef const& def, size_t index) {
textures.resize(index + 1);
},
[=](size_t indexA, size_t indexB) {
std::swap(textures[indexA], textures[indexB]);
}
);
auto& texture = textures[txIndex];
texture.target = GL_TEXTURE_2D;
createImageCaptureFramebuffer(framebuffer.resource, texture.resource,
framebuffer.depthbuffer, { framebufferDef.width, framebufferDef.height });
framebufferCreations++;
auto textureDef = framebufferDef;
textureDef.data.resize(sizeof(GLint));
*((GLint*) &textureDef.data.front()) = framebuffer.resource.id;
textureDef.pixelFiller = framebufferPixelFiller;
textureDefs[txIndex] = textureDef;
framebuffer.textureDef = textureDef;
framebufferDefs[framebufferIndex] = textureDef;
},
[=](size_t indexA, size_t indexB) {
std::swap(framebuffers[indexA], framebuffers[indexB]);
});
auto const& framebuffer = framebuffers[fbIndex];
return { framebuffer.resource.id, framebuffer.textureDef };
}
struct MeshMaterials {
GLuint vertexArray;
size_t indicesCount;
GLuint indicesBuffer;
std::vector<GLuint> vertexBuffers;
};
MeshMaterials mesh(GeometryDef geometryDef)
{
auto meshIndex = findOrCreate<GeometryDef>
(meshHeap,
geometryDef,
[&geometryDef](GeometryDef const& element) {
return element.data == geometryDef.data
&& element.definer == geometryDef.definer
&& element.arrayCount == geometryDef.arrayCount;
},
[=](GeometryDef const& def, size_t meshIndex) {
meshes.resize(1 + meshIndex);
auto& mesh = meshes[meshIndex];
if (def.definer) {
mesh.vertexBuffers.resize(def.arrayCount);
mesh.indicesCount = def.definer
(mesh.indices,
&mesh.vertexBuffers.front(),
&def.data.front());
}
meshCreations++;
},
[=](size_t indexA, size_t indexB) {
std::swap(meshes.at(indexA), meshes.at(indexB));
});
auto const& mesh = meshes.at(meshIndex);
auto vertexBufferIds = std::vector<GLuint> {};
std::transform(std::begin(mesh.vertexBuffers),
std::end(mesh.vertexBuffers),
std::back_inserter(vertexBufferIds),
[](BufferResource const& element) {
return element.id;
});
return {
mesh.vertexArray.id,
mesh.indicesCount,
mesh.indices.id,
vertexBufferIds
};
}
struct TextureMaterials {
GLuint textureId;
GLenum target;
};
TextureMaterials texture(TextureDef textureDef)
{
auto index = findOrCreate<TextureDef>(textureHeap,
textureDef,
[&textureDef](TextureDef const& element) {
return isEqual(element, textureDef);
},
[=](TextureDef const& def, size_t index) {
textures.resize(index + 1);
auto& texture = textures[index];
if (def.width > 0 && def.height > 0 && def.depth > 0) {
texture.target = GL_TEXTURE_3D;
} else if (def.width > 0 && def.height > 0) {
texture.target = GL_TEXTURE_2D;
} else if (def.width > 0) {
texture.target = GL_TEXTURE_1D;
} else {
texture.target = 0;
}
OGL_TRACE;
switch(texture.target) {
case GL_TEXTURE_2D:
glBindTexture(texture.target, texture.resource.id);
defineNonMipmappedARGB32Texture(def.width,
def.height,
[&def](uint32_t* data, int width, int height) {
def.pixelFiller(data, width, height, 0, &def.data.front());
});
break;
case GL_TEXTURE_3D:
glBindTexture(texture.target, texture.resource.id);
defineNonMipmappedARGB32Texture3d(def.width,
def.height,
def.depth,
[&def](uint32_t* data, int width, int height, int depth) {
def.pixelFiller(data, width, height, depth, &def.data.front());
});
break;
};
glBindTexture(texture.target, 0);
OGL_TRACE;
textureCreations++;
},
[=](size_t indexA, size_t indexB) {
std::swap(textures[indexA], textures[indexB]);
});
auto const& texture = textures[index];
return { texture.resource.id, texture.target };
}
struct ShaderProgramMaterials {
GLuint programId;
};
ShaderProgramMaterials program(ProgramDef programDef)
{
auto index = findOrCreate<ProgramDef>
(programHeap,
programDef,
[&programDef](ProgramDef const& element) {
return element.fragmentShader.source
== programDef.fragmentShader.source
&& element.vertexShader.source
== programDef.vertexShader.source;
},
[=](ProgramDef const& def, size_t index) {
programs.resize(index + 1);
vertexShaders.resize(index + 1);
fragmentShaders.resize(index + 1);
auto& program = programs[index];
auto& vertexShader = vertexShaders[index];
auto& fragmentShader = fragmentShaders[index];
compile(vertexShader, programDef.vertexShader.source);
compile(fragmentShader, programDef.fragmentShader.source);
link(program, vertexShader, fragmentShader);
OGL_TRACE;
programCreations++;
},
[=](size_t indexA, size_t indexB) {
std::swap(programs[indexA], programs[indexB]);
std::swap(vertexShaders[indexA], vertexShaders[indexB]);
std::swap(fragmentShaders[indexA], fragmentShaders[indexB]);
});
return { programs[index].id };
}
private:
// returns index to use (and create an entry if missing)
template <typename ResourceDef>
size_t findOrCreateDef(std::vector<ResourceDef>& definitions,
ResourceDef const& def,
std::function<bool(ResourceDef const&)> isDef,
size_t firstRecyclableIndex)
{
auto existing =
std::find_if(std::begin(definitions),
std::end(definitions),
isDef);
if (existing != std::end(definitions)) {
return &(*existing) - &definitions.front();
} else {
auto index = firstRecyclableIndex;
if (index >= definitions.size()) {
definitions.resize(1 + index);
}
definitions[index] = def;
return index;
}
}
template <typename ResourceDef>
struct RecyclingHeap {
size_t firstInactiveIndex;
size_t firstRecyclableIndex;
std::vector<ResourceDef>& definitions;
};
template <typename ResourceDef>
void reset(RecyclingHeap<ResourceDef>& heap)
{
heap.firstRecyclableIndex = heap.firstInactiveIndex;
heap.firstInactiveIndex = 0;
}
template <typename ResourceDef>
size_t findOrCreate(RecyclingHeap<ResourceDef>& heap,
ResourceDef const& def,
std::function<bool(ResourceDef const&)> isDef,
std::function<void(ResourceDef const&,size_t)> createAt,
std::function<void(size_t,size_t)> swap)
{
auto index = findOrCreateDef(heap.definitions,
def,
isDef,
heap.firstRecyclableIndex);
if (index == heap.firstRecyclableIndex) {
heap.firstRecyclableIndex++;
createAt(def, index);
}
auto newIndex = index;
if (heap.firstInactiveIndex < newIndex) {
newIndex = heap.firstInactiveIndex;
std::swap(heap.definitions.at(newIndex), heap.definitions.at(index));
swap(newIndex, index);
}
heap.firstInactiveIndex = newIndex + 1;
return newIndex;
}
struct Mesh {
VertexArrayResource vertexArray;
size_t indicesCount = 0;
BufferResource indices;
std::vector<BufferResource> vertexBuffers;
};
struct Framebuffer {
FramebufferResource resource;
RenderbufferResource depthbuffer;
TextureDef textureDef;
};
std::vector<Framebuffer> framebuffers;
std::vector<FramebufferDef> framebufferDefs;
RecyclingHeap<FramebufferDef> framebufferHeap = { 0, 0, framebufferDefs };
long framebufferCreations = 0;
std::vector<Mesh> meshes;
std::vector<GeometryDef> meshDefs;
RecyclingHeap<GeometryDef> meshHeap = { 0, 0, meshDefs };
long meshCreations = 0;
struct Texture {
TextureResource resource;
GLenum target;
};
std::vector<Texture> textures;
std::vector<TextureDef> textureDefs;
RecyclingHeap<TextureDef> textureHeap = { 0, 0, textureDefs };
long textureCreations = 0;
std::vector<VertexShaderResource> vertexShaders;
std::vector<FragmentShaderResource> fragmentShaders;
std::vector<ShaderProgramResource> programs;
std::vector<ProgramDef> programDefs;
RecyclingHeap<ProgramDef> programHeap = { 0, 0, programDefs };
long programCreations = 0;
};
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ftools.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-17 07:59:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"
#ifndef _BGFX_NUMERIC_FTOOLS_HXX
#include <basegfx/numeric/ftools.hxx>
#endif
namespace basegfx
{
// init static member of class fTools
double ::basegfx::fTools::mfSmallValue = 0.000000001;
} // end of namespace basegfx
// eof
<commit_msg>INTEGRATION: CWS changefileheader (1.5.60); FILE MERGED 2008/04/01 10:48:13 thb 1.5.60.2: #i85898# Stripping all external header guards 2008/03/28 16:05:50 rt 1.5.60.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ftools.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_basegfx.hxx"
#include <basegfx/numeric/ftools.hxx>
namespace basegfx
{
// init static member of class fTools
double ::basegfx::fTools::mfSmallValue = 0.000000001;
} // end of namespace basegfx
// eof
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016-2018 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/define.hpp>
#include <metaverse/explorer/extensions/command_extension.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
class signmultisigtx: public command_extension
{
public:
static const char* symbol() { return "signmultisigtx";}
const char* name() override { return symbol();}
bool category(int bs) override { return (ctgy_extension & bs ) == bs; }
const char* description() override { return "signmultisigtx "; }
arguments_metadata& load_arguments() override
{
return get_argument_metadata()
.add("ACCOUNTNAME", 1)
.add("ACCOUNTAUTH", 1)
.add("TRANSACTION", 1);
}
void load_fallbacks (std::istream& input,
po::variables_map& variables) override
{
const auto raw = requires_raw_input();
load_input(auth_.name, "ACCOUNTNAME", variables, input, raw);
load_input(auth_.auth, "ACCOUNTAUTH", variables, input, raw);
load_input(argument_.transaction, "TRANSACTION", variables, input, raw);
}
options_metadata& load_options() override
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_HELP_VARIABLE ",h",
value<bool>()->zero_tokens(),
"Get a description and instructions for this command."
)
(
"ACCOUNTNAME",
value<std::string>(&auth_.name)->required(),
BX_ACCOUNT_NAME
)
(
"ACCOUNTAUTH",
value<std::string>(&auth_.auth)->required(),
BX_ACCOUNT_AUTH
)
(
"TRANSACTION",
value<explorer::config::transaction>(&argument_.transaction)->required(),
"The input Base16 transaction to sign."
)
(
"selfpublickey,s",
value<std::string>(&option_.self_publickey)->default_value(""),
"The private key of this public key will be used to sign."
)
(
"broadcast,b",
value<bool>(&option_.broadcast_flag)->default_value(false)->zero_tokens(),
"Broadcast the tx automatically if it is fullly signed, enabled by default."
);
return options;
}
void set_defaults_from_config (po::variables_map& variables) override
{
}
console_result invoke (Json::Value& jv_output,
libbitcoin::server::server_node& node) override;
struct argument
{
explorer::config::transaction transaction;
} argument_;
struct option
{
option()
: broadcast_flag(false)
, self_publickey("")
{}
bool broadcast_flag;
std::string self_publickey;
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<commit_msg>update document.<commit_after>/**
* Copyright (c) 2016-2018 mvs developers
*
* This file is part of metaverse-explorer.
*
* metaverse-explorer is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <metaverse/explorer/define.hpp>
#include <metaverse/explorer/extensions/command_extension.hpp>
#include <metaverse/explorer/extensions/command_extension_func.hpp>
#include <metaverse/explorer/extensions/command_assistant.hpp>
namespace libbitcoin {
namespace explorer {
namespace commands {
class signmultisigtx: public command_extension
{
public:
static const char* symbol() { return "signmultisigtx";}
const char* name() override { return symbol();}
bool category(int bs) override { return (ctgy_extension & bs ) == bs; }
const char* description() override { return "signmultisigtx "; }
arguments_metadata& load_arguments() override
{
return get_argument_metadata()
.add("ACCOUNTNAME", 1)
.add("ACCOUNTAUTH", 1)
.add("TRANSACTION", 1);
}
void load_fallbacks (std::istream& input,
po::variables_map& variables) override
{
const auto raw = requires_raw_input();
load_input(auth_.name, "ACCOUNTNAME", variables, input, raw);
load_input(auth_.auth, "ACCOUNTAUTH", variables, input, raw);
load_input(argument_.transaction, "TRANSACTION", variables, input, raw);
}
options_metadata& load_options() override
{
using namespace po;
options_description& options = get_option_metadata();
options.add_options()
(
BX_HELP_VARIABLE ",h",
value<bool>()->zero_tokens(),
"Get a description and instructions for this command."
)
(
"ACCOUNTNAME",
value<std::string>(&auth_.name)->required(),
BX_ACCOUNT_NAME
)
(
"ACCOUNTAUTH",
value<std::string>(&auth_.auth)->required(),
BX_ACCOUNT_AUTH
)
(
"TRANSACTION",
value<explorer::config::transaction>(&argument_.transaction)->required(),
"The input Base16 transaction to sign."
)
(
"selfpublickey,s",
value<std::string>(&option_.self_publickey)->default_value(""),
"The private key of this public key will be used to sign."
)
(
"broadcast,b",
value<bool>(&option_.broadcast_flag)->default_value(false)->zero_tokens(),
"Broadcast the tx automatically if it is fullly signed, disabled by default."
);
return options;
}
void set_defaults_from_config (po::variables_map& variables) override
{
}
console_result invoke (Json::Value& jv_output,
libbitcoin::server::server_node& node) override;
struct argument
{
explorer::config::transaction transaction;
} argument_;
struct option
{
option()
: broadcast_flag(false)
, self_publickey("")
{}
bool broadcast_flag;
std::string self_publickey;
} option_;
};
} // namespace commands
} // namespace explorer
} // namespace libbitcoin
<|endoftext|> |
<commit_before>#ifndef DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
#define DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG
#include <vector>
#include <dune/common/shared_ptr.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/function/interface.hh>
namespace Dune {
namespace Detailed {
namespace Solvers {
namespace Stationary {
namespace Linear {
namespace Elliptic {
namespace Model {
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Interface;
template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
public:
typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;
typedef DomainFieldImp DomainFieldType;
static const int dimDomain = domainDim;
typedef RangeFieldImp RangeFieldType;
static const int dimRange = 1;
typedef typename Stuff::Common::Parameter::FieldType ParamFieldType;
static const int maxParamDim = Stuff::Common::Parameter::maxDim;
typedef typename Stuff::Common::Parameter::Type ParamType;
typedef Dune::Stuff::Function::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > FunctionType;
static const std::string id()
{
return "model.stationary.linear.elliptic";
}
/** \defgroup type ´´These methods determine the type of the model (and also, which of the below methods have to be implemented).'' */
/* @{ */
virtual bool parametric() const
{
if (diffusion()->parametric() || force()->parametric() || dirichlet()->parametric() || neumann()->parametric())
return true;
else
return false;
}
virtual bool separable() const
{
if (parametric()) {
if (diffusion()->parametric() && !diffusion()->separable())
return false;
if (force()->parametric() && !force()->separable())
return false;
if (dirichlet()->parametric() && !dirichlet()->separable())
return false;
if (neumann()->parametric() && !neumann()->separable())
return false;
return true;
} else
return false;
}
/* @} */
/** \defgroup purevirtual ´´These methods have to be implemented.'' */
/* @{ */
virtual Dune::shared_ptr< const FunctionType > diffusion() const = 0;
virtual Dune::shared_ptr< const FunctionType > force() const = 0;
virtual Dune::shared_ptr< const FunctionType > dirichlet() const = 0;
virtual Dune::shared_ptr< const FunctionType > neumann() const = 0;
/* @} */
/** \defgroup parametric ´´These methods have to be implemented additionally, if parametric() == true.'' */
/* @{ */
virtual size_t paramSize() const
{
if (!parametric())
return 0;
else
DUNE_THROW(Dune::NotImplemented,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
}
virtual const std::vector< ParamType >& paramRange() const
{
DUNE_THROW(Dune::NotImplemented,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
}
virtual const std::vector< std::string >& paramExplanation() const
{
DUNE_THROW(Dune::NotImplemented,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
}
/**
* \brief Maps a global to a local parameter.
* \param[in] ParamType _globalMu
* global parameter
* \param[in] std::string _id
* To identify the function, wrt which the localization is carried out. Has to be one of diffusion,
* force, dirichlet or neumann
* \return ParamType
* local parameter
*/
virtual ParamType mapParam(const ParamType& /*_globalMu*/, const std::string /*_id*/) const
{
if (!parametric())
return ParamType();
else
DUNE_THROW(Dune::NotImplemented,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
}
/* @} */
// virtual const Dune::shared_ptr< const NonparametricType > fix(const ParamType&) const = 0;
// void report(std::ostream& out = std::cout, std::string prefix = "") const
// {
// out << prefix << "parameter explanation:" << std::endl;
// assert(paramExplanation().size() == paramSize());
// assert(paramRange().size() == 2);
// assert(paramRange()[0].size() == paramSize());
// assert(paramRange()[1].size() == paramSize());
// for (size_t pp = 0; pp < paramSize(); ++pp)
// out << prefix << " " << paramExplanation()[pp] << ", between " << paramRange()[0](pp) << " and " << paramRange()[1](pp) << std::endl;
// }
template< class GridViewType >
void visualize(const GridViewType& gridView, std::string filename) const
{
// prepare data
Dune::VTKWriter< GridViewType > vtkWriter(gridView);
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > diffusionPlots
= preparePlot(gridView, *(diffusion()), "diffusion");
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > forcePlots
= preparePlot(gridView, *(force()), "force");
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > dirichletPlots
= preparePlot(gridView, *(dirichlet()), "dirichlet");
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > neumannPlots
= preparePlot(gridView, *(neumann()), "neumann");
// walk the grid view
for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
it != gridView.template end< 0 >();
++it) {
const typename GridViewType::template Codim< 0 >::Entity& entity = *it;
const typename GridViewType::IndexSet::IndexType index = gridView.indexSet().index(entity);
const typename FunctionType::DomainType center = entity.geometry().center();
// do a piecewise constant projection of the data functions
// * diffusion
if (diffusion()->parametric() && diffusion()->separable())
for (size_t qq = 0; qq < diffusion()->numComponents(); ++qq)
diffusionPlots[qq].second->operator[](index) = diffusion()->components()[qq]->evaluate(center);
else if (!diffusion()->parametric())
diffusionPlots[0].second->operator[](index) = diffusion()->evaluate(center);
else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
// * force
if (force()->parametric() && force()->separable())
for (size_t qq = 0; qq < force()->numComponents(); ++qq)
forcePlots[qq].second->operator[](index) = force()->components()[qq]->evaluate(center);
else if (!force()->parametric())
forcePlots[0].second->operator[](index) = force()->evaluate(center);
else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
// * dirichlet
if (dirichlet()->parametric() && dirichlet()->separable())
for (size_t qq = 0; qq < dirichlet()->numComponents(); ++qq)
dirichletPlots[qq].second->operator[](index) = dirichlet()->components()[qq]->evaluate(center);
else if (!dirichlet()->parametric())
dirichletPlots[0].second->operator[](index) = dirichlet()->evaluate(center);
else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
// * neumann
if (neumann()->parametric() && neumann()->separable())
for (size_t qq = 0; qq < neumann()->numComponents(); ++qq)
neumannPlots[qq].second->operator[](index) = neumann()->components()[qq]->evaluate(center);
else if (!neumann()->parametric())
neumannPlots[0].second->operator[](index) = neumann()->evaluate(center);
else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
} // walk the grid view
// write
// * diffusion
for (size_t qq = 0; qq < diffusionPlots.size(); ++qq)
vtkWriter.addCellData(*(diffusionPlots[qq].second), diffusionPlots[qq].first);
// * force
for (size_t qq = 0; qq < forcePlots.size(); ++qq)
vtkWriter.addCellData(*(forcePlots[qq].second), forcePlots[qq].first);
// * dirichlet
for (size_t qq = 0; qq < dirichletPlots.size(); ++qq)
vtkWriter.addCellData(*(dirichletPlots[qq].second), dirichletPlots[qq].first);
// * neumann
for (size_t qq = 0; qq < neumannPlots.size(); ++qq)
vtkWriter.addCellData(*(neumannPlots[qq].second), neumannPlots[qq].first);
vtkWriter.write(filename, Dune::VTK::ascii);
} // void visualize(const GridViewType& gridView, std::string filename) const
private:
template< class GridViewType, class FunctionType >
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(const GridViewType& gridView,
const FunctionType& function,
const std::string name) const
{
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > ret;
if (function.parametric()) {
if (function.separable()) {
const std::vector< std::string >& paramExplanations = function.paramExplanation();
for (size_t qq = 0; qq < function.numComponents(); ++qq)
ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
name + "_component_" + Dune::Stuff::Common::toString(qq) + ": " + paramExplanations[qq],
new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
} else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
} else {
ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
name,
new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
}
return ret;
} // std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(...) const
}; // class Interface
} // namespace Model
} // namespace Elliptic
} // namespace Linear
} // namespace Stationary
} // namespace Solvers
} // namespace Detailed
} // namespace Dune
#endif // DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
<commit_msg>[...elliptic.model.interface] added fix(mu)<commit_after>#ifndef DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
#define DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
#include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG
#include <vector>
#include <dune/common/shared_ptr.hh>
#include <dune/grid/io/file/vtk/vtkwriter.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>
#include <dune/stuff/function/interface.hh>
#include <dune/stuff/function/fixed.hh>
namespace Dune {
namespace Detailed {
namespace Solvers {
namespace Stationary {
namespace Linear {
namespace Elliptic {
namespace Model {
// forward of the nonparametric default
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Default;
// forward to allow for specialization
template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class Interface;
template< class DomainFieldImp, int domainDim, class RangeFieldImp >
class Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
public:
typedef Interface< DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;
typedef DomainFieldImp DomainFieldType;
static const int dimDomain = domainDim;
typedef RangeFieldImp RangeFieldType;
static const int dimRange = 1;
typedef typename Stuff::Common::Parameter::FieldType ParamFieldType;
static const int maxParamDim = Stuff::Common::Parameter::maxDim;
typedef typename Stuff::Common::Parameter::Type ParamType;
typedef Dune::Stuff::Function::Interface< DomainFieldType, dimDomain, RangeFieldType, dimRange > FunctionType;
static const std::string id()
{
return "model.stationary.linear.elliptic";
}
/** \defgroup type ´´These methods determine the type of the model (and also, which of the below methods have to be implemented).'' */
/* @{ */
virtual bool parametric() const
{
if (diffusion()->parametric() || force()->parametric() || dirichlet()->parametric() || neumann()->parametric())
return true;
else
return false;
}
virtual bool separable() const
{
if (parametric()) {
if (diffusion()->parametric() && !diffusion()->separable())
return false;
if (force()->parametric() && !force()->separable())
return false;
if (dirichlet()->parametric() && !dirichlet()->separable())
return false;
if (neumann()->parametric() && !neumann()->separable())
return false;
return true;
} else
return false;
}
/* @} */
/** \defgroup purevirtual ´´These methods have to be implemented.'' */
/* @{ */
virtual Dune::shared_ptr< const FunctionType > diffusion() const = 0;
virtual Dune::shared_ptr< const FunctionType > force() const = 0;
virtual Dune::shared_ptr< const FunctionType > dirichlet() const = 0;
virtual Dune::shared_ptr< const FunctionType > neumann() const = 0;
/* @} */
/** \defgroup parametric ´´These methods have to be implemented additionally, if parametric() == true.'' */
/* @{ */
virtual size_t paramSize() const
{
if (!parametric())
return 0;
else
DUNE_THROW(Dune::NotImplemented,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
}
virtual const std::vector< ParamType >& paramRange() const
{
DUNE_THROW(Dune::NotImplemented,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
}
virtual const std::vector< std::string >& paramExplanation() const
{
DUNE_THROW(Dune::NotImplemented,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
}
/**
* \brief Maps a global to a local parameter.
* \param[in] ParamType _globalMu
* global parameter
* \param[in] std::string _id
* To identify the function, wrt which the localization is carried out. Has to be one of diffusion,
* force, dirichlet or neumann
* \return ParamType
* local parameter
*/
virtual ParamType mapParam(const ParamType& /*_globalMu*/, const std::string /*_id*/) const
{
if (!parametric())
return ParamType();
else
DUNE_THROW(Dune::NotImplemented,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
}
/* @} */
virtual Dune::shared_ptr< const ThisType > fix(const ParamType& mu) const
{
typedef Dune::Stuff::Function::Fixed< DomainFieldType, dimDomain, RangeFieldType, dimRange > FixedFunctionType;
typedef Default< DomainFieldType, dimDomain, RangeFieldType, dimRange > DefaultModelType;
Dune::shared_ptr< DefaultModelType >
defaultModel(Dune::make_shared< DefaultModelType >(diffusion()->parametric() ? Dune::make_shared< const FixedFunctionType >(diffusion(), mapParam(mu, "diffusion")) : diffusion(),
force()->parametric() ? Dune::make_shared< const FixedFunctionType >(force(), mapParam(mu, "force")) : force(),
dirichlet()->parametric() ? Dune::make_shared< const FixedFunctionType >(dirichlet(), mapParam(mu, "dirichlet")) : dirichlet(),
neumann()->parametric() ? Dune::make_shared< const FixedFunctionType >(neumann(), mapParam(mu, "neumann")) : neumann()));
return defaultModel;
}
// void report(std::ostream& out = std::cout, std::string prefix = "") const
// {
// out << prefix << "parameter explanation:" << std::endl;
// assert(paramExplanation().size() == paramSize());
// assert(paramRange().size() == 2);
// assert(paramRange()[0].size() == paramSize());
// assert(paramRange()[1].size() == paramSize());
// for (size_t pp = 0; pp < paramSize(); ++pp)
// out << prefix << " " << paramExplanation()[pp] << ", between " << paramRange()[0](pp) << " and " << paramRange()[1](pp) << std::endl;
// }
template< class GridViewType >
void visualize(const GridViewType& gridView, std::string filename) const
{
// prepare data
Dune::VTKWriter< GridViewType > vtkWriter(gridView);
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > diffusionPlots
= preparePlot(gridView, *(diffusion()), "diffusion");
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > forcePlots
= preparePlot(gridView, *(force()), "force");
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > dirichletPlots
= preparePlot(gridView, *(dirichlet()), "dirichlet");
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > neumannPlots
= preparePlot(gridView, *(neumann()), "neumann");
// walk the grid view
for (typename GridViewType::template Codim< 0 >::Iterator it = gridView.template begin< 0 >();
it != gridView.template end< 0 >();
++it) {
const typename GridViewType::template Codim< 0 >::Entity& entity = *it;
const typename GridViewType::IndexSet::IndexType index = gridView.indexSet().index(entity);
const typename FunctionType::DomainType center = entity.geometry().center();
// do a piecewise constant projection of the data functions
// * diffusion
if (diffusion()->parametric() && diffusion()->separable())
for (size_t qq = 0; qq < diffusion()->numComponents(); ++qq)
diffusionPlots[qq].second->operator[](index) = diffusion()->components()[qq]->evaluate(center);
else if (!diffusion()->parametric())
diffusionPlots[0].second->operator[](index) = diffusion()->evaluate(center);
else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
// * force
if (force()->parametric() && force()->separable())
for (size_t qq = 0; qq < force()->numComponents(); ++qq)
forcePlots[qq].second->operator[](index) = force()->components()[qq]->evaluate(center);
else if (!force()->parametric())
forcePlots[0].second->operator[](index) = force()->evaluate(center);
else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
// * dirichlet
if (dirichlet()->parametric() && dirichlet()->separable())
for (size_t qq = 0; qq < dirichlet()->numComponents(); ++qq)
dirichletPlots[qq].second->operator[](index) = dirichlet()->components()[qq]->evaluate(center);
else if (!dirichlet()->parametric())
dirichletPlots[0].second->operator[](index) = dirichlet()->evaluate(center);
else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
// * neumann
if (neumann()->parametric() && neumann()->separable())
for (size_t qq = 0; qq < neumann()->numComponents(); ++qq)
neumannPlots[qq].second->operator[](index) = neumann()->components()[qq]->evaluate(center);
else if (!neumann()->parametric())
neumannPlots[0].second->operator[](index) = neumann()->evaluate(center);
else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
} // walk the grid view
// write
// * diffusion
for (size_t qq = 0; qq < diffusionPlots.size(); ++qq)
vtkWriter.addCellData(*(diffusionPlots[qq].second), diffusionPlots[qq].first);
// * force
for (size_t qq = 0; qq < forcePlots.size(); ++qq)
vtkWriter.addCellData(*(forcePlots[qq].second), forcePlots[qq].first);
// * dirichlet
for (size_t qq = 0; qq < dirichletPlots.size(); ++qq)
vtkWriter.addCellData(*(dirichletPlots[qq].second), dirichletPlots[qq].first);
// * neumann
for (size_t qq = 0; qq < neumannPlots.size(); ++qq)
vtkWriter.addCellData(*(neumannPlots[qq].second), neumannPlots[qq].first);
vtkWriter.write(filename, Dune::VTK::ascii);
} // void visualize(const GridViewType& gridView, std::string filename) const
private:
template< class GridViewType, class FunctionType >
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(const GridViewType& gridView,
const FunctionType& function,
const std::string name) const
{
std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > ret;
if (function.parametric()) {
if (function.separable()) {
const std::vector< std::string >& paramExplanations = function.paramExplanation();
for (size_t qq = 0; qq < function.numComponents(); ++qq)
ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
name + "_component_" + Dune::Stuff::Common::toString(qq) + ": " + paramExplanations[qq],
new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
} else
DUNE_THROW(Dune::InvalidStateException,
"\n" << Dune::Stuff::Common::colorStringRed("ERROR:")
<< " visualize() not yet implemented for parametric but not separable data functions!");
} else {
ret.push_back(std::pair< std::string, std::vector< RangeFieldType >* >(
name,
new std::vector< RangeFieldType >(gridView.indexSet().size(0), RangeFieldType(0))));
}
return ret;
} // std::vector< std::pair< std::string, std::vector< RangeFieldType >* > > preparePlot(...) const
}; // class Interface
} // namespace Model
} // namespace Elliptic
} // namespace Linear
} // namespace Stationary
} // namespace Solvers
} // namespace Detailed
} // namespace Dune
#endif // DUNE_RB_MODEL_STATIONARY_LINEAR_ELLIPTIC_INTERFACE_HH
<|endoftext|> |
<commit_before>//-----------------------------------------------------------------------------
// File: Date.cpp
//
// class: Date
// methods:
// Date::Date(short day, short month, short year)
// bool Date::operator==(const Comparable &other)const
// bool Date::operator<(const Comparable &other)const
// void Date::setCurrentDate(void)
// void Date::setDayOfWeek(void)
// void Date::setDayOfYear(void)
// short Date::countLeaps(short year)const
// void Date::setDayOfMonth(short dayOfMonth)
// void Date::setMonth(short month)
// void Date::setYear(short year)
//-----------------------------------------------------------------------------
#include "Date.h"
namespace NP_DATETIME
{
//-----------------------------------------------------------------------------
// method: Date(short day, short month, short year) -- constructor
//
// description: creates a new Date object
//
// Calls: setCurrentDate()
// daysInMonth(month, year)
// setDayOfYear()
// setDayOfWeek()
//
// Called By: ostream& operator<<(ostream& sout, const CComplex &c)
//
// Parameters: short day -- day to set
// short month -- month to set
// short year -- month to set
//
// History Log:
// 2/9/08 PB completed version 1.0
// ----------------------------------------------------------------------------
Date::Date(short day, short month, short year)
{
setDayOfMonth(day);
setMonth(month);
setYear(year);
}
//-----------------------------------------------------------------------------
// Class: Date
// method: operator==(const Comparable& other) const
//
// description: true if the two objects are exactly the same
//
// Parameters: const Comparable &other -- the other Date to compare
//
// Called By: main, >=, <=
//
// Returns: true if the two objects are exactly the same;
// false otherwise
// History Log:
// 5/8/16 PB completed version 1.1
//-----------------------------------------------------------------------------
bool Date::operator==(const Comparable &other) const
{
bool returnValue = false;
try
{
const Date &otherDate =
dynamic_cast<const Date&>(other);
returnValue = (
m_year == otherDate.m_year &&
getDayOfYear() == otherDate.getDayOfYear()
);
}
catch (bad_cast e)
{
// Should something happen here?
}
return returnValue;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: operator<(const Comparable& other) const
//
// description: true if the current object is before other
//
// Parameters: const Comparable &other -- the other Date to compare
//
// Called By: main, >, <=
//
// Calls: getYear, getDayOfYear
//
// Exceptions: throws bad_cast if other is not a Date
//
// Returns: true if the current object is before other;
// false otherwise
// History Log:
// 5/8/16 PB completed version 1.1
// ----------------------------------------------------------------------------
bool Date::operator<(const Comparable &other) const
{
bool returnValue = false;
try {
Date otherDate = dynamic_cast<const Date&>(other);
bool yearLT = otherDate.getYear() < getYear();
bool yearEQ = otherDate.getYear() == getYear();
bool dayLT = otherDate.getDayOfYear() < getDayOfYear();
returnValue = (yearLT || yearEQ && dayLT);
}
catch (bad_cast e) {
throw new invalid_argument("Date can only be compared to Date objects");
}
return returnValue;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: setCurrentDate()
//
// description: sets the date from the system clock
//
// Called By: constructor
//
// History Log:
// 2/9/08 PB completed version 1.0
// ----------------------------------------------------------------------------
void Date::setCurrentDate(void)
{
time_t rawtime;
tm *currentTimePtr;
time(&rawtime);
currentTimePtr = localtime(&rawtime);
m_year = currentTimePtr->tm_year + 1900;
m_month = currentTimePtr->tm_mon;
m_dayOfMonth = currentTimePtr->tm_mday;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: countLeaps(short year)const
//
// description: returns the number of leap years from 1760 to year
//
// Calls: isLeapYear(short)
//
// Returns: the number of leap years from 1760 to year
//
// History Log:
// 2/9/08 PB completed version 1.0
//-----------------------------------------------------------------------------
short Date::countLeaps(short year)const
{
short leaps = 0;
for (short i = LOWYEAR; i < year; i++)
if (isLeapYear(i))
leaps++;
return leaps;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: getDayOfYear() const
//
// description: python styled property for getting index of day in year
//
// Calls: getDayOfMonth(), daysInMonty(), Accessors
//
// Parameters:
//
// Returns: totalDays -- int of day index of day in year
//
// History Log:
// 02/09/08 PB completed version 1.0
// 04/13/17 NP appeneded to version 1.0
//-----------------------------------------------------------------------------
short Date::getDayOfYear() const
{
short totalDays = getDayOfMonth();
for (short month = 0; month < getMonth(); month++) {
totalDays += daysInMonth(m_month, getYear());
}
return totalDays;
}
const string Date::monthName(int monthNum)
{
string month;
switch (monthNum) {
case 0:
month = "January";
break;
case 1:
month = "February";
break;
case 2:
month = "March";
break;
case 3:
month = "April";
break;
case 4:
month = "May";
break;
case 5:
month = "June";
break;
case 6:
month = "July";
break;
case 7:
month = "August";
break;
case 8:
month = "September";
break;
case 9:
month = "October";
break;
case 10:
month = "November";
break;
case 11:
month = "December";
break;
}
return month;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: setDayOfMonth(short dayOfMonth)
//
// description: mutator for m_dayOfMonth
//
// Calls: daysInMonth(short, short)
//
// Parameters: dayOfMonth -- day of month to set
//
// History Log:
// 2/9/08 PB completed version 1.0
//-----------------------------------------------------------------------------
void Date::setDayOfMonth(short dayOfMonth)
{
if (dayOfMonth > 0
&& dayOfMonth <= daysInMonth(m_month, m_year))
{
m_dayOfMonth = dayOfMonth;
}
}
//-----------------------------------------------------------------------------
// Class: Date
// method: setMonth(short dmonth)
//
// description: mutator for m_month
//
// Calls: daysInMonth(short, short)
//
// Parameters: month -- month to set
//
// History Log:
// 2/9/08 PB completed version 1.0
//-----------------------------------------------------------------------------
void Date::setMonth(short month)
{
if (month > 0 && month < MONTHSINYEAR)
m_month = month;
else
m_month = 0;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: setYear(short year)
//
// description: mutator for m_year
//
// Calls: isLeapYear(short)
//
// Parameters: year -- year to set
//
// History Log:
// 2/9/08 PB completed version 1.0
//-----------------------------------------------------------------------------
void Date::setYear(short year)
{
if (year > LOWYEAR)
m_year = year;
else
m_year = LOWYEAR;
}
//-----------------------------------------------------------------------------
void Date::input(istream& sin)
{
}
//-----------------------------------------------------------------------------
void Date::print(ostream& sout)const
{
sout << m_dayOfMonth << '/' << m_month << '/' << m_year;
}
}
<commit_msg>add weekdayName method<commit_after>//-----------------------------------------------------------------------------
// File: Date.cpp
//
// class: Date
// methods:
// Date::Date(short day, short month, short year)
// bool Date::operator==(const Comparable &other)const
// bool Date::operator<(const Comparable &other)const
// void Date::setCurrentDate(void)
// void Date::setDayOfWeek(void)
// void Date::setDayOfYear(void)
// short Date::countLeaps(short year)const
// void Date::setDayOfMonth(short dayOfMonth)
// void Date::setMonth(short month)
// void Date::setYear(short year)
//-----------------------------------------------------------------------------
#include "Date.h"
namespace NP_DATETIME
{
//-----------------------------------------------------------------------------
// method: Date(short day, short month, short year) -- constructor
//
// description: creates a new Date object
//
// Calls: setCurrentDate()
// daysInMonth(month, year)
// setDayOfYear()
// setDayOfWeek()
//
// Called By: ostream& operator<<(ostream& sout, const CComplex &c)
//
// Parameters: short day -- day to set
// short month -- month to set
// short year -- month to set
//
// History Log:
// 2/9/08 PB completed version 1.0
// ----------------------------------------------------------------------------
Date::Date(short day, short month, short year)
{
setDayOfMonth(day);
setMonth(month);
setYear(year);
}
//-----------------------------------------------------------------------------
// Class: Date
// method: operator==(const Comparable& other) const
//
// description: true if the two objects are exactly the same
//
// Parameters: const Comparable &other -- the other Date to compare
//
// Called By: main, >=, <=
//
// Returns: true if the two objects are exactly the same;
// false otherwise
// History Log:
// 5/8/16 PB completed version 1.1
//-----------------------------------------------------------------------------
bool Date::operator==(const Comparable &other) const
{
bool returnValue = false;
try
{
const Date &otherDate =
dynamic_cast<const Date&>(other);
returnValue = (
m_year == otherDate.m_year &&
getDayOfYear() == otherDate.getDayOfYear()
);
}
catch (bad_cast e)
{
// Should something happen here?
}
return returnValue;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: operator<(const Comparable& other) const
//
// description: true if the current object is before other
//
// Parameters: const Comparable &other -- the other Date to compare
//
// Called By: main, >, <=
//
// Calls: getYear, getDayOfYear
//
// Exceptions: throws bad_cast if other is not a Date
//
// Returns: true if the current object is before other;
// false otherwise
// History Log:
// 5/8/16 PB completed version 1.1
// ----------------------------------------------------------------------------
bool Date::operator<(const Comparable &other) const
{
bool returnValue = false;
try {
Date otherDate = dynamic_cast<const Date&>(other);
bool yearLT = otherDate.getYear() < getYear();
bool yearEQ = otherDate.getYear() == getYear();
bool dayLT = otherDate.getDayOfYear() < getDayOfYear();
returnValue = (yearLT || yearEQ && dayLT);
}
catch (bad_cast e) {
throw new invalid_argument("Date can only be compared to Date objects");
}
return returnValue;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: setCurrentDate()
//
// description: sets the date from the system clock
//
// Called By: constructor
//
// History Log:
// 2/9/08 PB completed version 1.0
// ----------------------------------------------------------------------------
void Date::setCurrentDate(void)
{
time_t rawtime;
tm *currentTimePtr;
time(&rawtime);
currentTimePtr = localtime(&rawtime);
m_year = currentTimePtr->tm_year + 1900;
m_month = currentTimePtr->tm_mon;
m_dayOfMonth = currentTimePtr->tm_mday;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: countLeaps(short year)const
//
// description: returns the number of leap years from 1760 to year
//
// Calls: isLeapYear(short)
//
// Returns: the number of leap years from 1760 to year
//
// History Log:
// 2/9/08 PB completed version 1.0
//-----------------------------------------------------------------------------
short Date::countLeaps(short year)const
{
short leaps = 0;
for (short i = LOWYEAR; i < year; i++)
if (isLeapYear(i))
leaps++;
return leaps;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: getDayOfYear() const
//
// description: python styled property for getting index of day in year
//
// Calls: getDayOfMonth(), daysInMonty(), Accessors
//
// Parameters:
//
// Returns: totalDays -- int of day index of day in year
//
// History Log:
// 02/09/08 PB completed version 1.0
// 04/13/17 NP appeneded to version 1.0
//-----------------------------------------------------------------------------
short Date::getDayOfYear() const
{
short totalDays = getDayOfMonth();
for (short month = 0; month < getMonth(); month++) {
totalDays += daysInMonth(m_month, getYear());
}
return totalDays;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: monthName() const
//
// description: returns string of month name
//
// Calls:
//
// Parameters:
//
// Returns: string -- month name
//
// History Log:
// 02/09/08 PB completed version 1.0
// 04/13/17 NP appeneded to version 1.0
//-----------------------------------------------------------------------------
const string Date::monthName(int monthNum)
{
string month;
switch (monthNum) {
case 0:
month = "January";
break;
case 1:
month = "February";
break;
case 2:
month = "March";
break;
case 3:
month = "April";
break;
case 4:
month = "May";
break;
case 5:
month = "June";
break;
case 6:
month = "July";
break;
case 7:
month = "August";
break;
case 8:
month = "September";
break;
case 9:
month = "October";
break;
case 10:
month = "November";
break;
case 11:
month = "December";
break;
}
return month;
}
const string Date::weekdayName(int weekdayNum)
{
string dayOfWeek;
switch (getDayOfWeek()) {
case 0:
dayOfWeek = "Sunday";
break;
case 1:
dayOfWeek = "Monday";
break;
case 2:
dayOfWeek = "Tuesday";
break;
case 3:
dayOfWeek = "Wednesday";
break;
case 4:
dayOfWeek = "Thursday";
break;
case 5:
dayOfWeek = "Friday";
break;
case 6:
dayOfWeek = "Saturday";
break;
}
return dayOfWeek;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: setDayOfMonth(short dayOfMonth)
//
// description: mutator for m_dayOfMonth
//
// Calls: daysInMonth(short, short)
//
// Parameters: dayOfMonth -- day of month to set
//
// History Log:
// 2/9/08 PB completed version 1.0
//-----------------------------------------------------------------------------
void Date::setDayOfMonth(short dayOfMonth)
{
if (dayOfMonth > 0
&& dayOfMonth <= daysInMonth(m_month, m_year))
{
m_dayOfMonth = dayOfMonth;
}
}
//-----------------------------------------------------------------------------
// Class: Date
// method: setMonth(short dmonth)
//
// description: mutator for m_month
//
// Calls: daysInMonth(short, short)
//
// Parameters: month -- month to set
//
// History Log:
// 2/9/08 PB completed version 1.0
//-----------------------------------------------------------------------------
void Date::setMonth(short month)
{
if (month > 0 && month < MONTHSINYEAR)
m_month = month;
else
m_month = 0;
}
//-----------------------------------------------------------------------------
// Class: Date
// method: setYear(short year)
//
// description: mutator for m_year
//
// Calls: isLeapYear(short)
//
// Parameters: year -- year to set
//
// History Log:
// 2/9/08 PB completed version 1.0
//-----------------------------------------------------------------------------
void Date::setYear(short year)
{
if (year > LOWYEAR)
m_year = year;
else
m_year = LOWYEAR;
}
//-----------------------------------------------------------------------------
void Date::input(istream& sin)
{
}
//-----------------------------------------------------------------------------
void Date::print(ostream& sout)const
{
sout << m_dayOfMonth << '/' << m_month << '/' << m_year;
}
}
<|endoftext|> |
<commit_before>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation //
// //
// 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 "Builder.h"
#include "ospray_testing.h"
// stl
#include <random>
#include <vector>
// ospcommon
#include "ospcommon/tasking/parallel_for.h"
// raw_to_amr
#include "rawToAMR.h"
using namespace ospcommon;
using namespace ospcommon::math;
namespace ospray {
namespace testing {
using VoxelArray = std::vector<float>;
struct GravitySpheres : public detail::Builder
{
GravitySpheres(bool addVolume = true,
bool asAMR = false,
bool addIsosurface = false);
~GravitySpheres() override = default;
void commit() override;
cpp::Group buildGroup() const override;
private:
VoxelArray generateVoxels() const;
cpp::Volume createStructuredVolume(const VoxelArray &voxels) const;
cpp::Volume createAMRVolume(const VoxelArray &voxels) const;
// Data //
vec3i volumeDimensions{128};
int numPoints{10};
bool withVolume{true};
bool createAsAMR{false};
bool withIsosurface{false};
float isovalue{2.5f};
};
// Inlined definitions ////////////////////////////////////////////////////
GravitySpheres::GravitySpheres(bool addVolume,
bool asAMR,
bool addIsosurface)
: withVolume(addVolume),
createAsAMR(asAMR),
withIsosurface(addIsosurface)
{
}
void GravitySpheres::commit()
{
Builder::commit();
volumeDimensions = getParam<vec3i>("volumeDimensions", vec3i(128));
numPoints = getParam<int>("numPoints", 10);
withVolume = getParam<bool>("withVolume", withVolume);
createAsAMR = getParam<bool>("asAMR", createAsAMR);
withIsosurface = getParam<bool>("withIsosurface", withIsosurface);
isovalue = getParam<float>("isovalue", 2.5f);
addPlane = false;
}
cpp::Group GravitySpheres::buildGroup() const
{
auto voxels = generateVoxels();
auto voxelRange = vec2f(0.f, 10.f);
cpp::Volume volume = createAsAMR ? createAMRVolume(voxels)
: createStructuredVolume(voxels);
cpp::VolumetricModel model(volume);
model.setParam("transferFunction", makeTransferFunction(voxelRange));
model.commit();
cpp::Group group;
if (withVolume)
group.setParam("volume", cpp::Data(model));
if (withIsosurface) {
cpp::Geometry isoGeom("isosurfaces");
isoGeom.setParam("isovalue", cpp::Data(isovalue));
isoGeom.setParam("volume", model);
isoGeom.commit();
cpp::Material mat(rendererType, "OBJMaterial");
mat.setParam("Ks", vec3f(0.2f));
mat.commit();
cpp::GeometricModel isoModel(isoGeom);
isoModel.setParam("material", cpp::Data(mat));
isoModel.commit();
group.setParam("geometry", cpp::Data(isoModel));
}
group.commit();
return group;
}
std::vector<float> GravitySpheres::generateVoxels() const
{
struct Point
{
vec3f center;
float weight;
};
// create random number distributions for point center and weight
std::mt19937 gen(randomSeed);
std::uniform_real_distribution<float> centerDistribution(-1.f, 1.f);
std::uniform_real_distribution<float> weightDistribution(0.1f, 0.3f);
// populate the points
std::vector<Point> points(numPoints);
for (auto &p : points) {
p.center.x = centerDistribution(gen);
p.center.y = centerDistribution(gen);
p.center.z = centerDistribution(gen);
p.weight = weightDistribution(gen);
}
// get world coordinate in [-1.f, 1.f] from logical coordinates in [0,
// volumeDimension)
auto logicalToWorldCoordinates = [&](int i, int j, int k) {
return vec3f(-1.f + float(i) / float(volumeDimensions.x - 1) * 2.f,
-1.f + float(j) / float(volumeDimensions.y - 1) * 2.f,
-1.f + float(k) / float(volumeDimensions.z - 1) * 2.f);
};
// generate voxels
std::vector<float> voxels(volumeDimensions.long_product());
tasking::parallel_for(volumeDimensions.z, [&](int k) {
for (int j = 0; j < volumeDimensions.y; j++) {
for (int i = 0; i < volumeDimensions.x; i++) {
// index in array
size_t index = k * volumeDimensions.z * volumeDimensions.y +
j * volumeDimensions.x + i;
// compute volume value
float value = 0.f;
for (auto &p : points) {
vec3f pointCoordinate = logicalToWorldCoordinates(i, j, k);
const float distance = length(pointCoordinate - p.center);
// contribution proportional to weighted inverse-square distance
// (i.e. gravity)
value += p.weight / (distance * distance);
}
voxels[index] = value;
}
}
});
return voxels;
}
cpp::Volume GravitySpheres::createStructuredVolume(
const VoxelArray &voxels) const
{
cpp::Volume volume("structured_volume");
volume.setParam("dimensions", volumeDimensions);
volume.setParam("voxelType", int(OSP_FLOAT));
volume.setParam("gridOrigin", vec3f(-1.f, -1.f, -1.f));
volume.setParam("gridSpacing", vec3f(2.f / reduce_max(volumeDimensions)));
volume.setParam("voxelData", cpp::Data(voxels));
volume.commit();
return volume;
}
cpp::Volume GravitySpheres::createAMRVolume(const VoxelArray &voxels) const
{
const int numLevels = 2;
const int blockSize = 16;
const int refinementLevel = 4;
const float threshold = 1.0;
std::vector<box3i> blockBounds;
std::vector<int> refinementLevels;
std::vector<float> cellWidths;
std::vector<std::vector<float>> blockDataVectors;
std::vector<cpp::Data> blockData;
// convert the structured volume to AMR
ospray::amr::makeAMR(voxels,
volumeDimensions,
numLevels,
blockSize,
refinementLevel,
threshold,
blockBounds,
refinementLevels,
cellWidths,
blockDataVectors);
for (const std::vector<float> &bd : blockDataVectors)
blockData.emplace_back(bd.size(), OSP_FLOAT, bd.data());
// create an AMR volume and assign attributes
cpp::Volume volume("amr_volume");
volume.setParam("voxelType", int(OSP_FLOAT));
volume.setParam("block.data", cpp::Data(blockData));
volume.setParam("block.bounds", cpp::Data(blockBounds));
volume.setParam("block.level", cpp::Data(refinementLevels));
volume.setParam("block.cellWidth", cpp::Data(cellWidths));
volume.commit();
return volume;
}
OSP_REGISTER_TESTING_BUILDER(GravitySpheres, gravity_spheres_volume);
OSP_REGISTER_TESTING_BUILDER(GravitySpheres(true, true, false),
gravity_spheres_amr);
OSP_REGISTER_TESTING_BUILDER(GravitySpheres(false, false, true),
gravity_spheres_isosurface);
} // namespace testing
} // namespace ospray
<commit_msg>fix for 64-bit addresses + use 3D dimensions in GravitySpheresVolume<commit_after>// ======================================================================== //
// Copyright 2009-2019 Intel Corporation //
// //
// 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 "Builder.h"
#include "ospray_testing.h"
// stl
#include <random>
#include <vector>
// ospcommon
#include "ospcommon/tasking/parallel_for.h"
// raw_to_amr
#include "rawToAMR.h"
using namespace ospcommon;
using namespace ospcommon::math;
namespace ospray {
namespace testing {
using VoxelArray = std::vector<float>;
struct GravitySpheres : public detail::Builder
{
GravitySpheres(bool addVolume = true,
bool asAMR = false,
bool addIsosurface = false);
~GravitySpheres() override = default;
void commit() override;
cpp::Group buildGroup() const override;
private:
VoxelArray generateVoxels() const;
cpp::Volume createStructuredVolume(const VoxelArray &voxels) const;
cpp::Volume createAMRVolume(const VoxelArray &voxels) const;
// Data //
vec3i volumeDimensions{128};
int numPoints{10};
bool withVolume{true};
bool createAsAMR{false};
bool withIsosurface{false};
float isovalue{2.5f};
};
// Inlined definitions ////////////////////////////////////////////////////
GravitySpheres::GravitySpheres(bool addVolume,
bool asAMR,
bool addIsosurface)
: withVolume(addVolume),
createAsAMR(asAMR),
withIsosurface(addIsosurface)
{
}
void GravitySpheres::commit()
{
Builder::commit();
volumeDimensions = getParam<vec3i>("volumeDimensions", vec3i(128));
numPoints = getParam<int>("numPoints", 10);
withVolume = getParam<bool>("withVolume", withVolume);
createAsAMR = getParam<bool>("asAMR", createAsAMR);
withIsosurface = getParam<bool>("withIsosurface", withIsosurface);
isovalue = getParam<float>("isovalue", 2.5f);
addPlane = false;
}
cpp::Group GravitySpheres::buildGroup() const
{
auto voxels = generateVoxels();
auto voxelRange = vec2f(0.f, 10.f);
cpp::Volume volume = createAsAMR ? createAMRVolume(voxels)
: createStructuredVolume(voxels);
cpp::VolumetricModel model(volume);
model.setParam("transferFunction", makeTransferFunction(voxelRange));
model.commit();
cpp::Group group;
if (withVolume)
group.setParam("volume", cpp::Data(model));
if (withIsosurface) {
cpp::Geometry isoGeom("isosurfaces");
isoGeom.setParam("isovalue", cpp::Data(isovalue));
isoGeom.setParam("volume", model);
isoGeom.commit();
cpp::Material mat(rendererType, "OBJMaterial");
mat.setParam("Ks", vec3f(0.2f));
mat.commit();
cpp::GeometricModel isoModel(isoGeom);
isoModel.setParam("material", cpp::Data(mat));
isoModel.commit();
group.setParam("geometry", cpp::Data(isoModel));
}
group.commit();
return group;
}
std::vector<float> GravitySpheres::generateVoxels() const
{
struct Point
{
vec3f center;
float weight;
};
// create random number distributions for point center and weight
std::mt19937 gen(randomSeed);
std::uniform_real_distribution<float> centerDistribution(-1.f, 1.f);
std::uniform_real_distribution<float> weightDistribution(0.1f, 0.3f);
// populate the points
std::vector<Point> points(numPoints);
for (auto &p : points) {
p.center.x = centerDistribution(gen);
p.center.y = centerDistribution(gen);
p.center.z = centerDistribution(gen);
p.weight = weightDistribution(gen);
}
// get world coordinate in [-1.f, 1.f] from logical coordinates in [0,
// volumeDimension)
auto logicalToWorldCoordinates = [&](int i, int j, int k) {
return vec3f(-1.f + float(i) / float(volumeDimensions.x - 1) * 2.f,
-1.f + float(j) / float(volumeDimensions.y - 1) * 2.f,
-1.f + float(k) / float(volumeDimensions.z - 1) * 2.f);
};
// generate voxels
std::vector<float> voxels(volumeDimensions.long_product());
tasking::parallel_for(volumeDimensions.z, [&](int k) {
for (int j = 0; j < volumeDimensions.y; j++) {
for (int i = 0; i < volumeDimensions.x; i++) {
// index in array
size_t index = size_t(k) * volumeDimensions.z * volumeDimensions.y +
size_t(j) * volumeDimensions.x + size_t(i);
// compute volume value
float value = 0.f;
for (auto &p : points) {
vec3f pointCoordinate = logicalToWorldCoordinates(i, j, k);
const float distance = length(pointCoordinate - p.center);
// contribution proportional to weighted inverse-square distance
// (i.e. gravity)
value += p.weight / (distance * distance);
}
voxels[index] = value;
}
}
});
return voxels;
}
cpp::Volume GravitySpheres::createStructuredVolume(
const VoxelArray &voxels) const
{
cpp::Volume volume("structured_volume");
volume.setParam("dimensions", volumeDimensions);
volume.setParam("voxelType", int(OSP_FLOAT));
volume.setParam("gridOrigin", vec3f(-1.f, -1.f, -1.f));
volume.setParam("gridSpacing", vec3f(2.f / reduce_max(volumeDimensions)));
volume.setParam("voxelData",
cpp::Data(volumeDimensions, {0}, voxels.data()));
volume.commit();
return volume;
}
cpp::Volume GravitySpheres::createAMRVolume(const VoxelArray &voxels) const
{
const int numLevels = 2;
const int blockSize = 16;
const int refinementLevel = 4;
const float threshold = 1.0;
std::vector<box3i> blockBounds;
std::vector<int> refinementLevels;
std::vector<float> cellWidths;
std::vector<std::vector<float>> blockDataVectors;
std::vector<cpp::Data> blockData;
// convert the structured volume to AMR
ospray::amr::makeAMR(voxels,
volumeDimensions,
numLevels,
blockSize,
refinementLevel,
threshold,
blockBounds,
refinementLevels,
cellWidths,
blockDataVectors);
for (const std::vector<float> &bd : blockDataVectors)
blockData.emplace_back(bd.size(), OSP_FLOAT, bd.data());
// create an AMR volume and assign attributes
cpp::Volume volume("amr_volume");
volume.setParam("voxelType", int(OSP_FLOAT));
volume.setParam("block.data", cpp::Data(blockData));
volume.setParam("block.bounds", cpp::Data(blockBounds));
volume.setParam("block.level", cpp::Data(refinementLevels));
volume.setParam("block.cellWidth", cpp::Data(cellWidths));
volume.commit();
return volume;
}
OSP_REGISTER_TESTING_BUILDER(GravitySpheres, gravity_spheres_volume);
OSP_REGISTER_TESTING_BUILDER(GravitySpheres(true, true, false),
gravity_spheres_amr);
OSP_REGISTER_TESTING_BUILDER(GravitySpheres(false, false, true),
gravity_spheres_isosurface);
} // namespace testing
} // namespace ospray
<|endoftext|> |
<commit_before>/*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
//
// MapCell.cpp
//
#include "StdAfx.h"
MapCell::~MapCell()
{
RemoveObjects();
}
void MapCell::Init(uint32 x, uint32 y, uint32 mapid, MapMgr *mapmgr)
{
_mapmgr = mapmgr;
_active = false;
_loaded = false;
_playerCount = 0;
_x=x;
_y=y;
_unloadpending=false;
_objects.clear();
}
void MapCell::AddObject(Object *obj)
{
if(obj->IsPlayer())
++_playerCount;
_objects.insert(obj);
}
void MapCell::RemoveObject(Object *obj)
{
if(obj->IsPlayer())
--_playerCount;
_objects.erase(obj);
}
void MapCell::SetActivity(bool state)
{
if(!_active && state)
{
// Move all objects to active set.
for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
{
if(!(*itr)->Active && (*itr)->CanActivate())
(*itr)->Activate(_mapmgr);
}
if(_unloadpending)
CancelPendingUnload();
if (sWorld.Collision) {
CollideInterface.ActivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
}
} else if(_active && !state)
{
// Move all objects from active set.
for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
{
if((*itr)->Active)
(*itr)->Deactivate(_mapmgr);
}
if(sWorld.map_unload_time && !_unloadpending)
QueueUnloadPending();
if (sWorld.Collision) {
CollideInterface.DeactivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
}
}
_active = state;
}
void MapCell::RemoveObjects()
{
ObjectSet::iterator itr;
uint32 count = 0;
//uint32 ltime = getMSTime();
/* delete objects in pending respawn state */
for(itr = _respawnObjects.begin(); itr != _respawnObjects.end(); ++itr)
{
switch((*itr)->GetTypeId())
{
case TYPEID_UNIT: {
if( !(*itr)->IsPet() )
{
_mapmgr->_reusable_guids_creature.push_back( (*itr)->GetUIdFromGUID() );
static_cast< Creature* >( *itr )->m_respawnCell=NULL;
delete static_cast< Creature* >( *itr );
}
}break;
case TYPEID_GAMEOBJECT: {
_mapmgr->_reusable_guids_gameobject.push_back( (*itr)->GetUIdFromGUID() );
static_cast< GameObject* >( *itr )->m_respawnCell=NULL;
delete static_cast< GameObject* >( *itr );
}break;
}
}
_respawnObjects.clear();
//This time it's simpler! We just remove everything :)
for(itr = _objects.begin(); itr != _objects.end(); )
{
count++;
Object *obj = (*itr);
itr++;
if(!obj || _unloadpending)
continue;
if( obj->Active )
obj->Deactivate( _mapmgr );
if( obj->IsInWorld() )
obj->RemoveFromWorld( true );
delete obj;
}
_objects.clear();
_playerCount = 0;
_loaded = false;
}
void MapCell::LoadObjects(CellSpawns * sp)
{
_loaded = true;
Instance * pInstance = _mapmgr->pInstance;
InstanceBossInfoMap *bossInfoMap = objmgr.m_InstanceBossInfoMap[_mapmgr->GetMapId()];
if(sp->CreatureSpawns.size())//got creatures
{
for(CreatureSpawnList::iterator i=sp->CreatureSpawns.begin();i!=sp->CreatureSpawns.end();i++)
{
uint32 respawnTimeOverride = 0;
if(pInstance)
{
if(bossInfoMap != NULL && IS_PERSISTENT_INSTANCE(pInstance))
{
bool skip = false;
for(std::set<uint32>::iterator killedNpc = pInstance->m_killedNpcs.begin(); killedNpc != pInstance->m_killedNpcs.end(); ++killedNpc)
{
// Do not spawn the killed boss.
if((*killedNpc) == (*i)->entry)
{
skip = true;
break;
}
// Do not spawn the killed boss' trash.
InstanceBossInfoMap::const_iterator bossInfo = bossInfoMap->find((*killedNpc));
if (bossInfo != bossInfoMap->end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
{
skip = true;
break;
}
}
if(skip)
continue;
for(InstanceBossInfoMap::iterator bossInfo = bossInfoMap->begin(); bossInfo != bossInfoMap->end(); ++bossInfo)
{
if(pInstance->m_killedNpcs.find(bossInfo->second->creatureid) == pInstance->m_killedNpcs.end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
{
respawnTimeOverride = bossInfo->second->trashRespawnOverride;
}
}
}
else
{
// No boss information available ... fallback ...
if(pInstance->m_killedNpcs.find((*i)->id) != pInstance->m_killedNpcs.end())
continue;
}
}
Creature * c=_mapmgr->CreateCreature((*i)->entry);
c->SetMapId(_mapmgr->GetMapId());
c->SetInstanceID(_mapmgr->GetInstanceID());
c->m_loadedFromDB = true;
if(respawnTimeOverride > 0)
c->m_respawnTimeOverride = respawnTimeOverride;
if(c->Load(*i, _mapmgr->iInstanceMode, _mapmgr->GetMapInfo()))
{
if(!c->CanAddToWorld())
delete c;
c->PushToWorld(_mapmgr);
}
else
delete c;//missing proto or smth of that kind
}
}
if(sp->GOSpawns.size())//got GOs
{
for(GOSpawnList::iterator i=sp->GOSpawns.begin();i!=sp->GOSpawns.end();i++)
{
GameObject * go=_mapmgr->CreateGameObject((*i)->entry);
go->SetInstanceID(_mapmgr->GetInstanceID());
if(go->Load(*i))
{
//uint32 state = go->GetUInt32Value(GAMEOBJECT_STATE);
// FIXME - burlex
/*
if(pInstance && pInstance->FindObject((*i)->stateNpcLink))
{
go->SetUInt32Value(GAMEOBJECT_STATE, (state ? 0 : 1));
}*/
go->m_loadedFromDB = true;
go->PushToWorld(_mapmgr);
}
else
delete go;//missing proto or smth of that kind
}
}
}
void MapCell::QueueUnloadPending()
{
if(_unloadpending)
return;
_unloadpending = true;
//Log.Debug("MapCell", "Queueing pending unload of cell %u %u", _x, _y);
sEventMgr.AddEvent(_mapmgr, &MapMgr::UnloadCell,(uint32)_x,(uint32)_y,MAKE_CELL_EVENT(_x,_y),sWorld.map_unload_time * 1000,1,0);
}
void MapCell::CancelPendingUnload()
{
//Log.Debug("MapCell", "Cancelling pending unload of cell %u %u", _x, _y);
if(!_unloadpending)
return;
sEventMgr.RemoveEvents(_mapmgr,MAKE_CELL_EVENT(_x,_y));
}
void MapCell::Unload()
{
//Log.Debug("MapCell", "Unloading cell %u %u", _x, _y);
ASSERT(_unloadpending);
if(_active)
return;
RemoveObjects();
_unloadpending=false;
}
<commit_msg>extending rev 1235 crashfix by 0x0f7afc68. I think there was a logic problem there. The pointout seemed to be good but the fix not. Not sure that was actually a crash issue though. Problem was with cells that entered pending state and meanwhile they got active. This made them get stuck in pending state and not unload anymore and stay loaded forever. NTY.<commit_after>/*
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
//
// MapCell.cpp
//
#include "StdAfx.h"
MapCell::~MapCell()
{
RemoveObjects();
}
void MapCell::Init(uint32 x, uint32 y, uint32 mapid, MapMgr *mapmgr)
{
_mapmgr = mapmgr;
_active = false;
_loaded = false;
_playerCount = 0;
_x=x;
_y=y;
_unloadpending=false;
_objects.clear();
}
void MapCell::AddObject(Object *obj)
{
if(obj->IsPlayer())
++_playerCount;
_objects.insert(obj);
}
void MapCell::RemoveObject(Object *obj)
{
if(obj->IsPlayer())
--_playerCount;
_objects.erase(obj);
}
void MapCell::SetActivity(bool state)
{
if(!_active && state)
{
// Move all objects to active set.
for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
{
if(!(*itr)->Active && (*itr)->CanActivate())
(*itr)->Activate(_mapmgr);
}
if(_unloadpending)
CancelPendingUnload();
if (sWorld.Collision) {
CollideInterface.ActivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
}
} else if(_active && !state)
{
// Move all objects from active set.
for(ObjectSet::iterator itr = _objects.begin(); itr != _objects.end(); ++itr)
{
if((*itr)->Active)
(*itr)->Deactivate(_mapmgr);
}
if(sWorld.map_unload_time && !_unloadpending)
QueueUnloadPending();
if (sWorld.Collision) {
CollideInterface.DeactivateTile(_mapmgr->GetMapId(), _x/8, _y/8);
}
}
_active = state;
}
void MapCell::RemoveObjects()
{
ObjectSet::iterator itr;
uint32 count = 0;
//uint32 ltime = getMSTime();
//Zack : we are delaying cell removal so transports can see objects far away. We are waiting for the event to remove us
if( _unloadpending == true )
return;
/* delete objects in pending respawn state */
for(itr = _respawnObjects.begin(); itr != _respawnObjects.end(); ++itr)
{
switch((*itr)->GetTypeId())
{
case TYPEID_UNIT: {
if( !(*itr)->IsPet() )
{
_mapmgr->_reusable_guids_creature.push_back( (*itr)->GetUIdFromGUID() );
static_cast< Creature* >( *itr )->m_respawnCell=NULL;
delete static_cast< Creature* >( *itr );
}
}break;
case TYPEID_GAMEOBJECT: {
_mapmgr->_reusable_guids_gameobject.push_back( (*itr)->GetUIdFromGUID() );
static_cast< GameObject* >( *itr )->m_respawnCell=NULL;
delete static_cast< GameObject* >( *itr );
}break;
}
}
_respawnObjects.clear();
//This time it's simpler! We just remove everything :)
for(itr = _objects.begin(); itr != _objects.end(); )
{
count++;
Object *obj = (*itr);
itr++;
//zack : we actually never set this to null. Useless check for lucky memory corruption hit.
if(!obj)
continue;
if( obj->Active )
obj->Deactivate( _mapmgr );
if( obj->IsInWorld() )
obj->RemoveFromWorld( true );
delete obj;
}
_objects.clear();
_playerCount = 0;
_loaded = false;
}
void MapCell::LoadObjects(CellSpawns * sp)
{
//we still have mobs loaded on cell. There is no point of loading them again
if( _loaded == true )
return;
_loaded = true;
Instance * pInstance = _mapmgr->pInstance;
InstanceBossInfoMap *bossInfoMap = objmgr.m_InstanceBossInfoMap[_mapmgr->GetMapId()];
if(sp->CreatureSpawns.size())//got creatures
{
for(CreatureSpawnList::iterator i=sp->CreatureSpawns.begin();i!=sp->CreatureSpawns.end();i++)
{
uint32 respawnTimeOverride = 0;
if(pInstance)
{
if(bossInfoMap != NULL && IS_PERSISTENT_INSTANCE(pInstance))
{
bool skip = false;
for(std::set<uint32>::iterator killedNpc = pInstance->m_killedNpcs.begin(); killedNpc != pInstance->m_killedNpcs.end(); ++killedNpc)
{
// Do not spawn the killed boss.
if((*killedNpc) == (*i)->entry)
{
skip = true;
break;
}
// Do not spawn the killed boss' trash.
InstanceBossInfoMap::const_iterator bossInfo = bossInfoMap->find((*killedNpc));
if (bossInfo != bossInfoMap->end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
{
skip = true;
break;
}
}
if(skip)
continue;
for(InstanceBossInfoMap::iterator bossInfo = bossInfoMap->begin(); bossInfo != bossInfoMap->end(); ++bossInfo)
{
if(pInstance->m_killedNpcs.find(bossInfo->second->creatureid) == pInstance->m_killedNpcs.end() && bossInfo->second->trash.find((*i)->id) != bossInfo->second->trash.end())
{
respawnTimeOverride = bossInfo->second->trashRespawnOverride;
}
}
}
else
{
// No boss information available ... fallback ...
if(pInstance->m_killedNpcs.find((*i)->id) != pInstance->m_killedNpcs.end())
continue;
}
}
Creature * c=_mapmgr->CreateCreature((*i)->entry);
c->SetMapId(_mapmgr->GetMapId());
c->SetInstanceID(_mapmgr->GetInstanceID());
c->m_loadedFromDB = true;
if(respawnTimeOverride > 0)
c->m_respawnTimeOverride = respawnTimeOverride;
if(c->Load(*i, _mapmgr->iInstanceMode, _mapmgr->GetMapInfo()))
{
if(!c->CanAddToWorld())
delete c;
c->PushToWorld(_mapmgr);
}
else
delete c;//missing proto or smth of that kind
}
}
if(sp->GOSpawns.size())//got GOs
{
for(GOSpawnList::iterator i=sp->GOSpawns.begin();i!=sp->GOSpawns.end();i++)
{
GameObject * go=_mapmgr->CreateGameObject((*i)->entry);
go->SetInstanceID(_mapmgr->GetInstanceID());
if(go->Load(*i))
{
//uint32 state = go->GetUInt32Value(GAMEOBJECT_STATE);
// FIXME - burlex
/*
if(pInstance && pInstance->FindObject((*i)->stateNpcLink))
{
go->SetUInt32Value(GAMEOBJECT_STATE, (state ? 0 : 1));
}*/
go->m_loadedFromDB = true;
go->PushToWorld(_mapmgr);
}
else
delete go;//missing proto or smth of that kind
}
}
}
void MapCell::QueueUnloadPending()
{
if(_unloadpending)
return;
_unloadpending = true;
//Log.Debug("MapCell", "Queueing pending unload of cell %u %u", _x, _y);
sEventMgr.AddEvent(_mapmgr, &MapMgr::UnloadCell,(uint32)_x,(uint32)_y,MAKE_CELL_EVENT(_x,_y),sWorld.map_unload_time * 1000,1,0);
}
void MapCell::CancelPendingUnload()
{
//Log.Debug("MapCell", "Cancelling pending unload of cell %u %u", _x, _y);
if(!_unloadpending)
return;
sEventMgr.RemoveEvents(_mapmgr,MAKE_CELL_EVENT(_x,_y));
}
void MapCell::Unload()
{
//Log.Debug("MapCell", "Unloading cell %u %u", _x, _y);
ASSERT(_unloadpending);
if(_active)
{
_unloadpending=false;
return;
}
_unloadpending=false;
RemoveObjects();
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2007 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
*/
/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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 COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#include "arch/x86/floatregfile.hh"
#include "sim/serialize.hh"
#include <string.h>
using namespace X86ISA;
using namespace std;
class Checkpoint;
string X86ISA::getFloatRegName(RegIndex index)
{
static std::string floatRegName[NumFloatRegs] =
{"mmx0", "mmx1", "mmx2", "mmx3", "mmx4", "mmx5", "mmx6", "mmx7",
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"};
return floatRegName[index];
}
void FloatRegFile::clear()
{
memset(q, 0, sizeof(FloatReg) * NumFloatRegs);
}
FloatReg FloatRegFile::readReg(int floatReg, int width)
{
return d[floatReg];
}
FloatRegBits FloatRegFile::readRegBits(int floatReg, int width)
{
return q[floatReg];
}
Fault FloatRegFile::setReg(int floatReg, const FloatReg &val, int width)
{
d[floatReg] = val;
return NoFault;
}
Fault FloatRegFile::setRegBits(int floatReg, const FloatRegBits &val, int width)
{
q[floatReg] = val;
return NoFault;
}
void FloatRegFile::serialize(std::ostream &os)
{
SERIALIZE_ARRAY(q, NumFloatRegs);
}
void FloatRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_ARRAY(q, NumFloatRegs);
}
<commit_msg>X86: Add tracing to the floating point register file.<commit_after>/*
* Copyright (c) 2003-2007 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders 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.
*
* Authors: Gabe Black
*/
/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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 COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#include "arch/x86/floatregfile.hh"
#include "base/trace.hh"
#include "sim/serialize.hh"
#include <string.h>
using namespace X86ISA;
using namespace std;
class Checkpoint;
string X86ISA::getFloatRegName(RegIndex index)
{
static std::string floatRegName[NumFloatRegs] =
{"mmx0", "mmx1", "mmx2", "mmx3", "mmx4", "mmx5", "mmx6", "mmx7",
"xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15"};
return floatRegName[index];
}
void FloatRegFile::clear()
{
memset(q, 0, sizeof(FloatReg) * NumFloatRegs);
}
FloatReg FloatRegFile::readReg(int floatReg, int width)
{
FloatReg reg = d[floatReg];
DPRINTF(X86, "Reading %f from register %d.\n", reg, floatReg);
return reg;
}
FloatRegBits FloatRegFile::readRegBits(int floatReg, int width)
{
FloatRegBits reg = q[floatReg];
DPRINTF(X86, "Reading %#x from register %d.\n", reg, floatReg);
return reg;
}
Fault FloatRegFile::setReg(int floatReg, const FloatReg &val, int width)
{
DPRINTF(X86, "Writing %f to register %d.\n", val, floatReg);
d[floatReg] = val;
return NoFault;
}
Fault FloatRegFile::setRegBits(int floatReg, const FloatRegBits &val, int width)
{
DPRINTF(X86, "Writing bits %#x to register %d.\n", val, floatReg);
q[floatReg] = val;
return NoFault;
}
void FloatRegFile::serialize(std::ostream &os)
{
SERIALIZE_ARRAY(q, NumFloatRegs);
}
void FloatRegFile::unserialize(Checkpoint *cp, const std::string §ion)
{
UNSERIALIZE_ARRAY(q, NumFloatRegs);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive 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.
*
* cclive 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
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HOST_W32
// A peculiar thing this one. If commented out or included *after* "config.h",
// mingw32-g++ returns: error: '::malloc' has not been declared
#include <cstdlib>
#endif
#include "config.h"
#include <iterator>
#include <sstream>
#include <climits>
#include <iomanip>
#include <string>
#include <vector>
#include "except.h"
#include "util.h"
#include "opts.h"
#include "curl.h"
#include "video.h"
VideoProperties::VideoProperties()
: id(""), link(""), host(""), domain(""),
formats("flv"), title(""), length(0), initial(0),
contentType(""), suffix("flv"), filename(""),pageLink("")
{
}
void
VideoProperties::setId(const std::string& id) {
this->id = id;
}
void
VideoProperties::setLink(std::string link) {
this->link = curlmgr.unescape(link);
}
void
VideoProperties::setHost(const std::string& host) {
this->host = host;
}
void
VideoProperties::setDomain(const std::string& domain) {
this->domain = domain;
}
void
VideoProperties::setFormats(const std::string& formats) {
this->formats = formats;
}
void
VideoProperties::setLength(const double length) {
this->length = length;
}
void
VideoProperties::setPageLink(const std::string& link) {
this->pageLink = link;
}
void
VideoProperties::setContentType(const std::string& contentType) {
this->contentType = contentType;
std::string::size_type pos = contentType.find("/");
if (pos != std::string::npos) {
suffix = contentType.substr(pos+1);
// set to "flv" for these:
if (suffix.find("octet") != std::string::npos
|| suffix.find("plain") != std::string::npos)
{
suffix = "flv";
}
Util::subStrReplace(suffix, "x-", "");
}
}
void
VideoProperties::setInitial(const double initial) {
this->initial = initial;
}
#include <iostream>
void
VideoProperties::setTitle(const std::string& title) {
this->title = title;
std::cout << __func__ << ": " << title << std::endl;
}
const std::string&
VideoProperties::getId() const {
return id;
}
const std::string&
VideoProperties::getLink() const {
return link;
}
const std::string&
VideoProperties::getHost() const {
return host;
}
const std::string&
VideoProperties::getDomain() const {
return domain;
}
const std::string&
VideoProperties::getFormats() const {
return formats;
}
const std::string&
VideoProperties::getTitle() const {
return title;
}
const double
VideoProperties::getLength() const {
return length;
}
const std::string&
VideoProperties::getPageLink() const {
return pageLink;
}
const double
VideoProperties::getInitial() const {
return initial;
}
const std::string&
VideoProperties::getContentType() const {
return contentType;
}
const std::string&
VideoProperties::getFilename() const {
return filename;
}
static int video_num;
void
VideoProperties::formatOutputFilename() {
std::cout << __func__ << ": " << title << std::endl;
Options opts = optsmgr.getOptions();
if (!opts.output_video_given) {
std::stringstream b;
if (opts.number_videos_given) {
b << std::setw(4)
<< std::setfill('0')
<< ++video_num
<< "_";
}
if (!opts.filename_format_given)
defaultOutputFilenameFormatter(b);
else
customOutputFilenameFormatter(b);
filename = b.str();
for (register int i=1; i<INT_MAX; ++i) {
initial = Util::fileExists(filename);
if (initial == 0)
break;
else if (initial == length)
throw NothingToDoException();
else {
if (opts.continue_given)
break;
}
std::stringstream tmp;
tmp << b.str() << "." << i;
filename = tmp.str();
}
}
else {
initial = Util::fileExists(opts.output_video_arg);
if (initial == length)
throw NothingToDoException();
filename = opts.output_video_arg;
}
if (!opts.continue_given)
initial = 0;
}
void
VideoProperties::defaultOutputFilenameFormatter(
std::stringstream& b)
{
Options opts = optsmgr.getOptions();
if (opts.title_given && title.length() > 0)
b << title;
else {
Util::subStrReplace(id, "-", "_");
b << host << "_" << id;
}
b << "." << suffix;
}
void
VideoProperties::customOutputFilenameFormatter(
std::stringstream& b)
{
Options opts = optsmgr.getOptions();
std::string fmt = opts.filename_format_arg;
std::string _title = id;
#ifdef WITH_PERL
if (opts.title_given && title.length() > 0)
_title = title;
#endif
Util::subStrReplace(fmt, "%t", _title);
Util::subStrReplace(fmt, "%i", id);
Util::subStrReplace(fmt, "%h", host);
Util::subStrReplace(fmt, "%s", suffix);
b << fmt;
}
VideoProperties::
NothingToDoException::NothingToDoException()
: RuntimeException(CCLIVE_NOTHINGTODO)
{
}
<commit_msg>video.cpp: remove std::cout from earlier debugging.<commit_after>/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive 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.
*
* cclive 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
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HOST_W32
// A peculiar thing this one. If commented out or included *after* "config.h",
// mingw32-g++ returns: error: '::malloc' has not been declared
#include <cstdlib>
#endif
#include "config.h"
#include <iterator>
#include <sstream>
#include <climits>
#include <iomanip>
#include <string>
#include <vector>
#include "except.h"
#include "util.h"
#include "opts.h"
#include "curl.h"
#include "video.h"
VideoProperties::VideoProperties()
: id(""), link(""), host(""), domain(""),
formats("flv"), title(""), length(0), initial(0),
contentType(""), suffix("flv"), filename(""),pageLink("")
{
}
void
VideoProperties::setId(const std::string& id) {
this->id = id;
}
void
VideoProperties::setLink(std::string link) {
this->link = curlmgr.unescape(link);
}
void
VideoProperties::setHost(const std::string& host) {
this->host = host;
}
void
VideoProperties::setDomain(const std::string& domain) {
this->domain = domain;
}
void
VideoProperties::setFormats(const std::string& formats) {
this->formats = formats;
}
void
VideoProperties::setLength(const double length) {
this->length = length;
}
void
VideoProperties::setPageLink(const std::string& link) {
this->pageLink = link;
}
void
VideoProperties::setContentType(const std::string& contentType) {
this->contentType = contentType;
std::string::size_type pos = contentType.find("/");
if (pos != std::string::npos) {
suffix = contentType.substr(pos+1);
// set to "flv" for these:
if (suffix.find("octet") != std::string::npos
|| suffix.find("plain") != std::string::npos)
{
suffix = "flv";
}
Util::subStrReplace(suffix, "x-", "");
}
}
void
VideoProperties::setInitial(const double initial) {
this->initial = initial;
}
void
VideoProperties::setTitle(const std::string& title) {
this->title = title;
}
const std::string&
VideoProperties::getId() const {
return id;
}
const std::string&
VideoProperties::getLink() const {
return link;
}
const std::string&
VideoProperties::getHost() const {
return host;
}
const std::string&
VideoProperties::getDomain() const {
return domain;
}
const std::string&
VideoProperties::getFormats() const {
return formats;
}
const std::string&
VideoProperties::getTitle() const {
return title;
}
const double
VideoProperties::getLength() const {
return length;
}
const std::string&
VideoProperties::getPageLink() const {
return pageLink;
}
const double
VideoProperties::getInitial() const {
return initial;
}
const std::string&
VideoProperties::getContentType() const {
return contentType;
}
const std::string&
VideoProperties::getFilename() const {
return filename;
}
static int video_num;
void
VideoProperties::formatOutputFilename() {
Options opts = optsmgr.getOptions();
if (!opts.output_video_given) {
std::stringstream b;
if (opts.number_videos_given) {
b << std::setw(4)
<< std::setfill('0')
<< ++video_num
<< "_";
}
if (!opts.filename_format_given)
defaultOutputFilenameFormatter(b);
else
customOutputFilenameFormatter(b);
filename = b.str();
for (register int i=1; i<INT_MAX; ++i) {
initial = Util::fileExists(filename);
if (initial == 0)
break;
else if (initial == length)
throw NothingToDoException();
else {
if (opts.continue_given)
break;
}
std::stringstream tmp;
tmp << b.str() << "." << i;
filename = tmp.str();
}
}
else {
initial = Util::fileExists(opts.output_video_arg);
if (initial == length)
throw NothingToDoException();
filename = opts.output_video_arg;
}
if (!opts.continue_given)
initial = 0;
}
void
VideoProperties::defaultOutputFilenameFormatter(
std::stringstream& b)
{
Options opts = optsmgr.getOptions();
if (opts.title_given && title.length() > 0)
b << title;
else {
Util::subStrReplace(id, "-", "_");
b << host << "_" << id;
}
b << "." << suffix;
}
void
VideoProperties::customOutputFilenameFormatter(
std::stringstream& b)
{
Options opts = optsmgr.getOptions();
std::string fmt = opts.filename_format_arg;
std::string _title = id;
#ifdef WITH_PERL
if (opts.title_given && title.length() > 0)
_title = title;
#endif
Util::subStrReplace(fmt, "%t", _title);
Util::subStrReplace(fmt, "%i", id);
Util::subStrReplace(fmt, "%h", host);
Util::subStrReplace(fmt, "%s", suffix);
b << fmt;
}
VideoProperties::
NothingToDoException::NothingToDoException()
: RuntimeException(CCLIVE_NOTHINGTODO)
{
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <[email protected]>
Copyright (C) 2009 Martin Sandsmark <[email protected]>
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.), Nokia Corporation
(or its successors, if any) and the KDE Free Qt Foundation, 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 "audiodataoutput.h"
#include "gsthelper.h"
#include "medianode.h"
#include "mediaobject.h"
#include <QtCore/QVector>
#include <QtCore/QMap>
#include <phonon/audiooutput.h>
namespace Phonon
{
namespace Gstreamer
{
AudioDataOutput::AudioDataOutput(Backend *backend, QObject *parent)
: QObject(parent),
MediaNode(backend, AudioSink | AudioSource)
{
static int count = 0;
m_name = "AudioDataOutput" + QString::number(count++);
m_queue = gst_element_factory_make ("identify", NULL);
gst_object_ref(m_queue);
m_isValid = true;
}
AudioDataOutput::~AudioDataOutput()
{
gst_element_set_state(m_queue, GST_STATE_NULL);
gst_object_unref(m_queue);
}
int AudioDataOutput::dataSize() const
{
return m_dataSize;
}
int AudioDataOutput::sampleRate() const
{
return 44100;
}
void AudioDataOutput::setDataSize(int size)
{
m_dataSize = size;
}
typedef QMap<Phonon::AudioDataOutput::Channel, QVector<float> > FloatMap;
typedef QMap<Phonon::AudioDataOutput::Channel, QVector<qint16> > IntMap;
inline void AudioDataOutput::convertAndEmit(const QVector<qint16> &leftBuffer, const QVector<qint16> &rightBuffer)
{
//TODO: Floats
IntMap map;
map.insert(Phonon::AudioDataOutput::LeftChannel, leftBuffer);
map.insert(Phonon::AudioDataOutput::RightChannel, rightBuffer);
emit dataReady(map);
}
void AudioDataOutput::processBuffer(GstPad*, GstBuffer* buffer, gpointer gThat)
{
// TODO emit endOfMedia
AudioDataOutput *that = reinterpret_cast<AudioDataOutput*>(gThat);
// determine the number of channels
GstStructure* structure = gst_caps_get_structure (GST_BUFFER_CAPS(buffer), 0);
gst_structure_get_int (structure, "channels", &that->m_channels);
if (that->m_channels > 2 || that->m_channels < 0) {
qWarning() << Q_FUNC_INFO << ": Number of channels not supported: " << that->m_channels;
return;
}
gint16 *data = reinterpret_cast<gint16*>(GST_BUFFER_DATA(buffer));
guint size = GST_BUFFER_SIZE(buffer) / sizeof(gint16);
that->m_pendingData.reserve(that->m_pendingData.size() + size);
for (uint i=0; i<size; i++) {
// 8 bit? interleaved? yay for lacking documentation!
that->m_pendingData.append(data[i]);
}
while (that->m_pendingData.size() > that->m_dataSize * that->m_channels) {
if (that->m_channels == 1) {
QVector<qint16> intBuffer(that->m_dataSize);
memcpy(intBuffer.data(), that->m_pendingData.constData(), that->m_dataSize * sizeof(qint16));
that->convertAndEmit(intBuffer, intBuffer);
int newSize = that->m_pendingData.size() - that->m_dataSize;
memmove(that->m_pendingData.data(), that->m_pendingData.constData() + that->m_dataSize, newSize * sizeof(qint16));
that->m_pendingData.resize(newSize);
} else {
QVector<qint16> left(that->m_dataSize), right(that->m_dataSize);
for (int i=0; i<that->m_dataSize; i++) {
left[i] = that->m_pendingData[i*2];
right[i] = that->m_pendingData[i*2+1];
}
that->m_pendingData.resize(that->m_pendingData.size() - that->m_dataSize*2);
that->convertAndEmit(left, right);
}
}
}
void AudioDataOutput::mediaNodeEvent(const MediaNodeEvent *event)
{
if (event->type() == MediaNodeEvent::MediaObjectConnected && root()) {
g_object_set(G_OBJECT(audioElement()), "sync", true, (const char*)NULL);
GstPad *audiopad = gst_element_get_pad (audioElement(), "src");
gst_pad_add_buffer_probe (audiopad, G_CALLBACK(processBuffer), this);
gst_object_unref (audiopad);
return;
}
MediaNode::mediaNodeEvent(event);
}
}} //namespace Phonon::Gstreamer
#include "moc_audiodataoutput.cpp"
// vim: sw=4 ts=4
<commit_msg>typo (identify vs. identity)<commit_after>/* This file is part of the KDE project
Copyright (C) 2006 Matthias Kretz <[email protected]>
Copyright (C) 2009 Martin Sandsmark <[email protected]>
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.), Nokia Corporation
(or its successors, if any) and the KDE Free Qt Foundation, 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 "audiodataoutput.h"
#include "gsthelper.h"
#include "medianode.h"
#include "mediaobject.h"
#include <QtCore/QVector>
#include <QtCore/QMap>
#include <phonon/audiooutput.h>
namespace Phonon
{
namespace Gstreamer
{
AudioDataOutput::AudioDataOutput(Backend *backend, QObject *parent)
: QObject(parent),
MediaNode(backend, AudioSink | AudioSource)
{
static int count = 0;
m_name = "AudioDataOutput" + QString::number(count++);
m_queue = gst_element_factory_make ("identity", NULL);
gst_object_ref(m_queue);
m_isValid = true;
}
AudioDataOutput::~AudioDataOutput()
{
gst_element_set_state(m_queue, GST_STATE_NULL);
gst_object_unref(m_queue);
}
int AudioDataOutput::dataSize() const
{
return m_dataSize;
}
int AudioDataOutput::sampleRate() const
{
return 44100;
}
void AudioDataOutput::setDataSize(int size)
{
m_dataSize = size;
}
typedef QMap<Phonon::AudioDataOutput::Channel, QVector<float> > FloatMap;
typedef QMap<Phonon::AudioDataOutput::Channel, QVector<qint16> > IntMap;
inline void AudioDataOutput::convertAndEmit(const QVector<qint16> &leftBuffer, const QVector<qint16> &rightBuffer)
{
//TODO: Floats
IntMap map;
map.insert(Phonon::AudioDataOutput::LeftChannel, leftBuffer);
map.insert(Phonon::AudioDataOutput::RightChannel, rightBuffer);
emit dataReady(map);
}
void AudioDataOutput::processBuffer(GstPad*, GstBuffer* buffer, gpointer gThat)
{
// TODO emit endOfMedia
AudioDataOutput *that = reinterpret_cast<AudioDataOutput*>(gThat);
// determine the number of channels
GstStructure* structure = gst_caps_get_structure (GST_BUFFER_CAPS(buffer), 0);
gst_structure_get_int (structure, "channels", &that->m_channels);
if (that->m_channels > 2 || that->m_channels < 0) {
qWarning() << Q_FUNC_INFO << ": Number of channels not supported: " << that->m_channels;
return;
}
gint16 *data = reinterpret_cast<gint16*>(GST_BUFFER_DATA(buffer));
guint size = GST_BUFFER_SIZE(buffer) / sizeof(gint16);
that->m_pendingData.reserve(that->m_pendingData.size() + size);
for (uint i=0; i<size; i++) {
// 8 bit? interleaved? yay for lacking documentation!
that->m_pendingData.append(data[i]);
}
while (that->m_pendingData.size() > that->m_dataSize * that->m_channels) {
if (that->m_channels == 1) {
QVector<qint16> intBuffer(that->m_dataSize);
memcpy(intBuffer.data(), that->m_pendingData.constData(), that->m_dataSize * sizeof(qint16));
that->convertAndEmit(intBuffer, intBuffer);
int newSize = that->m_pendingData.size() - that->m_dataSize;
memmove(that->m_pendingData.data(), that->m_pendingData.constData() + that->m_dataSize, newSize * sizeof(qint16));
that->m_pendingData.resize(newSize);
} else {
QVector<qint16> left(that->m_dataSize), right(that->m_dataSize);
for (int i=0; i<that->m_dataSize; i++) {
left[i] = that->m_pendingData[i*2];
right[i] = that->m_pendingData[i*2+1];
}
that->m_pendingData.resize(that->m_pendingData.size() - that->m_dataSize*2);
that->convertAndEmit(left, right);
}
}
}
void AudioDataOutput::mediaNodeEvent(const MediaNodeEvent *event)
{
if (event->type() == MediaNodeEvent::MediaObjectConnected && root()) {
g_object_set(G_OBJECT(audioElement()), "sync", true, (const char*)NULL);
GstPad *audiopad = gst_element_get_pad (audioElement(), "src");
gst_pad_add_buffer_probe (audiopad, G_CALLBACK(processBuffer), this);
gst_object_unref (audiopad);
return;
}
MediaNode::mediaNodeEvent(event);
}
}} //namespace Phonon::Gstreamer
#include "moc_audiodataoutput.cpp"
// vim: sw=4 ts=4
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "common/main_delegate.h"
#include "browser/browser_client.h"
#include "common/content_client.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"
namespace brightray {
MainDelegate::MainDelegate() {
}
MainDelegate::~MainDelegate() {
}
scoped_ptr<ContentClient> MainDelegate::CreateContentClient() {
return make_scoped_ptr(new ContentClient).Pass();
}
bool MainDelegate::BasicStartupComplete(int* exit_code) {
content_client_ = CreateContentClient().Pass();
SetContentClient(content_client_.get());
return false;
}
void MainDelegate::PreSandboxStartup() {
#if defined(OS_MACOSX)
OverrideChildProcessPath();
OverrideFrameworkBundlePath();
#endif
InitializeResourceBundle();
}
void MainDelegate::InitializeResourceBundle() {
base::FilePath path;
#if defined(OS_MACOSX)
path = GetResourcesPakFilePath();
#else
base::FilePath pak_dir;
PathService::Get(base::DIR_MODULE, &pak_dir);
path = pak_dir.Append(FILE_PATH_LITERAL("content_shell.pak"));
#endif
ui::ResourceBundle::InitSharedInstanceWithPakPath(path);
std::vector<base::FilePath> pak_paths;
AddPakPaths(&pak_paths);
for (auto it = pak_paths.begin(), end = pak_paths.end(); it != end; ++it) {
ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
*it, ui::SCALE_FACTOR_NONE);
}
}
content::ContentBrowserClient* MainDelegate::CreateContentBrowserClient() {
browser_client_ = CreateBrowserClient().Pass();
return browser_client_.get();
}
scoped_ptr<BrowserClient> MainDelegate::CreateBrowserClient() {
return make_scoped_ptr(new BrowserClient).Pass();
}
} // namespace brightray
<commit_msg>Fix assertion in InitializeICU on launch<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE-CHROMIUM file.
#include "common/main_delegate.h"
#include "browser/browser_client.h"
#include "common/content_client.h"
#include "base/command_line.h"
#include "base/path_service.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"
namespace brightray {
MainDelegate::MainDelegate() {
}
MainDelegate::~MainDelegate() {
}
scoped_ptr<ContentClient> MainDelegate::CreateContentClient() {
return make_scoped_ptr(new ContentClient).Pass();
}
bool MainDelegate::BasicStartupComplete(int* exit_code) {
content_client_ = CreateContentClient().Pass();
SetContentClient(content_client_.get());
#if defined(OS_MACOSX)
OverrideChildProcessPath();
OverrideFrameworkBundlePath();
#endif
return false;
}
void MainDelegate::PreSandboxStartup() {
InitializeResourceBundle();
}
void MainDelegate::InitializeResourceBundle() {
base::FilePath path;
#if defined(OS_MACOSX)
path = GetResourcesPakFilePath();
#else
base::FilePath pak_dir;
PathService::Get(base::DIR_MODULE, &pak_dir);
path = pak_dir.Append(FILE_PATH_LITERAL("content_shell.pak"));
#endif
ui::ResourceBundle::InitSharedInstanceWithPakPath(path);
std::vector<base::FilePath> pak_paths;
AddPakPaths(&pak_paths);
for (auto it = pak_paths.begin(), end = pak_paths.end(); it != end; ++it) {
ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
*it, ui::SCALE_FACTOR_NONE);
}
}
content::ContentBrowserClient* MainDelegate::CreateContentBrowserClient() {
browser_client_ = CreateBrowserClient().Pass();
return browser_client_.get();
}
scoped_ptr<BrowserClient> MainDelegate::CreateBrowserClient() {
return make_scoped_ptr(new BrowserClient).Pass();
}
} // namespace brightray
<|endoftext|> |
<commit_before>
#include <node.h>
#ifdef WIN32
#include <windows.h>
#endif
using namespace v8;
using namespace node;
Handle<Value> load(const Arguments& args)
{
HandleScope scope;
if (args.Length() < 1 || !args[0]->IsString()) {
return ThrowException(
Exception::Error(String::New("Missing param: load(pythonHome).")));
}
String::Utf8Value pythonHome(args[0]->ToString());
#ifdef WIN32
char lpPathStringA[MAX_PATH];
wchar_t lpPathStringW[MAX_PATH];
sprintf(lpPathStringA, "%s", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0, lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (!SetEnvironmentVariable(L"PYTHONHOME", lpPathStringW)) {
return ThrowException(
Exception::Error(String::New("Failed to set environment variable: PYTHONHOME.")));
}
sprintf(lpPathStringA, "%s\\python27.dll", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0, lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (LoadLibrary(lpPathStringW) == NULL) {
return ThrowException(
Exception::Error(String::New("Failed to load library: python27.dll.")));
}
sprintf(lpPathStringA, "%s\\pywintypes27.dll", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0,lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (LoadLibrary(lpPathStringW) == NULL) {
return ThrowException(
Exception::Error(String::New("Failed to load library: pywintypes27.dll.")));
}
sprintf(lpPathStringA, "%s\\pythoncomloader27.dll", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0, lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (LoadLibrary(lpPathStringW) == NULL) {
return ThrowException(
Exception::Error(String::New("Failed to load library: pythoncomloader27.dll.")));
}
sprintf(lpPathStringA, "%s\\pythoncom27.dll", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0, lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (LoadLibrary(lpPathStringW) == NULL) {
return ThrowException(
Exception::Error(String::New("FFailed to load library: pythoncom27.dll.")));
}
#elif __APPLE__
setenv("PYTHONHOME", *pythonHome, 1);
#endif
return Undefined();
}
void init(Handle<Object> exports)
{
HandleScope scope;
// module.exports.load
exports->Set(String::NewSymbol("load"),
FunctionTemplate::New(load)->GetFunction());
}
NODE_MODULE(binding, init)
<commit_msg>update for nodejs(0.12.0), v8(3.28.73); available for nw.js(0.11.6), nodejs(0.11.13-pre), v8(3.22.24.19)<commit_after>
#include <node.h>
#ifdef WIN32
#include <windows.h>
#endif
using namespace v8;
using namespace node;
void load(const FunctionCallbackInfo<Value>& args)
{
HandleScope scope(args.GetIsolate());
if (args.Length() < 1 || !args[0]->IsString()) {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(
Exception::Error(String::NewFromUtf8(args.GetIsolate(), "Missing param: load(pythonHome)."))));
return;
}
String::Utf8Value pythonHome(args[0]->ToString());
#ifdef WIN32
char lpPathStringA[MAX_PATH];
wchar_t lpPathStringW[MAX_PATH];
sprintf(lpPathStringA, "%s", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0, lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (!SetEnvironmentVariable(L"PYTHONHOME", lpPathStringW)) {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(
Exception::Error(String::NewFromUtf8(args.GetIsolate(), "Failed to set environment variable: PYTHONHOME."))));
return;
}
sprintf(lpPathStringA, "%s\\python27.dll", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0, lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (LoadLibrary(lpPathStringW) == NULL) {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(
Exception::Error(String::NewFromUtf8(args.GetIsolate(), "Failed to load library: python27.dll."))));
return;
}
sprintf(lpPathStringA, "%s\\pywintypes27.dll", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0,lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (LoadLibrary(lpPathStringW) == NULL) {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(
Exception::Error(String::NewFromUtf8(args.GetIsolate(), "Failed to load library: pywintypes27.dll."))));
return;
}
sprintf(lpPathStringA, "%s\\pythoncomloader27.dll", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0, lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (LoadLibrary(lpPathStringW) == NULL) {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(
Exception::Error(String::NewFromUtf8(args.GetIsolate(), "Failed to load library: pythoncomloader27.dll."))));
return;
}
sprintf(lpPathStringA, "%s\\pythoncom27.dll", *pythonHome);
MultiByteToWideChar(CP_UTF8, 0, lpPathStringA, -1, lpPathStringW, MAX_PATH);
if (LoadLibrary(lpPathStringW) == NULL) {
args.GetReturnValue().Set(args.GetIsolate()->ThrowException(
Exception::Error(String::NewFromUtf8(args.GetIsolate(), "Failed to load library: pythoncom27.dll."))));
return;
}
#elif __APPLE__
setenv("PYTHONHOME", *pythonHome, 1);
#endif
args.GetReturnValue().Set(Undefined(args.GetIsolate()));
}
void init(Handle<Object> exports)
{
HandleScope scope(Isolate::GetCurrent());
// module.exports.load
exports->Set(String::NewFromUtf8(Isolate::GetCurrent(), "load", String::kInternalizedString),
FunctionTemplate::New(Isolate::GetCurrent(), load)->GetFunction());
}
NODE_MODULE(binding, init)
<|endoftext|> |
<commit_before>#include "SafierWind.hpp"
#include "DebugUtils.hpp"
#include "IDiskHump.hpp"
#include <cmath>
#include <string>
struct SafierWindModel
{
double dxi0;
double a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8;
double b_0, b_1, b_2, b_3, b_4, b_5, b_6, b_7, b_8, b_9;
};
namespace
{
constexpr SafierWindModel modelB{1.73,
-0.30, 0.54, 1.14, 0.26, 1.76, 0.92, 0.09, 0.27,
0.035, 7.7, 1.01, 0.31, 1.1, 0.40, -0.10, 0.0, 1.25, 0.60};
constexpr SafierWindModel modelC{1.73,
0.21, 0.30, 1.23, 0.21, 1.27, 0.92, 0.04, 0.28,
0.035, 12.16, 0.65, 0.33, 1.0, 0.40, 0.50, 0.0, 1.25, 0.60};
constexpr SafierWindModel modelD {1.73,
0.49, 0.17, 1.27, 0.11, 0.89, 0.97, 0.02, 0.31,
0.035, 20.08, 0.42, 0.34, 1.0, 0.40, 0.90, 0.0, 1.00, 0.60};
constexpr SafierWindModel modelI{1.73,
0.18, 0.14, 1.86, 0.26, 1.30, 0.92, 0.02, 0.24,
0.035, 33.52, 0.55, 0.26, 2.5, 0.50, 1.00, 0.0, 0.75, 1.00};
constexpr SafierWindModel modelE{3.73,
-0.51, 0.62, 1.02, 0.03, 2.46, 0.91, 0.01, 0.32,
0.01, 6.95, 0.53, 0.30, 1.0, 0.40, 0.90, 0.0, 1.00, 0.60};
constexpr SafierWindModel modelF{3.73,
-0.22, 0.50, 0.98, 0.09, 2.78, 0.92, 0.01, 0.27,
0.01, 11.62, 0.67, 0.20, 1.8, 0.40, 1.00, 0.0, 0.85, 0.55};
constexpr SafierWindModel modelG {3.73,
0.07, 0.05, 0.42, 0.05, 2.95, 0.94, 0.008, 0.26,
0.01, 18.70, 0.78, 0.14, 3.3, 0.55, 1.00, 0.0, 0.30, 1.10};
SafierWindModel const* getModel(char const key)
{
if (key == 'B')
{
return &modelB;
} else if (key == 'C') {
return &modelC;
} else if (key == 'D') {
return &modelD;
} else if (key == 'I') {
return &modelI;
} else if (key == 'E') {
return &modelE;
} else if (key == 'F') {
return &modelF;
} else if (key == 'G') {
return &modelG;
}
return nullptr;
}
double rho0(const SafierWindModel* const model, double mOut, double mStar, double h0, double rRatio)
{
return 1.064e-15 * (mOut/1e-7) * std::pow(mStar/0.5, -0.5) / std::log(rRatio) /
model->b_0/(1.0-h0*model->dxi0);
}
double xi(const SafierWindModel* const model, double h)
{
double xi1 = (1+model->a_1*h + model->a_2*pow(h, model->a_3)) * exp(-model->a_4*h);
double xi2 = model->a_5 * pow(h, model->a_6) * exp(-4*model->a_7*pow(h, model->a_8));
return xi1 + xi2;
}
double psi(const SafierWindModel* const model, double h)
{
double psi1 = (model->b_0 + model->b_6*h + model->b_7*h*h) * exp(-model->b_8 * pow(h, model->b_9));
double psi2 = model->b_1 * exp(-1.0/(model->b_2*pow(h, model->b_3))) * exp(-model->b_4/(h*model->b_5));
return psi1 + psi2;
}
double dXidChi(const SafierWindModel* const model, double h)
{
double dXidChi1 = (model->a_1 + model->a_2*model->a_3*pow(h, model->a_3 - 1.0) - model->a_4 - model->a_1*model->a_4*h - model->a_2*model->a_4*pow(h, model->a_3))
*exp(-model->a_4*h);
double dXidChi2 = (model->a_5 * model->a_6 * pow(h, model->a_6-1.0) -4*model->a_5*model->a_7*model->a_8*pow(h,model->a_6)*pow(h, model->a_8 -1.0) )
* exp(-4*model->a_7*pow(h, model->a_8));
return dXidChi1 + dXidChi2;
}
double eta(const SafierWindModel* const model, double chi, double h0)
{
double const h = fabs(chi) - h0;
double const xi = ::xi(model, h);
double const psi = ::psi(model, h);
double const dxi = dXidChi(model, h);
return model->b_0 * (1. - h0*model->dxi0) / (xi*psi*(xi-chi*dxi));
}
}
SafierWind::SafierWind(
char const model,
double const mOut,
double const mStar,
double const h0,
double const rMin,
double const rMax,
IDiskHumpCPtr hump)
: model_{ getModel(model) }
, rho0_{ rho0(model_, mOut, mStar, h0, rMax / rMin) }
, h0_{ h0 }
, hump_{ std::move(hump) }
{
DATA_ASSERT(
std::string("BCDIEFG").find(model) != std::string::npos,
"Safier Wind model must be B, C, D, I, E, F, or G");
DATA_ASSERT(mOut > 0., "mOut (the mass outflow rate of the wind) must be positive.");
DATA_ASSERT(mStar > 0., "mStar (the stellar mass) must be positive.");
DATA_ASSERT(h0 > 0., "h0 (density of the sphere envelope) must be positive.");
DATA_ASSERT(rMin > 0., "rMin (inner radius of the wind formation region) must be positive.");
DATA_ASSERT(rMax > 0., "rMax (outer radius of the wind formation region) must be positive.");
DATA_ASSERT(rMax > rMin, "rMax (outer radius) must be greater than rMin (inner radius of the wind formation region).");
}
double SafierWind::density(Vector3d const& position) const
{
double r = sqrt(position.x()*position.x() + position.y()*position.y());
double chi = position.z()/r;
if (chi < h0_ || rho0_ == 0.0)
{
return 0.0;
}
double const rho = rho0_ * std::pow(r, -1.5) * eta(model_, chi, h0_);
if (hump_)
{
return hump_->hump(rho, position);
}
return rho;
}
<commit_msg>Fix Safier wind to be applied not only to the top half but also to the bottom half of the disc<commit_after>#include "SafierWind.hpp"
#include "DebugUtils.hpp"
#include "IDiskHump.hpp"
#include <cmath>
#include <string>
struct SafierWindModel
{
double dxi0;
double a_1, a_2, a_3, a_4, a_5, a_6, a_7, a_8;
double b_0, b_1, b_2, b_3, b_4, b_5, b_6, b_7, b_8, b_9;
};
namespace
{
constexpr SafierWindModel modelB{1.73,
-0.30, 0.54, 1.14, 0.26, 1.76, 0.92, 0.09, 0.27,
0.035, 7.7, 1.01, 0.31, 1.1, 0.40, -0.10, 0.0, 1.25, 0.60};
constexpr SafierWindModel modelC{1.73,
0.21, 0.30, 1.23, 0.21, 1.27, 0.92, 0.04, 0.28,
0.035, 12.16, 0.65, 0.33, 1.0, 0.40, 0.50, 0.0, 1.25, 0.60};
constexpr SafierWindModel modelD {1.73,
0.49, 0.17, 1.27, 0.11, 0.89, 0.97, 0.02, 0.31,
0.035, 20.08, 0.42, 0.34, 1.0, 0.40, 0.90, 0.0, 1.00, 0.60};
constexpr SafierWindModel modelI{1.73,
0.18, 0.14, 1.86, 0.26, 1.30, 0.92, 0.02, 0.24,
0.035, 33.52, 0.55, 0.26, 2.5, 0.50, 1.00, 0.0, 0.75, 1.00};
constexpr SafierWindModel modelE{3.73,
-0.51, 0.62, 1.02, 0.03, 2.46, 0.91, 0.01, 0.32,
0.01, 6.95, 0.53, 0.30, 1.0, 0.40, 0.90, 0.0, 1.00, 0.60};
constexpr SafierWindModel modelF{3.73,
-0.22, 0.50, 0.98, 0.09, 2.78, 0.92, 0.01, 0.27,
0.01, 11.62, 0.67, 0.20, 1.8, 0.40, 1.00, 0.0, 0.85, 0.55};
constexpr SafierWindModel modelG {3.73,
0.07, 0.05, 0.42, 0.05, 2.95, 0.94, 0.008, 0.26,
0.01, 18.70, 0.78, 0.14, 3.3, 0.55, 1.00, 0.0, 0.30, 1.10};
SafierWindModel const* getModel(char const key)
{
if (key == 'B')
{
return &modelB;
} else if (key == 'C') {
return &modelC;
} else if (key == 'D') {
return &modelD;
} else if (key == 'I') {
return &modelI;
} else if (key == 'E') {
return &modelE;
} else if (key == 'F') {
return &modelF;
} else if (key == 'G') {
return &modelG;
}
return nullptr;
}
double rho0(const SafierWindModel* const model, double mOut, double mStar, double h0, double rRatio)
{
return 1.064e-15 * (mOut/1e-7) * std::pow(mStar/0.5, -0.5) / std::log(rRatio) /
model->b_0/(1.0-h0*model->dxi0);
}
double xi(const SafierWindModel* const model, double h)
{
double xi1 = (1+model->a_1*h + model->a_2*pow(h, model->a_3)) * exp(-model->a_4*h);
double xi2 = model->a_5 * pow(h, model->a_6) * exp(-4*model->a_7*pow(h, model->a_8));
return xi1 + xi2;
}
double psi(const SafierWindModel* const model, double h)
{
double psi1 = (model->b_0 + model->b_6*h + model->b_7*h*h) * exp(-model->b_8 * pow(h, model->b_9));
double psi2 = model->b_1 * exp(-1.0/(model->b_2*pow(h, model->b_3))) * exp(-model->b_4/(h*model->b_5));
return psi1 + psi2;
}
double dXidChi(const SafierWindModel* const model, double h)
{
double dXidChi1 = (model->a_1 + model->a_2*model->a_3*pow(h, model->a_3 - 1.0) - model->a_4 - model->a_1*model->a_4*h - model->a_2*model->a_4*pow(h, model->a_3))
*exp(-model->a_4*h);
double dXidChi2 = (model->a_5 * model->a_6 * pow(h, model->a_6-1.0) -4*model->a_5*model->a_7*model->a_8*pow(h,model->a_6)*pow(h, model->a_8 -1.0) )
* exp(-4*model->a_7*pow(h, model->a_8));
return dXidChi1 + dXidChi2;
}
double eta(const SafierWindModel* const model, double chi, double h0)
{
double const h = fabs(chi) - h0;
double const xi = ::xi(model, h);
double const psi = ::psi(model, h);
double const dxi = dXidChi(model, h);
return model->b_0 * (1. - h0*model->dxi0) / (xi*psi*(xi-chi*dxi));
}
}
SafierWind::SafierWind(
char const model,
double const mOut,
double const mStar,
double const h0,
double const rMin,
double const rMax,
IDiskHumpCPtr hump)
: model_{ getModel(model) }
, rho0_{ rho0(model_, mOut, mStar, h0, rMax / rMin) }
, h0_{ h0 }
, hump_{ std::move(hump) }
{
DATA_ASSERT(
std::string("BCDIEFG").find(model) != std::string::npos,
"Safier Wind model must be B, C, D, I, E, F, or G");
DATA_ASSERT(mOut > 0., "mOut (the mass outflow rate of the wind) must be positive.");
DATA_ASSERT(mStar > 0., "mStar (the stellar mass) must be positive.");
DATA_ASSERT(h0 > 0., "h0 (density of the sphere envelope) must be positive.");
DATA_ASSERT(rMin > 0., "rMin (inner radius of the wind formation region) must be positive.");
DATA_ASSERT(rMax > 0., "rMax (outer radius of the wind formation region) must be positive.");
DATA_ASSERT(rMax > rMin, "rMax (outer radius) must be greater than rMin (inner radius of the wind formation region).");
}
double SafierWind::density(Vector3d const& position) const
{
double const r = std::sqrt(position.x()*position.x() + position.y()*position.y());
double const chi = std::abs(position.z()/r);
if (chi < h0_ || rho0_ == 0.0)
{
return 0.0;
}
double const rho = rho0_ * std::pow(r, -1.5) * eta(model_, chi, h0_);
if (hump_)
{
return hump_->hump(rho, position);
}
return rho;
}
<|endoftext|> |
<commit_before>//===-- ABI.cpp -------------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/ABI.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Value.h"
#include "lldb/Core/ValueObjectConstResult.h"
#include "lldb/Expression/ExpressionVariable.h"
#include "lldb/Symbol/CompilerType.h"
#include "lldb/Symbol/TypeSystem.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
using namespace lldb;
using namespace lldb_private;
ABISP
ABI::FindPlugin(lldb::ProcessSP process_sp, const ArchSpec &arch) {
ABISP abi_sp;
ABICreateInstance create_callback;
for (uint32_t idx = 0;
(create_callback = PluginManager::GetABICreateCallbackAtIndex(idx)) !=
nullptr;
++idx) {
abi_sp = create_callback(process_sp, arch);
if (abi_sp)
return abi_sp;
}
abi_sp.reset();
return abi_sp;
}
ABI::~ABI() = default;
bool ABI::GetRegisterInfoByName(ConstString name, RegisterInfo &info) {
uint32_t count = 0;
const RegisterInfo *register_info_array = GetRegisterInfoArray(count);
if (register_info_array) {
const char *unique_name_cstr = name.GetCString();
uint32_t i;
for (i = 0; i < count; ++i) {
if (register_info_array[i].name == unique_name_cstr) {
info = register_info_array[i];
return true;
}
}
for (i = 0; i < count; ++i) {
if (register_info_array[i].alt_name == unique_name_cstr) {
info = register_info_array[i];
return true;
}
}
}
return false;
}
bool ABI::GetRegisterInfoByKind(RegisterKind reg_kind, uint32_t reg_num,
RegisterInfo &info) {
if (reg_kind < eRegisterKindEHFrame || reg_kind >= kNumRegisterKinds)
return false;
uint32_t count = 0;
const RegisterInfo *register_info_array = GetRegisterInfoArray(count);
if (register_info_array) {
for (uint32_t i = 0; i < count; ++i) {
if (register_info_array[i].kinds[reg_kind] == reg_num) {
info = register_info_array[i];
return true;
}
}
}
return false;
}
ValueObjectSP ABI::GetReturnValueObject(Thread &thread, CompilerType &ast_type,
bool persistent) const {
if (!ast_type.IsValid())
return ValueObjectSP();
ValueObjectSP return_valobj_sp;
return_valobj_sp = GetReturnValueObjectImpl(thread, ast_type);
if (!return_valobj_sp)
return return_valobj_sp;
// Now turn this into a persistent variable.
// FIXME: This code is duplicated from Target::EvaluateExpression, and it is
// used in similar form in a couple
// of other places. Figure out the correct Create function to do all this
// work.
if (persistent) {
Target &target = *thread.CalculateTarget();
PersistentExpressionState *persistent_expression_state =
target.GetPersistentExpressionStateForLanguage(
ast_type.GetMinimumLanguage());
if (!persistent_expression_state)
return ValueObjectSP();
auto prefix = persistent_expression_state->GetPersistentVariablePrefix();
ConstString persistent_variable_name =
persistent_expression_state->GetNextPersistentVariableName(target,
prefix);
lldb::ValueObjectSP const_valobj_sp;
// Check in case our value is already a constant value
if (return_valobj_sp->GetIsConstant()) {
const_valobj_sp = return_valobj_sp;
const_valobj_sp->SetName(persistent_variable_name);
} else
const_valobj_sp =
return_valobj_sp->CreateConstantValue(persistent_variable_name);
lldb::ValueObjectSP live_valobj_sp = return_valobj_sp;
return_valobj_sp = const_valobj_sp;
ExpressionVariableSP clang_expr_variable_sp(
persistent_expression_state->CreatePersistentVariable(
return_valobj_sp));
assert(clang_expr_variable_sp);
// Set flags and live data as appropriate
const Value &result_value = live_valobj_sp->GetValue();
switch (result_value.GetValueType()) {
case Value::eValueTypeHostAddress:
case Value::eValueTypeFileAddress:
// we don't do anything with these for now
break;
case Value::eValueTypeScalar:
case Value::eValueTypeVector:
clang_expr_variable_sp->m_flags |=
ExpressionVariable::EVIsFreezeDried;
clang_expr_variable_sp->m_flags |=
ExpressionVariable::EVIsLLDBAllocated;
clang_expr_variable_sp->m_flags |=
ExpressionVariable::EVNeedsAllocation;
break;
case Value::eValueTypeLoadAddress:
clang_expr_variable_sp->m_live_sp = live_valobj_sp;
clang_expr_variable_sp->m_flags |=
ExpressionVariable::EVIsProgramReference;
break;
}
return_valobj_sp = clang_expr_variable_sp->GetValueObject();
}
return return_valobj_sp;
}
ValueObjectSP ABI::GetReturnValueObject(Thread &thread, llvm::Type &ast_type,
bool persistent) const {
ValueObjectSP return_valobj_sp;
return_valobj_sp = GetReturnValueObjectImpl(thread, ast_type);
return return_valobj_sp;
}
// specialized to work with llvm IR types
//
// for now we will specify a default implementation so that we don't need to
// modify other ABIs
lldb::ValueObjectSP ABI::GetReturnValueObjectImpl(Thread &thread,
llvm::Type &ir_type) const {
ValueObjectSP return_valobj_sp;
/* this is a dummy and will only be called if an ABI does not override this */
return return_valobj_sp;
}
bool ABI::PrepareTrivialCall(Thread &thread, lldb::addr_t sp,
lldb::addr_t functionAddress,
lldb::addr_t returnAddress, llvm::Type &returntype,
llvm::ArrayRef<ABI::CallArgument> args) const {
// dummy prepare trivial call
llvm_unreachable("Should never get here!");
}
bool ABI::GetFallbackRegisterLocation(
const RegisterInfo *reg_info,
UnwindPlan::Row::RegisterLocation &unwind_regloc) {
// Did the UnwindPlan fail to give us the caller's stack pointer? The stack
// pointer is defined to be the same as THIS frame's CFA, so return the CFA
// value as the caller's stack pointer. This is true on x86-32/x86-64 at
// least.
if (reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_SP) {
unwind_regloc.SetIsCFAPlusOffset(0);
return true;
}
// If a volatile register is being requested, we don't want to forward the
// next frame's register contents up the stack -- the register is not
// retrievable at this frame.
if (RegisterIsVolatile(reg_info)) {
unwind_regloc.SetUndefined();
return true;
}
return false;
}
<commit_msg>[Target][NFCI] Rename variable<commit_after>//===-- ABI.cpp -------------------------------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Target/ABI.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Value.h"
#include "lldb/Core/ValueObjectConstResult.h"
#include "lldb/Expression/ExpressionVariable.h"
#include "lldb/Symbol/CompilerType.h"
#include "lldb/Symbol/TypeSystem.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
using namespace lldb;
using namespace lldb_private;
ABISP
ABI::FindPlugin(lldb::ProcessSP process_sp, const ArchSpec &arch) {
ABISP abi_sp;
ABICreateInstance create_callback;
for (uint32_t idx = 0;
(create_callback = PluginManager::GetABICreateCallbackAtIndex(idx)) !=
nullptr;
++idx) {
abi_sp = create_callback(process_sp, arch);
if (abi_sp)
return abi_sp;
}
abi_sp.reset();
return abi_sp;
}
ABI::~ABI() = default;
bool ABI::GetRegisterInfoByName(ConstString name, RegisterInfo &info) {
uint32_t count = 0;
const RegisterInfo *register_info_array = GetRegisterInfoArray(count);
if (register_info_array) {
const char *unique_name_cstr = name.GetCString();
uint32_t i;
for (i = 0; i < count; ++i) {
if (register_info_array[i].name == unique_name_cstr) {
info = register_info_array[i];
return true;
}
}
for (i = 0; i < count; ++i) {
if (register_info_array[i].alt_name == unique_name_cstr) {
info = register_info_array[i];
return true;
}
}
}
return false;
}
bool ABI::GetRegisterInfoByKind(RegisterKind reg_kind, uint32_t reg_num,
RegisterInfo &info) {
if (reg_kind < eRegisterKindEHFrame || reg_kind >= kNumRegisterKinds)
return false;
uint32_t count = 0;
const RegisterInfo *register_info_array = GetRegisterInfoArray(count);
if (register_info_array) {
for (uint32_t i = 0; i < count; ++i) {
if (register_info_array[i].kinds[reg_kind] == reg_num) {
info = register_info_array[i];
return true;
}
}
}
return false;
}
ValueObjectSP ABI::GetReturnValueObject(Thread &thread, CompilerType &ast_type,
bool persistent) const {
if (!ast_type.IsValid())
return ValueObjectSP();
ValueObjectSP return_valobj_sp;
return_valobj_sp = GetReturnValueObjectImpl(thread, ast_type);
if (!return_valobj_sp)
return return_valobj_sp;
// Now turn this into a persistent variable.
// FIXME: This code is duplicated from Target::EvaluateExpression, and it is
// used in similar form in a couple
// of other places. Figure out the correct Create function to do all this
// work.
if (persistent) {
Target &target = *thread.CalculateTarget();
PersistentExpressionState *persistent_expression_state =
target.GetPersistentExpressionStateForLanguage(
ast_type.GetMinimumLanguage());
if (!persistent_expression_state)
return ValueObjectSP();
auto prefix = persistent_expression_state->GetPersistentVariablePrefix();
ConstString persistent_variable_name =
persistent_expression_state->GetNextPersistentVariableName(target,
prefix);
lldb::ValueObjectSP const_valobj_sp;
// Check in case our value is already a constant value
if (return_valobj_sp->GetIsConstant()) {
const_valobj_sp = return_valobj_sp;
const_valobj_sp->SetName(persistent_variable_name);
} else
const_valobj_sp =
return_valobj_sp->CreateConstantValue(persistent_variable_name);
lldb::ValueObjectSP live_valobj_sp = return_valobj_sp;
return_valobj_sp = const_valobj_sp;
ExpressionVariableSP expr_variable_sp(
persistent_expression_state->CreatePersistentVariable(
return_valobj_sp));
assert(expr_variable_sp);
// Set flags and live data as appropriate
const Value &result_value = live_valobj_sp->GetValue();
switch (result_value.GetValueType()) {
case Value::eValueTypeHostAddress:
case Value::eValueTypeFileAddress:
// we don't do anything with these for now
break;
case Value::eValueTypeScalar:
case Value::eValueTypeVector:
expr_variable_sp->m_flags |=
ExpressionVariable::EVIsFreezeDried;
expr_variable_sp->m_flags |=
ExpressionVariable::EVIsLLDBAllocated;
expr_variable_sp->m_flags |=
ExpressionVariable::EVNeedsAllocation;
break;
case Value::eValueTypeLoadAddress:
expr_variable_sp->m_live_sp = live_valobj_sp;
expr_variable_sp->m_flags |=
ExpressionVariable::EVIsProgramReference;
break;
}
return_valobj_sp = expr_variable_sp->GetValueObject();
}
return return_valobj_sp;
}
ValueObjectSP ABI::GetReturnValueObject(Thread &thread, llvm::Type &ast_type,
bool persistent) const {
ValueObjectSP return_valobj_sp;
return_valobj_sp = GetReturnValueObjectImpl(thread, ast_type);
return return_valobj_sp;
}
// specialized to work with llvm IR types
//
// for now we will specify a default implementation so that we don't need to
// modify other ABIs
lldb::ValueObjectSP ABI::GetReturnValueObjectImpl(Thread &thread,
llvm::Type &ir_type) const {
ValueObjectSP return_valobj_sp;
/* this is a dummy and will only be called if an ABI does not override this */
return return_valobj_sp;
}
bool ABI::PrepareTrivialCall(Thread &thread, lldb::addr_t sp,
lldb::addr_t functionAddress,
lldb::addr_t returnAddress, llvm::Type &returntype,
llvm::ArrayRef<ABI::CallArgument> args) const {
// dummy prepare trivial call
llvm_unreachable("Should never get here!");
}
bool ABI::GetFallbackRegisterLocation(
const RegisterInfo *reg_info,
UnwindPlan::Row::RegisterLocation &unwind_regloc) {
// Did the UnwindPlan fail to give us the caller's stack pointer? The stack
// pointer is defined to be the same as THIS frame's CFA, so return the CFA
// value as the caller's stack pointer. This is true on x86-32/x86-64 at
// least.
if (reg_info->kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_SP) {
unwind_regloc.SetIsCFAPlusOffset(0);
return true;
}
// If a volatile register is being requested, we don't want to forward the
// next frame's register contents up the stack -- the register is not
// retrievable at this frame.
if (RegisterIsVolatile(reg_info)) {
unwind_regloc.SetUndefined();
return true;
}
return false;
}
<|endoftext|> |
<commit_before>#pragma once
#include <Automaton.h>
class Atm_player : public Machine {
public:
enum { IDLE, START, SOUND, QUIET, NEXT, REPEAT, FINISH }; // STATES
enum { EVT_START, EVT_STOP, EVT_TOGGLE, EVT_TIMER, EVT_EOPAT, EVT_REPEAT, ELSE }; // EVENTS
Atm_player( void ) : Machine(){};
Atm_player& begin( int pin = -1 );
Atm_player& trace( Stream& stream );
Atm_player& trigger( int event );
int state( void );
Atm_player& onNote( atm_cb_push_t callback, int idx = 0 );
Atm_player& onNote( Machine& machine, int event = 0 );
Atm_player& onNote( bool status, atm_cb_push_t callback, int idx = 0 );
Atm_player& onNote( bool status, Machine& machine, int event = 0 );
Atm_player& onFinish( atm_cb_push_t callback, int idx = 0 );
Atm_player& onFinish( Machine& machine, int event = 0 );
Atm_player& play( int* pat, int size );
Atm_player& play( int freq, int period, int pause = 0 );
Atm_player& repeat( uint16_t v );
Atm_player& speed( float v );
Atm_player& pitch( float v );
private:
int pin;
int* pattern;
int patternsize;
int step;
uint16_t repeatCount;
float speedFactor, pitchFactor;
int stub[3];
atm_timer_millis timer;
atm_counter counter_repeat;
atm_connector onnote[2], onfinish;
enum { ENT_IDLE, ENT_START, ENT_SOUND, ENT_QUIET, ENT_NEXT, ENT_REPEAT, ENT_FINISH }; // ACTIONS
int event( int id );
void action( int id );
};
/*
Automaton::SMDL::begin - State Machine Definition Language
<?xml version="1.0" encoding="UTF-8"?>
<machines>
<machine name="Atm_player">
<states>
<IDLE index="0" sleep="1" on_enter="ENT_IDLE">
<EVT_START>START</EVT_START>
<EVT_TOGGLE>START</EVT_TOGGLE>
</IDLE>
<START index="1" on_enter="ENT_START">
<ELSE>SOUND</ELSE>
</START>
<SOUND index="2" on_enter="ENT_SOUND">
<EVT_STOP>IDLE</EVT_STOP>
<EVT_TOGGLE>IDLE</EVT_TOGGLE>
<EVT_TIMER>QUIET</EVT_TIMER>
</SOUND>
<QUIET index="3" on_enter="ENT_QUIET">
<EVT_STOP>IDLE</EVT_STOP>
<EVT_TOGGLE>IDLE</EVT_TOGGLE>
<EVT_TIMER>NEXT</EVT_TIMER>
</QUIET>
<NEXT index="4" on_enter="ENT_NEXT">
<EVT_STOP>IDLE</EVT_STOP>
<EVT_TOGGLE>IDLE</EVT_TOGGLE>
<EVT_EOPAT>REPEAT</EVT_EOPAT>
<ELSE>SOUND</ELSE>
</NEXT>
<REPEAT index="5" on_enter="ENT_REPEAT">
<EVT_STOP>IDLE</EVT_STOP>
<EVT_TOGGLE>IDLE</EVT_TOGGLE>
<EVT_REPEAT>FINISH</EVT_REPEAT>
<ELSE>START</ELSE>
</REPEAT>
<FINISH index="6" on_enter="ENT_FINISH">
<EVT_REPEAT>IDLE</EVT_REPEAT>
<ELSE>START</ELSE>
</FINISH>
</states>
<events>
<EVT_START index="0"/>
<EVT_STOP index="1"/>
<EVT_TOGGLE index="2"/>
<EVT_TIMER index="3"/>
<EVT_EOPAT index="4"/>
<EVT_REPEAT index="5"/>
</events>
<connectors>
</connectors>
<methods>
</methods>
</machine>
</machines>
Automaton::SMDL::end
*/
<commit_msg>Changed SDML -> ATML<commit_after>#pragma once
#include <Automaton.h>
class Atm_player : public Machine {
public:
enum { IDLE, START, SOUND, QUIET, NEXT, REPEAT, FINISH }; // STATES
enum { EVT_START, EVT_STOP, EVT_TOGGLE, EVT_TIMER, EVT_EOPAT, EVT_REPEAT, ELSE }; // EVENTS
Atm_player( void ) : Machine(){};
Atm_player& begin( int pin = -1 );
Atm_player& trace( Stream& stream );
Atm_player& trigger( int event );
int state( void );
Atm_player& onNote( atm_cb_push_t callback, int idx = 0 );
Atm_player& onNote( Machine& machine, int event = 0 );
Atm_player& onNote( bool status, atm_cb_push_t callback, int idx = 0 );
Atm_player& onNote( bool status, Machine& machine, int event = 0 );
Atm_player& onFinish( atm_cb_push_t callback, int idx = 0 );
Atm_player& onFinish( Machine& machine, int event = 0 );
Atm_player& play( int* pat, int size );
Atm_player& play( int freq, int period, int pause = 0 );
Atm_player& repeat( uint16_t v );
Atm_player& speed( float v );
Atm_player& pitch( float v );
private:
int pin;
int* pattern;
int patternsize;
int step;
uint16_t repeatCount;
float speedFactor, pitchFactor;
int stub[3];
atm_timer_millis timer;
atm_counter counter_repeat;
atm_connector onnote[2], onfinish;
enum { ENT_IDLE, ENT_START, ENT_SOUND, ENT_QUIET, ENT_NEXT, ENT_REPEAT, ENT_FINISH }; // ACTIONS
int event( int id );
void action( int id );
};
/*
Automaton::ATML::begin - State Machine Definition Language
<?xml version="1.0" encoding="UTF-8"?>
<machines>
<machine name="Atm_player">
<states>
<IDLE index="0" sleep="1" on_enter="ENT_IDLE">
<EVT_START>START</EVT_START>
<EVT_TOGGLE>START</EVT_TOGGLE>
</IDLE>
<START index="1" on_enter="ENT_START">
<ELSE>SOUND</ELSE>
</START>
<SOUND index="2" on_enter="ENT_SOUND">
<EVT_STOP>IDLE</EVT_STOP>
<EVT_TOGGLE>IDLE</EVT_TOGGLE>
<EVT_TIMER>QUIET</EVT_TIMER>
</SOUND>
<QUIET index="3" on_enter="ENT_QUIET">
<EVT_STOP>IDLE</EVT_STOP>
<EVT_TOGGLE>IDLE</EVT_TOGGLE>
<EVT_TIMER>NEXT</EVT_TIMER>
</QUIET>
<NEXT index="4" on_enter="ENT_NEXT">
<EVT_STOP>IDLE</EVT_STOP>
<EVT_TOGGLE>IDLE</EVT_TOGGLE>
<EVT_EOPAT>REPEAT</EVT_EOPAT>
<ELSE>SOUND</ELSE>
</NEXT>
<REPEAT index="5" on_enter="ENT_REPEAT">
<EVT_STOP>IDLE</EVT_STOP>
<EVT_TOGGLE>IDLE</EVT_TOGGLE>
<EVT_REPEAT>FINISH</EVT_REPEAT>
<ELSE>START</ELSE>
</REPEAT>
<FINISH index="6" on_enter="ENT_FINISH">
<EVT_REPEAT>IDLE</EVT_REPEAT>
<ELSE>START</ELSE>
</FINISH>
</states>
<events>
<EVT_START index="0"/>
<EVT_STOP index="1"/>
<EVT_TOGGLE index="2"/>
<EVT_TIMER index="3"/>
<EVT_EOPAT index="4"/>
<EVT_REPEAT index="5"/>
</events>
<connectors>
</connectors>
<methods>
</methods>
</machine>
</machines>
Automaton::ATML::end
*/
<|endoftext|> |
<commit_before>#ifndef BROKER_H_
#define BROKER_H_
#include "dtypes.hpp"
#include "message.hpp"
#include <vector>
#include <deque>
#include <string>
#include <unordered_map>
#include <memory>
#include <iostream>
#include <boost/algorithm/string.hpp>
class MqttSubscriber {
public:
virtual void newMessage(const std::string& topic, const std::vector<ubyte>& payload) = 0;
};
using TopicParts = std::deque<std::string>;
class OldSubscription {
public:
friend class SubscriptionTree;
OldSubscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic,
TopicParts topicParts);
void newMessage(const std::string& topic, const std::vector<ubyte>& payload);
bool isSubscriber(const MqttSubscriber& subscriber) const;
bool isSubscription(const MqttSubscriber& subscriber,
std::vector<std::string> topics) const;
bool isTopic(const std::vector<std::string>& topics) const;
ubyte qos() const { return _qos; }
private:
MqttSubscriber& _subscriber;
std::string _part;
std::string _topic;
ubyte _qos;
};
class SubscriptionTree {
private:
struct Node {
using NodePtr = Node*;
Node(std::string pt, NodePtr pr):part(pt), parent(pr) {}
~Node() { for(auto l: leaves) delete l; }
std::string part;
NodePtr parent;
std::unordered_map<std::string, NodePtr> branches;
std::vector<OldSubscription*> leaves;
};
public:
using NodePtr = Node::NodePtr;
SubscriptionTree();
void addSubscription(OldSubscription* s, const TopicParts& parts);
void removeSubscription(MqttSubscriber& subscriber,
std::unordered_map<std::string, NodePtr>& nodes);
void removeSubscription(MqttSubscriber& subscriber,
std::vector<std::string> topic,
std::unordered_map<std::string, NodePtr>& nodes);
void publish(std::string topic, TopicParts topParts,
const std::vector<ubyte>& payload);
void publish(std::string topic,
TopicParts::const_iterator topPartsBegin,
TopicParts::const_iterator topPartsEnd,
const std::vector<ubyte>& payload,
std::unordered_map<std::string, NodePtr>& nodes);
void publishLeaves(std::string topic, const std::vector<ubyte>& payload,
TopicParts::const_iterator topPartsBegin,
TopicParts::const_iterator topPartsEnd,
std::vector<OldSubscription*> subscriptions);
void publishLeaf(OldSubscription* sub, std::string topic, const std::vector<ubyte>& payload);
void useCache(bool u) { _useCache = u; }
bool _useCache;
std::unordered_map<std::string, std::vector<OldSubscription*>> _cache;
std::unordered_map<std::string, NodePtr> _nodes;
friend class OldMqttBroker;
void addSubscriptionImpl(OldSubscription* s,
TopicParts parts,
NodePtr parent,
std::unordered_map<std::string, NodePtr>& nodes);
NodePtr addOrFindNode(std::string part, NodePtr parent,
std::unordered_map<std::string, NodePtr>& nodes);
void clearCache() { if(_useCache) _cache.clear(); }
void removeNode(NodePtr parent, NodePtr child);
};
class OldMqttBroker {
public:
void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics);
void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics);
void unsubscribe(MqttSubscriber& subscriber);
void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics);
void publish(const std::string& topic, const std::string& payload);
void publish(const std::string& topic, const std::vector<ubyte>& payload);
void useCache(bool u) { _subscriptions.useCache(u); }
private:
SubscriptionTree _subscriptions;
void publish(const std::string& topic,
const TopicParts& topParts,
const std::vector<ubyte>& payload);
};
#include "string_span.h"
template<typename S> class Subscription;
template<typename S>
class MqttBroker {
public:
MqttBroker(bool useCache):
_useCache{useCache}
{
}
void subscribe(S& subscriber, std::vector<std::string> topics) {
std::vector<MqttSubscribe::Topic> newTopics(topics.size());
std::transform(topics.cbegin(), topics.cend(), newTopics.begin(),
[](auto t) { return MqttSubscribe::Topic(t, 0); });
subscribe(subscriber, newTopics);
}
void subscribe(S& subscriber, std::vector<MqttSubscribe::Topic> topics) {
invalidateCache();
for(const auto& topic: topics) {
std::deque<std::string> subParts;
boost::split(subParts, topic.topic, boost::is_any_of("/"));
auto& node = addOrFindNode(_tree, subParts);
node.leaves.emplace_back(Subscription<S>{&subscriber, topic.topic});
}
}
void unsubscribe(const S& subscriber) {
std::vector<std::string> topics{};
unsubscribe(subscriber, topics);
}
void unsubscribe(const S& subscriber, const std::vector<std::string>& topics) {
invalidateCache();
unsubscribeImpl(_tree, subscriber, topics);
}
void publish(const gsl::cstring_span<> topicSpan, const gsl::span<ubyte> bytes) {
const auto topic = gsl::to_string(topicSpan);
if(_useCache && _cache.find(topic) != _cache.end()) {
for(auto subscriber: _cache[topic]) subscriber->newMessage(bytes);
return;
}
std::deque<std::string> pubParts;
boost::split(pubParts, topic, boost::is_any_of("/"));
publishImpl(_tree, pubParts, topic, bytes);
}
private:
struct Node;
using NodePtr = std::shared_ptr<Node>;
struct Node {
std::unordered_map<std::string, NodePtr> children;
std::vector<Subscription<S>> leaves;
};
bool _useCache;
std::unordered_map<std::string, std::vector<S*>> _cache;
Node _tree;
void invalidateCache() {
if(_useCache) _cache.clear();
}
static Node& addOrFindNode(Node& tree, std::deque<std::string>& parts) {
if(parts.size() == 0) return tree;
const auto part = parts[0]; //copying is good here
//create if not already here
if(tree.children.find(part) == tree.children.end()) {
tree.children[part] = std::make_shared<Node>();
}
parts.pop_front();
return addOrFindNode(*tree.children[part], parts);
}
void publishImpl(Node& tree, std::deque<std::string>& pubParts,
const std::string& topic, const gsl::span<ubyte> bytes) {
if(pubParts.size() == 0) return;
const std::string front = pubParts[0];
pubParts.pop_front();
for(const auto& part: std::vector<std::string>{front, "#", "+"}) {
if(tree.children.find(part) != tree.children.end()) {
Node& node = *tree.children[part];
if(pubParts.size() == 0 || part == "#") publishNode(node, topic, bytes);
if(pubParts.size() == 0 && node.children.find("#") != node.children.end()) {
//So that "finance/#" matches "finance"
publishNode(*node.children["#"], topic, bytes);
}
publishImpl(node, pubParts, topic, bytes);
}
}
}
void publishNode(Node& node, const std::string& topic, gsl::span<ubyte> bytes) {
for(auto& subscription: node.leaves) {
subscription.subscriber->newMessage(bytes);
if(_useCache) _cache[topic].emplace_back(subscription.subscriber);
}
}
void unsubscribeImpl(Node& tree, const S& subscriber, const std::vector<std::string>& topics) {
(void)tree; (void)subscriber; (void)topics;
decltype(tree.leaves) leaves;
std::copy_if(tree.leaves.cbegin(), tree.leaves.cend(), std::back_inserter(leaves),
[&subscriber, &topics](auto&& a) {
return !a.isSubscriber(subscriber, topics);
});
std::swap(tree.leaves, leaves);
if(tree.children.size() == 0) return;
for(const auto& item: tree.children) {
unsubscribeImpl(*item.second, subscriber, topics);
}
}
};
template<typename S>
class Subscription {
public:
Subscription(S* subscriber, gsl::cstring_span<> topic) noexcept :
subscriber{subscriber}, topic{gsl::to_string(topic)} {
}
bool isSubscriber(const S& sub, const std::vector<std::string>& topics) const {
const auto isSameTopic = topics.size() == 0 ||
std::find(topics.cbegin(), topics.cend(), topic) != topics.end();
return isSameTopic && subscriber == ⊂
}
S* subscriber;
std::string topic;
};
#endif // BROKER_H_
<commit_msg>not_null<commit_after>#ifndef BROKER_H_
#define BROKER_H_
#include "dtypes.hpp"
#include "message.hpp"
#include <vector>
#include <deque>
#include <string>
#include <unordered_map>
#include <memory>
#include <iostream>
#include <boost/algorithm/string.hpp>
class MqttSubscriber {
public:
virtual void newMessage(const std::string& topic, const std::vector<ubyte>& payload) = 0;
};
using TopicParts = std::deque<std::string>;
class OldSubscription {
public:
friend class SubscriptionTree;
OldSubscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic,
TopicParts topicParts);
void newMessage(const std::string& topic, const std::vector<ubyte>& payload);
bool isSubscriber(const MqttSubscriber& subscriber) const;
bool isSubscription(const MqttSubscriber& subscriber,
std::vector<std::string> topics) const;
bool isTopic(const std::vector<std::string>& topics) const;
ubyte qos() const { return _qos; }
private:
MqttSubscriber& _subscriber;
std::string _part;
std::string _topic;
ubyte _qos;
};
class SubscriptionTree {
private:
struct Node {
using NodePtr = Node*;
Node(std::string pt, NodePtr pr):part(pt), parent(pr) {}
~Node() { for(auto l: leaves) delete l; }
std::string part;
NodePtr parent;
std::unordered_map<std::string, NodePtr> branches;
std::vector<OldSubscription*> leaves;
};
public:
using NodePtr = Node::NodePtr;
SubscriptionTree();
void addSubscription(OldSubscription* s, const TopicParts& parts);
void removeSubscription(MqttSubscriber& subscriber,
std::unordered_map<std::string, NodePtr>& nodes);
void removeSubscription(MqttSubscriber& subscriber,
std::vector<std::string> topic,
std::unordered_map<std::string, NodePtr>& nodes);
void publish(std::string topic, TopicParts topParts,
const std::vector<ubyte>& payload);
void publish(std::string topic,
TopicParts::const_iterator topPartsBegin,
TopicParts::const_iterator topPartsEnd,
const std::vector<ubyte>& payload,
std::unordered_map<std::string, NodePtr>& nodes);
void publishLeaves(std::string topic, const std::vector<ubyte>& payload,
TopicParts::const_iterator topPartsBegin,
TopicParts::const_iterator topPartsEnd,
std::vector<OldSubscription*> subscriptions);
void publishLeaf(OldSubscription* sub, std::string topic, const std::vector<ubyte>& payload);
void useCache(bool u) { _useCache = u; }
bool _useCache;
std::unordered_map<std::string, std::vector<OldSubscription*>> _cache;
std::unordered_map<std::string, NodePtr> _nodes;
friend class OldMqttBroker;
void addSubscriptionImpl(OldSubscription* s,
TopicParts parts,
NodePtr parent,
std::unordered_map<std::string, NodePtr>& nodes);
NodePtr addOrFindNode(std::string part, NodePtr parent,
std::unordered_map<std::string, NodePtr>& nodes);
void clearCache() { if(_useCache) _cache.clear(); }
void removeNode(NodePtr parent, NodePtr child);
};
class OldMqttBroker {
public:
void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics);
void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics);
void unsubscribe(MqttSubscriber& subscriber);
void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics);
void publish(const std::string& topic, const std::string& payload);
void publish(const std::string& topic, const std::vector<ubyte>& payload);
void useCache(bool u) { _subscriptions.useCache(u); }
private:
SubscriptionTree _subscriptions;
void publish(const std::string& topic,
const TopicParts& topParts,
const std::vector<ubyte>& payload);
};
#include "gsl.h"
template<typename S> class Subscription;
template<typename S>
class MqttBroker {
public:
MqttBroker(bool useCache):
_useCache{useCache}
{
}
void subscribe(S& subscriber, std::vector<std::string> topics) {
std::vector<MqttSubscribe::Topic> newTopics(topics.size());
std::transform(topics.cbegin(), topics.cend(), newTopics.begin(),
[](auto t) { return MqttSubscribe::Topic(t, 0); });
subscribe(subscriber, newTopics);
}
void subscribe(S& subscriber, std::vector<MqttSubscribe::Topic> topics) {
invalidateCache();
for(const auto& topic: topics) {
std::deque<std::string> subParts;
boost::split(subParts, topic.topic, boost::is_any_of("/"));
auto& node = addOrFindNode(_tree, subParts);
node.leaves.emplace_back(Subscription<S>{&subscriber, topic.topic});
}
}
void unsubscribe(const S& subscriber) {
std::vector<std::string> topics{};
unsubscribe(subscriber, topics);
}
void unsubscribe(const S& subscriber, const std::vector<std::string>& topics) {
invalidateCache();
unsubscribeImpl(_tree, subscriber, topics);
}
void publish(const gsl::cstring_span<> topicSpan, const gsl::span<ubyte> bytes) {
const auto topic = gsl::to_string(topicSpan);
if(_useCache && _cache.find(topic) != _cache.end()) {
for(auto subscriber: _cache[topic]) subscriber->newMessage(bytes);
return;
}
std::deque<std::string> pubParts;
boost::split(pubParts, topic, boost::is_any_of("/"));
publishImpl(_tree, pubParts, topic, bytes);
}
private:
struct Node;
using NodePtr = std::shared_ptr<Node>;
struct Node {
std::unordered_map<std::string, NodePtr> children;
std::vector<Subscription<S>> leaves;
};
bool _useCache;
std::unordered_map<std::string, std::vector<S*>> _cache;
Node _tree;
void invalidateCache() {
if(_useCache) _cache.clear();
}
static Node& addOrFindNode(Node& tree, std::deque<std::string>& parts) {
if(parts.size() == 0) return tree;
const auto part = parts[0]; //copying is good here
//create if not already here
if(tree.children.find(part) == tree.children.end()) {
tree.children[part] = std::make_shared<Node>();
}
parts.pop_front();
return addOrFindNode(*tree.children[part], parts);
}
void publishImpl(Node& tree, std::deque<std::string>& pubParts,
const std::string& topic, const gsl::span<ubyte> bytes) {
if(pubParts.size() == 0) return;
const std::string front = pubParts[0];
pubParts.pop_front();
for(const auto& part: std::vector<std::string>{front, "#", "+"}) {
if(tree.children.find(part) != tree.children.end()) {
Node& node = *tree.children[part];
if(pubParts.size() == 0 || part == "#") publishNode(node, topic, bytes);
if(pubParts.size() == 0 && node.children.find("#") != node.children.end()) {
//So that "finance/#" matches "finance"
publishNode(*node.children["#"], topic, bytes);
}
publishImpl(node, pubParts, topic, bytes);
}
}
}
void publishNode(Node& node, const std::string& topic, gsl::span<ubyte> bytes) {
for(auto& subscription: node.leaves) {
subscription.subscriber->newMessage(bytes);
if(_useCache) _cache[topic].emplace_back(subscription.subscriber);
}
}
void unsubscribeImpl(Node& tree, const S& subscriber, const std::vector<std::string>& topics) {
(void)tree; (void)subscriber; (void)topics;
decltype(tree.leaves) leaves;
std::copy_if(tree.leaves.cbegin(), tree.leaves.cend(), std::back_inserter(leaves),
[&subscriber, &topics](auto&& a) {
return !a.isSubscriber(subscriber, topics);
});
std::swap(tree.leaves, leaves);
if(tree.children.size() == 0) return;
for(const auto& item: tree.children) {
unsubscribeImpl(*item.second, subscriber, topics);
}
}
};
template<typename S>
class Subscription {
public:
Subscription(gsl::not_null<S*> subscriber, gsl::cstring_span<> topic) noexcept :
subscriber{subscriber}, topic{gsl::to_string(topic)} {
}
bool isSubscriber(const S& sub, const std::vector<std::string>& topics) const {
const auto isSameTopic = topics.size() == 0 ||
std::find(topics.cbegin(), topics.cend(), topic) != topics.end();
return isSameTopic && subscriber == ⊂
}
gsl::not_null<S*> subscriber;
std::string topic;
};
#endif // BROKER_H_
<|endoftext|> |
<commit_before>#include <bitcoin/blockchain/organizer.hpp>
#include <bitcoin/utility/assert.hpp>
namespace libbitcoin {
block_detail::block_detail(const message::block& actual_block)
: block_hash_(hash_block_header(actual_block)),
processed_(false), info_{block_status::orphan, 0}
{
actual_block_ = std::make_shared<message::block>(actual_block);
}
const message::block& block_detail::actual() const
{
return *actual_block_;
}
std::shared_ptr<message::block> block_detail::actual_ptr() const
{
return actual_block_;
}
void block_detail::mark_processed()
{
processed_ = true;
}
bool block_detail::is_processed()
{
return processed_;
}
const hash_digest& block_detail::hash() const
{
return block_hash_;
}
void block_detail::set_info(const block_info& replace_info)
{
info_ = replace_info;
}
const block_info& block_detail::info() const
{
return info_;
}
void block_detail::set_errc(const std::error_code& ec)
{
ec_ = ec;
}
const std::error_code& block_detail::errc() const
{
return ec_;
}
orphans_pool::orphans_pool(size_t pool_size)
: pool_(pool_size)
{
}
void orphans_pool::add(block_detail_ptr incoming_block)
{
// No duplicates
for (block_detail_ptr current_block: pool_)
if (current_block->actual() == incoming_block->actual())
return;
pool_.push_back(incoming_block);
}
block_detail_list orphans_pool::trace(block_detail_ptr end_block)
{
block_detail_list traced_chain;
traced_chain.push_back(end_block);
while (true)
{
resume_loop:
const hash_digest& previous_hash =
traced_chain.back()->actual().previous_block_hash;
for (const block_detail_ptr current_block: pool_)
if (current_block->hash() == previous_hash)
{
traced_chain.push_back(current_block);
goto resume_loop;
}
break;
}
BITCOIN_ASSERT(traced_chain.size() > 0);
std::reverse(traced_chain.begin(), traced_chain.end());
return traced_chain;
}
block_detail_list orphans_pool::unprocessed()
{
block_detail_list unprocessed_blocks;
for (const block_detail_ptr current_block: pool_)
{
if (!current_block->is_processed())
unprocessed_blocks.push_back(current_block);
}
// Earlier blocks come into pool first. Lets match that
// Helps avoid fragmentation, but isn't neccessary
std::reverse(unprocessed_blocks.begin(), unprocessed_blocks.end());
return unprocessed_blocks;
}
void orphans_pool::remove(block_detail_ptr remove_block)
{
auto it = std::find(pool_.begin(), pool_.end(), remove_block);
BITCOIN_ASSERT(it != pool_.end());
pool_.erase(it);
}
organizer::organizer(orphans_pool_ptr orphans, chain_keeper_ptr chain)
: orphans_(orphans), chain_(chain)
{
}
void organizer::start()
{
// Load unprocessed blocks
process_queue_ = orphans_->unprocessed();
// As we loop, we pop blocks off and process them
while (!process_queue_.empty())
{
block_detail_ptr process_block = process_queue_.back();
process_queue_.pop_back();
// process() can remove blocks from the queue too
chain_->start();
process(process_block);
// May have already been stopped by replace_chain
chain_->stop();
}
}
void organizer::process(block_detail_ptr process_block)
{
// Trace the chain in the orphan pool
block_detail_list orphan_chain = orphans_->trace(process_block);
int fork_index =
chain_->find_index(orphan_chain[0]->actual().previous_block_hash);
if (fork_index != -1)
// replace_chain will call chain_->stop()
replace_chain(fork_index, orphan_chain);
// Don't mark all orphan_chain as processed here because there might be
// a winning fork from an earlier block
}
void organizer::replace_chain(int fork_index,
block_detail_list& orphan_chain)
{
big_number orphan_work = 0;
// Starting from beginning of the chain, validate blocks
for (int orphan_index = 0; orphan_index < orphan_chain.size();
++orphan_index)
{
std::error_code invalid_reason =
verify(fork_index, orphan_chain, orphan_index);
// Invalid block found
if (invalid_reason)
{
clip_orphans(orphan_chain, orphan_index, invalid_reason);
// Stop summing work once we discover an invalid block
break;
}
const message::block& orphan_block =
orphan_chain[orphan_index]->actual();
orphan_work += block_work(orphan_block.bits);
}
// All remaining blocks in orphan_chain should all be valid now
// Compare the difficulty of the 2 forks (original and orphan)
big_number main_work = chain_->end_slice_difficulty(fork_index + 1);
if (orphan_work <= main_work)
return;
// Replace! Switch!
block_detail_list replaced_slice = chain_->end_slice(fork_index + 1);
// We add the arriving blocks first to the main chain because if
// we add the blocks being replaced back to the pool first then
// the we can push the arrival blocks off the bottom of the
// circular buffer.
// Then when we try to remove the block from the orphans pool,
// if will fail to find it. I would rather not add an exception
// there so that problems will show earlier.
// All arrival_blocks should be blocks from the pool.
int arrival_index = fork_index;
for (block_detail_ptr arrival_block: orphan_chain)
{
orphans_->remove(arrival_block);
++arrival_index;
arrival_block->set_info({block_status::confirmed, arrival_index});
chain_->add(arrival_block);
}
// Now add the old blocks back to the pool
for (block_detail_ptr replaced_block: replaced_slice)
{
replaced_block->mark_processed();
replaced_block->set_info({block_status::orphan, 0});
orphans_->add(replaced_block);
}
chain_->stop();
notify_reorganize(fork_index, orphan_chain, replaced_slice);
}
void lazy_remove(block_detail_list& process_queue,
block_detail_ptr remove_block)
{
auto it = std::find(process_queue.begin(), process_queue.end(),
remove_block);
if (it != process_queue.end())
process_queue.erase(it);
}
void organizer::clip_orphans(block_detail_list& orphan_chain,
int orphan_index, const std::error_code& invalid_reason)
{
auto orphan_start = orphan_chain.begin() + orphan_index;
// Remove from orphans pool
for (auto it = orphan_start; it != orphan_chain.end(); ++it)
{
if (it == orphan_start)
(*it)->set_errc(invalid_reason);
else
(*it)->set_errc(error::previous_block_invalid);
(*it)->set_info({block_status::rejected, 0});
orphans_->remove(*it);
// Also erase from process_queue so we avoid trying to re-process
// invalid blocks and remove try to remove non-existant blocks.
lazy_remove(process_queue_, *it);
}
orphan_chain.erase(orphan_start, orphan_chain.end());
}
void organizer::notify_reorganize(
size_t fork_point,
const block_detail_list& orphan_chain,
const block_detail_list& replaced_slice)
{
// Strip out the meta-info, to convert to format which can
// be passed to subscribe handlers
// orphan_chain = arrival blocks
// replaced slice = replaced chain
blockchain::block_list arrival_blocks, replaced_blocks;
for (block_detail_ptr arrival_block: orphan_chain)
arrival_blocks.push_back(arrival_block->actual_ptr());
for (block_detail_ptr replaced_block: replaced_slice)
replaced_blocks.push_back(replaced_block->actual_ptr());
reorganize_occured(fork_point, arrival_blocks, replaced_blocks);
}
} // namespace libbitcoin
<commit_msg>BUGFIX: mark as processed blocks removed from queue.<commit_after>#include <bitcoin/blockchain/organizer.hpp>
#include <bitcoin/utility/assert.hpp>
namespace libbitcoin {
block_detail::block_detail(const message::block& actual_block)
: block_hash_(hash_block_header(actual_block)),
processed_(false), info_{block_status::orphan, 0}
{
actual_block_ = std::make_shared<message::block>(actual_block);
}
const message::block& block_detail::actual() const
{
return *actual_block_;
}
std::shared_ptr<message::block> block_detail::actual_ptr() const
{
return actual_block_;
}
void block_detail::mark_processed()
{
processed_ = true;
}
bool block_detail::is_processed()
{
return processed_;
}
const hash_digest& block_detail::hash() const
{
return block_hash_;
}
void block_detail::set_info(const block_info& replace_info)
{
info_ = replace_info;
}
const block_info& block_detail::info() const
{
return info_;
}
void block_detail::set_errc(const std::error_code& ec)
{
ec_ = ec;
}
const std::error_code& block_detail::errc() const
{
return ec_;
}
orphans_pool::orphans_pool(size_t pool_size)
: pool_(pool_size)
{
}
void orphans_pool::add(block_detail_ptr incoming_block)
{
// No duplicates
for (block_detail_ptr current_block: pool_)
if (current_block->actual() == incoming_block->actual())
return;
pool_.push_back(incoming_block);
}
block_detail_list orphans_pool::trace(block_detail_ptr end_block)
{
block_detail_list traced_chain;
traced_chain.push_back(end_block);
while (true)
{
resume_loop:
const hash_digest& previous_hash =
traced_chain.back()->actual().previous_block_hash;
for (const block_detail_ptr current_block: pool_)
if (current_block->hash() == previous_hash)
{
traced_chain.push_back(current_block);
goto resume_loop;
}
break;
}
BITCOIN_ASSERT(traced_chain.size() > 0);
std::reverse(traced_chain.begin(), traced_chain.end());
return traced_chain;
}
block_detail_list orphans_pool::unprocessed()
{
block_detail_list unprocessed_blocks;
for (const block_detail_ptr current_block: pool_)
{
if (!current_block->is_processed())
unprocessed_blocks.push_back(current_block);
}
// Earlier blocks come into pool first. Lets match that
// Helps avoid fragmentation, but isn't neccessary
std::reverse(unprocessed_blocks.begin(), unprocessed_blocks.end());
return unprocessed_blocks;
}
void orphans_pool::remove(block_detail_ptr remove_block)
{
auto it = std::find(pool_.begin(), pool_.end(), remove_block);
BITCOIN_ASSERT(it != pool_.end());
pool_.erase(it);
}
organizer::organizer(orphans_pool_ptr orphans, chain_keeper_ptr chain)
: orphans_(orphans), chain_(chain)
{
}
void organizer::start()
{
// Load unprocessed blocks
process_queue_ = orphans_->unprocessed();
// As we loop, we pop blocks off and process them
while (!process_queue_.empty())
{
block_detail_ptr process_block = process_queue_.back();
process_queue_.pop_back();
// process() can remove blocks from the queue too
chain_->start();
process(process_block);
// May have already been stopped by replace_chain
chain_->stop();
}
}
void organizer::process(block_detail_ptr process_block)
{
// Trace the chain in the orphan pool
block_detail_list orphan_chain = orphans_->trace(process_block);
int fork_index =
chain_->find_index(orphan_chain[0]->actual().previous_block_hash);
if (fork_index != -1)
// replace_chain will call chain_->stop()
replace_chain(fork_index, orphan_chain);
// Don't mark all orphan_chain as processed here because there might be
// a winning fork from an earlier block
process_block->mark_processed();
}
void organizer::replace_chain(int fork_index,
block_detail_list& orphan_chain)
{
big_number orphan_work = 0;
// Starting from beginning of the chain, validate blocks
for (int orphan_index = 0; orphan_index < orphan_chain.size();
++orphan_index)
{
std::error_code invalid_reason =
verify(fork_index, orphan_chain, orphan_index);
// Invalid block found
if (invalid_reason)
{
clip_orphans(orphan_chain, orphan_index, invalid_reason);
// Stop summing work once we discover an invalid block
break;
}
const message::block& orphan_block =
orphan_chain[orphan_index]->actual();
orphan_work += block_work(orphan_block.bits);
}
// All remaining blocks in orphan_chain should all be valid now
// Compare the difficulty of the 2 forks (original and orphan)
big_number main_work = chain_->end_slice_difficulty(fork_index + 1);
if (orphan_work <= main_work)
return;
// Replace! Switch!
block_detail_list replaced_slice = chain_->end_slice(fork_index + 1);
// We add the arriving blocks first to the main chain because if
// we add the blocks being replaced back to the pool first then
// the we can push the arrival blocks off the bottom of the
// circular buffer.
// Then when we try to remove the block from the orphans pool,
// if will fail to find it. I would rather not add an exception
// there so that problems will show earlier.
// All arrival_blocks should be blocks from the pool.
int arrival_index = fork_index;
for (block_detail_ptr arrival_block: orphan_chain)
{
orphans_->remove(arrival_block);
++arrival_index;
arrival_block->set_info({block_status::confirmed, arrival_index});
chain_->add(arrival_block);
}
// Now add the old blocks back to the pool
for (block_detail_ptr replaced_block: replaced_slice)
{
replaced_block->mark_processed();
replaced_block->set_info({block_status::orphan, 0});
orphans_->add(replaced_block);
}
chain_->stop();
notify_reorganize(fork_index, orphan_chain, replaced_slice);
}
void lazy_remove(block_detail_list& process_queue,
block_detail_ptr remove_block)
{
auto it = std::find(process_queue.begin(), process_queue.end(),
remove_block);
if (it != process_queue.end())
process_queue.erase(it);
remove_block->mark_processed();
}
void organizer::clip_orphans(block_detail_list& orphan_chain,
int orphan_index, const std::error_code& invalid_reason)
{
auto orphan_start = orphan_chain.begin() + orphan_index;
// Remove from orphans pool
for (auto it = orphan_start; it != orphan_chain.end(); ++it)
{
if (it == orphan_start)
(*it)->set_errc(invalid_reason);
else
(*it)->set_errc(error::previous_block_invalid);
(*it)->set_info({block_status::rejected, 0});
orphans_->remove(*it);
// Also erase from process_queue so we avoid trying to re-process
// invalid blocks and remove try to remove non-existant blocks.
lazy_remove(process_queue_, *it);
}
orphan_chain.erase(orphan_start, orphan_chain.end());
}
void organizer::notify_reorganize(
size_t fork_point,
const block_detail_list& orphan_chain,
const block_detail_list& replaced_slice)
{
// Strip out the meta-info, to convert to format which can
// be passed to subscribe handlers
// orphan_chain = arrival blocks
// replaced slice = replaced chain
blockchain::block_list arrival_blocks, replaced_blocks;
for (block_detail_ptr arrival_block: orphan_chain)
arrival_blocks.push_back(arrival_block->actual_ptr());
for (block_detail_ptr replaced_block: replaced_slice)
replaced_blocks.push_back(replaced_block->actual_ptr());
reorganize_occured(fork_point, arrival_blocks, replaced_blocks);
}
} // namespace libbitcoin
<|endoftext|> |
<commit_before>#include "rosenbrock.h"
#include <qmath.h>
namespace
{
Rosenbrock instance;
}
RpnOperand Rosenbrock::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments)
{
m_calculator = calculator;
m_functionName = actualArguments[0].value.value<QString>();
m_sourcePoint = actualArguments[1].value.value<QList<Number> >();
if (m_calculator->functionArguments(m_functionName).size() != m_sourcePoint.size()) {
THROW(EWrongParametersCount(QObject::tr("Source point"), m_calculator->functionArguments(m_functionName).size()));
}
m_stopValue = actualArguments[2].value.value<Number>();
m_accelerationStep = actualArguments[3].value.value<Number>();
m_decreaseStep = actualArguments[4].value.value<Number>();
m_steps = actualArguments[5].value.value<QList<Number> >();
if (m_calculator->functionArguments(m_functionName).size() != m_steps.size()) {
THROW(EWrongParametersCount(QObject::tr("Coordinate steps"), m_calculator->functionArguments(m_functionName).size()));
}
m_wrongStepsNumber = actualArguments[6].value.value<Number>();
// Set start directions
for (int i = 0; i < m_sourcePoint.size(); i++) {
m_directions << QList<Number>();
for (int k = 0; k < m_sourcePoint.size(); k++) {
if (k == i) {
m_directions[i] << 1;
}
else {
m_directions[i] << 0;
}
}
}
RpnOperand result;
result.type = RpnOperandVector;
result.value = QVariant::fromValue(findMinimum());
return result;
}
QList<RpnArgument> Rosenbrock::requiredArguments()
{
QList<RpnArgument> arguments;
arguments
// NOTE: QVariant() shows that number of arguments is not fixed, maybe there is other way
<< RpnArgument(RpnOperandFunctionName, QString(), QVariant())
<< RpnArgument(RpnOperandVector)
<< RpnArgument(RpnOperandNumber)
<< RpnArgument(RpnOperandNumber)
<< RpnArgument(RpnOperandNumber)
<< RpnArgument(RpnOperandVector)
<< RpnArgument(RpnOperandNumber);
return arguments;
}
QList<Number> Rosenbrock::findMinimum()
{
QList<Number> firstCurrentPoint = m_sourcePoint;
QList<Number> sourceSteps = m_steps;
QList<Number> currentPoint = firstCurrentPoint;
forever {
forever {
int failStepsCount = 0;
for (int i = 0; i < currentPoint.size(); i++) {
if (countFunction(increaseDirection(currentPoint, i)) < countFunction(currentPoint)) {
currentPoint = increaseDirection(currentPoint, i);
m_steps[i] = m_steps[i] * m_accelerationStep;
}
else {
m_steps[i] = m_steps[i] * m_decreaseStep;
failStepsCount++;
}
}
if (countFunction(currentPoint) == countFunction(firstCurrentPoint)) {
if (countFunction(currentPoint) < countFunction(m_sourcePoint)) {
// Loop exit condition
break;
}
else if (countFunction(currentPoint) == countFunction(m_sourcePoint)) {
if (failStepsCount <= m_wrongStepsNumber) {
bool isFinish = true;
for (int i = 0; i < m_steps.size(); i++) {
if (qAbs(m_steps[i]) > m_stopValue) {
isFinish = false;
}
}
if (isFinish) {
// Main loop exit condition
return m_sourcePoint;
}
else {
firstCurrentPoint = currentPoint;
continue;
}
}
// Loop exit condition
else {
break;
}
}
}
else {
firstCurrentPoint = currentPoint;
continue;
}
}
Number modulus = modulusList(diffListList(currentPoint, m_sourcePoint));
if (modulus <= m_stopValue) {
// Main loop exit condition
return currentPoint;
}
else {
getNewDirections(getStepLengths(currentPoint, m_sourcePoint));
m_steps = sourceSteps;
m_sourcePoint = currentPoint;
firstCurrentPoint = currentPoint;
}
}
}
void Rosenbrock::getNewDirections(QList<Number> stepSizes)
{
QList<QList<Number> > gramStepOne;
for (int i = 0; i < stepSizes.size(); i++) {
if (stepSizes[i] == 0) {
gramStepOne << m_directions[i];
}
else {
QList<Number> element;
for (int j = i; j < stepSizes.size(); j++) {
if (element != QList<Number>()) {
element = sumListList(element, productListNumber(m_directions[j], stepSizes[j]));
}
else {
element = productListNumber(m_directions[j], stepSizes[j]);
}
}
gramStepOne << element;
}
}
QList<QList<Number> > gramStepTwo;
for (int i = 0; i < stepSizes.size(); i++) {
QList<Number> element;
if (i == 0) {
element = gramStepOne[i];
}
else {
QList<Number> subtractin;
for (int j = 0; j < i; j++) {
subtractin = productListNumber(gramStepTwo[j], productListList(gramStepOne[i], gramStepTwo[j]));
if (j != 0) {
subtractin = sumListList(subtractin, gramStepTwo[j]);
}
}
element = diffListList(gramStepOne[i], subtractin);
}
m_directions[i] = quotientListNumber(element, modulusList(element));
gramStepTwo << m_directions[i];
}
}
QList<Number> Rosenbrock::getStepLengths(QList<Number> currentPoint, QList<Number> previousPoint)
{
QList<QList<Number> > equationCoefficients;
equationCoefficients << diffListList(currentPoint, previousPoint);
foreach (QList<Number> direction, m_directions) {
equationCoefficients << direction;
}
return solveEquationSystem(equationCoefficients);
}
// First list of coefficients is equations results
QList<Number> Rosenbrock::solveEquationSystem(QList<QList<Number> > coefficients)
{
QList<Number> result;
QVector<QVector<Number> > mainMatrix;
for (int i = 1; i < coefficients.size(); i++) {
mainMatrix << QVector<Number>::fromList(coefficients[i]);
}
Number mainDeterminant = countDeterminant(mainMatrix);
for (int i = 1; i < coefficients.size(); i++) {
QVector<QVector<Number> > elementMatrix;
for (int j = 1; j < coefficients.size(); j++) {
if (j == i) {
elementMatrix << QVector<Number>::fromList(coefficients[0]);
}
else {
elementMatrix << QVector<Number>::fromList(coefficients[j]);
}
}
result << countDeterminant(elementMatrix) / mainDeterminant;
}
return result;
}
Number Rosenbrock::countDeterminant(QVector<QVector<Number> > matrix)
{
Number result = 0;
if (matrix.size() == 1) {
result = matrix[0][0];
}
else if (matrix.size() == 2) {
result = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
}
else {
// Go threw first line
for (int i = 0; i < matrix.size(); i++) {
// Initialize minor matrix
QVector<QVector<Number> > minorMatrix;
minorMatrix.resize(matrix.size() - 1);
for (int j = 0; j < minorMatrix.size(); j++) {
minorMatrix[j].resize(matrix.size() - 1);
}
// Fill minor matrix
for (int j = 0; j < matrix.size(); j++) {
int k = 0;
for (int l = 0; l < matrix.size(); l++) {
// Don't conpy the minor column
if (l != i) {
minorMatrix[j - 1][k] = minorMatrix[j][l];
k++;
}
}
}
result +=
qPow(-1, 1 + i + 1) *
minorMatrix[0][i] *
countDeterminant(minorMatrix);
}
}
return result;
}
QList<Number> Rosenbrock::increaseDirection(QList<Number> point, int direction)
{
QList<Number> result = point;
for (int i = 0; i < point.size(); i++) {
result[i] += m_directions[direction][i] * m_steps[direction];
}
return result;
}
QList<Number> Rosenbrock::productListNumber(QList<Number> list, Number number)
{
QList<Number> result;
foreach (Number element, list) {
result << element * number;
}
return result;
}
QList<Number> Rosenbrock::diffListList(QList<Number> source, QList<Number> subtractin)
{
QList<Number> result;
for (int i = 0; i < source.size(); i++) {
result << source[i] - subtractin[i];
}
return result;
}
QList<Number> Rosenbrock::sumListList(QList<Number> source, QList<Number> item)
{
QList<Number> result;
for (int i = 0; i < source.size(); i++) {
result << source[i] + item[i];
}
return result;
}
Number Rosenbrock::productListList(QList<Number> source, QList<Number> item)
{
Number result = 0;
for (int i = 0; i < source.size(); i++) {
result += source[i] * item[i];
}
return result;
}
Number Rosenbrock::modulusList(QList<Number> list)
{
Number result = 0;
foreach (Number element, list) {
result += qPow(element, 2);
}
return qSqrt(result);
}
QList<Number> Rosenbrock::quotientListNumber(QList<Number> source, Number divisor)
{
QList<Number> result;
foreach (Number element, source) {
result << element / divisor;
}
return result;
}
Number Rosenbrock::countFunction(QList<Number> arguments)
{
QList<RpnOperand> functionArguments;
foreach (Number argument, arguments) {
RpnOperand functionArgument(RpnOperandNumber, argument);
functionArguments << functionArgument;
}
RpnOperand result = m_calculator->calculate(m_functionName, functionArguments);
return result.value.value<Number>();
}
<commit_msg>Fix for crash on double using Rosenbrock method<commit_after>#include "rosenbrock.h"
#include <qmath.h>
namespace
{
Rosenbrock instance;
}
RpnOperand Rosenbrock::calculate(FunctionCalculator *calculator, QList<RpnOperand> actualArguments)
{
m_calculator = calculator;
m_functionName = actualArguments[0].value.value<QString>();
m_sourcePoint = actualArguments[1].value.value<QList<Number> >();
if (m_calculator->functionArguments(m_functionName).size() != m_sourcePoint.size()) {
THROW(EWrongParametersCount(QObject::tr("Source point"), m_calculator->functionArguments(m_functionName).size()));
}
m_stopValue = actualArguments[2].value.value<Number>();
m_accelerationStep = actualArguments[3].value.value<Number>();
m_decreaseStep = actualArguments[4].value.value<Number>();
m_steps = actualArguments[5].value.value<QList<Number> >();
if (m_calculator->functionArguments(m_functionName).size() != m_steps.size()) {
THROW(EWrongParametersCount(QObject::tr("Coordinate steps"), m_calculator->functionArguments(m_functionName).size()));
}
m_wrongStepsNumber = actualArguments[6].value.value<Number>();
// Set start directions
m_directions.clear();
for (int i = 0; i < m_sourcePoint.size(); i++) {
m_directions << QList<Number>();
for (int k = 0; k < m_sourcePoint.size(); k++) {
if (k == i) {
m_directions[i] << 1;
}
else {
m_directions[i] << 0;
}
}
}
RpnOperand result;
result.type = RpnOperandVector;
result.value = QVariant::fromValue(findMinimum());
return result;
}
QList<RpnArgument> Rosenbrock::requiredArguments()
{
QList<RpnArgument> arguments;
arguments
// NOTE: QVariant() shows that number of arguments is not fixed, maybe there is other way
<< RpnArgument(RpnOperandFunctionName, QString(), QVariant())
<< RpnArgument(RpnOperandVector)
<< RpnArgument(RpnOperandNumber)
<< RpnArgument(RpnOperandNumber)
<< RpnArgument(RpnOperandNumber)
<< RpnArgument(RpnOperandVector)
<< RpnArgument(RpnOperandNumber);
return arguments;
}
QList<Number> Rosenbrock::findMinimum()
{
QList<Number> firstCurrentPoint = m_sourcePoint;
QList<Number> sourceSteps = m_steps;
QList<Number> currentPoint = firstCurrentPoint;
forever {
forever {
int failStepsCount = 0;
for (int i = 0; i < currentPoint.size(); i++) {
if (countFunction(increaseDirection(currentPoint, i)) < countFunction(currentPoint)) {
currentPoint = increaseDirection(currentPoint, i);
m_steps[i] = m_steps[i] * m_accelerationStep;
}
else {
m_steps[i] = m_steps[i] * m_decreaseStep;
failStepsCount++;
}
}
if (countFunction(currentPoint) == countFunction(firstCurrentPoint)) {
if (countFunction(currentPoint) < countFunction(m_sourcePoint)) {
// Loop exit condition
break;
}
else if (countFunction(currentPoint) == countFunction(m_sourcePoint)) {
if (failStepsCount <= m_wrongStepsNumber) {
bool isFinish = true;
for (int i = 0; i < m_steps.size(); i++) {
if (qAbs(m_steps[i]) > m_stopValue) {
isFinish = false;
}
}
if (isFinish) {
// Main loop exit condition
return m_sourcePoint;
}
else {
firstCurrentPoint = currentPoint;
continue;
}
}
// Loop exit condition
else {
break;
}
}
}
else {
firstCurrentPoint = currentPoint;
continue;
}
}
Number modulus = modulusList(diffListList(currentPoint, m_sourcePoint));
if (modulus <= m_stopValue) {
// Main loop exit condition
return currentPoint;
}
else {
getNewDirections(getStepLengths(currentPoint, m_sourcePoint));
m_steps = sourceSteps;
m_sourcePoint = currentPoint;
firstCurrentPoint = currentPoint;
}
}
}
void Rosenbrock::getNewDirections(QList<Number> stepSizes)
{
QList<QList<Number> > gramStepOne;
for (int i = 0; i < stepSizes.size(); i++) {
if (stepSizes[i] == 0) {
gramStepOne << m_directions[i];
}
else {
QList<Number> element;
for (int j = i; j < stepSizes.size(); j++) {
if (element != QList<Number>()) {
element = sumListList(element, productListNumber(m_directions[j], stepSizes[j]));
}
else {
element = productListNumber(m_directions[j], stepSizes[j]);
}
}
gramStepOne << element;
}
}
QList<QList<Number> > gramStepTwo;
for (int i = 0; i < stepSizes.size(); i++) {
QList<Number> element;
if (i == 0) {
element = gramStepOne[i];
}
else {
QList<Number> subtractin;
for (int j = 0; j < i; j++) {
subtractin = productListNumber(gramStepTwo[j], productListList(gramStepOne[i], gramStepTwo[j]));
if (j != 0) {
subtractin = sumListList(subtractin, gramStepTwo[j]);
}
}
element = diffListList(gramStepOne[i], subtractin);
}
m_directions[i] = quotientListNumber(element, modulusList(element));
gramStepTwo << m_directions[i];
}
}
QList<Number> Rosenbrock::getStepLengths(QList<Number> currentPoint, QList<Number> previousPoint)
{
QList<QList<Number> > equationCoefficients;
equationCoefficients << diffListList(currentPoint, previousPoint);
foreach (QList<Number> direction, m_directions) {
equationCoefficients << direction;
}
return solveEquationSystem(equationCoefficients);
}
// First list of coefficients is equations results
QList<Number> Rosenbrock::solveEquationSystem(QList<QList<Number> > coefficients)
{
QList<Number> result;
QVector<QVector<Number> > mainMatrix;
for (int i = 1; i < coefficients.size(); i++) {
mainMatrix << QVector<Number>::fromList(coefficients[i]);
}
Number mainDeterminant = countDeterminant(mainMatrix);
for (int i = 1; i < coefficients.size(); i++) {
QVector<QVector<Number> > elementMatrix;
for (int j = 1; j < coefficients.size(); j++) {
if (j == i) {
elementMatrix << QVector<Number>::fromList(coefficients[0]);
}
else {
elementMatrix << QVector<Number>::fromList(coefficients[j]);
}
}
result << countDeterminant(elementMatrix) / mainDeterminant;
}
return result;
}
Number Rosenbrock::countDeterminant(QVector<QVector<Number> > matrix)
{
Number result = 0;
if (matrix.size() == 1) {
result = matrix[0][0];
}
else if (matrix.size() == 2) {
result = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
}
else {
// Go threw first line
for (int i = 0; i < matrix.size(); i++) {
// Initialize minor matrix
QVector<QVector<Number> > minorMatrix;
minorMatrix.resize(matrix.size() - 1);
for (int j = 0; j < minorMatrix.size(); j++) {
minorMatrix[j].resize(matrix.size() - 1);
}
// Fill minor matrix
for (int j = 0; j < matrix.size(); j++) {
int k = 0;
for (int l = 0; l < matrix.size(); l++) {
// Don't conpy the minor column
if (l != i) {
minorMatrix[j - 1][k] = minorMatrix[j][l];
k++;
}
}
}
result +=
qPow(-1, 1 + i + 1) *
minorMatrix[0][i] *
countDeterminant(minorMatrix);
}
}
return result;
}
QList<Number> Rosenbrock::increaseDirection(QList<Number> point, int direction)
{
QList<Number> result = point;
for (int i = 0; i < point.size(); i++) {
result[i] += m_directions[direction][i] * m_steps[direction];
}
return result;
}
QList<Number> Rosenbrock::productListNumber(QList<Number> list, Number number)
{
QList<Number> result;
foreach (Number element, list) {
result << element * number;
}
return result;
}
QList<Number> Rosenbrock::diffListList(QList<Number> source, QList<Number> subtractin)
{
QList<Number> result;
for (int i = 0; i < source.size(); i++) {
result << source[i] - subtractin[i];
}
return result;
}
QList<Number> Rosenbrock::sumListList(QList<Number> source, QList<Number> item)
{
QList<Number> result;
for (int i = 0; i < source.size(); i++) {
result << source[i] + item[i];
}
return result;
}
Number Rosenbrock::productListList(QList<Number> source, QList<Number> item)
{
Number result = 0;
for (int i = 0; i < source.size(); i++) {
result += source[i] * item[i];
}
return result;
}
Number Rosenbrock::modulusList(QList<Number> list)
{
Number result = 0;
foreach (Number element, list) {
result += qPow(element, 2);
}
return qSqrt(result);
}
QList<Number> Rosenbrock::quotientListNumber(QList<Number> source, Number divisor)
{
QList<Number> result;
foreach (Number element, source) {
result << element / divisor;
}
return result;
}
Number Rosenbrock::countFunction(QList<Number> arguments)
{
QList<RpnOperand> functionArguments;
foreach (Number argument, arguments) {
RpnOperand functionArgument(RpnOperandNumber, argument);
functionArguments << functionArgument;
}
RpnOperand result = m_calculator->calculate(m_functionName, functionArguments);
return result.value.value<Number>();
}
<|endoftext|> |
<commit_before>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* 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 "hal/LowPowerTickerWrapper.h"
#include "platform/Callback.h"
LowPowerTickerWrapper::LowPowerTickerWrapper(const ticker_data_t *data, const ticker_interface_t *interface, uint32_t min_cycles_between_writes, uint32_t min_cycles_until_match)
: _intf(data->interface), _min_count_between_writes(min_cycles_between_writes + 1), _min_count_until_match(min_cycles_until_match + 1), _suspended(false)
{
core_util_critical_section_enter();
this->data.interface = interface;
this->data.queue = data->queue;
_reset();
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::irq_handler(ticker_irq_handler_type handler)
{
core_util_critical_section_enter();
if (_suspended) {
if (handler) {
handler(&data);
}
core_util_critical_section_exit();
return;
}
if (_pending_fire_now || _match_check(_intf->read())) {
_timeout.detach();
_pending_timeout = false;
_pending_match = false;
_pending_fire_now = false;
if (handler) {
handler(&data);
}
} else {
// Spurious interrupt
_intf->clear_interrupt();
}
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::suspend()
{
core_util_critical_section_enter();
// Wait until rescheduling is allowed
while (!_set_interrupt_allowed) {
timestamp_t current = _intf->read();
if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) {
_set_interrupt_allowed = true;
}
}
_reset();
_suspended = true;
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::resume()
{
core_util_critical_section_enter();
_suspended = false;
core_util_critical_section_exit();
}
bool LowPowerTickerWrapper::timeout_pending()
{
core_util_critical_section_enter();
bool pending = _pending_timeout;
core_util_critical_section_exit();
return pending;
}
void LowPowerTickerWrapper::init()
{
core_util_critical_section_enter();
_reset();
_intf->init();
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::free()
{
core_util_critical_section_enter();
_reset();
_intf->free();
core_util_critical_section_exit();
}
uint32_t LowPowerTickerWrapper::read()
{
core_util_critical_section_enter();
timestamp_t current = _intf->read();
if (_match_check(current)) {
_intf->fire_interrupt();
}
core_util_critical_section_exit();
return current;
}
void LowPowerTickerWrapper::set_interrupt(timestamp_t timestamp)
{
core_util_critical_section_enter();
_last_set_interrupt = _intf->read();
_cur_match_time = timestamp;
_pending_match = true;
_schedule_match(_last_set_interrupt);
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::disable_interrupt()
{
core_util_critical_section_enter();
_intf->disable_interrupt();
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::clear_interrupt()
{
core_util_critical_section_enter();
_intf->clear_interrupt();
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::fire_interrupt()
{
core_util_critical_section_enter();
_pending_fire_now = 1;
_intf->fire_interrupt();
core_util_critical_section_exit();
}
const ticker_info_t *LowPowerTickerWrapper::get_info()
{
core_util_critical_section_enter();
const ticker_info_t *info = _intf->get_info();
core_util_critical_section_exit();
return info;
}
void LowPowerTickerWrapper::_reset()
{
MBED_ASSERT(core_util_in_critical_section());
_timeout.detach();
_pending_timeout = false;
_pending_match = false;
_pending_fire_now = false;
_set_interrupt_allowed = true;
_cur_match_time = 0;
_last_set_interrupt = 0;
_last_actual_set_interrupt = 0;
const ticker_info_t *info = _intf->get_info();
if (info->bits >= 32) {
_mask = 0xffffffff;
} else {
_mask = ((uint64_t)1 << info->bits) - 1;
}
// Round us_per_tick up
_us_per_tick = (1000000 + info->frequency - 1) / info->frequency;
}
void LowPowerTickerWrapper::_timeout_handler()
{
core_util_critical_section_enter();
_pending_timeout = false;
timestamp_t current = _intf->read();
if (_ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time)) {
_intf->fire_interrupt();
} else {
_schedule_match(current);
}
core_util_critical_section_exit();
}
bool LowPowerTickerWrapper::_match_check(timestamp_t current)
{
MBED_ASSERT(core_util_in_critical_section());
if (!_pending_match) {
return false;
}
return _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time);
}
uint32_t LowPowerTickerWrapper::_lp_ticks_to_us(uint32_t ticks)
{
MBED_ASSERT(core_util_in_critical_section());
// Add 4 microseconds to round up the micro second ticker time (which has a frequency of at least 250KHz - 4us period)
return _us_per_tick * ticks + 4;
}
void LowPowerTickerWrapper::_schedule_match(timestamp_t current)
{
MBED_ASSERT(core_util_in_critical_section());
// Check if _intf->set_interrupt is allowed
if (!_set_interrupt_allowed) {
if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) {
_set_interrupt_allowed = true;
}
}
uint32_t cycles_until_match = (_cur_match_time - _last_set_interrupt) & _mask;
bool too_close = cycles_until_match < _min_count_until_match;
if (!_set_interrupt_allowed) {
// Can't use _intf->set_interrupt so use microsecond Timeout instead
uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match;
_timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks));
_pending_timeout = true;
return;
}
if (!too_close) {
// Schedule LP ticker
_intf->set_interrupt(_cur_match_time);
current = _intf->read();
_last_actual_set_interrupt = current;
_set_interrupt_allowed = false;
// Check for overflow
uint32_t new_cycles_until_match = (_cur_match_time - current) & _mask;
if (new_cycles_until_match > cycles_until_match) {
// Overflow so fire now
_intf->fire_interrupt();
return;
}
// Update variables with new time
cycles_until_match = new_cycles_until_match;
too_close = cycles_until_match < _min_count_until_match;
}
if (too_close) {
// Low power ticker incremented to less than _min_count_until_match
// so low power ticker may not fire. Use Timeout to ensure it does fire.
uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match;
_timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks));
_pending_timeout = true;
return;
}
}
<commit_msg>Speed optimization for LowPowerTickerWrapper<commit_after>/* mbed Microcontroller Library
* Copyright (c) 2018 ARM Limited
*
* 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 "hal/LowPowerTickerWrapper.h"
#include "platform/Callback.h"
LowPowerTickerWrapper::LowPowerTickerWrapper(const ticker_data_t *data, const ticker_interface_t *interface, uint32_t min_cycles_between_writes, uint32_t min_cycles_until_match)
: _intf(data->interface), _min_count_between_writes(min_cycles_between_writes + 1), _min_count_until_match(min_cycles_until_match + 1), _suspended(false)
{
core_util_critical_section_enter();
this->data.interface = interface;
this->data.queue = data->queue;
_reset();
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::irq_handler(ticker_irq_handler_type handler)
{
core_util_critical_section_enter();
if (_suspended) {
if (handler) {
handler(&data);
}
core_util_critical_section_exit();
return;
}
if (_pending_fire_now || _match_check(_intf->read())) {
_timeout.detach();
_pending_timeout = false;
_pending_match = false;
_pending_fire_now = false;
if (handler) {
handler(&data);
}
} else {
// Spurious interrupt
_intf->clear_interrupt();
}
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::suspend()
{
core_util_critical_section_enter();
// Wait until rescheduling is allowed
while (!_set_interrupt_allowed) {
timestamp_t current = _intf->read();
if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) {
_set_interrupt_allowed = true;
}
}
_reset();
_suspended = true;
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::resume()
{
core_util_critical_section_enter();
_suspended = false;
core_util_critical_section_exit();
}
bool LowPowerTickerWrapper::timeout_pending()
{
core_util_critical_section_enter();
bool pending = _pending_timeout;
core_util_critical_section_exit();
return pending;
}
void LowPowerTickerWrapper::init()
{
core_util_critical_section_enter();
_reset();
_intf->init();
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::free()
{
core_util_critical_section_enter();
_reset();
_intf->free();
core_util_critical_section_exit();
}
uint32_t LowPowerTickerWrapper::read()
{
core_util_critical_section_enter();
timestamp_t current = _intf->read();
if (_match_check(current)) {
_intf->fire_interrupt();
}
core_util_critical_section_exit();
return current;
}
void LowPowerTickerWrapper::set_interrupt(timestamp_t timestamp)
{
core_util_critical_section_enter();
_last_set_interrupt = _intf->read();
_cur_match_time = timestamp;
_pending_match = true;
_schedule_match(_last_set_interrupt);
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::disable_interrupt()
{
core_util_critical_section_enter();
_intf->disable_interrupt();
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::clear_interrupt()
{
core_util_critical_section_enter();
_intf->clear_interrupt();
core_util_critical_section_exit();
}
void LowPowerTickerWrapper::fire_interrupt()
{
core_util_critical_section_enter();
_pending_fire_now = 1;
_intf->fire_interrupt();
core_util_critical_section_exit();
}
const ticker_info_t *LowPowerTickerWrapper::get_info()
{
core_util_critical_section_enter();
const ticker_info_t *info = _intf->get_info();
core_util_critical_section_exit();
return info;
}
void LowPowerTickerWrapper::_reset()
{
MBED_ASSERT(core_util_in_critical_section());
_timeout.detach();
_pending_timeout = false;
_pending_match = false;
_pending_fire_now = false;
_set_interrupt_allowed = true;
_cur_match_time = 0;
_last_set_interrupt = 0;
_last_actual_set_interrupt = 0;
const ticker_info_t *info = _intf->get_info();
if (info->bits >= 32) {
_mask = 0xffffffff;
} else {
_mask = ((uint64_t)1 << info->bits) - 1;
}
// Round us_per_tick up
_us_per_tick = (1000000 + info->frequency - 1) / info->frequency;
}
void LowPowerTickerWrapper::_timeout_handler()
{
core_util_critical_section_enter();
_pending_timeout = false;
timestamp_t current = _intf->read();
if (_ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time)) {
_intf->fire_interrupt();
} else {
_schedule_match(current);
}
core_util_critical_section_exit();
}
bool LowPowerTickerWrapper::_match_check(timestamp_t current)
{
MBED_ASSERT(core_util_in_critical_section());
if (!_pending_match) {
return false;
}
return _ticker_match_interval_passed(_last_set_interrupt, current, _cur_match_time);
}
uint32_t LowPowerTickerWrapper::_lp_ticks_to_us(uint32_t ticks)
{
MBED_ASSERT(core_util_in_critical_section());
// Add 4 microseconds to round up the micro second ticker time (which has a frequency of at least 250KHz - 4us period)
return _us_per_tick * ticks + 4;
}
void LowPowerTickerWrapper::_schedule_match(timestamp_t current)
{
MBED_ASSERT(core_util_in_critical_section());
// Check if _intf->set_interrupt is allowed
if (!_set_interrupt_allowed) {
if (((current - _last_actual_set_interrupt) & _mask) >= _min_count_between_writes) {
_set_interrupt_allowed = true;
}
}
uint32_t cycles_until_match = (_cur_match_time - _last_set_interrupt) & _mask;
bool too_close = cycles_until_match < _min_count_until_match;
if (!_set_interrupt_allowed) {
// Can't use _intf->set_interrupt so use microsecond Timeout instead
// Speed optimization - if a timer has already been scheduled
// then don't schedule it again.
if (!_pending_timeout) {
uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match;
_timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks));
_pending_timeout = true;
}
return;
}
if (!too_close) {
// Schedule LP ticker
_intf->set_interrupt(_cur_match_time);
current = _intf->read();
_last_actual_set_interrupt = current;
_set_interrupt_allowed = false;
// Check for overflow
uint32_t new_cycles_until_match = (_cur_match_time - current) & _mask;
if (new_cycles_until_match > cycles_until_match) {
// Overflow so fire now
_intf->fire_interrupt();
return;
}
// Update variables with new time
cycles_until_match = new_cycles_until_match;
too_close = cycles_until_match < _min_count_until_match;
}
if (too_close) {
// Low power ticker incremented to less than _min_count_until_match
// so low power ticker may not fire. Use Timeout to ensure it does fire.
uint32_t ticks = cycles_until_match < _min_count_until_match ? cycles_until_match : _min_count_until_match;
_timeout.attach_us(mbed::callback(this, &LowPowerTickerWrapper::_timeout_handler), _lp_ticks_to_us(ticks));
_pending_timeout = true;
return;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppRoster.h"
#include "QXmppUtils.h"
#include "QXmppRosterIq.h"
#include "QXmppPresence.h"
#include "QXmppStream.h"
QXmppRoster::QXmppRoster(QXmppStream* stream) : m_stream(stream),
m_isRosterReceived(false)
{
}
QXmppRoster::~QXmppRoster()
{
}
void QXmppRoster::disconnected()
{
m_entries = QMap<QString, QXmppRoster::QXmppRosterEntry>();
m_presences = QMap<QString, QMap<QString, QXmppPresence> >();
m_isRosterReceived = false;
}
void QXmppRoster::presenceReceived(const QXmppPresence& presence)
{
QString jid = presence.from();
QString bareJid = jidToBareJid(jid);
QString resource = jidToResource(jid);
if (presence.getType() == QXmppPresence::Available)
m_presences[bareJid][resource] = presence;
else if (presence.getType() == QXmppPresence::Unavailable)
m_presences[bareJid].remove(resource);
else
return;
emit presenceChanged(bareJid, resource);
}
void QXmppRoster::rosterIqReceived(const QXmppRosterIq& rosterIq)
{
switch(rosterIq.type())
{
case QXmppIq::Set:
case QXmppIq::Result:
{
QList<QXmppRosterIq::Item> items = rosterIq.items();
for(int i = 0; i < items.count(); ++i)
{
QString bareJid = items.at(i).bareJid();
m_entries[bareJid].setBareJid(bareJid);
m_entries[bareJid].setName(items.at(i).name());
m_entries[bareJid].setSubscriptionType(
static_cast<QXmppRosterEntry::SubscriptionType>(
items.at(i).subscriptionType()));
m_entries[bareJid].setSubscriptionStatus(
items.at(i).subscriptionStatus());
m_entries[bareJid].setGroups(items.at(i).groups());
emit rosterChanged(bareJid);
}
if(rosterIq.type() == QXmppIq::Set) // send result iq
{
QXmppIq returnIq(QXmppIq::Result);
returnIq.setId(rosterIq.id());
m_stream->sendPacket(returnIq);
}
break;
}
default:
break;
}
}
void QXmppRoster::rosterRequestIqReceived(const QXmppRosterIq& rosterIq)
{
switch(rosterIq.type())
{
case QXmppIq::Set:
case QXmppIq::Result:
{
QList<QXmppRosterIq::Item> items = rosterIq.items();
for(int i = 0; i < items.count(); ++i)
{
QString bareJid = items.at(i).bareJid();
m_entries[bareJid].setBareJid(bareJid);
m_entries[bareJid].setName(items.at(i).name());
m_entries[bareJid].setSubscriptionType(
static_cast<QXmppRosterEntry::SubscriptionType>(
items.at(i).subscriptionType()));
m_entries[bareJid].setSubscriptionStatus(
items.at(i).subscriptionStatus());
m_entries[bareJid].setGroups(items.at(i).groups());
}
if(rosterIq.type() == QXmppIq::Set) // send result iq
{
QXmppIq returnIq(QXmppIq::Result);
returnIq.setId(rosterIq.id());
m_stream->sendPacket(returnIq);
}
m_isRosterReceived = true;
emit rosterReceived();
break;
}
default:
break;
}
}
/// Returns the bareJid of the roster entry.
///
/// \return bareJid as a QString
///
QString QXmppRoster::QXmppRosterEntry::bareJid() const
{
return m_bareJid;
}
/// Returns the name of the roster entry.
///
/// \return name as a QString
///
QString QXmppRoster::QXmppRosterEntry::name() const
{
return m_name;
}
/// Returns the subscription type of the roster entry.
///
/// \return QXmppRosterEntry::SubscriptionType
///
QXmppRoster::QXmppRosterEntry::SubscriptionType
QXmppRoster::QXmppRosterEntry::subscriptionType() const
{
return m_type;
}
/// Sets the subscription status of the roster entry. It is the "ask"
/// attribute in the Roster IQ stanza. Its value can be "subscribe" or "unsubscribe"
/// or empty.
///
/// \return subscription status as a QString
///
///
QString QXmppRoster::QXmppRosterEntry::subscriptionStatus() const
{
return m_subscriptionStatus;
}
/// Returns the groups of the roster entry.
///
/// \return QSet<QString> list of all the groups
///
QSet<QString> QXmppRoster::QXmppRosterEntry::groups() const
{
return m_groups;
}
/// Sets the bareJid of the roster entry.
///
/// \param bareJid as a QString
///
void QXmppRoster::QXmppRosterEntry::setBareJid(const QString& bareJid )
{
m_bareJid = bareJid ;
}
/// Sets the name of the roster entry.
///
/// \param name as a QString
///
void QXmppRoster::QXmppRosterEntry::setName(const QString& name)
{
m_name = name;
}
/// Sets the subscription type of the roster entry.
///
/// \param type as a QXmppRosterEntry::SubscriptionType
///
void QXmppRoster::QXmppRosterEntry::setSubscriptionType(
QXmppRosterEntry::SubscriptionType type)
{
m_type = type;
}
/// Sets the subscription status of the roster entry. It is the "ask"
/// attribute in the Roster IQ stanza. Its value can be "subscribe" or "unsubscribe"
/// or empty.
///
/// \param status as a QString
///
void QXmppRoster::QXmppRosterEntry::setSubscriptionStatus(const QString& status)
{
m_subscriptionStatus = status;
}
/// Adds the group entry of the roster entry.
///
/// \param group name as a QString
///
void QXmppRoster::QXmppRosterEntry::addGroupEntry(const QString& group)
{
m_groups << group;
}
/// Sets the groups of the roster entry.
///
/// \param groups list of all the groups as a QSet<QString>
///
void QXmppRoster::QXmppRosterEntry::setGroups(const QSet<QString>& groups)
{
m_groups = groups;
}
/// Function to get all the bareJids present in the roster.
///
/// \return QStringList list of all the bareJids
///
QStringList QXmppRoster::getRosterBareJids() const
{
return m_entries.keys();
}
/// Returns the roster entry of the given bareJid. If the bareJid is not in the
/// database and empty QXmppRoster::QXmppRosterEntry will be returned.
///
/// \param bareJid as a QString
/// \return QXmppRoster::QXmppRosterEntry
///
QXmppRoster::QXmppRosterEntry QXmppRoster::getRosterEntry(
const QString& bareJid) const
{
// will return blank entry if bareJid does'nt exist
if(m_entries.contains(bareJid))
return m_entries.value(bareJid);
else
{
qWarning("QXmppRoster::getRosterEntry(): bareJid doesn't exist in roster db");
return QXmppRoster::QXmppRosterEntry();
}
}
/// [OBSOLETE] Returns all the roster entries in the database.
///
/// \return Map of bareJid and its respective QXmppRoster::QXmppRosterEntry
///
/// \note This function is obsolete, use getRosterBareJids() and
/// getRosterEntry() to get all the roster entries.
///
QMap<QString, QXmppRoster::QXmppRosterEntry>
QXmppRoster::getRosterEntries() const
{
return m_entries;
}
/// Get all the associated resources with the given bareJid.
///
/// \param bareJid as a QString
/// \return list of associated resources as a QStringList
///
QStringList QXmppRoster::getResources(const QString& bareJid) const
{
if(m_presences.contains(bareJid))
{
return m_presences[bareJid].keys();
}
else
return QStringList();
}
/// Get all the presences of all the resources of the given bareJid. A bareJid
/// can have multiple resources and each resource will have a presence
/// associated with it.
///
/// \param bareJid as a QString
/// \return Map of resource and its respective presence QMap<QString, QXmppPresence>
///
QMap<QString, QXmppPresence> QXmppRoster::getAllPresencesForBareJid(
const QString& bareJid) const
{
if(m_presences.contains(bareJid))
return m_presences[bareJid];
else
{
qWarning("QXmppRoster::getAllPresences(): invalid bareJid");
return QMap<QString, QXmppPresence>();
}
}
/// Get the presence of the given resource of the given bareJid.
///
/// \param bareJid as a QString
/// \param resource as a QString
/// \return QXmppPresence
///
QXmppPresence QXmppRoster::getPresence(const QString& bareJid,
const QString& resource) const
{
if(m_presences.contains(bareJid) && m_presences[bareJid].contains(resource))
return m_presences[bareJid][resource];
else
{
qWarning("QXmppRoster::getPresence(): invalid bareJid");
return QXmppPresence();
}
}
/// [OBSOLETE] Returns all the presence entries in the database.
///
/// \return Map of bareJid and map of resource and its presence that is
/// QMap<QString, QMap<QString, QXmppPresence> >
///
/// \note This function is obsolete, use getRosterBareJids(), getResources()
/// and getPresence() or getAllPresencesForBareJid()
/// to get all the presence entries.
QMap<QString, QMap<QString, QXmppPresence> > QXmppRoster::getAllPresences() const
{
return m_presences;
}
/// Function to check whether the roster has been received or not.
///
/// \return true if roster received else false
bool QXmppRoster::isRosterReceived()
{
return m_isRosterReceived;
}
QString QXmppRoster::QXmppRosterEntry::getBareJid() const
{
return m_bareJid;
}
QString QXmppRoster::QXmppRosterEntry::getName() const
{
return m_name;
}
QXmppRoster::QXmppRosterEntry::SubscriptionType
QXmppRoster::QXmppRosterEntry::getSubscriptionType() const
{
return m_type;
}
QString QXmppRoster::QXmppRosterEntry::getSubscriptionStatus() const
{
return m_subscriptionStatus;
}
QSet<QString> QXmppRoster::QXmppRosterEntry::getGroups() const
{
return m_groups;
}
<commit_msg>silence warning when QXmppRoster::getAllPresencesForBareJid is called for an unknown JID<commit_after>/*
* Copyright (C) 2008-2010 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppRoster.h"
#include "QXmppUtils.h"
#include "QXmppRosterIq.h"
#include "QXmppPresence.h"
#include "QXmppStream.h"
QXmppRoster::QXmppRoster(QXmppStream* stream) : m_stream(stream),
m_isRosterReceived(false)
{
}
QXmppRoster::~QXmppRoster()
{
}
void QXmppRoster::disconnected()
{
m_entries = QMap<QString, QXmppRoster::QXmppRosterEntry>();
m_presences = QMap<QString, QMap<QString, QXmppPresence> >();
m_isRosterReceived = false;
}
void QXmppRoster::presenceReceived(const QXmppPresence& presence)
{
QString jid = presence.from();
QString bareJid = jidToBareJid(jid);
QString resource = jidToResource(jid);
if (presence.getType() == QXmppPresence::Available)
m_presences[bareJid][resource] = presence;
else if (presence.getType() == QXmppPresence::Unavailable)
m_presences[bareJid].remove(resource);
else
return;
emit presenceChanged(bareJid, resource);
}
void QXmppRoster::rosterIqReceived(const QXmppRosterIq& rosterIq)
{
switch(rosterIq.type())
{
case QXmppIq::Set:
case QXmppIq::Result:
{
QList<QXmppRosterIq::Item> items = rosterIq.items();
for(int i = 0; i < items.count(); ++i)
{
QString bareJid = items.at(i).bareJid();
m_entries[bareJid].setBareJid(bareJid);
m_entries[bareJid].setName(items.at(i).name());
m_entries[bareJid].setSubscriptionType(
static_cast<QXmppRosterEntry::SubscriptionType>(
items.at(i).subscriptionType()));
m_entries[bareJid].setSubscriptionStatus(
items.at(i).subscriptionStatus());
m_entries[bareJid].setGroups(items.at(i).groups());
emit rosterChanged(bareJid);
}
if(rosterIq.type() == QXmppIq::Set) // send result iq
{
QXmppIq returnIq(QXmppIq::Result);
returnIq.setId(rosterIq.id());
m_stream->sendPacket(returnIq);
}
break;
}
default:
break;
}
}
void QXmppRoster::rosterRequestIqReceived(const QXmppRosterIq& rosterIq)
{
switch(rosterIq.type())
{
case QXmppIq::Set:
case QXmppIq::Result:
{
QList<QXmppRosterIq::Item> items = rosterIq.items();
for(int i = 0; i < items.count(); ++i)
{
QString bareJid = items.at(i).bareJid();
m_entries[bareJid].setBareJid(bareJid);
m_entries[bareJid].setName(items.at(i).name());
m_entries[bareJid].setSubscriptionType(
static_cast<QXmppRosterEntry::SubscriptionType>(
items.at(i).subscriptionType()));
m_entries[bareJid].setSubscriptionStatus(
items.at(i).subscriptionStatus());
m_entries[bareJid].setGroups(items.at(i).groups());
}
if(rosterIq.type() == QXmppIq::Set) // send result iq
{
QXmppIq returnIq(QXmppIq::Result);
returnIq.setId(rosterIq.id());
m_stream->sendPacket(returnIq);
}
m_isRosterReceived = true;
emit rosterReceived();
break;
}
default:
break;
}
}
/// Returns the bareJid of the roster entry.
///
/// \return bareJid as a QString
///
QString QXmppRoster::QXmppRosterEntry::bareJid() const
{
return m_bareJid;
}
/// Returns the name of the roster entry.
///
/// \return name as a QString
///
QString QXmppRoster::QXmppRosterEntry::name() const
{
return m_name;
}
/// Returns the subscription type of the roster entry.
///
/// \return QXmppRosterEntry::SubscriptionType
///
QXmppRoster::QXmppRosterEntry::SubscriptionType
QXmppRoster::QXmppRosterEntry::subscriptionType() const
{
return m_type;
}
/// Sets the subscription status of the roster entry. It is the "ask"
/// attribute in the Roster IQ stanza. Its value can be "subscribe" or "unsubscribe"
/// or empty.
///
/// \return subscription status as a QString
///
///
QString QXmppRoster::QXmppRosterEntry::subscriptionStatus() const
{
return m_subscriptionStatus;
}
/// Returns the groups of the roster entry.
///
/// \return QSet<QString> list of all the groups
///
QSet<QString> QXmppRoster::QXmppRosterEntry::groups() const
{
return m_groups;
}
/// Sets the bareJid of the roster entry.
///
/// \param bareJid as a QString
///
void QXmppRoster::QXmppRosterEntry::setBareJid(const QString& bareJid )
{
m_bareJid = bareJid ;
}
/// Sets the name of the roster entry.
///
/// \param name as a QString
///
void QXmppRoster::QXmppRosterEntry::setName(const QString& name)
{
m_name = name;
}
/// Sets the subscription type of the roster entry.
///
/// \param type as a QXmppRosterEntry::SubscriptionType
///
void QXmppRoster::QXmppRosterEntry::setSubscriptionType(
QXmppRosterEntry::SubscriptionType type)
{
m_type = type;
}
/// Sets the subscription status of the roster entry. It is the "ask"
/// attribute in the Roster IQ stanza. Its value can be "subscribe" or "unsubscribe"
/// or empty.
///
/// \param status as a QString
///
void QXmppRoster::QXmppRosterEntry::setSubscriptionStatus(const QString& status)
{
m_subscriptionStatus = status;
}
/// Adds the group entry of the roster entry.
///
/// \param group name as a QString
///
void QXmppRoster::QXmppRosterEntry::addGroupEntry(const QString& group)
{
m_groups << group;
}
/// Sets the groups of the roster entry.
///
/// \param groups list of all the groups as a QSet<QString>
///
void QXmppRoster::QXmppRosterEntry::setGroups(const QSet<QString>& groups)
{
m_groups = groups;
}
/// Function to get all the bareJids present in the roster.
///
/// \return QStringList list of all the bareJids
///
QStringList QXmppRoster::getRosterBareJids() const
{
return m_entries.keys();
}
/// Returns the roster entry of the given bareJid. If the bareJid is not in the
/// database and empty QXmppRoster::QXmppRosterEntry will be returned.
///
/// \param bareJid as a QString
/// \return QXmppRoster::QXmppRosterEntry
///
QXmppRoster::QXmppRosterEntry QXmppRoster::getRosterEntry(
const QString& bareJid) const
{
// will return blank entry if bareJid does'nt exist
if(m_entries.contains(bareJid))
return m_entries.value(bareJid);
else
{
qWarning("QXmppRoster::getRosterEntry(): bareJid doesn't exist in roster db");
return QXmppRoster::QXmppRosterEntry();
}
}
/// [OBSOLETE] Returns all the roster entries in the database.
///
/// \return Map of bareJid and its respective QXmppRoster::QXmppRosterEntry
///
/// \note This function is obsolete, use getRosterBareJids() and
/// getRosterEntry() to get all the roster entries.
///
QMap<QString, QXmppRoster::QXmppRosterEntry>
QXmppRoster::getRosterEntries() const
{
return m_entries;
}
/// Get all the associated resources with the given bareJid.
///
/// \param bareJid as a QString
/// \return list of associated resources as a QStringList
///
QStringList QXmppRoster::getResources(const QString& bareJid) const
{
if(m_presences.contains(bareJid))
return m_presences[bareJid].keys();
else
return QStringList();
}
/// Get all the presences of all the resources of the given bareJid. A bareJid
/// can have multiple resources and each resource will have a presence
/// associated with it.
///
/// \param bareJid as a QString
/// \return Map of resource and its respective presence QMap<QString, QXmppPresence>
///
QMap<QString, QXmppPresence> QXmppRoster::getAllPresencesForBareJid(
const QString& bareJid) const
{
if(m_presences.contains(bareJid))
return m_presences[bareJid];
else
return QMap<QString, QXmppPresence>();
}
/// Get the presence of the given resource of the given bareJid.
///
/// \param bareJid as a QString
/// \param resource as a QString
/// \return QXmppPresence
///
QXmppPresence QXmppRoster::getPresence(const QString& bareJid,
const QString& resource) const
{
if(m_presences.contains(bareJid) && m_presences[bareJid].contains(resource))
return m_presences[bareJid][resource];
else
{
qWarning("QXmppRoster::getPresence(): invalid bareJid");
return QXmppPresence();
}
}
/// [OBSOLETE] Returns all the presence entries in the database.
///
/// \return Map of bareJid and map of resource and its presence that is
/// QMap<QString, QMap<QString, QXmppPresence> >
///
/// \note This function is obsolete, use getRosterBareJids(), getResources()
/// and getPresence() or getAllPresencesForBareJid()
/// to get all the presence entries.
QMap<QString, QMap<QString, QXmppPresence> > QXmppRoster::getAllPresences() const
{
return m_presences;
}
/// Function to check whether the roster has been received or not.
///
/// \return true if roster received else false
bool QXmppRoster::isRosterReceived()
{
return m_isRosterReceived;
}
QString QXmppRoster::QXmppRosterEntry::getBareJid() const
{
return m_bareJid;
}
QString QXmppRoster::QXmppRosterEntry::getName() const
{
return m_name;
}
QXmppRoster::QXmppRosterEntry::SubscriptionType
QXmppRoster::QXmppRosterEntry::getSubscriptionType() const
{
return m_type;
}
QString QXmppRoster::QXmppRosterEntry::getSubscriptionStatus() const
{
return m_subscriptionStatus;
}
QSet<QString> QXmppRoster::QXmppRosterEntry::getGroups() const
{
return m_groups;
}
<|endoftext|> |
<commit_before>#include "sdl_rw_ops.h"
using namespace Halley;
std::unique_ptr<ResourceDataReader> SDLRWOps::fromPath(const String& path, int64_t start, int64_t end)
{
auto fp = SDL_RWFromFile(path.c_str(), "rb");
if (!fp) {
throw Exception("Unable to open file: " + path);
}
return std::make_unique<SDLRWOps>(fp, start, end, true);
}
std::unique_ptr<ResourceDataReader> SDLRWOps::fromMemory(gsl::span<const gsl::byte> span)
{
auto fp = SDL_RWFromConstMem(span.data(), int(span.size()));
if (!fp) {
throw Exception("Unable to open data from memory");
}
return std::make_unique<SDLRWOps>(fp, 0, 0, true);
}
SDLRWOps::SDLRWOps(SDL_RWops* _fp, int64_t _start, int64_t _end, bool _closeOnFinish)
: fp(_fp)
, pos(_start)
, start(_start)
, end(_end)
, closeOnFinish(_closeOnFinish)
{
Expects(fp);
if (end == -1) {
SDL_RWseek(fp, 0, SEEK_END);
end = SDL_RWtell(fp);
SDL_RWseek(fp, 0, SEEK_SET);
}
int64_t size = end - start;
if (size < 0) {
throw Exception("Invalid file size for resource: " + String::integerToString(int(size)) + " bytes.");
}
}
size_t SDLRWOps::size() const
{
return end - start;
}
int SDLRWOps::read(gsl::span<gsl::byte> dst)
{
if (!fp) return -1;
size_t toRead = std::min(size_t(dst.size()), size_t(end - pos));
SDL_RWseek(fp, pos, SEEK_SET);
int n = static_cast<int>(SDL_RWread(fp, dst.data(), 1, static_cast<int>(toRead)));
if (n > 0) pos += n;
return n;
}
void SDLRWOps::close()
{
if (fp) {
if (closeOnFinish) {
SDL_RWclose(fp);
}
fp = nullptr;
pos = end;
}
}
void SDLRWOps::seek(long long offset, int whence)
{
if (whence == SEEK_SET) pos = int(offset + start);
else if (whence == SEEK_CUR) pos += int(offset);
else if (whence == SEEK_END) pos = int(end + offset);
SDL_RWseek(fp, pos, SEEK_SET);
}
size_t SDLRWOps::tell() const
{
return pos - start;
}
<commit_msg><commit_after>#include "sdl_rw_ops.h"
using namespace Halley;
std::unique_ptr<ResourceDataReader> SDLRWOps::fromPath(const String& path, int64_t start, int64_t end)
{
auto fp = SDL_RWFromFile(path.c_str(), "rb");
if (!fp) {
throw Exception("Unable to open file: " + path);
}
return std::make_unique<SDLRWOps>(fp, start, end, true);
}
std::unique_ptr<ResourceDataReader> SDLRWOps::fromMemory(gsl::span<const gsl::byte> span)
{
auto fp = SDL_RWFromConstMem(span.data(), int(span.size()));
if (!fp) {
throw Exception("Unable to open data from memory");
}
return std::make_unique<SDLRWOps>(fp, 0, 0, true);
}
SDLRWOps::SDLRWOps(SDL_RWops* _fp, int64_t _start, int64_t _end, bool _closeOnFinish)
: fp(_fp)
, pos(_start)
, start(_start)
, end(_end)
, closeOnFinish(_closeOnFinish)
{
Expects(fp);
if (end == -1) {
SDL_RWseek(fp, 0, SEEK_END);
end = SDL_RWtell(fp);
SDL_RWseek(fp, 0, SEEK_SET);
}
int64_t size = end - start;
if (size < 0) {
throw Exception("Invalid file size for resource: " + String::integerToString(int(size)) + " bytes.");
}
}
size_t SDLRWOps::size() const
{
return end - start;
}
int SDLRWOps::read(gsl::span<gsl::byte> dst)
{
if (!fp) return -1;
size_t toRead = std::min(size_t(dst.size()), size_t(end - pos));
SDL_RWseek(fp, pos, SEEK_SET);
int n = static_cast<int>(SDL_RWread(fp, dst.data(), 1, static_cast<int>(toRead)));
if (n > 0) pos += n;
return n;
}
void SDLRWOps::close()
{
if (fp) {
if (closeOnFinish) {
SDL_RWclose(fp);
}
fp = nullptr;
pos = end;
}
}
void SDLRWOps::seek(int64_t offset, int whence)
{
if (whence == SEEK_SET) pos = int(offset + start);
else if (whence == SEEK_CUR) pos += int(offset);
else if (whence == SEEK_END) pos = int(end + offset);
SDL_RWseek(fp, pos, SEEK_SET);
}
size_t SDLRWOps::tell() const
{
return pos - start;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2009 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppStanza.h"
#include "QXmppUtils.h"
#include "QXmppConstants.h"
#include <QDomElement>
#include <QXmlStreamWriter>
uint QXmppStanza::s_uniqeIdNo = 0;
QXmppStanza::Error::Error():
m_code(0),
m_type(static_cast<QXmppStanza::Error::Type>(-1)),
m_condition(static_cast<QXmppStanza::Error::Condition>(-1)),
m_text("")
{
}
QXmppStanza::Error::Error(Type type, Condition cond, const QString& text):
m_code(0),
m_type(type),
m_condition(cond),
m_text(text)
{
}
QXmppStanza::Error::Error(const QString& type, const QString& cond,
const QString& text):
m_code(0),
m_text(text)
{
setTypeFromStr(type);
setConditionFromStr(cond);
}
void QXmppStanza::Error::setText(const QString& text)
{
m_text = text;
}
void QXmppStanza::Error::setCode(int code)
{
m_code = code;
}
void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond)
{
m_condition = cond;
}
void QXmppStanza::Error::setType(QXmppStanza::Error::Type type)
{
m_type = type;
}
QString QXmppStanza::Error::getText() const
{
return m_text;
}
int QXmppStanza::Error::getCode() const
{
return m_code;
}
QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const
{
return m_condition;
}
QXmppStanza::Error::Type QXmppStanza::Error::getType() const
{
return m_type;
}
QString QXmppStanza::Error::getTypeStr() const
{
switch(m_type)
{
case Cancel:
return "cancel";
case Continue:
return "continue";
case Modify:
return "modify";
case Auth:
return "auth";
case Wait:
return "wait";
default:
return "";
}
}
QString QXmppStanza::Error::getConditionStr() const
{
switch(m_condition)
{
case BadRequest:
return "bad-request";
case Conflict:
return "conflict";
case FeatureNotImplemented:
return "feature-not-implemented";
case Forbidden:
return "forbidden";
case Gone:
return "gone";
case InternalServerError:
return "internal-server-error";
case ItemNotFound:
return "item-not-found";
case JidMalformed:
return "jid-malformed";
case NotAcceptable:
return "not-acceptable";
case NotAllowed:
return "not-allowed";
case NotAuthorized:
return "not-authorized";
case PaymentRequired:
return "payment-required";
case RecipientUnavailable:
return "recipient-unavailable";
case Redirect:
return "redirect";
case RegistrationRequired:
return "registration-required";
case RemoteServerNotFound:
return "remote-server-not-found";
case RemoteServerTimeout:
return "remote-server-timeout";
case ResourceConstraint:
return "resource-constraint";
case ServiceUnavailable:
return "service-unavailable";
case SubscriptionRequired:
return "subscription-required";
case UndefinedCondition:
return "undefined-condition";
case UnexpectedRequest:
return "unexpected-request";
default:
return "";
}
}
void QXmppStanza::Error::setTypeFromStr(const QString& type)
{
if(type == "cancel")
setType(Cancel);
else if(type == "continue")
setType(Continue);
else if(type == "modify")
setType(Modify);
else if(type == "auth")
setType(Auth);
else if(type == "wait")
setType(Wait);
else
setType(static_cast<QXmppStanza::Error::Type>(-1));
}
void QXmppStanza::Error::setConditionFromStr(const QString& type)
{
if(type == "bad-request")
setCondition(BadRequest);
else if(type == "conflict")
setCondition(Conflict);
else if(type == "feature-not-implemented")
setCondition(FeatureNotImplemented);
else if(type == "forbidden")
setCondition(Forbidden);
else if(type == "gone")
setCondition(Gone);
else if(type == "internal-server-error")
setCondition(InternalServerError);
else if(type == "item-not-found")
setCondition(ItemNotFound);
else if(type == "jid-malformed")
setCondition(JidMalformed);
else if(type == "not-acceptable")
setCondition(NotAcceptable);
else if(type == "not-allowed")
setCondition(NotAllowed);
else if(type == "not-authorized")
setCondition(NotAuthorized);
else if(type == "payment-required")
setCondition(PaymentRequired);
else if(type == "recipient-unavailable")
setCondition(RecipientUnavailable);
else if(type == "redirect")
setCondition(Redirect);
else if(type == "registration-required")
setCondition(RegistrationRequired);
else if(type == "remote-server-not-found")
setCondition(RemoteServerNotFound);
else if(type == "remote-server-timeout")
setCondition(RemoteServerTimeout);
else if(type == "resource-constraint")
setCondition(ResourceConstraint);
else if(type == "service-unavailable")
setCondition(ServiceUnavailable);
else if(type == "subscription-required")
setCondition(SubscriptionRequired);
else if(type == "undefined-condition")
setCondition(UndefinedCondition);
else if(type == "unexpected-request")
setCondition(UnexpectedRequest);
else
setCondition(static_cast<QXmppStanza::Error::Condition>(-1));
}
bool QXmppStanza::Error::isValid()
{
return !(getTypeStr().isEmpty() && getConditionStr().isEmpty());
}
void QXmppStanza::Error::parse(const QDomElement &errorElement)
{
setCode(errorElement.attribute("code").toInt());
setTypeFromStr(errorElement.attribute("type"));
QString text;
QString cond;
QDomElement element = errorElement.firstChildElement();
while(!element.isNull())
{
if(element.tagName() == "text")
text = element.text();
else if(element.namespaceURI() == ns_stanza)
{
cond = element.tagName();
}
element = element.nextSiblingElement();
}
setConditionFromStr(cond);
setText(text);
}
void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const
{
QString cond = getConditionStr();
QString type = getTypeStr();
if(cond.isEmpty() && type.isEmpty())
return;
writer->writeStartElement("error");
helperToXmlAddAttribute(writer, "type", type);
if (m_code > 0)
helperToXmlAddAttribute(writer, "code", QString::number(m_code));
if(!cond.isEmpty())
{
writer->writeStartElement(cond);
helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
writer->writeEndElement();
}
if(!m_text.isEmpty())
{
writer->writeStartElement("text");
helperToXmlAddAttribute(writer,"xml:lang", "en");
helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
writer->writeCharacters(m_text);
writer->writeEndElement();
}
writer->writeEndElement();
}
QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(),
m_to(to), m_from(from)
{
}
QXmppStanza::~QXmppStanza()
{
}
QString QXmppStanza::to() const
{
return m_to;
}
void QXmppStanza::setTo(const QString& to)
{
m_to = to;
}
QString QXmppStanza::from() const
{
return m_from;
}
void QXmppStanza::setFrom(const QString& from)
{
m_from = from;
}
QString QXmppStanza::id() const
{
return m_id;
}
void QXmppStanza::setId(const QString& id)
{
m_id = id;
}
QString QXmppStanza::lang() const
{
return m_lang;
}
void QXmppStanza::setLang(const QString& lang)
{
m_lang = lang;
}
QXmppStanza::Error QXmppStanza::error() const
{
return m_error;
}
void QXmppStanza::setError(QXmppStanza::Error& error)
{
m_error = error;
}
QXmppElementList QXmppStanza::extensions() const
{
return m_extensions;
}
void QXmppStanza::setExtensions(const QXmppElementList &extensions)
{
m_extensions = extensions;
}
void QXmppStanza::generateAndSetNextId()
{
// get back
++s_uniqeIdNo;
m_id = "qxmpp" + QString::number(s_uniqeIdNo);
}
bool QXmppStanza::isErrorStanza()
{
return m_error.isValid();
}
void QXmppStanza::parse(const QDomElement &element)
{
m_from = element.attribute("from");
m_to = element.attribute("to");
m_id = element.attribute("id");
m_lang = element.attribute("lang");
QDomElement errorElement = element.firstChildElement("error");
if(!errorElement.isNull())
m_error.parse(errorElement);
}
// deprecated
QString QXmppStanza::getTo() const
{
return m_to;
}
QString QXmppStanza::getFrom() const
{
return m_from;
}
QString QXmppStanza::getId() const
{
return m_id;
}
QString QXmppStanza::getLang() const
{
return m_lang;
}
QXmppStanza::Error QXmppStanza::getError() const
{
return m_error;
}
<commit_msg>cleanup QXmppStanza::Error API<commit_after>/*
* Copyright (C) 2008-2009 Manjeet Dahiya
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppStanza.h"
#include "QXmppUtils.h"
#include "QXmppConstants.h"
#include <QDomElement>
#include <QXmlStreamWriter>
uint QXmppStanza::s_uniqeIdNo = 0;
QXmppStanza::Error::Error():
m_code(0),
m_type(static_cast<QXmppStanza::Error::Type>(-1)),
m_condition(static_cast<QXmppStanza::Error::Condition>(-1)),
m_text("")
{
}
QXmppStanza::Error::Error(Type type, Condition cond, const QString& text):
m_code(0),
m_type(type),
m_condition(cond),
m_text(text)
{
}
QXmppStanza::Error::Error(const QString& type, const QString& cond,
const QString& text):
m_code(0),
m_text(text)
{
setTypeFromStr(type);
setConditionFromStr(cond);
}
QString QXmppStanza::Error::text() const
{
return m_text;
}
void QXmppStanza::Error::setText(const QString& text)
{
m_text = text;
}
int QXmppStanza::Error::code() const
{
return m_code;
}
void QXmppStanza::Error::setCode(int code)
{
m_code = code;
}
QXmppStanza::Error::Condition QXmppStanza::Error::condition() const
{
return m_condition;
}
void QXmppStanza::Error::setCondition(QXmppStanza::Error::Condition cond)
{
m_condition = cond;
}
QXmppStanza::Error::Type QXmppStanza::Error::type() const
{
return m_type;
}
void QXmppStanza::Error::setType(QXmppStanza::Error::Type type)
{
m_type = type;
}
QString QXmppStanza::Error::getTypeStr() const
{
switch(m_type)
{
case Cancel:
return "cancel";
case Continue:
return "continue";
case Modify:
return "modify";
case Auth:
return "auth";
case Wait:
return "wait";
default:
return "";
}
}
QString QXmppStanza::Error::getConditionStr() const
{
switch(m_condition)
{
case BadRequest:
return "bad-request";
case Conflict:
return "conflict";
case FeatureNotImplemented:
return "feature-not-implemented";
case Forbidden:
return "forbidden";
case Gone:
return "gone";
case InternalServerError:
return "internal-server-error";
case ItemNotFound:
return "item-not-found";
case JidMalformed:
return "jid-malformed";
case NotAcceptable:
return "not-acceptable";
case NotAllowed:
return "not-allowed";
case NotAuthorized:
return "not-authorized";
case PaymentRequired:
return "payment-required";
case RecipientUnavailable:
return "recipient-unavailable";
case Redirect:
return "redirect";
case RegistrationRequired:
return "registration-required";
case RemoteServerNotFound:
return "remote-server-not-found";
case RemoteServerTimeout:
return "remote-server-timeout";
case ResourceConstraint:
return "resource-constraint";
case ServiceUnavailable:
return "service-unavailable";
case SubscriptionRequired:
return "subscription-required";
case UndefinedCondition:
return "undefined-condition";
case UnexpectedRequest:
return "unexpected-request";
default:
return "";
}
}
void QXmppStanza::Error::setTypeFromStr(const QString& type)
{
if(type == "cancel")
setType(Cancel);
else if(type == "continue")
setType(Continue);
else if(type == "modify")
setType(Modify);
else if(type == "auth")
setType(Auth);
else if(type == "wait")
setType(Wait);
else
setType(static_cast<QXmppStanza::Error::Type>(-1));
}
void QXmppStanza::Error::setConditionFromStr(const QString& type)
{
if(type == "bad-request")
setCondition(BadRequest);
else if(type == "conflict")
setCondition(Conflict);
else if(type == "feature-not-implemented")
setCondition(FeatureNotImplemented);
else if(type == "forbidden")
setCondition(Forbidden);
else if(type == "gone")
setCondition(Gone);
else if(type == "internal-server-error")
setCondition(InternalServerError);
else if(type == "item-not-found")
setCondition(ItemNotFound);
else if(type == "jid-malformed")
setCondition(JidMalformed);
else if(type == "not-acceptable")
setCondition(NotAcceptable);
else if(type == "not-allowed")
setCondition(NotAllowed);
else if(type == "not-authorized")
setCondition(NotAuthorized);
else if(type == "payment-required")
setCondition(PaymentRequired);
else if(type == "recipient-unavailable")
setCondition(RecipientUnavailable);
else if(type == "redirect")
setCondition(Redirect);
else if(type == "registration-required")
setCondition(RegistrationRequired);
else if(type == "remote-server-not-found")
setCondition(RemoteServerNotFound);
else if(type == "remote-server-timeout")
setCondition(RemoteServerTimeout);
else if(type == "resource-constraint")
setCondition(ResourceConstraint);
else if(type == "service-unavailable")
setCondition(ServiceUnavailable);
else if(type == "subscription-required")
setCondition(SubscriptionRequired);
else if(type == "undefined-condition")
setCondition(UndefinedCondition);
else if(type == "unexpected-request")
setCondition(UnexpectedRequest);
else
setCondition(static_cast<QXmppStanza::Error::Condition>(-1));
}
bool QXmppStanza::Error::isValid()
{
return !(getTypeStr().isEmpty() && getConditionStr().isEmpty());
}
void QXmppStanza::Error::parse(const QDomElement &errorElement)
{
setCode(errorElement.attribute("code").toInt());
setTypeFromStr(errorElement.attribute("type"));
QString text;
QString cond;
QDomElement element = errorElement.firstChildElement();
while(!element.isNull())
{
if(element.tagName() == "text")
text = element.text();
else if(element.namespaceURI() == ns_stanza)
{
cond = element.tagName();
}
element = element.nextSiblingElement();
}
setConditionFromStr(cond);
setText(text);
}
void QXmppStanza::Error::toXml( QXmlStreamWriter *writer ) const
{
QString cond = getConditionStr();
QString type = getTypeStr();
if(cond.isEmpty() && type.isEmpty())
return;
writer->writeStartElement("error");
helperToXmlAddAttribute(writer, "type", type);
if (m_code > 0)
helperToXmlAddAttribute(writer, "code", QString::number(m_code));
if(!cond.isEmpty())
{
writer->writeStartElement(cond);
helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
writer->writeEndElement();
}
if(!m_text.isEmpty())
{
writer->writeStartElement("text");
helperToXmlAddAttribute(writer,"xml:lang", "en");
helperToXmlAddAttribute(writer,"xmlns", ns_stanza);
writer->writeCharacters(m_text);
writer->writeEndElement();
}
writer->writeEndElement();
}
QXmppStanza::QXmppStanza(const QString& from, const QString& to) : QXmppPacket(),
m_to(to), m_from(from)
{
}
QXmppStanza::~QXmppStanza()
{
}
QString QXmppStanza::to() const
{
return m_to;
}
void QXmppStanza::setTo(const QString& to)
{
m_to = to;
}
QString QXmppStanza::from() const
{
return m_from;
}
void QXmppStanza::setFrom(const QString& from)
{
m_from = from;
}
QString QXmppStanza::id() const
{
return m_id;
}
void QXmppStanza::setId(const QString& id)
{
m_id = id;
}
QString QXmppStanza::lang() const
{
return m_lang;
}
void QXmppStanza::setLang(const QString& lang)
{
m_lang = lang;
}
QXmppStanza::Error QXmppStanza::error() const
{
return m_error;
}
void QXmppStanza::setError(QXmppStanza::Error& error)
{
m_error = error;
}
QXmppElementList QXmppStanza::extensions() const
{
return m_extensions;
}
void QXmppStanza::setExtensions(const QXmppElementList &extensions)
{
m_extensions = extensions;
}
void QXmppStanza::generateAndSetNextId()
{
// get back
++s_uniqeIdNo;
m_id = "qxmpp" + QString::number(s_uniqeIdNo);
}
bool QXmppStanza::isErrorStanza()
{
return m_error.isValid();
}
void QXmppStanza::parse(const QDomElement &element)
{
m_from = element.attribute("from");
m_to = element.attribute("to");
m_id = element.attribute("id");
m_lang = element.attribute("lang");
QDomElement errorElement = element.firstChildElement("error");
if(!errorElement.isNull())
m_error.parse(errorElement);
}
// deprecated
QString QXmppStanza::Error::getText() const
{
return m_text;
}
int QXmppStanza::Error::getCode() const
{
return m_code;
}
QXmppStanza::Error::Condition QXmppStanza::Error::getCondition() const
{
return m_condition;
}
QXmppStanza::Error::Type QXmppStanza::Error::getType() const
{
return m_type;
}
QString QXmppStanza::getTo() const
{
return m_to;
}
QString QXmppStanza::getFrom() const
{
return m_from;
}
QString QXmppStanza::getId() const
{
return m_id;
}
QString QXmppStanza::getLang() const
{
return m_lang;
}
QXmppStanza::Error QXmppStanza::getError() const
{
return m_error;
}
<|endoftext|> |
<commit_before><commit_msg>Change the Linux sad tab message wrapping to match Windows.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2008, Google 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 Google 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 "client/windows/crash_generation/minidump_generator.h"
#include <cassert>
#include "client/windows/common/auto_critical_section.h"
#include "common/windows/guid_string.h"
using std::wstring;
namespace google_breakpad {
MinidumpGenerator::MinidumpGenerator(const wstring& dump_path)
: dbghelp_module_(NULL),
rpcrt4_module_(NULL),
dump_path_(dump_path),
write_dump_(NULL),
create_uuid_(NULL) {
InitializeCriticalSection(&module_load_sync_);
InitializeCriticalSection(&get_proc_address_sync_);
}
MinidumpGenerator::~MinidumpGenerator() {
if (dbghelp_module_) {
FreeLibrary(dbghelp_module_);
}
if (rpcrt4_module_) {
FreeLibrary(rpcrt4_module_);
}
DeleteCriticalSection(&get_proc_address_sync_);
DeleteCriticalSection(&module_load_sync_);
}
bool MinidumpGenerator::WriteMinidump(HANDLE process_handle,
DWORD process_id,
DWORD thread_id,
DWORD requesting_thread_id,
EXCEPTION_POINTERS* exception_pointers,
MDRawAssertionInfo* assert_info,
MINIDUMP_TYPE dump_type,
bool is_client_pointers,
wstring* dump_path) {
MiniDumpWriteDumpType write_dump = GetWriteDump();
if (!write_dump) {
return false;
}
wstring dump_file_path;
if (!GenerateDumpFilePath(&dump_file_path)) {
return false;
}
HANDLE dump_file = CreateFile(dump_file_path.c_str(),
GENERIC_WRITE,
0,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (dump_file == INVALID_HANDLE_VALUE) {
return false;
}
MINIDUMP_EXCEPTION_INFORMATION* dump_exception_pointers = NULL;
MINIDUMP_EXCEPTION_INFORMATION dump_exception_info;
// Setup the exception information object only if it's a dump
// due to an exception.
if (exception_pointers) {
dump_exception_pointers = &dump_exception_info;
dump_exception_info.ThreadId = thread_id;
dump_exception_info.ExceptionPointers = exception_pointers;
dump_exception_info.ClientPointers = is_client_pointers;
}
// Add an MDRawBreakpadInfo stream to the minidump, to provide additional
// information about the exception handler to the Breakpad processor.
// The information will help the processor determine which threads are
// relevant. The Breakpad processor does not require this information but
// can function better with Breakpad-generated dumps when it is present.
// The native debugger is not harmed by the presence of this information.
MDRawBreakpadInfo breakpad_info;
breakpad_info.validity = MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID |
MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID;
breakpad_info.dump_thread_id = thread_id;
breakpad_info.requesting_thread_id = requesting_thread_id;
// Leave room in user_stream_array for a possible assertion info stream.
MINIDUMP_USER_STREAM user_stream_array[2];
user_stream_array[0].Type = MD_BREAKPAD_INFO_STREAM;
user_stream_array[0].BufferSize = sizeof(breakpad_info);
user_stream_array[0].Buffer = &breakpad_info;
MINIDUMP_USER_STREAM_INFORMATION user_streams;
user_streams.UserStreamCount = 1;
user_streams.UserStreamArray = user_stream_array;
MDRawAssertionInfo* actual_assert_info = assert_info;
MDRawAssertionInfo client_assert_info = {0};
if (assert_info) {
// If the assertion info object lives in the client process,
// read the memory of the client process.
if (is_client_pointers) {
SIZE_T bytes_read = 0;
if (!ReadProcessMemory(process_handle,
assert_info,
&client_assert_info,
sizeof(client_assert_info),
&bytes_read)) {
CloseHandle(dump_file);
return false;
}
if (bytes_read != sizeof(client_assert_info)) {
CloseHandle(dump_file);
return false;
}
actual_assert_info = &client_assert_info;
}
user_stream_array[1].Type = MD_ASSERTION_INFO_STREAM;
user_stream_array[1].BufferSize = sizeof(MDRawAssertionInfo);
user_stream_array[1].Buffer = actual_assert_info;
++user_streams.UserStreamCount;
}
bool result = write_dump(process_handle,
process_id,
dump_file,
dump_type,
exception_pointers ? &dump_exception_info : NULL,
&user_streams,
NULL) != FALSE;
CloseHandle(dump_file);
// Store the path of the dump file in the out parameter if dump generation
// succeeded.
if (result && dump_path) {
*dump_path = dump_file_path;
}
return result;
}
HMODULE MinidumpGenerator::GetDbghelpModule() {
AutoCriticalSection lock(&module_load_sync_);
if (!dbghelp_module_) {
dbghelp_module_ = LoadLibrary(TEXT("dbghelp.dll"));
}
return dbghelp_module_;
}
MinidumpGenerator::MiniDumpWriteDumpType MinidumpGenerator::GetWriteDump() {
AutoCriticalSection lock(&get_proc_address_sync_);
if (!write_dump_) {
HMODULE module = GetDbghelpModule();
if (module) {
FARPROC proc = GetProcAddress(module, "MiniDumpWriteDump");
write_dump_ = reinterpret_cast<MiniDumpWriteDumpType>(proc);
}
}
return write_dump_;
}
HMODULE MinidumpGenerator::GetRpcrt4Module() {
AutoCriticalSection lock(&module_load_sync_);
if (!rpcrt4_module_) {
rpcrt4_module_ = LoadLibrary(TEXT("rpcrt4.dll"));
}
return rpcrt4_module_;
}
MinidumpGenerator::UuidCreateType MinidumpGenerator::GetCreateUuid() {
AutoCriticalSection lock(&module_load_sync_);
if (!create_uuid_) {
HMODULE module = GetRpcrt4Module();
if (module) {
FARPROC proc = GetProcAddress(module, "UuidCreate");
create_uuid_ = reinterpret_cast<UuidCreateType>(proc);
}
}
return create_uuid_;
}
bool MinidumpGenerator::GenerateDumpFilePath(wstring* file_path) {
UUID id = {0};
UuidCreateType create_uuid = GetCreateUuid();
if(!create_uuid) {
return false;
}
create_uuid(&id);
wstring id_str = GUIDString::GUIDToWString(&id);
*file_path = dump_path_ + TEXT("\\") + id_str + TEXT(".dmp");
return true;
}
} // namespace google_breakpad
<commit_msg><commit_after>// Copyright (c) 2008, Google 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 Google 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 "client/windows/crash_generation/minidump_generator.h"
#include <cassert>
#include "client/windows/common/auto_critical_section.h"
#include "common/windows/guid_string.h"
using std::wstring;
namespace google_breakpad {
MinidumpGenerator::MinidumpGenerator(const wstring& dump_path)
: dbghelp_module_(NULL),
rpcrt4_module_(NULL),
dump_path_(dump_path),
write_dump_(NULL),
create_uuid_(NULL) {
InitializeCriticalSection(&module_load_sync_);
InitializeCriticalSection(&get_proc_address_sync_);
}
MinidumpGenerator::~MinidumpGenerator() {
if (dbghelp_module_) {
FreeLibrary(dbghelp_module_);
}
if (rpcrt4_module_) {
FreeLibrary(rpcrt4_module_);
}
DeleteCriticalSection(&get_proc_address_sync_);
DeleteCriticalSection(&module_load_sync_);
}
bool MinidumpGenerator::WriteMinidump(HANDLE process_handle,
DWORD process_id,
DWORD thread_id,
DWORD requesting_thread_id,
EXCEPTION_POINTERS* exception_pointers,
MDRawAssertionInfo* assert_info,
MINIDUMP_TYPE dump_type,
bool is_client_pointers,
wstring* dump_path) {
MiniDumpWriteDumpType write_dump = GetWriteDump();
if (!write_dump) {
return false;
}
wstring dump_file_path;
if (!GenerateDumpFilePath(&dump_file_path)) {
return false;
}
HANDLE dump_file = CreateFile(dump_file_path.c_str(),
GENERIC_WRITE,
0,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (dump_file == INVALID_HANDLE_VALUE) {
return false;
}
MINIDUMP_EXCEPTION_INFORMATION* dump_exception_pointers = NULL;
MINIDUMP_EXCEPTION_INFORMATION dump_exception_info;
// Setup the exception information object only if it's a dump
// due to an exception.
if (exception_pointers) {
dump_exception_pointers = &dump_exception_info;
dump_exception_info.ThreadId = thread_id;
dump_exception_info.ExceptionPointers = exception_pointers;
dump_exception_info.ClientPointers = is_client_pointers;
}
// Add an MDRawBreakpadInfo stream to the minidump, to provide additional
// information about the exception handler to the Breakpad processor.
// The information will help the processor determine which threads are
// relevant. The Breakpad processor does not require this information but
// can function better with Breakpad-generated dumps when it is present.
// The native debugger is not harmed by the presence of this information.
MDRawBreakpadInfo breakpad_info = {0};
if (!is_client_pointers) {
// Set the dump thread id and requesting thread id only in case of
// in-process dump generation.
breakpad_info.validity = MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID |
MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID;
breakpad_info.dump_thread_id = thread_id;
breakpad_info.requesting_thread_id = requesting_thread_id;
}
// Leave room in user_stream_array for a possible assertion info stream.
MINIDUMP_USER_STREAM user_stream_array[2];
user_stream_array[0].Type = MD_BREAKPAD_INFO_STREAM;
user_stream_array[0].BufferSize = sizeof(breakpad_info);
user_stream_array[0].Buffer = &breakpad_info;
MINIDUMP_USER_STREAM_INFORMATION user_streams;
user_streams.UserStreamCount = 1;
user_streams.UserStreamArray = user_stream_array;
MDRawAssertionInfo* actual_assert_info = assert_info;
MDRawAssertionInfo client_assert_info = {0};
if (assert_info) {
// If the assertion info object lives in the client process,
// read the memory of the client process.
if (is_client_pointers) {
SIZE_T bytes_read = 0;
if (!ReadProcessMemory(process_handle,
assert_info,
&client_assert_info,
sizeof(client_assert_info),
&bytes_read)) {
CloseHandle(dump_file);
return false;
}
if (bytes_read != sizeof(client_assert_info)) {
CloseHandle(dump_file);
return false;
}
actual_assert_info = &client_assert_info;
}
user_stream_array[1].Type = MD_ASSERTION_INFO_STREAM;
user_stream_array[1].BufferSize = sizeof(MDRawAssertionInfo);
user_stream_array[1].Buffer = actual_assert_info;
++user_streams.UserStreamCount;
}
bool result = write_dump(process_handle,
process_id,
dump_file,
dump_type,
exception_pointers ? &dump_exception_info : NULL,
&user_streams,
NULL) != FALSE;
CloseHandle(dump_file);
// Store the path of the dump file in the out parameter if dump generation
// succeeded.
if (result && dump_path) {
*dump_path = dump_file_path;
}
return result;
}
HMODULE MinidumpGenerator::GetDbghelpModule() {
AutoCriticalSection lock(&module_load_sync_);
if (!dbghelp_module_) {
dbghelp_module_ = LoadLibrary(TEXT("dbghelp.dll"));
}
return dbghelp_module_;
}
MinidumpGenerator::MiniDumpWriteDumpType MinidumpGenerator::GetWriteDump() {
AutoCriticalSection lock(&get_proc_address_sync_);
if (!write_dump_) {
HMODULE module = GetDbghelpModule();
if (module) {
FARPROC proc = GetProcAddress(module, "MiniDumpWriteDump");
write_dump_ = reinterpret_cast<MiniDumpWriteDumpType>(proc);
}
}
return write_dump_;
}
HMODULE MinidumpGenerator::GetRpcrt4Module() {
AutoCriticalSection lock(&module_load_sync_);
if (!rpcrt4_module_) {
rpcrt4_module_ = LoadLibrary(TEXT("rpcrt4.dll"));
}
return rpcrt4_module_;
}
MinidumpGenerator::UuidCreateType MinidumpGenerator::GetCreateUuid() {
AutoCriticalSection lock(&module_load_sync_);
if (!create_uuid_) {
HMODULE module = GetRpcrt4Module();
if (module) {
FARPROC proc = GetProcAddress(module, "UuidCreate");
create_uuid_ = reinterpret_cast<UuidCreateType>(proc);
}
}
return create_uuid_;
}
bool MinidumpGenerator::GenerateDumpFilePath(wstring* file_path) {
UUID id = {0};
UuidCreateType create_uuid = GetCreateUuid();
if(!create_uuid) {
return false;
}
create_uuid(&id);
wstring id_str = GUIDString::GUIDToWString(&id);
*file_path = dump_path_ + TEXT("\\") + id_str + TEXT(".dmp");
return true;
}
} // namespace google_breakpad
<|endoftext|> |
<commit_before><commit_msg>Prediction: implement build adc trajectory<commit_after><|endoftext|> |
<commit_before>#include "StdAfx.h"
#include "DngDecoderSlices.h"
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
http://www.klauspost.com
*/
namespace RawSpeed {
void *DecodeThread(void *_this) {
DngDecoderThread* me = (DngDecoderThread*)_this;
DngDecoderSlices* parent = me->parent;
try {
parent->decodeSlice(me);
} catch (...) {
parent->setError("DNGDEcodeThread: Caught exception.");
}
pthread_exit(NULL);
return NULL;
}
DngDecoderSlices::DngDecoderSlices(FileMap* file, RawImage img) :
mFile(file), mRaw(img) {
mFixLjpeg = false;
#ifdef WIN32
nThreads = pthread_num_processors_np();
#else
nThreads = 2; // FIXME: Port this to unix
#endif
}
DngDecoderSlices::~DngDecoderSlices(void) {
}
void DngDecoderSlices::addSlice(DngSliceElement slice) {
slices.push(slice);
}
void DngDecoderSlices::startDecoding() {
// Create threads
int slicesPerThread = ((int)slices.size() + nThreads - 1) / nThreads;
// decodedSlices = 0;
pthread_attr_t attr;
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&errMutex, NULL);
for (guint i = 0; i < nThreads; i++) {
DngDecoderThread* t = new DngDecoderThread();
for (int j = 0; j < slicesPerThread ; j++) {
if (!slices.empty()) {
t->slices.push(slices.front());
slices.pop();
}
}
t->parent = this;
pthread_create(&t->threadid, &attr, DecodeThread, t);
threads.push_back(t);
}
pthread_attr_destroy(&attr);
void *status;
for (guint i = 0; i < nThreads; i++) {
pthread_join(threads[i]->threadid, &status);
delete(threads[i]);
}
pthread_mutex_destroy(&errMutex);
}
void DngDecoderSlices::decodeSlice(DngDecoderThread* t) {
while (!t->slices.empty()) {
LJpegPlain l(mFile, mRaw);
l.mDNGCompatible = mFixLjpeg;
l.mUseBigtable = false;
DngSliceElement e = t->slices.front();
t->slices.pop();
try {
l.startDecoder(e.byteOffset, e.byteCount, e.offX, e.offY);
} catch (RawDecoderException err) {
setError(err.what());
} catch (IOException err) {
setError("DngDecoderSlices::decodeSlice: IO error occurred.");
}
}
}
int DngDecoderSlices::size() {
return (int)slices.size();
}
void DngDecoderSlices::setError( const char* err )
{
pthread_mutex_lock(&errMutex);
errors.push_back(_strdup(err));
pthread_mutex_unlock(&errMutex);
}
} // namespace RawSpeed
<commit_msg>Properly propagate Bigtable usage on DNG Slices.<commit_after>#include "StdAfx.h"
#include "DngDecoderSlices.h"
/*
RawSpeed - RAW file decoder.
Copyright (C) 2009 Klaus Post
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
http://www.klauspost.com
*/
namespace RawSpeed {
void *DecodeThread(void *_this) {
DngDecoderThread* me = (DngDecoderThread*)_this;
DngDecoderSlices* parent = me->parent;
try {
parent->decodeSlice(me);
} catch (...) {
parent->setError("DNGDEcodeThread: Caught exception.");
}
pthread_exit(NULL);
return NULL;
}
DngDecoderSlices::DngDecoderSlices(FileMap* file, RawImage img) :
mFile(file), mRaw(img) {
mFixLjpeg = false;
#ifdef WIN32
nThreads = pthread_num_processors_np();
#else
nThreads = 2; // FIXME: Port this to unix
#endif
}
DngDecoderSlices::~DngDecoderSlices(void) {
}
void DngDecoderSlices::addSlice(DngSliceElement slice) {
slices.push(slice);
}
void DngDecoderSlices::startDecoding() {
// Create threads
int slicesPerThread = ((int)slices.size() + nThreads - 1) / nThreads;
// decodedSlices = 0;
pthread_attr_t attr;
/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&errMutex, NULL);
for (guint i = 0; i < nThreads; i++) {
DngDecoderThread* t = new DngDecoderThread();
for (int j = 0; j < slicesPerThread ; j++) {
if (!slices.empty()) {
t->slices.push(slices.front());
slices.pop();
}
}
t->parent = this;
pthread_create(&t->threadid, &attr, DecodeThread, t);
threads.push_back(t);
}
pthread_attr_destroy(&attr);
void *status;
for (guint i = 0; i < nThreads; i++) {
pthread_join(threads[i]->threadid, &status);
delete(threads[i]);
}
pthread_mutex_destroy(&errMutex);
}
void DngDecoderSlices::decodeSlice(DngDecoderThread* t) {
while (!t->slices.empty()) {
LJpegPlain l(mFile, mRaw);
l.mDNGCompatible = mFixLjpeg;
DngSliceElement e = t->slices.front();
l.mUseBigtable = e.mUseBigtable;
t->slices.pop();
try {
l.startDecoder(e.byteOffset, e.byteCount, e.offX, e.offY);
} catch (RawDecoderException err) {
setError(err.what());
} catch (IOException err) {
setError("DngDecoderSlices::decodeSlice: IO error occurred.");
}
}
}
int DngDecoderSlices::size() {
return (int)slices.size();
}
void DngDecoderSlices::setError( const char* err )
{
pthread_mutex_lock(&errMutex);
errors.push_back(_strdup(err));
pthread_mutex_unlock(&errMutex);
}
} // namespace RawSpeed
<|endoftext|> |
<commit_before>#include "itkCommandLineArgumentParser.h"
#include "itkImage.h"
#include "itkPoint.h"
#include "itkLandmarkBasedTransformInitializer.h"
#include "itkVersorRigid3DTransform.h"
#include "vnl/vnl_math.h"
#include <iostream>
#include <fstream>
#include <iomanip>
//-------------------------------------------------------------------------------------
void PrintHelp( void );
void ComputeClosestVersor(
std::string fixedLandmarkFileName,
std::string movingLandmarkFileName,
std::vector<double> & parameters,
std::vector<double> & centerOfRotation );
void ReadLandmarks(
std::string landmarkFileName,
std::vector< itk::Point<double,3> > & landmarkContainer );
void ConvertVersorToEuler(
const std::vector<double> & parVersor,
std::vector<double> & parEuler );
//-------------------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
/** Check arguments for help. */
if ( argc < 5 || argc > 5 )
{
PrintHelp();
return 1;
}
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
/** Get arguments. */
std::string fixedLandmarkFileName = "";
bool retf = parser->GetCommandLineArgument( "-f", fixedLandmarkFileName );
std::string movingLandmarkFileName = "";
bool retm = parser->GetCommandLineArgument( "-m", movingLandmarkFileName );
/** Check if the required arguments are given. */
if ( !retf )
{
std::cerr << "ERROR: You should specify \"-f\"." << std::endl;
return 1;
}
if ( !retm )
{
std::cerr << "ERROR: You should specify \"-m\"." << std::endl;
return 1;
}
/** Compute the closest rigid transformation. */
std::vector<double> parVersor, centerOfRotation;
try
{
ComputeClosestVersor(
fixedLandmarkFileName, movingLandmarkFileName,
parVersor, centerOfRotation );
}
catch( itk::ExceptionObject &excp )
{
std::cerr << "Caught ITK exception: " << excp << std::endl;
return 1;
}
/** Convert from versor to Euler angles. */
std::vector<double> parEuler;
ConvertVersorToEuler( parVersor, parEuler );
/** Print. */
std::cout << std::fixed;
std::cout << std::showpoint;
std::cout << std::setprecision( 6 );
unsigned int nop = parVersor.size();
std::cout << "versor: ";
for ( unsigned int i = 0; i < nop - 1; i++ )
{
std::cout << parVersor[ i ] << " ";
}
std::cout << parVersor[ nop - 1 ] << std::endl;
std::cout << "Euler: ";
for ( unsigned int i = 0; i < nop - 1; i++ )
{
std::cout << parEuler[ i ] << " ";
}
std::cout << parEuler[ nop - 1 ] << std::endl;
std::cout << "center of rotation: ";
for ( unsigned int i = 0; i < 2; i++ )
{
std::cout << centerOfRotation[ i ] << " ";
}
std::cout << centerOfRotation[ 2 ] << std::endl;
/** End program. */
return 0;
} // end main
/**
* ******************* ComputeClosestVersor *******************
*/
void ComputeClosestVersor(
std::string fixedLandmarkFileName,
std::string movingLandmarkFileName,
std::vector<double> & parameters,
std::vector<double> & centerOfRotation )
{
/** Some consts. */
const unsigned int Dimension = 3;
typedef short PixelType;
/** Typedefs. */
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::VersorRigid3DTransform< double > TransformType;
typedef TransformType::ParametersType ParametersType;
typedef TransformType::CenterType CenterType;
typedef itk::LandmarkBasedTransformInitializer<
TransformType, ImageType, ImageType > EstimatorType;
typedef EstimatorType::LandmarkPointType LandmarkType;
typedef EstimatorType::LandmarkPointContainer LandmarkContainer;
/** Read the fixed landmark points. */
LandmarkContainer fixedLandmarkContainer;
ReadLandmarks( fixedLandmarkFileName, fixedLandmarkContainer );
/** Read the moving landmark points. */
LandmarkContainer movingLandmarkContainer;
ReadLandmarks( movingLandmarkFileName, movingLandmarkContainer );
/** Check the sizes. */
if ( fixedLandmarkContainer.size() != movingLandmarkContainer.size() )
{
std::cerr << "ERROR: the two sets of landmarks are not of the same size." << std::endl;
return;
}
/** Create transform. */
TransformType::Pointer transform = TransformType::New();
transform->SetIdentity();
/** Create estimator. */
EstimatorType::Pointer estimator = EstimatorType::New();
estimator->SetTransform( transform );
estimator->SetFixedLandmarks( fixedLandmarkContainer );
estimator->SetMovingLandmarks( movingLandmarkContainer );
/** Run. */
estimator->InitializeTransform();
/** Get the parameters of the estimated closest rigid transformation. */
ParametersType params = transform->GetParameters();
unsigned int nop = transform->GetNumberOfParameters();
parameters.resize( nop, 0.0 );
for ( unsigned int i = 0; i < nop; ++i )
{
parameters[ i ] = params[ i ];
}
/** Get the estimated center of rotation. */
CenterType center = transform->GetCenter();
centerOfRotation.resize( Dimension, 0.0 );
for ( unsigned int i = 0; i < Dimension; ++i )
{
centerOfRotation[ i ] = center[ i ];
}
} // end ComputeClosestVersor()
/**
* ******************* ReadLandmarks *******************
*/
void ReadLandmarks(
std::string landmarkFileName,
std::vector< itk::Point<double,3> > & landmarkContainer )
{
/** Typedef's. */
const unsigned int Dimension = 3;
typedef itk::Image< short, Dimension > ImageType;
typedef itk::VersorRigid3DTransform< double > TransformType;
typedef TransformType::ParametersType ParametersType;
typedef itk::LandmarkBasedTransformInitializer<
TransformType, ImageType, ImageType > EstimatorType;
typedef EstimatorType::LandmarkPointType LandmarkType;
typedef EstimatorType::LandmarkPointContainer LandmarkContainer;
/** Open file for reading and read landmarks. */
std::ifstream landmarkFile( landmarkFileName.c_str() );
if ( landmarkFile.is_open() )
{
LandmarkType landmark;
while ( !landmarkFile.eof() )
{
for ( unsigned int i = 0; i < Dimension; i++ )
{
landmarkFile >> landmark[ i ];
}
landmarkContainer.push_back( landmark );
}
}
landmarkFile.close();
landmarkContainer.pop_back();
} // end ReadLandMarks()
/**
* ******************* ConvertVersorToEuler *******************
*/
void ConvertVersorToEuler(
const std::vector<double> & parVersor,
std::vector<double> & parEuler )
{
/** Create an Euler parameter vector. */
unsigned int nop = parVersor.size();
if ( nop != 6 ) return;
parEuler.resize( nop, 0.0 );
/** Easy notation. */
double q0 = vcl_sqrt( 1.0 - parVersor[ 0 ] * parVersor[ 0 ]
- parVersor[ 1 ] * parVersor[ 1 ] - parVersor[ 2 ] * parVersor[ 2 ] );
double q1 = parVersor[ 0 ];
double q2 = parVersor[ 1 ];
double q3 = parVersor[ 2 ];
/** Computer Euler angles. */
parEuler[ 0 ] = vcl_atan2( 2.0 * ( q0 * q1 + q2 * q3 ), 1.0 - 2.0 * ( q1 * q1 + q2 * q2 ) );
parEuler[ 1 ] = vcl_asin( 2.0 * ( q0 * q2 - q3 * q1 ) );
parEuler[ 2 ] = vcl_atan2( 2.0 * ( q0 * q3 + q1 * q2 ), 1.0 - 2.0 * ( q2 * q2 + q3 * q3 ) );
parEuler[ 3 ] = parVersor[ 3 ];
parEuler[ 4 ] = parVersor[ 4 ];
parEuler[ 5 ] = parVersor[ 5 ];
} // end ConvertVersorToEuler()
/**
* ******************* PrintHelp *******************
*/
void PrintHelp( void )
{
std::cout << "Calculates the closest rigid transform (VersorRigid3D) between" << std::endl;
std::cout << "two sets of landmarks. The two sets should be of equal size." << std::endl;
std::cout << "Usage:" << std::endl << "pxclosestversor3Dtransform" << std::endl;
std::cout << " -f the file containing the fixed landmarks" << std::endl;
std::cout << " -m the file containing the moving landmarks" << std::endl;
} // end PrintHelp()
<commit_msg>New style arguments for closestversor3Dtransform<commit_after>#include "itkCommandLineArgumentParser.h"
#include "itkImage.h"
#include "itkPoint.h"
#include "itkLandmarkBasedTransformInitializer.h"
#include "itkVersorRigid3DTransform.h"
#include "vnl/vnl_math.h"
#include <iostream>
#include <fstream>
#include <iomanip>
//-------------------------------------------------------------------------------------
std::string PrintHelp( void );
void ComputeClosestVersor(
std::string fixedLandmarkFileName,
std::string movingLandmarkFileName,
std::vector<double> & parameters,
std::vector<double> & centerOfRotation );
void ReadLandmarks(
std::string landmarkFileName,
std::vector< itk::Point<double,3> > & landmarkContainer );
void ConvertVersorToEuler(
const std::vector<double> & parVersor,
std::vector<double> & parEuler );
//-------------------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
/** Create a command line argument parser. */
itk::CommandLineArgumentParser::Pointer parser = itk::CommandLineArgumentParser::New();
parser->SetCommandLineArguments( argc, argv );
parser->SetProgramHelpText(PrintHelp());
parser->MarkArgumentAsRequired( "-f", "The fixed landmark filename." );
parser->MarkArgumentAsRequired( "-m", "The moving landmark filename." );
/** Get arguments. */
std::string fixedLandmarkFileName = "";
parser->GetCommandLineArgument( "-f", fixedLandmarkFileName );
std::string movingLandmarkFileName = "";
parser->GetCommandLineArgument( "-m", movingLandmarkFileName );
bool validateArguments = parser->CheckForRequiredArguments();
if(!validateArguments)
{
return EXIT_FAILURE;
}
/** Compute the closest rigid transformation. */
std::vector<double> parVersor, centerOfRotation;
try
{
ComputeClosestVersor(
fixedLandmarkFileName, movingLandmarkFileName,
parVersor, centerOfRotation );
}
catch( itk::ExceptionObject &excp )
{
std::cerr << "Caught ITK exception: " << excp << std::endl;
return 1;
}
/** Convert from versor to Euler angles. */
std::vector<double> parEuler;
ConvertVersorToEuler( parVersor, parEuler );
/** Print. */
std::cout << std::fixed;
std::cout << std::showpoint;
std::cout << std::setprecision( 6 );
unsigned int nop = parVersor.size();
std::cout << "versor: ";
for ( unsigned int i = 0; i < nop - 1; i++ )
{
std::cout << parVersor[ i ] << " ";
}
std::cout << parVersor[ nop - 1 ] << std::endl;
std::cout << "Euler: ";
for ( unsigned int i = 0; i < nop - 1; i++ )
{
std::cout << parEuler[ i ] << " ";
}
std::cout << parEuler[ nop - 1 ] << std::endl;
std::cout << "center of rotation: ";
for ( unsigned int i = 0; i < 2; i++ )
{
std::cout << centerOfRotation[ i ] << " ";
}
std::cout << centerOfRotation[ 2 ] << std::endl;
/** End program. */
return 0;
} // end main
/**
* ******************* ComputeClosestVersor *******************
*/
void ComputeClosestVersor(
std::string fixedLandmarkFileName,
std::string movingLandmarkFileName,
std::vector<double> & parameters,
std::vector<double> & centerOfRotation )
{
/** Some consts. */
const unsigned int Dimension = 3;
typedef short PixelType;
/** Typedefs. */
typedef itk::Image< PixelType, Dimension > ImageType;
typedef itk::VersorRigid3DTransform< double > TransformType;
typedef TransformType::ParametersType ParametersType;
typedef TransformType::CenterType CenterType;
typedef itk::LandmarkBasedTransformInitializer<
TransformType, ImageType, ImageType > EstimatorType;
typedef EstimatorType::LandmarkPointType LandmarkType;
typedef EstimatorType::LandmarkPointContainer LandmarkContainer;
/** Read the fixed landmark points. */
LandmarkContainer fixedLandmarkContainer;
ReadLandmarks( fixedLandmarkFileName, fixedLandmarkContainer );
/** Read the moving landmark points. */
LandmarkContainer movingLandmarkContainer;
ReadLandmarks( movingLandmarkFileName, movingLandmarkContainer );
/** Check the sizes. */
if ( fixedLandmarkContainer.size() != movingLandmarkContainer.size() )
{
std::cerr << "ERROR: the two sets of landmarks are not of the same size." << std::endl;
return;
}
/** Create transform. */
TransformType::Pointer transform = TransformType::New();
transform->SetIdentity();
/** Create estimator. */
EstimatorType::Pointer estimator = EstimatorType::New();
estimator->SetTransform( transform );
estimator->SetFixedLandmarks( fixedLandmarkContainer );
estimator->SetMovingLandmarks( movingLandmarkContainer );
/** Run. */
estimator->InitializeTransform();
/** Get the parameters of the estimated closest rigid transformation. */
ParametersType params = transform->GetParameters();
unsigned int nop = transform->GetNumberOfParameters();
parameters.resize( nop, 0.0 );
for ( unsigned int i = 0; i < nop; ++i )
{
parameters[ i ] = params[ i ];
}
/** Get the estimated center of rotation. */
CenterType center = transform->GetCenter();
centerOfRotation.resize( Dimension, 0.0 );
for ( unsigned int i = 0; i < Dimension; ++i )
{
centerOfRotation[ i ] = center[ i ];
}
} // end ComputeClosestVersor()
/**
* ******************* ReadLandmarks *******************
*/
void ReadLandmarks(
std::string landmarkFileName,
std::vector< itk::Point<double,3> > & landmarkContainer )
{
/** Typedef's. */
const unsigned int Dimension = 3;
typedef itk::Image< short, Dimension > ImageType;
typedef itk::VersorRigid3DTransform< double > TransformType;
typedef TransformType::ParametersType ParametersType;
typedef itk::LandmarkBasedTransformInitializer<
TransformType, ImageType, ImageType > EstimatorType;
typedef EstimatorType::LandmarkPointType LandmarkType;
typedef EstimatorType::LandmarkPointContainer LandmarkContainer;
/** Open file for reading and read landmarks. */
std::ifstream landmarkFile( landmarkFileName.c_str() );
if ( landmarkFile.is_open() )
{
LandmarkType landmark;
while ( !landmarkFile.eof() )
{
for ( unsigned int i = 0; i < Dimension; i++ )
{
landmarkFile >> landmark[ i ];
}
landmarkContainer.push_back( landmark );
}
}
landmarkFile.close();
landmarkContainer.pop_back();
} // end ReadLandMarks()
/**
* ******************* ConvertVersorToEuler *******************
*/
void ConvertVersorToEuler(
const std::vector<double> & parVersor,
std::vector<double> & parEuler )
{
/** Create an Euler parameter vector. */
unsigned int nop = parVersor.size();
if ( nop != 6 ) return;
parEuler.resize( nop, 0.0 );
/** Easy notation. */
double q0 = vcl_sqrt( 1.0 - parVersor[ 0 ] * parVersor[ 0 ]
- parVersor[ 1 ] * parVersor[ 1 ] - parVersor[ 2 ] * parVersor[ 2 ] );
double q1 = parVersor[ 0 ];
double q2 = parVersor[ 1 ];
double q3 = parVersor[ 2 ];
/** Computer Euler angles. */
parEuler[ 0 ] = vcl_atan2( 2.0 * ( q0 * q1 + q2 * q3 ), 1.0 - 2.0 * ( q1 * q1 + q2 * q2 ) );
parEuler[ 1 ] = vcl_asin( 2.0 * ( q0 * q2 - q3 * q1 ) );
parEuler[ 2 ] = vcl_atan2( 2.0 * ( q0 * q3 + q1 * q2 ), 1.0 - 2.0 * ( q2 * q2 + q3 * q3 ) );
parEuler[ 3 ] = parVersor[ 3 ];
parEuler[ 4 ] = parVersor[ 4 ];
parEuler[ 5 ] = parVersor[ 5 ];
} // end ConvertVersorToEuler()
/**
* ******************* PrintHelp *******************
*/
std::string PrintHelp( void )
{
std::string helpString = "Calculates the closest rigid transform (VersorRigid3D) between \
two sets of landmarks. The two sets should be of equal size. \
Usage:\n \
pxclosestversor3Dtransform \
-f the file containing the fixed landmarks \
-m the file containing the moving landmarks";
return helpString;
} // end PrintHelp()
<|endoftext|> |
<commit_before>#include "errors.hpp"
#include <boost/variant.hpp>
#include "clustering/immediate_consistency/branch/backfillee.hpp"
#include "clustering/immediate_consistency/branch/history.hpp"
#include "concurrency/coro_pool.hpp"
#include "concurrency/promise.hpp"
#include "concurrency/queue/unlimited_fifo.hpp"
#include "containers/death_runner.hpp"
template<class protocol_t>
void on_receive_backfill_chunk(
store_view_t<protocol_t> *store,
signal_t *dont_go_until,
typename protocol_t::backfill_chunk_t chunk,
signal_t *interruptor,
fifo_enforcer_write_token_t tok,
fifo_enforcer_queue_t<std::pair<std::pair<bool, typename protocol_t::backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue
)
THROWS_NOTHING
{
{
wait_any_t waiter(dont_go_until, interruptor);
waiter.wait_lazily_unordered();
if (interruptor->is_pulsed()) {
return;
}
}
try {
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> write_token;
store->new_write_token(write_token);
queue->finish_write(tok);
store->receive_backfill(chunk, write_token, interruptor);
} catch (interrupted_exc_t) {
return;
}
};
template <class backfill_chunk_t>
void push_on_queue(fifo_enforcer_queue_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue, backfill_chunk_t chunk, fifo_enforcer_write_token_t token) {
queue->push(token, std::make_pair(std::make_pair(true, chunk), token));
}
template<class protocol_t>
void backfillee(
mailbox_manager_t *mailbox_manager,
UNUSED boost::shared_ptr<semilattice_read_view_t<branch_history_t<protocol_t> > > branch_history,
store_view_t<protocol_t> *store,
typename protocol_t::region_t region,
clone_ptr_t<watchable_t<boost::optional<boost::optional<backfiller_business_card_t<protocol_t> > > > > backfiller_metadata,
backfill_session_id_t backfill_session_id,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t, resource_lost_exc_t)
{
rassert(region_is_superset(store->get_region(), region));
resource_access_t<backfiller_business_card_t<protocol_t> > backfiller(backfiller_metadata);
/* Read the metadata to determine where we're starting from */
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> read_token;
store->new_read_token(read_token);
region_map_t<protocol_t, version_range_t> start_point =
region_map_transform<protocol_t, binary_blob_t, version_range_t>(
store->get_metainfo(read_token, interruptor),
&binary_blob_t::get<version_range_t>
);
start_point = start_point.mask(region);
/* The backfiller will send a message to `end_point_mailbox` before it sends
any other messages; that message will tell us what the version will be when
the backfill is over. */
promise_t<region_map_t<protocol_t, version_range_t> > end_point_cond;
mailbox_t<void(region_map_t<protocol_t, version_range_t>)> end_point_mailbox(
mailbox_manager,
boost::bind(&promise_t<region_map_t<protocol_t, version_range_t> >::pulse, &end_point_cond, _1),
mailbox_callback_mode_inline);
/* `dont_go_until` prevents any backfill chunks from being applied before we
update the store metadata to indicate that the backfill is in progress. */
cond_t dont_go_until;
/* The backfiller will notify `done_mailbox` when the backfill is all over
and the version described in `end_point_mailbox` has been achieved. */
promise_t<fifo_enforcer_write_token_t> done_cond;
mailbox_t<void(fifo_enforcer_write_token_t)> done_mailbox(
mailbox_manager,
boost::bind(&promise_t<fifo_enforcer_write_token_t>::pulse, &done_cond, _1),
mailbox_callback_mode_inline);
{
/* A queue of the requests the backfill chunk mailbox receives, a coro
* pool services these requests and poops them off one at a time to
* perform them. */
typedef typename protocol_t::backfill_chunk_t backfill_chunk_t;
typedef fifo_enforcer_queue_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> > chunk_queue_t;
chunk_queue_t chunk_queue;
struct chunk_callback_t : public coro_pool_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> >::callback_t {
chunk_callback_t(store_view_t<protocol_t> *_store, signal_t *_dont_go_until,
signal_t *_interruptor, chunk_queue_t *_chunk_queue)
: store(_store), dont_go_until(_dont_go_until), interruptor(_interruptor), chunk_queue(_chunk_queue)
{ }
void coro_pool_callback(std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> chunk) {
on_receive_backfill_chunk(store, dont_go_until, chunk.first.second, interruptor, chunk.second, chunk_queue);
}
store_view_t<protocol_t> *store;
signal_t *dont_go_until;
signal_t *interruptor;
chunk_queue_t *chunk_queue;
};
chunk_callback_t chunk_callback(store, &dont_go_until, interruptor, &chunk_queue);
/* A callback, this function will be called on backfill_chunk_ts as
* they are popped off the queue. */
//typename coro_pool_t<std::pair<backfill_chunk_t, auto_drainer_t::lock_t> >::boost_function_callback_t
// chunk_callback(boost::bind(&on_receive_backfill_chunk<protocol_t>,
// store, &dont_go_until, boost::bind(&std::pair::first, _1), interruptor, boost::bind(&std::pair::second, _1)
// ));
coro_pool_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> > backfill_workers(10, &chunk_queue, &chunk_callback);
/* Use an `auto_drainer_t` to wait for all the bits of the backfill to
finish being applied. Construct it before `chunk_mailbox` so that we
don't get any chunks after `drainer` is destroyed. */
auto_drainer_t drainer;
/* The backfiller will send individual chunks of the backfill to
`chunk_mailbox`. */
mailbox_t<void(backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_mailbox(
mailbox_manager, boost::bind(&push_on_queue<backfill_chunk_t>, &chunk_queue, _1, _2));
/* Send off the backfill request */
send(mailbox_manager,
backfiller.access().backfill_mailbox,
backfill_session_id,
start_point,
end_point_mailbox.get_address(),
chunk_mailbox.get_address(),
done_mailbox.get_address()
);
/* If something goes wrong, we'd like to inform the backfiller that it
it has gone wrong, so it doesn't just keep blindly sending us chunks.
`backfiller_notifier` notifies the backfiller in its destructor. If
everything goes right, we'll explicitly disarm it. */
death_runner_t backfiller_notifier;
{
/* We have to cast `send()` to the correct type before we pass
it to `boost::bind()`, or else C++ can't figure out which
overload to use. */
void (*send_cast_to_correct_type)(
mailbox_manager_t *,
typename backfiller_business_card_t<protocol_t>::cancel_backfill_mailbox_t::address_t,
const backfill_session_id_t &) = &send;
backfiller_notifier.fun = boost::bind(
send_cast_to_correct_type, mailbox_manager,
backfiller.access().cancel_backfill_mailbox,
backfill_session_id);
}
/* Wait until we get a message in `end_point_mailbox`. */
{
wait_any_t waiter(end_point_cond.get_ready_signal(), backfiller.get_failed_signal());
wait_interruptible(&waiter, interruptor);
/* Throw an exception if backfiller died */
backfiller.access();
rassert(end_point_cond.get_ready_signal()->is_pulsed());
}
/* Indicate in the metadata that a backfill is happening. We do this by
marking every region as indeterminate between the current state and the
backfill end state, since we don't know whether the backfill has reached
that region yet. */
typedef region_map_t<protocol_t, version_range_t> version_map_t;
version_map_t end_point = end_point_cond.get_value();
std::vector<std::pair<typename protocol_t::region_t, version_range_t> > span_parts;
for (typename version_map_t::const_iterator it = start_point.begin();
it != start_point.end();
it++) {
for (typename version_map_t::const_iterator jt = end_point.begin();
jt != end_point.end();
jt++) {
typename protocol_t::region_t ixn = region_intersection(it->first, jt->first);
if (!region_is_empty(ixn)) {
rassert(version_is_ancestor(branch_history->get(),
it->second.earliest,
jt->second.latest,
ixn),
"We're on a different timeline than the backfiller, "
"but it somehow failed to notice.");
span_parts.push_back(std::make_pair(
ixn,
version_range_t(it->second.earliest, jt->second.latest)
));
}
}
}
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> write_token;
store->new_write_token(write_token);
store->set_metainfo(
region_map_transform<protocol_t, version_range_t, binary_blob_t>(
region_map_t<protocol_t, version_range_t>(span_parts.begin(), span_parts.end()),
&binary_blob_t::make<version_range_t>
),
write_token,
interruptor
);
/* Now that the metadata indicates that the backfill is happening, it's
OK for backfill chunks to be applied */
dont_go_until.pulse();
/* Now wait for the backfill to be over */
{
wait_any_t waiter(done_cond.get_ready_signal(), backfiller.get_failed_signal());
wait_interruptible(&waiter, interruptor);
/* Throw an exception if backfiller died */
backfiller.access();
rassert(done_cond.get_ready_signal()->is_pulsed());
}
/* All went well, so don't send a cancel message to the backfiller */
backfiller_notifier.fun = 0;
/* `drainer` destructor is run here; we block until all the chunks are
done being applied. */
}
/* Update the metadata to indicate that the backfill occurred */
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> write_token;
store->new_write_token(write_token);
store->set_metainfo(
region_map_transform<protocol_t, version_range_t, binary_blob_t>(
end_point_cond.get_value(),
&binary_blob_t::make<version_range_t>
),
write_token,
interruptor
);
}
#include "memcached/protocol.hpp"
#include "mock/dummy_protocol.hpp"
template void backfillee<mock::dummy_protocol_t>(
mailbox_manager_t *mailbox_manager,
UNUSED boost::shared_ptr<semilattice_read_view_t<branch_history_t<mock::dummy_protocol_t> > > branch_history,
store_view_t<mock::dummy_protocol_t> *store,
mock::dummy_protocol_t::region_t region,
clone_ptr_t<watchable_t<boost::optional<boost::optional<backfiller_business_card_t<mock::dummy_protocol_t> > > > > backfiller_metadata,
backfill_session_id_t backfill_session_id,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t, resource_lost_exc_t);
template void on_receive_backfill_chunk<mock::dummy_protocol_t>(
store_view_t<mock::dummy_protocol_t> *store,
signal_t *dont_go_until,
mock::dummy_protocol_t::backfill_chunk_t chunk,
signal_t *interruptor,
fifo_enforcer_write_token_t tok,
fifo_enforcer_queue_t<std::pair<std::pair<bool, mock::dummy_protocol_t::backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue)
THROWS_NOTHING;
template void backfillee<memcached_protocol_t>(
mailbox_manager_t *mailbox_manager,
UNUSED boost::shared_ptr<semilattice_read_view_t<branch_history_t<memcached_protocol_t> > > branch_history,
store_view_t<memcached_protocol_t> *store,
memcached_protocol_t::region_t region,
clone_ptr_t<watchable_t<boost::optional<boost::optional<backfiller_business_card_t<memcached_protocol_t> > > > > backfiller_metadata,
backfill_session_id_t backfill_session_id,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t, resource_lost_exc_t);
template void on_receive_backfill_chunk<memcached_protocol_t>(
store_view_t<memcached_protocol_t> *store,
signal_t *dont_go_until,
memcached_protocol_t::backfill_chunk_t chunk,
signal_t *interruptor,
fifo_enforcer_write_token_t tok,
fifo_enforcer_queue_t<std::pair<std::pair<bool, memcached_protocol_t::backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue)
THROWS_NOTHING;
<commit_msg>Completes the backfill ordering fix.<commit_after>#include "errors.hpp"
#include <boost/variant.hpp>
#include "clustering/immediate_consistency/branch/backfillee.hpp"
#include "clustering/immediate_consistency/branch/history.hpp"
#include "concurrency/coro_pool.hpp"
#include "concurrency/promise.hpp"
#include "concurrency/queue/unlimited_fifo.hpp"
#include "containers/death_runner.hpp"
template<class protocol_t>
void on_receive_backfill_chunk(
store_view_t<protocol_t> *store,
signal_t *dont_go_until,
typename protocol_t::backfill_chunk_t chunk,
signal_t *interruptor,
fifo_enforcer_write_token_t tok,
fifo_enforcer_queue_t<std::pair<std::pair<bool, typename protocol_t::backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue
)
THROWS_NOTHING
{
{
wait_any_t waiter(dont_go_until, interruptor);
waiter.wait_lazily_unordered();
if (interruptor->is_pulsed()) {
return;
}
}
try {
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> write_token;
store->new_write_token(write_token);
queue->finish_write(tok);
store->receive_backfill(chunk, write_token, interruptor);
} catch (interrupted_exc_t) {
return;
}
};
template <class backfill_chunk_t>
void push_chunk_on_queue(fifo_enforcer_queue_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue, backfill_chunk_t chunk, fifo_enforcer_write_token_t token) {
queue->push(token, std::make_pair(std::make_pair(true, chunk), token));
}
template <class backfill_chunk_t>
void push_finish_on_queue(fifo_enforcer_queue_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue, fifo_enforcer_write_token_t token) {
queue->push(token, std::make_pair(std::make_pair(false, backfill_chunk_t()), token));
}
template<class protocol_t>
void backfillee(
mailbox_manager_t *mailbox_manager,
UNUSED boost::shared_ptr<semilattice_read_view_t<branch_history_t<protocol_t> > > branch_history,
store_view_t<protocol_t> *store,
typename protocol_t::region_t region,
clone_ptr_t<watchable_t<boost::optional<boost::optional<backfiller_business_card_t<protocol_t> > > > > backfiller_metadata,
backfill_session_id_t backfill_session_id,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t, resource_lost_exc_t)
{
rassert(region_is_superset(store->get_region(), region));
resource_access_t<backfiller_business_card_t<protocol_t> > backfiller(backfiller_metadata);
/* Read the metadata to determine where we're starting from */
boost::scoped_ptr<fifo_enforcer_sink_t::exit_read_t> read_token;
store->new_read_token(read_token);
region_map_t<protocol_t, version_range_t> start_point =
region_map_transform<protocol_t, binary_blob_t, version_range_t>(
store->get_metainfo(read_token, interruptor),
&binary_blob_t::get<version_range_t>
);
start_point = start_point.mask(region);
/* The backfiller will send a message to `end_point_mailbox` before it sends
any other messages; that message will tell us what the version will be when
the backfill is over. */
promise_t<region_map_t<protocol_t, version_range_t> > end_point_cond;
mailbox_t<void(region_map_t<protocol_t, version_range_t>)> end_point_mailbox(
mailbox_manager,
boost::bind(&promise_t<region_map_t<protocol_t, version_range_t> >::pulse, &end_point_cond, _1),
mailbox_callback_mode_inline);
/* `dont_go_until` prevents any backfill chunks from being applied before we
update the store metadata to indicate that the backfill is in progress. */
cond_t dont_go_until;
{
typedef typename protocol_t::backfill_chunk_t backfill_chunk_t;
/* A queue of the requests the backfill chunk mailbox receives, a coro
* pool services these requests and poops them off one at a time to
* perform them. */
typedef fifo_enforcer_queue_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> > chunk_queue_t;
chunk_queue_t chunk_queue;
/* The backfiller will notify `done_mailbox` when the backfill is all over
and the version described in `end_point_mailbox` has been achieved. */
cond_t done_cond;
mailbox_t<void(fifo_enforcer_write_token_t)> done_mailbox(
mailbox_manager,
boost::bind(&push_finish_on_queue<backfill_chunk_t>, &chunk_queue, _1),
mailbox_callback_mode_inline);
struct chunk_callback_t : public coro_pool_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> >::callback_t {
chunk_callback_t(store_view_t<protocol_t> *_store, signal_t *_dont_go_until,
signal_t *_interruptor, chunk_queue_t *_chunk_queue,
cond_t *_done_cond)
: store(_store), dont_go_until(_dont_go_until), interruptor(_interruptor),
chunk_queue(_chunk_queue), done_cond(_done_cond)
{ }
void coro_pool_callback(std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> chunk) {
if (chunk.first.first) {
on_receive_backfill_chunk(store, dont_go_until, chunk.first.second, interruptor, chunk.second, chunk_queue);
} else {
rassert(!done_cond->is_pulsed());
done_cond->pulse();
}
}
store_view_t<protocol_t> *store;
signal_t *dont_go_until;
signal_t *interruptor;
chunk_queue_t *chunk_queue;
cond_t *done_cond;
};
chunk_callback_t chunk_callback(store, &dont_go_until, interruptor, &chunk_queue, &done_cond);
/* A callback, this function will be called on backfill_chunk_ts as
* they are popped off the queue. */
//typename coro_pool_t<std::pair<backfill_chunk_t, auto_drainer_t::lock_t> >::boost_function_callback_t
// chunk_callback(boost::bind(&on_receive_backfill_chunk<protocol_t>,
// store, &dont_go_until, boost::bind(&std::pair::first, _1), interruptor, boost::bind(&std::pair::second, _1)
// ));
coro_pool_t<std::pair<std::pair<bool, backfill_chunk_t>, fifo_enforcer_write_token_t> > backfill_workers(10, &chunk_queue, &chunk_callback);
/* Use an `auto_drainer_t` to wait for all the bits of the backfill to
finish being applied. Construct it before `chunk_mailbox` so that we
don't get any chunks after `drainer` is destroyed. */
auto_drainer_t drainer;
/* The backfiller will send individual chunks of the backfill to
`chunk_mailbox`. */
mailbox_t<void(backfill_chunk_t, fifo_enforcer_write_token_t)> chunk_mailbox(
mailbox_manager, boost::bind(&push_chunk_on_queue<backfill_chunk_t>, &chunk_queue, _1, _2));
/* Send off the backfill request */
send(mailbox_manager,
backfiller.access().backfill_mailbox,
backfill_session_id,
start_point,
end_point_mailbox.get_address(),
chunk_mailbox.get_address(),
done_mailbox.get_address()
);
/* If something goes wrong, we'd like to inform the backfiller that it
it has gone wrong, so it doesn't just keep blindly sending us chunks.
`backfiller_notifier` notifies the backfiller in its destructor. If
everything goes right, we'll explicitly disarm it. */
death_runner_t backfiller_notifier;
{
/* We have to cast `send()` to the correct type before we pass
it to `boost::bind()`, or else C++ can't figure out which
overload to use. */
void (*send_cast_to_correct_type)(
mailbox_manager_t *,
typename backfiller_business_card_t<protocol_t>::cancel_backfill_mailbox_t::address_t,
const backfill_session_id_t &) = &send;
backfiller_notifier.fun = boost::bind(
send_cast_to_correct_type, mailbox_manager,
backfiller.access().cancel_backfill_mailbox,
backfill_session_id);
}
/* Wait until we get a message in `end_point_mailbox`. */
{
wait_any_t waiter(end_point_cond.get_ready_signal(), backfiller.get_failed_signal());
wait_interruptible(&waiter, interruptor);
/* Throw an exception if backfiller died */
backfiller.access();
rassert(end_point_cond.get_ready_signal()->is_pulsed());
}
/* Indicate in the metadata that a backfill is happening. We do this by
marking every region as indeterminate between the current state and the
backfill end state, since we don't know whether the backfill has reached
that region yet. */
typedef region_map_t<protocol_t, version_range_t> version_map_t;
version_map_t end_point = end_point_cond.get_value();
std::vector<std::pair<typename protocol_t::region_t, version_range_t> > span_parts;
for (typename version_map_t::const_iterator it = start_point.begin();
it != start_point.end();
it++) {
for (typename version_map_t::const_iterator jt = end_point.begin();
jt != end_point.end();
jt++) {
typename protocol_t::region_t ixn = region_intersection(it->first, jt->first);
if (!region_is_empty(ixn)) {
rassert(version_is_ancestor(branch_history->get(),
it->second.earliest,
jt->second.latest,
ixn),
"We're on a different timeline than the backfiller, "
"but it somehow failed to notice.");
span_parts.push_back(std::make_pair(
ixn,
version_range_t(it->second.earliest, jt->second.latest)
));
}
}
}
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> write_token;
store->new_write_token(write_token);
store->set_metainfo(
region_map_transform<protocol_t, version_range_t, binary_blob_t>(
region_map_t<protocol_t, version_range_t>(span_parts.begin(), span_parts.end()),
&binary_blob_t::make<version_range_t>
),
write_token,
interruptor
);
/* Now that the metadata indicates that the backfill is happening, it's
OK for backfill chunks to be applied */
dont_go_until.pulse();
/* Now wait for the backfill to be over */
{
wait_any_t waiter(&done_cond, backfiller.get_failed_signal());
wait_interruptible(&waiter, interruptor);
/* Throw an exception if backfiller died */
backfiller.access();
rassert(done_cond.is_pulsed());
}
/* All went well, so don't send a cancel message to the backfiller */
backfiller_notifier.fun = 0;
/* `drainer` destructor is run here; we block until all the chunks are
done being applied. */
}
/* Update the metadata to indicate that the backfill occurred */
boost::scoped_ptr<fifo_enforcer_sink_t::exit_write_t> write_token;
store->new_write_token(write_token);
store->set_metainfo(
region_map_transform<protocol_t, version_range_t, binary_blob_t>(
end_point_cond.get_value(),
&binary_blob_t::make<version_range_t>
),
write_token,
interruptor
);
}
#include "memcached/protocol.hpp"
#include "mock/dummy_protocol.hpp"
template void backfillee<mock::dummy_protocol_t>(
mailbox_manager_t *mailbox_manager,
UNUSED boost::shared_ptr<semilattice_read_view_t<branch_history_t<mock::dummy_protocol_t> > > branch_history,
store_view_t<mock::dummy_protocol_t> *store,
mock::dummy_protocol_t::region_t region,
clone_ptr_t<watchable_t<boost::optional<boost::optional<backfiller_business_card_t<mock::dummy_protocol_t> > > > > backfiller_metadata,
backfill_session_id_t backfill_session_id,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t, resource_lost_exc_t);
template void on_receive_backfill_chunk<mock::dummy_protocol_t>(
store_view_t<mock::dummy_protocol_t> *store,
signal_t *dont_go_until,
mock::dummy_protocol_t::backfill_chunk_t chunk,
signal_t *interruptor,
fifo_enforcer_write_token_t tok,
fifo_enforcer_queue_t<std::pair<std::pair<bool, mock::dummy_protocol_t::backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue)
THROWS_NOTHING;
template void backfillee<memcached_protocol_t>(
mailbox_manager_t *mailbox_manager,
UNUSED boost::shared_ptr<semilattice_read_view_t<branch_history_t<memcached_protocol_t> > > branch_history,
store_view_t<memcached_protocol_t> *store,
memcached_protocol_t::region_t region,
clone_ptr_t<watchable_t<boost::optional<boost::optional<backfiller_business_card_t<memcached_protocol_t> > > > > backfiller_metadata,
backfill_session_id_t backfill_session_id,
signal_t *interruptor)
THROWS_ONLY(interrupted_exc_t, resource_lost_exc_t);
template void on_receive_backfill_chunk<memcached_protocol_t>(
store_view_t<memcached_protocol_t> *store,
signal_t *dont_go_until,
memcached_protocol_t::backfill_chunk_t chunk,
signal_t *interruptor,
fifo_enforcer_write_token_t tok,
fifo_enforcer_queue_t<std::pair<std::pair<bool, memcached_protocol_t::backfill_chunk_t>, fifo_enforcer_write_token_t> > *queue)
THROWS_NOTHING;
<|endoftext|> |
<commit_before>/*
Copyright (c) 2010, The Barbarian Group
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 "cinder/app/App.h"
#include "cinder/params/Params.h"
#if defined( CINDER_MSW )
#include "cinder/dx/dx.h"
#include "cinder/app/AppImplMswRendererDx.h"
#endif
#include "AntTweakBar.h"
#include <boost/assign/list_of.hpp>
using namespace std;
namespace cinder { namespace params {
namespace {
#undef DELETE
#define SYNONYM(ck,ak) ((int)cinder::app::KeyEvent::KEY_ ## ck, TW_KEY_ ## ak)
#define HOMONYM(k) SYNONYM(k,k)
std::map<int,TwKeySpecial> specialKeys = boost::assign::map_list_of
HOMONYM(RIGHT)
HOMONYM(LEFT)
HOMONYM(BACKSPACE)
HOMONYM(DELETE)
HOMONYM(TAB)
HOMONYM(F1)
HOMONYM(F2)
HOMONYM(F3)
HOMONYM(F4)
HOMONYM(F5)
HOMONYM(F6)
HOMONYM(F7)
HOMONYM(F8)
HOMONYM(F9)
HOMONYM(F10)
HOMONYM(F11)
HOMONYM(F12)
HOMONYM(F13)
HOMONYM(F14)
HOMONYM(F15)
HOMONYM(HOME)
HOMONYM(END)
SYNONYM(PAGEUP,PAGE_UP)
SYNONYM(PAGEDOWN,PAGE_DOWN)
;
#undef SYNONYM
#undef HOMONYM
void mouseDown( app::MouseEvent &event )
{
TwMouseButtonID button;
if( event.isLeft() )
button = TW_MOUSE_LEFT;
else if( event.isRight() )
button = TW_MOUSE_RIGHT;
else
button = TW_MOUSE_MIDDLE;
event.setHandled( TwMouseButton( TW_MOUSE_PRESSED, button ) != 0 );
}
void mouseUp( app::MouseEvent &event )
{
TwMouseButtonID button;
if( event.isLeft() )
button = TW_MOUSE_LEFT;
else if( event.isRight() )
button = TW_MOUSE_RIGHT;
else
button = TW_MOUSE_MIDDLE;
event.setHandled( TwMouseButton( TW_MOUSE_RELEASED, button ) != 0 );
}
void mouseWheel( app::MouseEvent &event )
{
static float sWheelPos = 0;
sWheelPos += event.getWheelIncrement();
event.setHandled( TwMouseWheel( (int)(sWheelPos) ) != 0 );
}
void mouseMove( app::MouseEvent &event )
{
event.setHandled( TwMouseMotion( event.getX(), event.getY() ) != 0 );
}
void keyDown( app::KeyEvent &event )
{
int kmod = 0;
if( event.isShiftDown() )
kmod |= TW_KMOD_SHIFT;
if( event.isControlDown() )
kmod |= TW_KMOD_CTRL;
if( event.isAltDown() )
kmod |= TW_KMOD_ALT;
event.setHandled( TwKeyPressed(
(specialKeys.count( event.getCode() ) > 0)
? specialKeys[event.getCode()]
: event.getChar(),
kmod ) != 0 );
}
void resize( cinder::app::WindowRef window )
{
TwWindowSize( window->getWidth(), window->getHeight() );
}
void TW_CALL implStdStringToClient( std::string& destinationClientString, const std::string& sourceLibraryString )
{
// copy strings from the library to the client app
destinationClientString = sourceLibraryString;
}
class AntMgr {
public:
AntMgr() {
#if defined( CINDER_MSW )
app::Renderer::RendererType rendererType = app::App::get()->getRenderer()->getRendererType();
if( ! TwInit( (rendererType == app::Renderer::RENDERER_GL) ? TW_OPENGL : TW_DIRECT3D11, (rendererType == app::Renderer::RENDERER_GL) ? NULL : dx::getDxRenderer()->md3dDevice ) )
throw Exception();
#else
if( ! TwInit( TW_OPENGL, NULL ) ) {
throw Exception();
}
#endif
}
~AntMgr() {
TwTerminate();
}
};
} // anonymous namespace
void initAntGl()
{
static std::shared_ptr<AntMgr> mgr;
if( ! mgr )
mgr = std::shared_ptr<AntMgr>( new AntMgr );
}
InterfaceGl::InterfaceGl( const std::string &title, const Vec2i &size, const ColorA color )
{
init( app::App::get()->getWindow(), title, size, color );
}
InterfaceGl::InterfaceGl( app::WindowRef window, const std::string &title, const Vec2i &size, const ColorA color )
{
init( window, title, size, color );
}
void InterfaceGl::init( app::WindowRef window, const std::string &title, const Vec2i &size, const ColorA color )
{
initAntGl();
mWindow = window;
mBar = std::shared_ptr<TwBar>( TwNewBar( title.c_str() ), TwDeleteBar );
char optionsStr[1024];
sprintf( optionsStr, "`%s` size='%d %d' color='%d %d %d' alpha=%d", title.c_str(), size.x, size.y, (int)(color.r * 255), (int)(color.g * 255), (int)(color.b * 255), (int)(color.a * 255) );
TwDefine( optionsStr );
TwCopyStdStringToClientFunc( implStdStringToClient );
mWindow->getSignalMouseDown().connect( mouseDown );
mWindow->getSignalMouseUp().connect( mouseUp );
mWindow->getSignalMouseWheel().connect( mouseWheel );
mWindow->getSignalMouseMove().connect( mouseMove );
mWindow->getSignalMouseDrag().connect( mouseMove );
mWindow->getSignalKeyDown().connect( keyDown );
mWindow->getSignalResize().connect( std::bind( resize, mWindow ) );
}
void InterfaceGl::draw()
{
TwDraw();
}
void InterfaceGl::show( bool visible )
{
int32_t visibleInt = ( visible ) ? 1 : 0;
TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
}
void InterfaceGl::hide()
{
int32_t visibleInt = 0;
TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
}
bool InterfaceGl::isVisible() const
{
int32_t visibleInt;
TwGetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
return visibleInt != 0;
}
void InterfaceGl::implAddParam( const std::string &name, void *param, int type, const std::string &optionsStr, bool readOnly )
{
if( readOnly )
TwAddVarRO( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );
else
TwAddVarRW( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );
}
void InterfaceGl::addParam( const std::string &name, bool *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_BOOLCPP, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, float *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_FLOAT, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, double *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_DOUBLE, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, int32_t *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_INT32, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Vec3f *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_DIR3F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Quatf *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_QUAT4F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Color *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_COLOR3F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, ColorA *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_COLOR4F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, std::string *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_STDSTRING, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, const std::vector<std::string> &enumNames, int *param, const std::string &optionsStr, bool readOnly )
{
TwEnumVal *ev = new TwEnumVal[enumNames.size()];
for( size_t v = 0; v < enumNames.size(); ++v ) {
ev[v].Value = v;
ev[v].Label = const_cast<char*>( enumNames[v].c_str() );
}
TwType evType = TwDefineEnum( (name + "EnumType").c_str(), ev, enumNames.size() );
if( readOnly )
TwAddVarRO( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );
else
TwAddVarRW( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );
delete [] ev;
}
void InterfaceGl::addSeparator( const std::string &name, const std::string &optionsStr )
{
TwAddSeparator( mBar.get(), name.c_str(), optionsStr.c_str() );
}
void InterfaceGl::addText( const std::string &name, const std::string &optionsStr )
{
TwAddButton( mBar.get(), name.c_str(), NULL, NULL, optionsStr.c_str() );
}
namespace { // anonymous namespace
void TW_CALL implButtonCallback( void *clientData )
{
std::function<void ()> *fn = reinterpret_cast<std::function<void ()>*>( clientData );
(*fn)();
}
} // anonymous namespace
void InterfaceGl::addButton( const std::string &name, const std::function<void ()> &callback, const std::string &optionsStr )
{
std::shared_ptr<std::function<void ()> > callbackPtr( new std::function<void ()>( callback ) );
mButtonCallbacks.push_back( callbackPtr );
TwAddButton( mBar.get(), name.c_str(), implButtonCallback, (void*)callbackPtr.get(), optionsStr.c_str() );
}
void InterfaceGl::removeParam( const std::string &name )
{
TwRemoveVar( mBar.get(), name.c_str() );
}
void InterfaceGl::clear()
{
TwRemoveAllVars( mBar.get() );
}
void InterfaceGl::setOptions( const std::string &name, const std::string &optionsStr )
{
std::string target = "`" + (std::string)TwGetBarName( mBar.get() ) + "`";
if( !( name.empty() ) )
target += "/`" + name + "`";
TwDefine( ( target + " " + optionsStr ).c_str() );
}
} } // namespace cinder::params
<commit_msg>Added USE_DIRECTX define to prevent DirectX dependency when building for OpenGL<commit_after>/*
Copyright (c) 2010, The Barbarian Group
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 "cinder/app/App.h"
#include "cinder/params/Params.h"
#if (defined( CINDER_MSW ) && defined( USE_DIRECTX ))
#include "cinder/dx/dx.h"
#include "cinder/app/AppImplMswRendererDx.h"
#endif
#include "AntTweakBar.h"
#include <boost/assign/list_of.hpp>
using namespace std;
namespace cinder { namespace params {
namespace {
#undef DELETE
#define SYNONYM(ck,ak) ((int)cinder::app::KeyEvent::KEY_ ## ck, TW_KEY_ ## ak)
#define HOMONYM(k) SYNONYM(k,k)
std::map<int,TwKeySpecial> specialKeys = boost::assign::map_list_of
HOMONYM(RIGHT)
HOMONYM(LEFT)
HOMONYM(BACKSPACE)
HOMONYM(DELETE)
HOMONYM(TAB)
HOMONYM(F1)
HOMONYM(F2)
HOMONYM(F3)
HOMONYM(F4)
HOMONYM(F5)
HOMONYM(F6)
HOMONYM(F7)
HOMONYM(F8)
HOMONYM(F9)
HOMONYM(F10)
HOMONYM(F11)
HOMONYM(F12)
HOMONYM(F13)
HOMONYM(F14)
HOMONYM(F15)
HOMONYM(HOME)
HOMONYM(END)
SYNONYM(PAGEUP,PAGE_UP)
SYNONYM(PAGEDOWN,PAGE_DOWN)
;
#undef SYNONYM
#undef HOMONYM
void mouseDown( app::MouseEvent &event )
{
TwMouseButtonID button;
if( event.isLeft() )
button = TW_MOUSE_LEFT;
else if( event.isRight() )
button = TW_MOUSE_RIGHT;
else
button = TW_MOUSE_MIDDLE;
event.setHandled( TwMouseButton( TW_MOUSE_PRESSED, button ) != 0 );
}
void mouseUp( app::MouseEvent &event )
{
TwMouseButtonID button;
if( event.isLeft() )
button = TW_MOUSE_LEFT;
else if( event.isRight() )
button = TW_MOUSE_RIGHT;
else
button = TW_MOUSE_MIDDLE;
event.setHandled( TwMouseButton( TW_MOUSE_RELEASED, button ) != 0 );
}
void mouseWheel( app::MouseEvent &event )
{
static float sWheelPos = 0;
sWheelPos += event.getWheelIncrement();
event.setHandled( TwMouseWheel( (int)(sWheelPos) ) != 0 );
}
void mouseMove( app::MouseEvent &event )
{
event.setHandled( TwMouseMotion( event.getX(), event.getY() ) != 0 );
}
void keyDown( app::KeyEvent &event )
{
int kmod = 0;
if( event.isShiftDown() )
kmod |= TW_KMOD_SHIFT;
if( event.isControlDown() )
kmod |= TW_KMOD_CTRL;
if( event.isAltDown() )
kmod |= TW_KMOD_ALT;
event.setHandled( TwKeyPressed(
(specialKeys.count( event.getCode() ) > 0)
? specialKeys[event.getCode()]
: event.getChar(),
kmod ) != 0 );
}
void resize( cinder::app::WindowRef window )
{
TwWindowSize( window->getWidth(), window->getHeight() );
}
void TW_CALL implStdStringToClient( std::string& destinationClientString, const std::string& sourceLibraryString )
{
// copy strings from the library to the client app
destinationClientString = sourceLibraryString;
}
class AntMgr {
public:
AntMgr() {
#if defined( USE_DIRECTX )
if( ! TwInit( TW_DIRECT3D11, dx::getDxRenderer()->md3dDevice ) ) {
throw Exception();
}
#else
if( ! TwInit( TW_OPENGL, NULL ) ) {
throw Exception();
}
#endif
}
~AntMgr() {
TwTerminate();
}
};
} // anonymous namespace
void initAntGl()
{
static std::shared_ptr<AntMgr> mgr;
if( ! mgr )
mgr = std::shared_ptr<AntMgr>( new AntMgr );
}
InterfaceGl::InterfaceGl( const std::string &title, const Vec2i &size, const ColorA color )
{
init( app::App::get()->getWindow(), title, size, color );
}
InterfaceGl::InterfaceGl( app::WindowRef window, const std::string &title, const Vec2i &size, const ColorA color )
{
init( window, title, size, color );
}
void InterfaceGl::init( app::WindowRef window, const std::string &title, const Vec2i &size, const ColorA color )
{
initAntGl();
mWindow = window;
mBar = std::shared_ptr<TwBar>( TwNewBar( title.c_str() ), TwDeleteBar );
char optionsStr[1024];
sprintf( optionsStr, "`%s` size='%d %d' color='%d %d %d' alpha=%d", title.c_str(), size.x, size.y, (int)(color.r * 255), (int)(color.g * 255), (int)(color.b * 255), (int)(color.a * 255) );
TwDefine( optionsStr );
TwCopyStdStringToClientFunc( implStdStringToClient );
mWindow->getSignalMouseDown().connect( mouseDown );
mWindow->getSignalMouseUp().connect( mouseUp );
mWindow->getSignalMouseWheel().connect( mouseWheel );
mWindow->getSignalMouseMove().connect( mouseMove );
mWindow->getSignalMouseDrag().connect( mouseMove );
mWindow->getSignalKeyDown().connect( keyDown );
mWindow->getSignalResize().connect( std::bind( resize, mWindow ) );
}
void InterfaceGl::draw()
{
TwDraw();
}
void InterfaceGl::show( bool visible )
{
int32_t visibleInt = ( visible ) ? 1 : 0;
TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
}
void InterfaceGl::hide()
{
int32_t visibleInt = 0;
TwSetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
}
bool InterfaceGl::isVisible() const
{
int32_t visibleInt;
TwGetParam( mBar.get(), NULL, "visible", TW_PARAM_INT32, 1, &visibleInt );
return visibleInt != 0;
}
void InterfaceGl::implAddParam( const std::string &name, void *param, int type, const std::string &optionsStr, bool readOnly )
{
if( readOnly )
TwAddVarRO( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );
else
TwAddVarRW( mBar.get(), name.c_str(), (TwType)type, param, optionsStr.c_str() );
}
void InterfaceGl::addParam( const std::string &name, bool *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_BOOLCPP, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, float *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_FLOAT, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, double *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_DOUBLE, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, int32_t *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_INT32, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Vec3f *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_DIR3F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Quatf *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_QUAT4F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, Color *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_COLOR3F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, ColorA *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_COLOR4F, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, std::string *param, const std::string &optionsStr, bool readOnly )
{
implAddParam( name, param, TW_TYPE_STDSTRING, optionsStr, readOnly );
}
void InterfaceGl::addParam( const std::string &name, const std::vector<std::string> &enumNames, int *param, const std::string &optionsStr, bool readOnly )
{
TwEnumVal *ev = new TwEnumVal[enumNames.size()];
for( size_t v = 0; v < enumNames.size(); ++v ) {
ev[v].Value = v;
ev[v].Label = const_cast<char*>( enumNames[v].c_str() );
}
TwType evType = TwDefineEnum( (name + "EnumType").c_str(), ev, enumNames.size() );
if( readOnly )
TwAddVarRO( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );
else
TwAddVarRW( mBar.get(), name.c_str(), evType, param, optionsStr.c_str() );
delete [] ev;
}
void InterfaceGl::addSeparator( const std::string &name, const std::string &optionsStr )
{
TwAddSeparator( mBar.get(), name.c_str(), optionsStr.c_str() );
}
void InterfaceGl::addText( const std::string &name, const std::string &optionsStr )
{
TwAddButton( mBar.get(), name.c_str(), NULL, NULL, optionsStr.c_str() );
}
namespace { // anonymous namespace
void TW_CALL implButtonCallback( void *clientData )
{
std::function<void ()> *fn = reinterpret_cast<std::function<void ()>*>( clientData );
(*fn)();
}
} // anonymous namespace
void InterfaceGl::addButton( const std::string &name, const std::function<void ()> &callback, const std::string &optionsStr )
{
std::shared_ptr<std::function<void ()> > callbackPtr( new std::function<void ()>( callback ) );
mButtonCallbacks.push_back( callbackPtr );
TwAddButton( mBar.get(), name.c_str(), implButtonCallback, (void*)callbackPtr.get(), optionsStr.c_str() );
}
void InterfaceGl::removeParam( const std::string &name )
{
TwRemoveVar( mBar.get(), name.c_str() );
}
void InterfaceGl::clear()
{
TwRemoveAllVars( mBar.get() );
}
void InterfaceGl::setOptions( const std::string &name, const std::string &optionsStr )
{
std::string target = "`" + (std::string)TwGetBarName( mBar.get() ) + "`";
if( !( name.empty() ) )
target += "/`" + name + "`";
TwDefine( ( target + " " + optionsStr ).c_str() );
}
} } // namespace cinder::params
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include <boost/algorithm/string.hpp>
#ifndef unix
#include <float.h>
#else
#include "CoreTypes.h"
#endif
#include "RexNetworkUtils.h"
#include "QuatUtils.h"
#include <QStringList>
namespace RexTypes
{
bool ParseBool(const std::string &value)
{
std::string testedvalue = value;
boost::algorithm::to_lower(testedvalue);
return (boost::algorithm::starts_with(testedvalue,"true") || boost::algorithm::starts_with(testedvalue,"1"));
}
Quaternion GetProcessedQuaternion(const uint8_t* bytes)
{
uint16_t *rot = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
Quaternion rotation = UnpackQuaternionFromU16_4(rot);
rotation.normalize();
return rotation;
}
Vector3df GetProcessedScaledVectorFromUint16(const uint8_t* bytes, float scale)
{
uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
Vector3df resultvector;
resultvector.x = scale * ((vec[0] / 32768.0f) - 1.0f);
resultvector.y = scale * ((vec[1] / 32768.0f) - 1.0f);
resultvector.z = scale * ((vec[2] / 32768.0f) - 1.0f);
return resultvector;
}
Vector3df GetProcessedVectorFromUint16(const uint8_t* bytes)
{
uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
return Vector3df(vec[0],vec[1],vec[2]);
}
Vector3df GetProcessedVector(const uint8_t* bytes)
{
Vector3df resultvector = *reinterpret_cast<Vector3df*>((Vector3df*)&bytes[0]);
return resultvector;
}
bool IsValidPositionVector(const Vector3df &pos)
{
// This is a heuristic check to guard against the OpenSim server sending us stupid positions.
if (fabs(pos.x) > 1e6f || fabs(pos.y) > 1e6f || fabs(pos.z) > 1e6f)
return false;
if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z))
return false;
if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z))
return false;
return true;
}
bool IsValidVelocityVector(const Vector3df &pos)
{
// This is a heuristic check to guard against the OpenSim server sending us stupid velocity vectors.
if (fabs(pos.x) > 1e3f || fabs(pos.y) > 1e3f || fabs(pos.z) > 1e3f)
return false;
if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z))
return false;
if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z))
return false;
return true;
}
bool ReadBoolFromBytes(const uint8_t* bytes, int& idx)
{
bool result = *(bool*)(&bytes[idx]);
idx += sizeof(bool);
return result;
}
uint8_t ReadUInt8FromBytes(const uint8_t* bytes, int& idx)
{
uint8_t result = bytes[idx];
idx++;
return result;
}
uint16_t ReadUInt16FromBytes(const uint8_t* bytes, int& idx)
{
uint16_t result = *(uint16_t*)(&bytes[idx]);
idx += sizeof(uint16_t);
return result;
}
uint32_t ReadUInt32FromBytes(const uint8_t* bytes, int& idx)
{
uint32_t result = *(uint32_t*)(&bytes[idx]);
idx += sizeof(uint32_t);
return result;
}
int16_t ReadSInt16FromBytes(const uint8_t* bytes, int& idx)
{
int16_t result = *(int16_t*)(&bytes[idx]);
idx += sizeof(int16_t);
return result;
}
int32_t ReadSInt32FromBytes(const uint8_t* bytes, int& idx)
{
int32_t result = *(int32_t*)(&bytes[idx]);
idx += sizeof(int32_t);
return result;
}
float ReadFloatFromBytes(const uint8_t* bytes, int& idx)
{
float result = *(float*)(&bytes[idx]);
idx += sizeof(float);
return result;
}
RexUUID ReadUUIDFromBytes(const uint8_t* bytes, int& idx)
{
RexUUID result = *(RexUUID*)(&bytes[idx]);
idx += sizeof(RexUUID);
return result;
}
Color ReadColorFromBytes(const uint8_t* bytes, int& idx)
{
uint8_t r = bytes[idx++];
uint8_t g = bytes[idx++];
uint8_t b = bytes[idx++];
uint8_t a = bytes[idx++];
return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
}
Color ReadColorFromBytesInverted(const uint8_t* bytes, int& idx)
{
uint8_t r = 255 - bytes[idx++];
uint8_t g = 255 - bytes[idx++];
uint8_t b = 255 - bytes[idx++];
uint8_t a = 255 - bytes[idx++];
return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
}
std::string ReadNullTerminatedStringFromBytes(const uint8_t* bytes, int& idx)
{
std::string result = "";
uint8_t readbyte = bytes[idx];
idx++;
while(readbyte != 0)
{
result.push_back((char)readbyte);
readbyte = bytes[idx];
idx++;
}
return result;
}
void WriteBoolToBytes(bool value, uint8_t* bytes, int& idx)
{
bytes[idx] = (uint8_t)value;
idx++;
}
void WriteUInt8ToBytes(uint8_t value, uint8_t* bytes, int& idx)
{
bytes[idx] = value;
idx++;
}
void WriteUInt16ToBytes(uint16_t value, uint8_t* bytes, int& idx)
{
*(uint16_t*)(&bytes[idx]) = value;
idx += sizeof(uint16_t);
}
void WriteUInt32ToBytes(uint32_t value, uint8_t* bytes, int& idx)
{
*(uint32_t*)(&bytes[idx]) = value;
idx += sizeof(uint32_t);
}
void WriteFloatToBytes(float value, uint8_t* bytes, int& idx)
{
*(float*)(&bytes[idx]) = value;
idx += sizeof(float);
}
void WriteUUIDToBytes(const RexUUID &value, uint8_t* bytes, int& idx)
{
*(RexUUID*)(&bytes[idx]) = value;
idx += sizeof(RexUUID);
}
void WriteNullTerminatedStringToBytes(const std::string& value, uint8_t* bytes, int& idx)
{
const char* c_str = value.c_str();
memcpy(&bytes[idx], c_str, value.length() + 1);
idx += value.length() + 1;
}
NameValueMap ParseNameValueMap(const std::string& namevalue)
{
// NameValue contains: "FirstName STRING RW SV <firstName>\nLastName STRING RW SV <lastName>"
// When using rex auth <firstName> contains both first and last name and <lastName> contains the auth server address
// Split into lines
NameValueMap map;
StringVector lines = SplitString(namevalue, '\n');
for (unsigned i = 0; i < lines.size(); ++i)
{
StringVector line = SplitString(lines[i], ' ');
if (line.size() > 4)
{
// First element is the name
const std::string& name = line[0];
std::string value;
// Skip over the STRING RW SV etc. (3 values)
// Concatenate the rest of the values
for (unsigned j = 4; j < line.size(); ++j)
{
value += line[j];
if (j != line.size()-1)
value += " ";
}
map[name] = value;
}
}
// Parse auth server address out from the NameValue if it exists
QString fullname = QString(map["FirstName"].c_str()) + " " + QString(map["LastName"].c_str());
// Rex auth has: <First Last> <rex auth url>
if (fullname.count('@') == 1)
{
QStringList names;
if (fullname.contains('@'))
{
names = fullname.split(" ");
foreach(QString name, names)
{
if (name.contains('@'))
{
map["RexAuth"] = name.toStdString();
names.removeOne(name);
}
}
}
assert(names[0].size() >= 2);
map["FirstName"] = names[0].toStdString();
map["LastName"] = names[1].toStdString();
}
// Web auth has: <url> <url>
else if (fullname.count('@') == 2)
{
QStringList names = fullname.split(" ");
map["FirstName"] = names[0].toStdString();
map["LastName"] = "";
}
return map;
}
bool ReadTextureEntryBits(uint32_t& bits, int& num_bits, const uint8_t* bytes, int& idx)
{
bits = 0;
num_bits = 0;
uint8_t byte;
do
{
byte = bytes[idx++];
bits <<= 7;
bits |= byte & 0x7f;
num_bits += 7;
}
while (byte & 0x80);
return bits != 0;
}
}
<commit_msg>Avoid crash on missing last name<commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include <boost/algorithm/string.hpp>
#ifndef unix
#include <float.h>
#else
#include "CoreTypes.h"
#endif
#include "RexNetworkUtils.h"
#include "QuatUtils.h"
#include <QStringList>
namespace RexTypes
{
bool ParseBool(const std::string &value)
{
std::string testedvalue = value;
boost::algorithm::to_lower(testedvalue);
return (boost::algorithm::starts_with(testedvalue,"true") || boost::algorithm::starts_with(testedvalue,"1"));
}
Quaternion GetProcessedQuaternion(const uint8_t* bytes)
{
uint16_t *rot = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
Quaternion rotation = UnpackQuaternionFromU16_4(rot);
rotation.normalize();
return rotation;
}
Vector3df GetProcessedScaledVectorFromUint16(const uint8_t* bytes, float scale)
{
uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
Vector3df resultvector;
resultvector.x = scale * ((vec[0] / 32768.0f) - 1.0f);
resultvector.y = scale * ((vec[1] / 32768.0f) - 1.0f);
resultvector.z = scale * ((vec[2] / 32768.0f) - 1.0f);
return resultvector;
}
Vector3df GetProcessedVectorFromUint16(const uint8_t* bytes)
{
uint16_t *vec = reinterpret_cast<uint16_t*>((uint16_t*)&bytes[0]);
return Vector3df(vec[0],vec[1],vec[2]);
}
Vector3df GetProcessedVector(const uint8_t* bytes)
{
Vector3df resultvector = *reinterpret_cast<Vector3df*>((Vector3df*)&bytes[0]);
return resultvector;
}
bool IsValidPositionVector(const Vector3df &pos)
{
// This is a heuristic check to guard against the OpenSim server sending us stupid positions.
if (fabs(pos.x) > 1e6f || fabs(pos.y) > 1e6f || fabs(pos.z) > 1e6f)
return false;
if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z))
return false;
if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z))
return false;
return true;
}
bool IsValidVelocityVector(const Vector3df &pos)
{
// This is a heuristic check to guard against the OpenSim server sending us stupid velocity vectors.
if (fabs(pos.x) > 1e3f || fabs(pos.y) > 1e3f || fabs(pos.z) > 1e3f)
return false;
if (_isnan(pos.x) || _isnan(pos.y) || _isnan(pos.z))
return false;
if (!_finite(pos.x) || !_finite(pos.y) || !_finite(pos.z))
return false;
return true;
}
bool ReadBoolFromBytes(const uint8_t* bytes, int& idx)
{
bool result = *(bool*)(&bytes[idx]);
idx += sizeof(bool);
return result;
}
uint8_t ReadUInt8FromBytes(const uint8_t* bytes, int& idx)
{
uint8_t result = bytes[idx];
idx++;
return result;
}
uint16_t ReadUInt16FromBytes(const uint8_t* bytes, int& idx)
{
uint16_t result = *(uint16_t*)(&bytes[idx]);
idx += sizeof(uint16_t);
return result;
}
uint32_t ReadUInt32FromBytes(const uint8_t* bytes, int& idx)
{
uint32_t result = *(uint32_t*)(&bytes[idx]);
idx += sizeof(uint32_t);
return result;
}
int16_t ReadSInt16FromBytes(const uint8_t* bytes, int& idx)
{
int16_t result = *(int16_t*)(&bytes[idx]);
idx += sizeof(int16_t);
return result;
}
int32_t ReadSInt32FromBytes(const uint8_t* bytes, int& idx)
{
int32_t result = *(int32_t*)(&bytes[idx]);
idx += sizeof(int32_t);
return result;
}
float ReadFloatFromBytes(const uint8_t* bytes, int& idx)
{
float result = *(float*)(&bytes[idx]);
idx += sizeof(float);
return result;
}
RexUUID ReadUUIDFromBytes(const uint8_t* bytes, int& idx)
{
RexUUID result = *(RexUUID*)(&bytes[idx]);
idx += sizeof(RexUUID);
return result;
}
Color ReadColorFromBytes(const uint8_t* bytes, int& idx)
{
uint8_t r = bytes[idx++];
uint8_t g = bytes[idx++];
uint8_t b = bytes[idx++];
uint8_t a = bytes[idx++];
return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
}
Color ReadColorFromBytesInverted(const uint8_t* bytes, int& idx)
{
uint8_t r = 255 - bytes[idx++];
uint8_t g = 255 - bytes[idx++];
uint8_t b = 255 - bytes[idx++];
uint8_t a = 255 - bytes[idx++];
return Color(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);
}
std::string ReadNullTerminatedStringFromBytes(const uint8_t* bytes, int& idx)
{
std::string result = "";
uint8_t readbyte = bytes[idx];
idx++;
while(readbyte != 0)
{
result.push_back((char)readbyte);
readbyte = bytes[idx];
idx++;
}
return result;
}
void WriteBoolToBytes(bool value, uint8_t* bytes, int& idx)
{
bytes[idx] = (uint8_t)value;
idx++;
}
void WriteUInt8ToBytes(uint8_t value, uint8_t* bytes, int& idx)
{
bytes[idx] = value;
idx++;
}
void WriteUInt16ToBytes(uint16_t value, uint8_t* bytes, int& idx)
{
*(uint16_t*)(&bytes[idx]) = value;
idx += sizeof(uint16_t);
}
void WriteUInt32ToBytes(uint32_t value, uint8_t* bytes, int& idx)
{
*(uint32_t*)(&bytes[idx]) = value;
idx += sizeof(uint32_t);
}
void WriteFloatToBytes(float value, uint8_t* bytes, int& idx)
{
*(float*)(&bytes[idx]) = value;
idx += sizeof(float);
}
void WriteUUIDToBytes(const RexUUID &value, uint8_t* bytes, int& idx)
{
*(RexUUID*)(&bytes[idx]) = value;
idx += sizeof(RexUUID);
}
void WriteNullTerminatedStringToBytes(const std::string& value, uint8_t* bytes, int& idx)
{
const char* c_str = value.c_str();
memcpy(&bytes[idx], c_str, value.length() + 1);
idx += value.length() + 1;
}
NameValueMap ParseNameValueMap(const std::string& namevalue)
{
// NameValue contains: "FirstName STRING RW SV <firstName>\nLastName STRING RW SV <lastName>"
// When using rex auth <firstName> contains both first and last name and <lastName> contains the auth server address
// Split into lines
NameValueMap map;
StringVector lines = SplitString(namevalue, '\n');
for (unsigned i = 0; i < lines.size(); ++i)
{
StringVector line = SplitString(lines[i], ' ');
if (line.size() > 4)
{
// First element is the name
const std::string& name = line[0];
std::string value;
// Skip over the STRING RW SV etc. (3 values)
// Concatenate the rest of the values
for (unsigned j = 4; j < line.size(); ++j)
{
value += line[j];
if (j != line.size()-1)
value += " ";
}
map[name] = value;
}
}
// Parse auth server address out from the NameValue if it exists
QString fullname = QString(map["FirstName"].c_str()) + " " + QString(map["LastName"].c_str());
// Rex auth has: <First Last> <rex auth url>
if (fullname.count('@') == 1)
{
QStringList names;
if (fullname.contains('@'))
{
names = fullname.split(" ");
foreach(QString name, names)
{
if (name.contains('@'))
{
map["RexAuth"] = name.toStdString();
names.removeOne(name);
}
}
}
assert(names[0].size() >= 2);
if (names.length() >= 1)
map["FirstName"] = names[0].toStdString();
if (names.length() >= 2)
map["LastName"] = names[1].toStdString();
}
// Web auth has: <url> <url>
else if (fullname.count('@') == 2)
{
QStringList names = fullname.split(" ");
map["FirstName"] = names[0].toStdString();
map["LastName"] = "";
}
return map;
}
bool ReadTextureEntryBits(uint32_t& bits, int& num_bits, const uint8_t* bytes, int& idx)
{
bits = 0;
num_bits = 0;
uint8_t byte;
do
{
byte = bytes[idx++];
bits <<= 7;
bits |= byte & 0x7f;
num_bits += 7;
}
while (byte & 0x80);
return bits != 0;
}
}
<|endoftext|> |
<commit_before>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file EdsdkPropertyAccess.hpp EDSDK - Property access
//
#pragma once
// includes
#include "EdsdkCommon.hpp"
#include "Variant.hpp"
#include "ImageProperty.hpp"
#include <boost/noncopyable.hpp>
namespace EDSDK
{
/// unknown property (available on EOS 40D)
#define kEdsPropID_Unknown1 0x00000065
/// shutter counter property; can't be read out with newest SDK anymore
#define kEdsPropID_ShutterCounter 0x00000022
/// combined image or device property access
class PropertyAccess : public boost::noncopyable
{
public:
/// ctor
PropertyAccess(const Handle& h) throw()
:m_h(h)
{
}
/// gets property value
Variant Get(EdsPropertyID propId, int iParam = 0) const
{
// first, get type and size of property
EdsDataType dataType = kEdsDataType_Unknown;
EdsUInt32 size = 0;
GetTypeAndSize(propId, iParam, dataType, size);
// now get the data bytes
std::vector<BYTE> vecData(size);
EdsError err = EdsGetPropertyData(m_h, propId, iParam, size, &vecData[0]);
//LOG_TRACE(_T("EdsGetPropertyData(ref = %08x, id = %04x, param = %u, size = %u, &data) returned %08x\n"),
// m_h.Get(), propId, iParam, size, err);
EDSDK::CheckError(_T("EdsGetPropertyData"), err, __FILE__, __LINE__);
// convert to variant
Variant v;
SetRawEdsdk(v, dataType, vecData);
return v;
}
/// sets new property value
void Set(EdsPropertyID propId, Variant value, int iParam = 0)
{
// first, get type and size of property
EdsDataType dataType = kEdsDataType_Unknown;
EdsUInt32 size = 0;
GetTypeAndSize(propId, iParam, dataType, size);
// then generate data bytes from variant
std::vector<BYTE> vecData;
GetRawEdsdk(value, dataType, vecData);
LOG_TRACE(_T("Property [%s] set to value [%s]\n"),
PropertyAccess::NameFromId(propId),
PropertyAccess::DisplayTextFromIdAndValue(propId, value));
// now set the property
EdsError err = EdsSetPropertyData(m_h, propId, iParam, size, &vecData[0]);
if (err != EDS_ERR_OK) // only log errors here
LOG_TRACE(_T("EdsSetPropertyData(ref = %08x, id = %04x, param = %u, size = %u, &data) returned %08x\n"),
m_h.Get(), propId, iParam, size, err);
EDSDK::CheckError(_T("EdsSetPropertyData"), err, __FILE__, __LINE__);
}
/// enumerates possible property values
void Enum(EdsPropertyID propId, std::vector<Variant>& vecValues, bool& bReadOnly)
{
// note: since all properties that can be retrieved are of type UInt8, assume that
EdsPropertyDesc propDesc = {0};
EdsError err = EdsGetPropertyDesc(m_h, propId, &propDesc);
//LOG_TRACE(_T("EdsGetPropertyDesc(ref = %08x, id = %04x, &numProp = %u) returned %08x\n"),
// m_h.Get(), propId, propDesc.numElements, err);
EDSDK::CheckError(_T("EdsGetPropertyDesc"), err, __FILE__, __LINE__);
// note: this reinterpret cast assumes that EdsInt32 and EdsUInt32 have the same size
static_assert(sizeof(propDesc.propDesc[0]) == sizeof(EdsUInt32), "propDesc must have type and size EdsUInt32");
if (propDesc.access == 0)
bReadOnly = true;
if (propDesc.numElements > 0)
{
unsigned int* puiData = reinterpret_cast<unsigned int*>(propDesc.propDesc);
for (EdsInt32 i=0; i<propDesc.numElements; i++)
{
Variant v;
v.Set(puiData[i]);
v.SetType(Variant::typeUInt32);
vecValues.push_back(v);
}
}
}
/// returns if property currently is read only
bool IsReadOnly(EdsPropertyID propId) const
{
EdsPropertyDesc propDesc = {0};
EdsError err = EdsGetPropertyDesc(m_h, propId, &propDesc);
//LOG_TRACE(_T("EdsGetPropertyDesc(ref = %08x, id = %04x, &numProp = %u) returned %08x\n"),
// m_h.Get(), propId, propDesc.numElements, err);
EDSDK::CheckError(_T("EdsGetPropertyDesc"), err, __FILE__, __LINE__);
// note: this reinterpret cast assumes that EdsInt32 and EdsUInt32 have the same size
static_assert(sizeof(propDesc.propDesc[0]) == sizeof(EdsUInt32), "propDesc must have type and size EdsUInt32");
return (propDesc.access == 0);
}
/// returns type and size of given property
void GetTypeAndSize(EdsPropertyID propId, int iParam, EdsDataType& dataType, EdsUInt32& size) const
{
dataType = kEdsDataType_Unknown;
size = 0;
EdsError err = EdsGetPropertySize(m_h, propId, iParam, &dataType, &size);
//LOG_TRACE(_T("EdsGetPropertySize(ref = %08x, id = %04x, param = %u, &type = %u, &size = %u) returned %08x\n"),
// m_h.Get(), propId, iParam, dataType, size, err);
EDSDK::CheckError(_T("EdsGetPropertySize"), err, __FILE__, __LINE__);
// it seems white balance returns the wrong data type (Int32) here; fix this
if (propId == kEdsPropID_WhiteBalance)
dataType = kEdsDataType_UInt32;
}
/// returns if property is available
bool IsPropertyAvail(unsigned int uiPropId) const throw()
{
// check if property exists by retrieving type and size
EdsDataType dataType = kEdsDataType_Unknown;
EdsUInt32 size = 0;
EdsError err = EdsGetPropertySize(m_h.Get(), uiPropId, 0, &dataType, &size);
return (err == EDS_ERR_OK && dataType != kEdsDataType_Unknown);
}
/// enumerates device ids
void EnumDeviceIds(std::vector<unsigned int>& vecDeviceIds);
/// enumerates image ids
void EnumImageIds(std::vector<unsigned int>& vecImageIds);
/// sets raw bytes to given variant
static void SetRawEdsdk(Variant& v, unsigned int datatype, std::vector<unsigned char> vecData);
/// gets raw bytes from variant
static void GetRawEdsdk(const Variant& v, unsigned int datatype, std::vector<unsigned char>& vecData);
/// formats image format value
static CString FormatImageFormatValue(unsigned int uiValue);
/// maps property type to property id
static EdsPropertyID MapToPropertyID(T_enImagePropertyType enProperty) throw()
{
switch(enProperty)
{
case propShootingMode: return kEdsPropID_AEMode;//kEdsPropID_AEModeSelect;
case propDriveMode: return kEdsPropID_DriveMode;
case propISOSpeed: return kEdsPropID_ISOSpeed;
case propMeteringMode: return kEdsPropID_MeteringMode;
case propAFMode: return kEdsPropID_AFMode;
case propAv: return kEdsPropID_Av;
case propTv: return kEdsPropID_Tv;
case propExposureCompensation: return kEdsPropID_ExposureCompensation;
case propFlashExposureComp: return kEdsPropID_FlashCompensation;
case propFocalLength: return kEdsPropID_FocalLength;
case propFlashMode: return kEdsPropID_FlashMode;
case propWhiteBalance: return kEdsPropID_WhiteBalance;
case propAFDistance: return kEdsPropID_Unknown;
case propCurrentZoomPos: return kEdsPropID_Unknown;
case propMaxZoomPos: return kEdsPropID_Unknown;
case propAvailableShots: return kEdsPropID_AvailableShots;
case propSaveTo: return kEdsPropID_SaveTo;
case propBatteryLevel: return kEdsPropID_BatteryQuality;
default:
ATLASSERT(false);
return kEdsPropID_Unknown;
}
}
/// returns name from property id
static LPCTSTR NameFromId(EdsPropertyID propertyId) throw();
/// formats display text from id and value
static CString DisplayTextFromIdAndValue(EdsPropertyID /*propertyId*/, Variant value);
private:
/// handle to object
const Handle& m_h;
};
} // namespace EDSDK
<commit_msg>added propImageFormat to property mapping for ED-SDK<commit_after>//
// RemotePhotoTool - remote camera control software
// Copyright (C) 2008-2014 Michael Fink
//
/// \file EdsdkPropertyAccess.hpp EDSDK - Property access
//
#pragma once
// includes
#include "EdsdkCommon.hpp"
#include "Variant.hpp"
#include "ImageProperty.hpp"
#include <boost/noncopyable.hpp>
namespace EDSDK
{
/// unknown property (available on EOS 40D)
#define kEdsPropID_Unknown1 0x00000065
/// shutter counter property; can't be read out with newest SDK anymore
#define kEdsPropID_ShutterCounter 0x00000022
/// combined image or device property access
class PropertyAccess : public boost::noncopyable
{
public:
/// ctor
PropertyAccess(const Handle& h) throw()
:m_h(h)
{
}
/// gets property value
Variant Get(EdsPropertyID propId, int iParam = 0) const
{
// first, get type and size of property
EdsDataType dataType = kEdsDataType_Unknown;
EdsUInt32 size = 0;
GetTypeAndSize(propId, iParam, dataType, size);
// now get the data bytes
std::vector<BYTE> vecData(size);
EdsError err = EdsGetPropertyData(m_h, propId, iParam, size, &vecData[0]);
//LOG_TRACE(_T("EdsGetPropertyData(ref = %08x, id = %04x, param = %u, size = %u, &data) returned %08x\n"),
// m_h.Get(), propId, iParam, size, err);
EDSDK::CheckError(_T("EdsGetPropertyData"), err, __FILE__, __LINE__);
// convert to variant
Variant v;
SetRawEdsdk(v, dataType, vecData);
return v;
}
/// sets new property value
void Set(EdsPropertyID propId, Variant value, int iParam = 0)
{
// first, get type and size of property
EdsDataType dataType = kEdsDataType_Unknown;
EdsUInt32 size = 0;
GetTypeAndSize(propId, iParam, dataType, size);
// then generate data bytes from variant
std::vector<BYTE> vecData;
GetRawEdsdk(value, dataType, vecData);
LOG_TRACE(_T("Property [%s] set to value [%s]\n"),
PropertyAccess::NameFromId(propId),
PropertyAccess::DisplayTextFromIdAndValue(propId, value));
// now set the property
EdsError err = EdsSetPropertyData(m_h, propId, iParam, size, &vecData[0]);
if (err != EDS_ERR_OK) // only log errors here
LOG_TRACE(_T("EdsSetPropertyData(ref = %08x, id = %04x, param = %u, size = %u, &data) returned %08x\n"),
m_h.Get(), propId, iParam, size, err);
EDSDK::CheckError(_T("EdsSetPropertyData"), err, __FILE__, __LINE__);
}
/// enumerates possible property values
void Enum(EdsPropertyID propId, std::vector<Variant>& vecValues, bool& bReadOnly)
{
// note: since all properties that can be retrieved are of type UInt8, assume that
EdsPropertyDesc propDesc = {0};
EdsError err = EdsGetPropertyDesc(m_h, propId, &propDesc);
//LOG_TRACE(_T("EdsGetPropertyDesc(ref = %08x, id = %04x, &numProp = %u) returned %08x\n"),
// m_h.Get(), propId, propDesc.numElements, err);
EDSDK::CheckError(_T("EdsGetPropertyDesc"), err, __FILE__, __LINE__);
// note: this reinterpret cast assumes that EdsInt32 and EdsUInt32 have the same size
static_assert(sizeof(propDesc.propDesc[0]) == sizeof(EdsUInt32), "propDesc must have type and size EdsUInt32");
if (propDesc.access == 0)
bReadOnly = true;
if (propDesc.numElements > 0)
{
unsigned int* puiData = reinterpret_cast<unsigned int*>(propDesc.propDesc);
for (EdsInt32 i=0; i<propDesc.numElements; i++)
{
Variant v;
v.Set(puiData[i]);
v.SetType(Variant::typeUInt32);
vecValues.push_back(v);
}
}
}
/// returns if property currently is read only
bool IsReadOnly(EdsPropertyID propId) const
{
EdsPropertyDesc propDesc = {0};
EdsError err = EdsGetPropertyDesc(m_h, propId, &propDesc);
//LOG_TRACE(_T("EdsGetPropertyDesc(ref = %08x, id = %04x, &numProp = %u) returned %08x\n"),
// m_h.Get(), propId, propDesc.numElements, err);
EDSDK::CheckError(_T("EdsGetPropertyDesc"), err, __FILE__, __LINE__);
// note: this reinterpret cast assumes that EdsInt32 and EdsUInt32 have the same size
static_assert(sizeof(propDesc.propDesc[0]) == sizeof(EdsUInt32), "propDesc must have type and size EdsUInt32");
return (propDesc.access == 0);
}
/// returns type and size of given property
void GetTypeAndSize(EdsPropertyID propId, int iParam, EdsDataType& dataType, EdsUInt32& size) const
{
dataType = kEdsDataType_Unknown;
size = 0;
EdsError err = EdsGetPropertySize(m_h, propId, iParam, &dataType, &size);
//LOG_TRACE(_T("EdsGetPropertySize(ref = %08x, id = %04x, param = %u, &type = %u, &size = %u) returned %08x\n"),
// m_h.Get(), propId, iParam, dataType, size, err);
EDSDK::CheckError(_T("EdsGetPropertySize"), err, __FILE__, __LINE__);
// it seems white balance returns the wrong data type (Int32) here; fix this
if (propId == kEdsPropID_WhiteBalance)
dataType = kEdsDataType_UInt32;
}
/// returns if property is available
bool IsPropertyAvail(unsigned int uiPropId) const throw()
{
// check if property exists by retrieving type and size
EdsDataType dataType = kEdsDataType_Unknown;
EdsUInt32 size = 0;
EdsError err = EdsGetPropertySize(m_h.Get(), uiPropId, 0, &dataType, &size);
return (err == EDS_ERR_OK && dataType != kEdsDataType_Unknown);
}
/// enumerates device ids
void EnumDeviceIds(std::vector<unsigned int>& vecDeviceIds);
/// enumerates image ids
void EnumImageIds(std::vector<unsigned int>& vecImageIds);
/// sets raw bytes to given variant
static void SetRawEdsdk(Variant& v, unsigned int datatype, std::vector<unsigned char> vecData);
/// gets raw bytes from variant
static void GetRawEdsdk(const Variant& v, unsigned int datatype, std::vector<unsigned char>& vecData);
/// formats image format value
static CString FormatImageFormatValue(unsigned int uiValue);
/// maps property type to property id
static EdsPropertyID MapToPropertyID(T_enImagePropertyType enProperty) throw()
{
switch(enProperty)
{
case propShootingMode: return kEdsPropID_AEMode;//kEdsPropID_AEModeSelect;
case propDriveMode: return kEdsPropID_DriveMode;
case propISOSpeed: return kEdsPropID_ISOSpeed;
case propMeteringMode: return kEdsPropID_MeteringMode;
case propAFMode: return kEdsPropID_AFMode;
case propAv: return kEdsPropID_Av;
case propTv: return kEdsPropID_Tv;
case propExposureCompensation: return kEdsPropID_ExposureCompensation;
case propFlashExposureComp: return kEdsPropID_FlashCompensation;
case propFocalLength: return kEdsPropID_FocalLength;
case propFlashMode: return kEdsPropID_FlashMode;
case propWhiteBalance: return kEdsPropID_WhiteBalance;
case propAFDistance: return kEdsPropID_Unknown;
case propCurrentZoomPos: return kEdsPropID_Unknown;
case propMaxZoomPos: return kEdsPropID_Unknown;
case propAvailableShots: return kEdsPropID_AvailableShots;
case propSaveTo: return kEdsPropID_SaveTo;
case propBatteryLevel: return kEdsPropID_BatteryQuality;
case propImageFormat: return kEdsPropID_ImageQuality;
default:
ATLASSERT(false);
return kEdsPropID_Unknown;
}
}
/// returns name from property id
static LPCTSTR NameFromId(EdsPropertyID propertyId) throw();
/// formats display text from id and value
static CString DisplayTextFromIdAndValue(EdsPropertyID /*propertyId*/, Variant value);
private:
/// handle to object
const Handle& m_h;
};
} // namespace EDSDK
<|endoftext|> |
<commit_before>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCodec.h"
#include "SkCodecPriv.h"
#include "SkMath.h"
#include "SkSampledCodec.h"
SkSampledCodec::SkSampledCodec(SkCodec* codec)
: INHERITED(codec->getInfo())
, fCodec(codec)
{}
SkISize SkSampledCodec::accountForNativeScaling(int* sampleSizePtr, int* nativeSampleSize) const {
SkISize preSampledSize = fCodec->getInfo().dimensions();
int sampleSize = *sampleSizePtr;
SkASSERT(sampleSize > 1);
if (nativeSampleSize) {
*nativeSampleSize = 1;
}
// Only JPEG supports native downsampling.
if (fCodec->getEncodedFormat() == kJPEG_SkEncodedFormat) {
// See if libjpeg supports this scale directly
switch (sampleSize) {
case 2:
case 4:
case 8:
// This class does not need to do any sampling.
*sampleSizePtr = 1;
return fCodec->getScaledDimensions(get_scale_from_sample_size(sampleSize));
default:
break;
}
// Check if sampleSize is a multiple of something libjpeg can support.
int remainder;
const int sampleSizes[] = { 8, 4, 2 };
for (int supportedSampleSize : sampleSizes) {
int actualSampleSize;
SkTDivMod(sampleSize, supportedSampleSize, &actualSampleSize, &remainder);
if (0 == remainder) {
float scale = get_scale_from_sample_size(supportedSampleSize);
// fCodec will scale to this size.
preSampledSize = fCodec->getScaledDimensions(scale);
// And then this class will sample it.
*sampleSizePtr = actualSampleSize;
if (nativeSampleSize) {
*nativeSampleSize = supportedSampleSize;
}
break;
}
}
}
return preSampledSize;
}
SkISize SkSampledCodec::onGetSampledDimensions(int sampleSize) const {
const SkISize size = this->accountForNativeScaling(&sampleSize);
return SkISize::Make(get_scaled_dimension(size.width(), sampleSize),
get_scaled_dimension(size.height(), sampleSize));
}
SkCodec::Result SkSampledCodec::onGetAndroidPixels(const SkImageInfo& info, void* pixels,
size_t rowBytes, const AndroidOptions& options) {
// Create an Options struct for the codec.
SkCodec::Options codecOptions;
codecOptions.fZeroInitialized = options.fZeroInitialized;
SkIRect* subset = options.fSubset;
if (!subset || subset->size() == fCodec->getInfo().dimensions()) {
if (fCodec->dimensionsSupported(info.dimensions())) {
return fCodec->getPixels(info, pixels, rowBytes, &codecOptions, options.fColorPtr,
options.fColorCount);
}
// If the native codec does not support the requested scale, scale by sampling.
return this->sampledDecode(info, pixels, rowBytes, options);
}
// We are performing a subset decode.
int sampleSize = options.fSampleSize;
SkISize scaledSize = this->getSampledDimensions(sampleSize);
if (!fCodec->dimensionsSupported(scaledSize)) {
// If the native codec does not support the requested scale, scale by sampling.
return this->sampledDecode(info, pixels, rowBytes, options);
}
// Calculate the scaled subset bounds.
int scaledSubsetX = subset->x() / sampleSize;
int scaledSubsetY = subset->y() / sampleSize;
int scaledSubsetWidth = info.width();
int scaledSubsetHeight = info.height();
// Start the scanline decode.
SkIRect scanlineSubset = SkIRect::MakeXYWH(scaledSubsetX, 0, scaledSubsetWidth,
scaledSize.height());
codecOptions.fSubset = &scanlineSubset;
SkCodec::Result result = fCodec->startScanlineDecode(info.makeWH(scaledSize.width(),
scaledSize.height()), &codecOptions, options.fColorPtr, options.fColorCount);
if (SkCodec::kSuccess != result) {
return result;
}
// At this point, we are only concerned with subsetting. Either no scale was
// requested, or the fCodec is handling the scale.
switch (fCodec->getScanlineOrder()) {
case SkCodec::kTopDown_SkScanlineOrder:
case SkCodec::kNone_SkScanlineOrder: {
if (!fCodec->skipScanlines(scaledSubsetY)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
scaledSubsetHeight, 0);
return SkCodec::kIncompleteInput;
}
int decodedLines = fCodec->getScanlines(pixels, scaledSubsetHeight, rowBytes);
if (decodedLines != scaledSubsetHeight) {
return SkCodec::kIncompleteInput;
}
return SkCodec::kSuccess;
}
default:
SkASSERT(false);
return SkCodec::kUnimplemented;
}
}
SkCodec::Result SkSampledCodec::sampledDecode(const SkImageInfo& info, void* pixels,
size_t rowBytes, const AndroidOptions& options) {
// We should only call this function when sampling.
SkASSERT(options.fSampleSize > 1);
// Create options struct for the codec.
SkCodec::Options sampledOptions;
sampledOptions.fZeroInitialized = options.fZeroInitialized;
// FIXME: This was already called by onGetAndroidPixels. Can we reduce that?
int sampleSize = options.fSampleSize;
int nativeSampleSize;
SkISize nativeSize = this->accountForNativeScaling(&sampleSize, &nativeSampleSize);
// Check if there is a subset.
SkIRect subset;
int subsetY = 0;
int subsetWidth = nativeSize.width();
int subsetHeight = nativeSize.height();
if (options.fSubset) {
// We will need to know about subsetting in the y-dimension in order to use the
// scanline decoder.
// Update the subset to account for scaling done by fCodec.
SkIRect* subsetPtr = options.fSubset;
// Do the divide ourselves, instead of calling get_scaled_dimension. If
// X and Y are 0, they should remain 0, rather than being upgraded to 1
// due to being smaller than the sampleSize.
const int subsetX = subsetPtr->x() / nativeSampleSize;
subsetY = subsetPtr->y() / nativeSampleSize;
subsetWidth = get_scaled_dimension(subsetPtr->width(), nativeSampleSize);
subsetHeight = get_scaled_dimension(subsetPtr->height(), nativeSampleSize);
// The scanline decoder only needs to be aware of subsetting in the x-dimension.
subset.setXYWH(subsetX, 0, subsetWidth, nativeSize.height());
sampledOptions.fSubset = ⊂
}
// Start the scanline decode.
SkCodec::Result result = fCodec->startScanlineDecode(
info.makeWH(nativeSize.width(), nativeSize.height()), &sampledOptions,
options.fColorPtr, options.fColorCount);
if (SkCodec::kSuccess != result) {
return result;
}
SkSampler* sampler = fCodec->getSampler(true);
if (!sampler) {
return SkCodec::kUnimplemented;
}
// Since we guarantee that output dimensions are always at least one (even if the sampleSize
// is greater than a given dimension), the input sampleSize is not always the sampleSize that
// we use in practice.
const int sampleX = subsetWidth / info.width();
const int sampleY = subsetHeight / info.height();
if (sampler->setSampleX(sampleX) != info.width()) {
return SkCodec::kInvalidScale;
}
if (get_scaled_dimension(subsetHeight, sampleY) != info.height()) {
return SkCodec::kInvalidScale;
}
const int samplingOffsetY = get_start_coord(sampleY);
const int startY = samplingOffsetY + subsetY;
int dstHeight = info.height();
switch(fCodec->getScanlineOrder()) {
case SkCodec::kTopDown_SkScanlineOrder: {
if (!fCodec->skipScanlines(startY)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
dstHeight, 0);
return SkCodec::kIncompleteInput;
}
void* pixelPtr = pixels;
for (int y = 0; y < dstHeight; y++) {
if (1 != fCodec->getScanlines(pixelPtr, 1, rowBytes)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
dstHeight, y + 1);
return SkCodec::kIncompleteInput;
}
int linesToSkip = SkTMin(sampleY - 1, dstHeight - y - 1);
if (!fCodec->skipScanlines(linesToSkip)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
dstHeight, y + 1);
return SkCodec::kIncompleteInput;
}
pixelPtr = SkTAddOffset<void>(pixelPtr, rowBytes);
}
return SkCodec::kSuccess;
}
case SkCodec::kNone_SkScanlineOrder: {
const int linesNeeded = subsetHeight - samplingOffsetY;
SkAutoMalloc storage(linesNeeded * rowBytes);
uint8_t* storagePtr = static_cast<uint8_t*>(storage.get());
if (!fCodec->skipScanlines(startY)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
dstHeight, 0);
return SkCodec::kIncompleteInput;
}
int scanlines = fCodec->getScanlines(storagePtr, linesNeeded, rowBytes);
for (int y = 0; y < dstHeight; y++) {
memcpy(pixels, storagePtr, info.minRowBytes());
storagePtr += sampleY * rowBytes;
pixels = SkTAddOffset<void>(pixels, rowBytes);
}
if (scanlines < dstHeight) {
// fCodec has already handled filling uninitialized memory.
return SkCodec::kIncompleteInput;
}
return SkCodec::kSuccess;
}
default:
SkASSERT(false);
return SkCodec::kUnimplemented;
}
}
<commit_msg>Fix bug in sampled decodes<commit_after>/*
* Copyright 2015 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCodec.h"
#include "SkCodecPriv.h"
#include "SkMath.h"
#include "SkSampledCodec.h"
SkSampledCodec::SkSampledCodec(SkCodec* codec)
: INHERITED(codec->getInfo())
, fCodec(codec)
{}
SkISize SkSampledCodec::accountForNativeScaling(int* sampleSizePtr, int* nativeSampleSize) const {
SkISize preSampledSize = fCodec->getInfo().dimensions();
int sampleSize = *sampleSizePtr;
SkASSERT(sampleSize > 1);
if (nativeSampleSize) {
*nativeSampleSize = 1;
}
// Only JPEG supports native downsampling.
if (fCodec->getEncodedFormat() == kJPEG_SkEncodedFormat) {
// See if libjpeg supports this scale directly
switch (sampleSize) {
case 2:
case 4:
case 8:
// This class does not need to do any sampling.
*sampleSizePtr = 1;
return fCodec->getScaledDimensions(get_scale_from_sample_size(sampleSize));
default:
break;
}
// Check if sampleSize is a multiple of something libjpeg can support.
int remainder;
const int sampleSizes[] = { 8, 4, 2 };
for (int supportedSampleSize : sampleSizes) {
int actualSampleSize;
SkTDivMod(sampleSize, supportedSampleSize, &actualSampleSize, &remainder);
if (0 == remainder) {
float scale = get_scale_from_sample_size(supportedSampleSize);
// fCodec will scale to this size.
preSampledSize = fCodec->getScaledDimensions(scale);
// And then this class will sample it.
*sampleSizePtr = actualSampleSize;
if (nativeSampleSize) {
*nativeSampleSize = supportedSampleSize;
}
break;
}
}
}
return preSampledSize;
}
SkISize SkSampledCodec::onGetSampledDimensions(int sampleSize) const {
const SkISize size = this->accountForNativeScaling(&sampleSize);
return SkISize::Make(get_scaled_dimension(size.width(), sampleSize),
get_scaled_dimension(size.height(), sampleSize));
}
SkCodec::Result SkSampledCodec::onGetAndroidPixels(const SkImageInfo& info, void* pixels,
size_t rowBytes, const AndroidOptions& options) {
// Create an Options struct for the codec.
SkCodec::Options codecOptions;
codecOptions.fZeroInitialized = options.fZeroInitialized;
SkIRect* subset = options.fSubset;
if (!subset || subset->size() == fCodec->getInfo().dimensions()) {
if (fCodec->dimensionsSupported(info.dimensions())) {
return fCodec->getPixels(info, pixels, rowBytes, &codecOptions, options.fColorPtr,
options.fColorCount);
}
// If the native codec does not support the requested scale, scale by sampling.
return this->sampledDecode(info, pixels, rowBytes, options);
}
// We are performing a subset decode.
int sampleSize = options.fSampleSize;
SkISize scaledSize = this->getSampledDimensions(sampleSize);
if (!fCodec->dimensionsSupported(scaledSize)) {
// If the native codec does not support the requested scale, scale by sampling.
return this->sampledDecode(info, pixels, rowBytes, options);
}
// Calculate the scaled subset bounds.
int scaledSubsetX = subset->x() / sampleSize;
int scaledSubsetY = subset->y() / sampleSize;
int scaledSubsetWidth = info.width();
int scaledSubsetHeight = info.height();
// Start the scanline decode.
SkIRect scanlineSubset = SkIRect::MakeXYWH(scaledSubsetX, 0, scaledSubsetWidth,
scaledSize.height());
codecOptions.fSubset = &scanlineSubset;
SkCodec::Result result = fCodec->startScanlineDecode(info.makeWH(scaledSize.width(),
scaledSize.height()), &codecOptions, options.fColorPtr, options.fColorCount);
if (SkCodec::kSuccess != result) {
return result;
}
// At this point, we are only concerned with subsetting. Either no scale was
// requested, or the fCodec is handling the scale.
switch (fCodec->getScanlineOrder()) {
case SkCodec::kTopDown_SkScanlineOrder:
case SkCodec::kNone_SkScanlineOrder: {
if (!fCodec->skipScanlines(scaledSubsetY)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
scaledSubsetHeight, 0);
return SkCodec::kIncompleteInput;
}
int decodedLines = fCodec->getScanlines(pixels, scaledSubsetHeight, rowBytes);
if (decodedLines != scaledSubsetHeight) {
return SkCodec::kIncompleteInput;
}
return SkCodec::kSuccess;
}
default:
SkASSERT(false);
return SkCodec::kUnimplemented;
}
}
SkCodec::Result SkSampledCodec::sampledDecode(const SkImageInfo& info, void* pixels,
size_t rowBytes, const AndroidOptions& options) {
// We should only call this function when sampling.
SkASSERT(options.fSampleSize > 1);
// Create options struct for the codec.
SkCodec::Options sampledOptions;
sampledOptions.fZeroInitialized = options.fZeroInitialized;
// FIXME: This was already called by onGetAndroidPixels. Can we reduce that?
int sampleSize = options.fSampleSize;
int nativeSampleSize;
SkISize nativeSize = this->accountForNativeScaling(&sampleSize, &nativeSampleSize);
// Check if there is a subset.
SkIRect subset;
int subsetY = 0;
int subsetWidth = nativeSize.width();
int subsetHeight = nativeSize.height();
if (options.fSubset) {
// We will need to know about subsetting in the y-dimension in order to use the
// scanline decoder.
// Update the subset to account for scaling done by fCodec.
SkIRect* subsetPtr = options.fSubset;
// Do the divide ourselves, instead of calling get_scaled_dimension. If
// X and Y are 0, they should remain 0, rather than being upgraded to 1
// due to being smaller than the sampleSize.
const int subsetX = subsetPtr->x() / nativeSampleSize;
subsetY = subsetPtr->y() / nativeSampleSize;
subsetWidth = get_scaled_dimension(subsetPtr->width(), nativeSampleSize);
subsetHeight = get_scaled_dimension(subsetPtr->height(), nativeSampleSize);
// The scanline decoder only needs to be aware of subsetting in the x-dimension.
subset.setXYWH(subsetX, 0, subsetWidth, nativeSize.height());
sampledOptions.fSubset = ⊂
}
// Start the scanline decode.
SkCodec::Result result = fCodec->startScanlineDecode(
info.makeWH(nativeSize.width(), nativeSize.height()), &sampledOptions,
options.fColorPtr, options.fColorCount);
if (SkCodec::kSuccess != result) {
return result;
}
SkSampler* sampler = fCodec->getSampler(true);
if (!sampler) {
return SkCodec::kUnimplemented;
}
// Since we guarantee that output dimensions are always at least one (even if the sampleSize
// is greater than a given dimension), the input sampleSize is not always the sampleSize that
// we use in practice.
const int sampleX = subsetWidth / info.width();
const int sampleY = subsetHeight / info.height();
if (sampler->setSampleX(sampleX) != info.width()) {
return SkCodec::kInvalidScale;
}
if (get_scaled_dimension(subsetHeight, sampleY) != info.height()) {
return SkCodec::kInvalidScale;
}
const int samplingOffsetY = get_start_coord(sampleY);
const int startY = samplingOffsetY + subsetY;
int dstHeight = info.height();
switch(fCodec->getScanlineOrder()) {
case SkCodec::kTopDown_SkScanlineOrder: {
if (!fCodec->skipScanlines(startY)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
dstHeight, 0);
return SkCodec::kIncompleteInput;
}
void* pixelPtr = pixels;
for (int y = 0; y < dstHeight; y++) {
if (1 != fCodec->getScanlines(pixelPtr, 1, rowBytes)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
dstHeight, y + 1);
return SkCodec::kIncompleteInput;
}
if (y < dstHeight - 1) {
if (!fCodec->skipScanlines(sampleY - 1)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes,
options.fZeroInitialized, dstHeight, y + 1);
return SkCodec::kIncompleteInput;
}
}
pixelPtr = SkTAddOffset<void>(pixelPtr, rowBytes);
}
return SkCodec::kSuccess;
}
case SkCodec::kNone_SkScanlineOrder: {
const int linesNeeded = subsetHeight - samplingOffsetY;
SkAutoMalloc storage(linesNeeded * rowBytes);
uint8_t* storagePtr = static_cast<uint8_t*>(storage.get());
if (!fCodec->skipScanlines(startY)) {
fCodec->fillIncompleteImage(info, pixels, rowBytes, options.fZeroInitialized,
dstHeight, 0);
return SkCodec::kIncompleteInput;
}
int scanlines = fCodec->getScanlines(storagePtr, linesNeeded, rowBytes);
for (int y = 0; y < dstHeight; y++) {
memcpy(pixels, storagePtr, info.minRowBytes());
storagePtr += sampleY * rowBytes;
pixels = SkTAddOffset<void>(pixels, rowBytes);
}
if (scanlines < dstHeight) {
// fCodec has already handled filling uninitialized memory.
return SkCodec::kIncompleteInput;
}
return SkCodec::kSuccess;
}
default:
SkASSERT(false);
return SkCodec::kUnimplemented;
}
}
<|endoftext|> |
<commit_before>#include <IO/AssimpLoader/AssimpFileLoader.hpp>
#include <Core/Asset/FileData.hpp>
#include <Core/Utils/StringUtils.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <IO/AssimpLoader/AssimpAnimationDataLoader.hpp>
#include <IO/AssimpLoader/AssimpCameraDataLoader.hpp>
#include <IO/AssimpLoader/AssimpGeometryDataLoader.hpp>
#include <IO/AssimpLoader/AssimpHandleDataLoader.hpp>
#include <IO/AssimpLoader/AssimpLightDataLoader.hpp>
#include <iostream>
namespace Ra {
namespace IO {
using namespace Core::Utils; // log
using namespace Core::Asset;
AssimpFileLoader::AssimpFileLoader() = default;
AssimpFileLoader::~AssimpFileLoader() = default;
std::vector<std::string> AssimpFileLoader::getFileExtensions() const {
std::string extensionsList;
m_importer.GetExtensionList( extensionsList );
// source: https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/
std::istringstream iss( extensionsList );
std::string ext;
std::vector<std::string> extensions;
while ( std::getline( iss, ext, ';' ) )
{
extensions.push_back( ext );
}
return extensions;
}
bool AssimpFileLoader::handleFileExtension( const std::string& extension ) const {
return m_importer.IsExtensionSupported( extension );
}
FileData* AssimpFileLoader::loadFile( const std::string& filename ) {
auto fileData = new FileData( filename );
if ( !fileData->isInitialized() ) { return nullptr; }
const aiScene* scene = m_importer.ReadFile(
fileData->getFileName(),
aiProcess_GenSmoothNormals | aiProcess_SortByPType | aiProcess_FixInfacingNormals |
aiProcess_CalcTangentSpace | aiProcess_GenUVCoords );
if ( scene == nullptr )
{
LOG( logINFO ) << "File \"" << fileData->getFileName()
<< "\" assimp error : " << m_importer.GetErrorString() << ".";
return nullptr;
}
if ( fileData->isVerbose() ) { LOG( logINFO ) << "File Loading begin..."; }
std::clock_t startTime;
startTime = std::clock();
// FIXME : this workaround is related to assimp issue
// #2260 Mesh created for a light only file (collada)
// https://github.com/assimp/assimp/issues/2260
if ( scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE )
{
LOG( logWARNING )
<< " ai scene is incomplete, just try to load lights or skeletons (but not both).";
AssimpLightDataLoader lightLoader( Core::Utils::getDirName( filename ),
fileData->isVerbose() );
lightLoader.loadData( scene, fileData->m_lightData );
if ( !fileData->hasLight() )
{
AssimpHandleDataLoader handleLoader( fileData->isVerbose() );
handleLoader.loadData( scene, fileData->m_handleData );
AssimpAnimationDataLoader animationLoader( fileData->isVerbose() );
animationLoader.loadData( scene, fileData->m_animationData );
}
}
else
{
AssimpGeometryDataLoader geometryLoader( Core::Utils::getDirName( filename ),
fileData->isVerbose() );
geometryLoader.loadData( scene, fileData->m_geometryData );
// check if that the scene contains at least one mesh
// Note that currently, Assimp is ALWAYS creating faces, even when
// loading point clouds
// (see 3rdPartyLibraries/Assimp/code/PlyLoader.cpp:260)
bool ok = std::any_of( fileData->m_geometryData.begin(),
fileData->m_geometryData.end(),
[]( const auto& geom ) -> bool { return geom->hasFaces(); } );
if ( !ok )
{
if ( fileData->isVerbose() ) { LOG( logINFO ) << "Point-cloud found. Aborting"; }
delete fileData;
return nullptr;
}
AssimpHandleDataLoader handleLoader( fileData->isVerbose() );
handleLoader.loadData( scene, fileData->m_handleData );
AssimpAnimationDataLoader animationLoader( fileData->isVerbose() );
animationLoader.loadData( scene, fileData->m_animationData );
AssimpLightDataLoader lightLoader( Core::Utils::getDirName( filename ),
fileData->isVerbose() );
lightLoader.loadData( scene, fileData->m_lightData );
AssimpCameraDataLoader cameraLoader( fileData->isVerbose() );
cameraLoader.loadData( scene, fileData->m_cameraData );
}
fileData->m_loadingTime = ( std::clock() - startTime ) / Scalar( CLOCKS_PER_SEC );
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "File Loading end.";
fileData->displayInfo();
}
fileData->m_processed = true;
return fileData;
}
std::string AssimpFileLoader::name() const {
return "Assimp";
}
} // namespace IO
} // namespace Ra
<commit_msg>Remove FixInfacingNormals assimp process<commit_after>#include <IO/AssimpLoader/AssimpFileLoader.hpp>
#include <Core/Asset/FileData.hpp>
#include <Core/Utils/StringUtils.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include <IO/AssimpLoader/AssimpAnimationDataLoader.hpp>
#include <IO/AssimpLoader/AssimpCameraDataLoader.hpp>
#include <IO/AssimpLoader/AssimpGeometryDataLoader.hpp>
#include <IO/AssimpLoader/AssimpHandleDataLoader.hpp>
#include <IO/AssimpLoader/AssimpLightDataLoader.hpp>
#include <iostream>
namespace Ra {
namespace IO {
using namespace Core::Utils; // log
using namespace Core::Asset;
AssimpFileLoader::AssimpFileLoader() = default;
AssimpFileLoader::~AssimpFileLoader() = default;
std::vector<std::string> AssimpFileLoader::getFileExtensions() const {
std::string extensionsList;
m_importer.GetExtensionList( extensionsList );
// source: https://www.fluentcpp.com/2017/04/21/how-to-split-a-string-in-c/
std::istringstream iss( extensionsList );
std::string ext;
std::vector<std::string> extensions;
while ( std::getline( iss, ext, ';' ) )
{
extensions.push_back( ext );
}
return extensions;
}
bool AssimpFileLoader::handleFileExtension( const std::string& extension ) const {
return m_importer.IsExtensionSupported( extension );
}
FileData* AssimpFileLoader::loadFile( const std::string& filename ) {
auto fileData = new FileData( filename );
if ( !fileData->isInitialized() ) { return nullptr; }
/*
* TODO : allow user to parameterize assimp process on loaded meshes
*/
const aiScene* scene =
m_importer.ReadFile( fileData->getFileName(),
aiProcess_GenSmoothNormals | aiProcess_SortByPType |
aiProcess_CalcTangentSpace | aiProcess_GenUVCoords );
if ( scene == nullptr )
{
LOG( logINFO ) << "File \"" << fileData->getFileName()
<< "\" assimp error : " << m_importer.GetErrorString() << ".";
return nullptr;
}
if ( fileData->isVerbose() ) { LOG( logINFO ) << "File Loading begin..."; }
std::clock_t startTime;
startTime = std::clock();
// FIXME : this workaround is related to assimp issue
// #2260 Mesh created for a light only file (collada)
// https://github.com/assimp/assimp/issues/2260
if ( scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE )
{
LOG( logWARNING )
<< " ai scene is incomplete, just try to load lights or skeletons (but not both).";
AssimpLightDataLoader lightLoader( Core::Utils::getDirName( filename ),
fileData->isVerbose() );
lightLoader.loadData( scene, fileData->m_lightData );
if ( !fileData->hasLight() )
{
AssimpHandleDataLoader handleLoader( fileData->isVerbose() );
handleLoader.loadData( scene, fileData->m_handleData );
AssimpAnimationDataLoader animationLoader( fileData->isVerbose() );
animationLoader.loadData( scene, fileData->m_animationData );
}
}
else
{
AssimpGeometryDataLoader geometryLoader( Core::Utils::getDirName( filename ),
fileData->isVerbose() );
geometryLoader.loadData( scene, fileData->m_geometryData );
// check if that the scene contains at least one mesh
// Note that currently, Assimp is ALWAYS creating faces, even when
// loading point clouds
// (see 3rdPartyLibraries/Assimp/code/PlyLoader.cpp:260)
bool ok = std::any_of( fileData->m_geometryData.begin(),
fileData->m_geometryData.end(),
[]( const auto& geom ) -> bool { return geom->hasFaces(); } );
if ( !ok )
{
if ( fileData->isVerbose() ) { LOG( logINFO ) << "Point-cloud found. Aborting"; }
delete fileData;
return nullptr;
}
AssimpHandleDataLoader handleLoader( fileData->isVerbose() );
handleLoader.loadData( scene, fileData->m_handleData );
AssimpAnimationDataLoader animationLoader( fileData->isVerbose() );
animationLoader.loadData( scene, fileData->m_animationData );
AssimpLightDataLoader lightLoader( Core::Utils::getDirName( filename ),
fileData->isVerbose() );
lightLoader.loadData( scene, fileData->m_lightData );
AssimpCameraDataLoader cameraLoader( fileData->isVerbose() );
cameraLoader.loadData( scene, fileData->m_cameraData );
}
fileData->m_loadingTime = ( std::clock() - startTime ) / Scalar( CLOCKS_PER_SEC );
if ( fileData->isVerbose() )
{
LOG( logINFO ) << "File Loading end.";
fileData->displayInfo();
}
fileData->m_processed = true;
return fileData;
}
std::string AssimpFileLoader::name() const {
return "Assimp";
}
} // namespace IO
} // namespace Ra
<|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. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the V0 vertexer class
// reads tracks writes out V0 vertices
// fills the ESD with the V0s
// Origin: Iouri Belikov, IPHC, Strasbourg, [email protected]
//-------------------------------------------------------------------------
#include "AliESDEvent.h"
#include "AliESDv0.h"
#include "AliV0vertexer.h"
ClassImp(AliV0vertexer)
//A set of very loose cuts
Double_t AliV0vertexer::fgChi2max=33.; //max chi2
Double_t AliV0vertexer::fgDNmin=0.05; //min imp parameter for the 1st daughter
Double_t AliV0vertexer::fgDPmin=0.05; //min imp parameter for the 2nd daughter
Double_t AliV0vertexer::fgDCAmax=1.5; //max DCA between the daughter tracks
Double_t AliV0vertexer::fgCPAmin=0.9; //min cosine of V0's pointing angle
Double_t AliV0vertexer::fgRmin=0.2; //min radius of the fiducial volume
Double_t AliV0vertexer::fgRmax=200.; //max radius of the fiducial volume
Int_t AliV0vertexer::Tracks2V0vertices(AliESDEvent *event) {
//--------------------------------------------------------------------
//This function reconstructs V0 vertices
//--------------------------------------------------------------------
const AliESDVertex *vtxT3D=event->GetPrimaryVertex();
Double_t xPrimaryVertex=vtxT3D->GetXv();
Double_t yPrimaryVertex=vtxT3D->GetYv();
Double_t zPrimaryVertex=vtxT3D->GetZv();
Int_t nentr=event->GetNumberOfTracks();
Double_t b=event->GetMagneticField();
if (nentr<2) return 0;
TArrayI neg(nentr);
TArrayI pos(nentr);
Int_t nneg=0, npos=0, nvtx=0;
Int_t i;
for (i=0; i<nentr; i++) {
AliESDtrack *esdTrack=event->GetTrack(i);
ULong_t status=esdTrack->GetStatus();
//if ((status&AliESDtrack::kITSrefit)==0)//not to accept the ITS SA tracks
if ((status&AliESDtrack::kTPCrefit)==0) continue;
Double_t d=esdTrack->GetD(xPrimaryVertex,yPrimaryVertex,b);
if (TMath::Abs(d)<fDPmin) continue;
if (TMath::Abs(d)>fRmax) continue;
if (esdTrack->GetSign() < 0.) neg[nneg++]=i;
else pos[npos++]=i;
}
for (i=0; i<nneg; i++) {
Int_t nidx=neg[i];
AliESDtrack *ntrk=event->GetTrack(nidx);
for (Int_t k=0; k<npos; k++) {
Int_t pidx=pos[k];
AliESDtrack *ptrk=event->GetTrack(pidx);
if (TMath::Abs(ntrk->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDNmin)
if (TMath::Abs(ptrk->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDNmin) continue;
Double_t xn, xp, dca=ntrk->GetDCA(ptrk,b,xn,xp);
if (dca > fDCAmax) continue;
if ((xn+xp) > 2*fRmax) continue;
if ((xn+xp) < 2*fRmin) continue;
AliExternalTrackParam nt(*ntrk), pt(*ptrk);
Bool_t corrected=kFALSE;
if ((nt.GetX() > 3.) && (xn < 3.)) {
//correct for the beam pipe material
corrected=kTRUE;
}
if ((pt.GetX() > 3.) && (xp < 3.)) {
//correct for the beam pipe material
corrected=kTRUE;
}
if (corrected) {
dca=nt.GetDCA(&pt,b,xn,xp);
if (dca > fDCAmax) continue;
if ((xn+xp) > 2*fRmax) continue;
if ((xn+xp) < 2*fRmin) continue;
}
nt.PropagateTo(xn,b); pt.PropagateTo(xp,b);
AliESDv0 vertex(nt,nidx,pt,pidx);
if (vertex.GetChi2V0() > fChi2max) continue;
Double_t x=vertex.Xv(), y=vertex.Yv();
Double_t r2=x*x + y*y;
if (r2 < fRmin*fRmin) continue;
if (r2 > fRmax*fRmax) continue;
Float_t cpa=vertex.GetV0CosineOfPointingAngle(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex);
if (cpa < fCPAmin) continue;
vertex.SetDcaV0Daughters(dca);
vertex.SetV0CosineOfPointingAngle(cpa);
vertex.ChangeMassHypothesis(kK0Short);
event->AddV0(&vertex);
nvtx++;
}
}
Info("Tracks2V0vertices","Number of reconstructed V0 vertices: %d",nvtx);
return nvtx;
}
<commit_msg>The cut on V0 pointing angle is now momentum dependent below 1.5 GeV/c. Above this threshold, it is constant as it was before.<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. *
**************************************************************************/
//-------------------------------------------------------------------------
// Implementation of the V0 vertexer class
// reads tracks writes out V0 vertices
// fills the ESD with the V0s
// Origin: Iouri Belikov, IPHC, Strasbourg, [email protected]
//-------------------------------------------------------------------------
#include "AliESDEvent.h"
#include "AliESDv0.h"
#include "AliV0vertexer.h"
ClassImp(AliV0vertexer)
//A set of very loose cuts
Double_t AliV0vertexer::fgChi2max=33.; //max chi2
Double_t AliV0vertexer::fgDNmin=0.05; //min imp parameter for the 1st daughter
Double_t AliV0vertexer::fgDPmin=0.05; //min imp parameter for the 2nd daughter
Double_t AliV0vertexer::fgDCAmax=1.5; //max DCA between the daughter tracks
Double_t AliV0vertexer::fgCPAmin=0.9; //min cosine of V0's pointing angle
Double_t AliV0vertexer::fgRmin=0.2; //min radius of the fiducial volume
Double_t AliV0vertexer::fgRmax=200.; //max radius of the fiducial volume
Int_t AliV0vertexer::Tracks2V0vertices(AliESDEvent *event) {
//--------------------------------------------------------------------
//This function reconstructs V0 vertices
//--------------------------------------------------------------------
const AliESDVertex *vtxT3D=event->GetPrimaryVertex();
Double_t xPrimaryVertex=vtxT3D->GetXv();
Double_t yPrimaryVertex=vtxT3D->GetYv();
Double_t zPrimaryVertex=vtxT3D->GetZv();
Int_t nentr=event->GetNumberOfTracks();
Double_t b=event->GetMagneticField();
if (nentr<2) return 0;
TArrayI neg(nentr);
TArrayI pos(nentr);
Int_t nneg=0, npos=0, nvtx=0;
Int_t i;
for (i=0; i<nentr; i++) {
AliESDtrack *esdTrack=event->GetTrack(i);
ULong_t status=esdTrack->GetStatus();
//if ((status&AliESDtrack::kITSrefit)==0)//not to accept the ITS SA tracks
if ((status&AliESDtrack::kTPCrefit)==0) continue;
Double_t d=esdTrack->GetD(xPrimaryVertex,yPrimaryVertex,b);
if (TMath::Abs(d)<fDPmin) continue;
if (TMath::Abs(d)>fRmax) continue;
if (esdTrack->GetSign() < 0.) neg[nneg++]=i;
else pos[npos++]=i;
}
for (i=0; i<nneg; i++) {
Int_t nidx=neg[i];
AliESDtrack *ntrk=event->GetTrack(nidx);
for (Int_t k=0; k<npos; k++) {
Int_t pidx=pos[k];
AliESDtrack *ptrk=event->GetTrack(pidx);
if (TMath::Abs(ntrk->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDNmin)
if (TMath::Abs(ptrk->GetD(xPrimaryVertex,yPrimaryVertex,b))<fDNmin) continue;
Double_t xn, xp, dca=ntrk->GetDCA(ptrk,b,xn,xp);
if (dca > fDCAmax) continue;
if ((xn+xp) > 2*fRmax) continue;
if ((xn+xp) < 2*fRmin) continue;
AliExternalTrackParam nt(*ntrk), pt(*ptrk);
Bool_t corrected=kFALSE;
if ((nt.GetX() > 3.) && (xn < 3.)) {
//correct for the beam pipe material
corrected=kTRUE;
}
if ((pt.GetX() > 3.) && (xp < 3.)) {
//correct for the beam pipe material
corrected=kTRUE;
}
if (corrected) {
dca=nt.GetDCA(&pt,b,xn,xp);
if (dca > fDCAmax) continue;
if ((xn+xp) > 2*fRmax) continue;
if ((xn+xp) < 2*fRmin) continue;
}
nt.PropagateTo(xn,b); pt.PropagateTo(xp,b);
AliESDv0 vertex(nt,nidx,pt,pidx);
if (vertex.GetChi2V0() > fChi2max) continue;
Double_t x=vertex.Xv(), y=vertex.Yv();
Double_t r2=x*x + y*y;
if (r2 < fRmin*fRmin) continue;
if (r2 > fRmax*fRmax) continue;
Float_t cpa=vertex.GetV0CosineOfPointingAngle(xPrimaryVertex,yPrimaryVertex,zPrimaryVertex);
const Double_t pThr=1.5;
Double_t pv0=vertex.P();
if (pv0<pThr) {
//Below the threshold "pThr", try a momentum dependent cos(PA) cut
const Double_t bend=0.03; // approximate Xi bending angle
const Double_t qt=0.211; // max Lambda pT in Xi decay
const Double_t cpaThr=TMath::Cos(TMath::ASin(qt/pThr) + bend);
Double_t
cpaCut=(fCPAmin/cpaThr)*TMath::Cos(TMath::ASin(qt/pv0) + bend);
if (cpa < cpaCut) continue;
}
if (cpa < fCPAmin) continue;
vertex.SetDcaV0Daughters(dca);
vertex.SetV0CosineOfPointingAngle(cpa);
vertex.ChangeMassHypothesis(kK0Short);
event->AddV0(&vertex);
nvtx++;
}
}
Info("Tracks2V0vertices","Number of reconstructed V0 vertices: %d",nvtx);
return nvtx;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAcosImageAdaptor.h"
#include "itkAddImageAdaptor.h"
#include "itkAddPixelAccessor.h"
#include "itkAffineTransform.txx"
#include "itkArray.txx"
#include "itkArray2D.txx"
#include "itkAsinImageAdaptor.h"
#include "itkAtanImageAdaptor.h"
#include "itkAutoPointer.h"
#include "itkAzimuthElevationToCartesianTransform.txx"
#include "itkBSplineDeformableTransform.txx"
#include "itkBSplineDerivativeKernelFunction.h"
#include "itkBSplineInterpolationWeightFunction.txx"
#include "itkBSplineKernelFunction.h"
#include "itkBackwardDifferenceOperator.txx"
#include "itkBinaryBallStructuringElement.txx"
#include "itkBinaryThresholdImageFunction.txx"
#include "itkBloxBoundaryPointImage.txx"
#include "itkBloxBoundaryPointItem.txx"
#include "itkBloxBoundaryPointPixel.txx"
#include "itkBloxBoundaryProfileImage.txx"
#include "itkBloxBoundaryProfileItem.txx"
#include "itkBloxBoundaryProfilePixel.txx"
#include "itkBloxCoreAtomImage.txx"
#include "itkBloxCoreAtomItem.txx"
#include "itkBloxCoreAtomPixel.txx"
#include "itkBloxImage.txx"
#include "itkBloxItem.h"
#include "itkBloxPixel.txx"
#include "itkBluePixelAccessor.h"
#include "itkBoundingBox.txx"
#include "itkByteSwapper.txx"
#include "itkCellInterface.txx"
#include "itkCellInterfaceVisitor.h"
#include "itkCenteredAffineTransform.txx"
#include "itkCenteredRigid2DTransform.txx"
#include "itkCenteredTransformInitializer.txx"
#include "itkCentralDifferenceImageFunction.txx"
#include "itkChainCodePath.txx"
#include "itkChainCodePath2D.txx"
#include "itkColorTable.txx"
#include "itkCommand.h"
#include "itkConceptChecking.h"
#include "itkConditionalConstIterator.txx"
#include "itkConditionalIterator.txx"
#include "itkConicShellInteriorExteriorSpatialFunction.txx"
#include "itkConstNeighborhoodIterator.txx"
#include "itkConstShapedNeighborhoodIterator.txx"
#include "itkConstSliceIterator.h"
#include "itkConstantBoundaryCondition.h"
#include "itkContinuousIndex.h"
#include "itkCosImageAdaptor.h"
#include "itkCovariantVector.txx"
#include "itkCreateObjectFunction.h"
#include "itkDataObject.h"
#include "itkDecisionRuleBase.h"
#include "itkDefaultDynamicMeshTraits.h"
#include "itkDefaultImageTraits.h"
#include "itkDefaultPixelAccessor.h"
#include "itkDefaultStaticMeshTraits.h"
#include "itkDenseFiniteDifferenceImageFilter.txx"
#include "itkDerivativeOperator.txx"
#include "itkDifferenceImageFilter.txx"
#include "itkDirectory.h"
#include "itkDynamicLoader.h"
#include "itkElasticBodyReciprocalSplineKernelTransform.txx"
#include "itkElasticBodySplineKernelTransform.txx"
#include "itkEllipsoidInteriorExteriorSpatialFunction.txx"
#include "itkEquivalencyTable.h"
#include "itkEuler2DTransform.txx"
#include "itkEuler3DTransform.txx"
#include "itkEventObject.h"
#include "itkExceptionObject.h"
#include "itkExpImageAdaptor.h"
#include "itkExpNegativeImageAdaptor.h"
#include "itkFastMutexLock.h"
#include "itkFileOutputWindow.h"
#include "itkFiniteDifferenceFunction.txx"
#include "itkFiniteDifferenceImageFilter.txx"
#include "itkFixedArray.txx"
#include "itkFixedCenterOfRotationAffineTransform.txx"
#include "itkFloodFilledFunctionConditionalConstIterator.txx"
#include "itkFloodFilledFunctionConditionalIterator.txx"
#include "itkFloodFilledImageFunctionConditionalConstIterator.txx"
#include "itkFloodFilledImageFunctionConditionalIterator.txx"
#include "itkFloodFilledSpatialFunctionConditionalConstIterator.txx"
#include "itkFloodFilledSpatialFunctionConditionalIterator.txx"
#include "itkForwardDifferenceOperator.txx"
#include "itkFourierSeriesPath.txx"
#include "itkFrustumSpatialFunction.txx"
#include "itkFunctionBase.h"
#include "itkGaussianBlurImageFunction.txx"
#include "itkGaussianDerivativeImageFunction.txx"
#include "itkGaussianDerivativeSpatialFunction.txx"
#include "itkGaussianKernelFunction.h"
#include "itkGaussianOperator.txx"
#include "itkGaussianSpatialFunction.txx"
#include "itkGreenPixelAccessor.h"
#include "itkHexahedronCell.txx"
#include "itkHexahedronCellTopology.h"
#include "itkIdentityTransform.h"
#include "itkImage.txx"
#include "itkImageAdaptor.txx"
#include "itkImageBase.txx"
#include "itkImageBoundaryCondition.h"
#include "itkImageConstIterator.txx"
#include "itkImageConstIteratorWithIndex.txx"
#include "itkImageContainerInterface.h"
#include "itkImageFunction.txx"
#include "itkImageIterator.txx"
#include "itkImageIteratorWithIndex.txx"
#include "itkImageLinearConstIteratorWithIndex.txx"
#include "itkImageLinearIteratorWithIndex.txx"
#include "itkImageRandomConstIteratorWithIndex.txx"
#include "itkImageRandomIteratorWithIndex.txx"
#include "itkImageRegion.txx"
#include "itkImageRegionConstIterator.txx"
#include "itkImageRegionConstIteratorWithIndex.txx"
#include "itkImageRegionExclusionConstIteratorWithIndex.txx"
#include "itkImageRegionExclusionIteratorWithIndex.txx"
#include "itkImageRegionIterator.txx"
#include "itkImageRegionIteratorWithIndex.txx"
#include "itkImageRegionMultidimensionalSplitter.txx"
#include "itkImageRegionReverseConstIterator.txx"
#include "itkImageRegionReverseIterator.txx"
#include "itkImageRegionSplitter.txx"
#include "itkImageReverseConstIterator.txx"
#include "itkImageReverseIterator.txx"
#include "itkImageSliceConstIteratorWithIndex.txx"
#include "itkImageSliceIteratorWithIndex.txx"
#include "itkImageSource.txx"
#include "itkImageToImageFilter.txx"
#include "itkImageToImageFilterDetail.h"
#include "itkImportImageContainer.txx"
#include "itkInPlaceImageFilter.txx"
#include "itkIndent.h"
#include "itkIndex.h"
#include "itkIndexedContainerInterface.h"
#include "itkIntTypes.h"
#include "itkInteriorExteriorSpatialFunction.txx"
#include "itkInterpolateImageFunction.h"
#include "itkIterationReporter.h"
#include "itkKLMSegmentationBorder.h"
#include "itkKLMSegmentationRegion.h"
#include "itkKernelFunction.h"
#include "itkKernelTransform.txx"
#include "itkLaplacianOperator.txx"
#include "itkLevelSet.h"
#include "itkLevelSetFunction.txx"
#include "itkLevelSetFunctionBase.txx"
#include "itkLightObject.h"
#include "itkLightProcessObject.h"
#include "itkLineCell.txx"
#include "itkLinearInterpolateImageFunction.txx"
#include "itkLog10ImageAdaptor.h"
#include "itkLogImageAdaptor.h"
#include "itkMacro.h"
#include "itkMapContainer.txx"
#include "itkMatrix.txx"
#include "itkMaximumDecisionRule.h"
#include "itkMaximumRatioDecisionRule.h"
#include "itkMeanImageFunction.txx"
#include "itkMedianImageFunction.txx"
#include "itkMesh.txx"
#include "itkMeshRegion.h"
#include "itkMeshSource.txx"
#include "itkMeshToMeshFilter.txx"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.txx"
#include "itkMetaDataObjectBase.h"
#include "itkMinimumDecisionRule.h"
#include "itkMultiThreader.h"
#include "itkMutexLock.h"
#include "itkMutexLockHolder.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkNeighborhood.txx"
#include "itkNeighborhoodAlgorithm.txx"
#include "itkNeighborhoodAllocator.h"
#include "itkNeighborhoodBinaryThresholdImageFunction.txx"
#include "itkNeighborhoodInnerProduct.txx"
#include "itkNeighborhoodIterator.txx"
#include "itkNeighborhoodOperator.txx"
#include "itkNeighborhoodOperatorImageFunction.txx"
#include "itkNthElementImageAdaptor.h"
#include "itkNthElementPixelAccessor.h"
#include "itkNumericTraits.h"
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkObjectFactoryBase.h"
#include "itkObjectStore.txx"
#include "itkOctree.txx"
#include "itkOctreeNode.h"
#include "itkOffset.h"
#include "itkOneWayEquivalencyTable.h"
#include "itkOutputWindow.h"
#include "itkParametricPath.txx"
#include "itkPath.h"
#include "itkPathConstIterator.txx"
#include "itkPathFunctions.h"
#include "itkPathIterator.txx"
#include "itkPeriodicBoundaryCondition.txx"
#include "itkPixelAccessor.h"
#include "itkPixelTraits.h"
#include "itkPoint.txx"
#include "itkPointLocator.txx"
#include "itkPointSet.txx"
#include "itkPolyLineParametricPath.txx"
#include "itkPolygonCell.txx"
#include "itkProcessObject.h"
#include "itkProgressAccumulator.h"
#include "itkProgressReporter.h"
#include "itkQuadraticEdgeCell.txx"
#include "itkQuadraticTriangleCell.txx"
#include "itkQuadraticTriangleCellTopology.h"
#include "itkQuadrilateralCell.txx"
#include "itkQuadrilateralCellTopology.h"
#include "itkQuaternionRigidTransform.txx"
#include "itkRGBAPixel.txx"
#include "itkRGBPixel.txx"
#include "itkRGBToVectorImageAdaptor.h"
#include "itkRGBToVectorPixelAccessor.h"
#include "itkRedPixelAccessor.h"
#include "itkRegion.h"
#include "itkRigid2DTransform.txx"
#include "itkRigid3DPerspectiveTransform.txx"
#include "itkRigid3DTransform.txx"
#include "itkSTLConstContainerAdaptor.h"
#include "itkSTLContainerAdaptor.h"
#include "itkScalarToRGBPixelFunctor.txx"
#include "itkScalarVector.h"
#include "itkScaleTransform.txx"
#include "itkSegmentationBorder.h"
#include "itkSegmentationLevelSetFunction.txx"
#include "itkSegmentationRegion.h"
#include "itkShapedNeighborhoodIterator.txx"
#include "itkSimilarity2DTransform.txx"
#include "itkSimpleFastMutexLock.h"
#include "itkSinImageAdaptor.h"
#include "itkSize.h"
#include "itkSliceIterator.h"
#include "itkSmartPointer.h"
#include "itkSmartPointerForwardReference.txx"
#include "itkSobelOperator.txx"
#include "itkSpatialFunction.txx"
#include "itkSphereSpatialFunction.txx"
#include "itkSqrtImageAdaptor.h"
#include "itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx"
#include "itkTanImageAdaptor.h"
#include "itkTetrahedronCell.txx"
#include "itkTetrahedronCellTopology.h"
#include "itkTextOutput.h"
#include "itkThinPlateR2LogRSplineKernelTransform.txx"
#include "itkThinPlateSplineKernelTransform.txx"
#include "itkTimeProbe.h"
#include "itkTimeProbesCollectorBase.h"
#include "itkTimeStamp.h"
#include "itkTorusInteriorExteriorSpatialFunction.txx"
#include "itkTransform.txx"
#include "itkTranslationTransform.txx"
#include "itkTriangleCell.txx"
#include "itkTriangleCellTopology.h"
#include "itkValarrayImageContainer.h"
#include "itkVarianceImageFunction.txx"
#include "itkVector.txx"
#include "itkVectorContainer.txx"
#include "itkVectorInterpolateImageFunction.h"
#include "itkVectorLinearInterpolateImageFunction.txx"
#include "itkVectorNeighborhoodInnerProduct.txx"
#include "itkVectorToRGBImageAdaptor.h"
#include "itkVectorToRGBPixelAccessor.h"
#include "itkVersion.h"
#include "itkVersor.txx"
#include "itkVersorRigid3DTransform.txx"
#include "itkVersorTransform.txx"
#include "itkVertexCell.txx"
#include "itkVolumeSplineKernelTransform.txx"
#include "itkWeakPointer.h"
#include "itkXMLFileOutputWindow.h"
#include "itkZeroFluxNeumannBoundaryCondition.txx"
#include "itk_alloc.h"
#include "itk_hash_map.h"
#include "itk_hash_set.h"
#include "itk_hashtable.h"
#include "vcl_alloc.h"
int main ( int , char* )
{
return 0;
}
<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkAcosImageAdaptor.h"
#include "itkAddImageAdaptor.h"
#include "itkAddPixelAccessor.h"
#include "itkAffineTransform.txx"
#include "itkArray.txx"
#include "itkArray2D.txx"
#include "itkAsinImageAdaptor.h"
#include "itkAtanImageAdaptor.h"
#include "itkAutoPointer.h"
#include "itkAzimuthElevationToCartesianTransform.txx"
#include "itkBSplineDeformableTransform.txx"
#include "itkBSplineDerivativeKernelFunction.h"
#include "itkBSplineInterpolationWeightFunction.txx"
#include "itkBSplineKernelFunction.h"
#include "itkBackwardDifferenceOperator.txx"
#include "itkBinaryBallStructuringElement.txx"
#include "itkBinaryThresholdImageFunction.txx"
#include "itkBloxBoundaryPointImage.txx"
#include "itkBloxBoundaryPointItem.txx"
#include "itkBloxBoundaryPointPixel.txx"
#include "itkBloxBoundaryProfileImage.txx"
#include "itkBloxBoundaryProfileItem.txx"
#include "itkBloxBoundaryProfilePixel.txx"
#include "itkBloxCoreAtomImage.txx"
#include "itkBloxCoreAtomItem.txx"
#include "itkBloxCoreAtomPixel.txx"
#include "itkBloxImage.txx"
#include "itkBloxItem.h"
#include "itkBloxPixel.txx"
#include "itkBluePixelAccessor.h"
#include "itkBoundingBox.txx"
#include "itkByteSwapper.txx"
#include "itkCellInterface.txx"
#include "itkCellInterfaceVisitor.h"
#include "itkCenteredAffineTransform.txx"
#include "itkCenteredRigid2DTransform.txx"
#include "itkCenteredTransformInitializer.txx"
#include "itkCentralDifferenceImageFunction.txx"
#include "itkChainCodePath.txx"
#include "itkChainCodePath2D.txx"
#include "itkColorTable.txx"
#include "itkCommand.h"
#include "itkConceptChecking.h"
#include "itkConditionalConstIterator.txx"
#include "itkConditionalIterator.txx"
#include "itkConicShellInteriorExteriorSpatialFunction.txx"
#include "itkConstNeighborhoodIterator.txx"
#include "itkConstShapedNeighborhoodIterator.txx"
#include "itkConstSliceIterator.h"
#include "itkConstantBoundaryCondition.h"
#include "itkContinuousIndex.h"
#include "itkCosImageAdaptor.h"
#include "itkCovariantVector.txx"
#include "itkCreateObjectFunction.h"
#include "itkDataObject.h"
#include "itkDecisionRuleBase.h"
#include "itkDefaultDynamicMeshTraits.h"
#include "itkDefaultImageTraits.h"
#include "itkDefaultPixelAccessor.h"
#include "itkDefaultStaticMeshTraits.h"
#include "itkDenseFiniteDifferenceImageFilter.txx"
#include "itkDerivativeOperator.txx"
#include "itkDifferenceImageFilter.txx"
#include "itkDirectory.h"
#include "itkDynamicLoader.h"
#include "itkElasticBodyReciprocalSplineKernelTransform.txx"
#include "itkElasticBodySplineKernelTransform.txx"
#include "itkEllipsoidInteriorExteriorSpatialFunction.txx"
#include "itkEquivalencyTable.h"
#include "itkEuler2DTransform.txx"
#include "itkEuler3DTransform.txx"
#include "itkEventObject.h"
#include "itkExceptionObject.h"
#include "itkExpImageAdaptor.h"
#include "itkExpNegativeImageAdaptor.h"
#include "itkFastMutexLock.h"
#include "itkFileOutputWindow.h"
#include "itkFiniteDifferenceFunction.txx"
#include "itkFiniteDifferenceImageFilter.txx"
#include "itkFixedArray.txx"
#include "itkFixedCenterOfRotationAffineTransform.txx"
#include "itkFloodFilledFunctionConditionalConstIterator.txx"
#include "itkFloodFilledFunctionConditionalIterator.txx"
#include "itkFloodFilledImageFunctionConditionalConstIterator.txx"
#include "itkFloodFilledImageFunctionConditionalIterator.txx"
#include "itkFloodFilledSpatialFunctionConditionalConstIterator.txx"
#include "itkFloodFilledSpatialFunctionConditionalIterator.txx"
#include "itkForwardDifferenceOperator.txx"
#include "itkFourierSeriesPath.txx"
#include "itkFrustumSpatialFunction.txx"
#include "itkFunctionBase.h"
#include "itkGaussianBlurImageFunction.txx"
#include "itkGaussianDerivativeImageFunction.txx"
#include "itkGaussianDerivativeSpatialFunction.txx"
#include "itkGaussianKernelFunction.h"
#include "itkGaussianOperator.txx"
#include "itkGaussianSpatialFunction.txx"
#include "itkGreenPixelAccessor.h"
#include "itkHexahedronCell.txx"
#include "itkHexahedronCellTopology.h"
#include "itkIdentityTransform.h"
#include "itkImage.txx"
#include "itkImageAdaptor.txx"
#include "itkImageBase.txx"
#include "itkImageBoundaryCondition.h"
#include "itkImageConstIterator.txx"
#include "itkImageConstIteratorWithIndex.txx"
#include "itkImageContainerInterface.h"
#include "itkImageFunction.txx"
#include "itkImageIterator.txx"
#include "itkImageIteratorWithIndex.txx"
#include "itkImageLinearConstIteratorWithIndex.txx"
#include "itkImageLinearIteratorWithIndex.txx"
#include "itkImageRandomConstIteratorWithIndex.txx"
#include "itkImageRandomIteratorWithIndex.txx"
#include "itkImageRegion.txx"
#include "itkImageRegionConstIterator.txx"
#include "itkImageRegionConstIteratorWithIndex.txx"
#include "itkImageRegionExclusionConstIteratorWithIndex.txx"
#include "itkImageRegionExclusionIteratorWithIndex.txx"
#include "itkImageRegionIterator.txx"
#include "itkImageRegionIteratorWithIndex.txx"
#include "itkImageRegionMultidimensionalSplitter.txx"
#include "itkImageRegionReverseConstIterator.txx"
#include "itkImageRegionReverseIterator.txx"
#include "itkImageRegionSplitter.txx"
#include "itkImageReverseConstIterator.txx"
#include "itkImageReverseIterator.txx"
#include "itkImageSliceConstIteratorWithIndex.txx"
#include "itkImageSliceIteratorWithIndex.txx"
#include "itkImageSource.txx"
#include "itkImageToImageFilter.txx"
#include "itkImageToImageFilterDetail.h"
#include "itkImportImageContainer.txx"
#include "itkInPlaceImageFilter.txx"
#include "itkIndent.h"
#include "itkIndex.h"
#include "itkIndexedContainerInterface.h"
#include "itkIntTypes.h"
#include "itkInteriorExteriorSpatialFunction.txx"
#include "itkInterpolateImageFunction.h"
#include "itkIterationReporter.h"
#include "itkKLMSegmentationBorder.h"
#include "itkKLMSegmentationRegion.h"
#include "itkKernelFunction.h"
#include "itkKernelTransform.txx"
#include "itkLaplacianOperator.txx"
#include "itkLevelSet.h"
#include "itkLevelSetFunction.txx"
#include "itkLevelSetFunctionBase.txx"
#include "itkLightObject.h"
#include "itkLightProcessObject.h"
#include "itkLineCell.txx"
#include "itkLinearInterpolateImageFunction.txx"
#include "itkLog10ImageAdaptor.h"
#include "itkLogImageAdaptor.h"
#include "itkMacro.h"
#include "itkMapContainer.txx"
#include "itkMatrix.txx"
#include "itkMaximumDecisionRule.h"
#include "itkMaximumRatioDecisionRule.h"
#include "itkMeanImageFunction.txx"
#include "itkMedianImageFunction.txx"
#include "itkMesh.txx"
#include "itkMeshRegion.h"
#include "itkMeshSource.txx"
#include "itkMeshToMeshFilter.txx"
#include "itkMetaDataDictionary.h"
#include "itkMetaDataObject.txx"
#include "itkMetaDataObjectBase.h"
#include "itkMinimumDecisionRule.h"
#include "itkMultiThreader.h"
#include "itkMutexLock.h"
#include "itkMutexLockHolder.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkNeighborhood.txx"
#include "itkNeighborhoodAlgorithm.txx"
#include "itkNeighborhoodAllocator.h"
#include "itkNeighborhoodBinaryThresholdImageFunction.txx"
#include "itkNeighborhoodInnerProduct.txx"
#include "itkNeighborhoodIterator.txx"
#include "itkNeighborhoodOperator.txx"
#include "itkNeighborhoodOperatorImageFunction.txx"
#include "itkNthElementImageAdaptor.h"
#include "itkNthElementPixelAccessor.h"
#include "itkNumericTraits.h"
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkObjectFactoryBase.h"
#include "itkObjectStore.txx"
#include "itkOctree.txx"
#include "itkOctreeNode.h"
#include "itkOffset.h"
#include "itkOneWayEquivalencyTable.h"
#include "itkOutputWindow.h"
#include "itkParametricPath.txx"
#include "itkPath.h"
#include "itkPathConstIterator.txx"
#include "itkPathFunctions.h"
#include "itkPathIterator.txx"
#include "itkPeriodicBoundaryCondition.txx"
#include "itkPixelAccessor.h"
#include "itkPixelTraits.h"
#include "itkPoint.txx"
#include "itkPointLocator.txx"
#include "itkPointSet.txx"
#include "itkPolyLineParametricPath.txx"
#include "itkPolygonCell.txx"
#include "itkProcessObject.h"
#include "itkProgressAccumulator.h"
#include "itkProgressReporter.h"
#include "itkQuadraticEdgeCell.txx"
#include "itkQuadraticTriangleCell.txx"
#include "itkQuadraticTriangleCellTopology.h"
#include "itkQuadrilateralCell.txx"
#include "itkQuadrilateralCellTopology.h"
#include "itkQuaternionRigidTransform.txx"
#include "itkRGBAPixel.txx"
#include "itkRGBPixel.txx"
#include "itkRGBToVectorImageAdaptor.h"
#include "itkRGBToVectorPixelAccessor.h"
#include "itkRedPixelAccessor.h"
#include "itkRegion.h"
#include "itkRigid2DTransform.txx"
#include "itkRigid3DPerspectiveTransform.txx"
#include "itkRigid3DTransform.txx"
#include "itkSTLConstContainerAdaptor.h"
#include "itkSTLContainerAdaptor.h"
#include "itkScalarToRGBPixelFunctor.txx"
#include "itkScalarVector.h"
#include "itkScaleLogarithmicTransform.txx"
#include "itkScaleTransform.txx"
#include "itkSegmentationBorder.h"
#include "itkSegmentationLevelSetFunction.txx"
#include "itkSegmentationRegion.h"
#include "itkShapedNeighborhoodIterator.txx"
#include "itkSimilarity2DTransform.txx"
#include "itkSimpleFastMutexLock.h"
#include "itkSinImageAdaptor.h"
#include "itkSize.h"
#include "itkSliceIterator.h"
#include "itkSmartPointer.h"
#include "itkSmartPointerForwardReference.txx"
#include "itkSobelOperator.txx"
#include "itkSpatialFunction.txx"
#include "itkSphereSpatialFunction.txx"
#include "itkSqrtImageAdaptor.h"
#include "itkSymmetricEllipsoidInteriorExteriorSpatialFunction.txx"
#include "itkTanImageAdaptor.h"
#include "itkTetrahedronCell.txx"
#include "itkTetrahedronCellTopology.h"
#include "itkTextOutput.h"
#include "itkThinPlateR2LogRSplineKernelTransform.txx"
#include "itkThinPlateSplineKernelTransform.txx"
#include "itkTimeProbe.h"
#include "itkTimeProbesCollectorBase.h"
#include "itkTimeStamp.h"
#include "itkTorusInteriorExteriorSpatialFunction.txx"
#include "itkTransform.txx"
#include "itkTranslationTransform.txx"
#include "itkTriangleCell.txx"
#include "itkTriangleCellTopology.h"
#include "itkValarrayImageContainer.h"
#include "itkVarianceImageFunction.txx"
#include "itkVector.txx"
#include "itkVectorContainer.txx"
#include "itkVectorInterpolateImageFunction.h"
#include "itkVectorLinearInterpolateImageFunction.txx"
#include "itkVectorNeighborhoodInnerProduct.txx"
#include "itkVectorToRGBImageAdaptor.h"
#include "itkVectorToRGBPixelAccessor.h"
#include "itkVersion.h"
#include "itkVersor.txx"
#include "itkVersorRigid3DTransform.txx"
#include "itkVersorTransform.txx"
#include "itkVertexCell.txx"
#include "itkVolumeSplineKernelTransform.txx"
#include "itkWeakPointer.h"
#include "itkXMLFileOutputWindow.h"
#include "itkZeroFluxNeumannBoundaryCondition.txx"
#include "itk_alloc.h"
#include "itk_hash_map.h"
#include "itk_hash_set.h"
#include "itk_hashtable.h"
#include "vcl_alloc.h"
int main ( int , char* )
{
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/service/service_process.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/i18n/rtl.h"
#include "base/memory/singleton.h"
#include "base/path_service.h"
#include "base/prefs/json_pref_store.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/service_process_util.h"
#include "chrome/service/cloud_print/cloud_print_proxy.h"
#include "chrome/service/net/service_url_request_context.h"
#include "chrome/service/service_ipc_server.h"
#include "chrome/service/service_process_prefs.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/network_change_notifier.h"
#include "net/url_request/url_fetcher.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_switches.h"
#if defined(OS_LINUX) || defined(OS_OPENBSD)
#include <glib-object.h>
#endif
#if defined(TOOLKIT_GTK)
#include <gtk/gtk.h>
#include "ui/gfx/gtk_util.h"
#endif
ServiceProcess* g_service_process = NULL;
namespace {
// Delay in seconds after the last service is disabled before we attempt
// a shutdown.
const int kShutdownDelaySeconds = 60;
// Delay in hours between launching a browser process to check the
// policy for us.
const int64 kPolicyCheckDelayHours = 8;
const char kDefaultServiceProcessLocale[] = "en-US";
class ServiceIOThread : public base::Thread {
public:
explicit ServiceIOThread(const char* name);
virtual ~ServiceIOThread();
protected:
virtual void CleanUp() OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(ServiceIOThread);
};
ServiceIOThread::ServiceIOThread(const char* name) : base::Thread(name) {}
ServiceIOThread::~ServiceIOThread() {
Stop();
}
void ServiceIOThread::CleanUp() {
net::URLFetcher::CancelAll();
}
// Prepares the localized strings that are going to be displayed to
// the user if the service process dies. These strings are stored in the
// environment block so they are accessible in the early stages of the
// chrome executable's lifetime.
void PrepareRestartOnCrashEnviroment(
const CommandLine &parsed_command_line) {
scoped_ptr<base::Environment> env(base::Environment::Create());
// Clear this var so child processes don't show the dialog by default.
env->UnSetVar(env_vars::kShowRestart);
// For non-interactive tests we don't restart on crash.
if (env->HasVar(env_vars::kHeadless))
return;
// If the known command-line test options are used we don't create the
// environment block which means we don't get the restart dialog.
if (parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
return;
// The encoding we use for the info is "title|context|direction" where
// direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
// on the current locale.
base::string16 dlg_strings(
l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
dlg_strings.push_back('|');
base::string16 adjusted_string(l10n_util::GetStringFUTF16(
IDS_SERVICE_CRASH_RECOVERY_CONTENT,
l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));
base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
dlg_strings.append(adjusted_string);
dlg_strings.push_back('|');
dlg_strings.append(base::ASCIIToUTF16(
base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
}
} // namespace
ServiceProcess::ServiceProcess()
: shutdown_event_(true, false),
main_message_loop_(NULL),
enabled_services_(0),
update_available_(false) {
DCHECK(!g_service_process);
g_service_process = this;
}
bool ServiceProcess::Initialize(base::MessageLoopForUI* message_loop,
const CommandLine& command_line,
ServiceProcessState* state) {
#if defined(TOOLKIT_GTK)
// TODO(jamiewalch): Calling GtkInitFromCommandLine here causes the process
// to abort if run headless. The correct fix for this is to refactor the
// service process to be more modular, a task that is currently underway.
// However, since this problem is blocking cloud print, the following quick
// hack will have to do. Note that the situation with this hack in place is
// no worse than it was when we weren't initializing GTK at all.
int argc = 1;
scoped_ptr<char*[]> argv(new char*[2]);
argv[0] = strdup(command_line.argv()[0].c_str());
argv[1] = NULL;
char **argv_pointer = argv.get();
gtk_init_check(&argc, &argv_pointer);
free(argv[0]);
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
// g_type_init has been deprecated since version 2.35.
#if !GLIB_CHECK_VERSION(2, 35, 0)
// GLib type system initialization is needed for gconf.
g_type_init();
#endif
#endif // defined(OS_LINUX) || defined(OS_OPENBSD)
main_message_loop_ = message_loop;
service_process_state_.reset(state);
network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
base::Thread::Options options;
options.message_loop_type = base::MessageLoop::TYPE_IO;
io_thread_.reset(new ServiceIOThread("ServiceProcess_IO"));
file_thread_.reset(new base::Thread("ServiceProcess_File"));
if (!io_thread_->StartWithOptions(options) ||
!file_thread_->StartWithOptions(options)) {
NOTREACHED();
Teardown();
return false;
}
blocking_pool_ = new base::SequencedWorkerPool(3, "ServiceBlocking");
request_context_getter_ = new ServiceURLRequestContextGetter();
base::FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
base::FilePath pref_path =
user_data_dir.Append(chrome::kServiceStateFileName);
service_prefs_.reset(new ServiceProcessPrefs(
pref_path,
JsonPrefStore::GetTaskRunnerForFile(pref_path, blocking_pool_.get())
.get()));
service_prefs_->ReadPrefs();
// This switch it required to run connector with test gaia.
if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
net::URLFetcher::SetIgnoreCertificateRequests(true);
// Check if a locale override has been specified on the command-line.
std::string locale = command_line.GetSwitchValueASCII(switches::kLang);
if (!locale.empty()) {
service_prefs_->SetString(prefs::kApplicationLocale, locale);
service_prefs_->WritePrefs();
} else {
// If no command-line value was specified, read the last used locale from
// the prefs.
locale =
service_prefs_->GetString(prefs::kApplicationLocale, std::string());
// If no locale was specified anywhere, use the default one.
if (locale.empty())
locale = kDefaultServiceProcessLocale;
}
ResourceBundle::InitSharedInstanceWithLocale(locale, NULL);
PrepareRestartOnCrashEnviroment(command_line);
// Enable Cloud Print if needed. First check the command-line.
// Then check if the cloud print proxy was previously enabled.
if (command_line.HasSwitch(switches::kEnableCloudPrintProxy) ||
service_prefs_->GetBoolean(prefs::kCloudPrintProxyEnabled, false)) {
GetCloudPrintProxy()->EnableForUser();
}
VLOG(1) << "Starting Service Process IPC Server";
ipc_server_.reset(new ServiceIPCServer(
service_process_state_->GetServiceProcessChannel()));
ipc_server_->Init();
// After the IPC server has started we signal that the service process is
// ready.
if (!service_process_state_->SignalReady(
io_thread_->message_loop_proxy().get(),
base::Bind(&ServiceProcess::Terminate, base::Unretained(this)))) {
return false;
}
// See if we need to stay running.
ScheduleShutdownCheck();
// Occasionally check to see if we need to launch the browser to get the
// policy state information.
CloudPrintPolicyCheckIfNeeded();
return true;
}
bool ServiceProcess::Teardown() {
service_prefs_.reset();
cloud_print_proxy_.reset();
ipc_server_.reset();
// Signal this event before shutting down the service process. That way all
// background threads can cleanup.
shutdown_event_.Signal();
io_thread_.reset();
file_thread_.reset();
if (blocking_pool_.get()) {
// The goal is to make it impossible for chrome to 'infinite loop' during
// shutdown, but to reasonably expect that all BLOCKING_SHUTDOWN tasks
// queued during shutdown get run. There's nothing particularly scientific
// about the number chosen.
const int kMaxNewShutdownBlockingTasks = 1000;
blocking_pool_->Shutdown(kMaxNewShutdownBlockingTasks);
blocking_pool_ = NULL;
}
// The NetworkChangeNotifier must be destroyed after all other threads that
// might use it have been shut down.
network_change_notifier_.reset();
service_process_state_->SignalStopped();
return true;
}
// This method is called when a shutdown command is received from IPC channel
// or there was an error in the IPC channel.
void ServiceProcess::Shutdown() {
#if defined(OS_MACOSX)
// On MacOS X the service must be removed from the launchd job list.
// http://www.chromium.org/developers/design-documents/service-processes
// The best way to do that is to go through the ForceServiceProcessShutdown
// path. If it succeeds Terminate() will be called from the handler registered
// via service_process_state_->SignalReady().
// On failure call Terminate() directly to force the process to actually
// terminate.
if (!ForceServiceProcessShutdown("", 0)) {
Terminate();
}
#else
Terminate();
#endif
}
void ServiceProcess::Terminate() {
main_message_loop_->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
}
bool ServiceProcess::HandleClientDisconnect() {
// If there are no enabled services or if there is an update available
// we want to shutdown right away. Else we want to keep listening for
// new connections.
if (!enabled_services_ || update_available()) {
Shutdown();
return false;
}
return true;
}
cloud_print::CloudPrintProxy* ServiceProcess::GetCloudPrintProxy() {
if (!cloud_print_proxy_.get()) {
cloud_print_proxy_.reset(new cloud_print::CloudPrintProxy());
cloud_print_proxy_->Initialize(service_prefs_.get(), this);
}
return cloud_print_proxy_.get();
}
void ServiceProcess::OnCloudPrintProxyEnabled(bool persist_state) {
if (persist_state) {
// Save the preference that we have enabled the cloud print proxy.
service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, true);
service_prefs_->WritePrefs();
}
OnServiceEnabled();
}
void ServiceProcess::OnCloudPrintProxyDisabled(bool persist_state) {
if (persist_state) {
// Save the preference that we have disabled the cloud print proxy.
service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, false);
service_prefs_->WritePrefs();
}
OnServiceDisabled();
}
ServiceURLRequestContextGetter*
ServiceProcess::GetServiceURLRequestContextGetter() {
DCHECK(request_context_getter_.get());
return request_context_getter_.get();
}
void ServiceProcess::OnServiceEnabled() {
enabled_services_++;
if ((1 == enabled_services_) &&
!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNoServiceAutorun)) {
if (!service_process_state_->AddToAutoRun()) {
// TODO(scottbyer/sanjeevr/dmaclach): Handle error condition
LOG(ERROR) << "Unable to AddToAutoRun";
}
}
}
void ServiceProcess::OnServiceDisabled() {
DCHECK_NE(enabled_services_, 0);
enabled_services_--;
if (0 == enabled_services_) {
if (!service_process_state_->RemoveFromAutoRun()) {
// TODO(scottbyer/sanjeevr/dmaclach): Handle error condition
LOG(ERROR) << "Unable to RemoveFromAutoRun";
}
// We will wait for some time to respond to IPCs before shutting down.
ScheduleShutdownCheck();
}
}
void ServiceProcess::ScheduleShutdownCheck() {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ServiceProcess::ShutdownIfNeeded, base::Unretained(this)),
base::TimeDelta::FromSeconds(kShutdownDelaySeconds));
}
void ServiceProcess::ShutdownIfNeeded() {
if (0 == enabled_services_) {
if (ipc_server_->is_client_connected()) {
// If there is a client connected, we need to try again later.
// Note that there is still a timing window here because a client may
// decide to connect at this point.
// TODO(sanjeevr): Fix this timing window.
ScheduleShutdownCheck();
} else {
Shutdown();
}
}
}
void ServiceProcess::ScheduleCloudPrintPolicyCheck() {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ServiceProcess::CloudPrintPolicyCheckIfNeeded,
base::Unretained(this)),
base::TimeDelta::FromHours(kPolicyCheckDelayHours));
}
void ServiceProcess::CloudPrintPolicyCheckIfNeeded() {
if (enabled_services_ && !ipc_server_->is_client_connected()) {
GetCloudPrintProxy()->CheckCloudPrintProxyPolicy();
}
ScheduleCloudPrintPolicyCheck();
}
ServiceProcess::~ServiceProcess() {
Teardown();
g_service_process = NULL;
}
<commit_msg>Use USE_GLIB flag instead of OS_XXXX for choosing whether to initialize glib.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/service/service_process.h"
#include <algorithm>
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/environment.h"
#include "base/i18n/rtl.h"
#include "base/memory/singleton.h"
#include "base/path_service.h"
#include "base/prefs/json_pref_store.h"
#include "base/strings/string16.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/service_process_util.h"
#include "chrome/service/cloud_print/cloud_print_proxy.h"
#include "chrome/service/net/service_url_request_context.h"
#include "chrome/service/service_ipc_server.h"
#include "chrome/service/service_process_prefs.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "net/base/network_change_notifier.h"
#include "net/url_request/url_fetcher.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/ui_base_switches.h"
#if defined(USE_GLIB)
#include <glib-object.h>
#endif
#if defined(TOOLKIT_GTK)
#include <gtk/gtk.h>
#include "ui/gfx/gtk_util.h"
#endif
ServiceProcess* g_service_process = NULL;
namespace {
// Delay in seconds after the last service is disabled before we attempt
// a shutdown.
const int kShutdownDelaySeconds = 60;
// Delay in hours between launching a browser process to check the
// policy for us.
const int64 kPolicyCheckDelayHours = 8;
const char kDefaultServiceProcessLocale[] = "en-US";
class ServiceIOThread : public base::Thread {
public:
explicit ServiceIOThread(const char* name);
virtual ~ServiceIOThread();
protected:
virtual void CleanUp() OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(ServiceIOThread);
};
ServiceIOThread::ServiceIOThread(const char* name) : base::Thread(name) {}
ServiceIOThread::~ServiceIOThread() {
Stop();
}
void ServiceIOThread::CleanUp() {
net::URLFetcher::CancelAll();
}
// Prepares the localized strings that are going to be displayed to
// the user if the service process dies. These strings are stored in the
// environment block so they are accessible in the early stages of the
// chrome executable's lifetime.
void PrepareRestartOnCrashEnviroment(
const CommandLine &parsed_command_line) {
scoped_ptr<base::Environment> env(base::Environment::Create());
// Clear this var so child processes don't show the dialog by default.
env->UnSetVar(env_vars::kShowRestart);
// For non-interactive tests we don't restart on crash.
if (env->HasVar(env_vars::kHeadless))
return;
// If the known command-line test options are used we don't create the
// environment block which means we don't get the restart dialog.
if (parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
return;
// The encoding we use for the info is "title|context|direction" where
// direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
// on the current locale.
base::string16 dlg_strings(
l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
dlg_strings.push_back('|');
base::string16 adjusted_string(l10n_util::GetStringFUTF16(
IDS_SERVICE_CRASH_RECOVERY_CONTENT,
l10n_util::GetStringUTF16(IDS_GOOGLE_CLOUD_PRINT)));
base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
dlg_strings.append(adjusted_string);
dlg_strings.push_back('|');
dlg_strings.append(base::ASCIIToUTF16(
base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
env->SetVar(env_vars::kRestartInfo, base::UTF16ToUTF8(dlg_strings));
}
} // namespace
ServiceProcess::ServiceProcess()
: shutdown_event_(true, false),
main_message_loop_(NULL),
enabled_services_(0),
update_available_(false) {
DCHECK(!g_service_process);
g_service_process = this;
}
bool ServiceProcess::Initialize(base::MessageLoopForUI* message_loop,
const CommandLine& command_line,
ServiceProcessState* state) {
#if defined(TOOLKIT_GTK)
// TODO(jamiewalch): Calling GtkInitFromCommandLine here causes the process
// to abort if run headless. The correct fix for this is to refactor the
// service process to be more modular, a task that is currently underway.
// However, since this problem is blocking cloud print, the following quick
// hack will have to do. Note that the situation with this hack in place is
// no worse than it was when we weren't initializing GTK at all.
int argc = 1;
scoped_ptr<char*[]> argv(new char*[2]);
argv[0] = strdup(command_line.argv()[0].c_str());
argv[1] = NULL;
char **argv_pointer = argv.get();
gtk_init_check(&argc, &argv_pointer);
free(argv[0]);
#elif defined(USE_GLIB)
// g_type_init has been deprecated since version 2.35.
#if !GLIB_CHECK_VERSION(2, 35, 0)
// GLib type system initialization is needed for gconf.
g_type_init();
#endif
#endif // defined(OS_LINUX) || defined(OS_OPENBSD)
main_message_loop_ = message_loop;
service_process_state_.reset(state);
network_change_notifier_.reset(net::NetworkChangeNotifier::Create());
base::Thread::Options options;
options.message_loop_type = base::MessageLoop::TYPE_IO;
io_thread_.reset(new ServiceIOThread("ServiceProcess_IO"));
file_thread_.reset(new base::Thread("ServiceProcess_File"));
if (!io_thread_->StartWithOptions(options) ||
!file_thread_->StartWithOptions(options)) {
NOTREACHED();
Teardown();
return false;
}
blocking_pool_ = new base::SequencedWorkerPool(3, "ServiceBlocking");
request_context_getter_ = new ServiceURLRequestContextGetter();
base::FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
base::FilePath pref_path =
user_data_dir.Append(chrome::kServiceStateFileName);
service_prefs_.reset(new ServiceProcessPrefs(
pref_path,
JsonPrefStore::GetTaskRunnerForFile(pref_path, blocking_pool_.get())
.get()));
service_prefs_->ReadPrefs();
// This switch it required to run connector with test gaia.
if (command_line.HasSwitch(switches::kIgnoreUrlFetcherCertRequests))
net::URLFetcher::SetIgnoreCertificateRequests(true);
// Check if a locale override has been specified on the command-line.
std::string locale = command_line.GetSwitchValueASCII(switches::kLang);
if (!locale.empty()) {
service_prefs_->SetString(prefs::kApplicationLocale, locale);
service_prefs_->WritePrefs();
} else {
// If no command-line value was specified, read the last used locale from
// the prefs.
locale =
service_prefs_->GetString(prefs::kApplicationLocale, std::string());
// If no locale was specified anywhere, use the default one.
if (locale.empty())
locale = kDefaultServiceProcessLocale;
}
ResourceBundle::InitSharedInstanceWithLocale(locale, NULL);
PrepareRestartOnCrashEnviroment(command_line);
// Enable Cloud Print if needed. First check the command-line.
// Then check if the cloud print proxy was previously enabled.
if (command_line.HasSwitch(switches::kEnableCloudPrintProxy) ||
service_prefs_->GetBoolean(prefs::kCloudPrintProxyEnabled, false)) {
GetCloudPrintProxy()->EnableForUser();
}
VLOG(1) << "Starting Service Process IPC Server";
ipc_server_.reset(new ServiceIPCServer(
service_process_state_->GetServiceProcessChannel()));
ipc_server_->Init();
// After the IPC server has started we signal that the service process is
// ready.
if (!service_process_state_->SignalReady(
io_thread_->message_loop_proxy().get(),
base::Bind(&ServiceProcess::Terminate, base::Unretained(this)))) {
return false;
}
// See if we need to stay running.
ScheduleShutdownCheck();
// Occasionally check to see if we need to launch the browser to get the
// policy state information.
CloudPrintPolicyCheckIfNeeded();
return true;
}
bool ServiceProcess::Teardown() {
service_prefs_.reset();
cloud_print_proxy_.reset();
ipc_server_.reset();
// Signal this event before shutting down the service process. That way all
// background threads can cleanup.
shutdown_event_.Signal();
io_thread_.reset();
file_thread_.reset();
if (blocking_pool_.get()) {
// The goal is to make it impossible for chrome to 'infinite loop' during
// shutdown, but to reasonably expect that all BLOCKING_SHUTDOWN tasks
// queued during shutdown get run. There's nothing particularly scientific
// about the number chosen.
const int kMaxNewShutdownBlockingTasks = 1000;
blocking_pool_->Shutdown(kMaxNewShutdownBlockingTasks);
blocking_pool_ = NULL;
}
// The NetworkChangeNotifier must be destroyed after all other threads that
// might use it have been shut down.
network_change_notifier_.reset();
service_process_state_->SignalStopped();
return true;
}
// This method is called when a shutdown command is received from IPC channel
// or there was an error in the IPC channel.
void ServiceProcess::Shutdown() {
#if defined(OS_MACOSX)
// On MacOS X the service must be removed from the launchd job list.
// http://www.chromium.org/developers/design-documents/service-processes
// The best way to do that is to go through the ForceServiceProcessShutdown
// path. If it succeeds Terminate() will be called from the handler registered
// via service_process_state_->SignalReady().
// On failure call Terminate() directly to force the process to actually
// terminate.
if (!ForceServiceProcessShutdown("", 0)) {
Terminate();
}
#else
Terminate();
#endif
}
void ServiceProcess::Terminate() {
main_message_loop_->PostTask(FROM_HERE, base::MessageLoop::QuitClosure());
}
bool ServiceProcess::HandleClientDisconnect() {
// If there are no enabled services or if there is an update available
// we want to shutdown right away. Else we want to keep listening for
// new connections.
if (!enabled_services_ || update_available()) {
Shutdown();
return false;
}
return true;
}
cloud_print::CloudPrintProxy* ServiceProcess::GetCloudPrintProxy() {
if (!cloud_print_proxy_.get()) {
cloud_print_proxy_.reset(new cloud_print::CloudPrintProxy());
cloud_print_proxy_->Initialize(service_prefs_.get(), this);
}
return cloud_print_proxy_.get();
}
void ServiceProcess::OnCloudPrintProxyEnabled(bool persist_state) {
if (persist_state) {
// Save the preference that we have enabled the cloud print proxy.
service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, true);
service_prefs_->WritePrefs();
}
OnServiceEnabled();
}
void ServiceProcess::OnCloudPrintProxyDisabled(bool persist_state) {
if (persist_state) {
// Save the preference that we have disabled the cloud print proxy.
service_prefs_->SetBoolean(prefs::kCloudPrintProxyEnabled, false);
service_prefs_->WritePrefs();
}
OnServiceDisabled();
}
ServiceURLRequestContextGetter*
ServiceProcess::GetServiceURLRequestContextGetter() {
DCHECK(request_context_getter_.get());
return request_context_getter_.get();
}
void ServiceProcess::OnServiceEnabled() {
enabled_services_++;
if ((1 == enabled_services_) &&
!CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNoServiceAutorun)) {
if (!service_process_state_->AddToAutoRun()) {
// TODO(scottbyer/sanjeevr/dmaclach): Handle error condition
LOG(ERROR) << "Unable to AddToAutoRun";
}
}
}
void ServiceProcess::OnServiceDisabled() {
DCHECK_NE(enabled_services_, 0);
enabled_services_--;
if (0 == enabled_services_) {
if (!service_process_state_->RemoveFromAutoRun()) {
// TODO(scottbyer/sanjeevr/dmaclach): Handle error condition
LOG(ERROR) << "Unable to RemoveFromAutoRun";
}
// We will wait for some time to respond to IPCs before shutting down.
ScheduleShutdownCheck();
}
}
void ServiceProcess::ScheduleShutdownCheck() {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ServiceProcess::ShutdownIfNeeded, base::Unretained(this)),
base::TimeDelta::FromSeconds(kShutdownDelaySeconds));
}
void ServiceProcess::ShutdownIfNeeded() {
if (0 == enabled_services_) {
if (ipc_server_->is_client_connected()) {
// If there is a client connected, we need to try again later.
// Note that there is still a timing window here because a client may
// decide to connect at this point.
// TODO(sanjeevr): Fix this timing window.
ScheduleShutdownCheck();
} else {
Shutdown();
}
}
}
void ServiceProcess::ScheduleCloudPrintPolicyCheck() {
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&ServiceProcess::CloudPrintPolicyCheckIfNeeded,
base::Unretained(this)),
base::TimeDelta::FromHours(kPolicyCheckDelayHours));
}
void ServiceProcess::CloudPrintPolicyCheckIfNeeded() {
if (enabled_services_ && !ipc_server_->is_client_connected()) {
GetCloudPrintProxy()->CheckCloudPrintProxyPolicy();
}
ScheduleCloudPrintPolicyCheck();
}
ServiceProcess::~ServiceProcess() {
Teardown();
g_service_process = NULL;
}
<|endoftext|> |
<commit_before>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
Vladimír Vondruš <[email protected]>
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 <Corrade/Utility/Assert.h>
#include <Corrade/Utility/Resource.h>
#include "Magnum/AbstractShaderProgram.h"
#include "Magnum/Buffer.h"
#include "Magnum/Framebuffer.h"
#include "Magnum/Mesh.h"
#include "Magnum/PrimitiveQuery.h"
#include "Magnum/Renderbuffer.h"
#include "Magnum/RenderbufferFormat.h"
#include "Magnum/Shader.h"
#include "Magnum/TransformFeedback.h"
#include "Magnum/Math/Vector2.h"
#include "Magnum/Test/AbstractOpenGLTester.h"
namespace Magnum { namespace Test {
struct PrimitiveQueryGLTest: AbstractOpenGLTester {
explicit PrimitiveQueryGLTest();
void constructNoCreate();
void wrap();
#ifndef MAGNUM_TARGET_GLES
void primitivesGenerated();
void primitivesGeneratedIndexed();
#endif
void transformFeedbackPrimitivesWritten();
#ifndef MAGNUM_TARGET_GLES
void transformFeedbackOverflow();
#endif
};
PrimitiveQueryGLTest::PrimitiveQueryGLTest() {
addTests({&PrimitiveQueryGLTest::constructNoCreate,
&PrimitiveQueryGLTest::wrap,
#ifndef MAGNUM_TARGET_GLES
&PrimitiveQueryGLTest::primitivesGenerated,
&PrimitiveQueryGLTest::primitivesGeneratedIndexed,
#endif
&PrimitiveQueryGLTest::transformFeedbackPrimitivesWritten,
#ifndef MAGNUM_TARGET_GLES
&PrimitiveQueryGLTest::transformFeedbackOverflow
#endif
});
}
void PrimitiveQueryGLTest::constructNoCreate() {
{
PrimitiveQuery query{NoCreate};
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(query.id(), 0);
}
MAGNUM_VERIFY_NO_ERROR();
}
void PrimitiveQueryGLTest::wrap() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::transform_feedback2>())
CORRADE_SKIP(Extensions::GL::ARB::transform_feedback2::string() + std::string(" is not available."));
#endif
GLuint id;
glGenQueries(1, &id);
/* Releasing won't delete anything */
{
auto query = PrimitiveQuery::wrap(id, PrimitiveQuery::Target::TransformFeedbackPrimitivesWritten, ObjectFlag::DeleteOnDestruction);
CORRADE_COMPARE(query.release(), id);
}
/* ...so we can wrap it again */
PrimitiveQuery::wrap(id, PrimitiveQuery::Target::TransformFeedbackPrimitivesWritten);
glDeleteQueries(1, &id);
}
#ifndef MAGNUM_TARGET_GLES
void PrimitiveQueryGLTest::primitivesGenerated() {
if(!Context::current().isExtensionSupported<Extensions::GL::EXT::transform_feedback>())
CORRADE_SKIP(Extensions::GL::EXT::transform_feedback::string() + std::string(" is not available."));
/* Bind some FB to avoid errors on contexts w/o default FB */
Renderbuffer color;
color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32});
Framebuffer fb{{{}, Vector2i{32}}};
fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color)
.bind();
struct MyShader: AbstractShaderProgram {
typedef Attribute<0, Vector2> Position;
explicit MyShader() {
Shader vert(
#ifndef CORRADE_TARGET_APPLE
Version::GL210
#else
Version::GL310
#endif
, Shader::Type::Vertex);
CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource(
"#if __VERSION__ >= 130\n"
"#define attribute in\n"
"#endif\n"
"attribute vec4 position;\n"
"void main() {\n"
" gl_Position = position;\n"
"}\n").compile());
attachShader(vert);
bindAttributeLocation(Position::Location, "position");
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
}
} shader;
Buffer vertices;
vertices.setData({nullptr, 9*sizeof(Vector2)}, BufferUsage::StaticDraw);
Mesh mesh;
mesh.setPrimitive(MeshPrimitive::Triangles)
.setCount(9)
.addVertexBuffer(vertices, 0, MyShader::Position());
MAGNUM_VERIFY_NO_ERROR();
PrimitiveQuery q{PrimitiveQuery::Target::PrimitivesGenerated};
q.begin();
Renderer::enable(Renderer::Feature::RasterizerDiscard);
mesh.draw(shader);
q.end();
const bool availableBefore = q.resultAvailable();
const UnsignedInt count = q.result<UnsignedInt>();
const bool availableAfter = q.resultAvailable();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(!availableBefore);
CORRADE_VERIFY(availableAfter);
CORRADE_COMPARE(count, 3);
}
void PrimitiveQueryGLTest::primitivesGeneratedIndexed() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::transform_feedback3>())
CORRADE_SKIP(Extensions::GL::ARB::transform_feedback3::string() + std::string(" is not available."));
/* Bind some FB to avoid errors on contexts w/o default FB */
Renderbuffer color;
color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32});
Framebuffer fb{{{}, Vector2i{32}}};
fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color)
.bind();
struct MyShader: AbstractShaderProgram {
typedef Attribute<0, Vector2> Position;
explicit MyShader() {
Shader vert(
#ifndef CORRADE_TARGET_APPLE
Version::GL210
#else
Version::GL310
#endif
, Shader::Type::Vertex);
CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource(
"#if __VERSION__ >= 130\n"
"#define attribute in\n"
"#endif\n"
"attribute vec4 position;\n"
"void main() {\n"
" gl_Position = position;\n"
"}\n").compile());
attachShader(vert);
bindAttributeLocation(Position::Location, "position");
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
}
} shader;
Buffer vertices;
vertices.setData({nullptr, 9*sizeof(Vector2)}, BufferUsage::StaticDraw);
Mesh mesh;
mesh.setPrimitive(MeshPrimitive::Triangles)
.setCount(9)
.addVertexBuffer(vertices, 0, MyShader::Position());
MAGNUM_VERIFY_NO_ERROR();
PrimitiveQuery q{PrimitiveQuery::Target::PrimitivesGenerated};
q.begin(0);
Renderer::enable(Renderer::Feature::RasterizerDiscard);
mesh.draw(shader);
q.end();
const UnsignedInt count = q.result<UnsignedInt>();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(count, 3);
}
#endif
void PrimitiveQueryGLTest::transformFeedbackPrimitivesWritten() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::transform_feedback2>())
CORRADE_SKIP(Extensions::GL::ARB::transform_feedback2::string() + std::string(" is not available."));
#endif
/* Bind some FB to avoid errors on contexts w/o default FB */
Renderbuffer color;
color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32});
Framebuffer fb{{{}, Vector2i{32}}};
fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color)
.bind();
struct MyShader: AbstractShaderProgram {
explicit MyShader() {
#ifndef MAGNUM_TARGET_GLES
Shader vert(
#ifndef CORRADE_TARGET_APPLE
Version::GL300
#else
Version::GL310
#endif
, Shader::Type::Vertex);
#else
Shader vert(Version::GLES300, Shader::Type::Vertex);
Shader frag(Version::GLES300, Shader::Type::Fragment);
#endif
CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource(
"out mediump vec2 outputData;\n"
"void main() {\n"
" outputData = vec2(1.0, -1.0);\n"
/* Mesa drivers complain that vertex shader doesn't write to
gl_Position otherwise */
" gl_Position = vec4(1.0);\n"
"}\n").compile());
#ifndef MAGNUM_TARGET_GLES
attachShader(vert);
#else
/* ES for some reason needs both vertex and fragment shader */
CORRADE_INTERNAL_ASSERT_OUTPUT(frag.addSource("void main() {}\n").compile());
attachShaders({vert, frag});
#endif
setTransformFeedbackOutputs({"outputData"}, TransformFeedbackBufferMode::SeparateAttributes);
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
}
} shader;
Buffer output;
output.setData({nullptr, 18*sizeof(Vector2)}, BufferUsage::StaticDraw);
Mesh mesh;
mesh.setPrimitive(MeshPrimitive::Triangles)
.setCount(9);
MAGNUM_VERIFY_NO_ERROR();
TransformFeedback feedback;
feedback.attachBuffer(0, output);
PrimitiveQuery q{PrimitiveQuery::Target::TransformFeedbackPrimitivesWritten};
q.begin();
Renderer::enable(Renderer::Feature::RasterizerDiscard);
mesh.draw(shader); /* Draw once without XFB (shouldn't be counted) */
feedback.begin(shader, TransformFeedback::PrimitiveMode::Triangles);
mesh.draw(shader);
feedback.end();
q.end();
const UnsignedInt count = q.result<UnsignedInt>();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(count, 3); /* Three triangles (9 vertices) */
}
#ifndef MAGNUM_TARGET_GLES
void PrimitiveQueryGLTest::transformFeedbackOverflow() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::transform_feedback_overflow_query>())
CORRADE_SKIP(Extensions::GL::ARB::transform_feedback_overflow_query::string() + std::string(" is not available."));
#endif
/* Bind some FB to avoid errors on contexts w/o default FB */
Renderbuffer color;
color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32});
Framebuffer fb{{{}, Vector2i{32}}};
fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color)
.bind();
struct MyShader: AbstractShaderProgram {
explicit MyShader() {
#ifndef MAGNUM_TARGET_GLES
Shader vert(
#ifndef CORRADE_TARGET_APPLE
Version::GL300
#else
Version::GL310
#endif
, Shader::Type::Vertex);
#else
Shader vert(Version::GLES300, Shader::Type::Vertex);
Shader frag(Version::GLES300, Shader::Type::Fragment);
#endif
CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource(
"out mediump vec2 outputData;\n"
"void main() {\n"
" outputData = vec2(1.0, -1.0);\n"
/* Mesa drivers complain that vertex shader doesn't write to
gl_Position otherwise */
" gl_Position = vec4(1.0);\n"
"}\n").compile());
#ifndef MAGNUM_TARGET_GLES
attachShader(vert);
#else
/* ES for some reason needs both vertex and fragment shader */
CORRADE_INTERNAL_ASSERT_OUTPUT(frag.addSource("void main() {}\n").compile());
attachShaders({vert, frag});
#endif
setTransformFeedbackOutputs({"outputData"}, TransformFeedbackBufferMode::SeparateAttributes);
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
}
} shader;
Buffer output;
output.setData({nullptr, 18*sizeof(Vector2)}, BufferUsage::StaticDraw);
Mesh mesh;
mesh.setPrimitive(MeshPrimitive::Triangles)
.setCount(9);
MAGNUM_VERIFY_NO_ERROR();
TransformFeedback feedback;
/* Deliberately one vertex smaller to not fit two of them */
feedback.attachBuffer(0, output, 0, 17*sizeof(Vector2));
Renderer::enable(Renderer::Feature::RasterizerDiscard);
feedback.begin(shader, TransformFeedback::PrimitiveMode::Triangles);
PrimitiveQuery q1{PrimitiveQuery::Target::TransformFeedbackOverflow},
q2{PrimitiveQuery::Target::TransformFeedbackOverflow};
q1.begin();
mesh.draw(shader);
q1.end();
q2.begin();
mesh.draw(shader);
q2.end();
feedback.end();
const bool overflown1 = q1.result<bool>();
const bool overflown2 = q2.result<bool>();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(!overflown1);
CORRADE_VERIFY(overflown2); /* Got space for only 17 vertices instead of 2*9 */
}
#endif
}}
MAGNUM_GL_TEST_MAIN(Magnum::Test::PrimitiveQueryGLTest)
<commit_msg>Test: don't have unnecessarily large buffer size for XFB.<commit_after>/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016
Vladimír Vondruš <[email protected]>
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 <Corrade/Utility/Assert.h>
#include <Corrade/Utility/Resource.h>
#include "Magnum/AbstractShaderProgram.h"
#include "Magnum/Buffer.h"
#include "Magnum/Framebuffer.h"
#include "Magnum/Mesh.h"
#include "Magnum/PrimitiveQuery.h"
#include "Magnum/Renderbuffer.h"
#include "Magnum/RenderbufferFormat.h"
#include "Magnum/Shader.h"
#include "Magnum/TransformFeedback.h"
#include "Magnum/Math/Vector2.h"
#include "Magnum/Test/AbstractOpenGLTester.h"
namespace Magnum { namespace Test {
struct PrimitiveQueryGLTest: AbstractOpenGLTester {
explicit PrimitiveQueryGLTest();
void constructNoCreate();
void wrap();
#ifndef MAGNUM_TARGET_GLES
void primitivesGenerated();
void primitivesGeneratedIndexed();
#endif
void transformFeedbackPrimitivesWritten();
#ifndef MAGNUM_TARGET_GLES
void transformFeedbackOverflow();
#endif
};
PrimitiveQueryGLTest::PrimitiveQueryGLTest() {
addTests({&PrimitiveQueryGLTest::constructNoCreate,
&PrimitiveQueryGLTest::wrap,
#ifndef MAGNUM_TARGET_GLES
&PrimitiveQueryGLTest::primitivesGenerated,
&PrimitiveQueryGLTest::primitivesGeneratedIndexed,
#endif
&PrimitiveQueryGLTest::transformFeedbackPrimitivesWritten,
#ifndef MAGNUM_TARGET_GLES
&PrimitiveQueryGLTest::transformFeedbackOverflow
#endif
});
}
void PrimitiveQueryGLTest::constructNoCreate() {
{
PrimitiveQuery query{NoCreate};
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(query.id(), 0);
}
MAGNUM_VERIFY_NO_ERROR();
}
void PrimitiveQueryGLTest::wrap() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::transform_feedback2>())
CORRADE_SKIP(Extensions::GL::ARB::transform_feedback2::string() + std::string(" is not available."));
#endif
GLuint id;
glGenQueries(1, &id);
/* Releasing won't delete anything */
{
auto query = PrimitiveQuery::wrap(id, PrimitiveQuery::Target::TransformFeedbackPrimitivesWritten, ObjectFlag::DeleteOnDestruction);
CORRADE_COMPARE(query.release(), id);
}
/* ...so we can wrap it again */
PrimitiveQuery::wrap(id, PrimitiveQuery::Target::TransformFeedbackPrimitivesWritten);
glDeleteQueries(1, &id);
}
#ifndef MAGNUM_TARGET_GLES
void PrimitiveQueryGLTest::primitivesGenerated() {
if(!Context::current().isExtensionSupported<Extensions::GL::EXT::transform_feedback>())
CORRADE_SKIP(Extensions::GL::EXT::transform_feedback::string() + std::string(" is not available."));
/* Bind some FB to avoid errors on contexts w/o default FB */
Renderbuffer color;
color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32});
Framebuffer fb{{{}, Vector2i{32}}};
fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color)
.bind();
struct MyShader: AbstractShaderProgram {
typedef Attribute<0, Vector2> Position;
explicit MyShader() {
Shader vert(
#ifndef CORRADE_TARGET_APPLE
Version::GL210
#else
Version::GL310
#endif
, Shader::Type::Vertex);
CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource(
"#if __VERSION__ >= 130\n"
"#define attribute in\n"
"#endif\n"
"attribute vec4 position;\n"
"void main() {\n"
" gl_Position = position;\n"
"}\n").compile());
attachShader(vert);
bindAttributeLocation(Position::Location, "position");
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
}
} shader;
Buffer vertices;
vertices.setData({nullptr, 9*sizeof(Vector2)}, BufferUsage::StaticDraw);
Mesh mesh;
mesh.setPrimitive(MeshPrimitive::Triangles)
.setCount(9)
.addVertexBuffer(vertices, 0, MyShader::Position());
MAGNUM_VERIFY_NO_ERROR();
PrimitiveQuery q{PrimitiveQuery::Target::PrimitivesGenerated};
q.begin();
Renderer::enable(Renderer::Feature::RasterizerDiscard);
mesh.draw(shader);
q.end();
const bool availableBefore = q.resultAvailable();
const UnsignedInt count = q.result<UnsignedInt>();
const bool availableAfter = q.resultAvailable();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(!availableBefore);
CORRADE_VERIFY(availableAfter);
CORRADE_COMPARE(count, 3);
}
void PrimitiveQueryGLTest::primitivesGeneratedIndexed() {
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::transform_feedback3>())
CORRADE_SKIP(Extensions::GL::ARB::transform_feedback3::string() + std::string(" is not available."));
/* Bind some FB to avoid errors on contexts w/o default FB */
Renderbuffer color;
color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32});
Framebuffer fb{{{}, Vector2i{32}}};
fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color)
.bind();
struct MyShader: AbstractShaderProgram {
typedef Attribute<0, Vector2> Position;
explicit MyShader() {
Shader vert(
#ifndef CORRADE_TARGET_APPLE
Version::GL210
#else
Version::GL310
#endif
, Shader::Type::Vertex);
CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource(
"#if __VERSION__ >= 130\n"
"#define attribute in\n"
"#endif\n"
"attribute vec4 position;\n"
"void main() {\n"
" gl_Position = position;\n"
"}\n").compile());
attachShader(vert);
bindAttributeLocation(Position::Location, "position");
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
}
} shader;
Buffer vertices;
vertices.setData({nullptr, 9*sizeof(Vector2)}, BufferUsage::StaticDraw);
Mesh mesh;
mesh.setPrimitive(MeshPrimitive::Triangles)
.setCount(9)
.addVertexBuffer(vertices, 0, MyShader::Position());
MAGNUM_VERIFY_NO_ERROR();
PrimitiveQuery q{PrimitiveQuery::Target::PrimitivesGenerated};
q.begin(0);
Renderer::enable(Renderer::Feature::RasterizerDiscard);
mesh.draw(shader);
q.end();
const UnsignedInt count = q.result<UnsignedInt>();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(count, 3);
}
#endif
void PrimitiveQueryGLTest::transformFeedbackPrimitivesWritten() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::transform_feedback2>())
CORRADE_SKIP(Extensions::GL::ARB::transform_feedback2::string() + std::string(" is not available."));
#endif
/* Bind some FB to avoid errors on contexts w/o default FB */
Renderbuffer color;
color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32});
Framebuffer fb{{{}, Vector2i{32}}};
fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color)
.bind();
struct MyShader: AbstractShaderProgram {
explicit MyShader() {
#ifndef MAGNUM_TARGET_GLES
Shader vert(
#ifndef CORRADE_TARGET_APPLE
Version::GL300
#else
Version::GL310
#endif
, Shader::Type::Vertex);
#else
Shader vert(Version::GLES300, Shader::Type::Vertex);
Shader frag(Version::GLES300, Shader::Type::Fragment);
#endif
CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource(
"out mediump vec2 outputData;\n"
"void main() {\n"
" outputData = vec2(1.0, -1.0);\n"
/* Mesa drivers complain that vertex shader doesn't write to
gl_Position otherwise */
" gl_Position = vec4(1.0);\n"
"}\n").compile());
#ifndef MAGNUM_TARGET_GLES
attachShader(vert);
#else
/* ES for some reason needs both vertex and fragment shader */
CORRADE_INTERNAL_ASSERT_OUTPUT(frag.addSource("void main() {}\n").compile());
attachShaders({vert, frag});
#endif
setTransformFeedbackOutputs({"outputData"}, TransformFeedbackBufferMode::SeparateAttributes);
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
}
} shader;
Buffer output;
output.setData({nullptr, 9*sizeof(Vector2)}, BufferUsage::StaticDraw);
Mesh mesh;
mesh.setPrimitive(MeshPrimitive::Triangles)
.setCount(9);
MAGNUM_VERIFY_NO_ERROR();
TransformFeedback feedback;
feedback.attachBuffer(0, output);
PrimitiveQuery q{PrimitiveQuery::Target::TransformFeedbackPrimitivesWritten};
q.begin();
Renderer::enable(Renderer::Feature::RasterizerDiscard);
mesh.draw(shader); /* Draw once without XFB (shouldn't be counted) */
feedback.begin(shader, TransformFeedback::PrimitiveMode::Triangles);
mesh.draw(shader);
feedback.end();
q.end();
const UnsignedInt count = q.result<UnsignedInt>();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_COMPARE(count, 3); /* Three triangles (9 vertices) */
}
#ifndef MAGNUM_TARGET_GLES
void PrimitiveQueryGLTest::transformFeedbackOverflow() {
#ifndef MAGNUM_TARGET_GLES
if(!Context::current().isExtensionSupported<Extensions::GL::ARB::transform_feedback_overflow_query>())
CORRADE_SKIP(Extensions::GL::ARB::transform_feedback_overflow_query::string() + std::string(" is not available."));
#endif
/* Bind some FB to avoid errors on contexts w/o default FB */
Renderbuffer color;
color.setStorage(RenderbufferFormat::RGBA8, Vector2i{32});
Framebuffer fb{{{}, Vector2i{32}}};
fb.attachRenderbuffer(Framebuffer::ColorAttachment{0}, color)
.bind();
struct MyShader: AbstractShaderProgram {
explicit MyShader() {
#ifndef MAGNUM_TARGET_GLES
Shader vert(
#ifndef CORRADE_TARGET_APPLE
Version::GL300
#else
Version::GL310
#endif
, Shader::Type::Vertex);
#else
Shader vert(Version::GLES300, Shader::Type::Vertex);
Shader frag(Version::GLES300, Shader::Type::Fragment);
#endif
CORRADE_INTERNAL_ASSERT_OUTPUT(vert.addSource(
"out mediump vec2 outputData;\n"
"void main() {\n"
" outputData = vec2(1.0, -1.0);\n"
/* Mesa drivers complain that vertex shader doesn't write to
gl_Position otherwise */
" gl_Position = vec4(1.0);\n"
"}\n").compile());
#ifndef MAGNUM_TARGET_GLES
attachShader(vert);
#else
/* ES for some reason needs both vertex and fragment shader */
CORRADE_INTERNAL_ASSERT_OUTPUT(frag.addSource("void main() {}\n").compile());
attachShaders({vert, frag});
#endif
setTransformFeedbackOutputs({"outputData"}, TransformFeedbackBufferMode::SeparateAttributes);
CORRADE_INTERNAL_ASSERT_OUTPUT(link());
}
} shader;
Buffer output;
output.setData({nullptr, 18*sizeof(Vector2)}, BufferUsage::StaticDraw);
Mesh mesh;
mesh.setPrimitive(MeshPrimitive::Triangles)
.setCount(9);
MAGNUM_VERIFY_NO_ERROR();
TransformFeedback feedback;
/* Deliberately one vertex smaller to not fit two of them */
feedback.attachBuffer(0, output, 0, 17*sizeof(Vector2));
Renderer::enable(Renderer::Feature::RasterizerDiscard);
feedback.begin(shader, TransformFeedback::PrimitiveMode::Triangles);
PrimitiveQuery q1{PrimitiveQuery::Target::TransformFeedbackOverflow},
q2{PrimitiveQuery::Target::TransformFeedbackOverflow};
q1.begin();
mesh.draw(shader);
q1.end();
q2.begin();
mesh.draw(shader);
q2.end();
feedback.end();
const bool overflown1 = q1.result<bool>();
const bool overflown2 = q2.result<bool>();
MAGNUM_VERIFY_NO_ERROR();
CORRADE_VERIFY(!overflown1);
CORRADE_VERIFY(overflown2); /* Got space for only 17 vertices instead of 2*9 */
}
#endif
}}
MAGNUM_GL_TEST_MAIN(Magnum::Test::PrimitiveQueryGLTest)
<|endoftext|> |
<commit_before>//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file This file implements a clang-tidy tool.
///
/// This tool uses the Clang Tooling infrastructure, see
/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
/// for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//
#include "../ClangTidy.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "llvm/Support/Process.h"
using namespace clang::ast_matchers;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;
static cl::OptionCategory ClangTidyCategory("clang-tidy options");
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp ClangTidyHelp(
"Configuration files:\n"
" clang-tidy attempts to read configuration for each source file from a\n"
" .clang-tidy file located in the closest parent directory of the source\n"
" file. If any configuration options have a corresponding command-line\n"
" option, command-line option takes precedence. The effective\n"
" configuration can be inspected using -dump-config.\n\n");
const char DefaultChecks[] =
"*," // Enable all checks, except these:
"-clang-analyzer-alpha*," // Too many false positives.
"-llvm-include-order," // Not implemented yet.
"-google-*,"; // Doesn't apply to LLVM.
static cl::opt<std::string>
Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
"prefix. Globs are processed in order of appearance\n"
"in the list. Globs without '-' prefix add checks\n"
"with matching names to the set, globs with the '-'\n"
"prefix remove checks with matching names from the\n"
"set of enabled checks.\n"
"This option's value is appended to the value read\n"
"from a .clang-tidy file, if any."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
HeaderFilter("header-filter",
cl::desc("Regular expression matching the names of the\n"
"headers to output diagnostics from. Diagnostics\n"
"from the main file of each translation unit are\n"
"always displayed.\n"
"Can be used together with -line-filter.\n"
"This option overrides the value read from a\n"
".clang-tidy file."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
LineFilter("line-filter",
cl::desc("List of files with line ranges to filter the\n"
"warnings. Can be used together with\n"
"-header-filter. The format of the list is a JSON\n"
"array of objects:\n"
" [\n"
" {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
" {\"name\":\"file2.h\"}\n"
" ]"),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool>
ListChecks("list-checks",
cl::desc("List all enabled checks and exit. Use with\n"
"-checks='*' to list all available checks."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool>
DumpConfig("dump-config",
cl::desc("Dumps configuration in the YAML format to stdout."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool> AnalyzeTemporaryDtors(
"analyze-temporary-dtors",
cl::desc("Enable temporary destructor-aware analysis in\n"
"clang-analyzer- checks.\n"
"This option overrides the value read from a\n"
".clang-tidy file."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string> ExportFixes(
"export-fixes",
cl::desc("YAML file to store suggested fixes in. The\n"
"stored fixes can be applied to the input source\n"
"code with clang-apply-replacements."),
cl::value_desc("filename"), cl::cat(ClangTidyCategory));
namespace clang {
namespace tidy {
static void printStats(const ClangTidyStats &Stats) {
if (Stats.errorsIgnored()) {
llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
StringRef Separator = "";
if (Stats.ErrorsIgnoredNonUserCode) {
llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
Separator = ", ";
}
if (Stats.ErrorsIgnoredLineFilter) {
llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
<< " due to line filter";
Separator = ", ";
}
if (Stats.ErrorsIgnoredNOLINT) {
llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
Separator = ", ";
}
if (Stats.ErrorsIgnoredCheckFilter)
llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
<< " with check filters";
llvm::errs() << ").\n";
if (Stats.ErrorsIgnoredNonUserCode)
llvm::errs() << "Use -header-filter='.*' to display errors from all "
"non-system headers.\n";
}
}
int clangTidyMain(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory);
ClangTidyGlobalOptions GlobalOptions;
if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return 1;
}
ClangTidyOptions DefaultOptions;
DefaultOptions.Checks = DefaultChecks;
DefaultOptions.HeaderFilterRegex = HeaderFilter;
DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
// USERNAME is used on Windows.
if (!DefaultOptions.User)
DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
ClangTidyOptions OverrideOptions;
if (Checks.getNumOccurrences() > 0)
OverrideOptions.Checks = Checks;
if (HeaderFilter.getNumOccurrences() > 0)
OverrideOptions.HeaderFilterRegex = HeaderFilter;
if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
auto OptionsProvider = llvm::make_unique<FileOptionsProvider>(
GlobalOptions, DefaultOptions, OverrideOptions);
std::string FileName = OptionsParser.getSourcePathList().front();
ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
// FIXME: Allow using --list-checks without positional arguments.
if (ListChecks) {
llvm::outs() << "Enabled checks:";
for (auto CheckName : EnabledChecks)
llvm::outs() << "\n " << CheckName;
llvm::outs() << "\n\n";
return 0;
}
if (DumpConfig) {
EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults()
.mergeWith(EffectiveOptions))
<< "\n";
return 0;
}
if (EnabledChecks.empty()) {
llvm::errs() << "Error: no checks enabled.\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return 1;
}
std::vector<ClangTidyError> Errors;
ClangTidyStats Stats =
runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
OptionsParser.getSourcePathList(), &Errors);
handleErrors(Errors, Fix);
if (!ExportFixes.empty() && !Errors.empty()) {
std::error_code EC;
llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
if (EC) {
llvm::errs() << "Error opening output file: " << EC.message() << '\n';
return 1;
}
exportReplacements(Errors, OS);
}
printStats(Stats);
return 0;
}
// This anchor is used to force the linker to link the LLVMModule.
extern volatile int LLVMModuleAnchorSource;
static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
// This anchor is used to force the linker to link the GoogleModule.
extern volatile int GoogleModuleAnchorSource;
static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
// This anchor is used to force the linker to link the MiscModule.
extern volatile int MiscModuleAnchorSource;
static int MiscModuleAnchorDestination = MiscModuleAnchorSource;
} // namespace tidy
} // namespace clang
int main(int argc, const char **argv) {
return clang::tidy::clangTidyMain(argc, argv);
}
<commit_msg>[clang-tidy] Add a -config={YAML} option.<commit_after>//===--- tools/extra/clang-tidy/ClangTidyMain.cpp - Clang tidy tool -------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file This file implements a clang-tidy tool.
///
/// This tool uses the Clang Tooling infrastructure, see
/// http://clang.llvm.org/docs/HowToSetupToolingForLLVM.html
/// for details on setting it up with LLVM source tree.
///
//===----------------------------------------------------------------------===//
#include "../ClangTidy.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "llvm/Support/Process.h"
using namespace clang::ast_matchers;
using namespace clang::driver;
using namespace clang::tooling;
using namespace llvm;
static cl::OptionCategory ClangTidyCategory("clang-tidy options");
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
static cl::extrahelp ClangTidyHelp(
"Configuration files:\n"
" clang-tidy attempts to read configuration for each source file from a\n"
" .clang-tidy file located in the closest parent directory of the source\n"
" file. If any configuration options have a corresponding command-line\n"
" option, command-line option takes precedence. The effective\n"
" configuration can be inspected using -dump-config.\n\n");
const char DefaultChecks[] =
"*," // Enable all checks, except these:
"-clang-analyzer-alpha*," // Too many false positives.
"-llvm-include-order," // Not implemented yet.
"-google-*,"; // Doesn't apply to LLVM.
static cl::opt<std::string>
Checks("checks", cl::desc("Comma-separated list of globs with optional '-'\n"
"prefix. Globs are processed in order of appearance\n"
"in the list. Globs without '-' prefix add checks\n"
"with matching names to the set, globs with the '-'\n"
"prefix remove checks with matching names from the\n"
"set of enabled checks.\n"
"This option's value is appended to the value read\n"
"from a .clang-tidy file, if any."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
HeaderFilter("header-filter",
cl::desc("Regular expression matching the names of the\n"
"headers to output diagnostics from. Diagnostics\n"
"from the main file of each translation unit are\n"
"always displayed.\n"
"Can be used together with -line-filter.\n"
"This option overrides the value read from a\n"
".clang-tidy file."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<std::string>
LineFilter("line-filter",
cl::desc("List of files with line ranges to filter the\n"
"warnings. Can be used together with\n"
"-header-filter. The format of the list is a JSON\n"
"array of objects:\n"
" [\n"
" {\"name\":\"file1.cpp\",\"lines\":[[1,3],[5,7]]},\n"
" {\"name\":\"file2.h\"}\n"
" ]"),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool> Fix("fix", cl::desc("Fix detected errors if possible."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool>
ListChecks("list-checks",
cl::desc("List all enabled checks and exit. Use with\n"
"-checks='*' to list all available checks."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string> Config(
"config",
cl::desc("Specifies a configuration in YAML/JSON format:\n"
" -config=\"{Checks: '*', CheckOptions: {key: x, value: y}}\"\n"
"When the value is empty, clang-tidy will attempt to find\n"
"a file named .clang-tidy for each sorce file in its parent\n"
"directories."),
cl::init(""), cl::cat(ClangTidyCategory));
static cl::opt<bool>
DumpConfig("dump-config",
cl::desc("Dumps configuration in the YAML format to stdout."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<bool> AnalyzeTemporaryDtors(
"analyze-temporary-dtors",
cl::desc("Enable temporary destructor-aware analysis in\n"
"clang-analyzer- checks.\n"
"This option overrides the value read from a\n"
".clang-tidy file."),
cl::init(false), cl::cat(ClangTidyCategory));
static cl::opt<std::string> ExportFixes(
"export-fixes",
cl::desc("YAML file to store suggested fixes in. The\n"
"stored fixes can be applied to the input source\n"
"code with clang-apply-replacements."),
cl::value_desc("filename"), cl::cat(ClangTidyCategory));
namespace clang {
namespace tidy {
static void printStats(const ClangTidyStats &Stats) {
if (Stats.errorsIgnored()) {
llvm::errs() << "Suppressed " << Stats.errorsIgnored() << " warnings (";
StringRef Separator = "";
if (Stats.ErrorsIgnoredNonUserCode) {
llvm::errs() << Stats.ErrorsIgnoredNonUserCode << " in non-user code";
Separator = ", ";
}
if (Stats.ErrorsIgnoredLineFilter) {
llvm::errs() << Separator << Stats.ErrorsIgnoredLineFilter
<< " due to line filter";
Separator = ", ";
}
if (Stats.ErrorsIgnoredNOLINT) {
llvm::errs() << Separator << Stats.ErrorsIgnoredNOLINT << " NOLINT";
Separator = ", ";
}
if (Stats.ErrorsIgnoredCheckFilter)
llvm::errs() << Separator << Stats.ErrorsIgnoredCheckFilter
<< " with check filters";
llvm::errs() << ").\n";
if (Stats.ErrorsIgnoredNonUserCode)
llvm::errs() << "Use -header-filter='.*' to display errors from all "
"non-system headers.\n";
}
}
std::unique_ptr<ClangTidyOptionsProvider> createOptionsProvider() {
ClangTidyGlobalOptions GlobalOptions;
if (std::error_code Err = parseLineFilter(LineFilter, GlobalOptions)) {
llvm::errs() << "Invalid LineFilter: " << Err.message() << "\n\nUsage:\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return nullptr;
}
ClangTidyOptions DefaultOptions;
DefaultOptions.Checks = DefaultChecks;
DefaultOptions.HeaderFilterRegex = HeaderFilter;
DefaultOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
DefaultOptions.User = llvm::sys::Process::GetEnv("USER");
// USERNAME is used on Windows.
if (!DefaultOptions.User)
DefaultOptions.User = llvm::sys::Process::GetEnv("USERNAME");
ClangTidyOptions OverrideOptions;
if (Checks.getNumOccurrences() > 0)
OverrideOptions.Checks = Checks;
if (HeaderFilter.getNumOccurrences() > 0)
OverrideOptions.HeaderFilterRegex = HeaderFilter;
if (AnalyzeTemporaryDtors.getNumOccurrences() > 0)
OverrideOptions.AnalyzeTemporaryDtors = AnalyzeTemporaryDtors;
if (!Config.empty()) {
if (llvm::ErrorOr<ClangTidyOptions> ParsedConfig =
parseConfiguration(Config)) {
return llvm::make_unique<DefaultOptionsProvider>(
GlobalOptions, ClangTidyOptions::getDefaults()
.mergeWith(DefaultOptions)
.mergeWith(*ParsedConfig)
.mergeWith(OverrideOptions));
} else {
llvm::errs() << "Error: invalid configuration specified.\n"
<< ParsedConfig.getError().message() << "\n";
return nullptr;
}
}
return llvm::make_unique<FileOptionsProvider>(GlobalOptions, DefaultOptions,
OverrideOptions);
}
int clangTidyMain(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, ClangTidyCategory);
auto OptionsProvider = createOptionsProvider();
if (!OptionsProvider)
return 1;
std::string FileName = OptionsParser.getSourcePathList().front();
ClangTidyOptions EffectiveOptions = OptionsProvider->getOptions(FileName);
std::vector<std::string> EnabledChecks = getCheckNames(EffectiveOptions);
// FIXME: Allow using --list-checks without positional arguments.
if (ListChecks) {
llvm::outs() << "Enabled checks:";
for (auto CheckName : EnabledChecks)
llvm::outs() << "\n " << CheckName;
llvm::outs() << "\n\n";
return 0;
}
if (DumpConfig) {
EffectiveOptions.CheckOptions = getCheckOptions(EffectiveOptions);
llvm::outs() << configurationAsText(ClangTidyOptions::getDefaults()
.mergeWith(EffectiveOptions))
<< "\n";
return 0;
}
if (EnabledChecks.empty()) {
llvm::errs() << "Error: no checks enabled.\n";
llvm::cl::PrintHelpMessage(/*Hidden=*/false, /*Categorized=*/true);
return 1;
}
std::vector<ClangTidyError> Errors;
ClangTidyStats Stats =
runClangTidy(std::move(OptionsProvider), OptionsParser.getCompilations(),
OptionsParser.getSourcePathList(), &Errors);
handleErrors(Errors, Fix);
if (!ExportFixes.empty() && !Errors.empty()) {
std::error_code EC;
llvm::raw_fd_ostream OS(ExportFixes, EC, llvm::sys::fs::F_None);
if (EC) {
llvm::errs() << "Error opening output file: " << EC.message() << '\n';
return 1;
}
exportReplacements(Errors, OS);
}
printStats(Stats);
return 0;
}
// This anchor is used to force the linker to link the LLVMModule.
extern volatile int LLVMModuleAnchorSource;
static int LLVMModuleAnchorDestination = LLVMModuleAnchorSource;
// This anchor is used to force the linker to link the GoogleModule.
extern volatile int GoogleModuleAnchorSource;
static int GoogleModuleAnchorDestination = GoogleModuleAnchorSource;
// This anchor is used to force the linker to link the MiscModule.
extern volatile int MiscModuleAnchorSource;
static int MiscModuleAnchorDestination = MiscModuleAnchorSource;
} // namespace tidy
} // namespace clang
int main(int argc, const char **argv) {
return clang::tidy::clangTidyMain(argc, argv);
}
<|endoftext|> |
<commit_before>#include "onoff_gpio.h"
#include <QDebug>
OnOffMorse::OnOffMorse()
{
int pin = 30;
exportPin(pin);
setDirection(pin, "out");
QString path = QString("/sys/class/gpio%1/value").arg(pin);
m_file.setFileName(path);
if (!m_file.open(QIODevice::WriteOnly)) {
qDebug() << "Failed to open pin value setter:" << m_file.errorString();
}
}
OnOffMorse::~OnOffMorse()
{
}
void OnOffMorse::setOn(bool setOn)
{
m_file.write(setOn ? "1" : "0");
}
void OnOffMorse::exportPin(int pin)
{
QString path = QString("/sys/class/gip/export");
QFile file(path);
if (file.open(QIODevice::WriteOnly)) {
file.write( QString::number(pin).toLatin1() );
} else {
qDebug() << "Failed to export pin:" << file.errorString();
}
}
void OnOffMorse::setDirection(int pin, const QByteArray &direction)
{
QString path = QString("/sys/class/gpio%1/value").arg(pin);
QFile file(path);
if (file.open(QIODevice::WriteOnly)) {
file.write(direction);
} else {
qDebug() << "Failed to set value on pin:" << file.errorString();
}
}
<commit_msg>Fixed typos<commit_after>#include "onoff_gpio.h"
#include <QDebug>
OnOffMorse::OnOffMorse()
{
int pin = 30;
exportPin(pin);
setDirection(pin, "out");
QString path = QString("/sys/class/gpio/gpio%1/value").arg(pin);
m_file.setFileName(path);
if (!m_file.open(QIODevice::WriteOnly)) {
qDebug() << "Failed to open pin value setter:" << m_file.errorString();
}
}
OnOffMorse::~OnOffMorse()
{
}
void OnOffMorse::setOn(bool setOn)
{
m_file.write(setOn ? "1" : "0");
}
void OnOffMorse::exportPin(int pin)
{
QString path = QString("/sys/class/gpio/export");
QFile file(path);
if (file.open(QIODevice::WriteOnly)) {
file.write( QString::number(pin).toLatin1() );
} else {
qDebug() << "Failed to export pin:" << file.errorString();
}
}
void OnOffMorse::setDirection(int pin, const QByteArray &direction)
{
QString path = QString("/sys/class/gpio/gpio%1/direction").arg(pin);
QFile file(path);
if (file.open(QIODevice::WriteOnly)) {
file.write(direction);
} else {
qDebug() << "Failed to set value on pin:" << file.errorString();
}
}
<|endoftext|> |
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "persistencehandlerproxy.h"
#include "documentretriever.h"
#include "documentdb.h"
#include <vespa/searchcore/proton/feedoperation/createbucketoperation.h>
#include <vespa/searchcore/proton/feedoperation/deletebucketoperation.h>
#include <vespa/searchcore/proton/feedoperation/joinbucketsoperation.h>
#include <vespa/searchcore/proton/feedoperation/putoperation.h>
#include <vespa/searchcore/proton/feedoperation/removeoperation.h>
#include <vespa/searchcore/proton/feedoperation/splitbucketoperation.h>
#include <vespa/searchcore/proton/feedoperation/updateoperation.h>
#include <vespa/persistence/spi/result.h>
using storage::spi::Bucket;
using storage::spi::Timestamp;
namespace proton {
PersistenceHandlerProxy::PersistenceHandlerProxy(const DocumentDB::SP &documentDB)
: _documentDB(documentDB),
_feedHandler(_documentDB->getFeedHandler()),
_bucketHandler(_documentDB->getBucketHandler()),
_clusterStateHandler(_documentDB->getClusterStateHandler())
{
_documentDB->retain();
}
PersistenceHandlerProxy::~PersistenceHandlerProxy()
{
_documentDB->release();
}
void
PersistenceHandlerProxy::initialize()
{
_documentDB->waitForOnlineState();
}
void
PersistenceHandlerProxy::handlePut(FeedToken token,
const Bucket &bucket,
Timestamp timestamp,
const document::Document::SP &doc)
{
FeedOperation::UP op(new PutOperation(bucket.getBucketId().stripUnused(),
timestamp, doc));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleUpdate(FeedToken token,
const Bucket &bucket,
Timestamp timestamp,
const document::DocumentUpdate::SP &upd)
{
FeedOperation::UP op(new UpdateOperation(bucket.getBucketId().
stripUnused(),
timestamp, upd));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleRemove(FeedToken token,
const Bucket &bucket,
Timestamp timestamp,
const document::DocumentId &id)
{
FeedOperation::UP op(new RemoveOperation(bucket.getBucketId().
stripUnused(),
timestamp, id));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleListBuckets(IBucketIdListResultHandler &resultHandler)
{
_bucketHandler.handleListBuckets(resultHandler);
}
void
PersistenceHandlerProxy::handleSetClusterState(const storage::spi::ClusterState &calc,
IGenericResultHandler &resultHandler)
{
_clusterStateHandler.handleSetClusterState(calc, resultHandler);
}
void
PersistenceHandlerProxy::handleSetActiveState(
const storage::spi::Bucket &bucket,
storage::spi::BucketInfo::ActiveState newState,
IGenericResultHandler &resultHandler)
{
_bucketHandler.handleSetCurrentState(bucket.getBucketId().stripUnused(),
newState, resultHandler);
}
void
PersistenceHandlerProxy::handleGetBucketInfo(const Bucket &bucket,
IBucketInfoResultHandler &resultHandler)
{
_bucketHandler.handleGetBucketInfo(bucket, resultHandler);
}
void
PersistenceHandlerProxy::handleCreateBucket(FeedToken token,
const Bucket &bucket)
{
FeedOperation::UP op(new CreateBucketOperation(bucket.getBucketId().
stripUnused()));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleDeleteBucket(FeedToken token,
const Bucket &bucket)
{
FeedOperation::UP op(new DeleteBucketOperation(bucket.getBucketId().
stripUnused()));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleGetModifiedBuckets(IBucketIdListResultHandler &resultHandler)
{
_clusterStateHandler.handleGetModifiedBuckets(resultHandler);
}
void
PersistenceHandlerProxy::handleSplit(FeedToken token,
const Bucket &source,
const Bucket &target1,
const Bucket &target2)
{
FeedOperation::UP op(new SplitBucketOperation(source.getBucketId().
stripUnused(),
target1.getBucketId().
stripUnused(),
target2.getBucketId().
stripUnused()));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleJoin(FeedToken token,
const Bucket &source1,
const Bucket &source2,
const Bucket &target)
{
FeedOperation::UP op(new JoinBucketsOperation(source1.getBucketId().
stripUnused(),
source2.getBucketId().
stripUnused(),
target.getBucketId().
stripUnused()));
_feedHandler.handleOperation(token, std::move(op));
}
IPersistenceHandler::RetrieversSP
PersistenceHandlerProxy::getDocumentRetrievers(storage::spi::ReadConsistency consistency)
{
return _documentDB->getDocumentRetrievers(consistency);
}
BucketGuard::UP
PersistenceHandlerProxy::lockBucket(const storage::spi::Bucket &bucket)
{
return _documentDB->lockBucket(bucket.getBucketId().stripUnused());
}
void
PersistenceHandlerProxy::handleListActiveBuckets(
IBucketIdListResultHandler &resultHandler)
{
_bucketHandler.handleListActiveBuckets(resultHandler);
}
void
PersistenceHandlerProxy::handlePopulateActiveBuckets(
document::BucketId::List &buckets,
IGenericResultHandler &resultHandler)
{
_bucketHandler.handlePopulateActiveBuckets(buckets, resultHandler);
}
} // namespace proton
<commit_msg>Remove unused include.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "persistencehandlerproxy.h"
#include "documentretriever.h"
#include "documentdb.h"
#include <vespa/searchcore/proton/feedoperation/createbucketoperation.h>
#include <vespa/searchcore/proton/feedoperation/deletebucketoperation.h>
#include <vespa/searchcore/proton/feedoperation/joinbucketsoperation.h>
#include <vespa/searchcore/proton/feedoperation/putoperation.h>
#include <vespa/searchcore/proton/feedoperation/removeoperation.h>
#include <vespa/searchcore/proton/feedoperation/splitbucketoperation.h>
#include <vespa/searchcore/proton/feedoperation/updateoperation.h>
using storage::spi::Bucket;
using storage::spi::Timestamp;
namespace proton {
PersistenceHandlerProxy::PersistenceHandlerProxy(const DocumentDB::SP &documentDB)
: _documentDB(documentDB),
_feedHandler(_documentDB->getFeedHandler()),
_bucketHandler(_documentDB->getBucketHandler()),
_clusterStateHandler(_documentDB->getClusterStateHandler())
{
_documentDB->retain();
}
PersistenceHandlerProxy::~PersistenceHandlerProxy()
{
_documentDB->release();
}
void
PersistenceHandlerProxy::initialize()
{
_documentDB->waitForOnlineState();
}
void
PersistenceHandlerProxy::handlePut(FeedToken token,
const Bucket &bucket,
Timestamp timestamp,
const document::Document::SP &doc)
{
FeedOperation::UP op(new PutOperation(bucket.getBucketId().stripUnused(),
timestamp, doc));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleUpdate(FeedToken token,
const Bucket &bucket,
Timestamp timestamp,
const document::DocumentUpdate::SP &upd)
{
FeedOperation::UP op(new UpdateOperation(bucket.getBucketId().
stripUnused(),
timestamp, upd));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleRemove(FeedToken token,
const Bucket &bucket,
Timestamp timestamp,
const document::DocumentId &id)
{
FeedOperation::UP op(new RemoveOperation(bucket.getBucketId().
stripUnused(),
timestamp, id));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleListBuckets(IBucketIdListResultHandler &resultHandler)
{
_bucketHandler.handleListBuckets(resultHandler);
}
void
PersistenceHandlerProxy::handleSetClusterState(const storage::spi::ClusterState &calc,
IGenericResultHandler &resultHandler)
{
_clusterStateHandler.handleSetClusterState(calc, resultHandler);
}
void
PersistenceHandlerProxy::handleSetActiveState(
const storage::spi::Bucket &bucket,
storage::spi::BucketInfo::ActiveState newState,
IGenericResultHandler &resultHandler)
{
_bucketHandler.handleSetCurrentState(bucket.getBucketId().stripUnused(),
newState, resultHandler);
}
void
PersistenceHandlerProxy::handleGetBucketInfo(const Bucket &bucket,
IBucketInfoResultHandler &resultHandler)
{
_bucketHandler.handleGetBucketInfo(bucket, resultHandler);
}
void
PersistenceHandlerProxy::handleCreateBucket(FeedToken token,
const Bucket &bucket)
{
FeedOperation::UP op(new CreateBucketOperation(bucket.getBucketId().
stripUnused()));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleDeleteBucket(FeedToken token,
const Bucket &bucket)
{
FeedOperation::UP op(new DeleteBucketOperation(bucket.getBucketId().
stripUnused()));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleGetModifiedBuckets(IBucketIdListResultHandler &resultHandler)
{
_clusterStateHandler.handleGetModifiedBuckets(resultHandler);
}
void
PersistenceHandlerProxy::handleSplit(FeedToken token,
const Bucket &source,
const Bucket &target1,
const Bucket &target2)
{
FeedOperation::UP op(new SplitBucketOperation(source.getBucketId().
stripUnused(),
target1.getBucketId().
stripUnused(),
target2.getBucketId().
stripUnused()));
_feedHandler.handleOperation(token, std::move(op));
}
void
PersistenceHandlerProxy::handleJoin(FeedToken token,
const Bucket &source1,
const Bucket &source2,
const Bucket &target)
{
FeedOperation::UP op(new JoinBucketsOperation(source1.getBucketId().
stripUnused(),
source2.getBucketId().
stripUnused(),
target.getBucketId().
stripUnused()));
_feedHandler.handleOperation(token, std::move(op));
}
IPersistenceHandler::RetrieversSP
PersistenceHandlerProxy::getDocumentRetrievers(storage::spi::ReadConsistency consistency)
{
return _documentDB->getDocumentRetrievers(consistency);
}
BucketGuard::UP
PersistenceHandlerProxy::lockBucket(const storage::spi::Bucket &bucket)
{
return _documentDB->lockBucket(bucket.getBucketId().stripUnused());
}
void
PersistenceHandlerProxy::handleListActiveBuckets(
IBucketIdListResultHandler &resultHandler)
{
_bucketHandler.handleListActiveBuckets(resultHandler);
}
void
PersistenceHandlerProxy::handlePopulateActiveBuckets(
document::BucketId::List &buckets,
IGenericResultHandler &resultHandler)
{
_bucketHandler.handlePopulateActiveBuckets(buckets, resultHandler);
}
} // namespace proton
<|endoftext|> |
<commit_before>
/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MissionCommandTree.h"
#include "FactMetaData.h"
#include "Vehicle.h"
#include "FirmwarePluginManager.h"
#include "QGCApplication.h"
#include "QGroundControlQmlGlobal.h"
#include "MissionCommandUIInfo.h"
#include "MissionCommandList.h"
#include <QQmlEngine>
MissionCommandTree::MissionCommandTree(QGCApplication* app, bool unitTest)
: QGCTool(app)
, _unitTest(unitTest)
{
}
void MissionCommandTree::setToolbox(QGCToolbox* toolbox)
{
QGCTool::setToolbox(toolbox);
#ifdef UNITTEST_BUILD
if (_unitTest) {
// Load unit testing tree
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC] = new MissionCommandList(":/json/unittest/MavCmdInfoCommon.json", true, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_FIXED_WING] = new MissionCommandList(":/json/unittest/MavCmdInfoFixedWing.json", false, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_QUADROTOR] = new MissionCommandList(":/json/unittest/MavCmdInfoMultiRotor.json", false, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_VTOL_QUADROTOR] = new MissionCommandList(":/json/unittest/MavCmdInfoVTOL.json", false, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_SUBMARINE] = new MissionCommandList(":/json/unittest/MavCmdInfoSub.json", false, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GROUND_ROVER] = new MissionCommandList(":/json/unittest/MavCmdInfoRover.json", false, this);
} else {
#endif
// Load all levels of hierarchy
foreach (MAV_AUTOPILOT firmwareType, _toolbox->firmwarePluginManager()->knownFirmwareTypes()) {
FirmwarePlugin* plugin = _toolbox->firmwarePluginManager()->firmwarePluginForAutopilot(firmwareType, MAV_TYPE_QUADROTOR);
QList<MAV_TYPE> vehicleTypes;
vehicleTypes << MAV_TYPE_GENERIC << MAV_TYPE_FIXED_WING << MAV_TYPE_QUADROTOR << MAV_TYPE_VTOL_QUADROTOR << MAV_TYPE_GROUND_ROVER << MAV_TYPE_SUBMARINE;
foreach(MAV_TYPE vehicleType, vehicleTypes) {
QString overrideFile = plugin->missionCommandOverrides(vehicleType);
if (!overrideFile.isEmpty()) {
_staticCommandTree[firmwareType][vehicleType] = new MissionCommandList(overrideFile, firmwareType == MAV_AUTOPILOT_GENERIC && vehicleType == MAV_TYPE_GENERIC /* baseCommandList */, this);
}
}
}
#ifdef UNITTEST_BUILD
}
#endif
}
MAV_AUTOPILOT MissionCommandTree::_baseFirmwareType(MAV_AUTOPILOT firmwareType) const
{
if (qgcApp()->toolbox()->firmwarePluginManager()->knownFirmwareTypes().contains(firmwareType)) {
return firmwareType;
} else {
return MAV_AUTOPILOT_GENERIC;
}
}
MAV_TYPE MissionCommandTree::_baseVehicleType(MAV_TYPE mavType) const
{
if (QGCMAVLink::isFixedWing(mavType)) {
return MAV_TYPE_FIXED_WING;
} else if (QGCMAVLink::isMultiRotor(mavType)) {
return MAV_TYPE_QUADROTOR;
} else if (QGCMAVLink::isVTOL(mavType)) {
return MAV_TYPE_VTOL_QUADROTOR;
} else if (QGCMAVLink::isRover(mavType)) {
return MAV_TYPE_GROUND_ROVER;
} else if (QGCMAVLink::isSub(mavType)) {
return MAV_TYPE_SUBMARINE;
} else {
return MAV_TYPE_GENERIC;
}
}
/// Add the next level of the hierarchy to a collapsed tree.
/// @param vehicle Collapsed tree is for this vehicle
/// @param cmdList List of mission commands to collapse into ui info
/// @param collapsedTree Tree we are collapsing into
void MissionCommandTree::_collapseHierarchy(Vehicle* vehicle,
const MissionCommandList* cmdList,
QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
foreach (MAV_CMD command, cmdList->commandIds()) {
MissionCommandUIInfo* uiInfo = cmdList->getUIInfo(command);
if (uiInfo) {
if (collapsedTree.contains(command)) {
collapsedTree[command]->_overrideInfo(uiInfo);
} else {
collapsedTree[command] = new MissionCommandUIInfo(*uiInfo);
}
}
}
}
void MissionCommandTree::_buildAvailableCommands(Vehicle* vehicle)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
if (_availableCommands.contains(baseFirmwareType) &&
_availableCommands[baseFirmwareType].contains(baseVehicleType)) {
// Available commands list already built
return;
}
// Build new available commands list
QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree = _availableCommands[baseFirmwareType][baseVehicleType];
// Any Firmware, Any Vehicle
_collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC], collapsedTree);
// Any Firmware, Specific Vehicle
if (baseVehicleType != MAV_TYPE_GENERIC) {
_collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][baseVehicleType], collapsedTree);
}
// Known Firmware, Any Vehicle
if (baseFirmwareType != MAV_AUTOPILOT_GENERIC) {
_collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][MAV_TYPE_GENERIC], collapsedTree);
// Known Firmware, Specific Vehicle
if (baseVehicleType != MAV_TYPE_GENERIC) {
_collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][baseVehicleType], collapsedTree);
}
}
// Build category list
QMapIterator<MAV_CMD, MissionCommandUIInfo*> iter(collapsedTree);
while (iter.hasNext()) {
iter.next();
QString newCategory = iter.value()->category();
if (!_availableCategories[baseFirmwareType][baseVehicleType].contains(newCategory)) {
_availableCategories[baseFirmwareType][baseVehicleType].append(newCategory);
}
}
}
QStringList MissionCommandTree::_availableCategoriesForVehicle(Vehicle* vehicle)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
_buildAvailableCommands(vehicle);
return _availableCategories[baseFirmwareType][baseVehicleType];
}
QString MissionCommandTree::friendlyName(MAV_CMD command)
{
MissionCommandList * commandList = _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];
MissionCommandUIInfo* uiInfo = commandList->getUIInfo(command);
if (uiInfo) {
return uiInfo->friendlyName();
} else {
return QString("MAV_CMD(%1)").arg((int)command);
}
}
QString MissionCommandTree::rawName(MAV_CMD command)
{
MissionCommandList * commandList = _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];
MissionCommandUIInfo* uiInfo = commandList->getUIInfo(command);
if (uiInfo) {
return uiInfo->rawName();
} else {
return QString("MAV_CMD(%1)").arg((int)command);
}
}
const QList<MAV_CMD>& MissionCommandTree::allCommandIds(void) const
{
return _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC]->commandIds();
}
const MissionCommandUIInfo* MissionCommandTree::getUIInfo(Vehicle* vehicle, MAV_CMD command)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
_buildAvailableCommands(vehicle);
const QMap<MAV_CMD, MissionCommandUIInfo*>& infoMap = _availableCommands[baseFirmwareType][baseVehicleType];
if (infoMap.contains(command)) {
return infoMap[command];
} else {
return NULL;
}
}
QVariantList MissionCommandTree::getCommandsForCategory(Vehicle* vehicle, const QString& category)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
_buildAvailableCommands(vehicle);
QVariantList list;
QMap<MAV_CMD, MissionCommandUIInfo*> commandMap = _availableCommands[baseFirmwareType][baseVehicleType];
foreach (MAV_CMD command, commandMap.keys()) {
MissionCommandUIInfo* uiInfo = commandMap[command];
if (uiInfo->category() == category) {
list.append(QVariant::fromValue(uiInfo));
}
}
return list;
}
void MissionCommandTree::_baseVehicleInfo(Vehicle* vehicle, MAV_AUTOPILOT& baseFirmwareType, MAV_TYPE& baseVehicleType) const
{
if (vehicle) {
baseFirmwareType = _baseFirmwareType(vehicle->firmwareType());
baseVehicleType = _baseVehicleType(vehicle->vehicleType());
} else {
// No Vehicle means offline editing
baseFirmwareType = _baseFirmwareType((MAV_AUTOPILOT)QGroundControlQmlGlobal::offlineEditingFirmwareType()->rawValue().toInt());
baseVehicleType = _baseVehicleType((MAV_TYPE)QGroundControlQmlGlobal::offlineEditingVehicleType()->rawValue().toInt());
}
}
<commit_msg>Only add supported commands<commit_after>
/****************************************************************************
*
* (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
*
* QGroundControl is licensed according to the terms in the file
* COPYING.md in the root of the source code directory.
*
****************************************************************************/
#include "MissionCommandTree.h"
#include "FactMetaData.h"
#include "Vehicle.h"
#include "FirmwarePluginManager.h"
#include "QGCApplication.h"
#include "QGroundControlQmlGlobal.h"
#include "MissionCommandUIInfo.h"
#include "MissionCommandList.h"
#include <QQmlEngine>
MissionCommandTree::MissionCommandTree(QGCApplication* app, bool unitTest)
: QGCTool(app)
, _unitTest(unitTest)
{
}
void MissionCommandTree::setToolbox(QGCToolbox* toolbox)
{
QGCTool::setToolbox(toolbox);
#ifdef UNITTEST_BUILD
if (_unitTest) {
// Load unit testing tree
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC] = new MissionCommandList(":/json/unittest/MavCmdInfoCommon.json", true, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_FIXED_WING] = new MissionCommandList(":/json/unittest/MavCmdInfoFixedWing.json", false, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_QUADROTOR] = new MissionCommandList(":/json/unittest/MavCmdInfoMultiRotor.json", false, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_VTOL_QUADROTOR] = new MissionCommandList(":/json/unittest/MavCmdInfoVTOL.json", false, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_SUBMARINE] = new MissionCommandList(":/json/unittest/MavCmdInfoSub.json", false, this);
_staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GROUND_ROVER] = new MissionCommandList(":/json/unittest/MavCmdInfoRover.json", false, this);
} else {
#endif
// Load all levels of hierarchy
foreach (MAV_AUTOPILOT firmwareType, _toolbox->firmwarePluginManager()->knownFirmwareTypes()) {
FirmwarePlugin* plugin = _toolbox->firmwarePluginManager()->firmwarePluginForAutopilot(firmwareType, MAV_TYPE_QUADROTOR);
QList<MAV_TYPE> vehicleTypes;
vehicleTypes << MAV_TYPE_GENERIC << MAV_TYPE_FIXED_WING << MAV_TYPE_QUADROTOR << MAV_TYPE_VTOL_QUADROTOR << MAV_TYPE_GROUND_ROVER << MAV_TYPE_SUBMARINE;
foreach(MAV_TYPE vehicleType, vehicleTypes) {
QString overrideFile = plugin->missionCommandOverrides(vehicleType);
if (!overrideFile.isEmpty()) {
_staticCommandTree[firmwareType][vehicleType] = new MissionCommandList(overrideFile, firmwareType == MAV_AUTOPILOT_GENERIC && vehicleType == MAV_TYPE_GENERIC /* baseCommandList */, this);
}
}
}
#ifdef UNITTEST_BUILD
}
#endif
}
MAV_AUTOPILOT MissionCommandTree::_baseFirmwareType(MAV_AUTOPILOT firmwareType) const
{
if (qgcApp()->toolbox()->firmwarePluginManager()->knownFirmwareTypes().contains(firmwareType)) {
return firmwareType;
} else {
return MAV_AUTOPILOT_GENERIC;
}
}
MAV_TYPE MissionCommandTree::_baseVehicleType(MAV_TYPE mavType) const
{
if (QGCMAVLink::isFixedWing(mavType)) {
return MAV_TYPE_FIXED_WING;
} else if (QGCMAVLink::isMultiRotor(mavType)) {
return MAV_TYPE_QUADROTOR;
} else if (QGCMAVLink::isVTOL(mavType)) {
return MAV_TYPE_VTOL_QUADROTOR;
} else if (QGCMAVLink::isRover(mavType)) {
return MAV_TYPE_GROUND_ROVER;
} else if (QGCMAVLink::isSub(mavType)) {
return MAV_TYPE_SUBMARINE;
} else {
return MAV_TYPE_GENERIC;
}
}
/// Add the next level of the hierarchy to a collapsed tree.
/// @param vehicle Collapsed tree is for this vehicle
/// @param cmdList List of mission commands to collapse into ui info
/// @param collapsedTree Tree we are collapsing into
void MissionCommandTree::_collapseHierarchy(Vehicle* vehicle,
const MissionCommandList* cmdList,
QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
foreach (MAV_CMD command, cmdList->commandIds()) {
// Only add supported command to tree (MAV_CMD_NAV_LAST is used for planned home position)
if (!vehicle->firmwarePlugin()->supportedMissionCommands().contains(command) && command != MAV_CMD_NAV_LAST) {
continue;
}
MissionCommandUIInfo* uiInfo = cmdList->getUIInfo(command);
if (uiInfo) {
if (collapsedTree.contains(command)) {
collapsedTree[command]->_overrideInfo(uiInfo);
} else {
collapsedTree[command] = new MissionCommandUIInfo(*uiInfo);
}
}
}
}
void MissionCommandTree::_buildAvailableCommands(Vehicle* vehicle)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
if (_availableCommands.contains(baseFirmwareType) &&
_availableCommands[baseFirmwareType].contains(baseVehicleType)) {
// Available commands list already built
return;
}
// Build new available commands list
QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree = _availableCommands[baseFirmwareType][baseVehicleType];
// Any Firmware, Any Vehicle
_collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC], collapsedTree);
// Any Firmware, Specific Vehicle
if (baseVehicleType != MAV_TYPE_GENERIC) {
_collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][baseVehicleType], collapsedTree);
}
// Known Firmware, Any Vehicle
if (baseFirmwareType != MAV_AUTOPILOT_GENERIC) {
_collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][MAV_TYPE_GENERIC], collapsedTree);
// Known Firmware, Specific Vehicle
if (baseVehicleType != MAV_TYPE_GENERIC) {
_collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][baseVehicleType], collapsedTree);
}
}
// Build category list
QMapIterator<MAV_CMD, MissionCommandUIInfo*> iter(collapsedTree);
while (iter.hasNext()) {
iter.next();
QString newCategory = iter.value()->category();
if (!_availableCategories[baseFirmwareType][baseVehicleType].contains(newCategory)) {
_availableCategories[baseFirmwareType][baseVehicleType].append(newCategory);
}
}
}
QStringList MissionCommandTree::_availableCategoriesForVehicle(Vehicle* vehicle)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
_buildAvailableCommands(vehicle);
return _availableCategories[baseFirmwareType][baseVehicleType];
}
QString MissionCommandTree::friendlyName(MAV_CMD command)
{
MissionCommandList * commandList = _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];
MissionCommandUIInfo* uiInfo = commandList->getUIInfo(command);
if (uiInfo) {
return uiInfo->friendlyName();
} else {
return QString("MAV_CMD(%1)").arg((int)command);
}
}
QString MissionCommandTree::rawName(MAV_CMD command)
{
MissionCommandList * commandList = _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];
MissionCommandUIInfo* uiInfo = commandList->getUIInfo(command);
if (uiInfo) {
return uiInfo->rawName();
} else {
return QString("MAV_CMD(%1)").arg((int)command);
}
}
const QList<MAV_CMD>& MissionCommandTree::allCommandIds(void) const
{
return _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC]->commandIds();
}
const MissionCommandUIInfo* MissionCommandTree::getUIInfo(Vehicle* vehicle, MAV_CMD command)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
_buildAvailableCommands(vehicle);
const QMap<MAV_CMD, MissionCommandUIInfo*>& infoMap = _availableCommands[baseFirmwareType][baseVehicleType];
if (infoMap.contains(command)) {
return infoMap[command];
} else {
return NULL;
}
}
QVariantList MissionCommandTree::getCommandsForCategory(Vehicle* vehicle, const QString& category)
{
MAV_AUTOPILOT baseFirmwareType;
MAV_TYPE baseVehicleType;
_baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
_buildAvailableCommands(vehicle);
QVariantList list;
QMap<MAV_CMD, MissionCommandUIInfo*> commandMap = _availableCommands[baseFirmwareType][baseVehicleType];
foreach (MAV_CMD command, commandMap.keys()) {
MissionCommandUIInfo* uiInfo = commandMap[command];
if (uiInfo->category() == category) {
list.append(QVariant::fromValue(uiInfo));
}
}
return list;
}
void MissionCommandTree::_baseVehicleInfo(Vehicle* vehicle, MAV_AUTOPILOT& baseFirmwareType, MAV_TYPE& baseVehicleType) const
{
if (vehicle) {
baseFirmwareType = _baseFirmwareType(vehicle->firmwareType());
baseVehicleType = _baseVehicleType(vehicle->vehicleType());
} else {
// No Vehicle means offline editing
baseFirmwareType = _baseFirmwareType((MAV_AUTOPILOT)QGroundControlQmlGlobal::offlineEditingFirmwareType()->rawValue().toInt());
baseVehicleType = _baseVehicleType((MAV_TYPE)QGroundControlQmlGlobal::offlineEditingVehicleType()->rawValue().toInt());
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef APPLICATIONIO_HPP_INCLUDE
#define APPLICATIONIO_HPP_INCLUDE
#include <cstdint>
#include <set>
#include <string>
#include <memory>
#include <vector>
#include <map>
#include <list>
#include "geopm_message.h"
namespace geopm
{
class Comm;
class IApplicationIO
{
public:
IApplicationIO() = default;
virtual ~IApplicationIO() = default;
/// @brief Connect to the application via
/// shared memory.
virtual void connect(void) = 0;
/// @brief Returns true if the application has indicated
/// it is shutting down.
virtual bool do_shutdown(void) const = 0;
/// @brief Returns the path to the report file.
virtual std::string report_name(void) const = 0;
/// @brief Returns the profile name to be used in the
/// report.
virtual std::string profile_name(void) const = 0;
/// @brief Returns the set of region names recorded by the
/// application.
virtual std::set<std::string> region_name_set(void) const = 0;
/// @brief Returns the total runtime for a region.
/// @param [in] region_id The region ID.
virtual double total_region_runtime(uint64_t region_id) const = 0;
/// @brief Returns the total time spent in MPI for a
/// region.
/// @param [in] region_id The region ID.
virtual double total_region_mpi_runtime(uint64_t region_id) const = 0;
/// @brief Returns the total application runtime.
virtual double total_app_runtime(void) const = 0;
/// @brief Returns the total application package energy.
virtual double total_app_energy_pkg(void) const = 0;
/// @brief Returns the total application dram energy.
virtual double total_app_energy_dram(void) const = 0;
/// @brief Returns the total time spent in MPI for the
/// application.
virtual double total_app_mpi_runtime(void) const = 0;
/// @brief Returns the total time spent in ignored regions
/// for the application after the first call to epoch.
virtual double total_epoch_ignore_runtime(void) const = 0;
/// @brief Returns the total runtime after the first epoch
/// call.
virtual double total_epoch_runtime(void) const = 0;
/// @brief Returns the total time spent in MPI after the
/// first epoch call.
virtual double total_epoch_mpi_runtime(void) const = 0;
/// @brief Returns the total package energy since the
/// first epoch call.
virtual double total_epoch_energy_pkg(void) const = 0;
/// @brief Returns the total dram energy since the
/// first epoch call.
virtual double total_epoch_energy_dram(void) const = 0;
/// @brief Returns the total number of times a region was
/// entered and exited.
/// @param [in] region_id The region ID.
virtual int total_count(uint64_t region_id) const = 0;
/// @brief Check for updates from the application and
/// adjust totals accordingly.
/// @param [in] comm Shared pointer to the comm used by
/// the Controller.
virtual void update(std::shared_ptr<Comm> comm) = 0;
/// @brief Returns the list of all regions entered or
/// exited since the last call to
/// clear_region_info().
virtual std::list<geopm_region_info_s> region_info(void) const = 0;
/// @brief Resets the internal list of region entries and
/// exits.
virtual void clear_region_info(void) = 0;
/// @brief Signal to the application that the Controller
/// is ready to begin receiving samples.
virtual void controller_ready(void) = 0;
/// @brief Signal to the application that the Controller
/// has failed critically.
virtual void abort(void) = 0;
};
class IProfileSampler;
class IEpochRuntimeRegulator;
class IKprofileIOSample;
class IPlatformIO;
class IPlatformTopo;
class ApplicationIO : public IApplicationIO
{
public:
ApplicationIO(const std::string &shm_key);
ApplicationIO(const std::string &shm_key,
std::unique_ptr<IProfileSampler> sampler,
std::shared_ptr<IKprofileIOSample> pio_sample,
std::unique_ptr<IEpochRuntimeRegulator>,
IPlatformIO &platform_io,
IPlatformTopo &platform_topo);
virtual ~ApplicationIO();
void connect(void) override;
bool do_shutdown(void) const override;
std::string report_name(void) const override;
std::string profile_name(void) const override;
std::set<std::string> region_name_set(void) const override;
double total_region_runtime(uint64_t region_id) const override;
double total_region_mpi_runtime(uint64_t region_id) const override;
double total_app_runtime(void) const override;
double total_app_energy_pkg(void) const override;
double total_app_energy_dram(void) const override;
double total_app_mpi_runtime(void) const override;
double total_epoch_ignore_runtime(void) const override;
double total_epoch_runtime(void) const override;
double total_epoch_mpi_runtime(void) const override;
double total_epoch_energy_pkg(void) const override;
double total_epoch_energy_dram(void) const override;
int total_count(uint64_t region_id) const override;
void update(std::shared_ptr<Comm> comm) override;
std::list<geopm_region_info_s> region_info(void) const override;
void clear_region_info(void) override;
void controller_ready(void) override;
void abort(void) override;
private:
static constexpr size_t M_SHMEM_REGION_SIZE = 12288;
double current_energy_pkg(void) const;
double current_energy_dram(void) const;
std::unique_ptr<IProfileSampler> m_sampler;
std::shared_ptr<IKprofileIOSample> m_profile_io_sample;
std::vector<std::pair<uint64_t, struct geopm_prof_message_s> > m_prof_sample;
IPlatformIO &m_platform_io;
IPlatformTopo &m_platform_topo;
std::vector<uint64_t> m_region_id;
// Per rank vector counting number of entries into MPI.
std::vector<uint64_t> m_num_mpi_enter;
std::vector<bool> m_is_epoch_changed;
bool m_is_connected;
int m_rank_per_node;
std::unique_ptr<IEpochRuntimeRegulator> m_epoch_regulator;
double m_start_energy_pkg;
double m_start_energy_dram;
};
}
#endif
<commit_msg>Increase shmem table size to 2MB per rank.<commit_after>/*
* Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef APPLICATIONIO_HPP_INCLUDE
#define APPLICATIONIO_HPP_INCLUDE
#include <cstdint>
#include <set>
#include <string>
#include <memory>
#include <vector>
#include <map>
#include <list>
#include "geopm_message.h"
namespace geopm
{
class Comm;
class IApplicationIO
{
public:
IApplicationIO() = default;
virtual ~IApplicationIO() = default;
/// @brief Connect to the application via
/// shared memory.
virtual void connect(void) = 0;
/// @brief Returns true if the application has indicated
/// it is shutting down.
virtual bool do_shutdown(void) const = 0;
/// @brief Returns the path to the report file.
virtual std::string report_name(void) const = 0;
/// @brief Returns the profile name to be used in the
/// report.
virtual std::string profile_name(void) const = 0;
/// @brief Returns the set of region names recorded by the
/// application.
virtual std::set<std::string> region_name_set(void) const = 0;
/// @brief Returns the total runtime for a region.
/// @param [in] region_id The region ID.
virtual double total_region_runtime(uint64_t region_id) const = 0;
/// @brief Returns the total time spent in MPI for a
/// region.
/// @param [in] region_id The region ID.
virtual double total_region_mpi_runtime(uint64_t region_id) const = 0;
/// @brief Returns the total application runtime.
virtual double total_app_runtime(void) const = 0;
/// @brief Returns the total application package energy.
virtual double total_app_energy_pkg(void) const = 0;
/// @brief Returns the total application dram energy.
virtual double total_app_energy_dram(void) const = 0;
/// @brief Returns the total time spent in MPI for the
/// application.
virtual double total_app_mpi_runtime(void) const = 0;
/// @brief Returns the total time spent in ignored regions
/// for the application after the first call to epoch.
virtual double total_epoch_ignore_runtime(void) const = 0;
/// @brief Returns the total runtime after the first epoch
/// call.
virtual double total_epoch_runtime(void) const = 0;
/// @brief Returns the total time spent in MPI after the
/// first epoch call.
virtual double total_epoch_mpi_runtime(void) const = 0;
/// @brief Returns the total package energy since the
/// first epoch call.
virtual double total_epoch_energy_pkg(void) const = 0;
/// @brief Returns the total dram energy since the
/// first epoch call.
virtual double total_epoch_energy_dram(void) const = 0;
/// @brief Returns the total number of times a region was
/// entered and exited.
/// @param [in] region_id The region ID.
virtual int total_count(uint64_t region_id) const = 0;
/// @brief Check for updates from the application and
/// adjust totals accordingly.
/// @param [in] comm Shared pointer to the comm used by
/// the Controller.
virtual void update(std::shared_ptr<Comm> comm) = 0;
/// @brief Returns the list of all regions entered or
/// exited since the last call to
/// clear_region_info().
virtual std::list<geopm_region_info_s> region_info(void) const = 0;
/// @brief Resets the internal list of region entries and
/// exits.
virtual void clear_region_info(void) = 0;
/// @brief Signal to the application that the Controller
/// is ready to begin receiving samples.
virtual void controller_ready(void) = 0;
/// @brief Signal to the application that the Controller
/// has failed critically.
virtual void abort(void) = 0;
};
class IProfileSampler;
class IEpochRuntimeRegulator;
class IKprofileIOSample;
class IPlatformIO;
class IPlatformTopo;
class ApplicationIO : public IApplicationIO
{
public:
ApplicationIO(const std::string &shm_key);
ApplicationIO(const std::string &shm_key,
std::unique_ptr<IProfileSampler> sampler,
std::shared_ptr<IKprofileIOSample> pio_sample,
std::unique_ptr<IEpochRuntimeRegulator>,
IPlatformIO &platform_io,
IPlatformTopo &platform_topo);
virtual ~ApplicationIO();
void connect(void) override;
bool do_shutdown(void) const override;
std::string report_name(void) const override;
std::string profile_name(void) const override;
std::set<std::string> region_name_set(void) const override;
double total_region_runtime(uint64_t region_id) const override;
double total_region_mpi_runtime(uint64_t region_id) const override;
double total_app_runtime(void) const override;
double total_app_energy_pkg(void) const override;
double total_app_energy_dram(void) const override;
double total_app_mpi_runtime(void) const override;
double total_epoch_ignore_runtime(void) const override;
double total_epoch_runtime(void) const override;
double total_epoch_mpi_runtime(void) const override;
double total_epoch_energy_pkg(void) const override;
double total_epoch_energy_dram(void) const override;
int total_count(uint64_t region_id) const override;
void update(std::shared_ptr<Comm> comm) override;
std::list<geopm_region_info_s> region_info(void) const override;
void clear_region_info(void) override;
void controller_ready(void) override;
void abort(void) override;
private:
static constexpr size_t M_SHMEM_REGION_SIZE = 2*1024*1024;
double current_energy_pkg(void) const;
double current_energy_dram(void) const;
std::unique_ptr<IProfileSampler> m_sampler;
std::shared_ptr<IKprofileIOSample> m_profile_io_sample;
std::vector<std::pair<uint64_t, struct geopm_prof_message_s> > m_prof_sample;
IPlatformIO &m_platform_io;
IPlatformTopo &m_platform_topo;
std::vector<uint64_t> m_region_id;
// Per rank vector counting number of entries into MPI.
std::vector<uint64_t> m_num_mpi_enter;
std::vector<bool> m_is_epoch_changed;
bool m_is_connected;
int m_rank_per_node;
std::unique_ptr<IEpochRuntimeRegulator> m_epoch_regulator;
double m_start_energy_pkg;
double m_start_energy_dram;
};
}
#endif
<|endoftext|> |
<commit_before>/*
***************************************
* Asylum Project @ 2013-12-09
***************************************
*/
#ifndef __ASYLUM_HPP__
#define __ASYLUM_HPP__
#include "defs.h"
/* System Filter */
#if !defined(_CR_SYS32_) && \
!defined(_CR_SYS64_)
#error "asylum.hpp: system not supported!"
#endif
#if !defined(_CR_CC_MSC_) && \
!defined(_CR_CC_GCC_)
#error "asylum.hpp: compiler not supported!"
#endif
#if !defined(_CR_OS_UNIX_) && \
!defined(_CR_OS_WIN32_) && \
!defined(_CR_OS_WIN64_)
#error "asylum.hpp: os type not supported!"
#endif
/* Import CrHack Library */
#ifndef ASY_NO_CRHACK
#ifndef _CR_NO_PRAGMA_LIB_
#ifndef ASY_USE_STATIC
#pragma comment (lib, "CrH_CORE.lib")
#else
#pragma comment (lib, "COREs.lib")
#endif
#endif
#else
#include <stdlib.h>
#include <string.h>
/* ======================================= */
cr_inline void_t mem_free (const void_t* ptr)
{
::free((void*)ptr);
}
#if defined(_CR_NO_STDC_)
#define mem_set ::memset
#define mem_cpy ::memcpy
#define mem_cmp ::memcmp
#define mem_mov ::memmove
#endif
#define mem_malloc ::malloc
#define mem_calloc ::calloc
#define mem_malloc32 ::malloc
#define mem_calloc32 ::calloc
#define mem_realloc ::realloc
#ifndef _CR_SYS32_
#define mem_malloc64 ::malloc
#define mem_calloc64 ::calloc
#else
/* ====================================== */
cr_inline void_t* mem_malloc64 (int64u size)
{
if (size > CR_ULL(0xFFFFFFFF))
return (NULL);
return (mem_malloc32((int32u)size));
}
/* ================================================== */
cr_inline void_t* mem_calloc64 (int64u num, size_t size)
{
if (num > CR_ULL(0xFFFFFFFF))
return (NULL);
return (mem_calloc32((int32u)num, size));
}
#endif /* !_CR_SYS32_ */
#endif /* !ASY_NO_CRHACK */
#include "crhack.h"
/* Include */
#if defined(_CR_CC_MSC_)
#include <intrin.h>
typedef dist_t ssize_t;
#endif
#if defined(_CR_OS_MSWIN_)
#include <process.h>
#include <windows.h>
#else
#include <time.h>
#include <errno.h>
#include <sched.h>
#include <pthread.h>
#endif
/* BASIC STUFF */
#include "basic/basic.hpp"
#include "basic/defer.hpp"
#include "basic/safer.hpp"
/* CPU STUFF */
#include "cpu/thread.hpp"
#include "cpu/atomic.hpp"
#include "cpu/crisec.hpp"
#include "cpu/events.hpp"
#include "cpu/exlock.hpp"
#include "cpu/mtlock.hpp"
#include "cpu/nolock.hpp"
#include "cpu/rwlock.hpp"
#include "cpu/splock.hpp"
#include "cpu/doonce.hpp"
#include "cpu/mtpool.hpp"
/* CrHack C++ Wrapper */
#include "crhack/ascall.hpp"
#include "crhack/iports.hpp"
#if defined(ASY_USE_GDI)
#include "gfx2/gdiwin.h"
#include "crhack/gfx2_gdi.hpp"
#endif
#if defined(ASY_USE_DX8)
#include "gfx2/dx8win.h"
#include "crhack/gfx2_dx8.hpp"
#endif
#if defined(ASY_USE_DX9)
#include "gfx2/dx9win.h"
#include "crhack/gfx2_dx9.hpp"
#endif
/* Yet Another Wheel */
#include "yaw/array.hpp"
#include "yaw/bring.hpp"
#include "yaw/list2.hpp"
#include "yaw/map2d.hpp"
#include "yaw/map_a.hpp"
#include "yaw/map_l.hpp"
#include "yaw/oring.hpp"
#include "yaw/table.hpp"
#include "yaw/tree_a.hpp"
#include "yaw/tree_l.hpp"
#include "yaw/map_acs.hpp"
/* Misaka Network */
/* Asylum3D */
#include "draw3d/asylum3d.hpp"
#if defined(ASY_USE_DX9)
#include "draw3d/crh3d9/crh3d9_main.hpp"
#include "draw3d/crh3d9/crh3d9_shader.hpp"
#include "draw3d/crh3d9/crh3d9_texture.hpp"
#include "draw3d/crh3d9/crh3d9_graph.hpp"
#ifndef ASY_USE_STATIC
#pragma comment (lib, "CrH_GFX3.lib")
#else
#pragma comment (lib, "GFX3s.lib")
#endif
#endif
#endif /* __ASYLUM_HPP__ */
<commit_msg>Asylum: 修正编译错误<commit_after>/*
***************************************
* Asylum Project @ 2013-12-09
***************************************
*/
#ifndef __ASYLUM_HPP__
#define __ASYLUM_HPP__
#include "defs.h"
/* System Filter */
#if !defined(_CR_SYS32_) && \
!defined(_CR_SYS64_)
#error "asylum.hpp: system not supported!"
#endif
#if !defined(_CR_CC_MSC_) && \
!defined(_CR_CC_GCC_)
#error "asylum.hpp: compiler not supported!"
#endif
#if !defined(_CR_OS_UNIX_) && \
!defined(_CR_OS_WIN32_) && \
!defined(_CR_OS_WIN64_)
#error "asylum.hpp: os type not supported!"
#endif
/* Import CrHack Library */
#ifndef ASY_NO_CRHACK
#ifndef _CR_NO_PRAGMA_LIB_
#ifndef ASY_USE_STATIC
#pragma comment (lib, "CrH_CORE.lib")
#else
#pragma comment (lib, "COREs.lib")
#endif
#endif
#else
#include <stdlib.h>
#include <string.h>
/* ======================================= */
cr_inline void_t mem_free (const void_t* ptr)
{
::free((void*)ptr);
}
#if defined(_CR_NO_STDC_)
#define mem_set ::memset
#define mem_cpy ::memcpy
#define mem_cmp ::memcmp
#define mem_mov ::memmove
#endif
#define mem_malloc ::malloc
#define mem_calloc ::calloc
#define mem_malloc32 ::malloc
#define mem_calloc32 ::calloc
#define mem_realloc ::realloc
#ifndef _CR_SYS32_
#define mem_malloc64 ::malloc
#define mem_calloc64 ::calloc
#else
/* ====================================== */
cr_inline void_t* mem_malloc64 (int64u size)
{
if (size > CR_ULL(0xFFFFFFFF))
return (NULL);
return (mem_malloc32((int32u)size));
}
/* ================================================== */
cr_inline void_t* mem_calloc64 (int64u num, size_t size)
{
if (num > CR_ULL(0xFFFFFFFF))
return (NULL);
return (mem_calloc32((int32u)num, size));
}
#endif /* !_CR_SYS32_ */
#endif /* !ASY_NO_CRHACK */
#include "crhack.h"
/* Include */
#if defined(_CR_CC_MSC_)
#include <intrin.h>
typedef dist_t ssize_t;
#endif
#if defined(_CR_OS_MSWIN_)
#include <process.h>
#include <windows.h>
#else
#include <time.h>
#include <errno.h>
#include <sched.h>
#include <pthread.h>
#endif
/* BASIC STUFF */
#include "basic/basic.hpp"
#include "basic/defer.hpp"
#include "basic/safer.hpp"
/* CPU STUFF */
#include "cpu/thread.hpp"
#include "cpu/atomic.hpp"
#include "cpu/crisec.hpp"
#include "cpu/events.hpp"
#include "cpu/exlock.hpp"
#include "cpu/mtlock.hpp"
#include "cpu/nolock.hpp"
#include "cpu/rwlock.hpp"
#include "cpu/splock.hpp"
#include "cpu/doonce.hpp"
#include "cpu/mtpool.hpp"
/* CrHack C++ Wrapper */
#include "crhack/ascall.hpp"
#include "crhack/iports.hpp"
#if defined(ASY_USE_GDI)
#include "gfx2/gdiwin.h"
#include "crhack/gfx2_gdi.hpp"
#endif
#if defined(ASY_USE_DX8)
#include "gfx2/dx8win.h"
#include "crhack/gfx2_dx8.hpp"
#endif
#if defined(ASY_USE_DX9)
#include "gfx2/dx9win.h"
#include "crhack/gfx2_dx9.hpp"
#endif
/* Yet Another Wheel */
#include "yaw/array.hpp"
#include "yaw/bring.hpp"
#include "yaw/list2.hpp"
#include "yaw/map2d.hpp"
#include "yaw/map_a.hpp"
#include "yaw/map_l.hpp"
#include "yaw/oring.hpp"
#include "yaw/table.hpp"
#include "yaw/tree_a.hpp"
#include "yaw/tree_l.hpp"
#include "yaw/map_acs.hpp"
/* Misaka Network */
/* Asylum3D */
#include "draw3d/asylum3d.hpp"
#if defined(ASY_USE_DX9)
#include "draw3d/crh3d9/crh3d9_main.hpp"
#include "draw3d/crh3d9/crh3d9_shader.hpp"
#include "draw3d/crh3d9/crh3d9_texture.hpp"
#include "draw3d/crh3d9/crh3d9_graph.hpp"
#ifndef _CR_NO_PRAGMA_LIB_
#ifndef ASY_USE_STATIC
#pragma comment (lib, "CrH_GFX3.lib")
#else
#pragma comment (lib, "GFX3s.lib")
#endif
#endif
#endif
#endif /* __ASYLUM_HPP__ */
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9a/procedures/hwp/memory/p9a_mss_freq.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
<commit_msg>Add L1 procedures for p9a and makefiles<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9a/procedures/hwp/memory/p9a_mss_freq.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2018,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9a_mss_freq.C
/// @brief Calculate and save off DIMM frequencies
///
// *HWP HWP Owner: Andre Marin <[email protected]>
// *HWP HWP Backup: Louis Stermole <[email protected]>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB
// fapi2
#include <p9a_mss_freq.H>
///
/// @brief Calculate and save off DIMM frequencies
/// @param[in] i_target port target
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9a_mss_freq( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target )
{
return fapi2::FAPI2_RC_SUCCESS;
}
<|endoftext|> |
<commit_before>/**
* CinematicView.cpp
*/
#include "stdafx.h"
#include "CinematicView.h"
#include "CallCinematicCamera.h"
#include "CameraParamsOverride.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/view/CallRender3D.h"
using namespace megamol;
using namespace megamol::core;
using namespace cinematiccamera;
CinematicView::CinematicView(void) : View3D(),
keyframeKeeperSlot("keyframeKeeper", "Connects to the Keyframe Keeper."),
selectedKeyframeParam("cinematicCam::selectedKeyframeParam", "render selected Keyframe if true. render keyframe at animationtime if false"),
selectedSkyboxSideParam("cinematicCam::skyboxSide", "Skybox side rendering"),
autoLoadKeyframes("keyframeAutoLoad","shall the keyframes be loaded automatically from the file provided in the keyframe-keeper?"),
autoSetTotalTime("totalTimeAutoSet", "shall the total animation time be determined automatically?"),
paramEdit("edit", "Do not overwrite the camera such that the selected key frame can be edited."),
firstframe(true) {
this->keyframeKeeperSlot.SetCompatibleCall<CallCinematicCameraDescription>();
this->MakeSlotAvailable(&this->keyframeKeeperSlot);
this->selectedKeyframeParam << new core::param::BoolParam(true);
this->MakeSlotAvailable(&this->selectedKeyframeParam);
this->autoLoadKeyframes.SetParameter(new core::param::BoolParam(false));
this->MakeSlotAvailable(&this->autoLoadKeyframes);
this->autoSetTotalTime.SetParameter(new core::param::BoolParam(true));
this->MakeSlotAvailable(&this->autoSetTotalTime);
param::EnumParam *sbs = new param::EnumParam(SKYBOX_NONE);
sbs->SetTypePair(SKYBOX_NONE, "None");
sbs->SetTypePair(SKYBOX_FRONT, "Front");
sbs->SetTypePair(SKYBOX_BACK, "Back");
sbs->SetTypePair(SKYBOX_LEFT, "Left");
sbs->SetTypePair(SKYBOX_RIGHT, "Right");
sbs->SetTypePair(SKYBOX_UP, "Up");
sbs->SetTypePair(SKYBOX_DOWN, "Down");
this->selectedSkyboxSideParam << sbs;
this->MakeSlotAvailable(&this->selectedSkyboxSideParam);
this->paramEdit << new core::param::BoolParam(false);
this->MakeSlotAvailable(&this->paramEdit);
}
megamol::cinematiccamera::CinematicView::~CinematicView() {}
void megamol::cinematiccamera::CinematicView::Render(const mmcRenderViewContext& context) {
auto cr3d = this->rendererSlot.CallAs<core::view::CallRender3D>();
(*cr3d)(1); // get extents
auto kfc = this->keyframeKeeperSlot.CallAs<CallCinematicCamera>();
if (!kfc) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "KeyframeKeeper slot not connected!");
}
if (firstframe) {
if (autoLoadKeyframes.Param<param::BoolParam>()->Value()) {
(*kfc)(CallCinematicCamera::CallForLoadKeyframe);
}
if (autoSetTotalTime.Param<param::BoolParam>()->Value()) {
kfc->setTotalTime(static_cast<float>(cr3d->TimeFramesCount()));
(*kfc)(CallCinematicCamera::CallForSetTotalTime);
}
firstframe = false;
}
bool isSelectedKeyFrame = this->selectedKeyframeParam.Param<core::param::BoolParam>()->Value();
if (isSelectedKeyFrame) {
// Preview the currently selected key frame.
if ((*kfc)(CallCinematicCamera::CallForGetSelectedKeyframe)) {
auto id = kfc->getSelectedKeyframe().getID();
bool isEdit = this->paramEdit.Param<core::param::BoolParam>()->Value();
switch (id) {
case -2:
// There is no key frame yet.
break;
case -1:
// An interpolated position was selected.
kfc->getInterpolatedKeyframe().putCamParameters(this->cam.Parameters());
break;
default:
// A key frame was selected.
if (!isEdit) {
kfc->getSelectedKeyframe().putCamParameters(this->cam.Parameters());
}
break;
}
Base::Render(context);
if (this->paramEdit.IsDirty()) {
if (!isEdit && isSelectedKeyFrame && (id >= 0)) {
vislib::sys::Log::DefaultLog.WriteInfo("Updating key frame %d ...", id);
kfc->setCameraForNewKeyframe(cr3d->GetCameraParameters());
if ((*kfc)(CallCinematicCamera::CallForKeyFrameUpdate)) {
vislib::sys::Log::DefaultLog.WriteInfo("Key frame %d was updated.", id);
}
}
this->paramEdit.ResetDirty();
}
} else {
vislib::sys::Log::DefaultLog.WriteError("CallForGetSelectedKeyframe failed!");
}
} else {
// Select the key frame based on the current animation time.
kfc->setTimeofKeyframeToGet(static_cast<float>(context.Time));
if ((*kfc)(CallCinematicCamera::CallForGetKeyframeAtTime)){
kfc->getInterpolatedKeyframe().putCamParameters(this->cam.Parameters());
}
vislib::SmartPtr<vislib::graphics::CameraParameters> cp = this->cam.Parameters();
vislib::math::Point<float, 3> camPos = cp->Position();
vislib::math::Vector<float, 3> camRight = cp->Right();
vislib::math::Vector<float, 3> camUp = cp->Up();
vislib::math::Vector<float, 3> camFront = cp->Front();
float tmpDist = cp->FocalDistance();
// adjust cam to selected skybox side
SkyboxSides side = static_cast<SkyboxSides>(this->selectedSkyboxSideParam.Param<param::EnumParam>()->Value());
if (side != SKYBOX_NONE) {
// set aperture angle to 90 deg
cp->SetApertureAngle(90.0f);
if (side == SKYBOX_BACK) {
cp->SetView(camPos, camPos - camFront * tmpDist, camUp);
}
else if (side == SKYBOX_RIGHT) {
cp->SetView(camPos, camPos + camRight * tmpDist, camUp);
}
else if (side == SKYBOX_LEFT) {
cp->SetView(camPos, camPos - camRight * tmpDist, camUp);
}
else if (side == SKYBOX_UP) {
cp->SetView(camPos, camPos + camUp * tmpDist, -camFront);
}
else if (side == SKYBOX_DOWN) {
cp->SetView(camPos, camPos - camUp * tmpDist, camFront);
}
}
Base::Render(context);
// reset cam (in case some skybox side was rendered)
//if (side != SKYBOX_NONE) {
// cp->SetView(camPos, camPos + camFront * tmpDist, camUp);
//}
}
}<commit_msg>Fixor.<commit_after>/**
* CinematicView.cpp
*/
#include "stdafx.h"
#include "CinematicView.h"
#include "CallCinematicCamera.h"
#include "CameraParamsOverride.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/view/CallRender3D.h"
using namespace megamol;
using namespace megamol::core;
using namespace cinematiccamera;
CinematicView::CinematicView(void) : View3D(),
keyframeKeeperSlot("keyframeKeeper", "Connects to the Keyframe Keeper."),
selectedKeyframeParam("cinematicCam::selectedKeyframeParam", "render selected Keyframe if true. render keyframe at animationtime if false"),
selectedSkyboxSideParam("cinematicCam::skyboxSide", "Skybox side rendering"),
autoLoadKeyframes("keyframeAutoLoad","shall the keyframes be loaded automatically from the file provided in the keyframe-keeper?"),
autoSetTotalTime("totalTimeAutoSet", "shall the total animation time be determined automatically?"),
paramEdit("cinematicCam::edit", "Do not overwrite the camera such that the selected key frame can be edited."),
firstframe(true) {
this->keyframeKeeperSlot.SetCompatibleCall<CallCinematicCameraDescription>();
this->MakeSlotAvailable(&this->keyframeKeeperSlot);
this->selectedKeyframeParam << new core::param::BoolParam(true);
this->MakeSlotAvailable(&this->selectedKeyframeParam);
this->autoLoadKeyframes.SetParameter(new core::param::BoolParam(false));
this->MakeSlotAvailable(&this->autoLoadKeyframes);
this->autoSetTotalTime.SetParameter(new core::param::BoolParam(true));
this->MakeSlotAvailable(&this->autoSetTotalTime);
param::EnumParam *sbs = new param::EnumParam(SKYBOX_NONE);
sbs->SetTypePair(SKYBOX_NONE, "None");
sbs->SetTypePair(SKYBOX_FRONT, "Front");
sbs->SetTypePair(SKYBOX_BACK, "Back");
sbs->SetTypePair(SKYBOX_LEFT, "Left");
sbs->SetTypePair(SKYBOX_RIGHT, "Right");
sbs->SetTypePair(SKYBOX_UP, "Up");
sbs->SetTypePair(SKYBOX_DOWN, "Down");
this->selectedSkyboxSideParam << sbs;
this->MakeSlotAvailable(&this->selectedSkyboxSideParam);
this->paramEdit << new core::param::BoolParam(false);
this->MakeSlotAvailable(&this->paramEdit);
}
megamol::cinematiccamera::CinematicView::~CinematicView() {}
void megamol::cinematiccamera::CinematicView::Render(const mmcRenderViewContext& context) {
auto cr3d = this->rendererSlot.CallAs<core::view::CallRender3D>();
(*cr3d)(1); // get extents
auto kfc = this->keyframeKeeperSlot.CallAs<CallCinematicCamera>();
if (!kfc) {
vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "KeyframeKeeper slot not connected!");
}
if (firstframe) {
if (autoLoadKeyframes.Param<param::BoolParam>()->Value()) {
(*kfc)(CallCinematicCamera::CallForLoadKeyframe);
}
if (autoSetTotalTime.Param<param::BoolParam>()->Value()) {
kfc->setTotalTime(static_cast<float>(cr3d->TimeFramesCount()));
(*kfc)(CallCinematicCamera::CallForSetTotalTime);
}
firstframe = false;
}
bool isSelectedKeyFrame = this->selectedKeyframeParam.Param<core::param::BoolParam>()->Value();
if (isSelectedKeyFrame) {
// Preview the currently selected key frame.
if ((*kfc)(CallCinematicCamera::CallForGetSelectedKeyframe)) {
auto id = kfc->getSelectedKeyframe().getID();
bool isEdit = this->paramEdit.Param<core::param::BoolParam>()->Value();
switch (id) {
case -2:
// There is no key frame yet.
break;
case -1:
// An interpolated position was selected.
kfc->getInterpolatedKeyframe().putCamParameters(this->cam.Parameters());
break;
default:
// A key frame was selected.
if (!isEdit) {
kfc->getSelectedKeyframe().putCamParameters(this->cam.Parameters());
}
break;
}
Base::Render(context);
if (this->paramEdit.IsDirty()) {
if (!isEdit && isSelectedKeyFrame && (id >= 0)) {
vislib::sys::Log::DefaultLog.WriteInfo("Updating key frame %d ...", id);
kfc->setCameraForNewKeyframe(this->cam.Parameters());
if ((*kfc)(CallCinematicCamera::CallForKeyFrameUpdate)) {
vislib::sys::Log::DefaultLog.WriteInfo("Key frame %d was updated.", id);
}
}
this->paramEdit.ResetDirty();
}
} else {
vislib::sys::Log::DefaultLog.WriteError("CallForGetSelectedKeyframe failed!");
}
} else {
// Select the key frame based on the current animation time.
kfc->setTimeofKeyframeToGet(static_cast<float>(context.Time));
if ((*kfc)(CallCinematicCamera::CallForGetKeyframeAtTime)){
kfc->getInterpolatedKeyframe().putCamParameters(this->cam.Parameters());
}
vislib::SmartPtr<vislib::graphics::CameraParameters> cp = this->cam.Parameters();
vislib::math::Point<float, 3> camPos = cp->Position();
vislib::math::Vector<float, 3> camRight = cp->Right();
vislib::math::Vector<float, 3> camUp = cp->Up();
vislib::math::Vector<float, 3> camFront = cp->Front();
float tmpDist = cp->FocalDistance();
// adjust cam to selected skybox side
SkyboxSides side = static_cast<SkyboxSides>(this->selectedSkyboxSideParam.Param<param::EnumParam>()->Value());
if (side != SKYBOX_NONE) {
// set aperture angle to 90 deg
cp->SetApertureAngle(90.0f);
if (side == SKYBOX_BACK) {
cp->SetView(camPos, camPos - camFront * tmpDist, camUp);
}
else if (side == SKYBOX_RIGHT) {
cp->SetView(camPos, camPos + camRight * tmpDist, camUp);
}
else if (side == SKYBOX_LEFT) {
cp->SetView(camPos, camPos - camRight * tmpDist, camUp);
}
else if (side == SKYBOX_UP) {
cp->SetView(camPos, camPos + camUp * tmpDist, -camFront);
}
else if (side == SKYBOX_DOWN) {
cp->SetView(camPos, camPos - camUp * tmpDist, camFront);
}
}
Base::Render(context);
// reset cam (in case some skybox side was rendered)
//if (side != SKYBOX_NONE) {
// cp->SetView(camPos, camPos + camFront * tmpDist, camUp);
//}
}
}<|endoftext|> |
<commit_before>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_CdeclCallConv_msc64.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//..............................................................................
void
CdeclCallConv_msc64::prepareFunctionType (FunctionType* functionType)
{
Type* returnType = functionType->getReturnType ();
sl::Array <FunctionArg*> argArray = functionType->getArgArray ();
size_t argCount = argArray.getCount ();
char buffer [256];
sl::Array <llvm::Type*> llvmArgTypeArray (ref::BufKind_Stack, buffer, sizeof (buffer));
llvmArgTypeArray.setCount (argCount);
size_t j = 0;
if (returnType->getFlags () & TypeFlag_StructRet)
{
if (returnType->getSize () <= sizeof (uint64_t))
{
returnType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
}
else
{
returnType = returnType->getDataPtrType_c ();
argCount++;
llvmArgTypeArray.setCount (argCount);
llvmArgTypeArray [0] = returnType->getLlvmType ();
j = 1;
}
}
bool hasCoercedArgs = false;
for (size_t i = 0; j < argCount; i++, j++)
{
Type* type = argArray [i]->getType ();
if (!(type->getFlags () & TypeFlag_StructRet))
{
llvmArgTypeArray [j] = type->getLlvmType ();
}
else if (type->getSize () <= sizeof (uint64_t))
{
llvmArgTypeArray [j] = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getLlvmType ();
hasCoercedArgs = true;
}
else
{
llvmArgTypeArray [j] = type->getDataPtrType_c ()->getLlvmType ();
hasCoercedArgs = true;
}
}
if (hasCoercedArgs)
functionType->m_flags |= FunctionTypeFlag_CoercedArgs;
functionType->m_llvmType = llvm::FunctionType::get (
returnType->getLlvmType (),
llvm::ArrayRef <llvm::Type*> (llvmArgTypeArray, argCount),
(functionType->getFlags () & FunctionTypeFlag_VarArg) != 0
);
}
void
CdeclCallConv_msc64::call (
const Value& calleeValue,
FunctionType* functionType,
sl::BoxList <Value>* argValueList,
Value* resultValue
)
{
Type* returnType = functionType->getReturnType ();
if (!(functionType->getFlags () & FunctionTypeFlag_CoercedArgs) &&
!(returnType->getFlags () & TypeFlag_StructRet))
{
CallConv::call (calleeValue, functionType, argValueList, resultValue);
return;
}
Value tmpReturnValue;
if (returnType->getFlags () & TypeFlag_StructRet)
{
m_module->m_llvmIrBuilder.createAlloca (
returnType,
"tmpRetVal",
returnType->getDataPtrType_c (),
&tmpReturnValue
);
if (returnType->getSize () > sizeof (uint64_t))
argValueList->insertHead (tmpReturnValue);
}
if (functionType->getFlags () & FunctionTypeFlag_CoercedArgs)
{
sl::BoxIterator <Value> it = argValueList->getHead ();
for (; it; it++)
{
Type* type = it->getType ();
if (!(type->getFlags () & TypeFlag_StructRet))
continue;
if (type->getSize () > sizeof (uint64_t))
{
Value tmpValue;
m_module->m_llvmIrBuilder.createAlloca (type, "tmpArg", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore (*it, tmpValue);
*it = tmpValue;
}
else
{
Type* coerceType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
Value tmpValue, tmpValue2;
m_module->m_llvmIrBuilder.createAlloca (coerceType, "tmpArg", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createBitCast (tmpValue, type->getDataPtrType_c (), &tmpValue2);
m_module->m_llvmIrBuilder.createStore (*it, tmpValue2);
m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
*it = tmpValue;
}
}
}
m_module->m_llvmIrBuilder.createCall (
calleeValue,
functionType,
*argValueList,
resultValue
);
if (returnType->getFlags () & TypeFlag_StructRet)
{
if (returnType->getSize () <= sizeof (uint64_t))
{
Value tmpValue;
Type* type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getDataPtrType_c ();
m_module->m_llvmIrBuilder.createBitCast (tmpReturnValue, type, &tmpValue);
m_module->m_llvmIrBuilder.createStore (*resultValue, tmpValue);
}
m_module->m_llvmIrBuilder.createLoad (tmpReturnValue, returnType, resultValue);
}
}
void
CdeclCallConv_msc64::ret (
Function* function,
const Value& value
)
{
Type* returnType = function->getType ()->getReturnType ();
if (!(returnType->getFlags () & TypeFlag_StructRet))
{
CallConv::ret (function, value);
return;
}
if (returnType->getSize () > sizeof (uint64_t))
{
Value returnPtrValue (&*function->getLlvmFunction ()->arg_begin());
m_module->m_llvmIrBuilder.createStore (value, returnPtrValue);
m_module->m_llvmIrBuilder.createRet (returnPtrValue);
}
else
{
Type* type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getDataPtrType_c ();
Value tmpValue, tmpValue2;
m_module->m_llvmIrBuilder.createAlloca (type, "tmpRetVal", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createBitCast (tmpValue, returnType->getDataPtrType_c (), &tmpValue2);
m_module->m_llvmIrBuilder.createStore (value, tmpValue2);
m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
m_module->m_llvmIrBuilder.createRet (tmpValue);
}
}
Value
CdeclCallConv_msc64::getThisArgValue (Function* function)
{
ASSERT (function->isMember ());
FunctionType* functionType = function->getType ();
Type* returnType = functionType->getReturnType ();
llvm::Function::arg_iterator llvmArg = function->getLlvmFunction ()->arg_begin ();
if ((returnType->getFlags () & TypeFlag_StructRet) &&
returnType->getSize () > sizeof (uint64_t))
llvmArg++;
return getArgValue (&*llvmArg, functionType, 0);
}
Value
CdeclCallConv_msc64::getArgValue (
llvm::Value* llvmValue,
FunctionType* functionType,
size_t argIdx
)
{
Type* type = functionType->m_argArray [argIdx]->getType ();
if (!(type->getFlags () & TypeFlag_StructRet))
return Value (llvmValue, type);
if (type->getSize () > sizeof (uint64_t))
{
Value value;
m_module->m_llvmIrBuilder.createLoad (llvmValue, type, &value);
return value;
}
Type* int64Type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
Value value;
m_module->m_llvmIrBuilder.createAlloca (int64Type, "tmpArg", NULL, &value);
m_module->m_llvmIrBuilder.createStore (llvmValue, value);
m_module->m_llvmIrBuilder.createBitCast (value, type->getDataPtrType_c (), &value);
m_module->m_llvmIrBuilder.createLoad (value, type, &value);
return value;
}
void
CdeclCallConv_msc64::createArgVariables (Function* function)
{
Type* returnType = function->getType ()->getReturnType ();
llvm::Function::arg_iterator llvmArg = function->getLlvmFunction ()->arg_begin ();
if ((returnType->getFlags () & TypeFlag_StructRet) &&
returnType->getSize () > sizeof (uint64_t))
llvmArg++;
size_t i = 0;
if (function->isMember ()) // skip this
{
i++;
llvmArg++;
}
sl::Array <FunctionArg*> argArray = function->getType ()->getArgArray ();
size_t argCount = argArray.getCount ();
for (; i < argCount; i++, llvmArg++)
{
FunctionArg* arg = argArray [i];
if (!arg->isNamed ())
continue;
Type* type = arg->getType ();
llvm::Value* llvmArgValue = &*llvmArg;
if (!(type->getFlags () & TypeFlag_StructRet))
{
Variable* argVariable = m_module->m_variableMgr.createArgVariable (arg, i);
function->getScope ()->addItem (argVariable);
m_module->m_llvmIrBuilder.createStore (llvmArgValue, argVariable);
}
else
{
Variable* argVariable = m_module->m_variableMgr.createArgVariable (arg, i);
function->getScope ()->addItem (argVariable);
if (type->getSize () > sizeof (uint64_t))
{
Value tmpValue;
m_module->m_llvmIrBuilder.createLoad (llvmArgValue, NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore (tmpValue, argVariable);
}
else
{
Type* int64Type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
Value tmpValue;
m_module->m_llvmIrBuilder.createAlloca (int64Type, "tmpArg", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore (llvmArgValue, tmpValue);
m_module->m_llvmIrBuilder.createBitCast (tmpValue, type->getDataPtrType_c (), &tmpValue);
m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore (tmpValue, argVariable);
}
}
}
}
//..............................................................................
} // namespace ct
} // namespace jnc
<commit_msg>[jnc_ct] typo fix in CdeclCallConv_msc64::ret (int64* was used instead of int64)<commit_after>//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_CdeclCallConv_msc64.h"
#include "jnc_ct_Module.h"
namespace jnc {
namespace ct {
//..............................................................................
void
CdeclCallConv_msc64::prepareFunctionType (FunctionType* functionType)
{
Type* returnType = functionType->getReturnType ();
sl::Array <FunctionArg*> argArray = functionType->getArgArray ();
size_t argCount = argArray.getCount ();
char buffer [256];
sl::Array <llvm::Type*> llvmArgTypeArray (ref::BufKind_Stack, buffer, sizeof (buffer));
llvmArgTypeArray.setCount (argCount);
size_t j = 0;
if (returnType->getFlags () & TypeFlag_StructRet)
{
if (returnType->getSize () <= sizeof (uint64_t))
{
returnType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
}
else
{
returnType = returnType->getDataPtrType_c ();
argCount++;
llvmArgTypeArray.setCount (argCount);
llvmArgTypeArray [0] = returnType->getLlvmType ();
j = 1;
}
}
bool hasCoercedArgs = false;
for (size_t i = 0; j < argCount; i++, j++)
{
Type* type = argArray [i]->getType ();
if (!(type->getFlags () & TypeFlag_StructRet))
{
llvmArgTypeArray [j] = type->getLlvmType ();
}
else if (type->getSize () <= sizeof (uint64_t))
{
llvmArgTypeArray [j] = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getLlvmType ();
hasCoercedArgs = true;
}
else
{
llvmArgTypeArray [j] = type->getDataPtrType_c ()->getLlvmType ();
hasCoercedArgs = true;
}
}
if (hasCoercedArgs)
functionType->m_flags |= FunctionTypeFlag_CoercedArgs;
functionType->m_llvmType = llvm::FunctionType::get (
returnType->getLlvmType (),
llvm::ArrayRef <llvm::Type*> (llvmArgTypeArray, argCount),
(functionType->getFlags () & FunctionTypeFlag_VarArg) != 0
);
}
void
CdeclCallConv_msc64::call (
const Value& calleeValue,
FunctionType* functionType,
sl::BoxList <Value>* argValueList,
Value* resultValue
)
{
Type* returnType = functionType->getReturnType ();
if (!(functionType->getFlags () & FunctionTypeFlag_CoercedArgs) &&
!(returnType->getFlags () & TypeFlag_StructRet))
{
CallConv::call (calleeValue, functionType, argValueList, resultValue);
return;
}
Value tmpReturnValue;
if (returnType->getFlags () & TypeFlag_StructRet)
{
m_module->m_llvmIrBuilder.createAlloca (
returnType,
"tmpRetVal",
returnType->getDataPtrType_c (),
&tmpReturnValue
);
if (returnType->getSize () > sizeof (uint64_t))
argValueList->insertHead (tmpReturnValue);
}
if (functionType->getFlags () & FunctionTypeFlag_CoercedArgs)
{
sl::BoxIterator <Value> it = argValueList->getHead ();
for (; it; it++)
{
Type* type = it->getType ();
if (!(type->getFlags () & TypeFlag_StructRet))
continue;
if (type->getSize () > sizeof (uint64_t))
{
Value tmpValue;
m_module->m_llvmIrBuilder.createAlloca (type, "tmpArg", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore (*it, tmpValue);
*it = tmpValue;
}
else
{
Type* coerceType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
Value tmpValue, tmpValue2;
m_module->m_llvmIrBuilder.createAlloca (coerceType, "tmpArg", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createBitCast (tmpValue, type->getDataPtrType_c (), &tmpValue2);
m_module->m_llvmIrBuilder.createStore (*it, tmpValue2);
m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
*it = tmpValue;
}
}
}
m_module->m_llvmIrBuilder.createCall (
calleeValue,
functionType,
*argValueList,
resultValue
);
if (returnType->getFlags () & TypeFlag_StructRet)
{
if (returnType->getSize () <= sizeof (uint64_t))
{
Value tmpValue;
Type* type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getDataPtrType_c ();
m_module->m_llvmIrBuilder.createBitCast (tmpReturnValue, type, &tmpValue);
m_module->m_llvmIrBuilder.createStore (*resultValue, tmpValue);
}
m_module->m_llvmIrBuilder.createLoad (tmpReturnValue, returnType, resultValue);
}
}
void
CdeclCallConv_msc64::ret (
Function* function,
const Value& value
)
{
Type* returnType = function->getType ()->getReturnType ();
if (!(returnType->getFlags () & TypeFlag_StructRet))
{
CallConv::ret (function, value);
return;
}
if (returnType->getSize () > sizeof (uint64_t))
{
Value returnPtrValue (&*function->getLlvmFunction ()->arg_begin());
m_module->m_llvmIrBuilder.createStore (value, returnPtrValue);
m_module->m_llvmIrBuilder.createRet (returnPtrValue);
}
else
{
Type* type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
Value tmpValue, tmpValue2;
m_module->m_llvmIrBuilder.createAlloca (type, "tmpRetVal", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createBitCast (tmpValue, returnType->getDataPtrType_c (), &tmpValue2);
m_module->m_llvmIrBuilder.createStore (value, tmpValue2);
m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
m_module->m_llvmIrBuilder.createRet (tmpValue);
}
}
Value
CdeclCallConv_msc64::getThisArgValue (Function* function)
{
ASSERT (function->isMember ());
FunctionType* functionType = function->getType ();
Type* returnType = functionType->getReturnType ();
llvm::Function::arg_iterator llvmArg = function->getLlvmFunction ()->arg_begin ();
if ((returnType->getFlags () & TypeFlag_StructRet) &&
returnType->getSize () > sizeof (uint64_t))
llvmArg++;
return getArgValue (&*llvmArg, functionType, 0);
}
Value
CdeclCallConv_msc64::getArgValue (
llvm::Value* llvmValue,
FunctionType* functionType,
size_t argIdx
)
{
Type* type = functionType->m_argArray [argIdx]->getType ();
if (!(type->getFlags () & TypeFlag_StructRet))
return Value (llvmValue, type);
if (type->getSize () > sizeof (uint64_t))
{
Value value;
m_module->m_llvmIrBuilder.createLoad (llvmValue, type, &value);
return value;
}
Type* int64Type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
Value value;
m_module->m_llvmIrBuilder.createAlloca (int64Type, "tmpArg", NULL, &value);
m_module->m_llvmIrBuilder.createStore (llvmValue, value);
m_module->m_llvmIrBuilder.createBitCast (value, type->getDataPtrType_c (), &value);
m_module->m_llvmIrBuilder.createLoad (value, type, &value);
return value;
}
void
CdeclCallConv_msc64::createArgVariables (Function* function)
{
Type* returnType = function->getType ()->getReturnType ();
llvm::Function::arg_iterator llvmArg = function->getLlvmFunction ()->arg_begin ();
if ((returnType->getFlags () & TypeFlag_StructRet) &&
returnType->getSize () > sizeof (uint64_t))
llvmArg++;
size_t i = 0;
if (function->isMember ()) // skip this
{
i++;
llvmArg++;
}
sl::Array <FunctionArg*> argArray = function->getType ()->getArgArray ();
size_t argCount = argArray.getCount ();
for (; i < argCount; i++, llvmArg++)
{
FunctionArg* arg = argArray [i];
if (!arg->isNamed ())
continue;
Type* type = arg->getType ();
llvm::Value* llvmArgValue = &*llvmArg;
if (!(type->getFlags () & TypeFlag_StructRet))
{
Variable* argVariable = m_module->m_variableMgr.createArgVariable (arg, i);
function->getScope ()->addItem (argVariable);
m_module->m_llvmIrBuilder.createStore (llvmArgValue, argVariable);
}
else
{
Variable* argVariable = m_module->m_variableMgr.createArgVariable (arg, i);
function->getScope ()->addItem (argVariable);
if (type->getSize () > sizeof (uint64_t))
{
Value tmpValue;
m_module->m_llvmIrBuilder.createLoad (llvmArgValue, NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore (tmpValue, argVariable);
}
else
{
Type* int64Type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
Value tmpValue;
m_module->m_llvmIrBuilder.createAlloca (int64Type, "tmpArg", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore (llvmArgValue, tmpValue);
m_module->m_llvmIrBuilder.createBitCast (tmpValue, type->getDataPtrType_c (), &tmpValue);
m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore (tmpValue, argVariable);
}
}
}
}
//..............................................................................
} // namespace ct
} // namespace jnc
<|endoftext|> |
<commit_before>#include "boundingrecthighlighter.h"
#include "qdeclarativedesignview.h"
#include "qmlviewerconstants.h"
#include <QGraphicsPolygonItem>
#include <QTimer>
#include <QObject>
#include <QDebug>
namespace QmlViewer {
const qreal AnimDelta = 0.025f;
const int AnimInterval = 30;
const int AnimFrames = 10;
BoundingBox::BoundingBox(QGraphicsObject *itemToHighlight, QGraphicsItem *parentItem, QObject *parent)
: QObject(parent),
highlightedObject(itemToHighlight),
highlightPolygon(0),
highlightPolygonEdge(0)
{
highlightPolygon = new BoundingBoxPolygonItem(parentItem);
highlightPolygonEdge = new BoundingBoxPolygonItem(parentItem);
highlightPolygon->setPen(QPen(QColor(0, 22, 159)));
highlightPolygonEdge->setPen(QPen(QColor(158, 199, 255)));
highlightPolygon->setFlag(QGraphicsItem::ItemIsSelectable, false);
highlightPolygonEdge->setFlag(QGraphicsItem::ItemIsSelectable, false);
}
BoundingBox::~BoundingBox()
{
highlightedObject.clear();
}
BoundingBoxPolygonItem::BoundingBoxPolygonItem(QGraphicsItem *item) : QGraphicsPolygonItem(item)
{
QPen pen;
pen.setColor(QColor(108, 141, 221));
setPen(pen);
}
int BoundingBoxPolygonItem::type() const
{
return Constants::EditorItemType;
}
BoundingRectHighlighter::BoundingRectHighlighter(QDeclarativeDesignView *view) :
LayerItem(view->scene()),
m_view(view),
m_animFrame(0)
{
m_animTimer = new QTimer(this);
m_animTimer->setInterval(AnimInterval);
connect(m_animTimer, SIGNAL(timeout()), SLOT(animTimeout()));
}
BoundingRectHighlighter::~BoundingRectHighlighter()
{
}
void BoundingRectHighlighter::animTimeout()
{
++m_animFrame;
if (m_animFrame == AnimFrames) {
m_animTimer->stop();
}
qreal alpha = m_animFrame / float(AnimFrames);
foreach(BoundingBox *box, m_boxes) {
box->highlightPolygonEdge->setOpacity(alpha);
}
}
void BoundingRectHighlighter::clear()
{
if (m_boxes.length()) {
m_animTimer->stop();
foreach(BoundingBox *box, m_boxes) {
freeBoundingBox(box);
}
}
}
BoundingBox *BoundingRectHighlighter::boxFor(QGraphicsObject *item) const
{
foreach(BoundingBox *box, m_boxes) {
if (box->highlightedObject.data() == item) {
return box;
}
}
return 0;
}
void BoundingRectHighlighter::highlight(QList<QGraphicsObject*> items)
{
if (items.isEmpty())
return;
bool animate = false;
QList<BoundingBox *> newBoxes;
foreach(QGraphicsObject *itemToHighlight, items) {
BoundingBox *box = boxFor(itemToHighlight);
if (!box) {
box = createBoundingBox(itemToHighlight);
animate = true;
}
newBoxes << box;
}
qSort(newBoxes);
if (newBoxes != m_boxes) {
clear();
m_boxes << newBoxes;
}
highlightAll(animate);
}
void BoundingRectHighlighter::highlight(QGraphicsObject* itemToHighlight)
{
if (!itemToHighlight)
return;
bool animate = false;
BoundingBox *box = boxFor(itemToHighlight);
if (!box) {
box = createBoundingBox(itemToHighlight);
m_boxes << box;
animate = true;
qSort(m_boxes);
}
highlightAll(animate);
}
BoundingBox *BoundingRectHighlighter::createBoundingBox(QGraphicsObject *itemToHighlight)
{
if (!m_freeBoxes.isEmpty()) {
BoundingBox *box = m_freeBoxes.last();
if (box->highlightedObject.isNull()) {
box->highlightedObject = itemToHighlight;
box->highlightPolygon->show();
box->highlightPolygonEdge->show();
m_freeBoxes.removeLast();
return box;
}
}
BoundingBox *box = new BoundingBox(itemToHighlight, this, this);
connect(itemToHighlight, SIGNAL(xChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(yChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(widthChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(heightChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(rotationChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(destroyed(QObject*)), this, SLOT(itemDestroyed(QObject*)));
return box;
}
void BoundingRectHighlighter::removeBoundingBox(BoundingBox *box)
{
delete box;
box = 0;
}
void BoundingRectHighlighter::freeBoundingBox(BoundingBox *box)
{
if (!box->highlightedObject.isNull()) {
disconnect(box->highlightedObject.data(), SIGNAL(xChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(yChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(widthChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(heightChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(rotationChanged()), this, SLOT(refresh()));
}
box->highlightedObject.clear();
box->highlightPolygon->hide();
box->highlightPolygonEdge->hide();
m_boxes.removeOne(box);
m_freeBoxes << box;
}
void BoundingRectHighlighter::itemDestroyed(QObject *obj)
{
foreach(BoundingBox *box, m_boxes) {
if (box->highlightedObject.data() == obj) {
freeBoundingBox(box);
break;
}
}
}
void BoundingRectHighlighter::highlightAll(bool animate)
{
foreach(BoundingBox *box, m_boxes) {
if (box && box->highlightedObject.isNull()) {
// clear all highlights
clear();
return;
}
QGraphicsObject *item = box->highlightedObject.data();
QRectF itemAndChildRect = item->boundingRect() | item->childrenBoundingRect();
QPolygonF boundingRectInSceneSpace(item->mapToScene(itemAndChildRect));
QPolygonF boundingRectInLayerItemSpace = mapFromScene(boundingRectInSceneSpace);
QRectF bboxRect = m_view->adjustToScreenBoundaries(boundingRectInLayerItemSpace.boundingRect());
QRectF edgeRect = bboxRect;
edgeRect.adjust(-1, -1, 1, 1);
box->highlightPolygon->setPolygon(QPolygonF(bboxRect));
box->highlightPolygonEdge->setPolygon(QPolygonF(edgeRect));
if (animate)
box->highlightPolygonEdge->setOpacity(0);
}
if (animate) {
m_animFrame = 0;
m_animTimer->start();
}
}
void BoundingRectHighlighter::refresh()
{
if (!m_boxes.isEmpty())
highlightAll(true);
}
} // namespace QmlViewer
<commit_msg>qml observer: set default pen size to 1<commit_after>#include "boundingrecthighlighter.h"
#include "qdeclarativedesignview.h"
#include "qmlviewerconstants.h"
#include <QGraphicsPolygonItem>
#include <QTimer>
#include <QObject>
#include <QDebug>
namespace QmlViewer {
const qreal AnimDelta = 0.025f;
const int AnimInterval = 30;
const int AnimFrames = 10;
BoundingBox::BoundingBox(QGraphicsObject *itemToHighlight, QGraphicsItem *parentItem, QObject *parent)
: QObject(parent),
highlightedObject(itemToHighlight),
highlightPolygon(0),
highlightPolygonEdge(0)
{
highlightPolygon = new BoundingBoxPolygonItem(parentItem);
highlightPolygonEdge = new BoundingBoxPolygonItem(parentItem);
highlightPolygon->setPen(QPen(QColor(0, 22, 159)));
highlightPolygonEdge->setPen(QPen(QColor(158, 199, 255)));
highlightPolygon->setFlag(QGraphicsItem::ItemIsSelectable, false);
highlightPolygonEdge->setFlag(QGraphicsItem::ItemIsSelectable, false);
}
BoundingBox::~BoundingBox()
{
highlightedObject.clear();
}
BoundingBoxPolygonItem::BoundingBoxPolygonItem(QGraphicsItem *item) : QGraphicsPolygonItem(item)
{
QPen pen;
pen.setColor(QColor(108, 141, 221));
pen.setWidth(1);
setPen(pen);
}
int BoundingBoxPolygonItem::type() const
{
return Constants::EditorItemType;
}
BoundingRectHighlighter::BoundingRectHighlighter(QDeclarativeDesignView *view) :
LayerItem(view->scene()),
m_view(view),
m_animFrame(0)
{
m_animTimer = new QTimer(this);
m_animTimer->setInterval(AnimInterval);
connect(m_animTimer, SIGNAL(timeout()), SLOT(animTimeout()));
}
BoundingRectHighlighter::~BoundingRectHighlighter()
{
}
void BoundingRectHighlighter::animTimeout()
{
++m_animFrame;
if (m_animFrame == AnimFrames) {
m_animTimer->stop();
}
qreal alpha = m_animFrame / float(AnimFrames);
foreach(BoundingBox *box, m_boxes) {
box->highlightPolygonEdge->setOpacity(alpha);
}
}
void BoundingRectHighlighter::clear()
{
if (m_boxes.length()) {
m_animTimer->stop();
foreach(BoundingBox *box, m_boxes) {
freeBoundingBox(box);
}
}
}
BoundingBox *BoundingRectHighlighter::boxFor(QGraphicsObject *item) const
{
foreach(BoundingBox *box, m_boxes) {
if (box->highlightedObject.data() == item) {
return box;
}
}
return 0;
}
void BoundingRectHighlighter::highlight(QList<QGraphicsObject*> items)
{
if (items.isEmpty())
return;
bool animate = false;
QList<BoundingBox *> newBoxes;
foreach(QGraphicsObject *itemToHighlight, items) {
BoundingBox *box = boxFor(itemToHighlight);
if (!box) {
box = createBoundingBox(itemToHighlight);
animate = true;
}
newBoxes << box;
}
qSort(newBoxes);
if (newBoxes != m_boxes) {
clear();
m_boxes << newBoxes;
}
highlightAll(animate);
}
void BoundingRectHighlighter::highlight(QGraphicsObject* itemToHighlight)
{
if (!itemToHighlight)
return;
bool animate = false;
BoundingBox *box = boxFor(itemToHighlight);
if (!box) {
box = createBoundingBox(itemToHighlight);
m_boxes << box;
animate = true;
qSort(m_boxes);
}
highlightAll(animate);
}
BoundingBox *BoundingRectHighlighter::createBoundingBox(QGraphicsObject *itemToHighlight)
{
if (!m_freeBoxes.isEmpty()) {
BoundingBox *box = m_freeBoxes.last();
if (box->highlightedObject.isNull()) {
box->highlightedObject = itemToHighlight;
box->highlightPolygon->show();
box->highlightPolygonEdge->show();
m_freeBoxes.removeLast();
return box;
}
}
BoundingBox *box = new BoundingBox(itemToHighlight, this, this);
connect(itemToHighlight, SIGNAL(xChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(yChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(widthChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(heightChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(rotationChanged()), this, SLOT(refresh()));
connect(itemToHighlight, SIGNAL(destroyed(QObject*)), this, SLOT(itemDestroyed(QObject*)));
return box;
}
void BoundingRectHighlighter::removeBoundingBox(BoundingBox *box)
{
delete box;
box = 0;
}
void BoundingRectHighlighter::freeBoundingBox(BoundingBox *box)
{
if (!box->highlightedObject.isNull()) {
disconnect(box->highlightedObject.data(), SIGNAL(xChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(yChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(widthChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(heightChanged()), this, SLOT(refresh()));
disconnect(box->highlightedObject.data(), SIGNAL(rotationChanged()), this, SLOT(refresh()));
}
box->highlightedObject.clear();
box->highlightPolygon->hide();
box->highlightPolygonEdge->hide();
m_boxes.removeOne(box);
m_freeBoxes << box;
}
void BoundingRectHighlighter::itemDestroyed(QObject *obj)
{
foreach(BoundingBox *box, m_boxes) {
if (box->highlightedObject.data() == obj) {
freeBoundingBox(box);
break;
}
}
}
void BoundingRectHighlighter::highlightAll(bool animate)
{
foreach(BoundingBox *box, m_boxes) {
if (box && box->highlightedObject.isNull()) {
// clear all highlights
clear();
return;
}
QGraphicsObject *item = box->highlightedObject.data();
QRectF itemAndChildRect = item->boundingRect() | item->childrenBoundingRect();
QPolygonF boundingRectInSceneSpace(item->mapToScene(itemAndChildRect));
QPolygonF boundingRectInLayerItemSpace = mapFromScene(boundingRectInSceneSpace);
QRectF bboxRect = m_view->adjustToScreenBoundaries(boundingRectInLayerItemSpace.boundingRect());
QRectF edgeRect = bboxRect;
edgeRect.adjust(-1, -1, 1, 1);
box->highlightPolygon->setPolygon(QPolygonF(bboxRect));
box->highlightPolygonEdge->setPolygon(QPolygonF(edgeRect));
if (animate)
box->highlightPolygonEdge->setOpacity(0);
}
if (animate) {
m_animFrame = 0;
m_animTimer->start();
}
}
void BoundingRectHighlighter::refresh()
{
if (!m_boxes.isEmpty())
highlightAll(true);
}
} // namespace QmlViewer
<|endoftext|> |
<commit_before>#include <iostream>
#include <seqan/sequence.h>
#include <seqan/file.h>
using namespace seqan;
// Function to print simple alignment between two sequences with the same length
template <typename TText1, typename TText2>
void printAlign(TText1 const & genomeFragment, TText2 const & read)
{
std::cout << "Alignment " << std::endl;
std::cout << " genome : " << genomeFragment << std::endl;
std::cout << " read : " << read << std::endl;
}
int main(int, char const **)
{
// Build reads and genomes
DnaString chr1 = "TATAATATTGCTATCGCGATATCGCTAGCTAGCTACGGATTATGCGCTCTGCGATATATCGCGCTAGATGTGCAGCTCGATCGAATGCACGTGTGTGCGATCGATTAGCGTCGATCATCGATCTATATTAGCGCGCGGTATCGGACGATCATATTAGCGGTCTAGCATTTAG";
// Build List containing all reads
typedef String<DnaString> DnaList;
DnaList readList;
resize(readList, 4);
readList[0] = "TTGCTATCGCGATATCGCTAGCTAGCTACGGATTATGCGCTCTGCGATATATCGCGCT";
readList[1] = "TCGATTAGCGTCGATCATCGATCTATATTAGCGCGCGGTATCGGACGATCATATTAGCGGTCTAGCATT";
readList[2] = "AGCCTGCGTACGTTGCAGTGCGTGCGTAGACTGTTGCAAGCCGGGGGTTCATGTGCGCTGAAGCACACATGCACA";
readList[3] = "CGTGCACTGCTGACGTCGTGGTTGTCACATCGTCGTGCGTGCGTACTGCTGCTGACA";
// Append a second chromosome sequence fragment to chr1
DnaString chr2 = "AGCCTGCGTACGTTGCAGTGCGTGCGTAGACTGTTGCAAGCCGGGGGTTCATGTGCGCTGAAGCACACATGCACACGTCTCTGTGTTCCGACGTGTGTCACGTGCACTGCTGACGTCGTGGTTGTCACATCGTCGTGCGTGCGTACTGCTGCTGACACATGCTGCTG";
append(chr1, chr2);
// Print readlist
std::cout << " \n Read list: " << std::endl;
for(unsigned i = 0; i < length(readList); ++i)
std::cout << readList[i] << std::endl;
// Assume we have mapped the 4 reads to chr1 (and chr2) and now have the mapping start positions (no gaps).
// Store the start position in a String: 7, 100, 172, 272
String<unsigned> alignPosList;
resize(alignPosList, 4);
alignPosList[0] = 7;
alignPosList[1] = 100;
alignPosList[2] = 172;
alignPosList[3] = 272;
// Print alignments using Segment
std::cout << " \n Print alignment using Segment: " << std::endl;
for(unsigned i = 0; i < length(readList); ++i)
{
// Begin and end position of a given alignment between the read and the genome
unsigned beginPosition = alignPosList[i];
unsigned endPosition = beginPosition + length(readList[i]);
// Build infix
Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);
// Call of our function to print the simple alignment
printAlign(genomeFragment, readList[i]);
}
// Iterators :)
// Print alignments using Iterators: Do the same as above, but use Iterators to iterate over the read list.
// First, use Standard Iterators.
Iterator<DnaList>::Type it = begin(readList);
Iterator<DnaList, Standard>::Type itEnd = end(readList); //same Iterator as above
std::cout << " \n Print alignment using Standard Iterators: " << std::endl;
for(; it != itEnd; goNext(it))
{
// Get the right index for alignPosList
int i = position(it, readList);
// Begin and end position of a given alignment between the read and the genome
unsigned beginPosition = alignPosList[i];
unsigned endPosition = beginPosition + length(value(it));
// Build Infix
Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);
// Call of our function to print the simple alignment
printAlign(genomeFragment, value(it));
}
// Now, use Rooted Iterators.
Iterator<DnaList, Rooted>::Type it2 = begin(readList);
std::cout << " \n Print alignment using Rooted Iterators: " << std::endl;
for(; !atEnd(it2); goNext(it2))
{
int i = position(it2);
// Begin and end position of a given alignment between the read and the genome
unsigned beginPosition = alignPosList[i];
unsigned endPosition = beginPosition + length(value(it2));
// Build Infix
Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);
// Call of our function to print the simple alignment
printAlign(genomeFragment, value(it2));
}
return 1;
}
<commit_msg>[DOC] Deleted tutorial file.<commit_after><|endoftext|> |
<commit_before>
#include "common.h"
#include "settingskeys.h"
#include "logger.h"
// Didn't find sleep in QCore
#ifdef Q_OS_WIN
#include <winsock2.h> // for windows.h
#include <windows.h> // for Sleep
#endif
#include <QSettings>
#include <QMutex>
const QString alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789";
QString generateRandomString(uint32_t length)
{
// TODO make this cryptographically secure to avoid collisions
QString string;
for( unsigned int i = 0; i < length; ++i )
{
string.append(alphabet.at(qrand()%alphabet.size()));
}
return string;
}
bool settingEnabled(QString key)
{
return settingValue(key) == 1;
}
int settingValue(QString key)
{
QSettings settings(settingsFile, settingsFileFormat);
if (!settings.value(key).isValid())
{
Logger::getLogger()->printDebug(DEBUG_WARNING, "Common", "Found faulty setting",
{"Key"}, {key});
return 0;
}
return settings.value(key).toInt();
}
QString settingString(QString key)
{
QSettings settings(settingsFile, settingsFileFormat);
if (!settings.value(key).isValid())
{
Logger::getLogger()->printDebug(DEBUG_WARNING, "Common", "Found faulty setting",
{"Key"}, {key});
return "";
}
return settings.value(key).toString();
}
QString getLocalUsername()
{
QSettings settings(settingsFile, settingsFileFormat);
return !settings.value(SettingsKey::localUsername).isNull()
? settings.value(SettingsKey::localUsername).toString() : "anonymous";
}
<commit_msg>refactor(Common): Remove deprecated qrand call<commit_after>
#include "common.h"
#include "settingskeys.h"
#include "logger.h"
// Didn't find sleep in QCore
#ifdef Q_OS_WIN
#include <winsock2.h> // for windows.h
#include <windows.h> // for Sleep
#endif
#include <QSettings>
#include <QMutex>
#include <cstdlib>
const QString alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789";
QString generateRandomString(uint32_t length)
{
// TODO make this cryptographically secure to avoid collisions
QString string;
for( unsigned int i = 0; i < length; ++i )
{
string.append(alphabet.at(rand()%alphabet.size()));
}
return string;
}
bool settingEnabled(QString key)
{
return settingValue(key) == 1;
}
int settingValue(QString key)
{
QSettings settings(settingsFile, settingsFileFormat);
if (!settings.value(key).isValid())
{
Logger::getLogger()->printDebug(DEBUG_WARNING, "Common", "Found faulty setting",
{"Key"}, {key});
return 0;
}
return settings.value(key).toInt();
}
QString settingString(QString key)
{
QSettings settings(settingsFile, settingsFileFormat);
if (!settings.value(key).isValid())
{
Logger::getLogger()->printDebug(DEBUG_WARNING, "Common", "Found faulty setting",
{"Key"}, {key});
return "";
}
return settings.value(key).toString();
}
QString getLocalUsername()
{
QSettings settings(settingsFile, settingsFileFormat);
return !settings.value(SettingsKey::localUsername).isNull()
? settings.value(SettingsKey::localUsername).toString() : "anonymous";
}
<|endoftext|> |
<commit_before>/* ux++ - ux implementation for C++ */
/* LICENSE - The MIT License (MIT)
Copyright (c) 2013 Tomona Nanase
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.
*/
#ifndef COMMON_H
#define COMMON_H
/* クランプ関数 */
#define clamp(value, max, min) (value < min ? min : value > max ? max : value)
#endif /* COMMON_H */
<commit_msg>NetBeansのコード折りたたみ指定を追加<commit_after>/* ux++ - ux implementation for C++ */
/* LICENSE - The MIT License (MIT)
Copyright (c) 2013 Tomona Nanase
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.
*/
#ifndef COMMON_H
#define COMMON_H
// <editor-fold desc="-- Macros --">
/* クランプ関数 */
#define clamp(value, max, min) (value < min ? min : value > max ? max : value)
// </editor-fold>
#endif /* COMMON_H */
<|endoftext|> |
<commit_before><commit_msg>Create #15.cpp<commit_after><|endoftext|> |
<commit_before>#include <thread>
#include <future>
#include <ncurses.h>
#include "../../../src/show_message.hh"
#include "../../../src/split.hh"
#include "../../vick-shell-command/src/shell_command.hh"
#include "../../../src/file_contents.hh"
#include "../../../src/prompt.hh"
#include "../../../src/mode.hh"
#include "compile.hh"
namespace vick {
namespace compile {
static std::string last_cmd;
static int compile(std::string last_cmd, contents& cont)
{
// contents cont(&read_only_mode);
try {
shell_command::exec_shell_command(last_cmd + " ; printf '\n%s\n' \"$?\"", cont);
// Space required here: ~~~~~~~~~~~~~~~~~~~~~~^ so that ``;;`` won't occur by accident
} catch (const std::exception&) {}
int ret = std::stoi(cont.cont.back());
cont.cont.pop_back();
if (cont.cont.back().size() == 0) cont.cont.pop_back();
return ret;
}
boost::optional<std::shared_ptr<change> >
compile_project(contents& cont, boost::optional<int> force_prompt)
{
if (force_prompt or last_cmd.empty()) {
attron(COLOR_PAIR(1));
auto temp = prompt("Compile command: ");
if (temp) last_cmd = *temp;
attroff(COLOR_PAIR(1));
if (not temp) return boost::none;
}
std::packaged_task<int(std::string, contents&)> tsk(compile);
auto future = tsk.get_future();
std::thread thread(std::move(tsk), last_cmd, std::ref(cont));
thread.join();
int res = future.get();
if (res != 0) show_message("ERROR! " + std::to_string(res));
return boost::none;
}
}
}
<commit_msg>Fix up not using else and double testing<commit_after>#include <thread>
#include <future>
#include <ncurses.h>
#include "../../../src/show_message.hh"
#include "../../../src/split.hh"
#include "../../vick-shell-command/src/shell_command.hh"
#include "../../../src/file_contents.hh"
#include "../../../src/prompt.hh"
#include "../../../src/mode.hh"
#include "compile.hh"
namespace vick {
namespace compile {
static std::string last_cmd;
static int compile(std::string last_cmd, contents& cont)
{
// contents cont(&read_only_mode);
try {
shell_command::exec_shell_command(last_cmd + " ; printf '\n%s\n' \"$?\"", cont);
// Space required here: ~~~~~~~~~~~~~~~~~~~~~~^ so that ``;;`` won't occur by accident
} catch (const std::exception&) {}
int ret = std::stoi(cont.cont.back());
cont.cont.pop_back();
if (cont.cont.back().size() == 0) cont.cont.pop_back();
return ret;
}
boost::optional<std::shared_ptr<change> >
compile_project(contents& cont, boost::optional<int> force_prompt)
{
if (force_prompt or last_cmd.empty()) {
attron(COLOR_PAIR(1));
auto temp = prompt("Compile command: ");
attroff(COLOR_PAIR(1));
if (temp) last_cmd = *temp;
else return boost::none;
}
std::packaged_task<int(std::string, contents&)> tsk(compile);
auto future = tsk.get_future();
std::thread thread(std::move(tsk), last_cmd, std::ref(cont));
thread.join();
int res = future.get();
if (res != 0) show_message("ERROR! " + std::to_string(res));
return boost::none;
}
}
}
<|endoftext|> |
<commit_before>#include "config.hpp"
#include <sys/types.h>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <libconfig.h++>
#ifdef _WIN32
#include <shlobj.h>
#include <windows.h>
#include <tchar.h>
// Use explicitly wide char functions and compile for unicode.
tstring home_directory()
{
tchar app_data_path[MAX_PATH];
auto result = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL,
SHGFP_TYPE_CURRENT, app_data_path);
return tstring(SUCCEEDED(result) ? app_data_path : L"");
}
tstring sx_config_path()
{
tchar environment_buffer[MAX_PATH];
return tstring(GetEnvironmentVariableW(L"SX_CFG", environment_buffer,
MAX_PATH) == TRUE ? environment_buffer : L"");
}
#else
#include <unistd.h>
#include <pwd.h>
// This is ANSI/MBCS if compiled on Windows but is always Unicode on Linux,
// so we can safely return it as tstring when excluded from Windows.
/*
tstring home_directory()
{
const char* home_path = getenv("HOME");
return std::string(home_path == nullptr ? getpwuid(getuid())->pw_dir :
home_path);
}
tstring sx_config_path()
{
const char* config_path = getenv("SX_CFG");
return std::string(config_path == nullptr ? "" : config_path);
}
*/
using boost::filesystem::path;
path home_directory()
{
const char* home_path = getenv("HOME");
if (!home_path)
{
passwd* pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
return path(homedir);
}
return path(home_path);
}
*/
using boost::filesystem::path;
path home_directory()
{
const char* home_path = getenv("HOME");
if (!home_path)
{
passwd* pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
return path(homedir);
}
return path(home_path);
}
*/
using boost::filesystem::path;
path home_directory()
{
const char* home_path = getenv("HOME");
if (!home_path)
{
passwd* pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
return path(homedir);
}
return path(home_path);
}
*/
using boost::filesystem::path;
path home_directory()
{
const char* home_path = getenv("HOME");
if (!home_path)
{
passwd* pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
return path(homedir);
}
return path(home_path);
}
#endif
template <typename T>
void get_value(const libconfig::Setting& root, config_map_type& config_map,
const std::string& key_name, const T& fallback_value)
{
T value;
// libconfig is ANSI/MBCS on Windows - no Unicode support.
// This reads ANSI/MBCS values from XML. If they are UTF-8 (and above the
// ASCII band) the values will be misinterpreted upon use.
config_map[key_name] = (root.lookupValue(key_name, value)) ?
boost::lexical_cast<std::string>(value) :
boost::lexical_cast<std::string>(fallback_value);
}
void set_config_path(libconfig::Config& configuration, const char* config_path)
{
// Ignore error if unable to read config file.
try
{
// libconfig is ANSI/MBCS on Windows - no Unicode support.
// This translates the path from Unicode to a "generic" path in
// ANSI/MBCS, which can result in failures.
configuration.readFile(config_path);
}
catch (const libconfig::FileIOException&) {}
catch (const libconfig::ParseException&) {}
}
void load_config(config_map_type& config)
{
libconfig::Config configuration;
#ifdef _WIN32
tstring environment_path = sx_config_path();
tpath config_path = environment_path.empty() ?
tpath(home_directory()) / L".sx.cfg" : tpath(environment_path);
set_config_path(configuration, config_path.generic_string().c_str());
#else
path conf_path = home_directory() / ".sx.cfg";
// Check for env variable config to override default path.
char* env_path = getenv("SX_CFG");
if (env_path)
conf_path = env_path;
set_config_path(configuration, conf_path.native().c_str());
#endif
// Read off values.
const libconfig::Setting& root = configuration.getRoot();
get_value<std::string>(root, config, "service", "tcp://37.139.11.99:9091");
get_value<std::string>(root, config, "client-certificate", ".sx.cert");
get_value<std::string>(root, config, "server-public-key", "");
}
<commit_msg>Fix random merge error.<commit_after>#include "config.hpp"
#include <sys/types.h>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <libconfig.h++>
#ifdef _WIN32
#include <shlobj.h>
#include <windows.h>
#include <tchar.h>
// Use explicitly wide char functions and compile for unicode.
tstring home_directory()
{
tchar app_data_path[MAX_PATH];
auto result = SHGetFolderPathW(NULL, CSIDL_LOCAL_APPDATA, NULL,
SHGFP_TYPE_CURRENT, app_data_path);
return tstring(SUCCEEDED(result) ? app_data_path : L"");
}
tstring sx_config_path()
{
tchar environment_buffer[MAX_PATH];
return tstring(GetEnvironmentVariableW(L"SX_CFG", environment_buffer,
MAX_PATH) == TRUE ? environment_buffer : L"");
}
#else
#include <unistd.h>
#include <pwd.h>
// This is ANSI/MBCS if compiled on Windows but is always Unicode on Linux,
// so we can safely return it as tstring when excluded from Windows.
/*
tstring home_directory()
{
const char* home_path = getenv("HOME");
return std::string(home_path == nullptr ? getpwuid(getuid())->pw_dir :
home_path);
}
tstring sx_config_path()
{
const char* config_path = getenv("SX_CFG");
return std::string(config_path == nullptr ? "" : config_path);
}
*/
using boost::filesystem::path;
path home_directory()
{
const char* home_path = getenv("HOME");
if (!home_path)
{
passwd* pw = getpwuid(getuid());
const char *homedir = pw->pw_dir;
return path(homedir);
}
return path(home_path);
}
#endif
template <typename T>
void get_value(const libconfig::Setting& root, config_map_type& config_map,
const std::string& key_name, const T& fallback_value)
{
T value;
// libconfig is ANSI/MBCS on Windows - no Unicode support.
// This reads ANSI/MBCS values from XML. If they are UTF-8 (and above the
// ASCII band) the values will be misinterpreted upon use.
config_map[key_name] = (root.lookupValue(key_name, value)) ?
boost::lexical_cast<std::string>(value) :
boost::lexical_cast<std::string>(fallback_value);
}
void set_config_path(libconfig::Config& configuration, const char* config_path)
{
// Ignore error if unable to read config file.
try
{
// libconfig is ANSI/MBCS on Windows - no Unicode support.
// This translates the path from Unicode to a "generic" path in
// ANSI/MBCS, which can result in failures.
configuration.readFile(config_path);
}
catch (const libconfig::FileIOException&) {}
catch (const libconfig::ParseException&) {}
}
void load_config(config_map_type& config)
{
libconfig::Config configuration;
#ifdef _WIN32
tstring environment_path = sx_config_path();
tpath config_path = environment_path.empty() ?
tpath(home_directory()) / L".sx.cfg" : tpath(environment_path);
set_config_path(configuration, config_path.generic_string().c_str());
#else
path conf_path = home_directory() / ".sx.cfg";
// Check for env variable config to override default path.
char* env_path = getenv("SX_CFG");
if (env_path)
conf_path = env_path;
set_config_path(configuration, conf_path.native().c_str());
#endif
// Read off values.
const libconfig::Setting& root = configuration.getRoot();
get_value<std::string>(root, config, "service", "tcp://37.139.11.99:9091");
get_value<std::string>(root, config, "client-certificate", ".sx.cert");
get_value<std::string>(root, config, "server-public-key", "");
}
<|endoftext|> |
<commit_before>#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <algorithm> // find
#include <deque>
#include "config_t.hpp"
#include "observer.hpp"
namespace generic {
class config : public config_t
, public observer<config_t>
{
public:
template<typename ... CS>
config(config_t * c, CS ... cs)
{
attach(c, cs ...);
}
~config(void)
{
for (auto & c : m_configs) {
c->detach(this);
}
}
template<typename ... CS>
void
attach(config_t * c, CS ... cs)
{
unfold_attach(c, cs ...);
}
template<typename ... CS>
void
detach(config_t * c, CS ... cs)
{
unfold_detach(c, cs ...);
}
const option &
operator[](const std::string & name)
{
for (auto & c : m_configs) {
try {
return (*c)[name];
} catch (...) {}
}
throw std::invalid_argument("No config value for \"" + name + "\"");
}
void
notify(config_t * c)
{
observable::notify();
}
private:
std::deque<config_t *> m_configs;
void
unfold_attach(config_t * c)
{
c->attach(this);
m_configs.push_front(c);
}
void
unfold_detach(config_t * c)
{
c->detach(this);
auto result = std::find(m_configs.begin(), m_configs.end(), c);
if (result != m_configs.end()) {
m_configs.erase(result);
}
}
}; // class config
}; // namespace generic
#endif // CONFIG_HPP
<commit_msg>Use push_back to make behaviour more understandable<commit_after>#ifndef CONFIG_HPP
#define CONFIG_HPP
#include <algorithm> // find
#include <deque>
#include "config_t.hpp"
#include "observer.hpp"
namespace generic {
class config : public config_t
, public observer<config_t>
{
public:
template<typename ... CS>
config(config_t * c, CS ... cs)
{
attach(c, cs ...);
}
~config(void)
{
for (auto & c : m_configs) {
c->detach(this);
}
}
template<typename ... CS>
void
attach(config_t * c, CS ... cs)
{
unfold_attach(c, cs ...);
}
template<typename ... CS>
void
detach(config_t * c, CS ... cs)
{
unfold_detach(c, cs ...);
}
const option &
operator[](const std::string & name)
{
for (auto & c : m_configs) {
try {
return (*c)[name];
} catch (...) {}
}
throw std::invalid_argument("No config value for \"" + name + "\"");
}
void
notify(config_t * c)
{
observable::notify();
}
private:
std::deque<config_t *> m_configs;
void
unfold_attach(config_t * c)
{
c->attach(this);
m_configs.push_back(c);
}
void
unfold_detach(config_t * c)
{
c->detach(this);
auto result = std::find(m_configs.begin(), m_configs.end(), c);
if (result != m_configs.end()) {
m_configs.erase(result);
}
}
}; // class config
}; // namespace generic
#endif // CONFIG_HPP
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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 <Modules/Legacy/Fields/CreateImage.h>
#include <Core/GeometryPrimitives/Point.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Math/MiscMath.h> // for M_PI
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun;
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Width("Width");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Height("Height");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Depth("Depth");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::PadPercent("PadPercent");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Mode("Mode");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Axis("Axis");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::CenterX("CenterX");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::CenterY("CenterY");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::CenterZ("CenterZ");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::NormalX("NormalX");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::NormalY("NormalY");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::NormalZ("NormalZ");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Position("Position");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Index("Index");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::DataLocation("DataLocation");
MODULE_INFO_DEF(CreateImage, NewField, SCIRun)
CreateImage::CreateImage() : Module(staticInfo_)
{
INITIALIZE_PORT(InputField);
INITIALIZE_PORT(SizeMatrix);
INITIALIZE_PORT(OVMatrix);
INITIALIZE_PORT(OutputField);
}
void CreateImage::setStateDefaults()
{
auto state = get_state();
state->setValue(Width, 20);
state->setValue(Height, 20);
state->setValue(Depth, 2);
state->setValue(PadPercent, 0.0);
state->setValue(Mode, std::string("Manual"));
state->setValue(Axis, std::string("X"));
state->setValue(CenterX, 0);
state->setValue(CenterY, 0);
state->setValue(CenterZ, 0);
state->setValue(NormalX, 1);
state->setValue(NormalY, 1);
state->setValue(NormalZ, 1);
state->setValue(Position, 0);
state->setValue(Index, 0);
state->setValue(DataLocation, std::string("Nodes(linear basis)"));
}
void CreateImage::execute()
{
auto inputField = getOptionalInput(InputField);
auto sizeOption = getOptionalInput(SizeMatrix);
auto oVMatrixInput = getOptionalInput(OVMatrix);
FieldHandle output;
if (needToExecute())
{
Point customCenter;
Vector customNormal;
std::string axisInput = get_state()->getValue(Axis).toString();
int axisTemp;
if (axisInput == "X")
axisTemp = 0;
else if (axisInput == "Y")
axisTemp = 1;
else if (axisInput == "Z")
axisTemp = 2;
else if (axisInput == "Custom")
axisTemp = 3;
auto axis = std::min(2, std::max(0, axisTemp));
Transform trans;
trans.load_identity();
auto sizeMatrix = *sizeOption;
// checking for input matrices
if (sizeMatrix)
{
if (sizeMatrix->nrows() == 1 && sizeMatrix->ncols() == 1)
{
//double* data=sizeMatrix->getDatapointer();
const int size1 = static_cast<int>((*sizeMatrix)(0, 0));
const int size2 = static_cast<int>((*sizeMatrix)(0, 0));
get_state()->setValue(Width, size1);
get_state()->setValue(Height, size2);
}
else if (sizeMatrix->nrows() == 2 && sizeMatrix->ncols() == 1)
{
//double* data=sizeMatrix->get_data_pointer();
int size1 = static_cast<int>((*sizeMatrix)(0, 0));
int size2 = static_cast<int>((*sizeMatrix)(0, 1));
get_state()->setValue(Width, size1);
get_state()->setValue(Height, size2);
}
else
{
error("Image Size matrix must have only 1 or 2 elements");
}
}
auto oVMatrix = *oVMatrixInput;
if (oVMatrix)
{
if (oVMatrix->nrows() != 2 || oVMatrix->ncols() != 3)
{
error("Custom Center and Nomal matrix must be of size 2x3. The Center is the first row and the normal is the second");
}
customCenter = Point((*oVMatrix)(0, 0), (*oVMatrix)(0, 1), (*oVMatrix)(0, 2));
customNormal = Vector((*oVMatrix)(1, 0), (*oVMatrix)(1, 1), (*oVMatrix)(1, 2));
customNormal.safe_normalize();
}
double angle = 0;
Vector axisVector(0.0, 0.0, 1.0);
switch (axis)
{
case 0:
angle = M_PI * -0.5;
axisVector = Vector(0.0, 1.0, 0.0);
break;
case 1:
angle = M_PI * 0.5;
axisVector = Vector(1.0, 0.0, 0.0);
break;
case 2:
angle = 0.0;
axisVector = Vector(0.0, 0.0, 1.0);
break;
default:
break;
}
trans.pre_rotate(angle, axisVector);
if (axis == 3)
{
customNormal = Vector(get_state()->getValue(NormalX).toDouble(), get_state()->getValue(NormalY).toDouble(), get_state()->getValue(NormalZ).toDouble());
Vector tempNormal(-customNormal);
Vector fakey(Cross(Vector(0.0, 0.0, 1.0), tempNormal));
if (fakey.length2() < 1.0e-6)
fakey = Cross(Vector(1.0, 0.0, 0.0), tempNormal);
Vector fakex(Cross(tempNormal, fakey));
tempNormal.safe_normalize();
fakex.safe_normalize();
fakey.safe_normalize();
double dg = 1.0;
if (inputField)
{
BBox box = (*inputField)->vmesh()->get_bounding_box();
Vector diag(box.diagonal());
dg = diag.maxComponent();
trans.pre_scale(Vector(dg, dg, dg));
}
Transform trans2;
trans2.load_identity();
trans2.load_basis(Point(0, 0, 0), fakex, fakey, tempNormal);
trans2.invert();
trans.change_basis(trans2);
customCenter = Point(get_state()->getValue(CenterX).toDouble(), get_state()->getValue(CenterY).toDouble(), get_state()->getValue(CenterZ).toDouble());
trans.pre_translate(Vector(customCenter));
}
DataTypeEnum datatype;
int width, height, depth;
if (!inputField)
{
datatype = SCALAR;
// Create blank mesh.
width = std::max(2, get_state()->getValue(Width).toInt());
height = std::max(2, get_state()->getValue(Height).toInt());
}
else
{
datatype = SCALAR;
FieldInformation fi(*inputField);
if (fi.is_tensor())
{
datatype = TENSOR;
}
else if (fi.is_vector())
{
datatype = VECTOR;
}
int basis_order = 1;
if (get_state()->getValue(Mode).toString() == "Auto")
{
// Guess at the size of the sample plane.
// Currently we have only a simple algorithm for LatVolFields.
if (fi.is_latvolmesh())
{
VMesh *lvm = (*inputField)->vmesh();
basis_order = (*inputField)->vfield()->basis_order();
switch (axis)
{
case 0:
width = std::max(2, (int)lvm->get_nj());
get_state()->setValue(Width, width);
height = std::max(2, (int)lvm->get_nk());
get_state()->setValue(Height, height);
depth = std::max(2, (int)lvm->get_ni());
if (basis_order == 0)
{
get_state()->setValue(Depth, depth - 1);
}
else
{
get_state()->setValue(Depth, depth);
}
//TCLInterface::execute(get_id()+" edit_scale");
break;
case 1:
width = std::max(2, (int)lvm->get_ni());
get_state()->setValue(Width, width);
height = std::max(2, (int)lvm->get_nk());
get_state()->setValue(Height, height);
depth = std::max(2, (int)lvm->get_nj());
if (basis_order == 0)
{
get_state()->setValue(Depth, depth - 1);
}
else
{
get_state()->setValue(Depth, depth);
}
//TCLInterface::execute(get_id()+" edit_scale");
break;
case 2:
width = std::max(2, (int)lvm->get_ni());
get_state()->setValue(Width, width);
height = std::max(2, (int)lvm->get_nj());
get_state()->setValue(Height, height);
depth = std::max(2, (int)lvm->get_nk());
if (basis_order == 0)
{
get_state()->setValue(Depth, depth - 1);
}
else
{
get_state()->setValue(Depth, depth);
}
//TCLInterface::execute(get_id()+" edit_scale");
break;
default:
warning("Custom axis, resize manually.");
width = std::max(2, get_state()->getValue(Width).toInt());
height = std::max(2, get_state()->getValue(Height).toInt());
break;
}
}
else
{
warning("No autosize algorithm for this field type, resize manually.");
width = std::max(2, get_state()->getValue(Width).toInt());
height = std::max(2, get_state()->getValue(Height).toInt());
get_state()->setValue(Mode, std::string("Manual"));
//TCLInterface::execute(get_id()+" edit_scale");
}
}
else
{
// Create blank mesh.
width = std::max(2, get_state()->getValue(Width).toInt());
height = std::max(2, get_state()->getValue(Height).toInt());
}
if (axis != 3)
{
BBox box = (*inputField)->vmesh()->get_bounding_box();
Vector diag(box.diagonal());
trans.pre_scale(diag);
Point loc(box.center());
double dist;
if (get_state()->getValue(Mode).toString() == "Manual")
{
dist = get_state()->getValue(Position).toDouble() / 2.0;
}
else
{
if (basis_order == 0)
{
dist = double(get_state()->getValue(Index).toInt()) / get_state()->getValue(Depth).toDouble() + 0.5 / get_state()->getValue(Depth).toDouble();
get_state()->setValue(Position, (dist)* 2.0);
}
else
{
dist = double(get_state()->getValue(Index).toInt()) / get_state()->getValue(Depth).toDouble();
get_state()->setValue(Position, (dist)* 2.0);
}
}
switch (axis)
{
case 0:
loc.x(loc.x() + diag.x() * dist);
break;
case 1:
loc.y(loc.y() + diag.y() * dist);
break;
case 2:
loc.z(loc.z() + diag.z() * dist);
break;
default:
break;
}
trans.pre_translate(Vector(loc));
}
}
Point minb(-0.5, -0.5, 0.0);
Point maxb(0.5, 0.5, 0.0);
Vector diag((Vector(maxb) - Vector(minb)) * (get_state()->getValue(PadPercent).toDouble() / 100.0));
minb -= diag;
maxb += diag;
int basis_order = 1;
if (get_state()->getValue(DataLocation).toString() == "Nodes(linear basis)")
basis_order = 1;
else if (get_state()->getValue(DataLocation).toString() == "Faces(constant basis)")
basis_order = 0;
else if (get_state()->getValue(DataLocation).toString() == "None")
basis_order = -1;
/*else
{
error("Unsupported data_at location " + getOption(Parameters::DataLocation) + ".");
AlgorithmOutput result;
return result;
}*/
FieldInformation ifi("ImageMesh", basis_order, "double");
if (datatype == VECTOR)
ifi.make_vector();
else if (datatype == TENSOR)
ifi.make_tensor();
MeshHandle imagemesh = CreateMesh(ifi, width, height, minb, maxb);
output = CreateField(ifi, imagemesh);
output->vmesh()->transform(trans);
sendOutput(OutputField, output);
}
}
<commit_msg>Fix crash in CreateImage<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
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 <Modules/Legacy/Fields/CreateImage.h>
#include <Core/GeometryPrimitives/Point.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <Core/Datatypes/Legacy/Field/VField.h>
#include <Core/Datatypes/Legacy/Field/FieldInformation.h>
#include <Core/Math/MiscMath.h> // for M_PI
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Geometry;
using namespace SCIRun;
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Width("Width");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Height("Height");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Depth("Depth");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::PadPercent("PadPercent");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Mode("Mode");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Axis("Axis");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::CenterX("CenterX");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::CenterY("CenterY");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::CenterZ("CenterZ");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::NormalX("NormalX");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::NormalY("NormalY");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::NormalZ("NormalZ");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Position("Position");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::Index("Index");
const SCIRun::Core::Algorithms::AlgorithmParameterName CreateImage::DataLocation("DataLocation");
MODULE_INFO_DEF(CreateImage, NewField, SCIRun)
CreateImage::CreateImage() : Module(staticInfo_)
{
INITIALIZE_PORT(InputField);
INITIALIZE_PORT(SizeMatrix);
INITIALIZE_PORT(OVMatrix);
INITIALIZE_PORT(OutputField);
}
void CreateImage::setStateDefaults()
{
auto state = get_state();
state->setValue(Width, 20);
state->setValue(Height, 20);
state->setValue(Depth, 2);
state->setValue(PadPercent, 0.0);
state->setValue(Mode, std::string("Manual"));
state->setValue(Axis, std::string("X"));
state->setValue(CenterX, 0);
state->setValue(CenterY, 0);
state->setValue(CenterZ, 0);
state->setValue(NormalX, 1);
state->setValue(NormalY, 1);
state->setValue(NormalZ, 1);
state->setValue(Position, 0);
state->setValue(Index, 0);
state->setValue(DataLocation, std::string("Nodes(linear basis)"));
}
void CreateImage::execute()
{
auto inputField = getOptionalInput(InputField);
auto sizeOption = getOptionalInput(SizeMatrix);
auto oVMatrixInput = getOptionalInput(OVMatrix);
FieldHandle output;
if (needToExecute())
{
Point customCenter;
Vector customNormal;
std::string axisInput = get_state()->getValue(Axis).toString();
int axisTemp;
if (axisInput == "X")
axisTemp = 0;
else if (axisInput == "Y")
axisTemp = 1;
else if (axisInput == "Z")
axisTemp = 2;
else if (axisInput == "Custom")
axisTemp = 3;
auto axis = std::min(2, std::max(0, axisTemp));
Transform trans;
trans.load_identity();
if (sizeOption)
{
auto sizeMatrix = *sizeOption;
// checking for input matrices
if (sizeMatrix)
{
if (sizeMatrix->nrows() == 1 && sizeMatrix->ncols() == 1)
{
//double* data=sizeMatrix->getDatapointer();
const int size1 = static_cast<int>((*sizeMatrix)(0, 0));
const int size2 = static_cast<int>((*sizeMatrix)(0, 0));
get_state()->setValue(Width, size1);
get_state()->setValue(Height, size2);
}
else if (sizeMatrix->nrows() == 2 && sizeMatrix->ncols() == 1)
{
//double* data=sizeMatrix->get_data_pointer();
int size1 = static_cast<int>((*sizeMatrix)(0, 0));
int size2 = static_cast<int>((*sizeMatrix)(0, 1));
get_state()->setValue(Width, size1);
get_state()->setValue(Height, size2);
}
else
{
error("Image Size matrix must have only 1 or 2 elements");
}
}
}
if (oVMatrixInput)
{
auto oVMatrix = *oVMatrixInput;
if (oVMatrix)
{
if (oVMatrix->nrows() != 2 || oVMatrix->ncols() != 3)
{
error("Custom Center and Nomal matrix must be of size 2x3. The Center is the first row and the normal is the second");
}
customCenter = Point((*oVMatrix)(0, 0), (*oVMatrix)(0, 1), (*oVMatrix)(0, 2));
customNormal = Vector((*oVMatrix)(1, 0), (*oVMatrix)(1, 1), (*oVMatrix)(1, 2));
customNormal.safe_normalize();
}
}
double angle = 0;
Vector axisVector(0.0, 0.0, 1.0);
switch (axis)
{
case 0:
angle = M_PI * -0.5;
axisVector = Vector(0.0, 1.0, 0.0);
break;
case 1:
angle = M_PI * 0.5;
axisVector = Vector(1.0, 0.0, 0.0);
break;
case 2:
angle = 0.0;
axisVector = Vector(0.0, 0.0, 1.0);
break;
default:
break;
}
trans.pre_rotate(angle, axisVector);
if (axis == 3)
{
customNormal = Vector(get_state()->getValue(NormalX).toDouble(), get_state()->getValue(NormalY).toDouble(), get_state()->getValue(NormalZ).toDouble());
Vector tempNormal(-customNormal);
Vector fakey(Cross(Vector(0.0, 0.0, 1.0), tempNormal));
if (fakey.length2() < 1.0e-6)
fakey = Cross(Vector(1.0, 0.0, 0.0), tempNormal);
Vector fakex(Cross(tempNormal, fakey));
tempNormal.safe_normalize();
fakex.safe_normalize();
fakey.safe_normalize();
double dg = 1.0;
if (inputField)
{
BBox box = (*inputField)->vmesh()->get_bounding_box();
Vector diag(box.diagonal());
dg = diag.maxComponent();
trans.pre_scale(Vector(dg, dg, dg));
}
Transform trans2;
trans2.load_identity();
trans2.load_basis(Point(0, 0, 0), fakex, fakey, tempNormal);
trans2.invert();
trans.change_basis(trans2);
customCenter = Point(get_state()->getValue(CenterX).toDouble(), get_state()->getValue(CenterY).toDouble(), get_state()->getValue(CenterZ).toDouble());
trans.pre_translate(Vector(customCenter));
}
DataTypeEnum datatype;
int width, height, depth;
if (!inputField)
{
datatype = SCALAR;
// Create blank mesh.
width = std::max(2, get_state()->getValue(Width).toInt());
height = std::max(2, get_state()->getValue(Height).toInt());
}
else
{
datatype = SCALAR;
FieldInformation fi(*inputField);
if (fi.is_tensor())
{
datatype = TENSOR;
}
else if (fi.is_vector())
{
datatype = VECTOR;
}
int basis_order = 1;
if (get_state()->getValue(Mode).toString() == "Auto")
{
// Guess at the size of the sample plane.
// Currently we have only a simple algorithm for LatVolFields.
if (fi.is_latvolmesh())
{
VMesh *lvm = (*inputField)->vmesh();
basis_order = (*inputField)->vfield()->basis_order();
switch (axis)
{
case 0:
width = std::max(2, (int)lvm->get_nj());
get_state()->setValue(Width, width);
height = std::max(2, (int)lvm->get_nk());
get_state()->setValue(Height, height);
depth = std::max(2, (int)lvm->get_ni());
if (basis_order == 0)
{
get_state()->setValue(Depth, depth - 1);
}
else
{
get_state()->setValue(Depth, depth);
}
//TCLInterface::execute(get_id()+" edit_scale");
break;
case 1:
width = std::max(2, (int)lvm->get_ni());
get_state()->setValue(Width, width);
height = std::max(2, (int)lvm->get_nk());
get_state()->setValue(Height, height);
depth = std::max(2, (int)lvm->get_nj());
if (basis_order == 0)
{
get_state()->setValue(Depth, depth - 1);
}
else
{
get_state()->setValue(Depth, depth);
}
//TCLInterface::execute(get_id()+" edit_scale");
break;
case 2:
width = std::max(2, (int)lvm->get_ni());
get_state()->setValue(Width, width);
height = std::max(2, (int)lvm->get_nj());
get_state()->setValue(Height, height);
depth = std::max(2, (int)lvm->get_nk());
if (basis_order == 0)
{
get_state()->setValue(Depth, depth - 1);
}
else
{
get_state()->setValue(Depth, depth);
}
//TCLInterface::execute(get_id()+" edit_scale");
break;
default:
warning("Custom axis, resize manually.");
width = std::max(2, get_state()->getValue(Width).toInt());
height = std::max(2, get_state()->getValue(Height).toInt());
break;
}
}
else
{
warning("No autosize algorithm for this field type, resize manually.");
width = std::max(2, get_state()->getValue(Width).toInt());
height = std::max(2, get_state()->getValue(Height).toInt());
get_state()->setValue(Mode, std::string("Manual"));
//TCLInterface::execute(get_id()+" edit_scale");
}
}
else
{
// Create blank mesh.
width = std::max(2, get_state()->getValue(Width).toInt());
height = std::max(2, get_state()->getValue(Height).toInt());
}
if (axis != 3)
{
BBox box = (*inputField)->vmesh()->get_bounding_box();
Vector diag(box.diagonal());
trans.pre_scale(diag);
Point loc(box.center());
double dist;
if (get_state()->getValue(Mode).toString() == "Manual")
{
dist = get_state()->getValue(Position).toDouble() / 2.0;
}
else
{
if (basis_order == 0)
{
dist = double(get_state()->getValue(Index).toInt()) / get_state()->getValue(Depth).toDouble() + 0.5 / get_state()->getValue(Depth).toDouble();
get_state()->setValue(Position, (dist)* 2.0);
}
else
{
dist = double(get_state()->getValue(Index).toInt()) / get_state()->getValue(Depth).toDouble();
get_state()->setValue(Position, (dist)* 2.0);
}
}
switch (axis)
{
case 0:
loc.x(loc.x() + diag.x() * dist);
break;
case 1:
loc.y(loc.y() + diag.y() * dist);
break;
case 2:
loc.z(loc.z() + diag.z() * dist);
break;
default:
break;
}
trans.pre_translate(Vector(loc));
}
}
Point minb(-0.5, -0.5, 0.0);
Point maxb(0.5, 0.5, 0.0);
Vector diag((Vector(maxb) - Vector(minb)) * (get_state()->getValue(PadPercent).toDouble() / 100.0));
minb -= diag;
maxb += diag;
int basis_order = 1;
if (get_state()->getValue(DataLocation).toString() == "Nodes(linear basis)")
basis_order = 1;
else if (get_state()->getValue(DataLocation).toString() == "Faces(constant basis)")
basis_order = 0;
else if (get_state()->getValue(DataLocation).toString() == "None")
basis_order = -1;
/*else
{
error("Unsupported data_at location " + getOption(Parameters::DataLocation) + ".");
AlgorithmOutput result;
return result;
}*/
FieldInformation ifi("ImageMesh", basis_order, "double");
if (datatype == VECTOR)
ifi.make_vector();
else if (datatype == TENSOR)
ifi.make_tensor();
MeshHandle imagemesh = CreateMesh(ifi, width, height, minb, maxb);
output = CreateField(ifi, imagemesh);
output->vmesh()->transform(trans);
sendOutput(OutputField, output);
}
}
<|endoftext|> |
<commit_before>/* Copyright (C) 2013 Slawomir Cygan <[email protected]>
*
* 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<string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include "client.h"
namespace dglnet {
Client::Client(IController* controller, MessageHandler* handler):Transport(handler),m_controller(controller), m_Resolver(m_io_service) {}
void Client::connectServer(std::string host, std::string port) {
boost::asio::ip::tcp::resolver::query query(host, port);
m_Resolver.async_resolve(query, boost::bind(&Client::onResolve, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
m_controller->onSetStatus("Looking up server...");
}
Client::socket_fd_t Client::getSocketFD() {
return m_socket.native_handle();
}
void Client::onResolve(const boost::system::error_code& err,
boost::asio::ip::tcp::resolver::iterator endpoint_iterator) {
if (!err) {
m_socket.async_connect(*endpoint_iterator, boost::bind(&Client::onConnect, shared_from_this(),
boost::asio::placeholders::error));
m_controller->onSetStatus("Connecting...");
m_controller->onSocket();
} else {
notifyDisconnect(err.message());
}
}
void Client::onConnect(const boost::system::error_code &err) {
if (!err) {
m_controller->onSetStatus("Connected.");
read();
} else {
notifyDisconnect(err.message());
}
}
boost::shared_ptr<Client> Client::shared_from_this() {
return boost::static_pointer_cast<Client>(get_shared_from_base());
}
}
<commit_msg>Do not include whole asio.hpp<commit_after>/* Copyright (C) 2013 Slawomir Cygan <[email protected]>
*
* 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<string>
#include <boost/bind.hpp>
#include <boost/asio/placeholders.hpp>
#include "client.h"
namespace dglnet {
Client::Client(IController* controller, MessageHandler* handler):Transport(handler),m_controller(controller), m_Resolver(m_io_service) {}
void Client::connectServer(std::string host, std::string port) {
boost::asio::ip::tcp::resolver::query query(host, port);
m_Resolver.async_resolve(query, boost::bind(&Client::onResolve, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
m_controller->onSetStatus("Looking up server...");
}
Client::socket_fd_t Client::getSocketFD() {
return m_socket.native_handle();
}
void Client::onResolve(const boost::system::error_code& err,
boost::asio::ip::tcp::resolver::iterator endpoint_iterator) {
if (!err) {
m_socket.async_connect(*endpoint_iterator, boost::bind(&Client::onConnect, shared_from_this(),
boost::asio::placeholders::error));
m_controller->onSetStatus("Connecting...");
m_controller->onSocket();
} else {
notifyDisconnect(err.message());
}
}
void Client::onConnect(const boost::system::error_code &err) {
if (!err) {
m_controller->onSetStatus("Connected.");
read();
} else {
notifyDisconnect(err.message());
}
}
boost::shared_ptr<Client> Client::shared_from_this() {
return boost::static_pointer_cast<Client>(get_shared_from_base());
}
}
<|endoftext|> |
<commit_before><commit_msg>translate to English<commit_after><|endoftext|> |
<commit_before>/*
* BIDSConn.cpp
*
* Created on: Aug 17, 2012
* Author: Brennan Nowers
*/
#include "BIDSConn.hpp"
namespace PV {
BIDSConn::BIDSConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
HyPerLayer * post, const char * filename, InitWeights *weightInit)
{
initialize_base();
initialize(name, hc, pre, post, filename, weightInit);
#ifdef PV_USE_OPENCL
if(gpuAccelerateFlag)
initializeGPU();
#endif
}
int BIDSConn::readPatchSize(PVParams * params) {
int status;
//@lateralRadius: the radius of the mathematical patch in 64x64 space
double lateralRadius = params->value(name, "lateralRadius");
//@jitter: The maximum possible amount that a physical node in 256x256 can be placed from its original mathematical position in 256x256 space
//In order to get the full length of the radius at which a node can see its neighboring nodes in 256x256 physical space while accounting for jitter
//on both ends, we take into acct. the provided lateral radius, maximum jitter from the principle node, and maximum jitter from the furthest possible
//neighboring node. Since this occurs on both sides of the patch, the equation is multiplied by two.
const char * jitterSourceName = params->stringValue(name, "jitterSource");
double jitter = params->value(jitterSourceName, "jitter");
int xScalePre = pre->getXScale();
int xScalePost = post->getXScale();
int xScale = (int)pow(2, xScalePre);
//Convert to bids space, +1 to round up
nxp = (1 + 2*(int)(ceil(lateralRadius/(double)xScale) + ceil(2.0 * jitter/(double)xScale)));
status = checkPatchSize(nxp, xScalePre, xScalePost, 'x');
int yScalePre = pre->getYScale();
int yScalePost = post->getYScale();
int yScale = (int)pow(2, yScalePre);
//Convert to bids space, +1 to round up
nyp = (1 + 2*(int)(ceil(lateralRadius/(double)yScale) + ceil(2.0 * jitter/(double)yScale)));
status = checkPatchSize(nyp, yScalePre, yScalePost, 'y');
nxpShrunken = 1;
nypShrunken = 1;
return status;
}
int BIDSConn::setPatchSize(const char * filename)
{
int status = PV_SUCCESS;
PVParams * inputParams = parent->parameters();
if( filename != NULL ) {
bool useListOfArborFiles = inputParams->value(name, "useListOfArborFiles", false)!=0;
bool combineWeightFiles = inputParams->value(name, "combineWeightFiles", false)!=0;
if( !useListOfArborFiles && !combineWeightFiles) status = patchSizeFromFile(filename);
}
return status;
}
} // namespace PV
<commit_msg>minor bug fix + added a comment<commit_after>/*
* BIDSConn.cpp
*
* Created on: Aug 17, 2012
* Author: Brennan Nowers
*/
#include "BIDSConn.hpp"
namespace PV {
BIDSConn::BIDSConn(const char * name, HyPerCol * hc, HyPerLayer * pre,
HyPerLayer * post, const char * filename, InitWeights *weightInit)
{
initialize_base();
initialize(name, hc, pre, post, filename, weightInit);
#ifdef PV_USE_OPENCL
if(gpuAccelerateFlag)
initializeGPU();
#endif
}
//Comments in this conn are assuming a HyPerCol size of 256x256 and a bids_node layer of 1/4 the density.
//Adjust numbers accordingly for a given simulation
int BIDSConn::readPatchSize(PVParams * params) {
int status;
//@lateralRadius: the radius of the mathematical patch in 64x64 space
double lateralRadius = params->value(name, "lateralRadius");
//@jitter: The maximum possible amount that a physical node in 256x256 can be placed from its original mathematical position in 256x256 space
//In order to get the full length of the radius at which a node can see its neighboring nodes in 256x256 physical space while accounting for jitter
//on both ends, we take into acct. the provided lateral radius, maximum jitter from the principle node, and maximum jitter from the furthest possible
//neighboring node. Since this occurs on both sides of the patch, the equation is multiplied by two.
const char * jitterSourceName = params->stringValue(name, "jitterSource");
double jitter = params->value(jitterSourceName, "jitter");
int xScalePre = pre->getXScale();
int xScalePost = post->getXScale();
int xScale = (int)pow(2, xScalePre);
//Convert to bids space, +1 to round up
nxp = (1 + 2*(int)(ceil(lateralRadius/(double)xScale) + ceil(2.0 * jitter/(double)xScale)));
status = checkPatchSize(nxp, xScalePre, xScalePost, 'x');
int yScalePre = pre->getYScale();
int yScalePost = post->getYScale();
int yScale = (int)pow(2, yScalePre);
//Convert to bids space, +1 to round up
nyp = (1 + 2*(int)(ceil(lateralRadius/(double)yScale) + ceil(2.0 * jitter/(double)yScale)));
status = checkPatchSize(nyp, yScalePre, yScalePost, 'y');
nxpShrunken = nxp;
nypShrunken = nyp;
return status;
}
int BIDSConn::setPatchSize(const char * filename)
{
int status = PV_SUCCESS;
PVParams * inputParams = parent->parameters();
if( filename != NULL ) {
bool useListOfArborFiles = inputParams->value(name, "useListOfArborFiles", false)!=0;
bool combineWeightFiles = inputParams->value(name, "combineWeightFiles", false)!=0;
if( !useListOfArborFiles && !combineWeightFiles) status = patchSizeFromFile(filename);
}
return status;
}
} // namespace PV
<|endoftext|> |
<commit_before>/*
* RuleConn.cpp
*
* Created on: Apr 5, 2009
* Author: rasmussn
*/
#include "RuleConn.hpp"
#include <assert.h>
#include <string.h>
namespace PV {
RuleConn::RuleConn(const char * name,
HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel)
{
initialize_base();
initialize(name, hc, pre, post, channel, NULL);
}
int RuleConn::initializeWeights(const char * filename)
{
if (filename == NULL) {
PVParams * params = parent->parameters();
const float strength = params->value(name, "strength");
const int xScale = pre->clayer->xScale;
const int yScale = pre->clayer->yScale;
int nfPre = pre->clayer->numFeatures;
const int arbor = 0;
const int numPatches = numWeightPatches(arbor);
for (int i = 0; i < numPatches; i++) {
int fPre = i % nfPre;
ruleWeights(wPatches[arbor][i], fPre, xScale, yScale, strength);
}
}
else {
fprintf(stderr, "Initializing weights from a file not implemented for RuleConn\n");
exit(1);
} // end if for filename
return 0;
}
int RuleConn::ruleWeights(PVPatch * wp, int fPre, int xScale, int yScale, float strength)
{
pvdata_t * w = wp->data;
const int nx = (int) wp->nx;
const int ny = (int) wp->ny;
const int nf = (int) wp->nf;
// strides
const int sx = (int) wp->sx; assert(sx == nf);
const int sy = (int) wp->sy; assert(sy == nf*nx);
const int sf = (int) wp->sf; assert(sf == 1);
assert(fPre >= 0 && fPre <= 1);
assert(ny == 1);
assert(nf == 16);
// rule 16 (only 100 applies, left neighbor fires, I fire, all other patterns fire 0)
// left (post view) -> right (pre view) -> 100 -> 000
// loop over all post synaptic neurons in patch
// initialize connections of OFF and ON cells to 0
for (int f = 0; f < nf; f++) {
for (int j = 0; j < ny; j++) {
for (int i = 0; i < nx; i++) {
w[i*sx + j*sy + f*sf] = 0;
}
}
}
// now set the actual pattern for rule 16 (0 0 0 1 0 0 0 0)
// pre-synaptic neuron is an OFF cell
if (fPre == 0) {
for (int j = 0; j < ny; j++) {
// sub-rule 000 (first OFF cell fires)
int f = 0;
w[0*sx + j*sy + f*sf] = 1;
w[1*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 001 (second OFF cell fires)
f = 2;
w[1*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 010 (third OFF cell fires)
f = 4;
w[0*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 011 (fourth OFF cell fires)
f = 6;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 100 (fifth _ON_ cell fires)
f = 9;
w[0*sx + j*sy + f*sf] = 1;
w[1*sx + j*sy + f*sf] = 1;
// sub-rule 101 (six OFF cell fires)
f = 10;
w[1*sx + j*sy + f*sf] = 1;
// sub-rule 110 (seventh OFF cell fires)
f = 12;
w[0*sx + j*sy + f*sf] = 1;
// sub-rule 111 (eighth OFF cell fires)
f = 14;
}
}
// pre-synaptic neuron is an ON cell
if (fPre == 1) {
for (int j = 0; j < ny; j++) {
// sub-rule 000 (first OFF cell fires)
int f = 0;
// sub-rule 001 (second OFF cell fires)
f = 2;
w[0*sx + j*sy + f*sf] = 1;
// sub-rule 010 (third OFF cell fires)
f = 4;
w[1*sx + j*sy + f*sf] = 1;
// sub-rule 011 (fourth OFF cell fires)
f = 6;
w[0*sx + j*sy + f*sf] = 1;
w[1*sx + j*sy + f*sf] = 1;
// sub-rule 100 (fifth _ON_ cell fires)
f = 9;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 101 (six OFF cell fires)
f = 10;
w[0*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 110 (seventh OFF cell fires)
f = 12;
w[1*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 111 (eighth OFF cell fires)
f = 14;
w[0*sx + j*sy + f*sf] = 1;
w[1*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
}
}
for (int f = 0; f < nf; f++) {
float factor = strength;
for (int i = 0; i < nx*ny; i++) w[f + i*nf] *= factor;
}
return 0;
}
} // namespace PV
<commit_msg>Converted patch elements types to int from float.<commit_after>/*
* RuleConn.cpp
*
* Created on: Apr 5, 2009
* Author: rasmussn
*/
#include "RuleConn.hpp"
#include <assert.h>
#include <string.h>
namespace PV {
RuleConn::RuleConn(const char * name,
HyPerCol * hc, HyPerLayer * pre, HyPerLayer * post, int channel)
{
initialize_base();
initialize(name, hc, pre, post, channel, NULL);
}
int RuleConn::initializeWeights(const char * filename)
{
if (filename == NULL) {
PVParams * params = parent->parameters();
const float strength = params->value(name, "strength");
const int xScale = pre->clayer->xScale;
const int yScale = pre->clayer->yScale;
int nfPre = pre->clayer->numFeatures;
const int arbor = 0;
const int numPatches = numWeightPatches(arbor);
for (int i = 0; i < numPatches; i++) {
int fPre = i % nfPre;
ruleWeights(wPatches[arbor][i], fPre, xScale, yScale, strength);
}
}
else {
fprintf(stderr, "Initializing weights from a file not implemented for RuleConn\n");
exit(1);
} // end if for filename
return 0;
}
int RuleConn::ruleWeights(PVPatch * wp, int fPre, int xScale, int yScale, float strength)
{
pvdata_t * w = wp->data;
const int nx = wp->nx;
const int ny = wp->ny;
const int nf = wp->nf;
// strides
const int sx = wp->sx; assert(sx == nf);
const int sy = wp->sy; assert(sy == nf*nx);
const int sf = wp->sf; assert(sf == 1);
assert(fPre >= 0 && fPre <= 1);
assert(ny == 1);
assert(nf == 16);
// rule 16 (only 100 applies, left neighbor fires, I fire, all other patterns fire 0)
// left (post view) -> right (pre view) -> 100 -> 000
// loop over all post synaptic neurons in patch
// initialize connections of OFF and ON cells to 0
for (int f = 0; f < nf; f++) {
for (int j = 0; j < ny; j++) {
for (int i = 0; i < nx; i++) {
w[i*sx + j*sy + f*sf] = 0;
}
}
}
// now set the actual pattern for rule 16 (0 0 0 1 0 0 0 0)
// pre-synaptic neuron is an OFF cell
if (fPre == 0) {
for (int j = 0; j < ny; j++) {
// sub-rule 000 (first OFF cell fires)
int f = 0;
w[0*sx + j*sy + f*sf] = 1;
w[1*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 001 (second OFF cell fires)
f = 2;
w[1*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 010 (third OFF cell fires)
f = 4;
w[0*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 011 (fourth OFF cell fires)
f = 6;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 100 (fifth _ON_ cell fires)
f = 9;
w[0*sx + j*sy + f*sf] = 1;
w[1*sx + j*sy + f*sf] = 1;
// sub-rule 101 (six OFF cell fires)
f = 10;
w[1*sx + j*sy + f*sf] = 1;
// sub-rule 110 (seventh OFF cell fires)
f = 12;
w[0*sx + j*sy + f*sf] = 1;
// sub-rule 111 (eighth OFF cell fires)
f = 14;
}
}
// pre-synaptic neuron is an ON cell
if (fPre == 1) {
for (int j = 0; j < ny; j++) {
// sub-rule 000 (first OFF cell fires)
int f = 0;
// sub-rule 001 (second OFF cell fires)
f = 2;
w[0*sx + j*sy + f*sf] = 1;
// sub-rule 010 (third OFF cell fires)
f = 4;
w[1*sx + j*sy + f*sf] = 1;
// sub-rule 011 (fourth OFF cell fires)
f = 6;
w[0*sx + j*sy + f*sf] = 1;
w[1*sx + j*sy + f*sf] = 1;
// sub-rule 100 (fifth _ON_ cell fires)
f = 9;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 101 (six OFF cell fires)
f = 10;
w[0*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 110 (seventh OFF cell fires)
f = 12;
w[1*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
// sub-rule 111 (eighth OFF cell fires)
f = 14;
w[0*sx + j*sy + f*sf] = 1;
w[1*sx + j*sy + f*sf] = 1;
w[2*sx + j*sy + f*sf] = 1;
}
}
for (int f = 0; f < nf; f++) {
float factor = strength;
for (int i = 0; i < nx*ny; i++) w[f + i*nf] *= factor;
}
return 0;
}
} // namespace PV
<|endoftext|> |
<commit_before>
#include <iostream>
#include <lcm/lcm-cpp.hpp>
#include "lcmtypes/drc_lcmtypes.hpp"
#include "AffordanceCollectionListener.hpp"
using namespace std;
using namespace boost;
using namespace visualization_utils;
using namespace collision;
namespace renderer_affordances
{
//==================constructor / destructor
// AffordanceCollectionListener::AffordanceCollectionListener(boost::shared_ptr<lcm::LCM> &lcm, RendererAffordances* affordance_renderer):
// _lcm(lcm),
// _parent_affordance_renderer(affordance_renderer)
AffordanceCollectionListener::AffordanceCollectionListener( RendererAffordances* affordance_renderer):
_parent_affordance_renderer(affordance_renderer)
{
_lcm = affordance_renderer->lcm;
//lcm ok?
if(!_lcm->good())
{
cerr << "\nLCM Not Good: Robot State Handler" << endl;
return;
}
_lcm->subscribe("AFFORDANCE_COLLECTION", &AffordanceCollectionListener::handleAffordanceCollectionMsg, this);
_lcm->subscribe("AFFORDANCE", &AffordanceCollectionListener::handleAffordanceMsg, this);
_lcm->subscribe("AFFORDANCE_PLUS_COLLECTION", &AffordanceCollectionListener::handleAffordancePlusCollectionMsg, this);
_lcm->subscribe("AFFORDANCE_PLUS", &AffordanceCollectionListener::handleAffordancePlusMsg, this);
}
AffordanceCollectionListener::~AffordanceCollectionListener() {}
// =======================================================================
// message callbacks
// =======================================================================
// checks to see the affordances are in the parent renderer object list. If it is pre-existing
// it is updated and if its new a new instance is created.
void AffordanceCollectionListener::handleAffordanceCollectionMsg(const lcm::ReceiveBuffer* rbuf,
const string& chan,
const drc::affordance_collection_t* msg)
{
//cout << "Ok!: " << oss.str() << endl;
for (size_t i=0; i< (size_t)msg->naffs; i++)
{
const drc::affordance_t aff = msg->affs[i];
std::stringstream oss;
oss << aff.otdf_type << "_"<< aff.uid;
typedef std::map<std::string, OtdfInstanceStruc > object_instance_map_type_;
object_instance_map_type_::iterator it = _parent_affordance_renderer->instantiated_objects.find(oss.str());
if (it!=_parent_affordance_renderer->instantiated_objects.end()) {
//exists so update
//cout <<"updated_otdf_object_instance: "<< aff.otdf_type << " " << aff.uid << endl;
update_object_instance(aff);
}
else {
// add new otdf instance
std::string filename = aff.otdf_type;//get_filename(aff.otdf_id);
cout <<"add new otdf instance: "<< aff.otdf_type << "_"<< aff.uid << ", of template :" << filename << endl;
//std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
add_new_otdf_object_instance(filename, aff);
}
}
} // end handleMessage
void AffordanceCollectionListener::handleAffordancePlusCollectionMsg(const lcm::ReceiveBuffer* rbuf,
const string& chan,
const drc::affordance_plus_collection_t* msg)
{
for (size_t i=0; i< (size_t)msg->naffs; i++) {
const drc::affordance_plus_t& aff = msg->affs_plus[i];
handleAffordancePlusMsg(rbuf, chan, &aff);
}
}
// =======================================================================
void AffordanceCollectionListener::handleAffordanceMsg(const lcm::ReceiveBuffer* rbuf, const string& channel,
const drc::affordance_t* msg)
{
cout << "Received affordance: " << msg->otdf_type << " with uid: " << msg->uid << endl;
std::stringstream oss;
oss << msg->otdf_type << "_"<< msg->uid;
typedef std::map<std::string, OtdfInstanceStruc > object_instance_map_type_;
object_instance_map_type_::iterator it = _parent_affordance_renderer->instantiated_objects.find(oss.str());
if (it!=_parent_affordance_renderer->instantiated_objects.end()) {
//exists so update
cout <<"update_otdf_object_instance" << endl;
update_object_instance((*msg));
}
else{
// add new otdf instance
cout <<"add new otdf instance" << endl;
std::string filename = msg->otdf_type;//get_filename(msg->otdf_id);
add_new_otdf_object_instance(filename, (*msg));
}
}
void AffordanceCollectionListener::handleAffordancePlusMsg(const lcm::ReceiveBuffer* rbuf, const string& channel,
const drc::affordance_plus_t* msg)
{
// handle affordance
handleAffordanceMsg(rbuf,channel,&msg->aff);
// handle plus features
std::stringstream oss;
oss << msg->aff.otdf_type << "_"<< msg->aff.uid;
typedef std::map<std::string, OtdfInstanceStruc > object_instance_map_type_;
object_instance_map_type_::iterator it = _parent_affordance_renderer->instantiated_objects.find(oss.str());
if (it!=_parent_affordance_renderer->instantiated_objects.end()) {
std::vector<boost::shared_ptr<otdf::Link> > links;
it->second._otdf_instance->getLinks(links);
for(int i=0; i<links.size(); i++){
if(links[i]->visual && links[i]->visual->geometry){
cout << links[i]->visual->geometry->type << endl;
boost::shared_ptr<otdf::DynamicMesh> dmesh =
dynamic_pointer_cast<otdf::DynamicMesh>(links[i]->visual->geometry);
if(dmesh){
dmesh->points = msg->points;
dmesh->triangles = msg->triangles;
}
}
}
} else{
cout << "*** ERROR handleAffordancePlusMsg: shouldn't get here\n";
}
}
// =======================================================================
// Utils
// =======================================================================
/*std::string AffordanceCollectionListener::get_filename(int32_t otdf_id)
{
std::string filename;
//NOTE: Have to manually list all the otdf templates, not ideal.
//Much better if otdf_id is a string instead of a enumerated type.
if(otdf_id==drc::affordance_t::CYLINDER){
// check if cylinder exists in _parent_affordance_renderer->otdf_filenames
filename = "cylinder";
}
else if(otdf_id==drc::affordance_t::LEVER)
{
filename = "lever";
}
else if(otdf_id==drc::affordance_t::SPHERE)
{
filename = "sphere";
}
return filename;
}*/
// =======================================================================
void AffordanceCollectionListener::add_new_otdf_object_instance (std::string &filename, const drc::affordance_t &aff)
{
std::string xml_string;
if(!otdf::get_xml_string_from_file(filename, xml_string)){
return; // file extraction failed
}
OtdfInstanceStruc instance_struc;
instance_struc._otdf_instance = otdf::parseOTDF(xml_string);
if (!instance_struc._otdf_instance){
std::cerr << "ERROR: Model Parsing of " << filename << " the xml failed" << std::endl;
}
//instance_struc._otdf_instance->name_ = aff.name;
//set All Params
for (size_t i=0; i < (size_t)aff.nparams; i++)
{
instance_struc._otdf_instance->setParam(aff.param_names[i],aff.params[i]);
}
instance_struc._otdf_instance->update();
//TODO: set All JointStates too.
// create a KDL tree parser from OTDF instance, without having to convert to urdf.
// otdf can contain some elements that are not part of urdf. e.g. TORUS, DYNAMIC_MESH (They are handled as special cases)
std::string _urdf_xml_string = otdf::convertObjectInstanceToCompliantURDFstring(instance_struc._otdf_instance);
/*std::map<std::string, int >::iterator it;
it= _parent_affordance_renderer->instance_cnt.find(filename);
it->second = it->second + 1;*/
std::stringstream oss;
oss << aff.otdf_type << "_"<< aff.uid;
instance_struc.uid = aff.uid;
instance_struc.otdf_type = aff.otdf_type;
instance_struc._collision_detector.reset();
instance_struc._collision_detector = shared_ptr<Collision_Detector>(new Collision_Detector());
instance_struc._gl_object = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody(instance_struc._otdf_instance,instance_struc._collision_detector,true,oss.str()));
instance_struc._gl_object->set_state(instance_struc._otdf_instance);
//boost::shared_ptr<const otdf::BaseEntity> base = instance_struc._otdf_instance->getRoot();
//boost::shared_ptr<otdf::Link> link = dynamic_pointer_cast<otdf::Link>(instance_struc._otdf_instance->getRoot());
//->visual->geometry;
//_parent_affordance_renderer->instantiated_objects.insert(std::make_pair(oss.str(), instance_struc));
_parent_affordance_renderer->instantiated_objects.insert(std::make_pair(oss.str(), instance_struc));
// Update params
//Request redraw
bot_viewer_request_redraw(_parent_affordance_renderer->viewer);
}
// =======================================================================
void AffordanceCollectionListener::update_object_instance (const drc::affordance_t &aff)
{
std::stringstream oss;
oss << aff.otdf_type << "_"<< aff.uid;
typedef std::map<std::string, OtdfInstanceStruc > object_instance_map_type_;
object_instance_map_type_::iterator it = _parent_affordance_renderer->instantiated_objects.find(oss.str());
//set All Params
for (size_t i=0; i < (size_t)aff.nparams; i++)
{
it->second._otdf_instance->setParam(aff.param_names[i],aff.params[i]);
}
//TODO: set All JointStates too.
it->second._otdf_instance->update();
it->second._gl_object->set_state(it->second._otdf_instance);
//Request redraw
bot_viewer_request_redraw(_parent_affordance_renderer->viewer);
}
// =======================================================================
} //namespace affordance_renderer
<commit_msg>- added comments for code changes from previous commit<commit_after>
#include <iostream>
#include <lcm/lcm-cpp.hpp>
#include "lcmtypes/drc_lcmtypes.hpp"
#include "AffordanceCollectionListener.hpp"
using namespace std;
using namespace boost;
using namespace visualization_utils;
using namespace collision;
namespace renderer_affordances
{
//==================constructor / destructor
// AffordanceCollectionListener::AffordanceCollectionListener(boost::shared_ptr<lcm::LCM> &lcm, RendererAffordances* affordance_renderer):
// _lcm(lcm),
// _parent_affordance_renderer(affordance_renderer)
AffordanceCollectionListener::AffordanceCollectionListener( RendererAffordances* affordance_renderer):
_parent_affordance_renderer(affordance_renderer)
{
_lcm = affordance_renderer->lcm;
//lcm ok?
if(!_lcm->good())
{
cerr << "\nLCM Not Good: Robot State Handler" << endl;
return;
}
_lcm->subscribe("AFFORDANCE_COLLECTION", &AffordanceCollectionListener::handleAffordanceCollectionMsg, this);
_lcm->subscribe("AFFORDANCE", &AffordanceCollectionListener::handleAffordanceMsg, this);
_lcm->subscribe("AFFORDANCE_PLUS_COLLECTION", &AffordanceCollectionListener::handleAffordancePlusCollectionMsg, this);
_lcm->subscribe("AFFORDANCE_PLUS", &AffordanceCollectionListener::handleAffordancePlusMsg, this);
}
AffordanceCollectionListener::~AffordanceCollectionListener() {}
// =======================================================================
// message callbacks
// =======================================================================
// checks to see the affordances are in the parent renderer object list. If it is pre-existing
// it is updated and if its new a new instance is created.
void AffordanceCollectionListener::handleAffordanceCollectionMsg(const lcm::ReceiveBuffer* rbuf,
const string& chan,
const drc::affordance_collection_t* msg)
{
//cout << "Ok!: " << oss.str() << endl;
for (size_t i=0; i< (size_t)msg->naffs; i++)
{
const drc::affordance_t aff = msg->affs[i];
std::stringstream oss;
oss << aff.otdf_type << "_"<< aff.uid;
typedef std::map<std::string, OtdfInstanceStruc > object_instance_map_type_;
object_instance_map_type_::iterator it = _parent_affordance_renderer->instantiated_objects.find(oss.str());
if (it!=_parent_affordance_renderer->instantiated_objects.end()) {
//exists so update
//cout <<"updated_otdf_object_instance: "<< aff.otdf_type << " " << aff.uid << endl;
update_object_instance(aff);
}
else {
// add new otdf instance
std::string filename = aff.otdf_type;//get_filename(aff.otdf_id);
cout <<"add new otdf instance: "<< aff.otdf_type << "_"<< aff.uid << ", of template :" << filename << endl;
//std::transform(filename.begin(), filename.end(), filename.begin(), ::tolower);
add_new_otdf_object_instance(filename, aff);
}
}
} // end handleMessage
void AffordanceCollectionListener::handleAffordancePlusCollectionMsg(const lcm::ReceiveBuffer* rbuf,
const string& chan,
const drc::affordance_plus_collection_t* msg)
{
for (size_t i=0; i< (size_t)msg->naffs; i++) {
const drc::affordance_plus_t& aff = msg->affs_plus[i];
handleAffordancePlusMsg(rbuf, chan, &aff);
}
}
// =======================================================================
void AffordanceCollectionListener::handleAffordanceMsg(const lcm::ReceiveBuffer* rbuf, const string& channel,
const drc::affordance_t* msg)
{
cout << "Received affordance: " << msg->otdf_type << " with uid: " << msg->uid << endl;
std::stringstream oss;
oss << msg->otdf_type << "_"<< msg->uid;
typedef std::map<std::string, OtdfInstanceStruc > object_instance_map_type_;
object_instance_map_type_::iterator it = _parent_affordance_renderer->instantiated_objects.find(oss.str());
if (it!=_parent_affordance_renderer->instantiated_objects.end()) {
//exists so update
cout <<"update_otdf_object_instance" << endl;
update_object_instance((*msg));
}
else{
// add new otdf instance
cout <<"add new otdf instance" << endl;
std::string filename = msg->otdf_type;//get_filename(msg->otdf_id);
add_new_otdf_object_instance(filename, (*msg));
}
}
void AffordanceCollectionListener::handleAffordancePlusMsg(const lcm::ReceiveBuffer* rbuf, const string& channel,
const drc::affordance_plus_t* msg)
{
// handle affordance_t within affordance_plus_t message
handleAffordanceMsg(rbuf,channel,&msg->aff);
//////////////////////////
// handle plus features
// retrieve otdf object associates with current message
std::stringstream oss;
oss << msg->aff.otdf_type << "_"<< msg->aff.uid;
typedef std::map<std::string, OtdfInstanceStruc > object_instance_map_type_;
object_instance_map_type_::iterator it = _parent_affordance_renderer->instantiated_objects.find(oss.str());
if (it!=_parent_affordance_renderer->instantiated_objects.end()) {
// find links of type DynamicMesh and copy points and triangles into it.
std::vector<boost::shared_ptr<otdf::Link> > links;
it->second._otdf_instance->getLinks(links);
for(int i=0; i<links.size(); i++){
if(links[i]->visual && links[i]->visual->geometry){
cout << links[i]->visual->geometry->type << endl;
boost::shared_ptr<otdf::DynamicMesh> dmesh =
dynamic_pointer_cast<otdf::DynamicMesh>(links[i]->visual->geometry);
if(dmesh){
dmesh->points = msg->points;
dmesh->triangles = msg->triangles;
}
}
}
} else{
// object should always exist, so we should never get here
cout << "*** ERROR handleAffordancePlusMsg: shouldn't get here\n";
}
}
// =======================================================================
// Utils
// =======================================================================
/*std::string AffordanceCollectionListener::get_filename(int32_t otdf_id)
{
std::string filename;
//NOTE: Have to manually list all the otdf templates, not ideal.
//Much better if otdf_id is a string instead of a enumerated type.
if(otdf_id==drc::affordance_t::CYLINDER){
// check if cylinder exists in _parent_affordance_renderer->otdf_filenames
filename = "cylinder";
}
else if(otdf_id==drc::affordance_t::LEVER)
{
filename = "lever";
}
else if(otdf_id==drc::affordance_t::SPHERE)
{
filename = "sphere";
}
return filename;
}*/
// =======================================================================
void AffordanceCollectionListener::add_new_otdf_object_instance (std::string &filename, const drc::affordance_t &aff)
{
std::string xml_string;
if(!otdf::get_xml_string_from_file(filename, xml_string)){
return; // file extraction failed
}
OtdfInstanceStruc instance_struc;
instance_struc._otdf_instance = otdf::parseOTDF(xml_string);
if (!instance_struc._otdf_instance){
std::cerr << "ERROR: Model Parsing of " << filename << " the xml failed" << std::endl;
}
//instance_struc._otdf_instance->name_ = aff.name;
//set All Params
for (size_t i=0; i < (size_t)aff.nparams; i++)
{
instance_struc._otdf_instance->setParam(aff.param_names[i],aff.params[i]);
}
instance_struc._otdf_instance->update();
//TODO: set All JointStates too.
// create a KDL tree parser from OTDF instance, without having to convert to urdf.
// otdf can contain some elements that are not part of urdf. e.g. TORUS, DYNAMIC_MESH (They are handled as special cases)
std::string _urdf_xml_string = otdf::convertObjectInstanceToCompliantURDFstring(instance_struc._otdf_instance);
/*std::map<std::string, int >::iterator it;
it= _parent_affordance_renderer->instance_cnt.find(filename);
it->second = it->second + 1;*/
std::stringstream oss;
oss << aff.otdf_type << "_"<< aff.uid;
instance_struc.uid = aff.uid;
instance_struc.otdf_type = aff.otdf_type;
instance_struc._collision_detector.reset();
instance_struc._collision_detector = shared_ptr<Collision_Detector>(new Collision_Detector());
instance_struc._gl_object = shared_ptr<InteractableGlKinematicBody>(new InteractableGlKinematicBody(instance_struc._otdf_instance,instance_struc._collision_detector,true,oss.str()));
instance_struc._gl_object->set_state(instance_struc._otdf_instance);
//boost::shared_ptr<const otdf::BaseEntity> base = instance_struc._otdf_instance->getRoot();
//boost::shared_ptr<otdf::Link> link = dynamic_pointer_cast<otdf::Link>(instance_struc._otdf_instance->getRoot());
//->visual->geometry;
//_parent_affordance_renderer->instantiated_objects.insert(std::make_pair(oss.str(), instance_struc));
_parent_affordance_renderer->instantiated_objects.insert(std::make_pair(oss.str(), instance_struc));
// Update params
//Request redraw
bot_viewer_request_redraw(_parent_affordance_renderer->viewer);
}
// =======================================================================
void AffordanceCollectionListener::update_object_instance (const drc::affordance_t &aff)
{
std::stringstream oss;
oss << aff.otdf_type << "_"<< aff.uid;
typedef std::map<std::string, OtdfInstanceStruc > object_instance_map_type_;
object_instance_map_type_::iterator it = _parent_affordance_renderer->instantiated_objects.find(oss.str());
//set All Params
for (size_t i=0; i < (size_t)aff.nparams; i++)
{
it->second._otdf_instance->setParam(aff.param_names[i],aff.params[i]);
}
//TODO: set All JointStates too.
it->second._otdf_instance->update();
it->second._gl_object->set_state(it->second._otdf_instance);
//Request redraw
bot_viewer_request_redraw(_parent_affordance_renderer->viewer);
}
// =======================================================================
} //namespace affordance_renderer
<|endoftext|> |
<commit_before>#ifndef AX_DYNAMIC_MATRIX
#define AX_DYNAMIC_MATRIX
#include "DynamicMatrixExp.hpp"
#include <iostream>
#include <utility>
#include <vector>
namespace ax
{
class RealDynamicMatrix
{
public:
using value_trait = DynamicMatrix;
/* C x R matrix
C O L U M N s
R ( M_00 M_01 ... M_0C )
O ( M_10 . . )
W ( ... . . )
s ( M_R0 ... M_RC )
*/
public:
RealDynamicMatrix(){};
~RealDynamicMatrix() = default;
RealDynamicMatrix(const std::size_t Row, const std::size_t Col)
: values_(Row, std::vector<double>(Col, 0e0))
{}
RealDynamicMatrix(const std::vector<std::vector<double>>& val)
: values_(val)
{
if(val.empty()) throw std::invalid_argument("empty data");
if(val.at(0).empty()) throw std::invalid_argument("empty data");
const std::size_t col_size = val.at(0).size();
for(auto iter = val.cbegin(); iter != val.cend(); ++iter)
if(iter->size() != col_size)
throw std::invalid_argument("invalid size");
}
RealDynamicMatrix(const RealDynamicMatrix& mat)
: values_(mat.values_)
{}
RealDynamicMatrix(RealDynamicMatrix&& mat)
: values_(std::move(mat.values_))
{}
template<class E,
typename std::enable_if<
is_DynamicMatrixExpression<typename E::value_trait>::value
>::type*& = enabler>
RealDynamicMatrix(const E& exp)
: values_(exp.size_row(), std::vector<double>(exp.size_col(), 0e0))
{
for(auto i=0; i<exp.size_row(); ++i)
for(auto j=0; j<exp.size_col(); ++j)
(*this)(i, j) = exp(i, j);
}
template<class E,
typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value
>::type*& = enabler>
RealDynamicMatrix(const E& exp)
: values_(E::row, std::vector<double>(E::col, 0e0))
{
for(auto i=0; i<E::row; ++i)
for(auto j=0; j<E::col; ++j)
(*this)(i, j) = exp(i, j);
}
// operator =
RealDynamicMatrix& operator=(const RealDynamicMatrix& mat)
{
values_ = mat.values_;
return *this;
}
template<class E, typename std::enable_if<
is_DynamicMatrixExpression<typename E::value_trait>::value
>::type*& = enabler>
RealDynamicMatrix& operator=(const E& exp)
{
if(exp.size_row() != this->size_row() ||
exp.size_col() != this->size_col())
{
throw std::invalid_argument("different size matrix");
}
for(auto i=0; i<exp.size_row(); ++i)
for(auto j=0; j<exp.size_col(); ++j)
this->values_.at(i).at(j) = exp(i, j);
return *this;
}
template<class E, typename std::enable_if<
is_MatrixExpression<typename E::value_trait>::value
>::type*& = enabler>
RealDynamicMatrix& operator=(const E& exp)
{
if(E::row != this->size_row() || E::col != this->size_col())
{
throw std::invalid_argument("different size matrix");
}
for(auto i=0; i<E::row; ++i)
for(auto j=0; j<E::col; ++j)
this->values_.at(i).at(j) = exp(i,j);
return *this;
}
const double operator()(const std::size_t i, const std::size_t j) const
{
return values_[i][j];
}
double& operator()(const std::size_t i, const std::size_t j)
{
return values_[i][j];
}
const double at(const std::size_t i, const std::size_t j) const
{
return values_.at(i).at(j);
}
double& at(const std::size_t i, const std::size_t j)
{
return values_.at(i).at(j);
}
const std::size_t size_row() const
{
return values_.size();
}
const std::size_t size_col() const
{
return values_.at(0).size();
}
private:
std::vector<std::vector<double>> values_;
};
}
#endif /* AX_DYNAMIC_MATRIX */
<commit_msg>change dynamic_matrix<commit_after>#ifndef AX_DYNAMIC_MATRIX
#define AX_DYNAMIC_MATRIX
#include "MatrixExpression.hpp"
#include <vector>
#include <stdexcept>
namespace ax
{
/* C x R matrix
C O L U M N s
R ( M_00 M_01 ... M_0C )
O ( M_10 . . )
W ( ... . . )
s ( M_R0 ... M_RC ) */
template <typename T_elem, dimension_type I_row, dimension_type I_col,
typename std::enable_if<is_dynamic_dimension<I_row>::value&&
is_dynamic_dimension<I_col>::value>::type*& = enabler>
class Matrix
{
public:
using tag = matrix_tag;
using elem_t = T_elem;
constexpr static dimension_type dim_row = I_row;//number of row
constexpr static dimension_type dim_col = I_col;//number of column
using nest_container_type = std::vector<elem_t>;
using container_type = std::vector<nest_container_type>;
using self_type = Matrix<elem_t, dim_row, dim_col>;
public:
Matrix(){}
~Matrix() = default;
Matrix(const std::size_t Row, const std::size_t Col)
: values_(Row, std::vector<double>(Col, 0e0))
{}
Matrix(const std::vector<std::vector<double>>& val): values_(val)
{}
Matrix(const Matrix<elem_t, dim_row, dim_col>& mat)
: values_(mat.values_)
{}
Matrix(Matrix<elem_t, dim_row, dim_col>&& mat)
: values_(std::move(mat.values_))
{}
template<class T_expr, typename std::enable_if<
is_matrix_expression<typename T_expr::tag>::value&&
std::is_same<elem_t, typename T_expr::elem_t>::value
>::type*& = enabler>
Matrix(const T_expr& expr)
: values_(dimension_row(expr), nest_container_type(dimension_col(expr), 0e0))
{
for(auto i=0; i<dimension_row(expr); ++i)
for(auto j=0; j<dimension_col(expr); ++j)
(*this)(i, j) = expr(i, j);
}
// operator =
self_type& operator=(const self_type& mat)
{
this->values_ = mat.values_;
return *this;
}
template<class T_expr, typename std::enable_if<
is_matrix_expression<typename T_expr::tag>::value&&
std::is_same<elem_t, typename T_expr::elem_t>::value
>::type*& = enabler>
self_type& operator=(const T_expr& expr)
{
if(dimension_row(expr) != this->size_row() ||
dimension_col(expr) != this->size_col())
throw std::invalid_argument("different size matrix");
for(std::size_t i = 0; i<dimension_row(expr); ++i)
for(auto j=0; j<dimension_col(expr); ++j)
this->values_.at(i).at(j) = expr(i, j);
return *this;
}
template<class T_expr, typename std::enable_if<
is_matrix_expression<typename T_expr::tag>::value&&
std::is_same<elem_t, typename T_expr::elem_t>::value
>::type*& = enabler>
self_type& operator+=(const T_expr& expr)
{
return *this = (*this + expr);
}
template<class T_expr, typename std::enable_if<
is_matrix_expression<typename T_expr::tag>::value&&
std::is_same<elem_t, typename T_expr::elem_t>::value
>::type*& = enabler>
self_type& operator-=(const T_expr& expr)
{
return *this = (*this - expr);
}
self_type& operator*=(const elem_t& scl)
{
return *this = (*this * scl);
}
self_type& operator/=(const elem_t& scl)
{
return *this = (*this / scl);
}
elem_t const& operator()(const std::size_t i, const std::size_t j) const
{
return values_[i][j];
}
elem_t& operator()(const std::size_t i, const std::size_t j)
{
return values_[i][j];
}
elem_t const& at(const std::size_t i, const std::size_t j) const
{
return values_.at(i).at(j);
}
elem_t& at(const std::size_t i, const std::size_t j)
{
return values_.at(i).at(j);
}
std::size_t size_row() const {return values_.size();}
std::size_t size_col() const {return values_.front().size();}
private:
container_type values_;
};
}
#endif /* AX_DYNAMIC_MATRIX */
<|endoftext|> |
<commit_before>/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) CERN 2019
* Author: Georgios Bitzes <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "ContentProvider.hpp"
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
namespace Davix {
//------------------------------------------------------------------------------
// Empty constructor
//------------------------------------------------------------------------------
ContentProvider::ContentProvider() {
_errc = 0;
}
//------------------------------------------------------------------------------
// Is the object ok?
//------------------------------------------------------------------------------
bool ContentProvider::ok() const {
return (_errc == 0);
}
//------------------------------------------------------------------------------
// Has there been an error?
//------------------------------------------------------------------------------
int ContentProvider::getErrc() const {
return _errc;
}
//------------------------------------------------------------------------------
// Get error message
//------------------------------------------------------------------------------
std::string ContentProvider::getError() const {
return _errMsg;
}
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
BufferContentProvider::BufferContentProvider(const char* buf, size_t count)
: _buffer(buf), _count(count), _pos(0) {}
//------------------------------------------------------------------------------
// pullBytes implementation.
//------------------------------------------------------------------------------
ssize_t BufferContentProvider::pullBytes(char* target, size_t requestedBytes) {
if(_pos >= _count) {
// EOF
return 0;
}
size_t bytesToGive = requestedBytes;
if(_pos + bytesToGive > _count) {
// Asked for more bytes than we have, just give all remaining ones
bytesToGive = _count - _pos;
}
::memcpy(target, _buffer + _pos, bytesToGive);
_pos += bytesToGive;
return bytesToGive;
}
//------------------------------------------------------------------------------
// Rewind implementation.
//------------------------------------------------------------------------------
bool BufferContentProvider::rewind() {
_pos = 0;
return true;
}
//------------------------------------------------------------------------------
// getSize implementation.
//------------------------------------------------------------------------------
ssize_t BufferContentProvider::getSize() {
return _count;
}
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
OwnedBufferContentProvider::OwnedBufferContentProvider(const char* buf, size_t count)
: _provider(NULL, 0) {
_contents.resize(count);
::memcpy( (void*) _contents.data(), buf, count);
_provider = BufferContentProvider(_contents.c_str(), _contents.size());
}
//----------------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------------
OwnedBufferContentProvider::OwnedBufferContentProvider(const std::string &str)
: OwnedBufferContentProvider(str.c_str(), str.size()) {}
//------------------------------------------------------------------------------
// pullBytes implementation.
//------------------------------------------------------------------------------
ssize_t OwnedBufferContentProvider::pullBytes(char* target, size_t requestedBytes) {
return _provider.pullBytes(target, requestedBytes);
}
//------------------------------------------------------------------------------
// Rewind implementation.
//------------------------------------------------------------------------------
bool OwnedBufferContentProvider::rewind() {
return _provider.rewind();
}
//------------------------------------------------------------------------------
// getSize implementation.
//------------------------------------------------------------------------------
ssize_t OwnedBufferContentProvider::getSize() {
return _provider.getSize();
}
//------------------------------------------------------------------------------
// FdContentProvider constructor
//------------------------------------------------------------------------------
FdContentProvider::FdContentProvider(int fd) : _fd(fd) {
_fd_size = ::lseek(_fd, 0, SEEK_END);
if(_fd_size == -1) {
_errc = errno;
_errMsg = strerror(_errc);
}
else {
rewind();
}
}
//------------------------------------------------------------------------------
// pullBytes implementation.
//------------------------------------------------------------------------------
ssize_t FdContentProvider::pullBytes(char* target, size_t requestedBytes) {
if(!ok()) {
return - _errc;
}
while(true) {
ssize_t retval = ::read(_fd, target, requestedBytes);
if(retval >= 0) {
// No errors
return retval;
}
else if(retval == -1 && errno == EINTR) {
// Interrupted by a signal... retry...
continue;
}
else {
// Error
_errc = errno;
_errMsg = strerror(_errc);
return - _errc;
}
}
}
//------------------------------------------------------------------------------
// Rewind implementation.
//------------------------------------------------------------------------------
bool FdContentProvider::rewind() {
if(!ok()) {
return false;
}
off_t retval = ::lseek(_fd, 0, SEEK_SET);
if(retval == -1) {
_errc = errno;
_errMsg = strerror(_errc);
return false;
}
return true;
}
//------------------------------------------------------------------------------
// getSize implementation.
//------------------------------------------------------------------------------
ssize_t FdContentProvider::getSize() {
return _fd_size;
}
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
CallbackContentProvider::CallbackContentProvider(HttpBodyProvider provider, dav_size_t len,
void *udata) : _provider(provider), _len(len), _udata(udata) {}
//------------------------------------------------------------------------------
// pullBytes implementation.
//------------------------------------------------------------------------------
ssize_t CallbackContentProvider::pullBytes(char* target, size_t requestedBytes) {
if(!ok()) {
return - _errc;
}
if(requestedBytes == 0) {
return 0;
}
ssize_t retval = _provider(_udata, target, requestedBytes);
if(retval < 0) {
_errc = -retval;
_errMsg = strerror(_errc);
return -_errc;
}
return retval;
}
//------------------------------------------------------------------------------
// Rewind implementation.
//------------------------------------------------------------------------------
bool CallbackContentProvider::rewind() {
if(!ok()) {
return false;
}
_provider(_udata, 0, 0);
return true;
}
//------------------------------------------------------------------------------
// getSize implementation.
//------------------------------------------------------------------------------
ssize_t CallbackContentProvider::getSize() {
return _len;
}
}
<commit_msg>Fix compilation on SLC6, don't use delegating construction<commit_after>/*
* This File is part of Davix, The IO library for HTTP based protocols
* Copyright (C) CERN 2019
* Author: Georgios Bitzes <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "ContentProvider.hpp"
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
namespace Davix {
//------------------------------------------------------------------------------
// Empty constructor
//------------------------------------------------------------------------------
ContentProvider::ContentProvider() {
_errc = 0;
}
//------------------------------------------------------------------------------
// Is the object ok?
//------------------------------------------------------------------------------
bool ContentProvider::ok() const {
return (_errc == 0);
}
//------------------------------------------------------------------------------
// Has there been an error?
//------------------------------------------------------------------------------
int ContentProvider::getErrc() const {
return _errc;
}
//------------------------------------------------------------------------------
// Get error message
//------------------------------------------------------------------------------
std::string ContentProvider::getError() const {
return _errMsg;
}
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
BufferContentProvider::BufferContentProvider(const char* buf, size_t count)
: _buffer(buf), _count(count), _pos(0) {}
//------------------------------------------------------------------------------
// pullBytes implementation.
//------------------------------------------------------------------------------
ssize_t BufferContentProvider::pullBytes(char* target, size_t requestedBytes) {
if(_pos >= _count) {
// EOF
return 0;
}
size_t bytesToGive = requestedBytes;
if(_pos + bytesToGive > _count) {
// Asked for more bytes than we have, just give all remaining ones
bytesToGive = _count - _pos;
}
::memcpy(target, _buffer + _pos, bytesToGive);
_pos += bytesToGive;
return bytesToGive;
}
//------------------------------------------------------------------------------
// Rewind implementation.
//------------------------------------------------------------------------------
bool BufferContentProvider::rewind() {
_pos = 0;
return true;
}
//------------------------------------------------------------------------------
// getSize implementation.
//------------------------------------------------------------------------------
ssize_t BufferContentProvider::getSize() {
return _count;
}
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
OwnedBufferContentProvider::OwnedBufferContentProvider(const char* buf, size_t count)
: _provider(NULL, 0) {
_contents.resize(count);
::memcpy( (void*) _contents.data(), buf, count);
_provider = BufferContentProvider(_contents.c_str(), _contents.size());
}
//----------------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------------
OwnedBufferContentProvider::OwnedBufferContentProvider(const std::string &str)
: _provider(NULL, 0) {
_contents = str;
_provider = BufferContentProvider(_contents.c_str(), _contents.size());
}
//------------------------------------------------------------------------------
// pullBytes implementation.
//------------------------------------------------------------------------------
ssize_t OwnedBufferContentProvider::pullBytes(char* target, size_t requestedBytes) {
return _provider.pullBytes(target, requestedBytes);
}
//------------------------------------------------------------------------------
// Rewind implementation.
//------------------------------------------------------------------------------
bool OwnedBufferContentProvider::rewind() {
return _provider.rewind();
}
//------------------------------------------------------------------------------
// getSize implementation.
//------------------------------------------------------------------------------
ssize_t OwnedBufferContentProvider::getSize() {
return _provider.getSize();
}
//------------------------------------------------------------------------------
// FdContentProvider constructor
//------------------------------------------------------------------------------
FdContentProvider::FdContentProvider(int fd) : _fd(fd) {
_fd_size = ::lseek(_fd, 0, SEEK_END);
if(_fd_size == -1) {
_errc = errno;
_errMsg = strerror(_errc);
}
else {
rewind();
}
}
//------------------------------------------------------------------------------
// pullBytes implementation.
//------------------------------------------------------------------------------
ssize_t FdContentProvider::pullBytes(char* target, size_t requestedBytes) {
if(!ok()) {
return - _errc;
}
while(true) {
ssize_t retval = ::read(_fd, target, requestedBytes);
if(retval >= 0) {
// No errors
return retval;
}
else if(retval == -1 && errno == EINTR) {
// Interrupted by a signal... retry...
continue;
}
else {
// Error
_errc = errno;
_errMsg = strerror(_errc);
return - _errc;
}
}
}
//------------------------------------------------------------------------------
// Rewind implementation.
//------------------------------------------------------------------------------
bool FdContentProvider::rewind() {
if(!ok()) {
return false;
}
off_t retval = ::lseek(_fd, 0, SEEK_SET);
if(retval == -1) {
_errc = errno;
_errMsg = strerror(_errc);
return false;
}
return true;
}
//------------------------------------------------------------------------------
// getSize implementation.
//------------------------------------------------------------------------------
ssize_t FdContentProvider::getSize() {
return _fd_size;
}
//------------------------------------------------------------------------------
// Constructor
//------------------------------------------------------------------------------
CallbackContentProvider::CallbackContentProvider(HttpBodyProvider provider, dav_size_t len,
void *udata) : _provider(provider), _len(len), _udata(udata) {}
//------------------------------------------------------------------------------
// pullBytes implementation.
//------------------------------------------------------------------------------
ssize_t CallbackContentProvider::pullBytes(char* target, size_t requestedBytes) {
if(!ok()) {
return - _errc;
}
if(requestedBytes == 0) {
return 0;
}
ssize_t retval = _provider(_udata, target, requestedBytes);
if(retval < 0) {
_errc = -retval;
_errMsg = strerror(_errc);
return -_errc;
}
return retval;
}
//------------------------------------------------------------------------------
// Rewind implementation.
//------------------------------------------------------------------------------
bool CallbackContentProvider::rewind() {
if(!ok()) {
return false;
}
_provider(_udata, 0, 0);
return true;
}
//------------------------------------------------------------------------------
// getSize implementation.
//------------------------------------------------------------------------------
ssize_t CallbackContentProvider::getSize() {
return _len;
}
}
<|endoftext|> |
<commit_before>#include <GLUL/G2D/Line.h>
#include <GLUL/G2D/Quad.h>
#include <glm/geometric.hpp>
namespace GLUL {
namespace G2D {
Line::Line(unsigned int thickness) {
setThickness(thickness);
}
Line::Line(const Point& point1, const Point& point2, unsigned int thickness) {
points[0] = point1;
points[1] = point2;
setThickness(thickness);
}
Line::Line(const glm::vec2& position1, const glm::vec2& position2, unsigned int thickness)
: Line(Point { position1 }, Point { position2 }, thickness) { }
void Line::setColor(const glm::vec4& color) {
for(auto& point : points)
point.setColor(color);
}
const glm::vec4& Line::getColor() const {
return points[0].getColor();
}
void Line::setThickness(unsigned int thickness) {
for(auto& point : points)
point.size = thickness;
}
void Line::_pushToBatch(GeometryBatch& geometryBatch) const {
Quad quad;
Point point1 = points[0];
Point point2 = points[1];
{
// Make sure point1 is on left of (or exactly under) point2
const glm::vec2& pos1 = point1.getPosition();
const glm::vec2& pos2 = point2.getPosition();
if(pos1.x > pos2.x || (pos1.x == pos2.x && pos1.y > pos2.y))
std::swap(point1, point2);
}
std::array<Point, 4> qPoints = { point1, point2, point2, point1 };
glm::vec2 lineVector = glm::normalize(point2.getPosition() - point1.getPosition());
glm::vec2 perpendicularLineVector = { -lineVector.y, lineVector.x };
qPoints[0].setPosition(point1.getPosition() - (perpendicularLineVector * static_cast<float>(point1.size / 2)));
qPoints[1].setPosition(point2.getPosition() - (perpendicularLineVector * static_cast<float>(point2.size / 2)));
qPoints[2].setPosition(point2.getPosition() + (perpendicularLineVector * static_cast<float>(point2.size - (point2.size / 2))));
qPoints[3].setPosition(point1.getPosition() + (perpendicularLineVector * static_cast<float>(point1.size - (point1.size / 2))));
quad.points = qPoints;
geometryBatch.addPrimitive(quad);
}
}
}
<commit_msg>Fixed clang's warning.<commit_after>#include <GLUL/G2D/Line.h>
#include <GLUL/G2D/Quad.h>
#include <glm/geometric.hpp>
namespace GLUL {
namespace G2D {
Line::Line(unsigned int thickness) {
setThickness(thickness);
}
Line::Line(const Point& point1, const Point& point2, unsigned int thickness) {
points[0] = point1;
points[1] = point2;
setThickness(thickness);
}
Line::Line(const glm::vec2& position1, const glm::vec2& position2, unsigned int thickness)
: Line(Point { position1 }, Point { position2 }, thickness) { }
void Line::setColor(const glm::vec4& color) {
for(auto& point : points)
point.setColor(color);
}
const glm::vec4& Line::getColor() const {
return points[0].getColor();
}
void Line::setThickness(unsigned int thickness) {
for(auto& point : points)
point.size = thickness;
}
void Line::_pushToBatch(GeometryBatch& geometryBatch) const {
Quad quad;
Point point1 = points[0];
Point point2 = points[1];
{
// Make sure point1 is on left of (or exactly under) point2
const glm::vec2& pos1 = point1.getPosition();
const glm::vec2& pos2 = point2.getPosition();
if(pos1.x > pos2.x || (pos1.x == pos2.x && pos1.y > pos2.y))
std::swap(point1, point2);
}
std::array<Point, 4> qPoints { { point1, point2, point2, point1 } };
glm::vec2 lineVector = glm::normalize(point2.getPosition() - point1.getPosition());
glm::vec2 perpendicularLineVector = { -lineVector.y, lineVector.x };
qPoints[0].setPosition(point1.getPosition() - (perpendicularLineVector * static_cast<float>(point1.size / 2)));
qPoints[1].setPosition(point2.getPosition() - (perpendicularLineVector * static_cast<float>(point2.size / 2)));
qPoints[2].setPosition(point2.getPosition() + (perpendicularLineVector * static_cast<float>(point2.size - (point2.size / 2))));
qPoints[3].setPosition(point1.getPosition() + (perpendicularLineVector * static_cast<float>(point1.size - (point1.size / 2))));
quad.points = qPoints;
geometryBatch.addPrimitive(quad);
}
}
}
<|endoftext|> |
<commit_before>
#pragma once
#include "ChatEnums.hpp"
#include "NodeClient.hpp"
#include "SQLite3.hpp"
#include "easylogging++.h"
class ChatAvatar;
class ChatAvatarService;
class ChatRoom;
class ChatRoomService;
class GatewayNode;
class PersistentMessageService;
class UdpConnection;
struct PersistentHeader;
struct ReqSetAvatarAttributes;
struct ReqGetAnyAvatar;
class GatewayClient : public NodeClient {
public:
GatewayClient(UdpConnection* connection, GatewayNode* node);
virtual ~GatewayClient();
GatewayNode* GetNode() { return node_; }
void SendFriendLoginUpdate(const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar);
void SendFriendLoginUpdates(const ChatAvatar* avatar);
void SendFriendLogoutUpdates(const ChatAvatar* avatar);
void SendDestroyRoomUpdate(const ChatAvatar* srcAvatar, uint32_t roomId, std::vector<std::u16string> targets);
void SendInstantMessageUpdate(const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar, const std::u16string& message, const std::u16string& oob);
void SendRoomMessageUpdate(const ChatAvatar* srcAvatar, const ChatRoom* room, uint32_t messageId, const std::u16string& message, const std::u16string& oob);
void SendEnterRoomUpdate(const ChatAvatar* srcAvatar, const ChatRoom* room);
void SendLeaveRoomUpdate(const std::vector<std::u16string>& addresses, uint32_t srcAvatarId, uint32_t roomId);
void SendPersistentMessageUpdate(const ChatAvatar* destAvatar, const PersistentHeader& header);
void SendKickAvatarUpdate(const std::vector<std::u16string>& addresses, const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar, const ChatRoom* room);
private:
void OnIncoming(std::istringstream& istream) override;
template<typename HandlerT, typename StreamT>
void HandleIncomingMessage(StreamT& istream) {
typedef typename HandlerT::RequestType RequestT;
typedef typename HandlerT::ResponseType ResponseT;
RequestT request;
read(istream, request);
ResponseT response(request.track);
try {
HandlerT(this, request, response);
} catch (const ChatResultException& e) {
response.result = e.code;
LOG(ERROR) << "ChatAPI Error: [" << ToString(e.code) << "] " << e.message;
} catch (const SQLite3Exception& e) {
response.result = ChatResultCode::DATABASE;
LOG(ERROR) << "Database Error: [" << e.code << "] " << e.message;
}
Send(response);
}
GatewayNode* node_;
ChatAvatarService* avatarService_;
ChatRoomService* roomService_;
PersistentMessageService* messageService_;
};
<commit_msg>Updated this to say just that it is an exceptional situation as not all exceptions thrown are errors, they are just exceptional situations (ie, not the success path).<commit_after>
#pragma once
#include "ChatEnums.hpp"
#include "NodeClient.hpp"
#include "SQLite3.hpp"
#include "easylogging++.h"
class ChatAvatar;
class ChatAvatarService;
class ChatRoom;
class ChatRoomService;
class GatewayNode;
class PersistentMessageService;
class UdpConnection;
struct PersistentHeader;
struct ReqSetAvatarAttributes;
struct ReqGetAnyAvatar;
class GatewayClient : public NodeClient {
public:
GatewayClient(UdpConnection* connection, GatewayNode* node);
virtual ~GatewayClient();
GatewayNode* GetNode() { return node_; }
void SendFriendLoginUpdate(const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar);
void SendFriendLoginUpdates(const ChatAvatar* avatar);
void SendFriendLogoutUpdates(const ChatAvatar* avatar);
void SendDestroyRoomUpdate(const ChatAvatar* srcAvatar, uint32_t roomId, std::vector<std::u16string> targets);
void SendInstantMessageUpdate(const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar, const std::u16string& message, const std::u16string& oob);
void SendRoomMessageUpdate(const ChatAvatar* srcAvatar, const ChatRoom* room, uint32_t messageId, const std::u16string& message, const std::u16string& oob);
void SendEnterRoomUpdate(const ChatAvatar* srcAvatar, const ChatRoom* room);
void SendLeaveRoomUpdate(const std::vector<std::u16string>& addresses, uint32_t srcAvatarId, uint32_t roomId);
void SendPersistentMessageUpdate(const ChatAvatar* destAvatar, const PersistentHeader& header);
void SendKickAvatarUpdate(const std::vector<std::u16string>& addresses, const ChatAvatar* srcAvatar, const ChatAvatar* destAvatar, const ChatRoom* room);
private:
void OnIncoming(std::istringstream& istream) override;
template<typename HandlerT, typename StreamT>
void HandleIncomingMessage(StreamT& istream) {
typedef typename HandlerT::RequestType RequestT;
typedef typename HandlerT::ResponseType ResponseT;
RequestT request;
read(istream, request);
ResponseT response(request.track);
try {
HandlerT(this, request, response);
} catch (const ChatResultException& e) {
response.result = e.code;
LOG(ERROR) << "ChatAPI Result Exception: [" << ToString(e.code) << "] " << e.message;
} catch (const SQLite3Exception& e) {
response.result = ChatResultCode::DATABASE;
LOG(ERROR) << "Database Error: [" << e.code << "] " << e.message;
}
Send(response);
}
GatewayNode* node_;
ChatAvatarService* avatarService_;
ChatRoomService* roomService_;
PersistentMessageService* messageService_;
};
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009 Gregory Haynes <[email protected]>
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "documentviewinternal.h"
#include "documentview.h"
#include "documentcontroller.h"
#include "document.h"
#include "renderer.h"
#include <QPaintEvent>
#include <QPainter>
#include <QResizeEvent>
#include <QWheelEvent>
#include <QFontMetrics>
#include <QTimer>
#include <QCursor>
#include <QMouseEvent>
#include <QRect>
#include <QDebug>
#include "documentviewinternal.moc"
namespace QSourceView
{
class TextCursor
: public DocumentPosition
{
public:
TextCursor();
bool is_visible;
};
TextCursor::TextCursor()
: DocumentPosition(0, 0)
, is_visible(false)
{
}
DocumentViewInternal::DocumentViewInternal(DocumentView &parentView,
Renderer &renderer)
: QWidget(&parentView)
, m_view(&parentView)
, m_renderer(&renderer)
, m_startX(0)
, m_startY(0)
, m_caret(new TextCursor)
{
setAttribute(Qt::WA_OpaquePaintEvent);
setFocusPolicy(Qt::ClickFocus);
setCursor(Qt::IBeamCursor);
QTimer *caretTimer = new QTimer(this);
caretTimer->setSingleShot(false);
connect(caretTimer, SIGNAL(timeout()),
this, SLOT(toggleCaretVisibility()));
caretTimer->start(500);
}
int DocumentViewInternal::startX() const
{
return m_startX;
}
int DocumentViewInternal::startY() const
{
return m_startY;
}
int DocumentViewInternal::endY() const
{
return m_view->document().lineCount() * fontMetrics().height();
}
const DocumentPosition &DocumentViewInternal::caretPosition() const
{
return *m_caret;
}
void DocumentViewInternal::setCaretPosition(const DocumentPosition &pos)
{
m_caret->setLine(pos.line());
m_caret->setColumn(pos.column());
}
void DocumentViewInternal::setStartX(int x)
{
if(x < 0)
m_startX = 0;
else
m_startX = x;
update();
}
void DocumentViewInternal::setStartY(int y)
{
if(y < 0)
m_startY = 0;
else if(y > endY() - height())
m_startY = endY() - height();
else
m_startY = y;
update();
emit(startYChanged(m_startY));
}
void DocumentViewInternal::paintEvent(QPaintEvent *event)
{
QRect rect = event->rect();
QPainter paint(this);
unsigned int fontHeight = fontMetrics().height();
int lineYStart = (startY() % fontHeight);
int lineNumStart = lineAt(startY());
int numLines = (height() / fontHeight) + 2;
int i;
// Paint the text
Document *doc = &m_view->document();
for(i = 0;i < numLines;i++,lineNumStart++)
{
QRect bound = QRect(0, (i*fontHeight) - lineYStart, rect.width(), fontHeight);
paint.fillRect(bound, Qt::white);
paint.drawText(bound, doc->text(lineNumStart));
}
paintCaret(paint);
}
void DocumentViewInternal::resizeEvent(QResizeEvent *event)
{
emit(sizeChanged(event->size().width(), event->size().height()));
}
void DocumentViewInternal::keyPressEvent(QKeyEvent *event)
{
m_view->controller().keyPressEvent(event);
}
void DocumentViewInternal::mousePressEvent(QMouseEvent *event)
{
unsigned int pressLine = lineAt(event->y()+startY());
unsigned int pressColumn;
if(pressLine >= m_view->document().lineCount())
{
pressLine = m_view->document().lineCount()-1;
}
QString line = m_view->document().text(pressLine);
// Find the column were at
int i;
for(i = 0;i < line.size();i++)
{
if(event->x() <= fontMetrics().width(line.left(i+1)))
break;
}
pressColumn = i;
m_caret->setLine(pressLine);
m_caret->setColumn(pressColumn);
m_caret->is_visible = true;
update();
}
void DocumentViewInternal::wheelEvent(QWheelEvent *event)
{
event->ignore();
if(event->orientation() == Qt::Vertical)
{
setStartY(startY() - (event->delta() / 30));
}
}
void DocumentViewInternal::paintCaret(QPainter &paint)
{
unsigned int startLine = lineAt(startY());
if(startLine > m_caret->line()
|| lineAt(startY()+height()) <= m_caret->line())
return;
// Text printed infront of cursor
QString prevline = m_view->document().text(m_caret->line()).left(m_caret->column());
int xStart = fontMetrics().width(prevline);
QRect bound = QRect(xStart, (fontMetrics().height()*m_caret->line()) - startY(), 1, fontMetrics().height());
if(m_caret->is_visible)
{
if(m_caret->column() >= (unsigned int)m_view->document().text(m_caret->line()).size())
paint.fillRect(bound, Qt::white);
else
paint.drawText(bound, QString(m_view->document().text(m_caret->line())[m_caret->column()]));
}
else
{
paint.fillRect(bound, Qt::black);
}
}
void DocumentViewInternal::toggleCaretVisibility()
{
m_caret->is_visible = !m_caret->is_visible;
update();
}
unsigned int DocumentViewInternal::lineAt(unsigned int x) const
{
return x / fontMetrics().height();
}
}
<commit_msg>Fixed vertical wheel event bug on documents less than window size<commit_after>/*
* Copyright (C) 2009 Gregory Haynes <[email protected]>
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "documentviewinternal.h"
#include "documentview.h"
#include "documentcontroller.h"
#include "document.h"
#include "renderer.h"
#include <QPaintEvent>
#include <QPainter>
#include <QResizeEvent>
#include <QWheelEvent>
#include <QFontMetrics>
#include <QTimer>
#include <QCursor>
#include <QMouseEvent>
#include <QRect>
#include <QDebug>
#include "documentviewinternal.moc"
namespace QSourceView
{
class TextCursor
: public DocumentPosition
{
public:
TextCursor();
bool is_visible;
};
TextCursor::TextCursor()
: DocumentPosition(0, 0)
, is_visible(false)
{
}
DocumentViewInternal::DocumentViewInternal(DocumentView &parentView,
Renderer &renderer)
: QWidget(&parentView)
, m_view(&parentView)
, m_renderer(&renderer)
, m_startX(0)
, m_startY(0)
, m_caret(new TextCursor)
{
setAttribute(Qt::WA_OpaquePaintEvent);
setFocusPolicy(Qt::ClickFocus);
setCursor(Qt::IBeamCursor);
QTimer *caretTimer = new QTimer(this);
caretTimer->setSingleShot(false);
connect(caretTimer, SIGNAL(timeout()),
this, SLOT(toggleCaretVisibility()));
caretTimer->start(500);
}
int DocumentViewInternal::startX() const
{
return m_startX;
}
int DocumentViewInternal::startY() const
{
return m_startY;
}
int DocumentViewInternal::endY() const
{
return m_view->document().lineCount() * fontMetrics().height();
}
const DocumentPosition &DocumentViewInternal::caretPosition() const
{
return *m_caret;
}
void DocumentViewInternal::setCaretPosition(const DocumentPosition &pos)
{
if(pos.line() < m_view->document().lineCount())
m_caret->setLine(pos.line());
if(pos.column() < m_view->document().text(caretPosition().line()).size())
m_caret->setColumn(pos.column());
}
void DocumentViewInternal::setStartX(int x)
{
if(x < 0)
m_startX = 0;
else
m_startX = x;
update();
}
void DocumentViewInternal::setStartY(int y)
{
qDebug() << y;
if(y < 0)
m_startY = 0;
else if(y > (endY() - height()))
{
m_startY = endY() - height();
if(m_startY < 0)
m_startY = 0;
}
else
m_startY = y;
update();
emit(startYChanged(m_startY));
}
void DocumentViewInternal::paintEvent(QPaintEvent *event)
{
QRect rect = event->rect();
QPainter paint(this);
unsigned int fontHeight = fontMetrics().height();
int lineYStart = (startY() % fontHeight);
int lineNumStart = lineAt(startY());
int numLines = (height() / fontHeight) + 2;
int i;
// Paint the text
Document *doc = &m_view->document();
for(i = 0;i < numLines;i++,lineNumStart++)
{
QRect bound = QRect(0, (i*fontHeight) - lineYStart, rect.width(), fontHeight);
paint.fillRect(bound, Qt::white);
paint.drawText(bound, doc->text(lineNumStart));
}
paintCaret(paint);
}
void DocumentViewInternal::resizeEvent(QResizeEvent *event)
{
emit(sizeChanged(event->size().width(), event->size().height()));
}
void DocumentViewInternal::keyPressEvent(QKeyEvent *event)
{
m_view->controller().keyPressEvent(event);
}
void DocumentViewInternal::mousePressEvent(QMouseEvent *event)
{
unsigned int pressLine = lineAt(event->y()+startY());
unsigned int pressColumn;
if(pressLine >= m_view->document().lineCount())
{
pressLine = m_view->document().lineCount()-1;
}
QString line = m_view->document().text(pressLine);
// Find the column were at
int i;
for(i = 0;i < line.size();i++)
{
if(event->x() <= fontMetrics().width(line.left(i+1)))
break;
}
pressColumn = i;
m_caret->setLine(pressLine);
m_caret->setColumn(pressColumn);
m_caret->is_visible = true;
update();
}
void DocumentViewInternal::wheelEvent(QWheelEvent *event)
{
event->ignore();
if(event->orientation() == Qt::Vertical)
{
setStartY(startY() - (event->delta() / 30));
}
}
void DocumentViewInternal::paintCaret(QPainter &paint)
{
unsigned int startLine = lineAt(startY());
if(startLine > m_caret->line()
|| lineAt(startY()+height()) <= m_caret->line())
return;
// Text printed infront of cursor
QString prevline = m_view->document().text(m_caret->line()).left(m_caret->column());
int xStart = fontMetrics().width(prevline);
QRect bound = QRect(xStart, (fontMetrics().height()*m_caret->line()) - startY(), 1, fontMetrics().height());
if(m_caret->is_visible)
{
if(m_caret->column() >= (unsigned int)m_view->document().text(m_caret->line()).size())
paint.fillRect(bound, Qt::white);
else
paint.drawText(bound, QString(m_view->document().text(m_caret->line())[m_caret->column()]));
}
else
{
paint.fillRect(bound, Qt::black);
}
}
void DocumentViewInternal::toggleCaretVisibility()
{
m_caret->is_visible = !m_caret->is_visible;
update();
}
unsigned int DocumentViewInternal::lineAt(unsigned int x) const
{
return x / fontMetrics().height();
}
}
<|endoftext|> |
<commit_before>#include "MusicMessages.h"
#include <dmusic/Structs.h>
#include <dmusic/PlayingContext.h>
#include <cassert>
#include <cstdlib>
#include <cmath>
using namespace DirectMusic;
void MusicMessage::changeTempo(PlayingContext& ctx, double tempo) {
ctx.m_tempo = tempo;
}
std::shared_ptr<InstrumentPlayer> MusicMessage::createInstrument(PlayingContext& ctx,
std::uint8_t bank_lo, std::uint8_t bank_hi, std::uint8_t patch,
const DirectMusic::DLS::DownloadableSound& dls, float volume, float pan) {
return ctx.m_instrumentFactory(bank_lo, bank_hi, patch, dls, ctx.m_sampleRate, ctx.m_audioChannels, volume, pan);
}
void MusicMessage::setInstrument(PlayingContext& ctx, std::uint32_t channel, std::shared_ptr<InstrumentPlayer> instr) {
ctx.m_performanceChannels[channel] = instr;
}
// From the Microsoft DX8 SDK docs
static int StoredRangeToActualRange(std::uint8_t bRange) {
int nResult = 0;
if (0 <= bRange && bRange <= 190) {
nResult = bRange;
} else if (191 <= bRange && bRange <= 212) {
nResult = ((bRange - 190) * 5) + 190;
} else if (213 <= bRange && bRange <= 232) {
nResult = ((bRange - 212) * 10) + 300;
} else // bRange > 232
{
nResult = ((bRange - 232) * 50) + 500;
}
return nResult;
}
enum class Subdivision {
Grid,
Beat,
Measure
};
// Returns the nearest subdivision starting from time 'musicTime' according to 'timeSignature'
static std::uint32_t getNextGridSubdivision(std::uint32_t musicTime, Subdivision subd, DMUS_IO_TIMESIG timeSignature) {
std::uint32_t divisionCoeff;
if (timeSignature.bBeat == 0) {
divisionCoeff = PlayingContext::PulsesPerQuarterNote / 64;
} else if (timeSignature.bBeat > 4) {
divisionCoeff = (PlayingContext::PulsesPerQuarterNote * 4) / timeSignature.bBeat;
} else {
divisionCoeff = PlayingContext::PulsesPerQuarterNote * (4 / timeSignature.bBeat);
}
divisionCoeff *= timeSignature.wGridsPerBeat;
std::uint32_t nextGridDivision = (std::uint32_t)(ceil((double)musicTime / divisionCoeff));
std::uint32_t nextBeatDivision = nextGridDivision * timeSignature.wGridsPerBeat;
std::uint32_t nextMeasureDivision = nextBeatDivision * timeSignature.bBeatsPerMeasure;
switch (subd) {
case Subdivision::Beat:
return nextBeatDivision * divisionCoeff;
case Subdivision::Grid:
return nextGridDivision * divisionCoeff;
case Subdivision::Measure:
return nextMeasureDivision * divisionCoeff;
}
}
static std::uint32_t getMeasureLength(DMUS_IO_TIMESIG timeSignature) {
return (timeSignature.bBeatsPerMeasure * PlayingContext::PulsesPerQuarterNote * 4) / timeSignature.bBeat;
}
// From the Microsoft DX8 SDK docs
static std::uint32_t getMusicOffset(std::uint32_t mtGridStart, std::int16_t nTimeOffset, DMUS_IO_TIMESIG TimeSig) {
const std::uint32_t DMUS_PPQ = PlayingContext::PulsesPerQuarterNote;
return nTimeOffset +
(
(mtGridStart / TimeSig.wGridsPerBeat) * ((DMUS_PPQ * 4) / TimeSig.bBeat)
+
(mtGridStart % TimeSig.wGridsPerBeat) * (((DMUS_PPQ * 4) / TimeSig.bBeat) / TimeSig.wGridsPerBeat)
);
}
// Returns true if the specified degree is present in a certain scale, and puts the distance from the
// root note into offset. If not present, returns false.
static bool getOffsetFromScale(std::uint8_t degree, std::uint32_t scale, std::uint8_t* offset) {
assert(offset != nullptr);
// FIXME: There is probably a faster way to do this
std::vector<int> degrees;
for (int i = 0; i < 24; i++) {
if (scale & (0x00000001 << i)) {
degrees.push_back(i);
}
}
if (degree < degrees.size()) {
*offset = degrees[degree];
return true;
} else {
*offset = degrees[degrees.size() - 1];
return false;
}
}
static bool MusicValueToMIDI(std::uint32_t chord, const std::vector<DMUS_IO_SUBCHORD>& subchords, DMUS_IO_STYLENOTE note, DMUS_IO_STYLEPART part, std::uint8_t* value) {
assert(value != nullptr);
if (note.bPlayModeFlags == DMUS_PLAYMODE_FIXED) {
// In the original Gothic sountrack this is not used, but it might be useful for modding purposes
*value = (std::uint8_t)(note.wMusicValue);
return true;
}
assert(note.bPlayModeFlags == DMUS_PLAYMODE_CHORD_ROOT | DMUS_PLAYMODE_CHORD_INTERVALS | DMUS_PLAYMODE_SCALE_INTERVALS);
// TODO: The subchord level should be obtained from the part reference,
// but in Gothic's soundtrack it's always set to the first level.
/*
A chord (or a scale) has the following structure: the first 8 bits represent the
root of the chord (scale), with the standard MIDI notation:
0 -> C
1 -> C#
....
23 -> B
The following 24 bits represent which notes are present in the chord, with each
bit meaning a semitone from the root (the LSB). Example taken from G2:
chord = 0x00AB5AB5
0 0 A B 5 A B 5
00000000101010110101101010110101
|-------|-|-|-||-|-||-|-|-||-|-|
C W W W HW W HW W W HW W -----> C Major scale
*/
DMUS_IO_SUBCHORD subchord = subchords[0];
/* Had to dig hard for this one: https://msdn.microsoft.com/en-us/library/ms898477.aspx
Here is how to interpret wMusicValue:
First nibble: octave (from -2 to 14 (??? I guess they meant -2 to 13) )
Second nibble: chord tone (0 to 15)
Third nibble: scale offset (0 to 15)
Fourth nibble: accidentals (-8 to 7)
*/
int octave = ((note.wMusicValue & 0xF000) >> 12);
int chordTone = ((note.wMusicValue & 0x0F00) >> 8);
int scaleTone = ((note.wMusicValue & 0x00F0) >> 4);
// Explanation: the accidentals are represented as a two's complement 4bit value.
// We first take only the last four bits from the word, then we shift it left
// while keeping it unsigned, so that when we convert it into a signed byte
// it has the correct sign. Then we divide by 16 to simulate an arithmetic
// right shift of 4, to bring the value back into the correct range
int accidentals = (std::int8_t)(note.wMusicValue & 0x000F);
if (accidentals > 7) { accidentals = (accidentals - 16); }
int noteValue = ((chord & 0xFF000000) >> 24) + 12 * octave;
std::uint8_t chordOffset = 0;
std::uint8_t scaleOffset = 0;
if (getOffsetFromScale(chordTone, subchord.dwChordPattern, &chordOffset)) {
noteValue += chordOffset;
// Is it possible to not find chordTone?
// } else if (getOffsetFromScale(chordTone, subchord.dwScalePattern, &scaleOffset)) {
// noteValue += scaleOffset;
} else {
return false;
}
// Start scale offset from resolved chordTone.
// Let's draw an example:
// * chordTone is 2, scaleTone is 1
// * in normal chord chordTone 2 is resolved to 5th grade in scale
// * plus scaleTone 1 it makes 6th grade of the scale
// * depending on scale, it might be 8 semitones (minor) or 9 semitones (major)
// So, scaleOffset depends on chord's grade
// That works even if chord's grade doesn't fit into scale
// Chord grade might be off of the scale, so if scaleOffset = 0, don't ruin it
if (scaleTone && getOffsetFromScale(scaleTone, subchord.dwScalePattern >> chordOffset, &scaleOffset)) {
noteValue += scaleOffset;
}
noteValue += accidentals;
while (noteValue < 0) {
noteValue += 12;
}
while (noteValue > 127) {
noteValue -= 12;
}
*value = noteValue;
TRACE_VERBOSE((int)value);
return true;
}
void MusicMessage::playPattern(PlayingContext& ctx) {
ctx.m_patternMessageQueue = MessageQueue();
for (const auto& kvpair : ctx.m_performanceChannels) {
kvpair.second->allNotesOff();
}
if (ctx.m_primarySegment != nullptr && ctx.m_performanceChannels.size() > 0 && ctx.m_subchords.size() > 0) {
PlayingContext::Pattern pttn;
if (ctx.m_primarySegment->getRandomPattern(ctx.m_grooveLevel, &pttn)) {
std::uint32_t patternLength = pttn.header.wNbrMeasures * getMeasureLength(pttn.header.timeSig);
for (const auto& partTuple: pttn.parts) {
const auto& partRef = partTuple.first;
const auto& part = partTuple.second;
for (const auto& note: part.getNotes()) {
std::uint8_t midiNote;
std::uint32_t timeStart = getMusicOffset(note.mtGridStart, note.nTimeOffset, part.getHeader().timeSig);
if (MusicValueToMIDI(ctx.m_chord, ctx.m_subchords, note, part.getHeader(), &midiNote)) {
auto noteOnMessage = std::make_shared<NoteOnMessage>(ctx.m_musicTime + timeStart, midiNote, note.bVelocity, 0, partRef.wLogicalPartID);
assert(noteOnMessage != nullptr);
ctx.m_patternMessageQueue.push(noteOnMessage);
auto noteOffMessage = std::make_shared<NoteOffMessage>(ctx.m_musicTime + timeStart + note.mtDuration, midiNote, partRef.wLogicalPartID);
assert(noteOffMessage != nullptr);
ctx.m_patternMessageQueue.push(noteOffMessage);
}
}
}
auto patternEndMessage = std::make_shared<PatternEndMessage>(ctx.m_musicTime + patternLength);
ctx.m_patternMessageQueue.push(patternEndMessage);
}
}
}
void MusicMessage::setGrooveLevel(PlayingContext& ctx, std::uint8_t level) {
ctx.m_grooveLevel = level;
playPattern(ctx);
}
const std::map<std::uint32_t, std::shared_ptr<InstrumentPlayer>>& MusicMessage::getChannels(PlayingContext& ctx) {
return ctx.m_performanceChannels;
}
void MusicMessage::changeChord(PlayingContext& ctx, std::uint32_t chord, const std::vector<DMUS_IO_SUBCHORD>& subchords) {
ctx.m_chord = chord;
ctx.m_subchords = subchords;
}
void MusicMessage::enqueueNextSegment(PlayingContext& ctx) {
if (ctx.m_primarySegment == nullptr) {
if (ctx.m_nextSegment != nullptr) {
ctx.enqueueSegment(ctx.m_nextSegment);
ctx.m_primarySegment = std::move(ctx.m_nextSegment);
ctx.m_nextSegment = nullptr;
}
} else {
if (ctx.m_nextSegment != nullptr) {
ctx.enqueueSegment(ctx.m_nextSegment);
ctx.m_primarySegment = std::move(ctx.m_nextSegment);
ctx.m_nextSegment = nullptr;
} else {
ctx.enqueueSegment(ctx.m_primarySegment);
}
}
}
void TempoChangeMessage::Execute(PlayingContext& ctx) {
TRACE("Tempo change");
this->changeTempo(ctx, m_tempo);
}
BandChangeMessage::BandChangeMessage(PlayingContext& ctx, std::uint32_t time, const BandForm& form)
: MusicMessage(time) {
for (const auto& instr : form.getInstruments()) {
const auto& header = instr.getHeader();
const auto ref = instr.getReference();
if (ref != nullptr) {
std::uint8_t bankHi = (header.dwPatch & 0x00FF0000) >> 0x10;
std::uint8_t bankLo = (header.dwPatch & 0x0000FF00) >> 0x8;
std::uint8_t patch = (header.dwPatch & 0x000000FF);
float volume = header.bVolume / 255.0f;
float pan = ((float)(header.bPan) - 63.0f) / 64.0f;
auto dls = ctx.loadInstrumentCollection(ref->getFile());
assert(dls != nullptr);
instruments[header.dwPChannel] = createInstrument(ctx, bankLo, bankHi, patch, *dls, volume, pan);
}
}
}
void BandChangeMessage::Execute(PlayingContext& ctx) {
TRACE("Band change");
for (const auto& kvpair : instruments) {
setInstrument(ctx, kvpair.first, kvpair.second);
}
}
void GrooveLevelMessage::Execute(PlayingContext& ctx) {
TRACE("Groove change");
if (m_range == 0) {
setGrooveLevel(ctx, m_level);
} else {
std::int8_t offset = (std::rand() % m_range) - (m_range / 2);
setGrooveLevel(ctx, m_level - offset);
}
}
void ChordMessage::Execute(PlayingContext& ctx) {
TRACE("Chord change");
changeChord(ctx, this->m_chord, this->m_subchords);
}
void NoteOnMessage::Execute(PlayingContext& ctx) {
TRACE_VERBOSE("Note on");
const auto& channels = getChannels(ctx);
assert(channels.find(m_channel) != channels.end());
if (m_velRange == 0) {
channels.at(m_channel)->noteOn(m_note, m_vel);
} else {
std::int8_t offset = (std::rand() % m_velRange) - (m_velRange / 2);
channels.at(m_channel)->noteOn(m_note, m_vel - offset);
}
}
void NoteOffMessage::Execute(PlayingContext& ctx) {
TRACE_VERBOSE("Note off");
const auto& channels = getChannels(ctx);
assert(channels.find(m_channel) != channels.end());
channels.at(m_channel)->noteOff(m_note, 0);
}
void SegmentEndMessage::Execute(PlayingContext& ctx) {
TRACE("Segment end");
enqueueNextSegment(ctx);
}
void PatternEndMessage::Execute(PlayingContext& ctx) {
TRACE("Pattern end");
playPattern(ctx);
}<commit_msg>Add missing note trace<commit_after>#include "MusicMessages.h"
#include <dmusic/Structs.h>
#include <dmusic/PlayingContext.h>
#include <cassert>
#include <cstdlib>
#include <cmath>
using namespace DirectMusic;
void MusicMessage::changeTempo(PlayingContext& ctx, double tempo) {
ctx.m_tempo = tempo;
}
std::shared_ptr<InstrumentPlayer> MusicMessage::createInstrument(PlayingContext& ctx,
std::uint8_t bank_lo, std::uint8_t bank_hi, std::uint8_t patch,
const DirectMusic::DLS::DownloadableSound& dls, float volume, float pan) {
return ctx.m_instrumentFactory(bank_lo, bank_hi, patch, dls, ctx.m_sampleRate, ctx.m_audioChannels, volume, pan);
}
void MusicMessage::setInstrument(PlayingContext& ctx, std::uint32_t channel, std::shared_ptr<InstrumentPlayer> instr) {
ctx.m_performanceChannels[channel] = instr;
}
// From the Microsoft DX8 SDK docs
static int StoredRangeToActualRange(std::uint8_t bRange) {
int nResult = 0;
if (0 <= bRange && bRange <= 190) {
nResult = bRange;
} else if (191 <= bRange && bRange <= 212) {
nResult = ((bRange - 190) * 5) + 190;
} else if (213 <= bRange && bRange <= 232) {
nResult = ((bRange - 212) * 10) + 300;
} else // bRange > 232
{
nResult = ((bRange - 232) * 50) + 500;
}
return nResult;
}
enum class Subdivision {
Grid,
Beat,
Measure
};
// Returns the nearest subdivision starting from time 'musicTime' according to 'timeSignature'
static std::uint32_t getNextGridSubdivision(std::uint32_t musicTime, Subdivision subd, DMUS_IO_TIMESIG timeSignature) {
std::uint32_t divisionCoeff;
if (timeSignature.bBeat == 0) {
divisionCoeff = PlayingContext::PulsesPerQuarterNote / 64;
} else if (timeSignature.bBeat > 4) {
divisionCoeff = (PlayingContext::PulsesPerQuarterNote * 4) / timeSignature.bBeat;
} else {
divisionCoeff = PlayingContext::PulsesPerQuarterNote * (4 / timeSignature.bBeat);
}
divisionCoeff *= timeSignature.wGridsPerBeat;
std::uint32_t nextGridDivision = (std::uint32_t)(ceil((double)musicTime / divisionCoeff));
std::uint32_t nextBeatDivision = nextGridDivision * timeSignature.wGridsPerBeat;
std::uint32_t nextMeasureDivision = nextBeatDivision * timeSignature.bBeatsPerMeasure;
switch (subd) {
case Subdivision::Beat:
return nextBeatDivision * divisionCoeff;
case Subdivision::Grid:
return nextGridDivision * divisionCoeff;
case Subdivision::Measure:
return nextMeasureDivision * divisionCoeff;
}
}
static std::uint32_t getMeasureLength(DMUS_IO_TIMESIG timeSignature) {
return (timeSignature.bBeatsPerMeasure * PlayingContext::PulsesPerQuarterNote * 4) / timeSignature.bBeat;
}
// From the Microsoft DX8 SDK docs
static std::uint32_t getMusicOffset(std::uint32_t mtGridStart, std::int16_t nTimeOffset, DMUS_IO_TIMESIG TimeSig) {
const std::uint32_t DMUS_PPQ = PlayingContext::PulsesPerQuarterNote;
return nTimeOffset +
(
(mtGridStart / TimeSig.wGridsPerBeat) * ((DMUS_PPQ * 4) / TimeSig.bBeat)
+
(mtGridStart % TimeSig.wGridsPerBeat) * (((DMUS_PPQ * 4) / TimeSig.bBeat) / TimeSig.wGridsPerBeat)
);
}
// Returns true if the specified degree is present in a certain scale, and puts the distance from the
// root note into offset. If not present, returns false.
static bool getOffsetFromScale(std::uint8_t degree, std::uint32_t scale, std::uint8_t* offset) {
assert(offset != nullptr);
// FIXME: There is probably a faster way to do this
std::vector<int> degrees;
for (int i = 0; i < 24; i++) {
if (scale & (0x00000001 << i)) {
degrees.push_back(i);
}
}
if (degree < degrees.size()) {
*offset = degrees[degree];
return true;
} else {
*offset = degrees[degrees.size() - 1];
return false;
}
}
static bool MusicValueToMIDI(std::uint32_t chord, const std::vector<DMUS_IO_SUBCHORD>& subchords, DMUS_IO_STYLENOTE note, DMUS_IO_STYLEPART part, std::uint8_t* value) {
assert(value != nullptr);
if (note.bPlayModeFlags == DMUS_PLAYMODE_FIXED) {
// In the original Gothic sountrack this is not used, but it might be useful for modding purposes
*value = (std::uint8_t)(note.wMusicValue);
return true;
}
assert(note.bPlayModeFlags == DMUS_PLAYMODE_CHORD_ROOT | DMUS_PLAYMODE_CHORD_INTERVALS | DMUS_PLAYMODE_SCALE_INTERVALS);
// TODO: The subchord level should be obtained from the part reference,
// but in Gothic's soundtrack it's always set to the first level.
/*
A chord (or a scale) has the following structure: the first 8 bits represent the
root of the chord (scale), with the standard MIDI notation:
0 -> C
1 -> C#
....
23 -> B
The following 24 bits represent which notes are present in the chord, with each
bit meaning a semitone from the root (the LSB). Example taken from G2:
chord = 0x00AB5AB5
0 0 A B 5 A B 5
00000000101010110101101010110101
|-------|-|-|-||-|-||-|-|-||-|-|
C W W W HW W HW W W HW W -----> C Major scale
*/
DMUS_IO_SUBCHORD subchord = subchords[0];
/* Had to dig hard for this one: https://msdn.microsoft.com/en-us/library/ms898477.aspx
Here is how to interpret wMusicValue:
First nibble: octave (from -2 to 14 (??? I guess they meant -2 to 13) )
Second nibble: chord tone (0 to 15)
Third nibble: scale offset (0 to 15)
Fourth nibble: accidentals (-8 to 7)
*/
int octave = ((note.wMusicValue & 0xF000) >> 12);
int chordTone = ((note.wMusicValue & 0x0F00) >> 8);
int scaleTone = ((note.wMusicValue & 0x00F0) >> 4);
// Explanation: the accidentals are represented as a two's complement 4bit value.
// We first take only the last four bits from the word, then we shift it left
// while keeping it unsigned, so that when we convert it into a signed byte
// it has the correct sign. Then we divide by 16 to simulate an arithmetic
// right shift of 4, to bring the value back into the correct range
int accidentals = (std::int8_t)(note.wMusicValue & 0x000F);
if (accidentals > 7) { accidentals = (accidentals - 16); }
int noteValue = ((chord & 0xFF000000) >> 24) + 12 * octave;
std::uint8_t chordOffset = 0;
std::uint8_t scaleOffset = 0;
if (getOffsetFromScale(chordTone, subchord.dwChordPattern, &chordOffset)) {
noteValue += chordOffset;
// Is it possible to not find chordTone?
// } else if (getOffsetFromScale(chordTone, subchord.dwScalePattern, &scaleOffset)) {
// noteValue += scaleOffset;
} else {
TRACE_VERBOSE("Note not found: " << noteValue);
return false;
}
// Start scale offset from resolved chordTone.
// Let's draw an example:
// * chordTone is 2, scaleTone is 1
// * in normal chord chordTone 2 is resolved to 5th grade in scale
// * plus scaleTone 1 it makes 6th grade of the scale
// * depending on scale, it might be 8 semitones (minor) or 9 semitones (major)
// So, scaleOffset depends on chord's grade
// That works even if chord's grade doesn't fit into scale
// Chord grade might be off of the scale, so if scaleOffset = 0, don't ruin it
if (scaleTone && getOffsetFromScale(scaleTone, subchord.dwScalePattern >> chordOffset, &scaleOffset)) {
noteValue += scaleOffset;
}
noteValue += accidentals;
while (noteValue < 0) {
noteValue += 12;
}
while (noteValue > 127) {
noteValue -= 12;
}
*value = noteValue;
TRACE_VERBOSE((int)value);
return true;
}
void MusicMessage::playPattern(PlayingContext& ctx) {
ctx.m_patternMessageQueue = MessageQueue();
for (const auto& kvpair : ctx.m_performanceChannels) {
kvpair.second->allNotesOff();
}
if (ctx.m_primarySegment != nullptr && ctx.m_performanceChannels.size() > 0 && ctx.m_subchords.size() > 0) {
PlayingContext::Pattern pttn;
if (ctx.m_primarySegment->getRandomPattern(ctx.m_grooveLevel, &pttn)) {
std::uint32_t patternLength = pttn.header.wNbrMeasures * getMeasureLength(pttn.header.timeSig);
for (const auto& partTuple: pttn.parts) {
const auto& partRef = partTuple.first;
const auto& part = partTuple.second;
for (const auto& note: part.getNotes()) {
std::uint8_t midiNote;
std::uint32_t timeStart = getMusicOffset(note.mtGridStart, note.nTimeOffset, part.getHeader().timeSig);
if (MusicValueToMIDI(ctx.m_chord, ctx.m_subchords, note, part.getHeader(), &midiNote)) {
auto noteOnMessage = std::make_shared<NoteOnMessage>(ctx.m_musicTime + timeStart, midiNote, note.bVelocity, 0, partRef.wLogicalPartID);
assert(noteOnMessage != nullptr);
ctx.m_patternMessageQueue.push(noteOnMessage);
auto noteOffMessage = std::make_shared<NoteOffMessage>(ctx.m_musicTime + timeStart + note.mtDuration, midiNote, partRef.wLogicalPartID);
assert(noteOffMessage != nullptr);
ctx.m_patternMessageQueue.push(noteOffMessage);
}
}
}
auto patternEndMessage = std::make_shared<PatternEndMessage>(ctx.m_musicTime + patternLength);
ctx.m_patternMessageQueue.push(patternEndMessage);
}
}
}
void MusicMessage::setGrooveLevel(PlayingContext& ctx, std::uint8_t level) {
ctx.m_grooveLevel = level;
playPattern(ctx);
}
const std::map<std::uint32_t, std::shared_ptr<InstrumentPlayer>>& MusicMessage::getChannels(PlayingContext& ctx) {
return ctx.m_performanceChannels;
}
void MusicMessage::changeChord(PlayingContext& ctx, std::uint32_t chord, const std::vector<DMUS_IO_SUBCHORD>& subchords) {
ctx.m_chord = chord;
ctx.m_subchords = subchords;
}
void MusicMessage::enqueueNextSegment(PlayingContext& ctx) {
if (ctx.m_primarySegment == nullptr) {
if (ctx.m_nextSegment != nullptr) {
ctx.enqueueSegment(ctx.m_nextSegment);
ctx.m_primarySegment = std::move(ctx.m_nextSegment);
ctx.m_nextSegment = nullptr;
}
} else {
if (ctx.m_nextSegment != nullptr) {
ctx.enqueueSegment(ctx.m_nextSegment);
ctx.m_primarySegment = std::move(ctx.m_nextSegment);
ctx.m_nextSegment = nullptr;
} else {
ctx.enqueueSegment(ctx.m_primarySegment);
}
}
}
void TempoChangeMessage::Execute(PlayingContext& ctx) {
TRACE("Tempo change");
this->changeTempo(ctx, m_tempo);
}
BandChangeMessage::BandChangeMessage(PlayingContext& ctx, std::uint32_t time, const BandForm& form)
: MusicMessage(time) {
for (const auto& instr : form.getInstruments()) {
const auto& header = instr.getHeader();
const auto ref = instr.getReference();
if (ref != nullptr) {
std::uint8_t bankHi = (header.dwPatch & 0x00FF0000) >> 0x10;
std::uint8_t bankLo = (header.dwPatch & 0x0000FF00) >> 0x8;
std::uint8_t patch = (header.dwPatch & 0x000000FF);
float volume = header.bVolume / 255.0f;
float pan = ((float)(header.bPan) - 63.0f) / 64.0f;
auto dls = ctx.loadInstrumentCollection(ref->getFile());
assert(dls != nullptr);
instruments[header.dwPChannel] = createInstrument(ctx, bankLo, bankHi, patch, *dls, volume, pan);
}
}
}
void BandChangeMessage::Execute(PlayingContext& ctx) {
TRACE("Band change");
for (const auto& kvpair : instruments) {
setInstrument(ctx, kvpair.first, kvpair.second);
}
}
void GrooveLevelMessage::Execute(PlayingContext& ctx) {
TRACE("Groove change");
if (m_range == 0) {
setGrooveLevel(ctx, m_level);
} else {
std::int8_t offset = (std::rand() % m_range) - (m_range / 2);
setGrooveLevel(ctx, m_level - offset);
}
}
void ChordMessage::Execute(PlayingContext& ctx) {
TRACE("Chord change");
changeChord(ctx, this->m_chord, this->m_subchords);
}
void NoteOnMessage::Execute(PlayingContext& ctx) {
TRACE_VERBOSE("Note on");
const auto& channels = getChannels(ctx);
assert(channels.find(m_channel) != channels.end());
if (m_velRange == 0) {
channels.at(m_channel)->noteOn(m_note, m_vel);
} else {
std::int8_t offset = (std::rand() % m_velRange) - (m_velRange / 2);
channels.at(m_channel)->noteOn(m_note, m_vel - offset);
}
}
void NoteOffMessage::Execute(PlayingContext& ctx) {
TRACE_VERBOSE("Note off");
const auto& channels = getChannels(ctx);
assert(channels.find(m_channel) != channels.end());
channels.at(m_channel)->noteOff(m_note, 0);
}
void SegmentEndMessage::Execute(PlayingContext& ctx) {
TRACE("Segment end");
enqueueNextSegment(ctx);
}
void PatternEndMessage::Execute(PlayingContext& ctx) {
TRACE("Pattern end");
playPattern(ctx);
}<|endoftext|> |
<commit_before>#include <iostream>
#include <SDL2/SDL.h>
#include "cpu/intel8080.hpp"
#include "gfx/screen.hpp"
#include "machine/machine.hpp"
#include "program/program.hpp"
#define SCREEN_WIDTH 64
#define SCREEN_HEIGHT 32
#define SCALE 10
Intel8080 cpu;
Screen screen(SCREEN_WIDTH, SCREEN_HEIGHT, SCALE);
int main(int argc, char **argv) {
program_t *program = getProgram(argv[1]);
cpu.loadProgram(program);
free_program(program);
Machine machine(cpu, screen);
machine.start();
return 0;
}
<commit_msg>Updated screen size to actual Space Invaders dimensions<commit_after>#include <iostream>
#include <SDL2/SDL.h>
#include "cpu/intel8080.hpp"
#include "gfx/screen.hpp"
#include "machine/machine.hpp"
#include "program/program.hpp"
#define SCREEN_WIDTH 256
#define SCREEN_HEIGHT 244
#define SCALE 10
Intel8080 cpu;
Screen screen(SCREEN_WIDTH, SCREEN_HEIGHT, SCALE);
int main(int argc, char **argv) {
program_t *program = getProgram(argv[1]);
cpu.loadProgram(program);
free_program(program);
Machine machine(cpu, screen);
machine.start();
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "StdAfx.h"
#include "OptionsParser.h"
COptionsParser::COptionsParser()
{
this->Clean();
}
COptionsParser::COptionsParser(int nArgc, LPTSTR *pArgv)
{
(void) this->Init(nArgc, pArgv);
}
COptionsParser::COptionsParser(const CL_OPTIONS *pclOptions)
{
(void) this->Init(pclOptions);
}
COptionsParser::COptionsParser(int nArgc, LPTSTR *pArgv, const CL_OPTIONS *pclOptions)
{
(void) this->Init(nArgc, pArgv, pclOptions);
}
COptionsParser::~COptionsParser(void)
{
this->Clean();
}
bool COptionsParser::InitDone(void)
{
if ((this->bInit == true) && (this->pArgv != NULL))
return true;
if ((this->bHaveArgv == true) &&
(this->bHaveOptions == true))
{
this->nPosArgv = 0;
this->nParams = 0;
this->nParamsPos = -1;
this->nOptionId = -2;
this->bInit = true;
return true;
}
return false;
}
bool COptionsParser::Init(int nArgc, LPTSTR *pArgv)
{
if ((pArgv != NULL) && (nArgc >= 2))
{
this->nArgc = nArgc;
this->pArgv = pArgv;
this->bHaveArgv = true;
}
return this->InitDone();
}
bool COptionsParser::Init(const CL_OPTIONS *pclOptions)
{
if (pclOptions != NULL)
{
this->pclOptions = pclOptions;
this->bHaveOptions = true;
}
return this->InitDone();
}
bool COptionsParser::Init(int nArgc, LPTSTR *pArgv, const CL_OPTIONS *pclOptions)
{
if ((pArgv != NULL) && (nArgc >= 2))
{
this->nPosArgv = 0;
this->nArgc = nArgc;
this->pArgv = pArgv;
this->bHaveArgv = true;
}
if (pclOptions != NULL)
{
this->pclOptions = pclOptions;
this->bHaveOptions = true;
}
return this->InitDone();
}
void COptionsParser::Clean(void)
{
this->nPosArgv = -1;
this->nParams = -1;
this->nParamsPos = -1;
this->nOptionId = -2;
this->nArgc = -1;
this->pArgv = NULL;
this->pclOptions = NULL;
bool bHaveArgv = false;
bool bHaveOptions = false;
this->bInit = false;
}
bool COptionsParser::IsOpt(LPTSTR szOption)
{
if (szOption == NULL)
return false;
if (this->IsLongOpt(szOption) == true)
return true;
else if (this->IsShortOpt(szOption) == true)
return true;
else
return false;
}
bool COptionsParser::IsLongOpt(LPTSTR szOption)
{
if (szOption == NULL)
return false;
// is argument in long option format: --option, --o, --opt, etc...
if (lstrlen(szOption) >= 3)
{
if ((szOption[0] == '-') && (szOption[1] == '-'))
return true;
else
return false;
}
return false;
}
bool COptionsParser::IsShortOpt(LPTSTR szOption)
{
if (szOption == NULL)
return false;
// is argument in short option format: -o, /o, etc...
if (lstrlen(szOption) == 2)
{
if ((szOption[0] == '-') || (szOption[0] == '/'))
return true;
else
return false;
}
return false;
}
int COptionsParser::Next(void)
{
// Return values:
// 0...N - valid option
// -1 - finished
// -2 - error (invalid option or param)
if (this->InitDone() == false)
return(-2); // ERROR
// clean last options status
this->nParams = 0;
this->nParamsPos = -1;
this->nOptionId = -2;
// increment args counter
this->nPosArgv++;
// check if are at end of args
if (this->nPosArgv >= nArgc)
return(-1); // SUCCESS
LPTSTR szOption = NULL;
szOption = this->pArgv[this->nPosArgv];
// get valid option name
if (this->IsLongOpt(szOption) == true)
{
// long option format
szOption = (LPTSTR)(szOption + 2);
}
else if (this->IsShortOpt(szOption) == true)
{
// short option format
szOption = (LPTSTR)(szOption + 1);
}
else
{
// invalid option format
return(-2); // ERROR
}
int nOptionId = -2;
int i = 0;
#ifdef USE_PARSER_TOKENS
const TCHAR szTokenSeps[] = _T(" ;|,\t");
#endif // USE_PARSER_TOKENS
while (pclOptions[i].szOptionName != NULL)
{
#ifdef USE_PARSER_TOKENS
LPTSTR szOptionName = NULL;
size_t nLen = _tcslen(pclOptions[i].szOptionName);
szOptionName = (LPTSTR)malloc((nLen + 1) * sizeof(TCHAR));
if (szOptionName == NULL)
return(-2); // ERROR
memcpy(szOptionName, pclOptions[i].szOptionName, nLen * sizeof(TCHAR));
szOptionName[nLen] = '\0';
LPTSTR szToken = _tcstok(szOptionName, szTokenSeps);
while (szToken != NULL)
{
// check next token
if (lstrcmp(szOption, szToken) == 0)
#else
if (lstrcmp(szOption, pclOptions[i].szOptionName) == 0)
#endif // USE_PARSER_TOKENS
{
nOptionId = pclOptions[i].nOptionId;
if (pclOptions[i].bParamsRequired == false)
{
if (pclOptions[i].nParams == 1)
{
// check if we have 1 param that is not required
if ((this->nPosArgv + 1) >= nArgc)
{
// no more args available
this->nParams = 0;
this->nParamsPos = -1;
}
else
{
// if next arg is not an option then we have 1 param
if (this->IsOpt(this->pArgv[this->nPosArgv + 1]) == false)
{
this->nParams = 1;
this->nParamsPos = this->nPosArgv + 1;
// update position
this->nPosArgv++;
}
}
}
#ifdef USE_PARSER_TOKENS
free(szOptionName);
#endif // USE_PARSER_TOKENS
// SUCCESS
this->nOptionId = nOptionId;
return nOptionId;
}
else
{
// check if we have all required params
if (pclOptions[i].nParams > 0)
{
// check if we have all params
if ((this->nPosArgv + pclOptions[i].nParams) >= nArgc)
{
#ifdef USE_PARSER_TOKENS
free(szOptionName);
#endif // USE_PARSER_TOKENS
// out off args
return(-2); // ERROR
}
// check if all params are valid
for (int j = 0; j < pclOptions[i].nParams; j++)
{
if (this->IsOpt(this->pArgv[this->nPosArgv + 1 + j]) == true)
{
#ifdef USE_PARSER_TOKENS
free(szOptionName);
#endif // USE_PARSER_TOKENS
return(-2); // ERROR
}
}
// we have all params
this->nParams = pclOptions[i].nParams;
this->nParamsPos = this->nPosArgv + 1;
// update position
this->nPosArgv += this->nParams;
}
#ifdef USE_PARSER_TOKENS
free(szOptionName);
#endif // USE_PARSER_TOKENS
// SUCCESS
this->nOptionId = nOptionId;
return nOptionId;
}
}
#ifdef USE_PARSER_TOKENS
// get next token
szToken = _tcstok(NULL, szTokenSeps);
}
// free memory used for tokens options
free(szOptionName);
#endif // USE_PARSER_TOKENS
// check next option
i++;
}
return(-2); // ERROR
}
bool COptionsParser::GetParam(CString &szParam, int nNum)
{
if (this->InitDone() == false)
return false;
if ((this->nParams == 0) || (this->nParamsPos < 0))
return false;
if ((nNum < 0) || (nNum >= this->nParams))
return false;
szParam = this->pArgv[this->nParamsPos + nNum];
return true;
}
<commit_msg>Removed unused file<commit_after><|endoftext|> |
<commit_before>/* vim:set noet sts=0 sw=2 ts=2: */
#include <string>
#include <cctype>
#include <array>
#include <utility>
#include <iostream>
#include "ftoken.hpp"
namespace fusion {
const std::array<std::string, 29> tokens = {
"else", "if", "true", "false", "nil", "while", "in", "new", "extends",
"for", "async", "yield"
/* */
"&&", "||", ">>", "<<", "==", "!=", ">=", "<=", "..", "_/",
/* */
"...", "[num]", "[str]", "[name]", "[eof]", "[white]"
};
char get_next(uint32_t position, std::string input) {
/* this should ONLY be used when the input is pre-verified */
if (input.length() < position + 1)
return input.at(position); // position is already incremented
else
return '\0'; // there should not ever be a '\0' in input
}
std::pair<bool, std::string> try_parse_num(TokenizerState *ts) {
std::string input = ts->input;
char first = input.at(ts->position);
if (first == '0' && (f_check_next(1, 'x') || f_check_next(1, 'X'))) {
std::string hexable = "0123456789ABCDEF";
std::string scanned = "";
uint32_t pos = ts->position + 2;
while (input.find_first_of(hexable, pos) == pos)
scanned += get_next(++pos, input);
if (scanned.length() == 0)
return std::pair<bool, std::string>(false, "");
char exponent = get_next(pos);
if (exponent == 'p' || exponent == 'P') {
scanned += exponent;
if (get_next(pos + 1, input) == '-' ||
get_next(pos + 1, input) == '+')
scanned += get_next(++pos, input);
while (input.find_first_of("0123456789", pos) == pos)
scanned += get_next(++pos, input);
}
ts->position = pos;
return std::pair<bool, std::string>(true, scanned);
} else if (input.find_first_of("0123456789.", ts->position)) {
// period included for decimals
std::string scanned = "";
uint32_t pos = ts->position;
while (input.find_first_of("0123456789", pos) == pos)
scanned += get_next(++pos, input);
if (get_next(pos, input) == '.' &&
(input.find("0123456789", pos) == pos + 1)) {
pos++;
while (input.find_first_of("0123456789", pos) == pos)
scanned += get_next(++pos, input);
}
if (scanned != ".") { // it can potentially match just a period so don't do that
ts->position = pos;
return std::pair<bool, std::string>(true, scanned);
}
}
return std::pair<bool, std::string>(false, "");
}
void tokenize(TokenizerState *ts, std::string input) {
/* initialize the tokenizer state */
/* search through string for a token */
while (true) {
try {
switch (input.at(ts->position)) {
case '\r': {
/* ignore \r for Windows support */
ts->position++;
break;
}
case '\n': {
ts->current_line++;
ts->position++;
break;
}
case ' ': case '\t': case '\v': case '\f': {
std::string whitespace_token = "";
while (f_iswhitespace(get_next(ts->position))) {
whitespace_token += get_next(ts->position);
ts->position++;
}
ts->tokens.push_back({token::TOK_WHITE, whitespace_token});
break;
}
case '&': {
/* check for && otherwise & */
if (f_check_next(1, '&')) {
/* generate token for && and incr position to skip over */
ts->tokens.push_back({
token::TOK_BOOLAND, /* token::type */
"&&" /* string self */
});
ts->position += 2;
break;
} /* end if */ /* do not process just & */
/* the nonbreaking default will process single-char tokens */
} /* end case */
case '|': {
/* same as above, check for || otherwise | */
if (f_check_next(1, '|')) {
/* generate || token and incr */
ts->tokens.push_back({token::TOK_BOOLOR, "||"});
ts->position += 2;
break;
}
} /* end case */
case '>': {
/* check for >>, check for >=, or DON'T break */
/* the char lives as itself as a token if nobreak */
bool is_single_char = false;
switch (get_next(ts->position + 1, input)) {
case '>':
ts->tokens.push_back({token::TOK_RSHIFT, ">>"});
break;
case '=':
ts->tokens.push_back({token::TOK_GE, ">="});
break;
default:
is_single_char = true;
} /* end switch */
if (!is_single_char) {
ts->position += 2;
break;
}
} /* end case */
case '<': {
/* duplicate above again, but with < */
bool is_single_char = false;
switch(get_next(ts->position + 1, input)) {
case '<':
ts->tokens.push_back({token::TOK_LSHIFT, "<<"});
break;
case '=':
ts->tokens.push_back({token::TOK_LE, "<="});
break;
default:
is_single_char = true;
} /* end switch */
if (!is_single_char) {
ts->position += 2;
break;
}
} /* end case */
case '=': {
/* check == else = */
if (f_check_next(1, '=')) {
ts->tokens.push_back({token::TOK_EQ, "=="});
ts->position += 2;
break;
}
}
case '!': {
/* check != else = */
if (f_check_next(1, '=')) {
ts->tokens.push_back({token::TOK_NEQ, "!="});
ts->position += 2;
break;
}
}
case '.': {
/* check .., then ...; if not ... then ..; then . */
auto result = try_parse_num(ts);
if (std::get<0>(result)) { /* true if number, false if not */
/* get<1>(result) should return a std::string */
std::string result_num = std::get<1>(result);
ts->tokens.push_back({token::TOK_NUM, result_num});
ts->position += result_num.length();
} else if (f_check_next(1, '.')) {
if (f_check_next(2, '.')) {
/* ... */
ts->tokens.push_back({token::TOK_VARARG, "..."});
ts->position += 3;
break;
} else {
/* .. */
ts->tokens.push_back({token::TOK_CONCAT, ".."});
ts->position += 3;
break;
}
} /* end else if */
} /* end case */
case '_': { /* floor division */
if (f_check_next(1, '/')) {
ts->tokens.push_back({token::TOK_FLOORDIV, "_/"});
ts->position += 2;
break;
}
}
case '"': {
std::string buffer = "\"";
ts->position++; /* increment position past the " */
char current = '\0'; /* current in string */
while (current != '"') { /* we can pass over '\"' during the loop */
current = get_next(ts->position, input);
if (current == '\\') { /* process escape code, C-style */
buffer += "\\" + get_next(ts->position + 2, input);
// TODO verify not '\0'
ts->position += 2;
} else if (current == '"') {
buffer += '"';
ts->position++;
break;
} else {
buffer += current;
ts->position++;
}
} /* end while */
ts->tokens.push_back({token::TOK_STRING, buffer});
break;
} /* end case */
case '\'': {
std::string buffer = "'";
ts->position++; /* incr past ' */
char current = '\0';
while (current != '\'') {
buffer += get_next(ts->position++, input); // TODO verify !'\0'
} /* end while */
ts->tokens.push_back({token::TOK_STRING, buffer});
break;
}
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
/* no matter what, this should return a number */
/* we don't need to test try_parse_num[1] */
std::string result_num = std::get<1>(try_parse_num(ts));
ts->tokens.push_back({token::TOK_NUM, result_num});
ts->position += result_num.length();
break;
} /* end case */
default: {
char current_char = get_next(ts->position, input);
if (isalpha(current_char) || current_char == '_') {
std::string word = "";
while (isalnum(current_char) || current_char == '_') {
word += current_char;
current_char = get_next(++ts->position);
if (current_char == '\0')
break;
} /* end while */
/* fully captured word, check if reserved keyword */
bool is_reserved = false;
for (auto iter = tokens.begin();
iter != tokens.end(); ++iter) {
/* find reserved word and push token */
if (word == *iter) {
/* found reserved word */
uint16_t pos = iter - tokens.begin();
ts->tokens.push_back({
static_cast<token::token_t>(pos + FIRST_TOKEN),
word
});
is_reserved = true;
} /* end if */
} /* end for */
if (!is_reserved) ts->tokens.push_back({token::TOK_NAME, word});
/* used as an identifier */
} else {
ts->tokens.push_back({
static_cast<token::token_t>(get_next(ts->position, input)),
std::string(1, get_next(ts->position, input))
});
ts->position++;
} /* end else */
} /* end default */
} /* end switch */
} catch (std::out_of_range const &ignored_exception) {
ts->tokens.push_back({token::TOK_END, ""});
return;
} /* end try */ /* end of input, return final token */
} /* end while */
} /* end function */
} /* end namespace */
int main() {
fusion::TokenizerState ts = fusion::TOKENIZER_STATE_DEFAULT;
fusion::tokenize(&ts, "print( \"hi\" )");
for (auto token = ts.tokens.begin(); token != ts.tokens.end(); token++) {
if (token->type > 256)
std::cout << fusion::tokens[token->type - 256] << " ";
else
std::cout << token->type << " ";
std::cout << token->self << std::endl;
}
return 0;
}
<commit_msg>src/ftoken: not working, uploading to test<commit_after>/* vim:set noet sts=0 sw=2 ts=2: */
#include <string>
#include <cctype>
#include <array>
#include <utility>
#include <iostream>
#include "ftoken.hpp"
namespace fusion {
const std::array<std::string, 28> tokens = {
"else", "if", "true", "false", "nil", "while", "in", "new", "extends",
"for", "async", "yield"
/* */
"&&", "||", ">>", "<<", "==", "!=", ">=", "<=", "..", "_/",
/* */
"...", "[num]", "[str]", "[name]", "[eof]", "[white]"
};
char get_next(uint32_t position, std::string input) {
/* this should ONLY be used when the input is pre-verified */
if (input.length() > position) {
return input.at(position); // position is already incremented
} else
return '\0'; // there should not ever be a '\0' in input
}
std::pair<bool, std::string> try_parse_num(TokenizerState *ts) {
std::string input = ts->input;
char first = get_next(ts->position, input);
if (first == '0' && (f_check_next(1, 'x') || f_check_next(1, 'X'))) {
std::string hexable = "0123456789ABCDEF";
std::string scanned = "";
uint32_t pos = ts->position + 2;
while (input.find_first_of(hexable, pos) == pos)
scanned += get_next(++pos, input);
if (scanned.length() == 0)
return std::pair<bool, std::string>(false, "");
char exponent = get_next(pos, input);
if (exponent == 'p' || exponent == 'P') {
scanned += exponent;
if (get_next(pos + 1, input) == '-' ||
get_next(pos + 1, input) == '+')
scanned += get_next(++pos, input);
while (input.find_first_of("0123456789", pos) == pos)
scanned += get_next(++pos, input);
}
ts->position = pos;
return std::pair<bool, std::string>(true, scanned);
} else if (input.find_first_of("0123456789.", ts->position) ==
ts->position) {
// period included for decimals
std::string scanned = "";
uint32_t pos = ts->position;
while (input.find_first_of("0123456789", pos) == pos) {
scanned += get_next(++pos, input);
std::cout << scanned << "\n";
}
if (get_next(pos, input) == '.' &&
(input.find("0123456789", pos) == pos + 1)) {
pos++;
while (input.find_first_of("0123456789", pos) == pos) {
scanned += get_next(++pos, input);
}
}
if (scanned != ".") { // it can potentially match just a period so don't do that
ts->position = pos;
return std::pair<bool, std::string>(true, scanned);
}
}
return std::pair<bool, std::string>(false, "");
}
void tokenize(TokenizerState *ts, std::string input) {
/* initialize the tokenizer state */
/* search through string for a token */
ts->input = input;
while (true) {
try {
switch (input.at(ts->position)) {
case '\r': {
/* ignore \r for Windows support */
ts->position++;
break;
}
case '\n': {
ts->current_line++;
ts->position++;
break;
}
case ' ': case '\t': case '\v': case '\f': {
std::string whitespace_token = "";
while (f_iswhitespace(get_next(ts->position, input))) {
whitespace_token += get_next(ts->position, input);
ts->position++;
}
ts->tokens.push_back({token::TOK_WHITE, whitespace_token});
break;
}
case '&': {
/* check for && otherwise & */
if (f_check_next(1, '&')) {
/* generate token for && and incr position to skip over */
ts->tokens.push_back({
token::TOK_BOOLAND, /* token::type */
"&&" /* string self */
});
ts->position += 2;
break;
} /* end if */ /* do not process just & */
/* the nonbreaking default will process single-char tokens */
} /* end case */
case '|': {
/* same as above, check for || otherwise | */
if (f_check_next(1, '|')) {
/* generate || token and incr */
ts->tokens.push_back({token::TOK_BOOLOR, "||"});
ts->position += 2;
break;
}
} /* end case */
case '>': {
/* check for >>, check for >=, or DON'T break */
/* the char lives as itself as a token if nobreak */
bool is_single_char = false;
switch (get_next(ts->position + 1, input)) {
case '>':
ts->tokens.push_back({token::TOK_RSHIFT, ">>"});
break;
case '=':
ts->tokens.push_back({token::TOK_GE, ">="});
break;
default:
is_single_char = true;
} /* end switch */
if (!is_single_char) {
ts->position += 2;
break;
}
} /* end case */
case '<': {
/* duplicate above again, but with < */
bool is_single_char = false;
switch(get_next(ts->position + 1, input)) {
case '<':
ts->tokens.push_back({token::TOK_LSHIFT, "<<"});
break;
case '=':
ts->tokens.push_back({token::TOK_LE, "<="});
break;
default:
is_single_char = true;
} /* end switch */
if (!is_single_char) {
ts->position += 2;
break;
}
} /* end case */
case '=': {
/* check == else = */
if (f_check_next(1, '=')) {
ts->tokens.push_back({token::TOK_EQ, "=="});
ts->position += 2;
break;
}
}
case '!': {
/* check != else = */
if (f_check_next(1, '=')) {
ts->tokens.push_back({token::TOK_NEQ, "!="});
ts->position += 2;
break;
}
}
case '.': {
/* check .., then ...; if not ... then ..; then . */
auto result = try_parse_num(ts);
if (std::get<0>(result)) { /* true if number, false if not */
/* get<1>(result) should return a std::string */
std::string result_num = std::get<1>(result);
ts->tokens.push_back({token::TOK_NUM, result_num});
ts->position += result_num.length();
} else if (f_check_next(1, '.')) {
if (f_check_next(2, '.')) {
/* ... */
ts->tokens.push_back({token::TOK_VARARG, "..."});
ts->position += 3;
break;
} else {
/* .. */
ts->tokens.push_back({token::TOK_CONCAT, ".."});
ts->position += 3;
break;
}
} /* end else if */
} /* end case */
case '_': { /* floor division */
if (f_check_next(1, '/')) {
ts->tokens.push_back({token::TOK_FLOORDIV, "_/"});
ts->position += 2;
break;
}
}
case '"': {
std::string buffer = "\"";
ts->position++; /* increment position past the " */
char current = '\0'; /* current in string */
while (current != '"') { /* we can pass over '\"' during the loop */
current = get_next(ts->position, input);
if (current == '\\') { /* process escape code, C-style */
buffer += "\\" + get_next(ts->position + 2, input);
// TODO verify not '\0'
ts->position += 2;
} else if (current == '"') {
buffer += '"';
ts->position++;
break;
} else {
buffer += current;
ts->position++;
}
} /* end while */
ts->tokens.push_back({token::TOK_STRING, buffer});
break;
} /* end case */
case '\'': {
std::string buffer = "'";
ts->position++; /* incr past ' */
char current = '\0';
while (current != '\'') {
buffer += get_next(ts->position++, input); // TODO verify !'\0'
} /* end while */
ts->tokens.push_back({token::TOK_STRING, buffer});
break;
}
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9': {
/* no matter what, this should return a number */
/* we don't need to test try_parse_num[1] */
std::string result_num = std::get<1>(try_parse_num(ts));
ts->tokens.push_back({token::TOK_NUM, result_num});
ts->position += result_num.length();
break;
} /* end case */
default: {
char current_char = get_next(ts->position, input);
if (isalpha(current_char) || current_char == '_') {
std::string word = "";
while (isalnum(current_char) || current_char == '_') {
word += current_char;
current_char = get_next(++ts->position, input);
if (current_char == '\0')
break;
} /* end while */
/* fully captured word, check if reserved keyword */
bool is_reserved = false;
for (auto iter = tokens.begin();
iter != tokens.end(); ++iter) {
/* find reserved word and push token */
if (word == *iter) {
/* found reserved word */
uint16_t pos = iter - tokens.begin();
ts->tokens.push_back({
static_cast<token::token_t>(pos + FIRST_TOKEN),
word
});
is_reserved = true;
} /* end if */
} /* end for */
if (!is_reserved) ts->tokens.push_back({token::TOK_NAME, word});
/* used as an identifier */
} else {
ts->tokens.push_back({
static_cast<token::token_t>(get_next(ts->position, input)),
std::string(1, get_next(ts->position, input))
});
ts->position++;
} /* end else */
} /* end default */
} /* end switch */
} catch (std::out_of_range const &ignored_exception) {
ts->tokens.push_back({token::TOK_END, ""});
return;
} /* end try */ /* end of input, return final token */
} /* end while */
} /* end function */
} /* end namespace */
int main() {
fusion::TokenizerState ts = fusion::TOKENIZER_STATE_DEFAULT;
fusion::tokenize(&ts, "42");
for (auto token = ts.tokens.begin(); token != ts.tokens.end(); token++) {
if (token->type >= FIRST_TOKEN)
std::cout << fusion::tokens[token->type - FIRST_TOKEN - 1] << " ";
else
std::cout << token->type << " ";
std::cout << token->self << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "betweenness_centrality.hpp"
#include <cassert>
#include <queue>
#include <algorithm>
using namespace std;
namespace betweenness_centrality {
void BetweennessCentralityBase::BuildGraph(const vector<pair<int, int> > &es){
vertex2id.clear();
G[0].clear();
G[1].clear();
V = 0;
E = es.size();
for (const auto &e : es){
if (vertex2id.count(e.fst) == 0) vertex2id[e.fst] = V++;
if (vertex2id.count(e.snd) == 0) vertex2id[e.snd] = V++;
}
G[0].resize(V);
G[1].resize(V);
for (const auto &e : es){
G[0][vertex2id[e.fst]].push_back(vertex2id[e.snd]);
G[1][vertex2id[e.snd]].push_back(vertex2id[e.fst]);
}
}
void BetweennessCentralityNaive::PreCompute(const vector<pair<int, int> > &es) {
BuildGraph(es);
centrality_map = vector<double>(V, 0);
const auto &forward_adj = G[0];
for (int s = 0; (size_t)s < V; s++){
// Brandes' algorithm (2001)
// Step1. Compute distance and the number of shortest paths from s. O(m) time.
vector<int> distance(V, -1);
vector<double> num_paths(V, 0);
vector<double> delta(V, 0);
vector<int> order;
queue<int> que;
distance[s] = 0;
num_paths[s] = 1;
que.push(s);
while (!que.empty()){
int v = que.front(); que.pop(); order.push_back(v);
for (int w : forward_adj[v]){
if (distance[w] == -1){
distance[w] = distance[v] + 1;;
que.push(w);
}
if (distance[w] == distance[v] + 1){
num_paths[w] += num_paths[v];
}
}
}
// Step2. Aggregate betweenness centrality values. O(m) time.
reverse(order.begin(), order.end());
for (int v : order){
for (int w : forward_adj[v]){
if (distance[w] == distance[v] + 1 && num_paths[w] > 0){
delta[v] += num_paths[v] / num_paths[w];
delta[v] += num_paths[v] / num_paths[w] * delta[w];
}
}
}
for (int t = 0; (size_t)t < V; t++){
if (s != t) centrality_map[t] += delta[t];
}
}
}
// void BetweennessCentrality::Index::
// calcPaths(int s, const vector<IVec> &dag, DVec &num_ps){
// assert(num_ps.size() == dag.size() && 0 <= s && s < int(dag.size()));
// fill(num_ps.begin(), num_ps.end(), 0);
// queue<int> que;
// num_ps[s] = 1;
// que.push(s);
// while (!que.empty()){
// int v = que.front(); que.pop();
// for (int w : dag[v]){ // dag[v]は最短路DAGの辺なので距離のチェックは不要
// if (num_ps[w] < EPS) que.push(w);
// num_ps[w] += num_ps[v];
// }
// }
// }
// inline double StaticSketch::Index::getWeight(int id) const {
// if (0 <= id && id < int(id_to_vertex.size()) && id != sources[0] && id != sources[1]){
// return num_ps[0][id] / num_total_paths * num_ps[1][id];
// } else {
// return 0;
// }
// }
// StaticSketch::Index::Index(int s, int t,
// const vector<IVec> &dag_fadj,
// const vector<IVec> &dag_badj,
// const IVec &id_to_vertex)
// : sources({s, t}), adj({dag_fadj, dag_badj}), id_to_vertex(id_to_vertex)
// {
// int n = id_to_vertex.size();
// // assert(s < int(adj[0].size()));
// REP(i, 2){
// num_ps[i].resize(n, 0);
// calcPaths(sources[i], adj[i], num_ps[i]);
// }
// double abs_error = abs(num_ps[0][t] - num_ps[1][s]);
// double max_abs = max(num_ps[0][t], num_ps[1][s]);
// assert(max_abs < EPS || abs_error / max_abs < EPS);
// num_total_paths = num_ps[0][t];
// assert(num_total_paths < 1e100);
// assert(num_total_paths > 0);
// }
// StaticSketch::Index *StaticSketch::buildIndex(int s, int t){
// vector<int> &id_to_vertex = tmp_vars.id_to_vertex;
// vector<int> &vertex_to_id = tmp_vars.vertex_to_id;
// assert(id_to_vertex.empty());
// bidirectionalSearch(s, t);
// if (!id_to_vertex.empty()){
// vector<IVec > dag_fadj(id_to_vertex.size());
// vector<IVec > dag_badj(id_to_vertex.size());
// assert(vertex_to_id[s] != -1 && vertex_to_id[t] != -1);
// for (auto v : id_to_vertex){
// for (auto w : tmp_vars.adj[v]){
// dag_fadj[vertex_to_id[v]].push_back(vertex_to_id[w]);
// dag_badj[vertex_to_id[w]].push_back(vertex_to_id[v]);
// }
// }
// int s_id = vertex_to_id[s];
// int t_id = vertex_to_id[t];
// for (int v : id_to_vertex){
// tmp_vars.adj[v].clear();
// vertex_to_id[v] = -1;
// }
// for (auto v : vertex_to_id) assert(v == -1);
// Index *index = new Index(s_id, t_id, dag_fadj, dag_badj, id_to_vertex);
// id_to_vertex.clear();
// return index;
// } else {
// return nullptr;
// }
// }
// inline void StaticSketch::addNodeToDag(int v){
// if (tmp_vars.vertex_to_id[v] == -1){
// int id = tmp_vars.id_to_vertex.size();
// tmp_vars.id_to_vertex.push_back(v);
// tmp_vars.vertex_to_id[v] = id;
// }
// }
// inline void StaticSketch::
// updateDag(const IVec &dist, queue<int> &que, int v, int w, bool rev){
// if (dist[w] != -1 && dist[w] == dist[v] - 1){
// if (!tmp_vars.dag_nodes[w]){
// tmp_vars.dag_nodes[w] = true;
// que.push(w);
// addNodeToDag(w);
// }
// if (!rev){
// tmp_vars.adj[w].push_back(v);
// } else {
// tmp_vars.adj[v].push_back(w);
// }
// }
// }
// void StaticSketch::bidirectionalSearch(int s, int t){
// assert(s != t);
// int curr = 0;
// int next = 2;
// queue<int> que[4];
// vector<int> update[2];
// vector<int> center;
// que[0].push(s); tmp_vars.dist[0][s] = 0; update[0].push_back(s);
// que[1].push(t); tmp_vars.dist[1][t] = 0; update[1].push_back(t);
// while (!que[curr].empty() || !que[curr + 1].empty()){
// REP(i, 2){
// while (!que[curr + i].empty()){
// int v = que[curr + i].front(); que[curr + i].pop();
// for (int w : adj[i][v]){
// int &src_d = tmp_vars.dist[i ][w];
// int &dst_d = tmp_vars.dist[1 - i][w];
// if (src_d != -1) continue;
// if (dst_d != -1) center.push_back(w);
// que[next + i].push(w);
// update[i].push_back(w);
// tmp_vars.dist[i][w] = tmp_vars.dist[i][v] + 1;
// }
// }
// if (!center.empty()) goto LOOP_END;
// }
// swap(curr, next);
// }
// LOOP_END:
// tmp_vars.id_to_vertex.clear();
// for (int v : center) addNodeToDag(v);
// {
// queue<int> que;
// REP(i, 2){
// for (int v : center) que.push(v);
// while (!que.empty()){
// int v = que.front(); que.pop();
// for (int w : adj[1 - i][v]){
// updateDag(tmp_vars.dist[i], que, v, w, i);
// }
// }
// }
// }
// for (int v :tmp_vars.id_to_vertex) tmp_vars.dag_nodes[v] = false;
// REP(i, 2) {
// for (auto v : update[i]) tmp_vars.dist[i][v] = -1;
// }
// }
// void StaticSketch::init(){
// // adjacecy list以外のメンバ変数を初期化
// centrality = std::vector<double>(num_nodes, 0.0);
// tmp_vars.init(num_nodes);
// indices.clear();
// }
// void StaticSketch::constructSketch(){
// if (num_indices == -1){
// // test用のコード、厳密解をすべての頂点に対してサンプリングを行って求める
// num_indices = num_nodes * num_nodes;
// REP(s, num_nodes) REP(t, num_nodes){
// Index *e = nullptr;
// if (s != t && (e = buildIndex(s, t)) != nullptr){
// REP(j, e->getDagSize()){
// centrality[e->getNode(j)] += e->getWeight(j);
// }
// }
// indices.push_back(e);
// }
// } else {
// // 通常のインデックス作成
// REP(i, num_indices){
// int s = rand() % num_nodes;
// int t = rand() % num_nodes;
// Index *e = nullptr;
// if (s != t && (e = buildIndex(s, t)) != nullptr){
// REP(j, e->getDagSize()){
// centrality[e->getNode(j)] += e->getWeight(j);
// }
// }
// indices.push_back(e);
// }
// }
// }
// void StaticSketch::Compute(const vector<pair<int, int> > &es, int num_samples){
// // Only consider undirected graphs.
// int V = 0;
// for (const auto &e : es){
// V = max({V, e.fst + 1, e.snd + 1});
// }
// vector<vector<int> > G(V);
// for (const auto &e : es){
// G[e.fst].push_back(e.snd);
// G[e.snd].push_back(e.fst);
// }
// vector<vector<int> > dist(2, vector<int>(V));
// clear();
// num_nodes = computeNumNodes(es);
// num_indices = M;
// // setup adjacency lists.
// REP(i, 2){
// adj[i].resize(num_nodes);
// }
// for (auto &e : es){
// adj[0][e.first].push_back(e.second);
// adj[1][e.second].push_back(e.first);
// }
// REP(i, 2) REP(v, num_nodes){
// sort(ALL(adj[i][v]));
// make_unique<int>(adj[i][v]);
// }
// init();
// constructSketch();
// }
}
<commit_msg>Remove unnecessary comments<commit_after>#include "betweenness_centrality.hpp"
#include <cassert>
#include <queue>
#include <algorithm>
using namespace std;
namespace betweenness_centrality {
void BetweennessCentralityBase::BuildGraph(const vector<pair<int, int> > &es){
vertex2id.clear();
G[0].clear();
G[1].clear();
V = 0;
E = es.size();
for (const auto &e : es){
if (vertex2id.count(e.fst) == 0) vertex2id[e.fst] = V++;
if (vertex2id.count(e.snd) == 0) vertex2id[e.snd] = V++;
}
G[0].resize(V);
G[1].resize(V);
for (const auto &e : es){
G[0][vertex2id[e.fst]].push_back(vertex2id[e.snd]);
G[1][vertex2id[e.snd]].push_back(vertex2id[e.fst]);
}
}
void BetweennessCentralityNaive::PreCompute(const vector<pair<int, int> > &es) {
BuildGraph(es);
centrality_map = vector<double>(V, 0);
const auto &forward_adj = G[0];
for (int s = 0; (size_t)s < V; s++){
// Brandes' algorithm (2001)
// Step1. Compute distance and the number of shortest paths from s. O(m) time.
vector<int> distance(V, -1);
vector<double> num_paths(V, 0);
vector<double> delta(V, 0);
vector<int> order;
queue<int> que;
distance[s] = 0;
num_paths[s] = 1;
que.push(s);
while (!que.empty()){
int v = que.front(); que.pop(); order.push_back(v);
for (int w : forward_adj[v]){
if (distance[w] == -1){
distance[w] = distance[v] + 1;;
que.push(w);
}
if (distance[w] == distance[v] + 1){
num_paths[w] += num_paths[v];
}
}
}
// Step2. Aggregate betweenness centrality values. O(m) time.
reverse(order.begin(), order.end());
for (int v : order){
for (int w : forward_adj[v]){
if (distance[w] == distance[v] + 1 && num_paths[w] > 0){
delta[v] += num_paths[v] / num_paths[w];
delta[v] += num_paths[v] / num_paths[w] * delta[w];
}
}
}
for (int t = 0; (size_t)t < V; t++){
if (s != t) centrality_map[t] += delta[t];
}
}
}
}
<|endoftext|> |
<commit_before>#include "background.hpp"
#include "defs.hpp"
#include "client/texturefile.hpp"
#include "sys/rand.hpp"
#include <memory>
#include <stdio.h>
namespace LD22 {
namespace Bkgr {
struct CloudDef {
unsigned char x, y, w, h;
// Call inside a GL_QUADS with the cloud texture
void render(float px, float py) const
{
float x0 = px, x1 = px + 128 * w;
float y0 = py, y1 = py + 128 * h;
float u0 = x * 0.125f, u1 = (x + w) * 0.125f;
float v0 = (y + h) * 0.25f, v1 = y * 0.25f;
glTexCoord2f(u0, v0); glVertex2f(x0, y0);
glTexCoord2f(u0, v1); glVertex2f(x0, y1);
glTexCoord2f(u1, v1); glVertex2f(x1, y1);
glTexCoord2f(u1, v0); glVertex2f(x1, y0);
}
};
static const CloudDef CLOUDS[10] = {
// big clouds
{ 0, 0, 2, 2 },
{ 2, 0, 3, 2 },
{ 5, 0, 3, 2 },
{ 3, 2, 3, 2 },
// medium clouds
{ 0, 2, 3, 1 },
{ 0, 3, 3, 1 },
// small clouds
{ 6, 2, 1, 1 },
{ 6, 3, 1, 1 },
{ 7, 2, 1, 1 },
{ 7, 3, 1, 1 }
};
struct CloudInstance {
short cloud;
short dx;
short dy;
};
static const CloudInstance LAYER1[10] = {
{ 6, 43, 300 },
{ 7, 110, 250 },
{ 8, 177, 275 },
{ 9, 233, 290 },
{ 7, 523, 250 },
{ 6, 570, 300 },
{ 9, 817, 250 },
{ 8, 885, 300 },
{ 6, 893, 300 },
{ 7, 1004, 290 }
};
static const CloudInstance LAYER2[10] = {
{ 6, 0, 200 },
{ 6, 224, 200 },
{ 6, 283, 200 },
{ 6, 385, 200 },
{ 6, 495, 200 },
{ 6, 533, 200 },
{ 6, 640, 200 },
{ 6, 796, 200 },
{ 6, 903, 200 },
{ 6, 915, 200 }
};
static const CloudInstance LAYER3[10] = {
{ 0, 94, 50 },
{ 1, 235, 50 },
{ 2, 350, 50 },
{ 3, 508, 50 },
{ 0, 427, 50 },
{ 2, 477, 50 },
{ 3, 481, 50 },
{ 1, 535, 50 },
{ 2, 733, 50 },
{ 3, 863, 50 }
};
struct CloudLayer {
const CloudInstance *data;
unsigned count;
unsigned offset;
unsigned speed;
};
class Clouds {
static const int LAYERS = 3;
CloudLayer m_layer[LAYERS];
Texture::Ref m_tex;
public:
Clouds()
{ }
void init()
{
m_tex = TextureFile::open("back/clouds.jpg");
m_layer[0].data = LAYER1;
m_layer[1].data = LAYER2;
m_layer[2].data = LAYER3;
m_layer[0].count = 10;
m_layer[1].count = 10;
m_layer[2].count = 10;
for (int i = 0; i < LAYERS; ++i)
m_layer[i].offset = Rand::girand();
m_layer[0].speed = 3;
m_layer[1].speed = 6;
m_layer[2].speed = 8;
}
void advance()
{
for (int i = 0; i < LAYERS; ++i)
m_layer[i].offset += m_layer[i].speed;
}
void draw(int delta)
{
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
m_tex->bind();
// glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
int z = 160;
glColor3ub(z, z, z);
glBegin(GL_QUADS);
for (int i = 0; i < LAYERS; ++i) {
unsigned lpos = m_layer[i].offset +
m_layer[i].speed * delta / FRAME_TIME;
for (unsigned j = 0; j < m_layer[i].count; ++j) {
const CloudInstance &ci = m_layer[i].data[j];
int x = (-SCREEN_WIDTH / 2) + ((ci.dx * 2 + lpos) & 2047);
int y = ci.dy;
CLOUDS[ci.cloud].render(x, y);
}
}
glEnd();
// glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glColor3ub(255, 255, 255);
}
};
class Empty : public Background {
public:
Empty()
: Background(EMPTY)
{ }
virtual ~Empty()
{ }
virtual void init()
{ }
virtual void advance()
{ }
virtual void draw(int delta)
{
float x0 = 0.0f, x1 = SCREEN_WIDTH;
float y0 = 0.0f, y1 = SCREEN_HEIGHT;
glColor3ub(64, 64, 64);
glBegin(GL_QUADS);
glVertex2f(x0, y0);
glVertex2f(x0, y1);
glVertex2f(x1, y1);
glVertex2f(x1, y0);
glEnd();
glColor3ub(255, 255, 255);
(void) delta;
}
};
class Mountains : public Background {
Texture::Ref m_tex;
Clouds m_clouds;
public:
Mountains()
: Background(MOUNTAINS)
{ }
virtual ~Mountains()
{ }
virtual void init()
{
m_tex = TextureFile::open("back/mountains.jpg");
m_clouds.init();
}
virtual void advance()
{
m_clouds.advance();
}
virtual void draw(int delta)
{
float x0 = 0.0f, x1 = SCREEN_WIDTH;
float y0 = 0.0f, y1 = SCREEN_HEIGHT;
float u0 = 0.0f, u1 = 1.0f;
float v0 = 1.0f, v1 = 0.0f;
glEnable(GL_TEXTURE_2D);
m_tex->bind();
glBegin(GL_QUADS);
glTexCoord2f(u0, v0); glVertex2f(x0, y0);
glTexCoord2f(u0, v1); glVertex2f(x0, y1);
glTexCoord2f(u1, v1); glVertex2f(x1, y1);
glTexCoord2f(u1, v0); glVertex2f(x1, y0);
glEnd();
glDisable(GL_TEXTURE_2D);
m_clouds.draw(delta);
}
};
class City : public Background {
Texture::Ref m_tex;
public:
City()
: Background(CITY)
{ }
virtual ~City()
{ }
virtual void init()
{
m_tex = TextureFile::open("back/city.jpg");
}
virtual void advance()
{ }
virtual void draw(int delta)
{
float x0 = 0.0f, x1 = SCREEN_WIDTH;
float y0 = 0.0f, y1 = SCREEN_HEIGHT;
float u0 = 0.0f, u1 = 1.0f;
float v0 = 1.0f, v1 = 0.0f;
glEnable(GL_TEXTURE_2D);
m_tex->bind();
glBegin(GL_QUADS);
glTexCoord2f(u0, v0); glVertex2f(x0, y0);
glTexCoord2f(u0, v1); glVertex2f(x0, y1);
glTexCoord2f(u1, v1); glVertex2f(x1, y1);
glTexCoord2f(u1, v0); glVertex2f(x1, y0);
glEnd();
glDisable(GL_TEXTURE_2D);
}
};
}
Background::~Background()
{ }
Background *Background::getBackground(int which)
{
std::auto_ptr<Background> b;
switch (which) {
case EMPTY:
default:
b.reset(new Bkgr::Empty);
break;
case MOUNTAINS:
b.reset(new Bkgr::Mountains);
break;
case CITY:
b.reset(new Bkgr::City);
break;
}
b->init();
return b.release();
}
}
<commit_msg>Coalesce redundant background code<commit_after>#include "background.hpp"
#include "defs.hpp"
#include "client/texturefile.hpp"
#include "sys/rand.hpp"
#include <memory>
#include <stdio.h>
namespace LD22 {
namespace Bkgr {
struct CloudDef {
unsigned char x, y, w, h;
// Call inside a GL_QUADS with the cloud texture
void render(float px, float py) const
{
float x0 = px, x1 = px + 128 * w;
float y0 = py, y1 = py + 128 * h;
float u0 = x * 0.125f, u1 = (x + w) * 0.125f;
float v0 = (y + h) * 0.25f, v1 = y * 0.25f;
glTexCoord2f(u0, v0); glVertex2f(x0, y0);
glTexCoord2f(u0, v1); glVertex2f(x0, y1);
glTexCoord2f(u1, v1); glVertex2f(x1, y1);
glTexCoord2f(u1, v0); glVertex2f(x1, y0);
}
};
static const CloudDef CLOUDS[10] = {
// big clouds
{ 0, 0, 2, 2 },
{ 2, 0, 3, 2 },
{ 5, 0, 3, 2 },
{ 3, 2, 3, 2 },
// medium clouds
{ 0, 2, 3, 1 },
{ 0, 3, 3, 1 },
// small clouds
{ 6, 2, 1, 1 },
{ 6, 3, 1, 1 },
{ 7, 2, 1, 1 },
{ 7, 3, 1, 1 }
};
struct CloudInstance {
short cloud;
short dx;
short dy;
};
static const CloudInstance LAYER1[10] = {
{ 6, 43, 300 },
{ 7, 110, 250 },
{ 8, 177, 275 },
{ 9, 233, 290 },
{ 7, 523, 250 },
{ 6, 570, 300 },
{ 9, 817, 250 },
{ 8, 885, 300 },
{ 6, 893, 300 },
{ 7, 1004, 290 }
};
static const CloudInstance LAYER2[10] = {
{ 6, 0, 200 },
{ 6, 224, 200 },
{ 6, 283, 200 },
{ 6, 385, 200 },
{ 6, 495, 200 },
{ 6, 533, 200 },
{ 6, 640, 200 },
{ 6, 796, 200 },
{ 6, 903, 200 },
{ 6, 915, 200 }
};
static const CloudInstance LAYER3[10] = {
{ 0, 94, 50 },
{ 1, 235, 50 },
{ 2, 350, 50 },
{ 3, 508, 50 },
{ 0, 427, 50 },
{ 2, 477, 50 },
{ 3, 481, 50 },
{ 1, 535, 50 },
{ 2, 733, 50 },
{ 3, 863, 50 }
};
struct CloudLayer {
const CloudInstance *data;
unsigned count;
unsigned offset;
unsigned speed;
};
class Clouds {
static const int LAYERS = 3;
CloudLayer m_layer[LAYERS];
Texture::Ref m_tex;
public:
Clouds()
{ }
void init()
{
m_tex = TextureFile::open("back/clouds.jpg");
m_layer[0].data = LAYER1;
m_layer[1].data = LAYER2;
m_layer[2].data = LAYER3;
m_layer[0].count = 10;
m_layer[1].count = 10;
m_layer[2].count = 10;
for (int i = 0; i < LAYERS; ++i)
m_layer[i].offset = Rand::girand();
m_layer[0].speed = 3;
m_layer[1].speed = 6;
m_layer[2].speed = 8;
}
void advance()
{
for (int i = 0; i < LAYERS; ++i)
m_layer[i].offset += m_layer[i].speed;
}
void draw(int delta)
{
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
m_tex->bind();
// glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_COLOR);
int z = 160;
glColor3ub(z, z, z);
glBegin(GL_QUADS);
for (int i = 0; i < LAYERS; ++i) {
unsigned lpos = m_layer[i].offset +
m_layer[i].speed * delta / FRAME_TIME;
for (unsigned j = 0; j < m_layer[i].count; ++j) {
const CloudInstance &ci = m_layer[i].data[j];
int x = (-SCREEN_WIDTH / 2) + ((ci.dx * 2 + lpos) & 2047);
int y = ci.dy;
CLOUDS[ci.cloud].render(x, y);
}
}
glEnd();
// glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glColor3ub(255, 255, 255);
}
};
class Empty : public Background {
public:
Empty()
: Background(EMPTY)
{ }
virtual ~Empty()
{ }
virtual void init()
{ }
virtual void advance()
{ }
virtual void draw(int delta)
{
float x0 = 0.0f, x1 = SCREEN_WIDTH;
float y0 = 0.0f, y1 = SCREEN_HEIGHT;
glColor3ub(64, 64, 64);
glBegin(GL_QUADS);
glVertex2f(x0, y0);
glVertex2f(x0, y1);
glVertex2f(x1, y1);
glVertex2f(x1, y0);
glEnd();
glColor3ub(255, 255, 255);
(void) delta;
}
};
class Picture {
std::string m_path;
Texture::Ref m_tex;
public:
Picture(const std::string &path)
: m_path(path)
{ }
void init()
{
m_tex = TextureFile::open(m_path);
}
void draw()
{
float x0 = 0.0f, x1 = SCREEN_WIDTH;
float y0 = 0.0f, y1 = SCREEN_HEIGHT;
float u0 = 0.1f, u1 = 0.9f;
float v0 = 1.0f, v1 = 0.0f;
glEnable(GL_TEXTURE_2D);
m_tex->bind();
glBegin(GL_QUADS);
glTexCoord2f(u0, v0); glVertex2f(x0, y0);
glTexCoord2f(u0, v1); glVertex2f(x0, y1);
glTexCoord2f(u1, v1); glVertex2f(x1, y1);
glTexCoord2f(u1, v0); glVertex2f(x1, y0);
glEnd();
glDisable(GL_TEXTURE_2D);
}
};
class Mountains : public Background {
Picture m_pic;
Clouds m_clouds;
public:
Mountains()
: Background(MOUNTAINS), m_pic("back/mountains.jpg")
{ }
virtual ~Mountains()
{ }
virtual void init()
{
m_pic.init();
m_clouds.init();
}
virtual void advance()
{
m_clouds.advance();
}
virtual void draw(int delta)
{
m_pic.draw();
m_clouds.draw(delta);
}
};
class City : public Background {
Picture m_pic;
public:
City()
: Background(CITY), m_pic("back/city.jpg")
{ }
virtual ~City()
{ }
virtual void init()
{
m_pic.init();
}
virtual void advance()
{ }
virtual void draw(int delta)
{
m_pic.draw();
}
};
}
Background::~Background()
{ }
Background *Background::getBackground(int which)
{
std::auto_ptr<Background> b;
switch (which) {
case EMPTY:
default:
b.reset(new Bkgr::Empty);
break;
case MOUNTAINS:
b.reset(new Bkgr::Mountains);
break;
case CITY:
b.reset(new Bkgr::City);
break;
}
b->init();
return b.release();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 "ast.h"
#include "glsl_types.h"
#include "ir.h"
void
ast_array_specifier::print(void) const
{
if (this->is_unsized_array) {
printf("[ ] ");
}
foreach_list_typed (ast_node, array_dimension, link, &this->array_dimensions) {
printf("[ ");
array_dimension->print();
printf("] ");
}
}
/**
* If \c ir is a reference to an array for which we are tracking the max array
* element accessed, track that the given element has been accessed.
* Otherwise do nothing.
*
* This function also checks whether the array is a built-in array whose
* maximum size is too small to accommodate the given index, and if so uses
* loc and state to report the error.
*/
static void
update_max_array_access(ir_rvalue *ir, unsigned idx, YYLTYPE *loc,
struct _mesa_glsl_parse_state *state)
{
if (ir_dereference_variable *deref_var = ir->as_dereference_variable()) {
ir_variable *var = deref_var->var;
if (idx > var->data.max_array_access) {
var->data.max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly cause
* the size of a built-in array to be too large.
*/
check_builtin_array_max_size(var->name, idx+1, *loc, state);
}
} else if (ir_dereference_record *deref_record =
ir->as_dereference_record()) {
/* There are two possibilities we need to consider:
*
* - Accessing an element of an array that is a member of a named
* interface block (e.g. ifc.foo[i])
*
* - Accessing an element of an array that is a member of a named
* interface block array (e.g. ifc[j].foo[i]).
*/
ir_dereference_variable *deref_var =
deref_record->record->as_dereference_variable();
if (deref_var == NULL) {
if (ir_dereference_array *deref_array =
deref_record->record->as_dereference_array()) {
deref_var = deref_array->array->as_dereference_variable();
}
}
if (deref_var != NULL) {
if (deref_var->var->is_interface_instance()) {
const glsl_type *interface_type =
deref_var->var->get_interface_type();
unsigned field_index =
deref_record->record->type->field_index(deref_record->field);
assert(field_index < interface_type->length);
if (idx > deref_var->var->max_ifc_array_access[field_index]) {
deref_var->var->max_ifc_array_access[field_index] = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(deref_record->field, idx+1, *loc,
state);
}
}
}
}
}
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc)
{
if (!array->type->is_error()
&& !array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
}
if (!idx->type->is_error()) {
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns -1 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array())
update_max_array_access(array, idx, &loc, state);
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->is_unsized_array()) {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
} else if (array->type->fields.array->is_interface()
&& array->variable_referenced()->data.mode == ir_var_uniform
&& !state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
/* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
*
* "All indexes used to index a uniform block array must be
* constant integral expressions."
*/
_mesa_glsl_error(&loc, state,
"uniform block array index must be constant");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*/
if (array->type->element_type()->is_sampler()) {
if (!state->is_version(130, 100)) {
if (state->es_shader) {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is optional in %s",
state->get_version_string());
} else {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL 1.30 "
"and later");
}
} else {
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is forbidden in GLSL 1.30 and "
"later");
}
}
}
/* After performing all of the error checking, generate the IR for the
* expression.
*/
if (array->type->is_array()
|| array->type->is_matrix()) {
return new(mem_ctx) ir_dereference_array(array, idx);
} else if (array->type->is_vector()) {
return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
} else if (array->type->is_error()) {
return array;
} else {
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
result->type = glsl_type::error_type;
return result;
}
}
<commit_msg>glsl: Allow dynamically uniform sampler array indexing with 4.0/gs5<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 "ast.h"
#include "glsl_types.h"
#include "ir.h"
void
ast_array_specifier::print(void) const
{
if (this->is_unsized_array) {
printf("[ ] ");
}
foreach_list_typed (ast_node, array_dimension, link, &this->array_dimensions) {
printf("[ ");
array_dimension->print();
printf("] ");
}
}
/**
* If \c ir is a reference to an array for which we are tracking the max array
* element accessed, track that the given element has been accessed.
* Otherwise do nothing.
*
* This function also checks whether the array is a built-in array whose
* maximum size is too small to accommodate the given index, and if so uses
* loc and state to report the error.
*/
static void
update_max_array_access(ir_rvalue *ir, unsigned idx, YYLTYPE *loc,
struct _mesa_glsl_parse_state *state)
{
if (ir_dereference_variable *deref_var = ir->as_dereference_variable()) {
ir_variable *var = deref_var->var;
if (idx > var->data.max_array_access) {
var->data.max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly cause
* the size of a built-in array to be too large.
*/
check_builtin_array_max_size(var->name, idx+1, *loc, state);
}
} else if (ir_dereference_record *deref_record =
ir->as_dereference_record()) {
/* There are two possibilities we need to consider:
*
* - Accessing an element of an array that is a member of a named
* interface block (e.g. ifc.foo[i])
*
* - Accessing an element of an array that is a member of a named
* interface block array (e.g. ifc[j].foo[i]).
*/
ir_dereference_variable *deref_var =
deref_record->record->as_dereference_variable();
if (deref_var == NULL) {
if (ir_dereference_array *deref_array =
deref_record->record->as_dereference_array()) {
deref_var = deref_array->array->as_dereference_variable();
}
}
if (deref_var != NULL) {
if (deref_var->var->is_interface_instance()) {
const glsl_type *interface_type =
deref_var->var->get_interface_type();
unsigned field_index =
deref_record->record->type->field_index(deref_record->field);
assert(field_index < interface_type->length);
if (idx > deref_var->var->max_ifc_array_access[field_index]) {
deref_var->var->max_ifc_array_access[field_index] = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(deref_record->field, idx+1, *loc,
state);
}
}
}
}
}
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc)
{
if (!array->type->is_error()
&& !array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
}
if (!idx->type->is_error()) {
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns -1 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array())
update_max_array_access(array, idx, &loc, state);
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->is_unsized_array()) {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
} else if (array->type->fields.array->is_interface()
&& array->variable_referenced()->data.mode == ir_var_uniform
&& !state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
/* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
*
* "All indexes used to index a uniform block array must be
* constant integral expressions."
*/
_mesa_glsl_error(&loc, state,
"uniform block array index must be constant");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*
* In GLSL 4.00 / ARB_gpu_shader5, this requirement is relaxed again to allow
* indexing with dynamically uniform expressions. Note that these are not
* required to be uniforms or expressions based on them, but merely that the
* values must not diverge between shader invocations run together. If the
* values *do* diverge, then the behavior of the operation requiring a
* dynamically uniform expression is undefined.
*/
if (array->type->element_type()->is_sampler()) {
if (!state->is_version(130, 100)) {
if (state->es_shader) {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is optional in %s",
state->get_version_string());
} else {
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL 1.30 "
"and later");
}
} else if (!state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions is forbidden in GLSL 1.30 and "
"later");
}
}
}
/* After performing all of the error checking, generate the IR for the
* expression.
*/
if (array->type->is_array()
|| array->type->is_matrix()) {
return new(mem_ctx) ir_dereference_array(array, idx);
} else if (array->type->is_vector()) {
return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
} else if (array->type->is_error()) {
return array;
} else {
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
result->type = glsl_type::error_type;
return result;
}
}
<|endoftext|> |
<commit_before>#include <opencv2/opencv.hpp>
// #include "opencv2/highgui/highgui.hpp"
// #include "opencv2/imgproc/imgproc.hpp"
//#include "opencv2/gpu/gpu.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/cudaobjdetect.hpp"
using namespace cv;
using namespace std;
int main (int argc, const char * argv[]){
Mat img;
//init the descriptors
cv::Ptr<cv::cuda::HOG> gpu_hog = cv::cuda::HOG::create();
HOGDescriptor cpu_hog;
//set the svm to default people detector
gpu_hog->setSVMDetector(gpu_hog->getDefaultPeopleDetector());
cpu_hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
while (true){
img = imread("../walkingPeople.jpeg");
if (!img.data){
cerr<<"Couldn't open image"<<endl;
return -1;
}
// //resizing the video since it's so massive
// resize(img, img, Size(640, 360), 0, 0, INTER_CUBIC);
vector<Rect> found_cpu, found_filtered_cpu;
vector<Rect> found_gpu, found_filtered_gpu;
//comput for the gpu
cuda::GpuMat gpu_img;
gpu_img.upload(img);
gpu_hog->detectMultiScale(gpu_img, found_gpu);
//comput for the cpu
cpu_hog.detectMultiScale(img, found_cpu, 0, Size(8,8), Size(32,32), 1.05, 2);
size_t i, j;
for (i=0; i<found.size(); i++)
{
Rect r = found[i];
for (j=0; j<found.size(); j++)
if (j!=i && (r & found[j]) == r)
break;
if (j== found.size())
found_filtered.push_back(r);
}
for (i=0; i<found_filtered.size(); i++)
{
Rect r = found_filtered[i];
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
}
if(found_filtered.size() > 0){
cout<<"Rec: " << found_filtered[0].x << endl;
}
imwrite("tracking.jpeg",img);
}
return 0;
}
int findObject(vector<Rec> found, Mat img,string filename){
size_t j = 0, i = 0;
vector<Rec> found_filtered;
for (i=0; i<found.size(); i++){
Rect r = found[i];
for (j=0; j<found.size(); j++){
if (j!=i && (r & found[j]) == r){
break;
}
}
if (j== found.size()){
found_filtered.push_back(r);
}
}
for (i=0; i<found_filtered.size(); i++){
Rect r = found_filtered[i];
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
}
imwrite(filename,img);
}
<commit_msg>fixed the rect opencv datatype<commit_after>#include <opencv2/opencv.hpp>
// #include "opencv2/highgui/highgui.hpp"
// #include "opencv2/imgproc/imgproc.hpp"
//#include "opencv2/gpu/gpu.hpp"
#include "opencv2/core/cuda.hpp"
#include "opencv2/cudaobjdetect.hpp"
using namespace cv;
using namespace std;
int findObject(vector<Rect> found, Mat img,string filename);
int main (int argc, const char * argv[]){
Mat img;
//init the descriptors
cv::Ptr<cv::cuda::HOG> gpu_hog = cv::cuda::HOG::create();
HOGDescriptor cpu_hog;
//set the svm to default people detector
gpu_hog->setSVMDetector(gpu_hog->getDefaultPeopleDetector());
cpu_hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
while (true){
img = imread("../walkingPeople.jpeg");
if (!img.data){
cerr<<"Couldn't open image"<<endl;
return -1;
}
// //resizing the video since it's so massive
// resize(img, img, Size(640, 360), 0, 0, INTER_CUBIC);
vector<Rect> found_cpu, found_filtered_cpu;
vector<Rect> found_gpu, found_filtered_gpu;
//comput for the gpu
cuda::GpuMat gpu_img;
gpu_img.upload(img);
gpu_hog->detectMultiScale(gpu_img, found_gpu);
//comput for the cpu
cpu_hog.detectMultiScale(img, found_cpu, 0, Size(8,8), Size(32,32), 1.05, 2);
findObject(found_cpu,img,"tracking_cpu.jpeg");
findObject(found_gpu,img,"tracking_gpu.jpeg");
}
return 0;
}
int findObject(vector<Rect> found, Mat img,string filename){
size_t j = 0, i = 0;
vector<Rect> found_filtered;
for (i=0; i<found.size(); i++){
Rect r = found[i];
for (j=0; j<found.size(); j++){
if (j!=i && (r & found[j]) == r){
break;
}
}
if (j== found.size()){
found_filtered.push_back(r);
}
}
for (i=0; i<found_filtered.size(); i++){
Rect r = found_filtered[i];
r.x += cvRound(r.width*0.1);
r.width = cvRound(r.width*0.8);
r.y += cvRound(r.height*0.07);
r.height = cvRound(r.height*0.8);
rectangle(img, r.tl(), r.br(), Scalar(0,255,0), 3);
}
imwrite(filename,img);
}
<|endoftext|> |
<commit_before>/*
* experimental.cc
*
* Created on: May 1, 2015
* Author: isovic
*/
#include "graphmap/graphmap.h"
#include "graphmap/filter_anchors.h"
int GraphMap::AnchoredPostProcessRegionWithLCS_(ScoreRegistry* local_score, MappingData* mapping_data, const std::vector<Index *> &indexes, const SingleSequence* read, const ProgramParameters* parameters) {
LOG_DEBUG_SPEC("Entering function. [time: %.2f sec, RSS: %ld MB, peakRSS: %ld MB] current_readid = %ld, current_local_score = %ld\n", (((float) (clock())) / CLOCKS_PER_SEC), getCurrentRSS() / (1024 * 1024), getPeakRSS() / (1024 * 1024), read->get_sequence_id(), local_score->get_scores_id());
int lcskpp_length = 0;
std::vector<int> lcskpp_indices;
CalcLCSFromLocalScoresCacheFriendly_(&(local_score->get_registry_entries()), false, 0, 0, &lcskpp_length, &lcskpp_indices);
if (lcskpp_length == 0) {
LogSystem::GetInstance().Log(VERBOSE_LEVEL_ALL_DEBUG, read->get_sequence_id() == parameters->debug_read, FormatString("Current local scores: %ld, lcskpp_length == 0 || best_score == NULL\n", local_score->get_scores_id()), "ExperimentalPostProcessRegionWithLCS");
return 1;
}
if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
LOG_DEBUG_SPEC("After LCSk:\n", local_score->get_scores_id());
for (int64_t i = 0; i < lcskpp_indices.size(); i++) {
LOG_DEBUG_SPEC_NO_HEADER("[%ld] %s\n", i, local_score->get_registry_entries().VerboseToString(lcskpp_indices[i]).c_str());
}
LOG_DEBUG_SPEC_NEWLINE;
}
// std::reverse(first_filtered_lcskpp_indices.begin(), first_filtered_lcskpp_indices.end());
/// Filter the LCSk anchors.
std::vector<ClusterAndIndices *> clusters;
std::vector<int> cluster_indices;
std::vector<int32_t> cluster_ids;
/// Filter the LCSk anchors, first pass. This pass filters outliers, but does not generate clusters.
std::vector<int> first_filtered_lcskpp_indices;
std::vector<int> second_filtered_lcskpp_indices;
FilterAnchorsByChaining(read, local_score, parameters, lcskpp_indices, parameters->error_rate/2 + 0.01f, 200.0f, 0, 50, 2, first_filtered_lcskpp_indices, NULL);
FilterAnchorsByDiff(read, local_score, parameters, first_filtered_lcskpp_indices, second_filtered_lcskpp_indices);
GenerateClusters(2, 50, 50, 0.0, second_filtered_lcskpp_indices, local_score, mapping_data, indexes, read, parameters, clusters, cluster_indices, &cluster_ids);
// Find the L1 parameters (median line and the confidence intervals).
float l_diff = read->get_sequence_length() * parameters->error_rate;
float maximum_allowed_deviation = l_diff * sqrt(2.0f) / 2.0f;
float sigma_L2 = 0.0f, confidence_L1 = 0.0f;
int64_t k = 0, l = 0;
// Actuall L1 calculation.
int ret_L1 = CalculateL1ParametersWithMaximumDeviation_(local_score, cluster_indices, maximum_allowed_deviation, &k, &l, &sigma_L2, &confidence_L1);
// Sanity check.
if (ret_L1) {
LOG_DEBUG_SPEC("An error occured, L1 function (I) returned with %d!\n", ret_L1);
if (ret_L1 == 1) { LOG_DEBUG_SPEC(" lcskpp_indices.size() == 0\n"); }
else if (ret_L1 == 2) { LOG_DEBUG_SPEC(" num_points_under_max_dev_threshold == 0\n"); }
#ifndef RELEASE_VERSION
if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
LOG_DEBUG_SPEC("Writing all anchors to file scores-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/scores-%ld.csv", local_score->get_scores_id()), read, local_score, NULL, 0, 0, false);
LOG_DEBUG_SPEC("Writing LCSk anchors to file LCS-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &lcskpp_indices, 0, 0, false);
LOG_DEBUG_SPEC("Writing LCSk anchors to file LCSL1-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/LCSL1-%ld.csv", local_score->get_scores_id()), read, local_score, &second_filtered_lcskpp_indices, 0, 0, false);
LOG_DEBUG_SPEC("Writing LCSk anchors to file double_LCS-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/double_LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &cluster_indices, 0, 0, false, &cluster_ids);
}
#endif
return 1;
}
float allowed_L1_deviation = 3.0f * confidence_L1;
// Count the number of covered bases, and find the first and last element of the LCSk.
int64_t indexfirst = -1;
int64_t indexlast = -1;
int64_t covered_bases = 0;
int64_t covered_bases_query = 0, covered_bases_reference = 0;
int64_t num_covering_kmers = 0;
LOG_DEBUG_SPEC("Counting the covered bases and finding the first and the last brick index.\n");
for (uint64_t i = 0; i < cluster_indices.size(); i++) {
covered_bases_query += local_score->get_registry_entries().covered_bases_queries[cluster_indices[i]];
covered_bases_reference += local_score->get_registry_entries().covered_bases_references[cluster_indices[i]];
num_covering_kmers += local_score->get_registry_entries().num_kmers[cluster_indices[i]];
}
covered_bases = std::max(covered_bases_query, covered_bases_reference);
if (cluster_indices.size() > 0) {
indexfirst = cluster_indices.back();
indexlast = cluster_indices.front();
}
// There are no valid graph paths! All scores were dismissed because of high deviation.
// This is most likely a false positive.
if (indexfirst == -1 || indexlast == -1) {
LOG_DEBUG_SPEC("An error occured, indexfirst = %ld, indexlast = %ld\n", indexfirst, indexlast);
return 1;
}
MappingResults mapping_info;
mapping_info.lcs_length = lcskpp_length;
mapping_info.cov_bases_query = covered_bases_query;
mapping_info.cov_bases_ref = covered_bases_reference;
mapping_info.cov_bases_max = covered_bases;
mapping_info.query_coords.start = local_score->get_registry_entries().query_starts[indexlast];
mapping_info.query_coords.end = local_score->get_registry_entries().query_ends[indexfirst];
mapping_info.ref_coords.start = local_score->get_registry_entries().reference_starts[indexlast];
mapping_info.ref_coords.end = local_score->get_registry_entries().reference_ends[indexfirst];
mapping_info.num_covering_kmers = num_covering_kmers;
mapping_info.deviation = confidence_L1;
mapping_info.is_reverse = (local_score->get_region().reference_id >= indexes[0]->get_num_sequences_forward());
mapping_info.local_score_id = local_score->get_scores_id();
#ifndef RELEASE_VERSION
LOG_DEBUG_SPEC("Clusters:\n");
#endif
for (int64_t i=0; i<clusters.size(); i++) {
if (clusters[i]) {
Cluster mapping_cluster;
mapping_cluster.query = clusters[i]->query;
mapping_cluster.ref = clusters[i]->ref;
mapping_info.clusters.push_back(mapping_cluster);
#ifndef RELEASE_VERSION
int64_t reference_start = indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id];
int64_t region_start = local_score->get_region().start;
LOG_DEBUG_SPEC("start(%ld, %ld), end(%ld, %ld)\tstart(%ld, %ld), end(%ld, %ld)\n",
mapping_cluster.query.start, mapping_cluster.ref.start, mapping_cluster.query.end, mapping_cluster.ref.end,
mapping_cluster.query.start, mapping_cluster.ref.start - reference_start, mapping_cluster.query.end, mapping_cluster.ref.end - reference_start);
#endif
}
}
L1Results l1_info;
l1_info.l1_l = l;
l1_info.l1_k = 1.0f;
l1_info.l1_lmin = l - l_diff;
l1_info.l1_lmax = l + l_diff;
l1_info.l1_confidence_abs = confidence_L1;
l1_info.l1_std = sigma_L2;
l1_info.l1_rough_start = l1_info.l1_k * 0 + l1_info.l1_lmin;
l1_info.l1_rough_end = l1_info.l1_k * read->get_sequence_length() + l1_info.l1_lmax;
if (l1_info.l1_rough_start < indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id])
l1_info.l1_rough_start = indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id];
if (l1_info.l1_rough_end >= (indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id] + indexes[0]->get_reference_lengths()[local_score->get_region().reference_id]))
l1_info.l1_rough_end = (indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id] + indexes[0]->get_reference_lengths()[local_score->get_region().reference_id]) - 1;
mapping_info.is_mapped = true;
PathGraphEntry *new_entry = new PathGraphEntry(indexes[0], read, parameters, (Region &) local_score->get_region(), &mapping_info, &l1_info);
LogSystem::GetInstance().Log(VERBOSE_LEVEL_HIGH_DEBUG, read->get_sequence_id() == parameters->debug_read, "\n", "[]");
mapping_data->intermediate_mappings.push_back(new_entry);
#ifndef RELEASE_VERSION
if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
LOG_DEBUG_SPEC("Writing all anchors to file scores-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/scores-%ld.csv", local_score->get_scores_id()), read, local_score, NULL, 0, 0, false);
LOG_DEBUG_SPEC("Writing LCSk anchors to file LCS-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &lcskpp_indices, 0, 0, false, NULL);
LOG_DEBUG_SPEC("Writing cluster anchors to file LCSL1-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/LCSL1-%ld.csv", local_score->get_scores_id()), read, local_score, &second_filtered_lcskpp_indices, 0, 0, false);
LOG_DEBUG_SPEC("Writing cluster anchors (again) to file double_LCS-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/double_LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &cluster_indices, l, 3.0f * confidence_L1, false, &cluster_ids);
LOG_DEBUG_SPEC("LCSk clusters:\n");
for (int64_t i=0; i<clusters.size(); i++) {
LOG_DEBUG_SPEC_NO_HEADER("[%ld] num_anchors: %ld, length: %ld, coverage: %ld, query.start = %ld, query.end = %ld\n", i, clusters[i]->num_anchors, (clusters[i]->query.end - clusters[i]->query.start), clusters[i]->coverage, clusters[i]->query.start, clusters[i]->query.end);
}
LOG_DEBUG_SPEC_NEWLINE;
LOG_DEBUG_SPEC("mapping_info.clusters:\n");
for (int64_t i=0; i<mapping_info.clusters.size(); i++) {
LOG_DEBUG_SPEC_NO_HEADER("[%ld] query.start = %ld, query.end = %ld, ref.start = %ld, ref.end = %ld\n", i, mapping_info.clusters[i].query.start, mapping_info.clusters[i].query.end, mapping_info.clusters[i].ref.start, mapping_info.clusters[i].ref.end);
}
LOG_DEBUG_SPEC_NEWLINE;
VerboseClustersToFile_(FormatString("temp/clusters/clusters-read-%ld.csv", read->get_sequence_id()), local_score, mapping_data, indexes, read, parameters, clusters);
}
LOG_DEBUG_SPEC("Exiting function. [time: %.2f sec, RSS: %ld MB, peakRSS: %ld MB]\n", (((float) (clock())) / CLOCKS_PER_SEC), getCurrentRSS() / (1024 * 1024), getPeakRSS() / (1024 * 1024));
#endif
for (int64_t i=0; i<clusters.size(); i++) {
if (clusters[i]) {
delete clusters[i];
}
}
return 0;
}
<commit_msg>Minor parametrization of filter calls.<commit_after>/*
* experimental.cc
*
* Created on: May 1, 2015
* Author: isovic
*/
#include "graphmap/graphmap.h"
#include "graphmap/filter_anchors.h"
int GraphMap::AnchoredPostProcessRegionWithLCS_(ScoreRegistry* local_score, MappingData* mapping_data, const std::vector<Index *> &indexes, const SingleSequence* read, const ProgramParameters* parameters) {
LOG_DEBUG_SPEC("Entering function. [time: %.2f sec, RSS: %ld MB, peakRSS: %ld MB] current_readid = %ld, current_local_score = %ld\n", (((float) (clock())) / CLOCKS_PER_SEC), getCurrentRSS() / (1024 * 1024), getPeakRSS() / (1024 * 1024), read->get_sequence_id(), local_score->get_scores_id());
int lcskpp_length = 0;
std::vector<int> lcskpp_indices;
CalcLCSFromLocalScoresCacheFriendly_(&(local_score->get_registry_entries()), false, 0, 0, &lcskpp_length, &lcskpp_indices);
if (lcskpp_length == 0) {
LogSystem::GetInstance().Log(VERBOSE_LEVEL_ALL_DEBUG, read->get_sequence_id() == parameters->debug_read, FormatString("Current local scores: %ld, lcskpp_length == 0 || best_score == NULL\n", local_score->get_scores_id()), "ExperimentalPostProcessRegionWithLCS");
return 1;
}
if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
LOG_DEBUG_SPEC("After LCSk:\n", local_score->get_scores_id());
for (int64_t i = 0; i < lcskpp_indices.size(); i++) {
LOG_DEBUG_SPEC_NO_HEADER("[%ld] %s\n", i, local_score->get_registry_entries().VerboseToString(lcskpp_indices[i]).c_str());
}
LOG_DEBUG_SPEC_NEWLINE;
}
// std::reverse(first_filtered_lcskpp_indices.begin(), first_filtered_lcskpp_indices.end());
/// Filter the LCSk anchors.
std::vector<ClusterAndIndices *> clusters;
std::vector<int> cluster_indices;
std::vector<int32_t> cluster_ids;
/// Filter the LCSk anchors, first pass. This pass filters outliers, but does not generate clusters.
std::vector<int> first_filtered_lcskpp_indices;
std::vector<int> second_filtered_lcskpp_indices;
// Parameters for anchor filtering.
double indel_bandwidth_margin = parameters->error_rate/2 + 0.01f;
int32_t max_dist = 200;
int64_t min_covered_bases = 50; // TODO: need to experiment with this: std::min((int64_t) (read->get_sequence_length() * 0.10f), (int64_t) 50);
int64_t cluster_size_cutoff = 2; // TODO: need to experiment with this. 1; // 2
FilterAnchorsByChaining(read, local_score, parameters, lcskpp_indices, indel_bandwidth_margin, max_dist, 0, min_covered_bases, cluster_size_cutoff, first_filtered_lcskpp_indices, NULL);
FilterAnchorsByDiff(read, local_score, parameters, first_filtered_lcskpp_indices, second_filtered_lcskpp_indices);
// FilterAnchorsByChaining(read, local_score, parameters, lcskpp_indices, parameters->error_rate/2 + 0.01f, 200.0f, 0, 50, 2, first_filtered_lcskpp_indices, NULL);
// FilterAnchorsByDiff(read, local_score, parameters, first_filtered_lcskpp_indices, second_filtered_lcskpp_indices);
// Parameters for cluster filtering.
int64_t min_num_anchors_in_cluster = 2; // TODO: need to experiment with this. 1; // 2;
int64_t min_cluster_length = min_covered_bases; // 50;
int64_t min_cluster_covered_bases = min_cluster_length; // 50;
float min_cluster_coverage = 0.0f;
GenerateClusters(min_num_anchors_in_cluster, min_cluster_length, min_cluster_covered_bases, min_cluster_coverage,
second_filtered_lcskpp_indices, local_score, mapping_data, indexes, read, parameters, clusters, cluster_indices, &cluster_ids);
// GenerateClusters(2, 50, 50, 0.0, second_filtered_lcskpp_indices, local_score, mapping_data, indexes, read, parameters, clusters, cluster_indices, &cluster_ids);
// Find the L1 parameters (median line and the confidence intervals).
float l_diff = read->get_sequence_length() * parameters->error_rate;
float maximum_allowed_deviation = l_diff * sqrt(2.0f) / 2.0f;
float sigma_L2 = 0.0f, confidence_L1 = 0.0f;
int64_t k = 0, l = 0;
// Actual L1 calculation.
int ret_L1 = CalculateL1ParametersWithMaximumDeviation_(local_score, cluster_indices, maximum_allowed_deviation, &k, &l, &sigma_L2, &confidence_L1);
// Sanity check.
if (ret_L1) {
LOG_DEBUG_SPEC("An error occured, L1 function (I) returned with %d!\n", ret_L1);
if (ret_L1 == 1) { LOG_DEBUG_SPEC(" lcskpp_indices.size() == 0\n"); }
else if (ret_L1 == 2) { LOG_DEBUG_SPEC(" num_points_under_max_dev_threshold == 0\n"); }
#ifndef RELEASE_VERSION
if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
LOG_DEBUG_SPEC("Writing all anchors to file scores-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/scores-%ld.csv", local_score->get_scores_id()), read, local_score, NULL, 0, 0, false);
LOG_DEBUG_SPEC("Writing LCSk anchors to file LCS-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &lcskpp_indices, 0, 0, false);
LOG_DEBUG_SPEC("Writing LCSk anchors to file LCSL1-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/LCSL1-%ld.csv", local_score->get_scores_id()), read, local_score, &second_filtered_lcskpp_indices, 0, 0, false);
LOG_DEBUG_SPEC("Writing LCSk anchors to file double_LCS-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/double_LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &cluster_indices, 0, 0, false, &cluster_ids);
}
#endif
return 1;
}
float allowed_L1_deviation = 3.0f * confidence_L1;
// Count the number of covered bases, and find the first and last element of the LCSk.
int64_t indexfirst = -1;
int64_t indexlast = -1;
int64_t covered_bases = 0;
int64_t covered_bases_query = 0, covered_bases_reference = 0;
int64_t num_covering_kmers = 0;
LOG_DEBUG_SPEC("Counting the covered bases and finding the first and the last brick index.\n");
for (uint64_t i = 0; i < cluster_indices.size(); i++) {
covered_bases_query += local_score->get_registry_entries().covered_bases_queries[cluster_indices[i]];
covered_bases_reference += local_score->get_registry_entries().covered_bases_references[cluster_indices[i]];
num_covering_kmers += local_score->get_registry_entries().num_kmers[cluster_indices[i]];
}
covered_bases = std::max(covered_bases_query, covered_bases_reference);
if (cluster_indices.size() > 0) {
indexfirst = cluster_indices.back();
indexlast = cluster_indices.front();
}
// There are no valid graph paths! All scores were dismissed because of high deviation.
// This is most likely a false positive.
if (indexfirst == -1 || indexlast == -1) {
LOG_DEBUG_SPEC("An error occured, indexfirst = %ld, indexlast = %ld\n", indexfirst, indexlast);
return 1;
}
MappingResults mapping_info;
mapping_info.lcs_length = lcskpp_length;
mapping_info.cov_bases_query = covered_bases_query;
mapping_info.cov_bases_ref = covered_bases_reference;
mapping_info.cov_bases_max = covered_bases;
mapping_info.query_coords.start = local_score->get_registry_entries().query_starts[indexlast];
mapping_info.query_coords.end = local_score->get_registry_entries().query_ends[indexfirst];
mapping_info.ref_coords.start = local_score->get_registry_entries().reference_starts[indexlast];
mapping_info.ref_coords.end = local_score->get_registry_entries().reference_ends[indexfirst];
mapping_info.num_covering_kmers = num_covering_kmers;
mapping_info.deviation = confidence_L1;
mapping_info.is_reverse = (local_score->get_region().reference_id >= indexes[0]->get_num_sequences_forward());
mapping_info.local_score_id = local_score->get_scores_id();
#ifndef RELEASE_VERSION
LOG_DEBUG_SPEC("Clusters:\n");
#endif
for (int64_t i=0; i<clusters.size(); i++) {
if (clusters[i]) {
Cluster mapping_cluster;
mapping_cluster.query = clusters[i]->query;
mapping_cluster.ref = clusters[i]->ref;
mapping_info.clusters.push_back(mapping_cluster);
#ifndef RELEASE_VERSION
int64_t reference_start = indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id];
int64_t region_start = local_score->get_region().start;
LOG_DEBUG_SPEC("start(%ld, %ld), end(%ld, %ld)\tstart(%ld, %ld), end(%ld, %ld)\n",
mapping_cluster.query.start, mapping_cluster.ref.start, mapping_cluster.query.end, mapping_cluster.ref.end,
mapping_cluster.query.start, mapping_cluster.ref.start - reference_start, mapping_cluster.query.end, mapping_cluster.ref.end - reference_start);
#endif
}
}
L1Results l1_info;
l1_info.l1_l = l;
l1_info.l1_k = 1.0f;
l1_info.l1_lmin = l - l_diff;
l1_info.l1_lmax = l + l_diff;
l1_info.l1_confidence_abs = confidence_L1;
l1_info.l1_std = sigma_L2;
l1_info.l1_rough_start = l1_info.l1_k * 0 + l1_info.l1_lmin;
l1_info.l1_rough_end = l1_info.l1_k * read->get_sequence_length() + l1_info.l1_lmax;
if (l1_info.l1_rough_start < indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id])
l1_info.l1_rough_start = indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id];
if (l1_info.l1_rough_end >= (indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id] + indexes[0]->get_reference_lengths()[local_score->get_region().reference_id]))
l1_info.l1_rough_end = (indexes[0]->get_reference_starting_pos()[local_score->get_region().reference_id] + indexes[0]->get_reference_lengths()[local_score->get_region().reference_id]) - 1;
mapping_info.is_mapped = true;
PathGraphEntry *new_entry = new PathGraphEntry(indexes[0], read, parameters, (Region &) local_score->get_region(), &mapping_info, &l1_info);
LogSystem::GetInstance().Log(VERBOSE_LEVEL_HIGH_DEBUG, read->get_sequence_id() == parameters->debug_read, "\n", "[]");
mapping_data->intermediate_mappings.push_back(new_entry);
#ifndef RELEASE_VERSION
if (parameters->verbose_level > 5 && read->get_sequence_id() == parameters->debug_read) {
LOG_DEBUG_SPEC("Writing all anchors to file scores-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/scores-%ld.csv", local_score->get_scores_id()), read, local_score, NULL, 0, 0, false);
LOG_DEBUG_SPEC("Writing LCSk anchors to file LCS-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &lcskpp_indices, 0, 0, false, NULL);
LOG_DEBUG_SPEC("Writing cluster anchors to file LCSL1-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/LCSL1-%ld.csv", local_score->get_scores_id()), read, local_score, &second_filtered_lcskpp_indices, 0, 0, false);
LOG_DEBUG_SPEC("Writing cluster anchors (again) to file double_LCS-%ld.\n", local_score->get_scores_id());
VerboseLocalScoresToFile(FormatString("temp/local_scores/double_LCS-%ld.csv", local_score->get_scores_id()), read, local_score, &cluster_indices, l, 3.0f * confidence_L1, false, &cluster_ids);
LOG_DEBUG_SPEC("LCSk clusters:\n");
for (int64_t i=0; i<clusters.size(); i++) {
LOG_DEBUG_SPEC_NO_HEADER("[%ld] num_anchors: %ld, length: %ld, coverage: %ld, query.start = %ld, query.end = %ld\n", i, clusters[i]->num_anchors, (clusters[i]->query.end - clusters[i]->query.start), clusters[i]->coverage, clusters[i]->query.start, clusters[i]->query.end);
}
LOG_DEBUG_SPEC_NEWLINE;
LOG_DEBUG_SPEC("mapping_info.clusters:\n");
for (int64_t i=0; i<mapping_info.clusters.size(); i++) {
LOG_DEBUG_SPEC_NO_HEADER("[%ld] query.start = %ld, query.end = %ld, ref.start = %ld, ref.end = %ld\n", i, mapping_info.clusters[i].query.start, mapping_info.clusters[i].query.end, mapping_info.clusters[i].ref.start, mapping_info.clusters[i].ref.end);
}
LOG_DEBUG_SPEC_NEWLINE;
VerboseClustersToFile_(FormatString("temp/clusters/clusters-read-%ld.csv", read->get_sequence_id()), local_score, mapping_data, indexes, read, parameters, clusters);
}
LOG_DEBUG_SPEC("Exiting function. [time: %.2f sec, RSS: %ld MB, peakRSS: %ld MB]\n", (((float) (clock())) / CLOCKS_PER_SEC), getCurrentRSS() / (1024 * 1024), getPeakRSS() / (1024 * 1024));
#endif
for (int64_t i=0; i<clusters.size(); i++) {
if (clusters[i]) {
delete clusters[i];
}
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <chartsql/qtree/CallExpressionNode.h>
using namespace fnord;
namespace csql {
CallExpressionNode::CallExpressionNode(
const String& symbol,
Vector<RefPtr<ValueExpressionNode>> arguments) :
symbol_(symbol),
arguments_(arguments) {}
Vector<RefPtr<ValueExpressionNode>> CallExpressionNode::arguments() const {
return arguments_;
}
const String& CallExpressionNode::symbol() const {
return symbol_;
}
RefPtr<QueryTreeNode> CallExpressionNode::deepCopy() const {
Vector<RefPtr<ValueExpressionNode>> args;
for (const auto& arg : arguments_) {
args.emplace_back(arg->deepCopyAs<ValueExpressionNode>());
}
return new CallExpressionNode(symbol_, args);
}
} // namespace csql
<commit_msg>impl CallExpressionNode::toSQL<commit_after>/**
* This file is part of the "libfnord" project
* Copyright (c) 2015 Paul Asmuth
*
* FnordMetric is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License v3.0. You should have received a
* copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include <chartsql/qtree/CallExpressionNode.h>
using namespace fnord;
namespace csql {
CallExpressionNode::CallExpressionNode(
const String& symbol,
Vector<RefPtr<ValueExpressionNode>> arguments) :
symbol_(symbol),
arguments_(arguments) {}
Vector<RefPtr<ValueExpressionNode>> CallExpressionNode::arguments() const {
return arguments_;
}
const String& CallExpressionNode::symbol() const {
return symbol_;
}
RefPtr<QueryTreeNode> CallExpressionNode::deepCopy() const {
Vector<RefPtr<ValueExpressionNode>> args;
for (const auto& arg : arguments_) {
args.emplace_back(arg->deepCopyAs<ValueExpressionNode>());
}
return new CallExpressionNode(symbol_, args);
}
String CallExpressionNode::toSQL() const {
Vector<String> args_sql;
for (const auto& a : arguments_) {
args_sql.emplace_back(a->toSQL());
}
return StringUtil::format(
"$0($1)",
symbol_,
StringUtil::join(args_sql, ","));
}
} // namespace csql
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Arman Pazouki
// =============================================================================
//
// Utility function to print the save fluid, bce, and boundary data into file
// =============================================================================
#include "chrono_fsi/utils/ChUtilsPrintSph.h"
#include "chrono_fsi/ChDeviceUtils.cuh"
#include "chrono_fsi/ChParams.cuh"
#include <fstream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <thrust/reduce.h>
namespace chrono {
namespace fsi {
namespace utils {
//*******************************************************************************************************************************
void PrintToFile(const thrust::device_vector<Real3> &posRadD,
const thrust::device_vector<Real3> &velMasD,
const thrust::device_vector<Real4> &rhoPresMuD,
const thrust::host_vector<int4> &referenceArray,
const std::string &out_dir,
bool printToParaview) {
thrust::host_vector<Real3> posRadH = posRadD;
thrust::host_vector<Real3> velMasH = velMasD;
thrust::host_vector<Real4> rhoPresMuH = rhoPresMuD;
char fileCounter[5];
static int dumNumChar = -1;
dumNumChar++;
sprintf(fileCounter, "%d", dumNumChar);
//*****************************************************
const std::string nameFluid = out_dir + std::string("/fluid") +
std::string(fileCounter) + std::string(".csv");
std::ofstream fileNameFluidParticles;
fileNameFluidParticles.open(nameFluid);
std::stringstream ssFluidParticles;
if(printToParaview)
ssFluidParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";
for (int i = referenceArray[0].x; i < referenceArray[0].y; i++) {
Real3 pos = posRadH[i];
Real3 vel = velMasH[i];
Real4 rP = rhoPresMuH[i];
Real velMag = length(vel);
ssFluidParticles << pos.x << ", " << pos.y << ", " << pos.z << ", " << vel.x
<< ", " << vel.y << ", " << vel.z << ", " << velMag << ", "
<< rP.x << ", " << rP.y << ", " << rP.w << ", "
<< std::endl;
}
fileNameFluidParticles << ssFluidParticles.str();
fileNameFluidParticles.close();
//*****************************************************
const std::string nameFluidBoundaries =
out_dir + std::string("/fluid_boundary") + std::string(fileCounter) +
std::string(".csv");
std::ofstream fileNameFluidBoundaries;
fileNameFluidBoundaries.open(nameFluidBoundaries);
std::stringstream ssFluidBoundaryParticles;
if(printToParaview)
ssFluidParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";
// ssFluidBoundaryParticles.precision(20);
for (int i = referenceArray[0].x; i < referenceArray[1].y; i++) {
Real3 pos = posRadH[i];
Real3 vel = velMasH[i];
Real4 rP = rhoPresMuH[i];
Real velMag = length(vel);
ssFluidBoundaryParticles << pos.x << ", " << pos.y << ", " << pos.z << ", "
<< vel.x << ", " << vel.y << ", " << vel.z << ", "
<< velMag << ", " << rP.x << ", " << rP.y << ", "
<< rP.z << ", " << rP.w << ", " << std::endl;
}
fileNameFluidBoundaries << ssFluidBoundaryParticles.str();
fileNameFluidBoundaries.close();
//*****************************************************
const std::string nameBCE = out_dir + std::string("/BCE") +
std::string(fileCounter) + std::string(".csv");
std::ofstream fileNameBCE;
fileNameBCE.open(nameBCE);
std::stringstream ssBCE;
// ssFluidBoundaryParticles.precision(20);
if(printToParaview)
ssFluidParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";
int refSize = referenceArray.size();
if (refSize > 2) {
for (int i = referenceArray[2].x; i < referenceArray[refSize - 1].y; i++) {
Real3 pos = posRadH[i];
Real3 vel = velMasH[i];
Real4 rP = rhoPresMuH[i];
Real velMag = length(vel);
ssBCE << pos.x << ", " << pos.y << ", " << pos.z << ", " << vel.x << ", "
<< vel.y << ", " << vel.z << ", " << velMag << ", " << rP.x << ", "
<< rP.y << ", " << rP.z << ", " << rP.w << ", " << std::endl;
}
}
fileNameBCE << ssBCE.str();
fileNameBCE.close();
//*****************************************************
posRadH.clear();
velMasH.clear();
rhoPresMuH.clear();
}
} // end namespace utils
} // end namespace fsi
} // end namespace chrono
<commit_msg>bug fix in exporting to paraview file<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Author: Arman Pazouki
// =============================================================================
//
// Utility function to print the save fluid, bce, and boundary data into file
// =============================================================================
#include "chrono_fsi/utils/ChUtilsPrintSph.h"
#include "chrono_fsi/ChDeviceUtils.cuh"
#include "chrono_fsi/ChParams.cuh"
#include <fstream>
#include <sstream>
#include <cstdio>
#include <cstring>
#include <thrust/reduce.h>
namespace chrono {
namespace fsi {
namespace utils {
//*******************************************************************************************************************************
void PrintToFile(const thrust::device_vector<Real3> &posRadD,
const thrust::device_vector<Real3> &velMasD,
const thrust::device_vector<Real4> &rhoPresMuD,
const thrust::host_vector<int4> &referenceArray,
const std::string &out_dir,
bool printToParaview) {
thrust::host_vector<Real3> posRadH = posRadD;
thrust::host_vector<Real3> velMasH = velMasD;
thrust::host_vector<Real4> rhoPresMuH = rhoPresMuD;
char fileCounter[5];
static int dumNumChar = -1;
dumNumChar++;
sprintf(fileCounter, "%d", dumNumChar);
//*****************************************************
const std::string nameFluid = out_dir + std::string("/fluid") +
std::string(fileCounter) + std::string(".csv");
std::ofstream fileNameFluidParticles;
fileNameFluidParticles.open(nameFluid);
std::stringstream ssFluidParticles;
if(printToParaview)
ssFluidParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";
for (int i = referenceArray[0].x; i < referenceArray[0].y; i++) {
Real3 pos = posRadH[i];
Real3 vel = velMasH[i];
Real4 rP = rhoPresMuH[i];
Real velMag = length(vel);
ssFluidParticles << pos.x << ", " << pos.y << ", " << pos.z << ", " << vel.x
<< ", " << vel.y << ", " << vel.z << ", " << velMag << ", "
<< rP.x << ", " << rP.y << ", " << rP.w << ", "
<< std::endl;
}
fileNameFluidParticles << ssFluidParticles.str();
fileNameFluidParticles.close();
//*****************************************************
const std::string nameFluidBoundaries =
out_dir + std::string("/fluid_boundary") + std::string(fileCounter) +
std::string(".csv");
std::ofstream fileNameFluidBoundaries;
fileNameFluidBoundaries.open(nameFluidBoundaries);
std::stringstream ssFluidBoundaryParticles;
if(printToParaview)
ssFluidBoundaryParticles << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";
// ssFluidBoundaryParticles.precision(20);
for (int i = referenceArray[0].x; i < referenceArray[1].y; i++) {
Real3 pos = posRadH[i];
Real3 vel = velMasH[i];
Real4 rP = rhoPresMuH[i];
Real velMag = length(vel);
ssFluidBoundaryParticles << pos.x << ", " << pos.y << ", " << pos.z << ", "
<< vel.x << ", " << vel.y << ", " << vel.z << ", "
<< velMag << ", " << rP.x << ", " << rP.y << ", "
<< rP.z << ", " << rP.w << ", " << std::endl;
}
fileNameFluidBoundaries << ssFluidBoundaryParticles.str();
fileNameFluidBoundaries.close();
//*****************************************************
const std::string nameBCE = out_dir + std::string("/BCE") +
std::string(fileCounter) + std::string(".csv");
std::ofstream fileNameBCE;
fileNameBCE.open(nameBCE);
std::stringstream ssBCE;
// ssFluidBoundaryParticles.precision(20);
if(printToParaview)
ssBCE << "x,y,z,vx,vy,vz,U,rpx,rpy,rpz,rpw\n";
int refSize = referenceArray.size();
if (refSize > 2) {
for (int i = referenceArray[2].x; i < referenceArray[refSize - 1].y; i++) {
Real3 pos = posRadH[i];
Real3 vel = velMasH[i];
Real4 rP = rhoPresMuH[i];
Real velMag = length(vel);
ssBCE << pos.x << ", " << pos.y << ", " << pos.z << ", " << vel.x << ", "
<< vel.y << ", " << vel.z << ", " << velMag << ", " << rP.x << ", "
<< rP.y << ", " << rP.z << ", " << rP.w << ", " << std::endl;
}
}
fileNameBCE << ssBCE.str();
fileNameBCE.close();
//*****************************************************
posRadH.clear();
velMasH.clear();
rhoPresMuH.clear();
}
} // end namespace utils
} // end namespace fsi
} // end namespace chrono
<|endoftext|> |
<commit_before><commit_msg>remove empty file, leftover from r384<commit_after><|endoftext|> |
<commit_before>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WATCHER 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Connects to a Watcher server and writes the event stream to a KML file suitable for use
* with Google Earth.
*
* @author [email protected]
*/
#include <unistd.h>
#include <getopt.h>
#include <stdint.h>
#include <cassert>
#include <iostream>
#include <cstdlib>
#include "logger.h"
#include "initConfig.h"
#include "singletonConfig.h"
#include "libwatcher/messageStream.h"
#include "libwatcher/watcherGraph.h"
#include "libwatcher/playbackTimeRange.h"
#define TOOL_NAME "earthWatcher"
DECLARE_GLOBAL_LOGGER(TOOL_NAME);
using namespace watcher;
void write_kml(const WatcherGraph& graph, const std::string& outputFile); // kml.cc
namespace watcher {
float LayerPadding = 10;
float Lonoff = 0.0;
float Latoff = 0.0;
float Altoff = 0.0;
}
namespace {
//arguments to getopt_long()
const option OPTIONS[] = {
{ "latoff", required_argument, 0, 'a' },
{ "altoff", required_argument, 0, 'A' },
{ "config", required_argument, 0, 'c' },
{ "help", no_argument, 0, 'h' },
{ "output", required_argument, 0, 'o' },
{ "lonoff", required_argument, 0, 'O' },
{ "refresh", required_argument, 0, 'r' },
{ "seek", required_argument, 0, 'S' },
{ "server", required_argument, 0, 's' },
{ "speed", required_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
const char *CONFIG_FILE = TOOL_NAME ".cfg";
const char *OUTPUT_FILE = "watcher.kml";
const char *PROPERTY_FILE = TOOL_NAME ".log.properties";
const char *DEFAULT_HOST = "127.0.0.1";
const unsigned int DEFAULT_REFRESH = 1; // SECONDS
void usage()
{
const char *SEP = "\t\t"; // separator for argument/description columns
std::cout << "usage: earthWatcher [ -h ] [ -c FILE ]\n"
" -a, --latoff OFF" << SEP << "translate GPS coordinates relative to a given latitude\n"
" -A, --altoff OFF" << SEP << "translate GPS coordinates relative to the given altitude\n"
" -c, --config FILE" << SEP << "specify a configuration file (default: " << CONFIG_FILE << ")\n"
" -d, --speed SPEED" << SEP << "specify the event playback rate (default: 1.0)\n"
" -h, --help\t" << SEP << "display this help message\n"
" -o, --output FILE" << SEP << "specifies the output KML file (default: " << OUTPUT_FILE << ")\n"
" -O, --lonoff OFF" << SEP << "translate GPS coordinates relative to a given longitude\n"
" -r, --refresh SECS" << SEP << "write the the output every SECS seconds (default: " << DEFAULT_REFRESH << ")\n"
" -s, --server HOST" << SEP << "connect to the watcher server on the given host (default: " << DEFAULT_HOST << ")\n"
" -S, --seek POS" << SEP << "start event playback at timestamp POS (default: -1)\n"
"\tPOS may be specified relative to the first and last timestamps in the Watcher database by prefixing the offset with + or -\n"
"\tExample: +5000 means 5 seconds after the first event in the database.\n"
<< std::endl;
}
} // end namespace
int main(int argc, char **argv)
{
TRACE_ENTER();
const char *output_file = 0;
Timestamp start_timestamp = -1 ; // default to EOF (live playback)
unsigned int refresh = DEFAULT_REFRESH;
float speed = 1.0;
bool relativeTS = false; // when true, start_timestamp is relative to first or last event in the Watcher DB
unsigned int args = 0;
enum {
argLayerPadding = (1<<0),
argLonoff = (1<<1),
argLatoff = (1<<2),
argAltoff = (1<<3),
argOutputFile = (1<<4),
argServerName = (1<<5)
};
std::string outputFile(OUTPUT_FILE);
std::string serverName(DEFAULT_HOST);
for (int i; (i = getopt_long(argc, argv, "a:A:hc:d:o:O:r:S:", OPTIONS, 0)) != -1; ) {
switch (i) {
case 'c':
break; //handled by initConfig()
case 'a':
Latoff = atof(optarg);
args |= argLatoff;
break;
case 'A':
Altoff = atof(optarg);
args |= argAltoff;
break;
case 'd':
speed = atoi(optarg);
break;
case 'o': // output-file
outputFile = optarg;
args |= argOutputFile;
break;
case 'O':
Lonoff = atoi(optarg);
args |= argLonoff;
break;
case 'r':
refresh = atoi(optarg);
break;
case 'S':
relativeTS = (optarg[0] == '+' || optarg[0] == '-'); // when +/- is prefix, seek relative to starting/ending event
start_timestamp = atol(optarg);
if (start_timestamp == -1)
relativeTS = false; // special case for EOF value
break;
case 's':
serverName = optarg;
args |= argServerName;
case 'h':
default:
usage();
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
break;
}
}
libconfig::Config& config = SingletonConfig::instance();
SingletonConfig::lock();
std::string configFilename; //filled by initConfig()
if (! watcher::initConfig(config, argc, argv, configFilename))
std::cout << "Configuration file not found. Creating new configuration file and using default runtime values." << std::endl;
SingletonConfig::unlock();
std::string logConf(PROPERTY_FILE);
std::string service("watcherd");
struct {
const char *configName;
std::string *value;
unsigned int bit;
} ConfigString[] = {
{ "logPropertiesFile", &logConf, 0 },
{ "server", &serverName, argServerName },
{ "service", &service, 0 },
{ "outputFile", &outputFile, argOutputFile },
{ 0, 0, 0 } // terminator
};
for (size_t i = 0; ConfigString[i].configName != 0; ++i) {
if ((args & ConfigString[i].bit) == 0 && !config.lookupValue(ConfigString[i].configName, *ConfigString[i].value)) {
LOG_INFO("'" << ConfigString[i].configName << "' not found in the configuration file, using default: " << *ConfigString[i].value
<< " and adding this to the configuration file.");
config.getRoot().add(ConfigString[i].configName, libconfig::Setting::TypeString) = *ConfigString[i].value;
}
}
LOAD_LOG_PROPS(logConf);
LOG_INFO("Logger initialized from file \"" << logConf << "\"");
struct {
const char *configName;
float* value;
unsigned int bit;
} ConfigFloat[] = {
{ "layerPadding", &LayerPadding, argLayerPadding },
{ "lonOff", &Lonoff, argLonoff },
{ "latOff", &Latoff, argLatoff },
{ "altOff", &Altoff, argAltoff },
{ 0, 0, 0 } // terminator
};
for (size_t i = 0; ConfigFloat[i].configName != 0; ++i) {
if ((args & ConfigFloat[i].bit) == 0 && !config.lookupValue(ConfigFloat[i].configName, *ConfigFloat[i].value)) {
LOG_INFO("'" << ConfigFloat[i].configName << "' not found in the configuration file, using default: " << *ConfigFloat[i].value
<< " and adding this to the configuration file.");
config.getRoot().add(ConfigFloat[i].configName, libconfig::Setting::TypeFloat) = *ConfigFloat[i].value;
}
}
// open a message stream of live events for now
MessageStreamPtr ms(MessageStream::createNewMessageStream(serverName, service, start_timestamp, speed));
if (!ms) {
LOG_FATAL("Unable to create new message stream to server \"" << serverName << "\" using service (or port) \"" << service);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
if (relativeTS) {
ms->getMessageTimeRange();
} else {
LOG_INFO("Starting event playback");
ms->startStream();
}
srandom(time(0));//we use random() to select the icon below
WatcherGraph graph;
unsigned int messageNumber = 0;
MessagePtr mp;
time_t last_output = 0; // counter to allow for writing the kml file on a fixed time interval
bool changed = false;
bool needTimeRange = relativeTS;
LOG_INFO("Waiting for events ");
while (ms->getNextMessage(mp)) {
// std::cout << "Message #" << (++messageNumber) << ": " << *mp << std::endl;
if (needTimeRange) {
PlaybackTimeRangeMessagePtr trp(boost::dynamic_pointer_cast<PlaybackTimeRangeMessage>(mp));
if (trp.get() != 0) {
LOG_INFO( "first offset=" << trp->min_ << ", last offset=" << trp->max_ );
needTimeRange = false;
Timestamp off = start_timestamp + (( start_timestamp >= 0 ) ? trp->min_ : trp->max_ );
ms->setStreamTimeStart(off);
LOG_INFO("Starting event playback");
ms->startStream();
continue;
}
}
changed |= graph.updateGraph(mp);
if (changed) {
time_t now = time(0);
if (now - last_output >= refresh) {
graph.doMaintanence(); // expire stale links
LOG_DEBUG("writing kml file");
last_output = now;
write_kml(graph, outputFile);
}
changed = false; // reset flag
}
}
// Save any configuration changes made during the run.
LOG_INFO("Saving last known configuration to " << configFilename);
SingletonConfig::lock();
config.writeFile(configFilename.c_str());
TRACE_EXIT_RET(0);
return 0;
}
<commit_msg>Fixed floating point truncation in --speed and --lonOff arguments.<commit_after>/* Copyright 2009 SPARTA, Inc., dba Cobham Analytic Solutions
*
* This file is part of WATCHER.
*
* WATCHER is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WATCHER 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Watcher. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Connects to a Watcher server and writes the event stream to a KML file suitable for use
* with Google Earth.
*
* @author [email protected]
*/
#include <unistd.h>
#include <getopt.h>
#include <stdint.h>
#include <cassert>
#include <iostream>
#include <cstdlib>
#include "logger.h"
#include "initConfig.h"
#include "singletonConfig.h"
#include "libwatcher/messageStream.h"
#include "libwatcher/watcherGraph.h"
#include "libwatcher/playbackTimeRange.h"
#define TOOL_NAME "earthWatcher"
DECLARE_GLOBAL_LOGGER(TOOL_NAME);
using namespace watcher;
void write_kml(const WatcherGraph& graph, const std::string& outputFile); // kml.cc
namespace watcher {
float LayerPadding = 10;
float Lonoff = 0.0;
float Latoff = 0.0;
float Altoff = 0.0;
}
namespace {
//arguments to getopt_long()
const option OPTIONS[] = {
{ "latoff", required_argument, 0, 'a' },
{ "altoff", required_argument, 0, 'A' },
{ "config", required_argument, 0, 'c' },
{ "help", no_argument, 0, 'h' },
{ "output", required_argument, 0, 'o' },
{ "lonoff", required_argument, 0, 'O' },
{ "refresh", required_argument, 0, 'r' },
{ "seek", required_argument, 0, 'S' },
{ "server", required_argument, 0, 's' },
{ "speed", required_argument, 0, 'd' },
{ 0, 0, 0, 0 }
};
const char *CONFIG_FILE = TOOL_NAME ".cfg";
const char *OUTPUT_FILE = "watcher.kml";
const char *PROPERTY_FILE = TOOL_NAME ".log.properties";
const char *DEFAULT_HOST = "127.0.0.1";
const unsigned int DEFAULT_REFRESH = 1; // SECONDS
void usage()
{
const char *SEP = "\t\t"; // separator for argument/description columns
std::cout << "usage: earthWatcher [ -h ] [ -c FILE ]\n"
" -a, --latoff OFF" << SEP << "translate GPS coordinates relative to a given latitude\n"
" -A, --altoff OFF" << SEP << "translate GPS coordinates relative to the given altitude\n"
" -c, --config FILE" << SEP << "specify a configuration file (default: " << CONFIG_FILE << ")\n"
" -d, --speed SPEED" << SEP << "specify the event playback rate (default: 1.0)\n"
" -h, --help\t" << SEP << "display this help message\n"
" -o, --output FILE" << SEP << "specifies the output KML file (default: " << OUTPUT_FILE << ")\n"
" -O, --lonoff OFF" << SEP << "translate GPS coordinates relative to a given longitude\n"
" -r, --refresh SECS" << SEP << "write the the output every SECS seconds (default: " << DEFAULT_REFRESH << ")\n"
" -s, --server HOST" << SEP << "connect to the watcher server on the given host (default: " << DEFAULT_HOST << ")\n"
" -S, --seek POS" << SEP << "start event playback at timestamp POS (default: -1)\n"
"\tPOS may be specified relative to the first and last timestamps in the Watcher database by prefixing the offset with + or -\n"
"\tExample: +5000 means 5 seconds after the first event in the database.\n"
<< std::endl;
}
} // end namespace
int main(int argc, char **argv)
{
TRACE_ENTER();
const char *output_file = 0;
Timestamp start_timestamp = -1 ; // default to EOF (live playback)
unsigned int refresh = DEFAULT_REFRESH;
float speed = 1.0;
bool relativeTS = false; // when true, start_timestamp is relative to first or last event in the Watcher DB
unsigned int args = 0;
enum {
argLayerPadding = (1<<0),
argLonoff = (1<<1),
argLatoff = (1<<2),
argAltoff = (1<<3),
argOutputFile = (1<<4),
argServerName = (1<<5)
};
std::string outputFile(OUTPUT_FILE);
std::string serverName(DEFAULT_HOST);
for (int i; (i = getopt_long(argc, argv, "a:A:hc:d:o:O:r:S:", OPTIONS, 0)) != -1; ) {
switch (i) {
case 'c':
break; //handled by initConfig()
case 'a':
Latoff = atof(optarg);
args |= argLatoff;
break;
case 'A':
Altoff = atof(optarg);
args |= argAltoff;
break;
case 'd':
speed = atof(optarg);
break;
case 'o': // output-file
outputFile = optarg;
args |= argOutputFile;
break;
case 'O':
Lonoff = atof(optarg);
args |= argLonoff;
break;
case 'r':
refresh = atoi(optarg);
break;
case 'S':
relativeTS = (optarg[0] == '+' || optarg[0] == '-'); // when +/- is prefix, seek relative to starting/ending event
start_timestamp = atol(optarg);
if (start_timestamp == -1)
relativeTS = false; // special case for EOF value
break;
case 's':
serverName = optarg;
args |= argServerName;
case 'h':
default:
usage();
TRACE_EXIT_RET(EXIT_SUCCESS);
return EXIT_SUCCESS;
break;
}
}
libconfig::Config& config = SingletonConfig::instance();
SingletonConfig::lock();
std::string configFilename; //filled by initConfig()
if (! watcher::initConfig(config, argc, argv, configFilename))
std::cout << "Configuration file not found. Creating new configuration file and using default runtime values." << std::endl;
SingletonConfig::unlock();
/* handle log.properties file as a special case */
std::string logConf(PROPERTY_FILE);
if (!config.lookupValue("logProperties", logConf)) {
config.getRoot().add("logProperties", libconfig::Setting::TypeString) = logConf;
}
LOAD_LOG_PROPS(logConf);
LOG_INFO("Logger initialized from file \"" << logConf << "\"");
std::string service("watcherd");
struct {
const char *configName;
std::string *value;
unsigned int bit;
} ConfigString[] = {
{ "server", &serverName, argServerName },
{ "service", &service, 0 },
{ "outputFile", &outputFile, argOutputFile },
{ 0, 0, 0 } // terminator
};
for (size_t i = 0; ConfigString[i].configName != 0; ++i) {
if ((args & ConfigString[i].bit) == 0 && !config.lookupValue(ConfigString[i].configName, *ConfigString[i].value)) {
LOG_INFO("'" << ConfigString[i].configName << "' not found in the configuration file, using default: " << *ConfigString[i].value
<< " and adding this to the configuration file.");
config.getRoot().add(ConfigString[i].configName, libconfig::Setting::TypeString) = *ConfigString[i].value;
}
}
LOG_DEBUG("latOff=" << Latoff << " lonOff=" << Lonoff << " altOff=" << Altoff);
struct {
const char *configName;
float* value;
unsigned int bit;
} ConfigFloat[] = {
{ "layerPadding", &LayerPadding, argLayerPadding },
{ "lonOff", &Lonoff, argLonoff },
{ "latOff", &Latoff, argLatoff },
{ "altOff", &Altoff, argAltoff },
{ 0, 0, 0 } // terminator
};
for (size_t i = 0; ConfigFloat[i].configName != 0; ++i) {
if ((args & ConfigFloat[i].bit) == 0 && !config.lookupValue(ConfigFloat[i].configName, *ConfigFloat[i].value)) {
LOG_INFO("'" << ConfigFloat[i].configName << "' not found in the configuration file, using default: " << *ConfigFloat[i].value
<< " and adding this to the configuration file.");
config.getRoot().add(ConfigFloat[i].configName, libconfig::Setting::TypeFloat) = *ConfigFloat[i].value;
}
}
// open a message stream of live events for now
MessageStreamPtr ms(MessageStream::createNewMessageStream(serverName, service, start_timestamp, speed));
if (!ms) {
LOG_FATAL("Unable to create new message stream to server \"" << serverName << "\" using service (or port) \"" << service);
TRACE_EXIT_RET(EXIT_FAILURE);
return EXIT_FAILURE;
}
if (relativeTS) {
ms->getMessageTimeRange();
} else {
LOG_INFO("Starting event playback");
ms->startStream();
}
srandom(time(0));//we use random() to select the icon below
WatcherGraph graph;
unsigned int messageNumber = 0;
MessagePtr mp;
time_t last_output = 0; // counter to allow for writing the kml file on a fixed time interval
bool changed = false;
bool needTimeRange = relativeTS;
LOG_INFO("Waiting for events ");
while (ms->getNextMessage(mp)) {
// std::cout << "Message #" << (++messageNumber) << ": " << *mp << std::endl;
if (needTimeRange) {
PlaybackTimeRangeMessagePtr trp(boost::dynamic_pointer_cast<PlaybackTimeRangeMessage>(mp));
if (trp.get() != 0) {
LOG_INFO( "first offset=" << trp->min_ << ", last offset=" << trp->max_ );
needTimeRange = false;
Timestamp off = start_timestamp + (( start_timestamp >= 0 ) ? trp->min_ : trp->max_ );
ms->setStreamTimeStart(off);
LOG_INFO("Starting event playback");
ms->startStream();
continue;
}
}
changed |= graph.updateGraph(mp);
if (changed) {
time_t now = time(0);
if (now - last_output >= refresh) {
graph.doMaintanence(); // expire stale links
LOG_DEBUG("writing kml file");
last_output = now;
write_kml(graph, outputFile);
}
changed = false; // reset flag
}
}
// Save any configuration changes made during the run.
LOG_INFO("Saving last known configuration to " << configFilename);
SingletonConfig::lock();
config.writeFile(configFilename.c_str());
TRACE_EXIT_RET(0);
return 0;
}
<|endoftext|> |
<commit_before>/**
*
* Author : Shujia Huang
* Date : 2014-08-21
*
**/
#include "Region.h"
vector<Region> MergeRegion(vector<Region> ®Vect, int delta=1) {
// CAUTION: The 'info' value in each member of regVect will been clean
// after merge!
vector<Region> newVect;
map<string, long int> prePos;
Region reg;
bool flag(false);
for (size_t i(0); i < regVect.size(); ++i) {
if (regVect[i].start > regVect[i].end) {
cerr << "[ERROR] MergeRegion ERROR! Your region start > end, "
<< "which does not allow when calling MergeRegion()!\n";
exit(1);
}
if (prePos.count(regVect[i].id)) {
if (prePos[regVect[i].id] > regVect[i].start) {
cerr << "[ERROR]Your target hasn't been sorted.\n";
regVect[i].OutErrReg();
exit(1);
}
if (reg.end + delta >= regVect[i].start) {
if (reg.end < regVect[i].end) reg.end = regVect[i].end;
} else {
newVect.push_back(reg);
reg = regVect[i];
}
} else {
if (flag) newVect.push_back(reg);
reg = regVect[i];
flag = true;
}
prePos[regVect[i].id] = regVect[i].start;
}
if (flag) newVect.push_back(reg);
return newVect;
}
<commit_msg>Add Nocall region into VCF file<commit_after>/**
*
* Author : Shujia Huang
* Date : 2014-08-21
*
**/
#include "Region.h"
vector<Region> MergeRegion(vector<Region> ®Vect, int delta=1) {
// CAUTION: The 'info' value in each member of regVect will been clean
// after merge!
vector<Region> newVect;
map<string, long int> prePos;
Region reg;
bool flag(false);
for (size_t i(0); i < regVect.size(); ++i) {
if (regVect[i].start > regVect[i].end) {
cerr << "[ERROR] MergeRegion ERROR! Your region start > end, "
<< "which does not allow when calling MergeRegion()!\n";
exit(1);
}
if (prePos.count(regVect[i].id)) {
if (prePos[regVect[i].id] > regVect[i].start) {
cerr << "[ERROR]Your target hasn't been sorted.\n";
regVect[i].OutErrReg();
exit(1);
}
if (reg.end + delta >= regVect[i].start) {
if (reg.end < regVect[i].end) reg.end = regVect[i].end;
} else {
newVect.push_back(reg);
reg = regVect[i];
}
} else {
if (flag) newVect.push_back(reg);
reg = regVect[i];
flag = true;
}
prePos[regVect[i].id] = regVect[i].start;
}
if (flag) newVect.push_back(reg);
for (size_t i(0); i < regVect.size(); ++i) {
regVect[i].OutErrReg();
}
cerr << "**** Test Region Merge ****\n";
for (size_t i(0); i < newVect.size(); ++i) {
newVect[i].OutErrReg();
}
exit(1);
return newVect;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>
#include "QXmppConstants.h"
QXmppPresence::QXmppPresence(QXmppPresence::Type type,
const QXmppPresence::Status& status)
: QXmppStanza(), m_type(type), m_status(status)
{
}
QXmppPresence::~QXmppPresence()
{
}
QXmppPresence::Type QXmppPresence::type() const
{
return m_type;
}
void QXmppPresence::setType(QXmppPresence::Type type)
{
m_type = type;
}
const QXmppPresence::Status& QXmppPresence::status() const
{
return m_status;
}
QXmppPresence::Status& QXmppPresence::status()
{
return m_status;
}
void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
m_status = status;
}
void QXmppPresence::parse(const QDomElement &element)
{
QXmppStanza::parse(element);
setTypeFromStr(element.attribute("type"));
m_status.parse(element);
QXmppElementList extensions;
QDomElement xElement = element.firstChildElement();
m_vCardUpdateType = VCardUpdateNone;
while(!xElement.isNull())
{
// XEP-0153: vCard-Based Avatars
if(xElement.namespaceURI() == ns_vcard_update)
{
QDomElement photoElement = xElement.firstChildElement("photo");
if(!photoElement.isNull())
{
m_photoHash = QByteArray::fromHex(photoElement.text().toAscii());
if(m_photoHash.isEmpty())
m_vCardUpdateType = PhotoNotAdvertized;
else
m_vCardUpdateType = PhotoAdvertised;
}
else
{
m_photoHash = QByteArray();
m_vCardUpdateType = PhotoNotReady;
}
}
// XEP-0115: Entity Capabilities
else if(xElement.tagName() == "c" && xElement.namespaceURI() == ns_capabilities)
{
m_capabilityNode = xElement.attribute("node");
m_capabilityVer = QByteArray::fromBase64(xElement.attribute("ver").toAscii());
m_capabilityHash = xElement.attribute("hash");
m_capabilityExt = xElement.attribute("ext").split(" ", QString::SkipEmptyParts);
}
else if (xElement.tagName() == "error")
{
}
else if (xElement.tagName() == "show")
{
}
else if (xElement.tagName() == "status")
{
}
else if (xElement.tagName() == "priority")
{
}
else
{
// other extensions
extensions << QXmppElement(xElement);
}
xElement = xElement.nextSiblingElement();
}
setExtensions(extensions);
}
void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
xmlWriter->writeStartElement("presence");
helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
helperToXmlAddAttribute(xmlWriter,"id", id());
helperToXmlAddAttribute(xmlWriter,"to", to());
helperToXmlAddAttribute(xmlWriter,"from", from());
helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
m_status.toXml(xmlWriter);
error().toXml(xmlWriter);
// XEP-0153: vCard-Based Avatars
if(m_vCardUpdateType != VCardUpdateNone)
{
xmlWriter->writeStartElement("x");
helperToXmlAddAttribute(xmlWriter, "xmlns", ns_vcard_update);
switch(m_vCardUpdateType)
{
case PhotoNotAdvertized:
helperToXmlAddTextElement(xmlWriter, "photo", "");
break;
case PhotoAdvertised:
helperToXmlAddTextElement(xmlWriter, "photo", m_photoHash.toHex());
break;
case PhotoNotReady:
break;
default:
break;
}
xmlWriter->writeEndElement();
}
if(!m_capabilityNode.isEmpty() && !m_capabilityVer.isEmpty()
&& !m_capabilityHash.isEmpty())
{
xmlWriter->writeStartElement("c");
helperToXmlAddAttribute(xmlWriter, "xmlns", ns_capabilities);
helperToXmlAddAttribute(xmlWriter, "hash", m_capabilityHash);
helperToXmlAddAttribute(xmlWriter, "node", m_capabilityNode);
helperToXmlAddAttribute(xmlWriter, "ver", m_capabilityVer.toBase64());
xmlWriter->writeEndElement();
}
foreach (const QXmppElement &extension, extensions())
extension.toXml(xmlWriter);
xmlWriter->writeEndElement();
}
QString QXmppPresence::getTypeStr() const
{
QString text;
switch(m_type)
{
case QXmppPresence::Error:
text = "error";
break;
case QXmppPresence::Available:
// no type-attribute if available
text = "";
break;
case QXmppPresence::Unavailable:
text = "unavailable";
break;
case QXmppPresence::Subscribe:
text = "subscribe";
break;
case QXmppPresence::Subscribed:
text = "subscribed";
break;
case QXmppPresence::Unsubscribe:
text = "unsubscribe";
break;
case QXmppPresence::Unsubscribed:
text = "unsubscribed";
break;
case QXmppPresence::Probe:
text = "probe";
break;
default:
qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
break;
}
return text;
}
void QXmppPresence::setTypeFromStr(const QString& str)
{
QXmppPresence::Type type;
if(str == "error")
{
type = QXmppPresence::Error;
setType(type);
return;
}
else if(str == "unavailable")
{
type = QXmppPresence::Unavailable;
setType(type);
return;
}
else if(str == "subscribe")
{
type = QXmppPresence::Subscribe;
setType(type);
return;
}
else if(str == "subscribed")
{
type = QXmppPresence::Subscribed;
setType(type);
return;
}
else if(str == "unsubscribe")
{
type = QXmppPresence::Unsubscribe;
setType(type);
return;
}
else if(str == "unsubscribed")
{
type = QXmppPresence::Unsubscribed;
setType(type);
return;
}
else if(str == "probe")
{
type = QXmppPresence::Probe;
setType(type);
return;
}
else if(str == "")
{
type = QXmppPresence::Available;
setType(type);
return;
}
else
{
type = static_cast<QXmppPresence::Type>(-1);
qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
qPrintable(str));
setType(type);
return;
}
}
QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
const QString statusText, int priority) :
m_type(type),
m_statusText(statusText), m_priority(priority)
{
}
QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
return m_type;
}
void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
m_type = type;
}
void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
// there is no keyword for Offline
QXmppPresence::Status::Type type;
if(str == "") // not type-attribute means online
{
type = QXmppPresence::Status::Online;
setType(type);
return;
}
else if(str == "away")
{
type = QXmppPresence::Status::Away;
setType(type);
return;
}
else if(str == "xa")
{
type = QXmppPresence::Status::XA;
setType(type);
return;
}
else if(str == "dnd")
{
type = QXmppPresence::Status::DND;
setType(type);
return;
}
else if(str == "chat")
{
type = QXmppPresence::Status::Chat;
setType(type);
return;
}
else
{
type = static_cast<QXmppPresence::Status::Type>(-1);
qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
qPrintable(str));
setType(type);
}
}
QString QXmppPresence::Status::getTypeStr() const
{
QString text;
switch(m_type)
{
case QXmppPresence::Status::Online:
// no type-attribute if available
text = "";
break;
case QXmppPresence::Status::Offline:
text = "";
break;
case QXmppPresence::Status::Away:
text = "away";
break;
case QXmppPresence::Status::XA:
text = "xa";
break;
case QXmppPresence::Status::DND:
text = "dnd";
break;
case QXmppPresence::Status::Chat:
text = "chat";
break;
default:
qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
(int)m_type);
break;
}
return text;
}
QString QXmppPresence::Status::statusText() const
{
return m_statusText;
}
void QXmppPresence::Status::setStatusText(const QString& str)
{
m_statusText = str;
}
int QXmppPresence::Status::priority() const
{
return m_priority;
}
void QXmppPresence::Status::setPriority(int priority)
{
m_priority = priority;
}
void QXmppPresence::Status::parse(const QDomElement &element)
{
setTypeFromStr(element.firstChildElement("show").text());
m_statusText = element.firstChildElement("status").text();
m_priority = element.firstChildElement("priority").text().toInt();
}
void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
const QString show = getTypeStr();
if (!show.isEmpty())
helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
if (!m_statusText.isEmpty())
helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
if (m_priority != 0)
helperToXmlAddNumberElement(xmlWriter, "priority", m_priority);
}
QByteArray QXmppPresence::photoHash() const
{
return m_photoHash;
}
void QXmppPresence::setPhotoHash(const QByteArray& photoHash)
{
m_photoHash = photoHash;
}
QXmppPresence::VCardUpdateType QXmppPresence::vCardUpdateType()
{
return m_vCardUpdateType;
}
void QXmppPresence::setVCardUpdateType(VCardUpdateType type)
{
m_vCardUpdateType = type;
}
/// XEP-0115: Entity Capabilities
QString QXmppPresence::capabilityHash()
{
return m_capabilityHash;
}
/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityHash(const QString& hash)
{
m_capabilityHash = hash;
}
/// XEP-0115: Entity Capabilities
QString QXmppPresence::capabilityNode()
{
return m_capabilityNode;
}
/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityNode(const QString& node)
{
m_capabilityNode = node;
}
/// XEP-0115: Entity Capabilities
QByteArray QXmppPresence::capabilityVer()
{
return m_capabilityVer;
}
/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityVer(const QByteArray& ver)
{
m_capabilityVer = ver;
}
/// Legacy XEP-0115: Entity Capabilities
QStringList QXmppPresence::capabilityExt()
{
return m_capabilityExt;
}
/// \cond
QXmppPresence::Type QXmppPresence::getType() const
{
return m_type;
}
const QXmppPresence::Status& QXmppPresence::getStatus() const
{
return m_status;
}
QXmppPresence::Status& QXmppPresence::getStatus()
{
return m_status;
}
QXmppPresence::Status::Type QXmppPresence::Status::getType() const
{
return m_type;
}
QString QXmppPresence::Status::getStatusText() const
{
return m_statusText;
}
int QXmppPresence::Status::getPriority() const
{
return m_priority;
}
/// \endcond
<commit_msg>initialise QXmppPresence::m_vCardUpdateType (Closes: #82)<commit_after>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "QXmppPresence.h"
#include "QXmppUtils.h"
#include <QtDebug>
#include <QDomElement>
#include <QXmlStreamWriter>
#include "QXmppConstants.h"
QXmppPresence::QXmppPresence(QXmppPresence::Type type,
const QXmppPresence::Status& status)
: QXmppStanza(),
m_type(type),
m_status(status),
m_vCardUpdateType(VCardUpdateNone)
{
}
QXmppPresence::~QXmppPresence()
{
}
QXmppPresence::Type QXmppPresence::type() const
{
return m_type;
}
void QXmppPresence::setType(QXmppPresence::Type type)
{
m_type = type;
}
const QXmppPresence::Status& QXmppPresence::status() const
{
return m_status;
}
QXmppPresence::Status& QXmppPresence::status()
{
return m_status;
}
void QXmppPresence::setStatus(const QXmppPresence::Status& status)
{
m_status = status;
}
void QXmppPresence::parse(const QDomElement &element)
{
QXmppStanza::parse(element);
setTypeFromStr(element.attribute("type"));
m_status.parse(element);
QXmppElementList extensions;
QDomElement xElement = element.firstChildElement();
m_vCardUpdateType = VCardUpdateNone;
while(!xElement.isNull())
{
// XEP-0153: vCard-Based Avatars
if(xElement.namespaceURI() == ns_vcard_update)
{
QDomElement photoElement = xElement.firstChildElement("photo");
if(!photoElement.isNull())
{
m_photoHash = QByteArray::fromHex(photoElement.text().toAscii());
if(m_photoHash.isEmpty())
m_vCardUpdateType = PhotoNotAdvertized;
else
m_vCardUpdateType = PhotoAdvertised;
}
else
{
m_photoHash = QByteArray();
m_vCardUpdateType = PhotoNotReady;
}
}
// XEP-0115: Entity Capabilities
else if(xElement.tagName() == "c" && xElement.namespaceURI() == ns_capabilities)
{
m_capabilityNode = xElement.attribute("node");
m_capabilityVer = QByteArray::fromBase64(xElement.attribute("ver").toAscii());
m_capabilityHash = xElement.attribute("hash");
m_capabilityExt = xElement.attribute("ext").split(" ", QString::SkipEmptyParts);
}
else if (xElement.tagName() == "error")
{
}
else if (xElement.tagName() == "show")
{
}
else if (xElement.tagName() == "status")
{
}
else if (xElement.tagName() == "priority")
{
}
else
{
// other extensions
extensions << QXmppElement(xElement);
}
xElement = xElement.nextSiblingElement();
}
setExtensions(extensions);
}
void QXmppPresence::toXml(QXmlStreamWriter *xmlWriter) const
{
xmlWriter->writeStartElement("presence");
helperToXmlAddAttribute(xmlWriter,"xml:lang", lang());
helperToXmlAddAttribute(xmlWriter,"id", id());
helperToXmlAddAttribute(xmlWriter,"to", to());
helperToXmlAddAttribute(xmlWriter,"from", from());
helperToXmlAddAttribute(xmlWriter,"type", getTypeStr());
m_status.toXml(xmlWriter);
error().toXml(xmlWriter);
// XEP-0153: vCard-Based Avatars
if(m_vCardUpdateType != VCardUpdateNone)
{
xmlWriter->writeStartElement("x");
helperToXmlAddAttribute(xmlWriter, "xmlns", ns_vcard_update);
switch(m_vCardUpdateType)
{
case PhotoNotAdvertized:
helperToXmlAddTextElement(xmlWriter, "photo", "");
break;
case PhotoAdvertised:
helperToXmlAddTextElement(xmlWriter, "photo", m_photoHash.toHex());
break;
case PhotoNotReady:
break;
default:
break;
}
xmlWriter->writeEndElement();
}
if(!m_capabilityNode.isEmpty() && !m_capabilityVer.isEmpty()
&& !m_capabilityHash.isEmpty())
{
xmlWriter->writeStartElement("c");
helperToXmlAddAttribute(xmlWriter, "xmlns", ns_capabilities);
helperToXmlAddAttribute(xmlWriter, "hash", m_capabilityHash);
helperToXmlAddAttribute(xmlWriter, "node", m_capabilityNode);
helperToXmlAddAttribute(xmlWriter, "ver", m_capabilityVer.toBase64());
xmlWriter->writeEndElement();
}
foreach (const QXmppElement &extension, extensions())
extension.toXml(xmlWriter);
xmlWriter->writeEndElement();
}
QString QXmppPresence::getTypeStr() const
{
QString text;
switch(m_type)
{
case QXmppPresence::Error:
text = "error";
break;
case QXmppPresence::Available:
// no type-attribute if available
text = "";
break;
case QXmppPresence::Unavailable:
text = "unavailable";
break;
case QXmppPresence::Subscribe:
text = "subscribe";
break;
case QXmppPresence::Subscribed:
text = "subscribed";
break;
case QXmppPresence::Unsubscribe:
text = "unsubscribe";
break;
case QXmppPresence::Unsubscribed:
text = "unsubscribed";
break;
case QXmppPresence::Probe:
text = "probe";
break;
default:
qWarning("QXmppPresence::getTypeStr() invalid type %d", (int)m_type);
break;
}
return text;
}
void QXmppPresence::setTypeFromStr(const QString& str)
{
QXmppPresence::Type type;
if(str == "error")
{
type = QXmppPresence::Error;
setType(type);
return;
}
else if(str == "unavailable")
{
type = QXmppPresence::Unavailable;
setType(type);
return;
}
else if(str == "subscribe")
{
type = QXmppPresence::Subscribe;
setType(type);
return;
}
else if(str == "subscribed")
{
type = QXmppPresence::Subscribed;
setType(type);
return;
}
else if(str == "unsubscribe")
{
type = QXmppPresence::Unsubscribe;
setType(type);
return;
}
else if(str == "unsubscribed")
{
type = QXmppPresence::Unsubscribed;
setType(type);
return;
}
else if(str == "probe")
{
type = QXmppPresence::Probe;
setType(type);
return;
}
else if(str == "")
{
type = QXmppPresence::Available;
setType(type);
return;
}
else
{
type = static_cast<QXmppPresence::Type>(-1);
qWarning("QXmppPresence::setTypeFromStr() invalid input string type: %s",
qPrintable(str));
setType(type);
return;
}
}
QXmppPresence::Status::Status(QXmppPresence::Status::Type type,
const QString statusText, int priority) :
m_type(type),
m_statusText(statusText), m_priority(priority)
{
}
QXmppPresence::Status::Type QXmppPresence::Status::type() const
{
return m_type;
}
void QXmppPresence::Status::setType(QXmppPresence::Status::Type type)
{
m_type = type;
}
void QXmppPresence::Status::setTypeFromStr(const QString& str)
{
// there is no keyword for Offline
QXmppPresence::Status::Type type;
if(str == "") // not type-attribute means online
{
type = QXmppPresence::Status::Online;
setType(type);
return;
}
else if(str == "away")
{
type = QXmppPresence::Status::Away;
setType(type);
return;
}
else if(str == "xa")
{
type = QXmppPresence::Status::XA;
setType(type);
return;
}
else if(str == "dnd")
{
type = QXmppPresence::Status::DND;
setType(type);
return;
}
else if(str == "chat")
{
type = QXmppPresence::Status::Chat;
setType(type);
return;
}
else
{
type = static_cast<QXmppPresence::Status::Type>(-1);
qWarning("QXmppPresence::Status::setTypeFromStr() invalid input string type %s",
qPrintable(str));
setType(type);
}
}
QString QXmppPresence::Status::getTypeStr() const
{
QString text;
switch(m_type)
{
case QXmppPresence::Status::Online:
// no type-attribute if available
text = "";
break;
case QXmppPresence::Status::Offline:
text = "";
break;
case QXmppPresence::Status::Away:
text = "away";
break;
case QXmppPresence::Status::XA:
text = "xa";
break;
case QXmppPresence::Status::DND:
text = "dnd";
break;
case QXmppPresence::Status::Chat:
text = "chat";
break;
default:
qWarning("QXmppPresence::Status::getTypeStr() invalid type %d",
(int)m_type);
break;
}
return text;
}
QString QXmppPresence::Status::statusText() const
{
return m_statusText;
}
void QXmppPresence::Status::setStatusText(const QString& str)
{
m_statusText = str;
}
int QXmppPresence::Status::priority() const
{
return m_priority;
}
void QXmppPresence::Status::setPriority(int priority)
{
m_priority = priority;
}
void QXmppPresence::Status::parse(const QDomElement &element)
{
setTypeFromStr(element.firstChildElement("show").text());
m_statusText = element.firstChildElement("status").text();
m_priority = element.firstChildElement("priority").text().toInt();
}
void QXmppPresence::Status::toXml(QXmlStreamWriter *xmlWriter) const
{
const QString show = getTypeStr();
if (!show.isEmpty())
helperToXmlAddTextElement(xmlWriter, "show", getTypeStr());
if (!m_statusText.isEmpty())
helperToXmlAddTextElement(xmlWriter, "status", m_statusText);
if (m_priority != 0)
helperToXmlAddNumberElement(xmlWriter, "priority", m_priority);
}
QByteArray QXmppPresence::photoHash() const
{
return m_photoHash;
}
void QXmppPresence::setPhotoHash(const QByteArray& photoHash)
{
m_photoHash = photoHash;
}
QXmppPresence::VCardUpdateType QXmppPresence::vCardUpdateType()
{
return m_vCardUpdateType;
}
void QXmppPresence::setVCardUpdateType(VCardUpdateType type)
{
m_vCardUpdateType = type;
}
/// XEP-0115: Entity Capabilities
QString QXmppPresence::capabilityHash()
{
return m_capabilityHash;
}
/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityHash(const QString& hash)
{
m_capabilityHash = hash;
}
/// XEP-0115: Entity Capabilities
QString QXmppPresence::capabilityNode()
{
return m_capabilityNode;
}
/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityNode(const QString& node)
{
m_capabilityNode = node;
}
/// XEP-0115: Entity Capabilities
QByteArray QXmppPresence::capabilityVer()
{
return m_capabilityVer;
}
/// XEP-0115: Entity Capabilities
void QXmppPresence::setCapabilityVer(const QByteArray& ver)
{
m_capabilityVer = ver;
}
/// Legacy XEP-0115: Entity Capabilities
QStringList QXmppPresence::capabilityExt()
{
return m_capabilityExt;
}
/// \cond
QXmppPresence::Type QXmppPresence::getType() const
{
return m_type;
}
const QXmppPresence::Status& QXmppPresence::getStatus() const
{
return m_status;
}
QXmppPresence::Status& QXmppPresence::getStatus()
{
return m_status;
}
QXmppPresence::Status::Type QXmppPresence::Status::getType() const
{
return m_type;
}
QString QXmppPresence::Status::getStatusText() const
{
return m_statusText;
}
int QXmppPresence::Status::getPriority() const
{
return m_priority;
}
/// \endcond
<|endoftext|> |
<commit_before>#include "QpidPublisher.h"
#include <chrono>
using namespace std::chrono;
// Quote and prefix the project simple topic name.
// * The quotes pass the name to qpid messaging correctly
// * The prefix gets the AMQ broker to use a topic and not a queue
string AmqTopicName(const string name) {
return "'topic://" + name + "'";
}
string AmqQueueName(const string name) {
return "'queue://" + name + "'";
}
void QpidPublisher::start(bool asyncMode) {
printf("QpidPublisher, start, this=%p\n", this);
// Open connection
/* Reconnect behaviour can be controlled through the following options:
* - reconnect: true/false (enables/disables reconnect entirely)
* - reconnect_timeout: seconds (give up and report failure after specified time)
* - reconnect_limit: n (give up and report failure after specified number of attempts)
* - reconnect_interval_min: seconds (initial delay between failed reconnection attempts)
* - reconnect_interval_max: seconds (maximum delay between failed reconnection attempts)
* - reconnect_interval: shorthand for setting the same reconnect_interval_min/max
* - reconnect_urls: list of alternate urls to try when connecting
*
* The reconnect_interval is the time that the client waits for
* after a failed attempt to reconnect before retrying. It starts
* at the value of the min_retry_interval and is doubled every
* failure until the value of max_retry_interval is reached.
*/
// This does not work, reconnect fails to reestablish the flow of messages
//connection = messaging::Connection(brokerUrl, "{protocol:amqp1.0,reconnect:true,reconnect_interval:30}");
connection = messaging::Connection(brokerUrl, "{protocol:amqp1.0}");
connection.open();
disconnectCount = 0;
connected = true;
// Create session
if(useTransactions) {
session = connection.createTransactionalSession();
printf("Created transacted session\n");
}
else {
session = connection.createSession();
printf("Created non-transacted session\n");
}
// Create sender with default topic destination address
string destName = isUseTopics() ? AmqTopicName(destinationName) : AmqQueueName(destinationName);
sender = session.createSender(destName);
printf("Created new sender for: %s\n", destName.c_str());
senders[destName] = sender;
}
void QpidPublisher::stop() {
running = false;
if(sender)
sender.close();
if(session)
session.close();
if(connection)
connection.close();
if(heartbeatMonitorThread) {
heartbeatMonitorThread->detach();
heartbeatMonitorThread.reset(nullptr);
}
sender = messaging::Sender();
session = messaging::Session();
connection = messaging::Connection();
}
void QpidPublisher::queueForPublish(string const &topicName, MqttQOS qos, byte *payload, size_t len) {
// HACK ALERT: tbd
}
void QpidPublisher::publish(string const &destName, MqttQOS qos, byte *payload, size_t len) {
// Use default destination unless a new one is specified
messaging::Sender sndr = sender;
if (destName.length() > 0) {
string fullDestName = isUseTopics() ? AmqTopicName(destName) : AmqQueueName(destName);
sndr = senders[fullDestName];
if(!sndr) {
sndr = session.createSender(fullDestName);
printf("Created new sender for: %s\n", fullDestName.c_str());
senders[fullDestName] = sndr;
}
}
// Create message
messaging::Message message((const char *)payload, len);
if (clientID.length() > 0)
message.setUserId(clientID);
// Send message
sndr.send(message);
// Close temporary sender
if (sndr != sender)
sndr.close();
}
void QpidPublisher::publish(string const &destName, Beacon &beacon) {
// Use default destination unless a new one is specified
messaging::Sender sndr = sender;
if (destName.length() > 0) {
string fullDestName = isUseTopics() ? AmqTopicName(destName) : AmqQueueName(destName);
sndr = senders[fullDestName];
if(!sndr) {
sndr = session.createSender(fullDestName);
printf("Created new sender for: %s\n", fullDestName.c_str());
senders[fullDestName] = sndr;
}
}
doPublishProperties(sndr, beacon, BeconEventType::SCANNER_READ);
// Close temporary sender
if (sndr != sender)
sndr.close();
}
void QpidPublisher::publish(vector<Beacon> events) {
for(int n = 0; n < events.size(); n ++) {
Beacon& b = events.at(n);
publish("", b);
}
session.commit();
}
void QpidPublisher::publishStatus(Beacon &beacon) {
doPublishProperties(sender, beacon, BeconEventType::SCANNER_HEARTBEAT);
}
void QpidPublisher::doPublishProperties(messaging::Sender sndr, Beacon &beacon, BeconEventType messageType) {
messaging::Message message;
message.setProperty("uuid", beacon.getUuid());
message.setProperty("scannerID", beacon.getScannerID());
message.setProperty("major", beacon.getMajor());
message.setProperty("minor", beacon.getMinor());
message.setProperty("manufacturer", beacon.getManufacturer());
message.setProperty("code", beacon.getCode());
message.setProperty("power", beacon.getPower());
message.setProperty("calibratedPower", beacon.getCalibratedPower());
message.setProperty("rssi", beacon.getRssi());
message.setProperty("time", beacon.getTime());
message.setProperty("messageType", messageType);
message.setProperty("scannerSeqNo", beacon.getScannerSequenceNo());
if (clientID.length() > 0)
message.setUserId(clientID);
// Send message
sndr.send(message);
}
void QpidPublisher::publishProperties(string const &destName, map<string,string> const &properties) {
messaging::Sender sndr = sender;
if (destName.length() > 0) {
string fullDestName = isUseTopics() ? AmqTopicName(destName) : AmqQueueName(destName);
sndr = senders[fullDestName];
if(!sndr) {
sndr = session.createSender(fullDestName);
printf("Created new sender for: %s\n", fullDestName.c_str());
senders[fullDestName] = sndr;
}
}
messaging::Message message;
for(map<string, string>::const_iterator iter = properties.begin(); iter != properties.end(); iter ++) {
message.setProperty(iter->first, iter->second);
}
message.setProperty("messageType", SCANNER_STATUS);
if (clientID.length() > 0)
message.setUserId(clientID);
// Send message
sndr.send(message);
}
void QpidPublisher::calculateReconnectTime(int64_t now) {
setNextReconnectTime(now + reconnectInterval*1000);
milliseconds ms(now);
seconds s = duration_cast<seconds>(ms);
time_t t = s.count();
fprintf(stderr, "Will attempt reconnect at: %s\n", ctime(&t));
}
void QpidPublisher::monitorHeartbeats(string const &destinationName, heartbeatReceived callback) {
thread *t = new thread(&QpidPublisher::doMonitorHeartbeats, this, destinationName, callback);
this->heartbeatMonitorThread.reset(t);
}
void QpidPublisher::doMonitorHeartbeats(string const &destinationName, heartbeatReceived callback) {
string destName = isUseTopics() ? AmqTopicName(destinationName) : AmqQueueName(destinationName);
messaging::Receiver receiver = session.createReceiver(destName);
int missedCount = 0;
int receivedCount = 0;
while(running) {
messaging::Message message;
try {
receiver.fetch(message, messaging::Duration::MINUTE);
receivedCount ++;
missedCount = 0;
callback(true, receivedCount, missedCount);
} catch(messaging::NoMessageAvailable& e) {
fprintf(stderr, "Failed to receive own heartbeat for 1 minute, %s\n", e.what());
missedCount ++;
callback(false, receivedCount, missedCount);
}
}
}
<commit_msg>Back to reconnect on by default<commit_after>#include "QpidPublisher.h"
#include <chrono>
using namespace std::chrono;
// Quote and prefix the project simple topic name.
// * The quotes pass the name to qpid messaging correctly
// * The prefix gets the AMQ broker to use a topic and not a queue
string AmqTopicName(const string name) {
return "'topic://" + name + "'";
}
string AmqQueueName(const string name) {
return "'queue://" + name + "'";
}
void QpidPublisher::start(bool asyncMode) {
printf("QpidPublisher, start, this=%p\n", this);
// Open connection
/* Reconnect behaviour can be controlled through the following options:
* - reconnect: true/false (enables/disables reconnect entirely)
* - reconnect_timeout: seconds (give up and report failure after specified time)
* - reconnect_limit: n (give up and report failure after specified number of attempts)
* - reconnect_interval_min: seconds (initial delay between failed reconnection attempts)
* - reconnect_interval_max: seconds (maximum delay between failed reconnection attempts)
* - reconnect_interval: shorthand for setting the same reconnect_interval_min/max
* - reconnect_urls: list of alternate urls to try when connecting
*
* The reconnect_interval is the time that the client waits for
* after a failed attempt to reconnect before retrying. It starts
* at the value of the min_retry_interval and is doubled every
* failure until the value of max_retry_interval is reached.
*/
//connection = messaging::Connection(brokerUrl, "{protocol:amqp1.0}");
connection = messaging::Connection(brokerUrl, "{protocol:amqp1.0,reconnect:true,reconnect_interval:30}");
connection.open();
disconnectCount = 0;
connected = true;
// Create session
if(useTransactions) {
session = connection.createTransactionalSession();
printf("Created transacted session\n");
}
else {
session = connection.createSession();
printf("Created non-transacted session\n");
}
// Create sender with default topic destination address
string destName = isUseTopics() ? AmqTopicName(destinationName) : AmqQueueName(destinationName);
sender = session.createSender(destName);
printf("Created new sender for: %s\n", destName.c_str());
senders[destName] = sender;
}
void QpidPublisher::stop() {
running = false;
if(sender)
sender.close();
if(session)
session.close();
if(connection)
connection.close();
if(heartbeatMonitorThread) {
heartbeatMonitorThread->detach();
heartbeatMonitorThread.reset(nullptr);
}
sender = messaging::Sender();
session = messaging::Session();
connection = messaging::Connection();
}
void QpidPublisher::queueForPublish(string const &topicName, MqttQOS qos, byte *payload, size_t len) {
// HACK ALERT: tbd
}
void QpidPublisher::publish(string const &destName, MqttQOS qos, byte *payload, size_t len) {
// Use default destination unless a new one is specified
messaging::Sender sndr = sender;
if (destName.length() > 0) {
string fullDestName = isUseTopics() ? AmqTopicName(destName) : AmqQueueName(destName);
sndr = senders[fullDestName];
if(!sndr) {
sndr = session.createSender(fullDestName);
printf("Created new sender for: %s\n", fullDestName.c_str());
senders[fullDestName] = sndr;
}
}
// Create message
messaging::Message message((const char *)payload, len);
if (clientID.length() > 0)
message.setUserId(clientID);
// Send message
sndr.send(message);
// Close temporary sender
if (sndr != sender)
sndr.close();
}
void QpidPublisher::publish(string const &destName, Beacon &beacon) {
// Use default destination unless a new one is specified
messaging::Sender sndr = sender;
if (destName.length() > 0) {
string fullDestName = isUseTopics() ? AmqTopicName(destName) : AmqQueueName(destName);
sndr = senders[fullDestName];
if(!sndr) {
sndr = session.createSender(fullDestName);
printf("Created new sender for: %s\n", fullDestName.c_str());
senders[fullDestName] = sndr;
}
}
doPublishProperties(sndr, beacon, BeconEventType::SCANNER_READ);
// Close temporary sender
if (sndr != sender)
sndr.close();
}
void QpidPublisher::publish(vector<Beacon> events) {
for(int n = 0; n < events.size(); n ++) {
Beacon& b = events.at(n);
publish("", b);
}
session.commit();
}
void QpidPublisher::publishStatus(Beacon &beacon) {
doPublishProperties(sender, beacon, BeconEventType::SCANNER_HEARTBEAT);
}
void QpidPublisher::doPublishProperties(messaging::Sender sndr, Beacon &beacon, BeconEventType messageType) {
messaging::Message message;
message.setProperty("uuid", beacon.getUuid());
message.setProperty("scannerID", beacon.getScannerID());
message.setProperty("major", beacon.getMajor());
message.setProperty("minor", beacon.getMinor());
message.setProperty("manufacturer", beacon.getManufacturer());
message.setProperty("code", beacon.getCode());
message.setProperty("power", beacon.getPower());
message.setProperty("calibratedPower", beacon.getCalibratedPower());
message.setProperty("rssi", beacon.getRssi());
message.setProperty("time", beacon.getTime());
message.setProperty("messageType", messageType);
message.setProperty("scannerSeqNo", beacon.getScannerSequenceNo());
if (clientID.length() > 0)
message.setUserId(clientID);
// Send message
sndr.send(message);
}
void QpidPublisher::publishProperties(string const &destName, map<string,string> const &properties) {
messaging::Sender sndr = sender;
if (destName.length() > 0) {
string fullDestName = isUseTopics() ? AmqTopicName(destName) : AmqQueueName(destName);
sndr = senders[fullDestName];
if(!sndr) {
sndr = session.createSender(fullDestName);
printf("Created new sender for: %s\n", fullDestName.c_str());
senders[fullDestName] = sndr;
}
}
messaging::Message message;
for(map<string, string>::const_iterator iter = properties.begin(); iter != properties.end(); iter ++) {
message.setProperty(iter->first, iter->second);
}
message.setProperty("messageType", SCANNER_STATUS);
if (clientID.length() > 0)
message.setUserId(clientID);
// Send message
sndr.send(message);
}
void QpidPublisher::calculateReconnectTime(int64_t now) {
setNextReconnectTime(now + reconnectInterval*1000);
milliseconds ms(now);
seconds s = duration_cast<seconds>(ms);
time_t t = s.count();
fprintf(stderr, "Will attempt reconnect at: %s\n", ctime(&t));
}
void QpidPublisher::monitorHeartbeats(string const &destinationName, heartbeatReceived callback) {
thread *t = new thread(&QpidPublisher::doMonitorHeartbeats, this, destinationName, callback);
this->heartbeatMonitorThread.reset(t);
}
void QpidPublisher::doMonitorHeartbeats(string const &destinationName, heartbeatReceived callback) {
string destName = isUseTopics() ? AmqTopicName(destinationName) : AmqQueueName(destinationName);
messaging::Receiver receiver = session.createReceiver(destName);
int missedCount = 0;
int receivedCount = 0;
while(running) {
messaging::Message message;
try {
receiver.fetch(message, messaging::Duration::MINUTE);
receivedCount ++;
missedCount = 0;
callback(true, receivedCount, missedCount);
} catch(messaging::NoMessageAvailable& e) {
fprintf(stderr, "Failed to receive own heartbeat for 1 minute, %s\n", e.what());
missedCount ++;
callback(false, receivedCount, missedCount);
}
}
}
<|endoftext|> |
<commit_before>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include "base/fscapi.h"
#if FUN_TRANSPORT_AGENT == FUN_MAC_TRANSPORT_AGENT
#include <Foundation/Foundation.h>
#include <CoreFoundation/CoreFoundation.h>
//#if defined(FUN_IPHONE)
#include <SystemConfiguration/SystemConfiguration.h>
#include <SystemConfiguration/SCNetworkReachability.h>
//#if TARGET_IPHONE_SIMULATOR
//#include <CoreServices/CoreServices.h>
//#else
#include <CFNetwork/CFNetwork.h>
//#endif
//#else
//#include <CoreServices/CoreServices.h>
//#endif
#include "http/MacTransportAgent.h"
#include "http/constants.h"
#include "base/util/utils.h"
#include "base/util/StringBuffer.h"
USE_NAMESPACE
MacTransportAgent::MacTransportAgent() : TransportAgent() {}
MacTransportAgent::~MacTransportAgent() {}
/*
* Constructor.
* In this implementation newProxy is ignored, since proxy configuration
* is taken from the WinInet subsystem.
*
* @param url the url where messages will be sent with sendMessage()
* @param proxy proxy information or NULL if no proxy should be used
*/
MacTransportAgent::MacTransportAgent(URL& newURL, Proxy& newProxy, unsigned int maxResponseTimeout)
: TransportAgent(newURL, newProxy, maxResponseTimeout)
{}
/*
* Sends the given SyncML message to the server specified
* by the instal property 'url'. Returns the response status code or -1
* if it was not possible initialize the connection.
*
* Use getResponse() to get the server response.
*/
char* MacTransportAgent::sendMessage(const char* msg){
LOG.debug("MacTransportAgent::sendMessage begin");
if(!msg) {
LOG.error("MacTransportAgent::sendMessage error: NULL message.");
setError(ERR_NETWORK_INIT, "MacTransportAgent::sendMessage error: NULL message.");
return NULL;
}
bool gotflags = true;
bool isReachable = true;
bool noConnectionRequired = true;
StringBuffer result;
CFIndex bytesRead = 1;
int statusCode = -1;
#if defined(FUN_IPHONE)
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef scnReachRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, url.host);
gotflags = SCNetworkReachabilityGetFlags(scnReachRef, &flags);
isReachable = flags & kSCNetworkReachabilityFlagsReachable;
noConnectionRequired = !(flags & kSCNetworkReachabilityFlagsConnectionRequired);
if ((flags & kSCNetworkReachabilityFlagsIsWWAN)) {
noConnectionRequired = true;
}
CFRelease(scnReachRef);
#endif
if ( gotflags && isReachable && noConnectionRequired ){
char* ret=0;
// size_t size = strlen(msg);
LOG.debug("Requesting resource %s at %s:%d", url.resource, url.host, url.port);
LOG.debug("Sending HTTP Request: %s", msg);
// Construct some headers
CFStringRef headerFieldName = CFSTR("Content-Type");
CFStringRef headerFieldValue = CFSTR("application/vnd.syncml+xml");
// Construct URL
CFStringRef CFurl = CFStringCreateWithCString(NULL, url.fullURL, kCFStringEncodingUTF8);
CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, CFurl, NULL);
CFStringRef requestMethod = CFSTR("POST");
CFHTTPMessageRef httpRequest =
CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1);
CFStringRef useragent = CFStringCreateWithCString(NULL, getUserAgent(), kCFStringEncodingUTF8);
CFHTTPMessageSetHeaderFieldValue(httpRequest, CFSTR("user-agent"), useragent);
if(!httpRequest){
LOG.error("MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.");
setError(ERR_NETWORK_INIT, "MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.");
goto finally;
}
CFDataRef bodyData;
bodyData = CFDataCreate(kCFAllocatorDefault, (const UInt8*)msg, strlen(msg));
if (!bodyData){
LOG.error("MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.");
setError(ERR_NETWORK_INIT, "MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.");
goto finally;
}
CFHTTPMessageSetBody(httpRequest, bodyData);
CFHTTPMessageSetHeaderFieldValue(httpRequest, headerFieldName, headerFieldValue);
CFReadStreamRef responseStream;
responseStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, httpRequest);
//bool setProperty;
//if we are trying to sync on a https server we have to have a trusted certificate.
//no self signed certificates are accepted
/*if(strcmp(url.protocol, "https")==0){
NSDictionary *sslProperties;
sslProperties = [NSDictionary dictionaryWithObjectsAndKeys:
(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL, kCFStreamSSLLevel,
kCFBooleanFalse, kCFStreamSSLAllowsAnyRoot,
kCFBooleanTrue, kCFStreamSSLValidatesCertificateChain,
kCFNull, kCFStreamSSLPeerName,
nil];
setProperty = CFReadStreamSetProperty( responseStream,
kCFStreamPropertySSLSettings,
sslProperties );
[sslProperties release];
}*/
if (!CFReadStreamOpen(responseStream)) {//Sends request
LOG.error("Failed to send HTTP request...");
}
#define READ_SIZE 1000
UInt8 buffer[READ_SIZE];
while ( (bytesRead = CFReadStreamRead(responseStream, buffer, READ_SIZE-1)) > 0)
{
// Convert what was read to a C-string
buffer[bytesRead] = 0;
// Append it to the reply string
result.append((const char*)buffer);
}
CFHTTPMessageRef reply;
reply = (CFHTTPMessageRef) CFReadStreamCopyProperty( responseStream, kCFStreamPropertyHTTPResponseHeader);
// Pull the status code from the headers
if (reply) {
statusCode = CFHTTPMessageGetResponseStatusCode(reply);
CFRelease(reply);
}
LOG.debug("Status Code: %d", statusCode);
LOG.debug("Result: %s", result.c_str());
switch (statusCode) {
case 0: {
LOG.debug("Http request successful.");
// No errors, copy the response
// TODO: avoid byte copy
ret = stringdup(result.c_str());
break;
}
case 200: {
LOG.debug("Http request successful.");
// No errors, copy the response
// TODO: avoid byte copy
ret = stringdup(result.c_str());
break;
}
case -1: { // no connection (TODO: implement retry)
setErrorF(ERR_SERVER_ERROR, "Network error in server receiving data. ");
LOG.error("%s", getLastErrorMsg());
break;
}
case 400: { // 400 bad request error. TODO: retry to send the message
setErrorF(ERR_SERVER_ERROR, "HTTP server error: %d. Server failure.", statusCode);
LOG.debug("%s", getLastErrorMsg());
break;
}
case 500: { // 500 -> out code 2052
setErrorF(ERR_SERVER_ERROR, "HTTP server error: %d. Server failure.", statusCode);
LOG.debug("%s", getLastErrorMsg());
break;
}
case 404: { // 404 -> out code 2060
setErrorF(ERR_HTTP_NOT_FOUND, "HTTP request error: resource not found (status %d)", statusCode);
LOG.debug("%s", getLastErrorMsg());
break;
}
case 408: { // 408 -> out code 2061
setErrorF(ERR_HTTP_REQUEST_TIMEOUT, "HTTP request error: server timed out waiting for request (status %d)", statusCode);
LOG.debug("%s", getLastErrorMsg());
break;
}
default: {
setErrorF(statusCode, "HTTP request error: status received = %d", statusCode);
LOG.error("%s", getLastErrorMsg());
}
}
finally:
CFRelease(headerFieldName);
CFRelease(headerFieldValue);
CFRelease(CFurl);
CFRelease(myURL);
CFRelease(httpRequest);
CFRelease(bodyData);
CFRelease(responseStream);
CFRelease(requestMethod);
CFRelease(useragent);
LOG.debug("MacTransportAgent::sendMessage end");
return ret;
}else{
setErrorF(ERR_CONNECT, "Network error: the attempt to connect to the server failed -> exit");
LOG.debug("%s", getLastErrorMsg());
LOG.debug("MacTransportAgent::sendMessage end");
return NULL;
}
}
#endif
<commit_msg>corrected MacTransportAgent to avoid performance issues<commit_after>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#include "base/fscapi.h"
#if FUN_TRANSPORT_AGENT == FUN_MAC_TRANSPORT_AGENT
#include <Foundation/Foundation.h>
#include <CoreFoundation/CoreFoundation.h>
#if defined(FUN_IPHONE)
#include <SystemConfiguration/SystemConfiguration.h>
#include <SystemConfiguration/SCNetworkReachability.h>
//#if TARGET_IPHONE_SIMULATOR
//#include <CoreServices/CoreServices.h>
//#else
#include <CFNetwork/CFNetwork.h>
#else
#include <CoreServices/CoreServices.h>
#endif
#include "http/MacTransportAgent.h"
#include "http/constants.h"
#include "base/util/utils.h"
#include "base/util/StringBuffer.h"
USE_NAMESPACE
MacTransportAgent::MacTransportAgent() : TransportAgent() {}
MacTransportAgent::~MacTransportAgent() {}
/*
* Constructor.
* In this implementation newProxy is ignored, since proxy configuration
* is taken from the WinInet subsystem.
*
* @param url the url where messages will be sent with sendMessage()
* @param proxy proxy information or NULL if no proxy should be used
*/
MacTransportAgent::MacTransportAgent(URL& newURL, Proxy& newProxy, unsigned int maxResponseTimeout)
: TransportAgent(newURL, newProxy, maxResponseTimeout)
{}
/*
* Sends the given SyncML message to the server specified
* by the instal property 'url'. Returns the response status code or -1
* if it was not possible initialize the connection.
*
* Use getResponse() to get the server response.
*/
char* MacTransportAgent::sendMessage(const char* msg){
LOG.debug("MacTransportAgent::sendMessage begin");
if(!msg) {
LOG.error("MacTransportAgent::sendMessage error: NULL message.");
setError(ERR_NETWORK_INIT, "MacTransportAgent::sendMessage error: NULL message.");
return NULL;
}
bool gotflags = true;
bool isReachable = true;
bool noConnectionRequired = true;
StringBuffer result;
CFIndex bytesRead = 1;
int statusCode = -1;
#if defined(FUN_IPHONE)
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityRef scnReachRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, url.host);
gotflags = SCNetworkReachabilityGetFlags(scnReachRef, &flags);
isReachable = flags & kSCNetworkReachabilityFlagsReachable;
noConnectionRequired = !(flags & kSCNetworkReachabilityFlagsConnectionRequired);
if ((flags & kSCNetworkReachabilityFlagsIsWWAN)) {
noConnectionRequired = true;
}
CFRelease(scnReachRef);
#endif
if ( gotflags && isReachable && noConnectionRequired ){
char* ret=0;
// size_t size = strlen(msg);
LOG.debug("Requesting resource %s at %s:%d", url.resource, url.host, url.port);
LOG.debug("Sending HTTP Request: %s", msg);
// Construct some headers
CFStringRef headerFieldName = CFSTR("Content-Type");
CFStringRef headerFieldValue = CFSTR("application/vnd.syncml+xml");
// Construct URL
CFStringRef CFurl = CFStringCreateWithCString(NULL, url.fullURL, kCFStringEncodingUTF8);
CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, CFurl, NULL);
CFStringRef requestMethod = CFSTR("POST");
CFHTTPMessageRef httpRequest =
CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1);
CFStringRef useragent = CFStringCreateWithCString(NULL, getUserAgent(), kCFStringEncodingUTF8);
CFHTTPMessageSetHeaderFieldValue(httpRequest, CFSTR("user-agent"), useragent);
if(!httpRequest){
LOG.error("MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.");
setError(ERR_NETWORK_INIT, "MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.");
goto finally;
}
//CFDataRef bodyData;
CFDataRef bodyData = CFDataCreate(kCFAllocatorDefault, (const UInt8*)msg, strlen(msg));
if (!bodyData){
LOG.error("MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.");
setError(ERR_NETWORK_INIT, "MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.");
goto finally;
}
CFHTTPMessageSetBody(httpRequest, bodyData);
CFHTTPMessageSetHeaderFieldValue(httpRequest, headerFieldName, headerFieldValue);
//CFReadStreamRef responseStream;
CFReadStreamRef responseStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, httpRequest);
//bool setProperty;
//if we are trying to sync on a https server we have to have a trusted certificate.
//no self signed certificates are accepted
/*if(strcmp(url.protocol, "https")==0){
NSDictionary *sslProperties;
sslProperties = [NSDictionary dictionaryWithObjectsAndKeys:
(NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL, kCFStreamSSLLevel,
kCFBooleanFalse, kCFStreamSSLAllowsAnyRoot,
kCFBooleanTrue, kCFStreamSSLValidatesCertificateChain,
kCFNull, kCFStreamSSLPeerName,
nil];
setProperty = CFReadStreamSetProperty( responseStream,
kCFStreamPropertySSLSettings,
sslProperties );
[sslProperties release];
}*/
if (!CFReadStreamOpen(responseStream)) {//Sends request
LOG.error("Failed to send HTTP request...");
}
#define READ_SIZE 1000
UInt8 buffer[READ_SIZE];
while ( (bytesRead = CFReadStreamRead(responseStream, buffer, READ_SIZE-1)) > 0)
{
// Convert what was read to a C-string
buffer[bytesRead] = 0;
// Append it to the reply string
result.append((const char*)buffer);
}
//CFHTTPMessageRef reply;
CFHTTPMessageRef reply = (CFHTTPMessageRef) CFReadStreamCopyProperty( responseStream, kCFStreamPropertyHTTPResponseHeader);
// Pull the status code from the headers
if (reply) {
statusCode = CFHTTPMessageGetResponseStatusCode(reply);
CFRelease(reply);
}
LOG.debug("Status Code: %d", statusCode);
LOG.debug("Result: %s", result.c_str());
switch (statusCode) {
case 0: {
LOG.debug("Http request successful.");
// No errors, copy the response
// TODO: avoid byte copy
ret = stringdup(result.c_str());
break;
}
case 200: {
LOG.debug("Http request successful.");
// No errors, copy the response
// TODO: avoid byte copy
ret = stringdup(result.c_str());
break;
}
case -1: { // no connection (TODO: implement retry)
setErrorF(ERR_SERVER_ERROR, "Network error in server receiving data. ");
LOG.error("%s", getLastErrorMsg());
break;
}
case 400: { // 400 bad request error. TODO: retry to send the message
setErrorF(ERR_SERVER_ERROR, "HTTP server error: %d. Server failure.", statusCode);
LOG.debug("%s", getLastErrorMsg());
break;
}
case 500: { // 500 -> out code 2052
setErrorF(ERR_SERVER_ERROR, "HTTP server error: %d. Server failure.", statusCode);
LOG.debug("%s", getLastErrorMsg());
break;
}
case 404: { // 404 -> out code 2060
setErrorF(ERR_HTTP_NOT_FOUND, "HTTP request error: resource not found (status %d)", statusCode);
LOG.debug("%s", getLastErrorMsg());
break;
}
case 408: { // 408 -> out code 2061
setErrorF(ERR_HTTP_REQUEST_TIMEOUT, "HTTP request error: server timed out waiting for request (status %d)", statusCode);
LOG.debug("%s", getLastErrorMsg());
break;
}
default: {
setErrorF(statusCode, "HTTP request error: status received = %d", statusCode);
LOG.error("%s", getLastErrorMsg());
}
}
finally:
CFRelease(headerFieldName);
CFRelease(headerFieldValue);
CFRelease(CFurl);
CFRelease(myURL);
CFRelease(httpRequest);
CFRelease(bodyData);
CFRelease(responseStream);
CFRelease(requestMethod);
CFRelease(useragent);
LOG.debug("MacTransportAgent::sendMessage end");
return ret;
}else{
setErrorF(ERR_CONNECT, "Network error: the attempt to connect to the server failed -> exit");
LOG.debug("%s", getLastErrorMsg());
LOG.debug("MacTransportAgent::sendMessage end");
return NULL;
}
}
#endif
<|endoftext|> |
<commit_before>#ifdef _WIN32
#include <windows.h>
#pragma comment(lib,"user32.lib")
#endif
#ifdef unix
#include <iostream>
#include <stdlib.h> /* putenv */
#include <string.h> /* strdup */
#include <unistd.h> /* execvp */
#include <errno.h> /* errno */
#endif
#include <sstream>
#include <RefeusProcess.h>
/** constructor
*/
RefeusProcess::RefeusProcess() {
parametersvector.push_back("startup.ini");
#ifdef _WIN32
executable = "refeus.exe";
#endif
#ifdef unix
executable = "refeus.sh";
#endif
}
/**
* get the next argument from a vector that is split by blanks
* @return string
* @param arguments_separated_by_blank (unmodifyable vector, passed by reference for performance)
* @param start_iterater reference to move iterator for the argParser
* --last "noblank"
* --last "with blank"
* --last "with many blanks"
*/
std::string RefeusProcess::argParserNext(const std::vector<std::string> &arguments_separated_by_blank, std::vector<std::string>::iterator &start_iterator){
std::string next_arg = "";
next_arg = (*start_iterator);
for ( it = start_iterator
; it != arguments_separated_by_blank.end()
; it++
){
if ( (*it).at(0) == "\""
&& !(*it).at((*it).size()-1) == "\""
){
next_arg = (*it).substr(1,(*it).size()-2);
in_quotes = true;
}
if ( (*it).at(0) == "\""
&& (*it).at((*it).size()-1) == "\""
){
next_arg = (*it).substr(1,(*it).size()-3);
break;
}
if ( in_quotes && (*it).at((*it).size()-1) == "\"" ){
next_arg+= (*it).substr(0,(*it).size()-2);
break;
}
if ( in_quotes ){
next_arg+= " " + next_arg;
continue;
}
break;
}
start_iterator = it;
return next_arg;
}
/** Argument Parser parses takes as parameter the command line then parses
* all the arguments that are separated from each other with a single blank
* --help outputs all possible arguments
* --new opens a 'save file as' dialog window
* --open "C:/works with/spaces too.txt" but path name must be inside " "
* --refeus sets to refeus.ini
* --plus sets to plus.ini
* --cloud-enabled sets CLOUD_ENABLED to true
*/
bool RefeusProcess::argParser(std::string command_line) {
std::vector<std::string> per_blank_vector,per_quotes_vector;
//splitting command line per single blanks
split(command_line, " ", per_blank_vector);
std::vector<std::string>::iterator it;
for ( it = per_blank_vector.begin()
; it < per_blank_vector.end()
; ++it
) {
std::string hello = *it;
printf("the per blank vector is %s \n",hello.c_str());
if ( *it == "--help"
||*it == "/?"
) {
usage();
return false;
}
if ( *it == "--new" ) {
configureNewRefeusDocument();
} else if ( *it == "--open" ) {
//splitting command line per double quotes
// THIS is invalid: split takes character as parameter, you give string
split(command_line, "\"\"", per_quotes_vector);
//per_quotes_vector.erase(per_quotes_vector.begin());
if ( per_quotes_vector.size() > 1 ) {
//TODO: use refeus_database_autostart
configureOpenRefeusDocument(per_quotes_vector.at(1));
} else {
configureNewRefeusDocument();
}
} else if ( *it == "--plus" ) {
parametersvector.clear();
parametersvector.push_back("plus.ini");
} else if ( *it == "--refeus" ) {
parametersvector.clear();
parametersvector.push_back("refeus.ini");
} else if ( *it == "--cloud-enabled" ) {
configureCloudSetting();
} else if ( *it == "--debug" ) {
configureDebug();
} else if ( *it == "--language" ) {
configureLanguageFromIsoString(argParserNext(per_blank_vector, it));
} else if ( *it == "--auto-backup" ) {
//TODO: set AUTO_BACKUP=YES
} else if ( *it == "--no-auto-backup" ) {
//TODO: set AUTO_BACKUP=NO
} else if ( *it == "--skip-maintenance" ) {
//TODO: set SKIP_MAINTENANCE=YES
} else if ( *it == "--startup-activity" ) {
//TODO: set STARTUP_ACTIVITY=next parameter (eg manage::overview)
}
/**
* REFEUS_SETTINGS_LOCATION=[when set: ini-file for portable]
* REFEUS_DOCUMENTS_LOCATION=path/to/documents
* REFEUS_PICTURES_LOCATION=path/to/pictures
*/
}
return true;
}
void RefeusProcess::configureCloudSetting() {
environmentmap["CLOUD_ENABLED"] = "true";
}
void RefeusProcess::configureDebug() {
#ifdef _WIN32
executable = "code.exe"; /** start a commandline window to output debug messages*/
#endif
environmentmap["WKE_DEBUG"] = "YES";
environmentmap["WKE_DEBUG_CONSOLE"] = "YES";
}
void RefeusProcess::configureNewRefeusDocument() {
environmentmap["open_refeus_database"] = "true";
}
void RefeusProcess::configureLanguageFromIsoString(std::string iso_language) {
if ( iso_language == "en" ){
langcheck(0); //default
} else if (iso_language == "de") {
langcheck(1031);
} else if (iso_language == "fr") {
langcheck(1036);
} else if (iso_language == "pl") {
langcheck(1045);
}
}
void RefeusProcess::configureOpenRefeusDocument(std::string path_name) {
environmentmap["refeus_database"] = path_name;
}
/**
* Function langCheck takes as parameter the Language ID of the system
* Checks if it is German->French->Polish->English
* Then sets the appropriate Envir-Variables to the language that got
* matched first
* \param api_language_code - windows-api language code
*/
void RefeusProcess::langCheck(int api_language_code) {
switch ( api_language_code ) {
case 1031: //German
environmentmap["DSC_Language"] = "German";
environmentmap["Language"] = "German";
break;
case 1036: //French
environmentmap["DSC_Language"] = "French";
environmentmap["Language"] = "French";
break;
case 1045: //Polish
environmentmap["DSC_Language"] = "Polish";
environmentmap["Language"] = "Polish";
break;
default: //English
environmentmap["DSC_Language"] = "English";
environmentmap["Language"] = "English";
break;
}
}
void RefeusProcess::setEnvironment(std::string env_name, std::string env_value) {
environmentmap[env_name] = env_value;
}
/** \brief Split String into Vector using a delimter
* \param string_to_split - some string to be split by a specific character
* \param delimiter_character - character for splitting
* \param element_vector - reference vector for storing the split result
*/
std::vector<std::string> &RefeusProcess::split(const std::string &string_to_split, char* delimiter_character, std::vector<std::string> &element_vector) {
std::stringstream sstream(string_to_split);
std::string item;
while (std::getline(sstream, item, *delimiter_character)) {
element_vector.push_back(item);
}
return element_vector;
}
/** Function start takes no arguments
* sets all environment variables that are saved in environmenenmap
* prepares the full_executable path with the pre-configured ini file
* then creates the process with the appropriate env. variables and ini file
*/
int RefeusProcess:: start() {
std::string executable_with_parameter = executable;
std::vector<std::string>::iterator parameter_iterator;
std::map<std::string, std::string>::iterator map_iterator;
#ifdef _WIN32
STARTUPINFO StartupInfo; //This is an [in] parameter
PROCESS_INFORMATION ProcessInfo; //This is what we get as an [out] parameter
#endif
for ( map_iterator = environmentmap.begin(); map_iterator != environmentmap.end(); ++map_iterator) {
std::string env = map_iterator->first + "=" + map_iterator->second;
char * env_cstr = new char[env.size() + 1];
std::copy(env.begin(), env.end(), env_cstr);
env_cstr[env.size()] = '\0';
putenv(env_cstr);
}
#ifdef _WIN32
/**
* win32 implementation only
*/
for ( parameter_iterator = parametersvector.begin()
; parameter_iterator < parametersvector.end()
; ++parameter_iterator
) {
executable_with_parameter = executable_with_parameter + " " + *parameter_iterator;
}
ZeroMemory(&StartupInfo, sizeof(StartupInfo));
ZeroMemory(&ProcessInfo, sizeof(ProcessInfo));
StartupInfo.cb = sizeof(StartupInfo) ; //Only compulsory field
//Formatting exe to const char* and full_exe to char* for CreateProcess
char* executable_with_parameter_cstr = new char [executable_with_parameter.size() + 1];
const char* executable_cstr = strdup(executable.c_str());
std::copy(executable_with_parameter.begin(), executable_with_parameter.end(), executable_with_parameter_cstr);
executable_with_parameter_cstr[executable_with_parameter.size()] = '\0';
bool process_started = CreateProcess( executable_cstr
, executable_with_parameter_cstr //exe + ini names
, 0
, 0
, FALSE
, CREATE_DEFAULT_ERROR_MODE
, 0
, 0
, &StartupInfo
, &ProcessInfo);
if ( process_started ){
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
} else {
MessageBox(NULL, "The process could not be started... \n" , "Process Failed!", MB_OK);
return 1;
}
#endif
#ifdef unix
/**
* unix implementation only
*/
char **exec_argv = static_cast<char**>(malloc(sizeof(char*) * (parametersvector.size() + 1) ));
int parameter_iterator_index = 0;
for ( parameter_iterator = parametersvector.begin()
; parameter_iterator < parametersvector.end()
; ++parameter_iterator
) {
exec_argv[parameter_iterator_index] = strdup((*parameter_iterator).c_str());
parameter_iterator_index++;
}
exec_argv[parameter_iterator_index] = NULL;
if ( execvp(executable.c_str(),exec_argv) == -1 ){
std::cerr << strerror(errno);
}
#endif
return 0;
}
void RefeusProcess::usage() {
const char* help_string = "--help displays all possible arguments\n"
"--new opens a 'save as' dialog window\n"
"--open \"C:/file_name\" starts refeus with specific file\n"
"--plus sets the ini file to plus.ini\n"
"--refeus sets the ini file to refeus.ini\n"
"--debug sets the application to debug-mode (allows shift+ctrl+i)\n"
"--cloud-enabled sets CLOUD_ENABLED to true\n"
"TODO: add more parameters"
;
#ifdef _WIN32
MessageBox(NULL, help_string, "Help!", MB_OK);
#endif
#ifdef unix
std::cout << help_string << std::endl;
#endif
}
<commit_msg>make sure refeus autostarts when a filename is provided, use open-dialog otherwise<commit_after>#ifdef _WIN32
#include <windows.h>
#pragma comment(lib,"user32.lib")
#endif
#ifdef unix
#include <iostream>
#include <stdlib.h> /* putenv */
#include <string.h> /* strdup */
#include <unistd.h> /* execvp */
#include <errno.h> /* errno */
#endif
#include <sstream>
#include <RefeusProcess.h>
/** constructor
*/
RefeusProcess::RefeusProcess() {
parametersvector.push_back("startup.ini");
#ifdef _WIN32
executable = "refeus.exe";
#endif
#ifdef unix
executable = "refeus.sh";
#endif
}
/**
* get the next argument from a vector that is split by blanks
* @return string
* @param arguments_separated_by_blank (unmodifyable vector, passed by reference for performance)
* @param start_iterater reference to move iterator for the argParser
* --last "noblank"
* --last "with blank"
* --last "with many blanks"
*/
std::string RefeusProcess::argParserNext(const std::vector<std::string> &arguments_separated_by_blank, std::vector<std::string>::iterator &start_iterator){
std::string next_arg = "";
next_arg = (*start_iterator);
for ( it = start_iterator
; it != arguments_separated_by_blank.end()
; it++
){
if ( (*it).at(0) == "\""
&& !(*it).at((*it).size()-1) == "\""
){
next_arg = (*it).substr(1,(*it).size()-2);
in_quotes = true;
}
if ( (*it).at(0) == "\""
&& (*it).at((*it).size()-1) == "\""
){
next_arg = (*it).substr(1,(*it).size()-3);
break;
}
if ( in_quotes && (*it).at((*it).size()-1) == "\"" ){
next_arg+= (*it).substr(0,(*it).size()-2);
break;
}
if ( in_quotes ){
next_arg+= " " + next_arg;
continue;
}
break;
}
start_iterator = it;
return next_arg;
}
/** Argument Parser parses takes as parameter the command line then parses
* all the arguments that are separated from each other with a single blank
* --help outputs all possible arguments
* --new opens a 'save file as' dialog window
* --open "C:/works with/spaces too.txt" but path name must be inside " "
* --refeus sets to refeus.ini
* --plus sets to plus.ini
* --cloud-enabled sets CLOUD_ENABLED to true
*/
bool RefeusProcess::argParser(std::string command_line) {
std::vector<std::string> per_blank_vector,per_quotes_vector;
//splitting command line per single blanks
split(command_line, " ", per_blank_vector);
std::vector<std::string>::iterator it;
for ( it = per_blank_vector.begin()
; it < per_blank_vector.end()
; ++it
) {
std::string hello = *it;
printf("the per blank vector is %s \n",hello.c_str());
if ( *it == "--help"
||*it == "/?"
) {
usage();
return false;
}
if ( *it == "--new" ) {
configureNewRefeusDocument();
} else if ( *it == "--open" ) {
//splitting command line per double quotes
// THIS is invalid: split takes character as parameter, you give string
split(command_line, "\"\"", per_quotes_vector);
//per_quotes_vector.erase(per_quotes_vector.begin());
if ( per_quotes_vector.size() > 1 ) {
//TODO: use refeus_database_autostart
configureOpenRefeusDocument(per_quotes_vector.at(1));
} else {
configureNewRefeusDocument();
}
} else if ( *it == "--plus" ) {
parametersvector.clear();
parametersvector.push_back("plus.ini");
} else if ( *it == "--refeus" ) {
parametersvector.clear();
parametersvector.push_back("refeus.ini");
} else if ( *it == "--cloud-enabled" ) {
configureCloudSetting();
} else if ( *it == "--debug" ) {
configureDebug();
} else if ( *it == "--language" ) {
configureLanguageFromIsoString(argParserNext(per_blank_vector, it));
} else if ( *it == "--auto-backup" ) {
//TODO: set AUTO_BACKUP=YES
} else if ( *it == "--no-auto-backup" ) {
//TODO: set AUTO_BACKUP=NO
} else if ( *it == "--skip-maintenance" ) {
//TODO: set SKIP_MAINTENANCE=YES
} else if ( *it == "--startup-activity" ) {
//TODO: set STARTUP_ACTIVITY=next parameter (eg manage::overview)
}
/**
* REFEUS_SETTINGS_LOCATION=[when set: ini-file for portable]
* REFEUS_DOCUMENTS_LOCATION=path/to/documents
* REFEUS_PICTURES_LOCATION=path/to/pictures
*/
}
return true;
}
void RefeusProcess::configureCloudSetting() {
environmentmap["CLOUD_ENABLED"] = "true";
}
void RefeusProcess::configureDebug() {
#ifdef _WIN32
executable = "code.exe"; /** start a commandline window to output debug messages*/
#endif
environmentmap["WKE_DEBUG"] = "YES";
environmentmap["WKE_DEBUG_CONSOLE"] = "YES";
}
void RefeusProcess::configureNewRefeusDocument() {
environmentmap["open_refeus_database"] = "true";
}
void RefeusProcess::configureLanguageFromIsoString(std::string iso_language) {
if ( iso_language == "en" ){
langcheck(0); //default
} else if (iso_language == "de") {
langcheck(1031);
} else if (iso_language == "fr") {
langcheck(1036);
} else if (iso_language == "pl") {
langcheck(1045);
}
}
void RefeusProcess::configureOpenRefeusDocument(std::string path_name) {
environmentmap["refeus_database"] = path_name;
environmentmap["refeus_database_autostart"] = "true";
}
/**
* Function langCheck takes as parameter the Language ID of the system
* Checks if it is German->French->Polish->English
* Then sets the appropriate Envir-Variables to the language that got
* matched first
* \param api_language_code - windows-api language code
*/
void RefeusProcess::langCheck(int api_language_code) {
switch ( api_language_code ) {
case 1031: //German
environmentmap["DSC_Language"] = "German";
environmentmap["Language"] = "German";
break;
case 1036: //French
environmentmap["DSC_Language"] = "French";
environmentmap["Language"] = "French";
break;
case 1045: //Polish
environmentmap["DSC_Language"] = "Polish";
environmentmap["Language"] = "Polish";
break;
default: //English
environmentmap["DSC_Language"] = "English";
environmentmap["Language"] = "English";
break;
}
}
void RefeusProcess::setEnvironment(std::string env_name, std::string env_value) {
environmentmap[env_name] = env_value;
}
/** \brief Split String into Vector using a delimter
* \param string_to_split - some string to be split by a specific character
* \param delimiter_character - character for splitting
* \param element_vector - reference vector for storing the split result
*/
std::vector<std::string> &RefeusProcess::split(const std::string &string_to_split, char* delimiter_character, std::vector<std::string> &element_vector) {
std::stringstream sstream(string_to_split);
std::string item;
while (std::getline(sstream, item, *delimiter_character)) {
element_vector.push_back(item);
}
return element_vector;
}
/** Function start takes no arguments
* sets all environment variables that are saved in environmenenmap
* prepares the full_executable path with the pre-configured ini file
* then creates the process with the appropriate env. variables and ini file
*/
int RefeusProcess:: start() {
std::string executable_with_parameter = executable;
std::vector<std::string>::iterator parameter_iterator;
std::map<std::string, std::string>::iterator map_iterator;
#ifdef _WIN32
STARTUPINFO StartupInfo; //This is an [in] parameter
PROCESS_INFORMATION ProcessInfo; //This is what we get as an [out] parameter
#endif
for ( map_iterator = environmentmap.begin(); map_iterator != environmentmap.end(); ++map_iterator) {
std::string env = map_iterator->first + "=" + map_iterator->second;
char * env_cstr = new char[env.size() + 1];
std::copy(env.begin(), env.end(), env_cstr);
env_cstr[env.size()] = '\0';
putenv(env_cstr);
}
#ifdef _WIN32
/**
* win32 implementation only
*/
for ( parameter_iterator = parametersvector.begin()
; parameter_iterator < parametersvector.end()
; ++parameter_iterator
) {
executable_with_parameter = executable_with_parameter + " " + *parameter_iterator;
}
ZeroMemory(&StartupInfo, sizeof(StartupInfo));
ZeroMemory(&ProcessInfo, sizeof(ProcessInfo));
StartupInfo.cb = sizeof(StartupInfo) ; //Only compulsory field
//Formatting exe to const char* and full_exe to char* for CreateProcess
char* executable_with_parameter_cstr = new char [executable_with_parameter.size() + 1];
const char* executable_cstr = strdup(executable.c_str());
std::copy(executable_with_parameter.begin(), executable_with_parameter.end(), executable_with_parameter_cstr);
executable_with_parameter_cstr[executable_with_parameter.size()] = '\0';
bool process_started = CreateProcess( executable_cstr
, executable_with_parameter_cstr //exe + ini names
, 0
, 0
, FALSE
, CREATE_DEFAULT_ERROR_MODE
, 0
, 0
, &StartupInfo
, &ProcessInfo);
if ( process_started ){
WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
} else {
MessageBox(NULL, "The process could not be started... \n" , "Process Failed!", MB_OK);
return 1;
}
#endif
#ifdef unix
/**
* unix implementation only
*/
char **exec_argv = static_cast<char**>(malloc(sizeof(char*) * (parametersvector.size() + 1) ));
int parameter_iterator_index = 0;
for ( parameter_iterator = parametersvector.begin()
; parameter_iterator < parametersvector.end()
; ++parameter_iterator
) {
exec_argv[parameter_iterator_index] = strdup((*parameter_iterator).c_str());
parameter_iterator_index++;
}
exec_argv[parameter_iterator_index] = NULL;
if ( execvp(executable.c_str(),exec_argv) == -1 ){
std::cerr << strerror(errno);
}
#endif
return 0;
}
void RefeusProcess::usage() {
const char* help_string = "--help displays all possible arguments\n"
"--new opens a 'save as' dialog window\n"
"--open \"C:/file_name\" starts refeus with specific file\n"
"--plus sets the ini file to plus.ini\n"
"--refeus sets the ini file to refeus.ini\n"
"--debug sets the application to debug-mode (allows shift+ctrl+i)\n"
"--cloud-enabled sets CLOUD_ENABLED to true\n"
"TODO: add more parameters"
;
#ifdef _WIN32
MessageBox(NULL, help_string, "Help!", MB_OK);
#endif
#ifdef unix
std::cout << help_string << std::endl;
#endif
}
<|endoftext|> |
<commit_before>#include "../src/RobotLocation.hpp"
#include <WPILib.h>
#include <iostream>
RobotLocation::RobotLocation() : gyro(2, 3)
{
std::cout << "Hello World" << std::endl;
}
void RobotLocation::update()
{
std::cout << "Hello World" << std::endl;
}
<commit_msg>Update location<commit_after>#include <WPILib.h>
#include "RobotLocation.hpp"
#include <iostream>
#include <cmath>
bool tolerance(float val1, float val2, float tolVal)
{
if(fabs(val1 - val2) < tolVal)
{
return true;
}
}
RobotLocation::RobotLocation()
: gyro(1)
, left(0,1)
, right(0, 1)
{
std::cout << "Hello World" << std::endl;
}
void RobotLocation::update()
{
direction == gyro.GetAngle()*180/M_PI;
if(tolerance(left.GetDistance(), right.GetDistance(), 5e-5) == true)
{
float x = left.GetDistance()/cos(direction);
float y = right.GetDistance()/sin(direction);
pos.first += x;
pos.second += y;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "src/trace_processor/importers/systrace/systrace_parser.h"
#include "perfetto/ext/base/optional.h"
#include "src/trace_processor/event_tracker.h"
#include "src/trace_processor/process_tracker.h"
#include "src/trace_processor/slice_tracker.h"
#include "src/trace_processor/track_tracker.h"
namespace perfetto {
namespace trace_processor {
SystraceParser::SystraceParser(TraceProcessorContext* ctx)
: context_(ctx), lmk_id_(ctx->storage->InternString("mem.lmk")) {}
SystraceParser::~SystraceParser() = default;
void SystraceParser::ParsePrintEvent(int64_t ts,
uint32_t pid,
base::StringView event) {
systrace_utils::SystraceTracePoint point{};
switch (ParseSystraceTracePoint(event, &point)) {
case systrace_utils::SystraceParseResult::kSuccess:
ParseSystracePoint(ts, pid, point);
break;
case systrace_utils::SystraceParseResult::kFailure:
context_->storage->IncrementStats(stats::systrace_parse_failure);
break;
case systrace_utils::SystraceParseResult::kUnsupported:
// Silently ignore unsupported results.
break;
}
}
void SystraceParser::ParseZeroEvent(int64_t ts,
uint32_t pid,
int32_t flag,
base::StringView name,
uint32_t tgid,
int64_t value) {
systrace_utils::SystraceTracePoint point{};
point.name = name;
point.tgid = tgid;
point.value = value;
// The value of these constants can be found in the msm-google kernel.
constexpr int32_t kSystraceEventBegin = 1 << 0;
constexpr int32_t kSystraceEventEnd = 1 << 1;
constexpr int32_t kSystraceEventInt64 = 1 << 2;
if ((flag & kSystraceEventBegin) != 0) {
point.phase = 'B';
} else if ((flag & kSystraceEventEnd) != 0) {
point.phase = 'E';
} else if ((flag & kSystraceEventInt64) != 0) {
point.phase = 'C';
} else {
context_->storage->IncrementStats(stats::systrace_parse_failure);
return;
}
ParseSystracePoint(ts, pid, point);
}
void SystraceParser::ParseSdeTracingMarkWrite(int64_t ts,
uint32_t pid,
char trace_type,
bool trace_begin,
base::StringView trace_name,
uint32_t tgid,
int64_t value) {
systrace_utils::SystraceTracePoint point{};
point.name = trace_name;
point.tgid = tgid;
point.value = value;
if (trace_type == 0) {
point.phase = trace_begin ? 'B' : 'E';
} else if (trace_type == 'B' && trace_type == 'E' && trace_type == 'C') {
point.phase = trace_type;
} else {
context_->storage->IncrementStats(stats::systrace_parse_failure);
return;
}
ParseSystracePoint(ts, pid, point);
}
void SystraceParser::ParseSystracePoint(
int64_t ts,
uint32_t pid,
systrace_utils::SystraceTracePoint point) {
switch (point.phase) {
case 'B': {
StringId name_id = context_->storage->InternString(point.name);
UniqueTid utid = context_->process_tracker->UpdateThread(pid, point.tgid);
TrackId track_id = context_->track_tracker->InternThreadTrack(utid);
context_->slice_tracker->Begin(ts, track_id, kNullStringId /* cat */,
name_id);
break;
}
case 'E': {
// |point.tgid| can be 0 in older android versions where the end event
// would not contain the value.
UniqueTid utid;
if (point.tgid == 0) {
// If we haven't seen this thread before, there can't have been a Begin
// event for it so just ignore the event.
auto opt_utid = context_->process_tracker->GetThreadOrNull(pid);
if (!opt_utid)
break;
utid = *opt_utid;
} else {
utid = context_->process_tracker->UpdateThread(pid, point.tgid);
}
TrackId track_id = context_->track_tracker->InternThreadTrack(utid);
context_->slice_tracker->End(ts, track_id);
break;
}
case 'S':
case 'F': {
StringId name_id = context_->storage->InternString(point.name);
int64_t cookie = static_cast<int64_t>(point.value);
UniquePid upid =
context_->process_tracker->GetOrCreateProcess(point.tgid);
TrackId track_id = context_->track_tracker->InternAndroidAsyncTrack(
name_id, upid, cookie);
if (point.phase == 'S') {
context_->slice_tracker->Begin(ts, track_id, kNullStringId, name_id);
} else {
context_->slice_tracker->End(ts, track_id);
}
break;
}
case 'C': {
// LMK events from userspace are hacked as counter events with the "value"
// of the counter representing the pid of the killed process which is
// reset to 0 once the kill is complete.
// Homogenise this with kernel LMK events as an instant event, ignoring
// the resets to 0.
if (point.name == "kill_one_process") {
auto killed_pid = static_cast<uint32_t>(point.value);
if (killed_pid != 0) {
UniquePid killed_upid =
context_->process_tracker->GetOrCreateProcess(killed_pid);
context_->event_tracker->PushInstant(ts, lmk_id_, killed_upid,
RefType::kRefUpid);
}
// TODO(lalitm): we should not add LMK events to the counters table
// once the UI has support for displaying instants.
}
// This is per upid on purpose. Some counters are pushed from arbitrary
// threads but are really per process.
UniquePid upid =
context_->process_tracker->GetOrCreateProcess(point.tgid);
StringId name_id = context_->storage->InternString(point.name);
TrackId track =
context_->track_tracker->InternProcessCounterTrack(name_id, upid);
context_->event_tracker->PushCounter(ts, point.value, track);
}
}
}
} // namespace trace_processor
} // namespace perfetto
<commit_msg>trace_processor: Fix SDE parsing bug<commit_after>/*
* Copyright (C) 2018 The Android Open Source Project
*
* 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 "src/trace_processor/importers/systrace/systrace_parser.h"
#include "perfetto/ext/base/optional.h"
#include "src/trace_processor/event_tracker.h"
#include "src/trace_processor/process_tracker.h"
#include "src/trace_processor/slice_tracker.h"
#include "src/trace_processor/track_tracker.h"
namespace perfetto {
namespace trace_processor {
SystraceParser::SystraceParser(TraceProcessorContext* ctx)
: context_(ctx), lmk_id_(ctx->storage->InternString("mem.lmk")) {}
SystraceParser::~SystraceParser() = default;
void SystraceParser::ParsePrintEvent(int64_t ts,
uint32_t pid,
base::StringView event) {
systrace_utils::SystraceTracePoint point{};
switch (ParseSystraceTracePoint(event, &point)) {
case systrace_utils::SystraceParseResult::kSuccess:
ParseSystracePoint(ts, pid, point);
break;
case systrace_utils::SystraceParseResult::kFailure:
context_->storage->IncrementStats(stats::systrace_parse_failure);
break;
case systrace_utils::SystraceParseResult::kUnsupported:
// Silently ignore unsupported results.
break;
}
}
void SystraceParser::ParseZeroEvent(int64_t ts,
uint32_t pid,
int32_t flag,
base::StringView name,
uint32_t tgid,
int64_t value) {
systrace_utils::SystraceTracePoint point{};
point.name = name;
point.tgid = tgid;
point.value = value;
// The value of these constants can be found in the msm-google kernel.
constexpr int32_t kSystraceEventBegin = 1 << 0;
constexpr int32_t kSystraceEventEnd = 1 << 1;
constexpr int32_t kSystraceEventInt64 = 1 << 2;
if ((flag & kSystraceEventBegin) != 0) {
point.phase = 'B';
} else if ((flag & kSystraceEventEnd) != 0) {
point.phase = 'E';
} else if ((flag & kSystraceEventInt64) != 0) {
point.phase = 'C';
} else {
context_->storage->IncrementStats(stats::systrace_parse_failure);
return;
}
ParseSystracePoint(ts, pid, point);
}
void SystraceParser::ParseSdeTracingMarkWrite(int64_t ts,
uint32_t pid,
char trace_type,
bool trace_begin,
base::StringView trace_name,
uint32_t tgid,
int64_t value) {
systrace_utils::SystraceTracePoint point{};
point.name = trace_name;
point.tgid = tgid;
point.value = value;
// Some versions of this trace point fill trace_type with one of (B/E/C),
// others use the trace_begin boolean and only support begin/end events:
if (trace_type == 0) {
point.phase = trace_begin ? 'B' : 'E';
} else if (trace_type == 'B' || trace_type == 'E' || trace_type == 'C') {
point.phase = trace_type;
} else {
context_->storage->IncrementStats(stats::systrace_parse_failure);
return;
}
ParseSystracePoint(ts, pid, point);
}
void SystraceParser::ParseSystracePoint(
int64_t ts,
uint32_t pid,
systrace_utils::SystraceTracePoint point) {
switch (point.phase) {
case 'B': {
StringId name_id = context_->storage->InternString(point.name);
UniqueTid utid = context_->process_tracker->UpdateThread(pid, point.tgid);
TrackId track_id = context_->track_tracker->InternThreadTrack(utid);
context_->slice_tracker->Begin(ts, track_id, kNullStringId /* cat */,
name_id);
break;
}
case 'E': {
// |point.tgid| can be 0 in older android versions where the end event
// would not contain the value.
UniqueTid utid;
if (point.tgid == 0) {
// If we haven't seen this thread before, there can't have been a Begin
// event for it so just ignore the event.
auto opt_utid = context_->process_tracker->GetThreadOrNull(pid);
if (!opt_utid)
break;
utid = *opt_utid;
} else {
utid = context_->process_tracker->UpdateThread(pid, point.tgid);
}
TrackId track_id = context_->track_tracker->InternThreadTrack(utid);
context_->slice_tracker->End(ts, track_id);
break;
}
case 'S':
case 'F': {
StringId name_id = context_->storage->InternString(point.name);
int64_t cookie = static_cast<int64_t>(point.value);
UniquePid upid =
context_->process_tracker->GetOrCreateProcess(point.tgid);
TrackId track_id = context_->track_tracker->InternAndroidAsyncTrack(
name_id, upid, cookie);
if (point.phase == 'S') {
context_->slice_tracker->Begin(ts, track_id, kNullStringId, name_id);
} else {
context_->slice_tracker->End(ts, track_id);
}
break;
}
case 'C': {
// LMK events from userspace are hacked as counter events with the "value"
// of the counter representing the pid of the killed process which is
// reset to 0 once the kill is complete.
// Homogenise this with kernel LMK events as an instant event, ignoring
// the resets to 0.
if (point.name == "kill_one_process") {
auto killed_pid = static_cast<uint32_t>(point.value);
if (killed_pid != 0) {
UniquePid killed_upid =
context_->process_tracker->GetOrCreateProcess(killed_pid);
context_->event_tracker->PushInstant(ts, lmk_id_, killed_upid,
RefType::kRefUpid);
}
// TODO(lalitm): we should not add LMK events to the counters table
// once the UI has support for displaying instants.
}
// This is per upid on purpose. Some counters are pushed from arbitrary
// threads but are really per process.
UniquePid upid =
context_->process_tracker->GetOrCreateProcess(point.tgid);
StringId name_id = context_->storage->InternString(point.name);
TrackId track =
context_->track_tracker->InternProcessCounterTrack(name_id, upid);
context_->event_tracker->PushCounter(ts, point.value, track);
}
}
}
} // namespace trace_processor
} // namespace perfetto
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 <fstream>
#include <set>
#include <sstream>
#include <string>
#include "perfetto/ext/base/file_utils.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "test/gtest_and_gmock.h"
using testing::Contains;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::Not;
using testing::UnorderedElementsAre;
namespace perfetto {
namespace {
std::string GetFtracePath() {
size_t i = 0;
while (!FtraceProcfs::Create(FtraceController::kTracingPaths[i])) {
i++;
}
return std::string(FtraceController::kTracingPaths[i]);
}
void ResetFtrace(FtraceProcfs* ftrace) {
ftrace->DisableAllEvents();
ftrace->ClearTrace();
ftrace->EnableTracing();
}
std::string ReadFile(const std::string& name) {
std::string result;
PERFETTO_CHECK(base::ReadFile(GetFtracePath() + name, &result));
return result;
}
std::string GetTraceOutput() {
std::string output = ReadFile("trace");
if (output.empty()) {
ADD_FAILURE() << "Could not read trace output";
}
return output;
}
} // namespace
// TODO(lalitm): reenable these tests (see b/72306171).
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CreateWithGoodPath CreateWithGoodPath
#else
#define MAYBE_CreateWithGoodPath DISABLED_CreateWithGoodPath
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CreateWithGoodPath) {
EXPECT_TRUE(FtraceProcfs::Create(GetFtracePath()));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CreateWithBadPath CreateWithBadPath
#else
#define MAYBE_CreateWithBadPath DISABLED_CreateWithBadath
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CreateWithBadPath) {
EXPECT_FALSE(FtraceProcfs::Create(GetFtracePath() + std::string("bad_path")));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ClearTrace ClearTrace
#else
#define MAYBE_ClearTrace DISABLED_ClearTrace
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ClearTrace) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
ftrace.WriteTraceMarker("Hello, World!");
ftrace.ClearTrace();
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello, World!")));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_TraceMarker TraceMarker
#else
#define MAYBE_TraceMarker DISABLED_TraceMarker
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_TraceMarker) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
ftrace.WriteTraceMarker("Hello, World!");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello, World!"));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_EnableDisableEvent EnableDisableEvent
#else
#define MAYBE_EnableDisableEvent DISABLED_EnableDisableEvent
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_EnableDisableEvent) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
ftrace.EnableEvent("sched", "sched_switch");
sleep(1);
EXPECT_THAT(GetTraceOutput(), HasSubstr("sched_switch"));
ftrace.DisableEvent("sched", "sched_switch");
ftrace.ClearTrace();
sleep(1);
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("sched_switch")));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_EnableDisableTracing EnableDisableTracing
#else
#define MAYBE_EnableDisableTracing DISABLED_EnableDisableTracing
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_EnableDisableTracing) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
EXPECT_TRUE(ftrace.IsTracingEnabled());
ftrace.WriteTraceMarker("Before");
ftrace.DisableTracing();
EXPECT_FALSE(ftrace.IsTracingEnabled());
ftrace.WriteTraceMarker("During");
ftrace.EnableTracing();
EXPECT_TRUE(ftrace.IsTracingEnabled());
ftrace.WriteTraceMarker("After");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Before"));
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("During")));
EXPECT_THAT(GetTraceOutput(), HasSubstr("After"));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ReadFormatFile ReadFormatFile
#else
#define MAYBE_ReadFormatFile DISABLED_ReadFormatFile
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ReadFormatFile) {
FtraceProcfs ftrace(GetFtracePath());
std::string format = ftrace.ReadEventFormat("ftrace", "print");
EXPECT_THAT(format, HasSubstr("name: print"));
EXPECT_THAT(format, HasSubstr("field:char buf"));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CanOpenTracePipeRaw CanOpenTracePipeRaw
#else
#define MAYBE_CanOpenTracePipeRaw DISABLED_CanOpenTracePipeRaw
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CanOpenTracePipeRaw) {
FtraceProcfs ftrace(GetFtracePath());
EXPECT_TRUE(ftrace.OpenPipeForCpu(0));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_Clock Clock
#else
#define MAYBE_Clock DISABLED_Clock
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_Clock) {
FtraceProcfs ftrace(GetFtracePath());
std::set<std::string> clocks = ftrace.AvailableClocks();
EXPECT_THAT(clocks, Contains("local"));
EXPECT_THAT(clocks, Contains("global"));
EXPECT_TRUE(ftrace.SetClock("global"));
EXPECT_EQ(ftrace.GetClock(), "global");
EXPECT_TRUE(ftrace.SetClock("local"));
EXPECT_EQ(ftrace.GetClock(), "local");
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_CanSetBufferSize CanSetBufferSize
#else
#define MAYBE_CanSetBufferSize DISABLED_CanSetBufferSize
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_CanSetBufferSize) {
FtraceProcfs ftrace(GetFtracePath());
EXPECT_TRUE(ftrace.SetCpuBufferSizeInPages(4ul));
EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n"); // (4096 * 4) / 1024
EXPECT_TRUE(ftrace.SetCpuBufferSizeInPages(5ul));
EXPECT_EQ(ReadFile("buffer_size_kb"), "20\n"); // (4096 * 5) / 1024
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_FtraceControllerHardReset FtraceControllerHardReset
#else
#define MAYBE_FtraceControllerHardReset DISABLED_FtraceControllerHardReset
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_FtraceControllerHardReset) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
ftrace.SetCpuBufferSizeInPages(4ul);
ftrace.EnableTracing();
ftrace.EnableEvent("sched", "sched_switch");
ftrace.WriteTraceMarker("Hello, World!");
EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");
EXPECT_EQ(ReadFile("tracing_on"), "1\n");
EXPECT_EQ(ReadFile("events/enable"), "X\n");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello"));
HardResetFtraceState();
EXPECT_EQ(ReadFile("buffer_size_kb"), "4\n");
EXPECT_EQ(ReadFile("tracing_on"), "0\n");
EXPECT_EQ(ReadFile("events/enable"), "0\n");
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello")));
}
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define MAYBE_ReadEnabledEvents ReadEnabledEvents
#else
#define MAYBE_ReadEnabledEvents DISABLED_ReadEnabledEvents
#endif
TEST(FtraceProcfsIntegrationTest, MAYBE_ReadEnabledEvents) {
FtraceProcfs ftrace(GetFtracePath());
ResetFtrace(&ftrace);
EXPECT_THAT(ftrace.ReadEnabledEvents(), IsEmpty());
ftrace.EnableEvent("sched", "sched_switch");
ftrace.EnableEvent("kmem", "kmalloc");
EXPECT_THAT(ftrace.ReadEnabledEvents(),
UnorderedElementsAre("sched/sched_switch", "kmem/kmalloc"));
ftrace.DisableEvent("sched", "sched_switch");
ftrace.DisableEvent("kmem", "kmalloc");
EXPECT_THAT(ftrace.ReadEnabledEvents(), IsEmpty());
}
} // namespace perfetto
<commit_msg>Test: Improve FtraceProcfsIntegrationTest, skip if systrace is on am: 16b67309ba am: f9e65127ad am: 21be68b9b7 am: 032c2dc613 am: 7dd9748f5a<commit_after>/*
* Copyright (C) 2017 The Android Open Source Project
*
* 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 <fstream>
#include <set>
#include <sstream>
#include <string>
#include "perfetto/ext/base/file_utils.h"
#include "src/traced/probes/ftrace/ftrace_controller.h"
#include "src/traced/probes/ftrace/ftrace_procfs.h"
#include "test/gtest_and_gmock.h"
using testing::Contains;
using testing::HasSubstr;
using testing::IsEmpty;
using testing::Not;
using testing::UnorderedElementsAre;
// These tests run only on Android because on linux they require access to
// ftrace, which would be problematic in the CI when multiple tests run
// concurrently on the same machine. Android instead uses one emulator instance
// for each worker.
#if PERFETTO_BUILDFLAG(PERFETTO_OS_ANDROID)
#define ANDROID_ONLY_TEST(x) x
#else
#define ANDROID_ONLY_TEST(x) DISABLED_##x
#endif
namespace perfetto {
namespace {
std::string GetFtracePath() {
size_t i = 0;
while (!FtraceProcfs::Create(FtraceController::kTracingPaths[i])) {
i++;
}
return std::string(FtraceController::kTracingPaths[i]);
}
std::string ReadFile(const std::string& name) {
std::string result;
PERFETTO_CHECK(base::ReadFile(GetFtracePath() + name, &result));
return result;
}
std::string GetTraceOutput() {
std::string output = ReadFile("trace");
if (output.empty()) {
ADD_FAILURE() << "Could not read trace output";
}
return output;
}
class FtraceProcfsIntegrationTest : public testing::Test {
public:
void SetUp() override;
void TearDown() override;
std::unique_ptr<FtraceProcfs> ftrace_;
};
void FtraceProcfsIntegrationTest::SetUp() {
ftrace_ = FtraceProcfs::Create(GetFtracePath());
ASSERT_TRUE(ftrace_);
if (ftrace_->IsTracingEnabled()) {
GTEST_SKIP() << "Something else is using ftrace, skipping";
}
ftrace_->DisableAllEvents();
ftrace_->ClearTrace();
ftrace_->EnableTracing();
}
void FtraceProcfsIntegrationTest::TearDown() {
ftrace_->DisableAllEvents();
ftrace_->ClearTrace();
ftrace_->DisableTracing();
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CreateWithBadPath)) {
EXPECT_FALSE(FtraceProcfs::Create(GetFtracePath() + std::string("bad_path")));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ClearTrace)) {
ftrace_->WriteTraceMarker("Hello, World!");
ftrace_->ClearTrace();
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello, World!")));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(TraceMarker)) {
ftrace_->WriteTraceMarker("Hello, World!");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello, World!"));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(EnableDisableEvent)) {
ftrace_->EnableEvent("sched", "sched_switch");
sleep(1);
EXPECT_THAT(GetTraceOutput(), HasSubstr("sched_switch"));
ftrace_->DisableEvent("sched", "sched_switch");
ftrace_->ClearTrace();
sleep(1);
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("sched_switch")));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(EnableDisableTracing)) {
EXPECT_TRUE(ftrace_->IsTracingEnabled());
ftrace_->WriteTraceMarker("Before");
ftrace_->DisableTracing();
EXPECT_FALSE(ftrace_->IsTracingEnabled());
ftrace_->WriteTraceMarker("During");
ftrace_->EnableTracing();
EXPECT_TRUE(ftrace_->IsTracingEnabled());
ftrace_->WriteTraceMarker("After");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Before"));
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("During")));
EXPECT_THAT(GetTraceOutput(), HasSubstr("After"));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ReadFormatFile)) {
std::string format = ftrace_->ReadEventFormat("ftrace", "print");
EXPECT_THAT(format, HasSubstr("name: print"));
EXPECT_THAT(format, HasSubstr("field:char buf"));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CanOpenTracePipeRaw)) {
EXPECT_TRUE(ftrace_->OpenPipeForCpu(0));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(Clock)) {
std::set<std::string> clocks = ftrace_->AvailableClocks();
EXPECT_THAT(clocks, Contains("local"));
EXPECT_THAT(clocks, Contains("global"));
EXPECT_TRUE(ftrace_->SetClock("global"));
EXPECT_EQ(ftrace_->GetClock(), "global");
EXPECT_TRUE(ftrace_->SetClock("local"));
EXPECT_EQ(ftrace_->GetClock(), "local");
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(CanSetBufferSize)) {
EXPECT_TRUE(ftrace_->SetCpuBufferSizeInPages(4ul));
EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n"); // (4096 * 4) / 1024
EXPECT_TRUE(ftrace_->SetCpuBufferSizeInPages(5ul));
EXPECT_EQ(ReadFile("buffer_size_kb"), "20\n"); // (4096 * 5) / 1024
}
TEST_F(FtraceProcfsIntegrationTest,
ANDROID_ONLY_TEST(FtraceControllerHardReset)) {
ftrace_->SetCpuBufferSizeInPages(4ul);
ftrace_->EnableTracing();
ftrace_->EnableEvent("sched", "sched_switch");
ftrace_->WriteTraceMarker("Hello, World!");
EXPECT_EQ(ReadFile("buffer_size_kb"), "16\n");
EXPECT_EQ(ReadFile("tracing_on"), "1\n");
EXPECT_EQ(ReadFile("events/enable"), "X\n");
EXPECT_THAT(GetTraceOutput(), HasSubstr("Hello"));
HardResetFtraceState();
EXPECT_EQ(ReadFile("buffer_size_kb"), "4\n");
EXPECT_EQ(ReadFile("tracing_on"), "0\n");
EXPECT_EQ(ReadFile("events/enable"), "0\n");
EXPECT_THAT(GetTraceOutput(), Not(HasSubstr("Hello")));
}
TEST_F(FtraceProcfsIntegrationTest, ANDROID_ONLY_TEST(ReadEnabledEvents)) {
EXPECT_THAT(ftrace_->ReadEnabledEvents(), IsEmpty());
ftrace_->EnableEvent("sched", "sched_switch");
ftrace_->EnableEvent("kmem", "kmalloc");
EXPECT_THAT(ftrace_->ReadEnabledEvents(),
UnorderedElementsAre("sched/sched_switch", "kmem/kmalloc"));
ftrace_->DisableEvent("sched", "sched_switch");
ftrace_->DisableEvent("kmem", "kmalloc");
EXPECT_THAT(ftrace_->ReadEnabledEvents(), IsEmpty());
}
} // namespace
} // namespace perfetto
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgpainteditem.h"
#include <private/qsgpainteditem_p.h>
#include <private/qsgpainternode_p.h>
#include <private/qsgcontext_p.h>
#include <private/qsgadaptationlayer_p.h>
#include <qmath.h>
QT_BEGIN_NAMESPACE
/*!
\class QSGPaintedItem
\brief The QSGPaintedItem class provides a way to use the QPainter API in the
QML Scene Graph.
The QSGPaintedItem makes it possible to use the QPainter API with the QML Scene Graph.
It sets up a textured rectangle in the Scene Graph and uses a QPainter to paint
onto the texture. The render target can be either a QImage or a QGLFramebufferObject.
When the render target is a QImage, QPainter first renders into the image then
the content is uploaded to the texture.
When a QGLFramebufferObject is used, QPainter paints directly onto the texture.
Call update() to trigger a repaint.
To enable QPainter to do anti-aliased rendering, use setAntialiasing().
QSGPaintedItem is meant to make it easier to port old code that is using the
QPainter API to the QML Scene Graph API and it should be used only for that purpose.
To write your own painted item, you first create a subclass of QSGPaintedItem, and then
start by implementing its only pure virtual public function: paint(), which implements
the actual painting. To get the size of the area painted by the item, use
contentsBoundingRect().
*/
/*!
\enum QSGPaintedItem::RenderTarget
This enum describes QSGPaintedItem's render targets. The render target is the
surface QPainter paints onto before the item is rendered on screen.
\value Image The default; QPainter paints into a QImage using the raster paint engine.
The image's content needs to be uploaded to graphics memory afterward, this operation
can potentially be slow if the item is large. This render target allows high quality
anti-aliasing and fast item resizing.
\value FramebufferObject QPainter paints into a QGLFramebufferObject using the GL
paint engine. Painting can be faster as no texture upload is required, but anti-aliasing
quality is not as good as if using an image. This render target allows faster rendering
in some cases, but you should avoid using it if the item is resized often.
\sa setRenderTarget()
*/
/*!
\internal
*/
QSGPaintedItemPrivate::QSGPaintedItemPrivate()
: QSGItemPrivate()
, contentsScale(1.0)
, fillColor(Qt::transparent)
, renderTarget(QSGPaintedItem::Image)
, geometryDirty(false)
, contentsDirty(false)
, opaquePainting(false)
, antialiasing(false)
, mipmap(false)
{
}
/*!
Constructs a QSGPaintedItem with the given \a parent item.
*/
QSGPaintedItem::QSGPaintedItem(QSGItem *parent)
: QSGItem(*(new QSGPaintedItemPrivate), parent)
{
setFlag(ItemHasContents);
}
/*!
\internal
*/
QSGPaintedItem::QSGPaintedItem(QSGPaintedItemPrivate &dd, QSGItem *parent)
: QSGItem(dd, parent)
{
setFlag(ItemHasContents);
}
/*!
Destroys the QSGPaintedItem.
*/
QSGPaintedItem::~QSGPaintedItem()
{
}
/*!
Schedules a redraw of the area covered by \a rect in this item. You can call this function
whenever your item needs to be redrawn, such as if it changes appearance or size.
This function does not cause an immediate paint; instead it schedules a paint request that
is processed by the QML Scene Graph when the next frame is rendered. The item will only be
redrawn if it is visible.
Note that calling this function will trigger a repaint of the whole scene.
\sa paint()
*/
void QSGPaintedItem::update(const QRect &rect)
{
Q_D(QSGPaintedItem);
d->contentsDirty = true;
QRect srect(qCeil(rect.x()*d->contentsScale),
qCeil(rect.y()*d->contentsScale),
qCeil(rect.width()*d->contentsScale),
qCeil(rect.height()*d->contentsScale));
if (srect.isNull() && !d->dirtyRect.isNull())
d->dirtyRect = contentsBoundingRect().toAlignedRect();
else
d->dirtyRect |= (contentsBoundingRect() & srect).toAlignedRect();
QSGItem::update();
}
/*!
Returns true if this item is opaque; otherwise, false is returned.
By default, painted items are not opaque.
\sa setOpaquePainting()
*/
bool QSGPaintedItem::opaquePainting() const
{
Q_D(const QSGPaintedItem);
return d->opaquePainting;
}
/*!
If \a opaque is true, the item is opaque; otherwise, it is considered as translucent.
Opaque items are not blended with the rest of the scene, you should set this to true
if the content of the item is opaque to speed up rendering.
By default, painted items are not opaque.
\sa opaquePainting()
*/
void QSGPaintedItem::setOpaquePainting(bool opaque)
{
Q_D(QSGPaintedItem);
if (d->opaquePainting == opaque)
return;
d->opaquePainting = opaque;
QSGItem::update();
}
/*!
Returns true if antialiased painting is enabled; otherwise, false is returned.
By default, antialiasing is not enabled.
\sa setAntialiasing()
*/
bool QSGPaintedItem::antialiasing() const
{
Q_D(const QSGPaintedItem);
return d->antialiasing;
}
/*!
If \a enable is true, antialiased painting is enabled.
By default, antialiasing is not enabled.
\sa antialiasing()
*/
void QSGPaintedItem::setAntialiasing(bool enable)
{
Q_D(QSGPaintedItem);
if (d->antialiasing == enable)
return;
d->antialiasing = enable;
update();
}
/*!
Returns true if mipmaps are enabled; otherwise, false is returned.
By default, mipmapping is not enabled.
\sa setMipmap()
*/
bool QSGPaintedItem::mipmap() const
{
Q_D(const QSGPaintedItem);
return d->mipmap;
}
/*!
If \a enable is true, mipmapping is enabled on the associated texture.
Mipmapping increases rendering speed and reduces aliasing artifacts when the item is
scaled down.
By default, mipmapping is not enabled.
\sa mipmap()
*/
void QSGPaintedItem::setMipmap(bool enable)
{
Q_D(QSGPaintedItem);
if (d->mipmap == enable)
return;
d->mipmap = enable;
update();
}
/*!
This function returns the outer bounds of the item as a rectangle; all painting must be
restricted to inside an item's bounding rect.
If the contents size has not been set it reflects the size of the item; otherwise
it reflects the contents size scaled by the contents scale.
Use this function to know the area painted by the item.
\sa QSGItem::width(), QSGItem::height(), contentsSize(), contentsScale()
*/
QRectF QSGPaintedItem::contentsBoundingRect() const
{
Q_D(const QSGPaintedItem);
qreal w = d->width;
QSizeF sz = d->contentsSize * d->contentsScale;
if (w < sz.width())
w = sz.width();
qreal h = d->height;
if (h < sz.height())
h = sz.height();
return QRectF(0, 0, w, h);
}
/*!
\property QSGPaintedItem::contentsSize
\brief The size of the contents
The contents size is the size of the item in regards to how it is painted
using the paint() function. This is distinct from the size of the
item in regards to height() and width().
*/
QSize QSGPaintedItem::contentsSize() const
{
Q_D(const QSGPaintedItem);
return d->contentsSize;
}
void QSGPaintedItem::setContentsSize(const QSize &size)
{
Q_D(QSGPaintedItem);
if (d->contentsSize == size)
return;
d->contentsSize = size;
update();
}
/*!
This convenience function is equivalent to calling setContentsSize(QSize()).
*/
void QSGPaintedItem::resetContentsSize()
{
setContentsSize(QSize());
}
/*!
\property QSGPaintedItem::contentsScale
\brief The scale of the contents
All painting happening in paint() is scaled by the contents scale. This is distinct
from the scale of the item in regards to scale().
The default value is 1.
*/
qreal QSGPaintedItem::contentsScale() const
{
Q_D(const QSGPaintedItem);
return d->contentsScale;
}
void QSGPaintedItem::setContentsScale(qreal scale)
{
Q_D(QSGPaintedItem);
if (d->contentsScale == scale)
return;
d->contentsScale = scale;
update();
}
/*!
\property QSGPaintedItem::fillColor
\brief The item's background fill color.
By default, the fill color is set to Qt::transparent.
*/
QColor QSGPaintedItem::fillColor() const
{
Q_D(const QSGPaintedItem);
return d->fillColor;
}
void QSGPaintedItem::setFillColor(const QColor &c)
{
Q_D(QSGPaintedItem);
if (d->fillColor == c)
return;
d->fillColor = c;
update();
emit fillColorChanged();
}
/*!
\property QSGPaintedItem::renderTarget
\brief The item's render target.
This property defines which render target the QPainter renders into, it can be either
QSGPaintedItem::Image or QSGPaintedItem::FramebufferObject. Both have certains benefits,
typically performance versus quality. Using a framebuffer object avoids a costly upload
of the image contents to the texture in graphics memory, while using an image enables
high quality anti-aliasing.
\warning Resizing a framebuffer object is a costly operation, avoid using
the QSGPaintedItem::FramebufferObject render target if the item gets resized often.
By default, the render target is QSGPaintedItem::Image.
*/
QSGPaintedItem::RenderTarget QSGPaintedItem::renderTarget() const
{
Q_D(const QSGPaintedItem);
return d->renderTarget;
}
void QSGPaintedItem::setRenderTarget(RenderTarget target)
{
Q_D(QSGPaintedItem);
if (d->renderTarget == target)
return;
d->renderTarget = target;
update();
emit renderTargetChanged();
}
/*!
\fn virtual void QSGPaintedItem::paint(QPainter *painter) = 0
This function, which is usually called by the QML Scene Graph, paints the
contents of an item in local coordinates.
The function is called after the item has been filled with the fillColor.
Reimplement this function in a QSGPaintedItem subclass to provide the
item's painting implementation, using \a painter.
*/
/*!
This function is called after the item's geometry has changed.
*/
void QSGPaintedItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
Q_D(QSGPaintedItem);
d->geometryDirty = true;
QSGItem::geometryChanged(newGeometry, oldGeometry);
}
/*!
This function is called when the Scene Graph node associated to the item needs to
be updated.
*/
QSGNode *QSGPaintedItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
{
Q_UNUSED(data);
Q_D(QSGPaintedItem);
if (width() <= 0 || height() <= 0) {
delete oldNode;
return 0;
}
QSGPainterNode *node = static_cast<QSGPainterNode *>(oldNode);
if (!node)
node = new QSGPainterNode(this);
QRectF br = contentsBoundingRect();
node->setPreferredRenderTarget(d->renderTarget);
node->setSize(QSize(qRound(br.width()), qRound(br.height())));
node->setSmoothPainting(d->antialiasing);
node->setLinearFiltering(d->smooth);
node->setMipmapping(d->mipmap);
node->setOpaquePainting(d->opaquePainting);
node->setFillColor(d->fillColor);
node->setContentsScale(d->contentsScale);
node->setDirty(d->contentsDirty || d->geometryDirty, d->dirtyRect);
node->update();
d->contentsDirty = false;
d->geometryDirty = false;
d->dirtyRect = QRect();
return node;
}
QT_END_NAMESPACE
<commit_msg>Documented which thread gets the QSGPaintedItem::paint() call.<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsgpainteditem.h"
#include <private/qsgpainteditem_p.h>
#include <private/qsgpainternode_p.h>
#include <private/qsgcontext_p.h>
#include <private/qsgadaptationlayer_p.h>
#include <qmath.h>
QT_BEGIN_NAMESPACE
/*!
\class QSGPaintedItem
\brief The QSGPaintedItem class provides a way to use the QPainter API in the
QML Scene Graph.
The QSGPaintedItem makes it possible to use the QPainter API with the QML Scene Graph.
It sets up a textured rectangle in the Scene Graph and uses a QPainter to paint
onto the texture. The render target can be either a QImage or a QGLFramebufferObject.
When the render target is a QImage, QPainter first renders into the image then
the content is uploaded to the texture.
When a QGLFramebufferObject is used, QPainter paints directly onto the texture.
Call update() to trigger a repaint.
To enable QPainter to do anti-aliased rendering, use setAntialiasing().
QSGPaintedItem is meant to make it easier to port old code that is using the
QPainter API to the QML Scene Graph API and it should be used only for that purpose.
To write your own painted item, you first create a subclass of QSGPaintedItem, and then
start by implementing its only pure virtual public function: paint(), which implements
the actual painting. To get the size of the area painted by the item, use
contentsBoundingRect().
*/
/*!
\enum QSGPaintedItem::RenderTarget
This enum describes QSGPaintedItem's render targets. The render target is the
surface QPainter paints onto before the item is rendered on screen.
\value Image The default; QPainter paints into a QImage using the raster paint engine.
The image's content needs to be uploaded to graphics memory afterward, this operation
can potentially be slow if the item is large. This render target allows high quality
anti-aliasing and fast item resizing.
\value FramebufferObject QPainter paints into a QGLFramebufferObject using the GL
paint engine. Painting can be faster as no texture upload is required, but anti-aliasing
quality is not as good as if using an image. This render target allows faster rendering
in some cases, but you should avoid using it if the item is resized often.
\sa setRenderTarget()
*/
/*!
\internal
*/
QSGPaintedItemPrivate::QSGPaintedItemPrivate()
: QSGItemPrivate()
, contentsScale(1.0)
, fillColor(Qt::transparent)
, renderTarget(QSGPaintedItem::Image)
, geometryDirty(false)
, contentsDirty(false)
, opaquePainting(false)
, antialiasing(false)
, mipmap(false)
{
}
/*!
Constructs a QSGPaintedItem with the given \a parent item.
*/
QSGPaintedItem::QSGPaintedItem(QSGItem *parent)
: QSGItem(*(new QSGPaintedItemPrivate), parent)
{
setFlag(ItemHasContents);
}
/*!
\internal
*/
QSGPaintedItem::QSGPaintedItem(QSGPaintedItemPrivate &dd, QSGItem *parent)
: QSGItem(dd, parent)
{
setFlag(ItemHasContents);
}
/*!
Destroys the QSGPaintedItem.
*/
QSGPaintedItem::~QSGPaintedItem()
{
}
/*!
Schedules a redraw of the area covered by \a rect in this item. You can call this function
whenever your item needs to be redrawn, such as if it changes appearance or size.
This function does not cause an immediate paint; instead it schedules a paint request that
is processed by the QML Scene Graph when the next frame is rendered. The item will only be
redrawn if it is visible.
Note that calling this function will trigger a repaint of the whole scene.
\sa paint()
*/
void QSGPaintedItem::update(const QRect &rect)
{
Q_D(QSGPaintedItem);
d->contentsDirty = true;
QRect srect(qCeil(rect.x()*d->contentsScale),
qCeil(rect.y()*d->contentsScale),
qCeil(rect.width()*d->contentsScale),
qCeil(rect.height()*d->contentsScale));
if (srect.isNull() && !d->dirtyRect.isNull())
d->dirtyRect = contentsBoundingRect().toAlignedRect();
else
d->dirtyRect |= (contentsBoundingRect() & srect).toAlignedRect();
QSGItem::update();
}
/*!
Returns true if this item is opaque; otherwise, false is returned.
By default, painted items are not opaque.
\sa setOpaquePainting()
*/
bool QSGPaintedItem::opaquePainting() const
{
Q_D(const QSGPaintedItem);
return d->opaquePainting;
}
/*!
If \a opaque is true, the item is opaque; otherwise, it is considered as translucent.
Opaque items are not blended with the rest of the scene, you should set this to true
if the content of the item is opaque to speed up rendering.
By default, painted items are not opaque.
\sa opaquePainting()
*/
void QSGPaintedItem::setOpaquePainting(bool opaque)
{
Q_D(QSGPaintedItem);
if (d->opaquePainting == opaque)
return;
d->opaquePainting = opaque;
QSGItem::update();
}
/*!
Returns true if antialiased painting is enabled; otherwise, false is returned.
By default, antialiasing is not enabled.
\sa setAntialiasing()
*/
bool QSGPaintedItem::antialiasing() const
{
Q_D(const QSGPaintedItem);
return d->antialiasing;
}
/*!
If \a enable is true, antialiased painting is enabled.
By default, antialiasing is not enabled.
\sa antialiasing()
*/
void QSGPaintedItem::setAntialiasing(bool enable)
{
Q_D(QSGPaintedItem);
if (d->antialiasing == enable)
return;
d->antialiasing = enable;
update();
}
/*!
Returns true if mipmaps are enabled; otherwise, false is returned.
By default, mipmapping is not enabled.
\sa setMipmap()
*/
bool QSGPaintedItem::mipmap() const
{
Q_D(const QSGPaintedItem);
return d->mipmap;
}
/*!
If \a enable is true, mipmapping is enabled on the associated texture.
Mipmapping increases rendering speed and reduces aliasing artifacts when the item is
scaled down.
By default, mipmapping is not enabled.
\sa mipmap()
*/
void QSGPaintedItem::setMipmap(bool enable)
{
Q_D(QSGPaintedItem);
if (d->mipmap == enable)
return;
d->mipmap = enable;
update();
}
/*!
This function returns the outer bounds of the item as a rectangle; all painting must be
restricted to inside an item's bounding rect.
If the contents size has not been set it reflects the size of the item; otherwise
it reflects the contents size scaled by the contents scale.
Use this function to know the area painted by the item.
\sa QSGItem::width(), QSGItem::height(), contentsSize(), contentsScale()
*/
QRectF QSGPaintedItem::contentsBoundingRect() const
{
Q_D(const QSGPaintedItem);
qreal w = d->width;
QSizeF sz = d->contentsSize * d->contentsScale;
if (w < sz.width())
w = sz.width();
qreal h = d->height;
if (h < sz.height())
h = sz.height();
return QRectF(0, 0, w, h);
}
/*!
\property QSGPaintedItem::contentsSize
\brief The size of the contents
The contents size is the size of the item in regards to how it is painted
using the paint() function. This is distinct from the size of the
item in regards to height() and width().
*/
QSize QSGPaintedItem::contentsSize() const
{
Q_D(const QSGPaintedItem);
return d->contentsSize;
}
void QSGPaintedItem::setContentsSize(const QSize &size)
{
Q_D(QSGPaintedItem);
if (d->contentsSize == size)
return;
d->contentsSize = size;
update();
}
/*!
This convenience function is equivalent to calling setContentsSize(QSize()).
*/
void QSGPaintedItem::resetContentsSize()
{
setContentsSize(QSize());
}
/*!
\property QSGPaintedItem::contentsScale
\brief The scale of the contents
All painting happening in paint() is scaled by the contents scale. This is distinct
from the scale of the item in regards to scale().
The default value is 1.
*/
qreal QSGPaintedItem::contentsScale() const
{
Q_D(const QSGPaintedItem);
return d->contentsScale;
}
void QSGPaintedItem::setContentsScale(qreal scale)
{
Q_D(QSGPaintedItem);
if (d->contentsScale == scale)
return;
d->contentsScale = scale;
update();
}
/*!
\property QSGPaintedItem::fillColor
\brief The item's background fill color.
By default, the fill color is set to Qt::transparent.
*/
QColor QSGPaintedItem::fillColor() const
{
Q_D(const QSGPaintedItem);
return d->fillColor;
}
void QSGPaintedItem::setFillColor(const QColor &c)
{
Q_D(QSGPaintedItem);
if (d->fillColor == c)
return;
d->fillColor = c;
update();
emit fillColorChanged();
}
/*!
\property QSGPaintedItem::renderTarget
\brief The item's render target.
This property defines which render target the QPainter renders into, it can be either
QSGPaintedItem::Image or QSGPaintedItem::FramebufferObject. Both have certains benefits,
typically performance versus quality. Using a framebuffer object avoids a costly upload
of the image contents to the texture in graphics memory, while using an image enables
high quality anti-aliasing.
\warning Resizing a framebuffer object is a costly operation, avoid using
the QSGPaintedItem::FramebufferObject render target if the item gets resized often.
By default, the render target is QSGPaintedItem::Image.
*/
QSGPaintedItem::RenderTarget QSGPaintedItem::renderTarget() const
{
Q_D(const QSGPaintedItem);
return d->renderTarget;
}
void QSGPaintedItem::setRenderTarget(RenderTarget target)
{
Q_D(QSGPaintedItem);
if (d->renderTarget == target)
return;
d->renderTarget = target;
update();
emit renderTargetChanged();
}
/*!
\fn virtual void QSGPaintedItem::paint(QPainter *painter) = 0
This function, which is usually called by the QML Scene Graph, paints the
contents of an item in local coordinates.
The function is called after the item has been filled with the fillColor.
Reimplement this function in a QSGPaintedItem subclass to provide the
item's painting implementation, using \a painter.
\note The QML Scene Graph uses two separate threads, the main thread does things such as
processing events or updating animations while a second thread does the actual OpenGL rendering.
As a consequence, paint() is not called from the main GUI thread but from the GL enabled
renderer thread.
*/
/*!
This function is called after the item's geometry has changed.
*/
void QSGPaintedItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
Q_D(QSGPaintedItem);
d->geometryDirty = true;
QSGItem::geometryChanged(newGeometry, oldGeometry);
}
/*!
This function is called when the Scene Graph node associated to the item needs to
be updated.
*/
QSGNode *QSGPaintedItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *data)
{
Q_UNUSED(data);
Q_D(QSGPaintedItem);
if (width() <= 0 || height() <= 0) {
delete oldNode;
return 0;
}
QSGPainterNode *node = static_cast<QSGPainterNode *>(oldNode);
if (!node)
node = new QSGPainterNode(this);
QRectF br = contentsBoundingRect();
node->setPreferredRenderTarget(d->renderTarget);
node->setSize(QSize(qRound(br.width()), qRound(br.height())));
node->setSmoothPainting(d->antialiasing);
node->setLinearFiltering(d->smooth);
node->setMipmapping(d->mipmap);
node->setOpaquePainting(d->opaquePainting);
node->setFillColor(d->fillColor);
node->setContentsScale(d->contentsScale);
node->setDirty(d->contentsDirty || d->geometryDirty, d->dirtyRect);
node->update();
d->contentsDirty = false;
d->geometryDirty = false;
d->dirtyRect = QRect();
return node;
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform 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.
*/
/**
* @file tgPrismaticInfo.cpp
* @brief Contains the definition of members of the class tgPrismatic. A prismatic actuator builder.
* @author Alexander Xydes
* @copyright Copyright (C) 2014 NASA Ames Research Center
* $Id$
*/
#include "tgPrismaticInfo.h"
tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config) :
m_config(config),
tgConnectorInfo()
{
}
tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config, tgTags tags) :
m_config(config),
tgConnectorInfo(tags)
{}
tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config, const tgPair& pair) :
m_config(config),
tgConnectorInfo(pair)
{}
tgConnectorInfo* tgPrismaticInfo::createConnectorInfo(const tgPair& pair)
{
return new tgPrismaticInfo(m_config, pair);
}
void tgPrismaticInfo::initConnector(tgWorld& world)
{
// Anything to do here?
}
tgModel* tgPrismaticInfo::createModel(tgWorld& world)
{
tgNode startNode = this->getFrom();
tgNode endNode = this->getTo();
btVector3 buildVec = (endNode - startNode);
double m_startLength = buildVec.length();
tgNode midNode = tgNode(startNode + (buildVec / 2.0),"mid");
m_config.m_minTotalLength = m_startLength;
tgPrismatic* prism = new tgPrismatic(getTags(), m_config);
buildModel(world, prism);
return prism;
}
const int tgPrismaticInfo::getSegments() const
{
//@todo: make configurable
return 2;
}
double tgPrismaticInfo::getMass()
{
// @todo: add up the rigid bodies
return 0;
}
void tgPrismaticInfo::buildModel(tgWorld& world, tgModel* prismatic)
{
// get global from _ to - still need these is both places I think.
tgNode startNode = this->getFrom();
tgNode endNode = this->getTo();
// Calculate the size of the rods
double rodSize = m_config.m_minTotalLength / 2.0;
btVector3 buildVec = (endNode - startNode);
btVector3 offset = btVector3(0.1,0.1,0.1);
tgNode midNode = tgNode((buildVec / 2.0),"mid");
tgNode midNode1 = tgNode(midNode - offset,"mid1");
tgNode midNode2 = tgNode(midNode + offset,"mid2");
//super structure to the prismatic actuator's two rods
tgStructure prism;
tgStructure rod;
rod.addNode(0,0,0); //Bottom
rod.addNode(midNode1);
rod.addPair(0,1,"a rod");
tgStructure* rod1 = new tgStructure(rod);
rod1->addTags("rod v1");
rod1->move(startNode + offset);
prism.addChild(rod1);
tgStructure* rod2 = new tgStructure(rod);
rod2->addTags("rod v2");
rod2->move(startNode + midNode2);
prism.addChild(rod2);
std::vector<tgStructure*> children = prism.getChildren();
tgNodes n1 = children[0]->getNodes();
tgNodes n2 = children[1]->getNodes();
prism.addPair(n1[1], n2[0], "muscle seg");
tgBuildSpec spec;
spec.addBuilder("rod", new tgRodInfo(m_config.m_rod1Config));
spec.addBuilder("muscle", new tgLinearStringInfo(m_stringConfig));
// Create your structureInfo
tgStructureInfo structureInfo(prism, spec);
std::cout << "tgPrismaticInfo::buildModel() 7" << std::endl;
// Use the structureInfo to build our model
structureInfo.buildInto(*prismatic, world);
/* Now that the sub-structure has been created, attach it
* to the super-structure via hard links?
* Very manual from here, since this is the only place we have all
* of the necessary pointers
*/
// We have to delete these
std::vector<tgPair*> linkerPairs;
// "From" side:
linkerPairs.push_back(new tgPair(startNode, n1[0], tgString("anchor seg",1)));
// "To" side:
linkerPairs.push_back(new tgPair(n2[1], endNode, tgString("anchor seg",2)));
// Perhaps overkill...
// These pointers will be deleted by tgStructure
std::vector <tgRigidInfo*> allRigids(structureInfo.getAllRigids());
std::cout << "tgPrismaticInfo num rigids: " << allRigids.size() << std::endl;
allRigids.push_back(getToRigidInfo());
allRigids.push_back(getFromRigidInfo());
// We have to delete these
// std::vector <tgConnectorInfo* > linkerInfo;
// Can this part be done in a loop easily?
// linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[0]));
// linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[1]));
for (std::size_t i = 0; i < linkerInfo.size(); i++)
{
linkerInfo[i]->chooseRigids(allRigids);
linkerInfo[i]->initConnector(world);
tgModel* m = linkerInfo[i]->createModel(world);
m->setTags(linkerInfo[i]->getTags());
if(m != 0) {
prismatic->addChild(m);
}
}
// Clean up - see if there's a way to do this with references instead?
for (std::size_t i = 0; i < linkerInfo.size(); i++)
{
delete linkerInfo[i];
}
linkerInfo.clear();
for (std::size_t i = 0; i < linkerPairs.size(); i++)
{
delete linkerPairs[i];
}
linkerPairs.clear();
/**
double m_startLength = buildVec.length();
btVector3 offset = buildVec.normalize();
tgStructure rod;
rod.addNode(0,0,0); //Bottom
rod.addNode(midNode);
rod.addPair(0,1,"a rod");
//1st rod
tgStructure* rod1 = new tgStructure(rod);
//Move the first one into position
rod1->addTags("rod v1");
rod1->move(startNode);
prism.addChild(rod1);
//second rod
tgStructure* rod2 = new tgStructure(rod);
rod2->addTags("rod v2");
rod2->move(startNode + midNode);
prism.addChild(rod2);
std::vector<tgStructure*> children = prism.getChildren();
tgNodes n1 = children[0]->getNodes();
tgNodes n2 = children[1]->getNodes();
prism.addPair(n1[1], n2[0], "muscle seg");
tgBuildSpec spec;
spec.addBuilder("rod", new tgRodInfo(m_config.m_rod1Config));
// spec.addBuilder("rod v1", new tgRodInfo(m_config.m_rod1Config));
// spec.addBuilder("rod v2", new tgRodInfo(m_config.m_rod2Config));
spec.addBuilder("muscle", new tgLinearStringInfo(m_stringConfig));
// Create your structureInfo
tgStructureInfo structureInfo(prism, spec);
std::cout << "tgPrismaticInfo::buildModel() 7" << std::endl;
// Use the structureInfo to build our model
structureInfo.buildInto(*prismatic, world);
/* Now that the sub-structure has been created, attach it
* to the super-structure
* Very manual from here, since this is the only place we have all
* of the necessary pointers
*
// We have to delete these
std::vector<tgPair*> linkerPairs;
// "From" side:
linkerPairs.push_back(new tgPair(startNode, n1[0], tgString("anchor seg",1)));
// "To" side:
linkerPairs.push_back(new tgPair(n2[1], endNode, tgString("anchor seg",2)));
// Perhaps overkill...
// These pointers will be deleted by tgStructure
std::vector <tgRigidInfo*> allRigids(structureInfo.getAllRigids());
std::cout << "tgPrismaticInfo num rigids: " << allRigids.size() << std::endl;
allRigids.push_back(getToRigidInfo());
allRigids.push_back(getFromRigidInfo());
// We have to delete these
std::vector <tgConnectorInfo* > linkerInfo;
// Can this part be done in a loop easily?
linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[0]));
linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[1]));
for (std::size_t i = 0; i < linkerInfo.size(); i++)
{
linkerInfo[i]->chooseRigids(allRigids);
linkerInfo[i]->initConnector(world);
tgModel* m = linkerInfo[i]->createModel(world);
m->setTags(linkerInfo[i]->getTags());
if(m != 0) {
prismatic->addChild(m);
}
}
// Clean up - see if there's a way to do this with references instead?
for (std::size_t i = 0; i < linkerInfo.size(); i++)
{
delete linkerInfo[i];
}
linkerInfo.clear();
for (std::size_t i = 0; i < linkerPairs.size(); i++)
{
delete linkerPairs[i];
}
linkerPairs.clear();
/**/
std::cout << "tgPrismaticInfo::buildModel() 8" << std::endl;
//not needed?
// prismatic->setup(world);
#if(0)
// Debug printing
std::cout << "StructureInfo:" << std::endl;
std::cout << structureInfo << std::endl;
std::cout << "Model: " << std::endl;
std::cout << *prismatic << std::endl;
#endif
}
<commit_msg>Uncommenting accidentally commented line<commit_after>/*
* Copyright © 2012, United States Government, as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All rights reserved.
*
* The NASA Tensegrity Robotics Toolkit (NTRT) v1 platform 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.
*/
/**
* @file tgPrismaticInfo.cpp
* @brief Contains the definition of members of the class tgPrismatic. A prismatic actuator builder.
* @author Alexander Xydes
* @copyright Copyright (C) 2014 NASA Ames Research Center
* $Id$
*/
#include "tgPrismaticInfo.h"
tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config) :
m_config(config),
tgConnectorInfo()
{
}
tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config, tgTags tags) :
m_config(config),
tgConnectorInfo(tags)
{}
tgPrismaticInfo::tgPrismaticInfo(const tgPrismatic::Config& config, const tgPair& pair) :
m_config(config),
tgConnectorInfo(pair)
{}
tgConnectorInfo* tgPrismaticInfo::createConnectorInfo(const tgPair& pair)
{
return new tgPrismaticInfo(m_config, pair);
}
void tgPrismaticInfo::initConnector(tgWorld& world)
{
// Anything to do here?
}
tgModel* tgPrismaticInfo::createModel(tgWorld& world)
{
tgNode startNode = this->getFrom();
tgNode endNode = this->getTo();
btVector3 buildVec = (endNode - startNode);
double m_startLength = buildVec.length();
tgNode midNode = tgNode(startNode + (buildVec / 2.0),"mid");
m_config.m_minTotalLength = m_startLength;
tgPrismatic* prism = new tgPrismatic(getTags(), m_config);
buildModel(world, prism);
return prism;
}
const int tgPrismaticInfo::getSegments() const
{
//@todo: make configurable
return 2;
}
double tgPrismaticInfo::getMass()
{
// @todo: add up the rigid bodies
return 0;
}
void tgPrismaticInfo::buildModel(tgWorld& world, tgModel* prismatic)
{
// get global from _ to - still need these is both places I think.
tgNode startNode = this->getFrom();
tgNode endNode = this->getTo();
// Calculate the size of the rods
double rodSize = m_config.m_minTotalLength / 2.0;
btVector3 buildVec = (endNode - startNode);
btVector3 offset = btVector3(0.1,0.1,0.1);
tgNode midNode = tgNode((buildVec / 2.0),"mid");
tgNode midNode1 = tgNode(midNode - offset,"mid1");
tgNode midNode2 = tgNode(midNode + offset,"mid2");
//super structure to the prismatic actuator's two rods
tgStructure prism;
tgStructure rod;
rod.addNode(0,0,0); //Bottom
rod.addNode(midNode1);
rod.addPair(0,1,"a rod");
tgStructure* rod1 = new tgStructure(rod);
rod1->addTags("rod v1");
rod1->move(startNode + offset);
prism.addChild(rod1);
tgStructure* rod2 = new tgStructure(rod);
rod2->addTags("rod v2");
rod2->move(startNode + midNode2);
prism.addChild(rod2);
std::vector<tgStructure*> children = prism.getChildren();
tgNodes n1 = children[0]->getNodes();
tgNodes n2 = children[1]->getNodes();
prism.addPair(n1[1], n2[0], "muscle seg");
tgBuildSpec spec;
spec.addBuilder("rod", new tgRodInfo(m_config.m_rod1Config));
spec.addBuilder("muscle", new tgLinearStringInfo(m_stringConfig));
// Create your structureInfo
tgStructureInfo structureInfo(prism, spec);
std::cout << "tgPrismaticInfo::buildModel() 7" << std::endl;
// Use the structureInfo to build our model
structureInfo.buildInto(*prismatic, world);
/* Now that the sub-structure has been created, attach it
* to the super-structure via hard links?
* Very manual from here, since this is the only place we have all
* of the necessary pointers
*/
// We have to delete these
std::vector<tgPair*> linkerPairs;
// "From" side:
linkerPairs.push_back(new tgPair(startNode, n1[0], tgString("anchor seg",1)));
// "To" side:
linkerPairs.push_back(new tgPair(n2[1], endNode, tgString("anchor seg",2)));
// Perhaps overkill...
// These pointers will be deleted by tgStructure
std::vector <tgRigidInfo*> allRigids(structureInfo.getAllRigids());
std::cout << "tgPrismaticInfo num rigids: " << allRigids.size() << std::endl;
allRigids.push_back(getToRigidInfo());
allRigids.push_back(getFromRigidInfo());
// We have to delete these
std::vector <tgConnectorInfo* > linkerInfo;
// Can this part be done in a loop easily?
// linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[0]));
// linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[1]));
for (std::size_t i = 0; i < linkerInfo.size(); i++)
{
linkerInfo[i]->chooseRigids(allRigids);
linkerInfo[i]->initConnector(world);
tgModel* m = linkerInfo[i]->createModel(world);
m->setTags(linkerInfo[i]->getTags());
if(m != 0) {
prismatic->addChild(m);
}
}
// Clean up - see if there's a way to do this with references instead?
for (std::size_t i = 0; i < linkerInfo.size(); i++)
{
delete linkerInfo[i];
}
linkerInfo.clear();
for (std::size_t i = 0; i < linkerPairs.size(); i++)
{
delete linkerPairs[i];
}
linkerPairs.clear();
/**
double m_startLength = buildVec.length();
btVector3 offset = buildVec.normalize();
tgStructure rod;
rod.addNode(0,0,0); //Bottom
rod.addNode(midNode);
rod.addPair(0,1,"a rod");
//1st rod
tgStructure* rod1 = new tgStructure(rod);
//Move the first one into position
rod1->addTags("rod v1");
rod1->move(startNode);
prism.addChild(rod1);
//second rod
tgStructure* rod2 = new tgStructure(rod);
rod2->addTags("rod v2");
rod2->move(startNode + midNode);
prism.addChild(rod2);
std::vector<tgStructure*> children = prism.getChildren();
tgNodes n1 = children[0]->getNodes();
tgNodes n2 = children[1]->getNodes();
prism.addPair(n1[1], n2[0], "muscle seg");
tgBuildSpec spec;
spec.addBuilder("rod", new tgRodInfo(m_config.m_rod1Config));
// spec.addBuilder("rod v1", new tgRodInfo(m_config.m_rod1Config));
// spec.addBuilder("rod v2", new tgRodInfo(m_config.m_rod2Config));
spec.addBuilder("muscle", new tgLinearStringInfo(m_stringConfig));
// Create your structureInfo
tgStructureInfo structureInfo(prism, spec);
std::cout << "tgPrismaticInfo::buildModel() 7" << std::endl;
// Use the structureInfo to build our model
structureInfo.buildInto(*prismatic, world);
/* Now that the sub-structure has been created, attach it
* to the super-structure
* Very manual from here, since this is the only place we have all
* of the necessary pointers
*
// We have to delete these
std::vector<tgPair*> linkerPairs;
// "From" side:
linkerPairs.push_back(new tgPair(startNode, n1[0], tgString("anchor seg",1)));
// "To" side:
linkerPairs.push_back(new tgPair(n2[1], endNode, tgString("anchor seg",2)));
// Perhaps overkill...
// These pointers will be deleted by tgStructure
std::vector <tgRigidInfo*> allRigids(structureInfo.getAllRigids());
std::cout << "tgPrismaticInfo num rigids: " << allRigids.size() << std::endl;
allRigids.push_back(getToRigidInfo());
allRigids.push_back(getFromRigidInfo());
// We have to delete these
std::vector <tgConnectorInfo* > linkerInfo;
// Can this part be done in a loop easily?
linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[0]));
linkerInfo.push_back(new tgLinearStringInfo(m_stringConfig, *linkerPairs[1]));
for (std::size_t i = 0; i < linkerInfo.size(); i++)
{
linkerInfo[i]->chooseRigids(allRigids);
linkerInfo[i]->initConnector(world);
tgModel* m = linkerInfo[i]->createModel(world);
m->setTags(linkerInfo[i]->getTags());
if(m != 0) {
prismatic->addChild(m);
}
}
// Clean up - see if there's a way to do this with references instead?
for (std::size_t i = 0; i < linkerInfo.size(); i++)
{
delete linkerInfo[i];
}
linkerInfo.clear();
for (std::size_t i = 0; i < linkerPairs.size(); i++)
{
delete linkerPairs[i];
}
linkerPairs.clear();
/**/
std::cout << "tgPrismaticInfo::buildModel() 8" << std::endl;
//not needed?
// prismatic->setup(world);
#if(0)
// Debug printing
std::cout << "StructureInfo:" << std::endl;
std::cout << structureInfo << std::endl;
std::cout << "Model: " << std::endl;
std::cout << *prismatic << std::endl;
#endif
}
<|endoftext|> |
<commit_before>#line 2 "libsxc:Signal/Waiter.cxx"
// LICENSE/*{{{*/
/*
libsxc
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*}}}*/
// INCLUDE/*{{{*/
#include <map>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include <libsxc/Signal/Waiter.hxx>
/*}}}*/
namespace libsxc
{
namespace Signal
{
Waiter::Waiter(bool fill)/*{{{*/
: _handlers()
, _set()
, _threadId()
, _stopRequested(false)
, _running(false)
{
if (fill) {
// Fill with all signals.
if (sigfillset(&_set))
return;
} else {
// Clear the signal selection.
if (sigemptyset(&_set))
return;
}
// Publish the sigmask.
int status = pthread_sigmask(SIG_SETMASK, &_set, NULL);
if (status)
return;
}/*}}}*/
Waiter::~Waiter()/*{{{*/
{
if (_running) {
stop();
pthread_join(_threadId, NULL);
}
}/*}}}*/
void Waiter::reg(unsigned int signal, Handler &sh)/*{{{*/
{
if (_handlers.end() != _handlers.find(signal)) {
// There already is a signal handler registered for this signal.
// FIXME: throw appropriate exception
return;
}
if (_running) {
// Don't register signal handlers while running, as they would be added
// _after_ the next signal has been received.
// FIXME: throw appropriate exception
return;
}
if (sigaddset(&_set, signal))
return;
_handlers.insert(std::make_pair(signal, &sh));
int status = pthread_sigmask(SIG_SETMASK, &_set, NULL);
if (status)
return;
}/*}}}*/
void Waiter::run()/*{{{*/
{
if (_stopRequested) {
// A stop may have been requested even before the waiter is up and
// running.
return;
}
if (_handlers.empty() && !sigismember(&_set, SIGINT)) {
// We need at least one signal handler registered, or all signals set
// to ignore, so we can send it in case we want to stop the thread.
// FIXME: throw appropriate exception
return;
}
int status;
status = pthread_create(&_threadId, NULL, _wait, (void *) this);
if (status) {
// FIXME: throw exception.
return;
}
}/*}}}*/
void Waiter::join()/*{{{*/
{
if (_running)
pthread_join(_threadId, NULL);
}/*}}}*/
void Waiter::stop()/*{{{*/
{
_stopRequested = true;
if (!_running) {
// Allow this method without having the thread actually running. This
// will make the run method return immediately, as the stop is still
// requested.
return;
}
// Send a signal to the current process that will be caught by the
// running @ref wait thread and result in the thread to exit. Not using
// _threadId or raise(), as they are thread specific.
unsigned int signal;
if (_handlers.empty()) {
signal = SIGINT;
} else {
signal = _handlers.begin()->first;
}
if (-1 == kill(getpid(), signal)) {
int err = errno;
return;
}
}/*}}}*/
void *Waiter::_wait(void *rawThat)/*{{{*/
{
Waiter *that = reinterpret_cast<Waiter *>(rawThat);
that->_running = true;
int number;
int count = 0;
Handlers::iterator handler;
int status;
while (true) {
status = sigwait(&(that->_set), &number);
if (status)
break;
if (that->_stopRequested) {
// Don't call the handler as we have to exit immediately. The
// received signal is most probably the one sent by the @ref stop
// method, but this doesn't matter, and does not have to be proven,
// as we have to exit anyway without handling anything else (even the
// signals already in queue).
break;
}
handler = that->_handlers.find(number);
if (that->_handlers.end() != handler)
handler->second->handle(number);
// else: ignore.
}
that->_running = false;
return (void *) NULL;
}/*}}}*/
}
}
// Use no tabs at all; two spaces indentation; max. eighty chars per line.
// vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
<commit_msg>Fix: Include neccessary system headers<commit_after>#line 2 "libsxc:Signal/Waiter.cxx"
// LICENSE/*{{{*/
/*
libsxc
Copyright (C) 2008 Dennis Felsing, Andreas Waidler
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*}}}*/
// INCLUDE/*{{{*/
#include <map>
#include <pthread.h>
#include <signal.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#include <libsxc/Signal/Waiter.hxx>
/*}}}*/
namespace libsxc
{
namespace Signal
{
Waiter::Waiter(bool fill)/*{{{*/
: _handlers()
, _set()
, _threadId()
, _stopRequested(false)
, _running(false)
{
if (fill) {
// Fill with all signals.
if (sigfillset(&_set))
return;
} else {
// Clear the signal selection.
if (sigemptyset(&_set))
return;
}
// Publish the sigmask.
int status = pthread_sigmask(SIG_SETMASK, &_set, NULL);
if (status)
return;
}/*}}}*/
Waiter::~Waiter()/*{{{*/
{
if (_running) {
stop();
pthread_join(_threadId, NULL);
}
}/*}}}*/
void Waiter::reg(unsigned int signal, Handler &sh)/*{{{*/
{
if (_handlers.end() != _handlers.find(signal)) {
// There already is a signal handler registered for this signal.
// FIXME: throw appropriate exception
return;
}
if (_running) {
// Don't register signal handlers while running, as they would be added
// _after_ the next signal has been received.
// FIXME: throw appropriate exception
return;
}
if (sigaddset(&_set, signal))
return;
_handlers.insert(std::make_pair(signal, &sh));
int status = pthread_sigmask(SIG_SETMASK, &_set, NULL);
if (status)
return;
}/*}}}*/
void Waiter::run()/*{{{*/
{
if (_stopRequested) {
// A stop may have been requested even before the waiter is up and
// running.
return;
}
if (_handlers.empty() && !sigismember(&_set, SIGINT)) {
// We need at least one signal handler registered, or all signals set
// to ignore, so we can send it in case we want to stop the thread.
// FIXME: throw appropriate exception
return;
}
int status;
status = pthread_create(&_threadId, NULL, _wait, (void *) this);
if (status) {
// FIXME: throw exception.
return;
}
}/*}}}*/
void Waiter::join()/*{{{*/
{
if (_running)
pthread_join(_threadId, NULL);
}/*}}}*/
void Waiter::stop()/*{{{*/
{
_stopRequested = true;
if (!_running) {
// Allow this method without having the thread actually running. This
// will make the run method return immediately, as the stop is still
// requested.
return;
}
// Send a signal to the current process that will be caught by the
// running @ref wait thread and result in the thread to exit. Not using
// _threadId or raise(), as they are thread specific.
unsigned int signal;
if (_handlers.empty()) {
signal = SIGINT;
} else {
signal = _handlers.begin()->first;
}
if (-1 == kill(getpid(), signal)) {
int err = errno;
return;
}
}/*}}}*/
void *Waiter::_wait(void *rawThat)/*{{{*/
{
Waiter *that = reinterpret_cast<Waiter *>(rawThat);
that->_running = true;
int number;
int count = 0;
Handlers::iterator handler;
int status;
while (true) {
status = sigwait(&(that->_set), &number);
if (status)
break;
if (that->_stopRequested) {
// Don't call the handler as we have to exit immediately. The
// received signal is most probably the one sent by the @ref stop
// method, but this doesn't matter, and does not have to be proven,
// as we have to exit anyway without handling anything else (even the
// signals already in queue).
break;
}
handler = that->_handlers.find(number);
if (that->_handlers.end() != handler)
handler->second->handle(number);
// else: ignore.
}
that->_running = false;
return (void *) NULL;
}/*}}}*/
}
}
// Use no tabs at all; two spaces indentation; max. eighty chars per line.
// vim: et ts=2 sw=2 sts=2 tw=80 fdm=marker
<|endoftext|> |
<commit_before>
#include <libclientserver.h>
SignalHandler::SignalHandler(ISignalHandler *handler)
{
this->handler = handler;
m_loop = true;
if (sigemptyset(&m_sigs) < 0)
abort();
if (sigaddset(&m_sigs, SIGALRM) < 0)
abort();
if (sigaddset(&m_sigs, SIGCHLD) < 0)
abort();
if (sigaddset(&m_sigs, SIGHUP) < 0)
abort();
if (sigaddset(&m_sigs, SIGTERM) < 0)
abort();
if (sigaddset(&m_sigs, SIGUSR1) < 0)
abort();
if (sigaddset(&m_sigs, SIGUSR2) < 0)
abort();
if (sigaddset(&m_sigs, SIGPIPE) < 0)
abort();
if (sigprocmask(SIG_BLOCK, &m_sigs, NULL) < 0)
{
abort();
}
Thread::Start();
}
SignalHandler::~SignalHandler()
{
m_loop = false;
Thread::Signal(SIGUSR1);
Thread::Stop();
if (sigprocmask(SIG_UNBLOCK, &m_sigs, NULL) < 0)
{
abort();
}
}
void SignalHandler::Block()
{
m_mutex.Lock();
}
void SignalHandler::UnBlock()
{
m_mutex.Unlock();
}
void SignalHandler::Run()
{
while(1)
{
siginfo_t info;
if (sigwaitinfo(&m_sigs, &info) < 0)
abort();
if (m_loop == false)
break;
m_mutex.Lock();
switch(info.si_signo)
{
case SIGALRM:
handler->SigAlarm(&info);
break;
case SIGCHLD:
handler->SigChild(&info);
break;
case SIGHUP:
handler->SigHUP(&info);
break;
case SIGTERM:
handler->SigTerm(&info);
break;
case SIGUSR1:
handler->SigUser1(&info);
break;
case SIGUSR2:
handler->SigUser2(&info);
break;
case SIGPIPE:
handler->SigPipe(&info);
break;
default:
abort(); //Unknown signal
break;
}
m_mutex.Unlock();
}
}
<commit_msg>Fixed issue when debugger attached<commit_after>
#include <libclientserver.h>
SignalHandler::SignalHandler(ISignalHandler *handler)
{
this->handler = handler;
m_loop = true;
if (sigemptyset(&m_sigs) < 0)
abort();
if (sigaddset(&m_sigs, SIGALRM) < 0)
abort();
if (sigaddset(&m_sigs, SIGCHLD) < 0)
abort();
if (sigaddset(&m_sigs, SIGHUP) < 0)
abort();
if (sigaddset(&m_sigs, SIGTERM) < 0)
abort();
if (sigaddset(&m_sigs, SIGUSR1) < 0)
abort();
if (sigaddset(&m_sigs, SIGUSR2) < 0)
abort();
if (sigaddset(&m_sigs, SIGPIPE) < 0)
abort();
if (sigprocmask(SIG_BLOCK, &m_sigs, NULL) < 0)
{
abort();
}
Thread::Start();
}
SignalHandler::~SignalHandler()
{
m_loop = false;
Thread::Signal(SIGUSR1);
Thread::Stop();
if (sigprocmask(SIG_UNBLOCK, &m_sigs, NULL) < 0)
{
abort();
}
}
void SignalHandler::Block()
{
m_mutex.Lock();
}
void SignalHandler::UnBlock()
{
m_mutex.Unlock();
}
void SignalHandler::Run()
{
while(1)
{
siginfo_t info;
if (sigwaitinfo(&m_sigs, &info) < 0)
{
switch(errno)
{
case EINTR:
continue;
break;
default:
abort();
}
}
if (m_loop == false)
break;
m_mutex.Lock();
switch(info.si_signo)
{
case SIGALRM:
handler->SigAlarm(&info);
break;
case SIGCHLD:
handler->SigChild(&info);
break;
case SIGHUP:
handler->SigHUP(&info);
break;
case SIGTERM:
handler->SigTerm(&info);
break;
case SIGUSR1:
handler->SigUser1(&info);
break;
case SIGUSR2:
handler->SigUser2(&info);
break;
case SIGPIPE:
handler->SigPipe(&info);
break;
default:
abort(); //Unknown signal
break;
}
m_mutex.Unlock();
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <atomic>
#include <memory>
#include <thread>
#include <vector>
#include "types.hpp"
#include "utils/assert.hpp"
namespace opossum {
class TaskQueue;
/**
* To be executed on a separate Thread, fetches and executes tasks until the queue is empty AND the shutdown flag is set
* Ideally there should be one Worker actively doing work per CPU, but multiple might be active occasionally
*/
class Worker : public std::enable_shared_from_this<Worker>, private Noncopyable {
friend class CurrentScheduler;
public:
static std::shared_ptr<Worker> get_this_thread_worker();
Worker(const std::shared_ptr<TaskQueue>& queue, WorkerID id, CpuID cpu_id);
/**
* Unique ID of a worker. Currently not in use, but really helpful for debugging.
*/
WorkerID id() const;
std::shared_ptr<TaskQueue> queue() const;
CpuID cpu_id() const;
void start();
void join();
uint64_t num_finished_tasks() const;
void operator=(const Worker&) = delete;
void operator=(Worker&&) = delete;
protected:
void operator()();
void _work();
template <typename TaskType>
void _wait_for_tasks(const std::vector<std::shared_ptr<TaskType>>& tasks) {
auto tasks_completed = [&tasks]() {
for (auto& task : tasks) {
if (!task->is_done()) {
return false;
}
}
return true;
};
while (!tasks_completed()) {
_work();
}
}
private:
/**
* Pin a worker to a particular core.
* This does not work on non-NUMA systems, and might be addressed in the future.
*/
void _set_affinity();
std::shared_ptr<TaskQueue> _queue;
WorkerID _id;
CpuID _cpu_id;
std::thread _thread;
std::atomic<uint64_t> _num_finished_tasks{0};
};
} // namespace opossum
<commit_msg>Reverse check if tasks are completed in Worker::_wait_for_tasks(). (#1386)<commit_after>#pragma once
#include <atomic>
#include <memory>
#include <thread>
#include <vector>
#include "types.hpp"
#include "utils/assert.hpp"
namespace opossum {
class TaskQueue;
/**
* To be executed on a separate Thread, fetches and executes tasks until the queue is empty AND the shutdown flag is set
* Ideally there should be one Worker actively doing work per CPU, but multiple might be active occasionally
*/
class Worker : public std::enable_shared_from_this<Worker>, private Noncopyable {
friend class CurrentScheduler;
public:
static std::shared_ptr<Worker> get_this_thread_worker();
Worker(const std::shared_ptr<TaskQueue>& queue, WorkerID id, CpuID cpu_id);
/**
* Unique ID of a worker. Currently not in use, but really helpful for debugging.
*/
WorkerID id() const;
std::shared_ptr<TaskQueue> queue() const;
CpuID cpu_id() const;
void start();
void join();
uint64_t num_finished_tasks() const;
void operator=(const Worker&) = delete;
void operator=(Worker&&) = delete;
protected:
void operator()();
void _work();
template <typename TaskType>
void _wait_for_tasks(const std::vector<std::shared_ptr<TaskType>>& tasks) {
auto tasks_completed = [&tasks]() {
// Reversely iterate through the list of tasks, because unfinished tasks are likely at the end of the list.
for (auto it = tasks.rbegin() ; it != tasks.rend() ; ++it) {
if (!(*it)->is_done()) {
return false;
}
}
return true;
};
while (!tasks_completed()) {
_work();
}
}
private:
/**
* Pin a worker to a particular core.
* This does not work on non-NUMA systems, and might be addressed in the future.
*/
void _set_affinity();
std::shared_ptr<TaskQueue> _queue;
WorkerID _id;
CpuID _cpu_id;
std::thread _thread;
std::atomic<uint64_t> _num_finished_tasks{0};
};
} // namespace opossum
<|endoftext|> |
<commit_before>// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2020, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//************************* System Include Files ****************************
#include <sys/param.h>
#include <cstdlib> // for 'mkstemp' (not technically visible in C++)
#include <cstdio> // for 'tmpnam', 'rename'
#include <cerrno>
#include <cstdarg>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <string>
using std::string;
//*************************** User Include Files ****************************
#include "FileUtil.hpp"
#include "diagnostics.h"
#include "StrUtil.hpp"
#include "Trace.hpp"
#include <lib/support-lean/OSUtil.h>
//*************************** Forward Declarations **************************
using std::endl;
//***************************************************************************
//
//***************************************************************************
namespace FileUtil {
string
basename(const char* fName)
{
string baseFileName;
const char* lastSlash = strrchr(fName, '/');
if (lastSlash) {
// valid: "/foo" || ".../foo" AND invalid: "/" || ".../"
baseFileName = lastSlash + 1;
}
else {
// filename contains no slashes, already in short form
baseFileName = fName;
}
return baseFileName;
#if 0
// A "more C++" implementation (Gaurav)
std::string
PathFindMgr::getFileName(const std::string& path) const
{
size_t in = path.find_last_of("/");
if (in != path.npos && path.length() > 1)
return path.substr(in + 1);
return path;
}
#endif
}
string
rmSuffix(const char* fName)
{
string baseFileName = fName;
size_t pos = baseFileName.find_last_of('.');
if (pos != string::npos) {
baseFileName = baseFileName.substr(0, pos);
}
return baseFileName;
}
string
dirname(const char* fName)
{
const char* lastSlash = strrchr(fName, '/');
string pathComponent = ".";
if (lastSlash) {
pathComponent = fName;
pathComponent.resize(lastSlash - fName);
}
return pathComponent;
}
bool
fnmatch(const std::vector<std::string>& patternVec,
const char* string, int flags)
{
for (uint i = 0; i < patternVec.size(); ++i) {
const std::string& pat = patternVec[i];
bool fnd = FileUtil::fnmatch(pat, string, flags);
if (fnd) {
return true;
}
}
return false;
}
} // end of FileUtil namespace
//***************************************************************************
//
//***************************************************************************
namespace FileUtil {
bool
isReadable(const char* path)
{
struct stat sbuf;
if (stat(path, &sbuf) == 0) {
return true; // the file is readable
}
return false;
}
bool
isDir(const char* path)
{
struct stat sbuf;
if (stat(path, &sbuf) == 0) {
return (S_ISDIR(sbuf.st_mode)
/*|| S_ISLNK(sbuf.st_mode) && isDir(readlink(path))*/);
}
return false; // unknown
}
int
countChar(const char* path, char c)
{
int srcFd = open(path, O_RDONLY);
if (srcFd < 0) {
return -1;
}
int count = 0;
char buf[256];
ssize_t nRead;
while ((nRead = read(srcFd, buf, 256)) > 0) {
for (int i = 0; i < nRead; i++) {
if (buf[i] == c) count++;
}
}
return count;
}
} // end of FileUtil namespace
//***************************************************************************
//
//***************************************************************************
static void
cpy(int srcFd, int dstFd)
{
static const int bufSz = 4096;
char buf[bufSz];
ssize_t nRead;
while ((nRead = read(srcFd, buf, bufSz)) > 0) {
write(dstFd, buf, nRead);
}
}
namespace FileUtil {
void
copy(const char* dst, ...)
{
va_list srcFnmList;
va_start(srcFnmList, dst);
DIAG_MsgIf(0, "FileUtil::copy: ... -> " << dst);
int dstFd = open(dst, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dstFd < 0) {
DIAG_Throw("[FileUtil::copy] could not open destination file '"
<< dst << "' (" << strerror(errno) << ")");
}
string errorMsg;
char* srcFnm;
while ( (srcFnm = va_arg(srcFnmList, char*)) ) {
int srcFd = open(srcFnm, O_RDONLY);
if ((srcFd < 0) || (dstFd < 0)) {
errorMsg += (string("could not open '") + srcFnm + "' ("
+ strerror(errno) + ")");
}
else {
cpy(srcFd, dstFd);
close(srcFd);
}
}
va_end(srcFnmList);
close(dstFd);
if (!errorMsg.empty()) {
DIAG_Throw("[FileUtil::copy] could not open source files: " << errorMsg);
}
}
void
move(const char* dst, const char* src)
{
int ret = rename(src, dst);
if (ret != 0) {
DIAG_Throw("[FileUtil::move] '" << src << "' -> '" << dst << "'");
}
}
int
remove(const char* file)
{
return unlink(file);
}
int
mkdir(const char* dir)
{
if (!dir) {
DIAG_Throw("Invalid mkdir argument: (NULL)");
}
string pathStr = dir;
bool isAbsPath = (dir[0] == '/');
// -------------------------------------------------------
// 1. Convert path string to vector of path components
// "/p0/p1/p2/.../pn/px" ==> [p0 p1 p2 ... pn px]
// "/p0" ==> [p0]
// "p0" ==> [p0]
// "./p0" ==> [. p0]
//
// Note: we could do tokenization in place (string::find_last_of()),
// but (1) this is more elegant and (2) sytem calls and disk
// accesses will overwhelm any possible difference in performance.
// -------------------------------------------------------
std::vector<string> pathVec;
StrUtil::tokenize_char(pathStr, "/", pathVec);
DIAG_Assert(!pathVec.empty(), DIAG_UnexpectedInput);
// -------------------------------------------------------
// 2. Find 'curIdx' such that all paths before pathVec[curIdx] have
// been created.
//
// Note: Start search from the last path component, assuming that in
// the common case, intermediate directories are already created.
//
// Note: Could make this a binary search, but it would likely have
// insignificant effects.
// -------------------------------------------------------
size_t begIdx = 0;
size_t endIdx = pathVec.size() - 1;
size_t curIdx = endIdx;
for ( ; curIdx >= begIdx; --curIdx) {
string x = StrUtil::join(pathVec, "/", 0, curIdx + 1);
if (isAbsPath) {
x = "/" + x;
}
if (isDir(x)) {
break; // FIXME: double check: what if this is a symlink?
}
}
curIdx++;
// -------------------------------------------------------
// 3. Build directories from pathVec[curIdx ... endIdx]
// -------------------------------------------------------
mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
for ( ; curIdx <= endIdx; ++curIdx) {
string x = StrUtil::join(pathVec, "/", 0, curIdx + 1);
if (isAbsPath) {
x = "/" + x;
}
int ret = ::mkdir(x.c_str(), mode);
if (ret != 0) {
DIAG_Throw("[FileUtil::mkdir] '" << pathStr << "': Could not mkdir '"
<< x << "' (" << strerror(errno) << ")");
}
}
return 0;
}
std::pair<string, bool>
mkdirUnique(const char* dirnm)
{
string dirnm_new = dirnm;
bool is_done = false;
mode_t mkmode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
int ret = ::mkdir(dirnm, mkmode);
if (ret != 0) {
if (errno == EEXIST) {
std::vector<string> dirnmVec;
// qualifier 1: jobid
const char* jobid_cstr = OSUtil_jobid();
if (jobid_cstr) {
string dirnm1 = string(dirnm) + "-" + string(jobid_cstr);
dirnmVec.push_back(dirnm1);
}
// qualifier 2: pid
uint pid = OSUtil_pid();
string pid_str = StrUtil::toStr(pid);
string dirnm2 = string(dirnm) + "-" + pid_str;
dirnmVec.push_back(dirnm2);
// attempt to create alternative directories
for (uint i = 0; i < dirnmVec.size(); ++i) {
dirnm_new = dirnmVec[i];
DIAG_Msg(1, "Directory '" << dirnm << "' already exists. Trying '" << dirnm_new << "'");
ret = ::mkdir(dirnm_new.c_str(), mkmode);
if (ret == 0) {
is_done = true;
break;
}
}
if (is_done) {
DIAG_Msg(1, "Created directory: " << dirnm_new);
}
else {
DIAG_Die("Could not create an alternative to directory " << dirnm);
}
}
else {
DIAG_Die("Could not create database directory " << dirnm);
}
}
return make_pair(dirnm_new, is_done);
}
const char*
tmpname()
{
// below is a hack to replace the deprecated tmpnam which g++ 3.2.2 will
// no longer allow. the mkstemp routine, which is touted as the replacement
// for tmpnam, provides a file descriptor as a return value. there is
// unfortunately no way to interface this with the ofstream class constructor
// which requires a filename. thus, a hack is born ...
// John Mellor-Crummey 5/7/2003
// eraxxon: GNU is right that 'tmpnam' can be dangerous, but
// 'mkstemp' is not strictly part of C++! We could create an
// interface to 'mkstemp' within a C file, but this is getting
// cumbersome... and 'tmpnam' is not quite a WMD.
#ifdef __GNUC__
static char tmpfilename[MAXPATHLEN];
// creating a unique temp name with the new mkstemp interface now
// requires opening, closing, and deleting a file when all we want
// is the filename. sigh ...
strcpy(tmpfilename,"/tmp/hpcviewtmpXXXXXX");
close(mkstemp(tmpfilename));
unlink(tmpfilename);
return tmpfilename;
#else
return tmpnam(NULL);
#endif
}
} // end of FileUtil namespace
<commit_msg>changed FileUtil::copy fatal error into a warning<commit_after>// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// --------------------------------------------------------------------------
// Part of HPCToolkit (hpctoolkit.org)
//
// Information about sources of support for research and development of
// HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'.
// --------------------------------------------------------------------------
//
// Copyright ((c)) 2002-2020, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//************************* System Include Files ****************************
#include <sys/param.h>
#include <cstdlib> // for 'mkstemp' (not technically visible in C++)
#include <cstdio> // for 'tmpnam', 'rename'
#include <cerrno>
#include <cstdarg>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <string>
using std::string;
//*************************** User Include Files ****************************
#include "FileUtil.hpp"
#include "diagnostics.h"
#include "StrUtil.hpp"
#include "Trace.hpp"
#include <lib/support-lean/OSUtil.h>
//*************************** Forward Declarations **************************
using std::endl;
//***************************************************************************
//
//***************************************************************************
namespace FileUtil {
string
basename(const char* fName)
{
string baseFileName;
const char* lastSlash = strrchr(fName, '/');
if (lastSlash) {
// valid: "/foo" || ".../foo" AND invalid: "/" || ".../"
baseFileName = lastSlash + 1;
}
else {
// filename contains no slashes, already in short form
baseFileName = fName;
}
return baseFileName;
#if 0
// A "more C++" implementation (Gaurav)
std::string
PathFindMgr::getFileName(const std::string& path) const
{
size_t in = path.find_last_of("/");
if (in != path.npos && path.length() > 1)
return path.substr(in + 1);
return path;
}
#endif
}
string
rmSuffix(const char* fName)
{
string baseFileName = fName;
size_t pos = baseFileName.find_last_of('.');
if (pos != string::npos) {
baseFileName = baseFileName.substr(0, pos);
}
return baseFileName;
}
string
dirname(const char* fName)
{
const char* lastSlash = strrchr(fName, '/');
string pathComponent = ".";
if (lastSlash) {
pathComponent = fName;
pathComponent.resize(lastSlash - fName);
}
return pathComponent;
}
bool
fnmatch(const std::vector<std::string>& patternVec,
const char* string, int flags)
{
for (uint i = 0; i < patternVec.size(); ++i) {
const std::string& pat = patternVec[i];
bool fnd = FileUtil::fnmatch(pat, string, flags);
if (fnd) {
return true;
}
}
return false;
}
} // end of FileUtil namespace
//***************************************************************************
//
//***************************************************************************
namespace FileUtil {
bool
isReadable(const char* path)
{
struct stat sbuf;
if (stat(path, &sbuf) == 0) {
return true; // the file is readable
}
return false;
}
bool
isDir(const char* path)
{
struct stat sbuf;
if (stat(path, &sbuf) == 0) {
return (S_ISDIR(sbuf.st_mode)
/*|| S_ISLNK(sbuf.st_mode) && isDir(readlink(path))*/);
}
return false; // unknown
}
int
countChar(const char* path, char c)
{
int srcFd = open(path, O_RDONLY);
if (srcFd < 0) {
return -1;
}
int count = 0;
char buf[256];
ssize_t nRead;
while ((nRead = read(srcFd, buf, 256)) > 0) {
for (int i = 0; i < nRead; i++) {
if (buf[i] == c) count++;
}
}
return count;
}
} // end of FileUtil namespace
//***************************************************************************
//
//***************************************************************************
static void
cpy(int srcFd, int dstFd)
{
static const int bufSz = 4096;
char buf[bufSz];
ssize_t nRead;
while ((nRead = read(srcFd, buf, bufSz)) > 0) {
write(dstFd, buf, nRead);
}
}
namespace FileUtil {
void
copy(const char* dst, ...)
{
va_list srcFnmList;
va_start(srcFnmList, dst);
DIAG_MsgIf(0, "FileUtil::copy: ... -> " << dst);
int dstFd = open(dst, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dstFd < 0) {
DIAG_Throw("Unable to write file in hpctoolkit database '"
<< dst << "' (" << strerror(errno) << ")");
}
string errorMsg;
char* srcFnm;
while ( (srcFnm = va_arg(srcFnmList, char*)) ) {
int srcFd = open(srcFnm, O_RDONLY);
if ((srcFd < 0) || (dstFd < 0)) {
errorMsg += (string("unable to open '") + srcFnm + "' ("
+ strerror(errno) + ")");
}
else {
cpy(srcFd, dstFd);
close(srcFd);
}
}
va_end(srcFnmList);
close(dstFd);
if (!errorMsg.empty()) {
DIAG_Msg(1, "Unable to copy file into hpctoolkit database: " <<
errorMsg);
}
}
void
move(const char* dst, const char* src)
{
int ret = rename(src, dst);
if (ret != 0) {
DIAG_Throw("[FileUtil::move] '" << src << "' -> '" << dst << "'");
}
}
int
remove(const char* file)
{
return unlink(file);
}
int
mkdir(const char* dir)
{
if (!dir) {
DIAG_Throw("Invalid mkdir argument: (NULL)");
}
string pathStr = dir;
bool isAbsPath = (dir[0] == '/');
// -------------------------------------------------------
// 1. Convert path string to vector of path components
// "/p0/p1/p2/.../pn/px" ==> [p0 p1 p2 ... pn px]
// "/p0" ==> [p0]
// "p0" ==> [p0]
// "./p0" ==> [. p0]
//
// Note: we could do tokenization in place (string::find_last_of()),
// but (1) this is more elegant and (2) sytem calls and disk
// accesses will overwhelm any possible difference in performance.
// -------------------------------------------------------
std::vector<string> pathVec;
StrUtil::tokenize_char(pathStr, "/", pathVec);
DIAG_Assert(!pathVec.empty(), DIAG_UnexpectedInput);
// -------------------------------------------------------
// 2. Find 'curIdx' such that all paths before pathVec[curIdx] have
// been created.
//
// Note: Start search from the last path component, assuming that in
// the common case, intermediate directories are already created.
//
// Note: Could make this a binary search, but it would likely have
// insignificant effects.
// -------------------------------------------------------
size_t begIdx = 0;
size_t endIdx = pathVec.size() - 1;
size_t curIdx = endIdx;
for ( ; curIdx >= begIdx; --curIdx) {
string x = StrUtil::join(pathVec, "/", 0, curIdx + 1);
if (isAbsPath) {
x = "/" + x;
}
if (isDir(x)) {
break; // FIXME: double check: what if this is a symlink?
}
}
curIdx++;
// -------------------------------------------------------
// 3. Build directories from pathVec[curIdx ... endIdx]
// -------------------------------------------------------
mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
for ( ; curIdx <= endIdx; ++curIdx) {
string x = StrUtil::join(pathVec, "/", 0, curIdx + 1);
if (isAbsPath) {
x = "/" + x;
}
int ret = ::mkdir(x.c_str(), mode);
if (ret != 0) {
DIAG_Throw("[FileUtil::mkdir] '" << pathStr << "': Could not mkdir '"
<< x << "' (" << strerror(errno) << ")");
}
}
return 0;
}
std::pair<string, bool>
mkdirUnique(const char* dirnm)
{
string dirnm_new = dirnm;
bool is_done = false;
mode_t mkmode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
int ret = ::mkdir(dirnm, mkmode);
if (ret != 0) {
if (errno == EEXIST) {
std::vector<string> dirnmVec;
// qualifier 1: jobid
const char* jobid_cstr = OSUtil_jobid();
if (jobid_cstr) {
string dirnm1 = string(dirnm) + "-" + string(jobid_cstr);
dirnmVec.push_back(dirnm1);
}
// qualifier 2: pid
uint pid = OSUtil_pid();
string pid_str = StrUtil::toStr(pid);
string dirnm2 = string(dirnm) + "-" + pid_str;
dirnmVec.push_back(dirnm2);
// attempt to create alternative directories
for (uint i = 0; i < dirnmVec.size(); ++i) {
dirnm_new = dirnmVec[i];
DIAG_Msg(1, "Directory '" << dirnm << "' already exists. Trying '" << dirnm_new << "'");
ret = ::mkdir(dirnm_new.c_str(), mkmode);
if (ret == 0) {
is_done = true;
break;
}
}
if (is_done) {
DIAG_Msg(1, "Created directory: " << dirnm_new);
}
else {
DIAG_Die("Could not create an alternative to directory " << dirnm);
}
}
else {
DIAG_Die("Could not create database directory " << dirnm);
}
}
return make_pair(dirnm_new, is_done);
}
const char*
tmpname()
{
// below is a hack to replace the deprecated tmpnam which g++ 3.2.2 will
// no longer allow. the mkstemp routine, which is touted as the replacement
// for tmpnam, provides a file descriptor as a return value. there is
// unfortunately no way to interface this with the ofstream class constructor
// which requires a filename. thus, a hack is born ...
// John Mellor-Crummey 5/7/2003
// eraxxon: GNU is right that 'tmpnam' can be dangerous, but
// 'mkstemp' is not strictly part of C++! We could create an
// interface to 'mkstemp' within a C file, but this is getting
// cumbersome... and 'tmpnam' is not quite a WMD.
#ifdef __GNUC__
static char tmpfilename[MAXPATHLEN];
// creating a unique temp name with the new mkstemp interface now
// requires opening, closing, and deleting a file when all we want
// is the filename. sigh ...
strcpy(tmpfilename,"/tmp/hpcviewtmpXXXXXX");
close(mkstemp(tmpfilename));
unlink(tmpfilename);
return tmpfilename;
#else
return tmpnam(NULL);
#endif
}
} // end of FileUtil namespace
<|endoftext|> |
<commit_before>// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// -----------------------------------
// Part of HPCToolkit (hpctoolkit.org)
// -----------------------------------
//
// Copyright ((c)) 2002-2010, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//************************* System Include Files ****************************
#include <sys/param.h>
#include <cstdlib> // for 'mkstemp' (not technically visible in C++)
#include <cstdio> // for 'tmpnam', 'rename'
#include <cerrno>
#include <cstdarg>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <string>
using std::string;
//*************************** User Include Files ****************************
#include "FileUtil.hpp"
#include "diagnostics.h"
#include "StrUtil.hpp"
#include "Trace.hpp"
//*************************** Forward Declarations **************************
using std::endl;
//***************************************************************************
//
//***************************************************************************
namespace FileUtil {
string
basename(const char* fName)
{
string baseFileName;
const char* lastSlash = strrchr(fName, '/');
if (lastSlash) {
// valid: "/foo" || ".../foo" AND invalid: "/" || ".../"
baseFileName = lastSlash + 1;
}
else {
// filename contains no slashes, already in short form
baseFileName = fName;
}
return baseFileName;
#if 0
// A "more C++" implementation (Gaurav)
std::string
PathFindMgr::getFileName(const std::string& path) const
{
size_t in = path.find_last_of("/");
if (in != path.npos && path.length() > 1)
return path.substr(in + 1);
return path;
}
#endif
}
string
rmSuffix(const char* fName)
{
string baseFileName = fName;
size_t pos = baseFileName.find_last_of('.');
if (pos != string::npos) {
baseFileName = baseFileName.substr(0, pos);
}
return baseFileName;
}
string
dirname(const char* fName)
{
const char* lastSlash = strrchr(fName, '/');
string pathComponent = ".";
if (lastSlash) {
pathComponent = fName;
pathComponent.resize(lastSlash - fName);
}
return pathComponent;
}
bool
fnmatch(const std::vector<std::string>& patternVec,
const char* string, int flags)
{
for (uint i = 0; i < patternVec.size(); ++i) {
const std::string& pat = patternVec[i];
bool fnd = FileUtil::fnmatch(pat, string, flags);
if (fnd) {
return true;
}
}
return false;
}
} // end of FileUtil namespace
//***************************************************************************
//
//***************************************************************************
namespace FileUtil {
bool
isReadable(const char* path)
{
struct stat sbuf;
if (stat(path, &sbuf) == 0) {
return true; // the file is readable
}
return false;
}
bool
isDir(const char* path)
{
struct stat sbuf;
if (stat(path, &sbuf) == 0) {
return (S_ISDIR(sbuf.st_mode)
/*|| S_ISLNK(sbuf.st_mode) && isDir(readlink(path))*/);
}
return false; // unknown
}
int
countChar(const char* path, char c)
{
int srcFd = open(path, O_RDONLY);
if (srcFd < 0) {
return -1;
}
int count = 0;
char buf[256];
ssize_t nRead;
while ((nRead = read(srcFd, buf, 256)) > 0) {
for (int i = 0; i < nRead; i++) {
if (buf[i] == c) count++;
}
}
return count;
}
} // end of FileUtil namespace
//***************************************************************************
//
//***************************************************************************
static void
cpy(int srcFd, int dstFd)
{
static const int bufSz = 4096;
char buf[bufSz];
ssize_t nRead;
while ((nRead = read(srcFd, buf, bufSz)) > 0) {
write(dstFd, buf, nRead);
}
}
namespace FileUtil {
void
copy(const char* dst, ...)
{
va_list srcFnmList;
va_start(srcFnmList, dst);
DIAG_MsgIf(0, "FileUtil::copy: ... -> " << dst);
int dstFd = open(dst, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dstFd < 0) {
DIAG_Throw("could not open destination '" << dst << "' ("
<< strerror(errno) << ")");
}
string errorMsg;
char* srcFnm;
while ( (srcFnm = va_arg(srcFnmList, char*)) ) {
int srcFd = open(srcFnm, O_RDONLY);
if ((srcFd < 0) || (dstFd < 0)) {
errorMsg += (string("could not open '") + srcFnm + "' ("
+ strerror(errno) + ")");
}
else {
cpy(srcFd, dstFd);
close(srcFd);
}
}
va_end(srcFnmList);
close(dstFd);
if (!errorMsg.empty()) {
DIAG_Throw("could not open source files: " << errorMsg);
}
}
void
move(const char* dst, const char* src)
{
int ret = rename(src, dst);
if (ret != 0) {
DIAG_Throw("moving '" << src << "' -> '" << dst << "'");
}
}
int
remove(const char* file)
{
return unlink(file);
}
int
mkdir(const char* dir)
{
if (!dir) {
DIAG_Throw("Invalid mkdir argument: (NULL)");
}
string pathStr = dir;
bool isAbsPath = (dir[0] == '/');
// -------------------------------------------------------
// 1. Convert path string to vector of path components
// "/p0/p1/p2/.../pn/px" ==> [p0 p1 p2 ... pn px]
// "/p0" ==> [p0]
// "p0" ==> [p0]
// "./p0" ==> [. p0]
//
// Note: we could do tokenization in place (string::find_last_of()),
// but (1) this is more elegant and (2) sytem calls and disk
// accesses will overwhelm any possible difference in performance.
// -------------------------------------------------------
std::vector<string> pathVec;
StrUtil::tokenize_char(pathStr, "/", pathVec);
DIAG_Assert(!pathVec.empty(), DIAG_UnexpectedInput);
// -------------------------------------------------------
// 2. Find curIdx such that all paths before pathVec[curIdx] have
// been created.
//
// Note: Start search from the last path component, assuming that in
// the common case, intermediate directories are already created.
// -------------------------------------------------------
size_t begIdx = 0;
size_t endIdx = pathVec.size() - 1;
size_t curIdx = endIdx;
for ( ; curIdx >= begIdx; --curIdx) {
string x = StrUtil::join(pathVec, "/", 0, curIdx + 1);
if (isAbsPath) {
x = "/" + x;
}
if (isDir(x)) {
break; // FIXME: double check: what if this is a symlink?
}
}
curIdx++;
// -------------------------------------------------------
// 3. Build directories from pathVec[curIdx ... endIdx]
// -------------------------------------------------------
mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
for ( ; curIdx <= endIdx; ++curIdx) {
string x = StrUtil::join(pathVec, "/", 0, curIdx + 1);
if (isAbsPath) {
x = "/" + x;
}
int ret = ::mkdir(x.c_str(), mode);
if (ret != 0) {
DIAG_Throw("While mkdir-ing '" << pathStr << "': Could not mkdir '"
<< x << "' (" << strerror(errno) << ")");
}
}
return 0;
}
std::pair<string, bool>
mkdirUnique(const char* dirnm)
{
string dirnm_new = dirnm;
bool is_done = false;
mode_t mkmode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
int ret = ::mkdir(dirnm, mkmode);
if (ret == -1) {
if (errno == EEXIST) {
// attempt to create dirnm+pid;
pid_t pid = getpid();
string pid_str = StrUtil::toStr(pid);
dirnm_new = dirnm_new + "-" + pid_str;
DIAG_Msg(1, "Directory '" << dirnm << "' already exists. Trying " << dirnm_new);
ret = ::mkdir(dirnm_new.c_str(), mkmode);
if (ret == -1) {
DIAG_Die("Could not create alternate directory " << dirnm_new);
}
else {
DIAG_Msg(1, "Created directory: " << dirnm_new);
is_done = true;
}
}
else {
DIAG_Die("Could not create database directory " << dirnm);
}
}
return make_pair(dirnm_new, is_done);
}
const char*
tmpname()
{
// below is a hack to replace the deprecated tmpnam which g++ 3.2.2 will
// no longer allow. the mkstemp routine, which is touted as the replacement
// for tmpnam, provides a file descriptor as a return value. there is
// unfortunately no way to interface this with the ofstream class constructor
// which requires a filename. thus, a hack is born ...
// John Mellor-Crummey 5/7/2003
// eraxxon: GNU is right that 'tmpnam' can be dangerous, but
// 'mkstemp' is not strictly part of C++! We could create an
// interface to 'mkstemp' within a C file, but this is getting
// cumbersome... and 'tmpnam' is not quite a WMD.
#ifdef __GNUC__
static char tmpfilename[MAXPATHLEN];
// creating a unique temp name with the new mkstemp interface now
// requires opening, closing, and deleting a file when all we want
// is the filename. sigh ...
strcpy(tmpfilename,"/tmp/hpcviewtmpXXXXXX");
close(mkstemp(tmpfilename));
unlink(tmpfilename);
return tmpfilename;
#else
return tmpnam(NULL);
#endif
}
} // end of FileUtil namespace
<commit_msg>FileUtil::mkdir(): minor update to comments.<commit_after>// -*-Mode: C++;-*-
// * BeginRiceCopyright *****************************************************
//
// $HeadURL$
// $Id$
//
// -----------------------------------
// Part of HPCToolkit (hpctoolkit.org)
// -----------------------------------
//
// Copyright ((c)) 2002-2010, Rice University
// 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 Rice University (RICE) 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 RICE 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 RICE 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.
//
// ******************************************************* EndRiceCopyright *
//***************************************************************************
//************************* System Include Files ****************************
#include <sys/param.h>
#include <cstdlib> // for 'mkstemp' (not technically visible in C++)
#include <cstdio> // for 'tmpnam', 'rename'
#include <cerrno>
#include <cstdarg>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <string>
using std::string;
//*************************** User Include Files ****************************
#include "FileUtil.hpp"
#include "diagnostics.h"
#include "StrUtil.hpp"
#include "Trace.hpp"
//*************************** Forward Declarations **************************
using std::endl;
//***************************************************************************
//
//***************************************************************************
namespace FileUtil {
string
basename(const char* fName)
{
string baseFileName;
const char* lastSlash = strrchr(fName, '/');
if (lastSlash) {
// valid: "/foo" || ".../foo" AND invalid: "/" || ".../"
baseFileName = lastSlash + 1;
}
else {
// filename contains no slashes, already in short form
baseFileName = fName;
}
return baseFileName;
#if 0
// A "more C++" implementation (Gaurav)
std::string
PathFindMgr::getFileName(const std::string& path) const
{
size_t in = path.find_last_of("/");
if (in != path.npos && path.length() > 1)
return path.substr(in + 1);
return path;
}
#endif
}
string
rmSuffix(const char* fName)
{
string baseFileName = fName;
size_t pos = baseFileName.find_last_of('.');
if (pos != string::npos) {
baseFileName = baseFileName.substr(0, pos);
}
return baseFileName;
}
string
dirname(const char* fName)
{
const char* lastSlash = strrchr(fName, '/');
string pathComponent = ".";
if (lastSlash) {
pathComponent = fName;
pathComponent.resize(lastSlash - fName);
}
return pathComponent;
}
bool
fnmatch(const std::vector<std::string>& patternVec,
const char* string, int flags)
{
for (uint i = 0; i < patternVec.size(); ++i) {
const std::string& pat = patternVec[i];
bool fnd = FileUtil::fnmatch(pat, string, flags);
if (fnd) {
return true;
}
}
return false;
}
} // end of FileUtil namespace
//***************************************************************************
//
//***************************************************************************
namespace FileUtil {
bool
isReadable(const char* path)
{
struct stat sbuf;
if (stat(path, &sbuf) == 0) {
return true; // the file is readable
}
return false;
}
bool
isDir(const char* path)
{
struct stat sbuf;
if (stat(path, &sbuf) == 0) {
return (S_ISDIR(sbuf.st_mode)
/*|| S_ISLNK(sbuf.st_mode) && isDir(readlink(path))*/);
}
return false; // unknown
}
int
countChar(const char* path, char c)
{
int srcFd = open(path, O_RDONLY);
if (srcFd < 0) {
return -1;
}
int count = 0;
char buf[256];
ssize_t nRead;
while ((nRead = read(srcFd, buf, 256)) > 0) {
for (int i = 0; i < nRead; i++) {
if (buf[i] == c) count++;
}
}
return count;
}
} // end of FileUtil namespace
//***************************************************************************
//
//***************************************************************************
static void
cpy(int srcFd, int dstFd)
{
static const int bufSz = 4096;
char buf[bufSz];
ssize_t nRead;
while ((nRead = read(srcFd, buf, bufSz)) > 0) {
write(dstFd, buf, nRead);
}
}
namespace FileUtil {
void
copy(const char* dst, ...)
{
va_list srcFnmList;
va_start(srcFnmList, dst);
DIAG_MsgIf(0, "FileUtil::copy: ... -> " << dst);
int dstFd = open(dst, O_WRONLY | O_CREAT | O_TRUNC,
S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (dstFd < 0) {
DIAG_Throw("could not open destination '" << dst << "' ("
<< strerror(errno) << ")");
}
string errorMsg;
char* srcFnm;
while ( (srcFnm = va_arg(srcFnmList, char*)) ) {
int srcFd = open(srcFnm, O_RDONLY);
if ((srcFd < 0) || (dstFd < 0)) {
errorMsg += (string("could not open '") + srcFnm + "' ("
+ strerror(errno) + ")");
}
else {
cpy(srcFd, dstFd);
close(srcFd);
}
}
va_end(srcFnmList);
close(dstFd);
if (!errorMsg.empty()) {
DIAG_Throw("could not open source files: " << errorMsg);
}
}
void
move(const char* dst, const char* src)
{
int ret = rename(src, dst);
if (ret != 0) {
DIAG_Throw("moving '" << src << "' -> '" << dst << "'");
}
}
int
remove(const char* file)
{
return unlink(file);
}
int
mkdir(const char* dir)
{
if (!dir) {
DIAG_Throw("Invalid mkdir argument: (NULL)");
}
string pathStr = dir;
bool isAbsPath = (dir[0] == '/');
// -------------------------------------------------------
// 1. Convert path string to vector of path components
// "/p0/p1/p2/.../pn/px" ==> [p0 p1 p2 ... pn px]
// "/p0" ==> [p0]
// "p0" ==> [p0]
// "./p0" ==> [. p0]
//
// Note: we could do tokenization in place (string::find_last_of()),
// but (1) this is more elegant and (2) sytem calls and disk
// accesses will overwhelm any possible difference in performance.
// -------------------------------------------------------
std::vector<string> pathVec;
StrUtil::tokenize_char(pathStr, "/", pathVec);
DIAG_Assert(!pathVec.empty(), DIAG_UnexpectedInput);
// -------------------------------------------------------
// 2. Find 'curIdx' such that all paths before pathVec[curIdx] have
// been created.
//
// Note: Start search from the last path component, assuming that in
// the common case, intermediate directories are already created.
//
// Note: Could make this a binary search, but it would likely have
// insignificant effects.
// -------------------------------------------------------
size_t begIdx = 0;
size_t endIdx = pathVec.size() - 1;
size_t curIdx = endIdx;
for ( ; curIdx >= begIdx; --curIdx) {
string x = StrUtil::join(pathVec, "/", 0, curIdx + 1);
if (isAbsPath) {
x = "/" + x;
}
if (isDir(x)) {
break; // FIXME: double check: what if this is a symlink?
}
}
curIdx++;
// -------------------------------------------------------
// 3. Build directories from pathVec[curIdx ... endIdx]
// -------------------------------------------------------
mode_t mode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
for ( ; curIdx <= endIdx; ++curIdx) {
string x = StrUtil::join(pathVec, "/", 0, curIdx + 1);
if (isAbsPath) {
x = "/" + x;
}
int ret = ::mkdir(x.c_str(), mode);
if (ret != 0) {
DIAG_Throw("While mkdir-ing '" << pathStr << "': Could not mkdir '"
<< x << "' (" << strerror(errno) << ")");
}
}
return 0;
}
std::pair<string, bool>
mkdirUnique(const char* dirnm)
{
string dirnm_new = dirnm;
bool is_done = false;
mode_t mkmode = S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH;
int ret = ::mkdir(dirnm, mkmode);
if (ret == -1) {
if (errno == EEXIST) {
// attempt to create dirnm+pid;
pid_t pid = getpid();
string pid_str = StrUtil::toStr(pid);
dirnm_new = dirnm_new + "-" + pid_str;
DIAG_Msg(1, "Directory '" << dirnm << "' already exists. Trying " << dirnm_new);
ret = ::mkdir(dirnm_new.c_str(), mkmode);
if (ret == -1) {
DIAG_Die("Could not create alternate directory " << dirnm_new);
}
else {
DIAG_Msg(1, "Created directory: " << dirnm_new);
is_done = true;
}
}
else {
DIAG_Die("Could not create database directory " << dirnm);
}
}
return make_pair(dirnm_new, is_done);
}
const char*
tmpname()
{
// below is a hack to replace the deprecated tmpnam which g++ 3.2.2 will
// no longer allow. the mkstemp routine, which is touted as the replacement
// for tmpnam, provides a file descriptor as a return value. there is
// unfortunately no way to interface this with the ofstream class constructor
// which requires a filename. thus, a hack is born ...
// John Mellor-Crummey 5/7/2003
// eraxxon: GNU is right that 'tmpnam' can be dangerous, but
// 'mkstemp' is not strictly part of C++! We could create an
// interface to 'mkstemp' within a C file, but this is getting
// cumbersome... and 'tmpnam' is not quite a WMD.
#ifdef __GNUC__
static char tmpfilename[MAXPATHLEN];
// creating a unique temp name with the new mkstemp interface now
// requires opening, closing, and deleting a file when all we want
// is the filename. sigh ...
strcpy(tmpfilename,"/tmp/hpcviewtmpXXXXXX");
close(mkstemp(tmpfilename));
unlink(tmpfilename);
return tmpfilename;
#else
return tmpnam(NULL);
#endif
}
} // end of FileUtil namespace
<|endoftext|> |
<commit_before>/*
http://portaudio.com/docs/v19-doxydocs/api_overview.html
*/
/* BEGIN Setup */
#include "portaudio.h"
#include "pa_asio.h"
#include <nan.h>
using namespace Nan;
using String = v8::String;
using Number = v8::Number;
using Object = v8::Object;
using Value = v8::Value;
using Value = v8::Value;
using LocalString = v8::Local<String>;
using LocalNumber = v8::Local<Number>;
using LocalObject = v8::Local<Object>;
using LocalValue = v8::Local<Value>;
using MaybeLocalValue = v8::MaybeLocal<Value>;
/* BEGIN Helpers */
int LocalizeInt (MaybeLocalValue lvIn) {
return lvIn.ToLocalChecked()->Uint32Value();
}
/* BEGIN Initialization, termination, and utility */
NAN_METHOD(initialize) {
PaError err = Pa_Initialize();
if (err != paNoError) {
ThrowError(Pa_GetErrorText(err));
}
}
NAN_METHOD(terminate) {
PaError err = Pa_Terminate();
if (err != paNoError) {
ThrowError(Pa_GetErrorText(err));
}
}
NAN_METHOD(getVersion) {
info.GetReturnValue().Set(Pa_GetVersion());
}
/* BEGIN Host APIs */
NAN_METHOD(getHostApiCount) {
info.GetReturnValue().Set(Pa_GetHostApiCount());
}
NAN_METHOD(getDefaultHostApi) {
info.GetReturnValue().Set(Pa_GetDefaultHostApi());
}
NAN_METHOD(getHostApiInfo) {
HandleScope scope;
int api = info[0].IsEmpty() ? Pa_GetDefaultHostApi() : info[0]->Uint32Value();
const PaHostApiInfo* hai = Pa_GetHostApiInfo(api);
LocalObject obj = New<Object>();
LocalString haiIndex = New("apiIndex").ToLocalChecked();
LocalString haiType = New("type").ToLocalChecked();
LocalString haiName = New("name").ToLocalChecked();
LocalString haiDefC = New("deviceCount").ToLocalChecked();
LocalString haiDefIn = New("defaultInputDevice").ToLocalChecked();
LocalString haiDefOut = New("defaultOutputDevice").ToLocalChecked();
obj->Set(haiIndex, New<Number>(api));
obj->Set(haiType, New<Number>(hai->type));
obj->Set(haiName, New<String>(hai->name).ToLocalChecked());
obj->Set(haiDefC, New<Number>(hai->deviceCount));
obj->Set(haiDefIn, New<Number>(hai->defaultInputDevice));
obj->Set(haiDefOut, New<Number>(hai->defaultOutputDevice));
info.GetReturnValue().Set(obj);
}
/* BEGIN Device APIs */
NAN_METHOD(getDeviceCount) {
info.GetReturnValue().Set(Pa_GetDeviceCount());
}
NAN_METHOD(getDefaultInputDevice) {
info.GetReturnValue().Set(Pa_GetDefaultInputDevice());
}
NAN_METHOD(getDefaultOutputDevice) {
info.GetReturnValue().Set(Pa_GetDefaultOutputDevice());
}
NAN_METHOD(getDeviceInfo) {
HandleScope scope;
int dvc = info[0].IsEmpty()
? Pa_GetDefaultInputDevice()
: info[0]->Uint32Value();
const PaDeviceInfo* di = Pa_GetDeviceInfo(dvc);
LocalObject obj = New<Object>();
LocalString diIndex = New("deviceIndex").ToLocalChecked();
LocalString diHost = New("hostApi").ToLocalChecked();
LocalString diName = New("name").ToLocalChecked();
LocalString diMaxI = New("maxInputChannels").ToLocalChecked();
LocalString diMaxO = New("maxOutputChannels").ToLocalChecked();
LocalString diDefLIL = New("defaultLowInputLatency").ToLocalChecked();
LocalString diDefLOL = New("defaultLowOutputLatency").ToLocalChecked();
LocalString diDefHIL = New("defaultHighInputLatency").ToLocalChecked();
LocalString diDefHOL = New("defaultHighOutputLatency").ToLocalChecked();
LocalString diDefSR = New("defaultSampleRate").ToLocalChecked();
obj->Set(diIndex, New<Number>(dvc));
obj->Set(diHost, New<Number>(di->hostApi));
obj->Set(diName, New<String>(di->name).ToLocalChecked());
obj->Set(diMaxI, New<Number>(di->maxInputChannels));
obj->Set(diMaxO, New<Number>(di->maxOutputChannels));
obj->Set(diDefLIL, New<Number>(di->defaultLowInputLatency));
obj->Set(diDefLOL, New<Number>(di->defaultLowOutputLatency));
obj->Set(diDefHIL, New<Number>(di->defaultHighInputLatency));
obj->Set(diDefHOL, New<Number>(di->defaultHighOutputLatency));
obj->Set(diDefSR, New<Number>(di->defaultSampleRate));
info.GetReturnValue().Set(obj);
}
/* BEGIN Stream APIs */
NAN_METHOD(openStream) {
HandleScope scope;
LocalObject obj = info[0]->ToObject();
LocalString input = New("input").ToLocalChecked();
LocalString output = New("output").ToLocalChecked();
LocalObject objInput = Get(obj, input).ToLocalChecked()->ToObject();
LocalObject objOutput = Get(obj, output).ToLocalChecked()->ToObject();
LocalString device = New("device").ToLocalChecked();
LocalString channelCount = New("channelCount").ToLocalChecked();
LocalString sampleFormat = New("sampleFormat").ToLocalChecked();
LocalString suggestedLatency = New("suggestedLatency").ToLocalChecked();
PaStreamParameters paramsIn = {
static_cast<PaDeviceIndex>(LocalizeInt(Get(objInput, device))),
static_cast<int>(LocalizeInt(Get(objInput, channelCount))),
static_cast<PaSampleFormat>(LocalizeInt(Get(objInput, sampleFormat))),
static_cast<PaTime>(LocalizeInt(Get(objInput, suggestedLatency))),
NULL
};
PaStreamParameters paramsOut = {
static_cast<PaDeviceIndex>(LocalizeInt(Get(objOutput, device))),
static_cast<int>(LocalizeInt(Get(objOutput, channelCount))),
static_cast<PaSampleFormat>(LocalizeInt(Get(objOutput, sampleFormat))),
static_cast<PaTime>(LocalizeInt(Get(objOutput, suggestedLatency))),
NULL
};
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(paramsIn.device));
}
/* BEGIN Init & Exports */
NAN_MODULE_INIT(Init) {
NAN_EXPORT(target, initialize);
NAN_EXPORT(target, terminate);
NAN_EXPORT(target, getVersion);
NAN_EXPORT(target, getHostApiCount);
NAN_EXPORT(target, getDefaultHostApi);
NAN_EXPORT(target, getHostApiInfo);
NAN_EXPORT(target, getDeviceCount);
NAN_EXPORT(target, getDefaultInputDevice);
NAN_EXPORT(target, getDefaultOutputDevice);
NAN_EXPORT(target, getDeviceInfo);
NAN_EXPORT(target, openStream);
}
NODE_MODULE(jsaudio, Init)
<commit_msg>Refactor a bit<commit_after>/*
http://portaudio.com/docs/v19-doxydocs/api_overview.html
*/
/* BEGIN Setup */
// #include "helpers.cc"
#include "portaudio.h"
#include <nan.h>
#ifdef _WIN32
#include "pa_asio.h"
#endif
using namespace Nan;
using String = v8::String;
using Number = v8::Number;
using Object = v8::Object;
using Value = v8::Value;
using Value = v8::Value;
using LocalString = v8::Local<String>;
using LocalNumber = v8::Local<Number>;
using LocalObject = v8::Local<Object>;
using LocalValue = v8::Local<Value>;
using MaybeLocalValue = v8::MaybeLocal<Value>;
/* BEGIN Helpers */
int LocalizeInt (MaybeLocalValue lvIn) {
return lvIn.ToLocalChecked()->Uint32Value();
}
LocalString ToLocString (std::string str) {
return New(str).ToLocalChecked();
}
LocalObject ToLocObject (MaybeLocalValue lvIn) {
return lvIn.ToLocalChecked()->ToObject();
}
void HostApiInfoToLocalObject (LocalObject obj, const PaHostApiInfo* hai) {
obj->Set(
ToLocString("type"), New<Number>(hai->type));
obj->Set(
ToLocString("name"), New<String>(hai->name).ToLocalChecked());
obj->Set(
ToLocString("deviceCount"), New<Number>(hai->deviceCount));
obj->Set(
ToLocString("defaultInputDevice"), New<Number>(hai->defaultInputDevice));
obj->Set(
ToLocString("defaultOutputDevice"), New<Number>(hai->defaultOutputDevice));
return;
}
void DeviceInfoToLocalObject (LocalObject obj, const PaDeviceInfo* di) {
obj->Set(
ToLocString("hostApi"),
New<Number>(di->hostApi));
obj->Set(
ToLocString("name"),
New<String>(di->name).ToLocalChecked());
obj->Set(
ToLocString("maxInputChannels"),
New<Number>(di->maxInputChannels));
obj->Set(
ToLocString("maxOutputChannels"),
New<Number>(di->maxOutputChannels));
obj->Set(
ToLocString("defaultLowInputLatency"),
New<Number>(di->defaultLowInputLatency));
obj->Set(
ToLocString("defaultLowOutputLatency"),
New<Number>(di->defaultLowOutputLatency));
obj->Set(
ToLocString("defaultHighInputLatency"),
New<Number>(di->defaultHighInputLatency));
obj->Set(
ToLocString("defaultHighOutputLatency"),
New<Number>(di->defaultHighOutputLatency));
obj->Set(
ToLocString("defaultSampleRate"),
New<Number>(di->defaultSampleRate));
return;
}
PaStreamParameters LocObjToPaStreamParameters (LocalObject obj) {
PaStreamParameters params = {
static_cast<PaDeviceIndex>(
LocalizeInt(Get(obj, ToLocString("device")))),
static_cast<int>(
LocalizeInt(Get(obj, ToLocString("channelCount")))),
static_cast<PaSampleFormat>(
LocalizeInt(Get(obj, ToLocString("sampleFormat")))),
static_cast<PaTime>(
LocalizeInt(Get(obj, ToLocString("suggestedLatency")))),
NULL
};
return params;
}
/* BEGIN Initialization, termination, and utility */
NAN_METHOD(initialize) {
PaError err = Pa_Initialize();
if (err != paNoError) {
ThrowError(Pa_GetErrorText(err));
}
}
NAN_METHOD(terminate) {
PaError err = Pa_Terminate();
if (err != paNoError) {
ThrowError(Pa_GetErrorText(err));
}
}
NAN_METHOD(getVersion) {
info.GetReturnValue().Set(Pa_GetVersion());
}
/* BEGIN Host APIs */
NAN_METHOD(getHostApiCount) {
info.GetReturnValue().Set(Pa_GetHostApiCount());
}
NAN_METHOD(getDefaultHostApi) {
info.GetReturnValue().Set(Pa_GetDefaultHostApi());
}
NAN_METHOD(getHostApiInfo) {
HandleScope scope;
int api = info[0].IsEmpty() ? Pa_GetDefaultHostApi() : info[0]->Uint32Value();
const PaHostApiInfo* hai = Pa_GetHostApiInfo(api);
LocalObject obj = New<Object>();
obj->Set(ToLocString("apiIndex"), New<Number>(api));
HostApiInfoToLocalObject(obj, hai);
info.GetReturnValue().Set(obj);
}
/* BEGIN Device APIs */
NAN_METHOD(getDeviceCount) {
info.GetReturnValue().Set(Pa_GetDeviceCount());
}
NAN_METHOD(getDefaultInputDevice) {
info.GetReturnValue().Set(Pa_GetDefaultInputDevice());
}
NAN_METHOD(getDefaultOutputDevice) {
info.GetReturnValue().Set(Pa_GetDefaultOutputDevice());
}
NAN_METHOD(getDeviceInfo) {
HandleScope scope;
int dvc = info[0].IsEmpty()
? Pa_GetDefaultInputDevice()
: info[0]->Uint32Value();
const PaDeviceInfo* di = Pa_GetDeviceInfo(dvc);
LocalObject obj = New<Object>();
obj->Set(ToLocString("deviceIndex"), New<Number>(dvc));
DeviceInfoToLocalObject(obj, di);
info.GetReturnValue().Set(obj);
}
/* BEGIN Stream APIs */
NAN_METHOD(openStream) {
HandleScope scope;
LocalObject obj = info[0]->ToObject();
LocalObject objInput = ToLocObject(Get(obj, ToLocString("input")));
LocalObject objOutput = ToLocObject(Get(obj, ToLocString("output")));
PaStreamParameters paramsIn = LocObjToPaStreamParameters(objInput);
PaStreamParameters paramsOut = LocObjToPaStreamParameters(objOutput);
// Testing that params are set right
info.GetReturnValue().Set(New<Number>(paramsIn.device));
}
/* BEGIN Init & Exports */
NAN_MODULE_INIT(Init) {
NAN_EXPORT(target, initialize);
NAN_EXPORT(target, terminate);
NAN_EXPORT(target, getVersion);
NAN_EXPORT(target, getHostApiCount);
NAN_EXPORT(target, getDefaultHostApi);
NAN_EXPORT(target, getHostApiInfo);
NAN_EXPORT(target, getDeviceCount);
NAN_EXPORT(target, getDefaultInputDevice);
NAN_EXPORT(target, getDefaultOutputDevice);
NAN_EXPORT(target, getDeviceInfo);
NAN_EXPORT(target, openStream);
}
NODE_MODULE(jsaudio, Init)
<|endoftext|> |
<commit_before>
#include "ThymioTracker.h"
#include <vector>
#include <stdexcept>
#include <fstream>
#include <opencv2/core.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
namespace thymio_tracker
{
static const std::vector<cv::Scalar> colorPalette = {
cv::Scalar(76, 114, 176),
cv::Scalar(85, 168, 104),
cv::Scalar(196, 78, 82),
cv::Scalar(129, 114, 178),
cv::Scalar(204, 185, 116),
cv::Scalar(100, 181, 205)
};
Timer::Timer()
: mTicks{0}
, mIndex(0)
, mFps(-1.0)
{}
void Timer::tic()
{
std::clock_t current = std::clock();
std::clock_t prev = mTicks[mIndex];
mTicks[mIndex] = current;
++mIndex;
if(mIndex >= N)
mIndex = 0;
if(prev != 0)
mFps = CLOCKS_PER_SEC * N / static_cast<double>(current - prev);
}
void DetectionInfo::clear()
{
blobs.clear();
blobPairs.clear();
blobTriplets.clear();
blobQuadriplets.clear();
blobsinTriplets.clear();
matches.clear();
}
void drawPointsAndIds(cv::Mat& inputImage, const std::vector<DetectionGH>& matches)
{
//draw Id
for(unsigned int i = 0; i < matches.size(); ++i)
{
char pointIdStr[100];
sprintf(pointIdStr, "%d", matches[i].id);
circle(inputImage, matches[i].position, 4, cvScalar(0, 250, 250), -1, 8, 0);
putText(inputImage, pointIdStr, matches[i].position, cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(250,250,250), 1, CV_AA);
}
}
void drawAxes(cv::Mat& image, const cv::Mat& orientation)
{
static const cv::Scalar axes_colors[] = {cv::Scalar(255, 0, 0), cv::Scalar(0, 255, 0), cv::Scalar(0, 0, 255)};
cv::Size::value_type width = image.size().width;
cv::Point2d center(width * 0.1, width * 0.1);
double length = width * 0.05;
for(int i = 0; i < 3; ++i)
{
const cv::Point2d direction(orientation.at<float>(i, 1), orientation.at<float>(i, 0));
const cv::Point2d arrow = center - length * direction;
const cv::Scalar& color = axes_colors[i];
cv::line(image, center, arrow, color);
}
}
ThymioTracker::ThymioTracker(const std::string& calibrationFile,
const std::string& geomHashingFile,
const std::vector<std::string>& landmarkFiles)
: mDetectionInfo(landmarkFiles.size())
, mFeatureExtractor(cv::BRISK::create())
{
//static const std::string ghfilename = "/sdcard/GH_Arth_Perspective.dat";
std::ifstream geomHashingStream(geomHashingFile, std::ios::in | std::ios::binary);
if (!geomHashingStream.is_open())
{
std::cerr << "Could not open " << geomHashingFile << std::endl;
throw std::runtime_error("GHscale::loadFromFile > File not found!");
}
// loadCalibration("../data/calibration/embedded_camera_calib.xml", &calibration, &imgSize);
// loadCalibration("../data/calibration/nexus_camera_calib.xml", &calibration, &imgSize);
cv::FileStorage calibrationStorage(calibrationFile, cv::FileStorage::READ);
if(!calibrationStorage.isOpened())
{
std::cerr << "Could not open " << calibrationFile << std::endl;
throw std::runtime_error("Calibration file not found!");
}
std::vector<cv::FileStorage> landmarkStorages;
for(auto& landmarkFile : landmarkFiles)
{
cv::FileStorage fs(landmarkFile, cv::FileStorage::READ);
if(!fs.isOpened())
throw std::runtime_error("Marker file not found");
landmarkStorages.push_back(fs);
}
init(calibrationStorage, geomHashingStream, landmarkStorages);
}
ThymioTracker::ThymioTracker(cv::FileStorage& calibrationStorage,
std::istream& geomHashingStream,
std::vector<cv::FileStorage>& landmarkStorages)
: mDetectionInfo(landmarkStorages.size())
, mFeatureExtractor(cv::BRISK::create())
{
init(calibrationStorage, geomHashingStream, landmarkStorages);
}
void ThymioTracker::init(cv::FileStorage& calibrationStorage,
std::istream& geomHashingStream,
std::vector<cv::FileStorage>& landmarkStorages)
{
mGH.loadFromStream(geomHashingStream);
readCalibrationFromFileStorage(calibrationStorage, mCalibration);
mGH.setCalibration(mCalibration);
// Load landmarks
for(auto& landmarkStorage : landmarkStorages)
mLandmarks.push_back(Landmark::fromFileStorage(landmarkStorage));
}
void ThymioTracker::resizeCalibration(const cv::Size& imgSize)
{
// loadCalibration(mCalibrationFile, imgSize, &mCalibration);
rescaleCalibration(mCalibration, imgSize);
mGH.setCalibration(mCalibration);
}
void ThymioTracker::update(const cv::Mat& input,
const cv::Mat* deviceOrientation)
{
if(input.size() != mCalibration.imageSize)
resizeCalibration(input.size());
mDetectionInfo.clear();
//get the pairs which are likely to belong to group of blobs from model
mGrouping.getBlobsAndPairs(input,
mDetectionInfo.blobs,
mDetectionInfo.blobPairs);
// get triplet by checking homography and inertia
mGrouping.getTripletsFromPairs(mDetectionInfo.blobs,
mDetectionInfo.blobPairs,
mDetectionInfo.blobTriplets);
//get only blobs found in triplets
getBlobsInTriplets(mDetectionInfo.blobs,
mDetectionInfo.blobTriplets,
mDetectionInfo.blobsinTriplets);
mGrouping.getQuadripletsFromTriplets(mDetectionInfo.blobTriplets,
mDetectionInfo.blobQuadriplets);
//extract blobs and identify which one fit model, return set of positions and Id
mGH.getModelPointsFromImage(mDetectionInfo.blobsinTriplets, mDetectionInfo.matches);
mDetectionInfo.robotFound = mRobot.getPose(mCalibration,
mDetectionInfo.matches,
mDetectionInfo.robotPose,
mDetectionInfo.robotFound);
static int counter = 100;
++counter;
cv::Mat prevIm;input.copyTo(prevIm);//just to do some displaying and debugging and print stuff in input
// Landmark tracking
std::vector<cv::KeyPoint> detectedKeypoints;
cv::Mat detectedDescriptors;
//check if all the landmarks are tracked
bool allTracked = true;
auto lmcDetectionsIt = mDetectionInfo.landmarkDetections.cbegin();
for(; lmcDetectionsIt != mDetectionInfo.landmarkDetections.cend(); ++lmcDetectionsIt)
{
const cv::Mat& h = lmcDetectionsIt->getHomography();
if(h.empty())
allTracked = false;
}
// Extract features only once every 100 frames and only if need to do any detection
if(!allTracked && counter >= 20)
{
cv::Mat gray_input;
cv::cvtColor(input, gray_input, CV_RGB2GRAY);
mFeatureExtractor->detectAndCompute(gray_input, cv::noArray(),
detectedKeypoints, detectedDescriptors);
counter = 0;
}
auto landmarksIt = mLandmarks.cbegin();
auto lmDetectionsIt = mDetectionInfo.landmarkDetections.begin();
for(; landmarksIt != mLandmarks.cend(); ++landmarksIt, ++lmDetectionsIt)
landmarksIt->find(input, mDetectionInfo.prevImage, mCalibration, detectedKeypoints, detectedDescriptors, *lmDetectionsIt);
//input.copyTo(mDetectionInfo.prevImage);
prevIm.copyTo(mDetectionInfo.prevImage);
mTimer.tic();
}
void ThymioTracker::drawLastDetection(cv::Mat* output) const
{
// mDetectionInfo.image.copyTo(*output);
if(mDetectionInfo.robotFound)
mRobot.draw(*output, mCalibration, mDetectionInfo.robotPose);
else
putText(*output, "Lost",
cv::Point2i(10,10),
cv::FONT_HERSHEY_COMPLEX_SMALL,
0.8, cvScalar(0,0,250), 1, CV_AA);
drawBlobPairs(*output, mDetectionInfo.blobs, mDetectionInfo.blobPairs);
drawBlobTriplets(*output, mDetectionInfo.blobs, mDetectionInfo.blobTriplets);
drawBlobQuadruplets(*output, mDetectionInfo.blobs, mDetectionInfo.blobQuadriplets);
// drawPointsAndIds(output, mDetectionInfo.matches);
// if(deviceOrientation)
// drawAxes(*output, *deviceOrientation);
// Draw landmark detections
std::vector<cv::Point2f> corners(4);
auto lmDetectionsIt = mDetectionInfo.landmarkDetections.cbegin();
auto landmarksIt = mLandmarks.cbegin();
auto colorIt = colorPalette.cbegin();
for(; landmarksIt != mLandmarks.cend(); ++landmarksIt, ++lmDetectionsIt, ++colorIt)
{
const Landmark& landmark = *landmarksIt;
const cv::Mat& h = lmDetectionsIt->getHomography();
// Reset the color iterator if needed
if(colorIt == colorPalette.cend())
colorIt = colorPalette.cbegin();
if(h.empty())
continue;
cv::perspectiveTransform(landmark.getCorners(), corners, h);
cv::line(*output, corners[0], corners[1], *colorIt, 2);
cv::line(*output, corners[1], corners[2], *colorIt, 2);
cv::line(*output, corners[2], corners[3], *colorIt, 2);
cv::line(*output, corners[3], corners[0], *colorIt, 2);
for(auto c : lmDetectionsIt->getCorrespondences())
{
cv::Point2f p = c.second;
cv::circle(*output, p, 2, cv::Scalar(0, 255, 255));
}
//draw pose
//draw object frame (axis XYZ)
std::vector<cv::Point3f> framePoints;
framePoints.push_back(cv::Point3f(0,0,0));
framePoints.push_back(cv::Point3f(0.03,0,0));
framePoints.push_back(cv::Point3f(0,0.03,0));
framePoints.push_back(cv::Point3f(0,0,0.03));
//cv::Affine3d pose = lmDetectionsIt->getPose().inv();
cv::Affine3d pose = lmDetectionsIt->getPose();
std::vector<cv::Point2f> vprojVertices;
cv::projectPoints(framePoints, pose.rvec(), pose.translation(), mCalibration.cameraMatrix, mCalibration.distCoeffs, vprojVertices);
cv::line(*output, vprojVertices[0], vprojVertices[1], cv::Scalar(0,0,255), 2);
cv::line(*output, vprojVertices[0], vprojVertices[2], cv::Scalar(0,255,0), 2);
cv::line(*output, vprojVertices[0], vprojVertices[3], cv::Scalar(255,0,0), 2);
}
}
}
<commit_msg>receive grayscale images as input<commit_after>
#include "ThymioTracker.h"
#include <vector>
#include <stdexcept>
#include <fstream>
#include <opencv2/core.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgproc.hpp>
namespace thymio_tracker
{
static const std::vector<cv::Scalar> colorPalette = {
cv::Scalar(76, 114, 176),
cv::Scalar(85, 168, 104),
cv::Scalar(196, 78, 82),
cv::Scalar(129, 114, 178),
cv::Scalar(204, 185, 116),
cv::Scalar(100, 181, 205)
};
Timer::Timer()
: mTicks{0}
, mIndex(0)
, mFps(-1.0)
{}
void Timer::tic()
{
std::clock_t current = std::clock();
std::clock_t prev = mTicks[mIndex];
mTicks[mIndex] = current;
++mIndex;
if(mIndex >= N)
mIndex = 0;
if(prev != 0)
mFps = CLOCKS_PER_SEC * N / static_cast<double>(current - prev);
}
void DetectionInfo::clear()
{
blobs.clear();
blobPairs.clear();
blobTriplets.clear();
blobQuadriplets.clear();
blobsinTriplets.clear();
matches.clear();
}
void drawPointsAndIds(cv::Mat& inputImage, const std::vector<DetectionGH>& matches)
{
//draw Id
for(unsigned int i = 0; i < matches.size(); ++i)
{
char pointIdStr[100];
sprintf(pointIdStr, "%d", matches[i].id);
circle(inputImage, matches[i].position, 4, cvScalar(0, 250, 250), -1, 8, 0);
putText(inputImage, pointIdStr, matches[i].position, cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, cvScalar(250,250,250), 1, CV_AA);
}
}
void drawAxes(cv::Mat& image, const cv::Mat& orientation)
{
static const cv::Scalar axes_colors[] = {cv::Scalar(255, 0, 0), cv::Scalar(0, 255, 0), cv::Scalar(0, 0, 255)};
cv::Size::value_type width = image.size().width;
cv::Point2d center(width * 0.1, width * 0.1);
double length = width * 0.05;
for(int i = 0; i < 3; ++i)
{
const cv::Point2d direction(orientation.at<float>(i, 1), orientation.at<float>(i, 0));
const cv::Point2d arrow = center - length * direction;
const cv::Scalar& color = axes_colors[i];
cv::line(image, center, arrow, color);
}
}
ThymioTracker::ThymioTracker(const std::string& calibrationFile,
const std::string& geomHashingFile,
const std::vector<std::string>& landmarkFiles)
: mDetectionInfo(landmarkFiles.size())
, mFeatureExtractor(cv::BRISK::create())
{
//static const std::string ghfilename = "/sdcard/GH_Arth_Perspective.dat";
std::ifstream geomHashingStream(geomHashingFile, std::ios::in | std::ios::binary);
if (!geomHashingStream.is_open())
{
std::cerr << "Could not open " << geomHashingFile << std::endl;
throw std::runtime_error("GHscale::loadFromFile > File not found!");
}
// loadCalibration("../data/calibration/embedded_camera_calib.xml", &calibration, &imgSize);
// loadCalibration("../data/calibration/nexus_camera_calib.xml", &calibration, &imgSize);
cv::FileStorage calibrationStorage(calibrationFile, cv::FileStorage::READ);
if(!calibrationStorage.isOpened())
{
std::cerr << "Could not open " << calibrationFile << std::endl;
throw std::runtime_error("Calibration file not found!");
}
std::vector<cv::FileStorage> landmarkStorages;
for(auto& landmarkFile : landmarkFiles)
{
cv::FileStorage fs(landmarkFile, cv::FileStorage::READ);
if(!fs.isOpened())
throw std::runtime_error("Marker file not found");
landmarkStorages.push_back(fs);
}
init(calibrationStorage, geomHashingStream, landmarkStorages);
}
ThymioTracker::ThymioTracker(cv::FileStorage& calibrationStorage,
std::istream& geomHashingStream,
std::vector<cv::FileStorage>& landmarkStorages)
: mDetectionInfo(landmarkStorages.size())
, mFeatureExtractor(cv::BRISK::create())
{
init(calibrationStorage, geomHashingStream, landmarkStorages);
}
void ThymioTracker::init(cv::FileStorage& calibrationStorage,
std::istream& geomHashingStream,
std::vector<cv::FileStorage>& landmarkStorages)
{
mGH.loadFromStream(geomHashingStream);
readCalibrationFromFileStorage(calibrationStorage, mCalibration);
mGH.setCalibration(mCalibration);
// Load landmarks
for(auto& landmarkStorage : landmarkStorages)
mLandmarks.push_back(Landmark::fromFileStorage(landmarkStorage));
}
void ThymioTracker::resizeCalibration(const cv::Size& imgSize)
{
// loadCalibration(mCalibrationFile, imgSize, &mCalibration);
rescaleCalibration(mCalibration, imgSize);
mGH.setCalibration(mCalibration);
}
void ThymioTracker::update(const cv::Mat& input,
const cv::Mat* deviceOrientation)
{
if(input.size() != mCalibration.imageSize)
resizeCalibration(input.size());
mDetectionInfo.clear();
//get the pairs which are likely to belong to group of blobs from model
mGrouping.getBlobsAndPairs(input,
mDetectionInfo.blobs,
mDetectionInfo.blobPairs);
// get triplet by checking homography and inertia
mGrouping.getTripletsFromPairs(mDetectionInfo.blobs,
mDetectionInfo.blobPairs,
mDetectionInfo.blobTriplets);
//get only blobs found in triplets
getBlobsInTriplets(mDetectionInfo.blobs,
mDetectionInfo.blobTriplets,
mDetectionInfo.blobsinTriplets);
mGrouping.getQuadripletsFromTriplets(mDetectionInfo.blobTriplets,
mDetectionInfo.blobQuadriplets);
//extract blobs and identify which one fit model, return set of positions and Id
mGH.getModelPointsFromImage(mDetectionInfo.blobsinTriplets, mDetectionInfo.matches);
mDetectionInfo.robotFound = mRobot.getPose(mCalibration,
mDetectionInfo.matches,
mDetectionInfo.robotPose,
mDetectionInfo.robotFound);
static int counter = 100;
++counter;
cv::Mat prevIm;input.copyTo(prevIm);//just to do some displaying and debugging and print stuff in input
// Landmark tracking
std::vector<cv::KeyPoint> detectedKeypoints;
cv::Mat detectedDescriptors;
//check if all the landmarks are tracked
bool allTracked = true;
auto lmcDetectionsIt = mDetectionInfo.landmarkDetections.cbegin();
for(; lmcDetectionsIt != mDetectionInfo.landmarkDetections.cend(); ++lmcDetectionsIt)
{
const cv::Mat& h = lmcDetectionsIt->getHomography();
if(h.empty())
allTracked = false;
}
// Extract features only once every 100 frames and only if need to do any detection
if(!allTracked && counter >= 20)
{
mFeatureExtractor->detectAndCompute(input, cv::noArray(),
detectedKeypoints, detectedDescriptors);
counter = 0;
}
auto landmarksIt = mLandmarks.cbegin();
auto lmDetectionsIt = mDetectionInfo.landmarkDetections.begin();
for(; landmarksIt != mLandmarks.cend(); ++landmarksIt, ++lmDetectionsIt)
landmarksIt->find(input, mDetectionInfo.prevImage, mCalibration, detectedKeypoints, detectedDescriptors, *lmDetectionsIt);
//input.copyTo(mDetectionInfo.prevImage);
prevIm.copyTo(mDetectionInfo.prevImage);
mTimer.tic();
}
void ThymioTracker::drawLastDetection(cv::Mat* output) const
{
// mDetectionInfo.image.copyTo(*output);
if(mDetectionInfo.robotFound)
mRobot.draw(*output, mCalibration, mDetectionInfo.robotPose);
else
putText(*output, "Lost",
cv::Point2i(10,10),
cv::FONT_HERSHEY_COMPLEX_SMALL,
0.8, cvScalar(0,0,250), 1, CV_AA);
drawBlobPairs(*output, mDetectionInfo.blobs, mDetectionInfo.blobPairs);
drawBlobTriplets(*output, mDetectionInfo.blobs, mDetectionInfo.blobTriplets);
drawBlobQuadruplets(*output, mDetectionInfo.blobs, mDetectionInfo.blobQuadriplets);
// drawPointsAndIds(output, mDetectionInfo.matches);
// if(deviceOrientation)
// drawAxes(*output, *deviceOrientation);
// Draw landmark detections
std::vector<cv::Point2f> corners(4);
auto lmDetectionsIt = mDetectionInfo.landmarkDetections.cbegin();
auto landmarksIt = mLandmarks.cbegin();
auto colorIt = colorPalette.cbegin();
for(; landmarksIt != mLandmarks.cend(); ++landmarksIt, ++lmDetectionsIt, ++colorIt)
{
const Landmark& landmark = *landmarksIt;
const cv::Mat& h = lmDetectionsIt->getHomography();
// Reset the color iterator if needed
if(colorIt == colorPalette.cend())
colorIt = colorPalette.cbegin();
if(h.empty())
continue;
cv::perspectiveTransform(landmark.getCorners(), corners, h);
cv::line(*output, corners[0], corners[1], *colorIt, 2);
cv::line(*output, corners[1], corners[2], *colorIt, 2);
cv::line(*output, corners[2], corners[3], *colorIt, 2);
cv::line(*output, corners[3], corners[0], *colorIt, 2);
for(auto c : lmDetectionsIt->getCorrespondences())
{
cv::Point2f p = c.second;
cv::circle(*output, p, 2, cv::Scalar(0, 255, 255));
}
//draw pose
//draw object frame (axis XYZ)
std::vector<cv::Point3f> framePoints;
framePoints.push_back(cv::Point3f(0,0,0));
framePoints.push_back(cv::Point3f(0.03,0,0));
framePoints.push_back(cv::Point3f(0,0.03,0));
framePoints.push_back(cv::Point3f(0,0,0.03));
//cv::Affine3d pose = lmDetectionsIt->getPose().inv();
cv::Affine3d pose = lmDetectionsIt->getPose();
std::vector<cv::Point2f> vprojVertices;
cv::projectPoints(framePoints, pose.rvec(), pose.translation(), mCalibration.cameraMatrix, mCalibration.distCoeffs, vprojVertices);
cv::line(*output, vprojVertices[0], vprojVertices[1], cv::Scalar(0,0,255), 2);
cv::line(*output, vprojVertices[0], vprojVertices[2], cv::Scalar(0,255,0), 2);
cv::line(*output, vprojVertices[0], vprojVertices[3], cv::Scalar(255,0,0), 2);
}
}
}
<|endoftext|> |
<commit_before>/*
* (C) 2015,2017 Jack Lloyd
* (C) 2015 Simon Warta (Kullo GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/exceptn.h>
#include <botan/internal/filesystem.h>
#include <algorithm>
#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <filesystem>
#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)
#include <boost/filesystem.hpp>
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <deque>
#include <memory>
#include <functional>
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
#define NOMINMAX 1
#define _WINSOCKAPI_ // stop windows.h including winsock.h
#include <windows.h>
#include <deque>
#include <memory>
#endif
namespace Botan {
namespace {
#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
std::vector<std::string> impl_stl_filesystem(const std::string& dir)
{
#if (_MSVC_LANG >= 201703L)
using namespace std::filesystem;
#else
using namespace std::tr2::sys;
#endif
std::vector<std::string> out;
path p(dir);
if(is_directory(p))
{
for(recursive_directory_iterator itr(p), end; itr != end; ++itr)
{
if(is_regular_file(itr->path()))
{
out.push_back(itr->path().string());
}
}
}
return out;
}
#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)
std::vector<std::string> impl_boost_filesystem(const std::string& dir_path)
{
namespace fs = boost::filesystem;
std::vector<std::string> out;
for(fs::recursive_directory_iterator dir(dir_path), end; dir != end; ++dir)
{
if(fs::is_regular_file(dir->path()))
{
out.push_back(dir->path().string());
}
}
return out;
}
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
std::vector<std::string> impl_readdir(const std::string& dir_path)
{
std::vector<std::string> out;
std::deque<std::string> dir_list;
dir_list.push_back(dir_path);
while(!dir_list.empty())
{
const std::string cur_path = dir_list[0];
dir_list.pop_front();
std::unique_ptr<DIR, std::function<int (DIR*)>> dir(::opendir(cur_path.c_str()), ::closedir);
if(dir)
{
while(struct dirent* dirent = ::readdir(dir.get()))
{
const std::string filename = dirent->d_name;
if(filename == "." || filename == "..")
continue;
const std::string full_path = cur_path + "/" + filename;
struct stat stat_buf;
if(::stat(full_path.c_str(), &stat_buf) == -1)
continue;
if(S_ISDIR(stat_buf.st_mode))
dir_list.push_back(full_path);
else if(S_ISREG(stat_buf.st_mode))
out.push_back(full_path);
}
}
}
return out;
}
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
std::vector<std::string> impl_win32(const std::string& dir_path)
{
std::vector<std::string> out;
std::deque<std::string> dir_list;
dir_list.push_back(dir_path);
while(!dir_list.empty())
{
const std::string cur_path = dir_list[0];
dir_list.pop_front();
WIN32_FIND_DATA find_data;
HANDLE dir = ::FindFirstFile((cur_path + "/*").c_str(), &find_data);
if(dir != INVALID_HANDLE_VALUE)
{
do
{
const std::string filename = find_data.cFileName;
if(filename == "." || filename == "..")
continue;
const std::string full_path = cur_path + "/" + filename;
if(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
dir_list.push_back(full_path);
}
else
{
out.push_back(full_path);
}
}
while(::FindNextFile(dir, &find_data));
}
::FindClose(dir);
}
return out;
}
#endif
}
bool has_filesystem_impl()
{
#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
return true;
#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)
return true;
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
return true;
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
return true;
#else
return false;
#endif
}
std::vector<std::string> get_files_recursive(const std::string& dir)
{
std::vector<std::string> files;
#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
files = impl_stl_filesystem(dir);
#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)
files = impl_boost_filesystem(dir);
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
files = impl_readdir(dir);
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
files = impl_win32(dir);
#else
BOTAN_UNUSED(dir);
throw No_Filesystem_Access();
#endif
std::sort(files.begin(), files.end());
return files;
}
}
<commit_msg>Use ASCII specific function calls for Windows API calls<commit_after>/*
* (C) 2015,2017 Jack Lloyd
* (C) 2015 Simon Warta (Kullo GmbH)
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/exceptn.h>
#include <botan/internal/filesystem.h>
#include <algorithm>
#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <filesystem>
#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)
#include <boost/filesystem.hpp>
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <deque>
#include <memory>
#include <functional>
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
#define NOMINMAX 1
#define _WINSOCKAPI_ // stop windows.h including winsock.h
#include <windows.h>
#include <deque>
#include <memory>
#endif
namespace Botan {
namespace {
#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
std::vector<std::string> impl_stl_filesystem(const std::string& dir)
{
#if (_MSVC_LANG >= 201703L)
using namespace std::filesystem;
#else
using namespace std::tr2::sys;
#endif
std::vector<std::string> out;
path p(dir);
if(is_directory(p))
{
for(recursive_directory_iterator itr(p), end; itr != end; ++itr)
{
if(is_regular_file(itr->path()))
{
out.push_back(itr->path().string());
}
}
}
return out;
}
#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)
std::vector<std::string> impl_boost_filesystem(const std::string& dir_path)
{
namespace fs = boost::filesystem;
std::vector<std::string> out;
for(fs::recursive_directory_iterator dir(dir_path), end; dir != end; ++dir)
{
if(fs::is_regular_file(dir->path()))
{
out.push_back(dir->path().string());
}
}
return out;
}
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
std::vector<std::string> impl_readdir(const std::string& dir_path)
{
std::vector<std::string> out;
std::deque<std::string> dir_list;
dir_list.push_back(dir_path);
while(!dir_list.empty())
{
const std::string cur_path = dir_list[0];
dir_list.pop_front();
std::unique_ptr<DIR, std::function<int (DIR*)>> dir(::opendir(cur_path.c_str()), ::closedir);
if(dir)
{
while(struct dirent* dirent = ::readdir(dir.get()))
{
const std::string filename = dirent->d_name;
if(filename == "." || filename == "..")
continue;
const std::string full_path = cur_path + "/" + filename;
struct stat stat_buf;
if(::stat(full_path.c_str(), &stat_buf) == -1)
continue;
if(S_ISDIR(stat_buf.st_mode))
dir_list.push_back(full_path);
else if(S_ISREG(stat_buf.st_mode))
out.push_back(full_path);
}
}
}
return out;
}
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
std::vector<std::string> impl_win32(const std::string& dir_path)
{
std::vector<std::string> out;
std::deque<std::string> dir_list;
dir_list.push_back(dir_path);
while(!dir_list.empty())
{
const std::string cur_path = dir_list[0];
dir_list.pop_front();
WIN32_FIND_DATAA find_data;
HANDLE dir = ::FindFirstFileA((cur_path + "/*").c_str(), &find_data);
if(dir != INVALID_HANDLE_VALUE)
{
do
{
const std::string filename = find_data.cFileName;
if(filename == "." || filename == "..")
continue;
const std::string full_path = cur_path + "/" + filename;
if(find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
dir_list.push_back(full_path);
}
else
{
out.push_back(full_path);
}
}
while(::FindNextFileA(dir, &find_data));
}
::FindClose(dir);
}
return out;
}
#endif
}
bool has_filesystem_impl()
{
#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
return true;
#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)
return true;
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
return true;
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
return true;
#else
return false;
#endif
}
std::vector<std::string> get_files_recursive(const std::string& dir)
{
std::vector<std::string> files;
#if defined(BOTAN_TARGET_OS_HAS_STL_FILESYSTEM_MSVC) && defined(BOTAN_BUILD_COMPILER_IS_MSVC)
files = impl_stl_filesystem(dir);
#elif defined(BOTAN_HAS_BOOST_FILESYSTEM)
files = impl_boost_filesystem(dir);
#elif defined(BOTAN_TARGET_OS_HAS_POSIX1)
files = impl_readdir(dir);
#elif defined(BOTAN_TARGET_OS_HAS_WIN32)
files = impl_win32(dir);
#else
BOTAN_UNUSED(dir);
throw No_Filesystem_Access();
#endif
std::sort(files.begin(), files.end());
return files;
}
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.