commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
---|---|---|---|---|---|---|---|---|---|
e7bb05a38d60ac18850834b74adb71c487ef2472
|
src/ethereum/ethereum.cpp
|
src/ethereum/ethereum.cpp
|
// Copyright (c) 2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <uint256.h>
#include <arith_uint256.h>
#include <ethereum/ethereum.h>
#include <ethereum/sha3.h>
#include <services/witnessaddress.h>
#include <logging.h>
#include <util/strencodings.h>
int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {
std::string partialPath;
char pathPtrInt[2] = {encodedPartialPath[0], '\0'};
int partialPathInt = strtol(pathPtrInt, NULL, 10);
if(partialPathInt == 0 || partialPathInt == 2){
partialPath = encodedPartialPath.substr(2);
}else{
partialPath = encodedPartialPath.substr(1);
}
if(partialPath == path.substr(pathPtr, partialPath.size())){
return partialPath.size();
}else{
return -1;
}
}
bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {
try{
dev::RLP currentNode;
const int len = parentNodes.itemCount();
dev::RLP nodeKey = root;
int pathPtr = 0;
const std::string pathString = dev::toHex(path);
int nibbles;
char pathPtrInt[2];
for (int i = 0 ; i < len ; i++) {
currentNode = parentNodes[i];
if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){
return false;
}
if(pathPtr > (int)pathString.size()){
return false;
}
switch(currentNode.itemCount()){
case 17://branch node
if(pathPtr == (int)pathString.size()){
if(currentNode[16].payload().contentsEqual(value.data().toVector())){
return true;
}else{
return false;
}
}
pathPtrInt[0] = pathString[pathPtr];
pathPtrInt[1] = '\0';
nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]]))
pathPtr += 1;
break;
case 2:
nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);
if(nibbles <= -1)
return false;
pathPtr += nibbles;
if(pathPtr == (int)pathString.size()) { //leaf node
if(currentNode[1].payload().contentsEqual(value.data().toVector())){
return true;
} else {
return false;
}
} else {//extension node
nodeKey = currentNode[1];
}
break;
default:
return false;
}
}
}
catch(...){
return false;
}
return false;
}
/**
* Parse eth input string expected to contain smart contract method call data. If the method call is not what we
* expected, or the length of the expected string is not what we expect then return false.
*
* @param vchInputExpectedMethodHash The expected method hash
* @param vchInputData The input to parse
* @param vchAssetContract The ERC20 contract address of the token involved in moving over
* @param outputAmount The amount burned
* @param nAsset The asset burned
* @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a CAmount (int64) with truncation of insignifficant bits
* @param witnessAddress The destination witness address for the minting
* @return true if everything is valid
*/
bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const std::vector<unsigned char>& vchInputData, const std::vector<unsigned char>& vchAssetContract, CAmount& outputAmount, uint32_t& nAsset, const uint8_t& nLocalPrecision, CWitnessAddress& witnessAddress) {
if(vchAssetContract.empty()){
return false;
}
// total 7 or 8 fields are expected @ 32 bytes each field, 8 fields if witness > 32 bytes
if(vchInputData.size() < 196 || vchInputData.size() > 260) {
return false;
}
// method hash is 4 bytes
std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin();
std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4;
const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod);
// if the method hash doesn't match the expected method hash then return false
if(vchMethodHash != vchInputExpectedMethodHash) {
return false;
}
std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32);
// reverse endian
std::reverse(vchAmount.begin(), vchAmount.end());
arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));
// convert the vch into a uint32_t (nAsset)
// should be in position 68 walking backwards
nAsset = static_cast<uint32_t>(vchInputData[67]);
nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8;
nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16;
nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24;
// start from 100 offset (96 for 3rd field + 4 bytes for function signature) and subtract 20
std::vector<unsigned char>::const_iterator firstContractAddress = vchInputData.begin() + 80;
std::vector<unsigned char>::const_iterator lastContractAddress = firstContractAddress + 20;
const std::vector<unsigned char> vchERC20ContractAddress(firstContractAddress,lastContractAddress);
if(vchERC20ContractAddress != vchAssetContract)
{
return false;
}
// skip data position field of 32 bytes + 100 offset + 31 (offset to the varint _byte)
int dataPos = 163;
const unsigned char &dataLength = vchInputData[dataPos++] - 1; // // - 1 to account for the version byte
// witness programs can extend to 40 bytes, min length is 2 for min witness program
if(dataLength > 40 || dataLength < 2){
return false;
}
// get precision
dataPos += 31;
const int8_t &nPrecision = static_cast<uint8_t>(vchInputData[dataPos++]);
// ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision
// local precision can range between 0 and 8 decimal places, so it should fit within a CAmount
if(nLocalPrecision > nPrecision){
outputAmountArith /= pow(10, nLocalPrecision-nPrecision);
// or we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred
} else if(nLocalPrecision < nPrecision){
outputAmountArith *= pow(10, nPrecision-nLocalPrecision);
}
// once we have truncated it is safe to get low 64 bits of the uint256 which should encapsulate the entire value
outputAmount = outputAmountArith.GetLow64();
// witness address information starting at position dataPos till the end
// get version proceeded by witness program bytes
const unsigned char& nVersion = vchInputData[dataPos++];
std::vector<unsigned char>::const_iterator firstWitness = vchInputData.begin()+dataPos;
std::vector<unsigned char>::const_iterator lastWitness = firstWitness + dataLength;
witnessAddress = CWitnessAddress(nVersion, std::vector<unsigned char>(firstWitness,lastWitness));
return witnessAddress.IsValid();
}
|
// Copyright (c) 2019 The Syscoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <uint256.h>
#include <arith_uint256.h>
#include <ethereum/ethereum.h>
#include <ethereum/sha3.h>
#include <services/witnessaddress.h>
#include <logging.h>
#include <util/strencodings.h>
int nibblesToTraverse(const std::string &encodedPartialPath, const std::string &path, int pathPtr) {
std::string partialPath;
char pathPtrInt[2] = {encodedPartialPath[0], '\0'};
int partialPathInt = strtol(pathPtrInt, NULL, 10);
if(partialPathInt == 0 || partialPathInt == 2){
partialPath = encodedPartialPath.substr(2);
}else{
partialPath = encodedPartialPath.substr(1);
}
if(partialPath == path.substr(pathPtr, partialPath.size())){
return partialPath.size();
}else{
return -1;
}
}
bool VerifyProof(dev::bytesConstRef path, const dev::RLP& value, const dev::RLP& parentNodes, const dev::RLP& root) {
try{
dev::RLP currentNode;
const int len = parentNodes.itemCount();
dev::RLP nodeKey = root;
int pathPtr = 0;
const std::string pathString = dev::toHex(path);
int nibbles;
char pathPtrInt[2];
for (int i = 0 ; i < len ; i++) {
currentNode = parentNodes[i];
if(!nodeKey.payload().contentsEqual(sha3(currentNode.data()).ref().toVector())){
return false;
}
if(pathPtr > (int)pathString.size()){
return false;
}
switch(currentNode.itemCount()){
case 17://branch node
if(pathPtr == (int)pathString.size()){
if(currentNode[16].payload().contentsEqual(value.data().toVector())){
return true;
}else{
return false;
}
}
pathPtrInt[0] = pathString[pathPtr];
pathPtrInt[1] = '\0';
nodeKey = currentNode[strtol(pathPtrInt, NULL, 16)]; //must == sha3(rlp.encode(currentNode[path[pathptr]]))
pathPtr += 1;
break;
case 2:
nibbles = nibblesToTraverse(toHex(currentNode[0].payload()), pathString, pathPtr);
if(nibbles <= -1)
return false;
pathPtr += nibbles;
if(pathPtr == (int)pathString.size()) { //leaf node
if(currentNode[1].payload().contentsEqual(value.data().toVector())){
return true;
} else {
return false;
}
} else {//extension node
nodeKey = currentNode[1];
}
break;
default:
return false;
}
}
}
catch(...){
return false;
}
return false;
}
/**
* Parse eth input string expected to contain smart contract method call data. If the method call is not what we
* expected, or the length of the expected string is not what we expect then return false.
*
* @param vchInputExpectedMethodHash The expected method hash
* @param vchInputData The input to parse
* @param vchAssetContract The ERC20 contract address of the token involved in moving over
* @param outputAmount The amount burned
* @param nAsset The asset burned
* @param nLocalPrecision The local precision to know how to convert ethereum's uint256 to a CAmount (int64) with truncation of insignifficant bits
* @param witnessAddress The destination witness address for the minting
* @return true if everything is valid
*/
bool parseEthMethodInputData(const std::vector<unsigned char>& vchInputExpectedMethodHash, const std::vector<unsigned char>& vchInputData, const std::vector<unsigned char>& vchAssetContract, CAmount& outputAmount, uint32_t& nAsset, const uint8_t& nLocalPrecision, CWitnessAddress& witnessAddress) {
if(vchAssetContract.empty()){
return false;
}
// total 7 or 8 fields are expected @ 32 bytes each field, 8 fields if witness > 32 bytes
if(vchInputData.size() < 228 || vchInputData.size() > 260) {
return false;
}
// method hash is 4 bytes
std::vector<unsigned char>::const_iterator firstMethod = vchInputData.begin();
std::vector<unsigned char>::const_iterator lastMethod = firstMethod + 4;
const std::vector<unsigned char> vchMethodHash(firstMethod,lastMethod);
// if the method hash doesn't match the expected method hash then return false
if(vchMethodHash != vchInputExpectedMethodHash) {
return false;
}
std::vector<unsigned char> vchAmount(lastMethod,lastMethod + 32);
// reverse endian
std::reverse(vchAmount.begin(), vchAmount.end());
arith_uint256 outputAmountArith = UintToArith256(uint256(vchAmount));
// convert the vch into a uint32_t (nAsset)
// should be in position 68 walking backwards
nAsset = static_cast<uint32_t>(vchInputData[67]);
nAsset |= static_cast<uint32_t>(vchInputData[66]) << 8;
nAsset |= static_cast<uint32_t>(vchInputData[65]) << 16;
nAsset |= static_cast<uint32_t>(vchInputData[64]) << 24;
// start from 100 offset (96 for 3rd field + 4 bytes for function signature) and subtract 20
std::vector<unsigned char>::const_iterator firstContractAddress = vchInputData.begin() + 80;
std::vector<unsigned char>::const_iterator lastContractAddress = firstContractAddress + 20;
const std::vector<unsigned char> vchERC20ContractAddress(firstContractAddress,lastContractAddress);
if(vchERC20ContractAddress != vchAssetContract)
{
return false;
}
// skip data position field of 32 bytes + 100 offset + 31 (offset to the varint _byte)
int dataPos = 163;
const unsigned char &dataLength = vchInputData[dataPos++] - 1; // // - 1 to account for the version byte
// witness programs can extend to 40 bytes, min length is 2 for min witness program
if(dataLength > 40 || dataLength < 2){
return false;
}
// get precision
dataPos += 31;
const int8_t &nPrecision = static_cast<uint8_t>(vchInputData[dataPos++]);
// ensure we truncate decimals to fit within int64 if erc20's precision is more than our asset precision
// local precision can range between 0 and 8 decimal places, so it should fit within a CAmount
if(nLocalPrecision > nPrecision){
outputAmountArith /= pow(10, nLocalPrecision-nPrecision);
// or we pad zero's if erc20's precision is less than ours so we can accurately get the whole value of the amount transferred
} else if(nLocalPrecision < nPrecision){
outputAmountArith *= pow(10, nPrecision-nLocalPrecision);
}
// once we have truncated it is safe to get low 64 bits of the uint256 which should encapsulate the entire value
outputAmount = outputAmountArith.GetLow64();
// witness address information starting at position dataPos till the end
// get version proceeded by witness program bytes
const unsigned char& nVersion = vchInputData[dataPos++];
std::vector<unsigned char>::const_iterator firstWitness = vchInputData.begin()+dataPos;
std::vector<unsigned char>::const_iterator lastWitness = firstWitness + dataLength;
witnessAddress = CWitnessAddress(nVersion, std::vector<unsigned char>(firstWitness,lastWitness));
return witnessAddress.IsValid();
}
|
fix input data size check
|
fix input data size check
Former-commit-id: c97f63b1a8863101413e6f5ece345a7722daf103
|
C++
|
mit
|
syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin2,syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin,syscoin/syscoin2,syscoin/syscoin
|
01d24ad0dae75bb8ec9a05e7074381200a89c6f5
|
SKIRTcore/Parallel.hpp
|
SKIRTcore/Parallel.hpp
|
/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifndef PARALLEL_HPP
#define PARALLEL_HPP
#include <atomic>
#include <mutex>
#include <thread>
#include "ParallelTarget.hpp"
class FatalError;
class ParallelFactory;
class ProcessAssigner;
////////////////////////////////////////////////////////////////////
/** This class supports a simple parallel execution model similar to a for loop. The body of the
for loop consists of the body() function of a ParallelTarget subclass, or alternatively of
some class member function (specified by the caller) with a single integer argument, which
gets passed the index of the current iteration.
For example, to invoke a member function 1000 times one would write something like:
\code
void Test::body(size_t index) { ... }
...
IdenticalAssigner assigner;
ParallelFactory factory;
...
assigner.assign(1000);
factory.parallel()->call(this, &Test::body, &assigner);
\endcode
A Parallel instance can be created only through the ParallelFactory class. The default
construction shown above determines a reasonable number of threads for the computer on which
the code is running, and the call() function distributes the work over these threads.
The parallelized body should protect (write-) access to shared data through the use of an
std::mutex object. Shared data includes the data members of the target object (in the context
of which the target function executes) and essentially everything other than local variables.
Also note that the parallelized body includes all functions directly or indirectly called by
the target function.
When an exception is thrown by one of the threads excuting the parallelized body, all other
threads are gracefully shut down and a FatalError exception is thrown in the context of the
thread that invoked the call() function. If the original exception was a FatalError instance, the
newly thrown exception is a copy thereof. Otherwise a fresh FatalError instance is created with
a generic error message.
Between invocations of the call() function, the parallel threads are put in wait so that
they consume no CPU cycles (and very little memory). Thus a
particular Parallel instance can be reused many times for calling various member functions in
various objects, reducing the overhead of creating and destroying the threads. One can also
use multiple Parallel instances in an application. For example, a parallelized body can invoke
the call() function on another Parallel instance that is constructed and destructed within the
scope of the loop body. Recursively invoking the call() function on the same Parallel instance is
not allowed and results in undefined behavior.
The Parallel class uses C++11 multi-threading capabilities, avoiding the complexities of using
yet another library (such as OpenMP) and making it possible to properly handle exceptions. It
is designed to minimize the run-time overhead for loops with many iterations. */
class Parallel
{
friend class ParallelFactory;
//============= Construction - Setup - Destruction =============
private:
/** Constructs a Parallel instance with the specified number of execution threads. The
constructor is not public; use the ParallelFactory::parallel() function instead. */
Parallel(int threadCount, ParallelFactory* factory);
public:
/** Destructs the instance and its parallel threads. */
~Parallel();
//======================== Other Functions =======================
public:
/** Returns the number of threads used by this instance. */
int threadCount() const;
/** Calls the body() function of the specified specified target object a certain number of times,
with the \em index argument of that function taking values that are determined by the \em
assigner, which is also passed to this function. While the values assigned to a particular
process are fixed at the moment this function is called, the work will be distributed over the
parallel threads in an unpredicable manner. */
void call(ParallelTarget* target, ProcessAssigner* assigner);
/** Calls the specified member function for the specified target object a certain number of times,
with the \em index argument of that function taking values that are determined by the \em
assigner, which is also passed to this function. While the values assigned to a particular
process are fixed at the moment this function is called, the work will be distributed over the
parallel threads in an unpredicable manner. */
template<class T> void call(T* targetObject, void (T::*targetMember)(size_t index), ProcessAssigner* assigner);
private:
/** The function that gets executed inside each of the parallel threads. */
void run(int threadIndex);
/** The function to do the actual work; used by call() and run(). */
void doWork();
/** A function to report an exception; used by doWork(). */
void reportException(FatalError* exception);
/** A function to wait for the parallel threads; used by constructor and call(). */
void waitForThreads();
/** This helper function returns true if at least one of the parallel threads (not including
the parent thread) is still active, and false if not. This function does not perform any
locking; callers should lock the shared data members of this class instance. */
bool threadsActive();
//======================== Nested Classes =======================
private:
/** The declaration for this template class is nested in the Parallel class declaration. It is
used in the implementation of the call() template function to allow specifying a loop body
in the form of an arbitrary target member function and target object. An instance of this
target-type-dependent class bundles the relevant information into a single object with a
type-independent base class (ParallelTarget) so that it can be passed to the regular (i.e.
non-template) call() function. */
template<class T> class Target : public ParallelTarget
{
public:
/** Constructs a ParallelTarget instance with a body() function that calls the specified
target member function on the specified target object. */
Target(T* targetObject, void (T::*targetMember)(size_t index))
: _targetObject(targetObject), _targetMember(targetMember) { }
/** Calls the target member function on the target object specified in the constructor. */
void body(size_t index) { (_targetObject->*(_targetMember))(index); }
private:
T* _targetObject;
void (T::*_targetMember)(size_t index);
};
//======================== Data Members ========================
private:
// data members keeping track of the threads
int _threadCount; // the total number of threads, including the parent thread
std::thread::id _parentThread; // the ID of the thread that invoked our constructor
std::vector<std::thread> _threads; // the parallel threads (other than the parent thread)
// synchronization
std::mutex _mutex; // the mutex to synchronize with the parallel threads
std::condition_variable _conditionExtra; // the wait condition used by the parallel threads
std::condition_variable _conditionMain; // the wait condition used by the main thread
// data members shared by all threads; changes are protected by a mutex
ParallelTarget* _target; // the target to be called
ProcessAssigner* _assigner; // the process assigner
size_t _limit; // the limit of the for loop being implemented
std::vector<bool> _active; // flag for each parallel thread (other than the parent thread)
// ... that indicates whether the thread is currently active
FatalError* _exception; // a pointer to a heap-allocated copy of the exception thrown by a work thread
// ... or zero if no exception was thrown
bool _terminate; // becomes true when the parallel threads must exit
// data member shared by all threads; incrementing is atomic (no need for protection)
std::atomic<size_t> _next; // the current index of the for loop being implemented
};
////////////////////////////////////////////////////////////////////
// outermost portion of the call() template function implementation
template<class T> void Parallel::call(T* targetObject, void (T::*targetMember)(size_t index), ProcessAssigner* assigner)
{
Target<T> target(targetObject, targetMember);
call(&target, assigner);
}
////////////////////////////////////////////////////////////////////
#endif // PARALLEL_HPP
|
/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#ifndef PARALLEL_HPP
#define PARALLEL_HPP
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <thread>
#include "ParallelTarget.hpp"
class FatalError;
class ParallelFactory;
class ProcessAssigner;
////////////////////////////////////////////////////////////////////
/** This class supports a simple parallel execution model similar to a for loop. The body of the
for loop consists of the body() function of a ParallelTarget subclass, or alternatively of
some class member function (specified by the caller) with a single integer argument, which
gets passed the index of the current iteration.
For example, to invoke a member function 1000 times one would write something like:
\code
void Test::body(size_t index) { ... }
...
IdenticalAssigner assigner;
ParallelFactory factory;
...
assigner.assign(1000);
factory.parallel()->call(this, &Test::body, &assigner);
\endcode
A Parallel instance can be created only through the ParallelFactory class. The default
construction shown above determines a reasonable number of threads for the computer on which
the code is running, and the call() function distributes the work over these threads.
The parallelized body should protect (write-) access to shared data through the use of an
std::mutex object. Shared data includes the data members of the target object (in the context
of which the target function executes) and essentially everything other than local variables.
Also note that the parallelized body includes all functions directly or indirectly called by
the target function.
When an exception is thrown by one of the threads excuting the parallelized body, all other
threads are gracefully shut down and a FatalError exception is thrown in the context of the
thread that invoked the call() function. If the original exception was a FatalError instance, the
newly thrown exception is a copy thereof. Otherwise a fresh FatalError instance is created with
a generic error message.
Between invocations of the call() function, the parallel threads are put in wait so that
they consume no CPU cycles (and very little memory). Thus a
particular Parallel instance can be reused many times for calling various member functions in
various objects, reducing the overhead of creating and destroying the threads. One can also
use multiple Parallel instances in an application. For example, a parallelized body can invoke
the call() function on another Parallel instance that is constructed and destructed within the
scope of the loop body. Recursively invoking the call() function on the same Parallel instance is
not allowed and results in undefined behavior.
The Parallel class uses C++11 multi-threading capabilities, avoiding the complexities of using
yet another library (such as OpenMP) and making it possible to properly handle exceptions. It
is designed to minimize the run-time overhead for loops with many iterations. */
class Parallel
{
friend class ParallelFactory;
//============= Construction - Setup - Destruction =============
private:
/** Constructs a Parallel instance with the specified number of execution threads. The
constructor is not public; use the ParallelFactory::parallel() function instead. */
Parallel(int threadCount, ParallelFactory* factory);
public:
/** Destructs the instance and its parallel threads. */
~Parallel();
//======================== Other Functions =======================
public:
/** Returns the number of threads used by this instance. */
int threadCount() const;
/** Calls the body() function of the specified specified target object a certain number of times,
with the \em index argument of that function taking values that are determined by the \em
assigner, which is also passed to this function. While the values assigned to a particular
process are fixed at the moment this function is called, the work will be distributed over the
parallel threads in an unpredicable manner. */
void call(ParallelTarget* target, ProcessAssigner* assigner);
/** Calls the specified member function for the specified target object a certain number of times,
with the \em index argument of that function taking values that are determined by the \em
assigner, which is also passed to this function. While the values assigned to a particular
process are fixed at the moment this function is called, the work will be distributed over the
parallel threads in an unpredicable manner. */
template<class T> void call(T* targetObject, void (T::*targetMember)(size_t index), ProcessAssigner* assigner);
private:
/** The function that gets executed inside each of the parallel threads. */
void run(int threadIndex);
/** The function to do the actual work; used by call() and run(). */
void doWork();
/** A function to report an exception; used by doWork(). */
void reportException(FatalError* exception);
/** A function to wait for the parallel threads; used by constructor and call(). */
void waitForThreads();
/** This helper function returns true if at least one of the parallel threads (not including
the parent thread) is still active, and false if not. This function does not perform any
locking; callers should lock the shared data members of this class instance. */
bool threadsActive();
//======================== Nested Classes =======================
private:
/** The declaration for this template class is nested in the Parallel class declaration. It is
used in the implementation of the call() template function to allow specifying a loop body
in the form of an arbitrary target member function and target object. An instance of this
target-type-dependent class bundles the relevant information into a single object with a
type-independent base class (ParallelTarget) so that it can be passed to the regular (i.e.
non-template) call() function. */
template<class T> class Target : public ParallelTarget
{
public:
/** Constructs a ParallelTarget instance with a body() function that calls the specified
target member function on the specified target object. */
Target(T* targetObject, void (T::*targetMember)(size_t index))
: _targetObject(targetObject), _targetMember(targetMember) { }
/** Calls the target member function on the target object specified in the constructor. */
void body(size_t index) { (_targetObject->*(_targetMember))(index); }
private:
T* _targetObject;
void (T::*_targetMember)(size_t index);
};
//======================== Data Members ========================
private:
// data members keeping track of the threads
int _threadCount; // the total number of threads, including the parent thread
std::thread::id _parentThread; // the ID of the thread that invoked our constructor
std::vector<std::thread> _threads; // the parallel threads (other than the parent thread)
// synchronization
std::mutex _mutex; // the mutex to synchronize with the parallel threads
std::condition_variable _conditionExtra; // the wait condition used by the parallel threads
std::condition_variable _conditionMain; // the wait condition used by the main thread
// data members shared by all threads; changes are protected by a mutex
ParallelTarget* _target; // the target to be called
ProcessAssigner* _assigner; // the process assigner
size_t _limit; // the limit of the for loop being implemented
std::vector<bool> _active; // flag for each parallel thread (other than the parent thread)
// ... that indicates whether the thread is currently active
FatalError* _exception; // a pointer to a heap-allocated copy of the exception thrown by a work thread
// ... or zero if no exception was thrown
bool _terminate; // becomes true when the parallel threads must exit
// data member shared by all threads; incrementing is atomic (no need for protection)
std::atomic<size_t> _next; // the current index of the for loop being implemented
};
////////////////////////////////////////////////////////////////////
// outermost portion of the call() template function implementation
template<class T> void Parallel::call(T* targetObject, void (T::*targetMember)(size_t index), ProcessAssigner* assigner)
{
Target<T> target(targetObject, targetMember);
call(&target, assigner);
}
////////////////////////////////////////////////////////////////////
#endif // PARALLEL_HPP
|
fix compilation error with gcc on Ubuntu
|
fix compilation error with gcc on Ubuntu
|
C++
|
agpl-3.0
|
SKIRT/SKIRT,SKIRT/SKIRT,SKIRT/SKIRT
|
5cd25ff51ad9f2a2ef0d9a07e843b09a3e20c944
|
src/Exception.cpp
|
src/Exception.cpp
|
#include <ca-mgm/Exception.hpp>
namespace
{
char* dupString(const char* str)
{
if (!str)
{
return 0;
}
char* rv = new (std::nothrow) char[strlen(str)+1];
if (!rv)
{
return 0;
}
strcpy(rv, str);
return rv;
}
static void freeBuf(char** ptr)
{
delete [] *ptr;
*ptr = NULL;
}
}
namespace CA_MGM_NAMESPACE
{
Exception::Exception(const char* file, int line, const char* msg, int errorCode, const Exception* subException)
: std::exception()
, m_file(dupString(file))
, m_line(line)
, m_msg(dupString(msg))
, m_errorCode(errorCode)
{
if( subException != NULL )
{
try
{
m_msg = dupString(str::form("%s\n\t%s", m_msg, subException->getFullMessage().c_str()).c_str());
}
catch (...)
{}
}
}
Exception::Exception( const Exception& e )
: std::exception(e)
, m_file(dupString(e.m_file))
, m_line(e.m_line)
, m_msg(dupString(e.m_msg))
, m_errorCode(e.m_errorCode)
{}
Exception::~Exception() throw()
{
try
{
freeBuf(&m_file);
freeBuf(&m_msg);
}
catch (...)
{
// don't let exceptions escape
}
}
Exception&
Exception::operator=(const Exception& rhs)
{
if(this == &rhs) return *this;
m_file = rhs.m_file;
m_line = rhs.m_line;
m_msg = rhs.m_msg;
m_errorCode = rhs.m_errorCode;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
const char*
Exception::type() const
{
return "Exception";
}
//////////////////////////////////////////////////////////////////////////////
int
Exception::getLine() const
{
return m_line;
}
//////////////////////////////////////////////////////////////////////////////
const char*
Exception::getMessage() const
{
return (m_msg != NULL) ? m_msg : "";
}
//////////////////////////////////////////////////////////////////////////////
std::string
Exception::getFullMessage() const
{
try
{
return str::form("%s: %s %s: %s%s",
(getFile() == '\0')?"[no file]":getFile(),
(getLine() == 0)?"[no line]":str::numstring(getLine()).c_str(),
type(),
(getErrorCode() != 0)?(str::numstring(getErrorCode())+": ").c_str():" ",
(getMessage() == '\0')?"[no message]":getMessage()
);
}
catch (...)
{}
return "";
}
//////////////////////////////////////////////////////////////////////////////
const char*
Exception::getFile() const
{
return (m_file != NULL) ? m_file : "";
}
//////////////////////////////////////////////////////////////////////////////
std::ostream&
operator<<(std::ostream& os, const Exception& e)
{
if (*e.getFile() == '\0')
{
os << "[no file]: ";
}
else
{
os << e.getFile() << ": ";
}
if (e.getLine() == 0)
{
os << "[no line] ";
}
else
{
os << e.getLine() << ' ';
}
os << e.type() << ": ";
if (e.getErrorCode() != 0)
{
os << e.getErrorCode() << ": ";
}
if (*e.getMessage() == '\0')
{
os << "[no message]";
}
else
{
os << e.getMessage();
}
return os;
}
//////////////////////////////////////////////////////////////////////////////
const char*
Exception::what() const throw()
{
return getMessage();
}
//////////////////////////////////////////////////////////////////////////////
int
Exception::getErrorCode() const
{
return m_errorCode;
}
CA_MGM_DEFINE_EXCEPTION(Memory);
CA_MGM_DEFINE_EXCEPTION(Runtime);
CA_MGM_DEFINE_EXCEPTION(Overflow);
CA_MGM_DEFINE_EXCEPTION(Syntax);
CA_MGM_DEFINE_EXCEPTION(Value);
CA_MGM_DEFINE_EXCEPTION(System);
CA_MGM_DEFINE_EXCEPTION(OutOfBounds);
}
|
#include <ca-mgm/Exception.hpp>
namespace
{
char* dupString(const char* str)
{
if (!str)
{
return 0;
}
char* rv = new (std::nothrow) char[strlen(str)+1];
if (!rv)
{
return 0;
}
strcpy(rv, str);
return rv;
}
static void freeBuf(char** ptr)
{
delete [] *ptr;
*ptr = NULL;
}
}
namespace CA_MGM_NAMESPACE
{
Exception::Exception(const char* file, int line, const char* msg, int errorCode, const Exception* subException)
: std::exception()
, m_file(dupString(file))
, m_line(line)
, m_msg(dupString(msg))
, m_errorCode(errorCode)
{
if( subException != NULL )
{
try
{
m_msg = dupString(str::form("%s\n\t%s", m_msg, subException->getFullMessage().c_str()).c_str());
}
catch (...)
{}
}
}
Exception::Exception( const Exception& e )
: std::exception(e)
, m_file(dupString(e.m_file))
, m_line(e.m_line)
, m_msg(dupString(e.m_msg))
, m_errorCode(e.m_errorCode)
{}
Exception::~Exception() throw()
{
try
{
freeBuf(&m_file);
freeBuf(&m_msg);
}
catch (...)
{
// don't let exceptions escape
}
}
Exception&
Exception::operator=(const Exception& rhs)
{
if(this == &rhs) return *this;
m_file = rhs.m_file;
m_line = rhs.m_line;
m_msg = rhs.m_msg;
m_errorCode = rhs.m_errorCode;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
const char*
Exception::type() const
{
return "Exception";
}
//////////////////////////////////////////////////////////////////////////////
int
Exception::getLine() const
{
return m_line;
}
//////////////////////////////////////////////////////////////////////////////
const char*
Exception::getMessage() const
{
return (m_msg != NULL) ? m_msg : "";
}
//////////////////////////////////////////////////////////////////////////////
std::string
Exception::getFullMessage() const
{
try
{
return str::form("%s: %s %s: %s%s",
(getFile() == NULL)?"[no file]":getFile(),
(getLine() == 0)?"[no line]":str::numstring(getLine()).c_str(),
type(),
(getErrorCode() != 0)?(str::numstring(getErrorCode())+": ").c_str():" ",
(getMessage() == NULL)?"[no message]":getMessage()
);
}
catch (...)
{}
return "";
}
//////////////////////////////////////////////////////////////////////////////
const char*
Exception::getFile() const
{
return (m_file != NULL) ? m_file : "";
}
//////////////////////////////////////////////////////////////////////////////
std::ostream&
operator<<(std::ostream& os, const Exception& e)
{
if (*e.getFile() == '\0')
{
os << "[no file]: ";
}
else
{
os << e.getFile() << ": ";
}
if (e.getLine() == 0)
{
os << "[no line] ";
}
else
{
os << e.getLine() << ' ';
}
os << e.type() << ": ";
if (e.getErrorCode() != 0)
{
os << e.getErrorCode() << ": ";
}
if (*e.getMessage() == '\0')
{
os << "[no message]";
}
else
{
os << e.getMessage();
}
return os;
}
//////////////////////////////////////////////////////////////////////////////
const char*
Exception::what() const throw()
{
return getMessage();
}
//////////////////////////////////////////////////////////////////////////////
int
Exception::getErrorCode() const
{
return m_errorCode;
}
CA_MGM_DEFINE_EXCEPTION(Memory);
CA_MGM_DEFINE_EXCEPTION(Runtime);
CA_MGM_DEFINE_EXCEPTION(Overflow);
CA_MGM_DEFINE_EXCEPTION(Syntax);
CA_MGM_DEFINE_EXCEPTION(Value);
CA_MGM_DEFINE_EXCEPTION(System);
CA_MGM_DEFINE_EXCEPTION(OutOfBounds);
}
|
fix build with GCC7
|
fix build with GCC7
|
C++
|
lgpl-2.1
|
openSUSE/libcamgm,openSUSE/libcamgm,openSUSE/libcamgm,openSUSE/libcamgm
|
681510d90c1cc54984c99cb50d562db9f1a1c9d9
|
src/Game/Game.cpp
|
src/Game/Game.cpp
|
#include "Game/Game.h"
#include <string>
#include <stdexcept>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
#include <vector>
#ifndef _WIN32
#include <csignal>
#endif // _WIN32
#include "Players/Player.h"
#include "Players/Outside_Communicator.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Game/Color.h"
#include "Game/Game_Result.h"
#include "Moves/Move.h"
#include "Utility/String.h"
#include "Exceptions/Game_Ended.h"
Game_Result play_game(Board board,
Clock game_clock,
const Player& white,
const Player& black,
bool pondering_allowed,
const std::string& event_name,
const std::string& location,
const std::string& pgn_file_name)
{
if(board.whose_turn() != game_clock.running_for())
{
throw std::invalid_argument("Board and Clock disagree on whose turn it is.");
}
std::vector<const Move*> game_record;
try
{
game_clock.start();
Game_Result result;
while( ! result.game_has_ended())
{
auto& player = board.whose_turn() == WHITE ? white : black;
auto& thinker = board.whose_turn() == WHITE ? black : white;
thinker.ponder(board, game_clock, pondering_allowed);
const auto& move_chosen = player.choose_move(board, game_clock);
result = game_clock.punch(board);
if( ! result.game_has_ended())
{
result = board.submit_move(move_chosen);
}
game_record.push_back(&move_chosen);
}
game_clock.stop();
board.print_game_record(game_record,
&white,
&black,
pgn_file_name,
result,
game_clock,
event_name,
location);
return result;
}
catch(const std::exception& game_error)
{
board.print_game_record(game_record,
&white,
&black,
pgn_file_name,
{},
game_clock,
event_name,
location,
game_error.what());
throw;
}
}
void play_game_with_outsider(const Player& player,
const std::string& event_name,
const std::string& location,
const std::string& game_file_name)
{
#ifndef _WIN32
signal(SIGTSTP, SIG_IGN);
#endif // _WIN32
auto outsider = connect_to_outside(player);
Board board;
Clock clock;
Game_Result game_result;
std::vector<const Move*> game_record;
auto player_color = NONE;
while(true)
{
try
{
game_result = outsider->setup_turn(board, clock, game_record, player);
if(game_result.game_has_ended())
{
throw Game_Ended("");
}
outsider->listen(board, clock);
player_color = board.whose_turn();
const auto& chosen_move = player.choose_move(board, clock);
clock.punch(board);
game_result = outsider->handle_move(board, chosen_move, game_record, player);
if(game_result.game_has_ended())
{
throw Game_Ended("");
}
player.ponder(board, clock, outsider->pondering_allowed());
}
catch(const Game_Ended& game_end)
{
std::string reason = game_end.what();
if( ! reason.empty())
{
outsider->log("Game ended with: " + reason);
}
auto exit = false;
if(reason == "quit")
{
reason.clear();
exit = true;
}
if( ! game_file_name.empty())
{
clock.stop();
auto white = (player_color == WHITE ? &player : nullptr);
auto black = (player_color == BLACK ? &player : nullptr);
board.print_game_record(game_record,
white, black,
String::add_to_file_name(game_file_name, "-" + color_text(player_color)),
game_result,
clock,
event_name,
location,
reason);
}
if(exit)
{
return;
}
}
}
}
|
#include "Game/Game.h"
#include <string>
#include <stdexcept>
#include <thread>
#include <chrono>
using namespace std::chrono_literals;
#include <vector>
#ifndef _WIN32
#include <csignal>
#endif // _WIN32
#include "Players/Player.h"
#include "Players/Outside_Communicator.h"
#include "Game/Board.h"
#include "Game/Clock.h"
#include "Game/Color.h"
#include "Game/Game_Result.h"
#include "Moves/Move.h"
#include "Utility/String.h"
#include "Exceptions/Game_Ended.h"
Game_Result play_game(Board board,
Clock game_clock,
const Player& white,
const Player& black,
bool pondering_allowed,
const std::string& event_name,
const std::string& location,
const std::string& pgn_file_name)
{
if(board.whose_turn() != game_clock.running_for())
{
throw std::invalid_argument("Board and Clock disagree on whose turn it is.");
}
std::vector<const Move*> game_record;
try
{
game_clock.start();
Game_Result result;
while( ! result.game_has_ended())
{
auto& player = board.whose_turn() == WHITE ? white : black;
auto& thinker = board.whose_turn() == WHITE ? black : white;
thinker.ponder(board, game_clock, pondering_allowed);
const auto& move_chosen = player.choose_move(board, game_clock);
result = game_clock.punch(board);
if( ! result.game_has_ended())
{
result = board.submit_move(move_chosen);
}
game_record.push_back(&move_chosen);
}
game_clock.stop();
board.print_game_record(game_record,
&white,
&black,
pgn_file_name,
result,
game_clock,
event_name,
location);
return result;
}
catch(const std::exception& game_error)
{
board.print_game_record(game_record,
&white,
&black,
pgn_file_name,
{},
game_clock,
event_name,
location,
game_error.what());
throw;
}
}
void play_game_with_outsider(const Player& player,
const std::string& event_name,
const std::string& location,
const std::string& game_file_name)
{
auto outsider = connect_to_outside(player);
Board board;
Clock clock;
Game_Result game_result;
std::vector<const Move*> game_record;
auto player_color = NONE;
while(true)
{
try
{
game_result = outsider->setup_turn(board, clock, game_record, player);
if(game_result.game_has_ended())
{
throw Game_Ended("");
}
outsider->listen(board, clock);
player_color = board.whose_turn();
const auto& chosen_move = player.choose_move(board, clock);
clock.punch(board);
game_result = outsider->handle_move(board, chosen_move, game_record, player);
if(game_result.game_has_ended())
{
throw Game_Ended("");
}
player.ponder(board, clock, outsider->pondering_allowed());
}
catch(const Game_Ended& game_end)
{
std::string reason = game_end.what();
if( ! reason.empty())
{
outsider->log("Game ended with: " + reason);
}
auto exit = false;
if(reason == "quit")
{
reason.clear();
exit = true;
}
if( ! game_file_name.empty())
{
clock.stop();
auto white = (player_color == WHITE ? &player : nullptr);
auto black = (player_color == BLACK ? &player : nullptr);
board.print_game_record(game_record,
white, black,
String::add_to_file_name(game_file_name, "-" + color_text(player_color)),
game_result,
clock,
event_name,
location,
reason);
}
if(exit)
{
return;
}
}
}
}
|
Delete useless signal call
|
Delete useless signal call
|
C++
|
mit
|
MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess
|
be3b79409a78aa7fc3b479ff57edcfbbb83f3eac
|
tests/src/launch_bounds/hip_launch_bounds.cpp
|
tests/src/launch_bounds/hip_launch_bounds.cpp
|
/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Simple test for memset.
// Also serves as a template for other tests.
#include "hip_runtime.h"
#include "test_common.h"
__global__
void
myKern(hipLaunchParm lp, int *C, const int *A, int N)
{
int tid = hipThreadIdx_x;
C[tid] = A[tid];
};
int main(int argc, char *argv[])
{
HipTest::parseStandardArguments(argc, argv, true);
size_t Nbytes = N*sizeof(int);
int *A_d, *C_d, *A_h, *C_h;
HIPCHECK ( hipMalloc(&A_d, Nbytes) );
HIPCHECK ( hipMalloc(&C_d, Nbytes) );
A_h = (int*)malloc (Nbytes);
C_h = (int*)malloc (Nbytes);
for (int i=0; i<N; i++) {
A_h[i] = i*10;
C_h[i] = 0x0;
}
HIPCHECK ( hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice) );
hipLaunchKernel(myKern, dim3(N), dim3(256), 0, 0, A_d, C_d, N);
HIPCHECK ( hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost) );
for (int i=0; i<N; i++) {
int goldVal = i * 10;
if (A_h[i] != goldVal) {
failed("mismatch at index:%d computed:%02x, gold:%02x\n", i, (int)A_h[i], (int)goldVal);
}
}
passed();
};
|
/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Test launch bounds and initialization conditions.
#include "hip_runtime.h"
#include "test_common.h"
int p_blockSize = 256;
__global__
void
__launch_bounds__(256, 2)
myKern(hipLaunchParm lp, int *C, const int *A, int N, int xfactor)
{
int tid = (hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x);
if (tid < N) {
C[tid] = A[tid];
}
};
void parseMyArguments(int argc, char *argv[])
{
int more_argc = HipTest::parseStandardArguments(argc, argv, false);
// parse args for this test:
for (int i = 1; i < more_argc; i++) {
const char *arg = argv[i];
if (!strcmp(arg, "--blockSize")) {
if (++i >= argc || !HipTest::parseInt(argv[i], &p_blockSize)) {
failed("Bad peerDevice argument");
}
} else {
failed("Bad argument '%s'", arg);
}
};
};
int main(int argc, char *argv[])
{
parseMyArguments(argc, argv);
size_t Nbytes = N*sizeof(int);
int *A_d, *C_d, *A_h, *C_h;
HIPCHECK ( hipMalloc(&A_d, Nbytes) );
HIPCHECK ( hipMalloc(&C_d, Nbytes) );
A_h = (int*)malloc (Nbytes);
C_h = (int*)malloc (Nbytes);
for (int i=0; i<N; i++) {
A_h[i] = i*10;
C_h[i] = 0x0;
}
int blocks = N / p_blockSize;
printf ("running with N=%zu p_blockSize=%d blocks=%d\n", N, p_blockSize, blocks);
HIPCHECK ( hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice) );
HIPCHECK ( hipGetLastError() );
hipLaunchKernel(myKern, dim3(blocks), dim3(p_blockSize), 0, 0, C_d, A_d, N, 0);
cudaFuncAttributes attrib;
cudaFuncGetAttributes (&attrib, myKern);
printf ("binaryVersion = %d\n", attrib.binaryVersion);
printf ("cacheModeCA = %d\n", attrib.cacheModeCA);
printf ("constSizeBytes = %zu\n", attrib.constSizeBytes);
printf ("localSizeBytes = %zud\n", attrib.localSizeBytes);
printf ("maxThreadsPerBlock = %d\n", attrib.maxThreadsPerBlock);
printf ("numRegs = %d\n", attrib.numRegs);
printf ("ptxVersion = %d\n", attrib.ptxVersion);
printf ("sharedSizeBytes = %zud\n", attrib.sharedSizeBytes);
HIPCHECK ( hipDeviceSynchronize() );
HIPCHECK ( hipGetLastError() );
HIPCHECK ( hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost) );
HIPCHECK ( hipDeviceSynchronize() );
for (int i=0; i<N; i++) {
int goldVal = i * 10;
if (C_h[i] != goldVal) {
failed("mismatch at index:%d computed:%02d, gold:%02d\n", i, (int)C_h[i], (int)goldVal);
}
}
passed();
};
|
Update launch_bounds test
|
Update launch_bounds test
|
C++
|
mit
|
ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,GPUOpen-ProfessionalCompute-Tools/HIP,ROCm-Developer-Tools/HIP
|
45af104a75e0d6094b1a8c3e1d3251c80d159abe
|
src/vendor/cget/cget/pkg/pqrs-org__cpp-osx-iokit_hid_queue_value_monitor/install/include/pqrs/osx/iokit_hid_queue_value_monitor.hpp
|
src/vendor/cget/cget/pkg/pqrs-org__cpp-osx-iokit_hid_queue_value_monitor/install/include/pqrs/osx/iokit_hid_queue_value_monitor.hpp
|
#pragma once
// pqrs::iokit_hid_queue_value_monitor v1.9
// (C) Copyright Takayama Fumihiko 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See http://www.boost.org/LICENSE_1_0.txt)
#include <IOKit/hid/IOHIDDevice.h>
#include <IOKit/hid/IOHIDQueue.h>
#include <chrono>
#include <nod/nod.hpp>
#include <optional>
#include <pqrs/cf/run_loop_thread.hpp>
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/iokit_hid_device.hpp>
#include <pqrs/osx/iokit_return.hpp>
#include <pqrs/osx/iokit_types.hpp>
namespace pqrs {
namespace osx {
class iokit_hid_queue_value_monitor final : public dispatcher::extra::dispatcher_client {
public:
// Signals (invoked from the dispatcher thread)
nod::signal<void(void)> started;
nod::signal<void(void)> stopped;
nod::signal<void(std::shared_ptr<std::vector<cf::cf_ptr<IOHIDValueRef>>>)> values_arrived;
nod::signal<void(const std::string&, iokit_return)> error_occurred;
// Methods
iokit_hid_queue_value_monitor(const iokit_hid_queue_value_monitor&) = delete;
iokit_hid_queue_value_monitor(std::weak_ptr<dispatcher::dispatcher> weak_dispatcher,
IOHIDDeviceRef device) : dispatcher_client(weak_dispatcher),
hid_device_(device),
device_scheduled_(false),
open_timer_(*this),
last_open_error_(kIOReturnSuccess) {
cf_run_loop_thread_ = std::make_unique<cf::run_loop_thread>();
// Schedule device
cf_run_loop_thread_->enqueue(^{
if (hid_device_.get_device()) {
IOHIDDeviceRegisterRemovalCallback(*(hid_device_.get_device()),
static_device_removal_callback,
this);
IOHIDDeviceScheduleWithRunLoop(*(hid_device_.get_device()),
cf_run_loop_thread_->get_run_loop(),
kCFRunLoopCommonModes);
device_scheduled_ = true;
}
});
}
virtual ~iokit_hid_queue_value_monitor(void) {
// dispatcher_client
detach_from_dispatcher();
// cf_run_loop_thread
cf_run_loop_thread_->enqueue(^{
stop();
if (hid_device_.get_device()) {
// Note:
// IOHIDDeviceUnscheduleFromRunLoop causes SIGILL if IOHIDDeviceScheduleWithRunLoop is not called before.
// Thus, we have to check the state by `device_scheduled_`.
if (device_scheduled_) {
IOHIDDeviceUnscheduleFromRunLoop(*(hid_device_.get_device()),
cf_run_loop_thread_->get_run_loop(),
kCFRunLoopCommonModes);
}
}
});
cf_run_loop_thread_->terminate();
cf_run_loop_thread_ = nullptr;
}
void async_start(IOOptionBits open_options,
std::chrono::milliseconds open_timer_interval) {
open_timer_.start(
[this, open_options] {
cf_run_loop_thread_->enqueue(^{
start(open_options);
});
},
open_timer_interval);
}
void async_stop(void) {
cf_run_loop_thread_->enqueue(^{
stop();
});
}
private:
void start(IOOptionBits open_options) {
if (hid_device_.get_device()) {
if (!open_options_) {
iokit_return r = IOHIDDeviceOpen(*(hid_device_.get_device()),
open_options);
if (!r) {
if (last_open_error_ != r) {
last_open_error_ = r;
enqueue_to_dispatcher([this, r] {
error_occurred("IOHIDDeviceOpen is failed.", r);
});
}
// Retry
return;
}
open_options_ = open_options;
start_queue();
enqueue_to_dispatcher([this] {
started();
});
}
}
open_timer_.stop();
}
void stop(void) {
if (hid_device_.get_device()) {
stop_queue();
if (open_options_) {
IOHIDDeviceClose(*(hid_device_.get_device()),
*open_options_);
open_options_ = std::nullopt;
enqueue_to_dispatcher([this] {
stopped();
});
}
}
open_timer_.stop();
}
void start_queue(void) {
if (!queue_) {
const CFIndex depth = 1024;
queue_ = hid_device_.make_queue(depth);
if (queue_) {
for (const auto& e : hid_device_.make_elements()) {
IOHIDQueueAddElement(*queue_, *e);
}
IOHIDQueueRegisterValueAvailableCallback(*queue_,
static_queue_value_available_callback,
this);
IOHIDQueueScheduleWithRunLoop(*queue_,
cf_run_loop_thread_->get_run_loop(),
kCFRunLoopCommonModes);
IOHIDQueueStart(*queue_);
}
}
}
void stop_queue(void) {
if (queue_) {
IOHIDQueueStop(*queue_);
// IOHIDQueueUnscheduleFromRunLoop might cause SIGSEGV if it is not called in cf_run_loop_thread_.
IOHIDQueueUnscheduleFromRunLoop(*queue_,
cf_run_loop_thread_->get_run_loop(),
kCFRunLoopCommonModes);
queue_ = nullptr;
}
}
static void static_device_removal_callback(void* context,
IOReturn result,
void* sender) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<iokit_hid_queue_value_monitor*>(context);
if (!self) {
return;
}
self->cf_run_loop_thread_->enqueue(^{
self->device_removal_callback();
});
}
void device_removal_callback(void) {
stop();
}
static void static_queue_value_available_callback(void* context,
IOReturn result,
void* sender) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<iokit_hid_queue_value_monitor*>(context);
if (!self) {
return;
}
self->cf_run_loop_thread_->enqueue(^{
self->queue_value_available_callback();
});
}
void queue_value_available_callback(void) {
if (queue_) {
auto values = std::make_shared<std::vector<cf::cf_ptr<IOHIDValueRef>>>();
while (auto v = IOHIDQueueCopyNextValueWithTimeout(*queue_, 0.0)) {
values->emplace_back(v);
CFRelease(v);
}
enqueue_to_dispatcher([this, values] {
values_arrived(values);
});
}
}
iokit_hid_device hid_device_;
std::unique_ptr<cf::run_loop_thread> cf_run_loop_thread_;
bool device_scheduled_;
dispatcher::extra::timer open_timer_;
std::optional<IOOptionBits> open_options_;
iokit_return last_open_error_;
cf::cf_ptr<IOHIDQueueRef> queue_;
};
} // namespace osx
} // namespace pqrs
|
#pragma once
// pqrs::iokit_hid_queue_value_monitor v1.10
// (C) Copyright Takayama Fumihiko 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See http://www.boost.org/LICENSE_1_0.txt)
#include <IOKit/hid/IOHIDDevice.h>
#include <IOKit/hid/IOHIDQueue.h>
#include <chrono>
#include <nod/nod.hpp>
#include <optional>
#include <pqrs/cf/run_loop_thread.hpp>
#include <pqrs/dispatcher.hpp>
#include <pqrs/osx/iokit_hid_device.hpp>
#include <pqrs/osx/iokit_return.hpp>
#include <pqrs/osx/iokit_types.hpp>
namespace pqrs {
namespace osx {
class iokit_hid_queue_value_monitor final : public dispatcher::extra::dispatcher_client {
public:
// Signals (invoked from the dispatcher thread)
nod::signal<void(void)> started;
nod::signal<void(void)> stopped;
nod::signal<void(std::shared_ptr<std::vector<cf::cf_ptr<IOHIDValueRef>>>)> values_arrived;
nod::signal<void(const std::string&, iokit_return)> error_occurred;
// Methods
iokit_hid_queue_value_monitor(const iokit_hid_queue_value_monitor&) = delete;
iokit_hid_queue_value_monitor(std::weak_ptr<dispatcher::dispatcher> weak_dispatcher,
IOHIDDeviceRef device) : dispatcher_client(weak_dispatcher),
hid_device_(device),
device_scheduled_(false),
open_timer_(*this),
last_open_error_(kIOReturnSuccess) {
cf_run_loop_thread_ = std::make_unique<cf::run_loop_thread>();
// Schedule device
cf_run_loop_thread_->enqueue(^{
if (hid_device_.get_device()) {
IOHIDDeviceRegisterRemovalCallback(*(hid_device_.get_device()),
static_device_removal_callback,
this);
IOHIDDeviceScheduleWithRunLoop(*(hid_device_.get_device()),
cf_run_loop_thread_->get_run_loop(),
kCFRunLoopCommonModes);
device_scheduled_ = true;
}
});
}
virtual ~iokit_hid_queue_value_monitor(void) {
// dispatcher_client
detach_from_dispatcher();
// cf_run_loop_thread
cf_run_loop_thread_->enqueue(^{
stop();
if (hid_device_.get_device()) {
// Note:
// IOHIDDeviceUnscheduleFromRunLoop causes SIGILL if IOHIDDeviceScheduleWithRunLoop is not called before.
// Thus, we have to check the state by `device_scheduled_`.
if (device_scheduled_) {
IOHIDDeviceUnscheduleFromRunLoop(*(hid_device_.get_device()),
cf_run_loop_thread_->get_run_loop(),
kCFRunLoopCommonModes);
}
}
});
cf_run_loop_thread_->terminate();
cf_run_loop_thread_ = nullptr;
}
void async_start(IOOptionBits open_options,
std::chrono::milliseconds open_timer_interval) {
open_timer_.start(
[this, open_options] {
cf_run_loop_thread_->enqueue(^{
start(open_options);
});
},
open_timer_interval);
}
void async_stop(void) {
cf_run_loop_thread_->enqueue(^{
stop();
});
}
private:
void start(IOOptionBits open_options) {
if (hid_device_.get_device()) {
// Start queue before `IOHIDDeviceOpen` in order to avoid events drop.
start_queue();
if (!open_options_) {
iokit_return r = IOHIDDeviceOpen(*(hid_device_.get_device()),
open_options);
if (!r) {
if (last_open_error_ != r) {
last_open_error_ = r;
enqueue_to_dispatcher([this, r] {
error_occurred("IOHIDDeviceOpen is failed.", r);
});
}
// Retry
return;
}
open_options_ = open_options;
enqueue_to_dispatcher([this] {
started();
});
}
}
open_timer_.stop();
}
void stop(void) {
if (hid_device_.get_device()) {
stop_queue();
if (open_options_) {
IOHIDDeviceClose(*(hid_device_.get_device()),
*open_options_);
open_options_ = std::nullopt;
enqueue_to_dispatcher([this] {
stopped();
});
}
}
open_timer_.stop();
}
void start_queue(void) {
if (!queue_) {
const CFIndex depth = 1024;
queue_ = hid_device_.make_queue(depth);
if (queue_) {
for (const auto& e : hid_device_.make_elements()) {
IOHIDQueueAddElement(*queue_, *e);
}
IOHIDQueueRegisterValueAvailableCallback(*queue_,
static_queue_value_available_callback,
this);
IOHIDQueueScheduleWithRunLoop(*queue_,
cf_run_loop_thread_->get_run_loop(),
kCFRunLoopCommonModes);
IOHIDQueueStart(*queue_);
}
}
}
void stop_queue(void) {
if (queue_) {
IOHIDQueueStop(*queue_);
// IOHIDQueueUnscheduleFromRunLoop might cause SIGSEGV if it is not called in cf_run_loop_thread_.
IOHIDQueueUnscheduleFromRunLoop(*queue_,
cf_run_loop_thread_->get_run_loop(),
kCFRunLoopCommonModes);
queue_ = nullptr;
}
}
static void static_device_removal_callback(void* context,
IOReturn result,
void* sender) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<iokit_hid_queue_value_monitor*>(context);
if (!self) {
return;
}
self->cf_run_loop_thread_->enqueue(^{
self->device_removal_callback();
});
}
void device_removal_callback(void) {
stop();
}
static void static_queue_value_available_callback(void* context,
IOReturn result,
void* sender) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<iokit_hid_queue_value_monitor*>(context);
if (!self) {
return;
}
self->cf_run_loop_thread_->enqueue(^{
self->queue_value_available_callback();
});
}
void queue_value_available_callback(void) {
if (queue_) {
auto values = std::make_shared<std::vector<cf::cf_ptr<IOHIDValueRef>>>();
while (auto v = IOHIDQueueCopyNextValueWithTimeout(*queue_, 0.0)) {
values->emplace_back(v);
CFRelease(v);
}
enqueue_to_dispatcher([this, values] {
values_arrived(values);
});
}
}
iokit_hid_device hid_device_;
std::unique_ptr<cf::run_loop_thread> cf_run_loop_thread_;
bool device_scheduled_;
dispatcher::extra::timer open_timer_;
std::optional<IOOptionBits> open_options_;
iokit_return last_open_error_;
cf::cf_ptr<IOHIDQueueRef> queue_;
};
} // namespace osx
} // namespace pqrs
|
update vendor/cget
|
update vendor/cget
|
C++
|
unlicense
|
tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements,tekezo/Karabiner-Elements
|
bee7ee71f5614f5ae680048097914e484f9bb420
|
TelepathyQt4/Client/dbus-proxy.cpp
|
TelepathyQt4/Client/dbus-proxy.cpp
|
/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008 Nokia Corporation
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/Client/DBusProxy>
#include "TelepathyQt4/Client/_gen/dbus-proxy.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <QtCore/QTimer>
#include <QtDBus/QDBusConnectionInterface>
namespace Telepathy
{
namespace Client
{
struct DBusProxy::Private
{
// Public object
DBusProxy& parent;
QDBusConnection dbusConnection;
QString busName;
QString objectPath;
Private(const QDBusConnection& dbusConnection, const QString& busName,
const QString& objectPath, DBusProxy& p)
: parent(p),
dbusConnection(dbusConnection),
busName(busName),
objectPath(objectPath)
{
debug() << "Creating new DBusProxy";
}
};
DBusProxy::DBusProxy(const QDBusConnection& dbusConnection,
const QString& busName, const QString& path, QObject* parent)
: QObject(parent),
mPriv(new Private(dbusConnection, busName, path, *this))
{
}
DBusProxy::~DBusProxy()
{
delete mPriv;
}
QDBusConnection DBusProxy::dbusConnection() const
{
return mPriv->dbusConnection;
}
QString DBusProxy::objectPath() const
{
return mPriv->objectPath;
}
QString DBusProxy::busName() const
{
return mPriv->busName;
}
StatelessDBusProxy::StatelessDBusProxy(const QDBusConnection& dbusConnection,
const QString& busName, const QString& objectPath, QObject* parent)
: DBusProxy(dbusConnection, busName, objectPath, parent)
{
}
struct StatefulDBusProxy::Private
{
// Public object
StatefulDBusProxy& parent;
QString invalidationReason;
QString invalidationMessage;
Private(StatefulDBusProxy& p)
: parent(p),
invalidationReason(QString()),
invalidationMessage(QString())
{
debug() << "Creating new StatefulDBusProxy";
}
};
StatefulDBusProxy::StatefulDBusProxy(const QDBusConnection& dbusConnection,
const QString& busName, const QString& objectPath, QObject* parent)
: DBusProxy(dbusConnection, busName, objectPath, parent)
{
// FIXME: Am I on crack?
connect(dbusConnection.interface(), SIGNAL(serviceOwnerChanged(QString, QString, QString)),
this, SLOT(onServiceOwnerChanged(QString, QString, QString)));
}
bool StatefulDBusProxy::isValid() const
{
return mPriv->invalidationReason.isEmpty();
}
QString StatefulDBusProxy::invalidationReason() const
{
return mPriv->invalidationReason;
}
QString StatefulDBusProxy::invalidationMessage() const
{
return mPriv->invalidationMessage;
}
void StatefulDBusProxy::invalidate(const QString& reason, const QString& message)
{
Q_ASSERT(isValid());
Q_ASSERT(!reason.isEmpty());
mPriv->invalidationReason = reason;
mPriv->invalidationMessage = message;
Q_ASSERT(!isValid());
// Defer emitting the invalidated signal until we next
// return to the mainloop.
QTimer::singleShot(0, this, SLOT(emitInvalidated()));
}
void StatefulDBusProxy::emitInvalidated()
{
Q_ASSERT(!isValid());
emit invalidated(this, mPriv->invalidationReason, mPriv->invalidationMessage);
}
void StatefulDBusProxy::onServiceOwnerChanged(const QString& name, const QString& oldOwner, const QString& newOwner)
{
if (name == busName()) {
// FIXME: where do the error texts come from? the spec?
invalidate("NAME_OWNER_CHANGED", "NameOwnerChanged() received for this object.");
}
}
}
}
|
/*
* This file is part of TelepathyQt4
*
* Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
* Copyright (C) 2008 Nokia Corporation
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/Client/DBusProxy>
#include "TelepathyQt4/Client/_gen/dbus-proxy.moc.hpp"
#include "TelepathyQt4/debug-internal.h"
#include <QtCore/QTimer>
#include <QtDBus/QDBusConnectionInterface>
namespace Telepathy
{
namespace Client
{
struct DBusProxy::Private
{
// Public object
DBusProxy& parent;
QDBusConnection dbusConnection;
QString busName;
QString objectPath;
Private(const QDBusConnection& dbusConnection, const QString& busName,
const QString& objectPath, DBusProxy& p)
: parent(p),
dbusConnection(dbusConnection),
busName(busName),
objectPath(objectPath)
{
debug() << "Creating new DBusProxy";
}
};
DBusProxy::DBusProxy(const QDBusConnection& dbusConnection,
const QString& busName, const QString& path, QObject* parent)
: QObject(parent),
mPriv(new Private(dbusConnection, busName, path, *this))
{
}
DBusProxy::~DBusProxy()
{
delete mPriv;
}
QDBusConnection DBusProxy::dbusConnection() const
{
return mPriv->dbusConnection;
}
QString DBusProxy::objectPath() const
{
return mPriv->objectPath;
}
QString DBusProxy::busName() const
{
return mPriv->busName;
}
StatelessDBusProxy::StatelessDBusProxy(const QDBusConnection& dbusConnection,
const QString& busName, const QString& objectPath, QObject* parent)
: DBusProxy(dbusConnection, busName, objectPath, parent)
{
}
struct StatefulDBusProxy::Private
{
// Public object
StatefulDBusProxy& parent;
QString invalidationReason;
QString invalidationMessage;
Private(StatefulDBusProxy& p)
: parent(p),
invalidationReason(QString()),
invalidationMessage(QString())
{
debug() << "Creating new StatefulDBusProxy";
}
};
StatefulDBusProxy::StatefulDBusProxy(const QDBusConnection& dbusConnection,
const QString& busName, const QString& objectPath, QObject* parent)
: DBusProxy(dbusConnection, busName, objectPath, parent)
{
// FIXME: Am I on crack?
connect(dbusConnection.interface(), SIGNAL(serviceOwnerChanged(QString, QString, QString)),
this, SLOT(onServiceOwnerChanged(QString, QString, QString)));
}
bool StatefulDBusProxy::isValid() const
{
return mPriv->invalidationReason.isEmpty();
}
QString StatefulDBusProxy::invalidationReason() const
{
return mPriv->invalidationReason;
}
QString StatefulDBusProxy::invalidationMessage() const
{
return mPriv->invalidationMessage;
}
void StatefulDBusProxy::invalidate(const QString& reason, const QString& message)
{
Q_ASSERT(isValid());
Q_ASSERT(!reason.isEmpty());
mPriv->invalidationReason = reason;
mPriv->invalidationMessage = message;
Q_ASSERT(!isValid());
// Defer emitting the invalidated signal until we next
// return to the mainloop.
QTimer::singleShot(0, this, SLOT(emitInvalidated()));
}
void StatefulDBusProxy::emitInvalidated()
{
Q_ASSERT(!isValid());
emit invalidated(this, mPriv->invalidationReason, mPriv->invalidationMessage);
}
void StatefulDBusProxy::onServiceOwnerChanged(const QString& name, const QString& oldOwner, const QString& newOwner)
{
// We only want to invalidate this object if it is not already invalidated,
// and it's (not any other object's) name owner changed signal is emitted.
if (isValid() && (name == busName())) {
// FIXME: where do the error texts come from? the spec?
invalidate("NAME_OWNER_CHANGED", "NameOwnerChanged() received for this object.");
}
}
}
}
|
Change nameownerchanged handling slot to not call invalidate if the object is already invalidated.
|
Change nameownerchanged handling slot to not call invalidate if the object is already invalidated.
|
C++
|
lgpl-2.1
|
special/telepathy-qt-upstream,freedesktop-unofficial-mirror/telepathy__telepathy-qt,tiagosh/telepathy-qt,detrout/telepathy-qt,TelepathyQt/telepathy-qt,TelepathyQt/telepathy-qt,detrout/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,tiagosh/telepathy-qt,special/telepathy-qt-upstream,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,freedesktop-unofficial-mirror/telepathy__telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,detrout/telepathy-qt,TelepathyQt/telepathy-qt,TelepathyIM/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,TelepathyIM/telepathy-qt,TelepathyIM/telepathy-qt,anantkamath/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,tiagosh/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,TelepathyIM/telepathy-qt,TelepathyIM/telepathy-qt,anantkamath/telepathy-qt,TelepathyQt/telepathy-qt,special/telepathy-qt-upstream,anantkamath/telepathy-qt,tiagosh/telepathy-qt
|
5525cb3ef953a08e7102932bf2bfbd58f21d9023
|
tools/codesize/src/MainWindow.cpp
|
tools/codesize/src/MainWindow.cpp
|
/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "MainWindow.h"
#include "Application.h"
#include "nuiCSS.h"
#include "nuiVBox.h"
#include "nuiTreeView.h"
#include "nuiScrollView.h"
class Node: public nuiTreeNode
{
public:
Node(const nglString& rName)
: nuiTreeNode(new nuiLabel(rName)), mName(rName), mSize(0)
{
}
uint64 GetSize() const
{
return mSize;
}
void SetSize(uint64 s)
{
mSize = s;
nuiLabel* pLabel = (nuiLabel*)GetElement();
nglString txt;
txt.Add(mSize).Add(_T(" - ")).Add(mName);
pLabel->SetText(txt);
}
private:
uint64 mSize;
nglString mName;
};
/*
* MainWindow
*/
MainWindow::MainWindow(const nglContextInfo& rContextInfo, const nglWindowInfo& rInfo, bool ShowFPS, const nglContext* pShared )
: nuiMainWindow(rContextInfo, rInfo, pShared, nglPath(ePathCurrent)), mEventSink(this)
{
SetDebugMode(true);
#ifdef NUI_IPHONE
LoadCSS(_T("rsrc:/css/style-iPhone.css"));
#else
LoadCSS(_T("rsrc:/css/style.css"));
#endif
}
MainWindow::~MainWindow()
{
}
bool cmp(const std::pair<nglString, Node*>& rLeft, const std::pair<nglString, Node*>& rRight)
{
return rLeft.second->GetSize() < rRight.second->GetSize();
}
void MainWindow::OnCreation()
{
//Load(_T("/Users/meeloo/Desktop/nm.txt"));
mpScrollView = new nuiScrollView();
AddChild(mpScrollView);
}
nglDropEffect MainWindow::OnCanDrop(nglDragAndDrop* pDragObject, nuiSize X, nuiSize Y)
{
if (!pDragObject->IsTypeSupported(_T("ngl/Files")) && !pDragObject->IsTypeSupported(_T("ngl/PromiseFiles")))
return eDropEffectNone;
nglDataFilesObject* pFiles;
if (pDragObject->IsTypeSupported(_T("ngl/Files")))
pFiles = (nglDataFilesObject*)(pDragObject->GetType(_T("ngl/Files")));
else if (pDragObject->IsTypeSupported(_T("ngl/PromiseFiles")))
pFiles = (nglDataFilesObject*)(pDragObject->GetType(_T("ngl/PromiseFiles")));
nglPath path = *(pFiles->GetFiles().begin());
return eDropEffectLink;
}
// virtual
void MainWindow::OnDropped(nglDragAndDrop* pDragObject, nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
nglDataFilesObject* pFiles;
if (pDragObject->IsTypeSupported(_T("ngl/Files")))
pFiles = (nglDataFilesObject*)(pDragObject->GetType(_T("ngl/Files")));
else if (pDragObject->IsTypeSupported(_T("ngl/PromiseFiles")))
pFiles = (nglDataFilesObject*)(pDragObject->GetType(_T("ngl/PromiseFiles")));
nglPath path = *(pFiles->GetFiles().begin());
NGL_OUT(_T("dropped file : %ls\n"), path.GetChars());
if (!path.Exists())
return;
if (!path.IsLeaf())
{
nglPath p = path.GetRemovedExtension();
nglString name(p.GetNodeName());
path += "Contents";
path += "MacOS";
path += name;
if (!path.Exists() || !path.IsLeaf())
return;
}
Load(path);
}
void MainWindow::OnDropLeave()
{
}
void MainWindow::Load(const nglPath& p)
{
mpScrollView->Clear();
///////////////////////////////
nglString cmdline;
cmdline.Add("/usr/bin/nm -n -U -arch i386 ").Add(p.GetPathName()).Add(" | c++filt | c++filt -n");
printf("Launching\n%ls\n", cmdline.GetChars());
FILE * file = popen(cmdline.GetStdString().c_str(), "r");
nglOMemory omem;
uint32 res = 0;
do
{
char buf[1025];
memset(buf, 0, 1025);
uint32 res = fread(buf, 1024, 1, file);
//printf("%s", buf);
omem.Write(buf, 1024, 1);
} while (!feof(file));
pclose(file);
printf("redirection done\n");
nglIStream* pStream = new nglIMemory(omem.GetBufferData(), omem.GetBufferSize());;
nglString line;
uint64 lastaddr = 0;
nglString lastsymbol;
std::map<nglString, Node*> methods;
std::map<nglString, Node*> classes;
printf("read result\n");
while (pStream->ReadLine(line))
{
// Read address
int32 c = 0;
while (line[c] && line[c] != ' ')
c++;
nglString a(line.Extract(0, c));
uint64 address = a.GetCUInt(16);
c++;
// Read type char
nglChar type = line[c];
// Read Symbol if we are on a method / function decl
if (type == 't')
{
c++;
if (!lastsymbol.IsEmpty())
{
uint64 lastsize = address - lastaddr;
std::map<nglString, Node*>::iterator it = methods.find(lastsymbol);
bool skip = false;
Node* pMethod = NULL;
if (it != methods.end())
{
pMethod = it->second;
pMethod->SetSize(pMethod->GetSize() + lastsize);
//it->second += lastsize;
skip = true;
}
else
{
//NGL_OUT(_T("new method \t %ls\n"), lastsymbol.GetChars());
pMethod = new Node(lastsymbol);
pMethod->SetSize(lastsize);
methods[lastsymbol] = pMethod;
}
NGL_ASSERT(pMethod != NULL);
if (!skip) // The method already exist so no need to add it to its class
{
int32 pos = lastsymbol.Find(':');
if (pos > 0 && lastsymbol[pos+1] == ':')
{
nglString classname = lastsymbol.GetLeft(pos);
//NGL_OUT(_T("new class %ls\n"), classname.GetChars());
std::map<nglString, Node*>::iterator it = classes.find(classname);
Node* pNode = NULL;
if (it != classes.end())
{
pNode = it->second;
pNode->SetSize(it->second->GetSize() + lastsize);
}
else
{
pNode = new Node(classname);
pNode->SetSize(lastsize);
classes[classname] = pNode;
}
pNode->AddChild(pMethod);
}
}
}
lastaddr = address;
lastsymbol = line.GetRight(line.GetLength() - c);
}
}
printf("done\n");
printf("build tree\n");
delete pStream;
std::list<std::pair<nglString, Node*> > sorted;
{
std::map<nglString, Node*>::const_iterator it = classes.begin();
std::map<nglString, Node*>::const_iterator end = classes.end();
while (it != end)
{
//NGL_OUT(_T("add unsorted %ls\n"), it->first.GetChars());
sorted.push_back(std::pair<nglString, Node*>(it->first, it->second) );
++it;
}
}
sorted.sort(cmp);
nuiTreeNode* pTree = new nuiTreeNode(new nuiLabel(_T("Classes")));
{
std::list<std::pair<nglString, Node*> >::const_iterator it = sorted.begin();
std::list<std::pair<nglString, Node*> >::const_iterator end = sorted.end();
while (it != end)
{
//NGL_OUT(_T("%lld\t\t%ls\n"), it->second->GetSize(), it->first.GetChars());
pTree->AddChild(it->second);
++it;
}
}
nuiTreeView* pTreeView = new nuiTreeView(pTree);
mpScrollView->AddChild(pTreeView);
printf("done\n");
}
void MainWindow::OnClose()
{
if (GetNGLWindow()->IsInModalState())
return;
App->Quit();
}
bool MainWindow::LoadCSS(const nglPath& rPath)
{
nglIStream* pF = rPath.OpenRead();
if (!pF)
{
NGL_OUT(_T("Unable to open CSS source file '%ls'\n"), rPath.GetChars());
return false;
}
nuiCSS* pCSS = new nuiCSS();
bool res = pCSS->Load(*pF, rPath);
delete pF;
if (res)
{
nuiMainWindow::SetCSS(pCSS);
return true;
}
NGL_OUT(_T("%ls\n"), pCSS->GetErrorString().GetChars());
delete pCSS;
return false;
}
|
/*
NUI3 - C++ cross-platform GUI framework for OpenGL based applications
Copyright (C) 2002-2003 Sebastien Metrot
licence: see nui3/LICENCE.TXT
*/
#include "nui.h"
#include "MainWindow.h"
#include "Application.h"
#include "nuiCSS.h"
#include "nuiVBox.h"
#include "nuiTreeView.h"
#include "nuiScrollView.h"
class Node: public nuiTreeNode
{
public:
Node(const nglString& rName)
: nuiTreeNode(new nuiLabel(rName)), mName(rName), mSize(0)
{
}
uint64 GetSize() const
{
return mSize;
}
void SetSize(uint64 s)
{
mSize = s;
nuiLabel* pLabel = (nuiLabel*)GetElement();
nglString txt;
txt.Add(mSize).Add(_T(" - ")).Add(mName);
pLabel->SetText(txt);
}
private:
uint64 mSize;
nglString mName;
};
/*
* MainWindow
*/
MainWindow::MainWindow(const nglContextInfo& rContextInfo, const nglWindowInfo& rInfo, bool ShowFPS, const nglContext* pShared )
: nuiMainWindow(rContextInfo, rInfo, pShared, nglPath(ePathCurrent)), mEventSink(this)
{
SetDebugMode(true);
#ifdef NUI_IPHONE
LoadCSS(_T("rsrc:/css/style-iPhone.css"));
#else
LoadCSS(_T("rsrc:/css/style.css"));
#endif
}
MainWindow::~MainWindow()
{
}
bool cmp(const std::pair<nglString, Node*>& rLeft, const std::pair<nglString, Node*>& rRight)
{
return rLeft.second->GetSize() < rRight.second->GetSize();
}
void MainWindow::OnCreation()
{
//Load(_T("/Users/meeloo/Desktop/nm.txt"));
mpScrollView = new nuiScrollView();
AddChild(mpScrollView);
}
nglDropEffect MainWindow::OnCanDrop(nglDragAndDrop* pDragObject, nuiSize X, nuiSize Y)
{
if (!pDragObject->IsTypeSupported(_T("ngl/Files")) && !pDragObject->IsTypeSupported(_T("ngl/PromiseFiles")))
return eDropEffectNone;
nglDataFilesObject* pFiles;
if (pDragObject->IsTypeSupported(_T("ngl/Files")))
pFiles = (nglDataFilesObject*)(pDragObject->GetType(_T("ngl/Files")));
else if (pDragObject->IsTypeSupported(_T("ngl/PromiseFiles")))
pFiles = (nglDataFilesObject*)(pDragObject->GetType(_T("ngl/PromiseFiles")));
nglPath path = *(pFiles->GetFiles().begin());
return eDropEffectLink;
}
// virtual
void MainWindow::OnDropped(nglDragAndDrop* pDragObject, nuiSize X, nuiSize Y, nglMouseInfo::Flags Button)
{
nglDataFilesObject* pFiles;
if (pDragObject->IsTypeSupported(_T("ngl/Files")))
pFiles = (nglDataFilesObject*)(pDragObject->GetType(_T("ngl/Files")));
else if (pDragObject->IsTypeSupported(_T("ngl/PromiseFiles")))
pFiles = (nglDataFilesObject*)(pDragObject->GetType(_T("ngl/PromiseFiles")));
nglPath path = *(pFiles->GetFiles().begin());
NGL_OUT(_T("dropped file : %ls\n"), path.GetChars());
if (!path.Exists())
return;
// Try iPhone flat executable
if (!path.IsLeaf())
{
nglPath p = path.GetRemovedExtension();
nglString name(p.GetNodeName());
p = path;
p += name;
if (!p.Exists() || !p.IsLeaf())
{
p = path;
p += "Contents";
p += "MacOS";
p += name;
if (!p.Exists() || !p.IsLeaf())
{
printf("no iOS or MacOS executable found...\n");
return;
}
printf("MacOS executable found:\n%ls\n\n", p.GetChars());
}
else
{
printf("iOS executable found:\n%ls\n\n", p.GetChars());
}
path = p;
}
Load(path);
}
void MainWindow::OnDropLeave()
{
}
void MainWindow::Load(const nglPath& p)
{
mpScrollView->Clear();
///////////////////////////////
nglString cmdline;
//cmdline.Add("/usr/bin/nm -n -U -arch i386 ").Add(p.GetPathName()).Add(" | c++filt | c++filt -n");
cmdline.Add("/usr/bin/nm -n -U ").Add(p.GetPathName()).Add(" | c++filt | c++filt -n");
printf("Launching\n%ls\n", cmdline.GetChars());
FILE * file = popen(cmdline.GetStdString().c_str(), "r");
nglOMemory omem;
uint32 res = 0;
do
{
char buf[1025];
memset(buf, 0, 1025);
uint32 res = fread(buf, 1024, 1, file);
//printf("%s", buf);
omem.Write(buf, 1024, 1);
} while (!feof(file));
pclose(file);
printf("redirection done\n");
nglIStream* pStream = new nglIMemory(omem.GetBufferData(), omem.GetBufferSize());;
nglString line;
uint64 lastaddr = 0;
nglString lastsymbol;
std::map<nglString, Node*> methods;
std::map<nglString, Node*> classes;
printf("read result\n");
while (pStream->ReadLine(line))
{
// Read address
int32 c = 0;
while (line[c] && line[c] != ' ')
c++;
nglString a(line.Extract(0, c));
uint64 address = a.GetCUInt(16);
c++;
// Read type char
nglChar type = line[c];
// Read Symbol if we are on a method / function decl
if (type == 't')
{
c++;
if (!lastsymbol.IsEmpty())
{
uint64 lastsize = address - lastaddr;
std::map<nglString, Node*>::iterator it = methods.find(lastsymbol);
bool skip = false;
Node* pMethod = NULL;
if (it != methods.end())
{
pMethod = it->second;
pMethod->SetSize(pMethod->GetSize() + lastsize);
//it->second += lastsize;
skip = true;
}
else
{
//NGL_OUT(_T("new method \t %ls\n"), lastsymbol.GetChars());
pMethod = new Node(lastsymbol);
pMethod->SetSize(lastsize);
methods[lastsymbol] = pMethod;
}
NGL_ASSERT(pMethod != NULL);
if (!skip) // The method already exist so no need to add it to its class
{
int32 pos = lastsymbol.Find(':');
if (pos > 0 && lastsymbol[pos+1] == ':')
{
nglString classname = lastsymbol.GetLeft(pos);
//NGL_OUT(_T("new class %ls\n"), classname.GetChars());
std::map<nglString, Node*>::iterator it = classes.find(classname);
Node* pNode = NULL;
if (it != classes.end())
{
pNode = it->second;
pNode->SetSize(it->second->GetSize() + lastsize);
}
else
{
pNode = new Node(classname);
pNode->SetSize(lastsize);
classes[classname] = pNode;
}
pNode->AddChild(pMethod);
}
}
}
lastaddr = address;
lastsymbol = line.GetRight(line.GetLength() - c);
}
}
printf("done\n");
printf("build tree\n");
delete pStream;
std::list<std::pair<nglString, Node*> > sorted;
{
std::map<nglString, Node*>::const_iterator it = classes.begin();
std::map<nglString, Node*>::const_iterator end = classes.end();
while (it != end)
{
//NGL_OUT(_T("add unsorted %ls\n"), it->first.GetChars());
sorted.push_back(std::pair<nglString, Node*>(it->first, it->second) );
++it;
}
}
sorted.sort(cmp);
nuiTreeNode* pTree = new nuiTreeNode(new nuiLabel(_T("Classes")));
{
std::list<std::pair<nglString, Node*> >::const_iterator it = sorted.begin();
std::list<std::pair<nglString, Node*> >::const_iterator end = sorted.end();
while (it != end)
{
//NGL_OUT(_T("%lld\t\t%ls\n"), it->second->GetSize(), it->first.GetChars());
pTree->AddChild(it->second);
++it;
}
}
nuiTreeView* pTreeView = new nuiTreeView(pTree);
mpScrollView->AddChild(pTreeView);
printf("done\n");
}
void MainWindow::OnClose()
{
if (GetNGLWindow()->IsInModalState())
return;
App->Quit();
}
bool MainWindow::LoadCSS(const nglPath& rPath)
{
nglIStream* pF = rPath.OpenRead();
if (!pF)
{
NGL_OUT(_T("Unable to open CSS source file '%ls'\n"), rPath.GetChars());
return false;
}
nuiCSS* pCSS = new nuiCSS();
bool res = pCSS->Load(*pF, rPath);
delete pF;
if (res)
{
nuiMainWindow::SetCSS(pCSS);
return true;
}
NGL_OUT(_T("%ls\n"), pCSS->GetErrorString().GetChars());
delete pCSS;
return false;
}
|
sort font request results by filename if nothing else can
|
sort font request results by filename if nothing else can
|
C++
|
mpl-2.0
|
libnui/nui3,UIKit0/nui3,libnui/nui3,libnui/nui3,libnui/nui3,UIKit0/nui3,UIKit0/nui3,UIKit0/nui3,UIKit0/nui3,libnui/nui3,libnui/nui3,UIKit0/nui3,UIKit0/nui3
|
11476e9aaacc23a84e57998d64a7a4cc31815d08
|
src/PDBReader.hpp
|
src/PDBReader.hpp
|
#ifndef COFFEE_MILL_PURE_PDB_READER
#define COFFEE_MILL_PURE_PDB_READER
#include "PDBChain.hpp"
namespace coffeemill
{
class PDBReader
{
public:
PDBReader(){}
PDBReader(const std::string& filename)
: filename_(filename)
{}
~PDBReader(){}
void read();
std::vector<PDBChain> parse();
std::string& filename() {return filename_;}
const std::string& filename() const {return filename_;}
std::vector<std::shared_ptr<PDBAtom>>& atoms() {return atoms_;}
const std::vector<std::shared_ptr<PDBAtom>>& atoms() const {return atoms_;}
private:
std::string filename_;
std::vector<std::shared_ptr<PDBAtom>> atoms_;
};
}
#endif//COFFEE_MILL_PURE_PDB_READER
|
/*!
@file PDBReader.hpp
@brief definition of a class that reads pdb atom.
read pdb file and store the information as std::vector of shared_ptr of PDBAtom
@author Toru Niina ([email protected])
@date 2016-06-10 13:00
@copyright Toru Niina 2016 on MIT License
*/
#ifndef COFFEE_MILL_PURE_PDB_READER
#define COFFEE_MILL_PURE_PDB_READER
#include "PDBChain.hpp"
namespace coffeemill
{
//! PDBReader class
/*!
* read pdb file and store the data as vector of shared_ptr of PDBAtom.
* and also can parse the vector of PDBAtom into vector of PDBChains.
*/
class PDBReader
{
public:
//! ctor.
PDBReader(){}
//! ctor with the name of the file to read.
explicit PDBReader(const std::string& filename)
: filename_(filename)
{}
//! dtor.
~PDBReader(){}
//! read the file.
void read();
//! parse the data into chains.
std::vector<PDBChain> parse();
//! filename
std::string& filename() {return filename_;}
//! filename
const std::string& filename() const {return filename_;}
//! data
std::vector<std::shared_ptr<PDBAtom>>& atoms() {return atoms_;}
//! data
const std::vector<std::shared_ptr<PDBAtom>>& atoms() const {return atoms_;}
private:
std::string filename_; //!< the name of the file to read
std::vector<std::shared_ptr<PDBAtom>> atoms_;//!< data in the file
};
}
#endif//COFFEE_MILL_PURE_PDB_READER
|
add document of PDBReader
|
add document of PDBReader
|
C++
|
mit
|
ToruNiina/Coffee-mill,ToruNiina/Coffee-mill
|
f08bd094201a670c5d84543c3338c960de56c1af
|
Settings/Updater/UpdaterWindow.cpp
|
Settings/Updater/UpdaterWindow.cpp
|
// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "UpdaterWindow.h"
#include "../../3RVX/3RVX.h"
#include "../../3RVX/LanguageTranslator.h"
#include "../../3RVX/Logger.h"
#include "../../3RVX/CommCtl.h"
#include "../../3RVX/NotifyIcon.h"
#include "../../3RVX/Settings.h"
#include "../resource.h"
#include "ProgressWindow.h"
#include "Updater.h"
UpdaterWindow::UpdaterWindow() :
Window(_3RVX::CLASS_3RVX_UPDATER, _3RVX::CLASS_3RVX_UPDATER) {
HRESULT hr;
hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_SMALL,
&_smallIcon);
if (hr != S_OK) {
CLOG(L"Could not load notification icon");
}
hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_LARGE,
&_largeIcon);
if (hr != S_OK) {
CLOG(L"Could not load large notification icon");
}
}
UpdaterWindow::~UpdaterWindow() {
delete _notifyIcon;
DestroyIcon(_smallIcon);
DestroyIcon(_largeIcon);
}
void UpdaterWindow::InstallUpdate() {
delete _notifyIcon;
_notifyIcon = nullptr;
ProgressWindow pw(Window::Handle(), _version);
pw.Show();
SendMessage(Window::Handle(), WM_CLOSE, 0, 0);
}
void UpdaterWindow::CreateMenu() {
_menu = CreatePopupMenu();
LanguageTranslator *translator = _settings->Translator();
_menuInstallStr = translator->Translate(_menuInstallStr);
_menuNotesStr = translator->Translate(_menuNotesStr);
_menuIgnoreStr = translator->Translate(_menuIgnoreStr);
_menuRemindStr = translator->Translate(_menuRemindStr);
InsertMenu(_menu, -1, MF_ENABLED, MENU_INSTALL, _menuInstallStr.c_str());
InsertMenu(_menu, -1, MF_ENABLED, MENU_NOTES, _menuNotesStr.c_str());
InsertMenu(_menu, -1, MF_ENABLED, MENU_IGNORE, _menuIgnoreStr.c_str());
InsertMenu(_menu, -1, MF_ENABLED, MENU_REMIND, _menuRemindStr.c_str());
_menuFlags = TPM_RIGHTBUTTON;
if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {
_menuFlags |= TPM_RIGHTALIGN;
} else {
_menuFlags |= TPM_LEFTALIGN;
}
}
LRESULT UpdaterWindow::WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {
switch (wParam) {
case _3RVX::MSG_UPDATEICON:
_settings = Settings::Instance();
/* Set that we just checked for updates now */
_settings->LastUpdateCheckNow();
_settings->Save();
_version = Updater::RemoteVersion();
if (_version.Major() <= 0
|| _version.ToString() == _settings->IgnoreUpdate()) {
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
}
CLOG(L"Creating menu");
CreateMenu();
LanguageTranslator *translator = _settings->Translator();
_availableStr = translator->Translate(_availableStr);
_updateVersStr = translator->TranslateAndReplace(
_updateVersStr, _version.ToString());
CLOG(L"Creating update icon");
_notifyIcon = new NotifyIcon(
Window::Handle(),
_availableStr,
_smallIcon);
CLOG(L"Launching balloon notification");
_notifyIcon->Balloon(_availableStr, _updateVersStr, _largeIcon);
break;
}
} else if (message == MSG_NOTIFYICON) {
if (lParam == WM_LBUTTONUP
|| lParam == WM_RBUTTONUP
|| lParam == NIN_BALLOONUSERCLICK) {
POINT p;
GetCursorPos(&p);
SetForegroundWindow(hWnd);
TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y,
Window::Handle(), NULL);
PostMessage(hWnd, WM_NULL, 0, 0);
}
} else if (message == WM_COMMAND) {
int menuItem = LOWORD(wParam);
switch (menuItem) {
case MENU_INSTALL:
InstallUpdate();
break;
case MENU_IGNORE:
_settings->IgnoreUpdate(_version.ToString());
_settings->Save();
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
case MENU_REMIND:
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
}
} else if (message == WM_DESTROY) {
PostQuitMessage(0);
}
return Window::WndProc(hWnd, message, wParam, lParam);
}
void UpdaterWindow::DoModal() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
|
// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "UpdaterWindow.h"
#include "../../3RVX/3RVX.h"
#include "../../3RVX/LanguageTranslator.h"
#include "../../3RVX/Logger.h"
#include "../../3RVX/CommCtl.h"
#include "../../3RVX/NotifyIcon.h"
#include "../../3RVX/Settings.h"
#include "../resource.h"
#include "ProgressWindow.h"
#include "Updater.h"
UpdaterWindow::UpdaterWindow() :
Window(_3RVX::CLASS_3RVX_UPDATER, _3RVX::CLASS_3RVX_UPDATER) {
HRESULT hr;
hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_SMALL,
&_smallIcon);
if (hr != S_OK) {
CLOG(L"Could not load notification icon");
}
hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_LARGE,
&_largeIcon);
if (hr != S_OK) {
CLOG(L"Could not load large notification icon");
}
}
UpdaterWindow::~UpdaterWindow() {
delete _notifyIcon;
DestroyIcon(_smallIcon);
DestroyIcon(_largeIcon);
}
void UpdaterWindow::InstallUpdate() {
delete _notifyIcon;
_notifyIcon = nullptr;
ProgressWindow pw(Window::Handle(), _version);
pw.Show();
SendMessage(Window::Handle(), WM_CLOSE, 0, 0);
}
void UpdaterWindow::CreateMenu() {
_menu = CreatePopupMenu();
LanguageTranslator *translator = _settings->Translator();
_menuInstallStr = translator->Translate(_menuInstallStr);
_menuNotesStr = translator->Translate(_menuNotesStr);
_menuIgnoreStr = translator->Translate(_menuIgnoreStr);
_menuRemindStr = translator->Translate(_menuRemindStr);
InsertMenu(_menu, -1, MF_ENABLED, MENU_INSTALL, _menuInstallStr.c_str());
InsertMenu(_menu, -1, MF_ENABLED, MENU_NOTES, _menuNotesStr.c_str());
InsertMenu(_menu, -1, MF_ENABLED, MENU_IGNORE, _menuIgnoreStr.c_str());
InsertMenu(_menu, -1, MF_ENABLED, MENU_REMIND, _menuRemindStr.c_str());
_menuFlags = TPM_RIGHTBUTTON;
if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0) {
_menuFlags |= TPM_RIGHTALIGN;
} else {
_menuFlags |= TPM_LEFTALIGN;
}
}
LRESULT UpdaterWindow::WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {
switch (wParam) {
case _3RVX::MSG_UPDATEICON:
_settings = Settings::Instance();
/* Set that we just checked for updates now */
_settings->LastUpdateCheckNow();
_settings->Save();
_version = Updater::RemoteVersion();
if (_version.Major() <= 0
|| _version.ToString() == _settings->IgnoreUpdate()) {
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
}
CLOG(L"Creating menu");
CreateMenu();
LanguageTranslator *translator = _settings->Translator();
_availableStr = translator->Translate(_availableStr);
_updateVersStr = translator->TranslateAndReplace(
_updateVersStr, _version.ToString());
CLOG(L"Creating update icon");
_notifyIcon = new NotifyIcon(
Window::Handle(),
_availableStr,
_smallIcon);
CLOG(L"Launching balloon notification");
_notifyIcon->Balloon(_availableStr, _updateVersStr, _largeIcon);
break;
}
} else if (message == MSG_NOTIFYICON) {
if (lParam == WM_LBUTTONUP
|| lParam == WM_RBUTTONUP
|| lParam == NIN_BALLOONUSERCLICK) {
POINT p;
GetCursorPos(&p);
SetForegroundWindow(hWnd);
TrackPopupMenuEx(_menu, _menuFlags, p.x, p.y,
Window::Handle(), NULL);
PostMessage(hWnd, WM_NULL, 0, 0);
}
} else if (message == WM_COMMAND) {
int menuItem = LOWORD(wParam);
switch (menuItem) {
case MENU_INSTALL:
InstallUpdate();
break;
case MENU_NOTES: {
std::wstring url = L"https://3rvx.com/release-notes/"
+ _version.ToString() + L".html";
HINSTANCE ret = ShellExecute(NULL, L"open", url.c_str(),
NULL, NULL, SW_SHOWNORMAL);
break;
}
case MENU_IGNORE:
_settings->IgnoreUpdate(_version.ToString());
_settings->Save();
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
case MENU_REMIND:
SendMessage(Window::Handle(), WM_CLOSE, NULL, NULL);
break;
}
} else if (message == WM_DESTROY) {
PostQuitMessage(0);
}
return Window::WndProc(hWnd, message, wParam, lParam);
}
void UpdaterWindow::DoModal() {
MSG msg;
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
|
Implement release notes launcher
|
Implement release notes launcher
|
C++
|
bsd-2-clause
|
malensek/3RVX,malensek/3RVX,malensek/3RVX
|
4e787c527318432baee5e970d73ebbf7fedc4915
|
src/graphics/material.cpp
|
src/graphics/material.cpp
|
#include "graphics/material.h"
#include "core/crc32.h"
#include "core/fs/file_system.h"
#include "core/fs/ifile.h"
#include "core/json_serializer.h"
#include "core/log.h"
#include "core/path_utils.h"
#include "core/profiler.h"
#include "core/resource_manager.h"
#include "core/resource_manager_base.h"
#include "core/timer.h"
#include "graphics/frame_buffer.h"
#include "graphics/pipeline.h"
#include "graphics/renderer.h"
#include "graphics/shader.h"
#include "graphics/texture.h"
namespace Lumix
{
static const uint32_t SHADOWMAP_HASH = crc32("shadowmap");
Material::~Material()
{
ASSERT(isEmpty());
}
void Material::apply(Renderer& renderer, PipelineInstance& pipeline) const
{
PROFILE_FUNCTION();
if(getState() == State::READY)
{
renderer.applyShader(*m_shader);
switch (m_depth_func)
{
case DepthFunc::LEQUAL:
glDepthFunc(GL_LEQUAL);
break;
default:
glDepthFunc(GL_LESS);
break;
}
if (m_is_backface_culling)
{
glEnable(GL_CULL_FACE);
}
else
{
glDisable(GL_CULL_FACE);
}
for (int i = 0, c = m_textures.size(); i < c; ++i)
{
m_textures[i].m_texture->apply(i);
}
renderer.enableAlphaToCoverage(m_is_alpha_to_coverage);
renderer.enableZTest(m_is_z_test);
for (int i = 0, c = m_uniforms.size(); i < c; ++i)
{
const Uniform& uniform = m_uniforms[i];
switch (uniform.m_type)
{
case Uniform::FLOAT:
renderer.setUniform(*m_shader, uniform.m_name, uniform.m_name_hash, uniform.m_float);
break;
case Uniform::INT:
renderer.setUniform(*m_shader, uniform.m_name, uniform.m_name_hash, uniform.m_int);
break;
case Uniform::MATRIX:
renderer.setUniform(*m_shader, uniform.m_name, uniform.m_name_hash, uniform.m_matrix);
break;
case Uniform::TIME:
renderer.setUniform(*m_shader, uniform.m_name, uniform.m_name_hash, pipeline.getScene()->getTimer()->getTimeSinceStart());
break;
default:
ASSERT(false);
break;
}
}
if (m_shader->isShadowmapRequired())
{
glActiveTexture(GL_TEXTURE0 + m_textures.size());
glBindTexture(GL_TEXTURE_2D, pipeline.getShadowmapFramebuffer()->getDepthTexture());
renderer.setUniform(*m_shader, "shadowmap", SHADOWMAP_HASH, m_textures.size());
}
}
}
void Material::doUnload(void)
{
if(m_shader)
{
removeDependency(*m_shader);
m_resource_manager.get(ResourceManager::SHADER)->unload(*m_shader);
m_shader = NULL;
}
ResourceManagerBase* texture_manager = m_resource_manager.get(ResourceManager::TEXTURE);
for(int i = 0; i < m_textures.size(); i++)
{
removeDependency(*m_textures[i].m_texture);
texture_manager->unload(*m_textures[i].m_texture);
}
m_textures.clear();
m_size = 0;
onEmpty();
}
FS::ReadCallback Material::getReadCallback()
{
FS::ReadCallback rc;
rc.bind<Material, &Material::loaded>(this);
return rc;
}
bool Material::save(ISerializer& serializer)
{
serializer.beginObject();
serializer.serialize("shader", m_shader->getPath().c_str());
for (int i = 0; i < m_textures.size(); ++i)
{
char path[LUMIX_MAX_PATH];
PathUtils::getFilename(path, LUMIX_MAX_PATH, m_textures[i].m_texture->getPath().c_str());
serializer.serialize("texture", path);
}
serializer.serialize("alpha_to_coverage", m_is_alpha_to_coverage);
serializer.serialize("backface_culling", m_is_backface_culling);
serializer.serialize("z_test", m_is_z_test);
serializer.endObject();
return false;
}
void Material::deserializeUniforms(ISerializer& serializer)
{
serializer.deserializeArrayBegin();
while (!serializer.isArrayEnd())
{
Uniform& uniform = m_uniforms.pushEmpty();
serializer.nextArrayItem();
serializer.deserializeObjectBegin();
char label[256];
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, 255);
if (strcmp(label, "name") == 0)
{
serializer.deserialize(uniform.m_name, Uniform::MAX_NAME_LENGTH);
uniform.m_name_hash = crc32(uniform.m_name);
}
else if (strcmp(label, "int_value") == 0)
{
uniform.m_type = Uniform::INT;
serializer.deserialize(uniform.m_int);
}
else if (strcmp(label, "float_value") == 0)
{
uniform.m_type = Uniform::FLOAT;
serializer.deserialize(uniform.m_float);
}
else if (strcmp(label, "matrix_value") == 0)
{
uniform.m_type = Uniform::MATRIX;
serializer.deserializeArrayBegin();
for (int i = 0; i < 16; ++i)
{
serializer.deserializeArrayItem(uniform.m_matrix[i]);
ASSERT(i == 15 || !serializer.isArrayEnd());
}
serializer.deserializeArrayEnd();
}
else if (strcmp(label, "time") == 0)
{
uniform.m_type = Uniform::TIME;
serializer.deserialize(uniform.m_float);
}
else
{
ASSERT(false);
}
}
serializer.deserializeObjectEnd();
}
serializer.deserializeArrayEnd();
}
void Material::removeTexture(int i)
{
if (m_textures[i].m_texture)
{
removeDependency(*m_textures[i].m_texture);
m_resource_manager.get(ResourceManager::TEXTURE)->unload(*m_textures[i].m_texture);
}
m_textures.erase(i);
}
Texture* Material::getTextureByUniform(const char* uniform) const
{
for (int i = 0; i < m_textures.size(); ++i)
{
if (strcmp(m_textures[i].m_uniform, uniform) == 0)
{
return m_textures[i].m_texture;
}
}
return NULL;
}
void Material::setTexture(int i, Texture* texture)
{
if (m_textures[i].m_texture)
{
removeDependency(*m_textures[i].m_texture);
m_resource_manager.get(ResourceManager::TEXTURE)->unload(*m_textures[i].m_texture);
}
if (texture)
{
addDependency(*texture);
}
m_textures[i].m_texture = texture;
}
void Material::addTexture(Texture* texture)
{
if (texture)
{
addDependency(*texture);
}
m_textures.pushEmpty().m_texture = texture;
}
void Material::setShader(Shader* shader)
{
if (m_shader)
{
removeDependency(*m_shader);
m_resource_manager.get(ResourceManager::SHADER)->unload(*m_shader);
}
m_shader = shader;
if (m_shader)
{
addDependency(*m_shader);
}
}
bool Material::deserializeTexture(ISerializer& serializer, const char* material_dir)
{
char path[LUMIX_MAX_PATH];
TextureInfo& info = m_textures.pushEmpty();
serializer.deserializeObjectBegin();
char label[256];
bool data_kept = false;
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, sizeof(label));
if (strcmp(label, "source") == 0)
{
serializer.deserialize(path, MAX_PATH);
if (path[0] != '\0')
{
base_string<char, StackAllocator<LUMIX_MAX_PATH> > texture_path;
texture_path = material_dir;
texture_path += path;
info.m_texture = static_cast<Texture*>(m_resource_manager.get(ResourceManager::TEXTURE)->load(texture_path.c_str()));
addDependency(*info.m_texture);
if (info.m_keep_data)
{
if (info.m_texture->isReady() && !info.m_texture->getData())
{
g_log_error.log("Renderer") << "Cannot keep data for texture " << m_path.c_str() << "because the texture has already been loaded.";
return false;
}
if (!data_kept)
{
info.m_texture->addDataReference();
data_kept = true;
}
}
}
}
else if (strcmp("uniform", label) == 0)
{
Uniform& uniform = m_uniforms.pushEmpty();
serializer.deserialize(uniform.m_name, Uniform::MAX_NAME_LENGTH);
copyString(info.m_uniform, sizeof(info.m_uniform), uniform.m_name);
uniform.m_name_hash = crc32(uniform.m_name);
uniform.m_type = Uniform::INT;
uniform.m_int = info.m_texture ? m_textures.size() - 1 : m_textures.size();
}
else if (strcmp("keep_data", label) == 0)
{
serializer.deserialize(info.m_keep_data);
if (info.m_keep_data && info.m_texture)
{
if (info.m_texture->isReady() && !info.m_texture->getData())
{
g_log_error.log("Renderer") << "Cannot keep data for texture " << info.m_texture->getPath().c_str() << ", it's already loaded.";
return false;
}
if (!data_kept)
{
data_kept = true;
info.m_texture->addDataReference();
}
}
}
else
{
g_log_error.log("Renderer") << "Unknown data \"" << label << "\" in material " << m_path.c_str();
return false;
}
}
serializer.deserializeObjectEnd();
return true;
}
void Material::loaded(FS::IFile* file, bool success, FS::FileSystem& fs)
{
PROFILE_FUNCTION();
if(success)
{
JsonSerializer serializer(*file, JsonSerializer::READ, m_path.c_str());
serializer.deserializeObjectBegin();
char path[LUMIX_MAX_PATH];
char label[256];
char material_dir[LUMIX_MAX_PATH];
PathUtils::getDir(material_dir, LUMIX_MAX_PATH, m_path.c_str());
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, 255);
if (strcmp(label, "uniforms") == 0)
{
deserializeUniforms(serializer);
}
else if (strcmp(label, "texture") == 0)
{
if (!deserializeTexture(serializer, material_dir))
{
onFailure();
fs.close(file);
return;
}
}
else if (strcmp(label, "alpha_to_coverage") == 0)
{
serializer.deserialize(m_is_alpha_to_coverage);
}
else if (strcmp(label, "shader") == 0)
{
serializer.deserialize(path, MAX_PATH);
m_shader = static_cast<Shader*>(m_resource_manager.get(ResourceManager::SHADER)->load(path));
addDependency(*m_shader);
}
else if (strcmp(label, "z_test") == 0)
{
serializer.deserialize(m_is_z_test);
}
else if (strcmp(label, "backface_culling") == 0)
{
serializer.deserialize(m_is_backface_culling);
}
else if (strcmp(label, "depth_func") == 0)
{
char tmp[30];
serializer.deserialize(tmp, 30);
if (strcmp(tmp, "lequal") == 0)
{
m_depth_func = DepthFunc::LEQUAL;
}
else if (strcmp(tmp, "less") == 0)
{
m_depth_func = DepthFunc::LESS;
}
else
{
g_log_warning.log("Renderer") << "Unknown depth function " << tmp << " in material " << m_path.c_str();
}
}
else
{
g_log_warning.log("renderer") << "Unknown parameter " << label << " in material " << m_path.c_str();
}
}
serializer.deserializeObjectEnd();
if (!m_shader)
{
g_log_error.log("renderer") << "Material " << m_path.c_str() << " without a shader";
onFailure();
fs.close(file);
return;
}
m_size = file->size();
decrementDepCount();
}
else
{
g_log_info.log("renderer") << "Error loading material " << m_path.c_str();
onFailure();
}
fs.close(file);
}
} // ~namespace Lumix
|
#include "graphics/material.h"
#include "core/crc32.h"
#include "core/fs/file_system.h"
#include "core/fs/ifile.h"
#include "core/json_serializer.h"
#include "core/log.h"
#include "core/path_utils.h"
#include "core/profiler.h"
#include "core/resource_manager.h"
#include "core/resource_manager_base.h"
#include "core/timer.h"
#include "graphics/frame_buffer.h"
#include "graphics/pipeline.h"
#include "graphics/renderer.h"
#include "graphics/shader.h"
#include "graphics/texture.h"
namespace Lumix
{
static const uint32_t SHADOWMAP_HASH = crc32("shadowmap");
Material::~Material()
{
ASSERT(isEmpty());
}
void Material::apply(Renderer& renderer, PipelineInstance& pipeline) const
{
PROFILE_FUNCTION();
if(getState() == State::READY)
{
renderer.applyShader(*m_shader);
switch (m_depth_func)
{
case DepthFunc::LEQUAL:
glDepthFunc(GL_LEQUAL);
break;
default:
glDepthFunc(GL_LESS);
break;
}
if (m_is_backface_culling)
{
glEnable(GL_CULL_FACE);
}
else
{
glDisable(GL_CULL_FACE);
}
for (int i = 0, c = m_textures.size(); i < c; ++i)
{
m_textures[i].m_texture->apply(i);
}
renderer.enableAlphaToCoverage(m_is_alpha_to_coverage);
renderer.enableZTest(m_is_z_test);
for (int i = 0, c = m_uniforms.size(); i < c; ++i)
{
const Uniform& uniform = m_uniforms[i];
switch (uniform.m_type)
{
case Uniform::FLOAT:
renderer.setUniform(*m_shader, uniform.m_name, uniform.m_name_hash, uniform.m_float);
break;
case Uniform::INT:
renderer.setUniform(*m_shader, uniform.m_name, uniform.m_name_hash, uniform.m_int);
break;
case Uniform::MATRIX:
renderer.setUniform(*m_shader, uniform.m_name, uniform.m_name_hash, uniform.m_matrix);
break;
case Uniform::TIME:
renderer.setUniform(*m_shader, uniform.m_name, uniform.m_name_hash, pipeline.getScene()->getTimer()->getTimeSinceStart());
break;
default:
ASSERT(false);
break;
}
}
if (m_shader->isShadowmapRequired())
{
glActiveTexture(GL_TEXTURE0 + m_textures.size());
glBindTexture(GL_TEXTURE_2D, pipeline.getShadowmapFramebuffer()->getDepthTexture());
renderer.setUniform(*m_shader, "shadowmap", SHADOWMAP_HASH, m_textures.size());
}
}
}
void Material::doUnload(void)
{
if(m_shader)
{
removeDependency(*m_shader);
m_resource_manager.get(ResourceManager::SHADER)->unload(*m_shader);
m_shader = NULL;
}
ResourceManagerBase* texture_manager = m_resource_manager.get(ResourceManager::TEXTURE);
for(int i = 0; i < m_textures.size(); i++)
{
removeDependency(*m_textures[i].m_texture);
texture_manager->unload(*m_textures[i].m_texture);
}
m_textures.clear();
m_size = 0;
onEmpty();
}
FS::ReadCallback Material::getReadCallback()
{
FS::ReadCallback rc;
rc.bind<Material, &Material::loaded>(this);
return rc;
}
bool Material::save(ISerializer& serializer)
{
serializer.beginObject();
serializer.serialize("shader", m_shader->getPath().c_str());
for (int i = 0; i < m_textures.size(); ++i)
{
char path[LUMIX_MAX_PATH];
PathUtils::getFilename(path, LUMIX_MAX_PATH, m_textures[i].m_texture->getPath().c_str());
serializer.beginObject("texture");
serializer.serialize("source", path);
serializer.serialize("keep_data", m_textures[i].m_keep_data);
if (m_textures[i].m_uniform[0] != '\0')
{
serializer.serialize("uniform", m_textures[i].m_uniform);
}
serializer.endObject();
}
serializer.beginArray("uniforms");
for (int i = 0; i < m_uniforms.size(); ++i)
{
serializer.beginObject();
serializer.serialize("name", m_uniforms[i].m_name);
switch (m_uniforms[i].m_type)
{
case Uniform::FLOAT:
serializer.serialize("float_value", m_uniforms[i].m_float);
break;
case Uniform::TIME:
serializer.serialize("time", m_uniforms[i].m_float);
break;
case Uniform::INT:
serializer.serialize("int_value", m_uniforms[i].m_int);
break;
case Uniform::MATRIX:
serializer.beginArray("matrix_value");
for (int j = 0; j < 16; ++j)
{
serializer.serializeArrayItem(m_uniforms[i].m_matrix[j]);
}
serializer.endArray();
break;
default:
ASSERT(false);
break;
}
serializer.endObject();
}
serializer.endArray();
serializer.serialize("alpha_to_coverage", m_is_alpha_to_coverage);
serializer.serialize("backface_culling", m_is_backface_culling);
serializer.serialize("z_test", m_is_z_test);
serializer.endObject();
return false;
}
void Material::deserializeUniforms(ISerializer& serializer)
{
serializer.deserializeArrayBegin();
while (!serializer.isArrayEnd())
{
Uniform& uniform = m_uniforms.pushEmpty();
serializer.nextArrayItem();
serializer.deserializeObjectBegin();
char label[256];
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, 255);
if (strcmp(label, "name") == 0)
{
serializer.deserialize(uniform.m_name, Uniform::MAX_NAME_LENGTH);
uniform.m_name_hash = crc32(uniform.m_name);
}
else if (strcmp(label, "int_value") == 0)
{
uniform.m_type = Uniform::INT;
serializer.deserialize(uniform.m_int);
}
else if (strcmp(label, "float_value") == 0)
{
uniform.m_type = Uniform::FLOAT;
serializer.deserialize(uniform.m_float);
}
else if (strcmp(label, "matrix_value") == 0)
{
uniform.m_type = Uniform::MATRIX;
serializer.deserializeArrayBegin();
for (int i = 0; i < 16; ++i)
{
serializer.deserializeArrayItem(uniform.m_matrix[i]);
ASSERT(i == 15 || !serializer.isArrayEnd());
}
serializer.deserializeArrayEnd();
}
else if (strcmp(label, "time") == 0)
{
uniform.m_type = Uniform::TIME;
serializer.deserialize(uniform.m_float);
}
else
{
ASSERT(false);
}
}
serializer.deserializeObjectEnd();
}
serializer.deserializeArrayEnd();
}
void Material::removeTexture(int i)
{
if (m_textures[i].m_texture)
{
removeDependency(*m_textures[i].m_texture);
m_resource_manager.get(ResourceManager::TEXTURE)->unload(*m_textures[i].m_texture);
}
m_textures.erase(i);
}
Texture* Material::getTextureByUniform(const char* uniform) const
{
for (int i = 0; i < m_textures.size(); ++i)
{
if (strcmp(m_textures[i].m_uniform, uniform) == 0)
{
return m_textures[i].m_texture;
}
}
return NULL;
}
void Material::setTexture(int i, Texture* texture)
{
if (m_textures[i].m_texture)
{
removeDependency(*m_textures[i].m_texture);
m_resource_manager.get(ResourceManager::TEXTURE)->unload(*m_textures[i].m_texture);
}
if (texture)
{
addDependency(*texture);
}
m_textures[i].m_texture = texture;
}
void Material::addTexture(Texture* texture)
{
if (texture)
{
addDependency(*texture);
}
m_textures.pushEmpty().m_texture = texture;
}
void Material::setShader(Shader* shader)
{
if (m_shader)
{
removeDependency(*m_shader);
m_resource_manager.get(ResourceManager::SHADER)->unload(*m_shader);
}
m_shader = shader;
if (m_shader)
{
addDependency(*m_shader);
}
}
bool Material::deserializeTexture(ISerializer& serializer, const char* material_dir)
{
char path[LUMIX_MAX_PATH];
TextureInfo& info = m_textures.pushEmpty();
serializer.deserializeObjectBegin();
char label[256];
bool data_kept = false;
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, sizeof(label));
if (strcmp(label, "source") == 0)
{
serializer.deserialize(path, MAX_PATH);
if (path[0] != '\0')
{
base_string<char, StackAllocator<LUMIX_MAX_PATH> > texture_path;
texture_path = material_dir;
texture_path += path;
info.m_texture = static_cast<Texture*>(m_resource_manager.get(ResourceManager::TEXTURE)->load(texture_path.c_str()));
addDependency(*info.m_texture);
if (info.m_keep_data)
{
if (info.m_texture->isReady() && !info.m_texture->getData())
{
g_log_error.log("Renderer") << "Cannot keep data for texture " << m_path.c_str() << "because the texture has already been loaded.";
return false;
}
if (!data_kept)
{
info.m_texture->addDataReference();
data_kept = true;
}
}
}
}
else if (strcmp("uniform", label) == 0)
{
Uniform& uniform = m_uniforms.pushEmpty();
serializer.deserialize(uniform.m_name, Uniform::MAX_NAME_LENGTH);
copyString(info.m_uniform, sizeof(info.m_uniform), uniform.m_name);
uniform.m_name_hash = crc32(uniform.m_name);
uniform.m_type = Uniform::INT;
uniform.m_int = info.m_texture ? m_textures.size() - 1 : m_textures.size();
}
else if (strcmp("keep_data", label) == 0)
{
serializer.deserialize(info.m_keep_data);
if (info.m_keep_data && info.m_texture)
{
if (info.m_texture->isReady() && !info.m_texture->getData())
{
g_log_error.log("Renderer") << "Cannot keep data for texture " << info.m_texture->getPath().c_str() << ", it's already loaded.";
return false;
}
if (!data_kept)
{
data_kept = true;
info.m_texture->addDataReference();
}
}
}
else
{
g_log_error.log("Renderer") << "Unknown data \"" << label << "\" in material " << m_path.c_str();
return false;
}
}
serializer.deserializeObjectEnd();
return true;
}
void Material::loaded(FS::IFile* file, bool success, FS::FileSystem& fs)
{
PROFILE_FUNCTION();
if(success)
{
JsonSerializer serializer(*file, JsonSerializer::READ, m_path.c_str());
serializer.deserializeObjectBegin();
char path[LUMIX_MAX_PATH];
char label[256];
char material_dir[LUMIX_MAX_PATH];
PathUtils::getDir(material_dir, LUMIX_MAX_PATH, m_path.c_str());
while (!serializer.isObjectEnd())
{
serializer.deserializeLabel(label, 255);
if (strcmp(label, "uniforms") == 0)
{
deserializeUniforms(serializer);
}
else if (strcmp(label, "texture") == 0)
{
if (!deserializeTexture(serializer, material_dir))
{
onFailure();
fs.close(file);
return;
}
}
else if (strcmp(label, "alpha_to_coverage") == 0)
{
serializer.deserialize(m_is_alpha_to_coverage);
}
else if (strcmp(label, "shader") == 0)
{
serializer.deserialize(path, MAX_PATH);
m_shader = static_cast<Shader*>(m_resource_manager.get(ResourceManager::SHADER)->load(path));
addDependency(*m_shader);
}
else if (strcmp(label, "z_test") == 0)
{
serializer.deserialize(m_is_z_test);
}
else if (strcmp(label, "backface_culling") == 0)
{
serializer.deserialize(m_is_backface_culling);
}
else if (strcmp(label, "depth_func") == 0)
{
char tmp[30];
serializer.deserialize(tmp, 30);
if (strcmp(tmp, "lequal") == 0)
{
m_depth_func = DepthFunc::LEQUAL;
}
else if (strcmp(tmp, "less") == 0)
{
m_depth_func = DepthFunc::LESS;
}
else
{
g_log_warning.log("Renderer") << "Unknown depth function " << tmp << " in material " << m_path.c_str();
}
}
else
{
g_log_warning.log("renderer") << "Unknown parameter " << label << " in material " << m_path.c_str();
}
}
serializer.deserializeObjectEnd();
if (!m_shader)
{
g_log_error.log("renderer") << "Material " << m_path.c_str() << " without a shader";
onFailure();
fs.close(file);
return;
}
m_size = file->size();
decrementDepCount();
}
else
{
g_log_info.log("renderer") << "Error loading material " << m_path.c_str();
onFailure();
}
fs.close(file);
}
} // ~namespace Lumix
|
save all material's properties
|
save all material's properties
|
C++
|
mit
|
zhouxh1023/LumixEngine,dreamsxin/LuxEngine,dreamsxin/LuxEngine,JakubLukas/LumixEngine,JakubLukas/LumixEngine,JakubLukas/LumixEngine,zhouxh1023/LumixEngine,gamedevforks/LumixEngine,galek/LumixEngine,gamedevforks/LumixEngine,galek/LumixEngine
|
dae39f0a7abfc41c122f4f2d54d6cf9e26cafe7a
|
src/nix/describe-stores.cc
|
src/nix/describe-stores.cc
|
#include "command.hh"
#include "common-args.hh"
#include "shared.hh"
#include "store-api.hh"
#include <nlohmann/json.hpp>
using namespace nix;
struct CmdDescribeStores : Command, MixJSON
{
std::string description() override
{
return "show registered store types and their available options";
}
Category category() override { return catUtility; }
void run() override
{
if (json) {
auto availableStores = *implementations;
} else {
throw Error("Only json is available for describe-stores");
}
}
};
static auto r1 = registerCommand<CmdDescribeStores>("describe-stores");
|
#include "command.hh"
#include "common-args.hh"
#include "shared.hh"
#include "store-api.hh"
#include <nlohmann/json.hpp>
using namespace nix;
struct CmdDescribeStores : Command, MixJSON
{
std::string description() override
{
return "show registered store types and their available options";
}
Category category() override { return catUtility; }
void run() override
{
if (json) {
auto res = nlohmann::json::array();
for (auto & implem : *Implementations::registered) {
auto storeConfig = implem.getConfig();
std::cout << storeConfig->toJSON().dump() << std::endl;
}
} else {
throw Error("Only json is available for describe-stores");
}
}
};
static auto r1 = registerCommand<CmdDescribeStores>("describe-stores");
|
Make `nix describe-stores` functional
|
Make `nix describe-stores` functional
Using the `*Config` class hierarchy
|
C++
|
lgpl-2.1
|
rycee/nix,NixOS/nix,NixOS/nix,NixOS/nix,rycee/nix,rycee/nix,rycee/nix,NixOS/nix,rycee/nix,NixOS/nix
|
811aba4b25d4df3e7b6d0979ac10588f7594f046
|
allocore/allocore/graphics/al_Mesh.hpp
|
allocore/allocore/graphics/al_Mesh.hpp
|
#ifndef INCLUDE_AL_GRAPHICS_MESH_HPP
#define INCLUDE_AL_GRAPHICS_MESH_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
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 University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
A generic mesh object for vertex-based geometry
File author(s):
Wesley Smith, 2010, [email protected]
Lance Putnam, 2010, [email protected]
Graham Wakefield, 2010, [email protected]
*/
#include <stdio.h>
#include "allocore/math/al_Vec.hpp"
#include "allocore/math/al_Matrix4.hpp"
#include "allocore/types/al_Buffer.hpp"
#include "allocore/types/al_Color.hpp"
namespace al{
/// Stores buffers related to rendering graphical objects
/// A mesh is a collection of buffers storing vertices, colors, indices, etc.
/// that define the geometry and coloring/shading of a graphical object.
class Mesh {
public:
typedef Vec3f Vertex;
typedef Vec3f Normal;
//typedef Vec4f Color;
typedef Vec2f TexCoord2;
typedef Vec3f TexCoord3;
typedef unsigned int Index;
typedef Vec3i TriFace;
typedef Vec4i QuadFace;
typedef Buffer<Vertex> Vertices;
typedef Buffer<Normal> Normals;
typedef Buffer<Color> Colors;
typedef Buffer<Colori> Coloris;
typedef Buffer<TexCoord2> TexCoord2s;
typedef Buffer<TexCoord3> TexCoord3s;
typedef Buffer<Index> Indices;
/// @param[in] primitive renderer-dependent primitive number
Mesh(int primitive=0): mPrimitive(primitive){}
Mesh(const Mesh& cpy) :
mVertices(cpy.mVertices),
mNormals(cpy.mNormals),
mColors(cpy.mColors),
mColoris(cpy.mColoris),
mTexCoord2s(cpy.mTexCoord2s),
mTexCoord3s(cpy.mTexCoord3s),
mIndices(cpy.mIndices),
mPrimitive(cpy.mPrimitive)
{}
/// Get corners of bounding box of vertices
/// @param[out] min minimum corner of bounding box
/// @param[out] max maximum corner of bounding box
void getBounds(Vec3f& min, Vec3f& max) const;
/// Get center of vertices
Vertex getCenter() const;
// destructive edits to internal vertices:
/// Convert indices (if any) to flat vertex buffers
void decompress();
/// Extend buffers to match number of vertices
/// This will resize all populated buffers to match the size of the vertex
/// buffer. Buffers are extended by copying their last element.
void equalizeBuffers();
/// Append buffers from another mesh:
void merge(const Mesh& src);
/// Reset all buffers
Mesh& reset();
/// Scale all vertices to lie in [-1,1]
void unitize(bool proportional=true);
/// Scale all vertices
Mesh& scale(float x, float y, float z);
Mesh& scale(float s){ return scale(s,s,s); }
template <class T>
Mesh& scale(const Vec<3,T>& v){ return scale(v[0],v[1],v[2]); }
/// Translate all vertices
Mesh& translate(float x, float y, float z);
template <class T>
Mesh& translate(const Vec<3,T>& v){ return translate(v[0],v[1],v[2]); }
/// Transform vertices by projective transform matrix
/// @param[in] m projective transform matrix
/// @param[in] begin beginning index of vertices
/// @param[in] end ending index of vertices, negative amounts specify
/// distance from one past last element
template <class T>
Mesh& transform(const Mat<4,T>& m, int begin=0, int end=-1);
/// Generates indices for a set of vertices
void compress();
/// Generates normals for a set of vertices
/// This method will generate a normal for each vertex in the buffer
/// assuming the drawing primitive is either triangles or a triangle strip.
/// Averaged vertex normals are generated if indices are present and, for
/// triangles only, face normals are generated if no indices are present.
/// This will replace any normals currently in use.
///
/// @param[in] normalize whether to normalize normals
/// @param[in] equalWeightPerFace whether to use an equal weighting of
/// face normals rather than a weighting
/// based on face areas
void generateNormals(bool normalize=true, bool equalWeightPerFace=false);
/// Invert direction of normals
void invertNormals();
/// Creates a mesh filled with lines for each normal of the source
/// @param[out] mesh normal lines
/// @param[in] length length of normals
/// @param[in] perFace whether normals line should be generated per
/// face rather than per vertex
void createNormalsMesh(Mesh& mesh, float length=0.1, bool perFace=false);
/// Ribbonize curve
/// This creates a two-dimensional ribbon from a one-dimensional space curve.
/// The result is to be rendered with a triangle strip.
/// @param[in] width Width of ribbon
/// @param[in] faceBinormal If true, surface faces binormal vector of curve.
/// If false, surface faces normal vector of curve.
void ribbonize(float width=0.04, bool faceBinormal=false){
ribbonize(&width, 0, faceBinormal);
}
/// Ribbonize curve
/// This creates a two-dimensional ribbon from a one-dimensional space curve.
/// The result is to be rendered with a triangle strip.
/// @param[in] widths Array specifying width of ribbon at each point along curve
/// @param[in] widthsStride Stride factor of width array
/// @param[in] faceBinormal If true, surface faces binormal vector of curve.
/// If false, surface faces normal vector of curve.
void ribbonize(float * widths, int widthsStride=1, bool faceBinormal=false);
int primitive() const { return mPrimitive; }
const Buffer<Vertex>& vertices() const { return mVertices; }
const Buffer<Normal>& normals() const { return mNormals; }
const Buffer<Color>& colors() const { return mColors; }
const Buffer<Colori>& coloris() const { return mColoris; }
const Buffer<TexCoord2>& texCoord2s() const { return mTexCoord2s; }
const Buffer<TexCoord3>& texCoord3s() const { return mTexCoord3s; }
const Buffer<Index>& indices() const { return mIndices; }
/// Set geometric primitive
Mesh& primitive(int prim){ mPrimitive=prim; return *this; }
/// Repeat last vertex element(s)
Mesh& repeatLast();
/// Append index to index buffer
void index(unsigned int i){ indices().append(i); }
/// Append indices to index buffer
template <class Tindex>
void index(const Tindex * buf, int size, Tindex indexOffset=0){
for(int i=0; i<size; ++i) index((Index)(buf[i] + indexOffset)); }
/// Append color to color buffer
void color(const Color& v) { colors().append(v); }
/// Append color to color buffer
void color(const Colori& v) { coloris().append(v); }
/// Append color to color buffer
void color(const HSV& v) { colors().append(v); }
/// Append color to color buffer
void color(const RGB& v) { colors().append(v); }
/// Append color to color buffer
void color(float r, float g, float b, float a=1){ color(Color(r,g,b,a)); }
/// Append color to color buffer
template <class T>
void color(const Vec<4,T>& v) { color(v[0], v[1], v[2], v[3]); }
/// Append floating-point color to integer color buffer
void colori(const Color& v) { coloris().append(Colori(v)); }
/// Append normal to normal buffer
void normal(float x, float y, float z=0){ normal(Normal(x,y,z)); }
/// Append normal to normal buffer
void normal(const Normal& v) { normals().append(v); }
/// Append normal to normal buffer
template <class T>
void normal(const Vec<2,T>& v, float z=0){ normal(v[0], v[1], z); }
/// Append texture coordinate to 2D texture coordinate buffer
void texCoord(float u, float v){ texCoord(TexCoord2(u,v)); }
/// Append texture coordinate to 2D texture coordinate buffer
void texCoord(const TexCoord2& v){ texCoord2s().append(v); }
/// Append texture coordinate to 3D texture coordinate buffer
void texCoord(float u, float v, float w){ texCoord(TexCoord3(u,v,w)); }
/// Append texture coordinate to 3D texture coordinate buffer
void texCoord(const TexCoord3& v){ texCoord3s().append(v); }
/// Append vertex to vertex buffer
void vertex(float x, float y, float z=0){ vertex(Vertex(x,y,z)); }
/// Append vertex to vertex buffer
void vertex(const Vertex& v){ vertices().append(v); }
/// Append vertex to vertex buffer
template <class T>
void vertex(const Vec<2,T>& v, float z=0){ vertex(v[0], v[1], z); }
/// Append vertices to vertex buffer
template <class T>
void vertex(const T * buf, int size){
for(int i=0; i<size; ++i) vertex(buf[3*i+0], buf[3*i+1], buf[3*i+2]);
}
/// Append vertices to vertex buffer
template <class T>
void vertex(const Vec<3,T> * buf, int size){
for(int i=0; i<size; ++i) vertex(buf[i][0], buf[i][1], buf[i][2]);
}
// /// Get number of faces (assumes triangles or quads)
// int numFaces() const { return mIndices.size() / ( ( mPrimitive == Graphics::TRIANGLES ) ? 3 : 4 ); }
// /// Get indices as triangles
// TriFace& indexAsTri(){ return (TriFace*) indices(); }
// /// Get indices as quads
// QuadFace& indexAsQuad(){ return (QuadFace*) indices(); }
Vertices& vertices(){ return mVertices; }
Normals& normals(){ return mNormals; }
Colors& colors(){ return mColors; }
Coloris& coloris(){ return mColoris; }
TexCoord2s& texCoord2s(){ return mTexCoord2s; }
TexCoord3s& texCoord3s(){ return mTexCoord3s; }
Indices& indices(){ return mIndices; }
/// Export mesh to an STL file
/// STL (STereoLithography) is a file format used widely for
/// rapid prototyping. It contains only surface geometry (vertices and
/// normals) as a list of triangular facets.
/// This implementation saves an ASCII (as opposed to binary) STL file.
///
/// @param[in] filePath path of file to save to
/// @param[in] solidName solid name defined within the STL file (optional)
/// \returns true on successful export, otherwise false
bool exportSTL(const char * filePath, const char * solidName = "") const;
/// Print information about Mesh
void print(FILE * dst = stderr) const;
protected:
// Only populated (size>0) buffers will be used
Vertices mVertices;
Normals mNormals;
Colors mColors;
Coloris mColoris;
TexCoord2s mTexCoord2s;
TexCoord3s mTexCoord3s;
Indices mIndices;
int mPrimitive;
};
template <class T>
Mesh& Mesh::transform(const Mat<4,T>& m, int begin, int end){
if(end<0) end += vertices().size()+1; // negative index wraps to end of array
for(int i=begin; i<end; ++i){
Vertex& v = vertices()[i];
v.set(m * Vec<4,T>(v, 1));
}
return *this;
}
} // al::
#endif
|
#ifndef INCLUDE_AL_GRAPHICS_MESH_HPP
#define INCLUDE_AL_GRAPHICS_MESH_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
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 University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
A generic mesh object for vertex-based geometry
File author(s):
Wesley Smith, 2010, [email protected]
Lance Putnam, 2010, [email protected]
Graham Wakefield, 2010, [email protected]
*/
#include <stdio.h>
#include "allocore/math/al_Vec.hpp"
#include "allocore/math/al_Matrix4.hpp"
#include "allocore/types/al_Buffer.hpp"
#include "allocore/types/al_Color.hpp"
namespace al{
/// Stores buffers related to rendering graphical objects
/// A mesh is a collection of buffers storing vertices, colors, indices, etc.
/// that define the geometry and coloring/shading of a graphical object.
class Mesh {
public:
typedef Vec3f Vertex;
typedef Vec3f Normal;
//typedef Vec4f Color;
typedef Vec2f TexCoord2;
typedef Vec3f TexCoord3;
typedef unsigned int Index;
typedef Vec3i TriFace;
typedef Vec4i QuadFace;
typedef Buffer<Vertex> Vertices;
typedef Buffer<Normal> Normals;
typedef Buffer<Color> Colors;
typedef Buffer<Colori> Coloris;
typedef Buffer<TexCoord2> TexCoord2s;
typedef Buffer<TexCoord3> TexCoord3s;
typedef Buffer<Index> Indices;
/// @param[in] primitive renderer-dependent primitive number
Mesh(int primitive=0): mPrimitive(primitive){}
Mesh(const Mesh& cpy) :
mVertices(cpy.mVertices),
mNormals(cpy.mNormals),
mColors(cpy.mColors),
mColoris(cpy.mColoris),
mTexCoord2s(cpy.mTexCoord2s),
mTexCoord3s(cpy.mTexCoord3s),
mIndices(cpy.mIndices),
mPrimitive(cpy.mPrimitive)
{}
/// Get corners of bounding box of vertices
/// @param[out] min minimum corner of bounding box
/// @param[out] max maximum corner of bounding box
void getBounds(Vec3f& min, Vec3f& max) const;
/// Get center of vertices
Vertex getCenter() const;
// destructive edits to internal vertices:
/// Convert indices (if any) to flat vertex buffers
void decompress();
/// Extend buffers to match number of vertices
/// This will resize all populated buffers to match the size of the vertex
/// buffer. Buffers are extended by copying their last element.
void equalizeBuffers();
/// Append buffers from another mesh:
void merge(const Mesh& src);
/// Reset all buffers
Mesh& reset();
/// Scale all vertices to lie in [-1,1]
void unitize(bool proportional=true);
/// Scale all vertices
Mesh& scale(float x, float y, float z);
Mesh& scale(float s){ return scale(s,s,s); }
template <class T>
Mesh& scale(const Vec<3,T>& v){ return scale(v[0],v[1],v[2]); }
/// Translate all vertices
Mesh& translate(float x, float y, float z);
template <class T>
Mesh& translate(const Vec<3,T>& v){ return translate(v[0],v[1],v[2]); }
/// Transform vertices by projective transform matrix
/// @param[in] m projective transform matrix
/// @param[in] begin beginning index of vertices
/// @param[in] end ending index of vertices, negative amounts specify
/// distance from one past last element
template <class T>
Mesh& transform(const Mat<4,T>& m, int begin=0, int end=-1);
/// Generates indices for a set of vertices
void compress();
/// Generates normals for a set of vertices
/// This method will generate a normal for each vertex in the buffer
/// assuming the drawing primitive is either triangles or a triangle strip.
/// Averaged vertex normals are generated if indices are present and, for
/// triangles only, face normals are generated if no indices are present.
/// This will replace any normals currently in use.
///
/// @param[in] normalize whether to normalize normals
/// @param[in] equalWeightPerFace whether to use an equal weighting of
/// face normals rather than a weighting
/// based on face areas
void generateNormals(bool normalize=true, bool equalWeightPerFace=false);
/// Invert direction of normals
void invertNormals();
/// Creates a mesh filled with lines for each normal of the source
/// @param[out] mesh normal lines
/// @param[in] length length of normals
/// @param[in] perFace whether normals line should be generated per
/// face rather than per vertex
void createNormalsMesh(Mesh& mesh, float length=0.1, bool perFace=false);
/// Ribbonize curve
/// This creates a two-dimensional ribbon from a one-dimensional space curve.
/// The result is to be rendered with a triangle strip.
/// @param[in] width Width of ribbon
/// @param[in] faceBinormal If true, surface faces binormal vector of curve.
/// If false, surface faces normal vector of curve.
void ribbonize(float width=0.04, bool faceBinormal=false){
ribbonize(&width, 0, faceBinormal);
}
/// Ribbonize curve
/// This creates a two-dimensional ribbon from a one-dimensional space curve.
/// The result is to be rendered with a triangle strip.
/// @param[in] widths Array specifying width of ribbon at each point along curve
/// @param[in] widthsStride Stride factor of width array
/// @param[in] faceBinormal If true, surface faces binormal vector of curve.
/// If false, surface faces normal vector of curve.
void ribbonize(float * widths, int widthsStride=1, bool faceBinormal=false);
int primitive() const { return mPrimitive; }
const Buffer<Vertex>& vertices() const { return mVertices; }
const Buffer<Normal>& normals() const { return mNormals; }
const Buffer<Color>& colors() const { return mColors; }
const Buffer<Colori>& coloris() const { return mColoris; }
const Buffer<TexCoord2>& texCoord2s() const { return mTexCoord2s; }
const Buffer<TexCoord3>& texCoord3s() const { return mTexCoord3s; }
const Buffer<Index>& indices() const { return mIndices; }
/// Set geometric primitive
Mesh& primitive(int prim){ mPrimitive=prim; return *this; }
/// Repeat last vertex element(s)
Mesh& repeatLast();
/// Append index to index buffer
void index(unsigned int i){ indices().append(i); }
/// Append indices to index buffer
template <class Tindex>
void index(const Tindex * buf, int size, Tindex indexOffset=0){
for(int i=0; i<size; ++i) index((Index)(buf[i] + indexOffset)); }
/// Append color to color buffer
void color(const Color& v) { colors().append(v); }
/// Append color to color buffer
void color(const Colori& v) { coloris().append(v); }
/// Append color to color buffer
void color(const HSV& v) { colors().append(v); }
/// Append color to color buffer
void color(const RGB& v) { colors().append(v); }
/// Append color to color buffer
void color(float r, float g, float b, float a=1){ color(Color(r,g,b,a)); }
/// Append color to color buffer
template <class T>
void color(const Vec<4,T>& v) { color(v[0], v[1], v[2], v[3]); }
/// Append floating-point color to integer color buffer
void colori(const Color& v) { coloris().append(Colori(v)); }
/// Append normal to normal buffer
void normal(float x, float y, float z=0){ normal(Normal(x,y,z)); }
/// Append normal to normal buffer
void normal(const Normal& v) { normals().append(v); }
/// Append normal to normal buffer
template <class T>
void normal(const Vec<2,T>& v, float z=0){ normal(v[0], v[1], z); }
/// Append texture coordinate to 2D texture coordinate buffer
void texCoord(float u, float v){ texCoord2s().append(TexCoord2(u,v)); }
/// Append texture coordinate to 2D texture coordinate buffer
template <class T>
void texCoord(const Vec<2,T>& v){ texCoord(v[0], v[1]); }
/// Append texture coordinate to 3D texture coordinate buffer
void texCoord(float u, float v, float w){ texCoord3s().append(TexCoord3(u,v,w)); }
/// Append texture coordinate to 3D texture coordinate buffer
template <class T>
void texCoord(const Vec<3,T>& v){ texCoord(v[0], v[1], v[2]); }
/// Append vertex to vertex buffer
void vertex(float x, float y, float z=0){ vertex(Vertex(x,y,z)); }
/// Append vertex to vertex buffer
void vertex(const Vertex& v){ vertices().append(v); }
/// Append vertex to vertex buffer
template <class T>
void vertex(const Vec<2,T>& v, float z=0){ vertex(v[0], v[1], z); }
/// Append vertices to vertex buffer
template <class T>
void vertex(const T * buf, int size){
for(int i=0; i<size; ++i) vertex(buf[3*i+0], buf[3*i+1], buf[3*i+2]);
}
/// Append vertices to vertex buffer
template <class T>
void vertex(const Vec<3,T> * buf, int size){
for(int i=0; i<size; ++i) vertex(buf[i][0], buf[i][1], buf[i][2]);
}
// /// Get number of faces (assumes triangles or quads)
// int numFaces() const { return mIndices.size() / ( ( mPrimitive == Graphics::TRIANGLES ) ? 3 : 4 ); }
// /// Get indices as triangles
// TriFace& indexAsTri(){ return (TriFace*) indices(); }
// /// Get indices as quads
// QuadFace& indexAsQuad(){ return (QuadFace*) indices(); }
Vertices& vertices(){ return mVertices; }
Normals& normals(){ return mNormals; }
Colors& colors(){ return mColors; }
Coloris& coloris(){ return mColoris; }
TexCoord2s& texCoord2s(){ return mTexCoord2s; }
TexCoord3s& texCoord3s(){ return mTexCoord3s; }
Indices& indices(){ return mIndices; }
/// Export mesh to an STL file
/// STL (STereoLithography) is a file format used widely for
/// rapid prototyping. It contains only surface geometry (vertices and
/// normals) as a list of triangular facets.
/// This implementation saves an ASCII (as opposed to binary) STL file.
///
/// @param[in] filePath path of file to save to
/// @param[in] solidName solid name defined within the STL file (optional)
/// \returns true on successful export, otherwise false
bool exportSTL(const char * filePath, const char * solidName = "") const;
/// Print information about Mesh
void print(FILE * dst = stderr) const;
protected:
// Only populated (size>0) buffers will be used
Vertices mVertices;
Normals mNormals;
Colors mColors;
Coloris mColoris;
TexCoord2s mTexCoord2s;
TexCoord3s mTexCoord3s;
Indices mIndices;
int mPrimitive;
};
template <class T>
Mesh& Mesh::transform(const Mat<4,T>& m, int begin, int end){
if(end<0) end += vertices().size()+1; // negative index wraps to end of array
for(int i=begin; i<end; ++i){
Vertex& v = vertices()[i];
v.set(m * Vec<4,T>(v, 1));
}
return *this;
}
} // al::
#endif
|
fix ambiguous overload of texCoord when passing in a Vec
|
fix ambiguous overload of texCoord when passing in a Vec
|
C++
|
bsd-3-clause
|
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
|
aa171fa069728fbd39a9dd82be3bf61798d3d9cd
|
src/nostalgia/core/gfx.hpp
|
src/nostalgia/core/gfx.hpp
|
/*
* Copyright 2016 - 2019 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <ox/std/types.hpp>
#include "context.hpp"
#include "types.hpp"
namespace nostalgia::core {
using Color = uint16_t;
struct NostalgiaPalette {
static constexpr auto Fields = 1;
ox::Vector<Color> colors;
};
struct NostalgiaGraphic {
static constexpr auto Fields = 4;
uint8_t bpp = 0;
ox::FileAddress defaultPalette;
ox::Vector<Color> pal;
ox::Vector<uint8_t> tiles;
};
template<typename T>
ox::Error modelWrite(T *io, NostalgiaGraphic *ng) {
io->setTypeInfo("nostalgia::core::NostalgiaGraphic", NostalgiaGraphic::Fields);
oxReturnError(io->field("bpp", &ng->bpp));
oxReturnError(io->field("defaultPalette", &ng->defaultPalette));
oxReturnError(io->field("pal", &ng->pal));
oxReturnError(io->field("tiles", &ng->tiles));
return OxError(0);
}
template<typename T>
ox::Error modelWrite(T *io, NostalgiaPalette *pal) {
io->setTypeInfo("nostalgia::core::NostalgiaPalette", NostalgiaPalette::Fields);
oxReturnError(io->field("colors", &pal->colors));
return OxError(0);
}
ox::Error initGfx(Context *ctx);
ox::Error initConsole(Context *ctx);
ox::Error loadTileSheet(Context *ctx, ox::FileAddress file);
void puts(Context *ctx, int loc, const char *str);
void setTile(Context *ctx, int layer, int column, int row, uint8_t tile);
}
|
/*
* Copyright 2016 - 2019 [email protected]
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <ox/std/types.hpp>
#include "context.hpp"
#include "types.hpp"
namespace nostalgia::core {
using Color = uint16_t;
struct NostalgiaPalette {
static constexpr auto Fields = 1;
ox::Vector<Color> colors;
};
struct NostalgiaGraphic {
static constexpr auto Fields = 4;
uint8_t bpp = 0;
ox::FileAddress defaultPalette;
ox::Vector<Color> pal;
ox::Vector<uint8_t> tiles;
};
template<typename T>
ox::Error model(T *io, NostalgiaGraphic *ng) {
io->setTypeInfo("nostalgia::core::NostalgiaGraphic", NostalgiaGraphic::Fields);
oxReturnError(io->field("bpp", &ng->bpp));
oxReturnError(io->field("defaultPalette", &ng->defaultPalette));
oxReturnError(io->field("pal", &ng->pal));
oxReturnError(io->field("tiles", &ng->tiles));
return OxError(0);
}
template<typename T>
ox::Error model(T *io, NostalgiaPalette *pal) {
io->setTypeInfo("nostalgia::core::NostalgiaPalette", NostalgiaPalette::Fields);
oxReturnError(io->field("colors", &pal->colors));
return OxError(0);
}
ox::Error initGfx(Context *ctx);
ox::Error initConsole(Context *ctx);
ox::Error loadTileSheet(Context *ctx, ox::FileAddress file);
void puts(Context *ctx, int loc, const char *str);
void setTile(Context *ctx, int layer, int column, int row, uint8_t tile);
}
|
Remove Write distictions from Graphic and Palette models
|
[nostalgia/core] Remove Write distictions from Graphic and Palette models
|
C++
|
mpl-2.0
|
wombatant/nostalgia,wombatant/nostalgia,wombatant/nostalgia
|
842a4e5abd2c766e10368fac1251a16e2c389a00
|
paddle/fluid/inference/tests/api/analyzer_capi_tester.cc
|
paddle/fluid/inference/tests/api/analyzer_capi_tester.cc
|
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string>
#include <vector>
#include "paddle/fluid/inference/capi/paddle_c_api.h"
#include "paddle/fluid/inference/tests/api/tester_helper.h"
namespace paddle {
namespace inference {
namespace analysis {
void zero_copy_run() {
std::string model_dir = FLAGS_infer_model;
std::string prog_file = model_dir + "/model";
std::string params_file = model_dir + "/params";
PD_AnalysisConfig *config = PD_NewAnalysisConfig();
PD_DisableGpu(config);
PD_SetCpuMathLibraryNumThreads(config, 10);
PD_SwitchUseFeedFetchOps(config, false);
PD_SwitchSpecifyInputNames(config, true);
PD_SwitchIrDebug(config, true);
PD_SetModel(config, prog_file.c_str(), params_file.c_str());
bool use_feed_fetch = PD_UseFeedFetchOpsEnabled(config);
EXPECT_FALSE(use_feed_fetch);
bool specify_input_names = PD_SpecifyInputName(config);
EXPECT_TRUE(specify_input_names);
const int batch_size = 1;
const int channels = 3;
const int height = 318;
const int width = 318;
float *input = new float[batch_size * channels * height * width]();
int shape[4] = {batch_size, channels, height, width};
int shape_size = 4;
int in_size = 1;
int out_size;
PD_ZeroCopyData *inputs = new PD_ZeroCopyData;
PD_ZeroCopyData *outputs = new PD_ZeroCopyData;
inputs->data = static_cast<void *>(input);
inputs->dtype = PD_FLOAT32;
inputs->name = new char[5];
inputs->name[0] = 'd';
inputs->name[1] = 'a';
inputs->name[2] = 't';
inputs->name[3] = 'a';
inputs->name[4] = '\0';
inputs->shape = shape;
inputs->shape_size = shape_size;
PD_PredictorZeroCopyRun(config, inputs, in_size, &outputs, &out_size);
delete[] input;
delete[] inputs;
delete[] outputs;
}
TEST(PD_PredictorZeroCopyRun, zero_copy_run) { zero_copy_run(); }
#ifdef PADDLE_WITH_MKLDNN
TEST(PD_AnalysisConfig, profile_mkldnn) {
std::string model_dir = FLAGS_infer_model;
std::string prog_file = model_dir + "/model";
std::string params_file = model_dir + "/params";
PD_AnalysisConfig *config = PD_NewAnalysisConfig();
PD_DisableGpu(config);
PD_SetCpuMathLibraryNumThreads(config, 10);
PD_SwitchUseFeedFetchOps(config, false);
PD_SwitchSpecifyInputNames(config, true);
PD_SwitchIrDebug(config, true);
PD_EnableMKLDNN(config);
bool mkldnn_enable = PD_MkldnnEnabled(config);
EXPECT_TRUE(mkldnn_enable);
PD_EnableMkldnnQuantizer(config);
bool quantizer_enable = PD_MkldnnQuantizerEnabled(config);
EXPECT_TRUE(quantizer_enable);
PD_EnableMkldnnBfloat16(config);
bool bfloat16_enable = PD_MkldnnBfloat16Enabled(config);
EXPECT_TRUE(bfloat16_enable);
PD_SetMkldnnCacheCapacity(config, 0);
PD_SetModel(config, prog_file.c_str(), params_file.c_str());
PD_DeleteAnalysisConfig(config);
}
#endif
} // namespace analysis
} // namespace inference
} // namespace paddle
|
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string>
#include <vector>
#include "paddle/fluid/inference/capi/paddle_c_api.h"
#include "paddle/fluid/inference/tests/api/tester_helper.h"
namespace paddle {
namespace inference {
namespace analysis {
void zero_copy_run() {
std::string model_dir = FLAGS_infer_model;
std::string prog_file = model_dir + "/model";
std::string params_file = model_dir + "/params";
PD_AnalysisConfig *config = PD_NewAnalysisConfig();
PD_DisableGpu(config);
PD_SetCpuMathLibraryNumThreads(config, 10);
PD_SwitchUseFeedFetchOps(config, false);
PD_SwitchSpecifyInputNames(config, true);
PD_SwitchIrDebug(config, true);
PD_SetModel(config, prog_file.c_str(), params_file.c_str());
bool use_feed_fetch = PD_UseFeedFetchOpsEnabled(config);
EXPECT_FALSE(use_feed_fetch);
bool specify_input_names = PD_SpecifyInputName(config);
EXPECT_TRUE(specify_input_names);
const int batch_size = 1;
const int channels = 3;
const int height = 318;
const int width = 318;
float *input = new float[batch_size * channels * height * width]();
int shape[4] = {batch_size, channels, height, width};
int shape_size = 4;
int in_size = 1;
int out_size;
PD_ZeroCopyData *inputs = new PD_ZeroCopyData;
PD_ZeroCopyData *outputs = new PD_ZeroCopyData;
inputs->data = static_cast<void *>(input);
inputs->dtype = PD_FLOAT32;
inputs->name = new char[5];
inputs->name[0] = 'd';
inputs->name[1] = 'a';
inputs->name[2] = 't';
inputs->name[3] = 'a';
inputs->name[4] = '\0';
inputs->shape = shape;
inputs->shape_size = shape_size;
PD_PredictorZeroCopyRun(config, inputs, in_size, &outputs, &out_size);
delete[] input;
delete[] inputs;
delete[] outputs;
}
TEST(PD_PredictorZeroCopyRun, zero_copy_run) { zero_copy_run(); }
#ifdef PADDLE_WITH_MKLDNN
TEST(PD_AnalysisConfig, profile_mkldnn) {
std::string model_dir = FLAGS_infer_model;
std::string prog_file = model_dir + "/model";
std::string params_file = model_dir + "/params";
PD_AnalysisConfig *config = PD_NewAnalysisConfig();
PD_DisableGpu(config);
PD_SetCpuMathLibraryNumThreads(config, 10);
PD_SwitchUseFeedFetchOps(config, false);
PD_SwitchSpecifyInputNames(config, true);
PD_SwitchIrDebug(config, true);
PD_EnableMKLDNN(config);
bool mkldnn_enable = PD_MkldnnEnabled(config);
EXPECT_TRUE(mkldnn_enable);
PD_EnableMkldnnQuantizer(config);
bool quantizer_enable = PD_MkldnnQuantizerEnabled(config);
EXPECT_TRUE(quantizer_enable);
PD_EnableMkldnnBfloat16(config);
PD_SetMkldnnCacheCapacity(config, 0);
PD_SetModel(config, prog_file.c_str(), params_file.c_str());
PD_DeleteAnalysisConfig(config);
}
#endif
} // namespace analysis
} // namespace inference
} // namespace paddle
|
fix analyzer_capi_tester, test=develop (#28289)
|
fix analyzer_capi_tester, test=develop (#28289)
|
C++
|
apache-2.0
|
luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,PaddlePaddle/Paddle,luotao1/Paddle,PaddlePaddle/Paddle
|
a126100be60d4e75a2d6b4b33a63c4aadf58d961
|
src/npge/cpp/lua_model.cpp
|
src/npge/cpp/lua_model.cpp
|
/*
* NPG-explorer, Nucleotide PanGenome explorer
* Copyright (C) 2012-2015 Boris Nagaev
*
* See the LICENSE file for terms of use.
*/
#include <cstdlib>
#include <memory>
#define LUA_LIB
#include <lua.hpp>
#include "model.hpp"
#include "throw_assert.hpp"
using namespace npge;
#define LUA_CALL_WRAPPED(f) \
int results = f(L); \
if (results == -1) { \
return lua_error(L); \
} else { \
return results; \
}
// first upvalue: metatable for Sequence instance
int lua_Sequence_impl(lua_State *L) {
size_t name_size, text_size;
const char* name = luaL_checklstring(L, 1, &name_size);
const char* text = luaL_checklstring(L, 2, &text_size);
const char* description = "";
size_t description_size = 0;
if (lua_gettop(L) >= 3 && lua_type(L, 3) == LUA_TSTRING) {
description = luaL_checklstring(L, 3,
&description_size);
}
void* s = lua_newuserdata(L, sizeof(SequencePtr));
try {
SequencePtr seq = Sequence::make(name, description,
text, text_size);
new (s) SequencePtr(seq);
} catch (std::exception& e) {
lua_pushstring(L, e.what());
return -1;
}
// get metatable of Sequence
lua_pushvalue(L, lua_upvalueindex(1));
lua_setmetatable(L, -2);
return 1;
}
int lua_Sequence(lua_State *L) {
LUA_CALL_WRAPPED(lua_Sequence_impl);
}
static SequencePtr& lua_toseq(lua_State* L, int index) {
void* v = luaL_checkudata(L, index, "npge_Sequence");
SequencePtr* s = reinterpret_cast<SequencePtr*>(v);
return *s;
}
int lua_Sequence_gc(lua_State *L) {
SequencePtr& seq = lua_toseq(L, 1);
seq.reset();
return 0;
}
int lua_Sequence_type(lua_State *L) {
lua_pushstring(L, "Sequence");
return 1;
}
int lua_Sequence_name(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
const std::string& name = seq->name();
lua_pushlstring(L, name.c_str(), name.size());
return 1;
}
int lua_Sequence_description(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
const std::string& description = seq->description();
lua_pushlstring(L, description.c_str(),
description.size());
return 1;
}
int lua_Sequence_genome(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
std::string genome = seq->genome();
if (!genome.empty()) {
lua_pushlstring(L, genome.c_str(), genome.size());
} else {
lua_pushnil(L);
}
return 1;
}
int lua_Sequence_chromosome(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
std::string chr = seq->chromosome();
if (!chr.empty()) {
lua_pushlstring(L, chr.c_str(), chr.size());
} else {
lua_pushnil(L);
}
return 1;
}
int lua_Sequence_circular(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
int circular = seq->circular();
lua_pushboolean(L, circular);
return 1;
}
int lua_Sequence_text(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
const std::string& text = seq->text();
lua_pushlstring(L, text.c_str(), text.size());
return 1;
}
int lua_Sequence_length(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
lua_pushinteger(L, seq->length());
return 1;
}
int lua_Sequence_sub_impl(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
int min = luaL_checkint(L, 2);
int max = luaL_checkint(L, 3);
try {
ASSERT_LTE(0, min);
ASSERT_LTE(min, max);
ASSERT_LT(max, seq->length());
} catch (std::exception& e) {
lua_pushstring(L, e.what());
return -1;
}
int len = max - min + 1;
const std::string& text = seq->text();
const char* slice = text.c_str() + min;
lua_pushlstring(L, slice, len);
return 1;
}
int lua_Sequence_sub(lua_State *L) {
LUA_CALL_WRAPPED(lua_Sequence_sub_impl);
}
int lua_Sequence_tostring(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
std::string repr = seq->tostring();
lua_pushlstring(L, repr.c_str(), repr.size());
return 1;
}
int lua_Sequence_eq(lua_State *L) {
const SequencePtr& a = lua_toseq(L, 1);
const SequencePtr& b = lua_toseq(L, 2);
int eq = ((*a) == (*b));
lua_pushboolean(L, eq);
return 1;
}
static const luaL_Reg Sequence_methods[] = {
{"__gc", lua_Sequence_gc},
{"type", lua_Sequence_type},
{"name", lua_Sequence_name},
{"description", lua_Sequence_description},
{"genome", lua_Sequence_genome},
{"chromosome", lua_Sequence_chromosome},
{"circular", lua_Sequence_circular},
{"text", lua_Sequence_text},
{"length", lua_Sequence_length},
{"sub", lua_Sequence_sub},
{"__tostring", lua_Sequence_tostring},
{"__eq", lua_Sequence_eq},
{NULL, NULL}
};
// -1 is module "model"
static void registerType(lua_State *L,
const char* type_name,
const char* mt_name,
lua_CFunction constructor,
const luaL_Reg* methods) {
luaL_newmetatable(L, mt_name);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index"); // mt.__index = mt
luaL_register(L, NULL, Sequence_methods);
lua_pushcclosure(L, constructor, 1);
lua_setfield(L, -2, type_name);
}
extern "C" {
int luaopen_npge_cmodel(lua_State *L) {
lua_newtable(L);
registerType(L, "Sequence", "npge_Sequence",
lua_Sequence, Sequence_methods);
return 1;
}
}
|
/*
* NPG-explorer, Nucleotide PanGenome explorer
* Copyright (C) 2012-2015 Boris Nagaev
*
* See the LICENSE file for terms of use.
*/
#include <cstdlib>
#include <memory>
#define LUA_LIB
#include <lua.hpp>
#include "model.hpp"
#include "throw_assert.hpp"
using namespace npge;
#define LUA_CALL_WRAPPED(f) \
int results = f(L); \
if (results == -1) { \
return lua_error(L); \
} else { \
return results; \
}
// first upvalue: metatable for Sequence instance
int lua_Sequence_impl(lua_State *L) {
size_t name_size, text_size;
const char* name = luaL_checklstring(L, 1, &name_size);
const char* text = luaL_checklstring(L, 2, &text_size);
const char* description = "";
size_t description_size = 0;
if (lua_gettop(L) >= 3 && lua_type(L, 3) == LUA_TSTRING) {
description = luaL_checklstring(L, 3,
&description_size);
}
void* s = lua_newuserdata(L, sizeof(SequencePtr));
try {
SequencePtr seq = Sequence::make(name, description,
text, text_size);
new (s) SequencePtr(seq);
} catch (std::exception& e) {
lua_pushstring(L, e.what());
return -1;
}
// get metatable of Sequence
lua_pushvalue(L, lua_upvalueindex(1));
lua_setmetatable(L, -2);
return 1;
}
int lua_Sequence(lua_State *L) {
LUA_CALL_WRAPPED(lua_Sequence_impl);
}
static SequencePtr& lua_toseq(lua_State* L, int index) {
void* v = luaL_checkudata(L, index, "npge_Sequence");
SequencePtr* s = reinterpret_cast<SequencePtr*>(v);
return *s;
}
int lua_Sequence_gc(lua_State *L) {
SequencePtr& seq = lua_toseq(L, 1);
seq.reset();
return 0;
}
int lua_Sequence_type(lua_State *L) {
lua_pushstring(L, "Sequence");
return 1;
}
int lua_Sequence_name(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
const std::string& name = seq->name();
lua_pushlstring(L, name.c_str(), name.size());
return 1;
}
int lua_Sequence_description(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
const std::string& description = seq->description();
lua_pushlstring(L, description.c_str(),
description.size());
return 1;
}
int lua_Sequence_genome(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
std::string genome = seq->genome();
if (!genome.empty()) {
lua_pushlstring(L, genome.c_str(), genome.size());
} else {
lua_pushnil(L);
}
return 1;
}
int lua_Sequence_chromosome(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
std::string chr = seq->chromosome();
if (!chr.empty()) {
lua_pushlstring(L, chr.c_str(), chr.size());
} else {
lua_pushnil(L);
}
return 1;
}
int lua_Sequence_circular(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
int circular = seq->circular();
lua_pushboolean(L, circular);
return 1;
}
int lua_Sequence_text(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
const std::string& text = seq->text();
lua_pushlstring(L, text.c_str(), text.size());
return 1;
}
int lua_Sequence_length(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
lua_pushinteger(L, seq->length());
return 1;
}
int lua_Sequence_sub_impl(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
int min = luaL_checkint(L, 2);
int max = luaL_checkint(L, 3);
try {
ASSERT_LTE(0, min);
ASSERT_LTE(min, max);
ASSERT_LT(max, seq->length());
} catch (std::exception& e) {
lua_pushstring(L, e.what());
return -1;
}
int len = max - min + 1;
const std::string& text = seq->text();
const char* slice = text.c_str() + min;
lua_pushlstring(L, slice, len);
return 1;
}
int lua_Sequence_sub(lua_State *L) {
LUA_CALL_WRAPPED(lua_Sequence_sub_impl);
}
int lua_Sequence_tostring(lua_State *L) {
const SequencePtr& seq = lua_toseq(L, 1);
std::string repr = seq->tostring();
lua_pushlstring(L, repr.c_str(), repr.size());
return 1;
}
int lua_Sequence_eq(lua_State *L) {
const SequencePtr& a = lua_toseq(L, 1);
const SequencePtr& b = lua_toseq(L, 2);
int eq = ((*a) == (*b));
lua_pushboolean(L, eq);
return 1;
}
static const luaL_Reg Sequence_methods[] = {
{"__gc", lua_Sequence_gc},
{"type", lua_Sequence_type},
{"name", lua_Sequence_name},
{"description", lua_Sequence_description},
{"genome", lua_Sequence_genome},
{"chromosome", lua_Sequence_chromosome},
{"circular", lua_Sequence_circular},
{"text", lua_Sequence_text},
{"length", lua_Sequence_length},
{"sub", lua_Sequence_sub},
{"__tostring", lua_Sequence_tostring},
{"__eq", lua_Sequence_eq},
{NULL, NULL}
};
// -1 is module "model"
static void registerType(lua_State *L,
const char* type_name,
const char* mt_name,
lua_CFunction constructor,
const luaL_Reg* methods) {
luaL_newmetatable(L, mt_name);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index"); // mt.__index = mt
luaL_register(L, NULL, methods);
lua_pushcclosure(L, constructor, 1);
lua_setfield(L, -2, type_name);
}
extern "C" {
int luaopen_npge_cmodel(lua_State *L) {
lua_newtable(L);
registerType(L, "Sequence", "npge_Sequence",
lua_Sequence, Sequence_methods);
return 1;
}
}
|
fix function registerType
|
lua_model: fix function registerType
It used Sequence's methods for any type.
|
C++
|
mit
|
npge/lua-npge,starius/lua-npge,starius/lua-npge,starius/lua-npge,npge/lua-npge,npge/lua-npge
|
9d76bcb5ec08e08fa7cab726dedaedfd289a0db2
|
StarbuckLibrary/QtStageWebView.cpp
|
StarbuckLibrary/QtStageWebView.cpp
|
/*
* Copyright 2010-2011 Research In Motion 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 "stdafx.h"
#include "QtStageWebView.h"
#include "ScrollHandler.h"
#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include "remotedebugger.h"
using namespace BlackBerry::Starbuck;
QtStageWebView::QtStageWebView(QWidget *p) : waitForJsLoad(false)
{
//Turn off context menu's (i.e. menu when right clicking, you will need to uncommment this if you want to use web inspector,
//there is currently a conflict between the context menus when using two QWebView's
//this->setContextMenuPolicy(Qt::NoContextMenu);
// Connect signals for events
connect(this, SIGNAL(urlChanged(const QUrl&)), this, SLOT(notifyUrlChanged(const QUrl&)));
if (page() && page()->mainFrame())
{
connect(page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(notifyJavaScriptWindowObjectCleared()));
}
//Initialize headers to 0
_headersSize = 0;
//enable web inspector
this->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
m_pScrollHandler = new ScrollHandler(this);
m_inspector = new QWebInspector();
m_inspectorProcess = new QProcess();
//init the remote inspector and set the port
page()->setProperty("_q_webInspectorServerPort", 9292);
//install scroll handler
this->installEventFilter(m_pScrollHandler);
}
QtStageWebView::~QtStageWebView(void)
{
if (m_pScrollHandler != 0)
delete m_pScrollHandler;
if (m_inspector != 0)
delete m_inspector;
if (m_inspectorProcess != 0)
delete m_inspectorProcess;
}
void QtStageWebView::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
QMenu menu;
QAction *inspectAction = menu.addAction("Inspect");
QAction *selectedAction = menu.exec(event->screenPos());
if (inspectAction == selectedAction) {
m_inspector->setPage(page());
QString quotation = "\"";
QString cmd = QString(quotation + QApplication::applicationFilePath() + quotation + QString(" -inspect 9292"));
m_inspectorProcess->start(cmd);
}
}
void QtStageWebView::loadURL(QString url)
{
QNetworkRequest request(url);
//Add custom headers
for (unsigned int i = 0; i + 1 < _headersSize; i += 2)
request.setRawHeader(_headers[i], _headers[i + 1]);
load(request);
}
void QtStageWebView::reload()
{
QGraphicsWebView::reload();
}
void QtStageWebView::notifyUrlChanged(const QUrl& url)
{
emit urlChanged(url.toString());
m_inspector->setPage(page());
}
void QtStageWebView::notifyJavaScriptWindowObjectCleared()
{
// registerEventbus();
QEventLoop loop;
QObject::connect(this, SIGNAL(jsLoaded()), &loop, SLOT(quit()));
emit javaScriptWindowObjectCleared();
if (waitForJsLoad)
loop.exec();
}
#if 0
void QtStageWebView::registerEventbus()
{
QWebFrame* frame = page()->mainFrame();
frame->addToJavaScriptWindowObject(QString("eventbus2"), new BlackBerryBus(this, frame));
frame->evaluateJavaScript(BlackBerry::Starbuck::eventbusSource);
// check for iframes, if found add to window object
for(int i = 0; i < frame->childFrames().length(); i++)
{
frame->childFrames()[i]->addToJavaScriptWindowObject(QString("eventbus2"), new BlackBerryBus(this, frame->childFrames()[i]));
frame->childFrames()[i]->evaluateJavaScript(BlackBerry::Starbuck::eventbusSource);
}
}
#endif
void QtStageWebView::continueLoad()
{
emit jsLoaded();
waitForJsLoad = false;
}
bool QtStageWebView::enableCrossSiteXHR()
{
return this->settings()->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls);
}
void QtStageWebView::enableCrossSiteXHR(bool xhr)
{
return this->settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, xhr);
}
QVariant QtStageWebView::executeJavaScript(QString script)
{
return page()->mainFrame()->evaluateJavaScript(script);
}
QString QtStageWebView::location()
{
return url().toString();
}
bool QtStageWebView::isHistoryBackEnabled()
{
return history() ? history()->canGoBack() : false;
}
bool QtStageWebView::isHistoryForwardEnabled()
{
return history() ? history()->canGoForward() : false;
}
void QtStageWebView::historyBack()
{
back();
}
void QtStageWebView::historyForward()
{
forward();
}
int QtStageWebView::historyLength()
{
return history() ? history()->count() : 0;
}
int QtStageWebView::historyPosition()
{
return history() ? history()->currentItemIndex() : -1;
}
void QtStageWebView::historyPosition(int position)
{
if (history() && position >= 0 && position < history()->count())
{
history()->goToItem(history()->itemAt(position));
}
}
char** QtStageWebView::customHTTPHeaders()
{
return _headers;
}
void QtStageWebView::customHTTPHeaders(char *headers[], unsigned int headersSize)
{
_headers = new char*[headersSize];
for (unsigned int i = 0; i < headersSize; i++)
{
_headers[i] = new char[strlen(headers[i]) + 1];
strcpy(_headers[i], headers[i]);
}
_headersSize = headersSize;
}
void QtStageWebView::customHTTPHeaders(QString key, QString value)
{
QByteArray mKey = key.toAscii();
QByteArray mValue = value.toAscii();
char *headersArray[2];
headersArray[0] = mKey.data();
headersArray[1] = mValue.data();
customHTTPHeaders( headersArray, 2);
}
void QtStageWebView::visible(bool enable)
{
if (this->isVisible() == enable)
return;
(enable) ? this->show():this->hide();
}
void QtStageWebView::setZoom(float zoom) {
this->setZoomFactor(zoom);
}
float QtStageWebView::zoom() {
return this->zoomFactor();
}
|
/*
* Copyright 2010-2011 Research In Motion 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 "stdafx.h"
#include "QtStageWebView.h"
#include "ScrollHandler.h"
#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include "RemoteDebugger.h"
using namespace BlackBerry::Starbuck;
QtStageWebView::QtStageWebView(QWidget *p) : waitForJsLoad(false)
{
//Turn off context menu's (i.e. menu when right clicking, you will need to uncommment this if you want to use web inspector,
//there is currently a conflict between the context menus when using two QWebView's
//this->setContextMenuPolicy(Qt::NoContextMenu);
// Connect signals for events
connect(this, SIGNAL(urlChanged(const QUrl&)), this, SLOT(notifyUrlChanged(const QUrl&)));
if (page() && page()->mainFrame())
{
connect(page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()), this, SLOT(notifyJavaScriptWindowObjectCleared()));
}
//Initialize headers to 0
_headersSize = 0;
//enable web inspector
this->settings()->setAttribute(QWebSettings::DeveloperExtrasEnabled, true);
m_pScrollHandler = new ScrollHandler(this);
m_inspector = new QWebInspector();
m_inspectorProcess = new QProcess();
//init the remote inspector and set the port
page()->setProperty("_q_webInspectorServerPort", 9292);
//install scroll handler
this->installEventFilter(m_pScrollHandler);
}
QtStageWebView::~QtStageWebView(void)
{
if (m_pScrollHandler != 0)
delete m_pScrollHandler;
if (m_inspector != 0)
delete m_inspector;
if (m_inspectorProcess != 0)
delete m_inspectorProcess;
}
void QtStageWebView::contextMenuEvent(QGraphicsSceneContextMenuEvent *event)
{
QMenu menu;
QAction *inspectAction = menu.addAction("Inspect");
QAction *selectedAction = menu.exec(event->screenPos());
if (inspectAction == selectedAction) {
m_inspector->setPage(page());
QString quotation = "\"";
QString cmd = QString(quotation + QApplication::applicationFilePath() + quotation + QString(" -inspect 9292"));
m_inspectorProcess->start(cmd);
}
}
void QtStageWebView::loadURL(QString url)
{
QNetworkRequest request(url);
//Add custom headers
for (unsigned int i = 0; i + 1 < _headersSize; i += 2)
request.setRawHeader(_headers[i], _headers[i + 1]);
load(request);
}
void QtStageWebView::reload()
{
QGraphicsWebView::reload();
}
void QtStageWebView::notifyUrlChanged(const QUrl& url)
{
emit urlChanged(url.toString());
m_inspector->setPage(page());
}
void QtStageWebView::notifyJavaScriptWindowObjectCleared()
{
// registerEventbus();
QEventLoop loop;
QObject::connect(this, SIGNAL(jsLoaded()), &loop, SLOT(quit()));
emit javaScriptWindowObjectCleared();
if (waitForJsLoad)
loop.exec();
}
#if 0
void QtStageWebView::registerEventbus()
{
QWebFrame* frame = page()->mainFrame();
frame->addToJavaScriptWindowObject(QString("eventbus2"), new BlackBerryBus(this, frame));
frame->evaluateJavaScript(BlackBerry::Starbuck::eventbusSource);
// check for iframes, if found add to window object
for(int i = 0; i < frame->childFrames().length(); i++)
{
frame->childFrames()[i]->addToJavaScriptWindowObject(QString("eventbus2"), new BlackBerryBus(this, frame->childFrames()[i]));
frame->childFrames()[i]->evaluateJavaScript(BlackBerry::Starbuck::eventbusSource);
}
}
#endif
void QtStageWebView::continueLoad()
{
emit jsLoaded();
waitForJsLoad = false;
}
bool QtStageWebView::enableCrossSiteXHR()
{
return this->settings()->testAttribute(QWebSettings::LocalContentCanAccessRemoteUrls);
}
void QtStageWebView::enableCrossSiteXHR(bool xhr)
{
return this->settings()->setAttribute(QWebSettings::LocalContentCanAccessRemoteUrls, xhr);
}
QVariant QtStageWebView::executeJavaScript(QString script)
{
return page()->mainFrame()->evaluateJavaScript(script);
}
QString QtStageWebView::location()
{
return url().toString();
}
bool QtStageWebView::isHistoryBackEnabled()
{
return history() ? history()->canGoBack() : false;
}
bool QtStageWebView::isHistoryForwardEnabled()
{
return history() ? history()->canGoForward() : false;
}
void QtStageWebView::historyBack()
{
back();
}
void QtStageWebView::historyForward()
{
forward();
}
int QtStageWebView::historyLength()
{
return history() ? history()->count() : 0;
}
int QtStageWebView::historyPosition()
{
return history() ? history()->currentItemIndex() : -1;
}
void QtStageWebView::historyPosition(int position)
{
if (history() && position >= 0 && position < history()->count())
{
history()->goToItem(history()->itemAt(position));
}
}
char** QtStageWebView::customHTTPHeaders()
{
return _headers;
}
void QtStageWebView::customHTTPHeaders(char *headers[], unsigned int headersSize)
{
_headers = new char*[headersSize];
for (unsigned int i = 0; i < headersSize; i++)
{
_headers[i] = new char[strlen(headers[i]) + 1];
strcpy(_headers[i], headers[i]);
}
_headersSize = headersSize;
}
void QtStageWebView::customHTTPHeaders(QString key, QString value)
{
QByteArray mKey = key.toAscii();
QByteArray mValue = value.toAscii();
char *headersArray[2];
headersArray[0] = mKey.data();
headersArray[1] = mValue.data();
customHTTPHeaders( headersArray, 2);
}
void QtStageWebView::visible(bool enable)
{
if (this->isVisible() == enable)
return;
(enable) ? this->show():this->hide();
}
void QtStageWebView::setZoom(float zoom) {
this->setZoomFactor(zoom);
}
float QtStageWebView::zoom() {
return this->zoomFactor();
}
|
Fix Linux build
|
Fix Linux build
|
C++
|
apache-2.0
|
blackberry-webworks/Ripple-Framework,blackberry-webworks/Ripple-Framework,blackberry/Ripple-Framework,blackberry-webworks/Ripple-Framework,blackberry/Ripple-Framework,blackberry/Ripple-Framework,blackberry/Ripple-Framework,blackberry-webworks/Ripple-Framework,blackberry/Ripple-Framework
|
6c0165e13ac39bce9d3be5b0ef8a160752879c36
|
Sub-Terra/src/PlayerController.cpp
|
Sub-Terra/src/PlayerController.cpp
|
#include "common.h"
#include "PlayerController.h"
#include "EventManager.h"
#include "PositionComponent.h"
#include "OrientationComponent.h"
#include "BoundingComponent.h"
#include "ModelComponent.h"
void PlayerController::Init() {
const std::vector<Triangle> triangles = {
std::make_tuple(Point3(-0.5, -0.5, 0.5), Point3( 0.5, -0.5, 0.5), Point3(-0.5, 0.5, 0.5)),
std::make_tuple(Point3( 0.5, -0.5, 0.5), Point3( 0.5, 0.5, 0.5), Point3(-0.5, 0.5, 0.5)),
std::make_tuple(Point3(-0.5, 0.5, 0.5), Point3( 0.5, 0.5, 0.5), Point3(-0.5, 0.5, -0.5)),
std::make_tuple(Point3( 0.5, 0.5, 0.5), Point3( 0.5, 0.5, -0.5), Point3(-0.5, 0.5, -0.5)),
std::make_tuple(Point3(-0.5, 0.5, -0.5), Point3( 0.5, 0.5, -0.5), Point3(-0.5, -0.5, -0.5)),
std::make_tuple(Point3( 0.5, 0.5, -0.5), Point3( 0.5, -0.5, -0.5), Point3(-0.5, -0.5, -0.5)),
std::make_tuple(Point3(-0.5, -0.5, -0.5), Point3( 0.5, -0.5, -0.5), Point3(-0.5, -0.5, 0.5)),
std::make_tuple(Point3( 0.5, -0.5, -0.5), Point3( 0.5, -0.5, 0.5), Point3(-0.5, -0.5, 0.5)),
std::make_tuple(Point3( 0.5, -0.5, 0.5), Point3( 0.5, -0.5, -0.5), Point3( 0.5, 0.5, 0.5)),
std::make_tuple(Point3( 0.5, -0.5, -0.5), Point3( 0.5, 0.5, -0.5), Point3( 0.5, 0.5, 0.5)),
std::make_tuple(Point3(-0.5, -0.5, -0.5), Point3(-0.5, -0.5, 0.5), Point3(-0.5, 0.5, -0.5)),
std::make_tuple(Point3(-0.5, -0.5, 0.5), Point3(-0.5, 0.5, 0.5), Point3(-0.5, 0.5, -0.5))
};
object = engine->AddObject();
engine->AddComponent<PositionComponent>(object);
engine->AddComponent<OrientationComponent>(object);
engine->AddComponent<BoundingComponent>(object, Point3(-0.5f), Point3(1.0f));
engine->AddComponent<ModelComponent>(object, triangles);
InitObject();
auto ownPos = engine->GetComponent<PositionComponent>(object);
auto ownBounds = engine->GetComponent<BoundingComponent>(object);
/* gravity */
ownPos->position.Derivative(1) = Point3(0, -9.8f, 0);
/* collision detection and response */
engine->systems.Get<EventManager>()->ListenFor("integrator", "ticked", [this, ownPos, ownBounds] (Arg) {
auto pair = engine->objects.right.equal_range(&typeid(BoundingComponent));
for(auto it = pair.first; it != pair.second; ++it) {
auto id = it->get_left();
if(id == object) { continue; }
auto objPos = engine->GetComponent<PositionComponent>(id);
if(objPos != nullptr) {
auto objBounds = engine->GetComponent<BoundingComponent>(id);
if(objBounds != nullptr) {
if(ownBounds->box.CollidesWith(objBounds->box, *ownPos->position, *objPos->position)) {
ownPos->position.Derivative(1)->y = 0;
auto &y = ownPos->position.Derivative()->y;
y = (glm::max)(0.0f, y);
break;
} else {
ownPos->position.Derivative(1)->y = -9.8f;
}
}
}
}
});
}
void PlayerController::Update(DeltaTicks &dt) {
auto ownPos = engine->GetComponent<PositionComponent>(object);
auto ownOrient = engine->GetComponent<OrientationComponent>(object);
auto ownBounds = engine->GetComponent<BoundingComponent>(object);
auto rel = glm::normalize(Point4((moveLeft ? -1 : 0) + (moveRight ? 1 : 0), 0, (moveForward ? -1 : 0) + (moveBackward ? 1 : 0), 1));
auto abs = (glm::inverse(ownOrient->orientation) * rel) * 8.0f;
ownPos->position.Derivative()->x = abs.x;
//pos->position.Derivative()->y = abs.y;
ownPos->position.Derivative()->z = abs.z;
}
|
#include "common.h"
#include "PlayerController.h"
#include "EventManager.h"
#include "PositionComponent.h"
#include "OrientationComponent.h"
#include "BoundingComponent.h"
#include "ModelComponent.h"
void PlayerController::Init() {
const std::vector<Triangle> triangles = {
std::make_tuple(Point3(-0.5, -0.5, 0.5), Point3( 0.5, -0.5, 0.5), Point3(-0.5, 0.5, 0.5)),
std::make_tuple(Point3( 0.5, -0.5, 0.5), Point3( 0.5, 0.5, 0.5), Point3(-0.5, 0.5, 0.5)),
std::make_tuple(Point3(-0.5, 0.5, 0.5), Point3( 0.5, 0.5, 0.5), Point3(-0.5, 0.5, -0.5)),
std::make_tuple(Point3( 0.5, 0.5, 0.5), Point3( 0.5, 0.5, -0.5), Point3(-0.5, 0.5, -0.5)),
std::make_tuple(Point3(-0.5, 0.5, -0.5), Point3( 0.5, 0.5, -0.5), Point3(-0.5, -0.5, -0.5)),
std::make_tuple(Point3( 0.5, 0.5, -0.5), Point3( 0.5, -0.5, -0.5), Point3(-0.5, -0.5, -0.5)),
std::make_tuple(Point3(-0.5, -0.5, -0.5), Point3( 0.5, -0.5, -0.5), Point3(-0.5, -0.5, 0.5)),
std::make_tuple(Point3( 0.5, -0.5, -0.5), Point3( 0.5, -0.5, 0.5), Point3(-0.5, -0.5, 0.5)),
std::make_tuple(Point3( 0.5, -0.5, 0.5), Point3( 0.5, -0.5, -0.5), Point3( 0.5, 0.5, 0.5)),
std::make_tuple(Point3( 0.5, -0.5, -0.5), Point3( 0.5, 0.5, -0.5), Point3( 0.5, 0.5, 0.5)),
std::make_tuple(Point3(-0.5, -0.5, -0.5), Point3(-0.5, -0.5, 0.5), Point3(-0.5, 0.5, -0.5)),
std::make_tuple(Point3(-0.5, -0.5, 0.5), Point3(-0.5, 0.5, 0.5), Point3(-0.5, 0.5, -0.5))
};
object = engine->AddObject();
engine->AddComponent<PositionComponent>(object);
engine->AddComponent<OrientationComponent>(object);
engine->AddComponent<BoundingComponent>(object, Point3(-0.5f), Point3(1.0f));
engine->AddComponent<ModelComponent>(object, triangles);
InitObject();
auto ownPos = engine->GetComponent<PositionComponent>(object);
auto ownBounds = engine->GetComponent<BoundingComponent>(object);
/* gravity */
ownPos->position.Derivative(1) = Point3(0, -9.8f, 0);
/* collision detection and response */
engine->systems.Get<EventManager>()->ListenFor("integrator", "ticked", [this, ownPos, ownBounds] (Arg) {
auto pair = engine->objects.right.equal_range(&typeid(BoundingComponent));
for(auto it = pair.first; it != pair.second; ++it) {
auto id = it->get_left();
if(id == object) { continue; }
auto objPos = engine->GetComponent<PositionComponent>(id);
if(objPos != nullptr) {
auto objBounds = engine->GetComponent<BoundingComponent>(id);
if(objBounds != nullptr) {
if(ownBounds->box.CollidesWith(objBounds->box, *ownPos->position, *objPos->position)) {
ownPos->position.Derivative(1)->y = 0;
auto &y = ownPos->position.Derivative()->y;
y = (glm::max)(0.0f, y);
break;
} else {
ownPos->position.Derivative(1)->y = -9.8f;
}
}
}
}
});
}
void PlayerController::Update(DeltaTicks &dt) {
auto ownPos = engine->GetComponent<PositionComponent>(object);
auto ownOrient = engine->GetComponent<OrientationComponent>(object);
auto rel = glm::normalize(Point4((moveLeft ? -1 : 0) + (moveRight ? 1 : 0), 0, (moveForward ? -1 : 0) + (moveBackward ? 1 : 0), 1));
auto abs = (glm::inverse(ownOrient->orientation) * rel) * 8.0f;
ownPos->position.Derivative()->x = abs.x;
//pos->position.Derivative()->y = abs.y;
ownPos->position.Derivative()->z = abs.z;
}
|
Remove unused component retrieval
|
Remove unused component retrieval
|
C++
|
mpl-2.0
|
shockkolate/polar4,polar-engine/polar,polar-engine/polar,shockkolate/polar4,shockkolate/polar4,shockkolate/polar4
|
264ad5f77c87c016c92b4798682987aa1ea3c547
|
akregator/src/librss/loader.cpp
|
akregator/src/librss/loader.cpp
|
/*
* loader.cpp
*
* Copyright (c) 2001, 2002, 2003 Frerich Raabe <[email protected]>
*
* 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. For licensing and distribution details, check the
* accompanying file 'COPYING'.
*/
#include "loader.h"
#include "document.h"
#include <kio/job.h>
#include <kprocess.h>
#include <kurl.h>
#include <qdom.h>
#include <qbuffer.h>
#include <qregexp.h>
#include <qstringlist.h>
using namespace RSS;
DataRetriever::DataRetriever()
{
}
DataRetriever::~DataRetriever()
{
}
struct FileRetriever::Private
{
Private()
: buffer(NULL),
lastError(0), job(NULL)
{
}
~Private()
{
delete buffer;
}
QBuffer *buffer;
int lastError;
KIO::Job *job;
};
FileRetriever::FileRetriever()
: d(new Private)
{
}
FileRetriever::~FileRetriever()
{
delete d;
}
void FileRetriever::retrieveData(const KURL &url)
{
if (d->buffer)
return;
d->buffer = new QBuffer;
d->buffer->open(IO_WriteOnly);
KURL u=url;
if (u.protocol()=="feed")
u.setProtocol("http");
d->job = KIO::get(u, false, false);
connect(d->job, SIGNAL(data(KIO::Job *, const QByteArray &)),
SLOT(slotData(KIO::Job *, const QByteArray &)));
connect(d->job, SIGNAL(result(KIO::Job *)), SLOT(slotResult(KIO::Job *)));
connect(d->job, SIGNAL(permanentRedirection(KIO::Job *, const KURL &, const KURL &)),
SLOT(slotPermanentRedirection(KIO::Job *, const KURL &, const KURL &)));
}
int FileRetriever::errorCode() const
{
return d->lastError;
}
void FileRetriever::slotData(KIO::Job *, const QByteArray &data)
{
d->buffer->writeBlock(data.data(), data.size());
}
void FileRetriever::slotResult(KIO::Job *job)
{
QByteArray data = d->buffer->buffer();
data.detach();
delete d->buffer;
d->buffer = NULL;
d->lastError = job->error();
emit dataRetrieved(data, d->lastError == 0);
}
void FileRetriever::slotPermanentRedirection(KIO::Job *, const KURL &, const KURL &newUrl)
{
emit permanentRedirection(newUrl);
}
void FileRetriever::abort()
{
if (d->job)
{
d->job->kill(true);
d->job = NULL;
}
}
struct OutputRetriever::Private
{
Private() : process(NULL),
buffer(NULL),
lastError(0)
{
}
~Private()
{
delete process;
delete buffer;
}
KShellProcess *process;
QBuffer *buffer;
int lastError;
};
OutputRetriever::OutputRetriever() :
d(new Private)
{
}
OutputRetriever::~OutputRetriever()
{
delete d;
}
void OutputRetriever::retrieveData(const KURL &url)
{
// Ignore subsequent calls if we didn't finish the previous job yet.
if (d->buffer || d->process)
return;
d->buffer = new QBuffer;
d->buffer->open(IO_WriteOnly);
d->process = new KShellProcess();
connect(d->process, SIGNAL(processExited(KProcess *)),
SLOT(slotExited(KProcess *)));
connect(d->process, SIGNAL(receivedStdout(KProcess *, char *, int)),
SLOT(slotOutput(KProcess *, char *, int)));
*d->process << url.path();
d->process->start(KProcess::NotifyOnExit, KProcess::Stdout);
}
int OutputRetriever::errorCode() const
{
return d->lastError;
}
void OutputRetriever::slotOutput(KProcess *, char *data, int length)
{
d->buffer->writeBlock(data, length);
}
void OutputRetriever::slotExited(KProcess *p)
{
if (!p->normalExit())
d->lastError = p->exitStatus();
QByteArray data = d->buffer->buffer();
data.detach();
delete d->buffer;
d->buffer = NULL;
delete d->process;
d->process = NULL;
emit dataRetrieved(data, p->normalExit() && p->exitStatus() == 0);
}
struct Loader::Private
{
Private() : retriever(NULL),
lastError(0)
{
}
~Private()
{
delete retriever;
}
DataRetriever *retriever;
int lastError;
KURL discoveredFeedURL;
KURL url;
};
Loader *Loader::create()
{
return new Loader;
}
Loader *Loader::create(QObject *object, const char *slot)
{
Loader *loader = create();
connect(loader, SIGNAL(loadingComplete(Loader *, Document, Status)),
object, slot);
return loader;
}
Loader::Loader() : d(new Private)
{
}
Loader::~Loader()
{
delete d;
}
void Loader::loadFrom(const KURL &url, DataRetriever *retriever)
{
if (d->retriever != NULL)
return;
d->url=url;
d->retriever = retriever;
connect(d->retriever, SIGNAL(dataRetrieved(const QByteArray &, bool)),
this, SLOT(slotRetrieverDone(const QByteArray &, bool)));
d->retriever->retrieveData(url);
}
int Loader::errorCode() const
{
return d->lastError;
}
void Loader::abort()
{
if (d->retriever)
{
d->retriever->abort();
d->retriever=NULL;
}
}
const KURL &Loader::discoveredFeedURL() const
{
return d->discoveredFeedURL;
}
#include <kdebug.h>
void Loader::slotRetrieverDone(const QByteArray &data, bool success)
{
d->lastError = d->retriever->errorCode();
delete d->retriever;
d->retriever = NULL;
Document rssDoc;
Status status = Success;
if (success) {
QDomDocument doc;
/* Some servers insert whitespace before the <?xml...?> declaration.
* QDom doesn't tolerate that (and it's right, that's invalid XML),
* so we strip that.
*/
const char *charData = data.data();
int len = data.count();
while (len && QChar(*charData).isSpace()) {
--len;
++charData;
}
if (len > 3 && QChar(*charData) == 0357) { // 0357 0273 0277
len -= 3;
charData += 3;
}
QByteArray tmpData;
tmpData.setRawData(charData, len);
if (doc.setContent(tmpData))
{
rssDoc = Document(doc);
if (!rssDoc.isValid())
{
discoverFeeds(tmpData);
status = ParseError;
}
}
else
{
discoverFeeds(tmpData);
status = ParseError;
}
tmpData.resetRawData(charData, len);
} else
status = RetrieveError;
emit loadingComplete(this, rssDoc, status);
delete this;
}
void Loader::discoverFeeds(const QByteArray &data)
{
QString str = QString(data).simplifyWhiteSpace();
QString s2;
//QTextStream ts( &str, IO_WriteOnly );
//ts << data.data();
// "<[\\s]link[^>]*rel[\\s]=[\\s]\\\"[\\s]alternate[\\s]\\\"[^>]*>"
// "type[\\s]=[\\s]\\\"application/rss+xml\\\""
// "href[\\s]=[\\s]\\\"application/rss+xml\\\""
QRegExp rx( "(?:REL)[^=]*=[^sAa]*(?:service.feed|ALTERNATE)[\\s]*[^s][^s](?:[^>]*)(?:HREF)[^=]*=[^A-Z0-9-_~,./$]*([^'\">\\s]*)", false);
if (rx.search(str)!=-1)
s2=rx.cap(1);
else{
// does not support Atom/RSS autodiscovery.. try finding feeds by brute force....
int pos=0;
QStringList feeds;
QString host=d->url.host();
rx.setPattern("(?:<A )[^H]*(?:HREF)[^=]*=[^A-Z0-9-_~,./]*([^'\">\\s]*)");
while ( pos >= 0 ) {
pos = rx.search( str, pos );
s2=rx.cap(1);
if (s2.endsWith(".rdf")|s2.endsWith(".rss")|s2.endsWith(".xml"))
feeds.append(s2);
if ( pos >= 0 ) {
pos += rx.matchedLength();
}
}
s2=feeds.first();
KURL testURL;
// loop through, prefer feeds on same host
for ( QStringList::Iterator it = feeds.begin(); it != feeds.end(); ++it ) {
testURL=*it;
if (testURL.host()==host)
{
s2=*it;
break;
}
}
}
if (s2.isNull())
return;
if (KURL::isRelativeURL(s2))
{
if (s2.startsWith("//"))
{
s2=s2.prepend(d->url.protocol()+":");
d->discoveredFeedURL=s2;
}
else if (s2.startsWith("/"))
{
d->discoveredFeedURL=d->url;
d->discoveredFeedURL.setPath(s2);
}
else
{
d->discoveredFeedURL=d->url;
d->discoveredFeedURL.addPath(s2);
}
d->discoveredFeedURL.cleanPath();
}
else
d->discoveredFeedURL=s2;
d->discoveredFeedURL.cleanPath();
}
#include "loader.moc"
// vim:noet:ts=4
|
/*
* loader.cpp
*
* Copyright (c) 2001, 2002, 2003 Frerich Raabe <[email protected]>
*
* 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. For licensing and distribution details, check the
* accompanying file 'COPYING'.
*/
#include "loader.h"
#include "document.h"
#include <kio/job.h>
#include <kprocess.h>
#include <kurl.h>
#include <qdom.h>
#include <qbuffer.h>
#include <qregexp.h>
#include <qstringlist.h>
using namespace RSS;
DataRetriever::DataRetriever()
{
}
DataRetriever::~DataRetriever()
{
}
struct FileRetriever::Private
{
Private()
: buffer(NULL),
lastError(0), job(NULL)
{
}
~Private()
{
delete buffer;
}
QBuffer *buffer;
int lastError;
KIO::Job *job;
};
FileRetriever::FileRetriever()
: d(new Private)
{
}
FileRetriever::~FileRetriever()
{
delete d;
}
void FileRetriever::retrieveData(const KURL &url)
{
if (d->buffer)
return;
d->buffer = new QBuffer;
d->buffer->open(IO_WriteOnly);
KURL u=url;
if (u.protocol()=="feed")
u.setProtocol("http");
d->job = KIO::get(u, false, false);
connect(d->job, SIGNAL(data(KIO::Job *, const QByteArray &)),
SLOT(slotData(KIO::Job *, const QByteArray &)));
connect(d->job, SIGNAL(result(KIO::Job *)), SLOT(slotResult(KIO::Job *)));
connect(d->job, SIGNAL(permanentRedirection(KIO::Job *, const KURL &, const KURL &)),
SLOT(slotPermanentRedirection(KIO::Job *, const KURL &, const KURL &)));
}
int FileRetriever::errorCode() const
{
return d->lastError;
}
void FileRetriever::slotData(KIO::Job *, const QByteArray &data)
{
d->buffer->writeBlock(data.data(), data.size());
}
void FileRetriever::slotResult(KIO::Job *job)
{
QByteArray data = d->buffer->buffer();
data.detach();
delete d->buffer;
d->buffer = NULL;
d->lastError = job->error();
emit dataRetrieved(data, d->lastError == 0);
}
void FileRetriever::slotPermanentRedirection(KIO::Job *, const KURL &, const KURL &newUrl)
{
emit permanentRedirection(newUrl);
}
void FileRetriever::abort()
{
if (d->job)
{
d->job->kill(true);
d->job = NULL;
}
}
struct OutputRetriever::Private
{
Private() : process(NULL),
buffer(NULL),
lastError(0)
{
}
~Private()
{
delete process;
delete buffer;
}
KShellProcess *process;
QBuffer *buffer;
int lastError;
};
OutputRetriever::OutputRetriever() :
d(new Private)
{
}
OutputRetriever::~OutputRetriever()
{
delete d;
}
void OutputRetriever::retrieveData(const KURL &url)
{
// Ignore subsequent calls if we didn't finish the previous job yet.
if (d->buffer || d->process)
return;
d->buffer = new QBuffer;
d->buffer->open(IO_WriteOnly);
d->process = new KShellProcess();
connect(d->process, SIGNAL(processExited(KProcess *)),
SLOT(slotExited(KProcess *)));
connect(d->process, SIGNAL(receivedStdout(KProcess *, char *, int)),
SLOT(slotOutput(KProcess *, char *, int)));
*d->process << url.path();
d->process->start(KProcess::NotifyOnExit, KProcess::Stdout);
}
int OutputRetriever::errorCode() const
{
return d->lastError;
}
void OutputRetriever::slotOutput(KProcess *, char *data, int length)
{
d->buffer->writeBlock(data, length);
}
void OutputRetriever::slotExited(KProcess *p)
{
if (!p->normalExit())
d->lastError = p->exitStatus();
QByteArray data = d->buffer->buffer();
data.detach();
delete d->buffer;
d->buffer = NULL;
delete d->process;
d->process = NULL;
emit dataRetrieved(data, p->normalExit() && p->exitStatus() == 0);
}
struct Loader::Private
{
Private() : retriever(NULL),
lastError(0)
{
}
~Private()
{
delete retriever;
}
DataRetriever *retriever;
int lastError;
KURL discoveredFeedURL;
KURL url;
};
Loader *Loader::create()
{
return new Loader;
}
Loader *Loader::create(QObject *object, const char *slot)
{
Loader *loader = create();
connect(loader, SIGNAL(loadingComplete(Loader *, Document, Status)),
object, slot);
return loader;
}
Loader::Loader() : d(new Private)
{
}
Loader::~Loader()
{
delete d;
}
void Loader::loadFrom(const KURL &url, DataRetriever *retriever)
{
if (d->retriever != NULL)
return;
d->url=url;
d->retriever = retriever;
connect(d->retriever, SIGNAL(dataRetrieved(const QByteArray &, bool)),
this, SLOT(slotRetrieverDone(const QByteArray &, bool)));
d->retriever->retrieveData(url);
}
int Loader::errorCode() const
{
return d->lastError;
}
void Loader::abort()
{
if (d->retriever)
{
d->retriever->abort();
d->retriever=NULL;
}
}
const KURL &Loader::discoveredFeedURL() const
{
return d->discoveredFeedURL;
}
#include <kdebug.h>
void Loader::slotRetrieverDone(const QByteArray &data, bool success)
{
d->lastError = d->retriever->errorCode();
delete d->retriever;
d->retriever = NULL;
Document rssDoc;
Status status = Success;
if (success) {
QDomDocument doc;
/* Some servers insert whitespace before the <?xml...?> declaration.
* QDom doesn't tolerate that (and it's right, that's invalid XML),
* so we strip that.
*/
const char *charData = data.data();
int len = data.count();
while (len && QChar(*charData).isSpace()) {
--len;
++charData;
}
if ( len > 3 && QChar(*charData) == QChar(0357) ) { // 0357 0273 0277
len -= 3;
charData += 3;
}
QByteArray tmpData;
tmpData.setRawData(charData, len);
if (doc.setContent(tmpData))
{
rssDoc = Document(doc);
if (!rssDoc.isValid())
{
discoverFeeds(tmpData);
status = ParseError;
}
}
else
{
discoverFeeds(tmpData);
status = ParseError;
}
tmpData.resetRawData(charData, len);
} else
status = RetrieveError;
emit loadingComplete(this, rssDoc, status);
delete this;
}
void Loader::discoverFeeds(const QByteArray &data)
{
QString str = QString(data).simplifyWhiteSpace();
QString s2;
//QTextStream ts( &str, IO_WriteOnly );
//ts << data.data();
// "<[\\s]link[^>]*rel[\\s]=[\\s]\\\"[\\s]alternate[\\s]\\\"[^>]*>"
// "type[\\s]=[\\s]\\\"application/rss+xml\\\""
// "href[\\s]=[\\s]\\\"application/rss+xml\\\""
QRegExp rx( "(?:REL)[^=]*=[^sAa]*(?:service.feed|ALTERNATE)[\\s]*[^s][^s](?:[^>]*)(?:HREF)[^=]*=[^A-Z0-9-_~,./$]*([^'\">\\s]*)", false);
if (rx.search(str)!=-1)
s2=rx.cap(1);
else{
// does not support Atom/RSS autodiscovery.. try finding feeds by brute force....
int pos=0;
QStringList feeds;
QString host=d->url.host();
rx.setPattern("(?:<A )[^H]*(?:HREF)[^=]*=[^A-Z0-9-_~,./]*([^'\">\\s]*)");
while ( pos >= 0 ) {
pos = rx.search( str, pos );
s2=rx.cap(1);
if (s2.endsWith(".rdf")|s2.endsWith(".rss")|s2.endsWith(".xml"))
feeds.append(s2);
if ( pos >= 0 ) {
pos += rx.matchedLength();
}
}
s2=feeds.first();
KURL testURL;
// loop through, prefer feeds on same host
for ( QStringList::Iterator it = feeds.begin(); it != feeds.end(); ++it ) {
testURL=*it;
if (testURL.host()==host)
{
s2=*it;
break;
}
}
}
if (s2.isNull())
return;
if (KURL::isRelativeURL(s2))
{
if (s2.startsWith("//"))
{
s2=s2.prepend(d->url.protocol()+":");
d->discoveredFeedURL=s2;
}
else if (s2.startsWith("/"))
{
d->discoveredFeedURL=d->url;
d->discoveredFeedURL.setPath(s2);
}
else
{
d->discoveredFeedURL=d->url;
d->discoveredFeedURL.addPath(s2);
}
d->discoveredFeedURL.cleanPath();
}
else
d->discoveredFeedURL=s2;
d->discoveredFeedURL.cleanPath();
}
#include "loader.moc"
// vim:noet:ts=4
|
fix compile (gcc 3.3.4 complains about ambigous operator== ...)
|
fix compile (gcc 3.3.4 complains about ambigous operator== ...)
svn path=/trunk/kdepim/akregator/; revision=367564
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
64af2a0cfae9d083f76e1a66b4bb62dea28e8640
|
alloutil/alloutil/al_Simulator.hpp
|
alloutil/alloutil/al_Simulator.hpp
|
#ifndef AL_SIMULATOR_H
#define AL_SIMULATOR_H
#include "allocore/al_Allocore.hpp"
#include "allocore/protocol/al_OSC.hpp"
namespace al {
class Simulator : public osc::PacketHandler, public Main::Handler {
public:
Simulator(const char* deviceServerAddress = "127.0.0.1", int port = 12001,
int deviceServerPort = 12000);
virtual ~Simulator();
virtual void start();
virtual void stop();
virtual void init() = 0;
virtual void step(double dt) = 0;
virtual void exit() = 0;
virtual void onTick();
virtual void onExit();
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
virtual const char* name();
virtual const char* deviceServerConfig();
osc::Recv& oscRecv() { return mOSCRecv; }
osc::Send& oscSend() { return mOSCSend; }
virtual void onMessage(osc::Message& m);
protected:
bool started;
double time, lastTime;
osc::Recv mOSCRecv;
osc::Send mOSCSend;
Nav mNav;
Pose pose;
NavInputControl mNavControl;
StandardWindowKeyControls mStdControls;
double mNavSpeed, mNavTurnSpeed;
};
inline void Simulator::onTick() {
if (!started) {
started = true;
time = Main::get().realtime();
init();
}
while (oscRecv().recv()) {
}
lastTime = time;
time = Main::get().realtime();
nav().step(time - lastTime);
step(time - lastTime);
}
inline void Simulator::onExit() { exit(); }
inline void Simulator::onMessage(osc::Message& m) {
float x;
if (m.addressPattern() == "/mx") {
m >> x;
nav().moveR(-x * mNavSpeed);
} else if (m.addressPattern() == "/my") {
m >> x;
nav().moveU(x * mNavSpeed);
} else if (m.addressPattern() == "/mz") {
m >> x;
nav().moveF(x * mNavSpeed);
} else if (m.addressPattern() == "/tx") {
m >> x;
nav().spinR(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/ty") {
m >> x;
nav().spinU(x * mNavTurnSpeed);
} else if (m.addressPattern() == "/tz") {
m >> x;
nav().spinF(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/home") {
nav().home();
} else if (m.addressPattern() == "/halt") {
nav().halt();
} else {
}
if (m.addressPattern() == "/pose") {
m >> pose.pos().x;
m >> pose.pos().y;
m >> pose.pos().z;
m >> pose.quat().x;
m >> pose.quat().y;
m >> pose.quat().z;
m >> pose.quat().w;
}
}
inline void Simulator::start() {
if (oscSend().opened())
oscSend().send("/interface/applicationManager/createApplicationWithText",
deviceServerConfig());
Main::get().interval(1 / 60.0).add(*this).start();
}
inline void Simulator::stop() { Main::get().stop(); }
inline Simulator::~Simulator() {
oscSend().send("/interface/disconnectApplication", name());
}
Simulator::Simulator(const char* deviceServerAddress, int port,
int deviceServerPort)
: mOSCRecv(port),
mNavControl(mNav),
mOSCSend(deviceServerPort, deviceServerAddress) {
oscRecv().bufferSize(32000);
oscRecv().handler(*this);
mNavSpeed = 1;
mNavTurnSpeed = 0.02;
nav().smooth(0.8);
}
inline const char* Simulator::name() { return "default_no_name"; }
inline const char* Simulator::deviceServerConfig() {
return R"(
app = {
name : 'default_no_name',
receivers :[ {type : 'OSC', port : 12001}, ],
inputs: {
mx: {min: 0, max: 0.1, },
my: {min: 0, max: 0.1, },
mz: {min: 0, max: 0.1, },
tx: {min: 0, max: 1, },
ty: {min: 0, max: 1, },
tz: {min: 0, max: 1, },
home: {min: 0, max: 1, },
halt: {min: 0, max: 1, },
},
mappings: [
{ input: { io:'keypress', name:'`' }, output:{ io:'blob', name:'home' } },
{ input: { io:'keypress', name:'w' }, output:{ io:'blob', name:'mx'}, },
]
}
)";
}
} // al::
#endif
|
#ifndef AL_SIMULATOR_H
#define AL_SIMULATOR_H
#include "allocore/al_Allocore.hpp"
#include "allocore/protocol/al_OSC.hpp"
namespace al {
class Simulator : public osc::PacketHandler, public Main::Handler {
public:
Simulator(const char* deviceServerAddress = "127.0.0.1", int port = 12001,
int deviceServerPort = 12000);
virtual ~Simulator();
virtual void start();
virtual void stop();
virtual void init() = 0;
virtual void step(double dt) = 0;
virtual void exit() = 0;
virtual void onTick();
virtual void onExit();
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
virtual const char* name();
virtual const char* deviceServerConfig();
osc::Recv& oscRecv() { return mOSCRecv; }
osc::Send& oscSend() { return mOSCSend; }
virtual void onMessage(osc::Message& m);
protected:
bool started;
double time, lastTime;
osc::Recv mOSCRecv;
osc::Send mOSCSend;
Nav mNav;
NavInputControl mNavControl;
StandardWindowKeyControls mStdControls;
double mNavSpeed, mNavTurnSpeed;
};
inline void Simulator::onTick() {
if (!started) {
started = true;
time = Main::get().realtime();
init();
}
while (oscRecv().recv()) {
}
lastTime = time;
time = Main::get().realtime();
nav().step(time - lastTime);
step(time - lastTime);
}
inline void Simulator::onExit() { exit(); }
inline void Simulator::onMessage(osc::Message& m) {
float x;
if (m.addressPattern() == "/mx") {
m >> x;
nav().moveR(-x * mNavSpeed);
} else if (m.addressPattern() == "/my") {
m >> x;
nav().moveU(x * mNavSpeed);
} else if (m.addressPattern() == "/mz") {
m >> x;
nav().moveF(x * mNavSpeed);
} else if (m.addressPattern() == "/tx") {
m >> x;
nav().spinR(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/ty") {
m >> x;
nav().spinU(x * mNavTurnSpeed);
} else if (m.addressPattern() == "/tz") {
m >> x;
nav().spinF(x * -mNavTurnSpeed);
} else if (m.addressPattern() == "/home") {
nav().home();
} else if (m.addressPattern() == "/halt") {
nav().halt();
} else {
}
// This allows the graphics renderer (or whatever) to overwrite navigation
// data, so you can navigate from the graphics window when using a laptop.
//
if (m.addressPattern() == "/pose") {
Pose pose;
m >> pose.pos().x;
m >> pose.pos().y;
m >> pose.pos().z;
m >> pose.quat().x;
m >> pose.quat().y;
m >> pose.quat().z;
m >> pose.quat().w;
//pose.print();
nav().set(pose);
}
}
inline void Simulator::start() {
if (oscSend().opened())
oscSend().send("/interface/applicationManager/createApplicationWithText",
deviceServerConfig());
Main::get().interval(1 / 60.0).add(*this).start();
}
inline void Simulator::stop() { Main::get().stop(); }
inline Simulator::~Simulator() {
oscSend().send("/interface/disconnectApplication", name());
}
Simulator::Simulator(const char* deviceServerAddress, int port,
int deviceServerPort)
: mOSCRecv(port),
mNavControl(mNav),
mOSCSend(deviceServerPort, deviceServerAddress) {
oscRecv().bufferSize(32000);
oscRecv().handler(*this);
mNavSpeed = 1;
mNavTurnSpeed = 0.02;
nav().smooth(0.8);
}
inline const char* Simulator::name() { return "default_no_name"; }
inline const char* Simulator::deviceServerConfig() {
return R"(
app = {
name : 'default_no_name',
receivers :[ {type : 'OSC', port : 12001}, ],
inputs: {
mx: {min: 0, max: 0.1, },
my: {min: 0, max: 0.1, },
mz: {min: 0, max: 0.1, },
tx: {min: 0, max: 1, },
ty: {min: 0, max: 1, },
tz: {min: 0, max: 1, },
home: {min: 0, max: 1, },
halt: {min: 0, max: 1, },
},
mappings: [
{ input: { io:'keypress', name:'`' }, output:{ io:'blob', name:'home' } },
{ input: { io:'keypress', name:'w' }, output:{ io:'blob', name:'mx'}, },
]
}
)";
}
} // al::
#endif
|
fix for laptop mode with al::Simulator
|
fix for laptop mode with al::Simulator
|
C++
|
bsd-3-clause
|
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
|
f4e66942314b4623c5225b7228c968727b687167
|
alloGLV/alloGLV/al_ProtoApp.hpp
|
alloGLV/alloGLV/al_ProtoApp.hpp
|
#ifndef INCLUDE_AL_PROTOAPP_HPP
#define INCLUDE_AL_PROTOAPP_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
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 University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Helper app for audio/visual prototyping
File author(s):
Lance Putnam, 2012, [email protected]
*/
#include <math.h>
#include <string>
#include "allocore/io/al_App.hpp"
#include "alloGLV/al_ControlGLV.hpp"
#include "GLV/glv.h"
#define GAMMA_H_INC_ALL
#include "Gamma/Gamma.h"
namespace al{
/// Application for audio/visual prototyping
/// This App subclass provides a simpler way to setup an audio/visual app
/// with a GUI. Parameters can easily be added to the GUI and saved/loaded
/// to/from file.
class ProtoApp : public App{
public:
glv::NumberDialer cnFOV, cnScale;
glv::NumberDialer cnGain;
ProtoApp();
/// This should be called after configuring everything else with the app
void init(
const Window::Dim& dim = Window::Dim(800,600),
const std::string title="",
double fps=40,
Window::DisplayMode mode = Window::DEFAULT_BUF,
double sampleRate = 44100,
int blockSize = 256,
int chansOut = -1,
int chansIn = -1
);
/// Set the directory for application resources
ProtoApp& resourceDir(const std::string& dir, bool searchBack=true);
glv::ParamPanel& paramPanel(){ return mParamPanel; }
ProtoApp& addParam(
glv::View& v, const std::string& label="", bool nameViewFromLabel=true
){
paramPanel().addParam(v,label,nameViewFromLabel);
return *this;
}
ProtoApp& addParam(
glv::View * v, const std::string& label="", bool nameViewFromLabel=true
){
return addParam(*v,label,nameViewFromLabel);
}
double gainFactor() const { float v=cnGain.getValue(); return v*v; }
double scaleFactor() const { return ::pow(2., cnScale.getValue()); }
/// This should still be called via ProtoApp::onAnimate(dt) if overridden
virtual void onAnimate(double dt){
lens().fovy(cnFOV.getValue());
}
// virtual void onDraw(Graphics& g, const Viewpoint& v){}
// virtual void onSound(AudioIOData& io){}
protected:
GLVDetachable mGUI;
glv::Table mGUITable;
glv::ParamPanel mParamPanel;
glv::Table mTopBar;
glv::Label mAppLabel;
std::string mResourceDir;
};
} // al::
#endif
|
#ifndef INCLUDE_AL_PROTOAPP_HPP
#define INCLUDE_AL_PROTOAPP_HPP
/* Allocore --
Multimedia / virtual environment application class library
Copyright (C) 2009. AlloSphere Research Group, Media Arts & Technology, UCSB.
Copyright (C) 2012. The Regents of the University of California.
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 University of California nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
File description:
Helper app for audio/visual prototyping
File author(s):
Lance Putnam, 2012, [email protected]
*/
#include <math.h>
#include <string>
#include "allocore/io/al_App.hpp"
#include "alloGLV/al_ControlGLV.hpp"
#include "GLV/glv.h"
#define GAMMA_H_INC_ALL
#include "Gamma/Gamma.h"
namespace al{
/// Application for audio/visual prototyping
/// This App subclass provides a simpler way to setup an audio/visual app
/// with a GUI. Parameters can easily be added to the GUI and saved/loaded
/// to/from file.
class ProtoApp : public App{
public:
glv::NumberDialer cnFOV, cnScale;
glv::NumberDialer cnGain;
ProtoApp();
/// This should be called after configuring everything else with the app
void init(
const Window::Dim& dim = Window::Dim(800,600),
const std::string title="",
double fps=40,
Window::DisplayMode mode = Window::DEFAULT_BUF,
double sampleRate = 44100,
int blockSize = 256,
int chansOut = -1,
int chansIn = -1
);
/// Set the directory for application resources
ProtoApp& resourceDir(const std::string& dir, bool searchBack=true);
GLVDetachable& gui(){ return mGUI; }
glv::ParamPanel& paramPanel(){ return mParamPanel; }
ProtoApp& addParam(
glv::View& v, const std::string& label="", bool nameViewFromLabel=true
){
paramPanel().addParam(v,label,nameViewFromLabel);
return *this;
}
ProtoApp& addParam(
glv::View * v, const std::string& label="", bool nameViewFromLabel=true
){
return addParam(*v,label,nameViewFromLabel);
}
double gainFactor() const { float v=cnGain.getValue(); return v*v; }
double scaleFactor() const { return ::pow(2., cnScale.getValue()); }
/// This should still be called via ProtoApp::onAnimate(dt) if overridden
virtual void onAnimate(double dt){
lens().fovy(cnFOV.getValue());
}
// virtual void onDraw(Graphics& g, const Viewpoint& v){}
// virtual void onSound(AudioIOData& io){}
protected:
GLVDetachable mGUI;
glv::Table mGUITable;
glv::ParamPanel mParamPanel;
glv::Table mTopBar;
glv::Label mAppLabel;
std::string mResourceDir;
};
} // al::
#endif
|
add gui getter
|
add gui getter
|
C++
|
bsd-3-clause
|
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
|
548d8700ca70da2a1f8ab2497664b6738cc74982
|
tcmalloc/arena.cc
|
tcmalloc/arena.cc
|
// Copyright 2019 The TCMalloc Authors
//
// 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
//
// https://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 "tcmalloc/arena.h"
#include "tcmalloc/internal/logging.h"
#include "tcmalloc/system-alloc.h"
GOOGLE_MALLOC_SECTION_BEGIN
namespace tcmalloc {
namespace tcmalloc_internal {
void* Arena::Alloc(size_t bytes) {
char* result;
bytes = ((bytes + kAlignment - 1) / kAlignment) * kAlignment;
if (free_avail_ < bytes) {
size_t ask = bytes > kAllocIncrement ? bytes : kAllocIncrement;
size_t actual_size;
// TODO(b/171081864): Arena allocations should be made relatively
// infrequently. Consider tagging this memory with sampled objects which
// are also infrequently allocated.
free_area_ = reinterpret_cast<char*>(
SystemAlloc(ask, &actual_size, kPageSize, MemoryTag::kNormal));
if (ABSL_PREDICT_FALSE(free_area_ == nullptr)) {
Crash(kCrash, __FILE__, __LINE__,
"FATAL ERROR: Out of memory trying to allocate internal tcmalloc "
"data (bytes, object-size)",
kAllocIncrement, bytes);
}
SystemBack(free_area_, actual_size);
free_avail_ = actual_size;
}
ASSERT(reinterpret_cast<uintptr_t>(free_area_) % kAlignment == 0);
result = free_area_;
free_area_ += bytes;
free_avail_ -= bytes;
bytes_allocated_ += bytes;
return reinterpret_cast<void*>(result);
}
} // namespace tcmalloc_internal
} // namespace tcmalloc
GOOGLE_MALLOC_SECTION_END
|
// Copyright 2019 The TCMalloc Authors
//
// 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
//
// https://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 "tcmalloc/arena.h"
#include "tcmalloc/internal/logging.h"
#include "tcmalloc/system-alloc.h"
GOOGLE_MALLOC_SECTION_BEGIN
namespace tcmalloc {
namespace tcmalloc_internal {
void* Arena::Alloc(size_t bytes) {
char* result;
bytes = ((bytes + kAlignment - 1) / kAlignment) * kAlignment;
if (free_avail_ < bytes) {
size_t ask = bytes > kAllocIncrement ? bytes : kAllocIncrement;
size_t actual_size;
// TODO(b/171081864): Arena allocations should be made relatively
// infrequently. Consider tagging this memory with sampled objects which
// are also infrequently allocated.
free_area_ = reinterpret_cast<char*>(
SystemAlloc(ask, &actual_size, kPageSize, MemoryTag::kNormal));
if (ABSL_PREDICT_FALSE(free_area_ == nullptr)) {
Crash(kCrash, __FILE__, __LINE__,
"FATAL ERROR: Out of memory trying to allocate internal tcmalloc "
"data (bytes, object-size); is something preventing mmap from "
"succeeding (sandbox, VSS limitations)?",
kAllocIncrement, bytes);
}
SystemBack(free_area_, actual_size);
free_avail_ = actual_size;
}
ASSERT(reinterpret_cast<uintptr_t>(free_area_) % kAlignment == 0);
result = free_area_;
free_area_ += bytes;
free_avail_ -= bytes;
bytes_allocated_ += bytes;
return reinterpret_cast<void*>(result);
}
} // namespace tcmalloc_internal
} // namespace tcmalloc
GOOGLE_MALLOC_SECTION_END
|
Add more debugging notes on mmap failure.
|
Add more debugging notes on mmap failure.
Sandboxes and VSS restrictions can cause mmap to fail. Make that clear when we
crash.
PiperOrigin-RevId: 358502373
Change-Id: Ibf10b113061b7af39561b63920dbacd8abd87e53
|
C++
|
apache-2.0
|
google/tcmalloc,google/tcmalloc,google/tcmalloc
|
04831dbd134cac1b4190d2062aa5decc8da45724
|
test/correctness/extern_error.cpp
|
test/correctness/extern_error.cpp
|
#include <Halide.h>
#include <stdio.h>
using namespace Halide;
#ifdef _MSC_VER
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
extern "C" DLLEXPORT
int extern_error(buffer_t *out) {
return -1;
}
bool error_occurred = false;
extern "C" DLLEXPORT
void my_halide_error(void *user_context, const char *msg) {
printf("Expected: %s\n", msg);
error_occurred = true;
}
int main(int argc, char **argv) {
Func f;
f.define_extern("extern_error", std::vector<ExternFuncArgument>(),
Float(32), 1);
f.set_error_handler(&my_halide_error);
f.realize(100);
if (!error_occurred) {
printf("There was supposed to be an error\n");
return -1;
}
printf("Success!\n");
return 0;
}
|
#include <Halide.h>
#include <stdio.h>
using namespace Halide;
static void *context_pointer = (void *)0xf00dd00d;
#ifdef _MSC_VER
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
bool extern_error_called = false;
extern "C" DLLEXPORT
int extern_error(void *user_context, buffer_t *out) {
assert(user_context == context_pointer);
extern_error_called = true;
return -1;
}
bool error_occurred = false;
extern "C" DLLEXPORT
void my_halide_error(void *user_context, const char *msg) {
assert(user_context == context_pointer);
printf("Expected: %s\n", msg);
error_occurred = true;
}
int main(int argc, char **argv) {
Param<void*> my_user_context = user_context_param();
my_user_context.set(context_pointer);
std::vector<ExternFuncArgument> args;
args.push_back(my_user_context);
Func f;
f.define_extern("extern_error", args, Float(32), 1);
f.set_error_handler(&my_halide_error);
f.realize(100);
if (!error_occurred || !extern_error_called) {
printf("There was supposed to be an error\n");
return -1;
}
printf("Success!\n");
return 0;
}
|
Augment extern_error test to set and test a specific value for user_context
|
Augment extern_error test to set and test a specific value for user_context
|
C++
|
mit
|
myrtleTree33/Halide,tdenniston/Halide,ayanazmat/Halide,tdenniston/Halide,adasworks/Halide,damienfir/Halide,mcanthony/Halide,ayanazmat/Halide,ronen/Halide,ayanazmat/Halide,kenkuang1213/Halide,tdenniston/Halide,kgnk/Halide,kgnk/Halide,kgnk/Halide,aam/Halide,kenkuang1213/Halide,ronen/Halide,mcanthony/Halide,damienfir/Halide,tdenniston/Halide,adasworks/Halide,aam/Halide,ayanazmat/Halide,aam/Halide,mcanthony/Halide,smxlong/Halide,damienfir/Halide,jiawen/Halide,smxlong/Halide,ronen/Halide,rodrigob/Halide,jiawen/Halide,psuriana/Halide,delcypher/Halide,lglucin/Halide,adasworks/Halide,jiawen/Halide,ayanazmat/Halide,damienfir/Halide,dan-tull/Halide,lglucin/Halide,aam/Halide,kgnk/Halide,mcanthony/Halide,psuriana/Halide,smxlong/Halide,ronen/Halide,rodrigob/Halide,dan-tull/Halide,aam/Halide,kenkuang1213/Halide,ronen/Halide,psuriana/Halide,adasworks/Halide,damienfir/Halide,dougkwan/Halide,delcypher/Halide,fengzhyuan/Halide,smxlong/Halide,mcanthony/Halide,kenkuang1213/Halide,rodrigob/Halide,ronen/Halide,lglucin/Halide,dougkwan/Halide,gchauras/Halide,fengzhyuan/Halide,dougkwan/Halide,rodrigob/Halide,myrtleTree33/Halide,ayanazmat/Halide,myrtleTree33/Halide,dan-tull/Halide,kgnk/Halide,delcypher/Halide,damienfir/Halide,aam/Halide,rodrigob/Halide,ayanazmat/Halide,myrtleTree33/Halide,dougkwan/Halide,delcypher/Halide,psuriana/Halide,damienfir/Halide,fengzhyuan/Halide,jiawen/Halide,ronen/Halide,jiawen/Halide,psuriana/Halide,smxlong/Halide,myrtleTree33/Halide,dougkwan/Halide,fengzhyuan/Halide,kenkuang1213/Halide,gchauras/Halide,kgnk/Halide,dougkwan/Halide,myrtleTree33/Halide,tdenniston/Halide,lglucin/Halide,gchauras/Halide,kenkuang1213/Halide,ronen/Halide,dan-tull/Halide,psuriana/Halide,mcanthony/Halide,dougkwan/Halide,kenkuang1213/Halide,damienfir/Halide,dan-tull/Halide,ayanazmat/Halide,lglucin/Halide,jiawen/Halide,delcypher/Halide,adasworks/Halide,dan-tull/Halide,tdenniston/Halide,gchauras/Halide,lglucin/Halide,fengzhyuan/Halide,dougkwan/Halide,delcypher/Halide,delcypher/Halide,adasworks/Halide,kenkuang1213/Halide,fengzhyuan/Halide,delcypher/Halide,adasworks/Halide,fengzhyuan/Halide,smxlong/Halide,fengzhyuan/Halide,aam/Halide,lglucin/Halide,kgnk/Halide,adasworks/Halide,dan-tull/Halide,dan-tull/Halide,psuriana/Halide,mcanthony/Halide,jiawen/Halide,smxlong/Halide,kgnk/Halide,myrtleTree33/Halide,gchauras/Halide,tdenniston/Halide,rodrigob/Halide,smxlong/Halide,rodrigob/Halide,gchauras/Halide,tdenniston/Halide,mcanthony/Halide,myrtleTree33/Halide,rodrigob/Halide
|
7a4f23bdb7aeb6f1bcbc8c899a3ecfddcc6f7610
|
hw1.skel/hw2/HW2a.cpp
|
hw1.skel/hw2/HW2a.cpp
|
// ===============================================================
// Computer Graphics Homework Solutions
// Copyright (C) 2017 by George Wolberg
//
// HW2a.cpp - HW2a class
//
// Written by: George Wolberg, 2017
// ===============================================================
#include "HW2a.h"
// shader ID
enum { HW2A };
// uniform ID
enum { PROJ };
const int DrawModes[] = {
GL_POINTS,
GL_LINES,
GL_LINE_STRIP,
GL_LINE_LOOP,
GL_TRIANGLES,
GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN,
GL_QUADS,
GL_POLYGON
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::HW2a:
//
// HW2a constructor.
//
HW2a::HW2a(const QGLFormat &glf, QWidget *parent) : HW(glf, parent)
{
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::initializeGL:
//
// Initialization routine before display loop.
// Gets called once before the first time resizeGL() or paintGL() is called.
//
void
HW2a::initializeGL()
{
// initialize GL function resolution for current context
initializeGLFunctions();
// init vertex and fragment shaders
initShaders();
// initialize vertex buffer and write positions to vertex shader
initVertexBuffer();
// init state variables
glClearColor(0.0, 0.0, 0.0, 0.0); // set background color
glColor3f (1.0, 1.0, 0.0); // set foreground color
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::resizeGL:
//
// Resize event handler.
// The input parameters are the window width (w) and height (h).
//
void
HW2a::resizeGL(int w, int h)
{
// PUT YOUR CODE HERE
// save window dimensions
m_winW = w;
m_winH = h;
// compute aspect ratio
float ar = (float) w / h;
// set xmax, ymax;
float xmax, ymax;
if(ar > 1.0) { // wide screen
xmax = ar;
ymax = 1.;
} else { // tall screen
xmax = 1.;
ymax = 1 / ar;
}
// set viewport to occupy full canvas
glViewport(0, 0, w, h);
// compute orthographic projection from viewing coordinates;
// we use Qt's 4x4 matrix class in place of legacy OpenGL code:
// glLoadIdentity();
// glOrtho(-xmax, xmax, -ymax, ymax, -1.0, 1.0);
m_projection.setToIdentity();
m_projection.ortho(-xmax, xmax, -ymax, ymax, -1.0, 1.0);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::paintGL:
//
// Update GL scene.
//
void
HW2a::paintGL()
{
// clear canvas with background color
glClear(GL_COLOR_BUFFER_BIT);
// enable vertex shader point size adjustment
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
// draw data in nine viewports after splitting canvas into 3x3 cells;
// a different drawing mode is used in each viewport
// ********************
// * * * *
// * 7 * 8 * 9 *
// * * * *
// ********************
// * * * *
// * 4 * 5 * 6 *
// * * * *
// ********************
// * * * *
// * 1 * 2 * 3 *
// * * * *
// ********************
// viewport dimensions
int w = m_winW / 3;
int h = m_winH / 3;
// use glsl program
glUseProgram(m_program[HW2A].programId());
// PUT YOUR CODE HERE
// disable vertex shader point size adjustment
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::controlPanel:
//
// Create control panel groupbox.
//
QGroupBox*
HW2a::controlPanel()
{
// init group box
QGroupBox *groupBox = new QGroupBox("Homework 2a");
groupBox->setStyleSheet(GroupBoxStyle);
return(groupBox);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::reset:
//
// function to reset parameters.
//
void
HW2a::reset()
{
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::initShaders:
//
// Initialize shaders.
//
void
HW2a::initShaders()
{
// init uniforms hash table based on uniform variable names and location IDs
UniformMap uniforms;
uniforms["u_Projection"] = PROJ;
// compile shader, bind attribute vars, link shader, and initialize uniform var table
initShader(HW2A, QString(":/hw2/vshader2a.glsl"), QString(":/hw2/fshader2a.glsl"), uniforms);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::initVertexBuffer:
//
// Initialize vertex buffer.
//
void
HW2a::initVertexBuffer()
{
float vv[] = {
-0.5 , -0.75,
-0.5 , -0.5 ,
-0.5 , -0.25,
-0.5 , 0.0 ,
-0.5 , 0.25,
-0.5 , 0.5 ,
-0.25, 0.75,
0.0 , 0.75,
0.25, 0.75,
0.5 , 0.75,
0.75 , 0.5 ,
0.75, 0.25,
0.5 , 0.0 ,
0.25, 0.0 ,
0.0, 0.0 ,
-0.25, 0.0
};
std::vector<float> v (&vv[0], &vv[0]+sizeof(vv)/sizeof(float));
// init number of vertices
m_vertNum = (int) v.size() / 2;
// create a vertex buffer
GLuint vertexBuffer;
glGenBuffers(1, &vertexBuffer);
// bind vertex buffer to the GPU and copy the vertices from CPU to GPU
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, v.size()*sizeof(float), &v[0], GL_STATIC_DRAW);
// enable vertex buffer to be accessed via the attribute vertex variable and specify data format
glEnableVertexAttribArray(ATTRIB_VERTEX);
glVertexAttribPointer (ATTRIB_VERTEX, 2, GL_FLOAT, false, 0, 0);
}
|
// ===============================================================
// Computer Graphics Homework Solutions
// Copyright (C) 2017 by George Wolberg
//
// HW2a.cpp - HW2a class
//
// Written by: George Wolberg, 2017
// ===============================================================
#include "HW2a.h"
// shader ID
enum { HW2A };
// uniform ID
enum { PROJ };
const int DrawModes[] = {
GL_POINTS,
GL_LINES,
GL_LINE_STRIP,
GL_LINE_LOOP,
GL_TRIANGLES,
GL_TRIANGLE_STRIP,
GL_TRIANGLE_FAN,
GL_QUADS,
GL_POLYGON
};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::HW2a:
//
// HW2a constructor.
//
HW2a::HW2a(const QGLFormat &glf, QWidget *parent) : HW(glf, parent)
{
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::initializeGL:
//
// Initialization routine before display loop.
// Gets called once before the first time resizeGL() or paintGL() is called.
//
void
HW2a::initializeGL()
{
// initialize GL function resolution for current context
initializeGLFunctions();
// init vertex and fragment shaders
initShaders();
// initialize vertex buffer and write positions to vertex shader
initVertexBuffer();
// init state variables
glClearColor(0.0, 0.0, 0.0, 0.0); // set background color
glColor3f (1.0, 1.0, 0.0); // set foreground color
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::resizeGL:
//
// Resize event handler.
// The input parameters are the window width (w) and height (h).
//
void
HW2a::resizeGL(int w, int h)
{
// PUT YOUR CODE HERE
// save window dimensions
m_winW = w;
m_winH = h;
// compute aspect ratio
float ar = (float) w / h;
// set xmax, ymax;
float xmax, ymax;
if(ar > 1.0) { // wide screen
xmax = ar;
ymax = 1.;
} else { // tall screen
xmax = 1.;
ymax = 1 / ar;
}
// set viewport to occupy full canvas
glViewport(0, 0, w, h);
// init viewing coordinates for orthographic projection
glLoadIdentity();
glOrtho(-xmax, xmax, -ymax, ymax, -1.0, 1.0);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::paintGL:
//
// Update GL scene.
//
void
HW2a::paintGL()
{
// clear canvas with background color
glClear(GL_COLOR_BUFFER_BIT);
// enable vertex shader point size adjustment
glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
// draw data in nine viewports after splitting canvas into 3x3 cells;
// a different drawing mode is used in each viewport
// ********************
// * * * *
// * 7 * 8 * 9 *
// * * * *
// ********************
// * * * *
// * 4 * 5 * 6 *
// * * * *
// ********************
// * * * *
// * 1 * 2 * 3 *
// * * * *
// ********************
// viewport dimensions
int w = m_winW / 3;
int h = m_winH / 3;
// use glsl program
// glUseProgram(m_program[HW2A].programId());
// PUT YOUR CODE HERE
for(int i = 0; i < 3; ++i) {
for(int j = 0; j < 3; ++j) {
glViewport(j*w, i*h, w, h);
glDrawArrays(DrawModes[3*i+j], 0, 16);
}
}
// glUseProgram(0);
// disable vertex shader point size adjustment
glDisable(GL_VERTEX_PROGRAM_POINT_SIZE);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::controlPanel:
//
// Create control panel groupbox.
//
QGroupBox*
HW2a::controlPanel()
{
// init group box
QGroupBox *groupBox = new QGroupBox("Homework 2a");
groupBox->setStyleSheet(GroupBoxStyle);
return(groupBox);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::reset:
//
// function to reset parameters.
//
void
HW2a::reset()
{
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::initShaders:
//
// Initialize shaders.
//
void
HW2a::initShaders()
{
// init uniforms hash table based on uniform variable names and location IDs
UniformMap uniforms;
uniforms["u_Projection"] = PROJ;
// compile shader, bind attribute vars, link shader, and initialize uniform var table
initShader(HW2A, QString(":/hw2/vshader2a.glsl"), QString(":/hw2/fshader2a.glsl"), uniforms);
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// HW2a::initVertexBuffer:
//
// Initialize vertex buffer.
//
void
HW2a::initVertexBuffer()
{
float vv[] = {
-0.5 , -0.75,
-0.5 , -0.5 ,
-0.5 , -0.25,
-0.5 , 0.0 ,
-0.5 , 0.25,
-0.5 , 0.5 ,
-0.25, 0.75,
0.0 , 0.75,
0.25, 0.75,
0.5 , 0.75,
0.75 , 0.5 ,
0.75, 0.25,
0.5 , 0.0 ,
0.25, 0.0 ,
0.0, 0.0 ,
-0.25, 0.0
};
std::vector<float> v (&vv[0], &vv[0]+sizeof(vv)/sizeof(float));
// init number of vertices
m_vertNum = (int) v.size() / 2;
// create a vertex buffer
GLuint vertexBuffer;
glGenBuffers(1, &vertexBuffer);
// bind vertex buffer to the GPU and copy the vertices from CPU to GPU
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, v.size()*sizeof(float), &v[0], GL_STATIC_DRAW);
// enable vertex buffer to be accessed via the attribute vertex variable and specify data format
glEnableVertexAttribArray(ATTRIB_VERTEX);
glVertexAttribPointer (ATTRIB_VERTEX, 2, GL_FLOAT, false, 0, 0);
}
|
Complete HW2a.
|
Complete HW2a.
|
C++
|
mit
|
edzh/csc472-hw
|
c40cde3a2b571ad66ee2f8b56d64834474d651c4
|
applications/projects/qtQuickSofa/Main.cpp
|
applications/projects/qtQuickSofa/Main.cpp
|
#include <QtCore/QCoreApplication>
#include <QtWidgets/QApplication>
#include <QQmlApplicationEngine>
#include <QPluginLoader>
#include <QDebug>
#include "Tools.h"
using namespace sofa::qtquick;
int main(int argc, char **argv)
{
// TODO: this command disable the multithreaded render loop, currently we need this on Linux/OSX because our implementation of the sofa interface is not thread-safe
qputenv("QML_BAD_GUI_RENDER_LOOP", "1");
QApplication app(argc, argv);
app.addLibraryPath(QCoreApplication::applicationDirPath() + "/../lib/");
// application specific settings
app.setOrganizationName("Sofa");
app.setApplicationName("qtQuickSofa");
QSettings::setPath(QSettings::Format::IniFormat, QSettings::Scope::UserScope, QCoreApplication::applicationDirPath() + "/config/");
QSettings::setDefaultFormat(QSettings::Format::IniFormat);
// use the default.ini settings if it is the first time the user launch the application
Tools::useDefaultSettingsAtFirstLaunch();
// plugin initialization
QString pluginName("SofaQtQuickGUI");
#ifdef SOFA_LIBSUFFIX
pluginName += sofa_tostring(SOFA_LIBSUFFIX);
#endif
QPluginLoader pluginLoader(pluginName);
// first call to instance() initialize the plugin
if(0 == pluginLoader.instance()) {
qCritical() << "SofaQtQuickGUI plugin has not been found!";
return -1;
}
// launch the main script
QQmlApplicationEngine applicationEngine;
applicationEngine.addImportPath("qrc:/");
applicationEngine.addImportPath(QCoreApplication::applicationDirPath() + "/../lib/qml/");
applicationEngine.load(QUrl("qrc:/qml/Main.qml"));
return app.exec();
}
|
#include <QtCore/QCoreApplication>
#include <QtWidgets/QApplication>
#include <QQmlApplicationEngine>
#include <QPluginLoader>
#include <QDebug>
#include "Tools.h"
#include <sofa/helper/system/FileRepository.h>
#include <sofa/gui/BaseGUI.h>
using namespace sofa::qtquick;
int main(int argc, char **argv)
{
// TODO: this command disable the multithreaded render loop, currently we need this on Linux/OSX because our implementation of the sofa interface is not thread-safe
qputenv("QML_BAD_GUI_RENDER_LOOP", "1");
QApplication app(argc, argv);
app.addLibraryPath(QCoreApplication::applicationDirPath() + "/../lib/");
// Add the plugin directory to PluginRepository
#ifdef WIN32
const std::string pluginDir = "bin";
#else
const std::string pluginDir = "lib";
#endif
sofa::helper::system::PluginRepository.addFirstPath(sofa::gui::BaseGUI::getPathPrefix() + "/" + pluginDir);
// Initialise paths
sofa::gui::BaseGUI::setConfigDirectoryPath(sofa::gui::BaseGUI::getPathPrefix() + "/config");
sofa::gui::BaseGUI::setScreenshotDirectoryPath(sofa::gui::BaseGUI::getPathPrefix() + "/screenshots");
// application specific settings
app.setOrganizationName("Sofa");
app.setApplicationName("qtQuickSofa");
QSettings::setPath(QSettings::Format::IniFormat, QSettings::Scope::UserScope, QCoreApplication::applicationDirPath() + "/config/");
QSettings::setDefaultFormat(QSettings::Format::IniFormat);
// use the default.ini settings if it is the first time the user launch the application
Tools::useDefaultSettingsAtFirstLaunch();
// plugin initialization
QString pluginName("SofaQtQuickGUI");
#ifdef SOFA_LIBSUFFIX
pluginName += sofa_tostring(SOFA_LIBSUFFIX);
#endif
QPluginLoader pluginLoader(pluginName);
// first call to instance() initialize the plugin
if(0 == pluginLoader.instance()) {
qCritical() << "SofaQtQuickGUI plugin has not been found!";
return -1;
}
// launch the main script
QQmlApplicationEngine applicationEngine;
applicationEngine.addImportPath("qrc:/");
applicationEngine.addImportPath(QCoreApplication::applicationDirPath() + "/../lib/qml/");
applicationEngine.load(QUrl("qrc:/qml/Main.qml"));
return app.exec();
}
|
configure standard sofa plugin path
|
[QtQuickSofa] ADD: configure standard sofa plugin path
Former-commit-id: 0a64a872a99247d9b783116c145bcaae10714602
|
C++
|
lgpl-2.1
|
FabienPean/sofa,FabienPean/sofa,Anatoscope/sofa,FabienPean/sofa,Anatoscope/sofa,FabienPean/sofa,FabienPean/sofa,hdeling/sofa,hdeling/sofa,FabienPean/sofa,hdeling/sofa,Anatoscope/sofa,hdeling/sofa,Anatoscope/sofa,hdeling/sofa,Anatoscope/sofa,hdeling/sofa,hdeling/sofa,FabienPean/sofa,hdeling/sofa,hdeling/sofa,Anatoscope/sofa,Anatoscope/sofa,FabienPean/sofa,FabienPean/sofa,Anatoscope/sofa,Anatoscope/sofa,FabienPean/sofa,hdeling/sofa
|
49be19d1ce02afe1549336d3ea3714ec4a0fa837
|
CppImport/src/macro/MetaDefinitionManager.cpp
|
CppImport/src/macro/MetaDefinitionManager.cpp
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "MetaDefinitionManager.h"
#include "DefinitionManager.h"
#include "ExpansionManager.h"
#include "LexicalHelper.h"
#include "StaticStuff.h"
#include "XMacroManager.h"
namespace CppImport {
MetaDefinitionManager::MetaDefinitionManager(OOModel::Project* root, ClangHelper* clang,
DefinitionManager* definitionManager, ExpansionManager* expansionManager,
LexicalHelper* lexicalHelper, XMacroManager* xMacroManager)
: root_(root), clang_(clang), definitionManager_(definitionManager), expansionManager_(expansionManager),
lexicalHelper_(lexicalHelper), xMacroManager_(xMacroManager) {}
OOModel::Declaration* MetaDefinitionManager::metaDefinitionParent(const clang::MacroDirective* md)
{
OOModel::Declaration* result = nullptr;
QString namespaceName, fileName;
if (definitionManager_->macroDefinitionLocation(md, namespaceName, fileName))
{
// find the namespace module for md
OOModel::Module* namespaceModule =
DCast<OOModel::Module>(StaticStuff::findDeclaration(root_->modules(), namespaceName));
// this assertion holds if the project structure matches Envision's project structure
// alternatively if no such module could be found (project structure unlike Envision's) one could put it into root_
Q_ASSERT(namespaceModule); //if (!namespaceModule) return root_;
// try to find the module (includes macro containers) to put this macro in
result = StaticStuff::findDeclaration(namespaceModule->modules(), fileName);
// if no module could be found; try to find an appropriate class to put this macro in
if (!result) result = StaticStuff::findDeclaration(namespaceModule->classes(), fileName);
// if no existing place could be found: create a new module (macro container) and put the macro in there
if (!result)
{
result = new OOModel::Module(fileName);
namespaceModule->modules()->append(result);
}
}
else
{
result = StaticStuff::findDeclaration(root_->modules(), "notenvision");
if (!result)
{
result = new OOModel::Module("notenvision");
root_->modules()->append(result);
}
}
Q_ASSERT(result);
return result;
}
OOModel::MetaDefinition* MetaDefinitionManager::metaDefinition(const clang::MacroDirective* md)
{
QString h = definitionManager_->hash(md);
auto it = metaDefinitions_.find(h);
return it != metaDefinitions_.end() ? *it : nullptr;
}
void MetaDefinitionManager::createMetaDef(QVector<Model::Node*> nodes, MacroExpansion* expansion, NodeMapping* mapping,
QVector<MacroArgumentInfo>& arguments)
{
if (!metaDefinition(expansion->definition))
{
auto metaDef = new OOModel::MetaDefinition(definitionManager_->definitionName(expansion->definition));
metaDefinitions_.insert(definitionManager_->hash(expansion->definition), metaDef);
// add formal arguments based on the expansion definition
for (auto argName : clang_->argumentNames(expansion->definition))
metaDef->arguments()->append(new OOModel::FormalMetaArgument(argName));
auto metaDefParent = metaDefinitionParent(expansion->definition);
// check whether this expansion is not a potential partial begin macro specialization
if (auto beginChild = xMacroManager_->partialBeginChild(expansion))
xMacroManager_->handlePartialBeginSpecialization(metaDefParent, metaDef, expansion, beginChild);
else
{
// case: meta definition is not a partial begin macro specialization
if (nodes.size() > 0)
{
// create a new context with type equal to the first node's context
auto actualContext = StaticStuff::actualContext(mapping->original(nodes.first()));
metaDef->setContext(StaticStuff::createContext(actualContext));
// clone and add nodes to the metaDef
for (auto n : nodes)
{
NodeMapping childMapping;
auto cloned = StaticStuff::cloneWithMapping(mapping->original(n), &childMapping);
lexicalHelper_->applyLexicalTransformations(cloned, &childMapping,
clang_->argumentNames(expansion->definition));
insertChildMetaCalls(expansion, &childMapping);
if (removeUnownedNodes(cloned, expansion, &childMapping))
continue;
insertArgumentSplices(mapping, &childMapping, arguments);
StaticStuff::addNodeToDeclaration(cloned, metaDef->context());
}
}
// add all child expansion meta calls that are not yet added anywhere else as declaration meta calls
for (auto childExpansion : expansion->children)
if (!childExpansion->metaCall->parent())
metaDef->context()->metaCalls()->append(childExpansion->metaCall);
}
metaDefParent->subDeclarations()->append(metaDef);
}
// qualify the meta call
auto callee = DCast<OOModel::ReferenceExpression>(expansion->metaCall->callee());
callee->setPrefix(definitionManager_->expansionQualifier(expansion->definition));
}
void MetaDefinitionManager::renameMetaCalls(Model::Node* node, const QString& current, const QString& replace)
{
if (auto metaCall = DCast<OOModel::MetaCallExpression>(node))
{
if (auto ref = DCast<OOModel::ReferenceExpression>(metaCall->callee()))
if (ref->name() == current)
ref->setName(replace);
}
else
for (auto child : node->children())
renameMetaCalls(child, current, replace);
}
void MetaDefinitionManager::insertChildMetaCalls(MacroExpansion* expansion, NodeMapping* childMapping)
{
for (auto childExpansion : expansion->children)
{
// do not handle xMacro children here
if (childExpansion->xMacroParent) continue;
// retrieve the node that the child meta call should replace
if (auto replacementNode = childExpansion->replacementNode_)
// replacementNode is an original node therefore we need to get to the cloned domain first
// clonedReplacementNode represents the cloned version of replacementNode
if (auto clonedReplacementNode = childMapping->clone(replacementNode))
if (!DCast<OOModel::Declaration>(clonedReplacementNode))
{
if (clonedReplacementNode->parent())
clonedReplacementNode->parent()->replaceChild(clonedReplacementNode, childExpansion->metaCall);
else
qDebug() << "not inserted metacall" << clonedReplacementNode->typeName();
}
}
}
void MetaDefinitionManager::childrenUnownedByExpansion(Model::Node* node, MacroExpansion* expansion,
NodeMapping* mapping, QVector<Model::Node*>* result)
{
Q_ASSERT(expansion);
// do not remove child meta calls
if (DCast<OOModel::MetaCallExpression>(node)) return;
if (auto original = mapping->original(node))
if (expansionManager_->expansion(original).contains(expansion))
{
for (auto child : node->children())
childrenUnownedByExpansion(child, expansion, mapping, result);
return;
}
result->append(node);
}
bool MetaDefinitionManager::removeUnownedNodes(Model::Node* cloned, MacroExpansion* expansion, NodeMapping* mapping)
{
QVector<Model::Node*> unownedNodes;
childrenUnownedByExpansion(cloned, expansion, mapping, &unownedNodes);
// if the unowned nodes contain the node itself then the node should not even be added to the meta definition
if (unownedNodes.contains(cloned)) return true;
StaticStuff::removeNodes(StaticStuff::topLevelNodes(unownedNodes));
return false;
}
void MetaDefinitionManager::insertArgumentSplices(NodeMapping* mapping, NodeMapping* childMapping,
QVector<MacroArgumentInfo>& arguments)
{
for (auto argument : arguments)
{
// map the argument node to the corresponding node in childMapping
auto original = mapping->original(argument.node);
if (auto child = childMapping->clone(original))
{
// the first entry of the spelling history is where the splice for this argument should be
auto spliceLoc = argument.history.first();
// the splice name is equal to the formal argument name where the argument is coming from
auto argName = clang_->argumentNames(spliceLoc.expansion->definition).at(spliceLoc.argumentNumber);
auto newNode = new OOModel::ReferenceExpression(argName);
// insert the splice into the tree
if (child->parent()) child->parent()->replaceChild(child, newNode);
childMapping->replaceClone(child, newNode);
}
}
}
}
|
/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** 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 ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "MetaDefinitionManager.h"
#include "DefinitionManager.h"
#include "ExpansionManager.h"
#include "LexicalHelper.h"
#include "StaticStuff.h"
#include "XMacroManager.h"
namespace CppImport {
MetaDefinitionManager::MetaDefinitionManager(OOModel::Project* root, ClangHelper* clang,
DefinitionManager* definitionManager, ExpansionManager* expansionManager,
LexicalHelper* lexicalHelper, XMacroManager* xMacroManager)
: root_(root), clang_(clang), definitionManager_(definitionManager), expansionManager_(expansionManager),
lexicalHelper_(lexicalHelper), xMacroManager_(xMacroManager) {}
OOModel::Declaration* MetaDefinitionManager::metaDefinitionParent(const clang::MacroDirective* md)
{
OOModel::Declaration* result = nullptr;
QString namespaceName, fileName;
if (definitionManager_->macroDefinitionLocation(md, namespaceName, fileName))
{
// find the namespace module for md
OOModel::Module* namespaceModule =
DCast<OOModel::Module>(StaticStuff::findDeclaration(root_->modules(), namespaceName));
// this assertion holds if the project structure matches Envision's project structure
// alternatively if no such module could be found (project structure unlike Envision's) one could put it into root_
Q_ASSERT(namespaceModule); //if (!namespaceModule) return root_;
// try to find the module (includes macro containers) to put this macro in
result = StaticStuff::findDeclaration(namespaceModule->modules(), fileName);
// if no module could be found; try to find an appropriate class to put this macro in
if (!result) result = StaticStuff::findDeclaration(namespaceModule->classes(), fileName);
// if no existing place could be found: create a new module (macro container) and put the macro in there
if (!result)
{
result = new OOModel::Module(fileName);
namespaceModule->modules()->append(result);
}
}
else
{
result = StaticStuff::findDeclaration(root_->modules(), "ExternalMacro");
if (!result)
{
result = new OOModel::Module("ExternalMacro");
root_->modules()->append(result);
}
}
Q_ASSERT(result);
return result;
}
OOModel::MetaDefinition* MetaDefinitionManager::metaDefinition(const clang::MacroDirective* md)
{
QString h = definitionManager_->hash(md);
auto it = metaDefinitions_.find(h);
return it != metaDefinitions_.end() ? *it : nullptr;
}
void MetaDefinitionManager::createMetaDef(QVector<Model::Node*> nodes, MacroExpansion* expansion, NodeMapping* mapping,
QVector<MacroArgumentInfo>& arguments)
{
if (!metaDefinition(expansion->definition))
{
auto metaDef = new OOModel::MetaDefinition(definitionManager_->definitionName(expansion->definition));
metaDefinitions_.insert(definitionManager_->hash(expansion->definition), metaDef);
// add formal arguments based on the expansion definition
for (auto argName : clang_->argumentNames(expansion->definition))
metaDef->arguments()->append(new OOModel::FormalMetaArgument(argName));
auto metaDefParent = metaDefinitionParent(expansion->definition);
// check whether this expansion is not a potential partial begin macro specialization
if (auto beginChild = xMacroManager_->partialBeginChild(expansion))
xMacroManager_->handlePartialBeginSpecialization(metaDefParent, metaDef, expansion, beginChild);
else
{
// case: meta definition is not a partial begin macro specialization
if (nodes.size() > 0)
{
// create a new context with type equal to the first node's context
auto actualContext = StaticStuff::actualContext(mapping->original(nodes.first()));
metaDef->setContext(StaticStuff::createContext(actualContext));
// clone and add nodes to the metaDef
for (auto n : nodes)
{
NodeMapping childMapping;
auto cloned = StaticStuff::cloneWithMapping(mapping->original(n), &childMapping);
lexicalHelper_->applyLexicalTransformations(cloned, &childMapping,
clang_->argumentNames(expansion->definition));
insertChildMetaCalls(expansion, &childMapping);
if (removeUnownedNodes(cloned, expansion, &childMapping))
continue;
insertArgumentSplices(mapping, &childMapping, arguments);
StaticStuff::addNodeToDeclaration(cloned, metaDef->context());
}
}
// add all child expansion meta calls that are not yet added anywhere else as declaration meta calls
for (auto childExpansion : expansion->children)
if (!childExpansion->metaCall->parent())
metaDef->context()->metaCalls()->append(childExpansion->metaCall);
}
metaDefParent->subDeclarations()->append(metaDef);
}
// qualify the meta call
auto callee = DCast<OOModel::ReferenceExpression>(expansion->metaCall->callee());
callee->setPrefix(definitionManager_->expansionQualifier(expansion->definition));
}
void MetaDefinitionManager::renameMetaCalls(Model::Node* node, const QString& current, const QString& replace)
{
if (auto metaCall = DCast<OOModel::MetaCallExpression>(node))
{
if (auto ref = DCast<OOModel::ReferenceExpression>(metaCall->callee()))
if (ref->name() == current)
ref->setName(replace);
}
else
for (auto child : node->children())
renameMetaCalls(child, current, replace);
}
void MetaDefinitionManager::insertChildMetaCalls(MacroExpansion* expansion, NodeMapping* childMapping)
{
for (auto childExpansion : expansion->children)
{
// do not handle xMacro children here
if (childExpansion->xMacroParent) continue;
// retrieve the node that the child meta call should replace
if (auto replacementNode = childExpansion->replacementNode_)
// replacementNode is an original node therefore we need to get to the cloned domain first
// clonedReplacementNode represents the cloned version of replacementNode
if (auto clonedReplacementNode = childMapping->clone(replacementNode))
if (!DCast<OOModel::Declaration>(clonedReplacementNode))
{
if (clonedReplacementNode->parent())
clonedReplacementNode->parent()->replaceChild(clonedReplacementNode, childExpansion->metaCall);
else
qDebug() << "not inserted metacall" << clonedReplacementNode->typeName();
}
}
}
void MetaDefinitionManager::childrenUnownedByExpansion(Model::Node* node, MacroExpansion* expansion,
NodeMapping* mapping, QVector<Model::Node*>* result)
{
Q_ASSERT(expansion);
// do not remove child meta calls
if (DCast<OOModel::MetaCallExpression>(node)) return;
if (auto original = mapping->original(node))
if (expansionManager_->expansion(original).contains(expansion))
{
for (auto child : node->children())
childrenUnownedByExpansion(child, expansion, mapping, result);
return;
}
result->append(node);
}
bool MetaDefinitionManager::removeUnownedNodes(Model::Node* cloned, MacroExpansion* expansion, NodeMapping* mapping)
{
QVector<Model::Node*> unownedNodes;
childrenUnownedByExpansion(cloned, expansion, mapping, &unownedNodes);
// if the unowned nodes contain the node itself then the node should not even be added to the meta definition
if (unownedNodes.contains(cloned)) return true;
StaticStuff::removeNodes(StaticStuff::topLevelNodes(unownedNodes));
return false;
}
void MetaDefinitionManager::insertArgumentSplices(NodeMapping* mapping, NodeMapping* childMapping,
QVector<MacroArgumentInfo>& arguments)
{
for (auto argument : arguments)
{
// map the argument node to the corresponding node in childMapping
auto original = mapping->original(argument.node);
if (auto child = childMapping->clone(original))
{
// the first entry of the spelling history is where the splice for this argument should be
auto spliceLoc = argument.history.first();
// the splice name is equal to the formal argument name where the argument is coming from
auto argName = clang_->argumentNames(spliceLoc.expansion->definition).at(spliceLoc.argumentNumber);
auto newNode = new OOModel::ReferenceExpression(argName);
// insert the splice into the tree
if (child->parent()) child->parent()->replaceChild(child, newNode);
childMapping->replaceClone(child, newNode);
}
}
}
}
|
change container name of external macros
|
change container name of external macros
|
C++
|
bsd-3-clause
|
mgalbier/Envision,mgalbier/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,mgalbier/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,mgalbier/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,dimitar-asenov/Envision,dimitar-asenov/Envision,mgalbier/Envision,mgalbier/Envision
|
53ca4a51f92806471ed28e06cc4ca5c5c5ac105d
|
include/wonder_rabbit_project/wonderland.renderer.detail/model.detail/model.hxx
|
include/wonder_rabbit_project/wonderland.renderer.detail/model.detail/model.hxx
|
#pragma once
#include <map>
#include <unordered_map>
#include <functional>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
// assimp::Importer
#include <assimp/Importer.hpp>
// aiPostProcessSteps for assimp::Importer::ReadFile
#include <assimp/postprocess.h>
// aiScene, aiNode
#include <assimp/scene.h>
//#include "glew.detail/c.hxx"
//#include "glew.detail/gl_type.hxx"
#include "helper.hxx"
#include "material.hxx"
#include "mesh.hxx"
#include "node.hxx"
#include "bone.hxx"
#include "animation_data.hxx"
namespace wonder_rabbit_project
{
namespace wonderland
{
namespace renderer
{
namespace model
{
class model_t
{
// アニメーションデータ
std::unordered_map< std::string, animation_t > _animations;
// ボーン名 -> ボーンID
std::unordered_map< std::string, unsigned > _bone_name_to_bone_index_mapping;
// ボーンオフセット群
std::vector< glm::mat4 > _bone_offsets;
// アニメーション名
std::vector< std::string > _animation_names;
// モデルデータに含まれるマテリアル群を格納
std::vector< material_t > _materials;
// モデルデータに含まれるメッシュ群を格納
std::vector< mesh_t > _meshes;
// ノード
node_t _node;
// ルートノードの変形行列の逆行列(アニメーション適用で使用)
glm::mat4 _global_inverse_transformation;
inline auto apply_animation_recursive
( const animation_states_t& animation_states
, const node_t& node
, std::vector< glm::mat4 >& bone_animation_transformations
, const glm::mat4& parent_transformation
)
-> void
{
for ( auto& animation_state : animation_states )
{
glm::mat4 node_transformation( node.transformation() );
auto animation_iterator = _animations.find( animation_state.name );
if( animation_iterator not_eq _animations.end() )
node_transformation = animation_iterator -> second.transformation( node.name(), animation_state.time_in_seconds );
const auto global_transformation = parent_transformation * node_transformation;
const auto bone_name_to_index_iterator = _bone_name_to_bone_index_mapping.find( node.name() );
if( bone_name_to_index_iterator not_eq _bone_name_to_bone_index_mapping.end() )
{
const auto bone_index = bone_name_to_index_iterator -> second;
bone_animation_transformations[ bone_index ]
= _global_inverse_transformation * global_transformation * _bone_offsets[ bone_index ];
}
for ( const auto& child_node : node.nodes() )
apply_animation_recursive( animation_states, child_node, bone_animation_transformations, global_transformation );
// TODO: 複数のアニメーションの合成に対応する。現状: 最初の1つで break
break;
}
}
inline auto apply_animation( const animation_states_t& animation_states, const glew::gl_type::GLint program_id )
-> void
{
// update animation matrices
// アニメーション最終変形行列
std::vector< glm::mat4 > bone_animation_transformations;
bone_animation_transformations.resize( _bone_offsets.size(), glm::mat4( 1.0f ) );
apply_animation_recursive( animation_states, _node, bone_animation_transformations, glm::mat4( 1.0f ) );
const auto location_of_bones = glew::c::glGetUniformLocation( program_id, "bones" );
if ( location_of_bones not_eq -1 )
glew::c::glUniformMatrix4fv
( location_of_bones
, bone_animation_transformations.size()
, false
, &bone_animation_transformations[0][0][0]
);
}
public:
// const aiScene* からモデルデータ(メッシュ群、ノードグラフ)を生成
explicit model_t( const aiScene* scene, const std::string& path_prefix = "", const bool transpose_node = false )
: _node( scene -> mRootNode, _animations, transpose_node )
, _global_inverse_transformation( glm::inverse( helper::to_glm_mat4( scene -> mRootNode -> mTransformation ) ) )
{
// シーンからマテリアル群を _materials に生成
_materials.reserve( scene -> mNumMaterials );
for ( auto n = 0; n < scene -> mNumMaterials; ++n )
_materials.emplace_back( scene -> mMaterials[ n ], path_prefix );
// シーンからメッシュ群を _meshes に生成
_meshes.reserve( scene -> mNumMeshes );
for ( auto n = 0; n < scene -> mNumMeshes; ++n )
_meshes.emplace_back
( scene -> mMeshes[ n ]
, _materials
, _bone_offsets
, _bone_name_to_bone_index_mapping
, _animations
);
// アニメーション情報群を保存
for ( auto n = 0; n < scene -> mNumAnimations; ++n )
{
const auto animation = scene -> mAnimations[ n ];
animation_t data;
data.duration = animation -> mDuration;
data.ticks_per_second = animation -> mTicksPerSecond == 0.0f ? 25.0f : animation -> mTicksPerSecond;
for ( auto n_channels = 0; n_channels < animation -> mNumChannels; ++n_channels )
{
const auto channel = animation -> mChannels[ n_channels ];
animation_t::channel_t ch;
for ( auto n_key = 0; n_key < channel -> mNumScalingKeys; ++ n_key )
{
const auto key = channel -> mScalingKeys[ n_key ];
ch.scalings.emplace( std::move( key.mTime ), helper::to_glm_vec3( &key.mValue ) );
}
for ( auto n_key = 0; n_key < channel -> mNumRotationKeys; ++ n_key )
{
const auto key = channel -> mRotationKeys[ n_key ];
ch.rotations.emplace( std::move( key.mTime ), helper::to_glm_quat( &key.mValue ) );
}
for ( auto n_key = 0; n_key < channel -> mNumPositionKeys; ++ n_key )
{
const auto key = channel -> mPositionKeys[ n_key ];
ch.translations.emplace( std::move( key.mTime ), helper::to_glm_vec3( &key.mValue ) );
}
data.channels.emplace( std::string( channel -> mNodeName.C_Str() ), std::move( ch ) );
}
const std::string animation_name = animation -> mName.C_Str();
_animation_names.emplace_back( animation_name );
_animations.emplace
( std::move( animation_name )
, std::move( data )
);
}
}
// 描画
auto draw( const animation_states_t& animation_states = animation_states_t() )
-> void
{
glew::gl_type::GLint program_id;
glew::c::glGetIntegerv( GL_CURRENT_PROGRAM, &program_id );
const auto location_of_local_transformation = glew::c::glGetUniformLocation( program_id, "local_transformation" );
if ( location_of_local_transformation not_eq -1 )
{
const glm::mat4 gpu_local_transformation( 1.0f );
glew::c::glUniformMatrix4fv( location_of_local_transformation , 1, false, &gpu_local_transformation[0][0] );
}
apply_animation( animation_states, program_id );
_node.draw
( _meshes
, animation_states
, program_id
, location_of_local_transformation
);
}
// ボーンの名前のリストを提供
auto bone_names()
-> std::vector< std::string >
{
std::vector< std::string > r;
r.reserve( _bone_name_to_bone_index_mapping.size() );
for ( const auto& m : _bone_name_to_bone_index_mapping )
r.emplace_back( m.first );
return r;
}
// アニメーションの名前のリストを提供
auto animation_names()
-> std::vector< std::string >
{ return _animation_names; }
static constexpr unsigned int default_importer_readfile_flags
= aiProcess_CalcTangentSpace
//| aiProcess_JoinIdenticalVertices // 有効化すると結果的にボーン情報が削除される
| aiProcess_GenNormals
| aiProcess_GenSmoothNormals
//| aiProcess_PreTransformVertices // 有効化するとアニメーション関連情報が削除される
| aiProcess_ValidateDataStructure
| aiProcess_ImproveCacheLocality
| aiProcess_RemoveRedundantMaterials
| aiProcess_FixInfacingNormals
//| aiProcess_SortByPType
| aiProcess_FindInvalidData
| aiProcess_GenUVCoords
| aiProcess_FindInstances
| aiProcess_OptimizeMeshes
| aiProcess_OptimizeGraph
| aiProcess_Triangulate
;
// ファイルからモデルデータを生成
static auto create( const std::string& file_path, unsigned int importer_readfile_flags = default_importer_readfile_flags )
-> model_t
{
// Assimp::Importer ctor
// http://assimp.sourceforge.net/lib_html/class_assimp_1_1_importer.html#a2c207299ed05f1db1ad1e6dab005f719
// ctorはパラメーター無し版とコピーctor版のみ。
Assimp::Importer i;
// Assimp::Importer::ReadFile
// http://assimp.sourceforge.net/lib_html/class_assimp_1_1_importer.html#a174418ab41d5b8bc51a044895cb991e5
// C文字列版、std::string版があり、ReadFileの他にメモリー上の任意のアドレスから読み込むReadFileMemoryもある。
// 第二パラメーターで以下のポストプロセスのフラグを扱える。
// http://assimp.sourceforge.net/lib_html/postprocess_8h.html#a64795260b95f5a4b3f3dc1be4f52e410
// aiProcess_CalcTangentSpace : 接線空間(タンジェント・バイタンジェント)を計算
// aiProcess_JoinIdenticalVertices : 重複する頂点座標の削除
// aiProcess_MakeLeftHanded : 左手座標系へ変換
// aiProcess_Triangulate : 三角面へ変換
// aiProcess_RemoveComponent : コンポーネント(アニメーション、材質、光源、カメラ、テクスチャー、頂点)を除去
// aiProcess_GenNormals : 面法線を生成
// aiProcess_GenSmoothNormals : スムーズ法線を頂点に生成
// aiProcess_SplitLargeMeshes : 巨大なメッシュをサブメッシュに分割
// aiProcess_PreTransformVertices : ノードグラフから変形前のローカル頂点座標と変形行列を除去(スケルタルアニメーション用データが消えます)
// aiProcess_LimitBoneWeights : 1つの頂点に影響するボーン数を制限
// aiProcess_ValidateDataStructure : データ構造の整合性を確認
// aiProcess_ImproveCacheLocality : 頂点キャッシュの局所性により三角形を最適化
// aiProcess_RemoveRedundantMaterials: 冗長または未使用の材質を除去
// aiProcess_FixInfacingNormals : 面法線が内向きの場合に逆転させる
// aiProcess_SortByPType : 異なる複数のプリミティブ型からなるメッシュをサブメッシュに分割
// aiProcess_FindDegenerates : メッシュを線と点にする
// aiProcess_FindInvalidData : 不正な法線や不正なUV座標を除去または修正する
// aiProcess_GenUVCoords : 非UVマップ(球状または円筒状)からUVマップへ変換
// aiProcess_TransformUVCoords : UV変形を適用する
// aiProcess_FindInstances : 重複するメッシュを探し初出のメッシュに置き換える
// aiProcess_OptimizeMeshes : メッシュ最適化を行う
// aiProcess_OptimizeGraph : シーングラフ最適化を行う
// aiProcess_FlipUVs : UV座標を反転
// aiProcess_FlipWindingOrder : 面生成を時計回りにする
// aiProcess_SplitByBoneCount : ボーン数によりメッシュを分割
// aiProcess_Debone : ボーンをロスレスないし閾値まで除去
// このポストプロセスは ApplyPostProcessing() を後で呼んで行う事もできる。
auto flags = default_importer_readfile_flags;
auto transpose_node = false;
{
auto ext = file_path.substr( file_path.rfind('.') + 1 );
if ( ext == "x" )
flags |= aiProcess_FlipUVs;
else if ( ext == "cob" || ext == "fbx")
transpose_node = true;
}
auto scene = i.ReadFile( file_path, flags );
if ( not scene )
throw std::runtime_error( i.GetErrorString() );
model_t r( scene, file_path.substr(0, file_path.find_last_of('/')), transpose_node );
i.FreeScene();
return r;
}
};
}
}
}
}
|
#pragma once
#include <map>
#include <unordered_map>
#include <functional>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/quaternion.hpp>
#include <glm/mat4x4.hpp>
// assimp::Importer
#include <assimp/Importer.hpp>
// aiPostProcessSteps for assimp::Importer::ReadFile
#include <assimp/postprocess.h>
// aiScene, aiNode
#include <assimp/scene.h>
//#include "glew.detail/c.hxx"
//#include "glew.detail/gl_type.hxx"
#include "helper.hxx"
#include "material.hxx"
#include "mesh.hxx"
#include "node.hxx"
#include "bone.hxx"
#include "animation_data.hxx"
namespace wonder_rabbit_project
{
namespace wonderland
{
namespace renderer
{
namespace model
{
class model_t
{
// アニメーションデータ
std::unordered_map< std::string, animation_t > _animations;
// ボーン名 -> ボーンID
std::unordered_map< std::string, unsigned > _bone_name_to_bone_index_mapping;
// ボーンオフセット群
std::vector< glm::mat4 > _bone_offsets;
// アニメーション名
std::vector< std::string > _animation_names;
// モデルデータに含まれるマテリアル群を格納
std::vector< material_t > _materials;
// モデルデータに含まれるメッシュ群を格納
std::vector< mesh_t > _meshes;
// ノード
node_t _node;
// ルートノードの変形行列の逆行列(アニメーション適用で使用)
glm::mat4 _global_inverse_transformation;
inline auto apply_animation_recursive
( const animation_states_t& animation_states
, const node_t& node
, std::vector< glm::mat4 >& bone_animation_transformations
, const glm::mat4& parent_transformation
)
-> void
{
for ( auto& animation_state : animation_states )
{
glm::mat4 node_transformation( node.transformation() );
auto animation_iterator = _animations.find( animation_state.name );
if( animation_iterator not_eq _animations.end() )
node_transformation = animation_iterator -> second.transformation( node.name(), animation_state.time_in_seconds );
const auto global_transformation = parent_transformation * node_transformation;
const auto bone_name_to_index_iterator = _bone_name_to_bone_index_mapping.find( node.name() );
if( bone_name_to_index_iterator not_eq _bone_name_to_bone_index_mapping.end() )
{
const auto bone_index = bone_name_to_index_iterator -> second;
bone_animation_transformations[ bone_index ]
= _global_inverse_transformation * global_transformation * _bone_offsets[ bone_index ];
}
for ( const auto& child_node : node.nodes() )
apply_animation_recursive( animation_states, child_node, bone_animation_transformations, global_transformation );
// TODO: 複数のアニメーションの合成に対応する。現状: 最初の1つで break
break;
}
}
inline auto apply_animation( const animation_states_t& animation_states, const glew::gl_type::GLint program_id )
-> void
{
if ( _bone_offsets.empty() or animation_states.empty() )
return;
// update animation matrices
// アニメーション最終変形行列
std::vector< glm::mat4 > bone_animation_transformations;
bone_animation_transformations.resize( _bone_offsets.size(), glm::mat4( 1.0f ) );
apply_animation_recursive( animation_states, _node, bone_animation_transformations, glm::mat4( 1.0f ) );
const auto location_of_bones = glew::c::glGetUniformLocation( program_id, "bones" );
if ( location_of_bones not_eq -1 )
glew::c::glUniformMatrix4fv
( location_of_bones
, bone_animation_transformations.size()
, false
, &bone_animation_transformations[0][0][0]
);
}
public:
// const aiScene* からモデルデータ(メッシュ群、ノードグラフ)を生成
explicit model_t( const aiScene* scene, const std::string& path_prefix = "", const bool transpose_node = false )
: _node( scene -> mRootNode, _animations, transpose_node )
, _global_inverse_transformation( glm::inverse( helper::to_glm_mat4( scene -> mRootNode -> mTransformation ) ) )
{
// シーンからマテリアル群を _materials に生成
_materials.reserve( scene -> mNumMaterials );
for ( auto n = 0; n < scene -> mNumMaterials; ++n )
_materials.emplace_back( scene -> mMaterials[ n ], path_prefix );
// シーンからメッシュ群を _meshes に生成
_meshes.reserve( scene -> mNumMeshes );
for ( auto n = 0; n < scene -> mNumMeshes; ++n )
_meshes.emplace_back
( scene -> mMeshes[ n ]
, _materials
, _bone_offsets
, _bone_name_to_bone_index_mapping
, _animations
);
// アニメーション情報群を保存
for ( auto n = 0; n < scene -> mNumAnimations; ++n )
{
const auto animation = scene -> mAnimations[ n ];
animation_t data;
data.duration = animation -> mDuration;
data.ticks_per_second = animation -> mTicksPerSecond == 0.0f ? 25.0f : animation -> mTicksPerSecond;
for ( auto n_channels = 0; n_channels < animation -> mNumChannels; ++n_channels )
{
const auto channel = animation -> mChannels[ n_channels ];
animation_t::channel_t ch;
for ( auto n_key = 0; n_key < channel -> mNumScalingKeys; ++ n_key )
{
const auto key = channel -> mScalingKeys[ n_key ];
ch.scalings.emplace( std::move( key.mTime ), helper::to_glm_vec3( &key.mValue ) );
}
for ( auto n_key = 0; n_key < channel -> mNumRotationKeys; ++ n_key )
{
const auto key = channel -> mRotationKeys[ n_key ];
ch.rotations.emplace( std::move( key.mTime ), helper::to_glm_quat( &key.mValue ) );
}
for ( auto n_key = 0; n_key < channel -> mNumPositionKeys; ++ n_key )
{
const auto key = channel -> mPositionKeys[ n_key ];
ch.translations.emplace( std::move( key.mTime ), helper::to_glm_vec3( &key.mValue ) );
}
data.channels.emplace( std::string( channel -> mNodeName.C_Str() ), std::move( ch ) );
}
const std::string animation_name = animation -> mName.C_Str();
_animation_names.emplace_back( animation_name );
_animations.emplace
( std::move( animation_name )
, std::move( data )
);
}
}
// 描画
auto draw( const animation_states_t& animation_states = animation_states_t() )
-> void
{
glew::gl_type::GLint program_id;
glew::c::glGetIntegerv( GL_CURRENT_PROGRAM, &program_id );
const auto location_of_local_transformation = glew::c::glGetUniformLocation( program_id, "local_transformation" );
if ( location_of_local_transformation not_eq -1 )
{
const glm::mat4 gpu_local_transformation( 1.0f );
glew::c::glUniformMatrix4fv( location_of_local_transformation , 1, false, &gpu_local_transformation[0][0] );
}
apply_animation( animation_states, program_id );
_node.draw
( _meshes
, animation_states
, program_id
, location_of_local_transformation
);
}
// ボーンの名前のリストを提供
auto bone_names()
-> std::vector< std::string >
{
std::vector< std::string > r;
r.reserve( _bone_name_to_bone_index_mapping.size() );
for ( const auto& m : _bone_name_to_bone_index_mapping )
r.emplace_back( m.first );
return r;
}
// アニメーションの名前のリストを提供
auto animation_names()
-> std::vector< std::string >
{ return _animation_names; }
static constexpr unsigned int default_importer_readfile_flags
= aiProcess_CalcTangentSpace
//| aiProcess_JoinIdenticalVertices // 有効化すると結果的にボーン情報が削除される
| aiProcess_GenNormals
| aiProcess_GenSmoothNormals
//| aiProcess_PreTransformVertices // 有効化するとアニメーション関連情報が削除される
| aiProcess_ValidateDataStructure
| aiProcess_ImproveCacheLocality
| aiProcess_RemoveRedundantMaterials
| aiProcess_FixInfacingNormals
//| aiProcess_SortByPType
| aiProcess_FindInvalidData
| aiProcess_GenUVCoords
| aiProcess_FindInstances
| aiProcess_OptimizeMeshes
| aiProcess_OptimizeGraph
| aiProcess_Triangulate
;
// ファイルからモデルデータを生成
static auto create( const std::string& file_path, unsigned int importer_readfile_flags = default_importer_readfile_flags )
-> model_t
{
// Assimp::Importer ctor
// http://assimp.sourceforge.net/lib_html/class_assimp_1_1_importer.html#a2c207299ed05f1db1ad1e6dab005f719
// ctorはパラメーター無し版とコピーctor版のみ。
Assimp::Importer i;
// Assimp::Importer::ReadFile
// http://assimp.sourceforge.net/lib_html/class_assimp_1_1_importer.html#a174418ab41d5b8bc51a044895cb991e5
// C文字列版、std::string版があり、ReadFileの他にメモリー上の任意のアドレスから読み込むReadFileMemoryもある。
// 第二パラメーターで以下のポストプロセスのフラグを扱える。
// http://assimp.sourceforge.net/lib_html/postprocess_8h.html#a64795260b95f5a4b3f3dc1be4f52e410
// aiProcess_CalcTangentSpace : 接線空間(タンジェント・バイタンジェント)を計算
// aiProcess_JoinIdenticalVertices : 重複する頂点座標の削除
// aiProcess_MakeLeftHanded : 左手座標系へ変換
// aiProcess_Triangulate : 三角面へ変換
// aiProcess_RemoveComponent : コンポーネント(アニメーション、材質、光源、カメラ、テクスチャー、頂点)を除去
// aiProcess_GenNormals : 面法線を生成
// aiProcess_GenSmoothNormals : スムーズ法線を頂点に生成
// aiProcess_SplitLargeMeshes : 巨大なメッシュをサブメッシュに分割
// aiProcess_PreTransformVertices : ノードグラフから変形前のローカル頂点座標と変形行列を除去(スケルタルアニメーション用データが消えます)
// aiProcess_LimitBoneWeights : 1つの頂点に影響するボーン数を制限
// aiProcess_ValidateDataStructure : データ構造の整合性を確認
// aiProcess_ImproveCacheLocality : 頂点キャッシュの局所性により三角形を最適化
// aiProcess_RemoveRedundantMaterials: 冗長または未使用の材質を除去
// aiProcess_FixInfacingNormals : 面法線が内向きの場合に逆転させる
// aiProcess_SortByPType : 異なる複数のプリミティブ型からなるメッシュをサブメッシュに分割
// aiProcess_FindDegenerates : メッシュを線と点にする
// aiProcess_FindInvalidData : 不正な法線や不正なUV座標を除去または修正する
// aiProcess_GenUVCoords : 非UVマップ(球状または円筒状)からUVマップへ変換
// aiProcess_TransformUVCoords : UV変形を適用する
// aiProcess_FindInstances : 重複するメッシュを探し初出のメッシュに置き換える
// aiProcess_OptimizeMeshes : メッシュ最適化を行う
// aiProcess_OptimizeGraph : シーングラフ最適化を行う
// aiProcess_FlipUVs : UV座標を反転
// aiProcess_FlipWindingOrder : 面生成を時計回りにする
// aiProcess_SplitByBoneCount : ボーン数によりメッシュを分割
// aiProcess_Debone : ボーンをロスレスないし閾値まで除去
// このポストプロセスは ApplyPostProcessing() を後で呼んで行う事もできる。
auto flags = default_importer_readfile_flags;
auto transpose_node = false;
{
auto ext = file_path.substr( file_path.rfind('.') + 1 );
if ( ext == "x" )
flags |= aiProcess_FlipUVs;
else if ( ext == "cob" || ext == "fbx")
transpose_node = true;
}
auto scene = i.ReadFile( file_path, flags );
if ( not scene )
throw std::runtime_error( i.GetErrorString() );
model_t r( scene, file_path.substr(0, file_path.find_last_of('/')), transpose_node );
i.FreeScene();
return r;
}
};
}
}
}
}
|
fix to no process animation if model has not animation or draw with nothing animation state.
|
fix to no process animation if model has not animation or draw with nothing animation state.
|
C++
|
mit
|
usagi/wonderland.renderer,usagi/wonderland.renderer
|
b74ce2847a0209adb3e906cc8984ad3dd46f311e
|
api/hdf5_impl/hdf5Alignment.cpp
|
api/hdf5_impl/hdf5Alignment.cpp
|
/*
* Copyright (C) 2012 by Glenn Hickey ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
#include <cassert>
#include <iostream>
#include <cstdlib>
#include <deque>
#include "hdf5Alignment.h"
#include "hdf5MetaData.h"
#include "hdf5Genome.h"
extern "C" {
#include "sonLibTree.h"
}
using namespace hal;
using namespace std;
using namespace H5;
/** default group name for MetaData attributes, will be a subgroup
* of the top level of the file, ie /Meta */
const H5std_string HDF5Alignment::MetaGroupName = "Meta";
const H5std_string HDF5Alignment::TreeGroupName = "Phylogeny";
const H5std_string HDF5Alignment::GenomesGroupName = "Genomes";
HDF5Alignment::HDF5Alignment() :
_file(NULL),
_cprops(FileCreatPropList::DEFAULT),
_aprops(FileAccPropList::DEFAULT),
_dcprops(DSetCreatPropList::DEFAULT),
_flags(H5F_ACC_RDONLY),
_metaData(NULL),
_tree(NULL),
_dirty(false)
{
// Todo: verify chunk size
_dcprops = DSetCreatPropList();
_dcprops.setDeflate(9);
hsize_t chunkSize = 2000000;
_dcprops.setChunk(1, &chunkSize);
_aprops.setCache(11, 51, 100000000, 0.25);
}
HDF5Alignment::HDF5Alignment(const H5::FileCreatPropList& fileCreateProps,
const H5::FileAccPropList& fileAccessProps,
const H5::DSetCreatPropList& datasetCreateProps) :
_file(NULL),
_cprops(fileCreateProps),
_aprops(fileAccessProps),
_dcprops(datasetCreateProps),
_flags(H5F_ACC_RDONLY),
_metaData(NULL),
_tree(NULL),
_dirty(false)
{
}
HDF5Alignment::~HDF5Alignment()
{
close();
}
void HDF5Alignment::createNew(const string& alignmentPath)
{
close();
_flags = H5F_ACC_TRUNC;
_file = new H5File(alignmentPath.c_str(), _flags, _cprops, _aprops);
_file->createGroup(MetaGroupName);
_file->createGroup(TreeGroupName);
_file->createGroup(GenomesGroupName);
delete _metaData;
_metaData = new HDF5MetaData(_file, MetaGroupName);
_tree = NULL;
_dirty = true;
}
// todo: properly handle readonly
void HDF5Alignment::open(const string& alignmentPath, bool readOnly)
{
close();
delete _file;
int _flags = readOnly ? H5F_ACC_RDONLY : H5F_ACC_RDWR;
_file = new H5File(alignmentPath.c_str(), _flags, _cprops, _aprops);
delete _metaData;
_metaData = new HDF5MetaData(_file, MetaGroupName);
loadTree();
}
// todo: properly handle readonly
void HDF5Alignment::open(const string& alignmentPath) const
{
const_cast<HDF5Alignment*>(this)->open(alignmentPath, true);
}
void HDF5Alignment::close()
{
if (_file != NULL)
{
writeTree();
if (_tree != NULL)
{
stTree_destruct(_tree);
_tree = NULL;
}
// todo: make sure there's no memory leak with metadata
// smart pointer should prevent
if (_metaData != NULL)
{
_metaData->write();
delete _metaData;
_metaData = NULL;
}
map<string, HDF5Genome*>::iterator mapIt;
for (mapIt = _openGenomes.begin(); mapIt != _openGenomes.end(); ++mapIt)
{
HDF5Genome* genome = mapIt->second;
genome->write();
delete genome;
}
_openGenomes.clear();
_file->flush(H5F_SCOPE_LOCAL);
_file->close();
delete _file;
_file = NULL;
}
else
{
assert(_tree == NULL);
assert(_openGenomes.empty() == true);
}
}
Genome* HDF5Alignment::addLeafGenome(const string& name,
const string& parentName,
double branchLength)
{
if (name.empty() == true || parentName.empty())
{
throw hal_exception("name can't be empty");
}
map<string, stTree*>::iterator findIt = _nodeMap.find(name);
if (findIt != _nodeMap.end())
{
throw hal_exception(string("node ") + name + " already exists");
}
findIt = _nodeMap.find(parentName);
if (findIt == _nodeMap.end())
{
throw hal_exception(string("parent ") + parentName + " not found in tree");
}
stTree* parent = findIt->second;
stTree* node = stTree_construct();
stTree_setLabel(node, name.c_str());
stTree_setParent(node, parent);
stTree_setBranchLength(node, branchLength);
_nodeMap.insert(pair<string, stTree*>(name, node));
HDF5Genome* genome = new HDF5Genome(name, this, _file, _dcprops);
_openGenomes.insert(pair<string, HDF5Genome*>(name, genome));
_dirty = true;
return genome;
}
Genome* HDF5Alignment::addRootGenome(const string& name,
double branchLength)
{
if (name.empty() == true)
{
throw hal_exception("name can't be empty");
}
map<string, stTree*>::iterator findIt = _nodeMap.find(name);
if (findIt != _nodeMap.end())
{
throw hal_exception(string("node ") + name + " already exists");
}
stTree* node = stTree_construct();
stTree_setLabel(node, name.c_str());
if (_tree != NULL)
{
stTree_setParent(_tree, node);
stTree_setBranchLength(_tree, branchLength);
}
_tree = node;
_nodeMap.insert(pair<string, stTree*>(name, node));
HDF5Genome* genome = new HDF5Genome(name, this, _file, _dcprops);
_openGenomes.insert(pair<string, HDF5Genome*>(name, genome));
_dirty = true;
return genome;
}
void HDF5Alignment::removeGenome(const string& name)
{
}
const Genome* HDF5Alignment::openGenome(const string& name) const
{
map<string, HDF5Genome*>::iterator mapit = _openGenomes.find(name);
if (mapit != _openGenomes.end())
{
return mapit->second;
}
HDF5Genome* genome = NULL;
if (_nodeMap.find(name) != _nodeMap.end())
{
genome = new HDF5Genome(name, const_cast<HDF5Alignment*>(this),
_file, _dcprops);
genome->read();
_openGenomes.insert(pair<string, HDF5Genome*>(name, genome));
}
return genome;
}
Genome* HDF5Alignment::openGenome(const string& name)
{
map<string, HDF5Genome*>::iterator mapit = _openGenomes.find(name);
if (mapit != _openGenomes.end())
{
return mapit->second;
}
HDF5Genome* genome = NULL;
if (_nodeMap.find(name) != _nodeMap.end())
{
genome = new HDF5Genome(name, this, _file, _dcprops);
genome->read();
_openGenomes.insert(pair<string, HDF5Genome*>(name, genome));
}
return genome;
}
void HDF5Alignment::closeGenome(const Genome* genome) const
{
string name = genome->getName();
map<string, HDF5Genome*>::iterator mapIt = _openGenomes.find(name);
if (mapIt == _openGenomes.end())
{
throw hal_exception("Attempt to close non-open genome. "
"Should not even be possible");
}
mapIt->second->write();
delete mapIt->second;
_openGenomes.erase(mapIt);
}
string HDF5Alignment::getRootName() const
{
if (_tree == NULL)
{
throw hal_exception("Can't get root name of empty tree");
}
return stTree_getLabel(_tree);
}
string HDF5Alignment::getParentName(const string& name) const
{
map<string, stTree*>::iterator findIt = _nodeMap.find(name);
if (findIt == _nodeMap.end())
{
throw hal_exception(string("node not found: ") + name);
}
stTree* node = findIt->second;
stTree* parent = stTree_getParent(node);
if (parent == NULL)
{
return "";
}
return stTree_getLabel(parent);
}
double HDF5Alignment::getBranchLength(const string& parentName,
const string& childName) const
{
map<string, stTree*>::iterator findIt = _nodeMap.find(childName);
if (findIt == _nodeMap.end())
{
throw hal_exception(string("node ") + childName + " not found");
}
stTree* node = findIt->second;
stTree* parent = stTree_getParent(node);
if (parent == NULL || parentName != stTree_getLabel(parent))
{
throw hal_exception(string("edge ") + parentName + "--" + childName +
" not found");
}
return stTree_getBranchLength(node);
}
vector<string> HDF5Alignment::getChildNames(const string& name) const
{
map<string, stTree*>::iterator findIt = _nodeMap.find(name);
if (findIt == _nodeMap.end())
{
throw hal_exception(string("node ") + name + " not found");
}
stTree* node = findIt->second;
int32_t numChildren = stTree_getChildNumber(node);
vector<string> childNames(numChildren);
for (int32_t i = 0; i < numChildren; ++i)
{
childNames[i] = stTree_getLabel(stTree_getChild(node, i));
}
return childNames;
}
vector<string> HDF5Alignment::getLeafNamesBelow(const string& name) const
{
vector<string> leaves;
vector<string> children;
deque<string> bfQueue;
bfQueue.push_front(name);
while (bfQueue.empty() == false)
{
string& current = bfQueue.back();
children = getChildNames(current);
if (children.empty() == true && current != name)
{
leaves.push_back(current);
}
for (size_t i = 0; i < children.size(); ++i)
{
bfQueue.push_front(children[i]);
}
bfQueue.pop_back();
}
return leaves;
}
hal_size_t HDF5Alignment::getNumGenomes() const
{
if (_tree == NULL)
{
assert(_nodeMap.empty() == true);
return 0;
}
else
{
return _nodeMap.size();
}
}
MetaData* HDF5Alignment::getMetaData()
{
return _metaData;
}
const MetaData* HDF5Alignment::getMetaData() const
{
return _metaData;
}
string HDF5Alignment::getNewickTree() const
{
if (_tree == NULL)
{
return "";
}
else
{
char* treeString = stTree_getNewickTreeString(_tree);
string returnString(treeString);
free(treeString);
return returnString;
}
}
void HDF5Alignment::writeTree()
{
if (_dirty == false)
return;
char* treeString = NULL;
if (_tree != NULL)
{
treeString = stTree_getNewickTreeString(_tree);
}
else
{
treeString = (char*)malloc(sizeof(char));
treeString[0] = '\0';
}
assert (_file != NULL);
HDF5MetaData treeMeta(_file, TreeGroupName);
treeMeta.set(TreeGroupName, treeString);
free(treeString);
}
static void addNodeToMap(stTree* node, map<string, stTree*>& nodeMap)
{
const char* label = stTree_getLabel(node);
assert(label != NULL);
string name(label);
assert(nodeMap.find(name) == nodeMap.end());
nodeMap.insert(pair<string, stTree*>(name, node));
int32_t numChildren = stTree_getChildNumber(node);
for (int32_t i = 0; i < numChildren; ++i)
{
addNodeToMap(stTree_getChild(node, i), nodeMap);
}
}
void HDF5Alignment::loadTree()
{
_nodeMap.clear();
HDF5MetaData treeMeta(_file, TreeGroupName);
map<string, string> metaMap = treeMeta.getMap();
assert(metaMap.size() == 1);
assert(metaMap.find(TreeGroupName) != metaMap.end());
const string& treeString = metaMap[TreeGroupName];
if (_tree != NULL)
{
stTree_destruct(_tree);
}
if (treeString.empty() == true)
{
_tree = stTree_construct();
}
else
{
_tree = stTree_parseNewickString(const_cast<char*>(treeString.c_str()));
addNodeToMap(_tree, _nodeMap);
}
}
|
/*
* Copyright (C) 2012 by Glenn Hickey ([email protected])
*
* Released under the MIT license, see LICENSE.txt
*/
#include <cassert>
#include <iostream>
#include <cstdlib>
#include <deque>
#include "hdf5Alignment.h"
#include "hdf5MetaData.h"
#include "hdf5Genome.h"
extern "C" {
#include "sonLibTree.h"
}
using namespace hal;
using namespace std;
using namespace H5;
/** default group name for MetaData attributes, will be a subgroup
* of the top level of the file, ie /Meta */
const H5std_string HDF5Alignment::MetaGroupName = "Meta";
const H5std_string HDF5Alignment::TreeGroupName = "Phylogeny";
const H5std_string HDF5Alignment::GenomesGroupName = "Genomes";
HDF5Alignment::HDF5Alignment() :
_file(NULL),
_cprops(FileCreatPropList::DEFAULT),
_aprops(FileAccPropList::DEFAULT),
_dcprops(DSetCreatPropList::DEFAULT),
_flags(H5F_ACC_RDONLY),
_metaData(NULL),
_tree(NULL),
_dirty(false)
{
// Todo: verify chunk size
_dcprops = DSetCreatPropList();
_dcprops.setDeflate(2);
hsize_t chunkSize = 2000000;
_dcprops.setChunk(1, &chunkSize);
_aprops.setCache(11, 51, 100000000, 0.25);
}
HDF5Alignment::HDF5Alignment(const H5::FileCreatPropList& fileCreateProps,
const H5::FileAccPropList& fileAccessProps,
const H5::DSetCreatPropList& datasetCreateProps) :
_file(NULL),
_cprops(fileCreateProps),
_aprops(fileAccessProps),
_dcprops(datasetCreateProps),
_flags(H5F_ACC_RDONLY),
_metaData(NULL),
_tree(NULL),
_dirty(false)
{
}
HDF5Alignment::~HDF5Alignment()
{
close();
}
void HDF5Alignment::createNew(const string& alignmentPath)
{
close();
_flags = H5F_ACC_TRUNC;
_file = new H5File(alignmentPath.c_str(), _flags, _cprops, _aprops);
_file->createGroup(MetaGroupName);
_file->createGroup(TreeGroupName);
_file->createGroup(GenomesGroupName);
delete _metaData;
_metaData = new HDF5MetaData(_file, MetaGroupName);
_tree = NULL;
_dirty = true;
}
// todo: properly handle readonly
void HDF5Alignment::open(const string& alignmentPath, bool readOnly)
{
close();
delete _file;
int _flags = readOnly ? H5F_ACC_RDONLY : H5F_ACC_RDWR;
_file = new H5File(alignmentPath.c_str(), _flags, _cprops, _aprops);
delete _metaData;
_metaData = new HDF5MetaData(_file, MetaGroupName);
loadTree();
}
// todo: properly handle readonly
void HDF5Alignment::open(const string& alignmentPath) const
{
const_cast<HDF5Alignment*>(this)->open(alignmentPath, true);
}
void HDF5Alignment::close()
{
if (_file != NULL)
{
writeTree();
if (_tree != NULL)
{
stTree_destruct(_tree);
_tree = NULL;
}
// todo: make sure there's no memory leak with metadata
// smart pointer should prevent
if (_metaData != NULL)
{
_metaData->write();
delete _metaData;
_metaData = NULL;
}
map<string, HDF5Genome*>::iterator mapIt;
for (mapIt = _openGenomes.begin(); mapIt != _openGenomes.end(); ++mapIt)
{
HDF5Genome* genome = mapIt->second;
genome->write();
delete genome;
}
_openGenomes.clear();
_file->flush(H5F_SCOPE_LOCAL);
_file->close();
delete _file;
_file = NULL;
}
else
{
assert(_tree == NULL);
assert(_openGenomes.empty() == true);
}
}
Genome* HDF5Alignment::addLeafGenome(const string& name,
const string& parentName,
double branchLength)
{
if (name.empty() == true || parentName.empty())
{
throw hal_exception("name can't be empty");
}
map<string, stTree*>::iterator findIt = _nodeMap.find(name);
if (findIt != _nodeMap.end())
{
throw hal_exception(string("node ") + name + " already exists");
}
findIt = _nodeMap.find(parentName);
if (findIt == _nodeMap.end())
{
throw hal_exception(string("parent ") + parentName + " not found in tree");
}
stTree* parent = findIt->second;
stTree* node = stTree_construct();
stTree_setLabel(node, name.c_str());
stTree_setParent(node, parent);
stTree_setBranchLength(node, branchLength);
_nodeMap.insert(pair<string, stTree*>(name, node));
HDF5Genome* genome = new HDF5Genome(name, this, _file, _dcprops);
_openGenomes.insert(pair<string, HDF5Genome*>(name, genome));
_dirty = true;
return genome;
}
Genome* HDF5Alignment::addRootGenome(const string& name,
double branchLength)
{
if (name.empty() == true)
{
throw hal_exception("name can't be empty");
}
map<string, stTree*>::iterator findIt = _nodeMap.find(name);
if (findIt != _nodeMap.end())
{
throw hal_exception(string("node ") + name + " already exists");
}
stTree* node = stTree_construct();
stTree_setLabel(node, name.c_str());
if (_tree != NULL)
{
stTree_setParent(_tree, node);
stTree_setBranchLength(_tree, branchLength);
}
_tree = node;
_nodeMap.insert(pair<string, stTree*>(name, node));
HDF5Genome* genome = new HDF5Genome(name, this, _file, _dcprops);
_openGenomes.insert(pair<string, HDF5Genome*>(name, genome));
_dirty = true;
return genome;
}
void HDF5Alignment::removeGenome(const string& name)
{
}
const Genome* HDF5Alignment::openGenome(const string& name) const
{
map<string, HDF5Genome*>::iterator mapit = _openGenomes.find(name);
if (mapit != _openGenomes.end())
{
return mapit->second;
}
HDF5Genome* genome = NULL;
if (_nodeMap.find(name) != _nodeMap.end())
{
genome = new HDF5Genome(name, const_cast<HDF5Alignment*>(this),
_file, _dcprops);
genome->read();
_openGenomes.insert(pair<string, HDF5Genome*>(name, genome));
}
return genome;
}
Genome* HDF5Alignment::openGenome(const string& name)
{
map<string, HDF5Genome*>::iterator mapit = _openGenomes.find(name);
if (mapit != _openGenomes.end())
{
return mapit->second;
}
HDF5Genome* genome = NULL;
if (_nodeMap.find(name) != _nodeMap.end())
{
genome = new HDF5Genome(name, this, _file, _dcprops);
genome->read();
_openGenomes.insert(pair<string, HDF5Genome*>(name, genome));
}
return genome;
}
void HDF5Alignment::closeGenome(const Genome* genome) const
{
string name = genome->getName();
map<string, HDF5Genome*>::iterator mapIt = _openGenomes.find(name);
if (mapIt == _openGenomes.end())
{
throw hal_exception("Attempt to close non-open genome. "
"Should not even be possible");
}
mapIt->second->write();
delete mapIt->second;
_openGenomes.erase(mapIt);
}
string HDF5Alignment::getRootName() const
{
if (_tree == NULL)
{
throw hal_exception("Can't get root name of empty tree");
}
return stTree_getLabel(_tree);
}
string HDF5Alignment::getParentName(const string& name) const
{
map<string, stTree*>::iterator findIt = _nodeMap.find(name);
if (findIt == _nodeMap.end())
{
throw hal_exception(string("node not found: ") + name);
}
stTree* node = findIt->second;
stTree* parent = stTree_getParent(node);
if (parent == NULL)
{
return "";
}
return stTree_getLabel(parent);
}
double HDF5Alignment::getBranchLength(const string& parentName,
const string& childName) const
{
map<string, stTree*>::iterator findIt = _nodeMap.find(childName);
if (findIt == _nodeMap.end())
{
throw hal_exception(string("node ") + childName + " not found");
}
stTree* node = findIt->second;
stTree* parent = stTree_getParent(node);
if (parent == NULL || parentName != stTree_getLabel(parent))
{
throw hal_exception(string("edge ") + parentName + "--" + childName +
" not found");
}
return stTree_getBranchLength(node);
}
vector<string> HDF5Alignment::getChildNames(const string& name) const
{
map<string, stTree*>::iterator findIt = _nodeMap.find(name);
if (findIt == _nodeMap.end())
{
throw hal_exception(string("node ") + name + " not found");
}
stTree* node = findIt->second;
int32_t numChildren = stTree_getChildNumber(node);
vector<string> childNames(numChildren);
for (int32_t i = 0; i < numChildren; ++i)
{
childNames[i] = stTree_getLabel(stTree_getChild(node, i));
}
return childNames;
}
vector<string> HDF5Alignment::getLeafNamesBelow(const string& name) const
{
vector<string> leaves;
vector<string> children;
deque<string> bfQueue;
bfQueue.push_front(name);
while (bfQueue.empty() == false)
{
string& current = bfQueue.back();
children = getChildNames(current);
if (children.empty() == true && current != name)
{
leaves.push_back(current);
}
for (size_t i = 0; i < children.size(); ++i)
{
bfQueue.push_front(children[i]);
}
bfQueue.pop_back();
}
return leaves;
}
hal_size_t HDF5Alignment::getNumGenomes() const
{
if (_tree == NULL)
{
assert(_nodeMap.empty() == true);
return 0;
}
else
{
return _nodeMap.size();
}
}
MetaData* HDF5Alignment::getMetaData()
{
return _metaData;
}
const MetaData* HDF5Alignment::getMetaData() const
{
return _metaData;
}
string HDF5Alignment::getNewickTree() const
{
if (_tree == NULL)
{
return "";
}
else
{
char* treeString = stTree_getNewickTreeString(_tree);
string returnString(treeString);
free(treeString);
return returnString;
}
}
void HDF5Alignment::writeTree()
{
if (_dirty == false)
return;
char* treeString = NULL;
if (_tree != NULL)
{
treeString = stTree_getNewickTreeString(_tree);
}
else
{
treeString = (char*)malloc(sizeof(char));
treeString[0] = '\0';
}
assert (_file != NULL);
HDF5MetaData treeMeta(_file, TreeGroupName);
treeMeta.set(TreeGroupName, treeString);
free(treeString);
}
static void addNodeToMap(stTree* node, map<string, stTree*>& nodeMap)
{
const char* label = stTree_getLabel(node);
assert(label != NULL);
string name(label);
assert(nodeMap.find(name) == nodeMap.end());
nodeMap.insert(pair<string, stTree*>(name, node));
int32_t numChildren = stTree_getChildNumber(node);
for (int32_t i = 0; i < numChildren; ++i)
{
addNodeToMap(stTree_getChild(node, i), nodeMap);
}
}
void HDF5Alignment::loadTree()
{
_nodeMap.clear();
HDF5MetaData treeMeta(_file, TreeGroupName);
map<string, string> metaMap = treeMeta.getMap();
assert(metaMap.size() == 1);
assert(metaMap.find(TreeGroupName) != metaMap.end());
const string& treeString = metaMap[TreeGroupName];
if (_tree != NULL)
{
stTree_destruct(_tree);
}
if (treeString.empty() == true)
{
_tree = stTree_construct();
}
else
{
_tree = stTree_parseNewickString(const_cast<char*>(treeString.c_str()));
addNodeToMap(_tree, _nodeMap);
}
}
|
change default deflate from 9 to 2, since it seems 9 really sucks.
|
change default deflate from 9 to 2, since it seems 9 really sucks.
|
C++
|
mit
|
glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal,glennhickey/hal
|
4c3f3a197cc0b244bf8761f394a3db1c4d36d833
|
Tests/OgreMain/src/StringTests.cpp
|
Tests/OgreMain/src/StringTests.cpp
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "StringTests.h"
#include "OgreStringConverter.h"
#include "OgreVector3.h"
#include "OgreQuaternion.h"
#include "OgreMatrix4.h"
#include "OgreColourValue.h"
using namespace Ogre;
// Register the test suite
//--------------------------------------------------------------------------
void StringTests::SetUp()
{
testFileNoPath = "testfile.txt";
testFileRelativePathUnix = "this/is/relative/testfile.txt";
testFileRelativePathWindows = "this\\is\\relative\\testfile.txt";
testFileAbsolutePathUnix = "/this/is/absolute/testfile.txt";
testFileAbsolutePathWindows = "c:\\this\\is\\absolute\\testfile.txt";
}
//--------------------------------------------------------------------------
void StringTests::TearDown()
{
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameNoPath)
{
String basename, path;
StringUtil::splitFilename(testFileNoPath, basename, path);
EXPECT_EQ(testFileNoPath, basename);
EXPECT_TRUE(path.empty());
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameRelativePath)
{
String basename, path;
// Unix
StringUtil::splitFilename(testFileRelativePathUnix, basename, path);
EXPECT_EQ(String("testfile.txt"), basename);
EXPECT_EQ(String("this/is/relative/"), path);
// Windows
StringUtil::splitFilename(testFileRelativePathWindows, basename, path);
EXPECT_EQ(String("testfile.txt"), basename);
EXPECT_EQ(String("this/is/relative/"), path);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameAbsolutePath)
{
String basename, path;
// Unix
StringUtil::splitFilename(testFileAbsolutePathUnix, basename, path);
EXPECT_EQ(String("testfile.txt"), basename);
EXPECT_EQ(String("/this/is/absolute/"), path);
// Windows
StringUtil::splitFilename(testFileAbsolutePathWindows, basename, path);
EXPECT_EQ(String("testfile.txt"), basename);
EXPECT_EQ(String("c:/this/is/absolute/"), path);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchCaseSensitive)
{
// Test positive
EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, true));
// Test negative
String upperCase = testFileNoPath;
StringUtil::toUpperCase(upperCase);
EXPECT_TRUE(!StringUtil::match(testFileNoPath, upperCase, true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchCaseInSensitive)
{
// Test positive
EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, false));
// Test positive
String upperCase = testFileNoPath;
StringUtil::toUpperCase(upperCase);
EXPECT_TRUE(StringUtil::match(testFileNoPath, upperCase, false));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobAll)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobStart)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.txt", true));
EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.txt", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobEnd)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "testfile.*", true));
EXPECT_TRUE(!StringUtil::match(testFileNoPath, "testfile.d*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobStartAndEnd)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.*", true));
EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.d*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobMiddle)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "test*.txt", true));
EXPECT_TRUE(!StringUtil::match(testFileNoPath, "last*.txt*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchSuperGlobtastic)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "*e*tf*e.t*t", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseReal)
{
Real r = 23.454;
String s = StringConverter::toString(r);
Real t = StringConverter::parseReal(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseInt)
{
int r = 223546;
String s = StringConverter::toString(r);
int t = StringConverter::parseInt(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseLong)
{
long r = -2147483647;
String s = StringConverter::toString(r);
long t = StringConverter::parseLong(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseUnsignedLong)
{
unsigned long r = 4294967295UL;
String s = StringConverter::toString(r);
unsigned long t = StringConverter::parseUnsignedLong(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseVector3)
{
Vector3 r(0.12, 3.22, -4.04);
String s = StringConverter::toString(r);
Vector3 t = StringConverter::parseVector3(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseMatrix4)
{
Matrix4 r(1.12, 0, 0, 34, 0, 0.87, 0, 20, 0, 0, 0.56, 10, 0, 0, 0, 1);
String s = StringConverter::toString(r);
Matrix4 t = StringConverter::parseMatrix4(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseQuaternion)
{
Quaternion r(1.12, 0.87, 0.67, 1);
String s = StringConverter::toString(r);
Quaternion t = StringConverter::parseQuaternion(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseBool)
{
bool r = true;
String s = StringConverter::toString(r);
bool t = StringConverter::parseBool(s);
EXPECT_EQ(r, t);
r = false;
s = StringConverter::toString(r);
t = StringConverter::parseBool(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseColourValue)
{
ColourValue r(0.34, 0.44, 0.77, 1.0);
String s = StringConverter::toString(r);
ColourValue t = StringConverter::parseColourValue(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,EndsWith)
{
String s = "Hello World!";
EXPECT_TRUE(StringUtil::endsWith(s, "world!"));
EXPECT_FALSE(StringUtil::endsWith(s, "hello"));
EXPECT_FALSE(StringUtil::endsWith(s, "world!", false));
EXPECT_FALSE(StringUtil::endsWith(s, "", false));
}
TEST_F(StringTests,StartsWith)
{
String s = "Hello World!";
EXPECT_TRUE(StringUtil::startsWith(s, "hello"));
EXPECT_FALSE(StringUtil::startsWith(s, "world"));
EXPECT_FALSE(StringUtil::startsWith(s, "hello", false));
EXPECT_FALSE(StringUtil::startsWith(s, "", false));
}
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "StringTests.h"
#include "OgreStringConverter.h"
#include "OgreVector3.h"
#include "OgreQuaternion.h"
#include "OgreMatrix4.h"
#include "OgreColourValue.h"
using namespace Ogre;
// Register the test suite
//--------------------------------------------------------------------------
void StringTests::SetUp()
{
testFileNoPath = "testfile.txt";
testFileRelativePathUnix = "this/is/relative/testfile.txt";
testFileRelativePathWindows = "this\\is\\relative\\testfile.txt";
testFileAbsolutePathUnix = "/this/is/absolute/testfile.txt";
testFileAbsolutePathWindows = "c:\\this\\is\\absolute\\testfile.txt";
setlocale(LC_NUMERIC, "");
}
//--------------------------------------------------------------------------
void StringTests::TearDown()
{
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameNoPath)
{
String basename, path;
StringUtil::splitFilename(testFileNoPath, basename, path);
EXPECT_EQ(testFileNoPath, basename);
EXPECT_TRUE(path.empty());
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameRelativePath)
{
String basename, path;
// Unix
StringUtil::splitFilename(testFileRelativePathUnix, basename, path);
EXPECT_EQ(String("testfile.txt"), basename);
EXPECT_EQ(String("this/is/relative/"), path);
// Windows
StringUtil::splitFilename(testFileRelativePathWindows, basename, path);
EXPECT_EQ(String("testfile.txt"), basename);
EXPECT_EQ(String("this/is/relative/"), path);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,SplitFileNameAbsolutePath)
{
String basename, path;
// Unix
StringUtil::splitFilename(testFileAbsolutePathUnix, basename, path);
EXPECT_EQ(String("testfile.txt"), basename);
EXPECT_EQ(String("/this/is/absolute/"), path);
// Windows
StringUtil::splitFilename(testFileAbsolutePathWindows, basename, path);
EXPECT_EQ(String("testfile.txt"), basename);
EXPECT_EQ(String("c:/this/is/absolute/"), path);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchCaseSensitive)
{
// Test positive
EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, true));
// Test negative
String upperCase = testFileNoPath;
StringUtil::toUpperCase(upperCase);
EXPECT_TRUE(!StringUtil::match(testFileNoPath, upperCase, true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchCaseInSensitive)
{
// Test positive
EXPECT_TRUE(StringUtil::match(testFileNoPath, testFileNoPath, false));
// Test positive
String upperCase = testFileNoPath;
StringUtil::toUpperCase(upperCase);
EXPECT_TRUE(StringUtil::match(testFileNoPath, upperCase, false));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobAll)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobStart)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.txt", true));
EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.txt", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobEnd)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "testfile.*", true));
EXPECT_TRUE(!StringUtil::match(testFileNoPath, "testfile.d*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobStartAndEnd)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "*stfile.*", true));
EXPECT_TRUE(!StringUtil::match(testFileNoPath, "*astfile.d*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchGlobMiddle)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "test*.txt", true));
EXPECT_TRUE(!StringUtil::match(testFileNoPath, "last*.txt*", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,MatchSuperGlobtastic)
{
EXPECT_TRUE(StringUtil::match(testFileNoPath, "*e*tf*e.t*t", true));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseReal)
{
Real r = 23.454;
String s = StringConverter::toString(r);
EXPECT_EQ(r, StringConverter::parseReal(s));
EXPECT_EQ(r, StringConverter::parseReal("23.454"));
EXPECT_NE(r, StringConverter::parseReal("23,454"));
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseInt)
{
int r = 223546;
String s = StringConverter::toString(r);
int t = StringConverter::parseInt(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseLong)
{
long r = -2147483647;
String s = StringConverter::toString(r);
long t = StringConverter::parseLong(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseUnsignedLong)
{
unsigned long r = 4294967295UL;
String s = StringConverter::toString(r);
unsigned long t = StringConverter::parseUnsignedLong(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseVector3)
{
Vector3 r(0.12, 3.22, -4.04);
String s = StringConverter::toString(r);
Vector3 t = StringConverter::parseVector3(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseMatrix4)
{
Matrix4 r(1.12, 0, 0, 34, 0, 0.87, 0, 20, 0, 0, 0.56, 10, 0, 0, 0, 1);
String s = StringConverter::toString(r);
Matrix4 t = StringConverter::parseMatrix4(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseQuaternion)
{
Quaternion r(1.12, 0.87, 0.67, 1);
String s = StringConverter::toString(r);
Quaternion t = StringConverter::parseQuaternion(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseBool)
{
bool r = true;
String s = StringConverter::toString(r);
bool t = StringConverter::parseBool(s);
EXPECT_EQ(r, t);
r = false;
s = StringConverter::toString(r);
t = StringConverter::parseBool(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,ParseColourValue)
{
ColourValue r(0.34, 0.44, 0.77, 1.0);
String s = StringConverter::toString(r);
ColourValue t = StringConverter::parseColourValue(s);
EXPECT_EQ(r, t);
}
//--------------------------------------------------------------------------
TEST_F(StringTests,EndsWith)
{
String s = "Hello World!";
EXPECT_TRUE(StringUtil::endsWith(s, "world!"));
EXPECT_FALSE(StringUtil::endsWith(s, "hello"));
EXPECT_FALSE(StringUtil::endsWith(s, "world!", false));
EXPECT_FALSE(StringUtil::endsWith(s, "", false));
}
TEST_F(StringTests,StartsWith)
{
String s = "Hello World!";
EXPECT_TRUE(StringUtil::startsWith(s, "hello"));
EXPECT_FALSE(StringUtil::startsWith(s, "world"));
EXPECT_FALSE(StringUtil::startsWith(s, "hello", false));
EXPECT_FALSE(StringUtil::startsWith(s, "", false));
}
|
verify that we are independent of LC_NUMERIC
|
StringTests: verify that we are independent of LC_NUMERIC
|
C++
|
mit
|
paroj/ogre,paroj/ogre,paroj/ogre,OGRECave/ogre,OGRECave/ogre,paroj/ogre,OGRECave/ogre,paroj/ogre,OGRECave/ogre,OGRECave/ogre
|
cdcb56b5c50a4ac7cb4cd06b62dfc4b0d5ab83ec
|
allocore/src/io/al_ControlNav.cpp
|
allocore/src/io/al_ControlNav.cpp
|
#include "allocore/io/al_ControlNav.hpp"
namespace al {
NavInputControl::NavInputControl(const NavInputControl& v)
: mNav(v.mNav), mVScale(v.vscale()), mTScale(v.tscale()), mUseMouse(true)
{}
NavInputControl::NavInputControl(Nav& nav, double vscale, double tscale)
: mNav(&nav), mVScale(vscale), mTScale(tscale), mUseMouse(true)
{}
bool NavInputControl::onKeyDown(const Keyboard& k){
if(k.ctrl()) return true;
double a = mTScale * M_DEG2RAD; // rotational speed: rad/sec
double v = mVScale; // speed: world units/sec
if(k.alt()) v *= 10;
if(k.shift()) v *= 0.1;
switch(k.key()){
case '`': nav().halt().home(); return false;
case 's': nav().halt(); return false;
case Keyboard::UP: nav().spinR( a); return false;
case Keyboard::DOWN: nav().spinR(-a); return false;
case Keyboard::RIGHT: nav().spinU(-a); return false;
case Keyboard::LEFT: nav().spinU( a); return false;
case 'q': case 'Q': nav().spinF( a); return false;
case 'z': case 'Z': nav().spinF(-a); return false;
case 'a': case 'A': nav().moveR(-v); return false;
case 'd': case 'D': nav().moveR( v); return false;
case 'e': case 'E': nav().moveU( v); return false;
case 'c': case 'C': nav().moveU(-v); return false;
case 'x': case 'X': nav().moveF(-v); return false;
case 'w': case 'W': nav().moveF( v); return false;
default:;
}
return true;
}
bool NavInputControl::onKeyUp(const Keyboard& k) {
switch(k.key()){
case Keyboard::UP:
case Keyboard::DOWN: nav().spinR(0); return false;
case Keyboard::RIGHT:
case Keyboard::LEFT: nav().spinU(0); return false;
case 'q': case 'Q':
case 'z': case 'Z': nav().spinF(0); return false;
case 'a': case 'A':
case 'd': case 'D': nav().moveR(0); return false;
case 'e': case 'E':
case 'c': case 'C': nav().moveU(0); return false;
case 'x': case 'X':
case 'w': case 'W': nav().moveF(0); return false;
default:;
}
return true;
}
bool NavInputControl::onMouseDrag(const Mouse& m){
if(mUseMouse){
if(m.left()){
nav().turnU(-m.dx() * 0.2 * M_DEG2RAD);
nav().turnR(-m.dy() * 0.2 * M_DEG2RAD);
return false;
}
else if(m.right()){
nav().turnF( m.dx() * 0.2 * M_DEG2RAD);
nav().pullBack(nav().pullBack() + m.dy()*0.02);
return false;
}
}
return true;
}
NavInputControlCosm::NavInputControlCosm(Nav& nav, double vscale, double tscale)
: NavInputControl(nav, vscale, tscale)
{}
bool NavInputControlCosm::onKeyDown(const Keyboard& k){
double a = mTScale * M_DEG2RAD; // rotational speed: rad/sec
double v = mVScale; // speed: world units/sec
if(k.ctrl()) v *= 0.1;
if(k.alt()) v *= 10;
if(k.ctrl()) a *= 0.1;
if(k.alt()) a *= 10;
switch(k.key()){
case '`': nav().halt().home(); return false;
case 'w': nav().spinR( a); return false;
case 'x': nav().spinR(-a); return false;
case Keyboard::RIGHT: nav().spinU( -a); return false;
case Keyboard::LEFT: nav().spinU( a); return false;
case 'a': nav().spinF( a); return false;
case 'd': nav().spinF(-a); return false;
case ',': nav().moveR(-v); return false;
case '.': nav().moveR( v); return false;
case '\'': nav().moveU( v); return false;
case '/': nav().moveU(-v); return false;
case Keyboard::UP: nav().moveF( v); return false;
case Keyboard::DOWN: nav().moveF(-v); return false;
default:;
}
return true;
}
bool NavInputControlCosm::onKeyUp(const Keyboard& k) {
switch (k.key()) {
case 'w':
case 'x': nav().spinR(0); return false;
case Keyboard::RIGHT:
case Keyboard::LEFT: nav().spinU(0); return false;
case 'a':
case 'd': nav().spinF(0); return false;
case ',':
case '.': nav().moveR(0); return false;
case '\'':
case '/': nav().moveU(0); return false;
case Keyboard::UP:
case Keyboard::DOWN: nav().moveF(0); return false;
default:;
}
return true;
}
bool NavInputControlCosm::onMouseDrag(const Mouse& m){
return true;
}
} // al::
|
#include "allocore/io/al_ControlNav.hpp"
namespace al {
NavInputControl::NavInputControl(const NavInputControl& v)
: mNav(v.mNav), mVScale(v.vscale()), mTScale(v.tscale()), mUseMouse(true)
{}
NavInputControl::NavInputControl(Nav& nav, double vscale, double tscale)
: mNav(&nav), mVScale(vscale), mTScale(tscale), mUseMouse(true)
{}
bool NavInputControl::onKeyDown(const Keyboard& k){
if(k.ctrl()) return true;
double a = mTScale * M_DEG2RAD; // rotational speed: rad/sec
double v = mVScale; // speed: world units/sec
if(k.alt()){
switch(k.key()){
case Keyboard::UP: nav().pullBack(nav().pullBack()*0.8); return false;
case Keyboard::DOWN:nav().pullBack(nav().pullBack()/0.8); return false;
}
}
if(k.alt()) v *= 10;
if(k.shift()) v *= 0.1;
switch(k.key()){
case '`': nav().halt().home(); return false;
case 's': nav().halt(); return false;
case Keyboard::UP: nav().spinR( a); return false;
case Keyboard::DOWN: nav().spinR(-a); return false;
case Keyboard::RIGHT: nav().spinU(-a); return false;
case Keyboard::LEFT: nav().spinU( a); return false;
case 'q': case 'Q': nav().spinF( a); return false;
case 'z': case 'Z': nav().spinF(-a); return false;
case 'a': case 'A': nav().moveR(-v); return false;
case 'd': case 'D': nav().moveR( v); return false;
case 'e': case 'E': nav().moveU( v); return false;
case 'c': case 'C': nav().moveU(-v); return false;
case 'x': case 'X': nav().moveF(-v); return false;
case 'w': case 'W': nav().moveF( v); return false;
default:;
}
return true;
}
bool NavInputControl::onKeyUp(const Keyboard& k) {
switch(k.key()){
case Keyboard::UP:
case Keyboard::DOWN: nav().spinR(0); return false;
case Keyboard::RIGHT:
case Keyboard::LEFT: nav().spinU(0); return false;
case 'q': case 'Q':
case 'z': case 'Z': nav().spinF(0); return false;
case 'a': case 'A':
case 'd': case 'D': nav().moveR(0); return false;
case 'e': case 'E':
case 'c': case 'C': nav().moveU(0); return false;
case 'x': case 'X':
case 'w': case 'W': nav().moveF(0); return false;
default:;
}
return true;
}
bool NavInputControl::onMouseDrag(const Mouse& m){
if(mUseMouse){
if(m.left()){
nav().turnU(-m.dx() * 0.2 * M_DEG2RAD);
nav().turnR(-m.dy() * 0.2 * M_DEG2RAD);
return false;
}
else if(m.right()){
nav().turnF( m.dx() * 0.2 * M_DEG2RAD);
nav().pullBack(nav().pullBack() + m.dy()*0.02);
return false;
}
}
return true;
}
NavInputControlCosm::NavInputControlCosm(Nav& nav, double vscale, double tscale)
: NavInputControl(nav, vscale, tscale)
{}
bool NavInputControlCosm::onKeyDown(const Keyboard& k){
double a = mTScale * M_DEG2RAD; // rotational speed: rad/sec
double v = mVScale; // speed: world units/sec
if(k.ctrl()) v *= 0.1;
if(k.alt()) v *= 10;
if(k.ctrl()) a *= 0.1;
if(k.alt()) a *= 10;
switch(k.key()){
case '`': nav().halt().home(); return false;
case 'w': nav().spinR( a); return false;
case 'x': nav().spinR(-a); return false;
case Keyboard::RIGHT: nav().spinU( -a); return false;
case Keyboard::LEFT: nav().spinU( a); return false;
case 'a': nav().spinF( a); return false;
case 'd': nav().spinF(-a); return false;
case ',': nav().moveR(-v); return false;
case '.': nav().moveR( v); return false;
case '\'': nav().moveU( v); return false;
case '/': nav().moveU(-v); return false;
case Keyboard::UP: nav().moveF( v); return false;
case Keyboard::DOWN: nav().moveF(-v); return false;
default:;
}
return true;
}
bool NavInputControlCosm::onKeyUp(const Keyboard& k) {
switch (k.key()) {
case 'w':
case 'x': nav().spinR(0); return false;
case Keyboard::RIGHT:
case Keyboard::LEFT: nav().spinU(0); return false;
case 'a':
case 'd': nav().spinF(0); return false;
case ',':
case '.': nav().moveR(0); return false;
case '\'':
case '/': nav().moveU(0); return false;
case Keyboard::UP:
case Keyboard::DOWN: nav().moveF(0); return false;
default:;
}
return true;
}
bool NavInputControlCosm::onMouseDrag(const Mouse& m){
return true;
}
} // al::
|
Add key controls for camera pullback
|
Add key controls for camera pullback
|
C++
|
bsd-3-clause
|
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
|
7d15fdfd3137207347ad58de8938ee5daf33eee7
|
ksp_plugin/planetarium.cpp
|
ksp_plugin/planetarium.cpp
|
#include "ksp_plugin/planetarium.hpp"
#include <vector>
#include "geometry/point.hpp"
#include "quantities/elementary_functions.hpp"
namespace principia {
namespace ksp_plugin {
namespace internal_planetarium {
using geometry::Position;
using geometry::RP2Line;
using quantities::Pow;
using quantities::Sin;
using quantities::Sqrt;
using quantities::Tan;
using quantities::Speed;
using quantities::Square;
using quantities::Time;
Planetarium::Parameters::Parameters(double const sphere_radius_multiplier,
Angle const& angular_resolution,
Angle const& field_of_view)
: sphere_radius_multiplier_(sphere_radius_multiplier),
sin²_angular_resolution_(Pow<2>(Sin(angular_resolution))),
tan_angular_resolution_(Tan(angular_resolution)),
tan_field_of_view_(Tan(field_of_view)) {}
Planetarium::Planetarium(
Parameters const& parameters,
Perspective<Navigation, Camera, Length, OrthogonalMap> const& perspective,
not_null<Ephemeris<Barycentric> const*> const ephemeris,
not_null<NavigationFrame const*> const plotting_frame)
: parameters_(parameters),
perspective_(perspective),
ephemeris_(ephemeris),
plotting_frame_(plotting_frame) {}
RP2Lines<Length, Camera> Planetarium::PlotMethod0(
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end,
Instant const& now) const {
auto const plottable_spheres = ComputePlottableSpheres(now);
auto const plottable_segments = ComputePlottableSegments(plottable_spheres,
begin, end);
auto const field_of_view_radius² =
perspective_.focal() * perspective_.focal() *
parameters_.tan_field_of_view_ * parameters_.tan_field_of_view_;
std::experimental::optional<Position<Navigation>> previous_position;
RP2Lines<Length, Camera> rp2_lines;
for (auto const& plottable_segment : plottable_segments) {
// Apply the projection to the current plottable segment.
auto const rp2_first = perspective_(plottable_segment.first);
auto const rp2_second = perspective_(plottable_segment.second);
// If the segment is entirely outside the field of view, ignore it.
Length const x1 = rp2_first.x();
Length const y1 = rp2_first.y();
Length const x2 = rp2_second.x();
Length const y2 = rp2_second.y();
if (x1 * x1 + y1 * y1 > field_of_view_radius² &&
x2 * x2 + y2 * y2 > field_of_view_radius²) {
continue;
}
// Create a new ℝP² line when two segments are not consecutive. Don't
// compare ℝP² points for equality, that's expensive.
bool const are_consecutive =
previous_position == plottable_segment.first;
previous_position = plottable_segment.second;
if (are_consecutive) {
rp2_lines.back().push_back(rp2_second);
} else {
RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second};
rp2_lines.push_back(rp2_line);
}
}
return rp2_lines;
}
RP2Lines<Length, Camera> Planetarium::PlotMethod1(
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end,
Instant const& now) const {
Length const focal_plane_tolerance =
perspective_.focal() * parameters_.tan_angular_resolution_;
auto const focal_plane_tolerance² =
focal_plane_tolerance * focal_plane_tolerance;
auto const rp2_lines = PlotMethod0(begin, end, now);
int skipped = 0;
int total = 0;
RP2Lines<Length, Camera> new_rp2_lines;
for (auto const& rp2_line : rp2_lines) {
RP2Line<Length, Camera> new_rp2_line;
std::experimental::optional<RP2Point<Length, Camera>> start_rp2_point;
for (int i = 0; i < rp2_line.size(); ++i) {
RP2Point<Length, Camera> const& rp2_point = rp2_line[i];
if (i == 0) {
new_rp2_line.push_back(rp2_point);
start_rp2_point = rp2_point;
} else if (Pow<2>(rp2_point.x() - start_rp2_point->x()) +
Pow<2>(rp2_point.y() - start_rp2_point->y()) >
focal_plane_tolerance²) {
// TODO(phl): This creates a segment if the tolerance is exceeded. It
// should probably create a segment that stays just below the tolerance.
new_rp2_line.push_back(rp2_point);
start_rp2_point = rp2_point;
} else if (i == rp2_line.size() - 1) {
new_rp2_line.push_back(rp2_point);
} else {
++skipped;
}
++total;
}
new_rp2_lines.push_back(std::move(new_rp2_line));
}
LOG(INFO) << "Skipped " << skipped << " points out of " << total;
return new_rp2_lines;
}
RP2Lines<Length, Camera> Planetarium::PlotMethod2(
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end,
Instant const& now) const {
RP2Lines<Length, Camera> lines;
if (begin == end) {
return lines;
}
auto last = end;
--last;
if (begin == last) {
return lines;
}
auto const plottable_spheres = ComputePlottableSpheres(now);
auto const final_time = last.time();
auto const& trajectory = *begin.trajectory();
auto const tolerance =
perspective_.focal() * parameters_.sin²_angular_resolution_;
auto const squared_tolerance = Pow<2>(tolerance);
auto previous_time = begin.time();
auto previous_degrees_of_freedom = begin.degrees_of_freedom();
Position<Navigation> previous_position_in_navigation;
Length previous_projected_x;
Length previous_projected_y;
Speed previous_projected_velocity_x;
Speed previous_projected_velocity_y;
Time step;
{
previous_position_in_navigation =
plotting_frame_->ToThisFrameAtTime(
previous_time).rigid_transformation()(
previous_degrees_of_freedom.position());
auto const initial_displacement_from_camera =
perspective_.to_camera()(previous_position_in_navigation) -
Camera::origin;
auto const initial_velocity_in_camera =
perspective_.to_camera().linear_map()(
plotting_frame_->ToThisFrameAtTime(previous_time)
.orthogonal_map()(previous_degrees_of_freedom.velocity()));
previous_projected_x = perspective_.focal() *
initial_displacement_from_camera.coordinates().x /
initial_displacement_from_camera.coordinates().z;
previous_projected_y = perspective_.focal() *
initial_displacement_from_camera.coordinates().y /
initial_displacement_from_camera.coordinates().z;
previous_projected_velocity_x =
perspective_.focal() *
(initial_displacement_from_camera.coordinates().z *
initial_velocity_in_camera.coordinates().x -
initial_displacement_from_camera.coordinates().x *
initial_velocity_in_camera.coordinates().z) /
Pow<2>(initial_displacement_from_camera.coordinates().z);
previous_projected_velocity_y =
perspective_.focal() *
(initial_displacement_from_camera.coordinates().z *
initial_velocity_in_camera.coordinates().y -
initial_displacement_from_camera.coordinates().y *
initial_velocity_in_camera.coordinates().z) /
Pow<2>(initial_displacement_from_camera.coordinates().z);
step = parameters_.sin²_angular_resolution_ * perspective_.focal() /
Sqrt(Pow<2>(previous_projected_velocity_x) +
Pow<2>(previous_projected_velocity_y));
}
Square<Length> squared_error_estimate;
Position<Navigation> position_in_navigation;
Displacement<Camera> displacement_from_camera;
Length projected_x;
Length projected_y;
std::experimental::optional<Position<Navigation>> last_endpoint;
goto estimate_segment_error;
while (previous_time < final_time) {
do {
step *= Sqrt(Sqrt(squared_tolerance / squared_error_estimate));
estimate_segment_error:
if (previous_time + step > final_time) {
// TODO(egg): can this be greater than |final_time|?
step = final_time - previous_time;
}
Length const estimated_projected_x =
previous_projected_x + step * previous_projected_velocity_x;
Length const estimated_projected_y =
previous_projected_y + step * previous_projected_velocity_y;
position_in_navigation =
plotting_frame_->ToThisFrameAtTime(
previous_time + step).rigid_transformation()(
trajectory.EvaluatePosition(previous_time + step));
displacement_from_camera =
perspective_.to_camera()(position_in_navigation) - Camera::origin;
projected_x = perspective_.focal() *
displacement_from_camera.coordinates().x /
displacement_from_camera.coordinates().z;
projected_y = perspective_.focal() *
displacement_from_camera.coordinates().y /
displacement_from_camera.coordinates().z;
squared_error_estimate =
(Pow<2>(projected_x - estimated_projected_x) +
Pow<2>(projected_y - estimated_projected_y)) / 4;
} while (squared_error_estimate > squared_tolerance);
auto const segments =
perspective_.VisibleSegments(
Segment<Displacement<Navigation>>(previous_position_in_navigation,
position_in_navigation),
plottable_spheres);
for (auto const& segment : segments) {
if (last_endpoint != segment.first) {
lines.emplace_back();
lines.back().push_back(perspective_(segment.first));
}
lines.back().push_back(perspective_(segment.second));
last_endpoint = segment.second;
}
auto const velocity_in_camera = perspective_.to_camera().linear_map()(
plotting_frame_->ToThisFrameAtTime(
previous_time + step).orthogonal_map()(
trajectory.EvaluateVelocity(previous_time + step)));
previous_time = previous_time + step;
previous_position_in_navigation = position_in_navigation;
previous_projected_x = projected_x;
previous_projected_y = projected_y;
previous_projected_velocity_x =
perspective_.focal() *
(displacement_from_camera.coordinates().z *
velocity_in_camera.coordinates().x -
displacement_from_camera.coordinates().x *
velocity_in_camera.coordinates().z) /
Pow<2>(displacement_from_camera.coordinates().z);
previous_projected_velocity_y =
perspective_.focal() *
(displacement_from_camera.coordinates().z *
velocity_in_camera.coordinates().y -
displacement_from_camera.coordinates().y *
velocity_in_camera.coordinates().z) /
Pow<2>(displacement_from_camera.coordinates().z);
}
return lines;
}
std::vector<Sphere<Length, Navigation>> Planetarium::ComputePlottableSpheres(
Instant const& now) const {
RigidMotion<Barycentric, Navigation> const rigid_motion_at_now =
plotting_frame_->ToThisFrameAtTime(now);
std::vector<Sphere<Length, Navigation>> plottable_spheres;
auto const& bodies = ephemeris_->bodies();
for (auto const body : bodies) {
auto const trajectory = ephemeris_->trajectory(body);
Length const mean_radius = body->mean_radius();
Position<Barycentric> const centre_in_barycentric =
trajectory->EvaluatePosition(now);
Sphere<Length, Navigation> plottable_sphere(
rigid_motion_at_now.rigid_transformation()(centre_in_barycentric),
parameters_.sphere_radius_multiplier_ * mean_radius);
// If the sphere is seen under an angle that is very small it doesn't
// participate in hiding.
if (perspective_.SphereSin²HalfAngle(plottable_sphere) >
parameters_.sin²_angular_resolution_) {
plottable_spheres.emplace_back(std::move(plottable_sphere));
}
}
return plottable_spheres;
}
Segments<Displacement<Navigation>> Planetarium::ComputePlottableSegments(
const std::vector<Sphere<Length, Navigation>>& plottable_spheres,
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end) const {
std::vector<Segment<Displacement<Navigation>>> all_segments;
if (begin == end) {
return all_segments;
}
auto it1 = begin;
Instant t1 = it1.time();
RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 =
plotting_frame_->ToThisFrameAtTime(t1);
Position<Navigation> p1 =
rigid_motion_at_t1(it1.degrees_of_freedom()).position();
auto it2 = it1;
while (++it2 != end) {
// Processing one segment of the trajectory.
Instant const t2 = it2.time();
// Transform the degrees of freedom to the plotting frame.
RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 =
plotting_frame_->ToThisFrameAtTime(t2);
Position<Navigation> const p2 =
rigid_motion_at_t2(it2.degrees_of_freedom()).position();
// Find the part of the segment that is behind the focal plane. We don't
// care about things that are in front of the focal plane.
const Segment<Displacement<Navigation>> segment = {p1, p2};
auto const segment_behind_focal_plane =
perspective_.SegmentBehindFocalPlane(segment);
if (segment_behind_focal_plane) {
// Find the part(s) of the segment that are not hidden by spheres. These
// are the ones we want to plot.
auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane,
plottable_spheres);
std::move(segments.begin(),
segments.end(),
std::back_inserter(all_segments));
}
it1 = it2;
t1 = t2;
rigid_motion_at_t1 = rigid_motion_at_t2;
p1 = p2;
}
return all_segments;
}
} // namespace internal_planetarium
} // namespace ksp_plugin
} // namespace principia
|
#include "ksp_plugin/planetarium.hpp"
#include <vector>
#include "geometry/point.hpp"
#include "quantities/elementary_functions.hpp"
namespace principia {
namespace ksp_plugin {
namespace internal_planetarium {
using geometry::Position;
using geometry::RP2Line;
using quantities::Pow;
using quantities::Sin;
using quantities::Sqrt;
using quantities::Tan;
using quantities::Speed;
using quantities::Square;
using quantities::Time;
Planetarium::Parameters::Parameters(double const sphere_radius_multiplier,
Angle const& angular_resolution,
Angle const& field_of_view)
: sphere_radius_multiplier_(sphere_radius_multiplier),
sin²_angular_resolution_(Pow<2>(Sin(angular_resolution))),
tan_angular_resolution_(Tan(angular_resolution)),
tan_field_of_view_(Tan(field_of_view)) {}
Planetarium::Planetarium(
Parameters const& parameters,
Perspective<Navigation, Camera, Length, OrthogonalMap> const& perspective,
not_null<Ephemeris<Barycentric> const*> const ephemeris,
not_null<NavigationFrame const*> const plotting_frame)
: parameters_(parameters),
perspective_(perspective),
ephemeris_(ephemeris),
plotting_frame_(plotting_frame) {}
RP2Lines<Length, Camera> Planetarium::PlotMethod0(
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end,
Instant const& now) const {
auto const plottable_spheres = ComputePlottableSpheres(now);
auto const plottable_segments = ComputePlottableSegments(plottable_spheres,
begin, end);
auto const field_of_view_radius² =
perspective_.focal() * perspective_.focal() *
parameters_.tan_field_of_view_ * parameters_.tan_field_of_view_;
std::experimental::optional<Position<Navigation>> previous_position;
RP2Lines<Length, Camera> rp2_lines;
for (auto const& plottable_segment : plottable_segments) {
// Apply the projection to the current plottable segment.
auto const rp2_first = perspective_(plottable_segment.first);
auto const rp2_second = perspective_(plottable_segment.second);
// If the segment is entirely outside the field of view, ignore it.
Length const x1 = rp2_first.x();
Length const y1 = rp2_first.y();
Length const x2 = rp2_second.x();
Length const y2 = rp2_second.y();
if (x1 * x1 + y1 * y1 > field_of_view_radius² &&
x2 * x2 + y2 * y2 > field_of_view_radius²) {
continue;
}
// Create a new ℝP² line when two segments are not consecutive. Don't
// compare ℝP² points for equality, that's expensive.
bool const are_consecutive =
previous_position == plottable_segment.first;
previous_position = plottable_segment.second;
if (are_consecutive) {
rp2_lines.back().push_back(rp2_second);
} else {
RP2Line<Length, Camera> const rp2_line = {rp2_first, rp2_second};
rp2_lines.push_back(rp2_line);
}
}
return rp2_lines;
}
RP2Lines<Length, Camera> Planetarium::PlotMethod1(
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end,
Instant const& now) const {
Length const focal_plane_tolerance =
perspective_.focal() * parameters_.tan_angular_resolution_;
auto const focal_plane_tolerance² =
focal_plane_tolerance * focal_plane_tolerance;
auto const rp2_lines = PlotMethod0(begin, end, now);
int skipped = 0;
int total = 0;
RP2Lines<Length, Camera> new_rp2_lines;
for (auto const& rp2_line : rp2_lines) {
RP2Line<Length, Camera> new_rp2_line;
std::experimental::optional<RP2Point<Length, Camera>> start_rp2_point;
for (int i = 0; i < rp2_line.size(); ++i) {
RP2Point<Length, Camera> const& rp2_point = rp2_line[i];
if (i == 0) {
new_rp2_line.push_back(rp2_point);
start_rp2_point = rp2_point;
} else if (Pow<2>(rp2_point.x() - start_rp2_point->x()) +
Pow<2>(rp2_point.y() - start_rp2_point->y()) >
focal_plane_tolerance²) {
// TODO(phl): This creates a segment if the tolerance is exceeded. It
// should probably create a segment that stays just below the tolerance.
new_rp2_line.push_back(rp2_point);
start_rp2_point = rp2_point;
} else if (i == rp2_line.size() - 1) {
new_rp2_line.push_back(rp2_point);
} else {
++skipped;
}
++total;
}
new_rp2_lines.push_back(std::move(new_rp2_line));
}
LOG(INFO) << "Skipped " << skipped << " points out of " << total;
return new_rp2_lines;
}
RP2Lines<Length, Camera> Planetarium::PlotMethod2(
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end,
Instant const& now) const {
RP2Lines<Length, Camera> lines;
if (begin == end) {
return lines;
}
auto last = end;
--last;
if (begin == last) {
return lines;
}
auto const plottable_spheres = ComputePlottableSpheres(now);
auto const final_time = last.time();
auto const& trajectory = *begin.trajectory();
auto const squared_tolerance = Pow<2>(parameters_.tan_angular_resolution_);
auto previous_time = begin.time();
auto previous_degrees_of_freedom = begin.degrees_of_freedom();
Position<Navigation> previous_position_in_navigation;
Length previous_projected_x;
Length previous_projected_y;
Speed previous_projected_velocity_x;
Speed previous_projected_velocity_y;
Time step;
{
previous_position_in_navigation =
plotting_frame_->ToThisFrameAtTime(
previous_time).rigid_transformation()(
previous_degrees_of_freedom.position());
auto const initial_displacement_from_camera =
perspective_.to_camera()(previous_position_in_navigation) -
Camera::origin;
auto const initial_velocity_in_camera =
perspective_.to_camera().linear_map()(
plotting_frame_->ToThisFrameAtTime(previous_time)
.orthogonal_map()(previous_degrees_of_freedom.velocity()));
previous_projected_x = perspective_.focal() *
initial_displacement_from_camera.coordinates().x /
initial_displacement_from_camera.coordinates().z;
previous_projected_y = perspective_.focal() *
initial_displacement_from_camera.coordinates().y /
initial_displacement_from_camera.coordinates().z;
previous_projected_velocity_x =
perspective_.focal() *
(initial_displacement_from_camera.coordinates().z *
initial_velocity_in_camera.coordinates().x -
initial_displacement_from_camera.coordinates().x *
initial_velocity_in_camera.coordinates().z) /
Pow<2>(initial_displacement_from_camera.coordinates().z);
previous_projected_velocity_y =
perspective_.focal() *
(initial_displacement_from_camera.coordinates().z *
initial_velocity_in_camera.coordinates().y -
initial_displacement_from_camera.coordinates().y *
initial_velocity_in_camera.coordinates().z) /
Pow<2>(initial_displacement_from_camera.coordinates().z);
step = parameters_.sin²_angular_resolution_ * perspective_.focal() /
Sqrt(Pow<2>(previous_projected_velocity_x) +
Pow<2>(previous_projected_velocity_y));
}
Instant t;
double squared_error_estimate;
Position<Navigation> position_in_navigation;
Displacement<Camera> displacement_from_camera;
std::experimental::optional<Position<Navigation>> last_endpoint;
goto estimate_segment_error;
while (previous_time < final_time) {
do {
step *= Sqrt(Sqrt(squared_tolerance / squared_error_estimate));
estimate_segment_error:
t = previous_time + step;
if (t > final_time) {
t = final_time;
step = t - previous_time;
}
Length const estimated_projected_x =
previous_projected_x + step * previous_projected_velocity_x;
Length const estimated_projected_y =
previous_projected_y + step * previous_projected_velocity_y;
Displacement<Camera> estimated_unprojected(
{estimated_projected_x, estimated_projected_y, perspective_.focal()});
position_in_navigation =
plotting_frame_->ToThisFrameAtTime(t).rigid_transformation()(
trajectory.EvaluatePosition(t));
displacement_from_camera =
perspective_.to_camera()(position_in_navigation) - Camera::origin;
auto const wedge = Wedge(estimated_unprojected, displacement_from_camera);
squared_error_estimate =
InnerProduct(wedge, wedge) /
Pow<2>(InnerProduct(estimated_unprojected, displacement_from_camera));
} while (squared_error_estimate > squared_tolerance);
auto const segments =
perspective_.VisibleSegments(
Segment<Displacement<Navigation>>(previous_position_in_navigation,
position_in_navigation),
plottable_spheres);
for (auto const& segment : segments) {
if (last_endpoint != segment.first) {
lines.emplace_back();
lines.back().push_back(perspective_(segment.first));
}
lines.back().push_back(perspective_(segment.second));
last_endpoint = segment.second;
}
auto const velocity_in_camera = perspective_.to_camera().linear_map()(
plotting_frame_->ToThisFrameAtTime(t).orthogonal_map()(
trajectory.EvaluateVelocity(t)));
previous_time = t;
previous_position_in_navigation = position_in_navigation;
previous_projected_x = perspective_.focal() *
displacement_from_camera.coordinates().x /
displacement_from_camera.coordinates().z;
previous_projected_y = perspective_.focal() *
displacement_from_camera.coordinates().y /
displacement_from_camera.coordinates().z;
previous_projected_velocity_x =
perspective_.focal() *
(displacement_from_camera.coordinates().z *
velocity_in_camera.coordinates().x -
displacement_from_camera.coordinates().x *
velocity_in_camera.coordinates().z) /
Pow<2>(displacement_from_camera.coordinates().z);
previous_projected_velocity_y =
perspective_.focal() *
(displacement_from_camera.coordinates().z *
velocity_in_camera.coordinates().y -
displacement_from_camera.coordinates().y *
velocity_in_camera.coordinates().z) /
Pow<2>(displacement_from_camera.coordinates().z);
}
return lines;
}
std::vector<Sphere<Length, Navigation>> Planetarium::ComputePlottableSpheres(
Instant const& now) const {
RigidMotion<Barycentric, Navigation> const rigid_motion_at_now =
plotting_frame_->ToThisFrameAtTime(now);
std::vector<Sphere<Length, Navigation>> plottable_spheres;
auto const& bodies = ephemeris_->bodies();
for (auto const body : bodies) {
auto const trajectory = ephemeris_->trajectory(body);
Length const mean_radius = body->mean_radius();
Position<Barycentric> const centre_in_barycentric =
trajectory->EvaluatePosition(now);
Sphere<Length, Navigation> plottable_sphere(
rigid_motion_at_now.rigid_transformation()(centre_in_barycentric),
parameters_.sphere_radius_multiplier_ * mean_radius);
// If the sphere is seen under an angle that is very small it doesn't
// participate in hiding.
if (perspective_.SphereSin²HalfAngle(plottable_sphere) >
parameters_.sin²_angular_resolution_) {
plottable_spheres.emplace_back(std::move(plottable_sphere));
}
}
return plottable_spheres;
}
Segments<Displacement<Navigation>> Planetarium::ComputePlottableSegments(
const std::vector<Sphere<Length, Navigation>>& plottable_spheres,
DiscreteTrajectory<Barycentric>::Iterator const& begin,
DiscreteTrajectory<Barycentric>::Iterator const& end) const {
std::vector<Segment<Displacement<Navigation>>> all_segments;
if (begin == end) {
return all_segments;
}
auto it1 = begin;
Instant t1 = it1.time();
RigidMotion<Barycentric, Navigation> rigid_motion_at_t1 =
plotting_frame_->ToThisFrameAtTime(t1);
Position<Navigation> p1 =
rigid_motion_at_t1(it1.degrees_of_freedom()).position();
auto it2 = it1;
while (++it2 != end) {
// Processing one segment of the trajectory.
Instant const t2 = it2.time();
// Transform the degrees of freedom to the plotting frame.
RigidMotion<Barycentric, Navigation> const rigid_motion_at_t2 =
plotting_frame_->ToThisFrameAtTime(t2);
Position<Navigation> const p2 =
rigid_motion_at_t2(it2.degrees_of_freedom()).position();
// Find the part of the segment that is behind the focal plane. We don't
// care about things that are in front of the focal plane.
const Segment<Displacement<Navigation>> segment = {p1, p2};
auto const segment_behind_focal_plane =
perspective_.SegmentBehindFocalPlane(segment);
if (segment_behind_focal_plane) {
// Find the part(s) of the segment that are not hidden by spheres. These
// are the ones we want to plot.
auto segments = perspective_.VisibleSegments(*segment_behind_focal_plane,
plottable_spheres);
std::move(segments.begin(),
segments.end(),
std::back_inserter(all_segments));
}
it1 = it2;
t1 = t2;
rigid_motion_at_t1 = rigid_motion_at_t2;
p1 = p2;
}
return all_segments;
}
} // namespace internal_planetarium
} // namespace ksp_plugin
} // namespace principia
|
use the tangent
|
use the tangent
|
C++
|
mit
|
eggrobin/Principia,eggrobin/Principia,pleroy/Principia,eggrobin/Principia,mockingbirdnest/Principia,pleroy/Principia,mockingbirdnest/Principia,pleroy/Principia,pleroy/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia
|
e11862ae5cf4401efa11317ec366710f2f71968b
|
include/allocator.hpp
|
include/allocator.hpp
|
#include <utility>
#include "bitset.hpp"
template<typename T>
T* operatorNewCopiedArray(const T * source, size_t source_count, size_t destination_size) /*strong*/
{
T* new_array = nullptr;
size_t n_placed_elements = 0;
try {
new_array = static_cast<T*>(operator new(destination_size * sizeof(T)));
for (size_t i = 0; i < source_count; ++i) {
construct(&new_array[i], source[i]);
++n_placed_elements;
}
}
catch (...) {
destroy(new_array, new_array + n_placed_elements);
operator delete(new_array);
throw;
}
return new_array;
}
template <typename T>
class allocator
{
public:
explicit allocator(size_t size = 0); /*strong*/
allocator(allocator const & other); /*strong*/
auto operator=(allocator const & other) -> allocator & = delete;
~allocator();
auto resize() -> void; /*strong*/
auto construct(size_t index, T const & value) -> void; /*strong*/
auto destroy(size_t index) -> void; /*noexcept*/
auto get() -> T * { return ptr_; } /*noexcept*/
auto get() const -> T const * { return ptr_; } /*noexcept*/
auto getElement(size_t index) -> T & { return ptr_[index]; } /*noexcept*/
auto getElement(size_t index) const -> T const & { return ptr_[index]; } /*noexcept*/
auto count() const -> size_t { return map_->counter(); } /*noexcept*/
bool full() const { return map_->counter() == size_; } /*noexcept*/
bool empty() const { return map_->counter() == 0; } /*noexcept*/
void swap(allocator & other); /*noexcept*/
private:
//auto destroy(T * first, T * last) -> void; /*noexcept*/
T * ptr_;
size_t size_;
std::unique_ptr<bitset> map_;
};
template<typename T>
allocator<T>::allocator(size_t size)
: ptr_(static_cast<T*>(operator new(size * sizeof(T)))),
size_(size),
map_(std::make_unique<bitset>(size))
{
;
}
template<typename T>
allocator<T>::allocator(allocator const & other)
: allocator<T>(other.size_)
{
try {
for (size_t i = 0; i < size_; ++i) {
construct(i, other.ptr_[i]);
}
}
catch (...) {
this->~allocator();
throw;
}
}
template<typename T>
allocator<T>::~allocator() {
for (size_t i = 0; i < size_; ++i) {
if (map_->test(i)) {
this->destroy(i);
}
}
operator delete(ptr_);
}
template<typename T>
void allocator<T>::resize() {
allocator<T> temp((size_ * 3) / 2 + 1);
for (size_t i = 0; i < size_; ++i) {
if (map_->test(i)) {
temp.construct(i, ptr_[i]);
}
}
this->swap(temp);
}
template<typename T>
void allocator<T>::construct(size_t index, T const & value) {
if (index < size_) {
new (&(ptr_[index])) T(value);
map_->set(index);
}
else {
throw("index >= size_");
}
}
template<typename T>
void allocator<T>::destroy(size_t index) {
if (index < size_) {
if (map_->test(index)) {
ptr_[index].~T();
map_->reset(index);
}
else {
throw ("memory is occupied");
}
}
else {
throw ("index >= size_");
}
}
/*template<typename T>
auto allocator<T>::destroy(T * first, T * last)->void {
if (first >= ptr_&&last <= ptr_ + this->count())
for (; first != last; ++first) {
destroy(&*first);
}
}*/
template<typename T>
void allocator<T>::swap(allocator & other) {
std::swap(ptr_, other.ptr_);
std::swap(size_, other.size_);
std::swap(map_, other.map_);
}
|
#include <utility>
#include "bitset.hpp"
template<typename T>
T* operatorNewCopiedArray(const T * source, size_t source_count, size_t destination_size) /*strong*/
{
T* new_array = nullptr;
size_t n_placed_elements = 0;
try {
new_array = static_cast<T*>(operator new(destination_size * sizeof(T)));
for (size_t i = 0; i < source_count; ++i) {
construct(&new_array[i], source[i]);
++n_placed_elements;
}
}
catch (...) {
destroy(new_array, new_array + n_placed_elements);
operator delete(new_array);
throw;
}
return new_array;
}
template <typename T>
class allocator
{
public:
explicit allocator(size_t size = 0); /*strong*/
allocator(allocator const & other); /*strong*/
auto operator=(allocator const & other)->allocator & {
if (this != &other) {
(allocator<T>(other)).swap(*this);
}
return *this;
};
~allocator();
auto resize() -> void; /*strong*/
auto construct(size_t index, T const & value) -> void; /*strong*/
auto destroy(size_t index) -> void; /*noexcept*/
auto get() -> T * { return ptr_; } /*noexcept*/
auto get() const -> T const * { return ptr_; } /*noexcept*/
auto getElement(size_t index) -> T & { return ptr_[index]; } /*noexcept*/
auto getElement(size_t index) const -> T const & { return ptr_[index]; } /*noexcept*/
auto count() const -> size_t {
return map_->counter();
} /*noexcept*/
bool full() const { return map_->counter() == size_; } /*noexcept*/
bool empty() const { return map_->counter() == 0; } /*noexcept*/
void swap(allocator & other); /*noexcept*/
private:
//auto destroy(T * first, T * last) -> void; /*noexcept*/
T * ptr_;
size_t size_;
std::unique_ptr<bitset> map_;
};
template<typename T>
allocator<T>::allocator(size_t size)
: ptr_(static_cast<T*>(operator new(size * sizeof(T)))),
size_(size),
map_(std::make_unique<bitset>(size))
{
;
}
template<typename T>
allocator<T>::allocator(allocator const & other)
: allocator<T>(other.size_)
{
try {
for (size_t i = 0; i < size_; ++i) {
construct(i, other.ptr_[i]);
}
}
catch (...) {
this->~allocator();
}
}
template<typename T>
allocator<T>::~allocator() {
for (size_t i = 0; i < size_; ++i) {
if (map_->test(i)) {
this->destroy(i);
}
}
operator delete(ptr_);
}
template<typename T>
void allocator<T>::resize() {
allocator<T> temp((size_ * 3) / 2 + 1);
for (size_t i = 0; i < size_; ++i) {
if (map_->test(i)) {
temp.construct(i, ptr_[i]);
}
}
this->swap(temp);
}
template<typename T>
void allocator<T>::construct(size_t index, T const & value) {
if (index < size_) {
if (map_->test(index)) {
throw ("=(");
}
new (&(ptr_[index])) T(value);
map_->set(index);
}
else {
throw("index >= size_");
}
}
template<typename T>
void allocator<T>::destroy(size_t index) {
if (index < size_) {
if (map_->test(index)) {
ptr_->~T();
map_->reset(index);
}
else {
throw ("memory is occupied");
}
}
else {
throw ("index >= size_");
}
}
/*template<typename T>
auto allocator<T>::destroy(T * first, T * last)->void {
if (first >= ptr_&&last <= ptr_ + this->count())
for (; first != last; ++first) {
destroy(&*first);
}
}*/
template<typename T>
void allocator<T>::swap(allocator & other) {
std::swap(ptr_, other.ptr_);
std::swap(size_, other.size_);
std::swap(map_, other.map_);
}
|
Update allocator.hpp
|
Update allocator.hpp
|
C++
|
mit
|
ArtemKokorinStudent/StackW
|
2e096609b2f09512234ce69dcc0c30f8ab2d1b8f
|
gm/convexpolyclip.cpp
|
gm/convexpolyclip.cpp
|
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBitmap.h"
#include "SkGradientShader.h"
#include "SkTLList.h"
static SkBitmap make_bmp(int w, int h) {
SkBitmap bmp;
bmp.allocN32Pixels(w, h, true);
SkCanvas canvas(bmp);
SkScalar wScalar = SkIntToScalar(w);
SkScalar hScalar = SkIntToScalar(h);
SkPoint pt = { wScalar / 2, hScalar / 2 };
SkScalar radius = 3 * SkMaxScalar(wScalar, hScalar);
SkColor colors[] = { SK_ColorDKGRAY, 0xFF222255,
0xFF331133, 0xFF884422,
0xFF000022, SK_ColorWHITE,
0xFFAABBCC};
SkScalar pos[] = {0,
SK_Scalar1 / 6,
2 * SK_Scalar1 / 6,
3 * SK_Scalar1 / 6,
4 * SK_Scalar1 / 6,
5 * SK_Scalar1 / 6,
SK_Scalar1};
SkPaint paint;
SkRect rect = SkRect::MakeWH(wScalar, hScalar);
SkMatrix mat = SkMatrix::I();
for (int i = 0; i < 4; ++i) {
paint.setShader(SkGradientShader::CreateRadial(
pt, radius,
colors, pos,
SK_ARRAY_COUNT(colors),
SkShader::kRepeat_TileMode,
0, &mat))->unref();
canvas.drawRect(rect, paint);
rect.inset(wScalar / 8, hScalar / 8);
mat.preTranslate(6 * wScalar, 6 * hScalar);
mat.postScale(SK_Scalar1 / 3, SK_Scalar1 / 3);
}
paint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&paint);
paint.setTextSize(wScalar / 2.2f);
paint.setShader(0);
paint.setColor(SK_ColorLTGRAY);
static const char kTxt[] = "Skia";
SkPoint texPos = { wScalar / 17, hScalar / 2 + paint.getTextSize() / 2.5f };
canvas.drawText(kTxt, SK_ARRAY_COUNT(kTxt)-1, texPos.fX, texPos.fY, paint);
paint.setColor(SK_ColorBLACK);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SK_Scalar1);
canvas.drawText(kTxt, SK_ARRAY_COUNT(kTxt)-1, texPos.fX, texPos.fY, paint);
return bmp;
}
namespace skiagm {
/**
* This GM tests convex polygon clips.
*/
class ConvexPolyClip : public GM {
public:
ConvexPolyClip() {
this->setBGColor(0xFFFFFFFF);
}
protected:
SkString onShortName() override {
return SkString("convex_poly_clip");
}
SkISize onISize() override {
// When benchmarking the saveLayer set of draws is skipped.
int w = 435;
if (kBench_Mode != this->getMode()) {
w *= 2;
}
return SkISize::Make(w, 540);
}
void onOnceBeforeDraw() override {
SkPath tri;
tri.moveTo(5.f, 5.f);
tri.lineTo(100.f, 20.f);
tri.lineTo(15.f, 100.f);
fClips.addToTail()->setPath(tri);
SkPath hexagon;
static const SkScalar kRadius = 45.f;
const SkPoint center = { kRadius, kRadius };
for (int i = 0; i < 6; ++i) {
SkScalar angle = 2 * SK_ScalarPI * i / 6;
SkPoint point;
point.fY = SkScalarSinCos(angle, &point.fX);
point.scale(kRadius);
point = center + point;
if (0 == i) {
hexagon.moveTo(point);
} else {
hexagon.lineTo(point);
}
}
fClips.addToTail()->setPath(hexagon);
SkMatrix scaleM;
scaleM.setScale(1.1f, 0.4f, kRadius, kRadius);
hexagon.transform(scaleM);
fClips.addToTail()->setPath(hexagon);
fClips.addToTail()->setRect(SkRect::MakeXYWH(8.3f, 11.6f, 78.2f, 72.6f));
SkPath rotRect;
SkRect rect = SkRect::MakeLTRB(10.f, 12.f, 80.f, 86.f);
rotRect.addRect(rect);
SkMatrix rotM;
rotM.setRotate(23.f, rect.centerX(), rect.centerY());
rotRect.transform(rotM);
fClips.addToTail()->setPath(rotRect);
fBmp = make_bmp(100, 100);
}
void onDraw(SkCanvas* canvas) override {
SkScalar y = 0;
static const SkScalar kMargin = 10.f;
SkPaint bgPaint;
bgPaint.setAlpha(0x15);
SkISize size = canvas->getDeviceSize();
SkRect dstRect = SkRect::MakeWH(SkIntToScalar(size.fWidth),
SkIntToScalar(size.fHeight));
canvas->drawBitmapRectToRect(fBmp, NULL, dstRect, &bgPaint);
static const char kTxt[] = "Clip Me!";
SkPaint txtPaint;
txtPaint.setTextSize(23.f);
txtPaint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface(&txtPaint);
txtPaint.setColor(SK_ColorDKGRAY);
SkScalar textW = txtPaint.measureText(kTxt, SK_ARRAY_COUNT(kTxt)-1);
SkScalar startX = 0;
int testLayers = kBench_Mode != this->getMode();
for (int doLayer = 0; doLayer <= testLayers; ++doLayer) {
for (SkTLList<Clip>::Iter iter(fClips, SkTLList<Clip>::Iter::kHead_IterStart);
iter.get();
iter.next()) {
const Clip* clip = iter.get();
SkScalar x = startX;
for (int aa = 0; aa < 2; ++aa) {
if (doLayer) {
SkRect bounds;
clip->getBounds(&bounds);
bounds.outset(2, 2);
bounds.offset(x, y);
canvas->saveLayer(&bounds, NULL);
} else {
canvas->save();
}
canvas->translate(x, y);
clip->setOnCanvas(canvas, SkRegion::kIntersect_Op, SkToBool(aa));
canvas->drawBitmap(fBmp, 0, 0);
canvas->restore();
x += fBmp.width() + kMargin;
}
for (int aa = 0; aa < 2; ++aa) {
SkPaint clipOutlinePaint;
clipOutlinePaint.setAntiAlias(true);
clipOutlinePaint.setColor(0x50505050);
clipOutlinePaint.setStyle(SkPaint::kStroke_Style);
clipOutlinePaint.setStrokeWidth(0);
if (doLayer) {
SkRect bounds;
clip->getBounds(&bounds);
bounds.outset(2, 2);
bounds.offset(x, y);
canvas->saveLayer(&bounds, NULL);
} else {
canvas->save();
}
canvas->translate(x, y);
SkPath closedClipPath;
clip->asClosedPath(&closedClipPath);
canvas->drawPath(closedClipPath, clipOutlinePaint);
clip->setOnCanvas(canvas, SkRegion::kIntersect_Op, SkToBool(aa));
canvas->scale(1.f, 1.8f);
canvas->drawText(kTxt, SK_ARRAY_COUNT(kTxt)-1,
0, 1.5f * txtPaint.getTextSize(),
txtPaint);
canvas->restore();
x += textW + 2 * kMargin;
}
y += fBmp.height() + kMargin;
}
y = 0;
startX += 2 * fBmp.width() + SkScalarCeilToInt(2 * textW) + 6 * kMargin;
}
}
bool runAsBench() const override { return true; }
private:
class Clip {
public:
enum ClipType {
kNone_ClipType,
kPath_ClipType,
kRect_ClipType
};
Clip () : fClipType(kNone_ClipType) {}
void setOnCanvas(SkCanvas* canvas, SkRegion::Op op, bool aa) const {
switch (fClipType) {
case kPath_ClipType:
canvas->clipPath(fPath, op, aa);
break;
case kRect_ClipType:
canvas->clipRect(fRect, op, aa);
break;
case kNone_ClipType:
SkDEBUGFAIL("Uninitialized Clip.");
break;
}
}
void asClosedPath(SkPath* path) const {
switch (fClipType) {
case kPath_ClipType:
*path = fPath;
path->close();
break;
case kRect_ClipType:
path->reset();
path->addRect(fRect);
break;
case kNone_ClipType:
SkDEBUGFAIL("Uninitialized Clip.");
break;
}
}
void setPath(const SkPath& path) {
fClipType = kPath_ClipType;
fPath = path;
}
void setRect(const SkRect& rect) {
fClipType = kRect_ClipType;
fRect = rect;
fPath.reset();
}
ClipType getType() const { return fClipType; }
void getBounds(SkRect* bounds) const {
switch (fClipType) {
case kPath_ClipType:
*bounds = fPath.getBounds();
break;
case kRect_ClipType:
*bounds = fRect;
break;
case kNone_ClipType:
SkDEBUGFAIL("Uninitialized Clip.");
break;
}
}
private:
ClipType fClipType;
SkPath fPath;
SkRect fRect;
};
SkTLList<Clip> fClips;
SkBitmap fBmp;
typedef GM INHERITED;
};
DEF_GM( return SkNEW(ConvexPolyClip); )
}
|
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBitmap.h"
#include "SkGradientShader.h"
#include "SkTLList.h"
static SkBitmap make_bmp(int w, int h) {
SkBitmap bmp;
bmp.allocN32Pixels(w, h, true);
SkCanvas canvas(bmp);
SkScalar wScalar = SkIntToScalar(w);
SkScalar hScalar = SkIntToScalar(h);
SkPoint pt = { wScalar / 2, hScalar / 2 };
SkScalar radius = 3 * SkMaxScalar(wScalar, hScalar);
SkColor colors[] = { sk_tool_utils::color_to_565(SK_ColorDKGRAY),
sk_tool_utils::color_to_565(0xFF222255),
sk_tool_utils::color_to_565(0xFF331133),
sk_tool_utils::color_to_565(0xFF884422),
sk_tool_utils::color_to_565(0xFF000022), SK_ColorWHITE,
sk_tool_utils::color_to_565(0xFFAABBCC) };
SkScalar pos[] = {0,
SK_Scalar1 / 6,
2 * SK_Scalar1 / 6,
3 * SK_Scalar1 / 6,
4 * SK_Scalar1 / 6,
5 * SK_Scalar1 / 6,
SK_Scalar1};
SkPaint paint;
SkRect rect = SkRect::MakeWH(wScalar, hScalar);
SkMatrix mat = SkMatrix::I();
for (int i = 0; i < 4; ++i) {
paint.setShader(SkGradientShader::CreateRadial(
pt, radius,
colors, pos,
SK_ARRAY_COUNT(colors),
SkShader::kRepeat_TileMode,
0, &mat))->unref();
canvas.drawRect(rect, paint);
rect.inset(wScalar / 8, hScalar / 8);
mat.preTranslate(6 * wScalar, 6 * hScalar);
mat.postScale(SK_Scalar1 / 3, SK_Scalar1 / 3);
}
paint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface_always(&paint);
paint.setTextSize(wScalar / 2.2f);
paint.setShader(0);
paint.setColor(sk_tool_utils::color_to_565(SK_ColorLTGRAY));
static const char kTxt[] = "Skia";
SkPoint texPos = { wScalar / 17, hScalar / 2 + paint.getTextSize() / 2.5f };
canvas.drawText(kTxt, SK_ARRAY_COUNT(kTxt)-1, texPos.fX, texPos.fY, paint);
paint.setColor(SK_ColorBLACK);
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SK_Scalar1);
canvas.drawText(kTxt, SK_ARRAY_COUNT(kTxt)-1, texPos.fX, texPos.fY, paint);
return bmp;
}
namespace skiagm {
/**
* This GM tests convex polygon clips.
*/
class ConvexPolyClip : public GM {
public:
ConvexPolyClip() {
this->setBGColor(0xFFFFFFFF);
}
protected:
SkString onShortName() override {
return SkString("convex_poly_clip");
}
SkISize onISize() override {
// When benchmarking the saveLayer set of draws is skipped.
int w = 435;
if (kBench_Mode != this->getMode()) {
w *= 2;
}
return SkISize::Make(w, 540);
}
void onOnceBeforeDraw() override {
SkPath tri;
tri.moveTo(5.f, 5.f);
tri.lineTo(100.f, 20.f);
tri.lineTo(15.f, 100.f);
fClips.addToTail()->setPath(tri);
SkPath hexagon;
static const SkScalar kRadius = 45.f;
const SkPoint center = { kRadius, kRadius };
for (int i = 0; i < 6; ++i) {
SkScalar angle = 2 * SK_ScalarPI * i / 6;
SkPoint point;
point.fY = SkScalarSinCos(angle, &point.fX);
point.scale(kRadius);
point = center + point;
if (0 == i) {
hexagon.moveTo(point);
} else {
hexagon.lineTo(point);
}
}
fClips.addToTail()->setPath(hexagon);
SkMatrix scaleM;
scaleM.setScale(1.1f, 0.4f, kRadius, kRadius);
hexagon.transform(scaleM);
fClips.addToTail()->setPath(hexagon);
fClips.addToTail()->setRect(SkRect::MakeXYWH(8.3f, 11.6f, 78.2f, 72.6f));
SkPath rotRect;
SkRect rect = SkRect::MakeLTRB(10.f, 12.f, 80.f, 86.f);
rotRect.addRect(rect);
SkMatrix rotM;
rotM.setRotate(23.f, rect.centerX(), rect.centerY());
rotRect.transform(rotM);
fClips.addToTail()->setPath(rotRect);
fBmp = make_bmp(100, 100);
}
void onDraw(SkCanvas* canvas) override {
SkScalar y = 0;
static const SkScalar kMargin = 10.f;
SkPaint bgPaint;
bgPaint.setAlpha(0x15);
SkISize size = canvas->getDeviceSize();
SkRect dstRect = SkRect::MakeWH(SkIntToScalar(size.fWidth),
SkIntToScalar(size.fHeight));
canvas->drawBitmapRectToRect(fBmp, NULL, dstRect, &bgPaint);
static const char kTxt[] = "Clip Me!";
SkPaint txtPaint;
txtPaint.setTextSize(23.f);
txtPaint.setAntiAlias(true);
sk_tool_utils::set_portable_typeface_always(&txtPaint);
txtPaint.setColor(sk_tool_utils::color_to_565(SK_ColorDKGRAY));
SkScalar textW = txtPaint.measureText(kTxt, SK_ARRAY_COUNT(kTxt)-1);
SkScalar startX = 0;
int testLayers = kBench_Mode != this->getMode();
for (int doLayer = 0; doLayer <= testLayers; ++doLayer) {
for (SkTLList<Clip>::Iter iter(fClips, SkTLList<Clip>::Iter::kHead_IterStart);
iter.get();
iter.next()) {
const Clip* clip = iter.get();
SkScalar x = startX;
for (int aa = 0; aa < 2; ++aa) {
if (doLayer) {
SkRect bounds;
clip->getBounds(&bounds);
bounds.outset(2, 2);
bounds.offset(x, y);
canvas->saveLayer(&bounds, NULL);
} else {
canvas->save();
}
canvas->translate(x, y);
clip->setOnCanvas(canvas, SkRegion::kIntersect_Op, SkToBool(aa));
canvas->drawBitmap(fBmp, 0, 0);
canvas->restore();
x += fBmp.width() + kMargin;
}
for (int aa = 0; aa < 2; ++aa) {
SkPaint clipOutlinePaint;
clipOutlinePaint.setAntiAlias(true);
clipOutlinePaint.setColor(0x50505050);
clipOutlinePaint.setStyle(SkPaint::kStroke_Style);
clipOutlinePaint.setStrokeWidth(0);
if (doLayer) {
SkRect bounds;
clip->getBounds(&bounds);
bounds.outset(2, 2);
bounds.offset(x, y);
canvas->saveLayer(&bounds, NULL);
} else {
canvas->save();
}
canvas->translate(x, y);
SkPath closedClipPath;
clip->asClosedPath(&closedClipPath);
canvas->drawPath(closedClipPath, clipOutlinePaint);
clip->setOnCanvas(canvas, SkRegion::kIntersect_Op, SkToBool(aa));
canvas->scale(1.f, 1.8f);
canvas->drawText(kTxt, SK_ARRAY_COUNT(kTxt)-1,
0, 1.5f * txtPaint.getTextSize(),
txtPaint);
canvas->restore();
x += textW + 2 * kMargin;
}
y += fBmp.height() + kMargin;
}
y = 0;
startX += 2 * fBmp.width() + SkScalarCeilToInt(2 * textW) + 6 * kMargin;
}
}
bool runAsBench() const override { return true; }
private:
class Clip {
public:
enum ClipType {
kNone_ClipType,
kPath_ClipType,
kRect_ClipType
};
Clip () : fClipType(kNone_ClipType) {}
void setOnCanvas(SkCanvas* canvas, SkRegion::Op op, bool aa) const {
switch (fClipType) {
case kPath_ClipType:
canvas->clipPath(fPath, op, aa);
break;
case kRect_ClipType:
canvas->clipRect(fRect, op, aa);
break;
case kNone_ClipType:
SkDEBUGFAIL("Uninitialized Clip.");
break;
}
}
void asClosedPath(SkPath* path) const {
switch (fClipType) {
case kPath_ClipType:
*path = fPath;
path->close();
break;
case kRect_ClipType:
path->reset();
path->addRect(fRect);
break;
case kNone_ClipType:
SkDEBUGFAIL("Uninitialized Clip.");
break;
}
}
void setPath(const SkPath& path) {
fClipType = kPath_ClipType;
fPath = path;
}
void setRect(const SkRect& rect) {
fClipType = kRect_ClipType;
fRect = rect;
fPath.reset();
}
ClipType getType() const { return fClipType; }
void getBounds(SkRect* bounds) const {
switch (fClipType) {
case kPath_ClipType:
*bounds = fPath.getBounds();
break;
case kRect_ClipType:
*bounds = fRect;
break;
case kNone_ClipType:
SkDEBUGFAIL("Uninitialized Clip.");
break;
}
}
private:
ClipType fClipType;
SkPath fPath;
SkRect fRect;
};
SkTLList<Clip> fClips;
SkBitmap fBmp;
typedef GM INHERITED;
};
DEF_GM( return SkNEW(ConvexPolyClip); )
}
|
make convex poly clip portable
|
make convex poly clip portable
[email protected]
Review URL: https://codereview.chromium.org/1238483002
|
C++
|
bsd-3-clause
|
HalCanary/skia-hc,ominux/skia,ominux/skia,shahrzadmn/skia,rubenvb/skia,tmpvar/skia.cc,qrealka/skia-hc,rubenvb/skia,tmpvar/skia.cc,shahrzadmn/skia,noselhq/skia,aosp-mirror/platform_external_skia,google/skia,ominux/skia,Hikari-no-Tenshi/android_external_skia,pcwalton/skia,google/skia,ominux/skia,todotodoo/skia,noselhq/skia,Jichao/skia,pcwalton/skia,pcwalton/skia,tmpvar/skia.cc,vanish87/skia,HalCanary/skia-hc,HalCanary/skia-hc,google/skia,vanish87/skia,aosp-mirror/platform_external_skia,noselhq/skia,noselhq/skia,rubenvb/skia,todotodoo/skia,HalCanary/skia-hc,vanish87/skia,pcwalton/skia,nvoron23/skia,shahrzadmn/skia,google/skia,HalCanary/skia-hc,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,tmpvar/skia.cc,Hikari-no-Tenshi/android_external_skia,Jichao/skia,todotodoo/skia,qrealka/skia-hc,nvoron23/skia,ominux/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,vanish87/skia,shahrzadmn/skia,todotodoo/skia,aosp-mirror/platform_external_skia,nvoron23/skia,aosp-mirror/platform_external_skia,pcwalton/skia,aosp-mirror/platform_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,google/skia,todotodoo/skia,noselhq/skia,ominux/skia,rubenvb/skia,tmpvar/skia.cc,noselhq/skia,pcwalton/skia,Jichao/skia,todotodoo/skia,aosp-mirror/platform_external_skia,shahrzadmn/skia,shahrzadmn/skia,google/skia,nvoron23/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,qrealka/skia-hc,todotodoo/skia,tmpvar/skia.cc,pcwalton/skia,qrealka/skia-hc,vanish87/skia,Jichao/skia,ominux/skia,aosp-mirror/platform_external_skia,qrealka/skia-hc,Hikari-no-Tenshi/android_external_skia,tmpvar/skia.cc,nvoron23/skia,noselhq/skia,ominux/skia,shahrzadmn/skia,pcwalton/skia,vanish87/skia,rubenvb/skia,todotodoo/skia,vanish87/skia,qrealka/skia-hc,Jichao/skia,google/skia,aosp-mirror/platform_external_skia,Jichao/skia,Jichao/skia,qrealka/skia-hc,vanish87/skia,aosp-mirror/platform_external_skia,shahrzadmn/skia,tmpvar/skia.cc,shahrzadmn/skia,nvoron23/skia,HalCanary/skia-hc,vanish87/skia,rubenvb/skia,tmpvar/skia.cc,google/skia,pcwalton/skia,noselhq/skia,nvoron23/skia,rubenvb/skia,ominux/skia,google/skia,Hikari-no-Tenshi/android_external_skia,Jichao/skia,noselhq/skia,nvoron23/skia,todotodoo/skia,Hikari-no-Tenshi/android_external_skia,google/skia,qrealka/skia-hc,HalCanary/skia-hc,HalCanary/skia-hc,rubenvb/skia,Jichao/skia,nvoron23/skia
|
f1f8bd58513848440d76e49cc3fde585bc888ff5
|
gm/dstreadshuffle.cpp
|
gm/dstreadshuffle.cpp
|
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBitmap.h"
#include "SkRandom.h"
#include "SkShader.h"
#include "SkXfermode.h"
namespace skiagm {
/**
* Renders overlapping shapes with colorburn against a checkerboard.
*/
class DstReadShuffle : public GM {
public:
DstReadShuffle() {
this->setBGColor(SkColorSetARGB(0xff, 0xff, 0, 0xff));
}
protected:
enum ShapeType {
kCircle_ShapeType,
kRoundRect_ShapeType,
kRect_ShapeType,
kConvexPath_ShapeType,
kConcavePath_ShapeType,
kText_ShapeType,
kNumShapeTypes
};
SkString onShortName() override {
return SkString("dstreadshuffle");
}
SkISize onISize() override {
return SkISize::Make(kWidth, kHeight);
}
void drawShape(SkCanvas* canvas,
SkPaint* paint,
ShapeType type) {
static const SkRect kRect = SkRect::MakeXYWH(SkIntToScalar(-50), SkIntToScalar(-50),
SkIntToScalar(75), SkIntToScalar(105));
switch (type) {
case kCircle_ShapeType:
canvas->drawCircle(0, 0, 50, *paint);
break;
case kRoundRect_ShapeType:
canvas->drawRoundRect(kRect, SkIntToScalar(10), SkIntToScalar(20), *paint);
break;
case kRect_ShapeType:
canvas->drawRect(kRect, *paint);
break;
case kConvexPath_ShapeType:
if (fConvexPath.isEmpty()) {
SkPoint points[4];
kRect.toQuad(points);
fConvexPath.moveTo(points[0]);
fConvexPath.quadTo(points[1], points[2]);
fConvexPath.quadTo(points[3], points[0]);
SkASSERT(fConvexPath.isConvex());
}
canvas->drawPath(fConvexPath, *paint);
break;
case kConcavePath_ShapeType:
if (fConcavePath.isEmpty()) {
SkPoint points[5] = {{0, SkIntToScalar(-50)} };
SkMatrix rot;
rot.setRotate(SkIntToScalar(360) / 5);
for (int i = 1; i < 5; ++i) {
rot.mapPoints(points + i, points + i - 1, 1);
}
fConcavePath.moveTo(points[0]);
for (int i = 0; i < 5; ++i) {
fConcavePath.lineTo(points[(2 * i) % 5]);
}
fConcavePath.setFillType(SkPath::kEvenOdd_FillType);
SkASSERT(!fConcavePath.isConvex());
}
canvas->drawPath(fConcavePath, *paint);
break;
case kText_ShapeType: {
const char* text = "Hello!";
paint->setTextSize(30);
canvas->drawText(text, strlen(text), 0, 0, *paint);
}
default:
break;
}
}
static SkColor GetColor(SkRandom* random, int i, int nextColor) {
static SkColor colors[] = { SK_ColorRED,
sk_tool_utils::color_to_565(0xFFFF7F00), // Orange
SK_ColorYELLOW,
SK_ColorGREEN,
SK_ColorBLUE,
sk_tool_utils::color_to_565(0xFF4B0082), // indigo
sk_tool_utils::color_to_565(0xFF7F00FF) }; // violet
SkColor color;
int index = nextColor % SK_ARRAY_COUNT(colors);
switch (i) {
case 0:
color = SK_ColorTRANSPARENT;
break;
case 1:
color = SkColorSetARGB(0xff,
SkColorGetR(colors[index]),
SkColorGetG(colors[index]),
SkColorGetB(colors[index]));
break;
default:
uint8_t alpha = 0x80;
color = SkColorSetARGB(alpha,
SkColorGetR(colors[index]),
SkColorGetG(colors[index]),
SkColorGetB(colors[index]));
break;
}
return color;
}
static void SetStyle(SkPaint* p, int style, int width) {
switch (style) {
case 0:
p->setStyle(SkPaint::kStroke_Style);
p->setStrokeWidth((SkScalar)width);
break;
case 1:
p->setStyle(SkPaint::kStrokeAndFill_Style);
p->setStrokeWidth((SkScalar)width);
break;
default:
p->setStyle(SkPaint::kFill_Style);
break;
}
}
void onDraw(SkCanvas* canvas) override {
SkRandom random;
SkScalar y = 100;
for (int i = 0; i < kNumShapeTypes; i++) {
ShapeType shapeType = static_cast<ShapeType>(i);
SkScalar x = 25;
for (int style = 0; style < 3; style++) {
for (int width = 0; width <= 1; width++) {
for (int alpha = 0; alpha <= 2; alpha++) {
for (int r = 0; r <= 5; r++) {
SkColor color = GetColor(&random, alpha, style + width + alpha + r);
SkPaint p;
p.setAntiAlias(true);
p.setColor(color);
// In order to get some batching on the GPU backend we do 2 src over for
// each xfer mode which requires a dst read
p.setXfermodeMode(r % 3 == 0 ? SkXfermode::kLighten_Mode :
SkXfermode::kSrcOver_Mode);
SetStyle(&p, style, width);
canvas->save();
canvas->translate(x, y);
canvas->rotate((SkScalar)(r < 3 ? 10 : 0));
this->drawShape(canvas, &p, shapeType);
canvas->restore();
x += 8;
}
}
}
}
y += 50;
}
}
private:
enum {
kNumShapes = 100,
};
SkAutoTUnref<SkShader> fBG;
SkPath fConcavePath;
SkPath fConvexPath;
static const int kWidth = 900;
static const int kHeight = 400;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new DstReadShuffle; }
static GMRegistry reg(MyFactory);
}
|
/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "gm.h"
#include "SkBitmap.h"
#include "SkRandom.h"
#include "SkShader.h"
#include "SkXfermode.h"
namespace skiagm {
/**
* Renders overlapping shapes with colorburn against a checkerboard.
*/
class DstReadShuffle : public GM {
public:
DstReadShuffle() {
this->setBGColor(SkColorSetARGB(0xff, 0xff, 0, 0xff));
}
protected:
enum ShapeType {
kCircle_ShapeType,
kRoundRect_ShapeType,
kRect_ShapeType,
kConvexPath_ShapeType,
kConcavePath_ShapeType,
kText_ShapeType,
kNumShapeTypes
};
SkString onShortName() override {
return SkString("dstreadshuffle");
}
SkISize onISize() override {
return SkISize::Make(kWidth, kHeight);
}
void drawShape(SkCanvas* canvas,
SkPaint* paint,
ShapeType type) {
static const SkRect kRect = SkRect::MakeXYWH(SkIntToScalar(-50), SkIntToScalar(-50),
SkIntToScalar(75), SkIntToScalar(105));
switch (type) {
case kCircle_ShapeType:
canvas->drawCircle(0, 0, 50, *paint);
break;
case kRoundRect_ShapeType:
canvas->drawRoundRect(kRect, SkIntToScalar(10), SkIntToScalar(20), *paint);
break;
case kRect_ShapeType:
canvas->drawRect(kRect, *paint);
break;
case kConvexPath_ShapeType:
if (fConvexPath.isEmpty()) {
SkPoint points[4];
kRect.toQuad(points);
fConvexPath.moveTo(points[0]);
fConvexPath.quadTo(points[1], points[2]);
fConvexPath.quadTo(points[3], points[0]);
SkASSERT(fConvexPath.isConvex());
}
canvas->drawPath(fConvexPath, *paint);
break;
case kConcavePath_ShapeType:
if (fConcavePath.isEmpty()) {
SkPoint points[5] = {{0, SkIntToScalar(-50)} };
SkMatrix rot;
rot.setRotate(SkIntToScalar(360) / 5);
for (int i = 1; i < 5; ++i) {
rot.mapPoints(points + i, points + i - 1, 1);
}
fConcavePath.moveTo(points[0]);
for (int i = 0; i < 5; ++i) {
fConcavePath.lineTo(points[(2 * i) % 5]);
}
fConcavePath.setFillType(SkPath::kEvenOdd_FillType);
SkASSERT(!fConcavePath.isConvex());
}
canvas->drawPath(fConcavePath, *paint);
break;
case kText_ShapeType: {
const char* text = "Hello!";
paint->setTextSize(30);
sk_tool_utils::set_portable_typeface(paint);
canvas->drawText(text, strlen(text), 0, 0, *paint);
}
default:
break;
}
}
static SkColor GetColor(SkRandom* random, int i, int nextColor) {
static SkColor colors[] = { SK_ColorRED,
sk_tool_utils::color_to_565(0xFFFF7F00), // Orange
SK_ColorYELLOW,
SK_ColorGREEN,
SK_ColorBLUE,
sk_tool_utils::color_to_565(0xFF4B0082), // indigo
sk_tool_utils::color_to_565(0xFF7F00FF) }; // violet
SkColor color;
int index = nextColor % SK_ARRAY_COUNT(colors);
switch (i) {
case 0:
color = SK_ColorTRANSPARENT;
break;
case 1:
color = SkColorSetARGB(0xff,
SkColorGetR(colors[index]),
SkColorGetG(colors[index]),
SkColorGetB(colors[index]));
break;
default:
uint8_t alpha = 0x80;
color = SkColorSetARGB(alpha,
SkColorGetR(colors[index]),
SkColorGetG(colors[index]),
SkColorGetB(colors[index]));
break;
}
return color;
}
static void SetStyle(SkPaint* p, int style, int width) {
switch (style) {
case 0:
p->setStyle(SkPaint::kStroke_Style);
p->setStrokeWidth((SkScalar)width);
break;
case 1:
p->setStyle(SkPaint::kStrokeAndFill_Style);
p->setStrokeWidth((SkScalar)width);
break;
default:
p->setStyle(SkPaint::kFill_Style);
break;
}
}
void onDraw(SkCanvas* canvas) override {
SkRandom random;
SkScalar y = 100;
for (int i = 0; i < kNumShapeTypes; i++) {
ShapeType shapeType = static_cast<ShapeType>(i);
SkScalar x = 25;
for (int style = 0; style < 3; style++) {
for (int width = 0; width <= 1; width++) {
for (int alpha = 0; alpha <= 2; alpha++) {
for (int r = 0; r <= 5; r++) {
SkColor color = GetColor(&random, alpha, style + width + alpha + r);
SkPaint p;
p.setAntiAlias(true);
p.setColor(color);
// In order to get some batching on the GPU backend we do 2 src over for
// each xfer mode which requires a dst read
p.setXfermodeMode(r % 3 == 0 ? SkXfermode::kLighten_Mode :
SkXfermode::kSrcOver_Mode);
SetStyle(&p, style, width);
canvas->save();
canvas->translate(x, y);
canvas->rotate((SkScalar)(r < 3 ? 10 : 0));
this->drawShape(canvas, &p, shapeType);
canvas->restore();
x += 8;
}
}
}
}
y += 50;
}
}
private:
enum {
kNumShapes = 100,
};
SkAutoTUnref<SkShader> fBG;
SkPath fConcavePath;
SkPath fConvexPath;
static const int kWidth = 900;
static const int kHeight = 400;
typedef GM INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static GM* MyFactory(void*) { return new DstReadShuffle; }
static GMRegistry reg(MyFactory);
}
|
fix dstreadshuffle text portable gm
|
fix dstreadshuffle text portable gm
[email protected]
Review URL: https://codereview.chromium.org/1259093004
|
C++
|
bsd-3-clause
|
HalCanary/skia-hc,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,noselhq/skia,HalCanary/skia-hc,vanish87/skia,noselhq/skia,noselhq/skia,rubenvb/skia,google/skia,ominux/skia,tmpvar/skia.cc,tmpvar/skia.cc,qrealka/skia-hc,vanish87/skia,HalCanary/skia-hc,tmpvar/skia.cc,HalCanary/skia-hc,noselhq/skia,google/skia,google/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,todotodoo/skia,noselhq/skia,tmpvar/skia.cc,ominux/skia,qrealka/skia-hc,shahrzadmn/skia,nvoron23/skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,todotodoo/skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,tmpvar/skia.cc,noselhq/skia,vanish87/skia,ominux/skia,ominux/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,google/skia,qrealka/skia-hc,qrealka/skia-hc,shahrzadmn/skia,todotodoo/skia,Hikari-no-Tenshi/android_external_skia,nvoron23/skia,ominux/skia,todotodoo/skia,ominux/skia,nvoron23/skia,rubenvb/skia,vanish87/skia,todotodoo/skia,aosp-mirror/platform_external_skia,todotodoo/skia,rubenvb/skia,shahrzadmn/skia,rubenvb/skia,tmpvar/skia.cc,rubenvb/skia,google/skia,HalCanary/skia-hc,qrealka/skia-hc,google/skia,ominux/skia,shahrzadmn/skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,tmpvar/skia.cc,aosp-mirror/platform_external_skia,rubenvb/skia,rubenvb/skia,shahrzadmn/skia,nvoron23/skia,vanish87/skia,Hikari-no-Tenshi/android_external_skia,google/skia,ominux/skia,noselhq/skia,Hikari-no-Tenshi/android_external_skia,shahrzadmn/skia,shahrzadmn/skia,nvoron23/skia,rubenvb/skia,todotodoo/skia,tmpvar/skia.cc,shahrzadmn/skia,vanish87/skia,todotodoo/skia,todotodoo/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,shahrzadmn/skia,aosp-mirror/platform_external_skia,qrealka/skia-hc,noselhq/skia,noselhq/skia,tmpvar/skia.cc,google/skia,ominux/skia,nvoron23/skia,nvoron23/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,vanish87/skia,nvoron23/skia,aosp-mirror/platform_external_skia,google/skia,rubenvb/skia,qrealka/skia-hc,nvoron23/skia,vanish87/skia,qrealka/skia-hc,HalCanary/skia-hc,vanish87/skia
|
6ec629491c82643792a80d178ceb550a3d43dd21
|
plugin/plugin.cpp
|
plugin/plugin.cpp
|
// Copyright (c) 2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cassert>
#include <cstddef>
#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include <amx/amx.h>
#include "jit.h"
#include "jump-x86.h"
#include "plugin.h"
#include "version.h"
#ifdef WIN32
#include <Windows.h>
#else
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1 // for dladdr()
#endif
#include <dlfcn.h>
#endif
extern void *pAMXFunctions;
typedef void (*logprintf_t)(const char *format, ...);
static logprintf_t logprintf;
typedef std::map<AMX*, jit::Jitter*> AmxToJitterMap;
static AmxToJitterMap amx2jitter;
static JumpX86 amx_Exec_hook;
static cell *opcodeTable = 0;
static std::string InstrToString(const jit::AmxInstruction &instr) {
std::stringstream stream;
if (instr.getName() != 0) {
stream << instr.getName();
} else {
stream << std::setw(8) << std::setfill('0') << std::hex << instr.getOpcode();
}
std::vector<cell> opers = instr.getOperands();
for (std::vector<cell>::const_iterator it = opers.begin(); it != opers.end(); ++it) {
stream << ' ' << std::setw(8) << std::setfill('0') << std::hex << *it;
}
return stream.str();
}
static void CompileError(const jit::AmxVm &vm, const jit::AmxInstruction &instr) {
logprintf("JIT compilation error at %08x:", instr.getAddress());
logprintf(" %s", InstrToString(instr).c_str());
}
static void RuntimeError(int errorCode) {
static const char *errorStrings[] = {
/* AMX_ERR_NONE */ "(none)",
/* AMX_ERR_EXIT */ "Forced exit",
/* AMX_ERR_ASSERT */ "Assertion failed",
/* AMX_ERR_STACKERR */ "Stack/heap collision (insufficient stack size)",
/* AMX_ERR_BOUNDS */ "Array index out of bounds",
/* AMX_ERR_MEMACCESS */ "Invalid memory access",
/* AMX_ERR_INVINSTR */ "Invalid instruction",
/* AMX_ERR_STACKLOW */ "Stack underflow",
/* AMX_ERR_HEAPLOW */ "Heap underflow",
/* AMX_ERR_CALLBACK */ "No (valid) native function callback",
/* AMX_ERR_NATIVE */ "Native function failed",
/* AMX_ERR_DIVIDE */ "Divide by zero",
/* AMX_ERR_SLEEP */ "(sleep mode)",
/* 13 */ "(reserved)",
/* 14 */ "(reserved)",
/* 15 */ "(reserved)",
/* AMX_ERR_MEMORY */ "Out of memory",
/* AMX_ERR_FORMAT */ "Invalid/unsupported P-code file format",
/* AMX_ERR_VERSION */ "File is for a newer version of the AMX",
/* AMX_ERR_NOTFOUND */ "File or function is not found",
/* AMX_ERR_INDEX */ "Invalid index parameter (bad entry point)",
/* AMX_ERR_DEBUG */ "Debugger cannot run",
/* AMX_ERR_INIT */ "AMX not initialized (or doubly initialized)",
/* AMX_ERR_USERDATA */ "Unable to set user data field (table full)",
/* AMX_ERR_INIT_JIT */ "Cannot initialize the JIT",
/* AMX_ERR_PARAMS */ "Parameter error",
/* AMX_ERR_DOMAIN */ "Domain error, expression result does not fit in range",
/* AMX_ERR_GENERAL */ "General error (unknown or unspecific error)"
};
logprintf("JIT runtime error %d: \"%s\"", errorCode, errorStrings[errorCode]);
}
static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {
#if defined __GNUC__ && !defined WIN32
if ((amx->flags & AMX_FLAG_BROWSE) == AMX_FLAG_BROWSE) {
assert(::opcodeTable != 0);
*retval = reinterpret_cast<cell>(::opcodeTable);
return AMX_ERR_NONE;
}
#endif
AmxToJitterMap::iterator iterator = ::amx2jitter.find(amx);
if (iterator == ::amx2jitter.end()) {
// Compilation previously failed, call normal amx_Exec().
JumpX86::ScopedRemove r(&amx_Exec_hook);
return amx_Exec(amx, retval, index);
} else {
jit::Jitter *jitter = iterator->second;
int error = jitter->exec(index, retval);
if (error != AMX_ERR_NONE) {
RuntimeError(error);
}
return error;
}
}
static std::string GetModuleNameBySymbol(void *symbol) {
char module[FILENAME_MAX] = "";
if (symbol != 0) {
#ifdef WIN32
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(symbol, &mbi, sizeof(mbi));
GetModuleFileName((HMODULE)mbi.AllocationBase, module, FILENAME_MAX);
#else
Dl_info info;
dladdr(symbol, &info);
strcpy(module, info.dli_fname);
#endif
}
return std::string(module);
}
static std::string GetFileName(const std::string &path) {
std::string::size_type lastSep = path.find_last_of("/\\");
if (lastSep != std::string::npos) {
return path.substr(lastSep + 1);
}
return path;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
pAMXFunctions = reinterpret_cast<void*>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
void *funAddr = JumpX86::GetTargetAddress(((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec]);
if (funAddr != 0) {
std::string module = GetFileName(GetModuleNameBySymbol(funAddr));
if (!module.empty() && module != "samp-server.exe" && module != "samp03svr") {
logprintf(" JIT must be loaded before %s", module.c_str());
return false;
}
}
logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING);
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
for (AmxToJitterMap::iterator it = amx2jitter.begin(); it != amx2jitter.end(); ++it) {
delete it->second;
}
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
typedef int (AMXAPI *amx_Exec_t)(AMX *amx, cell *retval, int index);
amx_Exec_t amx_Exec = (amx_Exec_t)((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec];
typedef int (AMXAPI *amx_GetAddr_t)(AMX *amx, cell amx_addr, cell **phys_addr);
amx_GetAddr_t amx_GetAddr = (amx_GetAddr_t)((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetAddr];
#if defined __GNUC__ && !defined WIN32
// Get opcode list before we hook amx_Exec().
if (::opcodeTable == 0) {
amx->flags |= AMX_FLAG_BROWSE;
amx_Exec(amx, reinterpret_cast<cell*>(&::opcodeTable), 0);
amx->flags &= ~AMX_FLAG_BROWSE;
}
#endif
jit::Jitter *jitter = new jit::Jitter(amx, ::opcodeTable);
if (!jitter->compile(CompileError)) {
delete jitter;
} else {
::amx2jitter.insert(std::make_pair(amx, jitter));
}
if (!amx_Exec_hook.IsInstalled()) {
amx_Exec_hook.Install(
(void*)amx_Exec,
(void*)amx_Exec_JIT);
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
AmxToJitterMap::iterator it = amx2jitter.find(amx);
if (it != amx2jitter.end()) {
delete it->second;
amx2jitter.erase(it);
}
return AMX_ERR_NONE;
}
|
// Copyright (c) 2012, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <cassert>
#include <cstddef>
#include <iomanip>
#include <map>
#include <sstream>
#include <string>
#include "jit.h"
#include "jump-x86.h"
#include "plugin.h"
#include "version.h"
#ifdef WIN32
#include <Windows.h>
#else
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1 // for dladdr()
#endif
#include <dlfcn.h>
#endif
extern void *pAMXFunctions;
typedef void (*logprintf_t)(const char *format, ...);
static logprintf_t logprintf;
typedef std::map<AMX*, jit::Jitter*> AmxToJitterMap;
static AmxToJitterMap amx2jitter;
static JumpX86 amx_Exec_hook;
static cell *opcodeTable = 0;
static int AMXAPI amx_Exec_JIT(AMX *amx, cell *retval, int index) {
#if defined __GNUC__ && !defined WIN32
if ((amx->flags & AMX_FLAG_BROWSE) == AMX_FLAG_BROWSE) {
assert(::opcodeTable != 0);
*retval = reinterpret_cast<cell>(::opcodeTable);
return AMX_ERR_NONE;
}
#endif
AmxToJitterMap::iterator iterator = ::amx2jitter.find(amx);
if (iterator == ::amx2jitter.end()) {
// Compilation previously failed, call normal amx_Exec().
JumpX86::ScopedRemove r(&amx_Exec_hook);
return amx_Exec(amx, retval, index);
} else {
jit::Jitter *jitter = iterator->second;
return jitter->exec(index, retval);
}
}
static std::string GetModuleNameBySymbol(void *symbol) {
char module[FILENAME_MAX] = "";
if (symbol != 0) {
#ifdef WIN32
MEMORY_BASIC_INFORMATION mbi;
VirtualQuery(symbol, &mbi, sizeof(mbi));
GetModuleFileName((HMODULE)mbi.AllocationBase, module, FILENAME_MAX);
#else
Dl_info info;
dladdr(symbol, &info);
strcpy(module, info.dli_fname);
#endif
}
return std::string(module);
}
static std::string GetFileName(const std::string &path) {
std::string::size_type lastSep = path.find_last_of("/\\");
if (lastSep != std::string::npos) {
return path.substr(lastSep + 1);
}
return path;
}
static std::string InstrToString(const jit::AmxInstruction &instr) {
std::stringstream ss;
const char *name = instr.getName();
if (name != 0) {
ss << instr.getName();
} else {
ss << std::setw(8) << std::setfill('0') << std::hex << instr.getOpcode();
}
std::vector<cell> opers = instr.getOperands();
for (std::vector<cell>::const_iterator it = opers.begin(); it != opers.end(); ++it) {
ss << ' ' << std::setw(8) << std::setfill('0') << std::hex << *it;
}
return ss.str();
}
static void CompileError(const jit::AmxVm &vm, const jit::AmxInstruction &instr) {
logprintf("JIT failed to compile instruction at %08x:", instr.getAddress());
logprintf(" %s", InstrToString(instr).c_str());
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
pAMXFunctions = reinterpret_cast<void*>(ppData[PLUGIN_DATA_AMX_EXPORTS]);
void *funAddr = JumpX86::GetTargetAddress(((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec]);
if (funAddr != 0) {
std::string module = GetFileName(GetModuleNameBySymbol(funAddr));
if (!module.empty() && module != "samp-server.exe" && module != "samp03svr") {
logprintf(" JIT must be loaded before %s", module.c_str());
return false;
}
}
logprintf(" JIT plugin v%s is OK.", PLUGIN_VERSION_STRING);
return true;
}
PLUGIN_EXPORT void PLUGIN_CALL Unload() {
for (AmxToJitterMap::iterator it = amx2jitter.begin(); it != amx2jitter.end(); ++it) {
delete it->second;
}
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
typedef int (AMXAPI *amx_Exec_t)(AMX *amx, cell *retval, int index);
amx_Exec_t amx_Exec = (amx_Exec_t)((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec];
typedef int (AMXAPI *amx_GetAddr_t)(AMX *amx, cell amx_addr, cell **phys_addr);
amx_GetAddr_t amx_GetAddr = (amx_GetAddr_t)((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_GetAddr];
#if defined __GNUC__ && !defined WIN32
// Get opcode list before we hook amx_Exec().
if (::opcodeTable == 0) {
amx->flags |= AMX_FLAG_BROWSE;
amx_Exec(amx, reinterpret_cast<cell*>(&::opcodeTable), 0);
amx->flags &= ~AMX_FLAG_BROWSE;
}
#endif
jit::Jitter *jitter = new jit::Jitter(amx, ::opcodeTable);
if (!jitter->compile(CompileError)) {
delete jitter;
} else {
::amx2jitter.insert(std::make_pair(amx, jitter));
}
if (!amx_Exec_hook.IsInstalled()) {
amx_Exec_hook.Install(
(void*)amx_Exec,
(void*)amx_Exec_JIT);
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
AmxToJitterMap::iterator it = amx2jitter.find(amx);
if (it != amx2jitter.end()) {
delete it->second;
amx2jitter.erase(it);
}
return AMX_ERR_NONE;
}
|
Revert "Make JIT report runtime errors"
|
Revert "Make JIT report runtime errors"
This reverts commit a9ef7652deba3ed52b5127b7e230b8596852cd4e.
|
C++
|
bsd-2-clause
|
oscar-broman/samp-plugin-jit,Zeex/samp-plugin-jit,oscar-broman/samp-plugin-jit,Zeex/samp-plugin-jit
|
d69ca19e48ff3d6ce6a621045d24f2ec17f88ea7
|
plugin/plugin.cpp
|
plugin/plugin.cpp
|
// Copyright (c) 2011-2013, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <fstream>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <subhook.h>
#include <amx/amx.h>
#include <amx_profiler/call_graph_writer_dot.h>
#include <amx_profiler/debug_info.h>
#include <amx_profiler/statistics_writer_html.h>
#include <amx_profiler/statistics_writer_text.h>
#include <amx_profiler/statistics_writer_json.h>
#include <amx_profiler/profiler.h>
#include "amxpath.h"
#include "configreader.h"
#include "plugin.h"
#include "pluginversion.h"
typedef void (*logprintf_t)(const char *format, ...);
extern void *pAMXFunctions;
static logprintf_t logprintf;
typedef std::map<AMX*, AMX_DEBUG> AmxToAmxDebugMap;
static AmxToAmxDebugMap old_debug_hooks;
typedef std::map<AMX*, amx_profiler::Profiler*> AmxToProfilerMap;
static AmxToProfilerMap profilers;
typedef std::map<AMX*, amx_profiler::DebugInfo*> AmxToDebugInfoMap;
static AmxToDebugInfoMap debug_infos;
// Plugin settings and their defauls.
namespace cfg {
bool profile_gamemode = false;
std::string profile_filterscripts = "";
std::string profile_format = "html";
bool call_graph = false;
std::string call_graph_format = "dot";
}
static void PrintException(const std::exception &e) {
logprintf("[profiler] Error: %s", e.what());
}
namespace hooks {
SubHook amx_Exec_hook;
SubHook amx_Callback_hook;
int AMXAPI amx_Debug(AMX *amx) {
amx_profiler::Profiler *profiler = ::profilers[amx];
if (profiler) {
try {
profiler->DebugHook();
} catch (const std::exception &e) {
PrintException(e);
}
}
AmxToAmxDebugMap::const_iterator iterator = old_debug_hooks.find(amx);
if (iterator != old_debug_hooks.end()) {
if (iterator->second != 0) {
return (iterator->second)(amx);
}
}
return AMX_ERR_NONE;
}
int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) {
SubHook::ScopedRemove r(&amx_Callback_hook);
SubHook::ScopedInstall i(&amx_Exec_hook);
amx_profiler::Profiler *profiler = ::profilers[amx];
if (profiler != 0) {
try {
return profiler->CallbackHook(index, result, params);
} catch (const std::exception &e) {
PrintException(e);
}
}
return ::amx_Callback(amx, index, result, params);
}
int AMXAPI amx_Exec(AMX *amx, cell *retval, int index) {
SubHook::ScopedRemove r(&amx_Exec_hook);
SubHook::ScopedInstall i(&amx_Callback_hook);
amx_profiler::Profiler *profiler = ::profilers[amx];
if (profiler != 0) {
try {
return profiler->ExecHook(retval, index);
} catch (const std::exception &e) {
PrintException(e);
}
}
return ::amx_Exec(amx, retval, index);
}
} // namespace hooks
static void ToLower(std::string &s) {
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
}
static std::string GetAmxPath(AMX *amx) {
// Has to be static to make caching work in AmxUnload().
static AmxPathFinder finder;
finder.AddSearchDirectory("gamemodes");
finder.AddSearchDirectory("filterscripts");
return finder.FindAmxPath(amx);
}
static std::string ToUnixPath(const std::string &path) {
std::string fsPath = path;
std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
return fsPath;
}
static bool IsGameMode(const std::string &amx_name) {
return ToUnixPath(amx_name).find("gamemodes/") != std::string::npos;
}
static bool IsFilterScript(const std::string &amx_name) {
return ToUnixPath(amx_name).find("filterscripts/") != std::string::npos;
}
static bool WantsProfiler(const std::string &amx_name) {
std::string good_amx_name = ToUnixPath(amx_name);
if (IsGameMode(good_amx_name)) {
if (cfg::profile_gamemode) {
return true;
}
} else if (IsFilterScript(good_amx_name)) {
std::string fs_list = cfg::profile_filterscripts;
std::stringstream fs_stream(fs_list);
do {
std::string fs_name;
fs_stream >> fs_name;
if (good_amx_name == "filterscripts/" + fs_name + ".amx"
|| good_amx_name == "filterscripts/" + fs_name) {
return true;
}
} while (!fs_stream.eof());
}
return false;
}
template<typename Map, typename Key>
void DeleteMapEntry(Map &map, const Key &key) {
typename Map::iterator iterator = map.find(key);
if (iterator != map.end()) {
delete iterator->second;
map.erase(iterator);
}
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
static void *AMXAPI amx_Align_stub(void *v) {
return v;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)amx_Align_stub;
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)amx_Align_stub;
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)amx_Align_stub;
hooks::amx_Exec_hook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec],
(void*)hooks::amx_Exec);
hooks::amx_Callback_hook.Install(
((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback],
(void*)hooks::amx_Callback);
// Read plugin settings from server.cfg.
ConfigReader server_cfg("server.cfg");
server_cfg.GetOption("profile_gamemode", cfg::profile_gamemode);
server_cfg.GetOption("profile_filterscripts", cfg::profile_filterscripts);
server_cfg.GetOption("profile_format", cfg::profile_format);
server_cfg.GetOption("call_graph", cfg::call_graph);
server_cfg.GetOption("call_graph_format", cfg::call_graph_format);
logprintf(" Profiler v" PROJECT_VERSION_STRING " is OK.");
return true;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
std::string filename = GetAmxPath(amx);
if (filename.empty()) {
logprintf("[profiler] Failed to find corresponding .amx file");
return AMX_ERR_NONE;
}
if (!WantsProfiler(filename)) {
return AMX_ERR_NONE;
}
try {
amx_profiler::DebugInfo *debug_info = 0;
if (amx_profiler::HaveDebugInfo(amx)) {
debug_info = new amx_profiler::DebugInfo(filename);
if (debug_info->is_loaded()) {
logprintf("[profiler] Loaded debug info from '%s'", filename.c_str());
::debug_infos[amx] = debug_info;
} else {
logprintf("[profiler] Error loading debug info from '%s'",
filename.c_str());
delete debug_info;
}
}
amx_profiler::Profiler *profiler = new amx_profiler::Profiler(amx,
debug_info);
profiler->set_call_graph_enabled(cfg::call_graph);
if (debug_info != 0) {
logprintf("[profiler] Attached profiler to '%s'", filename.c_str());
} else {
logprintf("[profiler] Attached profiler to '%s' (no debug info)",
filename.c_str());
}
::old_debug_hooks[amx] = amx->debug;
amx_SetDebugHook(amx, hooks::amx_Debug);
::profilers[amx] = profiler;
}
catch (const std::exception &e) {
PrintException(e);
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
try {
amx_profiler::Profiler *profiler = ::profilers[amx];
if (profiler != 0) {
std::string amx_path = GetAmxPath(amx);
std::string amx_name = std::string(amx_path, 0,
amx_path.find_last_of("."));
ToLower(cfg::profile_format);
std::string profile_filename = amx_name + "-profile." +
cfg::profile_format;
std::ofstream profile_stream(profile_filename.c_str());
if (profile_stream.is_open()) {
amx_profiler::StatisticsWriter *writer = 0;
if (cfg::profile_format == "html") {
writer = new amx_profiler::StatisticsWriterHtml;
} else if (cfg::profile_format == "txt" ||
cfg::profile_format == "text") {
writer = new amx_profiler::StatisticsWriterText;
} else if (cfg::profile_format == "json") {
writer = new amx_profiler::StatisticsWriterJson;
} else {
logprintf("[profiler] Unrecognized profile format '%s'",
cfg::profile_format.c_str());
}
if (writer != 0) {
logprintf("[profiler] Writing profile to '%s'",
profile_filename.c_str());
writer->set_stream(&profile_stream);
writer->set_script_name(amx_path);
writer->set_print_date(true);
writer->set_print_run_time(true);
writer->Write(profiler->stats());
delete writer;
}
profile_stream.close();
} else {
logprintf("[profiler]: Error opening file '%s'",
profile_filename.c_str());
}
if (cfg::call_graph) {
ToLower(cfg::call_graph_format);
std::string call_graph_filename = amx_name + "-calls." +
cfg::call_graph_format;
std::ofstream call_graph_stream(call_graph_filename.c_str());
if (call_graph_stream.is_open()) {
amx_profiler::CallGraphWriterDot *writer = 0;
if (cfg::call_graph_format == "dot") {
writer = new amx_profiler::CallGraphWriterDot;
} else {
logprintf("[profiler] Unrecognized call graph format '%s'",
cfg::call_graph_format.c_str());
}
if (writer != 0) {
logprintf("[profiler] Writing call graph to '%s'",
call_graph_filename.c_str());
writer->set_stream(&call_graph_stream);
writer->set_script_name(amx_path);
writer->set_root_node_name("SA-MP Server");
writer->Write(profiler->call_graph());
delete writer;
}
call_graph_stream.close();
} else {
logprintf("[profiler]: Error opening file '%s'",
call_graph_filename.c_str());
}
}
}
}
catch (const std::exception &e) {
PrintException(e);
}
DeleteMapEntry(::profilers, amx);
DeleteMapEntry(::debug_infos, amx);
return AMX_ERR_NONE;
}
|
// Copyright (c) 2011-2013, Zeex
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <fstream>
#include <list>
#include <map>
#include <sstream>
#include <string>
#include <subhook.h>
#include <amx/amx.h>
#include <amx_profiler/call_graph_writer_dot.h>
#include <amx_profiler/debug_info.h>
#include <amx_profiler/statistics_writer_html.h>
#include <amx_profiler/statistics_writer_text.h>
#include <amx_profiler/statistics_writer_json.h>
#include <amx_profiler/profiler.h>
#include "amxpath.h"
#include "configreader.h"
#include "plugin.h"
#include "pluginversion.h"
typedef void (*logprintf_t)(const char *format, ...);
extern void *pAMXFunctions;
static logprintf_t logprintf;
typedef std::map<AMX*, AMX_DEBUG> AmxToAmxDebugMap;
static AmxToAmxDebugMap old_debug_hooks;
typedef std::map<AMX*, amx_profiler::Profiler*> AmxToProfilerMap;
static AmxToProfilerMap profilers;
typedef std::map<AMX*, amx_profiler::DebugInfo*> AmxToDebugInfoMap;
static AmxToDebugInfoMap debug_infos;
// Plugin settings and their defauls.
namespace cfg {
bool profile_gamemode = false;
std::string profile_filterscripts = "";
std::string profile_format = "html";
bool call_graph = false;
std::string call_graph_format = "dot";
}
static void PrintException(const std::exception &e) {
logprintf("[profiler] Error: %s", e.what());
}
namespace hooks {
SubHook amx_Exec_hook;
SubHook amx_Callback_hook;
int AMXAPI amx_Debug(AMX *amx) {
amx_profiler::Profiler *profiler = ::profilers[amx];
if (profiler) {
try {
profiler->DebugHook();
} catch (const std::exception &e) {
PrintException(e);
}
}
AmxToAmxDebugMap::const_iterator iterator = old_debug_hooks.find(amx);
if (iterator != old_debug_hooks.end()) {
if (iterator->second != 0) {
return (iterator->second)(amx);
}
}
return AMX_ERR_NONE;
}
int AMXAPI amx_Callback(AMX *amx, cell index, cell *result, cell *params) {
SubHook::ScopedRemove r(&amx_Callback_hook);
SubHook::ScopedInstall i(&amx_Exec_hook);
amx_profiler::Profiler *profiler = ::profilers[amx];
if (profiler != 0) {
try {
return profiler->CallbackHook(index, result, params);
} catch (const std::exception &e) {
PrintException(e);
}
}
return ::amx_Callback(amx, index, result, params);
}
int AMXAPI amx_Exec(AMX *amx, cell *retval, int index) {
SubHook::ScopedRemove r(&amx_Exec_hook);
SubHook::ScopedInstall i(&amx_Callback_hook);
amx_profiler::Profiler *profiler = ::profilers[amx];
if (profiler != 0) {
try {
return profiler->ExecHook(retval, index);
} catch (const std::exception &e) {
PrintException(e);
}
}
return ::amx_Exec(amx, retval, index);
}
} // namespace hooks
static void ToLower(std::string &s) {
std::transform(s.begin(), s.end(), s.begin(), ::tolower);
}
static std::string GetAmxPath(AMX *amx) {
// Has to be static to make caching work in AmxUnload().
static AmxPathFinder finder;
finder.AddSearchDirectory("gamemodes");
finder.AddSearchDirectory("filterscripts");
return finder.FindAmxPath(amx);
}
static std::string ToUnixPath(const std::string &path) {
std::string fsPath = path;
std::replace(fsPath.begin(), fsPath.end(), '\\', '/');
return fsPath;
}
static bool IsGameMode(const std::string &amx_name) {
return ToUnixPath(amx_name).find("gamemodes/") != std::string::npos;
}
static bool IsFilterScript(const std::string &amx_name) {
return ToUnixPath(amx_name).find("filterscripts/") != std::string::npos;
}
static bool WantsProfiler(const std::string &amx_name) {
std::string good_amx_name = ToUnixPath(amx_name);
if (IsGameMode(good_amx_name)) {
if (cfg::profile_gamemode) {
return true;
}
} else if (IsFilterScript(good_amx_name)) {
std::string fs_list = cfg::profile_filterscripts;
std::stringstream fs_stream(fs_list);
do {
std::string fs_name;
fs_stream >> fs_name;
if (good_amx_name == "filterscripts/" + fs_name + ".amx"
|| good_amx_name == "filterscripts/" + fs_name) {
return true;
}
} while (!fs_stream.eof());
}
return false;
}
template<typename Map, typename Key>
void DeleteMapEntry(Map &map, const Key &key) {
typename Map::iterator iterator = map.find(key);
if (iterator != map.end()) {
delete iterator->second;
map.erase(iterator);
}
}
template<typename Func>
void *FunctionToVoidPtr(Func func) {
return (void*)func;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() {
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
static void *AMXAPI amx_Align_stub(void *v) {
return v;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) {
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
void **exports = reinterpret_cast<void**>(pAMXFunctions);
exports[PLUGIN_AMX_EXPORT_Align16] = FunctionToVoidPtr(amx_Align_stub);
exports[PLUGIN_AMX_EXPORT_Align32] = FunctionToVoidPtr(amx_Align_stub);
exports[PLUGIN_AMX_EXPORT_Align64] = FunctionToVoidPtr(amx_Align_stub);
hooks::amx_Exec_hook.Install(exports[PLUGIN_AMX_EXPORT_Exec],
FunctionToVoidPtr(hooks::amx_Exec));
hooks::amx_Callback_hook.Install(exports[PLUGIN_AMX_EXPORT_Callback],
FunctionToVoidPtr(hooks::amx_Callback));
ConfigReader server_cfg("server.cfg");
server_cfg.GetOption("profile_gamemode", cfg::profile_gamemode);
server_cfg.GetOption("profile_filterscripts", cfg::profile_filterscripts);
server_cfg.GetOption("profile_format", cfg::profile_format);
server_cfg.GetOption("call_graph", cfg::call_graph);
server_cfg.GetOption("call_graph_format", cfg::call_graph_format);
logprintf(" Profiler v" PROJECT_VERSION_STRING " is OK.");
return true;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) {
std::string filename = GetAmxPath(amx);
if (filename.empty()) {
logprintf("[profiler] Failed to find corresponding .amx file");
return AMX_ERR_NONE;
}
if (!WantsProfiler(filename)) {
return AMX_ERR_NONE;
}
try {
amx_profiler::DebugInfo *debug_info = 0;
if (amx_profiler::HaveDebugInfo(amx)) {
debug_info = new amx_profiler::DebugInfo(filename);
if (debug_info->is_loaded()) {
logprintf("[profiler] Loaded debug info from '%s'", filename.c_str());
::debug_infos[amx] = debug_info;
} else {
logprintf("[profiler] Error loading debug info from '%s'",
filename.c_str());
delete debug_info;
}
}
amx_profiler::Profiler *profiler = new amx_profiler::Profiler(amx,
debug_info);
profiler->set_call_graph_enabled(cfg::call_graph);
if (debug_info != 0) {
logprintf("[profiler] Attached profiler to '%s'", filename.c_str());
} else {
logprintf("[profiler] Attached profiler to '%s' (no debug info)",
filename.c_str());
}
::old_debug_hooks[amx] = amx->debug;
amx_SetDebugHook(amx, hooks::amx_Debug);
::profilers[amx] = profiler;
}
catch (const std::exception &e) {
PrintException(e);
}
return AMX_ERR_NONE;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) {
try {
amx_profiler::Profiler *profiler = ::profilers[amx];
if (profiler != 0) {
std::string amx_path = GetAmxPath(amx);
std::string amx_name = std::string(amx_path, 0,
amx_path.find_last_of("."));
ToLower(cfg::profile_format);
std::string profile_filename = amx_name + "-profile." +
cfg::profile_format;
std::ofstream profile_stream(profile_filename.c_str());
if (profile_stream.is_open()) {
amx_profiler::StatisticsWriter *writer = 0;
if (cfg::profile_format == "html") {
writer = new amx_profiler::StatisticsWriterHtml;
} else if (cfg::profile_format == "txt" ||
cfg::profile_format == "text") {
writer = new amx_profiler::StatisticsWriterText;
} else if (cfg::profile_format == "json") {
writer = new amx_profiler::StatisticsWriterJson;
} else {
logprintf("[profiler] Unrecognized profile format '%s'",
cfg::profile_format.c_str());
}
if (writer != 0) {
logprintf("[profiler] Writing profile to '%s'",
profile_filename.c_str());
writer->set_stream(&profile_stream);
writer->set_script_name(amx_path);
writer->set_print_date(true);
writer->set_print_run_time(true);
writer->Write(profiler->stats());
delete writer;
}
profile_stream.close();
} else {
logprintf("[profiler]: Error opening file '%s'",
profile_filename.c_str());
}
if (cfg::call_graph) {
ToLower(cfg::call_graph_format);
std::string call_graph_filename = amx_name + "-calls." +
cfg::call_graph_format;
std::ofstream call_graph_stream(call_graph_filename.c_str());
if (call_graph_stream.is_open()) {
amx_profiler::CallGraphWriterDot *writer = 0;
if (cfg::call_graph_format == "dot") {
writer = new amx_profiler::CallGraphWriterDot;
} else {
logprintf("[profiler] Unrecognized call graph format '%s'",
cfg::call_graph_format.c_str());
}
if (writer != 0) {
logprintf("[profiler] Writing call graph to '%s'",
call_graph_filename.c_str());
writer->set_stream(&call_graph_stream);
writer->set_script_name(amx_path);
writer->set_root_node_name("SA-MP Server");
writer->Write(profiler->call_graph());
delete writer;
}
call_graph_stream.close();
} else {
logprintf("[profiler]: Error opening file '%s'",
call_graph_filename.c_str());
}
}
}
}
catch (const std::exception &e) {
PrintException(e);
}
DeleteMapEntry(::profilers, amx);
DeleteMapEntry(::debug_infos, amx);
return AMX_ERR_NONE;
}
|
Add FunctionToVoidPtr()
|
Add FunctionToVoidPtr()
|
C++
|
bsd-2-clause
|
Zeex/samp-plugin-profiler,Zeex/samp-plugin-profiler
|
ec60b29271f9619ad510723ee24d9cf1ebcf924e
|
applications/BVHApp/JacobianCov.cpp
|
applications/BVHApp/JacobianCov.cpp
|
#include "JacobianCov.h"
#define USINGCOV
JacobianCov::~JacobianCov(void)
{
}
void JacobianCov::solveOneStep(Skeleton* chain, std::vector<Vector3_>& targets)
{
chain->update();
int tries = 0;
MatrixX_ jacobian = chain->m_jacobian;
VectorX_ distance(jacobian.rows());
#ifdef USINGCOV
/*VectorX_ rotation = VectorX_::Zero(chain->m_dims.size());
for(int i = 0; i < chain->m_dims.size(); ++i)
{
rotation[i] = chain->m_dim_values[i];
}*/
if(!m_defined)
{
m_mu = VectorX_::Zero(chain->m_dims.size());
VectorX_ variance = VectorX_::Zero(chain->m_dims.size());
m_cov = MatrixX_::Identity(chain->m_dims.size(), chain->m_dims.size());
m_invcov = m_cov.inverse();
m_defined = true;
}
similarIndex(last_state);
#endif
for(int ei = 0; ei < chain->m_endeffectors.size(); ++ei)
{
int endeffectorIdx = chain->m_endeffectors[ei];
Vector3_& endpos = chain->m_joint_globalPositions[endeffectorIdx];
Vector3_ dis = (targets[ei]-endpos);
distance(ei * 3 + 0) = dis(0);
distance(ei * 3 + 1) = dis(1);
distance(ei * 3 + 2) = dis(2);
/*for(unsigned int j = 0; j < 3; ++j)
{
Skeleton::Dim& dim = chain->m_dims[j];
Vector3_ axis = chain->m_dim_axis[dim.m_idx];
int lastDim = dim.m_lastIdx;
if(lastDim >= 0)
{
axis = chain->m_dim_globalOrientations[lastDim] * axis;
}
Vector3_ axisXYZgradient = axis;
jacobian(ei * 3 + 0, j) = axisXYZgradient(0) * 0.00001;
jacobian(ei * 3 + 1, j) = axisXYZgradient(1) * 0.00001;
jacobian(ei * 3 + 2, j) = axisXYZgradient(2) * 0.00001;
}*/
for(unsigned int j = chain->m_startDim4IK; j < chain->m_dims.size(); ++j)
{
if(chain->m_jacobian(ei * 3 + 0, j) < 0.1) continue;
Skeleton::Dim& dim = chain->m_dims[j];
Vector3_& jointPos = chain->m_dim_globalPositions[dim.m_idx];
Vector3_ boneVector = endpos - jointPos;
if(boneVector.norm() == 0)
{
continue;
}
//boneVector.normalize();
Vector3_ axis = chain->m_dim_axis[dim.m_idx];
int lastDim = dim.m_lastIdx;
if(lastDim >= 0)
{
axis = chain->m_dim_globalOrientations[lastDim] * axis;
}
Vector3_ axisXYZgradient = axis.cross(boneVector);
jacobian(ei * 3 + 0, j) = axisXYZgradient(0);
jacobian(ei * 3 + 1, j) = axisXYZgradient(1);
jacobian(ei * 3 + 2, j) = axisXYZgradient(2);
}
}
#ifdef USINGCOV
MatrixX_ jacobianTranspose = jacobian.transpose();
MatrixX_ jtj = jacobianTranspose * jacobian;
MatrixX_ lamdaI = MatrixX_::Identity(jtj.rows(), jtj.cols());
double dampling2 = m_dampling2 * distance.norm();
MatrixX_ a = (2 * jtj + m_dampling1*lamdaI + dampling2* m_invcov).inverse();
MatrixX_ b = (2 * jacobianTranspose * distance + dampling2 * m_invcov * (m_mu - last_state)/ (m_mu - last_state).norm());
VectorX_ dR = a * b;
#else
MatrixX_ jacobianTranspose = jacobian.transpose();
MatrixX_ jtj = jacobian * jacobianTranspose;
MatrixX_ lamdaI = MatrixX_::Identity(jtj.rows(), jtj.cols());
VectorX_ dR = jacobianTranspose * ( jtj + lamdaI * m_dampling1).inverse() * distance;
#endif
/*for(int i = 0; i < 3; ++i)
{
chain->m_dim_values[i] = castPiRange(chain->m_dim_values[i] + dR[i]);
last_state[i] = chain->m_dim_values[i];//dR[i];
}*/
/*for(int i = 3; i < 6; ++i)
{
last_state[i] = dR[i];
}
*/
for(int i = chain->m_startDim4IK; i < chain->m_dims.size(); ++i)
{
chain->m_dim_values[i] = castPiRange(chain->m_dim_values[i] + dR[i]);
last_state[i] = chain->m_dim_values[i];
}
chain->update();
}
void trimString( std::string& _string)
{
// Trim Both leading and trailing spaces
size_t start = _string.find_first_not_of(" \t\r\n");
size_t end = _string.find_last_not_of(" \t\r\n");
if(( std::string::npos == start ) || ( std::string::npos == end))
_string = "";
else
_string = _string.substr( start, end-start+1 );
}
bool JacobianCov::loadGaussianFromFile(const std::string& filepath)
{
std::fstream in( filepath.c_str(), std::ios_base::in );
if (!in.is_open() || !in.good())
{
std::cerr << "[gaussian] : cannot not open file "
<< filepath
<< std::endl;
return false;
}
#if defined(_DEBUG) || defined(DEBUG)
std::cout<< "[gaussian] : start loading : "<< filepath <<std::endl;
#endif
std::string line;
while( in && !in.eof() )
{
//lineIndex++;
std::getline(in,line);
if ( in.bad() ){
std::cout << " Warning! Could not read file properly! BVH part: skeleton"<<std::endl;
}
trimString(line);
if ( line.size() == 0 || line[0] == '#' || isspace(line[0]) || line.empty() )
{
continue;
}
int index;
int dim;
std::stringstream stream(line);
stream >> index;
if(!stream.fail())
{
stream >> dim;
TargetGaussian tg;
m_gaussians.push_back(tg);
TargetGaussian& tgref = m_gaussians.back();
tgref.m_mu = VectorX_::Zero(dim);
tgref.m_cov = MatrixX_::Zero(dim, dim);
double value = 0;
std::getline(in,line);
std::stringstream stream2(line);
for(unsigned int n = 0; n < dim; ++n)
{
stream2 >> value;
tgref.m_mu[n] = value;
}
value = 0;
std::getline(in,line);
std::stringstream stream3(line);
for(unsigned int w = 0; w < dim; ++w)
{
for(unsigned int h = 0; h < dim; ++h)
{
stream3 >> value;
tgref.m_cov(w, h) = value;
}
}
tgref.m_invcov = (tgref.m_cov + MatrixX_::Identity(dim, dim) * 0.000001).inverse();
}
}
in.close();
#if defined(_DEBUG) || defined(DEBUG)
std::cout<< "[gaussian] : loading is successful "<<std::endl;
#endif
return true;
}
int JacobianCov::similarIndex(VectorX_ pos)
{
/*VectorX_ pos = VectorX_::Zero(rpos.size());
for(unsigned int i = 6; i < rpos.size(); ++i)
{
pos[i] = rpos[i];
}*/
int idx = -1;
double minNorm = 99999999999;
for(unsigned int i = 0; i < m_gaussians.size(); ++i)
{
VectorX_ diff = m_gaussians[i].m_mu - pos;
diff[2] = 0;
double current = diff.norm();
if(current < minNorm)
{
idx = i;
minNorm = current;
}
}
m_invcov = m_gaussians[idx].m_invcov;// MatrixX_::Identity(66,66) * 0.001;
m_mu = m_gaussians[idx].m_mu;
std::cout<<"idx: "<<idx<<std::endl;
return idx;
}
|
#include "JacobianCov.h"
#define USINGCOV
JacobianCov::~JacobianCov(void)
{
}
void JacobianCov::solveOneStep(Skeleton* chain, std::vector<Vector3_>& targets)
{
chain->update();
int tries = 0;
MatrixX_ jacobian = chain->m_jacobian;
VectorX_ distance(jacobian.rows());
#ifdef USINGCOV
/*VectorX_ rotation = VectorX_::Zero(chain->m_dims.size());
for(int i = 0; i < chain->m_dims.size(); ++i)
{
rotation[i] = chain->m_dim_values[i];
}*/
if(!m_defined)
{
m_mu = VectorX_::Zero(chain->m_dims.size());
VectorX_ variance = VectorX_::Zero(chain->m_dims.size());
m_cov = MatrixX_::Identity(chain->m_dims.size(), chain->m_dims.size());
m_invcov = m_cov.inverse();
m_defined = true;
}
similarIndex(last_state);
#endif
for(int ei = 0; ei < chain->m_endeffectors.size(); ++ei)
{
int endeffectorIdx = chain->m_endeffectors[ei];
Vector3_& endpos = chain->m_joint_globalPositions[endeffectorIdx];
Vector3_ dis = (targets[ei]-endpos);
distance(ei * 3 + 0) = dis(0);
distance(ei * 3 + 1) = dis(1);
distance(ei * 3 + 2) = dis(2);
for(unsigned int j = 0; j < 3; ++j)
{
Skeleton::Dim& dim = chain->m_dims[j];
Vector3_ axis = chain->m_dim_axis[dim.m_idx];
int lastDim = dim.m_lastIdx;
if(lastDim >= 0)
{
axis = chain->m_dim_globalOrientations[lastDim] * axis;
}
Vector3_ axisXYZgradient = axis;
jacobian(ei * 3 + 0, j) = axisXYZgradient(0) * 0.00001;
jacobian(ei * 3 + 1, j) = axisXYZgradient(1) * 0.00001;
jacobian(ei * 3 + 2, j) = axisXYZgradient(2) * 0.00001;
}
for(unsigned int j = chain->m_startDim4IK; j < chain->m_dims.size(); ++j)
{
if(chain->m_jacobian(ei * 3 + 0, j) < 0.1) continue;
Skeleton::Dim& dim = chain->m_dims[j];
Vector3_& jointPos = chain->m_dim_globalPositions[dim.m_idx];
Vector3_ boneVector = endpos - jointPos;
if(boneVector.norm() == 0)
{
continue;
}
//boneVector.normalize();
Vector3_ axis = chain->m_dim_axis[dim.m_idx];
int lastDim = dim.m_lastIdx;
if(lastDim >= 0)
{
axis = chain->m_dim_globalOrientations[lastDim] * axis;
}
Vector3_ axisXYZgradient = axis.cross(boneVector);
jacobian(ei * 3 + 0, j) = axisXYZgradient(0);
jacobian(ei * 3 + 1, j) = axisXYZgradient(1);
jacobian(ei * 3 + 2, j) = axisXYZgradient(2);
}
}
#ifdef USINGCOV
MatrixX_ jacobianTranspose = jacobian.transpose();
MatrixX_ jtj = jacobianTranspose * jacobian;
MatrixX_ lamdaI = MatrixX_::Identity(jtj.rows(), jtj.cols());
double dampling2 = m_dampling2 * distance.norm();
MatrixX_ a = (2 * jtj + m_dampling1*lamdaI + dampling2* m_invcov).inverse();
MatrixX_ b = (2 * jacobianTranspose * distance + dampling2 * m_invcov * (m_mu - last_state)/ (m_mu - last_state).norm());
VectorX_ dR = a * b;
#else
MatrixX_ jacobianTranspose = jacobian.transpose();
MatrixX_ jtj = jacobian * jacobianTranspose;
MatrixX_ lamdaI = MatrixX_::Identity(jtj.rows(), jtj.cols());
VectorX_ dR = jacobianTranspose * ( jtj + lamdaI * m_dampling1).inverse() * distance;
#endif
for(int i = 0; i < 3; ++i)
{
chain->m_dim_values[i] = chain->m_dim_values[i] + dR[i];
last_state[i] = 0;// chain->m_dim_values[i];//dR[i];
}
/*for(int i = 3; i < 6; ++i)
{
last_state[i] = dR[i];
}
*/
for(int i = chain->m_startDim4IK; i < chain->m_dims.size(); ++i)
{
chain->m_dim_values[i] = castPiRange(chain->m_dim_values[i] + dR[i]);
last_state[i] = chain->m_dim_values[i];
}
chain->update();
}
void trimString( std::string& _string)
{
// Trim Both leading and trailing spaces
size_t start = _string.find_first_not_of(" \t\r\n");
size_t end = _string.find_last_not_of(" \t\r\n");
if(( std::string::npos == start ) || ( std::string::npos == end))
_string = "";
else
_string = _string.substr( start, end-start+1 );
}
bool JacobianCov::loadGaussianFromFile(const std::string& filepath)
{
std::fstream in( filepath.c_str(), std::ios_base::in );
if (!in.is_open() || !in.good())
{
std::cerr << "[gaussian] : cannot not open file "
<< filepath
<< std::endl;
return false;
}
#if defined(_DEBUG) || defined(DEBUG)
std::cout<< "[gaussian] : start loading : "<< filepath <<std::endl;
#endif
std::string line;
while( in && !in.eof() )
{
//lineIndex++;
std::getline(in,line);
if ( in.bad() ){
std::cout << " Warning! Could not read file properly! BVH part: skeleton"<<std::endl;
}
trimString(line);
if ( line.size() == 0 || line[0] == '#' || isspace(line[0]) || line.empty() )
{
continue;
}
int index;
int dim;
std::stringstream stream(line);
stream >> index;
if(!stream.fail())
{
stream >> dim;
TargetGaussian tg;
m_gaussians.push_back(tg);
TargetGaussian& tgref = m_gaussians.back();
tgref.m_mu = VectorX_::Zero(dim);
tgref.m_cov = MatrixX_::Zero(dim, dim);
double value = 0;
std::getline(in,line);
std::stringstream stream2(line);
for(unsigned int n = 0; n < dim; ++n)
{
stream2 >> value;
tgref.m_mu[n] = value;
}
value = 0;
std::getline(in,line);
std::stringstream stream3(line);
for(unsigned int w = 0; w < dim; ++w)
{
for(unsigned int h = 0; h < dim; ++h)
{
stream3 >> value;
tgref.m_cov(w, h) = value;
}
}
tgref.m_invcov = (tgref.m_cov + MatrixX_::Identity(dim, dim) * 0.000001).inverse();
}
}
in.close();
#if defined(_DEBUG) || defined(DEBUG)
std::cout<< "[gaussian] : loading is successful "<<std::endl;
#endif
return true;
}
int JacobianCov::similarIndex(VectorX_ pos)
{
/*VectorX_ pos = VectorX_::Zero(rpos.size());
for(unsigned int i = 6; i < rpos.size(); ++i)
{
pos[i] = rpos[i];
}*/
int idx = -1;
double minNorm = 99999999999;
for(unsigned int i = 0; i < m_gaussians.size(); ++i)
{
VectorX_ diff = m_gaussians[i].m_mu - pos;
diff[2] = 0;
double current = diff.norm();
if(current < minNorm)
{
idx = i;
minNorm = current;
}
}
m_invcov = m_gaussians[idx].m_invcov;// MatrixX_::Identity(66,66) * 0.001;
m_mu = m_gaussians[idx].m_mu;
std::cout<<"idx: "<<idx<<std::endl;
return idx;
}
|
check root
|
check root
|
C++
|
apache-2.0
|
billhj/Etoile2015,billhj/Etoile2015
|
8c71622492fb06f4e6e8a6569deef02b4f347671
|
src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dp16_workarounds.C
|
src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dp16_workarounds.C
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dp16_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,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 workarounds/dp16.C
/// @brief Workarounds for the DP16 logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Steven Glancy <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/utils/scom.H>
#include <lib/utils/pos.H>
#include <lib/workarounds/dp16_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace dp16
{
///
/// @brief DQS polarity workaround
/// For Monza DDR port 2, one pair of DQS P/N is swapped polarity. Not in DDR port 6
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed. It is specific to the Monza module, but can be called for all modules as it
/// will enforce its requirements internally
///
fapi2::ReturnCode dqs_polarity( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
// Receiver config provided by S. Wyatt 8/16
constexpr uint64_t rx_config = 0x4000;
// For Monza DDR port 2, one pair of DQS P/N is swapped polarity. Not in DDR port 6
// For Monza DDR port 3, one pair of DQS P/N is swapped polarity. Not in DDR port 7
const auto l_pos = mss::pos(i_target);
// TODO RTC:160353 Need module/chip rev EC support for workarounds
// Need to check this for Monza only when attribute support for EC levels is in place
// So we need to make sure our position is 2 or 3 and skip for the other ports.
if (l_pos == 2)
{
FAPI_TRY( mss::putScom(i_target, MCA_DDRPHY_DP16_RX_PEAK_AMP_P0_4, rx_config) );
}
if (l_pos == 3)
{
FAPI_TRY( mss::putScom(i_target, MCA_DDRPHY_DP16_RX_PEAK_AMP_P0_0, rx_config) );
}
// Can't just return current_err, if we're not ports 2,3 we didn't touch it ...
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace dp16
} // close namespace workarounds
} // close namespace mss
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/workarounds/dp16_workarounds.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,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 workarounds/dp16.C
/// @brief Workarounds for the DP16 logic blocks
/// Workarounds are very deivce specific, so there is no attempt to generalize
/// this code in any way.
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Steven Glancy <[email protected]>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <p9_mc_scom_addresses.H>
#include <p9_mc_scom_addresses_fld.H>
#include <lib/utils/scom.H>
#include <lib/utils/pos.H>
#include <lib/workarounds/dp16_workarounds.H>
namespace mss
{
namespace workarounds
{
namespace dp16
{
///
/// @brief DQS polarity workaround
/// For Monza DDR port 2, one pair of DQS P/N is swapped polarity. Not in DDR port 6
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
/// @note This function is called during the phy scom init procedure, after the initfile is
/// processed. It is specific to the Monza module, but can be called for all modules as it
/// will enforce its requirements internally
///
fapi2::ReturnCode dqs_polarity( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
// Receiver config provided by S. Wyatt 8/16
constexpr uint64_t rx_config = 0x4000;
// For Monza DDR port 2, one pair of DQS P/N is swapped polarity. Not in DDR port 6
// For Monza DDR port 3, one pair of DQS P/N is swapped polarity. Not in DDR port 7
const auto l_pos = mss::pos(i_target);
// TODO RTC:160353 Need module/chip rev EC support for workarounds
// Need to check this for Monza only when attribute support for EC levels is in place
// So we need to make sure our position is 2 or 3 and skip for the other ports.
if (l_pos == 2)
{
FAPI_TRY( mss::putScom(i_target, MCA_DDRPHY_DP16_RX_PEAK_AMP_P0_4, rx_config) );
}
if (l_pos == 3)
{
FAPI_TRY( mss::putScom(i_target, MCA_DDRPHY_DP16_RX_PEAK_AMP_P0_0, rx_config) );
}
// Can't just return current_err, if we're not ports 2,3 we didn't touch it ...
return fapi2::FAPI2_RC_SUCCESS;
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief DP16 Read Diagnostic Configuration 5 work around
/// Not in the Model 67 spydef, so we scom them. Should be removed when they are
/// added to the spydef.
/// @param[in] i_target the fapi2 target of the port
/// @return fapi2::ReturnCode FAPI2_RC_SUCCESS if ok
///
fapi2::ReturnCode rd_dia_config5( const fapi2::Target<fapi2::TARGET_TYPE_MCA>& i_target )
{
// Config provided by S. Wyatt 8/16
constexpr uint64_t rd_dia_config = 0x0010;
static const std::vector<uint64_t> l_addrs =
{
MCA_DDRPHY_DP16_RD_DIA_CONFIG5_P0_0,
MCA_DDRPHY_DP16_RD_DIA_CONFIG5_P0_1,
MCA_DDRPHY_DP16_RD_DIA_CONFIG5_P0_2,
MCA_DDRPHY_DP16_RD_DIA_CONFIG5_P0_3,
MCA_DDRPHY_DP16_RD_DIA_CONFIG5_P0_4,
};
FAPI_TRY( mss::scom_blastah(i_target, l_addrs, rd_dia_config) );
fapi_try_exit:
return fapi2::current_err;
}
} // close namespace dp16
} // close namespace workarounds
} // close namespace mss
|
Add SEQ timing parameters, DP16 RD Diag config 5 inits
|
Add SEQ timing parameters, DP16 RD Diag config 5 inits
Change-Id: I32dc1b0bc9beefc3ebd391e6073eb3100f0dffc1
Original-Change-Id: I0425b4e35c4b11bb6c44c6fefb72ccfce633f669
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/29442
Tested-by: Jenkins Server <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: Louis Stermole <[email protected]>
Reviewed-by: JACOB L. HARVEY <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
|
C++
|
apache-2.0
|
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
|
941fd43a15c81779a4c5041a4d7c472e149d99dc
|
test/layer_filtering_transport.cc
|
test/layer_filtering_transport.cc
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <string.h>
#include <algorithm>
#include <memory>
#include <utility>
#include "api/rtp_headers.h"
#include "common_types.h" // NOLINT(build/include)
#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "modules/rtp_rtcp/source/rtp_format.h"
#include "modules/rtp_rtcp/source/rtp_utility.h"
#include "modules/rtp_rtcp/source/rtp_video_header.h"
#include "modules/video_coding/codecs/interface/common_constants.h"
#include "modules/video_coding/codecs/vp8/include/vp8_globals.h"
#include "modules/video_coding/codecs/vp9/include/vp9_globals.h"
#include "rtc_base/checks.h"
#include "test/layer_filtering_transport.h"
namespace webrtc {
namespace test {
LayerFilteringTransport::LayerFilteringTransport(
SingleThreadedTaskQueueForTesting* task_queue,
std::unique_ptr<SimulatedPacketReceiverInterface> pipe,
Call* send_call,
uint8_t vp8_video_payload_type,
uint8_t vp9_video_payload_type,
int selected_tl,
int selected_sl,
const std::map<uint8_t, MediaType>& payload_type_map,
uint32_t ssrc_to_filter_min,
uint32_t ssrc_to_filter_max)
: DirectTransport(task_queue, std::move(pipe), send_call, payload_type_map),
vp8_video_payload_type_(vp8_video_payload_type),
vp9_video_payload_type_(vp9_video_payload_type),
selected_tl_(selected_tl),
selected_sl_(selected_sl),
discarded_last_packet_(false),
ssrc_to_filter_min_(ssrc_to_filter_min),
ssrc_to_filter_max_(ssrc_to_filter_max) {}
LayerFilteringTransport::LayerFilteringTransport(
SingleThreadedTaskQueueForTesting* task_queue,
std::unique_ptr<SimulatedPacketReceiverInterface> pipe,
Call* send_call,
uint8_t vp8_video_payload_type,
uint8_t vp9_video_payload_type,
int selected_tl,
int selected_sl,
const std::map<uint8_t, MediaType>& payload_type_map)
: DirectTransport(task_queue, std::move(pipe), send_call, payload_type_map),
vp8_video_payload_type_(vp8_video_payload_type),
vp9_video_payload_type_(vp9_video_payload_type),
selected_tl_(selected_tl),
selected_sl_(selected_sl),
discarded_last_packet_(false),
ssrc_to_filter_min_(0),
ssrc_to_filter_max_(0xFFFFFFFF) {}
bool LayerFilteringTransport::DiscardedLastPacket() const {
return discarded_last_packet_;
}
bool LayerFilteringTransport::SendRtp(const uint8_t* packet,
size_t length,
const PacketOptions& options) {
if (selected_tl_ == -1 && selected_sl_ == -1) {
// Nothing to change, forward the packet immediately.
return test::DirectTransport::SendRtp(packet, length, options);
}
bool set_marker_bit = false;
RtpUtility::RtpHeaderParser parser(packet, length);
RTPHeader header;
parser.Parse(&header);
if (header.ssrc < ssrc_to_filter_min_ || header.ssrc > ssrc_to_filter_max_) {
// Nothing to change, forward the packet immediately.
return test::DirectTransport::SendRtp(packet, length, options);
}
RTC_DCHECK_LE(length, IP_PACKET_SIZE);
uint8_t temp_buffer[IP_PACKET_SIZE];
memcpy(temp_buffer, packet, length);
if (header.payloadType == vp8_video_payload_type_ ||
header.payloadType == vp9_video_payload_type_) {
const uint8_t* payload = packet + header.headerLength;
RTC_DCHECK_GT(length, header.headerLength);
const size_t payload_length = length - header.headerLength;
RTC_DCHECK_GT(payload_length, header.paddingLength);
const size_t payload_data_length = payload_length - header.paddingLength;
const bool is_vp8 = header.payloadType == vp8_video_payload_type_;
std::unique_ptr<RtpDepacketizer> depacketizer(
RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
RtpDepacketizer::ParsedPayload parsed_payload;
if (depacketizer->Parse(&parsed_payload, payload, payload_data_length)) {
int temporal_idx;
int spatial_idx;
bool non_ref_for_inter_layer_pred;
bool end_of_frame;
if (is_vp8) {
temporal_idx = absl::get<RTPVideoHeaderVP8>(
parsed_payload.video_header().video_type_header)
.temporalIdx;
spatial_idx = kNoSpatialIdx;
num_active_spatial_layers_ = 1;
non_ref_for_inter_layer_pred = false;
end_of_frame = true;
} else {
const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
parsed_payload.video_header().video_type_header);
temporal_idx = vp9_header.temporal_idx;
spatial_idx = vp9_header.spatial_idx;
non_ref_for_inter_layer_pred = vp9_header.non_ref_for_inter_layer_pred;
end_of_frame = vp9_header.end_of_frame;
// The number of spatial layers is sent in ssData, which is included
// only in the first packet of the first spatial layer of a key frame.
if (!vp9_header.inter_pic_predicted &&
vp9_header.beginning_of_frame == 1 && spatial_idx == 0) {
num_active_spatial_layers_ = vp9_header.num_spatial_layers;
}
}
if (spatial_idx == kNoSpatialIdx)
num_active_spatial_layers_ = 1;
RTC_CHECK_GT(num_active_spatial_layers_, 0);
if (selected_sl_ >= 0 &&
spatial_idx ==
std::min(num_active_spatial_layers_ - 1, selected_sl_) &&
end_of_frame) {
// This layer is now the last in the superframe.
set_marker_bit = true;
} else {
const bool higher_temporal_layer =
(selected_tl_ >= 0 && temporal_idx != kNoTemporalIdx &&
temporal_idx > selected_tl_);
const bool higher_spatial_layer =
(selected_sl_ >= 0 && spatial_idx != kNoSpatialIdx &&
spatial_idx > selected_sl_);
// Filter out non-reference lower spatial layers since they are not
// needed for decoding of target spatial layer.
const bool lower_non_ref_spatial_layer =
(selected_sl_ >= 0 && spatial_idx != kNoSpatialIdx &&
spatial_idx <
std::min(num_active_spatial_layers_ - 1, selected_sl_) &&
non_ref_for_inter_layer_pred);
if (higher_temporal_layer || higher_spatial_layer ||
lower_non_ref_spatial_layer) {
// Truncate packet to a padding packet.
length = header.headerLength + 1;
temp_buffer[0] |= (1 << 5); // P = 1.
temp_buffer[1] &= 0x7F; // M = 0.
discarded_last_packet_ = true;
temp_buffer[header.headerLength] = 1; // One byte of padding.
}
}
} else {
RTC_NOTREACHED() << "Parse error";
}
}
// We are discarding some of the packets (specifically, whole layers), so
// make sure the marker bit is set properly, and that sequence numbers are
// continuous.
if (set_marker_bit)
temp_buffer[1] |= kRtpMarkerBitMask;
return test::DirectTransport::SendRtp(temp_buffer, length, options);
}
} // namespace test
} // namespace webrtc
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <string.h>
#include <algorithm>
#include <memory>
#include <utility>
#include "api/rtp_headers.h"
#include "common_types.h" // NOLINT(build/include)
#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
#include "modules/rtp_rtcp/source/rtp_format.h"
#include "modules/rtp_rtcp/source/rtp_utility.h"
#include "modules/rtp_rtcp/source/rtp_video_header.h"
#include "modules/video_coding/codecs/interface/common_constants.h"
#include "modules/video_coding/codecs/vp8/include/vp8_globals.h"
#include "modules/video_coding/codecs/vp9/include/vp9_globals.h"
#include "rtc_base/checks.h"
#include "test/layer_filtering_transport.h"
namespace webrtc {
namespace test {
LayerFilteringTransport::LayerFilteringTransport(
SingleThreadedTaskQueueForTesting* task_queue,
std::unique_ptr<SimulatedPacketReceiverInterface> pipe,
Call* send_call,
uint8_t vp8_video_payload_type,
uint8_t vp9_video_payload_type,
int selected_tl,
int selected_sl,
const std::map<uint8_t, MediaType>& payload_type_map,
uint32_t ssrc_to_filter_min,
uint32_t ssrc_to_filter_max)
: DirectTransport(task_queue, std::move(pipe), send_call, payload_type_map),
vp8_video_payload_type_(vp8_video_payload_type),
vp9_video_payload_type_(vp9_video_payload_type),
selected_tl_(selected_tl),
selected_sl_(selected_sl),
discarded_last_packet_(false),
ssrc_to_filter_min_(ssrc_to_filter_min),
ssrc_to_filter_max_(ssrc_to_filter_max) {}
LayerFilteringTransport::LayerFilteringTransport(
SingleThreadedTaskQueueForTesting* task_queue,
std::unique_ptr<SimulatedPacketReceiverInterface> pipe,
Call* send_call,
uint8_t vp8_video_payload_type,
uint8_t vp9_video_payload_type,
int selected_tl,
int selected_sl,
const std::map<uint8_t, MediaType>& payload_type_map)
: DirectTransport(task_queue, std::move(pipe), send_call, payload_type_map),
vp8_video_payload_type_(vp8_video_payload_type),
vp9_video_payload_type_(vp9_video_payload_type),
selected_tl_(selected_tl),
selected_sl_(selected_sl),
discarded_last_packet_(false),
ssrc_to_filter_min_(0),
ssrc_to_filter_max_(0xFFFFFFFF) {}
bool LayerFilteringTransport::DiscardedLastPacket() const {
return discarded_last_packet_;
}
bool LayerFilteringTransport::SendRtp(const uint8_t* packet,
size_t length,
const PacketOptions& options) {
if (selected_tl_ == -1 && selected_sl_ == -1) {
// Nothing to change, forward the packet immediately.
return test::DirectTransport::SendRtp(packet, length, options);
}
bool set_marker_bit = false;
RtpUtility::RtpHeaderParser parser(packet, length);
RTPHeader header;
parser.Parse(&header);
if (header.ssrc < ssrc_to_filter_min_ || header.ssrc > ssrc_to_filter_max_) {
// Nothing to change, forward the packet immediately.
return test::DirectTransport::SendRtp(packet, length, options);
}
RTC_DCHECK_LE(length, IP_PACKET_SIZE);
uint8_t temp_buffer[IP_PACKET_SIZE];
memcpy(temp_buffer, packet, length);
if (header.payloadType == vp8_video_payload_type_ ||
header.payloadType == vp9_video_payload_type_) {
const uint8_t* payload = packet + header.headerLength;
RTC_DCHECK_GT(length, header.headerLength);
const size_t payload_length = length - header.headerLength;
RTC_DCHECK_GT(payload_length, header.paddingLength);
const size_t payload_data_length = payload_length - header.paddingLength;
const bool is_vp8 = header.payloadType == vp8_video_payload_type_;
std::unique_ptr<RtpDepacketizer> depacketizer(
RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
RtpDepacketizer::ParsedPayload parsed_payload;
if (depacketizer->Parse(&parsed_payload, payload, payload_data_length)) {
int temporal_idx;
int spatial_idx;
bool non_ref_for_inter_layer_pred;
bool end_of_frame;
if (is_vp8) {
temporal_idx = absl::get<RTPVideoHeaderVP8>(
parsed_payload.video_header().video_type_header)
.temporalIdx;
spatial_idx = kNoSpatialIdx;
num_active_spatial_layers_ = 1;
non_ref_for_inter_layer_pred = false;
end_of_frame = true;
} else {
const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
parsed_payload.video_header().video_type_header);
temporal_idx = vp9_header.temporal_idx;
spatial_idx = vp9_header.spatial_idx;
non_ref_for_inter_layer_pred = vp9_header.non_ref_for_inter_layer_pred;
end_of_frame = vp9_header.end_of_frame;
if (vp9_header.ss_data_available) {
RTC_DCHECK(vp9_header.temporal_idx == kNoTemporalIdx ||
vp9_header.temporal_idx == 0);
RTC_DCHECK(vp9_header.spatial_idx == kNoSpatialIdx ||
vp9_header.spatial_idx == 0);
num_active_spatial_layers_ = vp9_header.num_spatial_layers;
}
}
if (spatial_idx == kNoSpatialIdx)
num_active_spatial_layers_ = 1;
RTC_CHECK_GT(num_active_spatial_layers_, 0);
if (selected_sl_ >= 0 &&
spatial_idx ==
std::min(num_active_spatial_layers_ - 1, selected_sl_) &&
end_of_frame) {
// This layer is now the last in the superframe.
set_marker_bit = true;
} else {
const bool higher_temporal_layer =
(selected_tl_ >= 0 && temporal_idx != kNoTemporalIdx &&
temporal_idx > selected_tl_);
const bool higher_spatial_layer =
(selected_sl_ >= 0 && spatial_idx != kNoSpatialIdx &&
spatial_idx > selected_sl_);
// Filter out non-reference lower spatial layers since they are not
// needed for decoding of target spatial layer.
const bool lower_non_ref_spatial_layer =
(selected_sl_ >= 0 && spatial_idx != kNoSpatialIdx &&
spatial_idx <
std::min(num_active_spatial_layers_ - 1, selected_sl_) &&
non_ref_for_inter_layer_pred);
if (higher_temporal_layer || higher_spatial_layer ||
lower_non_ref_spatial_layer) {
// Truncate packet to a padding packet.
length = header.headerLength + 1;
temp_buffer[0] |= (1 << 5); // P = 1.
temp_buffer[1] &= 0x7F; // M = 0.
discarded_last_packet_ = true;
temp_buffer[header.headerLength] = 1; // One byte of padding.
}
}
} else {
RTC_NOTREACHED() << "Parse error";
}
}
// We are discarding some of the packets (specifically, whole layers), so
// make sure the marker bit is set properly, and that sequence numbers are
// continuous.
if (set_marker_bit)
temp_buffer[1] |= kRtpMarkerBitMask;
return test::DirectTransport::SendRtp(temp_buffer, length, options);
}
} // namespace test
} // namespace webrtc
|
Update number of spatial layers if SS is available.
|
Update number of spatial layers if SS is available.
Bug: webrtc:10149
Change-Id: I4e962283619590999a02a31b63f1dd7ce25aa11d
Reviewed-on: https://webrtc-review.googlesource.com/c/115041
Reviewed-by: Ilya Nikolaevskiy <[email protected]>
Reviewed-by: Sebastian Jansson <[email protected]>
Commit-Queue: Sergey Silkin <[email protected]>
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#26072}
|
C++
|
bsd-3-clause
|
TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc
|
31345c74c930c53da7131b2fb1387a3460a58b18
|
libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC11U6X/TOOLCHAIN_GCC_CR/TARGET_LPC11U68/startup_LPC11U68.cpp
|
libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC11U6X/TOOLCHAIN_GCC_CR/TARGET_LPC11U68/startup_LPC11U68.cpp
|
extern "C" {
#include "LPC11U6x.h"
#define WEAK __attribute__ ((weak))
#define ALIAS(f) __attribute__ ((weak, alias (#f)))
#define AFTER_VECTORS __attribute__ ((section(".after_vectors")))void ResetISR(void);
extern unsigned int __data_section_table;
extern unsigned int __data_section_table_end;
extern unsigned int __bss_section_table;
extern unsigned int __bss_section_table_end;
extern void __libc_init_array(void);
extern int main(void);
extern void _vStackTop(void);
extern void (* const g_pfnVectors[])(void);
void ResetISR(void);
WEAK void NMI_Handler(void);
WEAK void HardFault_Handler(void);
WEAK void SVC_Handler(void);
WEAK void PendSV_Handler(void);
WEAK void SysTick_Handler(void);
WEAK void IntDefaultHandler(void);
void PIN_INT0_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT1_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT2_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT3_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT4_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT5_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT6_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT7_IRQHandler (void) ALIAS(IntDefaultHandler);
void GINT0_IRQHandler (void) ALIAS(IntDefaultHandler);
void GINT1_IRQHandler (void) ALIAS(IntDefaultHandler);
void I2C1_IRQHandler (void) ALIAS(IntDefaultHandler);
void USART1_4_IRQHandler (void) ALIAS(IntDefaultHandler);
void USART2_3_IRQHandler (void) ALIAS(IntDefaultHandler);
void SCT0_1_IRQHandler (void) ALIAS(IntDefaultHandler);
void SSP1_IRQHandler (void) ALIAS(IntDefaultHandler);
void I2C0_IRQHandler (void) ALIAS(IntDefaultHandler);
void TIMER16_0_IRQHandler (void) ALIAS(IntDefaultHandler);
void TIMER16_1_IRQHandler (void) ALIAS(IntDefaultHandler);
void TIMER32_0_IRQHandler (void) ALIAS(IntDefaultHandler);
void TIMER32_1_IRQHandler (void) ALIAS(IntDefaultHandler);
void SSP0_IRQHandler (void) ALIAS(IntDefaultHandler);
void USART0_IRQHandler (void) ALIAS(IntDefaultHandler);
void USB_IRQHandler (void) ALIAS(IntDefaultHandler);
void USB_FIQHandler (void) ALIAS(IntDefaultHandler);
void ADCA_IRQHandler (void) ALIAS(IntDefaultHandler);
void RTC_IRQHandler (void) ALIAS(IntDefaultHandler);
void BOD_WDT_IRQHandler (void) ALIAS(IntDefaultHandler);
void FMC_IRQHandler (void) ALIAS(IntDefaultHandler);
void DMA_IRQHandler (void) ALIAS(IntDefaultHandler);
void ADCB_IRQHandler (void) ALIAS(IntDefaultHandler);
void USBWakeup_IRQHandler (void) ALIAS(IntDefaultHandler);
__attribute__ ((section(".isr_vector")))
void (* const g_pfnVectors[])(void) = {
// Core Level - CM0
&_vStackTop, // The initial stack pointer
ResetISR, // The reset handler
NMI_Handler, // The NMI handler
HardFault_Handler, // The hard fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
SVC_Handler, // SVCall handler
0, // Reserved
0, // Reserved
PendSV_Handler, // The PendSV handler
SysTick_Handler, // The SysTick handler
// Chip Level - LPC11U68
PIN_INT0_IRQHandler, // 0 - GPIO pin interrupt 0
PIN_INT1_IRQHandler, // 1 - GPIO pin interrupt 1
PIN_INT2_IRQHandler, // 2 - GPIO pin interrupt 2
PIN_INT3_IRQHandler, // 3 - GPIO pin interrupt 3
PIN_INT4_IRQHandler, // 4 - GPIO pin interrupt 4
PIN_INT5_IRQHandler, // 5 - GPIO pin interrupt 5
PIN_INT6_IRQHandler, // 6 - GPIO pin interrupt 6
PIN_INT7_IRQHandler, // 7 - GPIO pin interrupt 7
GINT0_IRQHandler, // 8 - GPIO GROUP0 interrupt
GINT1_IRQHandler, // 9 - GPIO GROUP1 interrupt
I2C1_IRQHandler, // 10 - I2C1
USART1_4_IRQHandler, // 11 - combined USART1 & 4 interrupt
USART2_3_IRQHandler, // 12 - combined USART2 & 3 interrupt
SCT0_1_IRQHandler, // 13 - combined SCT0 and 1 interrupt
SSP1_IRQHandler, // 14 - SPI/SSP1 Interrupt
I2C0_IRQHandler, // 15 - I2C0
TIMER16_0_IRQHandler, // 16 - CT16B0 (16-bit Timer 0)
TIMER16_1_IRQHandler, // 17 - CT16B1 (16-bit Timer 1)
TIMER32_0_IRQHandler, // 18 - CT32B0 (32-bit Timer 0)
TIMER32_1_IRQHandler, // 19 - CT32B1 (32-bit Timer 1)
SSP0_IRQHandler, // 20 - SPI/SSP0 Interrupt
USART0_IRQHandler, // 21 - USART0
USB_IRQHandler, // 22 - USB IRQ
USB_FIQHandler, // 23 - USB FIQ
ADCA_IRQHandler, // 24 - ADC A(A/D Converter)
RTC_IRQHandler, // 25 - Real Time CLock interrpt
BOD_WDT_IRQHandler, // 25 - Combined Brownout/Watchdog interrupt
FMC_IRQHandler, // 27 - IP2111 Flash Memory Controller
DMA_IRQHandler, // 28 - DMA interrupt
ADCB_IRQHandler, // 24 - ADC B (A/D Converter)
USBWakeup_IRQHandler, // 30 - USB wake-up interrupt
0, // 31 - Reserved
};
/* End Vector */
AFTER_VECTORS void data_init(unsigned int romstart, unsigned int start, unsigned int len) {
unsigned int *pulDest = (unsigned int*) start;
unsigned int *pulSrc = (unsigned int*) romstart;
unsigned int loop;
for (loop = 0; loop < len; loop = loop + 4) *pulDest++ = *pulSrc++;
}
AFTER_VECTORS void bss_init(unsigned int start, unsigned int len) {
unsigned int *pulDest = (unsigned int*) start;
unsigned int loop;
for (loop = 0; loop < len; loop = loop + 4) *pulDest++ = 0;
}
/* Reset entry point*/
extern "C" void software_init_hook(void) __attribute__((weak));
AFTER_VECTORS void ResetISR(void) {
unsigned int LoadAddr, ExeAddr, SectionLen;
unsigned int *SectionTableAddr;
SectionTableAddr = &__data_section_table;
while (SectionTableAddr < &__data_section_table_end) {
LoadAddr = *SectionTableAddr++;
ExeAddr = *SectionTableAddr++;
SectionLen = *SectionTableAddr++;
data_init(LoadAddr, ExeAddr, SectionLen);
}
while (SectionTableAddr < &__bss_section_table_end) {
ExeAddr = *SectionTableAddr++;
SectionLen = *SectionTableAddr++;
bss_init(ExeAddr, SectionLen);
}
SystemInit();
if (software_init_hook)
software_init_hook();
else {
__libc_init_array();
main();
}
while (1) {;}
}
AFTER_VECTORS void NMI_Handler (void) {}
AFTER_VECTORS void HardFault_Handler (void) {}
AFTER_VECTORS void MemManage_Handler (void) {}
AFTER_VECTORS void BusFault_Handler (void) {}
AFTER_VECTORS void UsageFault_Handler(void) {}
AFTER_VECTORS void SVC_Handler (void) {}
AFTER_VECTORS void DebugMon_Handler (void) {}
AFTER_VECTORS void PendSV_Handler (void) {}
AFTER_VECTORS void SysTick_Handler (void) {}
AFTER_VECTORS void IntDefaultHandler (void) {}
int __aeabi_atexit(void *object, void (*destructor)(void *), void *dso_handle) {return 0;}
}
#include <stdlib.h>
void *operator new(size_t size) {return malloc(size);}
void *operator new[](size_t size){return malloc(size);}
void operator delete(void *p) {free(p);}
void operator delete[](void *p) {free(p);}
|
extern "C" {
#include "LPC11U6x.h"
#define WEAK __attribute__ ((weak))
#define ALIAS(f) __attribute__ ((weak, alias (#f)))
#define AFTER_VECTORS __attribute__ ((section(".after_vectors")))void ResetISR(void);
// Patch the AEABI integer divide functions to use MCU's romdivide library
#ifdef __USE_ROMDIVIDE
// Location in memory that holds the address of the ROM Driver table
#define PTR_ROM_DRIVER_TABLE ((unsigned int *)(0x1FFF1FF8))
// Variables to store addresses of idiv and udiv functions within MCU ROM
unsigned int *pDivRom_idiv;
unsigned int *pDivRom_uidiv;
#endif
extern unsigned int __data_section_table;
extern unsigned int __data_section_table_end;
extern unsigned int __bss_section_table;
extern unsigned int __bss_section_table_end;
extern void __libc_init_array(void);
extern int main(void);
extern void _vStackTop(void);
extern void (* const g_pfnVectors[])(void);
void ResetISR(void);
WEAK void NMI_Handler(void);
WEAK void HardFault_Handler(void);
WEAK void SVC_Handler(void);
WEAK void PendSV_Handler(void);
WEAK void SysTick_Handler(void);
WEAK void IntDefaultHandler(void);
void PIN_INT0_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT1_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT2_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT3_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT4_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT5_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT6_IRQHandler (void) ALIAS(IntDefaultHandler);
void PIN_INT7_IRQHandler (void) ALIAS(IntDefaultHandler);
void GINT0_IRQHandler (void) ALIAS(IntDefaultHandler);
void GINT1_IRQHandler (void) ALIAS(IntDefaultHandler);
void I2C1_IRQHandler (void) ALIAS(IntDefaultHandler);
void USART1_4_IRQHandler (void) ALIAS(IntDefaultHandler);
void USART2_3_IRQHandler (void) ALIAS(IntDefaultHandler);
void SCT0_1_IRQHandler (void) ALIAS(IntDefaultHandler);
void SSP1_IRQHandler (void) ALIAS(IntDefaultHandler);
void I2C0_IRQHandler (void) ALIAS(IntDefaultHandler);
void TIMER16_0_IRQHandler (void) ALIAS(IntDefaultHandler);
void TIMER16_1_IRQHandler (void) ALIAS(IntDefaultHandler);
void TIMER32_0_IRQHandler (void) ALIAS(IntDefaultHandler);
void TIMER32_1_IRQHandler (void) ALIAS(IntDefaultHandler);
void SSP0_IRQHandler (void) ALIAS(IntDefaultHandler);
void USART0_IRQHandler (void) ALIAS(IntDefaultHandler);
void USB_IRQHandler (void) ALIAS(IntDefaultHandler);
void USB_FIQHandler (void) ALIAS(IntDefaultHandler);
void ADCA_IRQHandler (void) ALIAS(IntDefaultHandler);
void RTC_IRQHandler (void) ALIAS(IntDefaultHandler);
void BOD_WDT_IRQHandler (void) ALIAS(IntDefaultHandler);
void FMC_IRQHandler (void) ALIAS(IntDefaultHandler);
void DMA_IRQHandler (void) ALIAS(IntDefaultHandler);
void ADCB_IRQHandler (void) ALIAS(IntDefaultHandler);
void USBWakeup_IRQHandler (void) ALIAS(IntDefaultHandler);
__attribute__ ((section(".isr_vector")))
void (* const g_pfnVectors[])(void) = {
// Core Level - CM0
&_vStackTop, // The initial stack pointer
ResetISR, // The reset handler
NMI_Handler, // The NMI handler
HardFault_Handler, // The hard fault handler
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
0, // Reserved
SVC_Handler, // SVCall handler
0, // Reserved
0, // Reserved
PendSV_Handler, // The PendSV handler
SysTick_Handler, // The SysTick handler
// Chip Level - LPC11U68
PIN_INT0_IRQHandler, // 0 - GPIO pin interrupt 0
PIN_INT1_IRQHandler, // 1 - GPIO pin interrupt 1
PIN_INT2_IRQHandler, // 2 - GPIO pin interrupt 2
PIN_INT3_IRQHandler, // 3 - GPIO pin interrupt 3
PIN_INT4_IRQHandler, // 4 - GPIO pin interrupt 4
PIN_INT5_IRQHandler, // 5 - GPIO pin interrupt 5
PIN_INT6_IRQHandler, // 6 - GPIO pin interrupt 6
PIN_INT7_IRQHandler, // 7 - GPIO pin interrupt 7
GINT0_IRQHandler, // 8 - GPIO GROUP0 interrupt
GINT1_IRQHandler, // 9 - GPIO GROUP1 interrupt
I2C1_IRQHandler, // 10 - I2C1
USART1_4_IRQHandler, // 11 - combined USART1 & 4 interrupt
USART2_3_IRQHandler, // 12 - combined USART2 & 3 interrupt
SCT0_1_IRQHandler, // 13 - combined SCT0 and 1 interrupt
SSP1_IRQHandler, // 14 - SPI/SSP1 Interrupt
I2C0_IRQHandler, // 15 - I2C0
TIMER16_0_IRQHandler, // 16 - CT16B0 (16-bit Timer 0)
TIMER16_1_IRQHandler, // 17 - CT16B1 (16-bit Timer 1)
TIMER32_0_IRQHandler, // 18 - CT32B0 (32-bit Timer 0)
TIMER32_1_IRQHandler, // 19 - CT32B1 (32-bit Timer 1)
SSP0_IRQHandler, // 20 - SPI/SSP0 Interrupt
USART0_IRQHandler, // 21 - USART0
USB_IRQHandler, // 22 - USB IRQ
USB_FIQHandler, // 23 - USB FIQ
ADCA_IRQHandler, // 24 - ADC A(A/D Converter)
RTC_IRQHandler, // 25 - Real Time CLock interrpt
BOD_WDT_IRQHandler, // 25 - Combined Brownout/Watchdog interrupt
FMC_IRQHandler, // 27 - IP2111 Flash Memory Controller
DMA_IRQHandler, // 28 - DMA interrupt
ADCB_IRQHandler, // 24 - ADC B (A/D Converter)
USBWakeup_IRQHandler, // 30 - USB wake-up interrupt
0, // 31 - Reserved
};
/* End Vector */
AFTER_VECTORS void data_init(unsigned int romstart, unsigned int start, unsigned int len) {
unsigned int *pulDest = (unsigned int*) start;
unsigned int *pulSrc = (unsigned int*) romstart;
unsigned int loop;
for (loop = 0; loop < len; loop = loop + 4) *pulDest++ = *pulSrc++;
}
AFTER_VECTORS void bss_init(unsigned int start, unsigned int len) {
unsigned int *pulDest = (unsigned int*) start;
unsigned int loop;
for (loop = 0; loop < len; loop = loop + 4) *pulDest++ = 0;
}
/* Reset entry point*/
extern "C" void software_init_hook(void) __attribute__((weak));
AFTER_VECTORS void ResetISR(void) {
unsigned int LoadAddr, ExeAddr, SectionLen;
unsigned int *SectionTableAddr;
SectionTableAddr = &__data_section_table;
while (SectionTableAddr < &__data_section_table_end) {
LoadAddr = *SectionTableAddr++;
ExeAddr = *SectionTableAddr++;
SectionLen = *SectionTableAddr++;
data_init(LoadAddr, ExeAddr, SectionLen);
}
while (SectionTableAddr < &__bss_section_table_end) {
ExeAddr = *SectionTableAddr++;
SectionLen = *SectionTableAddr++;
bss_init(ExeAddr, SectionLen);
}
// Patch the AEABI integer divide functions to use MCU's romdivide library
#ifdef __USE_ROMDIVIDE
// Get address of Integer division routines function table in ROM
unsigned int *div_ptr = (unsigned int *)((unsigned int *)*(PTR_ROM_DRIVER_TABLE))[4];
// Get addresses of integer divide routines in ROM
// These address are then used by the code in aeabi_romdiv_patch.s
pDivRom_idiv = (unsigned int *)div_ptr[0];
pDivRom_uidiv = (unsigned int *)div_ptr[1];
#endif
SystemInit();
if (software_init_hook)
software_init_hook();
else {
__libc_init_array();
main();
}
while (1) {;}
}
AFTER_VECTORS void NMI_Handler (void) {}
AFTER_VECTORS void HardFault_Handler (void) {}
AFTER_VECTORS void MemManage_Handler (void) {}
AFTER_VECTORS void BusFault_Handler (void) {}
AFTER_VECTORS void UsageFault_Handler(void) {}
AFTER_VECTORS void SVC_Handler (void) {}
AFTER_VECTORS void DebugMon_Handler (void) {}
AFTER_VECTORS void PendSV_Handler (void) {}
AFTER_VECTORS void SysTick_Handler (void) {}
AFTER_VECTORS void IntDefaultHandler (void) {}
int __aeabi_atexit(void *object, void (*destructor)(void *), void *dso_handle) {return 0;}
}
#include <stdlib.h>
void *operator new(size_t size) {return malloc(size);}
void *operator new[](size_t size){return malloc(size);}
void operator delete(void *p) {free(p);}
void operator delete[](void *p) {free(p);}
|
Update startup_LPC11U68.cpp
|
Update startup_LPC11U68.cpp
|
C++
|
apache-2.0
|
jeremybrodt/mbed,bikeNomad/mbed,HeadsUpDisplayInc/mbed,c1728p9/mbed-os,bikeNomad/mbed,andreaslarssonublox/mbed,wodji/mbed,infinnovation/mbed-os,screamerbg/mbed,cvtsi2sd/mbed-os,naves-thiago/mbed-midi,tung7970/mbed-os,JasonHow44/mbed,bulislaw/mbed-os,svogl/mbed-os,GustavWi/mbed,rgrover/mbed,alertby/mbed,sg-/mbed-drivers,mbedmicro/mbed,geky/mbed,fahhem/mbed-os,adustm/mbed,Marcomissyou/mbed,mikaleppanen/mbed-os,Sweet-Peas/mbed,nabilbendafi/mbed,DanKupiniak/mbed,al177/mbed,fahhem/mbed-os,screamerbg/mbed,kpurusho/mbed,CalSol/mbed,HeadsUpDisplayInc/mbed,mikaleppanen/mbed-os,radhika-raghavendran/mbed-os5.1-onsemi,brstew/MBED-BUILD,screamerbg/mbed,mbedmicro/mbed,infinnovation/mbed-os,fpiot/mbed-ats,nRFMesh/mbed-os,andreaslarssonublox/mbed,al177/mbed,fanghuaqi/mbed,arostm/mbed-os,xcrespo/mbed,adamgreen/mbed,svogl/mbed-os,nRFMesh/mbed-os,tung7970/mbed-os-1,rosterloh/mbed,Timmmm/mbed,wodji/mbed,mmorenobarm/mbed-os,Timmmm/mbed,al177/mbed,maximmbed/mbed,nvlsianpu/mbed,andcor02/mbed-os,nvlsianpu/mbed,bcostm/mbed-os,kpurusho/mbed,mmorenobarm/mbed-os,rgrover/mbed,RonEld/mbed,RonEld/mbed,andcor02/mbed-os,hwfwgrp/mbed,NXPmicro/mbed,autopulated/mbed,cvtsi2sd/mbed-os,alertby/mbed,Sweet-Peas/mbed,pbrook/mbed,Archcady/mbed-os,mnlipp/mbed,CalSol/mbed,NXPmicro/mbed,K4zuki/mbed,FranklyDev/mbed,larks/mbed,betzw/mbed-os,netzimme/mbed-os,al177/mbed,jamesadevine/mbed,dbestm/mbed,fvincenzo/mbed-os,DanKupiniak/mbed,ARM-software/mbed-beetle,mikaleppanen/mbed-os,larks/mbed,NitinBhaskar/mbed,ryankurte/mbed-os,mbedmicro/mbed,wodji/mbed,bremoran/mbed-drivers,NXPmicro/mbed,Shengliang/mbed,pradeep-gr/mbed-os5-onsemi,sam-geek/mbed,mikaleppanen/mbed-os,pi19404/mbed,GustavWi/mbed,mmorenobarm/mbed-os,tung7970/mbed-os,pradeep-gr/mbed-os5-onsemi,Tiryoh/mbed,K4zuki/mbed,fahhem/mbed-os,dbestm/mbed,screamerbg/mbed,autopulated/mbed,dbestm/mbed,Tiryoh/mbed,devanlai/mbed,andcor02/mbed-os,svogl/mbed-os,NXPmicro/mbed,svogl/mbed-os,larks/mbed,naves-thiago/mbed-midi,brstew/MBED-BUILD,tung7970/mbed-os-1,jpbrucker/mbed,dbestm/mbed,NordicSemiconductor/mbed,logost/mbed,ban4jp/mbed,netzimme/mbed-os,logost/mbed,CalSol/mbed,0xc0170/mbed-drivers,bremoran/mbed-drivers,EmuxEvans/mbed,rosterloh/mbed,nabilbendafi/mbed,Tiryoh/mbed,fpiot/mbed-ats,ARM-software/mbed-beetle,betzw/mbed-os,pradeep-gr/mbed-os5-onsemi,kl-cruz/mbed-os,Tiryoh/mbed,cvtsi2sd/mbed-os,karsev/mbed-os,hwfwgrp/mbed,fvincenzo/mbed-os,j-greffe/mbed-os,kjbracey-arm/mbed,xcrespo/mbed,monkiineko/mbed-os,adustm/mbed,K4zuki/mbed,K4zuki/mbed,ban4jp/mbed,jrjang/mbed,rgrover/mbed,jferreir/mbed,Timmmm/mbed,GustavWi/mbed,bcostm/mbed-os,logost/mbed,fpiot/mbed-ats,Willem23/mbed,mikaleppanen/mbed-os,sam-geek/mbed,mmorenobarm/mbed-os,YarivCol/mbed-os,andreaslarssonublox/mbed,rosterloh/mbed,devanlai/mbed,rosterloh/mbed,Tiryoh/mbed,EmuxEvans/mbed,getopenmono/mbed,YarivCol/mbed-os,radhika-raghavendran/mbed-os5.1-onsemi,ban4jp/mbed,jpbrucker/mbed,mbedmicro/mbed,EmuxEvans/mbed,bcostm/mbed-os,netzimme/mbed-os,adamgreen/mbed,kpurusho/mbed,devanlai/mbed,monkiineko/mbed-os,tung7970/mbed-os-1,betzw/mbed-os,bikeNomad/mbed,pedromes/mbed,jeremybrodt/mbed,mbedmicro/mbed,theotherjimmy/mbed,svastm/mbed,Shengliang/mbed,jferreir/mbed,theotherjimmy/mbed,JasonHow44/mbed,alertby/mbed,nRFMesh/mbed-os,pi19404/mbed,ARM-software/mbed-beetle,andcor02/mbed-os,mmorenobarm/mbed-os,wodji/mbed,masaohamanaka/mbed,FranklyDev/mbed,autopulated/mbed,screamerbg/mbed,svastm/mbed,infinnovation/mbed-os,andcor02/mbed-os,bcostm/mbed-os,bentwire/mbed,catiedev/mbed-os,cvtsi2sd/mbed-os,andcor02/mbed-os,alertby/mbed,struempelix/mbed,Archcady/mbed-os,svastm/mbed,getopenmono/mbed,Archcady/mbed-os,karsev/mbed-os,Shengliang/mbed,Marcomissyou/mbed,svastm/mbed,nRFMesh/mbed-os,autopulated/mbed,bikeNomad/mbed,catiedev/mbed-os,sam-geek/mbed,kl-cruz/mbed-os,kjbracey-arm/mbed,struempelix/mbed,xcrespo/mbed,Willem23/mbed,netzimme/mbed-os,Timmmm/mbed,jpbrucker/mbed,pedromes/mbed,mnlipp/mbed,betzw/mbed-os,struempelix/mbed,RonEld/mbed,nabilbendafi/mbed,FranklyDev/mbed,masaohamanaka/mbed,alertby/mbed,wodji/mbed,tung7970/mbed-os-1,nRFMesh/mbed-os,maximmbed/mbed,K4zuki/mbed,jrjang/mbed,pedromes/mbed,pi19404/mbed,Shengliang/mbed,Shengliang/mbed,pbrook/mbed,GustavWi/mbed,geky/mbed,monkiineko/mbed-os,Timmmm/mbed,radhika-raghavendran/mbed-os5.1-onsemi,Timmmm/mbed,mnlipp/mbed,hwfwgrp/mbed,pbrook/mbed,pi19404/mbed,RonEld/mbed,kpurusho/mbed,jpbrucker/mbed,j-greffe/mbed-os,jpbrucker/mbed,EmuxEvans/mbed,ryankurte/mbed-os,betzw/mbed-os,svogl/mbed-os,hwfwgrp/mbed,pbrook/mbed,fanghuaqi/mbed,mazimkhan/mbed-os,NordicSemiconductor/mbed,sam-geek/mbed,arostm/mbed-os,bentwire/mbed,alertby/mbed,Marcomissyou/mbed,sam-geek/mbed,CalSol/mbed,masaohamanaka/mbed,geky/mbed,bulislaw/mbed-os,jrjang/mbed,tung7970/mbed-os,arostm/mbed-os,karsev/mbed-os,naves-thiago/mbed-midi,c1728p9/mbed-os,0xc0170/mbed-drivers,fvincenzo/mbed-os,dbestm/mbed,Shengliang/mbed,ARM-software/mbed-beetle,NitinBhaskar/mbed,NordicSemiconductor/mbed,fanghuaqi/mbed,xcrespo/mbed,sg-/mbed-drivers,j-greffe/mbed-os,fanghuaqi/mbed,maximmbed/mbed,adamgreen/mbed,rgrover/mbed,Marcomissyou/mbed,HeadsUpDisplayInc/mbed,jrjang/mbed,bulislaw/mbed-os,autopulated/mbed,tung7970/mbed-os,rosterloh/mbed,jamesadevine/mbed,brstew/MBED-BUILD,naves-thiago/mbed-midi,HeadsUpDisplayInc/mbed,mmorenobarm/mbed-os,bikeNomad/mbed,pedromes/mbed,nRFMesh/mbed-os,EmuxEvans/mbed,Sweet-Peas/mbed,nvlsianpu/mbed,monkiineko/mbed-os,ban4jp/mbed,jferreir/mbed,fvincenzo/mbed-os,hwfwgrp/mbed,JasonHow44/mbed,HeadsUpDisplayInc/mbed,geky/mbed,ryankurte/mbed-os,struempelix/mbed,jferreir/mbed,infinnovation/mbed-os,c1728p9/mbed-os,arostm/mbed-os,NordicSemiconductor/mbed,radhika-raghavendran/mbed-os5.1-onsemi,RonEld/mbed,jamesadevine/mbed,ban4jp/mbed,catiedev/mbed-os,monkiineko/mbed-os,adustm/mbed,Willem23/mbed,andreaslarssonublox/mbed,jferreir/mbed,adamgreen/mbed,c1728p9/mbed-os,Archcady/mbed-os,fahhem/mbed-os,Sweet-Peas/mbed,masaohamanaka/mbed,naves-thiago/mbed-midi,kjbracey-arm/mbed,Marcomissyou/mbed,screamerbg/mbed,Sweet-Peas/mbed,nabilbendafi/mbed,geky/mbed,mazimkhan/mbed-os,nvlsianpu/mbed,Archcady/mbed-os,svogl/mbed-os,Tiryoh/mbed,bulislaw/mbed-os,larks/mbed,struempelix/mbed,bentwire/mbed,nvlsianpu/mbed,hwfwgrp/mbed,nvlsianpu/mbed,logost/mbed,j-greffe/mbed-os,NitinBhaskar/mbed,DanKupiniak/mbed,getopenmono/mbed,al177/mbed,bulislaw/mbed-os,mazimkhan/mbed-os,ryankurte/mbed-os,j-greffe/mbed-os,CalSol/mbed,catiedev/mbed-os,jrjang/mbed,xcrespo/mbed,kl-cruz/mbed-os,kjbracey-arm/mbed,c1728p9/mbed-os,devanlai/mbed,catiedev/mbed-os,jamesadevine/mbed,theotherjimmy/mbed,fvincenzo/mbed-os,pbrook/mbed,cvtsi2sd/mbed-os,maximmbed/mbed,naves-thiago/mbed-midi,ban4jp/mbed,jferreir/mbed,YarivCol/mbed-os,Sweet-Peas/mbed,YarivCol/mbed-os,bcostm/mbed-os,NitinBhaskar/mbed,Willem23/mbed,arostm/mbed-os,pradeep-gr/mbed-os5-onsemi,devanlai/mbed,fpiot/mbed-ats,NXPmicro/mbed,netzimme/mbed-os,karsev/mbed-os,theotherjimmy/mbed,svastm/mbed,brstew/MBED-BUILD,monkiineko/mbed-os,FranklyDev/mbed,NitinBhaskar/mbed,j-greffe/mbed-os,xcrespo/mbed,fpiot/mbed-ats,radhika-raghavendran/mbed-os5.1-onsemi,iriark01/mbed-drivers,betzw/mbed-os,devanlai/mbed,netzimme/mbed-os,logost/mbed,nabilbendafi/mbed,pi19404/mbed,adustm/mbed,HeadsUpDisplayInc/mbed,radhika-raghavendran/mbed-os5.1-onsemi,jeremybrodt/mbed,ryankurte/mbed-os,bulislaw/mbed-os,mazimkhan/mbed-os,K4zuki/mbed,larks/mbed,FranklyDev/mbed,dbestm/mbed,YarivCol/mbed-os,adamgreen/mbed,rgrover/mbed,jamesadevine/mbed,YarivCol/mbed-os,bentwire/mbed,logost/mbed,c1728p9/mbed-os,kpurusho/mbed,Willem23/mbed,autopulated/mbed,karsev/mbed-os,JasonHow44/mbed,andreaslarssonublox/mbed,CalSol/mbed,GustavWi/mbed,infinnovation/mbed-os,cvtsi2sd/mbed-os,catiedev/mbed-os,jeremybrodt/mbed,DanKupiniak/mbed,arostm/mbed-os,fanghuaqi/mbed,bcostm/mbed-os,al177/mbed,adustm/mbed,Marcomissyou/mbed,pi19404/mbed,RonEld/mbed,mazimkhan/mbed-os,iriark01/mbed-drivers,NXPmicro/mbed,kl-cruz/mbed-os,bentwire/mbed,getopenmono/mbed,kl-cruz/mbed-os,pedromes/mbed,jeremybrodt/mbed,brstew/MBED-BUILD,bentwire/mbed,wodji/mbed,theotherjimmy/mbed,Archcady/mbed-os,jamesadevine/mbed,JasonHow44/mbed,getopenmono/mbed,masaohamanaka/mbed,struempelix/mbed,fpiot/mbed-ats,mazimkhan/mbed-os,rosterloh/mbed,tung7970/mbed-os,maximmbed/mbed,brstew/MBED-BUILD,mnlipp/mbed,karsev/mbed-os,EmuxEvans/mbed,tung7970/mbed-os-1,kpurusho/mbed,larks/mbed,adustm/mbed,nabilbendafi/mbed,mikaleppanen/mbed-os,pedromes/mbed,jrjang/mbed,adamgreen/mbed,maximmbed/mbed,pradeep-gr/mbed-os5-onsemi,infinnovation/mbed-os,mnlipp/mbed,fahhem/mbed-os,fahhem/mbed-os,ryankurte/mbed-os,kl-cruz/mbed-os,jpbrucker/mbed,pbrook/mbed,pradeep-gr/mbed-os5-onsemi,mnlipp/mbed,JasonHow44/mbed,getopenmono/mbed,theotherjimmy/mbed,masaohamanaka/mbed
|
a4f558181d767f680334cea6e985060e54ef2e71
|
plugins/match.hpp
|
plugins/match.hpp
|
/*
Copyright (c) 2015, Project OSRM contributors
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.
*/
#ifndef MATCH_HPP
#define MATCH_HPP
#include "plugin_base.hpp"
#include "../algorithms/bayes_classifier.hpp"
#include "../algorithms/object_encoder.hpp"
#include "../data_structures/search_engine.hpp"
#include "../descriptors/descriptor_base.hpp"
#include "../descriptors/json_descriptor.hpp"
#include "../routing_algorithms/map_matching.hpp"
#include "../util/compute_angle.hpp"
#include "../util/integer_range.hpp"
#include "../util/json_logger.hpp"
#include "../util/json_util.hpp"
#include "../util/string_util.hpp"
#include <cstdlib>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin
{
constexpr static const unsigned max_number_of_candidates = 10;
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
using ClassifierT = BayesClassifier<LaplaceDistribution, LaplaceDistribution, double>;
using TraceClassification = ClassifierT::ClassificationT;
public:
MapMatchingPlugin(DataFacadeT *facade, const int max_locations_map_matching)
: descriptor_string("match"), facade(facade),
max_locations_map_matching(max_locations_map_matching),
// the values where derived from fitting a laplace distribution
// to the values of manually classified traces
classifier(LaplaceDistribution(0.005986, 0.016646),
LaplaceDistribution(0.054385, 0.458432),
0.696774) // valid apriori probability
{
search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
}
virtual ~MapMatchingPlugin() {}
const std::string GetDescriptor() const final override { return descriptor_string; }
TraceClassification
classify(const float trace_length, const float matched_length, const int removed_points) const
{
const double distance_feature = -std::log(trace_length) + std::log(matched_length);
// matched to the same point
if (!std::isfinite(distance_feature))
{
return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
}
const auto label_with_confidence = classifier.classify(distance_feature);
return label_with_confidence;
}
bool getCandiates(const std::vector<FixedPointCoordinate> &input_coords,
std::vector<double> &sub_trace_lengths,
osrm::matching::CandidateLists &candidates_lists)
{
double last_distance =
coordinate_calculation::great_circle_distance(input_coords[0], input_coords[1]);
sub_trace_lengths.resize(input_coords.size());
sub_trace_lengths[0] = 0;
for (const auto current_coordinate : osrm::irange<std::size_t>(0, input_coords.size()))
{
bool allow_uturn = false;
if (0 < current_coordinate)
{
last_distance = coordinate_calculation::great_circle_distance(
input_coords[current_coordinate - 1], input_coords[current_coordinate]);
sub_trace_lengths[current_coordinate] +=
sub_trace_lengths[current_coordinate - 1] + last_distance;
}
if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate)
{
double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates(
input_coords[current_coordinate - 1], input_coords[current_coordinate],
input_coords[current_coordinate + 1]);
// sharp turns indicate a possible uturn
if (turn_angle <= 90.0 || turn_angle >= 270.0)
{
allow_uturn = true;
}
}
std::vector<std::pair<PhantomNode, double>> candidates;
if (!facade->IncrementalFindPhantomNodeForCoordinateWithMaxDistance(
input_coords[current_coordinate], candidates, last_distance / 2.0, 5,
max_number_of_candidates))
{
return false;
}
if (allow_uturn)
{
candidates_lists.push_back(candidates);
}
else
{
const auto compact_size = candidates.size();
for (const auto i : osrm::irange<std::size_t>(0, compact_size))
{
// Split edge if it is bidirectional and append reverse direction to end of list
if (candidates[i].first.forward_node_id != SPECIAL_NODEID &&
candidates[i].first.reverse_node_id != SPECIAL_NODEID)
{
PhantomNode reverse_node(candidates[i].first);
reverse_node.forward_node_id = SPECIAL_NODEID;
candidates.push_back(std::make_pair(reverse_node, candidates[i].second));
candidates[i].first.reverse_node_id = SPECIAL_NODEID;
}
}
candidates_lists.push_back(candidates);
}
}
return true;
}
osrm::json::Object submatchingToJSON(const osrm::matching::SubMatching &sub,
const RouteParameters &route_parameters,
const InternalRouteResult &raw_route)
{
osrm::json::Object subtrace;
if (route_parameters.classify)
{
subtrace.values["confidence"] = sub.confidence;
}
if (route_parameters.geometry)
{
DescriptionFactory factory;
FixedPointCoordinate current_coordinate;
factory.SetStartSegment(raw_route.segment_end_coordinates.front().source_phantom,
raw_route.source_traversed_in_reverse.front());
for (const auto i :
osrm::irange<std::size_t>(0, raw_route.unpacked_path_segments.size()))
{
for (const PathData &path_data : raw_route.unpacked_path_segments[i])
{
current_coordinate = facade->GetCoordinateOfNode(path_data.node);
factory.AppendSegment(current_coordinate, path_data);
}
factory.SetEndSegment(raw_route.segment_end_coordinates[i].target_phantom,
raw_route.target_traversed_in_reverse[i],
raw_route.is_via_leg(i));
}
// we need this because we don't run DP
for (auto &segment : factory.path_description)
{
segment.necessary = true;
}
subtrace.values["geometry"] =
factory.AppendGeometryString(route_parameters.compression);
}
subtrace.values["indices"] = osrm::json::make_array(sub.indices);
osrm::json::Array points;
for (const auto &node : sub.nodes)
{
points.values.emplace_back(
osrm::json::make_array(node.location.lat / COORDINATE_PRECISION,
node.location.lon / COORDINATE_PRECISION));
}
subtrace.values["matched_points"] = points;
return subtrace;
}
int HandleRequest(const RouteParameters &route_parameters,
osrm::json::Object &json_result) final override
{
// check number of parameters
if (!check_all_coordinates(route_parameters.coordinates))
{
return 400;
}
std::vector<double> sub_trace_lengths;
osrm::matching::CandidateLists candidates_lists;
const auto &input_coords = route_parameters.coordinates;
const auto &input_timestamps = route_parameters.timestamps;
if (input_timestamps.size() > 0 && input_coords.size() != input_timestamps.size())
{
return 400;
}
// enforce maximum number of locations for performance reasons
if (max_locations_map_matching > 0 &&
static_cast<int>(input_coords.size()) < max_locations_map_matching)
{
return 400;
}
const bool found_candidates =
getCandiates(input_coords, sub_trace_lengths, candidates_lists);
if (!found_candidates)
{
return 400;
}
// setup logging if enabled
if (osrm::json::Logger::get())
osrm::json::Logger::get()->initialize("matching");
// call the actual map matching
osrm::matching::SubMatchingList sub_matchings;
search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps,
route_parameters.matching_beta,
route_parameters.gps_precision, sub_matchings);
if (sub_matchings.empty())
{
return 400;
}
osrm::json::Array matchings;
for (auto &sub : sub_matchings)
{
// classify result
if (route_parameters.classify)
{
double trace_length =
sub_trace_lengths[sub.indices.back()] - sub_trace_lengths[sub.indices.front()];
TraceClassification classification =
classify(trace_length, sub.length,
(sub.indices.back() - sub.indices.front() + 1) - sub.nodes.size());
if (classification.first == ClassifierT::ClassLabel::POSITIVE)
{
sub.confidence = classification.second;
}
else
{
sub.confidence = 1 - classification.second;
}
}
BOOST_ASSERT(sub.nodes.size() > 1);
// FIXME we only run this to obtain the geometry
// The clean way would be to get this directly from the map matching plugin
InternalRouteResult raw_route;
PhantomNodes current_phantom_node_pair;
for (unsigned i = 0; i < sub.nodes.size() - 1; ++i)
{
current_phantom_node_pair.source_phantom = sub.nodes[i];
current_phantom_node_pair.target_phantom = sub.nodes[i + 1];
raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair);
}
search_engine_ptr->shortest_path(
raw_route.segment_end_coordinates,
std::vector<bool>(raw_route.segment_end_coordinates.size(), true), raw_route);
matchings.values.emplace_back(submatchingToJSON(sub, route_parameters, raw_route));
}
if (osrm::json::Logger::get())
osrm::json::Logger::get()->render("matching", json_result);
json_result.values["matchings"] = matchings;
return 200;
}
private:
std::string descriptor_string;
DataFacadeT *facade;
int max_locations_map_matching;
ClassifierT classifier;
};
#endif // MATCH_HPP
|
/*
Copyright (c) 2015, Project OSRM contributors
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.
*/
#ifndef MATCH_HPP
#define MATCH_HPP
#include "plugin_base.hpp"
#include "../algorithms/bayes_classifier.hpp"
#include "../algorithms/object_encoder.hpp"
#include "../data_structures/search_engine.hpp"
#include "../descriptors/descriptor_base.hpp"
#include "../descriptors/json_descriptor.hpp"
#include "../routing_algorithms/map_matching.hpp"
#include "../util/compute_angle.hpp"
#include "../util/integer_range.hpp"
#include "../util/json_logger.hpp"
#include "../util/json_util.hpp"
#include "../util/string_util.hpp"
#include <cstdlib>
#include <algorithm>
#include <memory>
#include <string>
#include <vector>
template <class DataFacadeT> class MapMatchingPlugin : public BasePlugin
{
constexpr static const unsigned max_number_of_candidates = 10;
std::shared_ptr<SearchEngine<DataFacadeT>> search_engine_ptr;
using ClassifierT = BayesClassifier<LaplaceDistribution, LaplaceDistribution, double>;
using TraceClassification = ClassifierT::ClassificationT;
public:
MapMatchingPlugin(DataFacadeT *facade, const int max_locations_map_matching)
: descriptor_string("match"), facade(facade),
max_locations_map_matching(max_locations_map_matching),
// the values where derived from fitting a laplace distribution
// to the values of manually classified traces
classifier(LaplaceDistribution(0.005986, 0.016646),
LaplaceDistribution(0.054385, 0.458432),
0.696774) // valid apriori probability
{
search_engine_ptr = std::make_shared<SearchEngine<DataFacadeT>>(facade);
}
virtual ~MapMatchingPlugin() {}
const std::string GetDescriptor() const final override { return descriptor_string; }
TraceClassification
classify(const float trace_length, const float matched_length, const int removed_points) const
{
const double distance_feature = -std::log(trace_length) + std::log(matched_length);
// matched to the same point
if (!std::isfinite(distance_feature))
{
return std::make_pair(ClassifierT::ClassLabel::NEGATIVE, 1.0);
}
const auto label_with_confidence = classifier.classify(distance_feature);
return label_with_confidence;
}
bool getCandiates(const std::vector<FixedPointCoordinate> &input_coords,
std::vector<double> &sub_trace_lengths,
osrm::matching::CandidateLists &candidates_lists)
{
double last_distance =
coordinate_calculation::great_circle_distance(input_coords[0], input_coords[1]);
sub_trace_lengths.resize(input_coords.size());
sub_trace_lengths[0] = 0;
for (const auto current_coordinate : osrm::irange<std::size_t>(0, input_coords.size()))
{
bool allow_uturn = false;
if (0 < current_coordinate)
{
last_distance = coordinate_calculation::great_circle_distance(
input_coords[current_coordinate - 1], input_coords[current_coordinate]);
sub_trace_lengths[current_coordinate] +=
sub_trace_lengths[current_coordinate - 1] + last_distance;
}
if (input_coords.size() - 1 > current_coordinate && 0 < current_coordinate)
{
double turn_angle = ComputeAngle::OfThreeFixedPointCoordinates(
input_coords[current_coordinate - 1], input_coords[current_coordinate],
input_coords[current_coordinate + 1]);
// sharp turns indicate a possible uturn
if (turn_angle <= 90.0 || turn_angle >= 270.0)
{
allow_uturn = true;
}
}
std::vector<std::pair<PhantomNode, double>> candidates;
if (!facade->IncrementalFindPhantomNodeForCoordinateWithMaxDistance(
input_coords[current_coordinate], candidates, last_distance / 2.0, 5,
max_number_of_candidates))
{
return false;
}
if (allow_uturn)
{
candidates_lists.push_back(candidates);
}
else
{
const auto compact_size = candidates.size();
for (const auto i : osrm::irange<std::size_t>(0, compact_size))
{
// Split edge if it is bidirectional and append reverse direction to end of list
if (candidates[i].first.forward_node_id != SPECIAL_NODEID &&
candidates[i].first.reverse_node_id != SPECIAL_NODEID)
{
PhantomNode reverse_node(candidates[i].first);
reverse_node.forward_node_id = SPECIAL_NODEID;
candidates.push_back(std::make_pair(reverse_node, candidates[i].second));
candidates[i].first.reverse_node_id = SPECIAL_NODEID;
}
}
candidates_lists.push_back(candidates);
}
}
return true;
}
osrm::json::Object submatchingToJSON(const osrm::matching::SubMatching &sub,
const RouteParameters &route_parameters,
const InternalRouteResult &raw_route)
{
osrm::json::Object subtrace;
if (route_parameters.classify)
{
subtrace.values["confidence"] = sub.confidence;
}
if (route_parameters.geometry)
{
DescriptionFactory factory;
FixedPointCoordinate current_coordinate;
factory.SetStartSegment(raw_route.segment_end_coordinates.front().source_phantom,
raw_route.source_traversed_in_reverse.front());
for (const auto i :
osrm::irange<std::size_t>(0, raw_route.unpacked_path_segments.size()))
{
for (const PathData &path_data : raw_route.unpacked_path_segments[i])
{
current_coordinate = facade->GetCoordinateOfNode(path_data.node);
factory.AppendSegment(current_coordinate, path_data);
}
factory.SetEndSegment(raw_route.segment_end_coordinates[i].target_phantom,
raw_route.target_traversed_in_reverse[i],
raw_route.is_via_leg(i));
}
// we need this because we don't run DP
for (auto &segment : factory.path_description)
{
segment.necessary = true;
}
subtrace.values["geometry"] =
factory.AppendGeometryString(route_parameters.compression);
}
subtrace.values["indices"] = osrm::json::make_array(sub.indices);
osrm::json::Array points;
for (const auto &node : sub.nodes)
{
points.values.emplace_back(
osrm::json::make_array(node.location.lat / COORDINATE_PRECISION,
node.location.lon / COORDINATE_PRECISION));
}
subtrace.values["matched_points"] = points;
return subtrace;
}
int HandleRequest(const RouteParameters &route_parameters,
osrm::json::Object &json_result) final override
{
// check number of parameters
if (!check_all_coordinates(route_parameters.coordinates))
{
json_result.values["status"] = "Invalid coordinates.";
return 400;
}
std::vector<double> sub_trace_lengths;
osrm::matching::CandidateLists candidates_lists;
const auto &input_coords = route_parameters.coordinates;
const auto &input_timestamps = route_parameters.timestamps;
if (input_timestamps.size() > 0 && input_coords.size() != input_timestamps.size())
{
json_result.values["status"] = "Number of timestamps does not match number of coordinates .";
return 400;
}
// enforce maximum number of locations for performance reasons
if (max_locations_map_matching > 0 &&
static_cast<int>(input_coords.size()) < max_locations_map_matching)
{
json_result.values["status"] = "Too many coodindates.";
return 400;
}
// enforce maximum number of locations for performance reasons
if (static_cast<int>(input_coords.size()) < 2)
{
json_result.values["status"] = "At least two coordinates needed.";
return 400;
}
const bool found_candidates =
getCandiates(input_coords, sub_trace_lengths, candidates_lists);
if (!found_candidates)
{
json_result.values["status"] = "No suitable matching candidates found.";
return 400;
}
// setup logging if enabled
if (osrm::json::Logger::get())
osrm::json::Logger::get()->initialize("matching");
// call the actual map matching
osrm::matching::SubMatchingList sub_matchings;
search_engine_ptr->map_matching(candidates_lists, input_coords, input_timestamps,
route_parameters.matching_beta,
route_parameters.gps_precision, sub_matchings);
if (sub_matchings.empty())
{
json_result.values["status"] = "No matchings found.";
return 400;
}
osrm::json::Array matchings;
for (auto &sub : sub_matchings)
{
// classify result
if (route_parameters.classify)
{
double trace_length =
sub_trace_lengths[sub.indices.back()] - sub_trace_lengths[sub.indices.front()];
TraceClassification classification =
classify(trace_length, sub.length,
(sub.indices.back() - sub.indices.front() + 1) - sub.nodes.size());
if (classification.first == ClassifierT::ClassLabel::POSITIVE)
{
sub.confidence = classification.second;
}
else
{
sub.confidence = 1 - classification.second;
}
}
BOOST_ASSERT(sub.nodes.size() > 1);
// FIXME we only run this to obtain the geometry
// The clean way would be to get this directly from the map matching plugin
InternalRouteResult raw_route;
PhantomNodes current_phantom_node_pair;
for (unsigned i = 0; i < sub.nodes.size() - 1; ++i)
{
current_phantom_node_pair.source_phantom = sub.nodes[i];
current_phantom_node_pair.target_phantom = sub.nodes[i + 1];
raw_route.segment_end_coordinates.emplace_back(current_phantom_node_pair);
}
search_engine_ptr->shortest_path(
raw_route.segment_end_coordinates,
std::vector<bool>(raw_route.segment_end_coordinates.size(), true), raw_route);
matchings.values.emplace_back(submatchingToJSON(sub, route_parameters, raw_route));
}
if (osrm::json::Logger::get())
osrm::json::Logger::get()->render("matching", json_result);
json_result.values["matchings"] = matchings;
return 200;
}
private:
std::string descriptor_string;
DataFacadeT *facade;
int max_locations_map_matching;
ClassifierT classifier;
};
#endif // MATCH_HPP
|
Add status field to match plugin response
|
Add status field to match plugin response
|
C++
|
bsd-2-clause
|
Conggge/osrm-backend,Conggge/osrm-backend,beemogmbh/osrm-backend,raymond0/osrm-backend,yuryleb/osrm-backend,yuryleb/osrm-backend,hydrays/osrm-backend,arnekaiser/osrm-backend,raymond0/osrm-backend,hydrays/osrm-backend,deniskoronchik/osrm-backend,yuryleb/osrm-backend,deniskoronchik/osrm-backend,bjtaylor1/osrm-backend,beemogmbh/osrm-backend,neilbu/osrm-backend,Project-OSRM/osrm-backend,Project-OSRM/osrm-backend,oxidase/osrm-backend,felixguendling/osrm-backend,bjtaylor1/osrm-backend,frodrigo/osrm-backend,arnekaiser/osrm-backend,arnekaiser/osrm-backend,yuryleb/osrm-backend,KnockSoftware/osrm-backend,deniskoronchik/osrm-backend,Conggge/osrm-backend,raymond0/osrm-backend,beemogmbh/osrm-backend,hydrays/osrm-backend,Conggge/osrm-backend,neilbu/osrm-backend,felixguendling/osrm-backend,duizendnegen/osrm-backend,beemogmbh/osrm-backend,oxidase/osrm-backend,neilbu/osrm-backend,neilbu/osrm-backend,oxidase/osrm-backend,raymond0/osrm-backend,hydrays/osrm-backend,duizendnegen/osrm-backend,KnockSoftware/osrm-backend,arnekaiser/osrm-backend,bjtaylor1/osrm-backend,duizendnegen/osrm-backend,frodrigo/osrm-backend,oxidase/osrm-backend,deniskoronchik/osrm-backend,KnockSoftware/osrm-backend,bjtaylor1/osrm-backend,duizendnegen/osrm-backend,Project-OSRM/osrm-backend,frodrigo/osrm-backend,KnockSoftware/osrm-backend,felixguendling/osrm-backend,frodrigo/osrm-backend,Project-OSRM/osrm-backend
|
9833578a11a1f7e65ce446c0b2b5e2eb6cf849e3
|
test/SeqTests.cpp
|
test/SeqTests.cpp
|
#include <catch.hpp>
#include <rapidcheck-catch.h>
#include "rapidcheck/Seq.h"
#include "util/Generators.h"
#include "util/TemplateProps.h"
#include "util/Logger.h"
using namespace rc;
using namespace rc::test;
namespace {
class LoggingSeqImpl : public Logger
{
public:
LoggingSeqImpl() : Logger() {}
LoggingSeqImpl(std::string theId) : Logger(std::move(theId)) {}
Maybe<std::pair<std::string, std::vector<std::string>>> operator()()
{ return {{ id, log }}; }
};
typedef Seq<std::pair<std::string, std::vector<std::string>>> LoggingSeq;
}
TEST_CASE("Seq") {
SECTION("default constructed Seq is empty") {
REQUIRE_FALSE(Seq<int>().next());
}
SECTION("calls operator()() of the implementation object") {
bool nextCalled = false;
Seq<int> seq = Seq<int>([&]{
nextCalled = true;
return Maybe<int>(1337);
});
REQUIRE(*seq.next() == 1337);
REQUIRE(nextCalled);
}
SECTION("copies implementation if constructed from lvalue") {
LoggingSeqImpl impl("foobar");
LoggingSeq seq(impl);
const auto value = seq.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"copy constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("moves implementation if constructed from rvalue") {
LoggingSeq seq(LoggingSeqImpl("foobar"));
const auto value = seq.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("copy construction copies the implementation object") {
LoggingSeq original(LoggingSeqImpl("foobar"));
auto copy(original);
const auto value = copy.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed",
"copy constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("copy assignment copies the implementation object") {
LoggingSeq original(LoggingSeqImpl("foobar"));
LoggingSeq copy;
copy = original;
const auto value = copy.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed",
"copy constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("move construction neither moves nor copies") {
LoggingSeq original(LoggingSeqImpl("foobar"));
LoggingSeq moved(std::move(original));
const auto value = moved.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("move assignment neither moves nor copies") {
LoggingSeq original(LoggingSeqImpl("foobar"));
LoggingSeq moved;
moved = std::move(original);
const auto value = moved.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("if exception is throw on next(), Seq ends immediately") {
auto x = 0;
const auto seq = Seq<int>([x]() mutable -> Maybe<int> {
if (x == 3)
throw std::string("foobar");
return ++x;
});
REQUIRE(seq == seq::just(1, 2, 3));
}
SECTION("operator==/operator!=") {
propConformsToEquals<Seq<std::string>>();
SECTION("empty sequences are equal") {
REQUIRE(Seq<int>() == Seq<int>());
}
SECTION("an exhausted sequence equals an originally empty sequence") {
auto seq = seq::just(1, 2, 3);
seq.next();
seq.next();
seq.next();
REQUIRE(seq == Seq<int>());
}
prop("sequences with different implementation classes can be equal",
[] (const std::string &a,
const std::string &b,
const std::string &c)
{
auto seqJust = seq::just(a, b, c);
std::vector<std::string> vec{a, b, c};
auto seqContainer = seq::fromContainer(vec);
RC_ASSERT(seqJust == seqContainer);
});
prop("changing a single element leads to inequal sequences",
[] {
const auto elements1 = *gen::suchThat<std::vector<std::string>>(
[](const std::vector<std::string> &x) {
return !x.empty();
});
auto elements2 = elements1;
const auto i = *gen::ranged<std::size_t>(0, elements2.size());
elements2[i] = *gen::distinctFrom(elements2[i]);
RC_ASSERT(seq::fromContainer(elements1) !=
seq::fromContainer(elements2));
});
}
SECTION("makeSeq") {
SECTION("constructs implementation object in place") {
auto seq = makeSeq<LoggingSeqImpl>("foobar");
const auto value = seq.next();
REQUIRE(value->first == "foobar");
std::vector<std::string> expectedLog{"constructed as foobar"};
REQUIRE(value->second == expectedLog);
}
}
}
|
#include <catch.hpp>
#include <rapidcheck-catch.h>
#include "rapidcheck/Seq.h"
#include "util/Generators.h"
#include "util/TemplateProps.h"
#include "util/Logger.h"
using namespace rc;
using namespace rc::test;
namespace {
class LoggingSeqImpl : public Logger
{
public:
LoggingSeqImpl() : Logger() {}
LoggingSeqImpl(std::string theId) : Logger(std::move(theId)) {}
Maybe<std::pair<std::string, std::vector<std::string>>> operator()()
{ return {{ id, log }}; }
};
typedef Seq<std::pair<std::string, std::vector<std::string>>> LoggingSeq;
}
TEST_CASE("Seq") {
SECTION("default constructed Seq is empty") {
REQUIRE_FALSE(Seq<int>().next());
}
SECTION("calls operator()() of the implementation object") {
bool nextCalled = false;
Seq<int> seq = Seq<int>([&]{
nextCalled = true;
return Maybe<int>(1337);
});
REQUIRE(*seq.next() == 1337);
REQUIRE(nextCalled);
}
SECTION("copies implementation if constructed from lvalue") {
LoggingSeqImpl impl("foobar");
LoggingSeq seq(impl);
const auto value = seq.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"copy constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("moves implementation if constructed from rvalue") {
LoggingSeq seq(LoggingSeqImpl("foobar"));
const auto value = seq.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("copy construction copies the implementation object") {
LoggingSeq original(LoggingSeqImpl("foobar"));
auto copy(original);
const auto value = copy.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed",
"copy constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("copy assignment copies the implementation object") {
LoggingSeq original(LoggingSeqImpl("foobar"));
LoggingSeq copy;
copy = original;
const auto value = copy.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed",
"copy constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("move construction neither moves nor copies") {
LoggingSeq original(LoggingSeqImpl("foobar"));
LoggingSeq moved(std::move(original));
const auto value = moved.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("move assignment neither moves nor copies") {
LoggingSeq original(LoggingSeqImpl("foobar"));
LoggingSeq moved;
moved = std::move(original);
const auto value = moved.next();
std::vector<std::string> expectedLog{
"constructed as foobar",
"move constructed"};
REQUIRE(value->first == "foobar");
REQUIRE(value->second == expectedLog);
}
SECTION("if exception is throw on next(), Seq ends immediately") {
auto x = 0;
const auto seq = Seq<int>([x]() mutable -> Maybe<int> {
if (x == 3)
throw std::string("foobar");
return ++x;
});
REQUIRE(seq == seq::just(1, 2, 3));
}
SECTION("operator==/operator!=") {
propConformsToEquals<Seq<std::string>>();
SECTION("empty sequences are equal") {
REQUIRE(Seq<int>() == Seq<int>());
}
SECTION("an exhausted sequence equals an originally empty sequence") {
auto seq = seq::just(1, 2, 3);
seq.next();
seq.next();
seq.next();
REQUIRE(seq == Seq<int>());
}
newprop(
"sequences with different implementation classes can be equal",
[] (const std::string &a,
const std::string &b,
const std::string &c)
{
auto seqJust = seq::just(a, b, c);
std::vector<std::string> vec{a, b, c};
auto seqContainer = seq::fromContainer(vec);
RC_ASSERT(seqJust == seqContainer);
});
newprop(
"changing a single element leads to inequal sequences",
[] {
// TODO non-empty generator
const auto elements1 =
*newgen::suchThat<std::vector<std::string>>(
[](const std::vector<std::string> &x) {
return !x.empty();
});
auto elements2 = elements1;
const auto i = *newgen::inRange<std::size_t>(0, elements2.size());
elements2[i] = *newgen::distinctFrom(elements2[i]);
RC_ASSERT(seq::fromContainer(elements1) !=
seq::fromContainer(elements2));
});
}
SECTION("makeSeq") {
SECTION("constructs implementation object in place") {
auto seq = makeSeq<LoggingSeqImpl>("foobar");
const auto value = seq.next();
REQUIRE(value->first == "foobar");
std::vector<std::string> expectedLog{"constructed as foobar"};
REQUIRE(value->second == expectedLog);
}
}
}
|
Move SeqTests to new framework
|
Move SeqTests to new framework
|
C++
|
bsd-2-clause
|
emil-e/rapidcheck,emil-e/rapidcheck,whoshuu/rapidcheck,emil-e/rapidcheck,tm604/rapidcheck,tm604/rapidcheck,whoshuu/rapidcheck,whoshuu/rapidcheck,tm604/rapidcheck,unapiedra/rapidfuzz,unapiedra/rapidfuzz,unapiedra/rapidfuzz
|
0fc6b70c84c66c0ab247db18d5a01daa34c6f3b4
|
X10_Project/Classes/StageScene.cpp
|
X10_Project/Classes/StageScene.cpp
|
#include "stdafx.h"
//scene
#include "StageScene.h"
#include "MainScene.h"
#include "GameScene.h"
#include "IntroScene.h"
#include "EndingScene.h"
//layer
#include "UILayer.h"
//info
#include "LightManager.h"
#include "StageInformation.h"
//manager
#include "GameManager.h"
//config
#include "ConstVars.h"
#include "FileStuff.h"
//etc
#include "Sling.h"
#include <SimpleAudioEngine.h>
Scene* StageScene::createScene()
{
Scene* scene = Scene::create();
scene->setAnchorPoint(Vec2::ZERO);
scene->setPosition(Vec2::ZERO);
Layer* layer = StageScene::create();
layer->setName("stageScene");
layer->setAnchorPoint(Vec2::ZERO);
layer->setPosition(Vec2::ZERO);
scene->addChild(layer);
return scene;
}
bool StageScene::init()
{
if (!LayerColor::initWithColor(Color4B::BLACK))
{
return false;
}
setName("StageScene");
m_stageToPlay = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTSTAGE);
m_maxStageNum = StageInformation::GetMaxStageNum();
m_background = LoadBackground();
addChild(m_background);
m_lightManager = new LightManager();
if (m_stageToPlay == 13)
{
scheduleOnce(schedule_selector(StageScene::EndingEvent), 0.0f);
return true;
}
SetBGM();
SetupLight();
SetupCharacter();
return true;
}
void StageScene::SetupCharacter()
{
Vector<MenuItem*> menuList;
MenuItemImage* backButton = MakeBackButton();
menuList.pushBack(backButton);
MenuItemImage* menuItem = MenuItemImage::create();
menuItem->setNormalImage(
Sprite::createWithSpriteFrame(
SpriteFrameCache::getInstance()->getSpriteFrameByName(FileStuff::CHARACTER_STANDING)
)
);
menuItem->setSelectedImage(
Sprite::createWithSpriteFrame(
SpriteFrameCache::getInstance()->getSpriteFrameByName(FileStuff::CHARACTER_SELECTED)
)
);
menuItem->setCallback(CC_CALLBACK_0(StageScene::GotoStage, this, m_stageToPlay));
menuItem = MoveCharacter(menuItem, m_stageToPlay);
menuList.pushBack(menuItem);
Menu* menu = Menu::createWithArray(menuList);
menu->setPosition(Vec2::ZERO);
addChild(menu);
}
Point StageScene::GetCharacterPosition(int stage)
{
Size screenSize = Director::getInstance()->getVisibleSize();
if (stage == 0)
{
return Point(screenSize.width / 2 , 0);
}
LightManager mng;
int odd = stage % 2;
Vec2 lightPos = mng.GetPosition(stage);
/* ġ ǥ.*/
float posRatio = .7f ;
Vec2 currentDelta = Vec2(-50, -70);
currentDelta.x *= -(odd);
currentDelta.x -= 20;
return lightPos + posRatio * currentDelta;
}
Sprite* StageScene::LoadBackground()
{
Sprite* background;
switch (m_stageToPlay)
{
case 1:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_01);
break;
case 2:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_02);
break;
case 3:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_03);
break;
case 4:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_04);
break;
case 5:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_05);
break;
case 6:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_06);
break;
case 7:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_07);
break;
case 8:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_08);
break;
case 9:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_09);
break;
case 10:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_10);
break;
case 11:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_11);
break;
case 12:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_12);
break;
case 13:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_13OFF);
break;
}
float scale = (Director::getInstance()->getVisibleSize().width) / (background->getContentSize().width);
background->setAnchorPoint(Point::ZERO);
background->setScale(scale);
return background;
}
void StageScene::SetBGM()
{
if (m_stageToPlay == 9)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(FileStuff::SOUND_BEFORE_ENDING_BACKGROUND, true);
}
else if (m_stageToPlay == 5)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(FileStuff::SOUND_MIDDLE_PHASE_BACKGROUND, true);
}
else if (m_stageToPlay == 1)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(FileStuff::SOUND_INITIAL_BACKGROUND, true);
}
}
void StageScene::SetupLight()
{
int last_played_stage = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTWALKSTAGE);
if (last_played_stage != m_stageToPlay)
{
for (int i = 1; i <= m_maxStageNum && i < last_played_stage; i++)
{
addChild(m_lightManager->GetLight(i));
}
// ȿ
Sprite* lastLight = m_lightManager->GetLight(last_played_stage);
lastLight->setOpacity(0);
FadeIn* fadeIn = FadeIn::create(2.0f);
lastLight->runAction(fadeIn);
addChild(lastLight);
//9ź ҳ
if (m_stageToPlay == 10){
Sprite* girlLikeGhost = Sprite::create(FileStuff::GHOSTGIRL);
girlLikeGhost->setOpacity(10);
girlLikeGhost->setScale(0.3f);
girlLikeGhost->setPosition(37, 45);
Sequence* seq = Sequence::create(DelayTime::create(0.5f),
DelayTime::create(0.5),
FadeTo::create(0.5f,100),
DelayTime::create(0.5f),
FadeOut::create(0.3f),
DelayTime::create(3.0f),
FadeTo::create(0.8f, 70),
FadeOut::create(0.9f),
nullptr
);
girlLikeGhost->runAction(seq);
lastLight->addChild(girlLikeGhost);
}
}
else
{
for (int i = 1; i <= m_maxStageNum && i < m_stageToPlay; i++)
{
addChild(m_lightManager->GetLight(i));
}
}
}
MenuItemImage* StageScene::MoveCharacter(MenuItemImage* character, int stageNum)
{
Point finishPos = GetCharacterPosition(stageNum);
Point startPos = GetCharacterPosition(m_stageToPlay - 1);
Size screenSize = Director::getInstance()->getVisibleSize();
float startScale = character->getScale()* (1 - startPos.y / (screenSize.height * 1.5));
float finishScale = character->getScale() * (1 - finishPos.y / (screenSize.height * 1.5));
float timeLength = 2.0f;
float standingTime = 2.0f;
if (stageNum == 1)
{
standingTime = 0.1f;
}
int last_played_stage = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTWALKSTAGE);
if (last_played_stage != m_stageToPlay)
{
//Ҹ
int stepsound = CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_FOOTSTEP);
//̵
character->setPosition(startPos);
DelayTime* delay = DelayTime::create(standingTime); // ִٰ
MoveTo* move = MoveTo::create(timeLength, finishPos);
Sequence* action = Sequence::create(delay, move, NULL);
character->runAction(action);
//ũ⺯ȭ
character->setScale(startScale);
ScaleTo* scaleAction = ScaleTo::create(timeLength, finishScale);
Sequence* delayAndScale = Sequence::create(delay, scaleAction, NULL);
character->runAction(delayAndScale);
UserDefault::getInstance()->setIntegerForKey(ConstVars::LASTWALKSTAGE, m_stageToPlay);
}
else
{
character->setPosition(finishPos);
character->setScale(startScale);
}
return character;
}
void StageScene::EndingEvent(float dt)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect(FileStuff::SOUND_SHOCKED);
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect(FileStuff::SOUND_CRASH);
Sequence* seq = Sequence::create(
DelayTime::create(2.3f),
CallFuncN::create(CC_CALLBACK_0(StageScene::ShowBlinkingLight, this)),
DelayTime::create(3.0f),
CallFuncN::create(CC_CALLBACK_0(StageScene::ShowDeadbody, this)),
DelayTime::create(2.0f),
CallFuncN::create(CC_CALLBACK_0(StageScene::ChangeToEndingScene, this)),
nullptr);
runAction(seq);
}
void StageScene::ChangeToEndingScene()
{
Director::getInstance()->replaceScene(EndingScene::createScene());
}
void StageScene::ShowDeadbody()
{
m_background->removeFromParent();
m_background = Sprite::create(FileStuff::STAGE_BACKGROUND_13APP);
float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
m_background->setAnchorPoint(Point::ZERO);
m_background->setScale(scale);
addChild(m_background);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_SHOCKED, false, 3.0f);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_CRASH, false, 3.0f);
}
void StageScene::TurnStreetLight(int isOn)
{
m_background->removeFromParent();
if (isOn)
m_background = Sprite::create(FileStuff::STAGE_BACKGROUND_13ON);
else
m_background = Sprite::create(FileStuff::STAGE_BACKGROUND_13OFF);
float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
m_background->setAnchorPoint(Point::ZERO);
m_background->setScale(scale);
addChild(m_background);
}
void StageScene::ShowBlinkingLight()
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_STREETLIGHTS);
CallFunc* lightOff = CallFunc::create(CC_CALLBACK_0(StageScene::TurnStreetLight, this, false));
CallFunc* lightOn = CallFunc::create(CC_CALLBACK_0(StageScene::TurnStreetLight, this, true));
Sequence* seq = Sequence::create(
lightOn,
DelayTime::create(0.25f),
lightOff,
DelayTime::create(1.0f),
lightOn,
DelayTime::create(0.2f),
lightOff,
DelayTime::create(0.2f),
lightOn,
nullptr);
runAction(seq);
}
MenuItemImage* StageScene::MakeBackButton()
{
MenuItemImage* button = MenuItemImage::create(
FileStuff::PAUSEBUTTON,
FileStuff::PAUSEBUTTON_CLICKED,
CC_CALLBACK_1(StageScene::ChangeToMainScene, this));
Size buttonSize = button->getContentSize();
float scale = MIN(
UILayer::PAUSE_BUTTON_WIDTH / buttonSize.width,
UILayer::PAUSE_BUTTON_HEIGHT / buttonSize.height);
button->setScale(scale);
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
button->setPosition(
origin.x + visibleSize.width - buttonSize.width*scale / 2,
origin.y + buttonSize.height*scale / 2
);
return button;
}
void StageScene::GotoStage(Ref* pSender, int stageNum)
{
Scene* scene = GameScene::createScene();
GameScene* gameScene = static_cast<GameScene*>(scene->getChildByName("GameScene"));
GameManager* gameManager = GameManager::GetInstance();
gameManager->SetUILayer(gameScene->GetUILayer());
gameManager->SetGameLayer(gameScene->GetGameLayer());
gameManager->SetStage(stageNum);
TransitionFade* sceneWithEffect = TransitionFade::create(1.5f, scene);
Director::getInstance()->replaceScene(sceneWithEffect);
}
void StageScene::ChangeToMainScene(Ref* pSender)
{
Director::getInstance()->replaceScene(MainScene::createScene());
}
void StageScene::ChangeToStageScene(Ref* pSender)
{
Director::getInstance()->replaceScene(StageScene::createScene());
}
|
#include "stdafx.h"
//scene
#include "StageScene.h"
#include "MainScene.h"
#include "GameScene.h"
#include "IntroScene.h"
#include "EndingScene.h"
//layer
#include "UILayer.h"
//info
#include "LightManager.h"
#include "StageInformation.h"
//manager
#include "GameManager.h"
//config
#include "ConstVars.h"
#include "FileStuff.h"
//etc
#include "Sling.h"
#include <SimpleAudioEngine.h>
Scene* StageScene::createScene()
{
Scene* scene = Scene::create();
scene->setAnchorPoint(Vec2::ZERO);
scene->setPosition(Vec2::ZERO);
Layer* layer = StageScene::create();
layer->setName("stageScene");
layer->setAnchorPoint(Vec2::ZERO);
layer->setPosition(Vec2::ZERO);
scene->addChild(layer);
return scene;
}
bool StageScene::init()
{
if (!LayerColor::initWithColor(Color4B::BLACK))
{
return false;
}
setName("StageScene");
m_stageToPlay = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTSTAGE);
m_maxStageNum = StageInformation::GetMaxStageNum();
m_background = LoadBackground();
addChild(m_background);
m_lightManager = new LightManager();
if (m_stageToPlay == 13)
{
scheduleOnce(schedule_selector(StageScene::EndingEvent), 0.0f);
return true;
}
SetBGM();
SetupLight();
SetupCharacter();
return true;
}
void StageScene::SetupCharacter()
{
Vector<MenuItem*> menuList;
MenuItemImage* backButton = MakeBackButton();
menuList.pushBack(backButton);
MenuItemImage* menuItem = MenuItemImage::create();
menuItem->setNormalImage(
Sprite::createWithSpriteFrame(
SpriteFrameCache::getInstance()->getSpriteFrameByName(FileStuff::CHARACTER_STANDING)
)
);
menuItem->setSelectedImage(
Sprite::createWithSpriteFrame(
SpriteFrameCache::getInstance()->getSpriteFrameByName(FileStuff::CHARACTER_SELECTED)
)
);
menuItem->setCallback(CC_CALLBACK_0(StageScene::GotoStage, this, m_stageToPlay));
menuItem = MoveCharacter(menuItem, m_stageToPlay);
menuList.pushBack(menuItem);
Menu* menu = Menu::createWithArray(menuList);
menu->setPosition(Vec2::ZERO);
addChild(menu);
}
Point StageScene::GetCharacterPosition(int stage)
{
Size screenSize = Director::getInstance()->getVisibleSize();
if (stage == 0)
{
return Point(screenSize.width / 2 , 0);
}
LightManager mng;
int odd = stage % 2;
Vec2 lightPos = mng.GetPosition(stage);
/* ġ ǥ.*/
float posRatio = .7f ;
Vec2 currentDelta = Vec2(-50, -70);
currentDelta.x *= -(odd);
currentDelta.x -= 20;
return lightPos + posRatio * currentDelta;
}
Sprite* StageScene::LoadBackground()
{
Sprite* background;
switch (m_stageToPlay)
{
case 1:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_01);
break;
case 2:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_02);
break;
case 3:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_03);
break;
case 4:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_04);
break;
case 5:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_05);
break;
case 6:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_06);
break;
case 7:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_07);
break;
case 8:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_08);
break;
case 9:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_09);
break;
case 10:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_10);
break;
case 11:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_11);
break;
case 12:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_12);
break;
case 13:
background = Sprite::create(FileStuff::STAGE_BACKGROUND_13OFF);
break;
}
float scale = (Director::getInstance()->getVisibleSize().width) / (background->getContentSize().width);
background->setAnchorPoint(Point::ZERO);
background->setScale(scale);
return background;
}
void StageScene::SetBGM()
{
if (m_stageToPlay == 9)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(FileStuff::SOUND_BEFORE_ENDING_BACKGROUND, true);
}
else if (m_stageToPlay == 5)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(FileStuff::SOUND_MIDDLE_PHASE_BACKGROUND, true);
}
else if (m_stageToPlay == 1)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->stopBackgroundMusic(true);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic(FileStuff::SOUND_INITIAL_BACKGROUND, true);
}
}
void StageScene::SetupLight()
{
int last_played_stage = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTWALKSTAGE);
if (last_played_stage == 0)
{
return;
}
if (last_played_stage != m_stageToPlay)
{
for (int i = 1; i <= m_maxStageNum && i < last_played_stage; i++)
{
addChild(m_lightManager->GetLight(i));
}
// ȿ
Sprite* lastLight = m_lightManager->GetLight(last_played_stage);
lastLight->setOpacity(0);
FadeIn* fadeIn = FadeIn::create(2.0f);
lastLight->runAction(fadeIn);
addChild(lastLight);
//9ź ҳ
if (m_stageToPlay == 10){
Sprite* girlLikeGhost = Sprite::create(FileStuff::GHOSTGIRL);
girlLikeGhost->setOpacity(10);
girlLikeGhost->setScale(0.3f);
girlLikeGhost->setPosition(37, 45);
Sequence* seq = Sequence::create(DelayTime::create(0.5f),
DelayTime::create(0.5),
FadeTo::create(0.5f,100),
DelayTime::create(0.5f),
FadeOut::create(0.3f),
DelayTime::create(3.0f),
FadeTo::create(0.8f, 70),
FadeOut::create(0.9f),
nullptr
);
girlLikeGhost->runAction(seq);
lastLight->addChild(girlLikeGhost);
}
}
else
{
for (int i = 1; i <= m_maxStageNum && i < m_stageToPlay; i++)
{
addChild(m_lightManager->GetLight(i));
}
}
}
MenuItemImage* StageScene::MoveCharacter(MenuItemImage* character, int stageNum)
{
Point finishPos = GetCharacterPosition(stageNum);
Point startPos = GetCharacterPosition(m_stageToPlay - 1);
Size screenSize = Director::getInstance()->getVisibleSize();
float startScale = character->getScale()* (1 - startPos.y / (screenSize.height * 1.5));
float finishScale = character->getScale() * (1 - finishPos.y / (screenSize.height * 1.5));
float timeLength = 2.0f;
float standingTime = 2.0f;
if (stageNum == 1)
{
standingTime = 0.1f;
}
int last_played_stage = UserDefault::getInstance()->getIntegerForKey(ConstVars::LASTWALKSTAGE);
if (last_played_stage != m_stageToPlay)
{
//Ҹ
int stepsound = CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_FOOTSTEP);
//̵
character->setPosition(startPos);
DelayTime* delay = DelayTime::create(standingTime); // ִٰ
MoveTo* move = MoveTo::create(timeLength, finishPos);
Sequence* action = Sequence::create(delay, move, NULL);
character->runAction(action);
//ũ⺯ȭ
character->setScale(startScale);
ScaleTo* scaleAction = ScaleTo::create(timeLength, finishScale);
Sequence* delayAndScale = Sequence::create(delay, scaleAction, NULL);
character->runAction(delayAndScale);
UserDefault::getInstance()->setIntegerForKey(ConstVars::LASTWALKSTAGE, m_stageToPlay);
}
else
{
character->setPosition(finishPos);
character->setScale(startScale);
}
return character;
}
void StageScene::EndingEvent(float dt)
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect(FileStuff::SOUND_SHOCKED);
CocosDenshion::SimpleAudioEngine::sharedEngine()->preloadEffect(FileStuff::SOUND_CRASH);
Sequence* seq = Sequence::create(
DelayTime::create(2.3f),
CallFuncN::create(CC_CALLBACK_0(StageScene::ShowBlinkingLight, this)),
DelayTime::create(3.0f),
CallFuncN::create(CC_CALLBACK_0(StageScene::ShowDeadbody, this)),
DelayTime::create(2.0f),
CallFuncN::create(CC_CALLBACK_0(StageScene::ChangeToEndingScene, this)),
nullptr);
runAction(seq);
}
void StageScene::ChangeToEndingScene()
{
Director::getInstance()->replaceScene(EndingScene::createScene());
}
void StageScene::ShowDeadbody()
{
m_background->removeFromParent();
m_background = Sprite::create(FileStuff::STAGE_BACKGROUND_13APP);
float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
m_background->setAnchorPoint(Point::ZERO);
m_background->setScale(scale);
addChild(m_background);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_SHOCKED, false, 3.0f);
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_CRASH, false, 3.0f);
}
void StageScene::TurnStreetLight(int isOn)
{
m_background->removeFromParent();
if (isOn)
m_background = Sprite::create(FileStuff::STAGE_BACKGROUND_13ON);
else
m_background = Sprite::create(FileStuff::STAGE_BACKGROUND_13OFF);
float scale = (Director::getInstance()->getVisibleSize().width) / (m_background->getContentSize().width);
m_background->setAnchorPoint(Point::ZERO);
m_background->setScale(scale);
addChild(m_background);
}
void StageScene::ShowBlinkingLight()
{
CocosDenshion::SimpleAudioEngine::sharedEngine()->playEffect(FileStuff::SOUND_STREETLIGHTS);
CallFunc* lightOff = CallFunc::create(CC_CALLBACK_0(StageScene::TurnStreetLight, this, false));
CallFunc* lightOn = CallFunc::create(CC_CALLBACK_0(StageScene::TurnStreetLight, this, true));
Sequence* seq = Sequence::create(
lightOn,
DelayTime::create(0.25f),
lightOff,
DelayTime::create(1.0f),
lightOn,
DelayTime::create(0.2f),
lightOff,
DelayTime::create(0.2f),
lightOn,
nullptr);
runAction(seq);
}
MenuItemImage* StageScene::MakeBackButton()
{
MenuItemImage* button = MenuItemImage::create(
FileStuff::PAUSEBUTTON,
FileStuff::PAUSEBUTTON_CLICKED,
CC_CALLBACK_1(StageScene::ChangeToMainScene, this));
Size buttonSize = button->getContentSize();
float scale = MIN(
UILayer::PAUSE_BUTTON_WIDTH / buttonSize.width,
UILayer::PAUSE_BUTTON_HEIGHT / buttonSize.height);
button->setScale(scale);
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
button->setPosition(
origin.x + visibleSize.width - buttonSize.width*scale / 2,
origin.y + buttonSize.height*scale / 2
);
return button;
}
void StageScene::GotoStage(Ref* pSender, int stageNum)
{
Scene* scene = GameScene::createScene();
GameScene* gameScene = static_cast<GameScene*>(scene->getChildByName("GameScene"));
GameManager* gameManager = GameManager::GetInstance();
gameManager->SetUILayer(gameScene->GetUILayer());
gameManager->SetGameLayer(gameScene->GetGameLayer());
gameManager->SetStage(stageNum);
TransitionFade* sceneWithEffect = TransitionFade::create(1.5f, scene);
Director::getInstance()->replaceScene(sceneWithEffect);
}
void StageScene::ChangeToMainScene(Ref* pSender)
{
Director::getInstance()->replaceScene(MainScene::createScene());
}
void StageScene::ChangeToStageScene(Ref* pSender)
{
Director::getInstance()->replaceScene(StageScene::createScene());
}
|
fix bug of UFO piece
|
fix bug of UFO piece
|
C++
|
mit
|
kimsin3003/X10,kimsin3003/X10,kimsin3003/X10,kimsin3003/X10,kimsin3003/X10
|
60ed427b03fa64b28d22082a053f50ddc38e4d23
|
OpenSim/Tests/ExampleMain/testExampleMain.cpp
|
OpenSim/Tests/ExampleMain/testExampleMain.cpp
|
/* -------------------------------------------------------------------------- *
* OpenSim: testExampleMain.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Cassidy Kelly *
* *
* 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. *
* -------------------------------------------------------------------------- */
// Author: Cassidy Kelly
//==============================================================================
//==============================================================================
#include <OpenSim/OpenSim.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
using namespace OpenSim;
using namespace std;
int main()
{
try {
Storage result1("tugOfWar_states.sto"), standard1("std_tugOfWar_states.sto");
CHECK_STORAGE_AGAINST_STANDARD(result1, standard1, Array<double>(0.1, 16), __FILE__, __LINE__, "tugOfWar states failed");
cout << "tugOfWar states passed\n";
Storage result3("tugOfWar_forces.mot"), standard3("std_tugOfWar_forces.mot");
Array<double> tols(1.0, 20);
// 10N is 1% of the muscles maximum isometric force
tols[0] = tols[1] = 10;
CHECK_STORAGE_AGAINST_STANDARD(result3, standard3, tols, __FILE__, __LINE__, "tugOfWar forces failed");
cout << "tugOfWar forces passed\n";
}
catch (const Exception& e) {
e.print(cerr);
return 1;
}
cout << "Done" << endl;
return 0;
}
|
/* -------------------------------------------------------------------------- *
* OpenSim: testExampleMain.cpp *
* -------------------------------------------------------------------------- *
* The OpenSim API is a toolkit for musculoskeletal modeling and simulation. *
* See http://opensim.stanford.edu and the NOTICE file for more information. *
* OpenSim is developed at Stanford University and supported by the US *
* National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA *
* through the Warrior Web program. *
* *
* Copyright (c) 2005-2012 Stanford University and the Authors *
* Author(s): Cassidy Kelly *
* *
* 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. *
* -------------------------------------------------------------------------- */
// Author: Cassidy Kelly
//==============================================================================
//==============================================================================
#include <OpenSim/OpenSim.h>
#include <OpenSim/Auxiliary/auxiliaryTestFunctions.h>
using namespace OpenSim;
using namespace std;
int main()
{
try {
Storage result1("tugOfWar_states.mot"),
standard1("std_tugOfWar_states.sto");
CHECK_STORAGE_AGAINST_STANDARD(result1, standard1,
Array<double>(0.1, 16),
__FILE__,
__LINE__,
"tugOfWar states failed");
cout << "tugOfWar states passed\n";
Storage result3("tugOfWar_forces.mot"),
standard3("std_tugOfWar_forces.mot");
Array<double> tols(1.0, 20);
// 10N is 1% of the muscles maximum isometric force
tols[0] = tols[1] = 10;
CHECK_STORAGE_AGAINST_STANDARD(result3, standard3,
tols,
__FILE__,
__LINE__,
"tugOfWar forces failed");
cout << "tugOfWar forces passed\n";
}
catch (const Exception& e) {
e.print(cerr);
return 1;
}
cout << "Done" << endl;
return 0;
}
|
Read mot file to check against standard instead of reading sto file.
|
Read mot file to check against standard instead of reading sto file.
|
C++
|
apache-2.0
|
opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core,opensim-org/opensim-core
|
d33f68042c0200a910c09abc2af1d6f8c5497cc0
|
modules/prediction/scenario/feature_extractor/feature_extractor_test.cc
|
modules/prediction/scenario/feature_extractor/feature_extractor_test.cc
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/scenario/feature_extractor/feature_extractor.h"
#include <memory>
#include "gtest/gtest.h"
#include "modules/localization/proto/localization.pb.h"
#include "modules/planning/proto/planning.pb.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/container/container_manager.h"
namespace apollo {
namespace prediction {
using apollo::common::adapter::AdapterConfig;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
class FeatureExtractorTest : public KMLMapBasedTest {
public:
virtual void SetUp() {}
protected:
LocalizationEstimate localization_message_;
ADCTrajectory adc_trajectory_;
};
TEST_F(FeatureExtractorTest, junction) {
ContainerManager::instance()->RegisterContainers();
std::unique_ptr<Container> adc_traj_container =
ContainerManager::instance()->CreateContainer(
AdapterConfig::PLANNING_TRAJECTORY);
FeatureExtractor feature_extractor;
feature_extractor.ExtractFrontJunctionFeatures();
ScenarioFeature scenario_feature =
feature_extractor.GetScenarioFeatures();
EXPECT_TRUE(!scenario_feature.has_junction_id());
}
} // namespace prediction
} // namespace apollo
|
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include "modules/prediction/scenario/feature_extractor/feature_extractor.h"
#include <memory>
#include "gtest/gtest.h"
#include "modules/localization/proto/localization.pb.h"
#include "modules/planning/proto/planning.pb.h"
#include "modules/prediction/common/kml_map_based_test.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/container/container_manager.h"
namespace apollo {
namespace prediction {
using apollo::common::adapter::AdapterConfig;
using apollo::localization::LocalizationEstimate;
using apollo::planning::ADCTrajectory;
class FeatureExtractorTest : public KMLMapBasedTest {};
TEST_F(FeatureExtractorTest, junction) {
ContainerManager::instance()->RegisterContainers();
std::unique_ptr<Container> adc_traj_container =
ContainerManager::instance()->CreateContainer(
AdapterConfig::PLANNING_TRAJECTORY);
FeatureExtractor feature_extractor;
feature_extractor.ExtractFrontJunctionFeatures();
ScenarioFeature scenario_feature =
feature_extractor.GetScenarioFeatures();
EXPECT_TRUE(!scenario_feature.has_junction_id());
}
} // namespace prediction
} // namespace apollo
|
refactor feature extractor test
|
Prediction: refactor feature extractor test
|
C++
|
apache-2.0
|
msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo,msbeta/apollo
|
c820d70dcbe045cc9bef05e5831ca09ead0d45c1
|
test/test_2or3_inverse_matrix.cpp
|
test/test_2or3_inverse_matrix.cpp
|
#define BOOST_TEST_MODULE "test_small_inverse_matrix"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include "InverseMatrix.hpp"
#include "test_Defs.hpp"
using ax::test::tolerance;
using ax::test::seed;
#include <random>
BOOST_AUTO_TEST_CASE(matrix_2x2)
{
constexpr std::size_t msize = 2;
std::mt19937 mt(seed);
std::uniform_real_distribution<double> randreal(0e0, 1e0);
ax::RealMatrix<msize,msize> mat;
double det = 0e0;
while(det == 0e0)
{
std::array<std::array<double, msize>, msize> rand1;
for(std::size_t i=0; i<msize; ++i)
for(std::size_t j=0; j<msize; ++j)
mat(i,j) = rand1[i][j] = randreal(mt);
det = ax::determinant(mat);
}
const ax::RealMatrix<msize,msize> inv = inverse(mat);
const ax::RealMatrix<msize,msize> E = inv * mat;
for(std::size_t i=0; i<msize; ++i)
for(std::size_t j=0; j<msize; ++j)
if(i==j)
BOOST_CHECK_CLOSE(E(i,j), 1e0, tolerance);
else
BOOST_CHECK_SMALL(E(i,j), tolerance);
}
BOOST_AUTO_TEST_CASE(matrix_3x3)
{
constexpr std::size_t msize = 3;
std::mt19937 mt(seed);
std::uniform_real_distribution<double> randreal(0e0, 1e0);
ax::RealMatrix<msize,msize> mat;
double det = 0e0;
while(det == 0e0)
{
std::array<std::array<double, msize>, msize> rand1;
for(std::size_t i=0; i<msize; ++i)
for(std::size_t j=0; j<msize; ++j)
mat(i,j) = rand1[i][j] = randreal(mt);
det = ax::determinant(mat);
}
const ax::RealMatrix<msize,msize> inv = inverse(mat);
const ax::RealMatrix<msize,msize> E = inv * mat;
for(std::size_t i=0; i<msize; ++i)
for(std::size_t j=0; j<msize; ++j)
if(i==j)
BOOST_CHECK_CLOSE(E(i,j), 1e0, tolerance);
else
BOOST_CHECK_SMALL(E(i,j), tolerance);
}
|
#define BOOST_TEST_MODULE "test_small_inverse_matrix"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include "../src/InverseMatrix.hpp"
#include "test_Defs.hpp"
using ax::test::tolerance;
using ax::test::seed;
#include <random>
BOOST_AUTO_TEST_CASE(matrix_2x2)
{
constexpr std::size_t msize = 2;
std::mt19937 mt(seed);
std::uniform_real_distribution<double> randreal(0e0, 1e0);
ax::Matrix<double, msize,msize> mat;
double det = 0e0;
while(det == 0e0)
{
std::array<std::array<double, msize>, msize> rand1;
for(std::size_t i=0; i<msize; ++i)
for(std::size_t j=0; j<msize; ++j)
mat(i,j) = rand1[i][j] = randreal(mt);
det = ax::determinant(mat);
}
const ax::Matrix<double, msize,msize> inv = inverse(mat);
const ax::Matrix<double, msize,msize> E = inv * mat;
for(std::size_t i=0; i<msize; ++i)
for(std::size_t j=0; j<msize; ++j)
if(i==j)
BOOST_CHECK_CLOSE(E(i,j), 1e0, tolerance);
else
BOOST_CHECK_SMALL(E(i,j), tolerance);
}
BOOST_AUTO_TEST_CASE(matrix_3x3)
{
constexpr std::size_t msize = 3;
std::mt19937 mt(seed);
std::uniform_real_distribution<double> randreal(0e0, 1e0);
ax::Matrix<double, msize,msize> mat;
double det = 0e0;
while(det == 0e0)
{
std::array<std::array<double, msize>, msize> rand1;
for(std::size_t i=0; i<msize; ++i)
for(std::size_t j=0; j<msize; ++j)
mat(i,j) = rand1[i][j] = randreal(mt);
det = ax::determinant(mat);
}
const ax::Matrix<double, msize,msize> inv = inverse(mat);
const ax::Matrix<double, msize,msize> E = inv * mat;
for(std::size_t i=0; i<msize; ++i)
for(std::size_t j=0; j<msize; ++j)
if(i==j)
BOOST_CHECK_CLOSE(E(i,j), 1e0, tolerance);
else
BOOST_CHECK_SMALL(E(i,j), tolerance);
}
|
add test of small inverse matrix
|
add test of small inverse matrix
|
C++
|
mit
|
ToruNiina/AX
|
b63e84088d5aa5df8e745ff33a0cd0b2955f21a2
|
src/booru/site.cc
|
src/booru/site.cc
|
#include <chrono>
#include <fstream>
#include <iostream>
#include "site.h"
using namespace AhoViewer::Booru;
#include "settings.h"
#include "tempdir.h"
#ifdef HAVE_LIBSECRET
#include <libsecret/secret.h>
#endif // HAVE_LIBSECRET
// 1: page, 2: limit, 3: tags
const std::map<Site::Type, std::string> Site::RequestURI =
{
{ Type::DANBOORU, "/post/index.xml?page=%1&limit=%2&tags=%3" },
{ Type::GELBOORU, "/index.php?page=dapi&s=post&q=index&pid=%1&limit=%2&tags=%3" },
{ Type::MOEBOORU, "/post.xml?page=%1&limit=%2&tags=%3" },
};
// 1: id
const std::map<Site::Type, std::string> Site::PostURI =
{
{ Type::DANBOORU, "/posts/%1" },
{ Type::GELBOORU, "/index.php?page=post&s=view&id=%1" },
{ Type::MOEBOORU, "/post/show/%1" },
};
const std::map<Site::Type, std::string> Site::RegisterURI =
{
{ Type::DANBOORU, "/users/new" },
{ Type::GELBOORU, "/index.php?page=account&s=reg" },
{ Type::MOEBOORU, "/user/signup" },
};
struct _shared_site : public Site
{
template<typename...Ts>
_shared_site(Ts&&...args) : Site(std::forward<Ts>(args)...) { }
};
std::shared_ptr<Site> Site::create(const std::string &name, const std::string &url, const Type type,
const std::string &user, const std::string &pass)
{
Type t = type == Type::UNKNOWN ? get_type_from_url(url) : type;
if (t != Type::UNKNOWN)
return std::make_shared<_shared_site>(name, url, t, user, pass);
return nullptr;
}
const Glib::RefPtr<Gdk::Pixbuf>& Site::get_missing_pixbuf()
{
static const Glib::RefPtr<Gdk::Pixbuf> pixbuf =
Gtk::Invisible().render_icon(Gtk::Stock::MISSING_IMAGE, Gtk::ICON_SIZE_MENU);
return pixbuf;
}
#ifdef HAVE_LIBSECRET
void Site::on_password_lookup(GObject*, GAsyncResult *result, gpointer ptr)
{
GError *error = NULL;
gchar *password = secret_password_lookup_finish(result, &error);
if (!error && password)
{
Site *s = static_cast<Site*>(ptr);
s->m_Password = password;
s->m_PasswordLookup();
secret_password_free(password);
}
else if (error)
{
g_error_free(error);
}
}
void Site::on_password_stored(GObject*, GAsyncResult *result, gpointer ptr)
{
GError *error = NULL;
secret_password_store_finish(result, &error);
if (error)
{
Site *s = static_cast<Site*>(ptr);
std::cerr << "Failed to set password for " << s->get_name() << std::endl
<< " " << error->message << std::endl;
g_error_free(error);
}
}
#endif // HAVE_LIBSECRET
Site::Type Site::get_type_from_url(const std::string &url)
{
Curler curler;
curler.set_no_body();
curler.set_follow_location(false);
for (const Type &type : { Type::GELBOORU, Type::MOEBOORU, Type::DANBOORU })
{
std::string uri(RequestURI.at(type));
if (type == Type::GELBOORU)
uri = uri.substr(0, uri.find("&pid"));
else
uri = uri.substr(0, uri.find("?"));
std::string s(url + uri);
curler.set_url(s);
if (curler.perform() && curler.get_response_code() == 200)
return type;
}
return Type::UNKNOWN;
}
Site::Site(const std::string &name, const std::string &url, const Type type,
const std::string &user, const std::string &pass)
: m_Name(name),
m_Url(url),
m_Username(user),
m_Password(pass),
m_IconPath(Glib::build_filename(Settings.get_booru_path(), m_Name + ".png")),
m_TagsPath(Glib::build_filename(Settings.get_booru_path(), m_Name + "-tags")),
m_CookiePath(Glib::build_filename(Settings.get_booru_path(), m_Name + "-cookie")),
m_Type(type),
m_NewAccount(false),
m_CookieTS(0),
m_IconCurlerThread(nullptr)
{
#ifdef HAVE_LIBSECRET
if (!m_Username.empty())
secret_password_lookup(SECRET_SCHEMA_COMPAT_NETWORK,
NULL,
&Site::on_password_lookup, this,
"user", m_Username.c_str(),
"server", m_Url.c_str(),
NULL);
#endif // HAVE_LIBSECRET
// Load tags
if (Glib::file_test(m_TagsPath, Glib::FILE_TEST_EXISTS))
{
std::ifstream ifs(m_TagsPath);
if (ifs)
std::copy(std::istream_iterator<std::string>(ifs),
std::istream_iterator<std::string>(),
std::inserter(m_Tags, m_Tags.begin()));
}
}
Site::~Site()
{
m_Curler.cancel();
if (m_IconCurlerThread)
{
m_IconCurlerThread->join();
m_IconCurlerThread = nullptr;
}
cleanup_cookie();
}
std::string Site::get_posts_url(const std::string &tags, size_t page)
{
return Glib::ustring::compose(m_Url + RequestURI.at(m_Type),
(m_Type == Type::GELBOORU ? page - 1 : page),
Settings.get_int("BooruLimit"), tags);
}
std::string Site::get_post_url(const std::string &id)
{
return Glib::ustring::compose(m_Url + PostURI.at(m_Type), id);
}
void Site::add_tags(const std::set<std::string> &tags)
{
m_Tags.insert(tags.begin(), tags.end());
}
bool Site::set_url(const std::string &url)
{
if (url != m_Url)
{
Type type = get_type_from_url(url);
if (type == Type::UNKNOWN)
return false;
m_Url = url;
m_Type = type;
}
return true;
}
void Site::set_password(const std::string &s)
{
m_NewAccount = true;
#ifdef HAVE_LIBSECRET
if (!m_Username.empty())
secret_password_store(SECRET_SCHEMA_COMPAT_NETWORK,
SECRET_COLLECTION_DEFAULT,
"password", s.c_str(),
NULL,
&Site::on_password_stored, this,
"user", m_Username.c_str(),
"server", m_Url.c_str(),
NULL);
#endif // HAVE_LIBSECRET
m_Password = s;
}
// FIXME: Hopefully Gelbooru implements basic HTTP Authentication
std::string Site::get_cookie()
{
if (m_Type != Type::GELBOORU)
return "";
if (!m_Username.empty() && !m_Password.empty())
{
using namespace std::chrono;
uint64_t cts = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
if (cts >= m_CookieTS || m_NewAccount)
{
// Get cookie expiration timestamp
if (Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))
{
std::ifstream ifs(m_CookiePath);
std::string line, tok;
while (std::getline(ifs, line))
{
if (line.substr(0, 10).compare("#HttpOnly_") == 0)
line = line.substr(1);
// Skip comments
if (line[0] == '#') continue;
std::istringstream iss(line);
size_t i = 0;
while (std::getline(iss, tok, '\t'))
{
// Timestamp is always at the 4th index
if (i == 4)
{
char *after = nullptr;
uint64_t ts = strtoull(tok.c_str(), &after, 10);
if (ts < m_CookieTS || m_CookieTS == 0)
m_CookieTS = ts;
}
++i;
}
}
}
// Login and get a new cookie
// This does not check whether or not the login succeeded.
if (cts >= m_CookieTS || m_NewAccount)
{
if (Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))
g_unlink(m_CookiePath.c_str());
Curler curler(m_Url + "/index.php?page=account&s=login&code=00");
std::string f = Glib::ustring::compose("user=%1&pass=%2", m_Username, m_Password);
curler.set_cookie_jar(m_CookiePath);
curler.set_post_fields(f);
curler.perform();
m_NewAccount = false;
}
}
}
return m_CookiePath;
}
void Site::cleanup_cookie() const
{
if ((m_Username.empty() || m_Password.empty() || m_NewAccount) &&
Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))
g_unlink(m_CookiePath.c_str());
}
std::string Site::get_path()
{
if (m_Path.empty())
{
m_Path = TempDir::get_instance().make_dir(m_Name);
g_mkdir_with_parents(Glib::build_filename(m_Path, "thumbnails").c_str(), 0755);
}
return m_Path;
}
Glib::RefPtr<Gdk::Pixbuf> Site::get_icon_pixbuf(const bool update)
{
if (!m_IconPixbuf || update)
{
if (!update && Glib::file_test(m_IconPath, Glib::FILE_TEST_EXISTS))
{
m_IconPixbuf = Gdk::Pixbuf::create_from_file(m_IconPath);
}
else
{
m_IconPixbuf = get_missing_pixbuf();
// Attempt to download the site's favicon
m_IconCurlerThread = Glib::Threads::Thread::create([ this ]()
{
for (const std::string &url : { m_Url + "/favicon.ico",
m_Url + "/favicon.png" })
{
m_Curler.set_url(url);
if (m_Curler.perform())
{
Glib::RefPtr<Gdk::PixbufLoader> loader = Gdk::PixbufLoader::create();
loader->set_size(16, 16);
try
{
loader->write(m_Curler.get_data(), m_Curler.get_data_size());
loader->close();
m_IconPixbuf = loader->get_pixbuf();
m_SignalIconDownloaded();
m_IconPixbuf->save(m_IconPath, "png");
break;
}
catch (const Gdk::PixbufError &ex)
{
std::cerr << "Error while creating icon for " << m_Name
<< ": " << std::endl << " " << ex.what() << std::endl;
}
}
}
});
if (update)
{
m_IconCurlerThread->join();
m_IconCurlerThread = nullptr;
}
}
}
return m_IconPixbuf;
}
void Site::save_tags() const
{
std::ofstream ofs(m_TagsPath);
if (ofs)
std::copy(m_Tags.begin(), m_Tags.end(), std::ostream_iterator<std::string>(ofs, "\n"));
}
|
#include <chrono>
#include <fstream>
#include <iostream>
#include "site.h"
using namespace AhoViewer::Booru;
#include "settings.h"
#include "tempdir.h"
#ifdef HAVE_LIBSECRET
#include <libsecret/secret.h>
#endif // HAVE_LIBSECRET
// 1: page, 2: limit, 3: tags
const std::map<Site::Type, std::string> Site::RequestURI =
{
{ Type::DANBOORU, "/post/index.xml?page=%1&limit=%2&tags=%3" },
{ Type::GELBOORU, "/index.php?page=dapi&s=post&q=index&pid=%1&limit=%2&tags=%3" },
{ Type::MOEBOORU, "/post.xml?page=%1&limit=%2&tags=%3" },
};
// 1: id
const std::map<Site::Type, std::string> Site::PostURI =
{
{ Type::DANBOORU, "/posts/%1" },
{ Type::GELBOORU, "/index.php?page=post&s=view&id=%1" },
{ Type::MOEBOORU, "/post/show/%1" },
};
const std::map<Site::Type, std::string> Site::RegisterURI =
{
{ Type::DANBOORU, "/users/new" },
{ Type::GELBOORU, "/index.php?page=account&s=reg" },
{ Type::MOEBOORU, "/user/signup" },
};
struct _shared_site : public Site
{
template<typename...Ts>
_shared_site(Ts&&...args) : Site(std::forward<Ts>(args)...) { }
};
std::shared_ptr<Site> Site::create(const std::string &name, const std::string &url, const Type type,
const std::string &user, const std::string &pass)
{
Type t = type == Type::UNKNOWN ? get_type_from_url(url) : type;
if (t != Type::UNKNOWN)
return std::make_shared<_shared_site>(name, url, t, user, pass);
return nullptr;
}
const Glib::RefPtr<Gdk::Pixbuf>& Site::get_missing_pixbuf()
{
static const Glib::RefPtr<Gdk::Pixbuf> pixbuf =
Gtk::Invisible().render_icon(Gtk::Stock::MISSING_IMAGE, Gtk::ICON_SIZE_MENU);
return pixbuf;
}
#ifdef HAVE_LIBSECRET
void Site::on_password_lookup(GObject*, GAsyncResult *result, gpointer ptr)
{
GError *error = NULL;
gchar *password = secret_password_lookup_finish(result, &error);
Site *s = static_cast<Site*>(ptr);
if (!error && password)
{
s->m_Password = password;
s->m_PasswordLookup();
secret_password_free(password);
}
else if (error)
{
std::cerr << "Failed to lookup password for " << s->get_name() << std::endl
<< " " << error->message << std::endl;
g_error_free(error);
}
}
void Site::on_password_stored(GObject*, GAsyncResult *result, gpointer ptr)
{
GError *error = NULL;
secret_password_store_finish(result, &error);
if (error)
{
Site *s = static_cast<Site*>(ptr);
std::cerr << "Failed to set password for " << s->get_name() << std::endl
<< " " << error->message << std::endl;
g_error_free(error);
}
}
#endif // HAVE_LIBSECRET
Site::Type Site::get_type_from_url(const std::string &url)
{
Curler curler;
curler.set_no_body();
curler.set_follow_location(false);
for (const Type &type : { Type::GELBOORU, Type::MOEBOORU, Type::DANBOORU })
{
std::string uri(RequestURI.at(type));
if (type == Type::GELBOORU)
uri = uri.substr(0, uri.find("&pid"));
else
uri = uri.substr(0, uri.find("?"));
std::string s(url + uri);
curler.set_url(s);
if (curler.perform() && curler.get_response_code() == 200)
return type;
}
return Type::UNKNOWN;
}
Site::Site(const std::string &name, const std::string &url, const Type type,
const std::string &user, const std::string &pass)
: m_Name(name),
m_Url(url),
m_Username(user),
m_Password(pass),
m_IconPath(Glib::build_filename(Settings.get_booru_path(), m_Name + ".png")),
m_TagsPath(Glib::build_filename(Settings.get_booru_path(), m_Name + "-tags")),
m_CookiePath(Glib::build_filename(Settings.get_booru_path(), m_Name + "-cookie")),
m_Type(type),
m_NewAccount(false),
m_CookieTS(0),
m_IconCurlerThread(nullptr)
{
#ifdef HAVE_LIBSECRET
if (!m_Username.empty())
secret_password_lookup(SECRET_SCHEMA_COMPAT_NETWORK,
NULL,
&Site::on_password_lookup, this,
"user", m_Username.c_str(),
"server", m_Url.c_str(),
NULL);
#endif // HAVE_LIBSECRET
// Load tags
if (Glib::file_test(m_TagsPath, Glib::FILE_TEST_EXISTS))
{
std::ifstream ifs(m_TagsPath);
if (ifs)
std::copy(std::istream_iterator<std::string>(ifs),
std::istream_iterator<std::string>(),
std::inserter(m_Tags, m_Tags.begin()));
}
}
Site::~Site()
{
m_Curler.cancel();
if (m_IconCurlerThread)
{
m_IconCurlerThread->join();
m_IconCurlerThread = nullptr;
}
cleanup_cookie();
}
std::string Site::get_posts_url(const std::string &tags, size_t page)
{
return Glib::ustring::compose(m_Url + RequestURI.at(m_Type),
(m_Type == Type::GELBOORU ? page - 1 : page),
Settings.get_int("BooruLimit"), tags);
}
std::string Site::get_post_url(const std::string &id)
{
return Glib::ustring::compose(m_Url + PostURI.at(m_Type), id);
}
void Site::add_tags(const std::set<std::string> &tags)
{
m_Tags.insert(tags.begin(), tags.end());
}
bool Site::set_url(const std::string &url)
{
if (url != m_Url)
{
Type type = get_type_from_url(url);
if (type == Type::UNKNOWN)
return false;
m_Url = url;
m_Type = type;
}
return true;
}
void Site::set_password(const std::string &s)
{
m_NewAccount = true;
#ifdef HAVE_LIBSECRET
if (!m_Username.empty())
secret_password_store(SECRET_SCHEMA_COMPAT_NETWORK,
SECRET_COLLECTION_DEFAULT,
"password", s.c_str(),
NULL,
&Site::on_password_stored, this,
"user", m_Username.c_str(),
"server", m_Url.c_str(),
NULL);
#endif // HAVE_LIBSECRET
m_Password = s;
}
// FIXME: Hopefully Gelbooru implements basic HTTP Authentication
std::string Site::get_cookie()
{
if (m_Type != Type::GELBOORU)
return "";
if (!m_Username.empty() && !m_Password.empty())
{
using namespace std::chrono;
uint64_t cts = duration_cast<seconds>(system_clock::now().time_since_epoch()).count();
if (cts >= m_CookieTS || m_NewAccount)
{
// Get cookie expiration timestamp
if (Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))
{
std::ifstream ifs(m_CookiePath);
std::string line, tok;
while (std::getline(ifs, line))
{
if (line.substr(0, 10).compare("#HttpOnly_") == 0)
line = line.substr(1);
// Skip comments
if (line[0] == '#') continue;
std::istringstream iss(line);
size_t i = 0;
while (std::getline(iss, tok, '\t'))
{
// Timestamp is always at the 4th index
if (i == 4)
{
char *after = nullptr;
uint64_t ts = strtoull(tok.c_str(), &after, 10);
if (ts < m_CookieTS || m_CookieTS == 0)
m_CookieTS = ts;
}
++i;
}
}
}
// Login and get a new cookie
// This does not check whether or not the login succeeded.
if (cts >= m_CookieTS || m_NewAccount)
{
if (Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))
g_unlink(m_CookiePath.c_str());
Curler curler(m_Url + "/index.php?page=account&s=login&code=00");
std::string f = Glib::ustring::compose("user=%1&pass=%2", m_Username, m_Password);
curler.set_cookie_jar(m_CookiePath);
curler.set_post_fields(f);
curler.perform();
m_NewAccount = false;
}
}
}
return m_CookiePath;
}
void Site::cleanup_cookie() const
{
if ((m_Username.empty() || m_Password.empty() || m_NewAccount) &&
Glib::file_test(m_CookiePath, Glib::FILE_TEST_EXISTS))
g_unlink(m_CookiePath.c_str());
}
std::string Site::get_path()
{
if (m_Path.empty())
{
m_Path = TempDir::get_instance().make_dir(m_Name);
g_mkdir_with_parents(Glib::build_filename(m_Path, "thumbnails").c_str(), 0755);
}
return m_Path;
}
Glib::RefPtr<Gdk::Pixbuf> Site::get_icon_pixbuf(const bool update)
{
if (!m_IconPixbuf || update)
{
if (!update && Glib::file_test(m_IconPath, Glib::FILE_TEST_EXISTS))
{
m_IconPixbuf = Gdk::Pixbuf::create_from_file(m_IconPath);
}
else
{
m_IconPixbuf = get_missing_pixbuf();
// Attempt to download the site's favicon
m_IconCurlerThread = Glib::Threads::Thread::create([ this ]()
{
for (const std::string &url : { m_Url + "/favicon.ico",
m_Url + "/favicon.png" })
{
m_Curler.set_url(url);
if (m_Curler.perform())
{
Glib::RefPtr<Gdk::PixbufLoader> loader = Gdk::PixbufLoader::create();
loader->set_size(16, 16);
try
{
loader->write(m_Curler.get_data(), m_Curler.get_data_size());
loader->close();
m_IconPixbuf = loader->get_pixbuf();
m_SignalIconDownloaded();
m_IconPixbuf->save(m_IconPath, "png");
break;
}
catch (const Gdk::PixbufError &ex)
{
std::cerr << "Error while creating icon for " << m_Name
<< ": " << std::endl << " " << ex.what() << std::endl;
}
}
}
});
if (update)
{
m_IconCurlerThread->join();
m_IconCurlerThread = nullptr;
}
}
}
return m_IconPixbuf;
}
void Site::save_tags() const
{
std::ofstream ofs(m_TagsPath);
if (ofs)
std::copy(m_Tags.begin(), m_Tags.end(), std::ostream_iterator<std::string>(ofs, "\n"));
}
|
Print error message when failing to lookup password
|
booru/site: Print error message when failing to lookup password
|
C++
|
mit
|
ahodesuka/ahoviewer,ahodesuka/ahoviewer,ahodesuka/ahoviewer
|
c4a5c14e8aae5916c1742513477106eb170bf9b7
|
webrtc/rtc_tools/event_log_visualizer/main.cc
|
webrtc/rtc_tools/event_log_visualizer/main.cc
|
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <iostream>
#include "webrtc/logging/rtc_event_log/rtc_event_log_parser.h"
#include "webrtc/rtc_base/flags.h"
#include "webrtc/rtc_tools/event_log_visualizer/analyzer.h"
#include "webrtc/rtc_tools/event_log_visualizer/plot_base.h"
#include "webrtc/rtc_tools/event_log_visualizer/plot_python.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/testsupport/fileutils.h"
DEFINE_bool(incoming, true, "Plot statistics for incoming packets.");
DEFINE_bool(outgoing, true, "Plot statistics for outgoing packets.");
DEFINE_bool(plot_all, true, "Plot all different data types.");
DEFINE_bool(plot_packets,
false,
"Plot bar graph showing the size of each packet.");
DEFINE_bool(plot_audio_playout,
false,
"Plot bar graph showing the time between each audio playout.");
DEFINE_bool(plot_audio_level,
false,
"Plot line graph showing the audio level.");
DEFINE_bool(
plot_sequence_number,
false,
"Plot the difference in sequence number between consecutive packets.");
DEFINE_bool(
plot_delay_change,
false,
"Plot the difference in 1-way path delay between consecutive packets.");
DEFINE_bool(plot_accumulated_delay_change,
false,
"Plot the accumulated 1-way path delay change, or the path delay "
"change compared to the first packet.");
DEFINE_bool(plot_total_bitrate,
false,
"Plot the total bitrate used by all streams.");
DEFINE_bool(plot_stream_bitrate,
false,
"Plot the bitrate used by each stream.");
DEFINE_bool(plot_bwe,
false,
"Run the bandwidth estimator with the logged rtp and rtcp and plot "
"the output.");
DEFINE_bool(plot_network_delay_feedback,
false,
"Compute network delay based on sent packets and the received "
"transport feedback.");
DEFINE_bool(plot_fraction_loss,
false,
"Plot packet loss in percent for outgoing packets (as perceived by "
"the send-side bandwidth estimator).");
DEFINE_bool(plot_timestamps,
false,
"Plot the rtp timestamps of all rtp and rtcp packets over time.");
DEFINE_bool(audio_encoder_bitrate_bps,
false,
"Plot the audio encoder target bitrate.");
DEFINE_bool(audio_encoder_frame_length_ms,
false,
"Plot the audio encoder frame length.");
DEFINE_bool(
audio_encoder_uplink_packet_loss_fraction,
false,
"Plot the uplink packet loss fraction which is send to the audio encoder.");
DEFINE_bool(audio_encoder_fec, false, "Plot the audio encoder FEC.");
DEFINE_bool(audio_encoder_dtx, false, "Plot the audio encoder DTX.");
DEFINE_bool(audio_encoder_num_channels,
false,
"Plot the audio encoder number of channels.");
DEFINE_bool(plot_audio_jitter_buffer,
false,
"Plot the audio jitter buffer delay profile.");
DEFINE_string(
force_fieldtrials,
"",
"Field trials control experimental feature code which can be forced. "
"E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enabled/"
" will assign the group Enabled to field trial WebRTC-FooFeature. Multiple "
"trials are separated by \"/\"");
DEFINE_bool(help, false, "prints this message");
DEFINE_bool(
show_detector_state,
false,
"Mark the delay based bwe detector state on the total bitrate graph");
int main(int argc, char* argv[]) {
std::string program_name = argv[0];
std::string usage =
"A tool for visualizing WebRTC event logs.\n"
"Example usage:\n" +
program_name + " <logfile> | python\n" + "Run " + program_name +
" --help for a list of command line options\n";
rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, true);
if (FLAG_help) {
rtc::FlagList::Print(nullptr, false);
return 0;
}
if (argc != 2) {
// Print usage information.
std::cout << usage;
return 0;
}
webrtc::test::SetExecutablePath(argv[0]);
webrtc::test::InitFieldTrialsFromString(FLAG_force_fieldtrials);
std::string filename = argv[1];
webrtc::ParsedRtcEventLog parsed_log;
if (!parsed_log.ParseFile(filename)) {
std::cerr << "Could not parse the entire log file." << std::endl;
std::cerr << "Proceeding to analyze the first "
<< parsed_log.GetNumberOfEvents() << " events in the file."
<< std::endl;
}
webrtc::plotting::EventLogAnalyzer analyzer(parsed_log);
std::unique_ptr<webrtc::plotting::PlotCollection> collection(
new webrtc::plotting::PythonPlotCollection());
if (FLAG_plot_all || FLAG_plot_packets) {
if (FLAG_incoming) {
analyzer.CreatePacketGraph(webrtc::PacketDirection::kIncomingPacket,
collection->AppendNewPlot());
analyzer.CreateAccumulatedPacketsGraph(
webrtc::PacketDirection::kIncomingPacket,
collection->AppendNewPlot());
}
if (FLAG_outgoing) {
analyzer.CreatePacketGraph(webrtc::PacketDirection::kOutgoingPacket,
collection->AppendNewPlot());
analyzer.CreateAccumulatedPacketsGraph(
webrtc::PacketDirection::kOutgoingPacket,
collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_audio_playout) {
analyzer.CreatePlayoutGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_audio_level) {
analyzer.CreateAudioLevelGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_sequence_number) {
if (FLAG_incoming) {
analyzer.CreateSequenceNumberGraph(collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_delay_change) {
if (FLAG_incoming) {
analyzer.CreateDelayChangeGraph(collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_accumulated_delay_change) {
if (FLAG_incoming) {
analyzer.CreateAccumulatedDelayChangeGraph(collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_fraction_loss) {
analyzer.CreateFractionLossGraph(collection->AppendNewPlot());
analyzer.CreateIncomingPacketLossGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_total_bitrate) {
if (FLAG_incoming) {
analyzer.CreateTotalBitrateGraph(webrtc::PacketDirection::kIncomingPacket,
collection->AppendNewPlot(),
FLAG_show_detector_state);
}
if (FLAG_outgoing) {
analyzer.CreateTotalBitrateGraph(webrtc::PacketDirection::kOutgoingPacket,
collection->AppendNewPlot(),
FLAG_show_detector_state);
}
}
if (FLAG_plot_all || FLAG_plot_stream_bitrate) {
if (FLAG_incoming) {
analyzer.CreateStreamBitrateGraph(
webrtc::PacketDirection::kIncomingPacket,
collection->AppendNewPlot());
}
if (FLAG_outgoing) {
analyzer.CreateStreamBitrateGraph(
webrtc::PacketDirection::kOutgoingPacket,
collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_bwe) {
analyzer.CreateBweSimulationGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_network_delay_feedback) {
analyzer.CreateNetworkDelayFeedbackGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_timestamps) {
analyzer.CreateTimestampGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_bitrate_bps) {
analyzer.CreateAudioEncoderTargetBitrateGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_frame_length_ms) {
analyzer.CreateAudioEncoderFrameLengthGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_uplink_packet_loss_fraction) {
analyzer.CreateAudioEncoderUplinkPacketLossFractionGraph(
collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_fec) {
analyzer.CreateAudioEncoderEnableFecGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_dtx) {
analyzer.CreateAudioEncoderEnableDtxGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_num_channels) {
analyzer.CreateAudioEncoderNumChannelsGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_audio_jitter_buffer) {
analyzer.CreateAudioJitterBufferGraph(
webrtc::test::ResourcePath(
"audio_processing/conversational_speech/EN_script2_F_sp2_B1",
"wav"),
48000, collection->AppendNewPlot());
}
collection->Draw();
return 0;
}
|
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include <iostream>
#include "webrtc/logging/rtc_event_log/rtc_event_log_parser.h"
#include "webrtc/rtc_base/flags.h"
#include "webrtc/rtc_tools/event_log_visualizer/analyzer.h"
#include "webrtc/rtc_tools/event_log_visualizer/plot_base.h"
#include "webrtc/rtc_tools/event_log_visualizer/plot_python.h"
#include "webrtc/test/field_trial.h"
#include "webrtc/test/testsupport/fileutils.h"
DEFINE_bool(incoming, true, "Plot statistics for incoming packets.");
DEFINE_bool(outgoing, true, "Plot statistics for outgoing packets.");
DEFINE_bool(plot_all, true, "Plot all different data types.");
DEFINE_bool(plot_packets,
false,
"Plot bar graph showing the size of each packet.");
DEFINE_bool(plot_audio_playout,
false,
"Plot bar graph showing the time between each audio playout.");
DEFINE_bool(plot_audio_level,
false,
"Plot line graph showing the audio level.");
DEFINE_bool(
plot_sequence_number,
false,
"Plot the difference in sequence number between consecutive packets.");
DEFINE_bool(
plot_delay_change,
false,
"Plot the difference in 1-way path delay between consecutive packets.");
DEFINE_bool(plot_accumulated_delay_change,
false,
"Plot the accumulated 1-way path delay change, or the path delay "
"change compared to the first packet.");
DEFINE_bool(plot_total_bitrate,
false,
"Plot the total bitrate used by all streams.");
DEFINE_bool(plot_stream_bitrate,
false,
"Plot the bitrate used by each stream.");
DEFINE_bool(plot_bwe,
false,
"Run the bandwidth estimator with the logged rtp and rtcp and plot "
"the output.");
DEFINE_bool(plot_network_delay_feedback,
false,
"Compute network delay based on sent packets and the received "
"transport feedback.");
DEFINE_bool(plot_fraction_loss,
false,
"Plot packet loss in percent for outgoing packets (as perceived by "
"the send-side bandwidth estimator).");
DEFINE_bool(plot_timestamps,
false,
"Plot the rtp timestamps of all rtp and rtcp packets over time.");
DEFINE_bool(audio_encoder_bitrate_bps,
false,
"Plot the audio encoder target bitrate.");
DEFINE_bool(audio_encoder_frame_length_ms,
false,
"Plot the audio encoder frame length.");
DEFINE_bool(
audio_encoder_uplink_packet_loss_fraction,
false,
"Plot the uplink packet loss fraction which is send to the audio encoder.");
DEFINE_bool(audio_encoder_fec, false, "Plot the audio encoder FEC.");
DEFINE_bool(audio_encoder_dtx, false, "Plot the audio encoder DTX.");
DEFINE_bool(audio_encoder_num_channels,
false,
"Plot the audio encoder number of channels.");
DEFINE_bool(plot_audio_jitter_buffer,
false,
"Plot the audio jitter buffer delay profile.");
DEFINE_string(
force_fieldtrials,
"",
"Field trials control experimental feature code which can be forced. "
"E.g. running with --force_fieldtrials=WebRTC-FooFeature/Enabled/"
" will assign the group Enabled to field trial WebRTC-FooFeature. Multiple "
"trials are separated by \"/\"");
DEFINE_bool(help, false, "prints this message");
DEFINE_bool(
show_detector_state,
false,
"Mark the delay based bwe detector state on the total bitrate graph");
int main(int argc, char* argv[]) {
std::string program_name = argv[0];
std::string usage =
"A tool for visualizing WebRTC event logs.\n"
"Example usage:\n" +
program_name + " <logfile> | python\n" + "Run " + program_name +
" --help for a list of command line options\n";
rtc::FlagList::SetFlagsFromCommandLine(&argc, argv, true);
if (argc != 2 || FLAG_help) {
// Print usage information.
std::cout << usage;
if (FLAG_help)
rtc::FlagList::Print(nullptr, false);
return 0;
}
webrtc::test::SetExecutablePath(argv[0]);
webrtc::test::InitFieldTrialsFromString(FLAG_force_fieldtrials);
std::string filename = argv[1];
webrtc::ParsedRtcEventLog parsed_log;
if (!parsed_log.ParseFile(filename)) {
std::cerr << "Could not parse the entire log file." << std::endl;
std::cerr << "Proceeding to analyze the first "
<< parsed_log.GetNumberOfEvents() << " events in the file."
<< std::endl;
}
webrtc::plotting::EventLogAnalyzer analyzer(parsed_log);
std::unique_ptr<webrtc::plotting::PlotCollection> collection(
new webrtc::plotting::PythonPlotCollection());
if (FLAG_plot_all || FLAG_plot_packets) {
if (FLAG_incoming) {
analyzer.CreatePacketGraph(webrtc::PacketDirection::kIncomingPacket,
collection->AppendNewPlot());
analyzer.CreateAccumulatedPacketsGraph(
webrtc::PacketDirection::kIncomingPacket,
collection->AppendNewPlot());
}
if (FLAG_outgoing) {
analyzer.CreatePacketGraph(webrtc::PacketDirection::kOutgoingPacket,
collection->AppendNewPlot());
analyzer.CreateAccumulatedPacketsGraph(
webrtc::PacketDirection::kOutgoingPacket,
collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_audio_playout) {
analyzer.CreatePlayoutGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_audio_level) {
analyzer.CreateAudioLevelGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_sequence_number) {
if (FLAG_incoming) {
analyzer.CreateSequenceNumberGraph(collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_delay_change) {
if (FLAG_incoming) {
analyzer.CreateDelayChangeGraph(collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_accumulated_delay_change) {
if (FLAG_incoming) {
analyzer.CreateAccumulatedDelayChangeGraph(collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_fraction_loss) {
analyzer.CreateFractionLossGraph(collection->AppendNewPlot());
analyzer.CreateIncomingPacketLossGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_total_bitrate) {
if (FLAG_incoming) {
analyzer.CreateTotalBitrateGraph(webrtc::PacketDirection::kIncomingPacket,
collection->AppendNewPlot(),
FLAG_show_detector_state);
}
if (FLAG_outgoing) {
analyzer.CreateTotalBitrateGraph(webrtc::PacketDirection::kOutgoingPacket,
collection->AppendNewPlot(),
FLAG_show_detector_state);
}
}
if (FLAG_plot_all || FLAG_plot_stream_bitrate) {
if (FLAG_incoming) {
analyzer.CreateStreamBitrateGraph(
webrtc::PacketDirection::kIncomingPacket,
collection->AppendNewPlot());
}
if (FLAG_outgoing) {
analyzer.CreateStreamBitrateGraph(
webrtc::PacketDirection::kOutgoingPacket,
collection->AppendNewPlot());
}
}
if (FLAG_plot_all || FLAG_plot_bwe) {
analyzer.CreateBweSimulationGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_network_delay_feedback) {
analyzer.CreateNetworkDelayFeedbackGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_timestamps) {
analyzer.CreateTimestampGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_bitrate_bps) {
analyzer.CreateAudioEncoderTargetBitrateGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_frame_length_ms) {
analyzer.CreateAudioEncoderFrameLengthGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_uplink_packet_loss_fraction) {
analyzer.CreateAudioEncoderUplinkPacketLossFractionGraph(
collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_fec) {
analyzer.CreateAudioEncoderEnableFecGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_dtx) {
analyzer.CreateAudioEncoderEnableDtxGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_audio_encoder_num_channels) {
analyzer.CreateAudioEncoderNumChannelsGraph(collection->AppendNewPlot());
}
if (FLAG_plot_all || FLAG_plot_audio_jitter_buffer) {
analyzer.CreateAudioJitterBufferGraph(
webrtc::test::ResourcePath(
"audio_processing/conversational_speech/EN_script2_F_sp2_B1",
"wav"),
48000, collection->AppendNewPlot());
}
collection->Draw();
return 0;
}
|
Print general usage information for event_log_analyzer
|
Print general usage information for event_log_analyzer
Print general usage information for event_log_analyzer (in addition to listing the command line flags) when called with '--help'.
BUG=None
Review-Url: https://codereview.webrtc.org/2986573002
Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#19104}
|
C++
|
bsd-3-clause
|
ShiftMediaProject/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc,ShiftMediaProject/libilbc,ShiftMediaProject/libilbc,TimothyGu/libilbc
|
18da266aa13efcb0948c954009fbbc4c6f297d58
|
src/bxconvert.cpp
|
src/bxconvert.cpp
|
#include "bxconvert.h"
#include <getopt.h>
#include <iostream>
#include <sstream>
#include "SeqLib/BamReader.h"
#include "SeqLib/BamWriter.h"
#include "SeqLib/GenomicRegionCollection.h"
#include "bxcommon.h"
namespace opt {
static std::string bam; // the bam to analyze
static bool verbose = false;
static int width = 1000;
static int overlap = 0;
static std::string bed; // optional bed file
}
static const char* shortopts = "hvw:O:b:";
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "bed", required_argument, NULL, 'b' },
{ "pad", required_argument, NULL, 'p' },
{ "width", required_argument, NULL, 'w' },
{ "overlap", required_argument, NULL, 'O' },
{ NULL, 0, NULL, 0 }
};
void runConvert(int argc, char** argv) {
parseConvertOptions(argc, argv);
SeqLib::BamReader reader;
BXOPEN(reader, opt::bam);
SeqLib::BamHeader hdr = reader.Header();
SeqLib::BamRecord r;
size_t count = 0;
std::unordered_map<std::string, size_t> bxtags;
while (reader.GetNextRecord(r)){
if (!bxtags.count(r.GetZTag("BX"))) {
bxtags.insert(std::pair<std::string, size_t>(r.GetZTag("BX"), ++count));
}
std::string chr = hdr.IDtoName(r.ChrID());
r.SetChrID(bxtags[r.GetZTag("BX")]);
r.AddZTag("CR", chr);
}
}
void parseConvertOptions(int argc, char** argv) {
bool die = false;
bool help = false;
if (argc < 2)
die = true;
opt::bam = std::string(argv[1]);
std::stringstream ss;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) \
{
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case 'v': opt::verbose = true; break;
case 'h': help = true; break;
case 'w': arg >> opt::width; break;
case 'O': arg >> opt::overlap; break;
case 'b': arg >> opt::bed; break;
}
}
}
|
#include "bxconvert.h"
#include <getopt.h>
#include <iostream>
#include <sstream>
#include "SeqLib/BamReader.h"
#include "SeqLib/BamWriter.h"
#include "SeqLib/GenomicRegionCollection.h"
#include "bxcommon.h"
#include <cassert>
namespace opt {
static std::string bam; // the bam to analyze
static std::string analysis_id = "foo"; // unique prefix for new BAM output
static bool verbose = false;
static int width = 1000;
static std::string bed; // optional bed file
}
static const char* shortopts = "hvw:a:b:";
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "bed", required_argument, NULL, 'b' },
{ "pad", required_argument, NULL, 'p' },
{ "width", required_argument, NULL, 'w' },
{ "analysis-id", required_argument, NULL, 'a' },
{ NULL, 0, NULL, 0 }
};
void runConvert(int argc, char** argv) {
parseConvertOptions(argc, argv);
SeqLib::BamReader reader;
BXOPEN(reader, opt::bam);
SeqLib::BamHeader hdr = reader.Header();
SeqLib::BamRecord r;
SeqLib::BamWriter w;
size_t count = 0;
std::unordered_map<std::string, size_t> bxtags;
std::stringstream ss;
const std::string empty_tag = "Empty";
if (opt::bam.compare("-") == 0){
std::cerr << "Cant accept standard input as file" << std::endl;
exit(EXIT_FAILURE);
}
// Loop through file once to grab all BX tags and store in string to generate header
ss << "@HD" << "\t" << "VN:1.4" << " " << "GO:none SO:unsorted" << std::endl;
while (reader.GetNextRecord(r)){
std::string bx = r.GetZTag("BX");
if (bx.empty()){
bx = empty_tag;
}
assert(!bx.empty());
if (!bxtags.count(bx)) {
bxtags.insert(std::pair<std::string, size_t>(bx, count));
++count;
ss << "@SQ" << "\t" << "SN:" << bx << "\t" << "LN:500000000" << std::endl;
}
}
//write new header based on string generated from BX tags
SeqLib::BamHeader bxbamheader (ss.str());
//std::string newbname = opt::analysis_id + "_BXsorted" + ".bam";
w.Open("/broad/hptmp/tkamath/foobar.bam");
w.SetHeader(bxbamheader);
w.WriteHeader();
//Loop through the BAM file again
reader.Close();
SeqLib::BamReader reader2;
BXOPEN(reader2, opt::bam);
SeqLib::BamRecord rr;
while (reader2.GetNextRecord(rr)){
std::string bx = rr.GetZTag("BX");
if (bx.empty()){
bx = empty_tag;
}
std::string chr = hdr.IDtoName(rr.ChrID());
rr.SetChrID(bxtags[bx]);
rr.AddZTag("CR", chr);
w.WriteRecord(rr);
}
w.Close();
}
void parseConvertOptions(int argc, char** argv) {
bool die = false;
bool help = false;
if (argc < 2)
die = true;
opt::bam = std::string(argv[1]);
std::stringstream ss;
for (char c; (c = getopt_long(argc, argv, shortopts, longopts, NULL)) != -1;) \
{
std::istringstream arg(optarg != NULL ? optarg : "");
switch (c) {
case 'v': opt::verbose = true; break;
case 'h': help = true; break;
case 'w': arg >> opt::width; break;
case 'a': arg >> opt::analysis_id; break;
case 'b': arg >> opt::bed; break;
}
}
}
|
Convert function successfully creates BX-indexed BAM file from regular BAM
|
Convert function successfully creates BX-indexed BAM file from regular BAM
|
C++
|
mit
|
walaj/bxtools,walaj/bxtools,walaj/bxtools
|
dd61ada9fb06c7171743f37eaa008bb5eabf0cdb
|
tests/memory/memory_allocator.cpp
|
tests/memory/memory_allocator.cpp
|
#include <catch2/catch.hpp>
#include <Windows.h>
#include <renhook/memory/memory_allocator.hpp>
#include <renhook/memory/virtual_protect.hpp>
TEST_CASE("memory::memory_allocator", "[memory][memory_allocator]")
{
SYSTEM_INFO system_info = { 0 };
GetSystemInfo(&system_info);
size_t region_size = system_info.dwAllocationGranularity;
auto minimum_address = reinterpret_cast<uintptr_t>(system_info.lpMinimumApplicationAddress);
auto maximum_address = reinterpret_cast<uintptr_t>(system_info.lpMaximumApplicationAddress);
renhook::memory::memory_allocator allocator;
char* block_a = static_cast<char*>(allocator.alloc(0, -1));
MEMORY_BASIC_INFORMATION memoryInfo = { 0 };
VirtualQuery(block_a, &memoryInfo, sizeof(memoryInfo));
REQUIRE(memoryInfo.Protect == PAGE_EXECUTE_READ);
renhook::memory::virtual_protect protection(block_a, renhook::memory::memory_allocator::block_size, renhook::memory::protection::write);
REQUIRE(block_a != nullptr);
block_a[0] = '1';
block_a[255] = '1';
auto block_b = allocator.alloc(minimum_address + 0x10000, minimum_address + 0x20000);
REQUIRE(block_b != nullptr);
auto block_c = allocator.alloc(minimum_address + 0x10000, minimum_address + 0x10500);
REQUIRE(block_c != nullptr);
size_t diff = std::abs(reinterpret_cast<intptr_t>(block_c) - reinterpret_cast<intptr_t>(block_b));
REQUIRE(diff < region_size);
REQUIRE_THROWS(allocator.alloc(minimum_address + 0x10500, minimum_address + 0x20000));
auto block_d = allocator.alloc(minimum_address + 0x30000, maximum_address);
REQUIRE(block_d != nullptr);
diff = std::abs(reinterpret_cast<intptr_t>(block_d) - reinterpret_cast<intptr_t>(block_b));
REQUIRE(diff >= region_size);
std::vector<void*> blocks;
for (size_t i = 0; i < 10000; i++)
{
auto block = allocator.alloc(0, -1);
blocks.emplace_back(block);
}
auto block_e = allocator.alloc(0, -1);
auto block_f = allocator.alloc(0, -1);
auto block_g = allocator.alloc(0, -1);
allocator.free(block_a);
auto block_h = allocator.alloc(0, -1);
allocator.free(block_b);
allocator.free(block_c);
allocator.free(block_g);
auto block_i = allocator.alloc(0, -1);
allocator.free(block_h);
allocator.free(block_d);
allocator.free(block_e);
allocator.free(block_f);
allocator.free(block_i);
for (auto block : blocks)
{
allocator.free(block);
}
}
|
#include <catch2/catch.hpp>
#include <Windows.h>
#include <renhook/memory/memory_allocator.hpp>
#include <renhook/memory/virtual_protect.hpp>
TEST_CASE("memory::memory_allocator", "[memory][memory_allocator]")
{
SYSTEM_INFO system_info = { 0 };
GetSystemInfo(&system_info);
size_t region_size = system_info.dwAllocationGranularity;
auto minimum_address = reinterpret_cast<uintptr_t>(system_info.lpMinimumApplicationAddress);
auto maximum_address = reinterpret_cast<uintptr_t>(system_info.lpMaximumApplicationAddress);
renhook::memory::memory_allocator allocator;
char* block_a = static_cast<char*>(allocator.alloc(0, -1));
MEMORY_BASIC_INFORMATION memoryInfo = { 0 };
VirtualQuery(block_a, &memoryInfo, sizeof(memoryInfo));
REQUIRE(memoryInfo.Protect == PAGE_EXECUTE_READ);
renhook::memory::virtual_protect protection(block_a, renhook::memory::memory_allocator::block_size, renhook::memory::protection::write);
REQUIRE(block_a != nullptr);
block_a[0] = '1';
block_a[255] = '1';
auto block_b = allocator.alloc(minimum_address + 0x10000, maximum_address / 2);
REQUIRE(block_b != nullptr);
auto block_c = allocator.alloc(minimum_address + 0x10000, maximum_address / 2 + 0x500);
REQUIRE(block_c != nullptr);
size_t diff = std::abs(reinterpret_cast<intptr_t>(block_c) - reinterpret_cast<intptr_t>(block_b));
REQUIRE(diff < region_size);
REQUIRE_THROWS(allocator.alloc(minimum_address + 0x10500, maximum_address / 2));
auto block_d = allocator.alloc(maximum_address / 2 + 0x100, maximum_address);
REQUIRE(block_d != nullptr);
diff = std::abs(reinterpret_cast<intptr_t>(block_d) - reinterpret_cast<intptr_t>(block_b));
REQUIRE(diff >= region_size);
std::vector<void*> blocks;
for (size_t i = 0; i < 10000; i++)
{
auto block = allocator.alloc(0, -1);
blocks.emplace_back(block);
}
auto block_e = allocator.alloc(0, -1);
auto block_f = allocator.alloc(0, -1);
auto block_g = allocator.alloc(0, -1);
allocator.free(block_a);
auto block_h = allocator.alloc(0, -1);
allocator.free(block_b);
allocator.free(block_c);
allocator.free(block_g);
auto block_i = allocator.alloc(0, -1);
allocator.free(block_h);
allocator.free(block_d);
allocator.free(block_e);
allocator.free(block_f);
allocator.free(block_i);
for (auto block : blocks)
{
allocator.free(block);
}
}
|
Increase the lower and upper bounds for tests
|
Increase the lower and upper bounds for tests
|
C++
|
mit
|
WopsS/RenHook
|
0811aff6207c9299dd4a8ea38b4bca2bfeab7405
|
test/test_rss.cpp
|
test/test_rss.cpp
|
/*
Copyright (c) 2012, 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"
#include "libtorrent/rss.hpp"
#include "libtorrent/fingerprint.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#include "libtorrent/http_parser.hpp"
#include "test.hpp"
using namespace libtorrent;
void print_feed(feed_status const& f)
{
fprintf(stderr, "FEED: %s\n",f.url.c_str());
if (f.error)
fprintf(stderr, "ERROR: %s\n", f.error.message().c_str());
fprintf(stderr, " %s\n %s\n", f.title.c_str(), f.description.c_str());
fprintf(stderr, " ttl: %d minutes\n", f.ttl);
fprintf(stderr, " num items: %d\n", int(f.items.size()));
for (std::vector<feed_item>::const_iterator i = f.items.begin()
, end(f.items.end()); i != end; ++i)
{
fprintf(stderr, "\033[32m%s\033[0m\n------------------------------------------------------\n"
" url: %s\n size: %"PRId64"\n info-hash: %s\n uuid: %s\n description: %s\n"
" comment: %s\n category: %s\n"
, i->title.c_str(), i->url.c_str(), i->size
, i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str()
, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());
}
}
struct rss_expect
{
rss_expect(int nitems, std::string url, std::string title, size_type size)
: num_items(nitems), first_url(url), first_title(title), first_size(size)
{}
int num_items;
std::string first_url;
std::string first_title;
size_type first_size;
};
void test_feed(std::string const& filename, rss_expect const& expect)
{
std::vector<char> buffer;
error_code ec;
load_file(filename, buffer, ec);
if (ec)
{
fprintf(stderr, "failed to load file \"%s\": %s\n", filename.c_str(), ec.message().c_str());
}
TEST_CHECK(!ec);
char* buf = buffer.size() ? &buffer[0] : NULL;
int len = buffer.size();
char const header[] = "HTTP/1.1 200 OK\r\n"
"\r\n";
boost::shared_ptr<aux::session_impl> s = boost::shared_ptr<aux::session_impl>(new aux::session_impl(
std::make_pair(100, 200), fingerprint("TT", 0, 0, 0 ,0), NULL, 0));
s->start_session();
feed_settings sett;
sett.auto_download = false;
sett.auto_map_handles = false;
boost::shared_ptr<feed> f = boost::shared_ptr<feed>(new feed(*s, sett));
http_parser parser;
bool err = false;
parser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err);
TEST_CHECK(err == false);
f->on_feed(error_code(), parser, buf, len);
feed_status st;
f->get_feed_status(&st);
TEST_CHECK(!st.error);
print_feed(st);
TEST_CHECK(st.items.size() == expect.num_items);
if (st.items.size() > 0)
{
TEST_CHECK(st.items[0].url == expect.first_url);
TEST_CHECK(st.items[0].size == expect.first_size);
TEST_CHECK(st.items[0].title == expect.first_title);
}
entry state;
f->save_state(state);
fprintf(stderr, "feed_state:\n");
#ifdef TORRENT_DEBUG
state.print(std::cerr);
#endif
// TODO: verify some key state is saved in 'state'
}
int test_main()
{
test_feed(combine_path("..", "eztv.xml"), rss_expect(30, "http://torrent.zoink.it/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent", "The Daily Show 2012-02-16 [HDTV - LMAO]", 183442338));
test_feed(combine_path("..", "cb.xml"), rss_expect(50, "http://www.clearbits.net/get/1911-norbergfestival-2011.torrent", "Norbergfestival 2011", 1160773632));
test_feed(combine_path("..", "kat.xml"), rss_expect(25, "http://kat.ph/torrents/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897/", "Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]", 168773863));
test_feed(combine_path("..", "mn.xml"), rss_expect(20, "http://www.mininova.org/get/13203100", "Dexcell - January TwentyTwelve Mix", 137311179));
test_feed(combine_path("..", "pb.xml"), rss_expect(60, "magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D", "Thompson Twins - 1989 - Big Trash [MP3]", 100160904));
return 0;
}
|
/*
Copyright (c) 2012, 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"
#include "libtorrent/rss.hpp"
#include "libtorrent/fingerprint.hpp"
#include "libtorrent/aux_/session_impl.hpp"
#include "libtorrent/http_parser.hpp"
#include "test.hpp"
using namespace libtorrent;
void print_feed(feed_status const& f)
{
fprintf(stderr, "FEED: %s\n",f.url.c_str());
if (f.error)
fprintf(stderr, "ERROR: %s\n", f.error.message().c_str());
fprintf(stderr, " %s\n %s\n", f.title.c_str(), f.description.c_str());
fprintf(stderr, " ttl: %d minutes\n", f.ttl);
fprintf(stderr, " num items: %d\n", int(f.items.size()));
for (std::vector<feed_item>::const_iterator i = f.items.begin()
, end(f.items.end()); i != end; ++i)
{
fprintf(stderr, "\033[32m%s\033[0m\n------------------------------------------------------\n"
" url: %s\n size: %"PRId64"\n info-hash: %s\n uuid: %s\n description: %s\n"
" comment: %s\n category: %s\n"
, i->title.c_str(), i->url.c_str(), i->size
, i->info_hash.is_all_zeros() ? "" : to_hex(i->info_hash.to_string()).c_str()
, i->uuid.c_str(), i->description.c_str(), i->comment.c_str(), i->category.c_str());
}
}
struct rss_expect
{
rss_expect(int nitems, std::string url, std::string title, size_type size)
: num_items(nitems), first_url(url), first_title(title), first_size(size)
{}
int num_items;
std::string first_url;
std::string first_title;
size_type first_size;
};
void test_feed(std::string const& filename, rss_expect const& expect)
{
std::vector<char> buffer;
error_code ec;
load_file(filename, buffer, ec);
if (ec)
{
fprintf(stderr, "failed to load file \"%s\": %s\n", filename.c_str(), ec.message().c_str());
}
TEST_CHECK(!ec);
char* buf = buffer.size() ? &buffer[0] : NULL;
int len = buffer.size();
char const header[] = "HTTP/1.1 200 OK\r\n"
"\r\n";
boost::shared_ptr<aux::session_impl> s = boost::shared_ptr<aux::session_impl>(new aux::session_impl(
std::make_pair(100, 200), fingerprint("TT", 0, 0, 0 ,0), NULL, 0));
s->start_session();
feed_settings sett;
sett.auto_download = false;
sett.auto_map_handles = false;
boost::shared_ptr<feed> f = boost::shared_ptr<feed>(new feed(*s, sett));
http_parser parser;
bool err = false;
parser.incoming(buffer::const_interval(header, header + sizeof(header)-1), err);
TEST_CHECK(err == false);
f->on_feed(error_code(), parser, buf, len);
feed_status st;
f->get_feed_status(&st);
TEST_CHECK(!st.error);
print_feed(st);
TEST_CHECK(st.items.size() == expect.num_items);
if (st.items.size() > 0)
{
TEST_CHECK(st.items[0].url == expect.first_url);
TEST_CHECK(st.items[0].size == expect.first_size);
TEST_CHECK(st.items[0].title == expect.first_title);
}
entry state;
f->save_state(state);
fprintf(stderr, "feed_state:\n");
#ifdef TORRENT_DEBUG
state.print(std::cerr);
#endif
// TODO: verify some key state is saved in 'state'
}
int test_main()
{
std::string root_dir = parent_path(current_working_directory());
test_feed(combine_path(root_dir, "eztv.xml"), rss_expect(30, "http://torrent.zoink.it/The.Daily.Show.2012.02.16.(HDTV-LMAO)[VTV].torrent", "The Daily Show 2012-02-16 [HDTV - LMAO]", 183442338));
test_feed(combine_path(root_dir, "cb.xml"), rss_expect(50, "http://www.clearbits.net/get/1911-norbergfestival-2011.torrent", "Norbergfestival 2011", 1160773632));
test_feed(combine_path(root_dir, "kat.xml"), rss_expect(25, "http://kat.ph/torrents/benito-di-paula-1975-benito-di-paula-lp-rip-ogg-at-500-jarax4u-t6194897/", "Benito Di Paula - 1975 - Benito Di Paula (LP Rip OGG at 500) [jarax4u]", 168773863));
test_feed(combine_path(root_dir, "mn.xml"), rss_expect(20, "http://www.mininova.org/get/13203100", "Dexcell - January TwentyTwelve Mix", 137311179));
test_feed(combine_path(root_dir, "pb.xml"), rss_expect(60, "magnet:?xt=urn:btih:FD4CDDB7BBE722D17A018EFD875EB0695ED7159C&dn=Thompson+Twins+-+1989+-+Big+Trash+%5BMP3%5D", "Thompson Twins - 1989 - Big Trash [MP3]", 100160904));
return 0;
}
|
fix test_rss for windows
|
fix test_rss for windows
|
C++
|
bsd-3-clause
|
hamedramzi/libtorrent,hamedramzi/libtorrent,snowyu/libtorrent,hamedramzi/libtorrent,hamedramzi/libtorrent,snowyu/libtorrent,snowyu/libtorrent,snowyu/libtorrent,TeoTwawki/libtorrent,hamedramzi/libtorrent,TeoTwawki/libtorrent,TeoTwawki/libtorrent,TeoTwawki/libtorrent,snowyu/libtorrent,TeoTwawki/libtorrent,snowyu/libtorrent,hamedramzi/libtorrent,TeoTwawki/libtorrent
|
675e19b0740f8268ab88566f55b282f8eb58b982
|
Source/Core/VideoSubsystem.cpp
|
Source/Core/VideoSubsystem.cpp
|
/*
* VideoSubsystem.cpp
*
* Created on: 30 kwi 2014
* Author: Lech Kulina
* E-Mail: [email protected]
*/
#include <Core/VideoSubsystem.hpp>
Cosmic::Core::VideoSubsystem::VideoSubsystem() :
logger(
boost::log::keywords::severity = Common::Severity::Trace,
boost::log::keywords::channel = Common::Channel::Subsystem
),
restoreScreenSaver(SDL_FALSE),
window(nullptr),
renderer(nullptr) {
}
Cosmic::Core::VideoSubsystem::~VideoSubsystem() {
}
void Cosmic::Core::VideoSubsystem::initialize(){
BOOST_LOG_FUNCTION();
if (isInitialized()) {
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Video subsystem has already been initialized.";
return;
}
//initialize SDL core stuff with the video subsystem
BOOST_LOG_SEV(logger, Common::Severity::Trace)
<< "Initializing SDL library and video subsystem.";
if (SDL_Init(0) != 0) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to initialize SDL library. " << SDL_GetError();
return;
}
SDL_version version;
memset(&version, 0, sizeof(SDL_version));
SDL_GetVersion(&version);
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "SDL " << int(version.major) << "." << int(version.minor) << "." << int(version.patch) << " initialized";
//initialize video subsystem
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to initialize SDL Video subsystem. " << SDL_GetError();
SDL_Quit();
return;
}
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Video subsystem initialized with " << SDL_GetCurrentVideoDriver() << " display driver.";
//create and rise window for our insane game !
if ((window = SDL_CreateWindow("Cosmic River Insanity", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
800, 600, SDL_WINDOW_SHOWN)) == nullptr) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to create window. " << SDL_GetError();
SDL_Quit();
return;
}
SDL_RaiseWindow(window);
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Window with ID " << SDL_GetWindowID(window) << " created.";
//create renderer
if ((renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)) == nullptr) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to create renderer. " << SDL_GetError();
SDL_DestroyWindow(window);
SDL_Quit();
window = nullptr;
return;
}
SDL_RendererInfo rendererInfo;
memset(&rendererInfo, 0, sizeof(SDL_RendererInfo));
if (SDL_GetRendererInfo(renderer, &rendererInfo) != 0) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to get renderer information" << SDL_GetError();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
renderer = nullptr;
window = nullptr;
return;
}
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Renderer " << rendererInfo.name << " created.";
//disable screen saver and hide cursor
restoreScreenSaver = SDL_IsScreenSaverEnabled();
SDL_DisableScreenSaver();
SDL_ShowCursor(SDL_DISABLE);
}
void Cosmic::Core::VideoSubsystem::uninitialize() {
BOOST_LOG_FUNCTION();
if (!isInitialized()) {
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Video subsystem has already been uninitialized";
return;
}
//restore screen saver state, destroy renderer, window and quit all SDL subsystems
BOOST_LOG_SEV(logger, Common::Severity::Trace)
<< "Uninitializing video subsystem and SDL library.";
if (restoreScreenSaver == SDL_TRUE) {
SDL_DisableScreenSaver();
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
restoreScreenSaver = SDL_FALSE;
renderer = nullptr;
window = nullptr;
}
bool Cosmic::Core::VideoSubsystem::isInitialized() const {
return SDL_WasInit(SDL_INIT_VIDEO) != 0;
}
|
/*
* VideoSubsystem.cpp
*
* Created on: 30 kwi 2014
* Author: Lech Kulina
* E-Mail: [email protected]
*/
#include <Core/VideoSubsystem.hpp>
Cosmic::Core::VideoSubsystem::VideoSubsystem() :
logger(
boost::log::keywords::severity = Common::Severity::Trace,
boost::log::keywords::channel = Common::Channel::Subsystem
),
restoreScreenSaver(SDL_FALSE),
window(nullptr),
renderer(nullptr) {
}
Cosmic::Core::VideoSubsystem::~VideoSubsystem() {
}
void Cosmic::Core::VideoSubsystem::initialize(){
BOOST_LOG_FUNCTION();
if (isInitialized()) {
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Video subsystem has already been initialized.";
return;
}
//initialize SDL core stuff with the video subsystem
BOOST_LOG_SEV(logger, Common::Severity::Trace)
<< "Initializing SDL library and video subsystem.";
if (SDL_Init(0) != 0) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to initialize SDL library. " << SDL_GetError();
return;
}
SDL_version version;
memset(&version, 0, sizeof(SDL_version));
SDL_GetVersion(&version);
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "SDL " << int(version.major) << "." << int(version.minor) << "." << int(version.patch) << " initialized";
//initialize video subsystem
if (SDL_InitSubSystem(SDL_INIT_VIDEO) != 0) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to initialize SDL Video subsystem. " << SDL_GetError();
SDL_Quit();
return;
}
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Video subsystem initialized with " << SDL_GetCurrentVideoDriver() << " display driver.";
//create and rise window for our insane game !
if ((window = SDL_CreateWindow("Cosmic River Insanity", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
800, 600, SDL_WINDOW_SHOWN)) == nullptr) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to create window. " << SDL_GetError();
SDL_Quit();
return;
}
SDL_RaiseWindow(window);
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Window with ID " << SDL_GetWindowID(window) << " created.";
//create renderer
if ((renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED)) == nullptr) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to create renderer. " << SDL_GetError();
SDL_DestroyWindow(window);
SDL_Quit();
window = nullptr;
return;
}
SDL_RendererInfo rendererInfo;
memset(&rendererInfo, 0, sizeof(SDL_RendererInfo));
if (SDL_GetRendererInfo(renderer, &rendererInfo) != 0) {
BOOST_LOG_SEV(logger, Common::Severity::Critical)
<< "Failed to get renderer information" << SDL_GetError();
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
renderer = nullptr;
window = nullptr;
return;
}
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Renderer " << rendererInfo.name << " created.";
//disable screen saver and hide cursor
restoreScreenSaver = SDL_IsScreenSaverEnabled();
SDL_DisableScreenSaver();
SDL_ShowCursor(SDL_DISABLE);
}
void Cosmic::Core::VideoSubsystem::uninitialize() {
BOOST_LOG_FUNCTION();
if (!isInitialized()) {
BOOST_LOG_SEV(logger, Common::Severity::Debug)
<< "Video subsystem has already been uninitialized";
return;
}
//restore screen saver state, destroy renderer, window and quit all SDL subsystems
BOOST_LOG_SEV(logger, Common::Severity::Trace)
<< "Uninitializing video subsystem and SDL library.";
if (restoreScreenSaver == SDL_TRUE) {
SDL_EnableScreenSaver();
}
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
restoreScreenSaver = SDL_FALSE;
renderer = nullptr;
window = nullptr;
}
bool Cosmic::Core::VideoSubsystem::isInitialized() const {
return SDL_WasInit(SDL_INIT_VIDEO) != 0;
}
|
Fix restoring screen saver state when video subsystem is being uninitialized
|
Fix restoring screen saver state when video subsystem is being uninitialized
|
C++
|
mit
|
lechkulina/CosmicRiverInsanity
|
da47a4b764bb9848662d06890e2e1e33d1905cb7
|
cec-simplest.cpp
|
cec-simplest.cpp
|
//#CXXFLAGS=-I/usr/local/include
//#LINKFLAGS=-lcec
#include <libcec/cec.h>
// cecloader.h uses std::cout _without_ including iosfwd or iostream
// Furthermore is uses cout and not std::cout
#include <iostream>
using std::cout;
using std::endl;
#include <libcec/cecloader.h>
#include "bcm_host.h"
//#LINKFLAGS=-lbcm_host
#include <algorithm> // for std::min
// The main loop will just continue until a ctrl-C is received
#include <signal.h>
bool exit_now = false;
void handle_signal(int signal)
{
exit_now = true;
}
//CEC::CBCecLogMessageType
//int on_log_message(void*, CEC::cec_log_message){return 0;}
//CEC::CBCecCommandType
//int on_command(void*, CEC::cec_command){return 0;}
//CEC::CBCecAlertType
//int on_alert(void*, CEC::libcec_alert, CEC::libcec_parameter){return 0;}
//CEC::CBCecKeyPressType
int on_keypress(void*, const CEC::cec_keypress msg)
{
std::string key;
switch( msg.keycode )
{
case CEC::CEC_USER_CONTROL_CODE_SELECT: { key = "select"; break; }
case CEC::CEC_USER_CONTROL_CODE_UP: { key = "up"; break; }
case CEC::CEC_USER_CONTROL_CODE_DOWN: { key = "down"; break; }
case CEC::CEC_USER_CONTROL_CODE_LEFT: { key = "left"; break; }
case CEC::CEC_USER_CONTROL_CODE_RIGHT: { key = "right"; break; }
};
std::cout << "on_keypress: " << static_cast<int>(msg.keycode) << " " << key << std::endl;
return 0;
}
int main(int argc, char* argv[])
{
// Install the ctrl-C signal handler
if( SIG_ERR == signal(SIGINT, handle_signal) )
{
std::cerr << "Failed to install the SIGINT signal handler\n";
return 1;
}
// Initialise the graphics pipeline for the raspberry pi
bcm_host_init();
// Set up the CEC config
CEC::ICECCallbacks cec_callbacks;
CEC::libcec_configuration cec_config;
cec_config.Clear();
cec_callbacks.Clear();
const std::string devicename("CECExample");
devicename.copy(cec_config.strDeviceName, std::min(devicename.size(),13u) );
cec_config.clientVersion = CEC::CEC_CLIENT_VERSION_CURRENT;
cec_config.bActivateSource = 0;
cec_config.callbacks = &cec_callbacks;
cec_config.deviceTypes.Add(CEC::CEC_DEVICE_TYPE_RECORDING_DEVICE);
// cec_callbacks.CBCecLogMessage = &on_log_message;
cec_callbacks.CBCecKeyPress = &on_keypress;
// cec_callbacks.CBCecCommand = &on_command;
// cec_callbacks.CBCecAlert = &on_alert;
// Get a cec adapter by initialising the cec library
CEC::ICECAdapter* cec_adapter = LibCecInitialise(&cec_config);
if( !cec_adapter )
{
std::cerr << "Failed loading libcec.so\n";
return 1;
}
// Try and automatically determine the CEC devices
CEC::cec_adapter devices[10];
int8_t devices_found = cec_adapter->FindAdapters(devices, 10, NULL);
if( devices_found <= 0)
{
std::cerr << "Could not automatically determine the cec adapter devices\n";
UnloadLibCec(cec_adapter);
return 1;
}
// Open a connection to the CEC adapter
if( !cec_adapter->Open(devices[0].comm) )
{
std::cerr << "Failed to open the CEC device on port " << devices[0].comm << std::endl;
UnloadLibCec(cec_adapter);
return 1;
}
// Loop until ctrl-C occurs
while( !exit_now )
{
// nothing to do. All happens in the CEC callback on another thread
sleep(1);
}
cec_adapter->Close();
UnloadLibCec(cec_adapter);
return 0;
}
|
// Build command:
// g++ -std=gnu++0x -fPIC -g -Wall -march=armv6 -mfpu=vfp -mfloat-abi=hard -isystem /opt/vc/include/ -isystem /opt/vc/include/interface/vcos/pthreads/ -isystem /opt/vc/include/interface/vmcs_host/linux/ -I/usr/local/include -L /opt/vc/lib -lcec -lbcm_host cec-simplest.cpp -o cec-simplest
//#CXXFLAGS=-I/usr/local/include
//#LINKFLAGS=-lcec
#include <libcec/cec.h>
// cecloader.h uses std::cout _without_ including iosfwd or iostream
// Furthermore is uses cout and not std::cout
#include <iostream>
using std::cout;
using std::endl;
#include <libcec/cecloader.h>
#include "bcm_host.h"
//#LINKFLAGS=-lbcm_host
#include <algorithm> // for std::min
// The main loop will just continue until a ctrl-C is received
#include <signal.h>
bool exit_now = false;
void handle_signal(int signal)
{
exit_now = true;
}
//CEC::CBCecKeyPressType
int on_keypress(void* not_used, const CEC::cec_keypress msg)
{
std::string key;
switch( msg.keycode )
{
case CEC::CEC_USER_CONTROL_CODE_SELECT: { key = "select"; break; }
case CEC::CEC_USER_CONTROL_CODE_UP: { key = "up"; break; }
case CEC::CEC_USER_CONTROL_CODE_DOWN: { key = "down"; break; }
case CEC::CEC_USER_CONTROL_CODE_LEFT: { key = "left"; break; }
case CEC::CEC_USER_CONTROL_CODE_RIGHT: { key = "right"; break; }
default: break;
};
std::cout << "on_keypress: " << static_cast<int>(msg.keycode) << " " << key << std::endl;
return 0;
}
int main(int argc, char* argv[])
{
// Install the ctrl-C signal handler
if( SIG_ERR == signal(SIGINT, handle_signal) )
{
std::cerr << "Failed to install the SIGINT signal handler\n";
return 1;
}
// Initialise the graphics pipeline for the raspberry pi. Yes, this is necessary.
bcm_host_init();
// Set up the CEC config and specify the keypress callback function
CEC::ICECCallbacks cec_callbacks;
CEC::libcec_configuration cec_config;
cec_config.Clear();
cec_callbacks.Clear();
const std::string devicename("CECExample");
devicename.copy(cec_config.strDeviceName, std::min(devicename.size(),13u) );
cec_config.clientVersion = CEC::CEC_CLIENT_VERSION_CURRENT;
cec_config.bActivateSource = 0;
cec_config.callbacks = &cec_callbacks;
cec_config.deviceTypes.Add(CEC::CEC_DEVICE_TYPE_RECORDING_DEVICE);
cec_callbacks.CBCecKeyPress = &on_keypress;
// Get a cec adapter by initialising the cec library
CEC::ICECAdapter* cec_adapter = LibCecInitialise(&cec_config);
if( !cec_adapter )
{
std::cerr << "Failed loading libcec.so\n";
return 1;
}
// Try to automatically determine the CEC devices
CEC::cec_adapter devices[10];
int8_t devices_found = cec_adapter->FindAdapters(devices, 10, NULL);
if( devices_found <= 0)
{
std::cerr << "Could not automatically determine the cec adapter devices\n";
UnloadLibCec(cec_adapter);
return 1;
}
// Open a connection to the zeroth CEC device
if( !cec_adapter->Open(devices[0].comm) )
{
std::cerr << "Failed to open the CEC device on port " << devices[0].comm << std::endl;
UnloadLibCec(cec_adapter);
return 1;
}
// Loop until ctrl-C occurs
while( !exit_now )
{
// nothing to do. All happens in the CEC callback on another thread
sleep(1);
}
// Close down and cleanup
cec_adapter->Close();
UnloadLibCec(cec_adapter);
return 0;
}
|
Remove some commented out code and add a comment for how to build the program using g++ directly
|
Remove some commented out code and add a comment for how to build the
program using g++ directly
|
C++
|
unlicense
|
DrGeoff/cec_simplest,DrGeoff/cec_simplest
|
30ccfb924d545cfefdb532143df2e987e3ff72a6
|
include/distortos/scheduler/SoftwareTimerControlBlockList-types.hpp
|
include/distortos/scheduler/SoftwareTimerControlBlockList-types.hpp
|
/**
* \file
* \brief Types used by SoftwareTimerControlBlockList
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-08-08
*/
#ifndef INCLUDE_DISTORTOS_SCHEDULER_SOFTWARETIMERCONTROLBLOCKLIST_TYPES_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_SOFTWARETIMERCONTROLBLOCKLIST_TYPES_HPP_
#include "distortos/containers/SortedContainer.hpp"
#include <list>
namespace distortos
{
namespace scheduler
{
class SoftwareTimerControlBlock;
/// type held by SoftwareTimerControlBlockList
using SoftwareTimerControlBlockListValueType = std::reference_wrapper<SoftwareTimerControlBlock>;
/// underlying unsorted container of SoftwareTimerControlBlockList
using SoftwareTimerControlBlockListContainer = std::list<SoftwareTimerControlBlockListValueType>;
/// generic iterator for SoftwareTimerControlBlockList
using SoftwareTimerControlBlockListIterator =
containers::SortedContainerBase<SoftwareTimerControlBlockListContainer>::iterator;
} // namespace scheduler
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SCHEDULER_SOFTWARETIMERCONTROLBLOCKLIST_TYPES_HPP_
|
/**
* \file
* \brief Types used by SoftwareTimerControlBlockList
*
* \author Copyright (C) 2014 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2014-09-07
*/
#ifndef INCLUDE_DISTORTOS_SCHEDULER_SOFTWARETIMERCONTROLBLOCKLIST_TYPES_HPP_
#define INCLUDE_DISTORTOS_SCHEDULER_SOFTWARETIMERCONTROLBLOCKLIST_TYPES_HPP_
#include "distortos/containers/SortedContainer.hpp"
#include "distortos/allocators/PoolAllocator.hpp"
#include "distortos/allocators/SimpleFeedablePool.hpp"
#include <list>
namespace distortos
{
namespace scheduler
{
class SoftwareTimerControlBlock;
/// type held by SoftwareTimerControlBlockList
using SoftwareTimerControlBlockListValueType = std::reference_wrapper<SoftwareTimerControlBlock>;
/// type of allocator used by SoftwareTimerControlBlockList
using SoftwareTimerControlBlockListAllocator =
allocators::PoolAllocator<SoftwareTimerControlBlockListValueType, allocators::SimpleFeedablePool>;
/// underlying unsorted container of SoftwareTimerControlBlockList
using SoftwareTimerControlBlockListContainer = std::list<SoftwareTimerControlBlockListValueType>;
/// generic iterator for SoftwareTimerControlBlockList
using SoftwareTimerControlBlockListIterator =
containers::SortedContainerBase<SoftwareTimerControlBlockListContainer>::iterator;
} // namespace scheduler
} // namespace distortos
#endif // INCLUDE_DISTORTOS_SCHEDULER_SOFTWARETIMERCONTROLBLOCKLIST_TYPES_HPP_
|
add SoftwareTimerControlBlockListAllocator type alias
|
SoftwareTimerControlBlockList-types.hpp: add SoftwareTimerControlBlockListAllocator type alias
|
C++
|
mpl-2.0
|
DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos
|
3652f6ea04f20d727156b38060f51a3869b832f8
|
ch18/ex18_29.cpp
|
ch18/ex18_29.cpp
|
/* Exercise 18.29:
Given the following class hierarchy:
class Class { ... }; class Base : public Class { ... };
class D1 : virtual public Base { ... };
class D2 : virtual public Base { ... };
class MI : public D1, public D2 { ... };
class Final : public MI, public Class { ... };
(a) In what order are constructors and destructors run on a Final object?
(b) A Final object has how many Base parts? How many Class parts?
(c) Which of the following assignments is a compile-time error?
Base *pb; Class *pc; MI *pmi; D2 *pd2;
(a) pb = new Class; (b) pc = new Final;
(c) pmi = pb; (d) pd2 = pmi;
Solution:
(a) Constructors run order: Class Base D1 D2 MI Class Final.
Destructors run order: Final Class MI D2 D1 Base Call.
Class parts are constructed from left to right and base class to derived class.
(b) 1 Base part and 2 Class parts.
Because ‘Base’ is a virtual base class of ‘D1’ and ‘D2’. There is only 1 Base part.
However, ‘Class’ is a normal base class of ‘Final’ and ‘Base’. So there is 2 Class part.
(c) error. Can't convert a pointer of base class to a pointer of derived class implicitly.
error. ‘Class’ is an ambiguous base of ‘Final’.
error. Can't convert a pointer of base class to a pointer of derived class implicitly.
pass. A pointer of derived class can be cast to a pointer of base class.
*/
#include <iostream>
using namespace std;
class Class {
public:
Class() { cout << "Class() called" << endl; }
~Class() { cout << "~Class() called" << endl; }
};
class Base : public Class {
public:
Base() { cout << "Base() called" << endl; }
~Base() { cout << "~Base() called" << endl; }
};
class D1 : virtual public Base {
public:
D1() { cout << "D1() called" << endl; }
~D1() { cout << "~D1() called" << endl; }
};
class D2 : virtual public Base {
public:
D2() { cout << "D2() called" << endl; }
~D2() { cout << "~D2() called" << endl; }
};
class MI : public D1, public D2 {
public:
MI() { cout << "MI() called" << endl; }
~MI() { cout << "~MI() called" << endl; }
};
class Final : public MI, public Class {
public:
Final() { cout << "Final() called" << endl; }
~Final() { cout << "~Final() called" << endl; }
};
int main(int argc, char const *argv[])
{
Final final;
Base *pb;
Class *pc;
MI *pmi;
D2 *pd2;
// pb = new Class;
// pc = new Final;
// pmi = pb;
pd2 = pmi;
return 0;
}
|
/* Exercise 18.29:
Given the following class hierarchy:
class Class { ... }; class Base : public Class { ... };
class D1 : virtual public Base { ... };
class D2 : virtual public Base { ... };
class MI : public D1, public D2 { ... };
class Final : public MI, public Class { ... };
(a) In what order are constructors and destructors run on a Final object?
(b) A Final object has how many Base parts? How many Class parts?
(c) Which of the following assignments is a compile-time error?
Base *pb; Class *pc; MI *pmi; D2 *pd2;
(a) pb = new Class; (b) pc = new Final;
(c) pmi = pb; (d) pd2 = pmi;
Solution:
(a) Constructors run order: Class Base D1 D2 MI Class Final.
Destructors run order: Final Class MI D2 D1 Base Class.
Class parts are constructed from left to right and base class to derived class.
(b) 1 Base part and 2 Class parts.
Because ‘Base’ is a virtual base class of ‘D1’ and ‘D2’. There is only 1 Base part.
However, ‘Class’ is a normal base class of ‘Final’ and ‘Base’. So there is 2 Class part.
(c) error. Can't convert a pointer of base class to a pointer of derived class implicitly.
error. ‘Class’ is an ambiguous base of ‘Final’.
error. Can't convert a pointer of base class to a pointer of derived class implicitly.
pass. A pointer of derived class can be cast to a pointer of base class.
*/
#include <iostream>
using namespace std;
class Class {
public:
Class() { cout << "Class() called" << endl; }
~Class() { cout << "~Class() called" << endl; }
};
class Base : public Class {
public:
Base() { cout << "Base() called" << endl; }
~Base() { cout << "~Base() called" << endl; }
};
class D1 : virtual public Base {
public:
D1() { cout << "D1() called" << endl; }
~D1() { cout << "~D1() called" << endl; }
};
class D2 : virtual public Base {
public:
D2() { cout << "D2() called" << endl; }
~D2() { cout << "~D2() called" << endl; }
};
class MI : public D1, public D2 {
public:
MI() { cout << "MI() called" << endl; }
~MI() { cout << "~MI() called" << endl; }
};
class Final : public MI, public Class {
public:
Final() { cout << "Final() called" << endl; }
~Final() { cout << "~Final() called" << endl; }
};
int main(int argc, char const *argv[])
{
Final final;
Base *pb;
Class *pc;
MI *pmi;
D2 *pd2;
// pb = new Class;
// pc = new Final;
// pmi = pb;
pd2 = pmi;
return 0;
}
|
Update ex18_29.cpp
|
Update ex18_29.cpp
|
C++
|
cc0-1.0
|
Mooophy/Cpp-Primer,Mooophy/Cpp-Primer
|
f1f33fd09220c88bdd64344fbfb3fcc6823861a7
|
check_anagram.cc
|
check_anagram.cc
|
// Copyright 2012 Philip Puryear
//
// 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 <algorithm>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
using namespace std;
struct ProgramArguments {
bool keep_case;
bool keep_nonword;
string string1;
string string2;
} g_program_args;
void Fatal(const string& msg) {
cerr << "check_anagram: error: " << msg << endl;
exit(EXIT_FAILURE);
}
void Usage(boost::program_options::options_description options_desc) {
cout << "usage: check_anagram [options] string1 string2\n\n";
cout << "Determine if two strings are anagrams.\n\n";
cout << options_desc << endl;
}
void ParseProgramArguments(int argc, char** argv) {
namespace po = boost::program_options;
bool show_usage;
po::options_description visible_options("Options");
visible_options.add_options()
("help,h", po::bool_switch(&show_usage), "show usage info")
("keep-case,c", po::bool_switch(&g_program_args.keep_case),
"do not ignore case")
("keep-nonword,w", po::bool_switch(&g_program_args.keep_nonword),
"do not ignore non-word characters");
// Put the positional arguments in a separate group so they can be omitted
// from Usage().
po::options_description hidden_options;
hidden_options.add_options()
("string1", po::value<string>(&g_program_args.string1))
("string2", po::value<string>(&g_program_args.string2));
po::positional_options_description positional_args;
positional_args.add("string1", 1);
positional_args.add("string2", 1);
po::options_description options;
options.add(visible_options);
options.add(hidden_options);
po::command_line_parser parser(argc, argv);
parser.options(options);
parser.positional(positional_args);
po::variables_map vars_map;
try {
po::store(parser.run(), vars_map);
} catch (po::error_with_option_name& e) {
Fatal(e.what());
} catch (po::too_many_positional_options_error& e) {
Fatal("too many inputs");
}
po::notify(vars_map);
if (show_usage) {
Usage(visible_options);
exit(EXIT_SUCCESS);
}
if (g_program_args.string1.empty() || g_program_args.string2.empty())
Fatal("not enough inputs");
}
string StripInput(string input) {
if (!g_program_args.keep_case)
boost::to_lower(input);
if (!g_program_args.keep_nonword) {
boost::regex strip_regex("\\W");
input = boost::regex_replace(input, strip_regex, "");
}
return input;
}
bool CheckAnagrams(string a, string b) {
// Fast path: a and b cannot be anagrams if their lengths differ.
if (a.length() != b.length())
return false;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
return a.compare(b) == 0;
}
int main(int argc, char** argv) {
ParseProgramArguments(argc, argv);
string stripped_string1 = StripInput(g_program_args.string1);
string stripped_string2 = StripInput(g_program_args.string2);
if (CheckAnagrams(stripped_string1, stripped_string2))
cout << "Yes.";
else
cout << "No.";
cout << endl;
return 0;
}
|
// Copyright 2012 Philip Puryear
//
// 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 <algorithm>
#include <iostream>
#include <string>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
using namespace std;
namespace boost_po = boost::program_options;
struct ProgramArguments {
bool keep_case;
bool keep_nonword;
string string1;
string string2;
} g_program_args;
void Fatal(const string& msg) {
cerr << "check_anagram: error: " << msg << endl;
exit(EXIT_FAILURE);
}
void Usage(const boost_po::options_description& options_desc) {
cout << "usage: check_anagram [options] string1 string2\n\n";
cout << "Determine if two strings are anagrams.\n\n";
cout << options_desc << endl;
}
void ParseProgramArguments(int argc, char** argv) {
bool show_usage;
boost_po::options_description visible_options("Options");
visible_options.add_options()
("help,h", boost_po::bool_switch(&show_usage), "show usage info")
("keep-case,c", boost_po::bool_switch(&g_program_args.keep_case),
"do not ignore case")
("keep-nonword,w", boost_po::bool_switch(&g_program_args.keep_nonword),
"do not ignore non-word characters");
// Put the positional arguments in a separate group so they can be omitted
// from Usage().
boost_po::options_description hidden_options;
hidden_options.add_options()
("string1", boost_po::value<string>(&g_program_args.string1))
("string2", boost_po::value<string>(&g_program_args.string2));
boost_po::positional_options_description positional_args;
positional_args.add("string1", 1);
positional_args.add("string2", 1);
boost_po::options_description options;
options.add(visible_options);
options.add(hidden_options);
boost_po::command_line_parser parser(argc, argv);
parser.options(options);
parser.positional(positional_args);
boost_po::variables_map vars_map;
try {
boost_po::store(parser.run(), vars_map);
} catch (boost_po::error_with_option_name& e) {
Fatal(e.what());
} catch (boost_po::too_many_positional_options_error& e) {
Fatal("too many inputs");
}
boost_po::notify(vars_map);
if (show_usage) {
Usage(visible_options);
exit(EXIT_SUCCESS);
}
if (g_program_args.string1.empty() || g_program_args.string2.empty())
Fatal("not enough inputs");
}
string StripInput(string input) {
if (!g_program_args.keep_case)
boost::to_lower(input);
if (!g_program_args.keep_nonword) {
boost::regex strip_regex("\\W");
input = boost::regex_replace(input, strip_regex, "");
}
return input;
}
bool CheckAnagrams(string a, string b) {
// Fast path: a and b cannot be anagrams if their lengths differ.
if (a.length() != b.length())
return false;
sort(a.begin(), a.end());
sort(b.begin(), b.end());
return a.compare(b) == 0;
}
int main(int argc, char** argv) {
ParseProgramArguments(argc, argv);
string stripped_string1 = StripInput(g_program_args.string1);
string stripped_string2 = StripInput(g_program_args.string2);
if (CheckAnagrams(stripped_string1, stripped_string2))
cout << "Yes.";
else
cout << "No.";
cout << endl;
return 0;
}
|
Use a global alias for boost::program_options.
|
[C++] Use a global alias for boost::program_options.
Also, make Usage() take a const reference instead of a value.
Signed-off-by: Philip Puryear <[email protected]>
|
C++
|
apache-2.0
|
ppuryear/check_anagram,ppuryear/check_anagram,ppuryear/check_anagram
|
36df6ebe4e5f0abd3f07c1e454710590f1de23c7
|
be/src/olap/rowset/alpha_rowset_reader.cpp
|
be/src/olap/rowset/alpha_rowset_reader.cpp
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "olap/rowset/alpha_rowset_reader.h"
#include "olap/rowset/alpha_rowset.h"
namespace doris {
AlphaRowsetReader::AlphaRowsetReader(
int num_rows_per_row_block,
RowsetSharedPtr rowset)
: _num_rows_per_row_block(num_rows_per_row_block),
_rowset(rowset),
_alpha_rowset_meta(nullptr),
_segment_groups(std::dynamic_pointer_cast<AlphaRowset>(rowset)->_segment_groups),
_key_range_size(0) {
RowsetMetaSharedPtr rowset_meta_ptr = (std::dynamic_pointer_cast<AlphaRowset>(rowset)->_rowset_meta);
_alpha_rowset_meta = reinterpret_cast<AlphaRowsetMeta*>(rowset_meta_ptr.get());
}
AlphaRowsetReader::~AlphaRowsetReader() {
delete _dst_cursor;
}
OLAPStatus AlphaRowsetReader::init(RowsetReaderContext* read_context) {
if (read_context == nullptr) {
return OLAP_ERR_INIT_FAILED;
}
_current_read_context = read_context;
if (_current_read_context->stats != nullptr) {
_stats = _current_read_context->stats;
}
Version version = _alpha_rowset_meta->version();
_is_singleton_rowset = (version.first == version.second);
_ordinal = 0;
bool merge = false;
/*
* For singleton rowset, there exists three situations.
* 1. QUERY task will set preaggregation.
* If preaggregation is set to be true
* there is not necessary to merge row in advance.
* 2. QEURY task for DUP_KEYS tablet has no necessities
* to merge row in advance.
* 2. COMPACTION/CHECKSUM/ALTER_TABLET task should merge
* row in advance.
* For cumulative rowset, there are no necessities to merge row in advance.
*/
RETURN_NOT_OK(_init_merge_ctxs(read_context));
if (_is_singleton_rowset && _merge_ctxs.size() > 1) {
if (_current_read_context->reader_type == READER_QUERY
&& _current_read_context->preaggregation) {
// 1. QUERY task which set pregaggregation to be true
_next_block = &AlphaRowsetReader::_union_block;
} else if (_current_read_context->reader_type == READER_QUERY
&& _current_read_context->tablet_schema->keys_type() == DUP_KEYS) {
// 2. QUERY task for DUP_KEYS tablet
_next_block = &AlphaRowsetReader::_union_block;
} else {
// 3. COMPACTION/CHECKSUM/ALTER_TABLET task
_next_block = &AlphaRowsetReader::_merge_block;
merge = true;
}
} else {
// query task to scan cumulative rowset
_next_block = &AlphaRowsetReader::_union_block;
}
if (merge) {
_read_block.reset(new (std::nothrow) RowBlock(_current_read_context->tablet_schema));
if (_read_block == nullptr) {
LOG(WARNING) << "new row block failed in reader";
return OLAP_ERR_MALLOC_ERROR;
}
RowBlockInfo block_info;
block_info.row_num = _current_read_context->tablet_schema->num_rows_per_row_block();
block_info.null_supported = true;
_read_block->init(block_info);
_dst_cursor = new (std::nothrow) RowCursor();
if (_dst_cursor == nullptr) {
LOG(WARNING) << "allocate memory for row cursor failed";
return OLAP_ERR_MALLOC_ERROR;
}
_dst_cursor->init(*(_current_read_context->tablet_schema),
*(_current_read_context->seek_columns));
for (size_t i = 0; i < _merge_ctxs.size(); ++i) {
_merge_ctxs[i].row_cursor.reset(new (std::nothrow) RowCursor());
_merge_ctxs[i].row_cursor->init(*(_current_read_context->tablet_schema),
*(_current_read_context->seek_columns));
}
}
return OLAP_SUCCESS;
}
OLAPStatus AlphaRowsetReader::next_block(RowBlock** block) {
return (this->*_next_block)(block);
}
bool AlphaRowsetReader::delete_flag() {
return _alpha_rowset_meta->delete_flag();
}
Version AlphaRowsetReader::version() {
return _alpha_rowset_meta->version();
}
VersionHash AlphaRowsetReader::version_hash() {
return _alpha_rowset_meta->version_hash();
}
void AlphaRowsetReader::close() {
_merge_ctxs.clear();
}
int64_t AlphaRowsetReader::filtered_rows() {
return _stats->rows_del_filtered;
}
OLAPStatus AlphaRowsetReader::_union_block(RowBlock** block) {
while (_ordinal < _merge_ctxs.size()) {
// union block only use one block to store
OLAPStatus status = _pull_next_block(&(_merge_ctxs[_ordinal]));
if (status == OLAP_ERR_DATA_EOF) {
_ordinal++;
continue;
} else if (status != OLAP_SUCCESS) {
return status;
} else {
(*block) = _merge_ctxs[_ordinal].row_block;
return OLAP_SUCCESS;
}
}
if (_ordinal == _merge_ctxs.size()) {
*block = nullptr;
return OLAP_ERR_DATA_EOF;
}
return OLAP_SUCCESS;
}
OLAPStatus AlphaRowsetReader::_merge_block(RowBlock** block) {
// Row among different segment groups may overlap with each other.
// Iterate all row_blocks to fetch min row each round.
OLAPStatus status = OLAP_SUCCESS;
_read_block->clear();
size_t num_rows_in_block = 0;
while (_read_block->pos() < _num_rows_per_row_block) {
RowCursor* row_cursor = nullptr;
status = _pull_next_row_for_merge_rowset(&row_cursor);
if (status == OLAP_ERR_DATA_EOF && _read_block->pos() > 0) {
status = OLAP_SUCCESS;
break;
} else if (status != OLAP_SUCCESS) {
return status;
}
_read_block->get_row(_read_block->pos(), _dst_cursor);
_dst_cursor->copy(*row_cursor, _read_block->mem_pool());
_read_block->pos_inc();
num_rows_in_block++;
}
_read_block->set_pos(0);
_read_block->set_limit(num_rows_in_block);
_read_block->finalize(num_rows_in_block);
*block = _read_block.get();
return status;
}
OLAPStatus AlphaRowsetReader::_pull_next_row_for_merge_rowset(RowCursor** row) {
RowCursor* min_row = nullptr;
int min_index = -1;
size_t ordinal = 0;
while (ordinal < _merge_ctxs.size()) {
MergeContext* merge_ctx = &(_merge_ctxs[ordinal]);
if (merge_ctx->row_block == nullptr || !merge_ctx->row_block->has_remaining()) {
OLAPStatus status = _pull_next_block(merge_ctx);
if (status == OLAP_ERR_DATA_EOF) {
_merge_ctxs.erase(_merge_ctxs.begin() + ordinal);
continue;
} else if (status != OLAP_SUCCESS) {
LOG(WARNING) << "read next row of singleton rowset failed:" << status;
return status;
}
}
RowCursor* current_row = merge_ctx->row_cursor.get();
merge_ctx->row_block->get_row(merge_ctx->row_block->pos(), current_row);
if (min_row == nullptr || min_row->cmp(*current_row) > 0) {
min_row = current_row;
min_index = ordinal;
}
ordinal++;
}
if (min_row == nullptr || min_index == -1) {
return OLAP_ERR_DATA_EOF;
}
*row = min_row;
_merge_ctxs[min_index].row_block->pos_inc();
return OLAP_SUCCESS;
}
OLAPStatus AlphaRowsetReader::_pull_next_block(MergeContext* merge_ctx) {
OLAPStatus status = OLAP_SUCCESS;
if (OLAP_UNLIKELY(merge_ctx->first_read_symbol)) {
if (_key_range_size > 0) {
status = _pull_first_block(merge_ctx);
} else {
status = merge_ctx->column_data->get_first_row_block(&(merge_ctx->row_block));
if (status != OLAP_SUCCESS && status != OLAP_ERR_DATA_EOF) {
LOG(WARNING) << "get first row block failed, status:" << status;
}
}
merge_ctx->first_read_symbol = false;
return status;
} else {
// get next block
status = merge_ctx->column_data->get_next_block(&(merge_ctx->row_block));
if (status == OLAP_ERR_DATA_EOF && _key_range_size > 0) {
// reach the end of one predicate
// currently, SegmentReader can only support filter one key range a time
// refresh the predicate and continue read
return _pull_first_block(merge_ctx);
}
}
return status;
}
OLAPStatus AlphaRowsetReader::_pull_first_block(MergeContext* merge_ctx) {
OLAPStatus status = OLAP_SUCCESS;
merge_ctx->key_range_index++;
while (merge_ctx->key_range_index < _key_range_size) {
status = merge_ctx->column_data->prepare_block_read(
_current_read_context->lower_bound_keys->at(merge_ctx->key_range_index),
_current_read_context->is_lower_keys_included->at(merge_ctx->key_range_index),
_current_read_context->upper_bound_keys->at(merge_ctx->key_range_index),
_current_read_context->is_upper_keys_included->at(merge_ctx->key_range_index),
&(merge_ctx->row_block));
if (status == OLAP_ERR_DATA_EOF) {
merge_ctx->key_range_index++;
continue;
} else if (status != OLAP_SUCCESS) {
LOG(WARNING) << "prepare block read failed. status=" << status;
return status;
} else {
break;
}
}
if (merge_ctx->key_range_index >= _key_range_size) {
merge_ctx->row_block = nullptr;
return OLAP_ERR_DATA_EOF;
}
return status;
}
OLAPStatus AlphaRowsetReader::_init_merge_ctxs(RowsetReaderContext* read_context) {
if (read_context->reader_type == READER_QUERY) {
if (read_context->lower_bound_keys->size() != read_context->is_lower_keys_included->size()
|| read_context->lower_bound_keys->size() != read_context->upper_bound_keys->size()
|| read_context->upper_bound_keys->size() != read_context->is_upper_keys_included->size()) {
std::string error_msg = "invalid key range arguments";
LOG(WARNING) << error_msg;
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
_key_range_size = read_context->lower_bound_keys->size();
}
for (auto& segment_group : _segment_groups) {
std::unique_ptr<ColumnData> new_column_data(ColumnData::create(segment_group.get()));
OLAPStatus status = new_column_data->init();
if (status != OLAP_SUCCESS) {
LOG(WARNING) << "init column data failed";
return OLAP_ERR_READER_READING_ERROR;
}
new_column_data->set_delete_handler(read_context->delete_handler);
new_column_data->set_stats(_stats);
new_column_data->set_lru_cache(read_context->lru_cache);
if (read_context->reader_type == READER_ALTER_TABLE) {
new_column_data->schema_change_init();
new_column_data->set_using_cache(read_context->is_using_cache);
if (new_column_data->empty() && new_column_data->zero_num_rows()) {
continue;
}
} else {
new_column_data->set_read_params(*read_context->return_columns,
*read_context->seek_columns,
*read_context->load_bf_columns,
*read_context->conditions,
*read_context->predicates,
read_context->is_using_cache,
read_context->runtime_state);
// filter
if (new_column_data->rowset_pruning_filter()) {
_stats->rows_stats_filtered += new_column_data->num_rows();
VLOG(3) << "filter segment group in query in condition. version="
<< new_column_data->version().first
<< "-" << new_column_data->version().second;
continue;
}
}
int ret = new_column_data->delete_pruning_filter();
if (ret == DEL_SATISFIED) {
_stats->rows_del_filtered += new_column_data->num_rows();
VLOG(3) << "filter segment group in delete predicate:"
<< new_column_data->version().first << ", " << new_column_data->version().second;
continue;
} else if (ret == DEL_PARTIAL_SATISFIED) {
VLOG(3) << "filter segment group partially in delete predicate:"
<< new_column_data->version().first << ", " << new_column_data->version().second;
new_column_data->set_delete_status(DEL_PARTIAL_SATISFIED);
} else {
VLOG(3) << "not filter segment group in delete predicate:"
<< new_column_data->version().first << ", " << new_column_data->version().second;
new_column_data->set_delete_status(DEL_NOT_SATISFIED);
}
MergeContext merge_ctx;
merge_ctx.column_data = std::move(new_column_data);
_merge_ctxs.emplace_back(std::move(merge_ctx));
}
if (!_is_singleton_rowset && _merge_ctxs.size() > 1) {
LOG(WARNING) << "invalid column_datas for cumulative rowset. column_datas size:"
<< _merge_ctxs.size();
return OLAP_ERR_READER_READING_ERROR;
}
return OLAP_SUCCESS;
}
RowsetSharedPtr AlphaRowsetReader::rowset() {
return _rowset;
}
} // namespace doris
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "olap/rowset/alpha_rowset_reader.h"
#include "olap/rowset/alpha_rowset.h"
namespace doris {
AlphaRowsetReader::AlphaRowsetReader(
int num_rows_per_row_block,
RowsetSharedPtr rowset)
: _num_rows_per_row_block(num_rows_per_row_block),
_rowset(rowset),
_alpha_rowset_meta(nullptr),
_segment_groups(std::dynamic_pointer_cast<AlphaRowset>(rowset)->_segment_groups),
_key_range_size(0) {
RowsetMetaSharedPtr rowset_meta_ptr = (std::dynamic_pointer_cast<AlphaRowset>(rowset)->_rowset_meta);
_alpha_rowset_meta = reinterpret_cast<AlphaRowsetMeta*>(rowset_meta_ptr.get());
}
AlphaRowsetReader::~AlphaRowsetReader() {
delete _dst_cursor;
}
OLAPStatus AlphaRowsetReader::init(RowsetReaderContext* read_context) {
if (read_context == nullptr) {
return OLAP_ERR_INIT_FAILED;
}
_current_read_context = read_context;
if (_current_read_context->stats != nullptr) {
_stats = _current_read_context->stats;
}
Version version = _alpha_rowset_meta->version();
_is_singleton_rowset = (version.first == version.second);
_ordinal = 0;
bool merge = false;
/*
* For singleton rowset, there exists three situations.
* 1. QUERY task will set preaggregation.
* If preaggregation is set to be true
* there is not necessary to merge row in advance.
* 2. QEURY task for DUP_KEYS tablet has no necessities
* to merge row in advance.
* 2. COMPACTION/CHECKSUM/ALTER_TABLET task should merge
* row in advance.
* For cumulative rowset, there are no necessities to merge row in advance.
*/
RETURN_NOT_OK(_init_merge_ctxs(read_context));
if (_is_singleton_rowset && _merge_ctxs.size() > 1) {
if (_current_read_context->reader_type == READER_QUERY
&& _current_read_context->preaggregation) {
// 1. QUERY task which set pregaggregation to be true
_next_block = &AlphaRowsetReader::_union_block;
} else if (_current_read_context->reader_type == READER_QUERY
&& _current_read_context->tablet_schema->keys_type() == DUP_KEYS) {
// 2. QUERY task for DUP_KEYS tablet
_next_block = &AlphaRowsetReader::_union_block;
} else {
// 3. COMPACTION/CHECKSUM/ALTER_TABLET task
_next_block = &AlphaRowsetReader::_merge_block;
merge = true;
}
} else {
// query task to scan cumulative rowset
_next_block = &AlphaRowsetReader::_union_block;
}
if (merge) {
_read_block.reset(new (std::nothrow) RowBlock(_current_read_context->tablet_schema));
if (_read_block == nullptr) {
LOG(WARNING) << "new row block failed in reader";
return OLAP_ERR_MALLOC_ERROR;
}
RowBlockInfo block_info;
block_info.row_num = _current_read_context->tablet_schema->num_rows_per_row_block();
block_info.null_supported = true;
_read_block->init(block_info);
_dst_cursor = new (std::nothrow) RowCursor();
if (_dst_cursor == nullptr) {
LOG(WARNING) << "allocate memory for row cursor failed";
return OLAP_ERR_MALLOC_ERROR;
}
if (_current_read_context->reader_type == READER_ALTER_TABLE) {
// Upon rollup/alter table, seek_columns is nullptr.
// Under this circumstance, init RowCursor with all columns.
_dst_cursor->init(*(_current_read_context->tablet_schema));
} else {
_dst_cursor->init(*(_current_read_context->tablet_schema),
*(_current_read_context->seek_columns));
}
for (size_t i = 0; i < _merge_ctxs.size(); ++i) {
_merge_ctxs[i].row_cursor.reset(new (std::nothrow) RowCursor());
_merge_ctxs[i].row_cursor->init(*(_current_read_context->tablet_schema),
*(_current_read_context->seek_columns));
}
}
return OLAP_SUCCESS;
}
OLAPStatus AlphaRowsetReader::next_block(RowBlock** block) {
return (this->*_next_block)(block);
}
bool AlphaRowsetReader::delete_flag() {
return _alpha_rowset_meta->delete_flag();
}
Version AlphaRowsetReader::version() {
return _alpha_rowset_meta->version();
}
VersionHash AlphaRowsetReader::version_hash() {
return _alpha_rowset_meta->version_hash();
}
void AlphaRowsetReader::close() {
_merge_ctxs.clear();
}
int64_t AlphaRowsetReader::filtered_rows() {
return _stats->rows_del_filtered;
}
OLAPStatus AlphaRowsetReader::_union_block(RowBlock** block) {
while (_ordinal < _merge_ctxs.size()) {
// union block only use one block to store
OLAPStatus status = _pull_next_block(&(_merge_ctxs[_ordinal]));
if (status == OLAP_ERR_DATA_EOF) {
_ordinal++;
continue;
} else if (status != OLAP_SUCCESS) {
return status;
} else {
(*block) = _merge_ctxs[_ordinal].row_block;
return OLAP_SUCCESS;
}
}
if (_ordinal == _merge_ctxs.size()) {
*block = nullptr;
return OLAP_ERR_DATA_EOF;
}
return OLAP_SUCCESS;
}
OLAPStatus AlphaRowsetReader::_merge_block(RowBlock** block) {
// Row among different segment groups may overlap with each other.
// Iterate all row_blocks to fetch min row each round.
OLAPStatus status = OLAP_SUCCESS;
_read_block->clear();
size_t num_rows_in_block = 0;
while (_read_block->pos() < _num_rows_per_row_block) {
RowCursor* row_cursor = nullptr;
status = _pull_next_row_for_merge_rowset(&row_cursor);
if (status == OLAP_ERR_DATA_EOF && _read_block->pos() > 0) {
status = OLAP_SUCCESS;
break;
} else if (status != OLAP_SUCCESS) {
return status;
}
_read_block->get_row(_read_block->pos(), _dst_cursor);
_dst_cursor->copy(*row_cursor, _read_block->mem_pool());
_read_block->pos_inc();
num_rows_in_block++;
}
_read_block->set_pos(0);
_read_block->set_limit(num_rows_in_block);
_read_block->finalize(num_rows_in_block);
*block = _read_block.get();
return status;
}
OLAPStatus AlphaRowsetReader::_pull_next_row_for_merge_rowset(RowCursor** row) {
RowCursor* min_row = nullptr;
int min_index = -1;
size_t ordinal = 0;
while (ordinal < _merge_ctxs.size()) {
MergeContext* merge_ctx = &(_merge_ctxs[ordinal]);
if (merge_ctx->row_block == nullptr || !merge_ctx->row_block->has_remaining()) {
OLAPStatus status = _pull_next_block(merge_ctx);
if (status == OLAP_ERR_DATA_EOF) {
_merge_ctxs.erase(_merge_ctxs.begin() + ordinal);
continue;
} else if (status != OLAP_SUCCESS) {
LOG(WARNING) << "read next row of singleton rowset failed:" << status;
return status;
}
}
RowCursor* current_row = merge_ctx->row_cursor.get();
merge_ctx->row_block->get_row(merge_ctx->row_block->pos(), current_row);
if (min_row == nullptr || min_row->cmp(*current_row) > 0) {
min_row = current_row;
min_index = ordinal;
}
ordinal++;
}
if (min_row == nullptr || min_index == -1) {
return OLAP_ERR_DATA_EOF;
}
*row = min_row;
_merge_ctxs[min_index].row_block->pos_inc();
return OLAP_SUCCESS;
}
OLAPStatus AlphaRowsetReader::_pull_next_block(MergeContext* merge_ctx) {
OLAPStatus status = OLAP_SUCCESS;
if (OLAP_UNLIKELY(merge_ctx->first_read_symbol)) {
if (_key_range_size > 0) {
status = _pull_first_block(merge_ctx);
} else {
status = merge_ctx->column_data->get_first_row_block(&(merge_ctx->row_block));
if (status != OLAP_SUCCESS && status != OLAP_ERR_DATA_EOF) {
LOG(WARNING) << "get first row block failed, status:" << status;
}
}
merge_ctx->first_read_symbol = false;
return status;
} else {
// get next block
status = merge_ctx->column_data->get_next_block(&(merge_ctx->row_block));
if (status == OLAP_ERR_DATA_EOF && _key_range_size > 0) {
// reach the end of one predicate
// currently, SegmentReader can only support filter one key range a time
// refresh the predicate and continue read
return _pull_first_block(merge_ctx);
}
}
return status;
}
OLAPStatus AlphaRowsetReader::_pull_first_block(MergeContext* merge_ctx) {
OLAPStatus status = OLAP_SUCCESS;
merge_ctx->key_range_index++;
while (merge_ctx->key_range_index < _key_range_size) {
status = merge_ctx->column_data->prepare_block_read(
_current_read_context->lower_bound_keys->at(merge_ctx->key_range_index),
_current_read_context->is_lower_keys_included->at(merge_ctx->key_range_index),
_current_read_context->upper_bound_keys->at(merge_ctx->key_range_index),
_current_read_context->is_upper_keys_included->at(merge_ctx->key_range_index),
&(merge_ctx->row_block));
if (status == OLAP_ERR_DATA_EOF) {
merge_ctx->key_range_index++;
continue;
} else if (status != OLAP_SUCCESS) {
LOG(WARNING) << "prepare block read failed. status=" << status;
return status;
} else {
break;
}
}
if (merge_ctx->key_range_index >= _key_range_size) {
merge_ctx->row_block = nullptr;
return OLAP_ERR_DATA_EOF;
}
return status;
}
OLAPStatus AlphaRowsetReader::_init_merge_ctxs(RowsetReaderContext* read_context) {
if (read_context->reader_type == READER_QUERY) {
if (read_context->lower_bound_keys->size() != read_context->is_lower_keys_included->size()
|| read_context->lower_bound_keys->size() != read_context->upper_bound_keys->size()
|| read_context->upper_bound_keys->size() != read_context->is_upper_keys_included->size()) {
std::string error_msg = "invalid key range arguments";
LOG(WARNING) << error_msg;
return OLAP_ERR_INPUT_PARAMETER_ERROR;
}
_key_range_size = read_context->lower_bound_keys->size();
}
for (auto& segment_group : _segment_groups) {
std::unique_ptr<ColumnData> new_column_data(ColumnData::create(segment_group.get()));
OLAPStatus status = new_column_data->init();
if (status != OLAP_SUCCESS) {
LOG(WARNING) << "init column data failed";
return OLAP_ERR_READER_READING_ERROR;
}
new_column_data->set_delete_handler(read_context->delete_handler);
new_column_data->set_stats(_stats);
new_column_data->set_lru_cache(read_context->lru_cache);
if (read_context->reader_type == READER_ALTER_TABLE) {
new_column_data->schema_change_init();
new_column_data->set_using_cache(read_context->is_using_cache);
if (new_column_data->empty() && new_column_data->zero_num_rows()) {
continue;
}
} else {
new_column_data->set_read_params(*read_context->return_columns,
*read_context->seek_columns,
*read_context->load_bf_columns,
*read_context->conditions,
*read_context->predicates,
read_context->is_using_cache,
read_context->runtime_state);
// filter
if (new_column_data->rowset_pruning_filter()) {
_stats->rows_stats_filtered += new_column_data->num_rows();
VLOG(3) << "filter segment group in query in condition. version="
<< new_column_data->version().first
<< "-" << new_column_data->version().second;
continue;
}
}
int ret = new_column_data->delete_pruning_filter();
if (ret == DEL_SATISFIED) {
_stats->rows_del_filtered += new_column_data->num_rows();
VLOG(3) << "filter segment group in delete predicate:"
<< new_column_data->version().first << ", " << new_column_data->version().second;
continue;
} else if (ret == DEL_PARTIAL_SATISFIED) {
VLOG(3) << "filter segment group partially in delete predicate:"
<< new_column_data->version().first << ", " << new_column_data->version().second;
new_column_data->set_delete_status(DEL_PARTIAL_SATISFIED);
} else {
VLOG(3) << "not filter segment group in delete predicate:"
<< new_column_data->version().first << ", " << new_column_data->version().second;
new_column_data->set_delete_status(DEL_NOT_SATISFIED);
}
MergeContext merge_ctx;
merge_ctx.column_data = std::move(new_column_data);
_merge_ctxs.emplace_back(std::move(merge_ctx));
}
if (!_is_singleton_rowset && _merge_ctxs.size() > 1) {
LOG(WARNING) << "invalid column_datas for cumulative rowset. column_datas size:"
<< _merge_ctxs.size();
return OLAP_ERR_READER_READING_ERROR;
}
return OLAP_SUCCESS;
}
RowsetSharedPtr AlphaRowsetReader::rowset() {
return _rowset;
}
} // namespace doris
|
Fix rollup bug when init RowCursor (#1502)
|
Fix rollup bug when init RowCursor (#1502)
When doing rollup, seek_columns equals to the complete set of tablet's columns.
There is no necessity to set it.
|
C++
|
apache-2.0
|
imay/palo,imay/palo,imay/palo,imay/palo,imay/palo,imay/palo
|
ce733a44c26d485af4e2466e14700cf8b5e9dd01
|
checks/bench.cpp
|
checks/bench.cpp
|
/*
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <iostream>
#include <iomanip>
#include <botan/benchmark.h>
#include <botan/libstate.h>
#include <botan/pipe.h>
#include <botan/filters.h>
#include <botan/engine.h>
#include <botan/parsing.h>
#include <botan/symkey.h>
#include <botan/time.h>
#include "common.h"
#include "bench.h"
namespace {
const std::string algos[] = {
/* Block ciphers */
"AES-128",
"AES-192",
"AES-256",
"Blowfish",
"CAST-128",
"CAST-256",
"DES",
"DESX",
"GOST",
"IDEA",
"KASUMI",
"MARS",
"MISTY1",
"Noekeon",
"RC2",
"RC5(12)",
"RC5(16)",
"RC6",
"SAFER-SK(10)",
"SEED",
"Serpent",
"Skipjack",
"Square",
"TEA",
"TripleDES",
"Twofish",
"XTEA",
/* Cipher constructions */
"Cascade(Serpent,AES-128)",
"Lion(SHA-256,Salsa20,8192)",
"Luby-Rackoff(SHA-512)",
/* Cipher modes */
"TripleDES/CBC/PKCS7",
"TripleDES/CBC/CTS",
"TripleDES/CTR-BE",
"TripleDES/EAX",
"TripleDES/OFB",
"TripleDES/CFB(64)",
"TripleDES/CFB(32)",
"TripleDES/CFB(16)",
"TripleDES/CFB(8)",
"AES-128/CBC/PKCS7",
"AES-128/CBC/CTS",
"AES-128/CTR-BE",
"AES-128/EAX",
"AES-128/OFB",
"AES-128/XTS",
"AES-128/CFB(128)",
"AES-128/CFB(64)",
"AES-128/CFB(32)",
"AES-128/CFB(16)",
"AES-128/CFB(8)",
"Serpent/CBC/PKCS7",
"Serpent/CBC/CTS",
"Serpent/CTR-BE",
"Serpent/EAX",
"Serpent/OFB",
"Serpent/XTS",
"Serpent/CFB(128)",
"Serpent/CFB(64)",
"Serpent/CFB(32)",
"Serpent/CFB(16)",
"Serpent/CFB(8)",
/* Stream ciphers */
"ARC4",
"Salsa20",
"Turing",
"WiderWake4+1-BE",
/* Checksums */
"Adler32",
"CRC24",
"CRC32",
/* Hashes */
"BMW-512",
"GOST-34.11",
"HAS-160",
"MD2",
"MD4",
"MD5",
"RIPEMD-128",
"RIPEMD-160",
"SHA-160",
"SHA-256",
"SHA-384",
"SHA-512",
"Skein-512",
"Tiger",
"Whirlpool",
/* MACs */
"CMAC(AES-128)",
"HMAC(SHA-1)",
"X9.19-MAC",
"",
};
void report_results(const std::string& algo,
const std::map<std::string, double>& speeds)
{
// invert, showing fastest impl first
std::map<double, std::string> results;
for(std::map<std::string, double>::const_iterator i = speeds.begin();
i != speeds.end(); ++i)
{
// Speeds might collide, tweak slightly to handle this
if(results[i->second] == "")
results[i->second] = i->first;
else
results[i->second - .01] = i->first;
}
std::cout << algo;
#if defined(__GNUC__) && __GNUC__ <= 3
// Work around GCC 3.x bug, reverse iterators don't work
for(std::map<double, std::string>::const_iterator i = results.begin(); i != results.end(); ++i)
#else
for(std::map<double, std::string>::const_reverse_iterator i = results.rbegin(); i != results.rend(); ++i)
#endif
{
std::cout << " [" << i->second << "] "
<< std::fixed << std::setprecision(2) << i->first;
}
std::cout << std::endl;
}
}
bool bench_algo(const std::string& algo,
Botan::RandomNumberGenerator& rng,
double seconds)
{
Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory();
u32bit milliseconds = static_cast<u32bit>(seconds * 1000);
std::map<std::string, double> speeds =
algorithm_benchmark(algo, milliseconds, rng, af);
if(speeds.empty()) // maybe a cipher mode, then?
{
Botan::Algorithm_Factory::Engine_Iterator i(af);
std::vector<std::string> algo_parts = Botan::split_on(algo, '/');
if(algo_parts.size() < 2) // not a cipher mode
return false;
std::string cipher = algo_parts[0];
const Botan::BlockCipher* proto_cipher =
af.prototype_block_cipher(cipher);
if(!proto_cipher)
{
std::cout << "Unknown algorithm " << cipher << "\n";
return false;
}
u32bit cipher_keylen = proto_cipher->MAXIMUM_KEYLENGTH;
u32bit cipher_ivlen = proto_cipher->BLOCK_SIZE;
if(algo_parts[1] == "XTS")
cipher_keylen *= 2; // hack!
std::vector<byte> buf(16 * 1024);
rng.randomize(&buf[0], buf.size());
while(Botan::Engine* engine = i.next())
{
u64bit nanoseconds_max = static_cast<u64bit>(seconds * 1000000000.0);
Botan::Keyed_Filter* filt =
engine->get_cipher(algo, Botan::ENCRYPTION, af);
if(!filt)
continue;
filt->set_key(Botan::SymmetricKey(&buf[0], cipher_keylen));
filt->set_iv(Botan::InitializationVector(&buf[0], cipher_ivlen));
Botan::Pipe pipe(filt, new Botan::BitBucket);
pipe.start_msg();
const u64bit start = Botan::get_nanoseconds_clock();
u64bit nanoseconds_used = 0;
u64bit reps = 0;
while(nanoseconds_used < nanoseconds_max)
{
pipe.write(&buf[0], buf.size());
++reps;
nanoseconds_used = Botan::get_nanoseconds_clock() - start;
}
double mbytes_per_second =
(953.67 * (buf.size() * reps)) / nanoseconds_used;
speeds[engine->provider_name()] = mbytes_per_second;
}
}
if(!speeds.empty())
report_results(algo, speeds);
return !speeds.empty();
}
void benchmark(Botan::RandomNumberGenerator& rng,
double seconds)
{
for(u32bit i = 0; algos[i] != ""; ++i)
bench_algo(algos[i], rng, seconds);
}
|
/*
* (C) 2009 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <iostream>
#include <iomanip>
#include <botan/benchmark.h>
#include <botan/libstate.h>
#include <botan/pipe.h>
#include <botan/filters.h>
#include <botan/engine.h>
#include <botan/parsing.h>
#include <botan/symkey.h>
#include <botan/time.h>
#include "common.h"
#include "bench.h"
namespace {
const std::string algos[] = {
/* Block ciphers */
"AES-128",
"AES-192",
"AES-256",
"Blowfish",
"CAST-128",
"CAST-256",
"DES",
"DESX",
"GOST",
"IDEA",
"KASUMI",
"MARS",
"MISTY1",
"Noekeon",
"RC2",
"RC5(12)",
"RC5(16)",
"RC6",
"SAFER-SK(10)",
"SEED",
"Serpent",
"Skipjack",
"Square",
"TEA",
"TripleDES",
"Twofish",
"XTEA",
/* Cipher constructions */
"Cascade(Serpent,AES-128)",
"Lion(SHA-256,Salsa20,8192)",
"Luby-Rackoff(SHA-512)",
/* Cipher modes */
"TripleDES/CBC/PKCS7",
"TripleDES/CBC/CTS",
"TripleDES/CTR-BE",
"TripleDES/EAX",
"TripleDES/OFB",
"TripleDES/CFB(64)",
"TripleDES/CFB(32)",
"TripleDES/CFB(16)",
"TripleDES/CFB(8)",
"AES-128/CBC/PKCS7",
"AES-128/CBC/CTS",
"AES-128/CTR-BE",
"AES-128/EAX",
"AES-128/OFB",
"AES-128/XTS",
"AES-128/CFB(128)",
"AES-128/CFB(64)",
"AES-128/CFB(32)",
"AES-128/CFB(16)",
"AES-128/CFB(8)",
"Serpent/CBC/PKCS7",
"Serpent/CBC/CTS",
"Serpent/CTR-BE",
"Serpent/EAX",
"Serpent/OFB",
"Serpent/XTS",
"Serpent/CFB(128)",
"Serpent/CFB(64)",
"Serpent/CFB(32)",
"Serpent/CFB(16)",
"Serpent/CFB(8)",
/* Stream ciphers */
"ARC4",
"Salsa20",
"Turing",
"WiderWake4+1-BE",
/* Checksums */
"Adler32",
"CRC24",
"CRC32",
/* Hashes */
"BMW-512",
"GOST-34.11",
"HAS-160",
"MD2",
"MD4",
"MD5",
"RIPEMD-128",
"RIPEMD-160",
"SHA-160",
"SHA-256",
"SHA-384",
"SHA-512",
"Skein-512",
"Tiger",
"Whirlpool",
/* MACs */
"CMAC(AES-128)",
"HMAC(SHA-1)",
"X9.19-MAC",
"",
};
void report_results(const std::string& algo,
const std::map<std::string, double>& speeds)
{
// invert, showing fastest impl first
std::map<double, std::string> results;
for(std::map<std::string, double>::const_iterator i = speeds.begin();
i != speeds.end(); ++i)
{
// Speeds might collide, tweak slightly to handle this
if(results[i->second] == "")
results[i->second] = i->first;
else
results[i->second - .01] = i->first;
}
std::cout << algo;
#if defined(__GNUC__) && __GNUC__ <= 3
// Work around GCC 3.x bug, reverse iterators don't work
for(std::map<double, std::string>::const_iterator i = results.begin(); i != results.end(); ++i)
#else
for(std::map<double, std::string>::const_reverse_iterator i = results.rbegin(); i != results.rend(); ++i)
#endif
{
std::cout << " [" << i->second << "] "
<< std::fixed << std::setprecision(2) << i->first;
}
std::cout << std::endl;
}
}
bool bench_algo(const std::string& algo,
Botan::RandomNumberGenerator& rng,
double seconds)
{
Botan::Algorithm_Factory& af = Botan::global_state().algorithm_factory();
u32bit milliseconds = static_cast<u32bit>(seconds * 1000);
std::map<std::string, double> speeds =
algorithm_benchmark(algo, milliseconds, rng, af);
if(speeds.empty()) // maybe a cipher mode, then?
{
Botan::Algorithm_Factory::Engine_Iterator i(af);
std::vector<std::string> algo_parts = Botan::split_on(algo, '/');
if(algo_parts.size() < 2) // not a cipher mode
return false;
std::string cipher = algo_parts[0];
const Botan::BlockCipher* proto_cipher =
af.prototype_block_cipher(cipher);
if(!proto_cipher)
{
std::cout << "Unknown algorithm " << cipher << "\n";
return false;
}
u32bit cipher_keylen = proto_cipher->MAXIMUM_KEYLENGTH;
u32bit cipher_ivlen = proto_cipher->BLOCK_SIZE;
if(algo_parts[1] == "XTS")
cipher_keylen *= 2; // hack!
std::vector<byte> buf(16 * 1024);
rng.randomize(&buf[0], buf.size());
while(Botan::Engine* engine = i.next())
{
u64bit nanoseconds_max = static_cast<u64bit>(seconds * 1000000000.0);
Botan::Keyed_Filter* filt =
engine->get_cipher(algo, Botan::ENCRYPTION, af);
if(!filt)
continue;
filt->set_key(Botan::SymmetricKey(&buf[0], cipher_keylen));
if(filt->valid_iv_length(cipher_ivlen / 2))
filt->set_iv(Botan::InitializationVector(&buf[0], cipher_ivlen));
Botan::Pipe pipe(filt, new Botan::BitBucket);
pipe.start_msg();
const u64bit start = Botan::get_nanoseconds_clock();
u64bit nanoseconds_used = 0;
u64bit reps = 0;
while(nanoseconds_used < nanoseconds_max)
{
pipe.write(&buf[0], buf.size());
++reps;
nanoseconds_used = Botan::get_nanoseconds_clock() - start;
}
double mbytes_per_second =
(953.67 * (buf.size() * reps)) / nanoseconds_used;
speeds[engine->provider_name()] = mbytes_per_second;
}
}
if(!speeds.empty())
report_results(algo, speeds);
return !speeds.empty();
}
void benchmark(Botan::RandomNumberGenerator& rng,
double seconds)
{
for(u32bit i = 0; algos[i] != ""; ++i)
bench_algo(algos[i], rng, seconds);
}
|
Fix ECB benchmarking
|
Fix ECB benchmarking
|
C++
|
bsd-2-clause
|
randombit/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,randombit/botan,webmaster128/botan,randombit/botan,webmaster128/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,webmaster128/botan,randombit/botan,webmaster128/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan,Rohde-Schwarz-Cybersecurity/botan
|
998eb215bf13cf3be9f631a443d7e2d13e38be0a
|
benchmarks/DNN/blocks/LSTM/cpu/wrapper.cpp
|
benchmarks/DNN/blocks/LSTM/cpu/wrapper.cpp
|
#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "wrapper.h"
typedef std::chrono::duration<double,std::milli> duration_t;
int main(int argc, char *argv[])
{
int testN = 1;
int warmupN = 0;
int feature_size = 512;
int batch_size = 64;
int num_layers = 4;
int seq_length = 100;
// Note that indices are flipped (see tutorial 2)
Halide::Buffer<int32_t> buf_params(4);
Halide::Buffer<float> buf_Weights(feature_size, 4 * feature_size, 2, num_layers);
Halide::Buffer<float> buf_biases(feature_size, 4, num_layers);
Halide::Buffer<float> buf_x(feature_size, batch_size, seq_length);
Halide::Buffer<float> buf_y(feature_size, batch_size, seq_length);
buf_params(0) = feature_size;
buf_params(1) = batch_size;
buf_params(2) = num_layers;
buf_params(3) = seq_length;
std::srand(0);
for (int i = 0; i < num_layers; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 4 * feature_size; k++) {
for (int l = 0; l < feature_size; l++) {
buf_Weights(l, k, j, i) = (std::rand() % 200 - 100) / 100.;
}
}
}
}
for (int i = 0; i < num_layers; i++) {
for (int j = 0; j < 4; j++) {
for (int k = 0; k < feature_size; k++) {
buf_biases(k, j, i) = (std::rand() % 200 - 100) / 100.;
}
}
}
for (int i = 0; i < seq_length; i++) {
for (int j = 0; j < batch_size; j++) {
for (int k = 0; k < feature_size; k++) {
buf_x(k, j, i) = (std::rand() % 200 - 100) / 100.;
}
}
}
for (int i = 0; i < warmupN; i++) {
lstm(buf_params.raw_buffer(),
buf_Weights.raw_buffer(),
buf_biases.raw_buffer(),
buf_x.raw_buffer(),
buf_y.raw_buffer());
}
std::vector<duration_t> durations;
for (int i = 0; i < testN; i++) {
auto t1 = std::chrono::high_resolution_clock::now();
lstm(buf_params.raw_buffer(),
buf_Weights.raw_buffer(),
buf_biases.raw_buffer(),
buf_x.raw_buffer(),
buf_y.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
durations.push_back(t2 - t1);
}
if (testN > 0) {
std::cout << "LSTM median runtime: " << median(durations) << "ms" << std::endl << std::flush;
}
std::cout << "LSTM done" << std::endl;
std::ofstream resultfile;
resultfile.open("tiramisu_result.txt");
for (int n = 0; n < seq_length; ++n)
for (int z = 0; z < batch_size; ++z)
for (int y = 0; y < feature_size; ++y)
{
resultfile << buf_y(y, z, n);
resultfile << "\n";
}
resultfile.close();
std::cout << "\t\t Result"
<< ":\n\n";
std::ifstream infile1("tiramisu_result.txt"), infile2("mkldnn_result.txt");
std::string line1, line2;
float file_count = 0, corr = 0, f1, f2;
while (std::getline(infile1, line1))
{
std::getline(infile2, line2);
file_count += 1;
f1 = std::stof(line1);
f2 = std::stof(line2);
if (abs(f1 - f2) < 0.02)
corr += 1;
}
printf("\t\t Percentage of correctness %f \n\n", corr / file_count * 100);
return 0;
}
|
#include "Halide.h"
#include <tiramisu/utils.h>
#include <cstdlib>
#include <iostream>
#include "wrapper.h"
typedef std::chrono::duration<double,std::milli> duration_t;
int main(int argc, char *argv[])
{
int testN = 1;
int warmupN = 0;
int feature_size = 512;
int batch_size = 64;
int num_layers = 4;
int seq_length = 100;
// Note that indices are flipped (see tutorial 2)
Halide::Buffer<int32_t> buf_params(4);
Halide::Buffer<float> buf_Weights(feature_size, 4 * feature_size, 2, num_layers);
Halide::Buffer<float> buf_biases(4 * feature_size, num_layers);
Halide::Buffer<float> buf_x(feature_size, batch_size, seq_length);
Halide::Buffer<float> buf_y(feature_size, batch_size, seq_length);
buf_params(0) = feature_size;
buf_params(1) = batch_size;
buf_params(2) = num_layers;
buf_params(3) = seq_length;
std::srand(0);
for (int i = 0; i < num_layers; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 4 * feature_size; k++) {
for (int l = 0; l < feature_size; l++) {
buf_Weights(l, k, j, i) = (std::rand() % 200 - 100) / 100.;
}
}
}
}
for (int i = 0; i < num_layers; i++) {
for (int j = 0; j < 4 * feature_size; j++) {
buf_biases(j, i) = (std::rand() % 200 - 100) / 100.;
}
}
for (int i = 0; i < seq_length; i++) {
for (int j = 0; j < batch_size; j++) {
for (int k = 0; k < feature_size; k++) {
buf_x(k, j, i) = (std::rand() % 200 - 100) / 100.;
}
}
}
for (int i = 0; i < warmupN; i++) {
lstm(buf_params.raw_buffer(),
buf_Weights.raw_buffer(),
buf_biases.raw_buffer(),
buf_x.raw_buffer(),
buf_y.raw_buffer());
}
std::vector<duration_t> durations;
for (int i = 0; i < testN; i++) {
auto t1 = std::chrono::high_resolution_clock::now();
lstm(buf_params.raw_buffer(),
buf_Weights.raw_buffer(),
buf_biases.raw_buffer(),
buf_x.raw_buffer(),
buf_y.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
durations.push_back(t2 - t1);
}
if (testN > 0) {
std::cout << "LSTM median runtime: " << median(durations) << "ms" << std::endl << std::flush;
}
std::cout << "LSTM done" << std::endl;
std::ofstream resultfile;
resultfile.open("tiramisu_result.txt");
for (int n = 0; n < seq_length; ++n)
for (int z = 0; z < batch_size; ++z)
for (int y = 0; y < feature_size; ++y)
{
resultfile << buf_y(y, z, n);
resultfile << "\n";
}
resultfile.close();
std::cout << "\t\t Result"
<< ":\n\n";
std::ifstream infile1("tiramisu_result.txt"), infile2("mkldnn_result.txt");
std::string line1, line2;
float file_count = 0, corr = 0, f1, f2;
while (std::getline(infile1, line1))
{
std::getline(infile2, line2);
file_count += 1;
f1 = std::stof(line1);
f2 = std::stof(line2);
if (abs(f1 - f2) < 0.02)
corr += 1;
}
printf("\t\t Percentage of correctness %f \n\n", corr / file_count * 100);
return 0;
}
|
Update wrapper.cpp
|
Update wrapper.cpp
|
C++
|
mit
|
rbaghdadi/ISIR,rbaghdadi/ISIR,rbaghdadi/COLi,rbaghdadi/COLi
|
cd44327c9a8fd3df9a23dbc04b03f8f0119dd376
|
tools/tfmanager/servermanager.cpp
|
tools/tfmanager/servermanager.cpp
|
/* Copyright (c) 2010-2012, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QtNetwork>
#include <TGlobal>
#include <TWebApplication>
#include <TSystemGlobal>
#include <TApplicationServer>
#include <TLog>
#include "qplatformdefs.h"
#include "servermanager.h"
namespace TreeFrog {
#if defined(Q_OS_WIN) && !defined(TF_NO_DEBUG)
# define TFSERVER_CMD INSTALL_PATH "/tadpoled"
#else
# define TFSERVER_CMD INSTALL_PATH "/tadpole"
#endif
static QMap<QProcess *, int> serversStatus;
ServerManager::ServerManager(int max, int min, int spare, QObject *parent)
: QObject(parent), listeningSocket(0), maxServers(max), minServers(min), spareServers(spare), running(false)
{
spareServers = qMax(spareServers, 0);
minServers = qMax(minServers, 1);
maxServers = qMax(maxServers, minServers);
}
ServerManager::~ServerManager()
{
stop();
}
bool ServerManager::start(const QHostAddress &address, quint16 port)
{
if (isRunning())
return true;
#ifdef Q_OS_UNIX
int sd = TApplicationServer::nativeListen(address, port, TApplicationServer::NonCloseOnExec);
if (sd <= 0) {
tSystemError("Failed to create listening socket");
fprintf(stderr, "Failed to create listening socket\n");
return false;
}
if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) {
listeningSocket = sd;
} else {
// Just tried to open a socket.
close(sd);
// tfserver process will open a socket of that.
}
#endif
running = true;
ajustServers();
tSystemInfo("TreeFrog application servers start up. port:%d", port);
return true;
}
bool ServerManager::start(const QString &fileDomain)
{
if (isRunning())
return true;
int sd = TApplicationServer::nativeListen(fileDomain, TApplicationServer::NonCloseOnExec);
if (sd <= 0) {
tSystemError("listening socket create failed [%s:%d]", __FILE__, __LINE__);
fprintf(stderr, "Failed to create listening socket of UNIX domain\n");
return false;
}
if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) {
listeningSocket = sd;
} else {
// Just tried to open a socket.
TF_CLOSE(sd);
// tfserver process will open a socket of that.
}
running = true;
ajustServers();
tSystemInfo("TreeFrog application servers start up. Domain file name:%s", qPrintable(fileDomain));
return true;
}
void ServerManager::stop()
{
if (!isRunning())
return;
running = false;
if (listeningSocket > 0) {
TF_CLOSE(listeningSocket);
}
listeningSocket = 0;
if (serverCount() > 0) {
tSystemInfo("TreeFrog application servers shutting down");
for (QMapIterator<QProcess *, int> i(serversStatus); i.hasNext(); ) {
QProcess *tfserver = i.next().key();
disconnect(tfserver, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0);
disconnect(tfserver, SIGNAL(readyReadStandardError()), 0, 0);
tfserver->terminate();
}
for (QMapIterator<QProcess *, int> i(serversStatus); i.hasNext(); ) {
QProcess *tfserver = i.next().key();
tfserver->waitForFinished(-1);
delete tfserver;
}
serversStatus.clear();
tSystemInfo("TreeFrog application servers shutdown completed");
}
}
bool ServerManager::isRunning() const
{
return running;
}
int ServerManager::serverCount() const
{
return serversStatus.count();
}
int ServerManager::spareServerCount() const
{
int count = 0;
for (QMapIterator<QProcess *, int> i(serversStatus); i.hasNext(); ) {
int state = i.next().value();
if (state == Listening) {
++count;
}
}
return count;
}
void ServerManager::ajustServers() const
{
if (isRunning()) {
tSystemDebug("serverCount: %d spare: %d", serverCount(), spareServerCount());
if (serverCount() < maxServers && (serverCount() < minServers || spareServerCount() < spareServers)) {
startServer();
}
}
}
void ServerManager::startServer() const
{
QStringList args = QCoreApplication::arguments();
args.removeFirst();
if (listeningSocket > 0) {
args.prepend(QString::number(listeningSocket));
args.prepend("-s");
}
QProcess *tfserver = new QProcess;
serversStatus.insert(tfserver, NotRunning);
connect(tfserver, SIGNAL(started()), this, SLOT(updateServerStatus()));
connect(tfserver, SIGNAL(error(QProcess::ProcessError)), this, SLOT(errorDetect(QProcess::ProcessError)));
connect(tfserver, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(serverFinish(int, QProcess::ExitStatus)));
connect(tfserver, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));
connect(tfserver, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError()));
#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
// Sets LD_LIBRARY_PATH environment variable
QString ldpath = "."; // means the lib dir
QString sysldpath = QProcess::systemEnvironment().filter("LD_LIBRARY_PATH=", Qt::CaseSensitive).value(0).mid(16);
if (!sysldpath.isEmpty()) {
ldpath += ":";
ldpath += sysldpath;
}
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("LD_LIBRARY_PATH", ldpath);
tfserver->setProcessEnvironment(env);
tSystemDebug("export %s=%s", "LD_LIBRARY_PATH", qPrintable(ldpath));
#endif
// Executes treefrog server
tfserver->start(TFSERVER_CMD, args, QIODevice::ReadOnly);
tfserver->closeWriteChannel();
tSystemDebug("tfserver started");
}
void ServerManager::updateServerStatus()
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
if (serversStatus.contains(server)) {
serversStatus.insert(server, Listening);
}
ajustServers();
}
}
void ServerManager::errorDetect(QProcess::ProcessError error)
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
tSystemError("tfserver error detected(%d). [%s]", error, TFSERVER_CMD);
//server->close(); // long blocking..
server->deleteLater();
serversStatus.remove(server);
ajustServers();
}
}
void ServerManager::serverFinish(int exitCode, QProcess::ExitStatus exitStatus) const
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
//server->close(); // long blocking..
server->deleteLater();
serversStatus.remove(server);
if (exitStatus == QProcess::CrashExit) {
ajustServers();
} else {
tSystemInfo("Detected normal exit of server. exitCode:%d", exitCode);
if (serversStatus.count() == 0) {
Tf::app()->exit(-1);
}
}
}
}
void ServerManager::readStandardOutput()
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
QByteArray buf = server->readAllStandardOutput();
// writes a TLog object to stdout
printf("treefrog stdout: %s", buf.constData());
}
}
void ServerManager::readStandardError() const
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
QByteArray buf = server->readAllStandardError();
if (buf == "_accepted") {
if (serversStatus.contains(server)) {
serversStatus.insert(server, Running);
ajustServers();
}
} else {
tSystemWarn("treefrog stderr: %s", buf.constData());
fprintf(stderr, "treefrog stderr: %s", buf.constData());
}
}
}
} // namespace TreeFrog
|
/* Copyright (c) 2010-2012, AOYAMA Kazuharu
* All rights reserved.
*
* This software may be used and distributed according to the terms of
* the New BSD License, which is incorporated herein by reference.
*/
#include <QtNetwork>
#include <TGlobal>
#include <TWebApplication>
#include <TSystemGlobal>
#include <TApplicationServer>
#include <TLog>
#include "qplatformdefs.h"
#include "servermanager.h"
namespace TreeFrog {
#if defined(Q_OS_WIN) && !defined(TF_NO_DEBUG)
# define TFSERVER_CMD INSTALL_PATH "/tadpoled"
#else
# define TFSERVER_CMD INSTALL_PATH "/tadpole"
#endif
static QMap<QProcess *, int> serversStatus;
ServerManager::ServerManager(int max, int min, int spare, QObject *parent)
: QObject(parent), listeningSocket(0), maxServers(max), minServers(min), spareServers(spare), running(false)
{
spareServers = qMax(spareServers, 0);
minServers = qMax(minServers, 1);
maxServers = qMax(maxServers, minServers);
}
ServerManager::~ServerManager()
{
stop();
}
bool ServerManager::start(const QHostAddress &address, quint16 port)
{
if (isRunning())
return true;
#ifdef Q_OS_UNIX
int sd = TApplicationServer::nativeListen(address, port, TApplicationServer::NonCloseOnExec);
if (sd <= 0) {
tSystemError("Failed to create listening socket");
fprintf(stderr, "Failed to create listening socket\n");
return false;
}
if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) {
listeningSocket = sd;
} else {
// Just tried to open a socket.
close(sd);
// tfserver process will open a socket of that.
}
#else
Q_UNUSED(address);
#endif
running = true;
ajustServers();
tSystemInfo("TreeFrog application servers start up. port:%d", port);
return true;
}
bool ServerManager::start(const QString &fileDomain)
{
if (isRunning())
return true;
int sd = TApplicationServer::nativeListen(fileDomain, TApplicationServer::NonCloseOnExec);
if (sd <= 0) {
tSystemError("listening socket create failed [%s:%d]", __FILE__, __LINE__);
fprintf(stderr, "Failed to create listening socket of UNIX domain\n");
return false;
}
if (Tf::app()->multiProcessingModule() == TWebApplication::Prefork) {
listeningSocket = sd;
} else {
// Just tried to open a socket.
TF_CLOSE(sd);
// tfserver process will open a socket of that.
}
running = true;
ajustServers();
tSystemInfo("TreeFrog application servers start up. Domain file name:%s", qPrintable(fileDomain));
return true;
}
void ServerManager::stop()
{
if (!isRunning())
return;
running = false;
if (listeningSocket > 0) {
TF_CLOSE(listeningSocket);
}
listeningSocket = 0;
if (serverCount() > 0) {
tSystemInfo("TreeFrog application servers shutting down");
for (QMapIterator<QProcess *, int> i(serversStatus); i.hasNext(); ) {
QProcess *tfserver = i.next().key();
disconnect(tfserver, SIGNAL(finished(int, QProcess::ExitStatus)), 0, 0);
disconnect(tfserver, SIGNAL(readyReadStandardError()), 0, 0);
tfserver->terminate();
}
for (QMapIterator<QProcess *, int> i(serversStatus); i.hasNext(); ) {
QProcess *tfserver = i.next().key();
tfserver->waitForFinished(-1);
delete tfserver;
}
serversStatus.clear();
tSystemInfo("TreeFrog application servers shutdown completed");
}
}
bool ServerManager::isRunning() const
{
return running;
}
int ServerManager::serverCount() const
{
return serversStatus.count();
}
int ServerManager::spareServerCount() const
{
int count = 0;
for (QMapIterator<QProcess *, int> i(serversStatus); i.hasNext(); ) {
int state = i.next().value();
if (state == Listening) {
++count;
}
}
return count;
}
void ServerManager::ajustServers() const
{
if (isRunning()) {
tSystemDebug("serverCount: %d spare: %d", serverCount(), spareServerCount());
if (serverCount() < maxServers && (serverCount() < minServers || spareServerCount() < spareServers)) {
startServer();
}
}
}
void ServerManager::startServer() const
{
QStringList args = QCoreApplication::arguments();
args.removeFirst();
if (listeningSocket > 0) {
args.prepend(QString::number(listeningSocket));
args.prepend("-s");
}
QProcess *tfserver = new QProcess;
serversStatus.insert(tfserver, NotRunning);
connect(tfserver, SIGNAL(started()), this, SLOT(updateServerStatus()));
connect(tfserver, SIGNAL(error(QProcess::ProcessError)), this, SLOT(errorDetect(QProcess::ProcessError)));
connect(tfserver, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(serverFinish(int, QProcess::ExitStatus)));
connect(tfserver, SIGNAL(readyReadStandardOutput()), this, SLOT(readStandardOutput()));
connect(tfserver, SIGNAL(readyReadStandardError()), this, SLOT(readStandardError()));
#if defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN)
// Sets LD_LIBRARY_PATH environment variable
QString ldpath = "."; // means the lib dir
QString sysldpath = QProcess::systemEnvironment().filter("LD_LIBRARY_PATH=", Qt::CaseSensitive).value(0).mid(16);
if (!sysldpath.isEmpty()) {
ldpath += ":";
ldpath += sysldpath;
}
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("LD_LIBRARY_PATH", ldpath);
tfserver->setProcessEnvironment(env);
tSystemDebug("export %s=%s", "LD_LIBRARY_PATH", qPrintable(ldpath));
#endif
// Executes treefrog server
tfserver->start(TFSERVER_CMD, args, QIODevice::ReadOnly);
tfserver->closeWriteChannel();
tSystemDebug("tfserver started");
}
void ServerManager::updateServerStatus()
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
if (serversStatus.contains(server)) {
serversStatus.insert(server, Listening);
}
ajustServers();
}
}
void ServerManager::errorDetect(QProcess::ProcessError error)
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
tSystemError("tfserver error detected(%d). [%s]", error, TFSERVER_CMD);
//server->close(); // long blocking..
server->deleteLater();
serversStatus.remove(server);
ajustServers();
}
}
void ServerManager::serverFinish(int exitCode, QProcess::ExitStatus exitStatus) const
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
//server->close(); // long blocking..
server->deleteLater();
serversStatus.remove(server);
if (exitStatus == QProcess::CrashExit) {
ajustServers();
} else {
tSystemInfo("Detected normal exit of server. exitCode:%d", exitCode);
if (serversStatus.count() == 0) {
Tf::app()->exit(-1);
}
}
}
}
void ServerManager::readStandardOutput()
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
QByteArray buf = server->readAllStandardOutput();
// writes a TLog object to stdout
printf("treefrog stdout: %s", buf.constData());
}
}
void ServerManager::readStandardError() const
{
QProcess *server = qobject_cast<QProcess *>(sender());
if (server) {
QByteArray buf = server->readAllStandardError();
if (buf == "_accepted") {
if (serversStatus.contains(server)) {
serversStatus.insert(server, Running);
ajustServers();
}
} else {
tSystemWarn("treefrog stderr: %s", buf.constData());
fprintf(stderr, "treefrog stderr: %s", buf.constData());
}
}
}
} // namespace TreeFrog
|
fix compile warnings.
|
fix compile warnings.
|
C++
|
bsd-3-clause
|
Akhilesh05/treefrog-framework,gonboy/treefrog-framework,gonboy/treefrog-framework,gonboy/treefrog-framework,skipbit/treefrog-framework,skipbit/treefrog-framework,seem-sky/treefrog-framework,treefrogframework/treefrog-framework,treefrogframework/treefrog-framework,froglogic/treefrog-framework,hks2002/treefrog-framework,AmiArt/treefrog-framework,treefrogframework/treefrog-framework,froglogic/treefrog-framework,Akhilesh05/treefrog-framework,ThomasGueldner/treefrog-framework,hks2002/treefrog-framework,treefrogframework/treefrog-framework,hks2002/treefrog-framework,froglogic/treefrog-framework,skipbit/treefrog-framework,hks2002/treefrog-framework,AmiArt/treefrog-framework,AmiArt/treefrog-framework,ThomasGueldner/treefrog-framework,seem-sky/treefrog-framework,treefrogframework/treefrog-framework,skipbit/treefrog-framework,ThomasGueldner/treefrog-framework,gonboy/treefrog-framework,froglogic/treefrog-framework,ThomasGueldner/treefrog-framework,ThomasGueldner/treefrog-framework,Akhilesh05/treefrog-framework,AmiArt/treefrog-framework,gonboy/treefrog-framework,AmiArt/treefrog-framework,Akhilesh05/treefrog-framework,seem-sky/treefrog-framework,froglogic/treefrog-framework,hks2002/treefrog-framework,skipbit/treefrog-framework
|
d1bea935185b3309669c449b55c53d8d287fd3fb
|
arangod/Cluster/ApplicationCluster.cpp
|
arangod/Cluster/ApplicationCluster.cpp
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "ApplicationCluster.h"
#include "Basics/FileUtils.h"
#include "Basics/JsonHelper.h"
#include "Basics/VelocyPackHelper.h"
#include "Basics/files.h"
#include "Cluster/ClusterComm.h"
#include "Cluster/ClusterInfo.h"
#include "Cluster/HeartbeatThread.h"
#include "Cluster/ServerState.h"
#include "Dispatcher/ApplicationDispatcher.h"
#include "Endpoint/Endpoint.h"
#include "Logger/Logger.h"
#include "SimpleHttpClient/ConnectionManager.h"
#include "V8Server/ApplicationV8.h"
#include "VocBase/server.h"
using namespace arangodb;
using namespace arangodb::basics;
ApplicationCluster::ApplicationCluster(
TRI_server_t* server, arangodb::rest::ApplicationDispatcher* dispatcher,
ApplicationV8* applicationV8,
arangodb::AgencyCallbackRegistry* agencyCallbackRegistry)
: ApplicationFeature("Sharding"),
_server(server),
_dispatcher(dispatcher),
_applicationV8(applicationV8),
_agencyCallbackRegistry(agencyCallbackRegistry),
_heartbeat(nullptr),
_heartbeatInterval(0),
_agencyEndpoints(),
_agencyPrefix(),
_myId(),
_myAddress(),
_username("root"),
_password(),
_dataPath(),
_logPath(),
_arangodPath(),
_dbserverConfig(),
_coordinatorConfig(),
_enableCluster(false),
_disableHeartbeat(false) {
TRI_ASSERT(_dispatcher != nullptr);
}
ApplicationCluster::~ApplicationCluster() {
delete _heartbeat;
// delete connection manager instance
auto cm = httpclient::ConnectionManager::instance();
delete cm;
}
void ApplicationCluster::setupOptions(
std::map<std::string, basics::ProgramOptionsDescription>& options) {
options["Cluster options:help-cluster"]("cluster.agency-endpoint",
&_agencyEndpoints,
"agency endpoint to connect to")(
"cluster.agency-prefix", &_agencyPrefix, "agency prefix")(
"cluster.my-local-info", &_myLocalInfo, "this server's local info")(
"cluster.my-id", &_myId, "this server's id")(
"cluster.my-address", &_myAddress, "this server's endpoint")(
"cluster.my-role", &_myRole, "this server's role")(
"cluster.username", &_username,
"username used for cluster-internal communication")(
"cluster.password", &_password,
"password used for cluster-internal communication")(
"cluster.data-path", &_dataPath, "path to cluster database directory")(
"cluster.log-path", &_logPath, "path to log directory for the cluster")(
"cluster.arangod-path", &_arangodPath,
"path to the arangod for the cluster")(
"cluster.dbserver-config", &_dbserverConfig,
"path to the DBserver configuration")(
"cluster.coordinator-config", &_coordinatorConfig,
"path to the coordinator configuration");
}
bool ApplicationCluster::prepare() {
ClusterInfo::createInstance(_agencyCallbackRegistry);
// set authentication data
ServerState::instance()->setAuthentication(_username, _password);
// overwrite memory area
_username = _password = "someotherusername";
ServerState::instance()->setDataPath(_dataPath);
ServerState::instance()->setLogPath(_logPath);
ServerState::instance()->setArangodPath(_arangodPath);
ServerState::instance()->setDBserverConfig(_dbserverConfig);
ServerState::instance()->setCoordinatorConfig(_coordinatorConfig);
// initialize ConnectionManager library
httpclient::ConnectionManager::initialize();
// initialize ClusterComm library
// must call initialize while still single-threaded
ClusterComm::initialize();
if (_disabled) {
// if ApplicationFeature is disabled
_enableCluster = false;
ServerState::instance()->setRole(ServerState::ROLE_SINGLE);
return true;
}
// check the cluster state
_enableCluster = !_agencyEndpoints.empty();
if (_agencyPrefix.empty()) {
_agencyPrefix = "arango";
}
if (!enabled()) {
ServerState::instance()->setRole(ServerState::ROLE_SINGLE);
return true;
}
ServerState::instance()->setClusterEnabled();
// validate --cluster.agency-prefix
size_t found = _agencyPrefix.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/");
if (found != std::string::npos || _agencyPrefix.empty()) {
LOG(FATAL) << "invalid value specified for --cluster.agency-prefix";
FATAL_ERROR_EXIT();
}
// register the prefix with the communicator
AgencyComm::setPrefix(_agencyPrefix);
// validate --cluster.agency-endpoint
if (_agencyEndpoints.empty()) {
LOG(FATAL)
<< "must at least specify one endpoint in --cluster.agency-endpoint";
FATAL_ERROR_EXIT();
}
for (size_t i = 0; i < _agencyEndpoints.size(); ++i) {
std::string const unified = Endpoint::unifiedForm(_agencyEndpoints[i]);
if (unified.empty()) {
LOG(FATAL) << "invalid endpoint '" << _agencyEndpoints[i]
<< "' specified for --cluster.agency-endpoint";
FATAL_ERROR_EXIT();
}
AgencyComm::addEndpoint(unified);
}
// validate --cluster.my-id
if (_myId.empty()) {
if (_myLocalInfo.empty()) {
LOG(FATAL) << "Need to specify a local cluster identifier via "
"--cluster.my-local-info";
FATAL_ERROR_EXIT();
}
if (_myAddress.empty()) {
LOG(FATAL)
<< "must specify --cluster.my-address if --cluster.my-id is empty";
FATAL_ERROR_EXIT();
}
} else {
size_t found = _myId.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
if (found != std::string::npos) {
LOG(FATAL) << "invalid value specified for --cluster.my-id";
FATAL_ERROR_EXIT();
}
}
// Now either _myId is set properly or _myId is empty and _myLocalInfo and
// _myAddress are set.
if (!_myAddress.empty()) {
ServerState::instance()->setAddress(_myAddress);
}
// initialize ConnectionManager library
// httpclient::ConnectionManager::initialize();
// initialize ClusterComm library
// must call initialize while still single-threaded
// ClusterComm::initialize();
// disable error logging for a while
ClusterComm::instance()->enableConnectionErrorLogging(false);
// perform an initial connect to the agency
std::string const endpoints = AgencyComm::getEndpointsString();
if (!AgencyComm::initialize()) {
LOG(FATAL) << "Could not connect to agency endpoints (" << endpoints << ")";
FATAL_ERROR_EXIT();
}
ServerState::instance()->setLocalInfo(_myLocalInfo);
if (!_myId.empty()) {
ServerState::instance()->setId(_myId);
}
if (!_myRole.empty()) {
ServerState::RoleEnum role = ServerState::stringToRole(_myRole);
if (role == ServerState::ROLE_SINGLE ||
role == ServerState::ROLE_UNDEFINED) {
LOG(FATAL) << "Invalid role provided. Possible values: PRIMARY, "
"SECONDARY, COORDINATOR";
FATAL_ERROR_EXIT();
}
if (!ServerState::instance()->registerWithRole(role)) {
LOG(FATAL) << "Couldn't register at agency.";
FATAL_ERROR_EXIT();
}
}
ServerState::RoleEnum role = ServerState::instance()->getRole();
if (role == ServerState::ROLE_UNDEFINED) {
// no role found
LOG(FATAL) << "unable to determine unambiguous role for server '" << _myId
<< "'. No role configured in agency (" << endpoints << ")";
FATAL_ERROR_EXIT();
}
if (_myId.empty()) {
_myId = ServerState::instance()->getId(); // has been set by getRole!
}
// check if my-address is set
if (_myAddress.empty()) {
// no address given, now ask the agency for our address
_myAddress = ServerState::instance()->getAddress();
}
// if nonempty, it has already been set above
// If we are a coordinator, we wait until at least one DBServer is there,
// otherwise we can do very little, in particular, we cannot create
// any collection:
if (role == ServerState::ROLE_COORDINATOR) {
ClusterInfo* ci = ClusterInfo::instance();
do {
LOG(INFO) << "Waiting for a DBserver to show up...";
ci->loadCurrentDBServers();
std::vector<ServerID> DBServers = ci->getCurrentDBServers();
if (!DBServers.empty()) {
LOG(INFO) << "Found a DBserver.";
break;
}
sleep(1);
} while (true);
}
return true;
}
bool ApplicationCluster::start() {
if (!enabled()) {
return true;
}
std::string const endpoints = AgencyComm::getEndpointsString();
ServerState::RoleEnum role = ServerState::instance()->getRole();
if (_myAddress.empty()) {
LOG(FATAL) << "unable to determine internal address for server '" << _myId
<< "'. Please specify --cluster.my-address or configure the "
"address for this server in the agency.";
FATAL_ERROR_EXIT();
}
// now we can validate --cluster.my-address
std::string const unified = Endpoint::unifiedForm(_myAddress);
if (unified.empty()) {
LOG(FATAL) << "invalid endpoint '" << _myAddress
<< "' specified for --cluster.my-address";
FATAL_ERROR_EXIT();
}
ServerState::instance()->setState(ServerState::STATE_STARTUP);
// the agency about our state
AgencyComm comm;
comm.sendServerState(0.0);
std::string const version = comm.getVersion();
ServerState::instance()->setInitialized();
LOG(INFO) << "Cluster feature is turned on. Agency version: " << version
<< ", Agency endpoints: " << endpoints << ", server id: '" << _myId
<< "', internal address: " << _myAddress
<< ", role: " << ServerState::roleToString(role);
if (!_disableHeartbeat) {
AgencyCommResult result = comm.getValues("Sync/HeartbeatIntervalMs", false);
if (result.successful()) {
result.parse("", false);
std::map<std::string, AgencyCommResultEntry>::const_iterator it =
result._values.begin();
if (it != result._values.end()) {
VPackSlice slice = (*it).second._vpack->slice();
_heartbeatInterval =
arangodb::basics::VelocyPackHelper::stringUInt64(slice);
LOG(INFO) << "using heartbeat interval value '" << _heartbeatInterval
<< " ms' from agency";
}
}
// no value set in agency. use default
if (_heartbeatInterval == 0) {
_heartbeatInterval = 5000; // 1/s
LOG(WARN) << "unable to read heartbeat interval from agency. Using "
"default value '"
<< _heartbeatInterval << " ms'";
}
// start heartbeat thread
_heartbeat = new HeartbeatThread(_server, _dispatcher, _applicationV8,
_agencyCallbackRegistry,
_heartbeatInterval * 1000, 5);
if (_heartbeat == nullptr) {
LOG(FATAL) << "unable to start cluster heartbeat thread";
FATAL_ERROR_EXIT();
}
if (!_heartbeat->init() || !_heartbeat->start()) {
LOG(FATAL) << "heartbeat could not connect to agency endpoints ("
<< endpoints << ")";
FATAL_ERROR_EXIT();
}
while (!_heartbeat->isReady()) {
// wait until heartbeat is ready
usleep(10000);
}
}
return true;
}
bool ApplicationCluster::open() {
if (!enabled()) {
return true;
}
AgencyComm comm;
AgencyCommResult result;
do {
AgencyCommLocker locker("Current", "WRITE");
bool success = locker.successful();
if (success) {
VPackBuilder builder;
try {
VPackObjectBuilder b(&builder);
builder.add("endpoint", VPackValue(_myAddress));
} catch (...) {
locker.unlock();
LOG(FATAL) << "out of memory";
FATAL_ERROR_EXIT();
}
result = comm.setValue("Current/ServersRegistered/" + _myId,
builder.slice(), 0.0);
}
if (!result.successful()) {
locker.unlock();
LOG(FATAL) << "unable to register server in agency: http code: "
<< result.httpCode() << ", body: " << result.body();
FATAL_ERROR_EXIT();
}
if (success) {
break;
}
sleep(1);
} while (true);
ServerState::RoleEnum role = ServerState::instance()->getRole();
if (role == ServerState::ROLE_COORDINATOR) {
ServerState::instance()->setState(ServerState::STATE_SERVING);
} else if (role == ServerState::ROLE_PRIMARY) {
ServerState::instance()->setState(ServerState::STATE_SERVINGASYNC);
} else if (role == ServerState::ROLE_SECONDARY) {
ServerState::instance()->setState(ServerState::STATE_SYNCING);
}
return true;
}
void ApplicationCluster::close() {
if (!enabled()) {
return;
}
if (_heartbeat != nullptr) {
_heartbeat->beginShutdown();
}
// change into shutdown state
ServerState::instance()->setState(ServerState::STATE_SHUTDOWN);
AgencyComm comm;
comm.sendServerState(0.0);
}
void ApplicationCluster::stop() {
ClusterComm::cleanup();
if (!enabled()) {
return;
}
// change into shutdown state
ServerState::instance()->setState(ServerState::STATE_SHUTDOWN);
AgencyComm comm;
comm.sendServerState(0.0);
if (_heartbeat != nullptr) {
_heartbeat->beginShutdown();
}
{
// Try only once to unregister because maybe the agencycomm
// is shutting down as well...
AgencyCommLocker locker("Current", "WRITE", 120.0, 0.001);
if (locker.successful()) {
// unregister ourselves
ServerState::RoleEnum role = ServerState::instance()->getRole();
if (role == ServerState::ROLE_PRIMARY) {
comm.removeValues("Current/DBServers/" + _myId, false);
} else if (role == ServerState::ROLE_COORDINATOR) {
comm.removeValues("Current/Coordinators/" + _myId, false);
}
// unregister ourselves
comm.removeValues("Current/ServersRegistered/" + _myId, false);
}
}
while (_heartbeat->isRunning()) {
usleep(50000);
}
// ClusterComm::cleanup();
AgencyComm::cleanup();
}
|
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#include "ApplicationCluster.h"
#include "Basics/FileUtils.h"
#include "Basics/JsonHelper.h"
#include "Basics/VelocyPackHelper.h"
#include "Basics/files.h"
#include "Cluster/ClusterComm.h"
#include "Cluster/ClusterInfo.h"
#include "Cluster/HeartbeatThread.h"
#include "Cluster/ServerState.h"
#include "Dispatcher/ApplicationDispatcher.h"
#include "Endpoint/Endpoint.h"
#include "Logger/Logger.h"
#include "SimpleHttpClient/ConnectionManager.h"
#include "V8Server/ApplicationV8.h"
#include "VocBase/server.h"
using namespace arangodb;
using namespace arangodb::basics;
ApplicationCluster::ApplicationCluster(
TRI_server_t* server, arangodb::rest::ApplicationDispatcher* dispatcher,
ApplicationV8* applicationV8,
arangodb::AgencyCallbackRegistry* agencyCallbackRegistry)
: ApplicationFeature("Sharding"),
_server(server),
_dispatcher(dispatcher),
_applicationV8(applicationV8),
_agencyCallbackRegistry(agencyCallbackRegistry),
_heartbeat(nullptr),
_heartbeatInterval(0),
_agencyEndpoints(),
_agencyPrefix(),
_myId(),
_myAddress(),
_username("root"),
_password(),
_dataPath(),
_logPath(),
_arangodPath(),
_dbserverConfig(),
_coordinatorConfig(),
_enableCluster(false),
_disableHeartbeat(false) {
TRI_ASSERT(_dispatcher != nullptr);
}
ApplicationCluster::~ApplicationCluster() {
delete _heartbeat;
// delete connection manager instance
auto cm = httpclient::ConnectionManager::instance();
delete cm;
}
void ApplicationCluster::setupOptions(
std::map<std::string, basics::ProgramOptionsDescription>& options) {
options["Cluster options:help-cluster"]("cluster.agency-endpoint",
&_agencyEndpoints,
"agency endpoint to connect to")(
"cluster.agency-prefix", &_agencyPrefix, "agency prefix")(
"cluster.my-local-info", &_myLocalInfo, "this server's local info")(
"cluster.my-id", &_myId, "this server's id")(
"cluster.my-address", &_myAddress, "this server's endpoint")(
"cluster.my-role", &_myRole, "this server's role")(
"cluster.username", &_username,
"username used for cluster-internal communication")(
"cluster.password", &_password,
"password used for cluster-internal communication")(
"cluster.data-path", &_dataPath, "path to cluster database directory")(
"cluster.log-path", &_logPath, "path to log directory for the cluster")(
"cluster.arangod-path", &_arangodPath,
"path to the arangod for the cluster")(
"cluster.dbserver-config", &_dbserverConfig,
"path to the DBserver configuration")(
"cluster.coordinator-config", &_coordinatorConfig,
"path to the coordinator configuration");
}
bool ApplicationCluster::prepare() {
ClusterInfo::createInstance(_agencyCallbackRegistry);
// set authentication data
ServerState::instance()->setAuthentication(_username, _password);
// overwrite memory area
_username = _password = "someotherusername";
ServerState::instance()->setDataPath(_dataPath);
ServerState::instance()->setLogPath(_logPath);
ServerState::instance()->setArangodPath(_arangodPath);
ServerState::instance()->setDBserverConfig(_dbserverConfig);
ServerState::instance()->setCoordinatorConfig(_coordinatorConfig);
// initialize ConnectionManager library
httpclient::ConnectionManager::initialize();
// initialize ClusterComm library
// must call initialize while still single-threaded
ClusterComm::initialize();
if (_disabled) {
// if ApplicationFeature is disabled
_enableCluster = false;
ServerState::instance()->setRole(ServerState::ROLE_SINGLE);
return true;
}
// check the cluster state
_enableCluster = !_agencyEndpoints.empty();
if (_agencyPrefix.empty()) {
_agencyPrefix = "arango";
}
if (!enabled()) {
ServerState::instance()->setRole(ServerState::ROLE_SINGLE);
return true;
}
ServerState::instance()->setClusterEnabled();
// validate --cluster.agency-prefix
size_t found = _agencyPrefix.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/");
if (found != std::string::npos || _agencyPrefix.empty()) {
LOG(FATAL) << "invalid value specified for --cluster.agency-prefix";
FATAL_ERROR_EXIT();
}
// register the prefix with the communicator
AgencyComm::setPrefix(_agencyPrefix);
// validate --cluster.agency-endpoint
if (_agencyEndpoints.empty()) {
LOG(FATAL)
<< "must at least specify one endpoint in --cluster.agency-endpoint";
FATAL_ERROR_EXIT();
}
for (size_t i = 0; i < _agencyEndpoints.size(); ++i) {
std::string const unified = Endpoint::unifiedForm(_agencyEndpoints[i]);
if (unified.empty()) {
LOG(FATAL) << "invalid endpoint '" << _agencyEndpoints[i]
<< "' specified for --cluster.agency-endpoint";
FATAL_ERROR_EXIT();
}
AgencyComm::addEndpoint(unified);
}
// validate --cluster.my-id
if (_myId.empty()) {
if (_myLocalInfo.empty()) {
LOG(FATAL) << "Need to specify a local cluster identifier via "
"--cluster.my-local-info";
FATAL_ERROR_EXIT();
}
if (_myAddress.empty()) {
LOG(FATAL)
<< "must specify --cluster.my-address if --cluster.my-id is empty";
FATAL_ERROR_EXIT();
}
} else {
size_t found = _myId.find_first_not_of(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789");
if (found != std::string::npos) {
LOG(FATAL) << "invalid value specified for --cluster.my-id";
FATAL_ERROR_EXIT();
}
}
// Now either _myId is set properly or _myId is empty and _myLocalInfo and
// _myAddress are set.
if (!_myAddress.empty()) {
ServerState::instance()->setAddress(_myAddress);
}
// initialize ConnectionManager library
// httpclient::ConnectionManager::initialize();
// initialize ClusterComm library
// must call initialize while still single-threaded
// ClusterComm::initialize();
// disable error logging for a while
ClusterComm::instance()->enableConnectionErrorLogging(false);
// perform an initial connect to the agency
std::string const endpoints = AgencyComm::getEndpointsString();
if (!AgencyComm::initialize()) {
LOG(FATAL) << "Could not connect to agency endpoints (" << endpoints << ")";
FATAL_ERROR_EXIT();
}
ServerState::instance()->setLocalInfo(_myLocalInfo);
if (!_myId.empty()) {
ServerState::instance()->setId(_myId);
}
if (!_myRole.empty()) {
ServerState::RoleEnum role = ServerState::stringToRole(_myRole);
if (role == ServerState::ROLE_SINGLE ||
role == ServerState::ROLE_UNDEFINED) {
LOG(FATAL) << "Invalid role provided. Possible values: PRIMARY, "
"SECONDARY, COORDINATOR";
FATAL_ERROR_EXIT();
}
if (!ServerState::instance()->registerWithRole(role)) {
LOG(FATAL) << "Couldn't register at agency.";
FATAL_ERROR_EXIT();
}
}
ServerState::RoleEnum role = ServerState::instance()->getRole();
if (role == ServerState::ROLE_UNDEFINED) {
// no role found
LOG(FATAL) << "unable to determine unambiguous role for server '" << _myId
<< "'. No role configured in agency (" << endpoints << ")";
FATAL_ERROR_EXIT();
}
if (_myId.empty()) {
_myId = ServerState::instance()->getId(); // has been set by getRole!
}
// check if my-address is set
if (_myAddress.empty()) {
// no address given, now ask the agency for our address
_myAddress = ServerState::instance()->getAddress();
}
// if nonempty, it has already been set above
// If we are a coordinator, we wait until at least one DBServer is there,
// otherwise we can do very little, in particular, we cannot create
// any collection:
if (role == ServerState::ROLE_COORDINATOR) {
ClusterInfo* ci = ClusterInfo::instance();
do {
LOG(INFO) << "Waiting for a DBserver to show up...";
ci->loadCurrentDBServers();
std::vector<ServerID> DBServers = ci->getCurrentDBServers();
if (!DBServers.empty()) {
LOG(INFO) << "Found a DBserver.";
break;
}
sleep(1);
} while (true);
}
return true;
}
bool ApplicationCluster::start() {
if (!enabled()) {
return true;
}
std::string const endpoints = AgencyComm::getEndpointsString();
ServerState::RoleEnum role = ServerState::instance()->getRole();
if (_myAddress.empty()) {
LOG(FATAL) << "unable to determine internal address for server '" << _myId
<< "'. Please specify --cluster.my-address or configure the "
"address for this server in the agency.";
FATAL_ERROR_EXIT();
}
// now we can validate --cluster.my-address
std::string const unified = Endpoint::unifiedForm(_myAddress);
if (unified.empty()) {
LOG(FATAL) << "invalid endpoint '" << _myAddress
<< "' specified for --cluster.my-address";
FATAL_ERROR_EXIT();
}
ServerState::instance()->setState(ServerState::STATE_STARTUP);
// the agency about our state
AgencyComm comm;
comm.sendServerState(0.0);
std::string const version = comm.getVersion();
ServerState::instance()->setInitialized();
LOG(INFO) << "Cluster feature is turned on. Agency version: " << version
<< ", Agency endpoints: " << endpoints << ", server id: '" << _myId
<< "', internal address: " << _myAddress
<< ", role: " << ServerState::roleToString(role);
if (!_disableHeartbeat) {
AgencyCommResult result = comm.getValues("Sync/HeartbeatIntervalMs", false);
if (result.successful()) {
result.parse("", false);
std::map<std::string, AgencyCommResultEntry>::const_iterator it =
result._values.begin();
if (it != result._values.end()) {
VPackSlice slice = (*it).second._vpack->slice();
_heartbeatInterval =
arangodb::basics::VelocyPackHelper::stringUInt64(slice);
LOG(INFO) << "using heartbeat interval value '" << _heartbeatInterval
<< " ms' from agency";
}
}
// no value set in agency. use default
if (_heartbeatInterval == 0) {
_heartbeatInterval = 5000; // 1/s
LOG(WARN) << "unable to read heartbeat interval from agency. Using "
"default value '"
<< _heartbeatInterval << " ms'";
}
// start heartbeat thread
_heartbeat = new HeartbeatThread(_server, _dispatcher, _applicationV8,
_agencyCallbackRegistry,
_heartbeatInterval * 1000, 5);
if (_heartbeat == nullptr) {
LOG(FATAL) << "unable to start cluster heartbeat thread";
FATAL_ERROR_EXIT();
}
if (!_heartbeat->init() || !_heartbeat->start()) {
LOG(FATAL) << "heartbeat could not connect to agency endpoints ("
<< endpoints << ")";
FATAL_ERROR_EXIT();
}
while (!_heartbeat->isReady()) {
// wait until heartbeat is ready
usleep(10000);
}
}
return true;
}
bool ApplicationCluster::open() {
if (!enabled()) {
return true;
}
AgencyComm comm;
AgencyCommResult result;
do {
AgencyCommLocker locker("Current", "WRITE");
bool success = locker.successful();
if (success) {
VPackBuilder builder;
try {
VPackObjectBuilder b(&builder);
builder.add("endpoint", VPackValue(_myAddress));
} catch (...) {
locker.unlock();
LOG(FATAL) << "out of memory";
FATAL_ERROR_EXIT();
}
result = comm.setValue("Current/ServersRegistered/" + _myId,
builder.slice(), 0.0);
}
if (!result.successful()) {
locker.unlock();
LOG(FATAL) << "unable to register server in agency: http code: "
<< result.httpCode() << ", body: " << result.body();
FATAL_ERROR_EXIT();
}
if (success) {
break;
}
sleep(1);
} while (true);
ServerState::RoleEnum role = ServerState::instance()->getRole();
if (role == ServerState::ROLE_COORDINATOR) {
ServerState::instance()->setState(ServerState::STATE_SERVING);
} else if (role == ServerState::ROLE_PRIMARY) {
ServerState::instance()->setState(ServerState::STATE_SERVINGASYNC);
} else if (role == ServerState::ROLE_SECONDARY) {
ServerState::instance()->setState(ServerState::STATE_SYNCING);
}
return true;
}
void ApplicationCluster::close() {
if (!enabled()) {
return;
}
if (_heartbeat != nullptr) {
_heartbeat->beginShutdown();
}
// change into shutdown state
ServerState::instance()->setState(ServerState::STATE_SHUTDOWN);
AgencyComm comm;
comm.sendServerState(0.0);
}
void ApplicationCluster::stop() {
ClusterComm::cleanup();
if (!enabled()) {
return;
}
// change into shutdown state
ServerState::instance()->setState(ServerState::STATE_SHUTDOWN);
AgencyComm comm;
comm.sendServerState(0.0);
if (_heartbeat != nullptr) {
_heartbeat->beginShutdown();
}
{
// Try only once to unregister because maybe the agencycomm
// is shutting down as well...
AgencyCommLocker locker("Current", "WRITE", 120.0, 1.000);
if (locker.successful()) {
// unregister ourselves
ServerState::RoleEnum role = ServerState::instance()->getRole();
if (role == ServerState::ROLE_PRIMARY) {
comm.removeValues("Current/DBServers/" + _myId, false);
} else if (role == ServerState::ROLE_COORDINATOR) {
comm.removeValues("Current/Coordinators/" + _myId, false);
}
// unregister ourselves
comm.removeValues("Current/ServersRegistered/" + _myId, false);
}
}
while (_heartbeat->isRunning()) {
usleep(50000);
}
// ClusterComm::cleanup();
AgencyComm::cleanup();
}
|
Fix too short timeout in server shutdown /Current/Lock in agency.
|
Fix too short timeout in server shutdown /Current/Lock in agency.
|
C++
|
apache-2.0
|
arangodb/arangodb,arangodb/arangodb,m0ppers/arangodb,wiltonlazary/arangodb,graetzer/arangodb,hkernbach/arangodb,graetzer/arangodb,baslr/ArangoDB,fceller/arangodb,graetzer/arangodb,m0ppers/arangodb,hkernbach/arangodb,joerg84/arangodb,baslr/ArangoDB,Simran-B/arangodb,wiltonlazary/arangodb,wiltonlazary/arangodb,joerg84/arangodb,joerg84/arangodb,graetzer/arangodb,baslr/ArangoDB,Simran-B/arangodb,baslr/ArangoDB,fceller/arangodb,wiltonlazary/arangodb,baslr/ArangoDB,m0ppers/arangodb,graetzer/arangodb,hkernbach/arangodb,graetzer/arangodb,joerg84/arangodb,graetzer/arangodb,joerg84/arangodb,m0ppers/arangodb,m0ppers/arangodb,hkernbach/arangodb,joerg84/arangodb,baslr/ArangoDB,Simran-B/arangodb,m0ppers/arangodb,graetzer/arangodb,m0ppers/arangodb,arangodb/arangodb,arangodb/arangodb,m0ppers/arangodb,fceller/arangodb,joerg84/arangodb,Simran-B/arangodb,Simran-B/arangodb,wiltonlazary/arangodb,joerg84/arangodb,baslr/ArangoDB,joerg84/arangodb,m0ppers/arangodb,joerg84/arangodb,baslr/ArangoDB,fceller/arangodb,arangodb/arangodb,baslr/ArangoDB,arangodb/arangodb,hkernbach/arangodb,joerg84/arangodb,Simran-B/arangodb,m0ppers/arangodb,baslr/ArangoDB,hkernbach/arangodb,hkernbach/arangodb,Simran-B/arangodb,hkernbach/arangodb,hkernbach/arangodb,joerg84/arangodb,Simran-B/arangodb,arangodb/arangodb,baslr/ArangoDB,hkernbach/arangodb,Simran-B/arangodb,graetzer/arangodb,graetzer/arangodb,graetzer/arangodb,fceller/arangodb,m0ppers/arangodb,Simran-B/arangodb,m0ppers/arangodb,fceller/arangodb,wiltonlazary/arangodb,fceller/arangodb,joerg84/arangodb,arangodb/arangodb,m0ppers/arangodb,joerg84/arangodb,hkernbach/arangodb,fceller/arangodb,graetzer/arangodb,wiltonlazary/arangodb,baslr/ArangoDB,graetzer/arangodb,hkernbach/arangodb,hkernbach/arangodb,hkernbach/arangodb,baslr/ArangoDB,fceller/arangodb,graetzer/arangodb,wiltonlazary/arangodb,baslr/ArangoDB,fceller/arangodb
|
e66cb93e75fa83b0a7161a782275baaa34077609
|
AndroidGatewayPlugin/AndroidServiceHandler.cpp
|
AndroidGatewayPlugin/AndroidServiceHandler.cpp
|
#include "AndroidServiceHandler.h"
#include "protocol/AmmoMessages.pb.h"
#include "AndroidMessageProcessor.h"
#include <iostream>
#include "ace/OS_NS_errno.h"
#include "log.h"
using namespace std;
extern std::string gatewayAddress;
extern int gatewayPort;
AndroidServiceHandler::AndroidServiceHandler() :
messageProcessor(NULL),
sendQueueMutex(),
receiveQueueMutex()
{
}
int AndroidServiceHandler::open(void *ptr) {
if(super::open(ptr) == -1) {
return -1;
}
state = READING_HEADER;
collectedData = NULL;
position = 0;
dataToSend = NULL;
position = 0;
messageHeader.magicNumber = 0;
messageHeader.size = 0;
messageHeader.checksum = 0;
messageHeader.headerChecksum = 0;
sentMessageCount = 0;
receivedMessageCount = 0;
connectionClosing = false;
messageProcessor = new AndroidMessageProcessor(this);
messageProcessor->activate();
this->peer().enable(ACE_NONBLOCK);
return 0;
}
int AndroidServiceHandler::handle_close(ACE_HANDLE fd, ACE_Reactor_Mask m) {
connectionClosing = true;
LOG_TRACE(this << " Closing Message Processor");
messageProcessor->close(0);
LOG_TRACE(this << " Waiting for message processor thread to finish...");
this->reactor()->lock().release(); //release the lock, or we'll hang if other threads try to do stuff with the reactor while we're waiting
messageProcessor->wait();
this->reactor()->lock().acquire(); //and put it back like it was
LOG_TRACE(this << " Message processor finished.");
super::handle_close(fd, m);
return 0;
}
int AndroidServiceHandler::handle_input(ACE_HANDLE fd) {
LOG_TRACE(this << " In handle_input");
int count = 0;
if(state == READING_HEADER) {
count = this->peer().recv_n(&messageHeader, sizeof(messageHeader));
//verify the message header (check its magic number and checksum)
if(count > 0) {
if(messageHeader.magicNumber == HEADER_MAGIC_NUMBER) {
unsigned int calculatedChecksum = ACE::crc32(&messageHeader, sizeof(messageHeader) - sizeof(messageHeader.headerChecksum));
if(calculatedChecksum != messageHeader.headerChecksum) {
LOG_ERROR("Invalid header checksum");
return -1;
}
} else {
LOG_ERROR("Invalid magic number: " << hex << messageHeader.magicNumber << dec);
return -1;
}
} else if(count == 0) {
LOG_INFO(this << " Connection closed.");
return -1;
} else if(count == -1) {
LOG_ERROR(this << " Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
} else if(state == READING_DATA) {
count = this->peer().recv(collectedData + position, messageHeader.size - position);
//LOG_TRACE("DATA Read " << count << " bytes");
} else {
LOG_ERROR(this << " Invalid state!");
return -1;
}
if(count > 0) {
if(state == READING_HEADER) {
try {
collectedData = new char[messageHeader.size];
} catch (std::bad_alloc &e) {
LOG_ERROR(this << " Couldn't allocate memory for message of size " << messageHeader.size);
return -1;
}
position = 0;
//LOG_TRACE("Got data size (" << dataSize << ")");
state = READING_DATA;
} else if(state == READING_DATA) {
LOG_TRACE(this << " Got some data...");
position += count;
if(position == messageHeader.size) {
//LOG_TRACE("Got all the data... processing");
processData(collectedData, messageHeader.size, messageHeader.checksum, messageHeader.priority);
//LOG_TRACE("Processsing complete. Deleting buffer.");
delete[] collectedData;
collectedData = NULL;
messageHeader.magicNumber = 0;
messageHeader.size = 0;
messageHeader.checksum = 0;
messageHeader.headerChecksum = 0;
position = 0;
state = READING_HEADER;
}
}
} else if(count == 0) {
LOG_INFO(this << " Connection closed.");
return -1;
} else if(count == -1 && ACE_OS::last_error () != EWOULDBLOCK) {
LOG_ERROR(this << " Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
LOG_TRACE(this << " Leaving handle_input()");
return 0;
}
int AndroidServiceHandler::handle_output(ACE_HANDLE fd) {
int count = 0;
do {
if(dataToSend == NULL) {
ammo::protocol::MessageWrapper *msg = getNextMessageToSend();
if(msg != NULL) {
LOG_TRACE("Getting a new message to send");
if(!msg->IsInitialized()) {
LOG_WARN(this << " Protocol Buffers message is missing a required element.");
}
unsigned int messageSize = msg->ByteSize();
sendBufferSize = messageSize + sizeof(MessageHeader);
dataToSend = new char[sendBufferSize];
MessageHeader *headerToSend = (MessageHeader *) dataToSend;
headerToSend->magicNumber = HEADER_MAGIC_NUMBER;
headerToSend->size = messageSize;
char *protobufSerializedMessage = dataToSend + sizeof(MessageHeader);
msg->SerializeToArray(protobufSerializedMessage, messageSize);
headerToSend->checksum = ACE::crc32(protobufSerializedMessage, messageSize);
headerToSend->headerChecksum = ACE::crc32(headerToSend, sizeof(messageHeader) - sizeof(messageHeader.headerChecksum));
sendPosition = 0;
delete msg;
} else {
//don't wake up the reactor when there's no data that needs to be sent
//(wake-up will be rescheduled when data becomes available in sendMessage
//below)
this->reactor()->cancel_wakeup(this, ACE_Event_Handler::WRITE_MASK);
return 0;
}
}
//timeout after ten seconds when sending data (in case connection drops
//in the middle, we don't want to wait until the socket connection dies)
//ACE_Time_Value timeout(10);
count = this->peer().send(dataToSend + sendPosition, sendBufferSize - sendPosition);
if(count >= 0) {
sendPosition += count;
}
LOG_TRACE("Sent " << count << " bytes (current postition " << sendPosition << "/" << sendBufferSize);
if(sendPosition >= (sendBufferSize)) {
delete[] dataToSend;
dataToSend = NULL;
sendBufferSize = 0;
sendPosition = 0;
}
} while(count != -1);
if(count == -1 && ACE_OS::last_error () == EWOULDBLOCK) {
LOG_TRACE("Received EWOULDBLOCK");
this->reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);
} else {
LOG_ERROR(this << " Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
return 0;
}
int AndroidServiceHandler::processData(char *data, unsigned int messageSize, unsigned int messageChecksum, char priority) {
//Validate checksum
unsigned int calculatedChecksum = ACE::crc32(data, messageSize);
if(calculatedChecksum != messageChecksum) {
LOG_ERROR(this << " Mismatched checksum " << std::hex << calculatedChecksum << " : " << messageChecksum);
LOG_ERROR(this << " size " << std::dec << messageSize ); // << " payload: " < );
return -1;
}
//checksum is valid; parse the data
ammo::protocol::MessageWrapper *msg = new ammo::protocol::MessageWrapper();
bool result = msg->ParseFromArray(data, messageSize);
if(result == false) {
LOG_ERROR(this << " MessageWrapper could not be deserialized.");
LOG_ERROR(this << " Client must have sent something that isn't a protocol buffer (or the wrong type).");
delete msg;
return -1;
}
addReceivedMessage(msg, priority);
messageProcessor->signalNewMessageAvailable();
return 0;
}
void AndroidServiceHandler::sendMessage(ammo::protocol::MessageWrapper *msg, char priority) {
QueuedMessage queuedMsg;
queuedMsg.priority = priority;
queuedMsg.message = msg;
if(priority != msg->message_priority()) {
LOG_WARN("Priority mismatch when adding message to send queue: Header = " << priority << ", Message = " << msg->message_priority());
}
sendQueueMutex.acquire();
queuedMsg.messageCount = sentMessageCount;
sentMessageCount++;
if(!connectionClosing) {
sendQueue.push(queuedMsg);
LOG_TRACE(this << " Queued a message to send. " << sendQueue.size() << " messages in queue.");
}
sendQueueMutex.release();
if(!connectionClosing) {
this->reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);
}
}
ammo::protocol::MessageWrapper *AndroidServiceHandler::getNextMessageToSend() {
ammo::protocol::MessageWrapper *msg = NULL;
sendQueueMutex.acquire();
if(!sendQueue.empty()) {
msg = sendQueue.top().message;
sendQueue.pop();
}
int size = sendQueue.size();
sendQueueMutex.release();
LOG_TRACE(this << " Dequeued a message to send. " << size << " messages remain in queue.");
return msg;
}
ammo::protocol::MessageWrapper *AndroidServiceHandler::getNextReceivedMessage() {
ammo::protocol::MessageWrapper *msg = NULL;
receiveQueueMutex.acquire();
if(!receiveQueue.empty()) {
msg = receiveQueue.top().message;
receiveQueue.pop();
}
receiveQueueMutex.release();
return msg;
}
void AndroidServiceHandler::addReceivedMessage(ammo::protocol::MessageWrapper *msg, char priority) {
QueuedMessage queuedMsg;
queuedMsg.priority = priority;
queuedMsg.message = msg;
if(priority != msg->message_priority()) {
LOG_WARN("Priority mismatch on received message: Header = " << priority << ", Message = " << msg->message_priority());
}
receiveQueueMutex.acquire();
queuedMsg.messageCount = receivedMessageCount;
receivedMessageCount++;
receiveQueue.push(queuedMsg);
receiveQueueMutex.release();
}
AndroidServiceHandler::~AndroidServiceHandler() {
LOG_TRACE(this << " In ~AndroidServiceHandler");
delete messageProcessor;
}
|
#include "AndroidServiceHandler.h"
#include "protocol/AmmoMessages.pb.h"
#include "AndroidMessageProcessor.h"
#include <iostream>
#include "ace/OS_NS_errno.h"
#include "log.h"
using namespace std;
extern std::string gatewayAddress;
extern int gatewayPort;
AndroidServiceHandler::AndroidServiceHandler() :
messageProcessor(NULL),
sendQueueMutex(),
receiveQueueMutex()
{
}
int AndroidServiceHandler::open(void *ptr) {
if(super::open(ptr) == -1) {
return -1;
}
state = READING_HEADER;
collectedData = NULL;
position = 0;
dataToSend = NULL;
position = 0;
messageHeader.magicNumber = 0;
messageHeader.size = 0;
messageHeader.checksum = 0;
messageHeader.headerChecksum = 0;
sentMessageCount = 0;
receivedMessageCount = 0;
connectionClosing = false;
messageProcessor = new AndroidMessageProcessor(this);
messageProcessor->activate();
this->peer().enable(ACE_NONBLOCK);
return 0;
}
int AndroidServiceHandler::handle_close(ACE_HANDLE fd, ACE_Reactor_Mask m) {
connectionClosing = true;
LOG_TRACE(this << " Closing Message Processor");
messageProcessor->close(0);
LOG_TRACE(this << " Waiting for message processor thread to finish...");
this->reactor()->lock().release(); //release the lock, or we'll hang if other threads try to do stuff with the reactor while we're waiting
messageProcessor->wait();
this->reactor()->lock().acquire(); //and put it back like it was
LOG_TRACE(this << " Message processor finished.");
super::handle_close(fd, m);
return 0;
}
int AndroidServiceHandler::handle_input(ACE_HANDLE fd) {
LOG_TRACE(this << " In handle_input");
int count = 0;
if(state == READING_HEADER) {
count = this->peer().recv_n(&messageHeader, sizeof(messageHeader));
//verify the message header (check its magic number and checksum)
if(count > 0) {
if(messageHeader.magicNumber == HEADER_MAGIC_NUMBER) {
unsigned int calculatedChecksum = ACE::crc32(&messageHeader, sizeof(messageHeader) - sizeof(messageHeader.headerChecksum));
if(calculatedChecksum != messageHeader.headerChecksum) {
LOG_ERROR("Invalid header checksum");
return -1;
}
} else {
LOG_ERROR("Invalid magic number: " << hex << messageHeader.magicNumber << dec);
return -1;
}
} else if(count == 0) {
LOG_INFO(this << " Connection closed.");
return -1;
} else if(count == -1) {
LOG_ERROR(this << " Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
} else if(state == READING_DATA) {
count = this->peer().recv(collectedData + position, messageHeader.size - position);
//LOG_TRACE("DATA Read " << count << " bytes");
} else {
LOG_ERROR(this << " Invalid state!");
return -1;
}
if(count > 0) {
if(state == READING_HEADER) {
try {
collectedData = new char[messageHeader.size];
} catch (std::bad_alloc &e) {
LOG_ERROR(this << " Couldn't allocate memory for message of size " << messageHeader.size);
return -1;
}
position = 0;
//LOG_TRACE("Got data size (" << dataSize << ")");
state = READING_DATA;
} else if(state == READING_DATA) {
LOG_TRACE(this << " Got some data...");
position += count;
if(position == messageHeader.size) {
//LOG_TRACE("Got all the data... processing");
processData(collectedData, messageHeader.size, messageHeader.checksum, messageHeader.priority);
//LOG_TRACE("Processsing complete. Deleting buffer.");
delete[] collectedData;
collectedData = NULL;
messageHeader.magicNumber = 0;
messageHeader.size = 0;
messageHeader.checksum = 0;
messageHeader.headerChecksum = 0;
position = 0;
state = READING_HEADER;
}
}
} else if(count == 0) {
LOG_INFO(this << " Connection closed.");
return -1;
} else if(count == -1 && ACE_OS::last_error () != EWOULDBLOCK) {
LOG_ERROR(this << " Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
LOG_TRACE(this << " Leaving handle_input()");
return 0;
}
int AndroidServiceHandler::handle_output(ACE_HANDLE fd) {
int count = 0;
do {
if(dataToSend == NULL) {
ammo::protocol::MessageWrapper *msg = getNextMessageToSend();
if(msg != NULL) {
LOG_TRACE("Getting a new message to send");
if(!msg->IsInitialized()) {
LOG_WARN(this << " Protocol Buffers message is missing a required element.");
}
unsigned int messageSize = msg->ByteSize();
sendBufferSize = messageSize + sizeof(MessageHeader);
dataToSend = new char[sendBufferSize];
MessageHeader *headerToSend = (MessageHeader *) dataToSend;
headerToSend->magicNumber = HEADER_MAGIC_NUMBER;
headerToSend->size = messageSize;
char *protobufSerializedMessage = dataToSend + sizeof(MessageHeader);
msg->SerializeToArray(protobufSerializedMessage, messageSize);
headerToSend->checksum = ACE::crc32(protobufSerializedMessage, messageSize);
headerToSend->headerChecksum = ACE::crc32(headerToSend, sizeof(messageHeader) - sizeof(messageHeader.headerChecksum));
sendPosition = 0;
delete msg;
} else {
//don't wake up the reactor when there's no data that needs to be sent
//(wake-up will be rescheduled when data becomes available in sendMessage
//below)
this->reactor()->cancel_wakeup(this, ACE_Event_Handler::WRITE_MASK);
return 0;
}
}
//timeout after ten seconds when sending data (in case connection drops
//in the middle, we don't want to wait until the socket connection dies)
//ACE_Time_Value timeout(10);
count = this->peer().send(dataToSend + sendPosition, sendBufferSize - sendPosition);
if(count >= 0) {
sendPosition += count;
}
LOG_TRACE("Sent " << count << " bytes (current postition " << sendPosition << "/" << sendBufferSize);
if(sendPosition >= (sendBufferSize)) {
delete[] dataToSend;
dataToSend = NULL;
sendBufferSize = 0;
sendPosition = 0;
}
} while(count != -1);
if(count == -1 && ACE_OS::last_error () == EWOULDBLOCK) {
LOG_TRACE("Received EWOULDBLOCK");
this->reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);
} else {
LOG_ERROR(this << " Socket error occurred. (" << ACE_OS::last_error() << ")");
return -1;
}
return 0;
}
int AndroidServiceHandler::processData(char *data, unsigned int messageSize, unsigned int messageChecksum, char priority) {
//Validate checksum
unsigned int calculatedChecksum = ACE::crc32(data, messageSize);
if(calculatedChecksum != messageChecksum) {
LOG_ERROR(this << " Mismatched checksum " << std::hex << calculatedChecksum << " : " << messageChecksum);
LOG_ERROR(this << " size " << std::dec << messageSize ); // << " payload: " < );
return -1;
}
//checksum is valid; parse the data
ammo::protocol::MessageWrapper *msg = new ammo::protocol::MessageWrapper();
bool result = msg->ParseFromArray(data, messageSize);
if(result == false) {
LOG_ERROR(this << " MessageWrapper could not be deserialized.");
LOG_ERROR(this << " Client must have sent something that isn't a protocol buffer (or the wrong type).");
delete msg;
return -1;
}
addReceivedMessage(msg, priority);
messageProcessor->signalNewMessageAvailable();
return 0;
}
void AndroidServiceHandler::sendMessage(ammo::protocol::MessageWrapper *msg, char priority) {
QueuedMessage queuedMsg;
queuedMsg.priority = priority;
queuedMsg.message = msg;
if(priority != msg->message_priority()) {
LOG_WARN("Priority mismatch when adding message to send queue: Header = " << (int) priority << ", Message = " << msg->message_priority());
}
sendQueueMutex.acquire();
queuedMsg.messageCount = sentMessageCount;
sentMessageCount++;
if(!connectionClosing) {
sendQueue.push(queuedMsg);
LOG_TRACE(this << " Queued a message to send. " << sendQueue.size() << " messages in queue.");
}
sendQueueMutex.release();
if(!connectionClosing) {
this->reactor()->schedule_wakeup(this, ACE_Event_Handler::WRITE_MASK);
}
}
ammo::protocol::MessageWrapper *AndroidServiceHandler::getNextMessageToSend() {
ammo::protocol::MessageWrapper *msg = NULL;
sendQueueMutex.acquire();
if(!sendQueue.empty()) {
msg = sendQueue.top().message;
sendQueue.pop();
}
int size = sendQueue.size();
sendQueueMutex.release();
LOG_TRACE(this << " Dequeued a message to send. " << size << " messages remain in queue.");
return msg;
}
ammo::protocol::MessageWrapper *AndroidServiceHandler::getNextReceivedMessage() {
ammo::protocol::MessageWrapper *msg = NULL;
receiveQueueMutex.acquire();
if(!receiveQueue.empty()) {
msg = receiveQueue.top().message;
receiveQueue.pop();
}
receiveQueueMutex.release();
return msg;
}
void AndroidServiceHandler::addReceivedMessage(ammo::protocol::MessageWrapper *msg, char priority) {
QueuedMessage queuedMsg;
queuedMsg.priority = priority;
queuedMsg.message = msg;
if(priority != msg->message_priority()) {
LOG_WARN("Priority mismatch on received message: Header = " << (int) priority << ", Message = " << msg->message_priority());
}
receiveQueueMutex.acquire();
queuedMsg.messageCount = receivedMessageCount;
receivedMessageCount++;
receiveQueue.push(queuedMsg);
receiveQueueMutex.release();
}
AndroidServiceHandler::~AndroidServiceHandler() {
LOG_TRACE(this << " In ~AndroidServiceHandler");
delete messageProcessor;
}
|
Make priority from header readable (it was printing a char)
|
Make priority from header readable (it was printing a char)
|
C++
|
mit
|
isis-ammo/ammo-gateway,isis-ammo/ammo-gateway,isis-ammo/ammo-gateway,isis-ammo/ammo-gateway,isis-ammo/ammo-gateway,isis-ammo/ammo-gateway
|
35501874900206144e19d76a960977ff63d12c8c
|
bottleopener/thingspeakSender.cpp
|
bottleopener/thingspeakSender.cpp
|
#include "thingspeakSender.h"
#include "ThingSpeak.h"
#define USE_WIFI101_SHIELD
#include "BridgeClient.h"
BridgeClient client;
#include "message.h"
#include "logger.h"
#include "secretKeys.h"
void ThingspeakSender::init()
{
logger->log("\nTry to connect to ThingSpeak ...");
ThingSpeak.begin(client);
logger->log(" Done ! \n");
}
void ThingspeakSender::sendMessage(const char* sender, int counter)
{
logger->log("Sending to ThingSpeak...\n");
char buf[128];
Message msg(sender, "ThingSpeak", counter);
Message::serialize(msg, buf, 128);
ThingSpeak.setField(1, (String)sender);
ThingSpeak.setField(2, (String)"ThingSpeak");
ThingSpeak.setField(3, (int)counter);
//ThingSpeak.setField(4, String(buf));
ThingSpeak.writeFields(THINGSPEAK_CHANNEL_NUMBER, THINGSPEAK_WRITE_API_KEY);
}
|
#include "thingspeakSender.h"
#include "ThingSpeak.h"
#define USE_WIFI101_SHIELD
#include "BridgeClient.h"
BridgeClient client;
#include "message.h"
#include "logger.h"
#include "secretKeys.h"
void ThingspeakSender::init()
{
logger->log("\nTry to connect to ThingSpeak ...");
ThingSpeak.begin(client);
logger->log(" Done ! \n");
}
void ThingspeakSender::sendMessage(const char* sender, int counter)
{
logger->log("Sending to ThingSpeak...\n");
char buf[128];
Message msg(sender, "ThingSpeak", counter);
Message::serialize(msg, buf, 128);
ThingSpeak.setField(1, (String)sender);
ThingSpeak.setField(2, (int)counter);
ThingSpeak.writeFields(THINGSPEAK_CHANNEL_NUMBER, THINGSPEAK_WRITE_API_KEY);
}
|
Simplify message sent
|
Simplify message sent
|
C++
|
mit
|
Zenika/bottleopener_iot,Zenika/bottleopener_iot,Zenika/bottleopener_iot,Zenika/bottleopener_iot
|
2423cad02cd544482a2d36d5e0067f6040dd737f
|
src/common/net.cc
|
src/common/net.cc
|
/* net.cc
Mathieu Stefani, 12 August 2015
*/
#include <pistache/net.h>
#include <pistache/common.h>
#include <pistache/config.h>
#include <stdexcept>
#include <limits>
#include <cstring>
#include <cassert>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <iostream>
namespace Pistache {
namespace {
bool IsIPv4HostName(const std::string& host)
{
in_addr addr;
char buff[INET_ADDRSTRLEN + 1] = {0, };
std::copy(host.begin(), host.end(), buff);
int res = inet_pton(AF_INET, buff, &addr);
return res;
}
bool IsIPv6HostName(const std::string& host)
{
in6_addr addr6;
char buff6[INET6_ADDRSTRLEN + 1] = {0, };
std::copy(host.begin(), host.end(), buff6);
int res = inet_pton(AF_INET6, buff6, &(addr6.s6_addr16));
return res;
}
}
Port::Port(uint16_t port)
: port(port)
{}
Port::Port(const std::string& data)
{
if (data.empty())
throw std::invalid_argument("Invalid port: empty port");
char *end = 0;
long port_num = strtol(data.c_str(), &end, 10);
if (*end != 0 || port_num < Port::min() || port_num > Port::max())
throw std::invalid_argument("Invalid port: " + data);
port = static_cast<uint16_t>(port_num);
}
bool
Port::isReserved() const {
return port < 1024;
}
bool
Port::isUsed() const {
throw std::runtime_error("Unimplemented");
return false;
}
std::string
Port::toString() const {
return std::to_string(port);
}
IP::IP() {
family = AF_INET;
addr = {0};
addr.sin_family = AF_INET;
uint8_t buff[INET_ADDRSTRLEN+1] = {0,0,0,0};
memcpy(&addr.sin_addr.s_addr, buff, INET_ADDRSTRLEN);
}
IP::IP(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
family = AF_INET;
addr = {0};
addr.sin_family = AF_INET;
uint8_t buff[INET_ADDRSTRLEN+1] = {a,b,c,d};
memcpy(&addr.sin_addr.s_addr, buff, INET_ADDRSTRLEN);
}
IP::IP(uint16_t a, uint16_t b, uint16_t c, uint16_t d, uint16_t e, uint16_t f, uint16_t g, uint16_t h){
family = AF_INET6;
addr6 = { 0 };
addr6.sin6_family = AF_INET6;
uint16_t buff[9] {a,b,c,d,e,f,g,h, '\0'};
uint16_t remap[9] = {0,0,0,0,0,0,0,0, '\0'};
if ( htonl(1) != 1 ) {
for (int i = 0; i<8; i++) {
uint16_t x = buff[i];
uint16_t y = htons(x);
remap[i] = y;
}
} else {
memcpy(&remap, &buff, sizeof(remap));
}
memcpy(&addr6.sin6_addr.s6_addr16, &remap, 8*sizeof(uint16_t));
}
IP::IP(struct sockaddr* _addr) {
if (_addr->sa_family == AF_INET) {
struct sockaddr_in *in_addr = reinterpret_cast<struct sockaddr_in *>(_addr);
family = AF_INET;
port = in_addr->sin_port;
memcpy(&(addr.sin_addr.s_addr), &(in_addr->sin_addr.s_addr), sizeof(in_addr_t));
} else if (_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *in_addr = reinterpret_cast<struct sockaddr_in6 *>(_addr);
family = AF_INET6;
port = in_addr->sin6_port;
memcpy(&(addr6.sin6_addr.s6_addr16), &(in_addr->sin6_addr.s6_addr16), 8*sizeof(uint16_t));
}
}
IP
IP::any() {
return IP(0, 0, 0, 0);
}
IP
IP::any(bool is_ipv6) {
if (is_ipv6) {
return IP(0, 0, 0, 0, 0, 0, 0, 0);
} else {
return IP(0, 0, 0, 0);
}
}
IP
IP::loopback(){
return IP(127, 0, 0, 1);
}
IP
IP::loopback(bool is_ipv6) {
if (is_ipv6) {
return IP(0, 0, 0, 0, 0, 0, 0, 1);
} else {
return IP(127, 0, 0, 1);
}
}
int IP::getFamily() const {
return family;
}
int IP::getPort() const {
return port;
}
std::string
IP::toString() const {
char buff[INET6_ADDRSTRLEN+1];
if (family == AF_INET) {
in_addr_t addr_;
toNetwork(&addr_);
inet_ntop(AF_INET, &addr_, buff, INET_ADDRSTRLEN);
} else if (family == AF_INET6) {
struct in6_addr addr_ = in6addr_any;
toNetwork(&addr_);
inet_ntop(AF_INET6, &addr_, buff, INET6_ADDRSTRLEN);
}
return std::string(buff);
}
void IP::toNetwork(in_addr_t *_addr) const {
memcpy(_addr, &addr.sin_addr.s_addr, sizeof(uint32_t));
}
void IP::toNetwork(struct in6_addr *out) const {
memcpy(&out->s6_addr16, &(addr6.sin6_addr.s6_addr16), 8*sizeof(uint16_t));
}
bool IP::supported() {
struct ifaddrs *ifaddr = nullptr;
struct ifaddrs *ifa = nullptr;
int addr_family, n;
bool supportsIpv6 = false;
if (getifaddrs(&ifaddr) == -1) {
throw std::runtime_error("Call to getifaddrs() failed");
}
for (ifa = ifaddr, n = 0; ifa != nullptr; ifa = ifa->ifa_next, n++) {
if (ifa->ifa_addr == nullptr) {
continue;
}
addr_family = ifa->ifa_addr->sa_family;
if (addr_family == AF_INET6) {
supportsIpv6 = true;
continue;
}
}
freeifaddrs(ifaddr);
return supportsIpv6;
}
AddressParser::AddressParser(const std::string& data)
{
std::size_t end_pos = data.find(']');
std::size_t start_pos = data.find('[');
if (start_pos != std::string::npos &&
end_pos != std::string::npos &&
start_pos < end_pos)
{
std::size_t colon_pos = data.find_first_of(':', end_pos);
if (colon_pos != std::string::npos)
{
hasColon_ = true;
}
host_ = data.substr(start_pos, end_pos + 1);
family_ = AF_INET6;
++end_pos;
}
else
{
std::size_t colon_pos = data.find(':');
if (colon_pos != std::string::npos)
{
hasColon_ = true;
}
end_pos = colon_pos;
host_ = data.substr(0, end_pos);
family_ = AF_INET;
}
if (end_pos != std::string::npos)
{
port_ = data.substr(end_pos + 1);
if (port_.empty())
throw std::invalid_argument("Invalid port");
}
}
const std::string& AddressParser::rawHost() const
{
return host_;
}
const std::string& AddressParser::rawPort() const
{
return port_;
}
bool AddressParser::hasColon() const
{
return hasColon_;
}
int AddressParser::family() const
{
return family_;
}
Address::Address() :
ip_{}, port_{0}
{}
Address::Address(std::string host, Port port)
{
std::string addr = std::move(host);
addr.append(":");
addr.append(port.toString());
init(std::move(addr));
}
Address::Address(std::string addr)
{
init(std::move(addr));
}
Address::Address(const char* addr)
{
init(std::string(addr));
}
Address::Address(IP ip, Port port)
: ip_(ip)
, port_(port)
{ }
Address
Address::fromUnix(struct sockaddr* addr) {
if ((addr->sa_family==AF_INET) or (addr->sa_family==AF_INET6)) {
IP ip = IP(addr);
Port port = Port(ip.getPort());
assert(addr);
return Address(ip, port);
}
throw Error("Not an IP socket");
}
std::string
Address::host() const {
return ip_.toString();
}
Port
Address::port() const {
return port_;
}
int
Address::family() const {
return ip_.getFamily();
}
void Address::init(const std::string& addr)
{
AddressParser parser(addr);
int family_ = parser.family();
std::string host_;
if (family_ == AF_INET6)
{
const std::string& raw_host = parser.rawHost();
assert(raw_host.size() > 2);
host_ = addr.substr(1, raw_host.size() - 2);
if (!IsIPv6HostName(host_))
{
throw std::invalid_argument("Invalid IPv6 address");
}
char buff[INET6_ADDRSTRLEN+1] = {};
memcpy(buff, host_.c_str(), INET6_ADDRSTRLEN);
struct in6_addr addr;
inet_pton(AF_INET6, buff, &addr);
struct sockaddr_in6 s_addr = {0};
s_addr.sin6_family = AF_INET6;
memcpy(&(s_addr.sin6_addr.s6_addr16), &addr.s6_addr16, 8*sizeof(uint16_t));
ip_ = IP(reinterpret_cast<struct sockaddr *>(&s_addr));
}
else if (family_ == AF_INET)
{
host_ = parser.rawHost();
if (host_ == "*")
{
host_ = "0.0.0.0";
}
else if (host_ == "localhost")
{
host_ = "127.0.0.1";
}
struct hostent *hp = ::gethostbyname(host_.c_str());
if (hp)
{
struct in_addr **addr_list;
addr_list = (struct in_addr **)hp->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++)
{
// Just take the first IP address
host_ = std::string(inet_ntoa(*addr_list[i]));
break;
}
}
if (!IsIPv4HostName(host_))
{
throw std::invalid_argument("Invalid IPv4 address");
}
char buff[INET_ADDRSTRLEN+1] = {};
memcpy(buff, host_.c_str(), INET_ADDRSTRLEN);
struct in_addr addr;
inet_pton(AF_INET, buff, &addr);
struct sockaddr_in s_addr = {0};
s_addr.sin_family = AF_INET;
memcpy(&(s_addr.sin_addr.s_addr), &addr.s_addr, sizeof(uint32_t));
ip_ = IP(reinterpret_cast<struct sockaddr *>(&s_addr));
}
else
{ assert(false); }
const std::string& portPart = parser.rawPort();
if (portPart.empty())
{
if (parser.hasColon())
{
// "www.example.com:" or "127.0.0.1:" cases
throw std::invalid_argument("Invalid port");
}
else
{
// "www.example.com" or "127.0.0.1" cases
port_ = Const::HTTP_STANDARD_PORT;
}
}
else
{
char *end = 0;
long port = strtol(portPart.c_str(), &end, 10);
if (*end != 0 || port < Port::min() || port > Port::max())
throw std::invalid_argument("Invalid port");
port_ = Port(port);
}
}
Error::Error(const char* message)
: std::runtime_error(message)
{ }
Error::Error(std::string message)
: std::runtime_error(std::move(message))
{ }
Error
Error::system(const char* message) {
const char *err = strerror(errno);
std::string str(message);
str += ": ";
str += err;
return Error(std::move(str));
}
} // namespace Pistache
|
/* net.cc
Mathieu Stefani, 12 August 2015
*/
#include <pistache/net.h>
#include <pistache/common.h>
#include <pistache/config.h>
#include <stdexcept>
#include <limits>
#include <cstring>
#include <cassert>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <iostream>
namespace Pistache {
namespace {
bool IsIPv4HostName(const std::string& host)
{
in_addr addr;
char buff[INET_ADDRSTRLEN + 1] = {0, };
std::copy(host.begin(), host.end(), buff);
int res = inet_pton(AF_INET, buff, &addr);
return res;
}
bool IsIPv6HostName(const std::string& host)
{
in6_addr addr6;
char buff6[INET6_ADDRSTRLEN + 1] = {0, };
std::copy(host.begin(), host.end(), buff6);
int res = inet_pton(AF_INET6, buff6, &(addr6.s6_addr16));
return res;
}
}
Port::Port(uint16_t port)
: port(port)
{}
Port::Port(const std::string& data)
{
if (data.empty())
throw std::invalid_argument("Invalid port: empty port");
char *end = 0;
long port_num = strtol(data.c_str(), &end, 10);
if (*end != 0 || port_num < Port::min() || port_num > Port::max())
throw std::invalid_argument("Invalid port: " + data);
port = static_cast<uint16_t>(port_num);
}
bool
Port::isReserved() const {
return port < 1024;
}
bool
Port::isUsed() const {
throw std::runtime_error("Unimplemented");
return false;
}
std::string
Port::toString() const {
return std::to_string(port);
}
IP::IP() {
family = AF_INET;
addr = {0};
addr.sin_family = AF_INET;
uint8_t buff[INET_ADDRSTRLEN+1] = {0,0,0,0};
memcpy(&addr.sin_addr.s_addr, buff, INET_ADDRSTRLEN);
}
IP::IP(uint8_t a, uint8_t b, uint8_t c, uint8_t d) {
family = AF_INET;
addr = {0};
addr.sin_family = AF_INET;
uint8_t buff[INET_ADDRSTRLEN+1] = {a,b,c,d};
memcpy(&addr.sin_addr.s_addr, buff, INET_ADDRSTRLEN);
}
IP::IP(uint16_t a, uint16_t b, uint16_t c, uint16_t d, uint16_t e, uint16_t f, uint16_t g, uint16_t h){
family = AF_INET6;
addr6 = { 0 };
addr6.sin6_family = AF_INET6;
uint16_t buff[9] {a,b,c,d,e,f,g,h, '\0'};
uint16_t remap[9] = {0,0,0,0,0,0,0,0, '\0'};
if ( htonl(1) != 1 ) {
for (int i = 0; i<8; i++) {
uint16_t x = buff[i];
uint16_t y = htons(x);
remap[i] = y;
}
} else {
memcpy(&remap, &buff, sizeof(remap));
}
memcpy(&addr6.sin6_addr.s6_addr16, &remap, 8*sizeof(uint16_t));
}
IP::IP(struct sockaddr* _addr) {
if (_addr->sa_family == AF_INET) {
struct sockaddr_in *in_addr = reinterpret_cast<struct sockaddr_in *>(_addr);
family = AF_INET;
port = in_addr->sin_port;
memcpy(&(addr.sin_addr.s_addr), &(in_addr->sin_addr.s_addr), sizeof(in_addr_t));
} else if (_addr->sa_family == AF_INET6) {
struct sockaddr_in6 *in_addr = reinterpret_cast<struct sockaddr_in6 *>(_addr);
family = AF_INET6;
port = in_addr->sin6_port;
memcpy(&(addr6.sin6_addr.s6_addr16), &(in_addr->sin6_addr.s6_addr16), 8*sizeof(uint16_t));
}
}
IP
IP::any() {
return IP(0, 0, 0, 0);
}
IP
IP::any(bool is_ipv6) {
if (is_ipv6) {
return IP(0, 0, 0, 0, 0, 0, 0, 0);
} else {
return IP(0, 0, 0, 0);
}
}
IP
IP::loopback(){
return IP(127, 0, 0, 1);
}
IP
IP::loopback(bool is_ipv6) {
if (is_ipv6) {
return IP(0, 0, 0, 0, 0, 0, 0, 1);
} else {
return IP(127, 0, 0, 1);
}
}
int IP::getFamily() const {
return family;
}
int IP::getPort() const {
return port;
}
std::string
IP::toString() const {
char buff[INET6_ADDRSTRLEN+1];
if (family == AF_INET) {
in_addr_t addr_;
toNetwork(&addr_);
inet_ntop(AF_INET, &addr_, buff, INET_ADDRSTRLEN);
} else if (family == AF_INET6) {
struct in6_addr addr_ = in6addr_any;
toNetwork(&addr_);
inet_ntop(AF_INET6, &addr_, buff, INET6_ADDRSTRLEN);
}
return std::string(buff);
}
void IP::toNetwork(in_addr_t *_addr) const {
memcpy(_addr, &addr.sin_addr.s_addr, sizeof(uint32_t));
}
void IP::toNetwork(struct in6_addr *out) const {
memcpy(&out->s6_addr16, &(addr6.sin6_addr.s6_addr16), 8*sizeof(uint16_t));
}
bool IP::supported() {
struct ifaddrs *ifaddr = nullptr;
struct ifaddrs *ifa = nullptr;
int addr_family, n;
bool supportsIpv6 = false;
if (getifaddrs(&ifaddr) == -1) {
throw std::runtime_error("Call to getifaddrs() failed");
}
for (ifa = ifaddr, n = 0; ifa != nullptr; ifa = ifa->ifa_next, n++) {
if (ifa->ifa_addr == nullptr) {
continue;
}
addr_family = ifa->ifa_addr->sa_family;
if (addr_family == AF_INET6) {
supportsIpv6 = true;
continue;
}
}
freeifaddrs(ifaddr);
return supportsIpv6;
}
AddressParser::AddressParser(const std::string& data)
{
std::size_t end_pos = data.find(']');
std::size_t start_pos = data.find('[');
if (start_pos != std::string::npos &&
end_pos != std::string::npos &&
start_pos < end_pos)
{
std::size_t colon_pos = data.find_first_of(':', end_pos);
if (colon_pos != std::string::npos)
{
hasColon_ = true;
}
host_ = data.substr(start_pos, end_pos + 1);
family_ = AF_INET6;
++end_pos;
}
else
{
std::size_t colon_pos = data.find(':');
if (colon_pos != std::string::npos)
{
hasColon_ = true;
}
end_pos = colon_pos;
host_ = data.substr(0, end_pos);
family_ = AF_INET;
}
if (end_pos != std::string::npos)
{
port_ = data.substr(end_pos + 1);
if (port_.empty())
throw std::invalid_argument("Invalid port");
}
}
const std::string& AddressParser::rawHost() const
{
return host_;
}
const std::string& AddressParser::rawPort() const
{
return port_;
}
bool AddressParser::hasColon() const
{
return hasColon_;
}
int AddressParser::family() const
{
return family_;
}
Address::Address() :
ip_{}, port_{0}
{}
Address::Address(std::string host, Port port)
{
std::string addr = std::move(host);
addr.append(":");
addr.append(port.toString());
init(std::move(addr));
}
Address::Address(std::string addr)
{
init(std::move(addr));
}
Address::Address(const char* addr)
{
init(std::string(addr));
}
Address::Address(IP ip, Port port)
: ip_(ip)
, port_(port)
{ }
Address
Address::fromUnix(struct sockaddr* addr) {
if ((addr->sa_family==AF_INET) or (addr->sa_family==AF_INET6)) {
IP ip = IP(addr);
Port port = Port(ip.getPort());
assert(addr);
return Address(ip, port);
}
throw Error("Not an IP socket");
}
std::string
Address::host() const {
return ip_.toString();
}
Port
Address::port() const {
return port_;
}
int
Address::family() const {
return ip_.getFamily();
}
void Address::init(const std::string& addr)
{
AddressParser parser(addr);
int family_ = parser.family();
std::string host_;
if (family_ == AF_INET6)
{
const std::string& raw_host = parser.rawHost();
assert(raw_host.size() > 2);
host_ = addr.substr(1, raw_host.size() - 2);
if (!IsIPv6HostName(host_))
{
throw std::invalid_argument("Invalid IPv6 address");
}
struct in6_addr addr;
inet_pton(AF_INET6, host_.c_str(), &addr);
struct sockaddr_in6 s_addr = {0};
s_addr.sin6_family = AF_INET6;
memcpy(&(s_addr.sin6_addr.s6_addr16), &addr.s6_addr16, 8*sizeof(uint16_t));
ip_ = IP(reinterpret_cast<struct sockaddr *>(&s_addr));
}
else if (family_ == AF_INET)
{
host_ = parser.rawHost();
if (host_ == "*")
{
host_ = "0.0.0.0";
}
else if (host_ == "localhost")
{
host_ = "127.0.0.1";
}
struct hostent *hp = ::gethostbyname(host_.c_str());
if (hp)
{
struct in_addr **addr_list;
addr_list = (struct in_addr **)hp->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++)
{
// Just take the first IP address
host_ = std::string(inet_ntoa(*addr_list[i]));
break;
}
}
if (!IsIPv4HostName(host_))
{
throw std::invalid_argument("Invalid IPv4 address");
}
struct in_addr addr;
inet_pton(AF_INET, host_.c_str(), &addr);
struct sockaddr_in s_addr = {0};
s_addr.sin_family = AF_INET;
memcpy(&(s_addr.sin_addr.s_addr), &addr.s_addr, sizeof(uint32_t));
ip_ = IP(reinterpret_cast<struct sockaddr *>(&s_addr));
}
else
{ assert(false); }
const std::string& portPart = parser.rawPort();
if (portPart.empty())
{
if (parser.hasColon())
{
// "www.example.com:" or "127.0.0.1:" cases
throw std::invalid_argument("Invalid port");
}
else
{
// "www.example.com" or "127.0.0.1" cases
port_ = Const::HTTP_STANDARD_PORT;
}
}
else
{
char *end = 0;
long port = strtol(portPart.c_str(), &end, 10);
if (*end != 0 || port < Port::min() || port > Port::max())
throw std::invalid_argument("Invalid port");
port_ = Port(port);
}
}
Error::Error(const char* message)
: std::runtime_error(message)
{ }
Error::Error(std::string message)
: std::runtime_error(std::move(message))
{ }
Error
Error::system(const char* message) {
const char *err = strerror(errno);
std::string str(message);
str += ": ";
str += err;
return Error(std::move(str));
}
} // namespace Pistache
|
Remove broken memcpy in Address::init
|
Remove broken memcpy in Address::init
There's no guarantee that `host_` is long enough for the `INET_ADDRSTRLEN` (or `INET6_ADDRSTRLEN`, respectively) memcpy to be valid, and in any event there doesn't seem to be a reason to copy it in the first place.
|
C++
|
apache-2.0
|
oktal/rest,oktal/rest,oktal/rest,oktal/pistache,oktal/rest,oktal/pistache,oktal/pistache,oktal/pistache,oktal/pistache
|
9d81a6e778f868da8b29106436b7be12f80ab77c
|
chrome/browser/gtk/tabs/dragged_tab_gtk.cc
|
chrome/browser/gtk/tabs/dragged_tab_gtk.cc
|
// Copyright (c) 2009 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/browser/gtk/tabs/dragged_tab_gtk.h"
#include <gdk/gdk.h>
#include <algorithm>
#include "app/gfx/canvas_paint.h"
#include "base/gfx/gtk_util.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/gtk/tabs/tab_renderer_gtk.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/x11_util.h"
#include "third_party/skia/include/core/SkShader.h"
namespace {
// The size of the dragged window frame.
const int kDragFrameBorderSize = 1;
const int kTwiceDragFrameBorderSize = 2 * kDragFrameBorderSize;
// Used to scale the dragged window sizes.
const float kScalingFactor = 0.5;
const int kAnimateToBoundsDurationMs = 150;
const gdouble kTransparentAlpha = (200.0f / 255.0f);
const gdouble kOpaqueAlpha = 1.0f;
const double kDraggedTabBorderColor[] = { 103.0 / 0xff,
129.0 / 0xff,
162.0 / 0xff };
} // namespace
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, public:
DraggedTabGtk::DraggedTabGtk(TabContents* datasource,
const gfx::Point& mouse_tab_offset,
const gfx::Size& contents_size)
: backing_store_(NULL),
renderer_(new TabRendererGtk),
attached_(false),
mouse_tab_offset_(mouse_tab_offset),
attached_tab_size_(TabRendererGtk::GetMinimumSelectedSize()),
contents_size_(contents_size),
close_animation_(this),
tab_width_(0) {
renderer_->UpdateData(datasource, false);
container_ = gtk_window_new(GTK_WINDOW_POPUP);
SetContainerColorMap();
gtk_widget_set_app_paintable(container_, TRUE);
g_signal_connect(G_OBJECT(container_), "expose-event",
G_CALLBACK(OnExposeEvent), this);
gtk_widget_add_events(container_, GDK_STRUCTURE_MASK);
gtk_container_add(GTK_CONTAINER(container_), renderer_->widget());
gtk_widget_show_all(container_);
}
DraggedTabGtk::~DraggedTabGtk() {
gtk_widget_destroy(container_);
}
void DraggedTabGtk::MoveTo(const gfx::Point& screen_point) {
int x = screen_point.x() + mouse_tab_offset_.x() -
ScaleValue(mouse_tab_offset_.x());
int y = screen_point.y() + mouse_tab_offset_.y() -
ScaleValue(mouse_tab_offset_.y());
gtk_window_move(GTK_WINDOW(container_), x, y);
}
void DraggedTabGtk::Attach(int selected_width) {
attached_ = true;
Resize(selected_width);
if (gtk_util::IsScreenComposited())
gdk_window_set_opacity(container_->window, kOpaqueAlpha);
}
void DraggedTabGtk::Resize(int width) {
attached_tab_size_.set_width(width);
ResizeContainer();
Update();
}
void DraggedTabGtk::set_pinned(bool pinned) {
renderer_->set_pinned(pinned);
}
bool DraggedTabGtk::is_pinned() const {
return renderer_->is_pinned();
}
void DraggedTabGtk::Detach(GtkWidget* contents, BackingStore* backing_store) {
// Detached tabs are never pinned.
renderer_->set_pinned(false);
if (attached_tab_size_.width() != tab_width_) {
// The attached tab size differs from current tab size. Resize accordingly.
Resize(tab_width_);
}
attached_ = false;
contents_ = contents;
backing_store_ = backing_store;
ResizeContainer();
if (gtk_util::IsScreenComposited())
gdk_window_set_opacity(container_->window, kTransparentAlpha);
}
void DraggedTabGtk::Update() {
gtk_widget_queue_draw(container_);
}
void DraggedTabGtk::AnimateToBounds(const gfx::Rect& bounds,
AnimateToBoundsCallback* callback) {
animation_callback_.reset(callback);
gint x, y, width, height;
gdk_window_get_origin(container_->window, &x, &y);
gdk_window_get_geometry(container_->window, NULL, NULL,
&width, &height, NULL);
animation_start_bounds_ = gfx::Rect(x, y, width, height);
animation_end_bounds_ = bounds;
close_animation_.SetSlideDuration(kAnimateToBoundsDurationMs);
close_animation_.SetTweenType(SlideAnimation::EASE_OUT);
if (!close_animation_.IsShowing()) {
close_animation_.Reset();
close_animation_.Show();
}
}
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, AnimationDelegate implementation:
void DraggedTabGtk::AnimationProgressed(const Animation* animation) {
int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());
int x = animation_start_bounds_.x() +
static_cast<int>(delta_x * animation->GetCurrentValue());
int y = animation_end_bounds_.y();
gdk_window_move(container_->window, x, y);
}
void DraggedTabGtk::AnimationEnded(const Animation* animation) {
animation_callback_->Run();
}
void DraggedTabGtk::AnimationCanceled(const Animation* animation) {
AnimationEnded(animation);
}
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, private:
void DraggedTabGtk::Layout() {
if (attached_) {
gfx::Size prefsize = GetPreferredSize();
renderer_->SetBounds(gfx::Rect(0, 0, prefsize.width(), prefsize.height()));
} else {
// TODO(jhawkins): RTL layout.
// The renderer_'s width should be attached_tab_size_.width() in both LTR
// and RTL locales. Wrong width will cause the wrong positioning of the tab
// view in dragging. Please refer to http://crbug.com/6223 for details.
renderer_->SetBounds(gfx::Rect(0, 0, attached_tab_size_.width(),
attached_tab_size_.height()));
}
}
gfx::Size DraggedTabGtk::GetPreferredSize() {
if (attached_)
return attached_tab_size_;
int width = std::max(attached_tab_size_.width(), contents_size_.width()) +
kTwiceDragFrameBorderSize;
int height = attached_tab_size_.height() + kDragFrameBorderSize +
contents_size_.height();
return gfx::Size(width, height);
}
void DraggedTabGtk::ResizeContainer() {
gfx::Size size = GetPreferredSize();
gtk_window_resize(GTK_WINDOW(container_),
ScaleValue(size.width()), ScaleValue(size.height()));
Layout();
Update();
}
int DraggedTabGtk::ScaleValue(int value) {
return attached_ ? value : static_cast<int>(value * kScalingFactor);
}
gfx::Rect DraggedTabGtk::bounds() const {
gint x, y, width, height;
gtk_window_get_position(GTK_WINDOW(container_), &x, &y);
gtk_window_get_size(GTK_WINDOW(container_), &width, &height);
return gfx::Rect(x, y, width, height);
}
void DraggedTabGtk::SetContainerColorMap() {
GdkScreen* screen = gtk_widget_get_screen(container_);
GdkColormap* colormap = gdk_screen_get_rgba_colormap(screen);
// If rgba is not available, use rgb instead.
if (!colormap)
colormap = gdk_screen_get_rgb_colormap(screen);
gtk_widget_set_colormap(container_, colormap);
}
void DraggedTabGtk::SetContainerTransparency() {
cairo_t* cairo_context = gdk_cairo_create(container_->window);
if (!cairo_context)
return;
// Make the background of the dragged tab window fully transparent. All of
// the content of the window (child widgets) will be completely opaque.
gfx::Size size = bounds().size();
cairo_scale(cairo_context, static_cast<double>(size.width()),
static_cast<double>(size.height()));
cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);
cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);
cairo_paint(cairo_context);
cairo_destroy(cairo_context);
}
void DraggedTabGtk::SetContainerShapeMask(GdkPixbuf* pixbuf) {
// Create a 1bpp bitmap the size of |container_|.
gfx::Size size = bounds().size();
GdkPixmap* pixmap = gdk_pixmap_new(NULL, size.width(), size.height(), 1);
cairo_t* cairo_context = gdk_cairo_create(GDK_DRAWABLE(pixmap));
// Set the transparency.
cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);
// Blit the rendered bitmap into a pixmap. Any pixel set in the pixmap will
// be opaque in the container window.
cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);
if (!attached_)
cairo_scale(cairo_context, kScalingFactor, kScalingFactor);
gdk_cairo_set_source_pixbuf(cairo_context, pixbuf, 0, 0);
cairo_paint(cairo_context);
if (!attached_) {
// Make the render area depiction opaque (leaving enough room for the
// border).
cairo_identity_matrix(cairo_context);
cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 1.0f);
int tab_height = kScalingFactor * gdk_pixbuf_get_height(pixbuf) -
kDragFrameBorderSize;
cairo_rectangle(cairo_context,
0, tab_height,
size.width(), size.height() - tab_height);
cairo_fill(cairo_context);
}
cairo_destroy(cairo_context);
// Set the shape mask.
gdk_window_shape_combine_mask(container_->window, pixmap, 0, 0);
g_object_unref(pixmap);
}
GdkPixbuf* DraggedTabGtk::PaintTab() {
SkBitmap bitmap = renderer_->PaintBitmap();
return gfx::GdkPixbufFromSkBitmap(&bitmap);
}
// static
gboolean DraggedTabGtk::OnExposeEvent(GtkWidget* widget,
GdkEventExpose* event,
DraggedTabGtk* dragged_tab) {
GdkPixbuf* pixbuf = dragged_tab->PaintTab();
if (gtk_util::IsScreenComposited()) {
dragged_tab->SetContainerTransparency();
} else {
dragged_tab->SetContainerShapeMask(pixbuf);
}
// Only used when not attached.
int tab_height = kScalingFactor * gdk_pixbuf_get_height(pixbuf);
int tab_width = kScalingFactor * gdk_pixbuf_get_width(pixbuf);
// Draw the render area.
if (dragged_tab->backing_store_ && !dragged_tab->attached_) {
// This leaves room for the border.
dragged_tab->backing_store_->PaintToRect(
gfx::Rect(kDragFrameBorderSize, tab_height,
widget->allocation.width - kTwiceDragFrameBorderSize,
widget->allocation.height - tab_height -
kDragFrameBorderSize),
GDK_DRAWABLE(widget->window));
}
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));
// Draw the border.
if (!dragged_tab->attached_) {
cairo_set_line_width(cr, kDragFrameBorderSize);
cairo_set_source_rgb(cr, kDraggedTabBorderColor[0],
kDraggedTabBorderColor[1],
kDraggedTabBorderColor[2]);
// |offset| is the distance from the edge of the image to the middle of
// the border line.
double offset = kDragFrameBorderSize / 2.0 - 0.5;
double left_x = offset;
double top_y = tab_height - kDragFrameBorderSize + offset;
double right_x = widget->allocation.width - offset;
double bottom_y = widget->allocation.height - offset;
double middle_x = tab_width + offset;
// We don't use cairo_rectangle() because we don't want to draw the border
// under the tab itself.
cairo_move_to(cr, left_x, top_y);
cairo_line_to(cr, left_x, bottom_y);
cairo_line_to(cr, right_x, bottom_y);
cairo_line_to(cr, right_x, top_y);
cairo_line_to(cr, middle_x, top_y);
cairo_stroke(cr);
}
// Draw the tab.
if (!dragged_tab->attached_)
cairo_scale(cr, kScalingFactor, kScalingFactor);
gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);
cairo_paint(cr);
cairo_destroy(cr);
g_object_unref(pixbuf);
// We've already drawn the tab, so don't propagate the expose-event signal.
return TRUE;
}
|
// Copyright (c) 2009 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/browser/gtk/tabs/dragged_tab_gtk.h"
#include <gdk/gdk.h>
#include <algorithm>
#include "app/gfx/canvas_paint.h"
#include "base/gfx/gtk_util.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/gtk/tabs/tab_renderer_gtk.h"
#include "chrome/common/gtk_util.h"
#include "chrome/common/x11_util.h"
#include "third_party/skia/include/core/SkShader.h"
namespace {
// The size of the dragged window frame.
const int kDragFrameBorderSize = 1;
const int kTwiceDragFrameBorderSize = 2 * kDragFrameBorderSize;
// Used to scale the dragged window sizes.
const float kScalingFactor = 0.5;
const int kAnimateToBoundsDurationMs = 150;
const gdouble kTransparentAlpha = (200.0f / 255.0f);
const gdouble kOpaqueAlpha = 1.0f;
const double kDraggedTabBorderColor[] = { 103.0 / 0xff,
129.0 / 0xff,
162.0 / 0xff };
} // namespace
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, public:
DraggedTabGtk::DraggedTabGtk(TabContents* datasource,
const gfx::Point& mouse_tab_offset,
const gfx::Size& contents_size)
: backing_store_(NULL),
renderer_(new TabRendererGtk),
attached_(false),
mouse_tab_offset_(mouse_tab_offset),
attached_tab_size_(TabRendererGtk::GetMinimumSelectedSize()),
contents_size_(contents_size),
close_animation_(this),
tab_width_(0) {
renderer_->UpdateData(datasource, false);
container_ = gtk_window_new(GTK_WINDOW_POPUP);
SetContainerColorMap();
gtk_widget_set_app_paintable(container_, TRUE);
g_signal_connect(G_OBJECT(container_), "expose-event",
G_CALLBACK(OnExposeEvent), this);
gtk_widget_add_events(container_, GDK_STRUCTURE_MASK);
gtk_container_add(GTK_CONTAINER(container_), renderer_->widget());
gtk_widget_show_all(container_);
}
DraggedTabGtk::~DraggedTabGtk() {
gtk_widget_destroy(container_);
}
void DraggedTabGtk::MoveTo(const gfx::Point& screen_point) {
int x = screen_point.x() + mouse_tab_offset_.x() -
ScaleValue(mouse_tab_offset_.x());
int y = screen_point.y() + mouse_tab_offset_.y() -
ScaleValue(mouse_tab_offset_.y());
gtk_window_move(GTK_WINDOW(container_), x, y);
}
void DraggedTabGtk::Attach(int selected_width) {
attached_ = true;
Resize(selected_width);
if (gtk_util::IsScreenComposited())
gdk_window_set_opacity(container_->window, kOpaqueAlpha);
}
void DraggedTabGtk::Resize(int width) {
attached_tab_size_.set_width(width);
ResizeContainer();
}
void DraggedTabGtk::set_pinned(bool pinned) {
renderer_->set_pinned(pinned);
}
bool DraggedTabGtk::is_pinned() const {
return renderer_->is_pinned();
}
void DraggedTabGtk::Detach(GtkWidget* contents, BackingStore* backing_store) {
// Detached tabs are never pinned.
renderer_->set_pinned(false);
if (attached_tab_size_.width() != tab_width_) {
// The attached tab size differs from current tab size. Resize accordingly.
Resize(tab_width_);
}
attached_ = false;
contents_ = contents;
backing_store_ = backing_store;
ResizeContainer();
if (gtk_util::IsScreenComposited())
gdk_window_set_opacity(container_->window, kTransparentAlpha);
}
void DraggedTabGtk::Update() {
gtk_widget_queue_draw(container_);
}
void DraggedTabGtk::AnimateToBounds(const gfx::Rect& bounds,
AnimateToBoundsCallback* callback) {
animation_callback_.reset(callback);
gint x, y, width, height;
gdk_window_get_origin(container_->window, &x, &y);
gdk_window_get_geometry(container_->window, NULL, NULL,
&width, &height, NULL);
animation_start_bounds_ = gfx::Rect(x, y, width, height);
animation_end_bounds_ = bounds;
close_animation_.SetSlideDuration(kAnimateToBoundsDurationMs);
close_animation_.SetTweenType(SlideAnimation::EASE_OUT);
if (!close_animation_.IsShowing()) {
close_animation_.Reset();
close_animation_.Show();
}
}
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, AnimationDelegate implementation:
void DraggedTabGtk::AnimationProgressed(const Animation* animation) {
int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());
int x = animation_start_bounds_.x() +
static_cast<int>(delta_x * animation->GetCurrentValue());
int y = animation_end_bounds_.y();
gdk_window_move(container_->window, x, y);
}
void DraggedTabGtk::AnimationEnded(const Animation* animation) {
animation_callback_->Run();
}
void DraggedTabGtk::AnimationCanceled(const Animation* animation) {
AnimationEnded(animation);
}
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, private:
void DraggedTabGtk::Layout() {
if (attached_) {
gfx::Size prefsize = GetPreferredSize();
renderer_->SetBounds(gfx::Rect(0, 0, prefsize.width(), prefsize.height()));
} else {
// TODO(jhawkins): RTL layout.
// The renderer_'s width should be attached_tab_size_.width() in both LTR
// and RTL locales. Wrong width will cause the wrong positioning of the tab
// view in dragging. Please refer to http://crbug.com/6223 for details.
renderer_->SetBounds(gfx::Rect(0, 0, attached_tab_size_.width(),
attached_tab_size_.height()));
}
}
gfx::Size DraggedTabGtk::GetPreferredSize() {
if (attached_)
return attached_tab_size_;
int width = std::max(attached_tab_size_.width(), contents_size_.width()) +
kTwiceDragFrameBorderSize;
int height = attached_tab_size_.height() + kDragFrameBorderSize +
contents_size_.height();
return gfx::Size(width, height);
}
void DraggedTabGtk::ResizeContainer() {
gfx::Size size = GetPreferredSize();
gtk_window_resize(GTK_WINDOW(container_),
ScaleValue(size.width()), ScaleValue(size.height()));
Layout();
}
int DraggedTabGtk::ScaleValue(int value) {
return attached_ ? value : static_cast<int>(value * kScalingFactor);
}
gfx::Rect DraggedTabGtk::bounds() const {
gint x, y, width, height;
gtk_window_get_position(GTK_WINDOW(container_), &x, &y);
gtk_window_get_size(GTK_WINDOW(container_), &width, &height);
return gfx::Rect(x, y, width, height);
}
void DraggedTabGtk::SetContainerColorMap() {
GdkScreen* screen = gtk_widget_get_screen(container_);
GdkColormap* colormap = gdk_screen_get_rgba_colormap(screen);
// If rgba is not available, use rgb instead.
if (!colormap)
colormap = gdk_screen_get_rgb_colormap(screen);
gtk_widget_set_colormap(container_, colormap);
}
void DraggedTabGtk::SetContainerTransparency() {
cairo_t* cairo_context = gdk_cairo_create(container_->window);
if (!cairo_context)
return;
// Make the background of the dragged tab window fully transparent. All of
// the content of the window (child widgets) will be completely opaque.
gfx::Size size = bounds().size();
cairo_scale(cairo_context, static_cast<double>(size.width()),
static_cast<double>(size.height()));
cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);
cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);
cairo_paint(cairo_context);
cairo_destroy(cairo_context);
}
void DraggedTabGtk::SetContainerShapeMask(GdkPixbuf* pixbuf) {
// Create a 1bpp bitmap the size of |container_|.
gfx::Size size = bounds().size();
GdkPixmap* pixmap = gdk_pixmap_new(NULL, size.width(), size.height(), 1);
cairo_t* cairo_context = gdk_cairo_create(GDK_DRAWABLE(pixmap));
// Set the transparency.
cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);
// Blit the rendered bitmap into a pixmap. Any pixel set in the pixmap will
// be opaque in the container window.
cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);
if (!attached_)
cairo_scale(cairo_context, kScalingFactor, kScalingFactor);
gdk_cairo_set_source_pixbuf(cairo_context, pixbuf, 0, 0);
cairo_paint(cairo_context);
if (!attached_) {
// Make the render area depiction opaque (leaving enough room for the
// border).
cairo_identity_matrix(cairo_context);
cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 1.0f);
int tab_height = kScalingFactor * gdk_pixbuf_get_height(pixbuf) -
kDragFrameBorderSize;
cairo_rectangle(cairo_context,
0, tab_height,
size.width(), size.height() - tab_height);
cairo_fill(cairo_context);
}
cairo_destroy(cairo_context);
// Set the shape mask.
gdk_window_shape_combine_mask(container_->window, pixmap, 0, 0);
g_object_unref(pixmap);
}
GdkPixbuf* DraggedTabGtk::PaintTab() {
SkBitmap bitmap = renderer_->PaintBitmap();
return gfx::GdkPixbufFromSkBitmap(&bitmap);
}
// static
gboolean DraggedTabGtk::OnExposeEvent(GtkWidget* widget,
GdkEventExpose* event,
DraggedTabGtk* dragged_tab) {
GdkPixbuf* pixbuf = dragged_tab->PaintTab();
if (gtk_util::IsScreenComposited()) {
dragged_tab->SetContainerTransparency();
} else {
dragged_tab->SetContainerShapeMask(pixbuf);
}
// Only used when not attached.
int tab_height = kScalingFactor * gdk_pixbuf_get_height(pixbuf);
int tab_width = kScalingFactor * gdk_pixbuf_get_width(pixbuf);
// Draw the render area.
if (dragged_tab->backing_store_ && !dragged_tab->attached_) {
// This leaves room for the border.
dragged_tab->backing_store_->PaintToRect(
gfx::Rect(kDragFrameBorderSize, tab_height,
widget->allocation.width - kTwiceDragFrameBorderSize,
widget->allocation.height - tab_height -
kDragFrameBorderSize),
GDK_DRAWABLE(widget->window));
}
cairo_t* cr = gdk_cairo_create(GDK_DRAWABLE(widget->window));
// Draw the border.
if (!dragged_tab->attached_) {
cairo_set_line_width(cr, kDragFrameBorderSize);
cairo_set_source_rgb(cr, kDraggedTabBorderColor[0],
kDraggedTabBorderColor[1],
kDraggedTabBorderColor[2]);
// |offset| is the distance from the edge of the image to the middle of
// the border line.
double offset = kDragFrameBorderSize / 2.0 - 0.5;
double left_x = offset;
double top_y = tab_height - kDragFrameBorderSize + offset;
double right_x = widget->allocation.width - offset;
double bottom_y = widget->allocation.height - offset;
double middle_x = tab_width + offset;
// We don't use cairo_rectangle() because we don't want to draw the border
// under the tab itself.
cairo_move_to(cr, left_x, top_y);
cairo_line_to(cr, left_x, bottom_y);
cairo_line_to(cr, right_x, bottom_y);
cairo_line_to(cr, right_x, top_y);
cairo_line_to(cr, middle_x, top_y);
cairo_stroke(cr);
}
// Draw the tab.
if (!dragged_tab->attached_)
cairo_scale(cr, kScalingFactor, kScalingFactor);
gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);
cairo_paint(cr);
cairo_destroy(cr);
g_object_unref(pixbuf);
// We've already drawn the tab, so don't propagate the expose-event signal.
return TRUE;
}
|
Remove two calls to Update that are unnecessary. When we layout the dragged tab, gtk will emit an expose-event signal for us if the widget changes size.
|
gtk: Remove two calls to Update that are unnecessary. When we layout the dragged tab, gtk will emit an expose-event signal for us if the widget changes size.
BUG=none
TEST=Drag a tab out of the browser. The tab should be sized and shown properly.
Review URL: http://codereview.chromium.org/149703
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@20791 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
479c0872c85513f61aeddaadff7e3b673ee11701
|
chrome/browser/gtk/tabs/dragged_tab_gtk.cc
|
chrome/browser/gtk/tabs/dragged_tab_gtk.cc
|
// Copyright (c) 2009 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/browser/gtk/tabs/dragged_tab_gtk.h"
#include <gdk/gdk.h>
#include "app/gfx/canvas.h"
#include "app/gfx/gtk_util.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/gtk/tabs/tab_renderer_gtk.h"
#include "third_party/skia/include/core/SkShader.h"
namespace {
// The size of the dragged window frame.
const int kDragFrameBorderSize = 2;
const int kTwiceDragFrameBorderSize = 2 * kDragFrameBorderSize;
// Used to scale the dragged window sizes.
const float kScalingFactor = 0.5;
const int kAnimateToBoundsDurationMs = 150;
bool IsScreenComposited() {
GdkScreen* screen = gdk_screen_get_default();
return gdk_screen_is_composited(screen) == TRUE;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, public:
DraggedTabGtk::DraggedTabGtk(TabContents* datasource,
const gfx::Point& mouse_tab_offset,
const gfx::Size& contents_size)
: renderer_(new TabRendererGtk),
attached_(false),
mouse_tab_offset_(mouse_tab_offset),
attached_tab_size_(TabRendererGtk::GetMinimumSelectedSize()),
contents_size_(contents_size),
close_animation_(this) {
renderer_->UpdateData(datasource, false);
container_ = gtk_window_new(GTK_WINDOW_POPUP);
SetContainerColorMap();
gtk_widget_set_app_paintable(container_, TRUE);
g_signal_connect(G_OBJECT(container_), "expose-event",
G_CALLBACK(OnExposeEvent), this);
gtk_widget_add_events(container_, GDK_STRUCTURE_MASK);
gtk_container_add(GTK_CONTAINER(container_), renderer_->widget());
gtk_widget_show_all(container_);
}
DraggedTabGtk::~DraggedTabGtk() {
gtk_widget_destroy(container_);
}
void DraggedTabGtk::MoveTo(const gfx::Point& screen_point) {
int x = screen_point.x() + mouse_tab_offset_.x() -
ScaleValue(mouse_tab_offset_.x());
int y = screen_point.y() + mouse_tab_offset_.y() -
ScaleValue(mouse_tab_offset_.y());
gtk_window_move(GTK_WINDOW(container_), x, y);
}
void DraggedTabGtk::Attach(int selected_width) {
attached_ = true;
attached_tab_size_.set_width(selected_width);
ResizeContainer();
Update();
}
void DraggedTabGtk::Update() {
gtk_widget_queue_draw(container_);
}
void DraggedTabGtk::AnimateToBounds(const gfx::Rect& bounds,
AnimateToBoundsCallback* callback) {
animation_callback_.reset(callback);
gint x, y, width, height;
gdk_window_get_origin(container_->window, &x, &y);
gdk_window_get_geometry(container_->window, NULL, NULL,
&width, &height, NULL);
animation_start_bounds_ = gfx::Rect(x, y, width, height);
animation_end_bounds_ = bounds;
close_animation_.SetSlideDuration(kAnimateToBoundsDurationMs);
close_animation_.SetTweenType(SlideAnimation::EASE_OUT);
if (!close_animation_.IsShowing()) {
close_animation_.Reset();
close_animation_.Show();
}
}
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, AnimationDelegate implementation:
void DraggedTabGtk::AnimationProgressed(const Animation* animation) {
int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());
int x = animation_start_bounds_.x() +
static_cast<int>(delta_x * animation->GetCurrentValue());
int y = animation_end_bounds_.y();
gdk_window_move(container_->window, x, y);
}
void DraggedTabGtk::AnimationEnded(const Animation* animation) {
animation_callback_->Run();
}
void DraggedTabGtk::AnimationCanceled(const Animation* animation) {
AnimationEnded(animation);
}
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, private:
gfx::Size DraggedTabGtk::GetPreferredSize() {
if (attached_)
return attached_tab_size_;
int width = std::max(attached_tab_size_.width(), contents_size_.width()) +
kTwiceDragFrameBorderSize;
int height = attached_tab_size_.height() + kDragFrameBorderSize +
contents_size_.height();
return gfx::Size(width, height);
}
void DraggedTabGtk::ResizeContainer() {
gfx::Size size = GetPreferredSize();
gtk_window_resize(GTK_WINDOW(container_),
ScaleValue(size.width()), ScaleValue(size.height()));
gfx::Rect bounds = renderer_->bounds();
bounds.set_width(ScaleValue(size.width()));
bounds.set_height(ScaleValue(size.height()));
renderer_->SetBounds(bounds);
Update();
}
int DraggedTabGtk::ScaleValue(int value) {
return attached_ ? value : static_cast<int>(value * kScalingFactor);
}
gfx::Rect DraggedTabGtk::bounds() const {
gint x, y, width, height;
gtk_window_get_position(GTK_WINDOW(container_), &x, &y);
gtk_window_get_size(GTK_WINDOW(container_), &width, &height);
return gfx::Rect(x, y, width, height);
}
void DraggedTabGtk::SetContainerColorMap() {
GdkScreen* screen = gtk_widget_get_screen(container_);
GdkColormap* colormap = gdk_screen_get_rgba_colormap(screen);
// If rgba is not available, use rgb instead.
if (!colormap)
colormap = gdk_screen_get_rgb_colormap(screen);
gtk_widget_set_colormap(container_, colormap);
}
void DraggedTabGtk::SetContainerTransparency() {
cairo_t* cairo_context = gdk_cairo_create(container_->window);
if (!cairo_context)
return;
// Make the background of the dragged tab window fully transparent. All of
// the content of the window (child widgets) will be completely opaque.
gfx::Size size = bounds().size();
cairo_scale(cairo_context, static_cast<double>(size.width()),
static_cast<double>(size.height()));
cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);
cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);
cairo_paint(cairo_context);
cairo_destroy(cairo_context);
}
void DraggedTabGtk::SetContainerShapeMask() {
// Render the tab as a bitmap.
SkBitmap tab = renderer_->PaintBitmap();
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&tab);
// Create a 1bpp bitmap the size of |container_|.
gfx::Size size = bounds().size();
GdkPixmap* pixmap = gdk_pixmap_new(NULL, size.width(), size.height(), 1);
cairo_t* cairo_context = gdk_cairo_create(GDK_DRAWABLE(pixmap));
// Set the transparency.
cairo_set_source_rgba(cairo_context, 1, 1, 1, 0);
// Blit the rendered bitmap into a pixmap. Any pixel set in the pixmap will
// be opaque in the container window.
cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);
gdk_cairo_set_source_pixbuf(cairo_context, pixbuf, 0, 0);
cairo_paint(cairo_context);
cairo_destroy(cairo_context);
// Set the shape mask.
gdk_window_shape_combine_mask(container_->window, pixmap, 0, 0);
g_object_unref(pixbuf);
g_object_unref(pixmap);
}
// static
gboolean DraggedTabGtk::OnExposeEvent(GtkWidget* widget,
GdkEventExpose* event,
DraggedTabGtk* dragged_tab) {
printf("OnExposeEvent\n");
if (IsScreenComposited()) {
dragged_tab->SetContainerTransparency();
} else {
dragged_tab->SetContainerShapeMask();
}
return FALSE;
}
|
// Copyright (c) 2009 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/browser/gtk/tabs/dragged_tab_gtk.h"
#include <gdk/gdk.h>
#include "app/gfx/canvas.h"
#include "app/gfx/gtk_util.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/gtk/tabs/tab_renderer_gtk.h"
#include "third_party/skia/include/core/SkShader.h"
namespace {
// The size of the dragged window frame.
const int kDragFrameBorderSize = 2;
const int kTwiceDragFrameBorderSize = 2 * kDragFrameBorderSize;
// Used to scale the dragged window sizes.
const float kScalingFactor = 0.5;
const int kAnimateToBoundsDurationMs = 150;
bool IsScreenComposited() {
GdkScreen* screen = gdk_screen_get_default();
return gdk_screen_is_composited(screen) == TRUE;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, public:
DraggedTabGtk::DraggedTabGtk(TabContents* datasource,
const gfx::Point& mouse_tab_offset,
const gfx::Size& contents_size)
: renderer_(new TabRendererGtk),
attached_(false),
mouse_tab_offset_(mouse_tab_offset),
attached_tab_size_(TabRendererGtk::GetMinimumSelectedSize()),
contents_size_(contents_size),
close_animation_(this) {
renderer_->UpdateData(datasource, false);
container_ = gtk_window_new(GTK_WINDOW_POPUP);
SetContainerColorMap();
gtk_widget_set_app_paintable(container_, TRUE);
g_signal_connect(G_OBJECT(container_), "expose-event",
G_CALLBACK(OnExposeEvent), this);
gtk_widget_add_events(container_, GDK_STRUCTURE_MASK);
gtk_container_add(GTK_CONTAINER(container_), renderer_->widget());
gtk_widget_show_all(container_);
}
DraggedTabGtk::~DraggedTabGtk() {
gtk_widget_destroy(container_);
}
void DraggedTabGtk::MoveTo(const gfx::Point& screen_point) {
int x = screen_point.x() + mouse_tab_offset_.x() -
ScaleValue(mouse_tab_offset_.x());
int y = screen_point.y() + mouse_tab_offset_.y() -
ScaleValue(mouse_tab_offset_.y());
gtk_window_move(GTK_WINDOW(container_), x, y);
}
void DraggedTabGtk::Attach(int selected_width) {
attached_ = true;
attached_tab_size_.set_width(selected_width);
ResizeContainer();
Update();
}
void DraggedTabGtk::Update() {
gtk_widget_queue_draw(container_);
}
void DraggedTabGtk::AnimateToBounds(const gfx::Rect& bounds,
AnimateToBoundsCallback* callback) {
animation_callback_.reset(callback);
gint x, y, width, height;
gdk_window_get_origin(container_->window, &x, &y);
gdk_window_get_geometry(container_->window, NULL, NULL,
&width, &height, NULL);
animation_start_bounds_ = gfx::Rect(x, y, width, height);
animation_end_bounds_ = bounds;
close_animation_.SetSlideDuration(kAnimateToBoundsDurationMs);
close_animation_.SetTweenType(SlideAnimation::EASE_OUT);
if (!close_animation_.IsShowing()) {
close_animation_.Reset();
close_animation_.Show();
}
}
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, AnimationDelegate implementation:
void DraggedTabGtk::AnimationProgressed(const Animation* animation) {
int delta_x = (animation_end_bounds_.x() - animation_start_bounds_.x());
int x = animation_start_bounds_.x() +
static_cast<int>(delta_x * animation->GetCurrentValue());
int y = animation_end_bounds_.y();
gdk_window_move(container_->window, x, y);
}
void DraggedTabGtk::AnimationEnded(const Animation* animation) {
animation_callback_->Run();
}
void DraggedTabGtk::AnimationCanceled(const Animation* animation) {
AnimationEnded(animation);
}
////////////////////////////////////////////////////////////////////////////////
// DraggedTabGtk, private:
gfx::Size DraggedTabGtk::GetPreferredSize() {
if (attached_)
return attached_tab_size_;
int width = std::max(attached_tab_size_.width(), contents_size_.width()) +
kTwiceDragFrameBorderSize;
int height = attached_tab_size_.height() + kDragFrameBorderSize +
contents_size_.height();
return gfx::Size(width, height);
}
void DraggedTabGtk::ResizeContainer() {
gfx::Size size = GetPreferredSize();
gtk_window_resize(GTK_WINDOW(container_),
ScaleValue(size.width()), ScaleValue(size.height()));
gfx::Rect bounds = renderer_->bounds();
bounds.set_width(ScaleValue(size.width()));
bounds.set_height(ScaleValue(size.height()));
renderer_->SetBounds(bounds);
Update();
}
int DraggedTabGtk::ScaleValue(int value) {
return attached_ ? value : static_cast<int>(value * kScalingFactor);
}
gfx::Rect DraggedTabGtk::bounds() const {
gint x, y, width, height;
gtk_window_get_position(GTK_WINDOW(container_), &x, &y);
gtk_window_get_size(GTK_WINDOW(container_), &width, &height);
return gfx::Rect(x, y, width, height);
}
void DraggedTabGtk::SetContainerColorMap() {
GdkScreen* screen = gtk_widget_get_screen(container_);
GdkColormap* colormap = gdk_screen_get_rgba_colormap(screen);
// If rgba is not available, use rgb instead.
if (!colormap)
colormap = gdk_screen_get_rgb_colormap(screen);
gtk_widget_set_colormap(container_, colormap);
}
void DraggedTabGtk::SetContainerTransparency() {
cairo_t* cairo_context = gdk_cairo_create(container_->window);
if (!cairo_context)
return;
// Make the background of the dragged tab window fully transparent. All of
// the content of the window (child widgets) will be completely opaque.
gfx::Size size = bounds().size();
cairo_scale(cairo_context, static_cast<double>(size.width()),
static_cast<double>(size.height()));
cairo_set_source_rgba(cairo_context, 1.0f, 1.0f, 1.0f, 0.0f);
cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);
cairo_paint(cairo_context);
cairo_destroy(cairo_context);
}
void DraggedTabGtk::SetContainerShapeMask() {
// Render the tab as a bitmap.
SkBitmap tab = renderer_->PaintBitmap();
GdkPixbuf* pixbuf = gfx::GdkPixbufFromSkBitmap(&tab);
// Create a 1bpp bitmap the size of |container_|.
gfx::Size size = bounds().size();
GdkPixmap* pixmap = gdk_pixmap_new(NULL, size.width(), size.height(), 1);
cairo_t* cairo_context = gdk_cairo_create(GDK_DRAWABLE(pixmap));
// Set the transparency.
cairo_set_source_rgba(cairo_context, 1, 1, 1, 0);
// Blit the rendered bitmap into a pixmap. Any pixel set in the pixmap will
// be opaque in the container window.
cairo_set_operator(cairo_context, CAIRO_OPERATOR_SOURCE);
gdk_cairo_set_source_pixbuf(cairo_context, pixbuf, 0, 0);
cairo_paint(cairo_context);
cairo_destroy(cairo_context);
// Set the shape mask.
gdk_window_shape_combine_mask(container_->window, pixmap, 0, 0);
g_object_unref(pixbuf);
g_object_unref(pixmap);
}
// static
gboolean DraggedTabGtk::OnExposeEvent(GtkWidget* widget,
GdkEventExpose* event,
DraggedTabGtk* dragged_tab) {
if (IsScreenComposited()) {
dragged_tab->SetContainerTransparency();
} else {
dragged_tab->SetContainerShapeMask();
}
return FALSE;
}
|
Remove a debugging statement that was left in my last commit.
|
Remove a debugging statement that was left in my last commit.
TBR
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@16440 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
jaruba/chromium.src,dednal/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,Just-D/chromium-1,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,Chilledheart/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,dednal/chromium.src,dednal/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,ltilve/chromium,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,patrickm/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,rogerwang/chromium,ltilve/chromium,hujiajie/pa-chromium,dednal/chromium.src,rogerwang/chromium,jaruba/chromium.src,nacl-webkit/chrome_deps,Jonekee/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,rogerwang/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,rogerwang/chromium,hujiajie/pa-chromium,hujiajie/pa-chromium,dednal/chromium.src,Jonekee/chromium.src,zcbenz/cefode-chromium,dushu1203/chromium.src,dednal/chromium.src,keishi/chromium,keishi/chromium,keishi/chromium,hujiajie/pa-chromium,ondra-novak/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,ltilve/chromium,hgl888/chromium-crosswalk,patrickm/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,markYoungH/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,rogerwang/chromium,robclark/chromium,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,rogerwang/chromium,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,ondra-novak/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,robclark/chromium,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,Just-D/chromium-1,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,robclark/chromium,ltilve/chromium,ondra-novak/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,keishi/chromium,jaruba/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,rogerwang/chromium,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,dednal/chromium.src,junmin-zhu/chromium-rivertrail,ltilve/chromium,keishi/chromium,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,keishi/chromium,M4sse/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,Just-D/chromium-1,littlstar/chromium.src,timopulkkinen/BubbleFish,ondra-novak/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,keishi/chromium,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,markYoungH/chromium.src,keishi/chromium,jaruba/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,patrickm/chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,keishi/chromium,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,Chilledheart/chromium,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,markYoungH/chromium.src,rogerwang/chromium,robclark/chromium,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,jaruba/chromium.src,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,anirudhSK/chromium,littlstar/chromium.src,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,M4sse/chromium.src,rogerwang/chromium,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,zcbenz/cefode-chromium,nacl-webkit/chrome_deps,littlstar/chromium.src,dednal/chromium.src,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,Jonekee/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,robclark/chromium,nacl-webkit/chrome_deps,patrickm/chromium.src,robclark/chromium,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,ondra-novak/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,timopulkkinen/BubbleFish,robclark/chromium,ltilve/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,robclark/chromium,hujiajie/pa-chromium,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,Chilledheart/chromium,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Just-D/chromium-1
|
c5907005aca35d33eaf36ad2dde6f94d657d9711
|
TelepathyQt/debug-receiver.cpp
|
TelepathyQt/debug-receiver.cpp
|
/**
* This file is part of TelepathyQt
*
* @copyright Copyright (C) 2011-2012 Collabora Ltd. <http://www.collabora.co.uk/>
* @license LGPL 2.1
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt/DebugReceiver>
#include "TelepathyQt/_gen/debug-receiver.moc.hpp"
#include "TelepathyQt/_gen/cli-debug-receiver-body.hpp"
#include "TelepathyQt/_gen/cli-debug-receiver.moc.hpp"
#include "TelepathyQt/debug-internal.h"
#include <TelepathyQt/Constants>
#include <TelepathyQt/PendingDebugMessageList>
#include <TelepathyQt/PendingFailure>
#include <TelepathyQt/PendingVariantMap>
#include <TelepathyQt/ReadinessHelper>
namespace Tp
{
struct TP_QT_NO_EXPORT DebugReceiver::Private
{
Private(DebugReceiver *parent);
static void introspectCore(Private *self);
DebugReceiver *parent;
Client::DebugInterface *baseInterface;
};
DebugReceiver::Private::Private(DebugReceiver *parent)
: parent(parent),
baseInterface(new Client::DebugInterface(parent))
{
ReadinessHelper::Introspectables introspectables;
ReadinessHelper::Introspectable introspectableCore(
QSet<uint>() << 0, // makesSenseForStatuses
Features(), // dependsOnFeatures (core)
QStringList(), // dependsOnInterfaces
(ReadinessHelper::IntrospectFunc) &DebugReceiver::Private::introspectCore,
this);
introspectables[DebugReceiver::FeatureCore] = introspectableCore;
parent->readinessHelper()->addIntrospectables(introspectables);
}
void DebugReceiver::Private::introspectCore(DebugReceiver::Private *self)
{
//this is done only to verify that the object exists...
PendingVariantMap *op = self->baseInterface->requestAllProperties();
self->parent->connect(op,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onRequestAllPropertiesFinished(Tp::PendingOperation*)));
}
/**
* \class DebugReceiver
* \ingroup clientsideproxies
* \headerfile TelepathyQt/debug-receiver.h <TelepathyQt/DebugReceiver>
*
* \brief The DebugReceiver class provides a D-Bus proxy for a Telepathy
* Debug object.
*
* A Debug object provides debugging messages from services.
*/
/**
* Feature representing the core that needs to become ready to make the DebugReceiver
* object usable.
*
* Note that this feature must be enabled in order to use most DebugReceiver methods.
* See specific methods documentation for more details.
*
* When calling isReady(), becomeReady(), this feature is implicitly added
* to the requested features.
*/
const Feature DebugReceiver::FeatureCore = Feature(QLatin1String(DebugReceiver::staticMetaObject.className()), 0, true);
DebugReceiverPtr DebugReceiver::create(const QString &busName, const QDBusConnection &bus)
{
return DebugReceiverPtr(new DebugReceiver(bus, busName));
}
DebugReceiver::DebugReceiver(const QDBusConnection &bus, const QString &busName)
: StatefulDBusProxy(bus, busName, TP_QT_DEBUG_OBJECT_PATH, DebugReceiver::FeatureCore),
mPriv(new Private(this))
{
}
DebugReceiver::~DebugReceiver()
{
delete mPriv;
}
PendingDebugMessageList *DebugReceiver::fetchMessages()
{
return new PendingDebugMessageList(mPriv->baseInterface->GetMessages(),
DebugReceiverPtr(this));
}
PendingOperation *DebugReceiver::setMonitoringEnabled(bool enabled)
{
if (!isReady()) {
warning() << "DebugReceiver::setMonitoringEnabled called without DebugReceiver being ready";
return new PendingFailure(TP_QT_ERROR_NOT_AVAILABLE,
QLatin1String("FeatureCore is not ready"), DebugReceiverPtr(this));
}
return mPriv->baseInterface->setPropertyEnabled(enabled);
}
void DebugReceiver::onRequestAllPropertiesFinished(Tp::PendingOperation *op)
{
if (op->isError()) {
readinessHelper()->setIntrospectCompleted(
FeatureCore, false, op->errorName(), op->errorMessage());
} else {
connect(mPriv->baseInterface,
SIGNAL(NewDebugMessage(double,QString,uint,QString)),
SLOT(onNewDebugMessage(double,QString,uint,QString)));
readinessHelper()->setIntrospectCompleted(FeatureCore, true);
}
}
void DebugReceiver::onNewDebugMessage(double time, const QString &domain,
uint level, const QString &message)
{
DebugMessage msg;
msg.timestamp = time;
msg.domain = domain;
msg.level = level;
msg.message = message;
emit newDebugMessage(msg);
}
} // Tp
|
/**
* This file is part of TelepathyQt
*
* @copyright Copyright (C) 2011-2012 Collabora Ltd. <http://www.collabora.co.uk/>
* @license LGPL 2.1
*
* 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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt/DebugReceiver>
#include "TelepathyQt/_gen/debug-receiver.moc.hpp"
#include "TelepathyQt/_gen/cli-debug-receiver-body.hpp"
#include "TelepathyQt/_gen/cli-debug-receiver.moc.hpp"
#include "TelepathyQt/debug-internal.h"
#include <TelepathyQt/Constants>
#include <TelepathyQt/PendingDebugMessageList>
#include <TelepathyQt/PendingFailure>
#include <TelepathyQt/PendingVariantMap>
#include <TelepathyQt/ReadinessHelper>
namespace Tp
{
struct TP_QT_NO_EXPORT DebugReceiver::Private
{
Private(DebugReceiver *parent);
static void introspectCore(Private *self);
DebugReceiver *parent;
Client::DebugInterface *baseInterface;
};
DebugReceiver::Private::Private(DebugReceiver *parent)
: parent(parent),
baseInterface(new Client::DebugInterface(parent))
{
ReadinessHelper::Introspectables introspectables;
ReadinessHelper::Introspectable introspectableCore(
QSet<uint>() << 0, // makesSenseForStatuses
Features(), // dependsOnFeatures (core)
QStringList(), // dependsOnInterfaces
(ReadinessHelper::IntrospectFunc) &DebugReceiver::Private::introspectCore,
this);
introspectables[DebugReceiver::FeatureCore] = introspectableCore;
parent->readinessHelper()->addIntrospectables(introspectables);
}
void DebugReceiver::Private::introspectCore(DebugReceiver::Private *self)
{
// this is done only to verify that the object exists...
PendingVariantMap *op = self->baseInterface->requestAllProperties();
self->parent->connect(op,
SIGNAL(finished(Tp::PendingOperation*)),
SLOT(onRequestAllPropertiesFinished(Tp::PendingOperation*)));
}
/**
* \class DebugReceiver
* \ingroup clientsideproxies
* \headerfile TelepathyQt/debug-receiver.h <TelepathyQt/DebugReceiver>
*
* \brief The DebugReceiver class provides a D-Bus proxy for a Telepathy
* Debug object.
*
* A Debug object provides debugging messages from services.
*/
/**
* Feature representing the core that needs to become ready to make the DebugReceiver
* object usable.
*
* Note that this feature must be enabled in order to use most DebugReceiver methods.
* See specific methods documentation for more details.
*
* When calling isReady(), becomeReady(), this feature is implicitly added
* to the requested features.
*/
const Feature DebugReceiver::FeatureCore = Feature(QLatin1String(DebugReceiver::staticMetaObject.className()), 0, true);
DebugReceiverPtr DebugReceiver::create(const QString &busName, const QDBusConnection &bus)
{
return DebugReceiverPtr(new DebugReceiver(bus, busName));
}
DebugReceiver::DebugReceiver(const QDBusConnection &bus, const QString &busName)
: StatefulDBusProxy(bus, busName, TP_QT_DEBUG_OBJECT_PATH, DebugReceiver::FeatureCore),
mPriv(new Private(this))
{
}
DebugReceiver::~DebugReceiver()
{
delete mPriv;
}
PendingDebugMessageList *DebugReceiver::fetchMessages()
{
return new PendingDebugMessageList(mPriv->baseInterface->GetMessages(),
DebugReceiverPtr(this));
}
PendingOperation *DebugReceiver::setMonitoringEnabled(bool enabled)
{
if (!isReady()) {
warning() << "DebugReceiver::setMonitoringEnabled called without DebugReceiver being ready";
return new PendingFailure(TP_QT_ERROR_NOT_AVAILABLE,
QLatin1String("FeatureCore is not ready"), DebugReceiverPtr(this));
}
return mPriv->baseInterface->setPropertyEnabled(enabled);
}
void DebugReceiver::onRequestAllPropertiesFinished(Tp::PendingOperation *op)
{
if (op->isError()) {
readinessHelper()->setIntrospectCompleted(
FeatureCore, false, op->errorName(), op->errorMessage());
} else {
connect(mPriv->baseInterface,
SIGNAL(NewDebugMessage(double,QString,uint,QString)),
SLOT(onNewDebugMessage(double,QString,uint,QString)));
readinessHelper()->setIntrospectCompleted(FeatureCore, true);
}
}
void DebugReceiver::onNewDebugMessage(double time, const QString &domain,
uint level, const QString &message)
{
DebugMessage msg;
msg.timestamp = time;
msg.domain = domain;
msg.level = level;
msg.message = message;
emit newDebugMessage(msg);
}
} // Tp
|
Add spaces in comments
|
DebugReceiver: Add spaces in comments
|
C++
|
lgpl-2.1
|
tiagosh/telepathy-qt,special/telepathy-qt-upstream,tiagosh/telepathy-qt,anantkamath/telepathy-qt,TelepathyIM/telepathy-qt,TelepathyQt/telepathy-qt,special/telepathy-qt-upstream,detrout/telepathy-qt,tiagosh/telepathy-qt,TelepathyQt/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,TelepathyIM/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,TelepathyQt/telepathy-qt,detrout/telepathy-qt,anantkamath/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt4,TelepathyIM/telepathy-qt,detrout/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,anantkamath/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,TelepathyIM/telepathy-qt,TelepathyIM/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,tiagosh/telepathy-qt,freedesktop-unofficial-mirror/telepathy__telepathy-qt,special/telepathy-qt-upstream,TelepathyQt/telepathy-qt
|
2caa29992597c3bb507a2bb996248b966d7edf70
|
chrome/renderer/pepper_scrollbar_widget.cc
|
chrome/renderer/pepper_scrollbar_widget.cc
|
// Copyright (c) 2010 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/renderer/pepper_scrollbar_widget.h"
#include "base/basictypes.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "chrome/renderer/pepper_devices.h"
#include "skia/ext/platform_canvas.h"
#include "skia/ext/platform_device.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScrollBar.h"
#include "webkit/glue/plugins/plugin_instance.h"
using WebKit::WebInputEvent;
using WebKit::WebKeyboardEvent;
using WebKit::WebMouseEvent;
using WebKit::WebMouseWheelEvent;
using WebKit::WebRect;
using WebKit::WebScrollbar;
using WebKit::WebVector;
// Anonymous namespace for functions converting NPAPI to WebInputEvents types.
namespace {
WebKeyboardEvent BuildKeyEvent(const NPPepperEvent& event) {
WebKeyboardEvent key_event;
switch (event.type) {
case NPEventType_RawKeyDown:
key_event.type = WebInputEvent::RawKeyDown;
break;
case NPEventType_KeyDown:
key_event.type = WebInputEvent::KeyDown;
break;
case NPEventType_KeyUp:
key_event.type = WebInputEvent::KeyUp;
break;
}
key_event.timeStampSeconds = event.timeStampSeconds;
key_event.modifiers = event.u.key.modifier;
key_event.windowsKeyCode = event.u.key.normalizedKeyCode;
return key_event;
}
WebKeyboardEvent BuildCharEvent(const NPPepperEvent& event) {
WebKeyboardEvent key_event;
key_event.type = WebInputEvent::Char;
key_event.timeStampSeconds = event.timeStampSeconds;
key_event.modifiers = event.u.character.modifier;
// For consistency, check that the sizes of the texts agree.
DCHECK(sizeof(event.u.character.text) == sizeof(key_event.text));
DCHECK(sizeof(event.u.character.unmodifiedText) ==
sizeof(key_event.unmodifiedText));
for (size_t i = 0; i < WebKeyboardEvent::textLengthCap; ++i) {
key_event.text[i] = event.u.character.text[i];
key_event.unmodifiedText[i] = event.u.character.unmodifiedText[i];
}
return key_event;
}
WebMouseEvent BuildMouseEvent(const NPPepperEvent& event) {
WebMouseEvent mouse_event;
switch (event.type) {
case NPEventType_MouseDown:
mouse_event.type = WebInputEvent::MouseDown;
break;
case NPEventType_MouseUp:
mouse_event.type = WebInputEvent::MouseUp;
break;
case NPEventType_MouseMove:
mouse_event.type = WebInputEvent::MouseMove;
break;
case NPEventType_MouseEnter:
mouse_event.type = WebInputEvent::MouseEnter;
break;
case NPEventType_MouseLeave:
mouse_event.type = WebInputEvent::MouseLeave;
break;
}
mouse_event.timeStampSeconds = event.timeStampSeconds;
mouse_event.modifiers = event.u.mouse.modifier;
mouse_event.button = static_cast<WebMouseEvent::Button>(event.u.mouse.button);
mouse_event.x = event.u.mouse.x;
mouse_event.y = event.u.mouse.y;
mouse_event.clickCount = event.u.mouse.clickCount;
return mouse_event;
}
WebMouseWheelEvent BuildMouseWheelEvent(const NPPepperEvent& event) {
WebMouseWheelEvent mouse_wheel_event;
mouse_wheel_event.type = WebInputEvent::MouseWheel;
mouse_wheel_event.timeStampSeconds = event.timeStampSeconds;
mouse_wheel_event.modifiers = event.u.wheel.modifier;
mouse_wheel_event.deltaX = event.u.wheel.deltaX;
mouse_wheel_event.deltaY = event.u.wheel.deltaY;
mouse_wheel_event.wheelTicksX = event.u.wheel.wheelTicksX;
mouse_wheel_event.wheelTicksY = event.u.wheel.wheelTicksY;
mouse_wheel_event.scrollByPage = event.u.wheel.scrollByPage;
return mouse_wheel_event;
}
} // namespace
PepperScrollbarWidget::PepperScrollbarWidget(
const NPScrollbarCreateParams& params) {
scrollbar_.reset(WebScrollbar::create(
static_cast<WebKit::WebScrollbarClient*>(this),
params.vertical ? WebScrollbar::Vertical : WebScrollbar::Horizontal));
AddRef();
}
PepperScrollbarWidget::~PepperScrollbarWidget() {
}
void PepperScrollbarWidget::Destroy() {
Release();
}
void PepperScrollbarWidget::Paint(Graphics2DDeviceContext* context,
const NPRect& dirty) {
gfx::Rect rect(dirty.left, dirty.top, dirty.right - dirty.left,
dirty.bottom - dirty.top);
#if defined(OS_WIN) || defined(OS_LINUX)
scrollbar_->paint(context->canvas(), rect);
#elif defined(OS_MACOSX)
// TODO(port)
#endif
dirty_rect_ = dirty_rect_.Subtract(rect);
}
bool PepperScrollbarWidget::HandleEvent(const NPPepperEvent& event) {
bool rv = false;
switch (event.type) {
case NPEventType_Undefined:
return false;
case NPEventType_MouseDown:
case NPEventType_MouseUp:
case NPEventType_MouseMove:
case NPEventType_MouseEnter:
case NPEventType_MouseLeave:
rv = scrollbar_->handleInputEvent(BuildMouseEvent(event));
break;
case NPEventType_MouseWheel:
rv = scrollbar_->handleInputEvent(BuildMouseWheelEvent(event));
break;
case NPEventType_RawKeyDown:
case NPEventType_KeyDown:
case NPEventType_KeyUp:
rv = scrollbar_->handleInputEvent(BuildKeyEvent(event));
break;
case NPEventType_Char:
rv = scrollbar_->handleInputEvent(BuildCharEvent(event));
break;
case NPEventType_Minimize:
case NPEventType_Focus:
case NPEventType_Device:
// NOTIMPLEMENTED();
break;
}
return rv;
}
void PepperScrollbarWidget::GetProperty(
NPWidgetProperty property, void* value) {
switch (property) {
case NPWidgetPropertyLocation: {
NPRect* rv = static_cast<NPRect*>(value);
rv->left = location_.x();
rv->top = location_.y();
rv->right = location_.right();
rv->bottom = location_.bottom();
break;
}
case NPWidgetPropertyDirtyRect: {
NPRect* rv = reinterpret_cast<NPRect*>(value);
rv->left = dirty_rect_.x();
rv->top = dirty_rect_.y();
rv->right = dirty_rect_.right();
rv->bottom = dirty_rect_.bottom();
break;
}
case NPWidgetPropertyScrollbarThickness: {
int32* rv = static_cast<int32*>(value);
*rv = WebScrollbar::defaultThickness();
break;
}
case NPWidgetPropertyScrollbarValue: {
int32* rv = static_cast<int32*>(value);
*rv = scrollbar_->value();
break;
}
default:
NOTREACHED();
break;
}
}
void PepperScrollbarWidget::SetProperty(
NPWidgetProperty property, void* value) {
switch (property) {
case NPWidgetPropertyLocation: {
NPRect* r = static_cast<NPRect*>(value);
location_ = gfx::Rect(
r->left, r->top, r->right - r->left, r->bottom - r->top);
scrollbar_->setLocation(location_);
break;
}
case NPWidgetPropertyScrollbarValue: {
int32* position = static_cast<int*>(value);
scrollbar_->setValue(*position);
break;
}
case NPWidgetPropertyScrollbarDocumentSize: {
int32* total_length = static_cast<int32*>(value);
scrollbar_->setDocumentSize(*total_length);
break;
}
case NPWidgetPropertyScrollbarTickMarks: {
NPScrollbarTickMarks* tickmarks =
static_cast<NPScrollbarTickMarks*>(value);
tickmarks_.resize(tickmarks->count);
for (uint32 i = 0; i < tickmarks->count; ++i) {
WebRect rect(
tickmarks->tickmarks[i].left,
tickmarks->tickmarks[i].top,
tickmarks->tickmarks[i].right - tickmarks->tickmarks[i].left,
tickmarks->tickmarks[i].bottom - tickmarks->tickmarks[i].top);
tickmarks_[i] = rect;
}
dirty_rect_ = location_;
NotifyInvalidate();
break;
}
case NPWidgetPropertyScrollbarScrollByLine:
case NPWidgetPropertyScrollbarScrollByPage:
case NPWidgetPropertyScrollbarScrollByDocument:
case NPWidgetPropertyScrollbarScrollByPixels: {
bool forward;
float multiplier = 1.0;
WebScrollbar::ScrollGranularity granularity;
if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByLine;
} else if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByPage;
} else if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByDocument;
} else {
multiplier = static_cast<float>(*static_cast<int32*>(value));
forward = multiplier >= 0;
if (multiplier < 0)
multiplier *= -1;
granularity = WebScrollbar::ScrollByPixel;
}
scrollbar_->scroll(
forward ? WebScrollbar::ScrollForward : WebScrollbar::ScrollBackward,
granularity, multiplier);
break;
}
default:
NOTREACHED();
break;
}
}
void PepperScrollbarWidget::valueChanged(WebScrollbar*) {
WidgetPropertyChanged(NPWidgetPropertyScrollbarValue);
}
void PepperScrollbarWidget::invalidateScrollbarRect(WebScrollbar*,
const WebRect& rect) {
dirty_rect_ = dirty_rect_.Union(rect);
// Can't call into the client to tell them about the invalidate right away,
// since the Scrollbar code is still in the middle of updating its internal
// state.
MessageLoop::current()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &PepperScrollbarWidget::NotifyInvalidate));
}
void PepperScrollbarWidget::getTickmarks(WebKit::WebScrollbar*,
WebVector<WebRect>* tickmarks) const {
if (tickmarks_.empty()) {
WebRect* rects = NULL;
tickmarks->assign(rects, 0);
} else {
tickmarks->assign(&tickmarks_[0], tickmarks_.size());
}
}
void PepperScrollbarWidget::NotifyInvalidate() {
if (!dirty_rect_.IsEmpty())
WidgetPropertyChanged(NPWidgetPropertyDirtyRect);
}
|
// Copyright (c) 2010 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/renderer/pepper_scrollbar_widget.h"
#include "base/basictypes.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "chrome/renderer/pepper_devices.h"
#include "skia/ext/platform_canvas.h"
#include "skia/ext/platform_device.h"
#include "third_party/WebKit/WebKit/chromium/public/WebScrollbar.h"
#include "webkit/glue/plugins/plugin_instance.h"
using WebKit::WebInputEvent;
using WebKit::WebKeyboardEvent;
using WebKit::WebMouseEvent;
using WebKit::WebMouseWheelEvent;
using WebKit::WebRect;
using WebKit::WebScrollbar;
using WebKit::WebVector;
// Anonymous namespace for functions converting NPAPI to WebInputEvents types.
namespace {
WebKeyboardEvent BuildKeyEvent(const NPPepperEvent& event) {
WebKeyboardEvent key_event;
switch (event.type) {
case NPEventType_RawKeyDown:
key_event.type = WebInputEvent::RawKeyDown;
break;
case NPEventType_KeyDown:
key_event.type = WebInputEvent::KeyDown;
break;
case NPEventType_KeyUp:
key_event.type = WebInputEvent::KeyUp;
break;
}
key_event.timeStampSeconds = event.timeStampSeconds;
key_event.modifiers = event.u.key.modifier;
key_event.windowsKeyCode = event.u.key.normalizedKeyCode;
return key_event;
}
WebKeyboardEvent BuildCharEvent(const NPPepperEvent& event) {
WebKeyboardEvent key_event;
key_event.type = WebInputEvent::Char;
key_event.timeStampSeconds = event.timeStampSeconds;
key_event.modifiers = event.u.character.modifier;
// For consistency, check that the sizes of the texts agree.
DCHECK(sizeof(event.u.character.text) == sizeof(key_event.text));
DCHECK(sizeof(event.u.character.unmodifiedText) ==
sizeof(key_event.unmodifiedText));
for (size_t i = 0; i < WebKeyboardEvent::textLengthCap; ++i) {
key_event.text[i] = event.u.character.text[i];
key_event.unmodifiedText[i] = event.u.character.unmodifiedText[i];
}
return key_event;
}
WebMouseEvent BuildMouseEvent(const NPPepperEvent& event) {
WebMouseEvent mouse_event;
switch (event.type) {
case NPEventType_MouseDown:
mouse_event.type = WebInputEvent::MouseDown;
break;
case NPEventType_MouseUp:
mouse_event.type = WebInputEvent::MouseUp;
break;
case NPEventType_MouseMove:
mouse_event.type = WebInputEvent::MouseMove;
break;
case NPEventType_MouseEnter:
mouse_event.type = WebInputEvent::MouseEnter;
break;
case NPEventType_MouseLeave:
mouse_event.type = WebInputEvent::MouseLeave;
break;
}
mouse_event.timeStampSeconds = event.timeStampSeconds;
mouse_event.modifiers = event.u.mouse.modifier;
mouse_event.button = static_cast<WebMouseEvent::Button>(event.u.mouse.button);
mouse_event.x = event.u.mouse.x;
mouse_event.y = event.u.mouse.y;
mouse_event.clickCount = event.u.mouse.clickCount;
return mouse_event;
}
WebMouseWheelEvent BuildMouseWheelEvent(const NPPepperEvent& event) {
WebMouseWheelEvent mouse_wheel_event;
mouse_wheel_event.type = WebInputEvent::MouseWheel;
mouse_wheel_event.timeStampSeconds = event.timeStampSeconds;
mouse_wheel_event.modifiers = event.u.wheel.modifier;
mouse_wheel_event.deltaX = event.u.wheel.deltaX;
mouse_wheel_event.deltaY = event.u.wheel.deltaY;
mouse_wheel_event.wheelTicksX = event.u.wheel.wheelTicksX;
mouse_wheel_event.wheelTicksY = event.u.wheel.wheelTicksY;
mouse_wheel_event.scrollByPage = event.u.wheel.scrollByPage;
return mouse_wheel_event;
}
} // namespace
PepperScrollbarWidget::PepperScrollbarWidget(
const NPScrollbarCreateParams& params) {
scrollbar_.reset(WebScrollbar::create(
static_cast<WebKit::WebScrollbarClient*>(this),
params.vertical ? WebScrollbar::Vertical : WebScrollbar::Horizontal));
AddRef();
}
PepperScrollbarWidget::~PepperScrollbarWidget() {
}
void PepperScrollbarWidget::Destroy() {
Release();
}
void PepperScrollbarWidget::Paint(Graphics2DDeviceContext* context,
const NPRect& dirty) {
gfx::Rect rect(dirty.left, dirty.top, dirty.right - dirty.left,
dirty.bottom - dirty.top);
#if defined(OS_WIN) || defined(OS_LINUX)
scrollbar_->paint(context->canvas(), rect);
#elif defined(OS_MACOSX)
// TODO(port)
#endif
dirty_rect_ = dirty_rect_.Subtract(rect);
}
bool PepperScrollbarWidget::HandleEvent(const NPPepperEvent& event) {
bool rv = false;
switch (event.type) {
case NPEventType_Undefined:
return false;
case NPEventType_MouseDown:
case NPEventType_MouseUp:
case NPEventType_MouseMove:
case NPEventType_MouseEnter:
case NPEventType_MouseLeave:
rv = scrollbar_->handleInputEvent(BuildMouseEvent(event));
break;
case NPEventType_MouseWheel:
rv = scrollbar_->handleInputEvent(BuildMouseWheelEvent(event));
break;
case NPEventType_RawKeyDown:
case NPEventType_KeyDown:
case NPEventType_KeyUp:
rv = scrollbar_->handleInputEvent(BuildKeyEvent(event));
break;
case NPEventType_Char:
rv = scrollbar_->handleInputEvent(BuildCharEvent(event));
break;
case NPEventType_Minimize:
case NPEventType_Focus:
case NPEventType_Device:
// NOTIMPLEMENTED();
break;
}
return rv;
}
void PepperScrollbarWidget::GetProperty(
NPWidgetProperty property, void* value) {
switch (property) {
case NPWidgetPropertyLocation: {
NPRect* rv = static_cast<NPRect*>(value);
rv->left = location_.x();
rv->top = location_.y();
rv->right = location_.right();
rv->bottom = location_.bottom();
break;
}
case NPWidgetPropertyDirtyRect: {
NPRect* rv = reinterpret_cast<NPRect*>(value);
rv->left = dirty_rect_.x();
rv->top = dirty_rect_.y();
rv->right = dirty_rect_.right();
rv->bottom = dirty_rect_.bottom();
break;
}
case NPWidgetPropertyScrollbarThickness: {
int32* rv = static_cast<int32*>(value);
*rv = WebScrollbar::defaultThickness();
break;
}
case NPWidgetPropertyScrollbarValue: {
int32* rv = static_cast<int32*>(value);
*rv = scrollbar_->value();
break;
}
default:
NOTREACHED();
break;
}
}
void PepperScrollbarWidget::SetProperty(
NPWidgetProperty property, void* value) {
switch (property) {
case NPWidgetPropertyLocation: {
NPRect* r = static_cast<NPRect*>(value);
location_ = gfx::Rect(
r->left, r->top, r->right - r->left, r->bottom - r->top);
scrollbar_->setLocation(location_);
break;
}
case NPWidgetPropertyScrollbarValue: {
int32* position = static_cast<int*>(value);
scrollbar_->setValue(*position);
break;
}
case NPWidgetPropertyScrollbarDocumentSize: {
int32* total_length = static_cast<int32*>(value);
scrollbar_->setDocumentSize(*total_length);
break;
}
case NPWidgetPropertyScrollbarTickMarks: {
NPScrollbarTickMarks* tickmarks =
static_cast<NPScrollbarTickMarks*>(value);
tickmarks_.resize(tickmarks->count);
for (uint32 i = 0; i < tickmarks->count; ++i) {
WebRect rect(
tickmarks->tickmarks[i].left,
tickmarks->tickmarks[i].top,
tickmarks->tickmarks[i].right - tickmarks->tickmarks[i].left,
tickmarks->tickmarks[i].bottom - tickmarks->tickmarks[i].top);
tickmarks_[i] = rect;
}
dirty_rect_ = location_;
NotifyInvalidate();
break;
}
case NPWidgetPropertyScrollbarScrollByLine:
case NPWidgetPropertyScrollbarScrollByPage:
case NPWidgetPropertyScrollbarScrollByDocument:
case NPWidgetPropertyScrollbarScrollByPixels: {
bool forward;
float multiplier = 1.0;
WebScrollbar::ScrollGranularity granularity;
if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByLine;
} else if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByPage;
} else if (property == NPWidgetPropertyScrollbarScrollByLine) {
forward = *static_cast<bool*>(value);
granularity = WebScrollbar::ScrollByDocument;
} else {
multiplier = static_cast<float>(*static_cast<int32*>(value));
forward = multiplier >= 0;
if (multiplier < 0)
multiplier *= -1;
granularity = WebScrollbar::ScrollByPixel;
}
scrollbar_->scroll(
forward ? WebScrollbar::ScrollForward : WebScrollbar::ScrollBackward,
granularity, multiplier);
break;
}
default:
NOTREACHED();
break;
}
}
void PepperScrollbarWidget::valueChanged(WebScrollbar*) {
WidgetPropertyChanged(NPWidgetPropertyScrollbarValue);
}
void PepperScrollbarWidget::invalidateScrollbarRect(WebScrollbar*,
const WebRect& rect) {
dirty_rect_ = dirty_rect_.Union(rect);
// Can't call into the client to tell them about the invalidate right away,
// since the Scrollbar code is still in the middle of updating its internal
// state.
MessageLoop::current()->PostTask(
FROM_HERE,
NewRunnableMethod(this, &PepperScrollbarWidget::NotifyInvalidate));
}
void PepperScrollbarWidget::getTickmarks(WebKit::WebScrollbar*,
WebVector<WebRect>* tickmarks) const {
if (tickmarks_.empty()) {
WebRect* rects = NULL;
tickmarks->assign(rects, 0);
} else {
tickmarks->assign(&tickmarks_[0], tickmarks_.size());
}
}
void PepperScrollbarWidget::NotifyInvalidate() {
if (!dirty_rect_.IsEmpty())
WidgetPropertyChanged(NPWidgetPropertyDirtyRect);
}
|
fix another typo
|
fix another typo
git-svn-id: http://src.chromium.org/svn/trunk/src@47004 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
Former-commit-id: e37879c1c9612ce0b273fdf93614bb160a0d6ae8
|
C++
|
bsd-3-clause
|
meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser,meego-tablet-ux/meego-app-browser
|
79baceb2b19ff5e6c598dac28b57455e2ab74a58
|
include/lofty/net.hxx
|
include/lofty/net.hxx
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015-2018 Raffaello D. Di Napoli
This file is part of Lofty.
Lofty is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the GNU
Lesser General Public License as published by the Free Software Foundation.
Lofty 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.
------------------------------------------------------------------------------------------------------------*/
#ifndef _LOFTY_NET_HXX
#define _LOFTY_NET_HXX
#ifndef _LOFTY_HXX
#error "Please #include <lofty.hxx> before this file"
#endif
#ifdef LOFTY_CXX_PRAGMA_ONCE
#pragma once
#endif
#include <lofty/io.hxx>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace lofty {
//! Networking facilities.
namespace net {
//! Internet Protocol-related classes and facilities.
namespace ip {}
} //namespace net
} //namespace lofty
namespace lofty { namespace net {
//! Networking protocols.
LOFTY_ENUM(protocol,
//! Transmission Control Protocol over Internet Protocol version 4 (TCP/IP).
(tcp_ipv4, 1),
//! Transmission Control Protocol over Internet Protocol version 6 (TCP/IPv6).
(tcp_ipv6, 2),
//! User Datagram Protocol over Internet Protocol version 4 (UDP/IP).
(udp_ipv4, 3),
//! User Datagram Protocol over Internet Protocol version 6 (UDP/IPv6).
(udp_ipv6, 4),
//! (UDP).
(udp, 2)
);
}} //namespace lofty::net
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if LOFTY_HOST_API_WIN32
namespace lofty { namespace net {
//! Adds scoped WinSock reference counting with implicit initialization and termination.
class LOFTY_SYM wsa_client {
protected:
//! Constructor. Adds one reference to the WinSock DLL.
wsa_client();
//! Destructor. Discards one reference to the WinSock DLL.
~wsa_client();
private:
//! Reference count for the WinSock DLL.
static _std::atomic<unsigned> refs;
};
}} //namespace lofty::net
#endif //if LOFTY_HOST_API_WIN32
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace lofty { namespace net {
//! Socket for networking I/O.
class LOFTY_SYM socket :
#if LOFTY_HOST_API_WIN32
private wsa_client,
#endif //if LOFTY_HOST_API_WIN32
public io::filedesc {
public:
//! Constructs an empty socket.
socket() {
}
/*! Constructor for a given protocol.
@param protocol_
Protocol for which to create the socket.
*/
explicit socket(protocol protocol_) :
io::filedesc(socket_filedesc(protocol_)) {
}
/*! Constructor for a given protocol. This overload is necessary to prevent the compiler, under POSIX, from
implicitly converting the enum into an int, which is the same thing as io::filedesc_t, and therefore pick
the wrong overload.
@param protocol_
Protocol for which to create the socket.
*/
explicit socket(protocol::enum_type protocol_) :
io::filedesc(socket_filedesc(protocol_)) {
}
/*! Constructor that takes ownership of a file descriptor.
@param fd_
Source file descriptor.
*/
explicit socket(io::filedesc_t fd_) :
io::filedesc(fd_) {
}
/*! Move constructor.
@param src
Source object.
*/
socket(socket && src) :
io::filedesc(_std::move(src)) {
}
~socket() {
}
/*! Move-assignment operator.
@param src
Source object.
@return
*this.
*/
socket & operator=(socket && src) {
io::filedesc::operator=(_std::move(src));
return *this;
}
private:
/*! Implementation of the main constructor, to allow for easy RAII.
@param protocol_
Protocol for which to create the socket.
*/
static io::filedesc socket_filedesc(protocol protocol_);
};
}} //namespace lofty::net
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifndef _LOFTY_NET_HXX
|
/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-
Copyright 2015-2018 Raffaello D. Di Napoli
This file is part of Lofty.
Lofty is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the GNU
Lesser General Public License as published by the Free Software Foundation.
Lofty 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.
------------------------------------------------------------------------------------------------------------*/
#ifndef _LOFTY_NET_HXX
#define _LOFTY_NET_HXX
#ifndef _LOFTY_HXX
#error "Please #include <lofty.hxx> before this file"
#endif
#ifdef LOFTY_CXX_PRAGMA_ONCE
#pragma once
#endif
#include <lofty/io.hxx>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace lofty {
//! Networking facilities.
namespace net {
//! Internet Protocol-related classes and facilities.
namespace ip {}
} //namespace net
} //namespace lofty
namespace lofty { namespace net {
//! Networking protocols.
LOFTY_ENUM(protocol,
//! Transmission Control Protocol over Internet Protocol version 4 (TCP/IP).
(tcp_ipv4, 1),
//! Transmission Control Protocol over Internet Protocol version 6 (TCP/IPv6).
(tcp_ipv6, 2),
//! User Datagram Protocol over Internet Protocol version 4 (UDP/IP).
(udp_ipv4, 3),
//! User Datagram Protocol over Internet Protocol version 6 (UDP/IPv6).
(udp_ipv6, 4)
);
}} //namespace lofty::net
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#if LOFTY_HOST_API_WIN32
namespace lofty { namespace net {
//! Adds scoped WinSock reference counting with implicit initialization and termination.
class LOFTY_SYM wsa_client {
protected:
//! Constructor. Adds one reference to the WinSock DLL.
wsa_client();
//! Destructor. Discards one reference to the WinSock DLL.
~wsa_client();
private:
//! Reference count for the WinSock DLL.
static _std::atomic<unsigned> refs;
};
}} //namespace lofty::net
#endif //if LOFTY_HOST_API_WIN32
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace lofty { namespace net {
//! Socket for networking I/O.
class LOFTY_SYM socket :
#if LOFTY_HOST_API_WIN32
private wsa_client,
#endif //if LOFTY_HOST_API_WIN32
public io::filedesc {
public:
//! Constructs an empty socket.
socket() {
}
/*! Constructor for a given protocol.
@param protocol_
Protocol for which to create the socket.
*/
explicit socket(protocol protocol_) :
io::filedesc(socket_filedesc(protocol_)) {
}
/*! Constructor for a given protocol. This overload is necessary to prevent the compiler, under POSIX, from
implicitly converting the enum into an int, which is the same thing as io::filedesc_t, and therefore pick
the wrong overload.
@param protocol_
Protocol for which to create the socket.
*/
explicit socket(protocol::enum_type protocol_) :
io::filedesc(socket_filedesc(protocol_)) {
}
/*! Constructor that takes ownership of a file descriptor.
@param fd_
Source file descriptor.
*/
explicit socket(io::filedesc_t fd_) :
io::filedesc(fd_) {
}
/*! Move constructor.
@param src
Source object.
*/
socket(socket && src) :
io::filedesc(_std::move(src)) {
}
~socket() {
}
/*! Move-assignment operator.
@param src
Source object.
@return
*this.
*/
socket & operator=(socket && src) {
io::filedesc::operator=(_std::move(src));
return *this;
}
private:
/*! Implementation of the main constructor, to allow for easy RAII.
@param protocol_
Protocol for which to create the socket.
*/
static io::filedesc socket_filedesc(protocol protocol_);
};
}} //namespace lofty::net
//////////////////////////////////////////////////////////////////////////////////////////////////////////////
#endif //ifndef _LOFTY_NET_HXX
|
Delete abandoned attempt
|
Delete abandoned attempt
|
C++
|
lgpl-2.1
|
raffaellod/lofty,raffaellod/lofty
|
d4159cd1af6f3dc271b1071118281e3f8d7b81bd
|
C++/backpack-ii.cpp
|
C++/backpack-ii.cpp
|
// Time: O(m * n)
// Space: O(m)
class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param A & V: Given n items with size A[i] and value V[i]
* @return: The maximum value
*/
int backPackII(int m, vector<int> A, vector<int> V) {
// table[i][j] denotes max_value of using the first elements
// to fulfill size j.
vector<vector<int>> table(2, vector<int>(m + 1, INT_MIN));
int max_value = 0;
table[0][0] = 0;
for (int i = 1; i <= A.size(); ++i) {
table[i % 2][0] = 0;
for (int j = 1; j <= m; ++j) {
// If first i - 1 elements could fulfill the backpack, then
// first i elements would also do.
table[i % 2][j] = table[(i - 1) % 2][j];
// Using the ith element to fulfill the backpack.
if (j >= A[i - 1] && table[(i - 1) % 2][j - A[i - 1]] >= 0) {
table[i % 2][j] = max(table[i % 2][j],
table[(i - 1) % 2][j - A[i - 1]] + V[i - 1]);
}
// If it fulfulls size j, update max size.
if (table[i % 2][j] >= 0) {
max_value = max(max_value, table[i % 2][j]);
}
}
}
return max_value;
}
};
|
// Time: O(m * n)
// Space: O(m)
class Solution {
public:
/**
* @param m: An integer m denotes the size of a backpack
* @param A & V: Given n items with size A[i] and value V[i]
* @return: The maximum value
*/
int backPackII(int m, vector<int> A, vector<int> V) {
// table[i][j] denotes max_value of using the first i elements
// to fulfill size j.
vector<vector<int>> table(2, vector<int>(m + 1, INT_MIN));
int max_value = 0;
table[0][0] = 0;
for (int i = 1; i <= A.size(); ++i) {
table[i % 2][0] = 0;
for (int j = 1; j <= m; ++j) {
// If first i - 1 elements could fulfill the backpack, then
// first i elements would also do.
table[i % 2][j] = table[(i - 1) % 2][j];
// Using the ith element to fulfill the backpack.
if (j >= A[i - 1] && table[(i - 1) % 2][j - A[i - 1]] >= 0) {
table[i % 2][j] = max(table[i % 2][j],
table[(i - 1) % 2][j - A[i - 1]] + V[i - 1]);
}
// If it fulfulls size j, update max size.
if (table[i % 2][j] >= 0) {
max_value = max(max_value, table[i % 2][j]);
}
}
}
return max_value;
}
};
|
Update backpack-ii.cpp
|
Update backpack-ii.cpp
|
C++
|
mit
|
jaredkoontz/lintcode,kamyu104/LintCode,jaredkoontz/lintcode,kamyu104/LintCode,jaredkoontz/lintcode,kamyu104/LintCode
|
459119fdae6a4aabf05ef2a5ad6fef964ba23f3d
|
C++/maximum-gap.cpp
|
C++/maximum-gap.cpp
|
// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param nums: a vector of integers
* @return: the maximum difference
*/
int maximumGap(vector<int> nums) {
if (nums.size() < 2) {
return 0;
}
// Init bucket.
int max_val = *max_element(nums.cbegin(), nums.cend());
int min_val = *min_element(nums.cbegin(), nums.cend());
int gap = max(1, static_cast<int>((max_val - min_val) / (nums.size() - 1)));
map<int, array<int, 2>> bucket;
typedef enum {MIN, MAX} ValueType;
// Find the bucket where the n should be put.
for (const auto& n : nums) {
// min_val / max_val is in the first / last bucket.
if (n == max_val || n == min_val) {
continue ;
}
int i = (n - min_val) / gap;
bucket[i][MIN] = min(!bucket[i][MIN] ? INT_MAX :
bucket[i][MIN], n);
bucket[i][MAX] = max(!bucket[i][MAX] ? INT_MIN :
bucket[i][MAX], n);
}
// Count each bucket gap between the first and the last bucket.
int max_gap = 0, pre_bucket_max = min_val;
for (auto& kvp : bucket) {
max_gap = max(max_gap, kvp.second[MIN] - pre_bucket_max);
pre_bucket_max = (kvp.second)[MAX];
}
// Count the last bucket.
max_gap = max(max_gap, max_val - pre_bucket_max);
return max_gap;
}
};
|
// Time: O(n)
// Space: O(n)
class Solution {
public:
/**
* @param nums: a vector of integers
* @return: the maximum difference
*/
int maximumGap(vector<int> nums) {
if (nums.size() < 2) {
return 0;
}
// Init bucket.
int max_val = *max_element(nums.cbegin(), nums.cend());
int min_val = *min_element(nums.cbegin(), nums.cend());
int gap = max(1, static_cast<int>((max_val - min_val) /
(nums.size() - 1)));
map<int, array<int, 2>> bucket;
typedef enum {MIN, MAX} ValueType;
// Find the bucket where the n should be put.
for (const auto& n : nums) {
// min_val / max_val is in the first / last bucket.
if (n == max_val || n == min_val) {
continue ;
}
int i = (n - min_val) / gap;
bucket[i][MIN] = min(!bucket[i][MIN] ? INT_MAX :
bucket[i][MIN], n);
bucket[i][MAX] = max(!bucket[i][MAX] ? INT_MIN :
bucket[i][MAX], n);
}
// Count each bucket gap between the first and the last bucket.
int max_gap = 0, pre_bucket_max = min_val;
for (auto& kvp : bucket) {
max_gap = max(max_gap, kvp.second[MIN] - pre_bucket_max);
pre_bucket_max = (kvp.second)[MAX];
}
// Count the last bucket.
max_gap = max(max_gap, max_val - pre_bucket_max);
return max_gap;
}
};
|
Update maximum-gap.cpp
|
Update maximum-gap.cpp
|
C++
|
mit
|
jaredkoontz/lintcode,jaredkoontz/lintcode,jaredkoontz/lintcode,kamyu104/LintCode,kamyu104/LintCode,kamyu104/LintCode
|
426ab0987209e9ff5318ae917bda116a55e4cfac
|
C++/paint-fence.cpp
|
C++/paint-fence.cpp
|
// Time: O(n)
// Space: O(1)
class Solution {
public:
int numWays(int n, int k) {
if (n == 0) {
return 0;
} else if (n == 1) {
return k;
}
vector<int> ways(3, 0);
ways[0] = k;
ways[1] = (k - 1) * ways[0] + k;
for (int i = 2; i < n; ++i) {
ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3]);
}
return ways[(n - 1) % 3];
}
};
// Time: O(n)
// Space: O(n)
class Solution2 {
public:
int numWays(int n, int k) {
if (n == 0) {
return 0;
} else if (n == 1) {
return k;
}
vector<int> ways(n, 0);
ways[0] = k;
ways[1] = (k - 1) * ways[0] + k;
for (int i = 2; i < n; ++i) {
ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2]);
}
return ways[n - 1];
}
};
|
// Time: O(n)
// Space: O(1)
// DP with rolling window.
class Solution {
public:
int numWays(int n, int k) {
if (n == 0) {
return 0;
} else if (n == 1) {
return k;
}
vector<int> ways(3, 0);
ways[0] = k;
ways[1] = (k - 1) * ways[0] + k;
for (int i = 2; i < n; ++i) {
ways[i % 3] = (k - 1) * (ways[(i - 1) % 3] + ways[(i - 2) % 3]);
}
return ways[(n - 1) % 3];
}
};
// Time: O(n)
// Space: O(n)
// DP solution.
class Solution2 {
public:
int numWays(int n, int k) {
if (n == 0) {
return 0;
} else if (n == 1) {
return k;
}
vector<int> ways(n, 0);
ways[0] = k;
ways[1] = (k - 1) * ways[0] + k;
for (int i = 2; i < n; ++i) {
ways[i] = (k - 1) * (ways[i - 1] + ways[i - 2]);
}
return ways[n - 1];
}
};
|
Update paint-fence.cpp
|
Update paint-fence.cpp
|
C++
|
mit
|
githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,jaredkoontz/leetcode,tudennis/LeetCode---kamyu104-11-24-2015,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,yiwen-luo/LeetCode,jaredkoontz/leetcode,githubutilities/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,kamyu104/LeetCode,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,yiwen-luo/LeetCode,githubutilities/LeetCode,yiwen-luo/LeetCode,jaredkoontz/leetcode,yiwen-luo/LeetCode,kamyu104/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode
|
e02eb106321aa0f3b50bc34fc092a068cb5dee95
|
COFF/InputFiles.cpp
|
COFF/InputFiles.cpp
|
//===- InputFiles.cpp -----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "InputFiles.h"
#include "Chunks.h"
#include "Config.h"
#include "Driver.h"
#include "Error.h"
#include "Memory.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "llvm-c/lto.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Object/Binary.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Target/TargetOptions.h"
#include <cstring>
#include <system_error>
#include <utility>
using namespace llvm;
using namespace llvm::COFF;
using namespace llvm::object;
using namespace llvm::support::endian;
using llvm::Triple;
using llvm::support::ulittle32_t;
namespace lld {
namespace coff {
/// Checks that Source is compatible with being a weak alias to Target.
/// If Source is Undefined and has no weak alias set, makes it a weak
/// alias to Target.
static void checkAndSetWeakAlias(SymbolTable *Symtab, InputFile *F,
SymbolBody *Source, SymbolBody *Target) {
auto *U = dyn_cast<Undefined>(Source);
if (!U)
return;
else if (!U->WeakAlias)
U->WeakAlias = Target;
else if (U->WeakAlias != Target)
Symtab->reportDuplicate(Source->symbol(), F);
}
ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {}
void ArchiveFile::parse() {
// Parse a MemoryBufferRef as an archive file.
File = check(Archive::create(MB), toString(this));
// Read the symbol table to construct Lazy objects.
for (const Archive::Symbol &Sym : File->symbols())
Symtab->addLazy(this, Sym);
}
// Returns a buffer pointing to a member file containing a given symbol.
void ArchiveFile::addMember(const Archive::Symbol *Sym) {
const Archive::Child &C =
check(Sym->getMember(),
"could not get the member for symbol " + Sym->getName());
// Return an empty buffer if we have already returned the same buffer.
if (!Seen.insert(C.getChildOffset()).second)
return;
Driver->enqueueArchiveMember(C, Sym->getName(), getName());
}
void ObjectFile::parse() {
// Parse a memory buffer as a COFF file.
std::unique_ptr<Binary> Bin = check(createBinary(MB), toString(this));
if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
Bin.release();
COFFObj.reset(Obj);
} else {
fatal(toString(this) + " is not a COFF file");
}
// Read section and symbol tables.
initializeChunks();
initializeSymbols();
initializeSEH();
}
void ObjectFile::initializeChunks() {
uint32_t NumSections = COFFObj->getNumberOfSections();
Chunks.reserve(NumSections);
SparseChunks.resize(NumSections + 1);
for (uint32_t I = 1; I < NumSections + 1; ++I) {
const coff_section *Sec;
StringRef Name;
if (auto EC = COFFObj->getSection(I, Sec))
fatal(EC, "getSection failed: #" + Twine(I));
if (auto EC = COFFObj->getSectionName(Sec, Name))
fatal(EC, "getSectionName failed: #" + Twine(I));
if (Name == ".sxdata") {
SXData = Sec;
continue;
}
if (Name == ".drectve") {
ArrayRef<uint8_t> Data;
COFFObj->getSectionContents(Sec, Data);
Directives = std::string((const char *)Data.data(), Data.size());
continue;
}
// Object files may have DWARF debug info or MS CodeView debug info
// (or both).
//
// DWARF sections don't need any special handling from the perspective
// of the linker; they are just a data section containing relocations.
// We can just link them to complete debug info.
//
// CodeView needs a linker support. We need to interpret and debug
// info, and then write it to a separate .pdb file.
// Ignore debug info unless /debug is given.
if (!Config->Debug && Name.startswith(".debug"))
continue;
// CodeView sections are stored to a different vector because they are
// not linked in the regular manner.
if (Name == ".debug" || Name.startswith(".debug$")) {
DebugChunks.push_back(make<SectionChunk>(this, Sec));
continue;
}
if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
continue;
auto *C = make<SectionChunk>(this, Sec);
Chunks.push_back(C);
SparseChunks[I] = C;
}
}
void ObjectFile::initializeSymbols() {
uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
SymbolBodies.reserve(NumSymbols);
SparseSymbolBodies.resize(NumSymbols);
SmallVector<std::pair<SymbolBody *, uint32_t>, 8> WeakAliases;
int32_t LastSectionNumber = 0;
for (uint32_t I = 0; I < NumSymbols; ++I) {
// Get a COFFSymbolRef object.
ErrorOr<COFFSymbolRef> SymOrErr = COFFObj->getSymbol(I);
if (!SymOrErr)
fatal(SymOrErr.getError(), "broken object file: " + toString(this));
COFFSymbolRef Sym = *SymOrErr;
const void *AuxP = nullptr;
if (Sym.getNumberOfAuxSymbols())
AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
SymbolBody *Body = nullptr;
if (Sym.isUndefined()) {
Body = createUndefined(Sym);
} else if (Sym.isWeakExternal()) {
Body = createUndefined(Sym);
uint32_t TagIndex =
static_cast<const coff_aux_weak_external *>(AuxP)->TagIndex;
WeakAliases.emplace_back(Body, TagIndex);
} else {
Body = createDefined(Sym, AuxP, IsFirst);
}
if (Body) {
SymbolBodies.push_back(Body);
SparseSymbolBodies[I] = Body;
}
I += Sym.getNumberOfAuxSymbols();
LastSectionNumber = Sym.getSectionNumber();
}
for (auto WeakAlias : WeakAliases)
checkAndSetWeakAlias(Symtab, this, WeakAlias.first,
SparseSymbolBodies[WeakAlias.second]);
}
SymbolBody *ObjectFile::createUndefined(COFFSymbolRef Sym) {
StringRef Name;
COFFObj->getSymbolName(Sym, Name);
return Symtab->addUndefined(Name, this, Sym.isWeakExternal())->body();
}
SymbolBody *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
bool IsFirst) {
StringRef Name;
if (Sym.isCommon()) {
auto *C = make<CommonChunk>(Sym);
Chunks.push_back(C);
COFFObj->getSymbolName(Sym, Name);
Symbol *S =
Symtab->addCommon(this, Name, Sym.getValue(), Sym.getGeneric(), C);
return S->body();
}
if (Sym.isAbsolute()) {
COFFObj->getSymbolName(Sym, Name);
// Skip special symbols.
if (Name == "@comp.id")
return nullptr;
// COFF spec 5.10.1. The .sxdata section.
if (Name == "@feat.00") {
if (Sym.getValue() & 1)
SEHCompat = true;
return nullptr;
}
if (Sym.isExternal())
return Symtab->addAbsolute(Name, Sym)->body();
else
return make<DefinedAbsolute>(Name, Sym);
}
int32_t SectionNumber = Sym.getSectionNumber();
if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
return nullptr;
// Reserved sections numbers don't have contents.
if (llvm::COFF::isReservedSectionNumber(SectionNumber))
fatal("broken object file: " + toString(this));
// This symbol references a section which is not present in the section
// header.
if ((uint32_t)SectionNumber >= SparseChunks.size())
fatal("broken object file: " + toString(this));
// Nothing else to do without a section chunk.
auto *SC = cast_or_null<SectionChunk>(SparseChunks[SectionNumber]);
if (!SC)
return nullptr;
// Handle section definitions
if (IsFirst && AuxP) {
auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
if (auto *ParentSC = cast_or_null<SectionChunk>(
SparseChunks[Aux->getNumber(Sym.isBigObj())]))
ParentSC->addAssociative(SC);
SC->Checksum = Aux->CheckSum;
}
DefinedRegular *B;
if (Sym.isExternal()) {
COFFObj->getSymbolName(Sym, Name);
Symbol *S =
Symtab->addRegular(this, Name, SC->isCOMDAT(), Sym.getGeneric(), SC);
B = cast<DefinedRegular>(S->body());
} else
B = make<DefinedRegular>(this, /*Name*/ "", SC->isCOMDAT(),
/*IsExternal*/ false, Sym.getGeneric(), SC);
if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
SC->setSymbol(B);
return B;
}
void ObjectFile::initializeSEH() {
if (!SEHCompat || !SXData)
return;
ArrayRef<uint8_t> A;
COFFObj->getSectionContents(SXData, A);
if (A.size() % 4 != 0)
fatal(".sxdata must be an array of symbol table indices");
auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
for (; I != E; ++I)
SEHandlers.insert(SparseSymbolBodies[*I]);
}
MachineTypes ObjectFile::getMachineType() {
if (COFFObj)
return static_cast<MachineTypes>(COFFObj->getMachine());
return IMAGE_FILE_MACHINE_UNKNOWN;
}
StringRef ltrim1(StringRef S, const char *Chars) {
if (!S.empty() && strchr(Chars, S[0]))
return S.substr(1);
return S;
}
void ImportFile::parse() {
const char *Buf = MB.getBufferStart();
const char *End = MB.getBufferEnd();
const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
// Check if the total size is valid.
if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
fatal("broken import library");
// Read names and create an __imp_ symbol.
StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
StringRef ImpName = Saver.save("__imp_" + Name);
const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
DLLName = StringRef(NameStart);
StringRef ExtName;
switch (Hdr->getNameType()) {
case IMPORT_ORDINAL:
ExtName = "";
break;
case IMPORT_NAME:
ExtName = Name;
break;
case IMPORT_NAME_NOPREFIX:
ExtName = ltrim1(Name, "?@_");
break;
case IMPORT_NAME_UNDECORATE:
ExtName = ltrim1(Name, "?@_");
ExtName = ExtName.substr(0, ExtName.find('@'));
break;
}
this->Hdr = Hdr;
ExternalName = ExtName;
ImpSym = cast<DefinedImportData>(
Symtab->addImportData(ImpName, this)->body());
if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
ConstSym =
cast<DefinedImportData>(Symtab->addImportData(Name, this)->body());
// If type is function, we need to create a thunk which jump to an
// address pointed by the __imp_ symbol. (This allows you to call
// DLL functions just like regular non-DLL functions.)
if (Hdr->getType() != llvm::COFF::IMPORT_CODE)
return;
ThunkSym = cast<DefinedImportThunk>(
Symtab->addImportThunk(Name, ImpSym, Hdr->Machine)->body());
}
void BitcodeFile::parse() {
Obj = check(lto::InputFile::create(MemoryBufferRef(
MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier()))));
for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
StringRef SymName = Saver.save(ObjSym.getName());
Symbol *Sym;
if (ObjSym.isUndefined()) {
Sym = Symtab->addUndefined(SymName, this, false);
} else if (ObjSym.isCommon()) {
Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
} else if (ObjSym.isWeak() && ObjSym.isIndirect()) {
// Weak external.
Sym = Symtab->addUndefined(SymName, this, true);
std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
SymbolBody *Alias = Symtab->addUndefined(Saver.save(Fallback));
checkAndSetWeakAlias(Symtab, this, Sym->body(), Alias);
} else {
bool IsCOMDAT = ObjSym.getComdatIndex() != -1;
Sym = Symtab->addRegular(this, SymName, IsCOMDAT);
}
SymbolBodies.push_back(Sym->body());
}
Directives = Obj->getCOFFLinkerOpts();
}
MachineTypes BitcodeFile::getMachineType() {
switch (Triple(Obj->getTargetTriple()).getArch()) {
case Triple::x86_64:
return AMD64;
case Triple::x86:
return I386;
case Triple::arm:
return ARMNT;
default:
return IMAGE_FILE_MACHINE_UNKNOWN;
}
}
} // namespace coff
} // namespace lld
// Returns the last element of a path, which is supposed to be a filename.
static StringRef getBasename(StringRef Path) {
size_t Pos = Path.find_last_of("\\/");
if (Pos == StringRef::npos)
return Path;
return Path.substr(Pos + 1);
}
// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
std::string lld::toString(coff::InputFile *File) {
if (!File)
return "(internal)";
if (File->ParentName.empty())
return File->getName().lower();
std::string Res =
(getBasename(File->ParentName) + "(" + getBasename(File->getName()) + ")")
.str();
return StringRef(Res).lower();
}
|
//===- InputFiles.cpp -----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "InputFiles.h"
#include "Chunks.h"
#include "Config.h"
#include "Driver.h"
#include "Error.h"
#include "Memory.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "llvm-c/lto.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Object/Binary.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/COFF.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Target/TargetOptions.h"
#include <cstring>
#include <system_error>
#include <utility>
using namespace llvm;
using namespace llvm::COFF;
using namespace llvm::object;
using namespace llvm::support::endian;
using llvm::Triple;
using llvm::support::ulittle32_t;
namespace lld {
namespace coff {
/// Checks that Source is compatible with being a weak alias to Target.
/// If Source is Undefined and has no weak alias set, makes it a weak
/// alias to Target.
static void checkAndSetWeakAlias(SymbolTable *Symtab, InputFile *F,
SymbolBody *Source, SymbolBody *Target) {
if (auto *U = dyn_cast<Undefined>(Source)) {
if (U->WeakAlias && U->WeakAlias != Target)
Symtab->reportDuplicate(Source->symbol(), F);
U->WeakAlias = Target;
}
}
ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {}
void ArchiveFile::parse() {
// Parse a MemoryBufferRef as an archive file.
File = check(Archive::create(MB), toString(this));
// Read the symbol table to construct Lazy objects.
for (const Archive::Symbol &Sym : File->symbols())
Symtab->addLazy(this, Sym);
}
// Returns a buffer pointing to a member file containing a given symbol.
void ArchiveFile::addMember(const Archive::Symbol *Sym) {
const Archive::Child &C =
check(Sym->getMember(),
"could not get the member for symbol " + Sym->getName());
// Return an empty buffer if we have already returned the same buffer.
if (!Seen.insert(C.getChildOffset()).second)
return;
Driver->enqueueArchiveMember(C, Sym->getName(), getName());
}
void ObjectFile::parse() {
// Parse a memory buffer as a COFF file.
std::unique_ptr<Binary> Bin = check(createBinary(MB), toString(this));
if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
Bin.release();
COFFObj.reset(Obj);
} else {
fatal(toString(this) + " is not a COFF file");
}
// Read section and symbol tables.
initializeChunks();
initializeSymbols();
initializeSEH();
}
void ObjectFile::initializeChunks() {
uint32_t NumSections = COFFObj->getNumberOfSections();
Chunks.reserve(NumSections);
SparseChunks.resize(NumSections + 1);
for (uint32_t I = 1; I < NumSections + 1; ++I) {
const coff_section *Sec;
StringRef Name;
if (auto EC = COFFObj->getSection(I, Sec))
fatal(EC, "getSection failed: #" + Twine(I));
if (auto EC = COFFObj->getSectionName(Sec, Name))
fatal(EC, "getSectionName failed: #" + Twine(I));
if (Name == ".sxdata") {
SXData = Sec;
continue;
}
if (Name == ".drectve") {
ArrayRef<uint8_t> Data;
COFFObj->getSectionContents(Sec, Data);
Directives = std::string((const char *)Data.data(), Data.size());
continue;
}
// Object files may have DWARF debug info or MS CodeView debug info
// (or both).
//
// DWARF sections don't need any special handling from the perspective
// of the linker; they are just a data section containing relocations.
// We can just link them to complete debug info.
//
// CodeView needs a linker support. We need to interpret and debug
// info, and then write it to a separate .pdb file.
// Ignore debug info unless /debug is given.
if (!Config->Debug && Name.startswith(".debug"))
continue;
// CodeView sections are stored to a different vector because they are
// not linked in the regular manner.
if (Name == ".debug" || Name.startswith(".debug$")) {
DebugChunks.push_back(make<SectionChunk>(this, Sec));
continue;
}
if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
continue;
auto *C = make<SectionChunk>(this, Sec);
Chunks.push_back(C);
SparseChunks[I] = C;
}
}
void ObjectFile::initializeSymbols() {
uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
SymbolBodies.reserve(NumSymbols);
SparseSymbolBodies.resize(NumSymbols);
SmallVector<std::pair<SymbolBody *, uint32_t>, 8> WeakAliases;
int32_t LastSectionNumber = 0;
for (uint32_t I = 0; I < NumSymbols; ++I) {
// Get a COFFSymbolRef object.
ErrorOr<COFFSymbolRef> SymOrErr = COFFObj->getSymbol(I);
if (!SymOrErr)
fatal(SymOrErr.getError(), "broken object file: " + toString(this));
COFFSymbolRef Sym = *SymOrErr;
const void *AuxP = nullptr;
if (Sym.getNumberOfAuxSymbols())
AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
SymbolBody *Body = nullptr;
if (Sym.isUndefined()) {
Body = createUndefined(Sym);
} else if (Sym.isWeakExternal()) {
Body = createUndefined(Sym);
uint32_t TagIndex =
static_cast<const coff_aux_weak_external *>(AuxP)->TagIndex;
WeakAliases.emplace_back(Body, TagIndex);
} else {
Body = createDefined(Sym, AuxP, IsFirst);
}
if (Body) {
SymbolBodies.push_back(Body);
SparseSymbolBodies[I] = Body;
}
I += Sym.getNumberOfAuxSymbols();
LastSectionNumber = Sym.getSectionNumber();
}
for (auto WeakAlias : WeakAliases)
checkAndSetWeakAlias(Symtab, this, WeakAlias.first,
SparseSymbolBodies[WeakAlias.second]);
}
SymbolBody *ObjectFile::createUndefined(COFFSymbolRef Sym) {
StringRef Name;
COFFObj->getSymbolName(Sym, Name);
return Symtab->addUndefined(Name, this, Sym.isWeakExternal())->body();
}
SymbolBody *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
bool IsFirst) {
StringRef Name;
if (Sym.isCommon()) {
auto *C = make<CommonChunk>(Sym);
Chunks.push_back(C);
COFFObj->getSymbolName(Sym, Name);
Symbol *S =
Symtab->addCommon(this, Name, Sym.getValue(), Sym.getGeneric(), C);
return S->body();
}
if (Sym.isAbsolute()) {
COFFObj->getSymbolName(Sym, Name);
// Skip special symbols.
if (Name == "@comp.id")
return nullptr;
// COFF spec 5.10.1. The .sxdata section.
if (Name == "@feat.00") {
if (Sym.getValue() & 1)
SEHCompat = true;
return nullptr;
}
if (Sym.isExternal())
return Symtab->addAbsolute(Name, Sym)->body();
else
return make<DefinedAbsolute>(Name, Sym);
}
int32_t SectionNumber = Sym.getSectionNumber();
if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
return nullptr;
// Reserved sections numbers don't have contents.
if (llvm::COFF::isReservedSectionNumber(SectionNumber))
fatal("broken object file: " + toString(this));
// This symbol references a section which is not present in the section
// header.
if ((uint32_t)SectionNumber >= SparseChunks.size())
fatal("broken object file: " + toString(this));
// Nothing else to do without a section chunk.
auto *SC = cast_or_null<SectionChunk>(SparseChunks[SectionNumber]);
if (!SC)
return nullptr;
// Handle section definitions
if (IsFirst && AuxP) {
auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
if (auto *ParentSC = cast_or_null<SectionChunk>(
SparseChunks[Aux->getNumber(Sym.isBigObj())]))
ParentSC->addAssociative(SC);
SC->Checksum = Aux->CheckSum;
}
DefinedRegular *B;
if (Sym.isExternal()) {
COFFObj->getSymbolName(Sym, Name);
Symbol *S =
Symtab->addRegular(this, Name, SC->isCOMDAT(), Sym.getGeneric(), SC);
B = cast<DefinedRegular>(S->body());
} else
B = make<DefinedRegular>(this, /*Name*/ "", SC->isCOMDAT(),
/*IsExternal*/ false, Sym.getGeneric(), SC);
if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
SC->setSymbol(B);
return B;
}
void ObjectFile::initializeSEH() {
if (!SEHCompat || !SXData)
return;
ArrayRef<uint8_t> A;
COFFObj->getSectionContents(SXData, A);
if (A.size() % 4 != 0)
fatal(".sxdata must be an array of symbol table indices");
auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
for (; I != E; ++I)
SEHandlers.insert(SparseSymbolBodies[*I]);
}
MachineTypes ObjectFile::getMachineType() {
if (COFFObj)
return static_cast<MachineTypes>(COFFObj->getMachine());
return IMAGE_FILE_MACHINE_UNKNOWN;
}
StringRef ltrim1(StringRef S, const char *Chars) {
if (!S.empty() && strchr(Chars, S[0]))
return S.substr(1);
return S;
}
void ImportFile::parse() {
const char *Buf = MB.getBufferStart();
const char *End = MB.getBufferEnd();
const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
// Check if the total size is valid.
if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
fatal("broken import library");
// Read names and create an __imp_ symbol.
StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
StringRef ImpName = Saver.save("__imp_" + Name);
const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
DLLName = StringRef(NameStart);
StringRef ExtName;
switch (Hdr->getNameType()) {
case IMPORT_ORDINAL:
ExtName = "";
break;
case IMPORT_NAME:
ExtName = Name;
break;
case IMPORT_NAME_NOPREFIX:
ExtName = ltrim1(Name, "?@_");
break;
case IMPORT_NAME_UNDECORATE:
ExtName = ltrim1(Name, "?@_");
ExtName = ExtName.substr(0, ExtName.find('@'));
break;
}
this->Hdr = Hdr;
ExternalName = ExtName;
ImpSym = cast<DefinedImportData>(
Symtab->addImportData(ImpName, this)->body());
if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
ConstSym =
cast<DefinedImportData>(Symtab->addImportData(Name, this)->body());
// If type is function, we need to create a thunk which jump to an
// address pointed by the __imp_ symbol. (This allows you to call
// DLL functions just like regular non-DLL functions.)
if (Hdr->getType() != llvm::COFF::IMPORT_CODE)
return;
ThunkSym = cast<DefinedImportThunk>(
Symtab->addImportThunk(Name, ImpSym, Hdr->Machine)->body());
}
void BitcodeFile::parse() {
Obj = check(lto::InputFile::create(MemoryBufferRef(
MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier()))));
for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
StringRef SymName = Saver.save(ObjSym.getName());
Symbol *Sym;
if (ObjSym.isUndefined()) {
Sym = Symtab->addUndefined(SymName, this, false);
} else if (ObjSym.isCommon()) {
Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
} else if (ObjSym.isWeak() && ObjSym.isIndirect()) {
// Weak external.
Sym = Symtab->addUndefined(SymName, this, true);
std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
SymbolBody *Alias = Symtab->addUndefined(Saver.save(Fallback));
checkAndSetWeakAlias(Symtab, this, Sym->body(), Alias);
} else {
bool IsCOMDAT = ObjSym.getComdatIndex() != -1;
Sym = Symtab->addRegular(this, SymName, IsCOMDAT);
}
SymbolBodies.push_back(Sym->body());
}
Directives = Obj->getCOFFLinkerOpts();
}
MachineTypes BitcodeFile::getMachineType() {
switch (Triple(Obj->getTargetTriple()).getArch()) {
case Triple::x86_64:
return AMD64;
case Triple::x86:
return I386;
case Triple::arm:
return ARMNT;
default:
return IMAGE_FILE_MACHINE_UNKNOWN;
}
}
} // namespace coff
} // namespace lld
// Returns the last element of a path, which is supposed to be a filename.
static StringRef getBasename(StringRef Path) {
size_t Pos = Path.find_last_of("\\/");
if (Pos == StringRef::npos)
return Path;
return Path.substr(Pos + 1);
}
// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
std::string lld::toString(coff::InputFile *File) {
if (!File)
return "(internal)";
if (File->ParentName.empty())
return File->getName().lower();
std::string Res =
(getBasename(File->ParentName) + "(" + getBasename(File->getName()) + ")")
.str();
return StringRef(Res).lower();
}
|
Change the control flow so that the function is a bit more readable. NFC.
|
Change the control flow so that the function is a bit more readable. NFC.
git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@303775 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/lld,llvm-mirror/lld
|
6be5e876533e38bd691e3b22c358ee2409ca7624
|
include/ten/ioproc.hh
|
include/ten/ioproc.hh
|
#ifndef LIBTEN_IOPROC_HH
#define LIBTEN_IOPROC_HH
#include "task.hh"
#include "channel.hh"
#include <boost/any.hpp>
#include <type_traits>
#include <exception>
#include <memory>
#include <fcntl.h>
namespace ten {
// anyfunc - hold and call a function that may return void non-void
using anyfunc = std::function<boost::any ()>;
namespace anyfunc_impl {
template <typename F> anyfunc make(F f, std::true_type) { return [f]() mutable -> boost::any { f(); return {}; }; }
template <typename F> anyfunc make(const F &f, std::false_type) { return anyfunc(f); }
}
template <typename F>
inline anyfunc make_anyfunc(const F &f) {
using result_t = typename std::result_of<F()>::type;
return anyfunc_impl::make(f, typename std::is_void<result_t>::type());
}
inline anyfunc make_anyfunc(const anyfunc &f) { return f; }
inline anyfunc make_anyfunc( anyfunc &&f) { return std::move(f); }
// return a boost::any even if it's empty
template <class T> inline T any_value( const boost::any &a) { return boost::any_cast<T>(a); }
template <class T> inline T any_value( boost::any &&a) { return std::move(boost::any_cast<T &>(a)); }
template <> inline void any_value<void>(const boost::any &) {}
template <> inline void any_value<void>( boost::any &&) {}
// thread pool for io or other tasks
struct pcall;
using iochannel = channel<std::unique_ptr<pcall>>;
//! remote call in another thread
struct pcall {
iochannel ch;
anyfunc op;
std::exception_ptr exception;
boost::any ret;
pcall(anyfunc op_, iochannel &ch_) : ch(ch_), op(std::move(op_)) {}
};
void ioproctask(iochannel &);
//! a pool of threads for making blocking calls
struct ioproc {
iochannel ch;
std::vector<uint64_t> tids;
ioproc(size_t stacksize = default_stacksize,
unsigned nprocs = 1,
unsigned chanbuf = 0,
std::function<void(iochannel &)> proctask = ioproctask)
: ch(chanbuf ? chanbuf : nprocs)
{
for (unsigned i=0; i<nprocs; ++i) {
tids.push_back(procspawn(std::bind(proctask, ch), stacksize));
}
}
~ioproc() {
DVLOG(5) << "closing ioproc channel: " << this;
ch.close();
DVLOG(5) << "freeing ioproc: " << this;
}
};
namespace ioproc_impl {
}
//! wait on an iochannel for a call to complete with a result
template <typename ResultT>
ResultT iowait(iochannel &reply_chan) {
try {
std::unique_ptr<pcall> reply(reply_chan.recv());
if (reply->exception != nullptr) {
std::rethrow_exception(reply->exception);
}
return any_value<ResultT>(std::move(reply->ret));
} catch (task_interrupted &e) {
reply_chan.close();
throw;
}
}
//! make an iocall, but dont wait for it to complete
template <typename Func>
void iocallasync(ioproc &io, Func &&f, iochannel reply_chan = iochannel()) {
std::unique_ptr<pcall> call(new pcall(make_anyfunc(f), reply_chan));
io.ch.send(std::move(call));
}
//! make an iocall, and wait for the result
template <typename Func, typename Result = typename std::result_of<Func()>::type>
Result iocall(ioproc &io, Func &&f, iochannel reply_chan = iochannel()) {
std::unique_ptr<pcall> call(new pcall(make_anyfunc(f), reply_chan));
io.ch.send(std::move(call));
return iowait<Result>(reply_chan);
}
////// iorw /////
template <typename ProcT> int ioopen(ProcT &io, char *path, int mode) {
return iocall(io, std::bind((int (*)(char *, int))::open, path, mode));
}
template <typename ProcT> int ioclose(ProcT &io, int fd) {
return iocall(io, std::bind(::close, fd));
}
template <typename ProcT> ssize_t ioread(ProcT &io, int fd, void *buf, size_t n) {
return iocall(io, std::bind(::read, fd, buf, n));
}
template <typename ProcT> ssize_t iowrite(ProcT &io, int fd, void *buf, size_t n) {
return iocall(io, std::bind(::write, fd, buf, n));
}
} // end namespace ten
#endif // LIBTEN_IOPROC_HH
|
#ifndef LIBTEN_IOPROC_HH
#define LIBTEN_IOPROC_HH
#include "task.hh"
#include "channel.hh"
#include <boost/any.hpp>
#include <type_traits>
#include <exception>
#include <memory>
#include <fcntl.h>
namespace ten {
// anyfunc - hold and call a function that may return void non-void
using anyfunc = std::function<boost::any ()>;
namespace anyfunc_impl {
template <typename F> anyfunc make(F f, std::true_type) { return [f]() mutable -> boost::any { f(); return {}; }; }
template <typename F> anyfunc make(const F &f, std::false_type) { return anyfunc(f); }
}
template <typename F>
inline anyfunc make_anyfunc(const F &f) {
using result_t = typename std::result_of<F()>::type;
return anyfunc_impl::make(f, typename std::is_void<result_t>::type());
}
inline anyfunc make_anyfunc(const anyfunc &f) { return f; }
inline anyfunc make_anyfunc( anyfunc &&f) { return std::move(f); }
inline anyfunc make_anyfunc(void (*f)()) { return anyfunc_impl::make(f, std::true_type()); } // workaround for libstdc++ result_of<>
// return a boost::any even if it's empty
template <class T> inline T any_value( const boost::any &a) { return boost::any_cast<T>(a); }
template <class T> inline T any_value( boost::any &&a) { return std::move(boost::any_cast<T &>(a)); }
template <> inline void any_value<void>(const boost::any &) {}
template <> inline void any_value<void>( boost::any &&) {}
// thread pool for io or other tasks
struct pcall;
using iochannel = channel<std::unique_ptr<pcall>>;
//! remote call in another thread
struct pcall {
iochannel ch;
anyfunc op;
std::exception_ptr exception;
boost::any ret;
pcall(anyfunc op_, iochannel &ch_) : ch(ch_), op(std::move(op_)) {}
};
void ioproctask(iochannel &);
//! a pool of threads for making blocking calls
struct ioproc {
iochannel ch;
std::vector<uint64_t> tids;
ioproc(size_t stacksize = default_stacksize,
unsigned nprocs = 1,
unsigned chanbuf = 0,
std::function<void(iochannel &)> proctask = ioproctask)
: ch(chanbuf ? chanbuf : nprocs)
{
for (unsigned i=0; i<nprocs; ++i) {
tids.push_back(procspawn(std::bind(proctask, ch), stacksize));
}
}
~ioproc() {
DVLOG(5) << "closing ioproc channel: " << this;
ch.close();
DVLOG(5) << "freeing ioproc: " << this;
}
};
namespace ioproc_impl {
}
//! wait on an iochannel for a call to complete with a result
template <typename ResultT>
ResultT iowait(iochannel &reply_chan) {
try {
std::unique_ptr<pcall> reply(reply_chan.recv());
if (reply->exception != nullptr) {
std::rethrow_exception(reply->exception);
}
return any_value<ResultT>(std::move(reply->ret));
} catch (task_interrupted &e) {
reply_chan.close();
throw;
}
}
//! make an iocall, but dont wait for it to complete
template <typename Func>
void iocallasync(ioproc &io, Func &&f, iochannel reply_chan = iochannel()) {
std::unique_ptr<pcall> call(new pcall(make_anyfunc(f), reply_chan));
io.ch.send(std::move(call));
}
//! make an iocall, and wait for the result
template <typename Func, typename Result = typename std::result_of<Func()>::type>
Result iocall(ioproc &io, Func &&f, iochannel reply_chan = iochannel()) {
std::unique_ptr<pcall> call(new pcall(make_anyfunc(f), reply_chan));
io.ch.send(std::move(call));
return iowait<Result>(reply_chan);
}
////// iorw /////
template <typename ProcT> int ioopen(ProcT &io, char *path, int mode) {
return iocall(io, std::bind((int (*)(char *, int))::open, path, mode));
}
template <typename ProcT> int ioclose(ProcT &io, int fd) {
return iocall(io, std::bind(::close, fd));
}
template <typename ProcT> ssize_t ioread(ProcT &io, int fd, void *buf, size_t n) {
return iocall(io, std::bind(::read, fd, buf, n));
}
template <typename ProcT> ssize_t iowrite(ProcT &io, int fd, void *buf, size_t n) {
return iocall(io, std::bind(::write, fd, buf, n));
}
} // end namespace ten
#endif // LIBTEN_IOPROC_HH
|
read special case for function pointer
|
read special case for function pointer
|
C++
|
apache-2.0
|
toffaletti/libten,toffaletti/libten,toffaletti/libten,toffaletti/libten,toffaletti/libten
|
382afe921cbd30d68d9c767fa22ba5e163364131
|
cint/cling/test/ErrorRecovery/NestedTags.C
|
cint/cling/test/ErrorRecovery/NestedTags.C
|
// RUN: cat %s | %cling -Xclang -verify -I%p | FileCheck %s
// Tests the removal of nested decls
struct Outer { struct Inner { enum E{i = 1}; }; };error_here; // expected-error {{error: use of undeclared identifier 'error_here'}}
.rawInput
namespace Outer { struct Inner { enum E{i = 2}; }; };
.rawInput
Outer::Inner::i
// CHECK: (enum Outer::Inner::E const) @0x{{[0-9A-Fa-f]{8,}.}}
enum A{a}; //
enum A{a}; // expected-error {{redefinition of 'A'}} expected-note {{previous definition is here}}
a // expected-error {{use of undeclared identifier 'a'}}
.q
|
// RUN: cat %s | %cling -Xclang -verify -I%p | FileCheck %s
// Tests the removal of nested decls
struct Outer { struct Inner { enum E{i = 1}; }; };error_here; // expected-error {{error: use of undeclared identifier 'error_here'}}
.rawInput
namespace Outer { struct Inner { enum E{i = 2}; }; };
.rawInput
Outer::Inner::i
// CHECK: (enum Outer::Inner::E const) @0x{{[0-9A-Fa-f]{7,12}.}}
// CHECK: (Outer::Inner::E::i) : (int) 2
enum A{a}; //
enum A{a}; // expected-error {{redefinition of 'A'}} expected-note {{previous definition is here}}
a // expected-error {{use of undeclared identifier 'a'}}
.q
|
Allow the test to succeed on 32-bit platforms as well
|
Allow the test to succeed on 32-bit platforms as well
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@43754 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical,bbockelm/root-historical
|
aa4f50199e194ecd7dbe5de8ffd81c3f11778395
|
src/core/item.hpp
|
src/core/item.hpp
|
#pragma once
#include <cassert>
#include <vector>
#include <string>
#include <array>
#include <tuple>
#include <map>
#include <algorithm>
using std::string;
using std::vector;
namespace bookwyrm::core {
namespace func {
/*
* Take two containers, zip over them and return a vector with the length of the shortest passed container.
*
* NOTE: This is some ugly template programming. Please fix it.
*/
template <typename Cont1, typename Cont2>
auto zip(const Cont1 &ac, const Cont2 &bc) -> std::vector<std::pair<typename Cont1::value_type, typename Cont2::value_type>>
{
std::vector<std::pair<typename Cont1::value_type, typename Cont2::value_type>> pairs;
auto a = std::cbegin(ac);
auto b = std::cbegin(bc);
while (a != std::cend(ac) && b != std::cend(bc))
pairs.emplace_back(*a++, *b++);
assert(pairs.size() == std::min(ac.size(), bc.size()));
return pairs;
}
/* Return true if any element is shared between two sets. */
template <typename Set>
inline bool any_intersection(const Set &a, const Set &b)
{
return std::find_first_of(a.cbegin(), a.cend(), b.cbegin(), b.cend()) != a.cend();
}
/* ns func */
}
/* Default value: "this value is empty". */
constexpr int empty = -1;
/*
* For --year:
* -y 2157 : list items from 2157 (equal)
* -y =>2157 : list items from 2157 and later (eq_gt)
* -y =<2157 : list items from 2157 and earlier (eq_lt)
* -y >2157 : list items from later than 2157 (gt)
* -y <2157 : list items from earlier than 2157 (lt)
*/
enum class year_mod { equal, eq_gt, eq_lt, lt, gt, unused };
struct exacts_t {
/* Holds exact data about an item (year, page count, format, etc.). */
explicit exacts_t(std::pair<year_mod, int> yearmod, int volume, int number, const string &extension)
: ymod(std::get<0>(yearmod)), year(std::get<1>(yearmod)), volume(volume), number(number),
pages(empty), size(empty), extension(extension) {}
explicit exacts_t(const std::map<string, int> &dict, const string &extension)
: ymod(year_mod::unused),
year(get_value(dict, "year")),
volume(get_value(dict, "volume")),
number(get_value(dict, "number")),
pages(get_value(dict, "pages")),
size(get_value(dict, "size")),
extension(extension) {}
bool operator==(const exacts_t &other) const
{
// TODO: use std::tie?
return (ymod == other.ymod &&
year == other.year &&
volume == other.year &&
number == other.number &&
pages == other.pages &&
size == other.size &&
extension == other.extension && // XXX: for some items, only this will differ. Check if first?
store == other.store);
}
const year_mod ymod;
const int year,
volume, /* no associated flag */
number, /* no associated flag */
pages, /* no associated flag */
size; /* in bytes; no associated flag */
const string extension;
/* Convenience container */
const std::array<int, 5> store = {{
year, volume, number, pages, year
}};
private:
static int get_value(const std::map<string, int> &dict, const string &&key);
};
struct nonexacts_t {
/* Holds strings, which are matched fuzzily. */
explicit nonexacts_t(const vector<string> &authors, const string &title, const string &series,
const string &publisher, const string &journal)
: authors(authors), title(title), series(series), publisher(publisher), journal(journal) {}
explicit nonexacts_t(const std::map<string, string> &dict, const vector<string> &authors)
: authors(authors),
title(get_value(dict, "title")),
series(get_value(dict, "series")),
publisher(get_value(dict, "publisher")),
journal(get_value(dict, "journal")),
edition(get_value(dict, "edition")) {}
bool operator==(const nonexacts_t &other) const
{
return (authors == other.authors &&
title == other.title &&
series == other.series &&
publisher == other.publisher &&
journal == other.journal &&
edition == other.edition);
}
const vector<string> authors;
const string title;
const string series;
const string publisher;
const string journal;
const string edition;
private:
static const string get_value(const std::map<string, string> &dict, const string &&key);
};
struct request {
/* Holds necessary data to download an item. */
/* some type enum? ´headers´ will only be used when the mirror is over HTTP. */
const string uri;
const std::map<string, string> headers;
};
struct misc_t {
/* Holds everything else. */
explicit misc_t(const vector<string> &uris, const vector<string> &isbns)
: uris(uris), isbns(isbns) {}
explicit misc_t() {}
bool operator==(const misc_t &other) const
{
return (uris == other.uris &&
isbns == other.isbns);
}
const vector<string> uris;
const vector<string> isbns;
};
struct item {
public:
explicit item(const nonexacts_t ne, const exacts_t e)
: nonexacts(ne), exacts(e), misc(), index(items_idx++) {}
/* Construct an item from a pybind11::tuple. */
explicit item(const std::tuple<nonexacts_t, exacts_t, misc_t> &tuple)
: nonexacts(std::get<0>(tuple)), exacts(std::get<1>(tuple)), misc(std::get<2>(tuple)), index(items_idx++) {}
/*
* Returns true if all specified exact values are equal
* and if all specified non-exact values passes the fuzzy ratio.
*/
bool matches(const item &wanted) const;
bool operator==(const item &other) const
{
return (nonexacts == other.nonexacts &&
exacts == other.exacts &&
misc == other.misc);
}
/* For keeping sort order in an std::set. */
bool operator<(const item &other) const
{
return index < other.index;
}
const nonexacts_t nonexacts;
const exacts_t exacts;
const misc_t misc;
const size_t index;
private:
static size_t items_idx; // = 0
};
/* ns bookwyrm::core */
}
|
#pragma once
#include <cassert>
#include <vector>
#include <string>
#include <array>
#include <tuple>
#include <map>
#include <algorithm>
using std::string;
using std::vector;
namespace bookwyrm::core {
namespace func {
/*
* Take two containers, zip over them and return a vector with the length of the shortest passed container.
*
* NOTE: This is some ugly template programming. Please fix it.
*/
template <typename Cont1, typename Cont2>
auto zip(const Cont1 &ac, const Cont2 &bc) -> std::vector<std::pair<typename Cont1::value_type, typename Cont2::value_type>>
{
std::vector<std::pair<typename Cont1::value_type, typename Cont2::value_type>> pairs;
auto a = std::cbegin(ac);
auto b = std::cbegin(bc);
while (a != std::cend(ac) && b != std::cend(bc))
pairs.emplace_back(*a++, *b++);
assert(pairs.size() == std::min(ac.size(), bc.size()));
return pairs;
}
/* Return true if any element is shared between two sets. */
template <typename Set>
inline bool any_intersection(const Set &a, const Set &b)
{
return std::find_first_of(a.cbegin(), a.cend(), b.cbegin(), b.cend()) != a.cend();
}
/* ns func */
}
/* Default value: "this value is empty". */
constexpr int empty = -1;
/*
* For --year:
* -y 2157 : list items from 2157 (equal)
* -y =>2157 : list items from 2157 and later (eq_gt)
* -y =<2157 : list items from 2157 and earlier (eq_lt)
* -y >2157 : list items from later than 2157 (gt)
* -y <2157 : list items from earlier than 2157 (lt)
*/
enum class year_mod { equal, eq_gt, eq_lt, lt, gt, unused };
struct exacts_t {
/* Holds exact data about an item (year, page count, format, etc.). */
explicit exacts_t(std::pair<year_mod, int> yearmod, int volume, int number, const string &extension)
: ymod(std::get<0>(yearmod)), year(std::get<1>(yearmod)), volume(volume), number(number),
pages(empty), size(empty), extension(extension) {}
explicit exacts_t(const std::map<string, int> &dict, const string &extension)
: ymod(year_mod::unused),
year(get_value(dict, "year")),
volume(get_value(dict, "volume")),
number(get_value(dict, "number")),
pages(get_value(dict, "pages")),
size(get_value(dict, "size")),
extension(extension) {}
bool operator==(const exacts_t &other) const
{
/* extension is checked first, because some sources offer items in multiple formats. */
return std::tie(extension, ymod, year, volume, number, pages, size) ==
std::tie(other.extension, other.ymod, other.year, other.volume, other.number, other.pages, other.size);
}
const year_mod ymod;
const int year,
volume, /* no associated flag */
number, /* no associated flag */
pages, /* no associated flag */
size; /* in bytes; no associated flag */
const string extension;
/* Convenience container */
const std::array<int, 5> store = {{
year, volume, number, pages, year
}};
private:
static int get_value(const std::map<string, int> &dict, const string &&key);
};
struct nonexacts_t {
/* Holds strings, which are matched fuzzily. */
explicit nonexacts_t(const vector<string> &authors, const string &title, const string &series,
const string &publisher, const string &journal)
: authors(authors), title(title), series(series), publisher(publisher), journal(journal) {}
explicit nonexacts_t(const std::map<string, string> &dict, const vector<string> &authors)
: authors(authors),
title(get_value(dict, "title")),
series(get_value(dict, "series")),
publisher(get_value(dict, "publisher")),
journal(get_value(dict, "journal")),
edition(get_value(dict, "edition")) {}
bool operator==(const nonexacts_t &other) const
{
return std::tie(authors, title, series, publisher, journal, edition) ==
std::tie(other.authors, other.title, other.series, other.publisher, other.journal, other.edition);
}
const vector<string> authors;
const string title;
const string series;
const string publisher;
const string journal;
const string edition;
private:
static const string get_value(const std::map<string, string> &dict, const string &&key);
};
struct request {
/* Holds necessary data to download an item. */
/* some type enum? ´headers´ will only be used when the mirror is over HTTP. */
const string uri;
const std::map<string, string> headers;
};
struct misc_t {
/* Holds everything else. */
explicit misc_t(const vector<string> &uris, const vector<string> &isbns)
: uris(uris), isbns(isbns) {}
explicit misc_t() {}
bool operator==(const misc_t &other) const
{
return std::tie(uris, isbns) == std::tie(other.uris, other.isbns);
}
const vector<string> uris;
const vector<string> isbns;
};
struct item {
public:
explicit item(const nonexacts_t ne, const exacts_t e)
: nonexacts(ne), exacts(e), misc(), index(items_idx++) {}
/* Construct an item from a pybind11::tuple. */
explicit item(const std::tuple<nonexacts_t, exacts_t, misc_t> &tuple)
: nonexacts(std::get<0>(tuple)), exacts(std::get<1>(tuple)), misc(std::get<2>(tuple)), index(items_idx++) {}
/*
* Returns true if all specified exact values are equal
* and if all specified non-exact values passes the fuzzy ratio.
*/
bool matches(const item &wanted) const;
bool operator==(const item &other) const
{
return std::tie(nonexacts, exacts, misc) ==
std::tie(other.nonexacts, other.exacts, other.misc);
}
/* For keeping sort order in an std::set. */
bool operator<(const item &other) const
{
return index < other.index;
}
const nonexacts_t nonexacts;
const exacts_t exacts;
const misc_t misc;
const size_t index;
private:
static size_t items_idx; // = 0
};
/* ns bookwyrm::core */
}
|
improve struct operator== readability
|
core: improve struct operator== readability
|
C++
|
mit
|
Tmplt/bookwyrm,Tmplt/bookwyrm,Tmplt/bookwyrm
|
fa03dec7e98bdda8aa596ef7943cf0a8d0bcb127
|
src/core_read.cpp
|
src/core_read.cpp
|
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <core_io.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>
#include <util/strencodings.h>
#include <version.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <algorithm>
#include <string>
namespace {
opcodetype ParseOpCode(const std::string& s)
{
static std::map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty())
{
for (unsigned int op = 0; op <= MAX_OPCODE; op++)
{
// Allow OP_RESERVED to get into mapOpNames
if (op < OP_NOP && op != OP_RESERVED)
continue;
std::string strName = GetOpName(static_cast<opcodetype>(op));
if (strName == "OP_UNKNOWN")
continue;
mapOpNames[strName] = static_cast<opcodetype>(op);
// Convenience: OP_ADD and just ADD are both recognized:
if (strName.compare(0, 3, "OP_") == 0) { // strName starts with "OP_"
mapOpNames[strName.substr(3)] = static_cast<opcodetype>(op);
}
}
}
auto it = mapOpNames.find(s);
if (it == mapOpNames.end()) throw std::runtime_error("script parse error: unknown opcode");
return it->second;
}
} // namespace
CScript ParseScript(const std::string& s)
{
CScript result;
std::vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
{
if (w->empty())
{
// Empty string, ignore. (boost::split given '' will return one word)
}
else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||
(w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))
{
// Number
int64_t n = LocaleIndependentAtoi<int64_t>(*w);
//limit the range of numbers ParseScript accepts in decimal
//since numbers outside -0xFFFFFFFF...0xFFFFFFFF are illegal in scripts
if (n > int64_t{0xffffffff} || n < -1 * int64_t{0xffffffff}) {
throw std::runtime_error("script parse error: decimal numeric value only allowed in the "
"range -0xFFFFFFFF...0xFFFFFFFF");
}
result << n;
}
else if (w->substr(0,2) == "0x" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))
{
// Raw hex data, inserted NOT pushed onto stack:
std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
result.insert(result.end(), raw.begin(), raw.end());
}
else if (w->size() >= 2 && w->front() == '\'' && w->back() == '\'')
{
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't work.
std::vector<unsigned char> value(w->begin()+1, w->end()-1);
result << value;
}
else
{
// opcode, e.g. OP_ADD or ADD:
result << ParseOpCode(*w);
}
}
return result;
}
// Check that all of the input and output scripts of a transaction contains valid opcodes
static bool CheckTxScriptsSanity(const CMutableTransaction& tx)
{
// Check input scripts for non-coinbase txs
if (!CTransaction(tx).IsCoinBase()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {
return false;
}
}
}
// Check output scripts
for (unsigned int i = 0; i < tx.vout.size(); i++) {
if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {
return false;
}
}
return true;
}
static bool DecodeTx(CMutableTransaction& tx, const std::vector<unsigned char>& tx_data, bool try_no_witness, bool try_witness)
{
// General strategy:
// - Decode both with extended serialization (which interprets the 0x0001 tag as a marker for
// the presence of witnesses) and with legacy serialization (which interprets the tag as a
// 0-input 1-output incomplete transaction).
// - Restricted by try_no_witness (which disables legacy if false) and try_witness (which
// disables extended if false).
// - Ignore serializations that do not fully consume the hex string.
// - If neither succeeds, fail.
// - If only one succeeds, return that one.
// - If both decode attempts succeed:
// - If only one passes the CheckTxScriptsSanity check, return that one.
// - If neither or both pass CheckTxScriptsSanity, return the extended one.
CMutableTransaction tx_extended, tx_legacy;
bool ok_extended = false, ok_legacy = false;
// Try decoding with extended serialization support, and remember if the result successfully
// consumes the entire input.
if (try_witness) {
CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> tx_extended;
if (ssData.empty()) ok_extended = true;
} catch (const std::exception&) {
// Fall through.
}
}
// Optimization: if extended decoding succeeded and the result passes CheckTxScriptsSanity,
// don't bother decoding the other way.
if (ok_extended && CheckTxScriptsSanity(tx_extended)) {
tx = std::move(tx_extended);
return true;
}
// Try decoding with legacy serialization, and remember if the result successfully consumes the entire input.
if (try_no_witness) {
CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
try {
ssData >> tx_legacy;
if (ssData.empty()) ok_legacy = true;
} catch (const std::exception&) {
// Fall through.
}
}
// If legacy decoding succeeded and passes CheckTxScriptsSanity, that's our answer, as we know
// at this point that extended decoding either failed or doesn't pass the sanity check.
if (ok_legacy && CheckTxScriptsSanity(tx_legacy)) {
tx = std::move(tx_legacy);
return true;
}
// If extended decoding succeeded, and neither decoding passes sanity, return the extended one.
if (ok_extended) {
tx = std::move(tx_extended);
return true;
}
// If legacy decoding succeeded and extended didn't, return the legacy one.
if (ok_legacy) {
tx = std::move(tx_legacy);
return true;
}
// If none succeeded, we failed.
return false;
}
bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
{
if (!IsHex(hex_tx)) {
return false;
}
std::vector<unsigned char> txData(ParseHex(hex_tx));
return DecodeTx(tx, txData, try_no_witness, try_witness);
}
bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
{
if (!IsHex(hex_header)) return false;
const std::vector<unsigned char> header_data{ParseHex(hex_header)};
CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ser_header >> header;
} catch (const std::exception&) {
return false;
}
return true;
}
bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
{
if (!IsHex(strHexBlk))
return false;
std::vector<unsigned char> blockData(ParseHex(strHexBlk));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssBlock >> block;
}
catch (const std::exception&) {
return false;
}
return true;
}
bool ParseHashStr(const std::string& strHex, uint256& result)
{
if ((strHex.size() != 64) || !IsHex(strHex))
return false;
result.SetHex(strHex);
return true;
}
std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{
std::string strHex;
if (v.isStr())
strHex = v.getValStr();
if (!IsHex(strHex))
throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
return ParseHex(strHex);
}
int ParseSighashString(const UniValue& sighash)
{
int hash_type = SIGHASH_ALL;
if (!sighash.isNull()) {
static std::map<std::string, int> map_sighash_values = {
{std::string("DEFAULT"), int(SIGHASH_DEFAULT)},
{std::string("ALL"), int(SIGHASH_ALL)},
{std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
{std::string("NONE"), int(SIGHASH_NONE)},
{std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
{std::string("SINGLE"), int(SIGHASH_SINGLE)},
{std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
};
std::string strHashType = sighash.get_str();
const auto& it = map_sighash_values.find(strHashType);
if (it != map_sighash_values.end()) {
hash_type = it->second;
} else {
throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
}
}
return hash_type;
}
|
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <core_io.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>
#include <util/strencodings.h>
#include <version.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <algorithm>
#include <string>
namespace {
opcodetype ParseOpCode(const std::string& s)
{
static std::map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty())
{
for (unsigned int op = 0; op <= MAX_OPCODE; op++)
{
// Allow OP_RESERVED to get into mapOpNames
if (op < OP_NOP && op != OP_RESERVED)
continue;
std::string strName = GetOpName(static_cast<opcodetype>(op));
if (strName == "OP_UNKNOWN")
continue;
mapOpNames[strName] = static_cast<opcodetype>(op);
// Convenience: OP_ADD and just ADD are both recognized:
if (strName.compare(0, 3, "OP_") == 0) { // strName starts with "OP_"
mapOpNames[strName.substr(3)] = static_cast<opcodetype>(op);
}
}
}
auto it = mapOpNames.find(s);
if (it == mapOpNames.end()) throw std::runtime_error("script parse error: unknown opcode");
return it->second;
}
} // namespace
CScript ParseScript(const std::string& s)
{
CScript result;
std::vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
for (const std::string& w : words)
{
if (w.empty())
{
// Empty string, ignore. (boost::split given '' will return one word)
}
else if (std::all_of(w.begin(), w.end(), ::IsDigit) ||
(w.front() == '-' && w.size() > 1 && std::all_of(w.begin()+1, w.end(), ::IsDigit)))
{
// Number
int64_t n = LocaleIndependentAtoi<int64_t>(w);
//limit the range of numbers ParseScript accepts in decimal
//since numbers outside -0xFFFFFFFF...0xFFFFFFFF are illegal in scripts
if (n > int64_t{0xffffffff} || n < -1 * int64_t{0xffffffff}) {
throw std::runtime_error("script parse error: decimal numeric value only allowed in the "
"range -0xFFFFFFFF...0xFFFFFFFF");
}
result << n;
}
else if (w.substr(0,2) == "0x" && w.size() > 2 && IsHex(std::string(w.begin()+2, w.end())))
{
// Raw hex data, inserted NOT pushed onto stack:
std::vector<unsigned char> raw = ParseHex(std::string(w.begin()+2, w.end()));
result.insert(result.end(), raw.begin(), raw.end());
}
else if (w.size() >= 2 && w.front() == '\'' && w.back() == '\'')
{
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't work.
std::vector<unsigned char> value(w.begin()+1, w.end()-1);
result << value;
}
else
{
// opcode, e.g. OP_ADD or ADD:
result << ParseOpCode(w);
}
}
return result;
}
// Check that all of the input and output scripts of a transaction contains valid opcodes
static bool CheckTxScriptsSanity(const CMutableTransaction& tx)
{
// Check input scripts for non-coinbase txs
if (!CTransaction(tx).IsCoinBase()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {
return false;
}
}
}
// Check output scripts
for (unsigned int i = 0; i < tx.vout.size(); i++) {
if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {
return false;
}
}
return true;
}
static bool DecodeTx(CMutableTransaction& tx, const std::vector<unsigned char>& tx_data, bool try_no_witness, bool try_witness)
{
// General strategy:
// - Decode both with extended serialization (which interprets the 0x0001 tag as a marker for
// the presence of witnesses) and with legacy serialization (which interprets the tag as a
// 0-input 1-output incomplete transaction).
// - Restricted by try_no_witness (which disables legacy if false) and try_witness (which
// disables extended if false).
// - Ignore serializations that do not fully consume the hex string.
// - If neither succeeds, fail.
// - If only one succeeds, return that one.
// - If both decode attempts succeed:
// - If only one passes the CheckTxScriptsSanity check, return that one.
// - If neither or both pass CheckTxScriptsSanity, return the extended one.
CMutableTransaction tx_extended, tx_legacy;
bool ok_extended = false, ok_legacy = false;
// Try decoding with extended serialization support, and remember if the result successfully
// consumes the entire input.
if (try_witness) {
CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> tx_extended;
if (ssData.empty()) ok_extended = true;
} catch (const std::exception&) {
// Fall through.
}
}
// Optimization: if extended decoding succeeded and the result passes CheckTxScriptsSanity,
// don't bother decoding the other way.
if (ok_extended && CheckTxScriptsSanity(tx_extended)) {
tx = std::move(tx_extended);
return true;
}
// Try decoding with legacy serialization, and remember if the result successfully consumes the entire input.
if (try_no_witness) {
CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
try {
ssData >> tx_legacy;
if (ssData.empty()) ok_legacy = true;
} catch (const std::exception&) {
// Fall through.
}
}
// If legacy decoding succeeded and passes CheckTxScriptsSanity, that's our answer, as we know
// at this point that extended decoding either failed or doesn't pass the sanity check.
if (ok_legacy && CheckTxScriptsSanity(tx_legacy)) {
tx = std::move(tx_legacy);
return true;
}
// If extended decoding succeeded, and neither decoding passes sanity, return the extended one.
if (ok_extended) {
tx = std::move(tx_extended);
return true;
}
// If legacy decoding succeeded and extended didn't, return the legacy one.
if (ok_legacy) {
tx = std::move(tx_legacy);
return true;
}
// If none succeeded, we failed.
return false;
}
bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
{
if (!IsHex(hex_tx)) {
return false;
}
std::vector<unsigned char> txData(ParseHex(hex_tx));
return DecodeTx(tx, txData, try_no_witness, try_witness);
}
bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
{
if (!IsHex(hex_header)) return false;
const std::vector<unsigned char> header_data{ParseHex(hex_header)};
CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ser_header >> header;
} catch (const std::exception&) {
return false;
}
return true;
}
bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
{
if (!IsHex(strHexBlk))
return false;
std::vector<unsigned char> blockData(ParseHex(strHexBlk));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssBlock >> block;
}
catch (const std::exception&) {
return false;
}
return true;
}
bool ParseHashStr(const std::string& strHex, uint256& result)
{
if ((strHex.size() != 64) || !IsHex(strHex))
return false;
result.SetHex(strHex);
return true;
}
std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{
std::string strHex;
if (v.isStr())
strHex = v.getValStr();
if (!IsHex(strHex))
throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
return ParseHex(strHex);
}
int ParseSighashString(const UniValue& sighash)
{
int hash_type = SIGHASH_ALL;
if (!sighash.isNull()) {
static std::map<std::string, int> map_sighash_values = {
{std::string("DEFAULT"), int(SIGHASH_DEFAULT)},
{std::string("ALL"), int(SIGHASH_ALL)},
{std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
{std::string("NONE"), int(SIGHASH_NONE)},
{std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
{std::string("SINGLE"), int(SIGHASH_SINGLE)},
{std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
};
std::string strHashType = sighash.get_str();
const auto& it = map_sighash_values.find(strHashType);
if (it != map_sighash_values.end()) {
hash_type = it->second;
} else {
throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
}
}
return hash_type;
}
|
Use C++11 range based for loop in ParseScript
|
refactor: Use C++11 range based for loop in ParseScript
|
C++
|
mit
|
mm-s/bitcoin,jambolo/bitcoin,anditto/bitcoin,namecoin/namecoin-core,domob1812/bitcoin,bitcoinknots/bitcoin,bitcoinknots/bitcoin,tecnovert/particl-core,jlopp/statoshi,andreaskern/bitcoin,domob1812/namecore,namecoin/namecoin-core,AkioNak/bitcoin,tecnovert/particl-core,pataquets/namecoin-core,mm-s/bitcoin,bitcoinsSG/bitcoin,GroestlCoin/bitcoin,fanquake/bitcoin,anditto/bitcoin,anditto/bitcoin,bitcoinsSG/bitcoin,dscotese/bitcoin,instagibbs/bitcoin,bitcoinsSG/bitcoin,ajtowns/bitcoin,instagibbs/bitcoin,GroestlCoin/GroestlCoin,bitcoinknots/bitcoin,instagibbs/bitcoin,sipsorcery/bitcoin,mm-s/bitcoin,GroestlCoin/bitcoin,AkioNak/bitcoin,GroestlCoin/GroestlCoin,sstone/bitcoin,ajtowns/bitcoin,jamesob/bitcoin,mm-s/bitcoin,pataquets/namecoin-core,particl/particl-core,andreaskern/bitcoin,sstone/bitcoin,sstone/bitcoin,sipsorcery/bitcoin,fanquake/bitcoin,bitcoinsSG/bitcoin,mm-s/bitcoin,instagibbs/bitcoin,anditto/bitcoin,mruddy/bitcoin,mm-s/bitcoin,achow101/bitcoin,tecnovert/particl-core,domob1812/bitcoin,anditto/bitcoin,MarcoFalke/bitcoin,lateminer/bitcoin,andreaskern/bitcoin,pataquets/namecoin-core,tecnovert/particl-core,bitcoin/bitcoin,Xekyo/bitcoin,fanquake/bitcoin,kallewoof/bitcoin,domob1812/bitcoin,prusnak/bitcoin,domob1812/bitcoin,ajtowns/bitcoin,namecoin/namecore,domob1812/bitcoin,fujicoin/fujicoin,bitcoin/bitcoin,ajtowns/bitcoin,mruddy/bitcoin,fujicoin/fujicoin,namecoin/namecoin-core,achow101/bitcoin,MarcoFalke/bitcoin,dscotese/bitcoin,jambolo/bitcoin,GroestlCoin/GroestlCoin,Xekyo/bitcoin,jlopp/statoshi,namecoin/namecore,domob1812/namecore,instagibbs/bitcoin,mruddy/bitcoin,GroestlCoin/bitcoin,MarcoFalke/bitcoin,namecoin/namecore,mruddy/bitcoin,domob1812/namecore,jlopp/statoshi,pataquets/namecoin-core,andreaskern/bitcoin,particl/particl-core,andreaskern/bitcoin,anditto/bitcoin,particl/particl-core,namecoin/namecore,domob1812/namecore,pataquets/namecoin-core,bitcoin/bitcoin,particl/particl-core,lateminer/bitcoin,prusnak/bitcoin,fanquake/bitcoin,bitcoin/bitcoin,sstone/bitcoin,kallewoof/bitcoin,GroestlCoin/bitcoin,lateminer/bitcoin,domob1812/bitcoin,Xekyo/bitcoin,AkioNak/bitcoin,lateminer/bitcoin,jlopp/statoshi,tecnovert/particl-core,ajtowns/bitcoin,jamesob/bitcoin,bitcoinsSG/bitcoin,kallewoof/bitcoin,prusnak/bitcoin,instagibbs/bitcoin,bitcoin/bitcoin,achow101/bitcoin,sipsorcery/bitcoin,achow101/bitcoin,dscotese/bitcoin,Xekyo/bitcoin,jambolo/bitcoin,GroestlCoin/bitcoin,tecnovert/particl-core,achow101/bitcoin,namecoin/namecoin-core,GroestlCoin/GroestlCoin,prusnak/bitcoin,AkioNak/bitcoin,GroestlCoin/GroestlCoin,kallewoof/bitcoin,namecoin/namecore,kallewoof/bitcoin,fanquake/bitcoin,MarcoFalke/bitcoin,fujicoin/fujicoin,lateminer/bitcoin,sipsorcery/bitcoin,namecoin/namecoin-core,MarcoFalke/bitcoin,lateminer/bitcoin,pataquets/namecoin-core,sstone/bitcoin,jambolo/bitcoin,andreaskern/bitcoin,dscotese/bitcoin,namecoin/namecore,Xekyo/bitcoin,namecoin/namecoin-core,domob1812/namecore,fujicoin/fujicoin,domob1812/namecore,dscotese/bitcoin,Xekyo/bitcoin,kallewoof/bitcoin,particl/particl-core,achow101/bitcoin,AkioNak/bitcoin,jlopp/statoshi,bitcoinknots/bitcoin,sipsorcery/bitcoin,prusnak/bitcoin,jambolo/bitcoin,jamesob/bitcoin,bitcoin/bitcoin,mruddy/bitcoin,jlopp/statoshi,particl/particl-core,sstone/bitcoin,dscotese/bitcoin,sipsorcery/bitcoin,prusnak/bitcoin,AkioNak/bitcoin,jambolo/bitcoin,jamesob/bitcoin,jamesob/bitcoin,fanquake/bitcoin,fujicoin/fujicoin,mruddy/bitcoin,bitcoinsSG/bitcoin,bitcoinknots/bitcoin,GroestlCoin/bitcoin,fujicoin/fujicoin,GroestlCoin/GroestlCoin,MarcoFalke/bitcoin,ajtowns/bitcoin,jamesob/bitcoin
|
27fc6a38f813b65e5110c77925a335214aec756a
|
src/core_read.cpp
|
src/core_read.cpp
|
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <core_io.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>
#include <util/strencodings.h>
#include <version.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <algorithm>
CScript ParseScript(const std::string& s)
{
CScript result;
static std::map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty())
{
for (unsigned int op = 0; op <= MAX_OPCODE; op++)
{
// Allow OP_RESERVED to get into mapOpNames
if (op < OP_NOP && op != OP_RESERVED)
continue;
const char* name = GetOpName(static_cast<opcodetype>(op));
if (strcmp(name, "OP_UNKNOWN") == 0)
continue;
std::string strName(name);
mapOpNames[strName] = static_cast<opcodetype>(op);
// Convenience: OP_ADD and just ADD are both recognized:
boost::algorithm::replace_first(strName, "OP_", "");
mapOpNames[strName] = static_cast<opcodetype>(op);
}
}
std::vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
{
if (w->empty())
{
// Empty string, ignore. (boost::split given '' will return one word)
}
else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||
(w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))
{
// Number
int64_t n = atoi64(*w);
result << n;
}
else if (w->substr(0,2) == "0x" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))
{
// Raw hex data, inserted NOT pushed onto stack:
std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
result.insert(result.end(), raw.begin(), raw.end());
}
else if (w->size() >= 2 && w->front() == '\'' && w->back() == '\'')
{
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't work.
std::vector<unsigned char> value(w->begin()+1, w->end()-1);
result << value;
}
else if (mapOpNames.count(*w))
{
// opcode, e.g. OP_ADD or ADD:
result << mapOpNames[*w];
}
else
{
throw std::runtime_error("script parse error");
}
}
return result;
}
// Check that all of the input and output scripts of a transaction contains valid opcodes
static bool CheckTxScriptsSanity(const CMutableTransaction& tx)
{
// Check input scripts for non-coinbase txs
if (!CTransaction(tx).IsCoinBase()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {
return false;
}
}
}
// Check output scripts
for (unsigned int i = 0; i < tx.vout.size(); i++) {
if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {
return false;
}
}
return true;
}
bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
{
if (!IsHex(hex_tx)) {
return false;
}
std::vector<unsigned char> txData(ParseHex(hex_tx));
if (try_witness) {
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> tx;
// If transaction looks sane, we don't try other mode even if requested
if (ssData.empty() && (!try_no_witness || CheckTxScriptsSanity(tx))) {
return true;
}
} catch (const std::exception&) {
// Fall through.
}
}
if (try_no_witness) {
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
try {
ssData >> tx;
if (ssData.empty()) {
return true;
}
} catch (const std::exception&) {
// Fall through.
}
}
return false;
}
bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
{
if (!IsHex(hex_header)) return false;
const std::vector<unsigned char> header_data{ParseHex(hex_header)};
CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ser_header >> header;
} catch (const std::exception&) {
return false;
}
return true;
}
bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
{
if (!IsHex(strHexBlk))
return false;
std::vector<unsigned char> blockData(ParseHex(strHexBlk));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssBlock >> block;
}
catch (const std::exception&) {
return false;
}
return true;
}
bool ParseHashStr(const std::string& strHex, uint256& result)
{
if ((strHex.size() != 64) || !IsHex(strHex))
return false;
result.SetHex(strHex);
return true;
}
std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{
std::string strHex;
if (v.isStr())
strHex = v.getValStr();
if (!IsHex(strHex))
throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
return ParseHex(strHex);
}
int ParseSighashString(const UniValue& sighash)
{
int hash_type = SIGHASH_ALL;
if (!sighash.isNull()) {
static std::map<std::string, int> map_sighash_values = {
{std::string("ALL"), int(SIGHASH_ALL)},
{std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
{std::string("NONE"), int(SIGHASH_NONE)},
{std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
{std::string("SINGLE"), int(SIGHASH_SINGLE)},
{std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
};
std::string strHashType = sighash.get_str();
const auto& it = map_sighash_values.find(strHashType);
if (it != map_sighash_values.end()) {
hash_type = it->second;
} else {
throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
}
}
return hash_type;
}
|
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <core_io.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <script/sign.h>
#include <serialize.h>
#include <streams.h>
#include <univalue.h>
#include <util/strencodings.h>
#include <version.h>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <algorithm>
CScript ParseScript(const std::string& s)
{
CScript result;
static std::map<std::string, opcodetype> mapOpNames;
if (mapOpNames.empty())
{
for (unsigned int op = 0; op <= MAX_OPCODE; op++)
{
// Allow OP_RESERVED to get into mapOpNames
if (op < OP_NOP && op != OP_RESERVED)
continue;
const char* name = GetOpName(static_cast<opcodetype>(op));
if (strcmp(name, "OP_UNKNOWN") == 0)
continue;
std::string strName(name);
mapOpNames[strName] = static_cast<opcodetype>(op);
// Convenience: OP_ADD and just ADD are both recognized:
boost::algorithm::replace_first(strName, "OP_", "");
mapOpNames[strName] = static_cast<opcodetype>(op);
}
}
std::vector<std::string> words;
boost::algorithm::split(words, s, boost::algorithm::is_any_of(" \t\n"), boost::algorithm::token_compress_on);
for (std::vector<std::string>::const_iterator w = words.begin(); w != words.end(); ++w)
{
if (w->empty())
{
// Empty string, ignore. (boost::split given '' will return one word)
}
else if (std::all_of(w->begin(), w->end(), ::IsDigit) ||
(w->front() == '-' && w->size() > 1 && std::all_of(w->begin()+1, w->end(), ::IsDigit)))
{
// Number
int64_t n = atoi64(*w);
result << n;
}
else if (w->substr(0,2) == "0x" && w->size() > 2 && IsHex(std::string(w->begin()+2, w->end())))
{
// Raw hex data, inserted NOT pushed onto stack:
std::vector<unsigned char> raw = ParseHex(std::string(w->begin()+2, w->end()));
result.insert(result.end(), raw.begin(), raw.end());
}
else if (w->size() >= 2 && w->front() == '\'' && w->back() == '\'')
{
// Single-quoted string, pushed as data. NOTE: this is poor-man's
// parsing, spaces/tabs/newlines in single-quoted strings won't work.
std::vector<unsigned char> value(w->begin()+1, w->end()-1);
result << value;
}
else if (mapOpNames.count(*w))
{
// opcode, e.g. OP_ADD or ADD:
result << mapOpNames[*w];
}
else
{
throw std::runtime_error("script parse error");
}
}
return result;
}
// Check that all of the input and output scripts of a transaction contains valid opcodes
static bool CheckTxScriptsSanity(const CMutableTransaction& tx)
{
// Check input scripts for non-coinbase txs
if (!CTransaction(tx).IsCoinBase()) {
for (unsigned int i = 0; i < tx.vin.size(); i++) {
if (!tx.vin[i].scriptSig.HasValidOps() || tx.vin[i].scriptSig.size() > MAX_SCRIPT_SIZE) {
return false;
}
}
}
// Check output scripts
for (unsigned int i = 0; i < tx.vout.size(); i++) {
if (!tx.vout[i].scriptPubKey.HasValidOps() || tx.vout[i].scriptPubKey.size() > MAX_SCRIPT_SIZE) {
return false;
}
}
return true;
}
static bool DecodeTx(CMutableTransaction& tx, const std::vector<unsigned char>& tx_data, bool try_no_witness, bool try_witness)
{
if (try_witness) {
CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ssData >> tx;
// If transaction looks sane, we don't try other mode even if requested
if (ssData.empty() && (!try_no_witness || CheckTxScriptsSanity(tx))) {
return true;
}
} catch (const std::exception&) {
// Fall through.
}
}
if (try_no_witness) {
CDataStream ssData(tx_data, SER_NETWORK, PROTOCOL_VERSION | SERIALIZE_TRANSACTION_NO_WITNESS);
try {
ssData >> tx;
if (ssData.empty()) {
return true;
}
} catch (const std::exception&) {
// Fall through.
}
}
return false;
}
bool DecodeHexTx(CMutableTransaction& tx, const std::string& hex_tx, bool try_no_witness, bool try_witness)
{
if (!IsHex(hex_tx)) {
return false;
}
std::vector<unsigned char> txData(ParseHex(hex_tx));
return DecodeTx(tx, txData, try_no_witness, try_witness);
}
bool DecodeHexBlockHeader(CBlockHeader& header, const std::string& hex_header)
{
if (!IsHex(hex_header)) return false;
const std::vector<unsigned char> header_data{ParseHex(hex_header)};
CDataStream ser_header(header_data, SER_NETWORK, PROTOCOL_VERSION);
try {
ser_header >> header;
} catch (const std::exception&) {
return false;
}
return true;
}
bool DecodeHexBlk(CBlock& block, const std::string& strHexBlk)
{
if (!IsHex(strHexBlk))
return false;
std::vector<unsigned char> blockData(ParseHex(strHexBlk));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
try {
ssBlock >> block;
}
catch (const std::exception&) {
return false;
}
return true;
}
bool ParseHashStr(const std::string& strHex, uint256& result)
{
if ((strHex.size() != 64) || !IsHex(strHex))
return false;
result.SetHex(strHex);
return true;
}
std::vector<unsigned char> ParseHexUV(const UniValue& v, const std::string& strName)
{
std::string strHex;
if (v.isStr())
strHex = v.getValStr();
if (!IsHex(strHex))
throw std::runtime_error(strName + " must be hexadecimal string (not '" + strHex + "')");
return ParseHex(strHex);
}
int ParseSighashString(const UniValue& sighash)
{
int hash_type = SIGHASH_ALL;
if (!sighash.isNull()) {
static std::map<std::string, int> map_sighash_values = {
{std::string("ALL"), int(SIGHASH_ALL)},
{std::string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)},
{std::string("NONE"), int(SIGHASH_NONE)},
{std::string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)},
{std::string("SINGLE"), int(SIGHASH_SINGLE)},
{std::string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)},
};
std::string strHashType = sighash.get_str();
const auto& it = map_sighash_values.find(strHashType);
if (it != map_sighash_values.end()) {
hash_type = it->second;
} else {
throw std::runtime_error(strHashType + " is not a valid sighash parameter.");
}
}
return hash_type;
}
|
Break out transaction decoding logic into own function
|
DecodeHexTx: Break out transaction decoding logic into own function
|
C++
|
mit
|
achow101/bitcoin,practicalswift/bitcoin,MeshCollider/bitcoin,jambolo/bitcoin,ElementsProject/elements,EthanHeilman/bitcoin,mruddy/bitcoin,achow101/bitcoin,Xekyo/bitcoin,jambolo/bitcoin,namecoin/namecoin-core,qtumproject/qtum,rnicoll/dogecoin,domob1812/bitcoin,pstratem/bitcoin,JeremyRubin/bitcoin,andreaskern/bitcoin,particl/particl-core,Xekyo/bitcoin,kallewoof/bitcoin,dscotese/bitcoin,jnewbery/bitcoin,pstratem/bitcoin,sstone/bitcoin,rnicoll/bitcoin,GroestlCoin/bitcoin,rnicoll/dogecoin,apoelstra/bitcoin,domob1812/bitcoin,n1bor/bitcoin,ElementsProject/elements,namecoin/namecore,litecoin-project/litecoin,fujicoin/fujicoin,sipsorcery/bitcoin,lateminer/bitcoin,JeremyRubin/bitcoin,achow101/bitcoin,Xekyo/bitcoin,domob1812/bitcoin,jonasschnelli/bitcoin,lateminer/bitcoin,apoelstra/bitcoin,bitcoinsSG/bitcoin,namecoin/namecore,sstone/bitcoin,n1bor/bitcoin,yenliangl/bitcoin,kallewoof/bitcoin,domob1812/namecore,JeremyRubin/bitcoin,sstone/bitcoin,jamesob/bitcoin,mm-s/bitcoin,ElementsProject/elements,rnicoll/bitcoin,prusnak/bitcoin,EthanHeilman/bitcoin,yenliangl/bitcoin,GroestlCoin/GroestlCoin,jonasschnelli/bitcoin,lateminer/bitcoin,pataquets/namecoin-core,fanquake/bitcoin,instagibbs/bitcoin,sipsorcery/bitcoin,particl/particl-core,namecoin/namecoin-core,namecoin/namecoin-core,jamesob/bitcoin,alecalve/bitcoin,tecnovert/particl-core,litecoin-project/litecoin,bitcoinknots/bitcoin,kallewoof/bitcoin,particl/particl-core,mm-s/bitcoin,namecoin/namecore,prusnak/bitcoin,instagibbs/bitcoin,rnicoll/bitcoin,mm-s/bitcoin,jamesob/bitcoin,AkioNak/bitcoin,bitcoinknots/bitcoin,JeremyRubin/bitcoin,instagibbs/bitcoin,litecoin-project/litecoin,fujicoin/fujicoin,litecoin-project/litecoin,jamesob/bitcoin,qtumproject/qtum,GroestlCoin/GroestlCoin,yenliangl/bitcoin,bitcoinsSG/bitcoin,Sjors/bitcoin,Sjors/bitcoin,namecoin/namecore,MarcoFalke/bitcoin,tecnovert/particl-core,yenliangl/bitcoin,sipsorcery/bitcoin,anditto/bitcoin,ElementsProject/elements,dscotese/bitcoin,n1bor/bitcoin,pstratem/bitcoin,GroestlCoin/GroestlCoin,GroestlCoin/bitcoin,pstratem/bitcoin,ajtowns/bitcoin,cdecker/bitcoin,domob1812/namecore,bitcoinknots/bitcoin,sipsorcery/bitcoin,qtumproject/qtum,ElementsProject/elements,Sjors/bitcoin,AkioNak/bitcoin,yenliangl/bitcoin,ajtowns/bitcoin,alecalve/bitcoin,bitcoinsSG/bitcoin,AkioNak/bitcoin,yenliangl/bitcoin,namecoin/namecoin-core,mruddy/bitcoin,rnicoll/dogecoin,jlopp/statoshi,MeshCollider/bitcoin,dscotese/bitcoin,andreaskern/bitcoin,alecalve/bitcoin,andreaskern/bitcoin,jnewbery/bitcoin,andreaskern/bitcoin,litecoin-project/litecoin,fanquake/bitcoin,tecnovert/particl-core,alecalve/bitcoin,cdecker/bitcoin,bitcoinknots/bitcoin,mm-s/bitcoin,kallewoof/bitcoin,jnewbery/bitcoin,jambolo/bitcoin,MeshCollider/bitcoin,instagibbs/bitcoin,cdecker/bitcoin,pataquets/namecoin-core,MarcoFalke/bitcoin,Xekyo/bitcoin,domob1812/namecore,domob1812/bitcoin,MeshCollider/bitcoin,rnicoll/bitcoin,apoelstra/bitcoin,alecalve/bitcoin,bitcoin/bitcoin,jamesob/bitcoin,apoelstra/bitcoin,ajtowns/bitcoin,EthanHeilman/bitcoin,bitcoinknots/bitcoin,lateminer/bitcoin,MarcoFalke/bitcoin,prusnak/bitcoin,sstone/bitcoin,namecoin/namecore,domob1812/namecore,mruddy/bitcoin,rnicoll/dogecoin,MeshCollider/bitcoin,fanquake/bitcoin,GroestlCoin/bitcoin,pstratem/bitcoin,JeremyRubin/bitcoin,prusnak/bitcoin,sstone/bitcoin,jambolo/bitcoin,cdecker/bitcoin,mm-s/bitcoin,litecoin-project/litecoin,jlopp/statoshi,achow101/bitcoin,n1bor/bitcoin,MeshCollider/bitcoin,qtumproject/qtum,bitcoinsSG/bitcoin,mruddy/bitcoin,apoelstra/bitcoin,fujicoin/fujicoin,apoelstra/bitcoin,AkioNak/bitcoin,GroestlCoin/bitcoin,jlopp/statoshi,fujicoin/fujicoin,fanquake/bitcoin,sipsorcery/bitcoin,GroestlCoin/GroestlCoin,anditto/bitcoin,prusnak/bitcoin,ajtowns/bitcoin,Sjors/bitcoin,n1bor/bitcoin,dscotese/bitcoin,fujicoin/fujicoin,anditto/bitcoin,jonasschnelli/bitcoin,jambolo/bitcoin,lateminer/bitcoin,achow101/bitcoin,domob1812/namecore,ajtowns/bitcoin,AkioNak/bitcoin,n1bor/bitcoin,dscotese/bitcoin,tecnovert/particl-core,jambolo/bitcoin,GroestlCoin/bitcoin,MarcoFalke/bitcoin,EthanHeilman/bitcoin,practicalswift/bitcoin,jlopp/statoshi,instagibbs/bitcoin,cdecker/bitcoin,bitcoin/bitcoin,fanquake/bitcoin,domob1812/bitcoin,Sjors/bitcoin,tecnovert/particl-core,qtumproject/qtum,jlopp/statoshi,AkioNak/bitcoin,cdecker/bitcoin,rnicoll/dogecoin,JeremyRubin/bitcoin,fujicoin/fujicoin,pataquets/namecoin-core,dscotese/bitcoin,pstratem/bitcoin,bitcoinsSG/bitcoin,pataquets/namecoin-core,kallewoof/bitcoin,Xekyo/bitcoin,jonasschnelli/bitcoin,qtumproject/qtum,anditto/bitcoin,bitcoin/bitcoin,sstone/bitcoin,qtumproject/qtum,MarcoFalke/bitcoin,namecoin/namecoin-core,jonasschnelli/bitcoin,alecalve/bitcoin,jnewbery/bitcoin,EthanHeilman/bitcoin,mruddy/bitcoin,Xekyo/bitcoin,practicalswift/bitcoin,kallewoof/bitcoin,practicalswift/bitcoin,andreaskern/bitcoin,MarcoFalke/bitcoin,tecnovert/particl-core,domob1812/namecore,GroestlCoin/GroestlCoin,EthanHeilman/bitcoin,sipsorcery/bitcoin,jlopp/statoshi,GroestlCoin/bitcoin,instagibbs/bitcoin,fanquake/bitcoin,rnicoll/bitcoin,pataquets/namecoin-core,achow101/bitcoin,bitcoin/bitcoin,mm-s/bitcoin,jamesob/bitcoin,bitcoin/bitcoin,bitcoinsSG/bitcoin,rnicoll/bitcoin,andreaskern/bitcoin,lateminer/bitcoin,namecoin/namecoin-core,namecoin/namecore,particl/particl-core,prusnak/bitcoin,pataquets/namecoin-core,particl/particl-core,mruddy/bitcoin,ajtowns/bitcoin,practicalswift/bitcoin,jnewbery/bitcoin,ElementsProject/elements,anditto/bitcoin,anditto/bitcoin,bitcoin/bitcoin,particl/particl-core,GroestlCoin/GroestlCoin,practicalswift/bitcoin,domob1812/bitcoin
|
e2f5a3ccb55dfc8c8b811ab44ebbd0f3fa841785
|
src/Native/Unix/System.Native/pal_interfaceaddresses.cpp
|
src/Native/Unix/System.Native/pal_interfaceaddresses.cpp
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "pal_config.h"
#include "pal_interfaceaddresses.h"
#include "pal_maphardwaretype.h"
#include "pal_utilities.h"
#include <sys/types.h>
#include <assert.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#if HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#if defined(AF_PACKET)
#include <linux/if_packet.h>
#elif defined(AF_LINK)
#include <net/if_dl.h>
#include <net/if_types.h>
#else
#error System must have AF_PACKET or AF_LINK.
#endif
#if HAVE_RT_MSGHDR
#include <net/route.h>
#endif
extern "C" int32_t SystemNative_EnumerateInterfaceAddresses(IPv4AddressFound onIpv4Found,
IPv6AddressFound onIpv6Found,
LinkLayerAddressFound onLinkLayerFound)
{
ifaddrs* headAddr;
if (getifaddrs(&headAddr) == -1)
{
return -1;
}
for (ifaddrs* current = headAddr; current != nullptr; current = current->ifa_next)
{
uint32_t interfaceIndex = if_nametoindex(current->ifa_name);
int family = current->ifa_addr->sa_family;
if (family == AF_INET)
{
if (onIpv4Found != nullptr)
{
// IP Address
IpAddressInfo iai;
memset(&iai, 0, sizeof(IpAddressInfo));
iai.InterfaceIndex = interfaceIndex;
iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;
sockaddr_in* sain = reinterpret_cast<sockaddr_in*>(current->ifa_addr);
memcpy(iai.AddressBytes, &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr));
// Net Mask
IpAddressInfo maskInfo;
memset(&maskInfo, 0, sizeof(IpAddressInfo));
maskInfo.InterfaceIndex = interfaceIndex;
maskInfo.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;
sockaddr_in* mask_sain = reinterpret_cast<sockaddr_in*>(current->ifa_netmask);
memcpy(maskInfo.AddressBytes, &mask_sain->sin_addr.s_addr, sizeof(mask_sain->sin_addr.s_addr));
onIpv4Found(current->ifa_name, &iai, &maskInfo);
}
}
else if (family == AF_INET6)
{
if (onIpv6Found != nullptr)
{
IpAddressInfo iai;
memset(&iai, 0, sizeof(IpAddressInfo));
iai.InterfaceIndex = interfaceIndex;
iai.NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS;
sockaddr_in6* sain6 = reinterpret_cast<sockaddr_in6*>(current->ifa_addr);
memcpy(iai.AddressBytes, sain6->sin6_addr.s6_addr, sizeof(sain6->sin6_addr.s6_addr));
uint32_t scopeId = sain6->sin6_scope_id;
onIpv6Found(current->ifa_name, &iai, &scopeId);
}
}
#if defined(AF_PACKET)
else if (family == AF_PACKET)
{
if (onLinkLayerFound != nullptr)
{
sockaddr_ll* sall = reinterpret_cast<sockaddr_ll*>(current->ifa_addr);
LinkLayerAddressInfo lla;
memset(&lla, 0, sizeof(LinkLayerAddressInfo));
lla.InterfaceIndex = interfaceIndex;
lla.NumAddressBytes = sall->sll_halen;
lla.HardwareType = MapHardwareType(sall->sll_hatype);
memcpy(&lla.AddressBytes, &sall->sll_addr, sall->sll_halen);
onLinkLayerFound(current->ifa_name, &lla);
}
}
#elif defined(AF_LINK)
else if (family == AF_LINK)
{
if (onLinkLayerFound != nullptr)
{
sockaddr_dl* sadl = reinterpret_cast<sockaddr_dl*>(current->ifa_addr);
LinkLayerAddressInfo lla = {
.InterfaceIndex = interfaceIndex,
.NumAddressBytes = sadl->sdl_alen,
.HardwareType = MapHardwareType(sadl->sdl_type),
};
memcpy(&lla.AddressBytes, reinterpret_cast<uint8_t*>(LLADDR(sadl)), sadl->sdl_alen);
onLinkLayerFound(current->ifa_name, &lla);
}
}
#endif
}
freeifaddrs(headAddr);
return 0;
}
#if HAVE_RT_MSGHDR
extern "C" int32_t SystemNative_EnumerateGatewayAddressesForInterface(uint32_t interfaceIndex, GatewayAddressFound onGatewayFound)
{
int routeDumpName[] = {CTL_NET, AF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0};
size_t byteCount;
if (sysctl(routeDumpName, 6, nullptr, &byteCount, nullptr, 0) != 0)
{
return -1;
}
uint8_t* buffer = new uint8_t[byteCount];
while (sysctl(routeDumpName, 6, buffer, &byteCount, nullptr, 0) != 0)
{
delete[] buffer;
buffer = new uint8_t[byteCount];
}
rt_msghdr* hdr;
for (size_t i = 0; i < byteCount; i += hdr->rtm_msglen)
{
hdr = reinterpret_cast<rt_msghdr*>(&buffer[i]);
int flags = hdr->rtm_flags;
int isGateway = flags & RTF_GATEWAY;
int gatewayPresent = hdr->rtm_addrs & RTA_GATEWAY;
if (isGateway && gatewayPresent)
{
IpAddressInfo iai = {};
iai.InterfaceIndex = interfaceIndex;
iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;
sockaddr_in* sain = reinterpret_cast<sockaddr_in*>(hdr + 1);
sain = sain + 1; // Skip over the first sockaddr, the destination address. The second is the gateway.
memcpy(iai.AddressBytes, &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr));
onGatewayFound(&iai);
}
}
delete[] buffer;
return 0;
}
#endif // HAVE_RT_MSGHDR
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#include "pal_config.h"
#include "pal_interfaceaddresses.h"
#include "pal_maphardwaretype.h"
#include "pal_utilities.h"
#include <sys/types.h>
#include <assert.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#if HAVE_SYS_SYSCTL_H
#include <sys/sysctl.h>
#endif
#if defined(AF_PACKET)
#include <linux/if_packet.h>
#elif defined(AF_LINK)
#include <net/if_dl.h>
#include <net/if_types.h>
#else
#error System must have AF_PACKET or AF_LINK.
#endif
#if HAVE_RT_MSGHDR
#include <net/route.h>
#endif
extern "C" int32_t SystemNative_EnumerateInterfaceAddresses(IPv4AddressFound onIpv4Found,
IPv6AddressFound onIpv6Found,
LinkLayerAddressFound onLinkLayerFound)
{
ifaddrs* headAddr;
if (getifaddrs(&headAddr) == -1)
{
return -1;
}
for (ifaddrs* current = headAddr; current != nullptr; current = current->ifa_next)
{
uint32_t interfaceIndex = if_nametoindex(current->ifa_name);
// ifa_name may be an aliased interface name.
// Use if_indextoname to map back to the true device name.
char actualName[IF_NAMESIZE];
char* result = if_indextoname(interfaceIndex, actualName);
assert(result == actualName && result != nullptr);
(void)result; // Silence compiler warnings about unused variables on release mode
int family = current->ifa_addr->sa_family;
if (family == AF_INET)
{
if (onIpv4Found != nullptr)
{
// IP Address
IpAddressInfo iai;
memset(&iai, 0, sizeof(IpAddressInfo));
iai.InterfaceIndex = interfaceIndex;
iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;
sockaddr_in* sain = reinterpret_cast<sockaddr_in*>(current->ifa_addr);
memcpy(iai.AddressBytes, &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr));
// Net Mask
IpAddressInfo maskInfo;
memset(&maskInfo, 0, sizeof(IpAddressInfo));
maskInfo.InterfaceIndex = interfaceIndex;
maskInfo.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;
sockaddr_in* mask_sain = reinterpret_cast<sockaddr_in*>(current->ifa_netmask);
memcpy(maskInfo.AddressBytes, &mask_sain->sin_addr.s_addr, sizeof(mask_sain->sin_addr.s_addr));
onIpv4Found(actualName, &iai, &maskInfo);
}
}
else if (family == AF_INET6)
{
if (onIpv6Found != nullptr)
{
IpAddressInfo iai;
memset(&iai, 0, sizeof(IpAddressInfo));
iai.InterfaceIndex = interfaceIndex;
iai.NumAddressBytes = NUM_BYTES_IN_IPV6_ADDRESS;
sockaddr_in6* sain6 = reinterpret_cast<sockaddr_in6*>(current->ifa_addr);
memcpy(iai.AddressBytes, sain6->sin6_addr.s6_addr, sizeof(sain6->sin6_addr.s6_addr));
uint32_t scopeId = sain6->sin6_scope_id;
onIpv6Found(actualName, &iai, &scopeId);
}
}
#if defined(AF_PACKET)
else if (family == AF_PACKET)
{
if (onLinkLayerFound != nullptr)
{
sockaddr_ll* sall = reinterpret_cast<sockaddr_ll*>(current->ifa_addr);
LinkLayerAddressInfo lla;
memset(&lla, 0, sizeof(LinkLayerAddressInfo));
lla.InterfaceIndex = interfaceIndex;
lla.NumAddressBytes = sall->sll_halen;
lla.HardwareType = MapHardwareType(sall->sll_hatype);
memcpy(&lla.AddressBytes, &sall->sll_addr, sall->sll_halen);
onLinkLayerFound(current->ifa_name, &lla);
}
}
#elif defined(AF_LINK)
else if (family == AF_LINK)
{
if (onLinkLayerFound != nullptr)
{
sockaddr_dl* sadl = reinterpret_cast<sockaddr_dl*>(current->ifa_addr);
LinkLayerAddressInfo lla = {
.InterfaceIndex = interfaceIndex,
.NumAddressBytes = sadl->sdl_alen,
.HardwareType = MapHardwareType(sadl->sdl_type),
};
memcpy(&lla.AddressBytes, reinterpret_cast<uint8_t*>(LLADDR(sadl)), sadl->sdl_alen);
onLinkLayerFound(current->ifa_name, &lla);
}
}
#endif
}
freeifaddrs(headAddr);
return 0;
}
#if HAVE_RT_MSGHDR
extern "C" int32_t SystemNative_EnumerateGatewayAddressesForInterface(uint32_t interfaceIndex, GatewayAddressFound onGatewayFound)
{
int routeDumpName[] = {CTL_NET, AF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0};
size_t byteCount;
if (sysctl(routeDumpName, 6, nullptr, &byteCount, nullptr, 0) != 0)
{
return -1;
}
uint8_t* buffer = new uint8_t[byteCount];
while (sysctl(routeDumpName, 6, buffer, &byteCount, nullptr, 0) != 0)
{
delete[] buffer;
buffer = new uint8_t[byteCount];
}
rt_msghdr* hdr;
for (size_t i = 0; i < byteCount; i += hdr->rtm_msglen)
{
hdr = reinterpret_cast<rt_msghdr*>(&buffer[i]);
int flags = hdr->rtm_flags;
int isGateway = flags & RTF_GATEWAY;
int gatewayPresent = hdr->rtm_addrs & RTA_GATEWAY;
if (isGateway && gatewayPresent)
{
IpAddressInfo iai = {};
iai.InterfaceIndex = interfaceIndex;
iai.NumAddressBytes = NUM_BYTES_IN_IPV4_ADDRESS;
sockaddr_in* sain = reinterpret_cast<sockaddr_in*>(hdr + 1);
sain = sain + 1; // Skip over the first sockaddr, the destination address. The second is the gateway.
memcpy(iai.AddressBytes, &sain->sin_addr.s_addr, sizeof(sain->sin_addr.s_addr));
onGatewayFound(&iai);
}
}
delete[] buffer;
return 0;
}
#endif // HAVE_RT_MSGHDR
|
Resolve aliased device names in SystemNative_EnumerateInterfaceAddresses.
|
Resolve aliased device names in SystemNative_EnumerateInterfaceAddresses.
Interface names returned from getifaddrs may refer to an aliased network
device, i.e. "wlan:0". Previously, we were returning this value from the
shim function, and managed code was then treating "wlan" and "wlan:0" to
be distinct network interfaces. Instead, we normalize the interface names
returned from the shim by calling if_indextoname to obtain the "true"
interface name.
|
C++
|
mit
|
yizhang82/corefx,yizhang82/corefx,elijah6/corefx,marksmeltzer/corefx,krk/corefx,mazong1123/corefx,cydhaselton/corefx,tijoytom/corefx,lggomez/corefx,wtgodbe/corefx,the-dwyer/corefx,gkhanna79/corefx,fgreinacher/corefx,alphonsekurian/corefx,stephenmichaelf/corefx,mmitche/corefx,twsouthwick/corefx,weltkante/corefx,cydhaselton/corefx,jlin177/corefx,fgreinacher/corefx,cydhaselton/corefx,dhoehna/corefx,ViktorHofer/corefx,ravimeda/corefx,YoupHulsebos/corefx,seanshpark/corefx,lggomez/corefx,lggomez/corefx,stephenmichaelf/corefx,MaggieTsang/corefx,Jiayili1/corefx,rubo/corefx,zhenlan/corefx,weltkante/corefx,twsouthwick/corefx,nchikanov/corefx,wtgodbe/corefx,yizhang82/corefx,weltkante/corefx,MaggieTsang/corefx,YoupHulsebos/corefx,DnlHarvey/corefx,ViktorHofer/corefx,ViktorHofer/corefx,YoupHulsebos/corefx,parjong/corefx,ericstj/corefx,seanshpark/corefx,the-dwyer/corefx,dhoehna/corefx,ericstj/corefx,dhoehna/corefx,dhoehna/corefx,fgreinacher/corefx,cydhaselton/corefx,rubo/corefx,ptoonen/corefx,Jiayili1/corefx,stephenmichaelf/corefx,seanshpark/corefx,alphonsekurian/corefx,JosephTremoulet/corefx,rahku/corefx,dotnet-bot/corefx,dhoehna/corefx,wtgodbe/corefx,Petermarcu/corefx,twsouthwick/corefx,mmitche/corefx,ericstj/corefx,elijah6/corefx,the-dwyer/corefx,richlander/corefx,alphonsekurian/corefx,DnlHarvey/corefx,seanshpark/corefx,krytarowski/corefx,stone-li/corefx,mazong1123/corefx,Ermiar/corefx,dotnet-bot/corefx,Jiayili1/corefx,DnlHarvey/corefx,ravimeda/corefx,krk/corefx,dotnet-bot/corefx,rahku/corefx,DnlHarvey/corefx,nchikanov/corefx,shimingsg/corefx,rjxby/corefx,stone-li/corefx,nchikanov/corefx,DnlHarvey/corefx,rjxby/corefx,cydhaselton/corefx,lggomez/corefx,elijah6/corefx,wtgodbe/corefx,Jiayili1/corefx,richlander/corefx,ptoonen/corefx,rubo/corefx,parjong/corefx,shimingsg/corefx,billwert/corefx,gkhanna79/corefx,stephenmichaelf/corefx,tijoytom/corefx,ViktorHofer/corefx,mazong1123/corefx,shmao/corefx,rahku/corefx,nchikanov/corefx,seanshpark/corefx,marksmeltzer/corefx,richlander/corefx,elijah6/corefx,nbarbettini/corefx,alphonsekurian/corefx,YoupHulsebos/corefx,Ermiar/corefx,gkhanna79/corefx,Ermiar/corefx,wtgodbe/corefx,weltkante/corefx,alexperovich/corefx,stone-li/corefx,ravimeda/corefx,wtgodbe/corefx,stephenmichaelf/corefx,ericstj/corefx,shmao/corefx,Jiayili1/corefx,shimingsg/corefx,rjxby/corefx,tijoytom/corefx,dhoehna/corefx,mmitche/corefx,ericstj/corefx,DnlHarvey/corefx,the-dwyer/corefx,lggomez/corefx,jlin177/corefx,ptoonen/corefx,axelheer/corefx,dotnet-bot/corefx,YoupHulsebos/corefx,parjong/corefx,stone-li/corefx,BrennanConroy/corefx,cydhaselton/corefx,rjxby/corefx,MaggieTsang/corefx,yizhang82/corefx,zhenlan/corefx,ptoonen/corefx,fgreinacher/corefx,DnlHarvey/corefx,jlin177/corefx,BrennanConroy/corefx,axelheer/corefx,wtgodbe/corefx,alexperovich/corefx,Petermarcu/corefx,ericstj/corefx,tijoytom/corefx,elijah6/corefx,YoupHulsebos/corefx,axelheer/corefx,zhenlan/corefx,nbarbettini/corefx,Jiayili1/corefx,billwert/corefx,ViktorHofer/corefx,alphonsekurian/corefx,shimingsg/corefx,tijoytom/corefx,krk/corefx,tijoytom/corefx,gkhanna79/corefx,parjong/corefx,jlin177/corefx,marksmeltzer/corefx,stephenmichaelf/corefx,twsouthwick/corefx,dhoehna/corefx,rjxby/corefx,Petermarcu/corefx,ravimeda/corefx,Petermarcu/corefx,rjxby/corefx,Jiayili1/corefx,JosephTremoulet/corefx,BrennanConroy/corefx,JosephTremoulet/corefx,mazong1123/corefx,mmitche/corefx,krk/corefx,mmitche/corefx,krytarowski/corefx,dotnet-bot/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,krytarowski/corefx,krk/corefx,rahku/corefx,parjong/corefx,mmitche/corefx,richlander/corefx,billwert/corefx,zhenlan/corefx,weltkante/corefx,marksmeltzer/corefx,lggomez/corefx,Ermiar/corefx,MaggieTsang/corefx,richlander/corefx,jlin177/corefx,JosephTremoulet/corefx,the-dwyer/corefx,ericstj/corefx,billwert/corefx,mazong1123/corefx,twsouthwick/corefx,shimingsg/corefx,MaggieTsang/corefx,zhenlan/corefx,cydhaselton/corefx,ravimeda/corefx,shmao/corefx,alphonsekurian/corefx,parjong/corefx,ptoonen/corefx,zhenlan/corefx,stephenmichaelf/corefx,the-dwyer/corefx,alexperovich/corefx,nbarbettini/corefx,ravimeda/corefx,gkhanna79/corefx,gkhanna79/corefx,shimingsg/corefx,yizhang82/corefx,jlin177/corefx,axelheer/corefx,mmitche/corefx,Petermarcu/corefx,shmao/corefx,nchikanov/corefx,rahku/corefx,Petermarcu/corefx,shmao/corefx,Ermiar/corefx,nbarbettini/corefx,marksmeltzer/corefx,dotnet-bot/corefx,elijah6/corefx,parjong/corefx,ptoonen/corefx,alexperovich/corefx,nbarbettini/corefx,YoupHulsebos/corefx,marksmeltzer/corefx,seanshpark/corefx,shmao/corefx,JosephTremoulet/corefx,gkhanna79/corefx,lggomez/corefx,Petermarcu/corefx,richlander/corefx,stone-li/corefx,alphonsekurian/corefx,ViktorHofer/corefx,billwert/corefx,krytarowski/corefx,shmao/corefx,mazong1123/corefx,yizhang82/corefx,krk/corefx,axelheer/corefx,mazong1123/corefx,stone-li/corefx,krytarowski/corefx,axelheer/corefx,rahku/corefx,stone-li/corefx,ptoonen/corefx,alexperovich/corefx,alexperovich/corefx,marksmeltzer/corefx,alexperovich/corefx,MaggieTsang/corefx,zhenlan/corefx,krytarowski/corefx,weltkante/corefx,billwert/corefx,twsouthwick/corefx,seanshpark/corefx,rahku/corefx,elijah6/corefx,nbarbettini/corefx,rubo/corefx,jlin177/corefx,richlander/corefx,rjxby/corefx,tijoytom/corefx,MaggieTsang/corefx,twsouthwick/corefx,rubo/corefx,yizhang82/corefx,krk/corefx,krytarowski/corefx,the-dwyer/corefx,JosephTremoulet/corefx,nbarbettini/corefx,nchikanov/corefx,billwert/corefx,shimingsg/corefx,ViktorHofer/corefx,Ermiar/corefx,Ermiar/corefx,weltkante/corefx,ravimeda/corefx,nchikanov/corefx
|
551e0a924f2a5bb4ff3d5d528ba0848bcc29f49c
|
chrome/app/nacl_fork_delegate_linux.cc
|
chrome/app/nacl_fork_delegate_linux.cc
|
// 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/app/nacl_fork_delegate_linux.h"
#include <signal.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <set>
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
#include "base/posix/unix_domain_socket_linux.h"
#include "base/process_util.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/nacl_helper_linux.h"
#include "chrome/common/nacl_paths.h"
#include "components/nacl/common/nacl_switches.h"
NaClForkDelegate::NaClForkDelegate()
: status_(kNaClHelperUnused),
fd_(-1) {}
// Note these need to match up with their counterparts in nacl_helper_linux.c
// and nacl_helper_bootstrap_linux.c.
const char kNaClHelperReservedAtZero[] =
"--reserved_at_zero=0xXXXXXXXXXXXXXXXX";
const char kNaClHelperRDebug[] = "--r_debug=0xXXXXXXXXXXXXXXXX";
void NaClForkDelegate::Init(const int sandboxdesc) {
VLOG(1) << "NaClForkDelegate::Init()";
int fds[2];
// Confirm a hard-wired assumption.
// The NaCl constant is from chrome/nacl/nacl_linux_helper.h
DCHECK(kNaClSandboxDescriptor == sandboxdesc);
CHECK(socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) == 0);
base::FileHandleMappingVector fds_to_map;
fds_to_map.push_back(std::make_pair(fds[1], kNaClZygoteDescriptor));
fds_to_map.push_back(std::make_pair(sandboxdesc, kNaClSandboxDescriptor));
status_ = kNaClHelperUnused;
base::FilePath helper_exe;
base::FilePath helper_bootstrap_exe;
if (!PathService::Get(nacl::FILE_NACL_HELPER, &helper_exe)) {
status_ = kNaClHelperMissing;
} else if (!PathService::Get(nacl::FILE_NACL_HELPER_BOOTSTRAP,
&helper_bootstrap_exe)) {
status_ = kNaClHelperBootstrapMissing;
} else if (RunningOnValgrind()) {
status_ = kNaClHelperValgrind;
} else {
CommandLine cmd_line(helper_bootstrap_exe);
cmd_line.AppendArgPath(helper_exe);
cmd_line.AppendArgNative(kNaClHelperReservedAtZero);
cmd_line.AppendArgNative(kNaClHelperRDebug);
base::LaunchOptions options;
options.fds_to_remap = &fds_to_map;
options.clone_flags = CLONE_FS | SIGCHLD;
// The NaCl processes spawned may need to exceed the ambient soft limit
// on RLIMIT_AS to allocate the untrusted address space and its guard
// regions. The nacl_helper itself cannot just raise its own limit,
// because the existing limit may prevent the initial exec of
// nacl_helper_bootstrap from succeeding, with its large address space
// reservation.
std::set<int> max_these_limits;
max_these_limits.insert(RLIMIT_AS);
options.maximize_rlimits = &max_these_limits;
if (!base::LaunchProcess(cmd_line.argv(), options, NULL))
status_ = kNaClHelperLaunchFailed;
// parent and error cases are handled below
}
if (HANDLE_EINTR(close(fds[1])) != 0)
LOG(ERROR) << "close(fds[1]) failed";
if (status_ == kNaClHelperUnused) {
const ssize_t kExpectedLength = strlen(kNaClHelperStartupAck);
char buf[kExpectedLength];
// Wait for ack from nacl_helper, indicating it is ready to help
const ssize_t nread = HANDLE_EINTR(read(fds[0], buf, sizeof(buf)));
if (nread == kExpectedLength &&
memcmp(buf, kNaClHelperStartupAck, nread) == 0) {
// all is well
status_ = kNaClHelperSuccess;
fd_ = fds[0];
return;
}
status_ = kNaClHelperAckFailed;
LOG(ERROR) << "Bad NaCl helper startup ack (" << nread << " bytes)";
}
// TODO(bradchen): Make this LOG(ERROR) when the NaCl helper
// becomes the default.
fd_ = -1;
if (HANDLE_EINTR(close(fds[0])) != 0)
LOG(ERROR) << "close(fds[0]) failed";
}
void NaClForkDelegate::InitialUMA(std::string* uma_name,
int* uma_sample,
int* uma_boundary_value) {
*uma_name = "NaCl.Client.Helper.InitState";
*uma_sample = status_;
*uma_boundary_value = kNaClHelperStatusBoundary;
}
NaClForkDelegate::~NaClForkDelegate() {
// side effect of close: delegate process will terminate
if (status_ == kNaClHelperSuccess) {
if (HANDLE_EINTR(close(fd_)) != 0)
LOG(ERROR) << "close(fd_) failed";
}
}
bool NaClForkDelegate::CanHelp(const std::string& process_type,
std::string* uma_name,
int* uma_sample,
int* uma_boundary_value) {
if (process_type != switches::kNaClLoaderProcess)
return false;
*uma_name = "NaCl.Client.Helper.StateOnFork";
*uma_sample = status_;
*uma_boundary_value = kNaClHelperStatusBoundary;
return status_ == kNaClHelperSuccess;
}
pid_t NaClForkDelegate::Fork(const std::vector<int>& fds) {
base::ProcessId naclchild;
VLOG(1) << "NaClForkDelegate::Fork";
DCHECK(fds.size() == kNaClParentFDIndex + 1);
if (!UnixDomainSocket::SendMsg(fd_, kNaClForkRequest,
strlen(kNaClForkRequest), fds)) {
LOG(ERROR) << "NaClForkDelegate::Fork: SendMsg failed";
return -1;
}
int nread = HANDLE_EINTR(read(fd_, &naclchild, sizeof(naclchild)));
if (nread != sizeof(naclchild)) {
LOG(ERROR) << "NaClForkDelegate::Fork: read failed";
return -1;
}
VLOG(1) << "nacl_child is " << naclchild << " (" << nread << " bytes)";
return naclchild;
}
bool NaClForkDelegate::AckChild(const int fd,
const std::string& channel_switch) {
int nwritten = HANDLE_EINTR(write(fd, channel_switch.c_str(),
channel_switch.length()));
if (nwritten != static_cast<int>(channel_switch.length())) {
return false;
}
return true;
}
|
// 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/app/nacl_fork_delegate_linux.h"
#include <signal.h>
#include <stdlib.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <set>
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/posix/eintr_wrapper.h"
#include "base/posix/unix_domain_socket_linux.h"
#include "base/process_util.h"
#include "base/third_party/dynamic_annotations/dynamic_annotations.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/nacl_helper_linux.h"
#include "chrome/common/nacl_paths.h"
#include "components/nacl/common/nacl_switches.h"
namespace {
// Using nacl_helper_bootstrap is not necessary on x86-64 because
// NaCl's x86-64 sandbox is not zero-address-based. Starting
// nacl_helper through nacl_helper_bootstrap works on x86-64, but it
// leaves nacl_helper_bootstrap mapped at a fixed address at the
// bottom of the address space, which is undesirable because it
// effectively defeats ASLR.
#if defined(ARCH_CPU_X86_64)
const bool kUseNaClBootstrap = false;
#else
const bool kUseNaClBootstrap = true;
#endif
// Note these need to match up with their counterparts in nacl_helper_linux.c
// and nacl_helper_bootstrap_linux.c.
const char kNaClHelperReservedAtZero[] =
"--reserved_at_zero=0xXXXXXXXXXXXXXXXX";
const char kNaClHelperRDebug[] = "--r_debug=0xXXXXXXXXXXXXXXXX";
}
NaClForkDelegate::NaClForkDelegate()
: status_(kNaClHelperUnused),
fd_(-1) {}
void NaClForkDelegate::Init(const int sandboxdesc) {
VLOG(1) << "NaClForkDelegate::Init()";
int fds[2];
// Confirm a hard-wired assumption.
// The NaCl constant is from chrome/nacl/nacl_linux_helper.h
DCHECK(kNaClSandboxDescriptor == sandboxdesc);
CHECK(socketpair(PF_UNIX, SOCK_SEQPACKET, 0, fds) == 0);
base::FileHandleMappingVector fds_to_map;
fds_to_map.push_back(std::make_pair(fds[1], kNaClZygoteDescriptor));
fds_to_map.push_back(std::make_pair(sandboxdesc, kNaClSandboxDescriptor));
status_ = kNaClHelperUnused;
base::FilePath helper_exe;
base::FilePath helper_bootstrap_exe;
if (!PathService::Get(nacl::FILE_NACL_HELPER, &helper_exe)) {
status_ = kNaClHelperMissing;
} else if (kUseNaClBootstrap &&
!PathService::Get(nacl::FILE_NACL_HELPER_BOOTSTRAP,
&helper_bootstrap_exe)) {
status_ = kNaClHelperBootstrapMissing;
} else if (RunningOnValgrind()) {
status_ = kNaClHelperValgrind;
} else {
CommandLine cmd_line(CommandLine::NO_PROGRAM);
if (kUseNaClBootstrap) {
cmd_line.SetProgram(helper_bootstrap_exe);
cmd_line.AppendArgPath(helper_exe);
cmd_line.AppendArgNative(kNaClHelperReservedAtZero);
cmd_line.AppendArgNative(kNaClHelperRDebug);
} else {
cmd_line.SetProgram(helper_exe);
}
base::LaunchOptions options;
options.fds_to_remap = &fds_to_map;
options.clone_flags = CLONE_FS | SIGCHLD;
// The NaCl processes spawned may need to exceed the ambient soft limit
// on RLIMIT_AS to allocate the untrusted address space and its guard
// regions. The nacl_helper itself cannot just raise its own limit,
// because the existing limit may prevent the initial exec of
// nacl_helper_bootstrap from succeeding, with its large address space
// reservation.
std::set<int> max_these_limits;
max_these_limits.insert(RLIMIT_AS);
options.maximize_rlimits = &max_these_limits;
if (!base::LaunchProcess(cmd_line.argv(), options, NULL))
status_ = kNaClHelperLaunchFailed;
// parent and error cases are handled below
}
if (HANDLE_EINTR(close(fds[1])) != 0)
LOG(ERROR) << "close(fds[1]) failed";
if (status_ == kNaClHelperUnused) {
const ssize_t kExpectedLength = strlen(kNaClHelperStartupAck);
char buf[kExpectedLength];
// Wait for ack from nacl_helper, indicating it is ready to help
const ssize_t nread = HANDLE_EINTR(read(fds[0], buf, sizeof(buf)));
if (nread == kExpectedLength &&
memcmp(buf, kNaClHelperStartupAck, nread) == 0) {
// all is well
status_ = kNaClHelperSuccess;
fd_ = fds[0];
return;
}
status_ = kNaClHelperAckFailed;
LOG(ERROR) << "Bad NaCl helper startup ack (" << nread << " bytes)";
}
// TODO(bradchen): Make this LOG(ERROR) when the NaCl helper
// becomes the default.
fd_ = -1;
if (HANDLE_EINTR(close(fds[0])) != 0)
LOG(ERROR) << "close(fds[0]) failed";
}
void NaClForkDelegate::InitialUMA(std::string* uma_name,
int* uma_sample,
int* uma_boundary_value) {
*uma_name = "NaCl.Client.Helper.InitState";
*uma_sample = status_;
*uma_boundary_value = kNaClHelperStatusBoundary;
}
NaClForkDelegate::~NaClForkDelegate() {
// side effect of close: delegate process will terminate
if (status_ == kNaClHelperSuccess) {
if (HANDLE_EINTR(close(fd_)) != 0)
LOG(ERROR) << "close(fd_) failed";
}
}
bool NaClForkDelegate::CanHelp(const std::string& process_type,
std::string* uma_name,
int* uma_sample,
int* uma_boundary_value) {
if (process_type != switches::kNaClLoaderProcess)
return false;
*uma_name = "NaCl.Client.Helper.StateOnFork";
*uma_sample = status_;
*uma_boundary_value = kNaClHelperStatusBoundary;
return status_ == kNaClHelperSuccess;
}
pid_t NaClForkDelegate::Fork(const std::vector<int>& fds) {
base::ProcessId naclchild;
VLOG(1) << "NaClForkDelegate::Fork";
DCHECK(fds.size() == kNaClParentFDIndex + 1);
if (!UnixDomainSocket::SendMsg(fd_, kNaClForkRequest,
strlen(kNaClForkRequest), fds)) {
LOG(ERROR) << "NaClForkDelegate::Fork: SendMsg failed";
return -1;
}
int nread = HANDLE_EINTR(read(fd_, &naclchild, sizeof(naclchild)));
if (nread != sizeof(naclchild)) {
LOG(ERROR) << "NaClForkDelegate::Fork: read failed";
return -1;
}
VLOG(1) << "nacl_child is " << naclchild << " (" << nread << " bytes)";
return naclchild;
}
bool NaClForkDelegate::AckChild(const int fd,
const std::string& channel_switch) {
int nwritten = HANDLE_EINTR(write(fd, channel_switch.c_str(),
channel_switch.length()));
if (nwritten != static_cast<int>(channel_switch.length())) {
return false;
}
return true;
}
|
Disable use of nacl_helper_bootstrap on x86-64
|
NaCl: Disable use of nacl_helper_bootstrap on x86-64
This stops nacl_helper_bootstrap from being left mapped at a fixed
address at the bottom of address space on x86-64, which effectively
defeats ASLR. Currently, this makes little difference because a NaCl
app can easily find the sandbox's base address, but we are aiming to
hide the sandbox base address under PNaCl.
This change means that nacl_helper_bootstrap in Chrome will
unfortunately no longer be tested by the default Linux trybot runs,
which cover x86-64. nacl_helper_bootstrap will only be used on x86-32
and ARM.
Also move two constants to be defined in a private namespace.
BUG=https://code.google.com/p/nativeclient/issues/detail?id=3584
TEST=browser_tests
Review URL: https://codereview.chromium.org/19793010
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@212997 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
hgl888/chromium-crosswalk-efl,M4sse/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,ondra-novak/chromium.src,patrickm/chromium.src,Jonekee/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,patrickm/chromium.src,M4sse/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,ChromiumWebApps/chromium,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,ChromiumWebApps/chromium,ondra-novak/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,ondra-novak/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,ltilve/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,jaruba/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,M4sse/chromium.src,ltilve/chromium,littlstar/chromium.src,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,anirudhSK/chromium,M4sse/chromium.src,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,ltilve/chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Just-D/chromium-1,Jonekee/chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,littlstar/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,Jonekee/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,littlstar/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,ltilve/chromium,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,anirudhSK/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,chuan9/chromium-crosswalk,Jonekee/chromium.src,anirudhSK/chromium,dednal/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,dednal/chromium.src,dednal/chromium.src,Just-D/chromium-1,chuan9/chromium-crosswalk,Just-D/chromium-1,fujunwei/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,Chilledheart/chromium,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,M4sse/chromium.src,ltilve/chromium,Chilledheart/chromium,jaruba/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,markYoungH/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,hgl888/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,dednal/chromium.src
|
183485b0641615a1b7b785baedd128b140e50cf9
|
ComponentFilter.cpp
|
ComponentFilter.cpp
|
#include "ComponentFilter.h"
#include <opencv2/imgproc/imgproc.hpp>
#ifdef _DEBUG
#include <iterator> // std::inserter
#endif
ComponentFilterCriterionInput::ComponentFilterCriterionInput(const cv::Mat& inputImage, const std::vector<cv::Point>& contour)
: inputImage(inputImage), contour(contour)
{}
cv::Mat DecideFindContoursTemp(const cv::Mat& input, cv::Mat& output, ComponentFilterTemp& temp)
{
if (input.data == output.data) {
// In-place operation
input.copyTo(temp.findContoursTemp);
return temp.findContoursTemp;
}
else {
input.copyTo(output);
return output;
}
}
unsigned int ComponentFilter(const cv::Mat& input, cv::Mat& output, const ComponentFilterCriterion& criterion, ComponentFilterTemp& temp)
{
cv::Mat findContoursTemp = DecideFindContoursTemp(input, output, temp);
cv::findContours(findContoursTemp, temp.contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
output.setTo(0);
for (size_t i = 0, end = temp.contours.size(); i < end; ++i) {
ComponentFilterCriterionInput componentFilterCriterionInput(input, temp.contours[i]);
if (criterion(componentFilterCriterionInput)) {
cv::drawContours(output, temp.contours, static_cast<int>(i), std::numeric_limits<unsigned char>::max(), -1);
}
}
#ifdef _DEBUG
// We can only filter - we can't introduce any new components. Ever.
std::vector<cv::Point> inputPoints, outputPoints, outputPointsLessInputPoints;
if (cv::countNonZero(input)) {
cv::findNonZero(input, inputPoints);
}
if (cv::countNonZero(output)) {
cv::findNonZero(output, outputPoints);
}
const auto sortCriterion = [](const cv::Point& point1, const cv::Point& point2) {
return point1.x < point2.x || ((point1.x == point2.x && point1.y < point2.y));
};
std::sort(inputPoints.begin(), inputPoints.end(), sortCriterion);
std::sort(outputPoints.begin(), outputPoints.end(), sortCriterion);
std::set_difference(outputPoints.begin(), outputPoints.end(), inputPoints.begin(), inputPoints.end(), std::inserter(outputPointsLessInputPoints, outputPointsLessInputPoints.begin()), sortCriterion);
assert(outputPointsLessInputPoints.empty());
#endif
return static_cast<unsigned int>(temp.contours.size());
}
|
#include "ComponentFilter.h"
#include <opencv2/imgproc/imgproc.hpp>
#ifdef _DEBUG
#include <iterator> // std::inserter
#endif
ComponentFilterCriterionInput::ComponentFilterCriterionInput(const cv::Mat& inputImage, const std::vector<cv::Point>& contour)
: inputImage(inputImage), contour(contour)
{}
cv::Mat DecideFindContoursTemp(const cv::Mat& input, cv::Mat& output, ComponentFilterTemp& temp)
{
if (input.data == output.data) {
// In-place operation
input.copyTo(temp.findContoursTemp);
return temp.findContoursTemp;
}
else {
input.copyTo(output);
return output;
}
}
unsigned int ComponentFilter(const cv::Mat& input, cv::Mat& output, const ComponentFilterCriterion& criterion, ComponentFilterTemp& temp)
{
cv::Mat findContoursTemp = DecideFindContoursTemp(input, output, temp);
cv::findContours(findContoursTemp, temp.contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
output.setTo(0);
unsigned int acceptedComponents = 0;
for (size_t i = 0, end = temp.contours.size(); i < end; ++i) {
ComponentFilterCriterionInput componentFilterCriterionInput(input, temp.contours[i]);
if (criterion(componentFilterCriterionInput)) {
cv::drawContours(output, temp.contours, static_cast<int>(i), std::numeric_limits<unsigned char>::max(), -1);
++acceptedComponents;
}
}
#ifdef _DEBUG
// We can only filter - we can't introduce any new components. Ever.
std::vector<cv::Point> inputPoints, outputPoints, outputPointsLessInputPoints;
if (cv::countNonZero(input)) {
cv::findNonZero(input, inputPoints);
}
if (cv::countNonZero(output)) {
cv::findNonZero(output, outputPoints);
}
const auto sortCriterion = [](const cv::Point& point1, const cv::Point& point2) {
return point1.x < point2.x || ((point1.x == point2.x && point1.y < point2.y));
};
std::sort(inputPoints.begin(), inputPoints.end(), sortCriterion);
std::sort(outputPoints.begin(), outputPoints.end(), sortCriterion);
std::set_difference(outputPoints.begin(), outputPoints.end(), inputPoints.begin(), inputPoints.end(), std::inserter(outputPointsLessInputPoints, outputPointsLessInputPoints.begin()), sortCriterion);
assert(outputPointsLessInputPoints.empty());
#endif
return acceptedComponents;
}
|
Fix the returned number of components
|
Fix the returned number of components
|
C++
|
mit
|
reunanen/puukot,reunanen/puukot
|
0d268ea5113d1237c58806c601d792a709084656
|
tests/TLSTest.cpp
|
tests/TLSTest.cpp
|
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkGraphics.h"
#include "SkPaint.h"
#include "SkTLS.h"
#include "SkThreadUtils.h"
static void thread_main(void*) {
SkGraphics::SetTLSFontCacheLimit(1 * 1024 * 1024);
const char text[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
size_t len = strlen(text);
SkPaint paint;
for (int j = 0; j < 10; ++j) {
for (int i = 9; i <= 48; ++i) {
paint.setTextSize(SkIntToScalar(i));
paint.setAntiAlias(false);
paint.measureText(text, len);
paint.setAntiAlias(true);
paint.measureText(text, len);
}
}
}
static void test_measuretext(skiatest::Reporter* reporter) {
SkThread* threads[8];
int N = SK_ARRAY_COUNT(threads);
int i;
for (i = 0; i < N; ++i) {
threads[i] = new SkThread(thread_main);
}
for (i = 0; i < N; ++i) {
threads[i]->start();
}
for (i = 0; i < N; ++i) {
threads[i]->join();
}
for (i = 0; i < N; ++i) {
delete threads[i];
}
}
static void TestTLS(skiatest::Reporter* reporter) {
test_measuretext(reporter);
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("TLS", TLSClass, TestTLS)
|
/*
* Copyright 2012 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "Test.h"
#include "SkGraphics.h"
#include "SkPaint.h"
#include "SkTLS.h"
#include "SkThreadUtils.h"
static void thread_main(void*) {
SkGraphics::SetTLSFontCacheLimit(1 * 1024 * 1024);
const char text[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
size_t len = strlen(text);
SkPaint paint;
for (int j = 0; j < 10; ++j) {
for (int i = 9; i <= 48; ++i) {
paint.setTextSize(SkIntToScalar(i));
paint.setAntiAlias(false);
paint.measureText(text, len);
paint.setAntiAlias(true);
paint.measureText(text, len);
}
}
}
static void test_measuretext(skiatest::Reporter* reporter) {
SkThread* threads[8];
int N = SK_ARRAY_COUNT(threads);
int i;
for (i = 0; i < N; ++i) {
threads[i] = new SkThread(thread_main);
}
for (i = 0; i < N; ++i) {
threads[i]->start();
}
for (i = 0; i < N; ++i) {
threads[i]->join();
}
for (i = 0; i < N; ++i) {
delete threads[i];
}
}
static void TestTLS(skiatest::Reporter* reporter) {
test_measuretext(reporter);
}
#include "TestClassDef.h"
// TODO: Disabled for now to work around
// http://code.google.com/p/skia/issues/detail?id=619
// ('flaky segfault in TLS test on Shuttle_Ubuntu12 buildbots')
// DEFINE_TESTCLASS("TLS", TLSClass, TestTLS)
|
Disable TLSTest for now, to work around http://code.google.com/p/skia/issues/detail?id=619 Review URL: https://codereview.appspot.com/6259056
|
Disable TLSTest for now, to work around http://code.google.com/p/skia/issues/detail?id=619
Review URL: https://codereview.appspot.com/6259056
git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@4090 2bbb7eff-a529-9590-31e7-b0007b416f81
|
C++
|
bsd-3-clause
|
metajack/skia,Cue/skia,metajack/skia,metajack/skia,mrobinson/skia,mrobinson/skia,mrobinson/skia,Cue/skia,Cue/skia,metajack/skia,Cue/skia,mrobinson/skia,mrobinson/skia
|
670863f3c88fad4d181fe9f59f8b154983c48bd5
|
Modules/Core/FiniteDifference/include/itkDenseFiniteDifferenceImageFilter.hxx
|
Modules/Core/FiniteDifference/include/itkDenseFiniteDifferenceImageFilter.hxx
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkDenseFiniteDifferenceImageFilter_hxx
#define itkDenseFiniteDifferenceImageFilter_hxx
#include "itkDenseFiniteDifferenceImageFilter.h"
#include <list>
#include "itkImageRegionIterator.h"
#include "itkNumericTraits.h"
#include "itkNeighborhoodAlgorithm.h"
namespace itk
{
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::CopyInputToOutput()
{
typename TInputImage::ConstPointer input = this->GetInput();
typename TOutputImage::Pointer output = this->GetOutput();
if (!input || !output)
{
itkExceptionMacro(<< "Either input and/or output is nullptr.");
}
// Check if we are doing in-place filtering
if (this->GetInPlace() && this->CanRunInPlace())
{
const void * const inputPixelContainer = input->GetPixelContainer();
const auto * const tempPtr = output.GetPointer();
if (tempPtr != nullptr && tempPtr->GetPixelContainer() == inputPixelContainer)
{
// the input and output container are the same - no need to copy
return;
}
}
ImageRegionConstIterator<TInputImage> in(input, output->GetRequestedRegion());
ImageRegionIterator<TOutputImage> out(output, output->GetRequestedRegion());
while (!out.IsAtEnd())
{
out.Value() = static_cast<PixelType>(in.Get()); // Supports input
// image adaptors only
++in;
++out;
}
}
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::AllocateUpdateBuffer()
{
// The update buffer looks just like the output.
typename TOutputImage::Pointer output = this->GetOutput();
m_UpdateBuffer->SetOrigin(output->GetOrigin());
m_UpdateBuffer->SetSpacing(output->GetSpacing());
m_UpdateBuffer->SetDirection(output->GetDirection());
m_UpdateBuffer->SetLargestPossibleRegion(output->GetLargestPossibleRegion());
m_UpdateBuffer->SetRequestedRegion(output->GetRequestedRegion());
m_UpdateBuffer->SetBufferedRegion(output->GetBufferedRegion());
m_UpdateBuffer->Allocate();
}
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::ApplyUpdate(const TimeStepType & dt)
{
// Set up for multithreaded processing.
DenseFDThreadStruct str;
str.Filter = this;
str.TimeStep = dt;
this->GetMultiThreader()->SetNumberOfWorkUnits(this->GetNumberOfWorkUnits());
this->GetMultiThreader()->SetSingleMethod(this->ApplyUpdateThreaderCallback, &str);
// Multithread the execution
this->GetMultiThreader()->SingleMethodExecute();
// Explicitely call Modified on GetOutput here
// since ThreadedApplyUpdate changes this buffer
// through iterators which do not increment the
// output timestamp
this->GetOutput()->Modified();
}
template <typename TInputImage, typename TOutputImage>
ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::ApplyUpdateThreaderCallback(void * arg)
{
ThreadIdType threadId = ((MultiThreaderBase::WorkUnitInfo *)(arg))->WorkUnitID;
ThreadIdType threadCount = ((MultiThreaderBase::WorkUnitInfo *)(arg))->NumberOfWorkUnits;
auto * str = (DenseFDThreadStruct *)(((MultiThreaderBase::WorkUnitInfo *)(arg))->UserData);
// Execute the actual method with appropriate output region
// first find out how many pieces extent can be split into.
// Using the SplitRequestedRegion method from itk::ImageSource.
ThreadRegionType splitRegion;
ThreadIdType total = str->Filter->SplitRequestedRegion(threadId, threadCount, splitRegion);
if (threadId < total)
{
str->Filter->ThreadedApplyUpdate(str->TimeStep, splitRegion, threadId);
}
return ITK_THREAD_RETURN_DEFAULT_VALUE;
}
template <typename TInputImage, typename TOutputImage>
typename DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::TimeStepType
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::CalculateChange()
{
// Set up for multithreaded processing.
DenseFDThreadStruct str;
str.Filter = this;
str.TimeStep = NumericTraits<TimeStepType>::ZeroValue(); // Not used during the
// calculate change step.
this->GetMultiThreader()->SetNumberOfWorkUnits(this->GetNumberOfWorkUnits());
this->GetMultiThreader()->SetSingleMethod(this->CalculateChangeThreaderCallback, &str);
// Initialize the list of time step values that will be generated by the
// various threads. There is one distinct slot for each possible thread,
// so this data structure is thread-safe.
ThreadIdType threadCount = this->GetMultiThreader()->GetNumberOfWorkUnits();
str.TimeStepList.clear();
str.TimeStepList.resize(threadCount, NumericTraits<TimeStepType>::ZeroValue());
str.ValidTimeStepList.clear();
str.ValidTimeStepList.resize(threadCount, false);
// Multithread the execution
this->GetMultiThreader()->SingleMethodExecute();
// Resolve the single value time step to return
TimeStepType dt = this->ResolveTimeStep(str.TimeStepList, str.ValidTimeStepList);
// Explicitely call Modified on m_UpdateBuffer here
// since ThreadedCalculateChange changes this buffer
// through iterators which do not increment the
// update buffer timestamp
this->m_UpdateBuffer->Modified();
return dt;
}
template <typename TInputImage, typename TOutputImage>
ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::CalculateChangeThreaderCallback(void * arg)
{
ThreadIdType threadId = ((MultiThreaderBase::WorkUnitInfo *)(arg))->WorkUnitID;
ThreadIdType threadCount = ((MultiThreaderBase::WorkUnitInfo *)(arg))->NumberOfWorkUnits;
auto * str = (DenseFDThreadStruct *)(((MultiThreaderBase::WorkUnitInfo *)(arg))->UserData);
// Execute the actual method with appropriate output region
// first find out how many pieces extent can be split into.
// Using the SplitRequestedRegion method from itk::ImageSource.
ThreadRegionType splitRegion;
ThreadIdType total = str->Filter->SplitRequestedRegion(threadId, threadCount, splitRegion);
if (threadId < total)
{
str->TimeStepList[threadId] = str->Filter->ThreadedCalculateChange(splitRegion, threadId);
str->ValidTimeStepList[threadId] = true;
}
return ITK_THREAD_RETURN_DEFAULT_VALUE;
}
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::ThreadedApplyUpdate(
const TimeStepType & dt,
const ThreadRegionType & regionToProcess,
ThreadIdType)
{
ImageRegionIterator<UpdateBufferType> u(m_UpdateBuffer, regionToProcess);
ImageRegionIterator<OutputImageType> o(this->GetOutput(), regionToProcess);
u.GoToBegin();
o.GoToBegin();
while (!u.IsAtEnd())
{
o.Value() += static_cast<PixelType>(u.Value() * dt); // no adaptor
// support here
++o;
++u;
}
}
template <typename TInputImage, typename TOutputImage>
typename DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::TimeStepType
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::ThreadedCalculateChange(
const ThreadRegionType & regionToProcess,
ThreadIdType)
{
using SizeType = typename OutputImageType::SizeType;
using NeighborhoodIteratorType = typename FiniteDifferenceFunctionType::NeighborhoodType;
using UpdateIteratorType = ImageRegionIterator<UpdateBufferType>;
typename OutputImageType::Pointer output = this->GetOutput();
// Get the FiniteDifferenceFunction to use in calculations.
const typename FiniteDifferenceFunctionType::Pointer df = this->GetDifferenceFunction();
const SizeType radius = df->GetRadius();
// Ask the function object for a pointer to a data structure it
// will use to manage any global values it needs. We'll pass this
// back to the function object at each calculation and then
// again so that the function object can use it to determine a
// time step for this iteration.
void * globalData = df->GetGlobalDataPointer();
// Break the input into a series of regions. The first region is free
// of boundary conditions, the rest with boundary conditions. We operate
// on the output region because input has been copied to output.
using FaceCalculatorType = NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<OutputImageType>;
using FaceListType = typename FaceCalculatorType::FaceListType;
FaceCalculatorType faceCalculator;
FaceListType faceList = faceCalculator(output, regionToProcess, radius);
auto fIt = faceList.begin();
auto fEnd = faceList.end();
// Process the non-boundary region.
NeighborhoodIteratorType nD(radius, output, *fIt);
UpdateIteratorType nU(m_UpdateBuffer, *fIt);
nD.GoToBegin();
while (!nD.IsAtEnd())
{
nU.Value() = df->ComputeUpdate(nD, globalData);
++nD;
++nU;
}
// Process each of the boundary faces.
for (++fIt; fIt != fEnd; ++fIt)
{
NeighborhoodIteratorType bD(radius, output, *fIt);
UpdateIteratorType bU(m_UpdateBuffer, *fIt);
bD.GoToBegin();
bU.GoToBegin();
while (!bD.IsAtEnd())
{
bU.Value() = df->ComputeUpdate(bD, globalData);
++bD;
++bU;
}
}
// Ask the finite difference function to compute the time step for
// this iteration. We give it the global data pointer to use, then
// ask it to free the global data memory.
TimeStepType timeStep = df->ComputeGlobalTimeStep(globalData);
df->ReleaseGlobalDataPointer(globalData);
return timeStep;
}
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
} // end namespace itk
#endif
|
/*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkDenseFiniteDifferenceImageFilter_hxx
#define itkDenseFiniteDifferenceImageFilter_hxx
#include "itkDenseFiniteDifferenceImageFilter.h"
#include "itkImageRegionIterator.h"
#include "itkNumericTraits.h"
#include "itkNeighborhoodAlgorithm.h"
#include <functional> // For equal_to.
namespace itk
{
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::CopyInputToOutput()
{
typename TInputImage::ConstPointer input = this->GetInput();
typename TOutputImage::Pointer output = this->GetOutput();
if (!input || !output)
{
itkExceptionMacro(<< "Either input and/or output is nullptr.");
}
// Check if we are doing in-place filtering
if (this->GetInPlace() && this->CanRunInPlace() &&
std::equal_to<const void *>{}(input->GetPixelContainer(), output->GetPixelContainer()))
{
// the input and output container are the same - no need to copy
return;
}
ImageRegionConstIterator<TInputImage> in(input, output->GetRequestedRegion());
ImageRegionIterator<TOutputImage> out(output, output->GetRequestedRegion());
while (!out.IsAtEnd())
{
out.Value() = static_cast<PixelType>(in.Get()); // Supports input
// image adaptors only
++in;
++out;
}
}
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::AllocateUpdateBuffer()
{
// The update buffer looks just like the output.
typename TOutputImage::Pointer output = this->GetOutput();
m_UpdateBuffer->SetOrigin(output->GetOrigin());
m_UpdateBuffer->SetSpacing(output->GetSpacing());
m_UpdateBuffer->SetDirection(output->GetDirection());
m_UpdateBuffer->SetLargestPossibleRegion(output->GetLargestPossibleRegion());
m_UpdateBuffer->SetRequestedRegion(output->GetRequestedRegion());
m_UpdateBuffer->SetBufferedRegion(output->GetBufferedRegion());
m_UpdateBuffer->Allocate();
}
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::ApplyUpdate(const TimeStepType & dt)
{
// Set up for multithreaded processing.
DenseFDThreadStruct str;
str.Filter = this;
str.TimeStep = dt;
this->GetMultiThreader()->SetNumberOfWorkUnits(this->GetNumberOfWorkUnits());
this->GetMultiThreader()->SetSingleMethod(this->ApplyUpdateThreaderCallback, &str);
// Multithread the execution
this->GetMultiThreader()->SingleMethodExecute();
// Explicitely call Modified on GetOutput here
// since ThreadedApplyUpdate changes this buffer
// through iterators which do not increment the
// output timestamp
this->GetOutput()->Modified();
}
template <typename TInputImage, typename TOutputImage>
ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::ApplyUpdateThreaderCallback(void * arg)
{
ThreadIdType threadId = ((MultiThreaderBase::WorkUnitInfo *)(arg))->WorkUnitID;
ThreadIdType threadCount = ((MultiThreaderBase::WorkUnitInfo *)(arg))->NumberOfWorkUnits;
auto * str = (DenseFDThreadStruct *)(((MultiThreaderBase::WorkUnitInfo *)(arg))->UserData);
// Execute the actual method with appropriate output region
// first find out how many pieces extent can be split into.
// Using the SplitRequestedRegion method from itk::ImageSource.
ThreadRegionType splitRegion;
ThreadIdType total = str->Filter->SplitRequestedRegion(threadId, threadCount, splitRegion);
if (threadId < total)
{
str->Filter->ThreadedApplyUpdate(str->TimeStep, splitRegion, threadId);
}
return ITK_THREAD_RETURN_DEFAULT_VALUE;
}
template <typename TInputImage, typename TOutputImage>
typename DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::TimeStepType
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::CalculateChange()
{
// Set up for multithreaded processing.
DenseFDThreadStruct str;
str.Filter = this;
str.TimeStep = NumericTraits<TimeStepType>::ZeroValue(); // Not used during the
// calculate change step.
this->GetMultiThreader()->SetNumberOfWorkUnits(this->GetNumberOfWorkUnits());
this->GetMultiThreader()->SetSingleMethod(this->CalculateChangeThreaderCallback, &str);
// Initialize the list of time step values that will be generated by the
// various threads. There is one distinct slot for each possible thread,
// so this data structure is thread-safe.
ThreadIdType threadCount = this->GetMultiThreader()->GetNumberOfWorkUnits();
str.TimeStepList.clear();
str.TimeStepList.resize(threadCount, NumericTraits<TimeStepType>::ZeroValue());
str.ValidTimeStepList.clear();
str.ValidTimeStepList.resize(threadCount, false);
// Multithread the execution
this->GetMultiThreader()->SingleMethodExecute();
// Resolve the single value time step to return
TimeStepType dt = this->ResolveTimeStep(str.TimeStepList, str.ValidTimeStepList);
// Explicitely call Modified on m_UpdateBuffer here
// since ThreadedCalculateChange changes this buffer
// through iterators which do not increment the
// update buffer timestamp
this->m_UpdateBuffer->Modified();
return dt;
}
template <typename TInputImage, typename TOutputImage>
ITK_THREAD_RETURN_FUNCTION_CALL_CONVENTION
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::CalculateChangeThreaderCallback(void * arg)
{
ThreadIdType threadId = ((MultiThreaderBase::WorkUnitInfo *)(arg))->WorkUnitID;
ThreadIdType threadCount = ((MultiThreaderBase::WorkUnitInfo *)(arg))->NumberOfWorkUnits;
auto * str = (DenseFDThreadStruct *)(((MultiThreaderBase::WorkUnitInfo *)(arg))->UserData);
// Execute the actual method with appropriate output region
// first find out how many pieces extent can be split into.
// Using the SplitRequestedRegion method from itk::ImageSource.
ThreadRegionType splitRegion;
ThreadIdType total = str->Filter->SplitRequestedRegion(threadId, threadCount, splitRegion);
if (threadId < total)
{
str->TimeStepList[threadId] = str->Filter->ThreadedCalculateChange(splitRegion, threadId);
str->ValidTimeStepList[threadId] = true;
}
return ITK_THREAD_RETURN_DEFAULT_VALUE;
}
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::ThreadedApplyUpdate(
const TimeStepType & dt,
const ThreadRegionType & regionToProcess,
ThreadIdType)
{
ImageRegionIterator<UpdateBufferType> u(m_UpdateBuffer, regionToProcess);
ImageRegionIterator<OutputImageType> o(this->GetOutput(), regionToProcess);
u.GoToBegin();
o.GoToBegin();
while (!u.IsAtEnd())
{
o.Value() += static_cast<PixelType>(u.Value() * dt); // no adaptor
// support here
++o;
++u;
}
}
template <typename TInputImage, typename TOutputImage>
typename DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::TimeStepType
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::ThreadedCalculateChange(
const ThreadRegionType & regionToProcess,
ThreadIdType)
{
using SizeType = typename OutputImageType::SizeType;
using NeighborhoodIteratorType = typename FiniteDifferenceFunctionType::NeighborhoodType;
using UpdateIteratorType = ImageRegionIterator<UpdateBufferType>;
typename OutputImageType::Pointer output = this->GetOutput();
// Get the FiniteDifferenceFunction to use in calculations.
const typename FiniteDifferenceFunctionType::Pointer df = this->GetDifferenceFunction();
const SizeType radius = df->GetRadius();
// Ask the function object for a pointer to a data structure it
// will use to manage any global values it needs. We'll pass this
// back to the function object at each calculation and then
// again so that the function object can use it to determine a
// time step for this iteration.
void * globalData = df->GetGlobalDataPointer();
// Break the input into a series of regions. The first region is free
// of boundary conditions, the rest with boundary conditions. We operate
// on the output region because input has been copied to output.
using FaceCalculatorType = NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<OutputImageType>;
using FaceListType = typename FaceCalculatorType::FaceListType;
FaceCalculatorType faceCalculator;
FaceListType faceList = faceCalculator(output, regionToProcess, radius);
auto fIt = faceList.begin();
auto fEnd = faceList.end();
// Process the non-boundary region.
NeighborhoodIteratorType nD(radius, output, *fIt);
UpdateIteratorType nU(m_UpdateBuffer, *fIt);
nD.GoToBegin();
while (!nD.IsAtEnd())
{
nU.Value() = df->ComputeUpdate(nD, globalData);
++nD;
++nU;
}
// Process each of the boundary faces.
for (++fIt; fIt != fEnd; ++fIt)
{
NeighborhoodIteratorType bD(radius, output, *fIt);
UpdateIteratorType bU(m_UpdateBuffer, *fIt);
bD.GoToBegin();
bU.GoToBegin();
while (!bD.IsAtEnd())
{
bU.Value() = df->ComputeUpdate(bD, globalData);
++bD;
++bU;
}
}
// Ask the finite difference function to compute the time step for
// this iteration. We give it the global data pointer to use, then
// ask it to free the global data memory.
TimeStepType timeStep = df->ComputeGlobalTimeStep(globalData);
df->ReleaseGlobalDataPointer(globalData);
return timeStep;
}
template <typename TInputImage, typename TOutputImage>
void
DenseFiniteDifferenceImageFilter<TInputImage, TOutputImage>::PrintSelf(std::ostream & os, Indent indent) const
{
Superclass::PrintSelf(os, indent);
}
} // end namespace itk
#endif
|
Use equal_to on pixel containers DenseFiniteDifferenceImageFilter
|
STYLE: Use equal_to on pixel containers DenseFiniteDifferenceImageFilter
Follow-up to pull request https://github.com/InsightSoftwareConsortium/ITK/pull/2386
commit 1c25350c93c33578b11c83bce501496c306ff3b1
"COMP: Fix image pointer casting error"
Also removed an unused `#include <list>`.
|
C++
|
apache-2.0
|
richardbeare/ITK,thewtex/ITK,InsightSoftwareConsortium/ITK,LucasGandel/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,BRAINSia/ITK,hjmjohnson/ITK,Kitware/ITK,hjmjohnson/ITK,Kitware/ITK,thewtex/ITK,LucasGandel/ITK,Kitware/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,richardbeare/ITK,LucasGandel/ITK,Kitware/ITK,vfonov/ITK,thewtex/ITK,richardbeare/ITK,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,vfonov/ITK,BRAINSia/ITK,InsightSoftwareConsortium/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,BRAINSia/ITK,BRAINSia/ITK,Kitware/ITK,vfonov/ITK,hjmjohnson/ITK,Kitware/ITK,thewtex/ITK,LucasGandel/ITK,LucasGandel/ITK,BRAINSia/ITK,hjmjohnson/ITK,thewtex/ITK,richardbeare/ITK,vfonov/ITK,hjmjohnson/ITK,thewtex/ITK,vfonov/ITK,BRAINSia/ITK,vfonov/ITK,InsightSoftwareConsortium/ITK,thewtex/ITK,LucasGandel/ITK,LucasGandel/ITK,Kitware/ITK,LucasGandel/ITK,BRAINSia/ITK,hjmjohnson/ITK,richardbeare/ITK,richardbeare/ITK
|
d227da30416df7002ecc7f48da373df5f6e5ccf7
|
chrome/app/google_update_client.cc
|
chrome/app/google_update_client.cc
|
// Copyright (c) 2006-2008 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/app/google_update_client.h"
#include <shlobj.h>
#include <strsafe.h>
#include "chrome/app/client_util.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/install_util.h"
namespace {
const wchar_t kEnvProductVersionKey[] = L"CHROME_VERSION";
// Allocates the out param on success.
bool GoogleUpdateEnvQueryStr(const wchar_t* key_name, wchar_t** out) {
DWORD count = ::GetEnvironmentVariableW(key_name, NULL, 0);
if (!count) {
return false;
}
wchar_t* value = new wchar_t[count + 1];
if (!::GetEnvironmentVariableW(key_name, value, count)) {
delete[] value;
return false;
}
*out = value;
return true;
}
} // anonymous namespace
namespace google_update {
GoogleUpdateClient::GoogleUpdateClient() : version_(NULL) {
}
GoogleUpdateClient::~GoogleUpdateClient() {
delete[] version_;
}
std::wstring GoogleUpdateClient::GetDLLPath() {
return client_util::GetDLLPath(dll_, dll_path_);
}
const wchar_t* GoogleUpdateClient::GetVersion() const {
return version_;
}
bool GoogleUpdateClient::Launch(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox,
wchar_t* command_line,
int show_command,
const char* entry_name,
int* ret) {
if (client_util::FileExists(dll_path_)) {
::SetCurrentDirectory(dll_path_);
// Setting the version on the environment block is a 'best effort' deal.
// It enables Google Update running on a child to load the same DLL version.
::SetEnvironmentVariableW(kEnvProductVersionKey, version_);
}
// The dll can be in the exe's directory or in the current directory.
// Use the alternate search path to be sure that it's not trying to load it
// calling application's directory.
HINSTANCE dll_handle = ::LoadLibraryEx(dll_.c_str(), NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (NULL == dll_handle) {
unsigned long err = GetLastError();
if (err) {
WCHAR message[500] = {0};
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
reinterpret_cast<LPWSTR>(&message), 500, NULL);
::OutputDebugStringW(message);
}
return false;
}
bool did_launch = false;
client_util::DLL_MAIN entry = reinterpret_cast<client_util::DLL_MAIN>(
::GetProcAddress(dll_handle, entry_name));
if (NULL != entry) {
// record did_run "dr" in client state
std::wstring key_path(google_update::kRegPathClientState);
key_path.append(L"\\" + guid_);
HKEY reg_key;
if (::RegOpenKeyEx(HKEY_CURRENT_USER, key_path.c_str(), 0,
KEY_WRITE, ®_key) == ERROR_SUCCESS) {
const wchar_t kVal[] = L"1";
::RegSetValueEx(reg_key, google_update::kRegDidRunField, 0, REG_SZ,
reinterpret_cast<const BYTE *>(kVal), sizeof(kVal));
::RegCloseKey(reg_key);
}
int rc = (entry)(instance, sandbox, command_line, show_command);
if (ret) {
*ret = rc;
}
did_launch = true;
}
#ifdef PURIFY
// We should never unload the dll. There is only risk and no gain from
// doing so. The singleton dtors have been already run by AtExitManager.
::FreeLibrary(dll_handle);
#endif
return did_launch;
}
bool GoogleUpdateClient::Init(const wchar_t* client_guid,
const wchar_t* client_dll) {
client_util::GetExecutablePath(dll_path_);
guid_.assign(client_guid);
dll_.assign(client_dll);
bool ret = false;
if (!guid_.empty()) {
if (GoogleUpdateEnvQueryStr(kEnvProductVersionKey, &version_)) {
ret = true;
} else {
std::wstring key(google_update::kRegPathClients);
key.append(L"\\");
key.append(guid_);
if (client_util::GetChromiumVersion(dll_path_, key.c_str(), &version_))
ret = true;
}
}
if (version_) {
::StringCchCat(dll_path_, MAX_PATH, version_);
}
return ret;
}
} // namespace google_update
|
// Copyright (c) 2006-2008 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/app/google_update_client.h"
#include <shlobj.h>
#include <strsafe.h>
#include "chrome/app/client_util.h"
#include "chrome/installer/util/google_update_constants.h"
#include "chrome/installer/util/install_util.h"
namespace {
const wchar_t kEnvProductVersionKey[] = L"CHROME_VERSION";
// Allocates the out param on success.
bool GoogleUpdateEnvQueryStr(const wchar_t* key_name, wchar_t** out) {
DWORD count = ::GetEnvironmentVariableW(key_name, NULL, 0);
if (!count) {
return false;
}
wchar_t* value = new wchar_t[count + 1];
if (!::GetEnvironmentVariableW(key_name, value, count)) {
delete[] value;
return false;
}
*out = value;
return true;
}
} // anonymous namespace
namespace google_update {
GoogleUpdateClient::GoogleUpdateClient() : version_(NULL) {
}
GoogleUpdateClient::~GoogleUpdateClient() {
delete[] version_;
}
std::wstring GoogleUpdateClient::GetDLLPath() {
return client_util::GetDLLPath(dll_, dll_path_);
}
const wchar_t* GoogleUpdateClient::GetVersion() const {
return version_;
}
bool GoogleUpdateClient::Launch(HINSTANCE instance,
sandbox::SandboxInterfaceInfo* sandbox,
wchar_t* command_line,
int show_command,
const char* entry_name,
int* ret) {
if (client_util::FileExists(dll_path_)) {
::SetCurrentDirectory(dll_path_);
// Setting the version on the environment block is a 'best effort' deal.
// It enables Google Update running on a child to load the same DLL version.
::SetEnvironmentVariableW(kEnvProductVersionKey, version_);
}
// The dll can be in the exe's directory or in the current directory.
// Use the alternate search path to be sure that it's not trying to load it
// calling application's directory.
HINSTANCE dll_handle = ::LoadLibraryEx(dll_.c_str(), NULL,
LOAD_WITH_ALTERED_SEARCH_PATH);
if (NULL == dll_handle) {
unsigned long err = GetLastError();
if (err) {
WCHAR message[500] = {0};
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, err, 0,
reinterpret_cast<LPWSTR>(&message), 500, NULL);
::OutputDebugStringW(message);
}
return false;
}
bool did_launch = false;
client_util::DLL_MAIN entry = reinterpret_cast<client_util::DLL_MAIN>(
::GetProcAddress(dll_handle, entry_name));
if (NULL != entry) {
// record did_run "dr" in client state
std::wstring key_path(google_update::kRegPathClientState);
key_path.append(L"\\" + guid_);
HKEY reg_key;
if (::RegOpenKeyEx(HKEY_CURRENT_USER, key_path.c_str(), 0,
KEY_WRITE, ®_key) == ERROR_SUCCESS) {
const wchar_t kVal[] = L"1";
::RegSetValueEx(reg_key, google_update::kRegDidRunField, 0, REG_SZ,
reinterpret_cast<const BYTE *>(kVal), sizeof(kVal));
::RegCloseKey(reg_key);
}
int rc = (entry)(instance, sandbox, command_line, show_command);
if (ret) {
*ret = rc;
}
did_launch = true;
}
#ifdef PURIFY
// We should never unload the dll. There is only risk and no gain from
// doing so. The singleton dtors have been already run by AtExitManager.
::FreeLibrary(dll_handle);
#endif
return did_launch;
}
bool GoogleUpdateClient::Init(const wchar_t* client_guid,
const wchar_t* client_dll) {
client_util::GetExecutablePath(dll_path_);
guid_.assign(client_guid);
dll_.assign(client_dll);
bool ret = false;
if (!guid_.empty()) {
if (GoogleUpdateEnvQueryStr(kEnvProductVersionKey, &version_)) {
ret = true;
} else {
std::wstring key(google_update::kRegPathClients);
key.append(L"\\" + guid_);
if (client_util::GetChromiumVersion(dll_path_, key.c_str(), &version_))
ret = true;
}
}
if (version_) {
::StringCchCat(dll_path_, MAX_PATH, version_);
}
return ret;
}
} // namespace google_update
|
fix minor style nit
|
fix minor style nit
Review URL: http://codereview.chromium.org/9662
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@4926 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
76c794ab7a36746ecfb7e572215b4fe694f16c9b
|
chrome/browser/plugin_observer.cc
|
chrome/browser/plugin_observer.cc
|
// Copyright (c) 2011 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/browser/plugin_observer.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/plugin_installer_infobar_delegate.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/simple_alert_infobar_delegate.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/view_messages.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/plugins/npapi/default_plugin_shared.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/npapi/webplugininfo.h"
namespace {
// PluginInfoBarDelegate ------------------------------------------------------
class PluginInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
PluginInfoBarDelegate(TabContents* tab_contents, const string16& name);
protected:
virtual ~PluginInfoBarDelegate();
// ConfirmInfoBarDelegate:
virtual void InfoBarClosed();
virtual bool Cancel();
virtual bool LinkClicked(WindowOpenDisposition disposition);
string16 name_;
TabContents* tab_contents_;
private:
// ConfirmInfoBarDelegate:
virtual SkBitmap* GetIcon() const;
virtual string16 GetLinkText();
DISALLOW_COPY_AND_ASSIGN(PluginInfoBarDelegate);
};
PluginInfoBarDelegate::PluginInfoBarDelegate(TabContents* tab_contents,
const string16& name)
: ConfirmInfoBarDelegate(tab_contents),
name_(name),
tab_contents_(tab_contents) {
}
PluginInfoBarDelegate::~PluginInfoBarDelegate() {
}
void PluginInfoBarDelegate::InfoBarClosed() {
delete this;
}
bool PluginInfoBarDelegate::Cancel() {
tab_contents_->render_view_host()->LoadBlockedPlugins();
return true;
}
bool PluginInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
GURL url = google_util::AppendGoogleLocaleParam(
GURL(chrome::kOutdatedPluginLearnMoreURL));
tab_contents_->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
return false;
}
SkBitmap* PluginInfoBarDelegate::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_PLUGIN_INSTALL);
}
string16 PluginInfoBarDelegate::GetLinkText() {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
// BlockedPluginInfoBarDelegate -----------------------------------------------
class BlockedPluginInfoBarDelegate : public PluginInfoBarDelegate {
public:
BlockedPluginInfoBarDelegate(TabContents* tab_contents,
const string16& name);
private:
virtual ~BlockedPluginInfoBarDelegate();
// PluginInfoBarDelegate:
virtual string16 GetMessageText() const;
virtual string16 GetButtonLabel(InfoBarButton button) const;
virtual bool Accept();
virtual bool Cancel();
virtual void InfoBarClosed();
virtual void InfoBarDismissed();
virtual bool LinkClicked(WindowOpenDisposition disposition);
DISALLOW_COPY_AND_ASSIGN(BlockedPluginInfoBarDelegate);
};
BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name)
: PluginInfoBarDelegate(tab_contents, utf16_name) {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer"));
}
BlockedPluginInfoBarDelegate::~BlockedPluginInfoBarDelegate() {
}
string16 BlockedPluginInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, name_);
}
string16 BlockedPluginInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PLUGIN_ENABLE_ALWAYS : IDS_PLUGIN_ENABLE_TEMPORARILY);
}
bool BlockedPluginInfoBarDelegate::Accept() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.AlwaysAllow"));
tab_contents_->profile()->GetHostContentSettingsMap()->AddExceptionForURL(
tab_contents_->GetURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(),
CONTENT_SETTING_ALLOW);
tab_contents_->render_view_host()->LoadBlockedPlugins();
return true;
}
bool BlockedPluginInfoBarDelegate::Cancel() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.AllowThisTime"));
return PluginInfoBarDelegate::Cancel();
}
void BlockedPluginInfoBarDelegate::InfoBarDismissed() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Dismissed"));
}
void BlockedPluginInfoBarDelegate::InfoBarClosed() {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Closed"));
PluginInfoBarDelegate::InfoBarClosed();
}
bool BlockedPluginInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.LearnMore"));
return PluginInfoBarDelegate::LinkClicked(disposition);
}
// OutdatedPluginInfoBarDelegate ----------------------------------------------
class OutdatedPluginInfoBarDelegate : public PluginInfoBarDelegate {
public:
OutdatedPluginInfoBarDelegate(TabContents* tab_contents,
const string16& name,
const GURL& update_url);
private:
virtual ~OutdatedPluginInfoBarDelegate();
// PluginInfoBarDelegate:
virtual string16 GetMessageText() const;
virtual string16 GetButtonLabel(InfoBarButton button) const;
virtual bool Accept();
virtual bool Cancel();
virtual void InfoBarClosed();
virtual void InfoBarDismissed();
virtual bool LinkClicked(WindowOpenDisposition disposition);
GURL update_url_;
DISALLOW_COPY_AND_ASSIGN(OutdatedPluginInfoBarDelegate);
};
OutdatedPluginInfoBarDelegate::OutdatedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name,
const GURL& update_url)
: PluginInfoBarDelegate(tab_contents, utf16_name),
update_url_(update_url) {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.RealPlayer"));
else if (name == webkit::npapi::PluginGroup::kSilverlightGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Silverlight"));
else if (name == webkit::npapi::PluginGroup::kAdobeReaderGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Reader"));
}
OutdatedPluginInfoBarDelegate::~OutdatedPluginInfoBarDelegate() {
}
string16 OutdatedPluginInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED_PROMPT, name_);
}
string16 OutdatedPluginInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PLUGIN_ENABLE_TEMPORARILY : IDS_PLUGIN_UPDATE);
}
bool OutdatedPluginInfoBarDelegate::Accept() {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.AllowThisTime"));
// This is intentional; the base class cancel is mapped to running all
// plug-ins and closing the infobar. We've rewired Accept() and Cancel() in
// the "outdated" case so that the first button is "Update..."
return PluginInfoBarDelegate::Cancel();
}
bool OutdatedPluginInfoBarDelegate::Cancel() {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Update"));
tab_contents_->OpenURL(update_url_, GURL(), NEW_FOREGROUND_TAB,
PageTransition::LINK);
return false;
}
void OutdatedPluginInfoBarDelegate::InfoBarDismissed() {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Dismissed"));
}
void OutdatedPluginInfoBarDelegate::InfoBarClosed() {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Closed"));
PluginInfoBarDelegate::InfoBarClosed();
}
bool OutdatedPluginInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.LearnMore"));
return PluginInfoBarDelegate::LinkClicked(disposition);
}
} // namespace
// PluginObserver -------------------------------------------------------------
PluginObserver::PluginObserver(TabContents* tab_contents)
: TabContentsObserver(tab_contents) {
}
PluginObserver::~PluginObserver() {
}
bool PluginObserver::OnMessageReceived(const IPC::Message& message) {
IPC_BEGIN_MESSAGE_MAP(PluginObserver, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_MissingPluginStatus, OnMissingPluginStatus)
IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)
IPC_MESSAGE_HANDLER(ViewHostMsg_BlockedOutdatedPlugin,
OnBlockedOutdatedPlugin)
IPC_MESSAGE_UNHANDLED(return false)
IPC_END_MESSAGE_MAP()
return true;
}
PluginInstallerInfoBarDelegate* PluginObserver::GetPluginInstaller() {
if (plugin_installer_ == NULL)
plugin_installer_.reset(new PluginInstallerInfoBarDelegate(tab_contents()));
return plugin_installer_->AsPluginInstallerInfoBarDelegate();
}
void PluginObserver::OnMissingPluginStatus(int status) {
// TODO(PORT): pull in when plug-ins work
#if defined(OS_WIN)
if (status == webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE) {
tab_contents()->AddInfoBar(
new PluginInstallerInfoBarDelegate(tab_contents()));
return;
}
DCHECK_EQ(webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD,
status);
for (size_t i = 0; i < tab_contents()->infobar_count(); ++i) {
InfoBarDelegate* delegate = tab_contents()->GetInfoBarDelegateAt(i);
if (delegate->AsPluginInstallerInfoBarDelegate() != NULL) {
tab_contents()->RemoveInfoBar(delegate);
return;
}
}
#endif
}
void PluginObserver::OnCrashedPlugin(const FilePath& plugin_path) {
DCHECK(!plugin_path.value().empty());
string16 plugin_name = plugin_path.LossyDisplayName();
webkit::npapi::WebPluginInfo plugin_info;
if (webkit::npapi::PluginList::Singleton()->GetPluginInfoByPath(
plugin_path, &plugin_info) &&
!plugin_info.name.empty()) {
plugin_name = plugin_info.name;
#if defined(OS_MACOSX)
// Many plugins on the Mac have .plugin in the actual name, which looks
// terrible, so look for that and strip it off if present.
const std::string kPluginExtension = ".plugin";
if (EndsWith(plugin_name, ASCIIToUTF16(kPluginExtension), true))
plugin_name.erase(plugin_name.length() - kPluginExtension.length());
#endif // OS_MACOSX
}
SkBitmap* crash_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_PLUGIN_CRASHED);
tab_contents()->AddInfoBar(new SimpleAlertInfoBarDelegate(tab_contents(),
crash_icon,
l10n_util::GetStringFUTF16(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
true));
}
void PluginObserver::OnBlockedOutdatedPlugin(const string16& name,
const GURL& update_url) {
tab_contents()->AddInfoBar(update_url.is_empty() ?
static_cast<InfoBarDelegate*>(new BlockedPluginInfoBarDelegate(
tab_contents(), name)) :
new OutdatedPluginInfoBarDelegate(tab_contents(), name, update_url));
}
|
// Copyright (c) 2011 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/browser/plugin_observer.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/google/google_util.h"
#include "chrome/browser/metrics/user_metrics.h"
#include "chrome/browser/plugin_installer_infobar_delegate.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/tab_contents/confirm_infobar_delegate.h"
#include "chrome/browser/tab_contents/simple_alert_infobar_delegate.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/url_constants.h"
#include "content/browser/renderer_host/render_view_host.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/common/view_messages.h"
#include "grit/generated_resources.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/plugins/npapi/default_plugin_shared.h"
#include "webkit/plugins/npapi/plugin_group.h"
#include "webkit/plugins/npapi/plugin_list.h"
#include "webkit/plugins/npapi/webplugininfo.h"
namespace {
// PluginInfoBarDelegate ------------------------------------------------------
class PluginInfoBarDelegate : public ConfirmInfoBarDelegate {
public:
PluginInfoBarDelegate(TabContents* tab_contents, const string16& name);
protected:
virtual ~PluginInfoBarDelegate();
// ConfirmInfoBarDelegate:
virtual void InfoBarClosed();
virtual bool Cancel();
virtual bool LinkClicked(WindowOpenDisposition disposition);
string16 name_;
TabContents* tab_contents_;
private:
// ConfirmInfoBarDelegate:
virtual SkBitmap* GetIcon() const;
virtual string16 GetLinkText();
DISALLOW_COPY_AND_ASSIGN(PluginInfoBarDelegate);
};
PluginInfoBarDelegate::PluginInfoBarDelegate(TabContents* tab_contents,
const string16& name)
: ConfirmInfoBarDelegate(tab_contents),
name_(name),
tab_contents_(tab_contents) {
}
PluginInfoBarDelegate::~PluginInfoBarDelegate() {
}
void PluginInfoBarDelegate::InfoBarClosed() {
delete this;
}
bool PluginInfoBarDelegate::Cancel() {
tab_contents_->render_view_host()->LoadBlockedPlugins();
return true;
}
bool PluginInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) {
GURL url = google_util::AppendGoogleLocaleParam(
GURL(chrome::kOutdatedPluginLearnMoreURL));
tab_contents_->OpenURL(url, GURL(), NEW_FOREGROUND_TAB, PageTransition::LINK);
return false;
}
SkBitmap* PluginInfoBarDelegate::GetIcon() const {
return ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_PLUGIN_INSTALL);
}
string16 PluginInfoBarDelegate::GetLinkText() {
return l10n_util::GetStringUTF16(IDS_LEARN_MORE);
}
// BlockedPluginInfoBarDelegate -----------------------------------------------
class BlockedPluginInfoBarDelegate : public PluginInfoBarDelegate {
public:
BlockedPluginInfoBarDelegate(TabContents* tab_contents,
const string16& name);
private:
virtual ~BlockedPluginInfoBarDelegate();
// PluginInfoBarDelegate:
virtual string16 GetMessageText() const;
virtual string16 GetButtonLabel(InfoBarButton button) const;
virtual bool Accept();
virtual bool Cancel();
virtual void InfoBarClosed();
virtual void InfoBarDismissed();
virtual bool LinkClicked(WindowOpenDisposition disposition);
DISALLOW_COPY_AND_ASSIGN(BlockedPluginInfoBarDelegate);
};
BlockedPluginInfoBarDelegate::BlockedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name)
: PluginInfoBarDelegate(tab_contents, utf16_name) {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Shown.RealPlayer"));
}
BlockedPluginInfoBarDelegate::~BlockedPluginInfoBarDelegate() {
}
string16 BlockedPluginInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_PLUGIN_NOT_AUTHORIZED, name_);
}
string16 BlockedPluginInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PLUGIN_ENABLE_ALWAYS : IDS_PLUGIN_ENABLE_TEMPORARILY);
}
bool BlockedPluginInfoBarDelegate::Accept() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.AlwaysAllow"));
tab_contents_->profile()->GetHostContentSettingsMap()->AddExceptionForURL(
tab_contents_->GetURL(), CONTENT_SETTINGS_TYPE_PLUGINS, std::string(),
CONTENT_SETTING_ALLOW);
tab_contents_->render_view_host()->LoadBlockedPlugins();
return true;
}
bool BlockedPluginInfoBarDelegate::Cancel() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.AllowThisTime"));
return PluginInfoBarDelegate::Cancel();
}
void BlockedPluginInfoBarDelegate::InfoBarDismissed() {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.Dismissed"));
}
void BlockedPluginInfoBarDelegate::InfoBarClosed() {
UserMetrics::RecordAction(UserMetricsAction("BlockedPluginInfobar.Closed"));
PluginInfoBarDelegate::InfoBarClosed();
}
bool BlockedPluginInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
UserMetrics::RecordAction(
UserMetricsAction("BlockedPluginInfobar.LearnMore"));
return PluginInfoBarDelegate::LinkClicked(disposition);
}
// OutdatedPluginInfoBarDelegate ----------------------------------------------
class OutdatedPluginInfoBarDelegate : public PluginInfoBarDelegate {
public:
OutdatedPluginInfoBarDelegate(TabContents* tab_contents,
const string16& name,
const GURL& update_url);
private:
virtual ~OutdatedPluginInfoBarDelegate();
// PluginInfoBarDelegate:
virtual string16 GetMessageText() const;
virtual string16 GetButtonLabel(InfoBarButton button) const;
virtual bool Accept();
virtual bool Cancel();
virtual void InfoBarClosed();
virtual void InfoBarDismissed();
virtual bool LinkClicked(WindowOpenDisposition disposition);
GURL update_url_;
DISALLOW_COPY_AND_ASSIGN(OutdatedPluginInfoBarDelegate);
};
OutdatedPluginInfoBarDelegate::OutdatedPluginInfoBarDelegate(
TabContents* tab_contents,
const string16& utf16_name,
const GURL& update_url)
: PluginInfoBarDelegate(tab_contents, utf16_name),
update_url_(update_url) {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Shown"));
std::string name = UTF16ToUTF8(utf16_name);
if (name == webkit::npapi::PluginGroup::kJavaGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Java"));
else if (name == webkit::npapi::PluginGroup::kQuickTimeGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.QuickTime"));
else if (name == webkit::npapi::PluginGroup::kShockwaveGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Shockwave"));
else if (name == webkit::npapi::PluginGroup::kRealPlayerGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.RealPlayer"));
else if (name == webkit::npapi::PluginGroup::kSilverlightGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Silverlight"));
else if (name == webkit::npapi::PluginGroup::kAdobeReaderGroupName)
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Shown.Reader"));
}
OutdatedPluginInfoBarDelegate::~OutdatedPluginInfoBarDelegate() {
}
string16 OutdatedPluginInfoBarDelegate::GetMessageText() const {
return l10n_util::GetStringFUTF16(IDS_PLUGIN_OUTDATED_PROMPT, name_);
}
string16 OutdatedPluginInfoBarDelegate::GetButtonLabel(
InfoBarButton button) const {
return l10n_util::GetStringUTF16((button == BUTTON_OK) ?
IDS_PLUGIN_UPDATE : IDS_PLUGIN_ENABLE_TEMPORARILY);
}
bool OutdatedPluginInfoBarDelegate::Accept() {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Update"));
tab_contents_->OpenURL(update_url_, GURL(), NEW_FOREGROUND_TAB,
PageTransition::LINK);
return false;
}
bool OutdatedPluginInfoBarDelegate::Cancel() {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.AllowThisTime"));
return PluginInfoBarDelegate::Cancel();
}
void OutdatedPluginInfoBarDelegate::InfoBarDismissed() {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.Dismissed"));
}
void OutdatedPluginInfoBarDelegate::InfoBarClosed() {
UserMetrics::RecordAction(UserMetricsAction("OutdatedPluginInfobar.Closed"));
PluginInfoBarDelegate::InfoBarClosed();
}
bool OutdatedPluginInfoBarDelegate::LinkClicked(
WindowOpenDisposition disposition) {
UserMetrics::RecordAction(
UserMetricsAction("OutdatedPluginInfobar.LearnMore"));
return PluginInfoBarDelegate::LinkClicked(disposition);
}
} // namespace
// PluginObserver -------------------------------------------------------------
PluginObserver::PluginObserver(TabContents* tab_contents)
: TabContentsObserver(tab_contents) {
}
PluginObserver::~PluginObserver() {
}
bool PluginObserver::OnMessageReceived(const IPC::Message& message) {
IPC_BEGIN_MESSAGE_MAP(PluginObserver, message)
IPC_MESSAGE_HANDLER(ViewHostMsg_MissingPluginStatus, OnMissingPluginStatus)
IPC_MESSAGE_HANDLER(ViewHostMsg_CrashedPlugin, OnCrashedPlugin)
IPC_MESSAGE_HANDLER(ViewHostMsg_BlockedOutdatedPlugin,
OnBlockedOutdatedPlugin)
IPC_MESSAGE_UNHANDLED(return false)
IPC_END_MESSAGE_MAP()
return true;
}
PluginInstallerInfoBarDelegate* PluginObserver::GetPluginInstaller() {
if (plugin_installer_ == NULL)
plugin_installer_.reset(new PluginInstallerInfoBarDelegate(tab_contents()));
return plugin_installer_->AsPluginInstallerInfoBarDelegate();
}
void PluginObserver::OnMissingPluginStatus(int status) {
// TODO(PORT): pull in when plug-ins work
#if defined(OS_WIN)
if (status == webkit::npapi::default_plugin::MISSING_PLUGIN_AVAILABLE) {
tab_contents()->AddInfoBar(
new PluginInstallerInfoBarDelegate(tab_contents()));
return;
}
DCHECK_EQ(webkit::npapi::default_plugin::MISSING_PLUGIN_USER_STARTED_DOWNLOAD,
status);
for (size_t i = 0; i < tab_contents()->infobar_count(); ++i) {
InfoBarDelegate* delegate = tab_contents()->GetInfoBarDelegateAt(i);
if (delegate->AsPluginInstallerInfoBarDelegate() != NULL) {
tab_contents()->RemoveInfoBar(delegate);
return;
}
}
#endif
}
void PluginObserver::OnCrashedPlugin(const FilePath& plugin_path) {
DCHECK(!plugin_path.value().empty());
string16 plugin_name = plugin_path.LossyDisplayName();
webkit::npapi::WebPluginInfo plugin_info;
if (webkit::npapi::PluginList::Singleton()->GetPluginInfoByPath(
plugin_path, &plugin_info) &&
!plugin_info.name.empty()) {
plugin_name = plugin_info.name;
#if defined(OS_MACOSX)
// Many plugins on the Mac have .plugin in the actual name, which looks
// terrible, so look for that and strip it off if present.
const std::string kPluginExtension = ".plugin";
if (EndsWith(plugin_name, ASCIIToUTF16(kPluginExtension), true))
plugin_name.erase(plugin_name.length() - kPluginExtension.length());
#endif // OS_MACOSX
}
SkBitmap* crash_icon = ResourceBundle::GetSharedInstance().GetBitmapNamed(
IDR_INFOBAR_PLUGIN_CRASHED);
tab_contents()->AddInfoBar(new SimpleAlertInfoBarDelegate(tab_contents(),
crash_icon,
l10n_util::GetStringFUTF16(IDS_PLUGIN_CRASHED_PROMPT, plugin_name),
true));
}
void PluginObserver::OnBlockedOutdatedPlugin(const string16& name,
const GURL& update_url) {
tab_contents()->AddInfoBar(update_url.is_empty() ?
static_cast<InfoBarDelegate*>(new BlockedPluginInfoBarDelegate(
tab_contents(), name)) :
new OutdatedPluginInfoBarDelegate(tab_contents(), name, update_url));
}
|
Revert 79775 - Re-order the "Run this time" and "Update..." buttons as additional attempt to try and put users in the right direction.
|
Revert 79775 - Re-order the "Run this time" and "Update..." buttons as additional attempt to
try and put users in the right direction.
[email protected]
Review URL: http://codereview.chromium.org/6718038
[email protected]
Review URL: http://codereview.chromium.org/6706006
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@80112 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
|
C++
|
bsd-3-clause
|
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
|
c38fa0ec0dd73d19cc2278c9ef443fd5a52ef143
|
source/reflectionzeug/include/reflectionzeug/property/AccessorValue.hpp
|
source/reflectionzeug/include/reflectionzeug/property/AccessorValue.hpp
|
#pragma once
#include <reflectionzeug/property/AccessorValue.h>
namespace reflectionzeug
{
// Read/write accessor
template <typename Type>
AccessorValue<Type>::AccessorValue()
: m_value()
{
}
template <typename Type>
AccessorValue<Type>::AccessorValue(const Type & defaultValue)
: m_value(defaultValue)
{
}
template <typename Type>
AccessorValue<Type>::~AccessorValue()
{
}
template <typename Type>
AbstractAccessor * AccessorValue<Type>::clone() const
{
return new AccessorValue<Type>(m_value);
}
template <typename Type>
Type * AccessorValue<Type>::ptr() const
{
return const_cast<Type *>(&m_value);
}
template <typename Type>
Type AccessorValue<Type>::value() const
{
return m_value;
}
template <typename Type>
void AccessorValue<Type>::setValue(const Type & value)
{
m_value = value;
}
// Read-only accessor
template <typename Type>
AccessorValue<const Type>::AccessorValue()
{
}
template <typename Type>
AccessorValue<const Type>::AccessorValue(const Type & defaultValue)
: m_value(defaultValue)
{
}
template <typename Type>
AccessorValue<const Type>::~AccessorValue()
{
}
template <typename Type>
AbstractAccessor * AccessorValue<const Type>::clone() const
{
return new AccessorValue<const Type>(m_value);
}
template <typename Type>
Type * AccessorValue<const Type>::ptr() const
{
return nullptr;
}
template <typename Type>
Type AccessorValue<const Type>::value() const
{
return m_value;
}
} // namespace reflectionzeug
|
#pragma once
#include <reflectionzeug/property/AccessorValue.h>
namespace reflectionzeug
{
// Read/write accessor
template <typename Type>
AccessorValue<Type>::AccessorValue()
: m_value()
{
}
template <typename Type>
AccessorValue<Type>::AccessorValue(const Type & defaultValue)
: m_value(defaultValue)
{
}
template <typename Type>
AccessorValue<Type>::~AccessorValue()
{
}
template <typename Type>
AbstractAccessor * AccessorValue<Type>::clone() const
{
return new AccessorValue<Type>(m_value);
}
template <typename Type>
Type * AccessorValue<Type>::ptr() const
{
return const_cast<Type *>(&m_value);
}
template <typename Type>
Type AccessorValue<Type>::value() const
{
return m_value;
}
template <typename Type>
void AccessorValue<Type>::setValue(const Type & value)
{
m_value = value;
}
// Read-only accessor
template <typename Type>
AccessorValue<const Type>::AccessorValue()
: m_value()
{
}
template <typename Type>
AccessorValue<const Type>::AccessorValue(const Type & defaultValue)
: m_value(defaultValue)
{
}
template <typename Type>
AccessorValue<const Type>::~AccessorValue()
{
}
template <typename Type>
AbstractAccessor * AccessorValue<const Type>::clone() const
{
return new AccessorValue<const Type>(m_value);
}
template <typename Type>
Type * AccessorValue<const Type>::ptr() const
{
return nullptr;
}
template <typename Type>
Type AccessorValue<const Type>::value() const
{
return m_value;
}
} // namespace reflectionzeug
|
Fix CID #27353
|
Fix CID #27353
|
C++
|
mit
|
j-o/libzeug,j-o/libzeug,j-o/libzeug,cginternals/libzeug,j-o/libzeug,lanice/libzeug,lanice/libzeug,cginternals/libzeug,lanice/libzeug,lanice/libzeug,cginternals/libzeug,cginternals/libzeug
|
2e6eedc6acfeaef81f2ff0e92aa93db95429d7d9
|
source/reflectionzeug/include/reflectionzeug/property/TypeConverter.hpp
|
source/reflectionzeug/include/reflectionzeug/property/TypeConverter.hpp
|
#pragma once
#include <reflectionzeug/property/TypeConverter.h>
#include <sstream>
namespace reflectionzeug
{
// Type conversion for primitive data types
template <typename Type>
PrimitiveTypeConverter<Type>::PrimitiveTypeConverter()
{
}
template <typename Type>
PrimitiveTypeConverter<Type>::~PrimitiveTypeConverter()
{
}
template <typename Type>
bool PrimitiveTypeConverter<Type>::canConvert(const std::type_info & targetType) const
{
if (targetType == typeid(bool) ||
targetType == typeid(char) ||
targetType == typeid(unsigned char) ||
targetType == typeid(short) ||
targetType == typeid(unsigned short) ||
targetType == typeid(int) ||
targetType == typeid(unsigned int) ||
targetType == typeid(long) ||
targetType == typeid(unsigned long) ||
targetType == typeid(long long) ||
targetType == typeid(unsigned long long) ||
targetType == typeid(float) ||
targetType == typeid(double) ||
targetType == typeid(std::string) )
{
return true;
} else {
return false;
}
}
template <typename Type>
bool PrimitiveTypeConverter<Type>::convert(const Type & value, void * target, const std::type_info & targetType) const
{
if (targetType == typeid(bool)) {
*reinterpret_cast<bool *>(target) = (bool)value;
} else if (targetType == typeid(char)) {
*reinterpret_cast<char *>(target) = (char)value;
} else if (targetType == typeid(unsigned char)) {
*reinterpret_cast<unsigned char *>(target) = (unsigned char)value;
} else if (targetType == typeid(short)) {
*reinterpret_cast<short *>(target) = (short)value;
} else if (targetType == typeid(unsigned short)) {
*reinterpret_cast<unsigned short *>(target) = (unsigned short)value;
} else if (targetType == typeid(int)) {
*reinterpret_cast<int *>(target) = (int)value;
} else if (targetType == typeid(unsigned int)) {
*reinterpret_cast<unsigned int *>(target) = (unsigned int)value;
} else if (targetType == typeid(long)) {
*reinterpret_cast<long *>(target) = (long)value;
} else if (targetType == typeid(unsigned long)) {
*reinterpret_cast<unsigned long *>(target) = (unsigned long)value;
} else if (targetType == typeid(long long)) {
*reinterpret_cast<long long *>(target) = (long long)value;
} else if (targetType == typeid(unsigned long long)) {
*reinterpret_cast<unsigned long long *>(target) = (unsigned long long)value;
} else if (targetType == typeid(float)) {
*reinterpret_cast<float *>(target) = (float)value;
} else if (targetType == typeid(double)) {
*reinterpret_cast<double *>(target) = (double)value;
} else if (targetType == typeid(std::string)) {
std::stringstream s;
s << value;
*reinterpret_cast<std::string *>(target) = s.str();
} else {
return false;
}
return true;
}
// Type conversion for string data types
template <typename Type>
StringConverter<Type>::StringConverter()
{
}
template <typename Type>
StringConverter<Type>::~StringConverter()
{
}
template <typename Type>
bool StringConverter<Type>::canConvert(const std::type_info & targetType) const
{
if (targetType == typeid(bool) ||
targetType == typeid(char) ||
targetType == typeid(unsigned char) ||
targetType == typeid(short) ||
targetType == typeid(unsigned short) ||
targetType == typeid(int) ||
targetType == typeid(unsigned int) ||
targetType == typeid(long) ||
targetType == typeid(unsigned long) ||
targetType == typeid(long long) ||
targetType == typeid(unsigned long long) ||
targetType == typeid(float) ||
targetType == typeid(double) ||
targetType == typeid(std::string) )
{
return true;
} else {
return false;
}
}
template <typename Type>
bool StringConverter<Type>::convert(const Type & value, void * target, const std::type_info & targetType) const
{
if (targetType == typeid(bool)) {
int & v = *reinterpret_cast<int *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(char)) {
char & v = *reinterpret_cast<char *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned char)) {
unsigned char & v = *reinterpret_cast<unsigned char *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(short)) {
short & v = *reinterpret_cast<short *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned short)) {
unsigned short & v = *reinterpret_cast<unsigned short *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(int)) {
int & v = *reinterpret_cast<int *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned int)) {
unsigned int & v = *reinterpret_cast<unsigned int *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(long)) {
long & v = *reinterpret_cast<long *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned long)) {
unsigned long & v = *reinterpret_cast<unsigned long *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(long long)) {
long long & v = *reinterpret_cast<long long *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned long long)) {
unsigned long long & v = *reinterpret_cast<unsigned long long *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(float)) {
float & v = *reinterpret_cast<float *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(double)) {
double & v = *reinterpret_cast<double *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(std::string)) {
*reinterpret_cast<std::string *>(target) = value;
} else {
return false;
}
return true;
}
// Type conversion for bool
template <typename Type>
BoolConverter<Type>::BoolConverter()
{
}
template <typename Type>
BoolConverter<Type>::~BoolConverter()
{
}
template <typename Type>
bool BoolConverter<Type>::convert(const Type & value, void * target, const std::type_info & targetType) const
{
if (targetType == typeid(std::string)) {
*reinterpret_cast<std::string *>(target) = (value ? "true" : "false");
return true;
} else {
return PrimitiveTypeConverter<Type>::convert(value, target, targetType);
}
}
// Type conversion (default empty implemention)
template <typename Type>
TypeConverter<Type>::TypeConverter()
{
}
template <typename Type>
TypeConverter<Type>::~TypeConverter()
{
}
template <typename Type>
bool TypeConverter<Type>::canConvert(const std::type_info & /*targetType*/) const
{
return false;
}
template <typename Type>
bool TypeConverter<Type>::convert(const Type & /*value*/, void * /*target*/, const std::type_info & /*targetType*/) const
{
return false;
}
} // namespace reflectionzeug
|
#pragma once
#include <reflectionzeug/property/TypeConverter.h>
#include <sstream>
namespace reflectionzeug
{
// Type conversion for primitive data types
template <typename Type>
PrimitiveTypeConverter<Type>::PrimitiveTypeConverter()
{
}
template <typename Type>
PrimitiveTypeConverter<Type>::~PrimitiveTypeConverter()
{
}
template <typename Type>
bool PrimitiveTypeConverter<Type>::canConvert(const std::type_info & targetType) const
{
if (targetType == typeid(bool) ||
targetType == typeid(char) ||
targetType == typeid(unsigned char) ||
targetType == typeid(short) ||
targetType == typeid(unsigned short) ||
targetType == typeid(int) ||
targetType == typeid(unsigned int) ||
targetType == typeid(long) ||
targetType == typeid(unsigned long) ||
targetType == typeid(long long) ||
targetType == typeid(unsigned long long) ||
targetType == typeid(float) ||
targetType == typeid(double) ||
targetType == typeid(std::string) )
{
return true;
} else {
return false;
}
}
template <typename Type>
bool PrimitiveTypeConverter<Type>::convert(const Type & value, void * target, const std::type_info & targetType) const
{
if (targetType == typeid(bool)) {
*reinterpret_cast<bool *>(target) = (bool)value;
} else if (targetType == typeid(char)) {
*reinterpret_cast<char *>(target) = (char)value;
} else if (targetType == typeid(unsigned char)) {
*reinterpret_cast<unsigned char *>(target) = (unsigned char)value;
} else if (targetType == typeid(short)) {
*reinterpret_cast<short *>(target) = (short)value;
} else if (targetType == typeid(unsigned short)) {
*reinterpret_cast<unsigned short *>(target) = (unsigned short)value;
} else if (targetType == typeid(int)) {
*reinterpret_cast<int *>(target) = (int)value;
} else if (targetType == typeid(unsigned int)) {
*reinterpret_cast<unsigned int *>(target) = (unsigned int)value;
} else if (targetType == typeid(long)) {
*reinterpret_cast<long *>(target) = (long)value;
} else if (targetType == typeid(unsigned long)) {
*reinterpret_cast<unsigned long *>(target) = (unsigned long)value;
} else if (targetType == typeid(long long)) {
*reinterpret_cast<long long *>(target) = (long long)value;
} else if (targetType == typeid(unsigned long long)) {
*reinterpret_cast<unsigned long long *>(target) = (unsigned long long)value;
} else if (targetType == typeid(float)) {
*reinterpret_cast<float *>(target) = (float)value;
} else if (targetType == typeid(double)) {
*reinterpret_cast<double *>(target) = (double)value;
} else if (targetType == typeid(std::string)) {
std::stringstream s;
s << value;
*reinterpret_cast<std::string *>(target) = s.str();
} else {
return false;
}
return true;
}
// Type conversion for string data types
template <typename Type>
StringConverter<Type>::StringConverter()
{
}
template <typename Type>
StringConverter<Type>::~StringConverter()
{
}
template <typename Type>
bool StringConverter<Type>::canConvert(const std::type_info & targetType) const
{
if (targetType == typeid(bool) ||
targetType == typeid(char) ||
targetType == typeid(unsigned char) ||
targetType == typeid(short) ||
targetType == typeid(unsigned short) ||
targetType == typeid(int) ||
targetType == typeid(unsigned int) ||
targetType == typeid(long) ||
targetType == typeid(unsigned long) ||
targetType == typeid(long long) ||
targetType == typeid(unsigned long long) ||
targetType == typeid(float) ||
targetType == typeid(double) ||
targetType == typeid(std::string) )
{
return true;
} else {
return false;
}
}
template <typename Type>
bool StringConverter<Type>::convert(const Type & value, void * target, const std::type_info & targetType) const
{
if (targetType == typeid(bool)) {
bool & v = *reinterpret_cast<bool *>(target);
if (value == "false" || value == "")
v = false;
else
v = true;
} else if (targetType == typeid(char)) {
char & v = *reinterpret_cast<char *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned char)) {
unsigned char & v = *reinterpret_cast<unsigned char *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(short)) {
short & v = *reinterpret_cast<short *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned short)) {
unsigned short & v = *reinterpret_cast<unsigned short *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(int)) {
int & v = *reinterpret_cast<int *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned int)) {
unsigned int & v = *reinterpret_cast<unsigned int *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(long)) {
long & v = *reinterpret_cast<long *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned long)) {
unsigned long & v = *reinterpret_cast<unsigned long *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(long long)) {
long long & v = *reinterpret_cast<long long *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(unsigned long long)) {
unsigned long long & v = *reinterpret_cast<unsigned long long *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(float)) {
float & v = *reinterpret_cast<float *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(double)) {
double & v = *reinterpret_cast<double *>(target);
std::istringstream(value) >> v;
} else if (targetType == typeid(std::string)) {
*reinterpret_cast<std::string *>(target) = value;
} else {
return false;
}
return true;
}
// Type conversion for bool
template <typename Type>
BoolConverter<Type>::BoolConverter()
{
}
template <typename Type>
BoolConverter<Type>::~BoolConverter()
{
}
template <typename Type>
bool BoolConverter<Type>::convert(const Type & value, void * target, const std::type_info & targetType) const
{
if (targetType == typeid(std::string)) {
*reinterpret_cast<std::string *>(target) = (value ? "true" : "false");
return true;
} else {
return PrimitiveTypeConverter<Type>::convert(value, target, targetType);
}
}
// Type conversion (default empty implemention)
template <typename Type>
TypeConverter<Type>::TypeConverter()
{
}
template <typename Type>
TypeConverter<Type>::~TypeConverter()
{
}
template <typename Type>
bool TypeConverter<Type>::canConvert(const std::type_info & /*targetType*/) const
{
return false;
}
template <typename Type>
bool TypeConverter<Type>::convert(const Type & /*value*/, void * /*target*/, const std::type_info & /*targetType*/) const
{
return false;
}
} // namespace reflectionzeug
|
Fix conversion string -> bool
|
Fix conversion string -> bool
|
C++
|
mit
|
lanice/libzeug,kateyy/libzeug,p-otto/libzeug,kateyy/libzeug,kateyy/libzeug,lanice/libzeug,j-o/libzeug,simonkrogmann/libzeug,j-o/libzeug,cginternals/libzeug,mjendruk/libzeug,cginternals/libzeug,lanice/libzeug,p-otto/libzeug,simonkrogmann/libzeug,mjendruk/libzeug,cginternals/libzeug,lanice/libzeug,mjendruk/libzeug,j-o/libzeug,cginternals/libzeug,j-o/libzeug,p-otto/libzeug
|
937818572b972c2991a3d59e47824f298cad8253
|
content/browser/gpu/gpu_surface_tracker.cc
|
content/browser/gpu/gpu_surface_tracker.cc
|
// 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 "content/browser/gpu/gpu_surface_tracker.h"
#include "base/logging.h"
GpuSurfaceTracker::GpuSurfaceTracker()
: next_surface_id_(1) {
}
GpuSurfaceTracker::~GpuSurfaceTracker() {
}
GpuSurfaceTracker* GpuSurfaceTracker::GetInstance() {
return Singleton<GpuSurfaceTracker>::get();
}
int GpuSurfaceTracker::AddSurfaceForRenderer(int renderer_id,
int render_widget_id) {
base::AutoLock lock(lock_);
SurfaceInfo info = {
renderer_id,
render_widget_id,
gfx::kNullAcceleratedWidget
};
int surface_id = next_surface_id_++;
surface_map_[surface_id] = info;
return surface_id;
}
int GpuSurfaceTracker::LookupSurfaceForRenderer(int renderer_id,
int render_widget_id) {
base::AutoLock lock(lock_);
for (SurfaceMap::iterator it = surface_map_.begin(); it != surface_map_.end();
++it) {
const SurfaceInfo& info = it->second;
if (info.renderer_id == renderer_id &&
info.render_widget_id == render_widget_id) {
return it->first;
}
}
return 0;
}
int GpuSurfaceTracker::AddSurfaceForNativeWidget(
gfx::AcceleratedWidget widget) {
base::AutoLock lock(lock_);
SurfaceInfo info = { 0, 0, widget };
int surface_id = next_surface_id_++;
surface_map_[surface_id] = info;
return surface_id;
}
void GpuSurfaceTracker::RemoveSurface(int surface_id) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
surface_map_.erase(surface_id);
}
bool GpuSurfaceTracker::GetRenderWidgetIDForSurface(int surface_id,
int* renderer_id,
int* render_widget_id) {
base::AutoLock lock(lock_);
SurfaceMap::iterator it = surface_map_.find(surface_id);
if (it == surface_map_.end())
return false;
const SurfaceInfo& info = it->second;
*renderer_id = info.renderer_id;
*render_widget_id = info.render_widget_id;
return true;
}
void GpuSurfaceTracker::SetSurfaceHandle(int surface_id,
const gfx::GLSurfaceHandle& handle) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
SurfaceInfo& info = surface_map_[surface_id];
info.handle = handle;
}
gfx::GLSurfaceHandle GpuSurfaceTracker::GetSurfaceHandle(int surface_id) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
return surface_map_[surface_id].handle;
}
gfx::PluginWindowHandle GpuSurfaceTracker::GetSurfaceWindowHandle(
int surface_id) {
base::AutoLock lock(lock_);
SurfaceMap::iterator it = surface_map_.find(surface_id);
if (it == surface_map_.end())
return gfx::kNullPluginWindow;
return it->second.handle.handle;
}
|
// 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 "content/browser/gpu/gpu_surface_tracker.h"
#include "base/logging.h"
GpuSurfaceTracker::GpuSurfaceTracker()
: next_surface_id_(1) {
}
GpuSurfaceTracker::~GpuSurfaceTracker() {
}
GpuSurfaceTracker* GpuSurfaceTracker::GetInstance() {
return Singleton<GpuSurfaceTracker>::get();
}
int GpuSurfaceTracker::AddSurfaceForRenderer(int renderer_id,
int render_widget_id) {
base::AutoLock lock(lock_);
SurfaceInfo info = {
renderer_id,
render_widget_id,
gfx::kNullAcceleratedWidget
};
int surface_id = next_surface_id_++;
surface_map_[surface_id] = info;
return surface_id;
}
int GpuSurfaceTracker::LookupSurfaceForRenderer(int renderer_id,
int render_widget_id) {
base::AutoLock lock(lock_);
for (SurfaceMap::iterator it = surface_map_.begin(); it != surface_map_.end();
++it) {
const SurfaceInfo& info = it->second;
if (info.renderer_id == renderer_id &&
info.render_widget_id == render_widget_id) {
return it->first;
}
}
return 0;
}
int GpuSurfaceTracker::AddSurfaceForNativeWidget(
gfx::AcceleratedWidget widget) {
base::AutoLock lock(lock_);
SurfaceInfo info = { 0, 0, widget };
int surface_id = next_surface_id_++;
surface_map_[surface_id] = info;
return surface_id;
}
void GpuSurfaceTracker::RemoveSurface(int surface_id) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
surface_map_.erase(surface_id);
}
bool GpuSurfaceTracker::GetRenderWidgetIDForSurface(int surface_id,
int* renderer_id,
int* render_widget_id) {
base::AutoLock lock(lock_);
SurfaceMap::iterator it = surface_map_.find(surface_id);
if (it == surface_map_.end())
return false;
const SurfaceInfo& info = it->second;
*renderer_id = info.renderer_id;
*render_widget_id = info.render_widget_id;
return true;
}
void GpuSurfaceTracker::SetSurfaceHandle(int surface_id,
const gfx::GLSurfaceHandle& handle) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
SurfaceInfo& info = surface_map_[surface_id];
info.handle = handle;
}
gfx::GLSurfaceHandle GpuSurfaceTracker::GetSurfaceHandle(int surface_id) {
base::AutoLock lock(lock_);
DCHECK(surface_map_.find(surface_id) != surface_map_.end());
return surface_map_[surface_id].handle;
}
gfx::PluginWindowHandle GpuSurfaceTracker::GetSurfaceWindowHandle(
int surface_id) {
base::AutoLock lock(lock_);
SurfaceMap::iterator it = surface_map_.find(surface_id);
if (it == surface_map_.end())
return gfx::kNullPluginWindow;
return it->second.handle.handle;
}
|
Fix mac_clang build. Review URL: https://chromiumcodereview.appspot.com/9768005
|
Fix mac_clang build.
Review URL: https://chromiumcodereview.appspot.com/9768005
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@127831 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
gavinp/chromium,ropik/chromium,ropik/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium
|
82246da99a1f9efd41c6a1720632841842032513
|
omaha/enterprise/installer/custom_actions/msi_tag_extractor_test.cc
|
omaha/enterprise/installer/custom_actions/msi_tag_extractor_test.cc
|
// Copyright 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
#include "omaha/enterprise/installer/custom_actions/msi_tag_extractor.h"
#include <atlpath.h>
#include <time.h>
#include <fstream>
#include <vector>
#include "omaha/base/app_util.h"
#include "omaha/base/file.h"
#include "omaha/base/utils.h"
#include "omaha/testing/unit_test.h"
namespace omaha {
class MsiTagExtractorTest : public testing::Test {
protected:
virtual void SetUp() {
unittest_file_path_ = app_util::GetModuleDirectory(NULL);
EXPECT_TRUE(::PathAppend(CStrBuf(unittest_file_path_, MAX_PATH),
_T("..\\staging\\unittest_support\\tagged_msi")));
EXPECT_TRUE(File::Exists(unittest_file_path_));
}
CString GetMsiFilePath(const CString& file_name) const {
CString tagged_msi_path(unittest_file_path_);
EXPECT_TRUE(::PathAppend(CStrBuf(tagged_msi_path, MAX_PATH), file_name));
EXPECT_TRUE(File::Exists(tagged_msi_path));
return tagged_msi_path;
}
private:
CString unittest_file_path_;
};
TEST_F(MsiTagExtractorTest, ValidTag) {
// GUH-brand-only.msi's tag:BRAND=QAQA
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-brand-only.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_TRUE(tag_extractor.GetValue("brand", &brand_code));
EXPECT_EQ(brand_code.compare("QAQA"), 0);
// Tag is case sensitive.
EXPECT_FALSE(tag_extractor.GetValue("Brand", &brand_code));
EXPECT_FALSE(tag_extractor.GetValue("NoneExistKey", &brand_code));
}
TEST_F(MsiTagExtractorTest, ValidTag_AmpersandAtEnd) {
// GUH-ampersand-ending.msi's tag: BRAND=QAQA&
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-ampersand-ending.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_TRUE(tag_extractor.GetValue("brand", &brand_code));
EXPECT_EQ(brand_code.compare("QAQA"), 0);
}
TEST_F(MsiTagExtractorTest, MultiValidTags) {
// File GUH-multiple.msi has tag:
// appguid={8A69D345-D564-463C-AFF1-A69D9E530F96}&
// iid={2D8C18E9-8D3A-4EFC-6D61-AE23E3530EA2}&
// lang=en&browser=4&usagestats=0&appname=Google%20Chrome&
// needsadmin=prefers&brand=CHMB&
// installdataindex=defaultbrowser
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-multiple.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string value;
EXPECT_TRUE(tag_extractor.GetValue("appguid", &value));
EXPECT_EQ(value.compare("{8A69D345-D564-463C-AFF1-A69D9E530F96}"), 0);
EXPECT_TRUE(tag_extractor.GetValue("iid", &value));
EXPECT_EQ(value.compare("{2D8C18E9-8D3A-4EFC-6D61-AE23E3530EA2}"), 0);
EXPECT_TRUE(tag_extractor.GetValue("lang", &value));
EXPECT_EQ(value.compare("en"), 0);
EXPECT_TRUE(tag_extractor.GetValue("browser", &value));
EXPECT_EQ(value.compare("4"), 0);
EXPECT_TRUE(tag_extractor.GetValue("usagestats", &value));
EXPECT_EQ(value.compare("0"), 0);
EXPECT_TRUE(tag_extractor.GetValue("appname", &value));
EXPECT_EQ(value.compare("Google%20Chrome"), 0);
EXPECT_TRUE(tag_extractor.GetValue("needsadmin", &value));
EXPECT_EQ(value.compare("prefers"), 0);
EXPECT_TRUE(tag_extractor.GetValue("brand", &value));
EXPECT_EQ(value.compare("CHMB"), 0);
EXPECT_TRUE(tag_extractor.GetValue("installdataindex", &value));
EXPECT_EQ(value.compare("defaultbrowser"), 0);
}
TEST_F(MsiTagExtractorTest, EmptyKey) {
// GUH-empty-key.msi's tag: =value&BRAND=QAQA
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-empty-key.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_TRUE(tag_extractor.GetValue("brand", &brand_code));
EXPECT_EQ(brand_code.compare("QAQA"), 0);
}
TEST_F(MsiTagExtractorTest, EmptyValue) {
// GUH-empty-value.msi's tag: BRAND=
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-empty-value.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_TRUE(tag_extractor.GetValue("brand", &brand_code));
EXPECT_TRUE(brand_code.empty());
}
TEST_F(MsiTagExtractorTest, NoTagString) {
// GUH-empty-tag.msi's tag:(empty string)
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-empty-tag.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
TEST_F(MsiTagExtractorTest, NoTag) {
// The original MSI is in parent folder.
std::wstring tagged_msi(GetMsiFilePath(_T("..\\GoogleUpdateHelper.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_FALSE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
}
TEST_F(MsiTagExtractorTest, InvalidMagicNumber) {
// GUH-invalid-marker.msi's has invalid magic number "Gact2.0Foo".
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-invalid-marker.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_FALSE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
TEST_F(MsiTagExtractorTest, InvalidTagCharacterInKey) {
// GUH-invalid-key.msi's has invalid charaters in the tag key.
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-invalid-key.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("br*nd", &brand_code));
}
TEST_F(MsiTagExtractorTest, InvalidTagCharacterInValue) {
// GUH-invalid-value.msi's has invalid charaters in the tag value.
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-invalid-value.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
TEST_F(MsiTagExtractorTest, InvalidTagFormat) {
// GUH-bad-format.msi's has invalid tag format.
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-bad-format.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
TEST_F(MsiTagExtractorTest, InvalidTagFormat2) {
// GUH-bad-format2.msi's has invalid tag format.
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-bad-format.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
} // namespace omaha
|
// Copyright 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========================================================================
#include "omaha/enterprise/installer/custom_actions/msi_tag_extractor.h"
#include <atlpath.h>
#include <time.h>
#include <fstream>
#include <vector>
#include "omaha/base/app_util.h"
#include "omaha/base/file.h"
#include "omaha/base/utils.h"
#include "omaha/testing/unit_test.h"
namespace omaha {
class MsiTagExtractorTest : public testing::Test {
protected:
virtual void SetUp() {
unittest_file_path_ = app_util::GetModuleDirectory(NULL);
EXPECT_TRUE(::PathAppend(CStrBuf(unittest_file_path_, MAX_PATH),
_T("unittest_support\\tagged_msi")));
EXPECT_TRUE(File::Exists(unittest_file_path_));
}
CString GetMsiFilePath(const CString& file_name) const {
CString tagged_msi_path(unittest_file_path_);
EXPECT_TRUE(::PathAppend(CStrBuf(tagged_msi_path, MAX_PATH), file_name));
EXPECT_TRUE(File::Exists(tagged_msi_path));
return tagged_msi_path;
}
private:
CString unittest_file_path_;
};
TEST_F(MsiTagExtractorTest, ValidTag) {
// GUH-brand-only.msi's tag:BRAND=QAQA
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-brand-only.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_TRUE(tag_extractor.GetValue("brand", &brand_code));
EXPECT_EQ(brand_code.compare("QAQA"), 0);
// Tag is case sensitive.
EXPECT_FALSE(tag_extractor.GetValue("Brand", &brand_code));
EXPECT_FALSE(tag_extractor.GetValue("NoneExistKey", &brand_code));
}
TEST_F(MsiTagExtractorTest, ValidTag_AmpersandAtEnd) {
// GUH-ampersand-ending.msi's tag: BRAND=QAQA&
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-ampersand-ending.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_TRUE(tag_extractor.GetValue("brand", &brand_code));
EXPECT_EQ(brand_code.compare("QAQA"), 0);
}
TEST_F(MsiTagExtractorTest, MultiValidTags) {
// File GUH-multiple.msi has tag:
// appguid={8A69D345-D564-463C-AFF1-A69D9E530F96}&
// iid={2D8C18E9-8D3A-4EFC-6D61-AE23E3530EA2}&
// lang=en&browser=4&usagestats=0&appname=Google%20Chrome&
// needsadmin=prefers&brand=CHMB&
// installdataindex=defaultbrowser
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-multiple.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string value;
EXPECT_TRUE(tag_extractor.GetValue("appguid", &value));
EXPECT_EQ(value.compare("{8A69D345-D564-463C-AFF1-A69D9E530F96}"), 0);
EXPECT_TRUE(tag_extractor.GetValue("iid", &value));
EXPECT_EQ(value.compare("{2D8C18E9-8D3A-4EFC-6D61-AE23E3530EA2}"), 0);
EXPECT_TRUE(tag_extractor.GetValue("lang", &value));
EXPECT_EQ(value.compare("en"), 0);
EXPECT_TRUE(tag_extractor.GetValue("browser", &value));
EXPECT_EQ(value.compare("4"), 0);
EXPECT_TRUE(tag_extractor.GetValue("usagestats", &value));
EXPECT_EQ(value.compare("0"), 0);
EXPECT_TRUE(tag_extractor.GetValue("appname", &value));
EXPECT_EQ(value.compare("Google%20Chrome"), 0);
EXPECT_TRUE(tag_extractor.GetValue("needsadmin", &value));
EXPECT_EQ(value.compare("prefers"), 0);
EXPECT_TRUE(tag_extractor.GetValue("brand", &value));
EXPECT_EQ(value.compare("CHMB"), 0);
EXPECT_TRUE(tag_extractor.GetValue("installdataindex", &value));
EXPECT_EQ(value.compare("defaultbrowser"), 0);
}
TEST_F(MsiTagExtractorTest, EmptyKey) {
// GUH-empty-key.msi's tag: =value&BRAND=QAQA
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-empty-key.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_TRUE(tag_extractor.GetValue("brand", &brand_code));
EXPECT_EQ(brand_code.compare("QAQA"), 0);
}
TEST_F(MsiTagExtractorTest, EmptyValue) {
// GUH-empty-value.msi's tag: BRAND=
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-empty-value.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_TRUE(tag_extractor.GetValue("brand", &brand_code));
EXPECT_TRUE(brand_code.empty());
}
TEST_F(MsiTagExtractorTest, NoTagString) {
// GUH-empty-tag.msi's tag:(empty string)
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-empty-tag.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
TEST_F(MsiTagExtractorTest, NoTag) {
// The original MSI is in parent folder.
std::wstring tagged_msi(GetMsiFilePath(_T("..\\GoogleUpdateHelper.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_FALSE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
}
TEST_F(MsiTagExtractorTest, InvalidMagicNumber) {
// GUH-invalid-marker.msi's has invalid magic number "Gact2.0Foo".
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-invalid-marker.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_FALSE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
TEST_F(MsiTagExtractorTest, InvalidTagCharacterInKey) {
// GUH-invalid-key.msi's has invalid charaters in the tag key.
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-invalid-key.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("br*nd", &brand_code));
}
TEST_F(MsiTagExtractorTest, InvalidTagCharacterInValue) {
// GUH-invalid-value.msi's has invalid charaters in the tag value.
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-invalid-value.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
TEST_F(MsiTagExtractorTest, InvalidTagFormat) {
// GUH-bad-format.msi's has invalid tag format.
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-bad-format.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
TEST_F(MsiTagExtractorTest, InvalidTagFormat2) {
// GUH-bad-format2.msi's has invalid tag format.
std::wstring tagged_msi(GetMsiFilePath(_T("GUH-bad-format.msi")));
custom_action::MsiTagExtractor tag_extractor;
EXPECT_TRUE(tag_extractor.ReadTagFromFile(tagged_msi.c_str()));
std::string brand_code;
EXPECT_FALSE(tag_extractor.GetValue("brand", &brand_code));
}
} // namespace omaha
|
read unittest_support files from direct relative path
|
MsiTagExtractorTest: read unittest_support files from direct relative path
|
C++
|
apache-2.0
|
google/omaha,google/omaha,google/omaha,google/omaha,google/omaha
|
efbbeb195fc8b9c0da900bd412e1293abfb23c4a
|
test/std/experimental/filesystem/fs.op.funcs/fs.op.proximate/proximate.pass.cpp
|
test/std/experimental/filesystem/fs.op.funcs/fs.op.proximate/proximate.pass.cpp
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// <experimental/filesystem>
// path proximate(const path& p, error_code &ec)
// path proximate(const path& p, const path& base = current_path())
// path proximate(const path& p, const path& base, error_code& ec);
#include "filesystem_include.hpp"
#include <type_traits>
#include <vector>
#include <iostream>
#include <cassert>
#include "test_macros.h"
#include "test_iterators.h"
#include "count_new.hpp"
#include "rapid-cxx-test.hpp"
#include "filesystem_test_helper.hpp"
static int count_path_elems(const fs::path& p) {
int count = 0;
for (auto& elem : p) {
if (elem != "/" && elem != "")
++count;
}
return count;
}
TEST_SUITE(filesystem_proximate_path_test_suite)
TEST_CASE(signature_test)
{
using fs::path;
const path p; ((void)p);
std::error_code ec; ((void)ec);
ASSERT_NOT_NOEXCEPT(proximate(p));
ASSERT_NOT_NOEXCEPT(proximate(p, p));
ASSERT_NOT_NOEXCEPT(proximate(p, ec));
ASSERT_NOT_NOEXCEPT(proximate(p, p, ec));
}
TEST_CASE(basic_test) {
using fs::path;
const path cwd = fs::current_path();
const path parent_cwd = cwd.parent_path();
const path curdir = cwd.filename();
TEST_REQUIRE(!cwd.native().empty());
int cwd_depth = count_path_elems(cwd);
path dot_dot_to_root;
for (int i=0; i < cwd_depth; ++i)
dot_dot_to_root /= "..";
path relative_cwd = cwd.native().substr(1);
// clang-format off
struct {
std::string input;
std::string base;
std::string expect;
} TestCases[] = {
{"", "", "."},
{cwd, "a", ".."},
{parent_cwd, "a", "../.."},
{"a", cwd, "a"},
{"a", parent_cwd, "fs.op.proximate/a"},
{"/", "a", dot_dot_to_root / ".."},
{"/", "a/b", dot_dot_to_root / "../.."},
{"/", "a/b/", dot_dot_to_root / "../../.."},
{"a", "/", relative_cwd / "a"},
{"a/b", "/", relative_cwd / "a/b"},
{"a", "/net", ".." / relative_cwd / "a"},
{"//net/", "//net", "/net/"},
{"//net", "//net/", ".."},
{"//net", "//net", "."},
{"//net/", "//net/", "."},
{"//base", "a", dot_dot_to_root / "../base"},
{"a", "a", "."},
{"a/b", "a/b", "."},
{"a/b/c/", "a/b/c/", "."},
{"//net/a/b", "//net/a/b", "."},
{"/a/d", "/a/b/c", "../../d"},
{"/a/b/c", "/a/d", "../b/c"},
{"a/b/c", "a", "b/c"},
{"a/b/c", "a/b/c/x/y", "../.."},
{"a/b/c", "a/b/c", "."},
{"a/b", "c/d", "../../a/b"}
};
// clang-format on
int ID = 0;
for (auto& TC : TestCases) {
++ID;
std::error_code ec = GetTestEC();
fs::path p(TC.input);
const fs::path output = fs::proximate(p, TC.base, ec);
TEST_CHECK(!ec);
TEST_CHECK(PathEq(output, TC.expect));
if (!PathEq(output, TC.expect)) {
const path canon_input = fs::weakly_canonical(TC.input);
const path canon_base = fs::weakly_canonical(TC.base);
const path lexically_p = canon_input.lexically_proximate(canon_base);
std::cerr << "TEST CASE #" << ID << " FAILED: \n";
std::cerr << " Input: '" << TC.input << "'\n";
std::cerr << " Base: '" << TC.base << "'\n";
std::cerr << " Expected: '" << TC.expect << "'\n";
std::cerr << " Output: '" << output.native() << "'\n";
std::cerr << " Lex Prox: '" << lexically_p.native() << "'\n";
std::cerr << " Canon Input: " << canon_input << "\n";
std::cerr << " Canon Base: " << canon_base << "\n";
std::cerr << std::endl;
}
}
}
TEST_SUITE_END()
|
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// <experimental/filesystem>
// path proximate(const path& p, error_code &ec)
// path proximate(const path& p, const path& base = current_path())
// path proximate(const path& p, const path& base, error_code& ec);
#include "filesystem_include.hpp"
#include <type_traits>
#include <vector>
#include <iostream>
#include <cassert>
#include "test_macros.h"
#include "test_iterators.h"
#include "count_new.hpp"
#include "rapid-cxx-test.hpp"
#include "filesystem_test_helper.hpp"
static int count_path_elems(const fs::path& p) {
int count = 0;
for (auto& elem : p) {
if (elem != "/" && elem != "")
++count;
}
return count;
}
TEST_SUITE(filesystem_proximate_path_test_suite)
TEST_CASE(signature_test)
{
using fs::path;
const path p; ((void)p);
std::error_code ec; ((void)ec);
ASSERT_NOT_NOEXCEPT(proximate(p));
ASSERT_NOT_NOEXCEPT(proximate(p, p));
ASSERT_NOT_NOEXCEPT(proximate(p, ec));
ASSERT_NOT_NOEXCEPT(proximate(p, p, ec));
}
TEST_CASE(basic_test) {
using fs::path;
const path cwd = fs::current_path();
const path parent_cwd = cwd.parent_path();
const path curdir = cwd.filename();
TEST_REQUIRE(!cwd.native().empty());
int cwd_depth = count_path_elems(cwd);
path dot_dot_to_root;
for (int i=0; i < cwd_depth; ++i)
dot_dot_to_root /= "..";
path relative_cwd = cwd.native().substr(1);
// clang-format off
struct {
std::string input;
std::string base;
std::string expect;
} TestCases[] = {
{"", "", "."},
{cwd, "a", ".."},
{parent_cwd, "a", "../.."},
{"a", cwd, "a"},
{"a", parent_cwd, "fs.op.proximate/a"},
{"/", "a", dot_dot_to_root / ".."},
{"/", "a/b", dot_dot_to_root / "../.."},
{"/", "a/b/", dot_dot_to_root / "../../.."},
{"a", "/", relative_cwd / "a"},
{"a/b", "/", relative_cwd / "a/b"},
{"a", "/net", ".." / relative_cwd / "a"},
{"//foo/", "//foo", "/foo/"},
{"//foo", "//foo/", ".."},
{"//foo", "//foo", "."},
{"//foo/", "//foo/", "."},
{"//base", "a", dot_dot_to_root / "../base"},
{"a", "a", "."},
{"a/b", "a/b", "."},
{"a/b/c/", "a/b/c/", "."},
{"//net/a/b", "//net/a/b", "."},
{"/a/d", "/a/b/c", "../../d"},
{"/a/b/c", "/a/d", "../b/c"},
{"a/b/c", "a", "b/c"},
{"a/b/c", "a/b/c/x/y", "../.."},
{"a/b/c", "a/b/c", "."},
{"a/b", "c/d", "../../a/b"}
};
// clang-format on
int ID = 0;
for (auto& TC : TestCases) {
++ID;
std::error_code ec = GetTestEC();
fs::path p(TC.input);
const fs::path output = fs::proximate(p, TC.base, ec);
TEST_CHECK(!ec);
TEST_CHECK(PathEq(output, TC.expect));
if (!PathEq(output, TC.expect)) {
const path canon_input = fs::weakly_canonical(TC.input);
const path canon_base = fs::weakly_canonical(TC.base);
const path lexically_p = canon_input.lexically_proximate(canon_base);
std::cerr << "TEST CASE #" << ID << " FAILED: \n";
std::cerr << " Input: '" << TC.input << "'\n";
std::cerr << " Base: '" << TC.base << "'\n";
std::cerr << " Expected: '" << TC.expect << "'\n";
std::cerr << " Output: '" << output.native() << "'\n";
std::cerr << " Lex Prox: '" << lexically_p.native() << "'\n";
std::cerr << " Canon Input: " << canon_input << "\n";
std::cerr << " Canon Base: " << canon_base << "\n";
std::cerr << std::endl;
}
}
}
TEST_SUITE_END()
|
Fix fs::proximate tests on platforms where /net exists.
|
Fix fs::proximate tests on platforms where /net exists.
The proximate tests depended on `/net` not being a valid path,
however, on OS X it is.
Correct the tests to handle this.
git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@329038 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
|
eba8f1b74bad5e5d1d899610578384665be8fc40
|
alloutil/alloutil/al_Simulator.hpp
|
alloutil/alloutil/al_Simulator.hpp
|
#ifndef AL_SIMULATOR_H
#define AL_SIMULATOR_H
#include "allocore/al_Allocore.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_InterfaceServerClient.hpp"
using namespace std;
using namespace al;
class Simulator : public InterfaceServerClient, public Main::Handler {
public:
Simulator(const char* deviceServerAddress="127.0.0.1", int port=12001,
int deviceServerPort=12000);
virtual ~Simulator();
virtual void start();
virtual void stop();
virtual void init() = 0;
virtual void step(double dt) = 0;
virtual void exit() = 0;
virtual void onTick();
virtual void onExit();
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
const Lens& lens() const { return mLens; }
Lens& lens() { return mLens; }
// virtual void onMessage(osc::Message& m);
static bool sim(){
std::string hostname = Socket::hostName();
return (hostname == "gr01" || hostname == "audio.10g");
}
static const char* defaultBroadcastIP(){
if(sim()) return "192.168.10.255";
else return "127.0.0.1";
}
static const char* defaultInterfaceServerIP(){
if(sim()) return "192.168.0.234"; //"192.168.0.74"; //interface mac mini
else return "127.0.0.1";
}
protected:
bool started;
double time, lastTime;
Nav mNav;
Lens mLens;
// NavInputControl mNavControl;
// StandardWindowKeyControls mStdControls;
// double mNavSpeed, mNavTurnSpeed;
};
inline void Simulator::onTick() {
if (!started) {
started = true;
time = Main::get().realtime();
init();
}
while (oscRecv().recv()) {
}
lastTime = time;
time = Main::get().realtime();
nav().step(time - lastTime);
step(time - lastTime);
}
inline void Simulator::onExit() { exit(); }
// inline void Simulator::onMessage(osc::Message& m) {
// // This allows the graphics renderer (or whatever) to overwrite navigation
// // data, so you can navigate from the graphics window when using a laptop.
// //
// // cout << "Simulator receive: " << m.addressPattern() << endl;
// // if (m.addressPattern() == "/pose") {
// // Pose pose;
// // m >> pose.pos().x;
// // m >> pose.pos().y;
// // m >> pose.pos().z;
// // m >> pose.quat().x;
// // m >> pose.quat().y;
// // m >> pose.quat().z;
// // m >> pose.quat().w;
// // //pose.print();
// // nav().set(pose);
// // }
// InterfaceServerClient::onMessage(m);
// // nav().print();
// }
inline void Simulator::start() {
InterfaceServerClient::connect();
Main::get().interval(1 / 60.0).add(*this).start();
}
inline void Simulator::stop() { cout << "Simulator stopped." <<endl; Main::get().stop(); }
inline Simulator::~Simulator() {
InterfaceServerClient::disconnect();
// oscSend().send("/interface/disconnectApplication", name());
}
#endif
|
#ifndef AL_SIMULATOR_H
#define AL_SIMULATOR_H
#include "allocore/al_Allocore.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_InterfaceServerClient.hpp"
using namespace std;
namespace al {
class Simulator : public InterfaceServerClient, public Main::Handler {
public:
Simulator(const char* deviceServerAddress="127.0.0.1", int port=12001,
int deviceServerPort=12000);
virtual ~Simulator();
virtual void start();
virtual void stop();
virtual void init() = 0;
virtual void step(double dt) = 0;
virtual void exit() = 0;
virtual void onTick();
virtual void onExit();
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
const Lens& lens() const { return mLens; }
Lens& lens() { return mLens; }
// virtual void onMessage(osc::Message& m);
static bool sim(){
std::string hostname = Socket::hostName();
return (hostname == "gr01" || hostname == "audio.10g");
}
static const char* defaultBroadcastIP(){
if(sim()) return "192.168.10.255";
else return "127.0.0.1";
}
static const char* defaultInterfaceServerIP(){
if(sim()) return "192.168.0.234"; //"192.168.0.74"; //interface mac mini
else return "127.0.0.1";
}
protected:
bool started;
double time, lastTime;
Nav mNav;
Lens mLens;
// NavInputControl mNavControl;
// StandardWindowKeyControls mStdControls;
// double mNavSpeed, mNavTurnSpeed;
};
inline void Simulator::onTick() {
if (!started) {
started = true;
time = Main::get().realtime();
init();
}
while (oscRecv().recv()) {
}
lastTime = time;
time = Main::get().realtime();
nav().step(time - lastTime);
step(time - lastTime);
}
inline void Simulator::onExit() { exit(); }
// inline void Simulator::onMessage(osc::Message& m) {
// // This allows the graphics renderer (or whatever) to overwrite navigation
// // data, so you can navigate from the graphics window when using a laptop.
// //
// // cout << "Simulator receive: " << m.addressPattern() << endl;
// // if (m.addressPattern() == "/pose") {
// // Pose pose;
// // m >> pose.pos().x;
// // m >> pose.pos().y;
// // m >> pose.pos().z;
// // m >> pose.quat().x;
// // m >> pose.quat().y;
// // m >> pose.quat().z;
// // m >> pose.quat().w;
// // //pose.print();
// // nav().set(pose);
// // }
// InterfaceServerClient::onMessage(m);
// // nav().print();
// }
inline void Simulator::start() {
InterfaceServerClient::connect();
Main::get().interval(1 / 60.0).add(*this).start();
}
inline void Simulator::stop() { cout << "Simulator stopped." <<endl; Main::get().stop(); }
inline Simulator::~Simulator() {
InterfaceServerClient::disconnect();
// oscSend().send("/interface/disconnectApplication", name());
}
}
#endif
|
Put Simulator class inside al namespace to avoid clashes
|
Put Simulator class inside al namespace to avoid clashes
|
C++
|
bsd-3-clause
|
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
|
e0834f7f385b69d67a6d3d9bc05f41257bdf4977
|
tgt-vhdl/logic.cc
|
tgt-vhdl/logic.cc
|
/*
* VHDL code generation for logic devices.
*
* Copyright (C) 2008 Nick Gasson ([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 "vhdl_target.h"
#include "vhdl_element.hh"
#include <cassert>
#include <iostream>
/*
* Convert the inputs of a logic gate to a binary expression.
*/
static vhdl_expr *inputs_to_expr(vhdl_scope *scope, vhdl_binop_t op,
ivl_net_logic_t log)
{
// Not always std_logic but this is probably OK since
// the program has already been type checked
vhdl_binop_expr *gate =
new vhdl_binop_expr(op, vhdl_type::std_logic());
int npins = ivl_logic_pins(log);
for (int i = 1; i < npins; i++) {
ivl_nexus_t input = ivl_logic_pin(log, i);
gate->add_expr(nexus_to_var_ref(scope, input));
}
return gate;
}
/*
* Convert a gate intput to an unary expression.
*/
static vhdl_expr *input_to_expr(vhdl_scope *scope, vhdl_unaryop_t op,
ivl_net_logic_t log)
{
ivl_nexus_t input = ivl_logic_pin(log, 1);
assert(input);
vhdl_expr *operand = nexus_to_var_ref(scope, input);
return new vhdl_unaryop_expr(op, operand, vhdl_type::std_logic());
}
static void bufif_logic(vhdl_arch *arch, ivl_net_logic_t log, bool if0)
{
ivl_nexus_t output = ivl_logic_pin(log, 0);
vhdl_var_ref *lhs = nexus_to_var_ref(arch->get_scope(), output);
assert(lhs);
vhdl_expr *val = nexus_to_var_ref(arch->get_scope(), ivl_logic_pin(log, 1));
assert(val);
vhdl_expr *sel = nexus_to_var_ref(arch->get_scope(), ivl_logic_pin(log, 2));
assert(val);
vhdl_expr *on = new vhdl_const_bit(if0 ? '0' : '1');
vhdl_expr *cmp = new vhdl_binop_expr(sel, VHDL_BINOP_EQ, on, NULL);
ivl_signal_t sig = find_signal_named(lhs->get_name(), arch->get_scope());
char zbit;
switch (ivl_signal_type(sig)) {
case IVL_SIT_TRI0:
zbit = '0';
break;
case IVL_SIT_TRI1:
zbit = '1';
break;
case IVL_SIT_TRI:
default:
zbit = 'Z';
}
vhdl_const_bit *z = new vhdl_const_bit(zbit);
vhdl_cassign_stmt *cass = new vhdl_cassign_stmt(lhs, z);
cass->add_condition(val, cmp);
arch->add_stmt(cass);
}
static void udp_logic(vhdl_arch *arch, ivl_net_logic_t log)
{
ivl_udp_t udp = ivl_logic_udp(log);
cout << "UDP " << ivl_udp_name(udp) << " nin="
<< ivl_udp_nin(udp) << " rows="
<< ivl_udp_rows(udp) << endl;
if (ivl_udp_sequ(udp)) {
error("Sequential UDP devices not supported yet");
return;
}
}
static vhdl_expr *translate_logic_inputs(vhdl_scope *scope, ivl_net_logic_t log)
{
switch (ivl_logic_type(log)) {
case IVL_LO_NOT:
return input_to_expr(scope, VHDL_UNARYOP_NOT, log);
case IVL_LO_AND:
return inputs_to_expr(scope, VHDL_BINOP_AND, log);
case IVL_LO_OR:
return inputs_to_expr(scope, VHDL_BINOP_OR, log);
case IVL_LO_XOR:
return inputs_to_expr(scope, VHDL_BINOP_XOR, log);
case IVL_LO_BUF:
case IVL_LO_BUFZ:
return nexus_to_var_ref(scope, ivl_logic_pin(log, 1));
case IVL_LO_PULLUP:
return new vhdl_const_bit('1');
case IVL_LO_PULLDOWN:
return new vhdl_const_bit('0');
default:
error("Don't know how to translate logic type = %d to expression",
ivl_logic_type(log));
return NULL;
}
}
void draw_logic(vhdl_arch *arch, ivl_net_logic_t log)
{
switch (ivl_logic_type(log)) {
case IVL_LO_BUFIF0:
bufif_logic(arch, log, true);
break;
case IVL_LO_BUFIF1:
bufif_logic(arch, log, false);
break;
case IVL_LO_UDP:
udp_logic(arch, log);
break;
default:
{
// The output is always pin zero
ivl_nexus_t output = ivl_logic_pin(log, 0);
vhdl_var_ref *lhs = nexus_to_var_ref(arch->get_scope(), output);
vhdl_expr *rhs = translate_logic_inputs(arch->get_scope(), log);
vhdl_cassign_stmt *ass = new vhdl_cassign_stmt(lhs, rhs);
ivl_expr_t delay = ivl_logic_delay(log, 1);
if (delay)
ass->set_after(translate_time_expr(delay));
arch->add_stmt(ass);
}
}
}
|
/*
* VHDL code generation for logic devices.
*
* Copyright (C) 2008 Nick Gasson ([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 "vhdl_target.h"
#include "vhdl_element.hh"
#include <cassert>
#include <iostream>
/*
* Convert the inputs of a logic gate to a binary expression.
*/
static vhdl_expr *inputs_to_expr(vhdl_scope *scope, vhdl_binop_t op,
ivl_net_logic_t log)
{
// Not always std_logic but this is probably OK since
// the program has already been type checked
vhdl_binop_expr *gate =
new vhdl_binop_expr(op, vhdl_type::std_logic());
int npins = ivl_logic_pins(log);
for (int i = 1; i < npins; i++) {
ivl_nexus_t input = ivl_logic_pin(log, i);
gate->add_expr(nexus_to_var_ref(scope, input));
}
return gate;
}
/*
* Convert a gate intput to an unary expression.
*/
static vhdl_expr *input_to_expr(vhdl_scope *scope, vhdl_unaryop_t op,
ivl_net_logic_t log)
{
ivl_nexus_t input = ivl_logic_pin(log, 1);
assert(input);
vhdl_expr *operand = nexus_to_var_ref(scope, input);
return new vhdl_unaryop_expr(op, operand, vhdl_type::std_logic());
}
static void bufif_logic(vhdl_arch *arch, ivl_net_logic_t log, bool if0)
{
ivl_nexus_t output = ivl_logic_pin(log, 0);
vhdl_var_ref *lhs = nexus_to_var_ref(arch->get_scope(), output);
assert(lhs);
vhdl_expr *val = nexus_to_var_ref(arch->get_scope(), ivl_logic_pin(log, 1));
assert(val);
vhdl_expr *sel = nexus_to_var_ref(arch->get_scope(), ivl_logic_pin(log, 2));
assert(val);
vhdl_expr *on = new vhdl_const_bit(if0 ? '0' : '1');
vhdl_expr *cmp = new vhdl_binop_expr(sel, VHDL_BINOP_EQ, on, NULL);
ivl_signal_t sig = find_signal_named(lhs->get_name(), arch->get_scope());
char zbit;
switch (ivl_signal_type(sig)) {
case IVL_SIT_TRI0:
zbit = '0';
break;
case IVL_SIT_TRI1:
zbit = '1';
break;
case IVL_SIT_TRI:
default:
zbit = 'Z';
}
vhdl_const_bit *z = new vhdl_const_bit(zbit);
vhdl_cassign_stmt *cass = new vhdl_cassign_stmt(lhs, z);
cass->add_condition(val, cmp);
arch->add_stmt(cass);
}
static void udp_logic(vhdl_arch *arch, ivl_net_logic_t log)
{
ivl_udp_t udp = ivl_logic_udp(log);
cout << "UDP " << ivl_udp_name(udp) << " nin="
<< ivl_udp_nin(udp) << " rows="
<< ivl_udp_rows(udp) << endl;
if (ivl_udp_sequ(udp)) {
error("Sequential UDP devices not supported yet");
return;
}
}
static vhdl_expr *translate_logic_inputs(vhdl_scope *scope, ivl_net_logic_t log)
{
switch (ivl_logic_type(log)) {
case IVL_LO_NOT:
return input_to_expr(scope, VHDL_UNARYOP_NOT, log);
case IVL_LO_AND:
return inputs_to_expr(scope, VHDL_BINOP_AND, log);
case IVL_LO_OR:
return inputs_to_expr(scope, VHDL_BINOP_OR, log);
case IVL_LO_NAND:
return inputs_to_expr(scope, VHDL_BINOP_NAND, log);
case IVL_LO_NOR:
return inputs_to_expr(scope, VHDL_BINOP_NOR, log);
case IVL_LO_XOR:
return inputs_to_expr(scope, VHDL_BINOP_XOR, log);
case IVL_LO_BUF:
case IVL_LO_BUFZ:
return nexus_to_var_ref(scope, ivl_logic_pin(log, 1));
case IVL_LO_PULLUP:
return new vhdl_const_bit('1');
case IVL_LO_PULLDOWN:
return new vhdl_const_bit('0');
default:
error("Don't know how to translate logic type = %d to expression",
ivl_logic_type(log));
return NULL;
}
}
void draw_logic(vhdl_arch *arch, ivl_net_logic_t log)
{
switch (ivl_logic_type(log)) {
case IVL_LO_BUFIF0:
bufif_logic(arch, log, true);
break;
case IVL_LO_BUFIF1:
bufif_logic(arch, log, false);
break;
case IVL_LO_UDP:
udp_logic(arch, log);
break;
default:
{
// The output is always pin zero
ivl_nexus_t output = ivl_logic_pin(log, 0);
vhdl_var_ref *lhs = nexus_to_var_ref(arch->get_scope(), output);
vhdl_expr *rhs = translate_logic_inputs(arch->get_scope(), log);
vhdl_cassign_stmt *ass = new vhdl_cassign_stmt(lhs, rhs);
ivl_expr_t delay = ivl_logic_delay(log, 1);
if (delay)
ass->set_after(translate_time_expr(delay));
arch->add_stmt(ass);
}
}
}
|
Add NAND and NOR logic devices
|
Add NAND and NOR logic devices
|
C++
|
lgpl-2.1
|
CastMi/iverilog,themperek/iverilog,themperek/iverilog,themperek/iverilog,CastMi/iverilog,CastMi/iverilog
|
0a2a1e0230eedd1f83047ddb34f8faa0149f5387
|
ELF/DriverUtils.cpp
|
ELF/DriverUtils.cpp
|
//===- DriverUtils.cpp ----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains utility functions for the driver. Because there
// are so many small functions, we created this separate file to make
// Driver.cpp less cluttered.
//
//===----------------------------------------------------------------------===//
#include "Driver.h"
#include "Error.h"
#include "Memory.h"
#include "lld/Config/Version.h"
#include "lld/Core/Reproduce.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
using namespace llvm;
using namespace llvm::sys;
using namespace lld;
using namespace lld::elf;
// Create OptTable
// Create prefix string literals used in Options.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX
// Create table mapping all options defined in Options.td
static const opt::OptTable::Info OptInfo[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
{X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
#include "Options.inc"
#undef OPTION
};
ELFOptTable::ELFOptTable() : OptTable(OptInfo) {}
// Parse -color-diagnostics={auto,always,never} or -no-color-diagnostics.
static bool getColorDiagnostics(opt::InputArgList &Args) {
auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
OPT_no_color_diagnostics);
if (!Arg)
return ErrorOS->has_colors();
if (Arg->getOption().getID() == OPT_color_diagnostics)
return true;
if (Arg->getOption().getID() == OPT_no_color_diagnostics)
return false;
StringRef S = Arg->getValue();
if (S == "auto")
return ErrorOS->has_colors();
if (S == "always")
return true;
if (S != "never")
error("unknown option: -color-diagnostics=" + S);
return false;
}
static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
StringRef S = Arg->getValue();
if (S != "windows" && S != "posix")
error("invalid response file quoting: " + S);
if (S == "windows")
return cl::TokenizeWindowsCommandLine;
return cl::TokenizeGNUCommandLine;
}
if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
return cl::TokenizeWindowsCommandLine;
return cl::TokenizeGNUCommandLine;
}
// Parses a given list of options.
opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
// Make InputArgList from string vectors.
unsigned MissingIndex;
unsigned MissingCount;
SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
// We need to get the quoting style for response files before parsing all
// options so we parse here before and ignore all the options but
// --rsp-quoting.
opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
// Expand response files (arguments in the form of @<filename>)
// and then parse the argument again.
cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
// Interpret -color-diagnostics early so that error messages
// for unknown flags are colored.
Config->ColorDiagnostics = getColorDiagnostics(Args);
if (MissingCount)
error(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
for (auto *Arg : Args.filtered(OPT_UNKNOWN))
error("unknown argument: " + Arg->getSpelling());
return Args;
}
void elf::printHelp(const char *Argv0) {
ELFOptTable Table;
Table.PrintHelp(outs(), Argv0, "lld", false);
outs() << "\n";
// Scripts generated by Libtool versions up to at least 2.4.6 (the most
// recent version as of March 2017) expect /: supported targets:.* elf/
// in a message for the -help option. If it doesn't match, the scripts
// assume that the linker doesn't support very basic features such as
// shared libraries. Therefore, we need to print out at least "elf".
// Here, we print out all the targets that we support.
outs() << Argv0 << ": supported targets: "
<< "elf32-i386 elf32-iamcu elf32-littlearm elf32-ntradbigmips "
<< "elf32-ntradlittlemips elf32-powerpc elf32-tradbigmips "
<< "elf32-tradlittlemips elf32-x86-64 "
<< "elf64-amdgpu elf64-littleaarch64 elf64-powerpc elf64-tradbigmips "
<< "elf64-tradlittlemips elf64-x86-64\n";
}
// Reconstructs command line arguments so that so that you can re-run
// the same command with the same inputs. This is for --reproduce.
std::string elf::createResponseFile(const opt::InputArgList &Args) {
SmallString<0> Data;
raw_svector_ostream OS(Data);
// Copy the command line to the output while rewriting paths.
for (auto *Arg : Args) {
switch (Arg->getOption().getID()) {
case OPT_reproduce:
break;
case OPT_INPUT:
OS << quote(rewritePath(Arg->getValue())) << "\n";
break;
case OPT_o:
// If -o path contains directories, "lld @response.txt" will likely
// fail because the archive we are creating doesn't contain empty
// directories for the output path (-o doesn't create directories).
// Strip directories to prevent the issue.
OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n";
break;
case OPT_L:
case OPT_dynamic_list:
case OPT_rpath:
case OPT_alias_script_T:
case OPT_script:
case OPT_version_script:
OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue()))
<< "\n";
break;
default:
OS << toString(Arg) << "\n";
}
}
return Data.str();
}
// Find a file by concatenating given paths. If a resulting path
// starts with "=", the character is replaced with a --sysroot value.
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
SmallString<128> S;
if (Path1.startswith("="))
path::append(S, Config->Sysroot, Path1.substr(1), Path2);
else
path::append(S, Path1, Path2);
if (fs::exists(S))
return S.str().str();
return None;
}
Optional<std::string> elf::findFromSearchPaths(StringRef Path) {
for (StringRef Dir : Config->SearchPaths)
if (Optional<std::string> S = findFile(Dir, Path))
return S;
return None;
}
// This is for -lfoo. We'll look for libfoo.so or libfoo.a from
// search paths.
Optional<std::string> elf::searchLibrary(StringRef Name) {
if (Name.startswith(":"))
return findFromSearchPaths(Name.substr(1));
for (StringRef Dir : Config->SearchPaths) {
if (!Config->Static)
if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".so"))
return S;
if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a"))
return S;
}
return None;
}
|
//===- DriverUtils.cpp ----------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains utility functions for the driver. Because there
// are so many small functions, we created this separate file to make
// Driver.cpp less cluttered.
//
//===----------------------------------------------------------------------===//
#include "Driver.h"
#include "Error.h"
#include "Memory.h"
#include "lld/Config/Version.h"
#include "lld/Core/Reproduce.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/Process.h"
using namespace llvm;
using namespace llvm::sys;
using namespace lld;
using namespace lld::elf;
// Create OptTable
// Create prefix string literals used in Options.td
#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
#include "Options.inc"
#undef PREFIX
// Create table mapping all options defined in Options.td
static const opt::OptTable::Info OptInfo[] = {
#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
{X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
#include "Options.inc"
#undef OPTION
};
ELFOptTable::ELFOptTable() : OptTable(OptInfo) {}
// Parse -color-diagnostics={auto,always,never} or -no-color-diagnostics.
static bool getColorDiagnostics(opt::InputArgList &Args) {
auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
OPT_no_color_diagnostics);
if (!Arg)
return ErrorOS->has_colors();
if (Arg->getOption().getID() == OPT_color_diagnostics)
return true;
if (Arg->getOption().getID() == OPT_no_color_diagnostics)
return false;
StringRef S = Arg->getValue();
if (S == "auto")
return ErrorOS->has_colors();
if (S == "always")
return true;
if (S != "never")
error("unknown option: -color-diagnostics=" + S);
return false;
}
static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
StringRef S = Arg->getValue();
if (S != "windows" && S != "posix")
error("invalid response file quoting: " + S);
if (S == "windows")
return cl::TokenizeWindowsCommandLine;
return cl::TokenizeGNUCommandLine;
}
if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
return cl::TokenizeWindowsCommandLine;
return cl::TokenizeGNUCommandLine;
}
// Parses a given list of options.
opt::InputArgList ELFOptTable::parse(ArrayRef<const char *> Argv) {
// Make InputArgList from string vectors.
unsigned MissingIndex;
unsigned MissingCount;
SmallVector<const char *, 256> Vec(Argv.data(), Argv.data() + Argv.size());
// We need to get the quoting style for response files before parsing all
// options so we parse here before and ignore all the options but
// --rsp-quoting.
opt::InputArgList Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
// Expand response files (arguments in the form of @<filename>)
// and then parse the argument again.
cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), Vec);
Args = this->ParseArgs(Vec, MissingIndex, MissingCount);
// Interpret -color-diagnostics early so that error messages
// for unknown flags are colored.
Config->ColorDiagnostics = getColorDiagnostics(Args);
if (MissingCount)
error(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
for (auto *Arg : Args.filtered(OPT_UNKNOWN))
error("unknown argument: " + Arg->getSpelling());
return Args;
}
void elf::printHelp(const char *Argv0) {
ELFOptTable Table;
Table.PrintHelp(outs(), Argv0, "lld", false);
outs() << "\n";
// Scripts generated by Libtool versions up to at least 2.4.6 (the most
// recent version as of March 2017) expect /: supported targets:.* elf/
// in a message for the -help option. If it doesn't match, the scripts
// assume that the linker doesn't support very basic features such as
// shared libraries. Therefore, we need to print out at least "elf".
// Here, we print out all the targets that we support.
outs() << Argv0 << ": supported targets: "
<< "elf32-i386 elf32-iamcu elf32-littlearm elf32-ntradbigmips "
<< "elf32-ntradlittlemips elf32-powerpc elf32-tradbigmips "
<< "elf32-tradlittlemips elf32-x86-64 "
<< "elf64-amdgpu elf64-littleaarch64 elf64-powerpc elf64-tradbigmips "
<< "elf64-tradlittlemips elf64-x86-64\n";
}
// Reconstructs command line arguments so that so that you can re-run
// the same command with the same inputs. This is for --reproduce.
std::string elf::createResponseFile(const opt::InputArgList &Args) {
SmallString<0> Data;
raw_svector_ostream OS(Data);
// Copy the command line to the output while rewriting paths.
for (auto *Arg : Args) {
switch (Arg->getOption().getUnaliasedOption().getID()) {
case OPT_reproduce:
break;
case OPT_INPUT:
OS << quote(rewritePath(Arg->getValue())) << "\n";
break;
case OPT_o:
// If -o path contains directories, "lld @response.txt" will likely
// fail because the archive we are creating doesn't contain empty
// directories for the output path (-o doesn't create directories).
// Strip directories to prevent the issue.
OS << "-o " << quote(sys::path::filename(Arg->getValue())) << "\n";
break;
case OPT_L:
case OPT_dynamic_list:
case OPT_rpath:
case OPT_script:
case OPT_version_script:
OS << Arg->getSpelling() << " " << quote(rewritePath(Arg->getValue()))
<< "\n";
break;
default:
OS << toString(Arg) << "\n";
}
}
return Data.str();
}
// Find a file by concatenating given paths. If a resulting path
// starts with "=", the character is replaced with a --sysroot value.
static Optional<std::string> findFile(StringRef Path1, const Twine &Path2) {
SmallString<128> S;
if (Path1.startswith("="))
path::append(S, Config->Sysroot, Path1.substr(1), Path2);
else
path::append(S, Path1, Path2);
if (fs::exists(S))
return S.str().str();
return None;
}
Optional<std::string> elf::findFromSearchPaths(StringRef Path) {
for (StringRef Dir : Config->SearchPaths)
if (Optional<std::string> S = findFile(Dir, Path))
return S;
return None;
}
// This is for -lfoo. We'll look for libfoo.so or libfoo.a from
// search paths.
Optional<std::string> elf::searchLibrary(StringRef Name) {
if (Name.startswith(":"))
return findFromSearchPaths(Name.substr(1));
for (StringRef Dir : Config->SearchPaths) {
if (!Config->Static)
if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".so"))
return S;
if (Optional<std::string> S = findFile(Dir, "lib" + Name + ".a"))
return S;
}
return None;
}
|
Fix one more occurrence of getOption().getID().
|
Fix one more occurrence of getOption().getID().
git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@308523 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/lld,llvm-mirror/lld
|
6bf6623cd41b2af1c5bae5f9cb8a733a3ab764f2
|
controlpanel/src/page/maintranslations.cpp
|
controlpanel/src/page/maintranslations.cpp
|
/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "maintranslations.h"
static const DcpCategoryInfo
AccountsAndApplicationsElements[] =
{
{
//% "Service accounts"
QT_TRID_NOOP ("qtn_sett_main_account"),
"Service accounts",
PageHandle::ServiceAccounts,
NULL
},
{
//% "Applications"
QT_TRID_NOOP ("qtn_sett_main_application"),
"Applications",
PageHandle::Applications,
NULL
},
{
// The last element must have the .titleId == 0
0, 0, PageHandle::NOPAGE, NULL
}
};
/*
* The applet categories that will be shown in the main window of the control
* panel.
*/
const DcpCategoryInfo
DcpMain::CategoryInfos[] =
{
{
//% "Look & Feel"
QT_TRID_NOOP ("qtn_sett_main_look"),
"Look & Feel",
PageHandle::LOOKANDFEEL,
NULL
},
{
//% "Connectivity"
QT_TRID_NOOP ("qtn_sett_main_connectivity"),
"Connectivity",
PageHandle::CONNECTIVITY,
NULL
},
{
//% "Language & Region"
QT_TRID_NOOP ("qtn_sett_main_region"),
"Language & Region",
PageHandle::REGIONALSETTING,
NULL
},
{
//% "Device system"
QT_TRID_NOOP ("qtn_sett_main_data"),
"Device system",
PageHandle::DEVICESYSTEM,
NULL
},
{
//% "Accounts & Applications"
QT_TRID_NOOP ("qtn_sett_main_combined"),
"Accounts & Applications",
PageHandle::ACCOUNTSANDAPPLICATIONS,
AccountsAndApplicationsElements
},
{
// The last element must have the .titleId == 0
0, 0, PageHandle::NOPAGE, NULL
}
};
//% "Settings"
const char* DcpMain::settingsTitleId = QT_TRID_NOOP("qtn_sett_main_title");
//% "Most recently used"
const char* DcpMain::mostRecentUsedTitleId = QT_TRID_NOOP("qtn_sett_main_most");
//% "Exit"
const char* DcpMain::quitMenuItemTextId = QT_TRID_NOOP("qtn_comm_exit");
/*!
* Will find a DcpCategoryInfo by the page type id. Uses recirsive search to
* find sub-categories.
*/
const DcpCategoryInfo *
dcp_find_category_info (
PageHandle::PageTypeId id,
const DcpCategoryInfo *info)
{
/*
* The default place to find infos.
*/
if (info == NULL) {
info = DcpMain::CategoryInfos;
}
for (int n = 0; ; ++n) {
/*
* The end of the array.
*/
if (info[n].titleId == 0) {
return 0;
}
/*
* If found it.
*/
if (info[n].subPageId == id)
return &info[n];
/*
* If we have a chance to search recursively.
*/
if (info[n].staticElements != NULL) {
const DcpCategoryInfo *retval;
retval = dcp_find_category_info (id, info[n].staticElements);
if (retval)
return retval;
}
}
return NULL;
}
|
/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et ai sw=4 ts=4 sts=4: tw=80 cino="(0,W2s,i2s,t0,l1,:0" */
#include "maintranslations.h"
static const DcpCategoryInfo
AccountsAndApplicationsElements[] =
{
{
//% "Service accounts"
QT_TRID_NOOP ("qtn_sett_main_account"),
"Service accounts",
PageHandle::ServiceAccounts,
NULL
},
{
//% "Applications"
QT_TRID_NOOP ("qtn_sett_main_application"),
"Applications",
PageHandle::Applications,
NULL
},
{
// The last element must have the .titleId == 0
0, 0, PageHandle::NOPAGE, NULL
}
};
/*
* The applet categories that will be shown in the main window of the control
* panel.
*/
const DcpCategoryInfo
DcpMain::CategoryInfos[] =
{
{
//% "Look & Feel"
QT_TRID_NOOP ("qtn_sett_main_look"),
"Look & Feel",
PageHandle::LOOKANDFEEL,
NULL
},
{
//% "Sounds"
QT_TRID_NOOP ("qtn_sett_main_sound"),
"Sound",
PageHandle::SOUND,
NULL
},
{
//% "Connectivity"
QT_TRID_NOOP ("qtn_sett_main_connectivity"),
"Connectivity",
PageHandle::CONNECTIVITY,
NULL
},
{
//% "Regional settings"
QT_TRID_NOOP ("qtn_sett_main_region"),
"Regional settings",
PageHandle::REGIONALSETTING,
NULL
},
{
//% "Device utilities"
QT_TRID_NOOP ("qtn_sett_main_device"),
"Device utilities",
PageHandle::DEVICEUTILITIES,
NULL
},
{
//% "Device system"
QT_TRID_NOOP ("qtn_sett_main_data"),
"Device system",
PageHandle::DEVICESYSTEM,
NULL
},
{
//% "Accounts & Applications"
QT_TRID_NOOP ("qtn_sett_main_combined"),
"Accounts & Applications",
PageHandle::ACCOUNTSANDAPPLICATIONS,
AccountsAndApplicationsElements
},
{
// The last element must have the .titleId == 0
0, 0, PageHandle::NOPAGE, NULL
}
};
//% "Settings"
const char* DcpMain::settingsTitleId = QT_TRID_NOOP("qtn_sett_main_title");
//% "Most recently used"
const char* DcpMain::mostRecentUsedTitleId = QT_TRID_NOOP("qtn_sett_main_most");
//% "Exit"
const char* DcpMain::quitMenuItemTextId = QT_TRID_NOOP("qtn_comm_exit");
/*!
* Will find a DcpCategoryInfo by the page type id. Uses recirsive search to
* find sub-categories.
*/
const DcpCategoryInfo *
dcp_find_category_info (
PageHandle::PageTypeId id,
const DcpCategoryInfo *info)
{
/*
* The default place to find infos.
*/
if (info == NULL) {
info = DcpMain::CategoryInfos;
}
for (int n = 0; ; ++n) {
/*
* The end of the array.
*/
if (info[n].titleId == 0) {
return 0;
}
/*
* If found it.
*/
if (info[n].subPageId == id)
return &info[n];
/*
* If we have a chance to search recursively.
*/
if (info[n].staticElements != NULL) {
const DcpCategoryInfo *retval;
retval = dcp_find_category_info (id, info[n].staticElements);
if (retval)
return retval;
}
}
return NULL;
}
|
Revert "updated category names"
|
Revert "updated category names"
This reverts commit 803314ef6a8a02ab66c2bfee0e97fb748bb61adc.
|
C++
|
lgpl-2.1
|
arcean/controlpanel,harmattan/meegotouch-controlpanel,arcean/controlpanel,arcean/controlpanel,harmattan/meegotouch-controlpanel,arcean/controlpanel,harmattan/meegotouch-controlpanel,arcean/controlpanel,harmattan/meegotouch-controlpanel
|
0edae560a64c404b97170d66aaf8c68a411edc90
|
libksync/src/utilities.cxx
|
libksync/src/utilities.cxx
|
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sstream>
#include <random>
#include <limits>
#include "ksync/utilities.h"
#include "ksync/logging.h"
namespace KSync {
namespace Utilities {
void set_up_common_arguments_and_defaults(ArgParse::ArgParser& Parser, std::string& connect_socket_url, bool& connect_socket_url_defined, bool& nanomsg) {
connect_socket_url = "";
connect_socket_url_defined = false;
nanomsg = false;
Parser.AddArgument("--nanomsg", "Use nanomsg comm backend. Deafult is zeromq", &nanomsg);
Parser.AddArgument("connect-socket", "Socket to use to negotiate new client connections. Default is : ipc:///tmp/ksync/<user>/ksync-connect.ipc", &connect_socket_url, ArgParse::Argument::Optional, &connect_socket_url_defined);
}
int get_socket_dir(std::string& dir) {
char* login_name = getlogin();
if(login_name == 0) {
Error("Couldn't get the username!\n");
return -1;
}
std::stringstream ss;
ss << "/tmp/" << login_name;
if(access(ss.str().c_str(), F_OK) != 0) {
if(errno != 2) {
Error("An error was encountered while checking for the existence of the user temporary directory!\n");
return -2;
}
//Directory doesn't exist, we better create it
if(mkdir(ss.str().c_str(), 0700) != 0) {
Error("An error was encountered while creating the user temporary directory!\n");
return -3;
}
}
ss.clear();
ss << "/tmp/" << login_name << "/ksync";
if(access(ss.str().c_str(), F_OK) != 0) {
if(errno != 2) {
Error("An error was encountered while checking for the existence of the ksync directory!\n");
return -2;
}
//Directory doesn't exist, we better create it
if(mkdir(ss.str().c_str(), 0700) != 0) {
Error("An error was encountered while creating the ksync directory!\n");
return -3;
}
}
dir = ss.str();
return 0;
}
int get_default_ipc_connection_url(std::string& connection_url) {
std::string socket_dir;
if(KSync::Utilities::get_socket_dir(socket_dir) < 0) {
Error("There was a problem getting the default socket directory!\n");
return -2;
}
std::stringstream ss;
ss << "ipc://" << socket_dir << "/ksync-connect.ipc";
connection_url = ss.str();
return 0;
}
int get_default_tcp_connection_url(std::string& connection_url) {
connection_url = "tcp://*:6060";
return 0;
}
int get_default_connection_url(std::string& connection_url) {
return get_default_ipc_connection_url(connection_url);
}
client_id_t GenerateNewClientId() {
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<client_id_t> dis(std::numeric_limits<client_id_t>::min(), std::numeric_limits<client_id_t>::max());
return dis(gen);
}
}
}
|
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sstream>
#include <random>
#include <limits>
#include "ksync/utilities.h"
#include "ksync/logging.h"
namespace KSync {
namespace Utilities {
void set_up_common_arguments_and_defaults(ArgParse::ArgParser& Parser, std::string& connect_socket_url, bool& connect_socket_url_defined, bool& nanomsg) {
connect_socket_url = "";
connect_socket_url_defined = false;
nanomsg = false;
Parser.AddArgument("--nanomsg", "Use nanomsg comm backend. Deafult is zeromq", &nanomsg);
Parser.AddArgument("connect-socket", "Socket to use to negotiate new client connections. Default is : ipc:///tmp/ksync/<user>/ksync-connect.ipc", &connect_socket_url, ArgParse::Argument::Optional, &connect_socket_url_defined);
}
int get_socket_dir(std::string& dir) {
char* login_name = getlogin();
if(login_name == 0) {
Error("Couldn't get the username!\n");
return -1;
}
std::stringstream ss;
ss << "/tmp/" << login_name;
if(access(ss.str().c_str(), F_OK) != 0) {
if(errno != 2) {
Error("An error was encountered while checking for the existence of the user temporary directory!\n");
return -2;
}
//Directory doesn't exist, we better create it
if(mkdir(ss.str().c_str(), 0700) != 0) {
Error("An error was encountered while creating the user temporary directory!\n");
return -3;
}
}
ss.str(std::string());
ss << "/tmp/" << login_name << "/ksync";
if(access(ss.str().c_str(), F_OK) != 0) {
if(errno != 2) {
Error("An error was encountered while checking for the existence of the ksync directory!\n");
return -2;
}
//Directory doesn't exist, we better create it
if(mkdir(ss.str().c_str(), 0700) != 0) {
Error("An error was encountered while creating the ksync directory (%s)!\n", ss.str().c_str());
return -3;
}
}
dir = ss.str();
return 0;
}
int get_default_ipc_connection_url(std::string& connection_url) {
std::string socket_dir;
if(KSync::Utilities::get_socket_dir(socket_dir) < 0) {
Error("There was a problem getting the default socket directory!\n");
return -2;
}
std::stringstream ss;
ss << "ipc://" << socket_dir << "/ksync-connect.ipc";
connection_url = ss.str();
return 0;
}
int get_default_tcp_connection_url(std::string& connection_url) {
connection_url = "tcp://*:6060";
return 0;
}
int get_default_connection_url(std::string& connection_url) {
return get_default_ipc_connection_url(connection_url);
}
client_id_t GenerateNewClientId() {
std::random_device rd;
std::mt19937_64 gen(rd());
std::uniform_int_distribution<client_id_t> dis(std::numeric_limits<client_id_t>::min(), std::numeric_limits<client_id_t>::max());
return dis(gen);
}
}
}
|
Correct socket directory problem
|
Correct socket directory problem
|
C++
|
mit
|
krafczyk/KSync,krafczyk/KSync
|
11e52b86ac56653fbcc12841441dfbf6fce54eab
|
code/cpp/echomesh/color/FColor.cpp
|
code/cpp/echomesh/color/FColor.cpp
|
#include "echomesh/color/Fcolor.h"
namespace echomesh {
namespace color {
namespace {
const FColor make_black() {
FColor black;
black.clear();
return black;
}
}
const FColor FColor::BLACK = make_black();
} // namespace color
} // namespace echomesh
|
#include "echomesh/color/FColor.h"
namespace echomesh {
namespace color {
namespace {
const FColor make_black() {
FColor black;
black.clear();
return black;
}
}
const FColor FColor::BLACK = make_black();
} // namespace color
} // namespace echomesh
|
Fix tiny case error in FColor.cpp
|
Fix tiny case error in FColor.cpp
|
C++
|
mit
|
rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh,rec/echomesh
|
c7901a67337885f6291d7cc5c401d8c73552eb21
|
be/src/util/blocking-queue-test.cc
|
be/src/util/blocking-queue-test.cc
|
// Copyright 2013 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <unistd.h>
#include "util/blocking-queue.h"
using namespace boost;
using namespace std;
namespace impala {
TEST(BlockingQueueTest, TestBasic) {
int32_t i;
BlockingQueue<int32_t> test_queue(5);
ASSERT_TRUE(test_queue.BlockingPut(1));
ASSERT_TRUE(test_queue.BlockingPut(2));
ASSERT_TRUE(test_queue.BlockingPut(3));
ASSERT_TRUE(test_queue.BlockingGet(&i));
ASSERT_EQ(1, i);
ASSERT_TRUE(test_queue.BlockingGet(&i));
ASSERT_EQ(2, i);
ASSERT_TRUE(test_queue.BlockingGet(&i));
ASSERT_EQ(3, i);
}
TEST(BlockingQueueTest, TestGetFromShutdownQueue) {
int64_t i;
BlockingQueue<int64_t> test_queue(2);
ASSERT_TRUE(test_queue.BlockingPut(123));
test_queue.Shutdown();
ASSERT_FALSE(test_queue.BlockingPut(456));
ASSERT_TRUE(test_queue.BlockingGet(&i));
ASSERT_EQ(123, i);
ASSERT_FALSE(test_queue.BlockingGet(&i));
}
class MultiThreadTest {
public:
MultiThreadTest()
: iterations_(10000),
nthreads_(5),
queue_(iterations_*nthreads_/10),
num_inserters_(nthreads_) {
}
void InserterThread(int arg) {
for (int i = 0; i < iterations_; ++i) {
queue_.BlockingPut(arg);
}
{
lock_guard<mutex> guard(lock_);
if (--num_inserters_ == 0) {
queue_.Shutdown();
}
}
}
void RemoverThread() {
for (int i = 0; i < iterations_; ++i) {
int32_t arg;
bool got = queue_.BlockingGet(&arg);
if (!got) arg = -1;
{
lock_guard<mutex> guard(lock_);
gotten_[arg] = gotten_[arg] + 1;
}
}
}
void Run() {
for (int i = 0; i < nthreads_; ++i) {
threads_.push_back(shared_ptr<thread>(
new thread(bind(&MultiThreadTest::InserterThread, this, i))));
threads_.push_back(shared_ptr<thread>(
new thread(bind(&MultiThreadTest::RemoverThread, this))));
}
// We add an extra thread to ensure that there aren't enough elements in
// the queue to go around. This way, we test removal after Shutdown.
threads_.push_back(shared_ptr<thread>(
new thread(bind(
&MultiThreadTest::RemoverThread, this))));
for (int i = 0; i < threads_.size(); ++i) {
threads_[i]->join();
}
// Let's check to make sure we got what we should have.
lock_guard<mutex> guard(lock_);
for (int i = 0; i < nthreads_; ++i) {
ASSERT_EQ(iterations_, gotten_[i]);
}
// And there were nthreads_ * (iterations_ + 1) elements removed, but only
// nthreads_ * iterations_ elements added. So some removers hit the shutdown
// case.
ASSERT_EQ(iterations_, gotten_[-1]);
}
private:
typedef vector<shared_ptr<thread> > ThreadVector;
int iterations_;
int nthreads_;
BlockingQueue<int32_t> queue_;
// Lock for gotten_ and num_inserters_.
mutex lock_;
// Map from inserter thread id to number of consumed elements from that id.
// Ultimately, this should map each thread id to insertions_ elements.
// Additionally, if the BlockingGet returns false, this increments id=-1.
map<int32_t, int> gotten_;
// All inserter and remover threads.
ThreadVector threads_;
// Number of inserters which haven't yet finished inserting.
int num_inserters_;
};
TEST(BlockingQueueTest, TestMultipleThreads) {
MultiThreadTest test;
test.Run();
}
}
|
// Copyright 2013 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <unistd.h>
#include "util/blocking-queue.h"
using namespace boost;
using namespace std;
namespace impala {
TEST(BlockingQueueTest, TestBasic) {
int32_t i;
BlockingQueue<int32_t> test_queue(5);
ASSERT_TRUE(test_queue.BlockingPut(1));
ASSERT_TRUE(test_queue.BlockingPut(2));
ASSERT_TRUE(test_queue.BlockingPut(3));
ASSERT_TRUE(test_queue.BlockingGet(&i));
ASSERT_EQ(1, i);
ASSERT_TRUE(test_queue.BlockingGet(&i));
ASSERT_EQ(2, i);
ASSERT_TRUE(test_queue.BlockingGet(&i));
ASSERT_EQ(3, i);
}
TEST(BlockingQueueTest, TestGetFromShutdownQueue) {
int64_t i;
BlockingQueue<int64_t> test_queue(2);
ASSERT_TRUE(test_queue.BlockingPut(123));
test_queue.Shutdown();
ASSERT_FALSE(test_queue.BlockingPut(456));
ASSERT_TRUE(test_queue.BlockingGet(&i));
ASSERT_EQ(123, i);
ASSERT_FALSE(test_queue.BlockingGet(&i));
}
class MultiThreadTest {
public:
MultiThreadTest()
: iterations_(10000),
nthreads_(5),
queue_(iterations_*nthreads_/10),
num_inserters_(nthreads_) {
}
void InserterThread(int arg) {
for (int i = 0; i < iterations_; ++i) {
queue_.BlockingPut(arg);
}
{
lock_guard<mutex> guard(lock_);
if (--num_inserters_ == 0) {
queue_.Shutdown();
}
}
}
void RemoverThread() {
for (int i = 0; i < iterations_; ++i) {
int32_t arg;
bool got = queue_.BlockingGet(&arg);
if (!got) arg = -1;
{
lock_guard<mutex> guard(lock_);
gotten_[arg] = gotten_[arg] + 1;
}
}
}
void Run() {
for (int i = 0; i < nthreads_; ++i) {
threads_.push_back(shared_ptr<thread>(
new thread(bind(&MultiThreadTest::InserterThread, this, i))));
threads_.push_back(shared_ptr<thread>(
new thread(bind(&MultiThreadTest::RemoverThread, this))));
}
// We add an extra thread to ensure that there aren't enough elements in
// the queue to go around. This way, we test removal after Shutdown.
threads_.push_back(shared_ptr<thread>(
new thread(bind(
&MultiThreadTest::RemoverThread, this))));
for (int i = 0; i < threads_.size(); ++i) {
threads_[i]->join();
}
// Let's check to make sure we got what we should have.
lock_guard<mutex> guard(lock_);
for (int i = 0; i < nthreads_; ++i) {
ASSERT_EQ(iterations_, gotten_[i]);
}
// And there were nthreads_ * (iterations_ + 1) elements removed, but only
// nthreads_ * iterations_ elements added. So some removers hit the shutdown
// case.
ASSERT_EQ(iterations_, gotten_[-1]);
}
private:
typedef vector<shared_ptr<thread> > ThreadVector;
int iterations_;
int nthreads_;
BlockingQueue<int32_t> queue_;
// Lock for gotten_ and num_inserters_.
mutex lock_;
// Map from inserter thread id to number of consumed elements from that id.
// Ultimately, this should map each thread id to insertions_ elements.
// Additionally, if the BlockingGet returns false, this increments id=-1.
map<int32_t, int> gotten_;
// All inserter and remover threads.
ThreadVector threads_;
// Number of inserters which haven't yet finished inserting.
int num_inserters_;
};
TEST(BlockingQueueTest, TestMultipleThreads) {
MultiThreadTest test;
test.Run();
}
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Fix block queue test.
|
Fix block queue test.
Change-Id: I0bf1cb09f9c21f18e9d417c902e7b3ed607c5694
Reviewed-on: http://gerrit.ent.cloudera.com:8080/779
Reviewed-by: Skye Wanderman-Milne <[email protected]>
Tested-by: jenkins
|
C++
|
apache-2.0
|
XiaominZhang/Impala,cchanning/Impala,XiaominZhang/Impala,grundprinzip/Impala,kapilrastogi/Impala,brightchen/Impala,rampage644/impala-cut,ImpalaToGo/ImpalaToGo,tempbottle/Impala,gerashegalov/Impala,scalingdata/Impala,gistic/PublicSpatialImpala,ibmsoe/ImpalaPPC,bowlofstew/Impala,cloudera/recordservice,gistic/PublicSpatialImpala,grundprinzip/Impala,rampage644/impala-cut,placrosse/ImpalaToGo,brightchen/Impala,scalingdata/Impala,lnliuxing/Impala,lirui-intel/Impala,bratatidas9/Impala-1,cloudera/recordservice,theyaa/Impala,AtScaleInc/Impala,henryr/Impala,placrosse/ImpalaToGo,ImpalaToGo/ImpalaToGo,ibmsoe/ImpalaPPC,bowlofstew/Impala,gerashegalov/Impala,ibmsoe/ImpalaPPC,lirui-intel/Impala,tempbottle/Impala,theyaa/Impala,cgvarela/Impala,ImpalaToGo/ImpalaToGo,gerashegalov/Impala,rdblue/Impala,rdblue/Impala,theyaa/Impala,cgvarela/Impala,henryr/Impala,gerashegalov/Impala,bowlofstew/Impala,scalingdata/Impala,theyaa/Impala,caseyching/Impala,rampage644/impala-cut,placrosse/ImpalaToGo,tempbottle/Impala,XiaominZhang/Impala,lirui-intel/Impala,cchanning/Impala,grundprinzip/Impala,caseyching/Impala,kapilrastogi/Impala,caseyching/Impala,lnliuxing/Impala,bowlofstew/Impala,AtScaleInc/Impala,tempbottle/Impala,cchanning/Impala,andybab/Impala,tempbottle/Impala,cchanning/Impala,placrosse/ImpalaToGo,ibmsoe/ImpalaPPC,gistic/PublicSpatialImpala,gerashegalov/Impala,mapr/impala,AtScaleInc/Impala,tempbottle/Impala,henryr/Impala,kapilrastogi/Impala,andybab/Impala,grundprinzip/Impala,henryr/Impala,rdblue/Impala,ibmsoe/ImpalaPPC,mapr/impala,ImpalaToGo/ImpalaToGo,AtScaleInc/Impala,rdblue/Impala,cgvarela/Impala,lirui-intel/Impala,rdblue/Impala,cloudera/recordservice,lirui-intel/Impala,cloudera/recordservice,caseyching/Impala,andybab/Impala,rampage644/impala-cut,lnliuxing/Impala,bowlofstew/Impala,gerashegalov/Impala,mapr/impala,theyaa/Impala,cchanning/Impala,grundprinzip/Impala,brightchen/Impala,kapilrastogi/Impala,lirui-intel/Impala,scalingdata/Impala,cgvarela/Impala,andybab/Impala,brightchen/Impala,ImpalaToGo/ImpalaToGo,lnliuxing/Impala,cloudera/recordservice,cloudera/recordservice,mapr/impala,grundprinzip/Impala,scalingdata/Impala,cgvarela/Impala,cchanning/Impala,brightchen/Impala,kapilrastogi/Impala,gistic/PublicSpatialImpala,AtScaleInc/Impala,cchanning/Impala,cgvarela/Impala,bratatidas9/Impala-1,placrosse/ImpalaToGo,gerashegalov/Impala,lnliuxing/Impala,rdblue/Impala,caseyching/Impala,bratatidas9/Impala-1,bratatidas9/Impala-1,lnliuxing/Impala,andybab/Impala,bratatidas9/Impala-1,kapilrastogi/Impala,rdblue/Impala,theyaa/Impala,lnliuxing/Impala,bowlofstew/Impala,gistic/PublicSpatialImpala,rampage644/impala-cut,gistic/PublicSpatialImpala,XiaominZhang/Impala,brightchen/Impala,cgvarela/Impala,bowlofstew/Impala,lirui-intel/Impala,XiaominZhang/Impala,caseyching/Impala,theyaa/Impala,andybab/Impala,caseyching/Impala,placrosse/ImpalaToGo,henryr/Impala,henryr/Impala,ibmsoe/ImpalaPPC,AtScaleInc/Impala,kapilrastogi/Impala,bratatidas9/Impala-1,scalingdata/Impala,cloudera/recordservice,XiaominZhang/Impala,tempbottle/Impala,ibmsoe/ImpalaPPC,brightchen/Impala,bratatidas9/Impala-1,XiaominZhang/Impala,rampage644/impala-cut,ImpalaToGo/ImpalaToGo,mapr/impala
|
5bac273cfefd4e18df0490bfe93c2b81ba6b56b1
|
alloutil/alloutil/al_Simulator.hpp
|
alloutil/alloutil/al_Simulator.hpp
|
#ifndef AL_SIMULATOR_H
#define AL_SIMULATOR_H
#include "allocore/al_Allocore.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_InterfaceServerClient.hpp"
using namespace std;
using namespace al;
class Simulator : public InterfaceServerClient, public Main::Handler {
public:
Simulator(const char* deviceServerAddress="127.0.0.1", int port=12001,
int deviceServerPort=12000);
virtual ~Simulator();
virtual void start();
virtual void stop();
virtual void init() = 0;
virtual void step(double dt) = 0;
virtual void exit() = 0;
virtual void onTick();
virtual void onExit();
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
const Lens& lens() const { return mLens; }
Lens& lens() { return mLens; }
// virtual void onMessage(osc::Message& m);
static bool sim(){
std::string hostname = Socket::hostName();
return (hostname == "gr01" || hostname == "audio.10g");
}
static const char* defaultBroadcastIP(){
if(sim()) return "192.168.10.255";
else return "127.0.0.1";
}
static const char* defaultInterfaceServerIP(){
if(sim()) return "192.168.0.234"; //"192.168.0.74"; //interface mac mini
else return "127.0.0.1";
}
protected:
bool started;
double time, lastTime;
Nav mNav;
Lens mLens;
// NavInputControl mNavControl;
// StandardWindowKeyControls mStdControls;
// double mNavSpeed, mNavTurnSpeed;
};
inline void Simulator::onTick() {
if (!started) {
started = true;
time = Main::get().realtime();
init();
}
while (oscRecv().recv()) {
}
lastTime = time;
time = Main::get().realtime();
nav().step(time - lastTime);
step(time - lastTime);
}
inline void Simulator::onExit() { exit(); }
// inline void Simulator::onMessage(osc::Message& m) {
// // This allows the graphics renderer (or whatever) to overwrite navigation
// // data, so you can navigate from the graphics window when using a laptop.
// //
// // cout << "Simulator receive: " << m.addressPattern() << endl;
// // if (m.addressPattern() == "/pose") {
// // Pose pose;
// // m >> pose.pos().x;
// // m >> pose.pos().y;
// // m >> pose.pos().z;
// // m >> pose.quat().x;
// // m >> pose.quat().y;
// // m >> pose.quat().z;
// // m >> pose.quat().w;
// // //pose.print();
// // nav().set(pose);
// // }
// InterfaceServerClient::onMessage(m);
// // nav().print();
// }
inline void Simulator::start() {
InterfaceServerClient::connect();
Main::get().interval(1 / 60.0).add(*this).start();
}
inline void Simulator::stop() { cout << "Simulator stopped." <<endl; Main::get().stop(); }
inline Simulator::~Simulator() {
InterfaceServerClient::disconnect();
// oscSend().send("/interface/disconnectApplication", name());
}
#endif
|
#ifndef AL_SIMULATOR_H
#define AL_SIMULATOR_H
#include "allocore/al_Allocore.hpp"
#include "allocore/protocol/al_OSC.hpp"
#include "alloutil/al_InterfaceServerClient.hpp"
using namespace std;
namespace al {
class Simulator : public InterfaceServerClient, public Main::Handler {
public:
Simulator(const char* deviceServerAddress="127.0.0.1", int port=12001,
int deviceServerPort=12000);
virtual ~Simulator();
virtual void start();
virtual void stop();
virtual void init() = 0;
virtual void step(double dt) = 0;
virtual void exit() = 0;
virtual void onTick();
virtual void onExit();
const Nav& nav() const { return mNav; }
Nav& nav() { return mNav; }
const Lens& lens() const { return mLens; }
Lens& lens() { return mLens; }
// virtual void onMessage(osc::Message& m);
static bool sim(){
std::string hostname = Socket::hostName();
return (hostname == "gr01" || hostname == "audio.10g");
}
static const char* defaultBroadcastIP(){
if(sim()) return "192.168.10.255";
else return "127.0.0.1";
}
static const char* defaultInterfaceServerIP(){
if(sim()) return "192.168.0.234"; //"192.168.0.74"; //interface mac mini
else return "127.0.0.1";
}
protected:
bool started;
double time, lastTime;
Nav mNav;
Lens mLens;
// NavInputControl mNavControl;
// StandardWindowKeyControls mStdControls;
// double mNavSpeed, mNavTurnSpeed;
};
inline void Simulator::onTick() {
if (!started) {
started = true;
time = Main::get().realtime();
init();
}
while (oscRecv().recv()) {
}
lastTime = time;
time = Main::get().realtime();
nav().step(time - lastTime);
step(time - lastTime);
}
inline void Simulator::onExit() { exit(); }
// inline void Simulator::onMessage(osc::Message& m) {
// // This allows the graphics renderer (or whatever) to overwrite navigation
// // data, so you can navigate from the graphics window when using a laptop.
// //
// // cout << "Simulator receive: " << m.addressPattern() << endl;
// // if (m.addressPattern() == "/pose") {
// // Pose pose;
// // m >> pose.pos().x;
// // m >> pose.pos().y;
// // m >> pose.pos().z;
// // m >> pose.quat().x;
// // m >> pose.quat().y;
// // m >> pose.quat().z;
// // m >> pose.quat().w;
// // //pose.print();
// // nav().set(pose);
// // }
// InterfaceServerClient::onMessage(m);
// // nav().print();
// }
inline void Simulator::start() {
InterfaceServerClient::connect();
Main::get().interval(1 / 60.0).add(*this).start();
}
inline void Simulator::stop() { cout << "Simulator stopped." <<endl; Main::get().stop(); }
inline Simulator::~Simulator() {
InterfaceServerClient::disconnect();
// oscSend().send("/interface/disconnectApplication", name());
}
}
#endif
|
Put Simulator class inside al namespace to avoid clashes
|
Put Simulator class inside al namespace to avoid clashes
|
C++
|
bsd-3-clause
|
AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem,AlloSphere-Research-Group/AlloSystem
|
e6c05b1693ec567c29584644bb15e7736d4e0765
|
lib/spin_wait.cpp
|
lib/spin_wait.cpp
|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#include "spin_wait.hpp"
#include <cppcoro/config.hpp>
#include <thread>
#if CPPCORO_OS_WINNT
# define WIN32_LEAN_AND_MEAN
# include <Windows.h>
#endif
namespace
{
namespace local
{
constexpr std::uint32_t yield_threshold = 10;
}
}
namespace cppcoro
{
spin_wait::spin_wait() noexcept
{
reset();
}
bool spin_wait::next_spin_will_yield() const noexcept
{
return m_count >= local::yield_threshold;
}
void spin_wait::reset() noexcept
{
static const std::uint32_t initialCount =
std::thread::hardware_concurrency() > 1 ? 0 : local::yield_threshold;
m_count = initialCount;
}
void spin_wait::spin_one() noexcept
{
#if CPPCORO_OS_WINNT
// Spin strategy taken from .NET System.SpinWait class.
// I assume the Microsoft guys knew what they're doing.
if (next_spin_will_yield())
{
// CPU-level pause
// Allow other hyper-threads to run while we busy-wait.
// Make each busy-spin exponentially longer
const std::uint32_t loopCount = 2u << m_count;
for (std::uint32_t i = 0; i < loopCount; ++i)
{
::YieldProcessor();
::YieldProcessor();
}
}
else
{
// We've already spun a number of iterations.
//
const auto yieldCount = m_count - local::yield_threshold;
if (yieldCount % 20 == 19)
{
// Yield remainder of time slice to another thread and
// don't schedule this thread for a little while.
::SleepEx(1, FALSE);
}
else if (yieldCount % 5 == 4)
{
// Yield remainder of time slice to another thread
// that is ready to run (possibly from another processor?).
::SleepEx(0, FALSE);
}
else
{
// Yield to another thread that is ready to run on the
// current processor.
::SwitchToThread();
}
}
#else
if (next_spin_will_yield())
{
std::this_thread::yield();
}
#endif
++m_count;
if (m_count == 0)
{
// Don't wrap around to zero as this would go back to
// busy-waiting.
m_count = local::yield_threshold;
}
}
}
|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) Lewis Baker
// Licenced under MIT license. See LICENSE.txt for details.
///////////////////////////////////////////////////////////////////////////////
#include "spin_wait.hpp"
#include <cppcoro/config.hpp>
#include <thread>
#if CPPCORO_OS_WINNT
# define WIN32_LEAN_AND_MEAN
# include <Windows.h>
#endif
namespace
{
namespace local
{
constexpr std::uint32_t yield_threshold = 10;
}
}
namespace cppcoro
{
spin_wait::spin_wait() noexcept
{
reset();
}
bool spin_wait::next_spin_will_yield() const noexcept
{
return m_count >= local::yield_threshold;
}
void spin_wait::reset() noexcept
{
static const std::uint32_t initialCount =
std::thread::hardware_concurrency() > 1 ? 0 : local::yield_threshold;
m_count = initialCount;
}
void spin_wait::spin_one() noexcept
{
#if CPPCORO_OS_WINNT
// Spin strategy taken from .NET System.SpinWait class.
// I assume the Microsoft guys knew what they're doing.
if (next_spin_will_yield())
{
// CPU-level pause
// Allow other hyper-threads to run while we busy-wait.
// Make each busy-spin exponentially longer
const std::uint32_t loopCount = 2u << m_count;
for (std::uint32_t i = 0; i < loopCount; ++i)
{
::YieldProcessor();
::YieldProcessor();
}
}
else
{
// We've already spun a number of iterations.
//
const auto yieldCount = m_count - local::yield_threshold;
if (yieldCount % 20 == 19)
{
// Yield remainder of time slice to another thread and
// don't schedule this thread for a little while.
::SleepEx(1, FALSE);
}
else if (yieldCount % 5 == 4)
{
// Yield remainder of time slice to another thread
// that is ready to run (possibly from another processor?).
::SleepEx(0, FALSE);
}
else
{
// Yield to another thread that is ready to run on the
// current processor.
::SwitchToThread();
}
}
#else
if (next_spin_will_yield())
{
std::this_thread::yield();
}
#endif
++m_count;
if (m_count == 0)
{
// Don't wrap around to zero as this would go back to
// busy-waiting.
m_count = local::yield_threshold;
}
}
}
|
Add missing newline at end of file.
|
Add missing newline at end of file.
|
C++
|
mit
|
lewissbaker/cppcoro,lewissbaker/cppcoro,lewissbaker/cppcoro,lewissbaker/cppcoro
|
088140362eaa3bb5f068d4bd6afa2cefb7af9dd5
|
libtbag/time/TimePoint.cpp
|
libtbag/time/TimePoint.cpp
|
/**
* @file TimePoint.cpp
* @brief TimePoint class implementation.
* @author zer0
* @date 2017-04-12
*/
#include <libtbag/time/TimePoint.hpp>
#include <libtbag/time/Time.hpp>
#include <libtbag/log/Log.hpp>
#include <libtbag/3rd/date/date.h>
#include <ctime>
#include <array>
#include <sstream>
#include <iostream>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace time {
TimePoint::TimePoint() : _system_tp(Microsec(0)), _local_diff(0)
{
// EMPTY.
}
TimePoint::TimePoint(now_time const & UNUSED_PARAM(flag))
{
using namespace std::chrono;
_system_tp = SystemClock::now();
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
TimePoint::TimePoint(SystemTp const & time_point) : _system_tp(time_point)
{
using namespace std::chrono;
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
TimePoint::TimePoint(SystemTp const & time_point, Microsec const & local_diff)
: _system_tp(time_point), _local_diff(local_diff)
{
// EMPTY.
}
TimePoint::TimePoint(Rep microseconds) : _system_tp(Microsec(microseconds))
{
using namespace std::chrono;
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
TimePoint::TimePoint(Rep microseconds, Rep local_diff)
: _system_tp(Microsec(microseconds)), _local_diff(local_diff)
{
// EMPTY.
}
TimePoint::TimePoint(int y, int m, int d, int hour, int min, int sec, int milli, int micro)
{
setAll(y, m, d, hour, min, sec, milli, micro);
using namespace std::chrono;
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
TimePoint::TimePoint(TimePoint const & obj)
{
(*this) = obj;
}
TimePoint::TimePoint(TimePoint && obj)
{
(*this) = std::move(obj);
}
TimePoint::~TimePoint()
{
// EMPTY.
}
TimePoint & TimePoint::operator =(SystemTp const & time_point)
{
_system_tp = time_point;
return *this;
}
TimePoint & TimePoint::operator =(Microsec const & microseconds)
{
_system_tp = SystemTp(microseconds);
return *this;
}
TimePoint & TimePoint::operator =(Rep microseconds)
{
_system_tp = SystemTp(Microsec(microseconds));
return *this;
}
TimePoint & TimePoint::operator =(TimePoint const & obj)
{
if (this != &obj) {
_system_tp = obj._system_tp;
_local_diff = obj._local_diff;
}
return *this;
}
TimePoint & TimePoint::operator =(TimePoint && obj)
{
if (this != &obj) {
_system_tp = obj._system_tp;
_local_diff = obj._local_diff;
}
return *this;
}
void TimePoint::setTimePoint(SystemTp const & time_point)
{
_system_tp = time_point;
}
void TimePoint::setTimePoint(Microsec const & microseconds)
{
_system_tp = SystemTp(microseconds);
}
void TimePoint::setTimePoint(Rep microseconds)
{
_system_tp = SystemTp(Microsec(microseconds));
}
void TimePoint::setLocalDiff(Microsec const & microseconds)
{
_local_diff = microseconds;
}
void TimePoint::setLocalDiff(Rep microseconds)
{
_local_diff = Microsec(microseconds);
}
void TimePoint::setNow()
{
_system_tp = SystemClock::now();
}
void TimePoint::setLocalDiff()
{
using namespace std::chrono;
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
void TimePoint::setAll(int y, int m, int d, int hour, int min, int sec, int milli, int micro)
{
if (fromString(TIMESTAMP_LONG_FORMAT, getLongTimeString(y, m, d, hour, min, sec, milli, micro)) == false) {
_system_tp = date::sys_days(date::year(y) / m / d)
+ std::chrono::hours(hour) + std::chrono::minutes(min) + std::chrono::seconds(sec)
+ std::chrono::milliseconds(milli) + std::chrono::microseconds(micro);
}
}
TimePoint::Microsec TimePoint::getTimeSinceEpoch() const
{
using namespace std::chrono;
return duration_cast<Microsec>(getTimePoint().time_since_epoch());
}
TimePoint::Microsec TimePoint::getLocalTimeSinceEpoch() const
{
using namespace std::chrono;
return duration_cast<Microsec>(getLocalTimePoint().time_since_epoch());
}
TimePoint::Rep TimePoint::getRepTimeSinceEpoch() const
{
return getTimeSinceEpoch().count();
}
TimePoint::Rep TimePoint::getLocalRepTimeSinceEpoch() const
{
return getLocalTimeSinceEpoch().count();
}
// @formatter:off
int TimePoint::year () const { return libtbag::time::getYear (getTimePoint()); }
int TimePoint::month () const { return libtbag::time::getMonth (getTimePoint()); }
int TimePoint::day () const { return libtbag::time::getDay (getTimePoint()); }
int TimePoint::hours () const { return libtbag::time::getHours (getTimePoint()); }
int TimePoint::minutes () const { return libtbag::time::getMinutes (getTimePoint()); }
int TimePoint::seconds () const { return libtbag::time::getSeconds (getTimePoint()); }
int TimePoint::millisec() const { return libtbag::time::getMillisec(getTimePoint()); }
int TimePoint::microsec() const { return libtbag::time::getMicrosec(getTimePoint()); }
int TimePoint::lyear () const { return libtbag::time::getYear (getLocalTimePoint()); }
int TimePoint::lmonth () const { return libtbag::time::getMonth (getLocalTimePoint()); }
int TimePoint::lday () const { return libtbag::time::getDay (getLocalTimePoint()); }
int TimePoint::lhours () const { return libtbag::time::getHours (getLocalTimePoint()); }
int TimePoint::lminutes () const { return libtbag::time::getMinutes (getLocalTimePoint()); }
int TimePoint::lseconds () const { return libtbag::time::getSeconds (getLocalTimePoint()); }
int TimePoint::lmillisec() const { return libtbag::time::getMillisec(getLocalTimePoint()); }
int TimePoint::lmicrosec() const { return libtbag::time::getMicrosec(getLocalTimePoint()); }
// @formatter:on
int TimePoint::getDays() const
{
return libtbag::time::getDays(getTimePoint());
}
int TimePoint::getLocalDays() const
{
return libtbag::time::getDays(getLocalTimePoint());
}
std::string TimePoint::toString(std::string const & format) const
{
std::stringstream ss;
date::to_stream(ss, format.c_str(), getTimePoint());
return ss.str();
}
std::string TimePoint::toLongString() const
{
return toString(TIMESTAMP_LONG_FORMAT);
}
std::string TimePoint::toShortString() const
{
return toString(TIMESTAMP_SHORT_FORMAT);
}
std::string TimePoint::toLocalString(std::string const & format) const
{
std::stringstream ss;
date::to_stream(ss, format.c_str(), getLocalTimePoint());
return ss.str();
}
std::string TimePoint::toLocalLongString() const
{
return toLocalString(TIMESTAMP_LONG_FORMAT);
}
std::string TimePoint::toLocalShortString() const
{
return toLocalString(TIMESTAMP_SHORT_FORMAT);
}
bool TimePoint::fromString(std::string const & format, std::string const & time_string)
{
std::istringstream in(time_string);
std::chrono::system_clock::time_point tp;
date::from_stream(in, format.c_str(), tp);
if (in.bad() || in.eof()) {
return false;
}
_system_tp = tp;
return true;
}
std::string TimePoint::getLongTimeString(int y, int m, int d, int hour, int min, int sec, int milli, int micro)
{
std::array<char, 32> buffer;
double sec_all = (double)sec + ((double)milli / 1000.0) + ((double)micro / (1000.0 * 1000.0));
int const WRITE_SIZE = sprintf(buffer.data(), "%04d-%02d-%02dT%02d:%02d:%.6f", y, m, d, hour, min, sec_all);
return std::string(buffer.begin(), buffer.begin() + WRITE_SIZE);
}
} // namespace time
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
|
/**
* @file TimePoint.cpp
* @brief TimePoint class implementation.
* @author zer0
* @date 2017-04-12
*/
#include <libtbag/time/TimePoint.hpp>
#include <libtbag/time/Time.hpp>
#include <libtbag/log/Log.hpp>
#include <libtbag/3rd/date/date.h>
#include <ctime>
#include <array>
#include <sstream>
#include <iostream>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace time {
TimePoint::TimePoint() : _system_tp(Microsec(0)), _local_diff(0)
{
// EMPTY.
}
TimePoint::TimePoint(now_time const & UNUSED_PARAM(flag))
{
using namespace std::chrono;
_system_tp = SystemClock::now();
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
TimePoint::TimePoint(SystemTp const & time_point) : _system_tp(time_point)
{
using namespace std::chrono;
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
TimePoint::TimePoint(SystemTp const & time_point, Microsec const & local_diff)
: _system_tp(time_point), _local_diff(local_diff)
{
// EMPTY.
}
TimePoint::TimePoint(Rep microseconds) : _system_tp(Microsec(microseconds))
{
using namespace std::chrono;
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
TimePoint::TimePoint(Rep microseconds, Rep local_diff)
: _system_tp(Microsec(microseconds)), _local_diff(local_diff)
{
// EMPTY.
}
TimePoint::TimePoint(int y, int m, int d, int hour, int min, int sec, int milli, int micro)
{
setAll(y, m, d, hour, min, sec, milli, micro);
using namespace std::chrono;
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
TimePoint::TimePoint(TimePoint const & obj)
{
(*this) = obj;
}
TimePoint::TimePoint(TimePoint && obj)
{
(*this) = std::move(obj);
}
TimePoint::~TimePoint()
{
// EMPTY.
}
TimePoint & TimePoint::operator =(SystemTp const & time_point)
{
_system_tp = time_point;
return *this;
}
TimePoint & TimePoint::operator =(Microsec const & microseconds)
{
_system_tp = SystemTp(microseconds);
return *this;
}
TimePoint & TimePoint::operator =(Rep microseconds)
{
_system_tp = SystemTp(Microsec(microseconds));
return *this;
}
TimePoint & TimePoint::operator =(TimePoint const & obj)
{
if (this != &obj) {
_system_tp = obj._system_tp;
_local_diff = obj._local_diff;
}
return *this;
}
TimePoint & TimePoint::operator =(TimePoint && obj)
{
if (this != &obj) {
_system_tp = obj._system_tp;
_local_diff = obj._local_diff;
}
return *this;
}
void TimePoint::setTimePoint(SystemTp const & time_point)
{
_system_tp = time_point;
}
void TimePoint::setTimePoint(Microsec const & microseconds)
{
_system_tp = SystemTp(microseconds);
}
void TimePoint::setTimePoint(Rep microseconds)
{
_system_tp = SystemTp(Microsec(microseconds));
}
void TimePoint::setLocalDiff(Microsec const & microseconds)
{
_local_diff = microseconds;
}
void TimePoint::setLocalDiff(Rep microseconds)
{
_local_diff = Microsec(microseconds);
}
void TimePoint::setNow()
{
_system_tp = SystemClock::now();
}
void TimePoint::setLocalDiff()
{
using namespace std::chrono;
_local_diff = duration_cast<Microsec>(getCurrentLocalDuration());
}
void TimePoint::setAll(int y, int m, int d, int hour, int min, int sec, int milli, int micro)
{
if (fromString(TIMESTAMP_LONG_FORMAT, getLongTimeString(y, m, d, hour, min, sec, milli, micro)) == false) {
_system_tp = date::sys_days(date::year(y) / m / d)
+ std::chrono::hours(hour) + std::chrono::minutes(min) + std::chrono::seconds(sec)
+ std::chrono::milliseconds(milli) + std::chrono::microseconds(micro);
}
}
TimePoint::Microsec TimePoint::getTimeSinceEpoch() const
{
using namespace std::chrono;
return duration_cast<Microsec>(getTimePoint().time_since_epoch());
}
TimePoint::Microsec TimePoint::getLocalTimeSinceEpoch() const
{
using namespace std::chrono;
return duration_cast<Microsec>(getLocalTimePoint().time_since_epoch());
}
TimePoint::Rep TimePoint::getRepTimeSinceEpoch() const
{
return getTimeSinceEpoch().count();
}
TimePoint::Rep TimePoint::getLocalRepTimeSinceEpoch() const
{
return getLocalTimeSinceEpoch().count();
}
// @formatter:off
int TimePoint::year () const { return libtbag::time::getYear (getTimePoint()); }
int TimePoint::month () const { return libtbag::time::getMonth (getTimePoint()); }
int TimePoint::day () const { return libtbag::time::getDay (getTimePoint()); }
int TimePoint::hours () const { return libtbag::time::getHours (getTimePoint()); }
int TimePoint::minutes () const { return libtbag::time::getMinutes (getTimePoint()); }
int TimePoint::seconds () const { return libtbag::time::getSeconds (getTimePoint()); }
int TimePoint::millisec() const { return libtbag::time::getMillisec(getTimePoint()); }
int TimePoint::microsec() const { return libtbag::time::getMicrosec(getTimePoint()); }
int TimePoint::lyear () const { return libtbag::time::getYear (getLocalTimePoint()); }
int TimePoint::lmonth () const { return libtbag::time::getMonth (getLocalTimePoint()); }
int TimePoint::lday () const { return libtbag::time::getDay (getLocalTimePoint()); }
int TimePoint::lhours () const { return libtbag::time::getHours (getLocalTimePoint()); }
int TimePoint::lminutes () const { return libtbag::time::getMinutes (getLocalTimePoint()); }
int TimePoint::lseconds () const { return libtbag::time::getSeconds (getLocalTimePoint()); }
int TimePoint::lmillisec() const { return libtbag::time::getMillisec(getLocalTimePoint()); }
int TimePoint::lmicrosec() const { return libtbag::time::getMicrosec(getLocalTimePoint()); }
// @formatter:on
int TimePoint::getDays() const
{
return libtbag::time::getDays(getTimePoint());
}
int TimePoint::getLocalDays() const
{
return libtbag::time::getDays(getLocalTimePoint());
}
std::string TimePoint::toString(std::string const & format) const
{
std::stringstream ss;
date::to_stream(ss, format.c_str(), getTimePoint());
return ss.str();
}
std::string TimePoint::toLongString() const
{
return toString(TIMESTAMP_LONG_FORMAT);
}
std::string TimePoint::toShortString() const
{
return toString(TIMESTAMP_SHORT_FORMAT);
}
std::string TimePoint::toLocalString(std::string const & format) const
{
std::stringstream ss;
date::to_stream(ss, format.c_str(), getLocalTimePoint());
return ss.str();
}
std::string TimePoint::toLocalLongString() const
{
return toLocalString(TIMESTAMP_LONG_FORMAT);
}
std::string TimePoint::toLocalShortString() const
{
return toLocalString(TIMESTAMP_SHORT_FORMAT);
}
bool TimePoint::fromString(std::string const & format, std::string const & time_string)
{
std::istringstream in(time_string);
std::chrono::system_clock::time_point tp;
date::from_stream(in, format.c_str(), tp);
if (in.bad() || in.eof()) {
return false;
}
_system_tp = tp;
return true;
}
std::string TimePoint::getLongTimeString(int y, int m, int d, int hour, int min, int sec, int milli, int micro)
{
std::array<char, 32> buffer;
double sec_all = (double)sec + ((double)milli / 1000.0) + ((double)micro / (1000.0 * 1000.0));
int const WRITE_SIZE = sprintf(buffer.data(), "%04d-%02d-%02dT%02d:%02d:%f", y, m, d, hour, min, sec_all);
return std::string(buffer.begin(), buffer.begin() + WRITE_SIZE);
}
} // namespace time
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
|
Fix the bug in TimePoint::getLongTimeString() method.
|
Fix the bug in TimePoint::getLongTimeString() method.
|
C++
|
mit
|
osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag,osom8979/tbag
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.