text
stringlengths 54
60.6k
|
---|
<commit_before>#ifndef POPULATION_HPP
#define POPULATION_HPP
namespace galgo {
//=================================================================================================
template <typename T, int N = 16>
class Population
{
static_assert(std::is_same<float,T>::value || std::is_same<double,T>::value, "variable type can only be float or double, please amend.");
static_assert(N > 0 && N <= 64, "number of bits cannot be ouside interval [1,64], please amend N");
template <typename K, int S>
friend class GeneticAlgorithm;
public:
// nullary constructor
Population() {}
// constructor
Population(const GeneticAlgorithm<T,N>& ga);
// create a population of chromosomes
void creation();
// evolve population, get next generation
void evolution();
// access element in current population at position pos
const CHR<T,N>& operator()(int pos) const;
// access element in mating population at position pos
const CHR<T,N>& operator[](int pos) const;
// return iterator at current population beginning
typename std::vector<CHR<T,N>>::iterator begin();
// return const iterator at current population beginning
typename std::vector<CHR<T,N>>::const_iterator cbegin() const;
// return iterator at current population ending
typename std::vector<CHR<T,N>>::iterator end();
// return const iterator at current population ending
typename std::vector<CHR<T,N>>::const_iterator cend() const;
// select element at position pos in current population and copy it into mating population
void select(int pos);
// set all fitness to positive values
void adjustFitness();
// compute fitness sum of current population
T getSumFitness() const;
// get worst objective function total result from current population
T getWorstTotal() const;
// return population size
int popsize() const;
// return mating population size
int matsize() const;
// return tournament size
int tntsize() const;
// return numero of generation
int nogen() const;
// return number of generations
int nbgen() const;
// return selection pressure
T SP() const;
private:
std::vector<CHR<T,N>> curpop; // current population
std::vector<CHR<T,N>> matpop; // mating population
std::vector<CHR<T,N>> newpop; // new population
const GeneticAlgorithm<T,N>* ptr = nullptr; // pointer to genetic algorithm
int nbrcrov; // number of cross-over
int matidx; // mating population index
// elitism => saving best chromosomes in new population
void elitism();
// create new population from recombination of the old one
void recombination();
// complete new population randomly
void completion();
// update population (adapting, sorting)
void updating();
};
/*-------------------------------------------------------------------------------------------------*/
// constructor
template <typename T, int N>
Population<T,N>::Population(const GeneticAlgorithm<T,N>& ga)
{
ptr = &ga;
nbrcrov = floor(ga.covrate * (ga.popsize - ga.elitpop));
// adjusting nbrcrov (must be an even number)
if (nbrcrov % 2 != 0) nbrcrov -= 1;
// for convenience, we add elitpop to nbrcrov
nbrcrov += ga.elitpop;
// allocating memory
curpop.resize(ga.popsize);
matpop.resize(ga.matsize);
}
/*-------------------------------------------------------------------------------------------------*/
// create a population of chromosomes
template <typename T, int N>
void Population<T,N>::creation()
{
// initializing first chromosome
curpop[0] = std::make_shared<Chromosome<T,N>>(*ptr);
if (!ptr->initialSet.empty()) {
curpop[0]->initialize();
} else {
curpop[0]->create();
}
curpop[0]->evaluate();
// getting the rest
#ifdef _OPENMP
#pragma omp parallel for num_threads(MAX_THREADS)
#endif
for (int i = 1; i < ptr->popsize; ++i) {
curpop[i] = std::make_shared<Chromosome<T,N>>(*ptr);
curpop[i]->create();
curpop[i]->evaluate();
}
// updating population
this->updating();
}
/*-------------------------------------------------------------------------------------------------*/
// population evolution (selection, recombination, completion, mutation), get next generation
template <typename T, int N>
void Population<T,N>::evolution()
{
// initializing mating population index
matidx = 0;
// selecting mating population
ptr->Selection(*this);
// applying elitism if required
this->elitism();
// crossing-over mating population
this->recombination();
// completing new population
this->completion();
// moving new population into current population for next generation
curpop = std::move(newpop);
// updating population
this->updating();
}
/*-------------------------------------------------------------------------------------------------*/
// elitism => saving best chromosomes in new population, making a copy of each elit chromosome
template <typename T, int N>
void Population<T,N>::elitism()
{
// (re)allocating new population
newpop.resize(ptr->popsize);
if (ptr->elitpop > 0) {
// copying elit chromosomes into new population
std::transform(curpop.cbegin(), curpop.cend(), newpop.begin(), [](const CHR<T,N>& chr)->CHR<T,N>{return std::make_shared<Chromosome<T,N>>(*chr);});
}
}
/*-------------------------------------------------------------------------------------------------*/
// create new population from recombination of the old one
template <typename T, int N>
void Population<T,N>::recombination()
{
// creating a new population by cross-over
#ifdef _OPENMP
#pragma omp parallel for num_threads(MAX_THREADS)
#endif
for (int i = ptr->elitpop; i < nbrcrov; i = i + 2) {
// initializing 2 new chromosome
newpop[i] = std::make_shared<Chromosome<T,N>>(*ptr);
newpop[i+1] = std::make_shared<Chromosome<T,N>>(*ptr);
// crossing-over mating population to create 2 new chromosomes
ptr->CrossOver(*this, newpop[i], newpop[i+1]);
// mutating new chromosomes
ptr->Mutation(newpop[i]);
ptr->Mutation(newpop[i+1]);
// evaluating new chromosomes
newpop[i]->evaluate();
newpop[i+1]->evaluate();
}
}
/*-------------------------------------------------------------------------------------------------*/
// complete new population
template <typename T, int N>
void Population<T,N>::completion()
{
#ifdef _OPENMP
#pragma omp parallel for num_threads(MAX_THREADS)
#endif
for (int i = nbrcrov; i < ptr->popsize; ++i) {
// selecting chromosome randomly from mating population
newpop[i] = std::make_shared<Chromosome<T,N>>(*matpop[uniform<int>(0, ptr->matsize)]);
// mutating chromosome
ptr->Mutation(newpop[i]);
// evaluating chromosome
newpop[i]->evaluate();
}
}
/*-------------------------------------------------------------------------------------------------*/
// update population (adapting, sorting)
template <typename T, int N>
void Population<T,N>::updating()
{
// adapting population to constraints
if (ptr->Constraint != nullptr) {
ptr->Adaptation(*this);
}
// sorting chromosomes from best to worst fitness
std::sort(curpop.begin(),curpop.end(),[](const CHR<T,N>& chr1,const CHR<T,N>& chr2)->bool{return chr1->fitness > chr2->fitness;});
}
/*-------------------------------------------------------------------------------------------------*/
// access element in current population at position pos
template <typename T, int N>
const CHR<T,N>& Population<T,N>::operator()(int pos) const
{
#ifndef NDEBUG
if (pos > ptr->popsize - 1) {
throw std::invalid_argument("Error: in galgo::Population<T>::operator()(int), exceeding current population memory.");
}
#endif
return curpop[pos];
}
/*-------------------------------------------------------------------------------------------------*/
// access element in mating population at position pos
template <typename T, int N>
const CHR<T,N>& Population<T,N>::operator[](int pos) const
{
#ifndef NDEBUG
if (pos > ptr->matsize - 1) {
throw std::invalid_argument("Error: in galgo::Population<T>::operator[](int), exceeding mating population memory.");
}
#endif
return matpop[pos];
}
/*-------------------------------------------------------------------------------------------------*/
// return iterator at current population beginning
template <typename T, int N>
inline typename std::vector<CHR<T,N>>::iterator Population<T,N>::begin()
{
return curpop.begin();
}
/*-------------------------------------------------------------------------------------------------*/
// return const iterator at current population beginning
template <typename T, int N>
inline typename std::vector<CHR<T,N>>::const_iterator Population<T,N>::cbegin() const
{
return curpop.cbegin();
}
/*-------------------------------------------------------------------------------------------------*/
// return iterator at current population ending
template <typename T, int N>
inline typename std::vector<CHR<T,N>>::iterator Population<T,N>::end()
{
return curpop.end();
}
/*-------------------------------------------------------------------------------------------------*/
// return const iterator at current population ending
template <typename T, int N>
inline typename std::vector<CHR<T,N>>::const_iterator Population<T,N>::cend() const
{
return curpop.cend();
}
/*-------------------------------------------------------------------------------------------------*/
// select element at position pos in current population and copy it into mating population
template <typename T, int N>
inline void Population<T,N>::select(int pos)
{
#ifndef NDEBUG
if (pos > ptr->popsize - 1) {
throw std::invalid_argument("Error: in galgo::Population<T>::select(int), exceeding current population memory.");
}
if (matidx == ptr->matsize) {
throw std::invalid_argument("Error: in galgo::Population<T>::select(int), exceeding mating population memory.");
}
#endif
matpop[matidx] = curpop[pos];
matidx++;
}
/*-------------------------------------------------------------------------------------------------*/
// set all fitness to positive values (used in RWS and SUS selection methods)
template <typename T, int N>
void Population<T,N>::adjustFitness()
{
// getting worst population fitness
T worstFitness = curpop.back()->fitness;
if (worstFitness < 0) {
// getting best fitness
T bestFitness = curpop.front()->fitness;
// case where all fitness are equal and negative
if (worstFitness == bestFitness) {
std::for_each(curpop.begin(), curpop.end(), [](CHR<T,N>& chr)->void{chr->fitness *= -1;});
} else {
std::for_each(curpop.begin(), curpop.end(), [worstFitness](CHR<T,N>& chr)->void{chr->fitness -= worstFitness;});
}
}
}
/*-------------------------------------------------------------------------------------------------*/
// compute population fitness sum (used in TRS, RWS and SUS selection methods)
template <typename T, int N>
inline T Population<T,N>::getSumFitness() const
{
return std::accumulate(curpop.cbegin(), curpop.cend(), 0.0, [](T sum, const CHR<T,N>& chr)->T{return sum + T(chr->fitness);});
}
/*-------------------------------------------------------------------------------------------------*/
// get worst objective function total result from current population (used in constraint(s) adaptation)
template <typename T, int N>
inline T Population<T,N>::getWorstTotal() const
{
auto it = std::min_element(curpop.begin(), curpop.end(), [](const CHR<T,N>& chr1, const CHR<T,N>& chr2)->bool{return chr1->getTotal() < chr2->getTotal();});
return (*it)->getTotal();
}
/*-------------------------------------------------------------------------------------------------*/
// return population size
template <typename T, int N>
inline int Population<T,N>::popsize() const
{
return ptr->popsize;
}
/*-------------------------------------------------------------------------------------------------*/
// return mating population size
template <typename T, int N>
inline int Population<T,N>::matsize() const
{
return ptr->matsize;
}
/*-------------------------------------------------------------------------------------------------*/
// return tournament size
template <typename T, int N>
inline int Population<T,N>::tntsize() const
{
return ptr->tntsize;
}
/*-------------------------------------------------------------------------------------------------*/
// return numero of generation
template <typename T, int N>
inline int Population<T,N>::nogen() const
{
return ptr->nogen;
}
/*-------------------------------------------------------------------------------------------------*/
// return number of generations
template <typename T, int N>
inline int Population<T,N>::nbgen() const
{
return ptr->nbgen;
}
/*-------------------------------------------------------------------------------------------------*/
// return selection pressure
template <typename T, int N>
inline T Population<T,N>::SP() const
{
return ptr->SP;
}
//=================================================================================================
}
#endif
<commit_msg>Delete Population.hpp<commit_after><|endoftext|> |
<commit_before>#include "RestClient.h"
#ifdef HTTP_DEBUG
#define HTTP_DEBUG_PRINT(string) (Serial.print(string))
#endif
#ifndef HTTP_DEBUG
#define HTTP_DEBUG_PRINT(string)
#endif
RestClient::RestClient(const char* _host){
host = _host;
port = 80;
num_headers = 0;
contentType = "x-www-form-urlencoded"; // default
}
RestClient::RestClient(const char* _host, int _port){
host = _host;
port = _port;
num_headers = 0;
contentType = "x-www-form-urlencoded"; // default
}
void RestClient::dhcp(){
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
if (begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
}
//give it time to initialize
delay(1000);
}
int RestClient::begin(byte mac[]){
return Ethernet.begin(mac);
//give it time to initialize
delay(1000);
}
// GET path
int RestClient::get(const char* path){
return request("GET", path, NULL, NULL);
}
//GET path with response
int RestClient::get(const char* path, String* response){
return request("GET", path, NULL, response);
}
// POST path and body
int RestClient::post(const char* path, const char* body){
return request("POST", path, body, NULL);
}
// POST path and body with response
int RestClient::post(const char* path, const char* body, String* response){
return request("POST", path, body, response);
}
// PUT path and body
int RestClient::put(const char* path, const char* body){
return request("PUT", path, body, NULL);
}
// PUT path and body with response
int RestClient::put(const char* path, const char* body, String* response){
return request("PUT", path, body, response);
}
// DELETE path
int RestClient::del(const char* path){
return request("DELETE", path, NULL, NULL);
}
// DELETE path and response
int RestClient::del(const char* path, String* response){
return request("DELETE", path, NULL, response);
}
// DELETE path and body
int RestClient::del(const char* path, const char* body ){
return request("DELETE", path, body, NULL);
}
// DELETE path and body with response
int RestClient::del(const char* path, const char* body, String* response){
return request("DELETE", path, body, response);
}
void RestClient::write(const char* string){
HTTP_DEBUG_PRINT(string);
client.print(string);
}
void RestClient::setHeader(const char* header){
headers[num_headers] = header;
num_headers++;
}
void RestClient::setContentType(const char* contentTypeValue){
contentType = contentTypeValue;
}
// The mother- generic request method.
//
int RestClient::request(const char* method, const char* path,
const char* body, String* response){
HTTP_DEBUG_PRINT("HTTP: connect\n");
if(client.connect(host, port)){
HTTP_DEBUG_PRINT("HTTP: connected\n");
HTTP_DEBUG_PRINT("REQUEST: \n");
// Make a HTTP request line:
write(method);
write(" ");
write(path);
write(" HTTP/1.1\r\n");
for(int i=0; i<num_headers; i++){
write(headers[i]);
write("\r\n");
}
write("Host: ");
write(host);
write("\r\n");
write("Connection: close\r\n");
if(body != NULL){
char contentLength[30];
sprintf(contentLength, "Content-Length: %d\r\n", strlen(body));
write(contentLength);
write("Content-Type: ");
write(contentType);
write("\r\n");
}
write("\r\n");
if(body != NULL){
write(body);
write("\r\n");
write("\r\n");
}
//make sure you write all those bytes.
delay(100);
HTTP_DEBUG_PRINT("HTTP: call readResponse\n");
int statusCode = readResponse(response);
HTTP_DEBUG_PRINT("HTTP: return readResponse\n");
//cleanup
HTTP_DEBUG_PRINT("HTTP: stop client\n");
num_headers = 0;
client.stop();
delay(50);
HTTP_DEBUG_PRINT("HTTP: client stopped\n");
return statusCode;
}else{
HTTP_DEBUG_PRINT("HTTP Connection failed\n");
return 0;
}
}
int RestClient::readResponse(String* response) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
boolean httpBody = false;
boolean inStatus = false;
char statusCode[4];
int i = 0;
int code = 0;
if(response == NULL){
HTTP_DEBUG_PRINT("HTTP: NULL RESPONSE POINTER: \n");
}else{
HTTP_DEBUG_PRINT("HTTP: NON-NULL RESPONSE POINTER: \n");
}
HTTP_DEBUG_PRINT("HTTP: RESPONSE: \n");
while (client.connected()) {
HTTP_DEBUG_PRINT(".");
if (client.available()) {
HTTP_DEBUG_PRINT(",");
char c = client.read();
HTTP_DEBUG_PRINT(c);
if(c == ' ' && !inStatus){
inStatus = true;
}
if(inStatus && i < 3 && c != ' '){
statusCode[i] = c;
i++;
}
if(i == 3){
statusCode[i] = '\0';
code = atoi(statusCode);
}
if(httpBody){
//only write response if its not null
if(response != NULL) response->concat(c);
}
else
{
if (c == '\n' && currentLineIsBlank) {
httpBody = true;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
}
HTTP_DEBUG_PRINT("HTTP: return readResponse3\n");
return code;
}
<commit_msg>Fix Default contentType<commit_after>#include "RestClient.h"
#ifdef HTTP_DEBUG
#define HTTP_DEBUG_PRINT(string) (Serial.print(string))
#endif
#ifndef HTTP_DEBUG
#define HTTP_DEBUG_PRINT(string)
#endif
RestClient::RestClient(const char* _host){
host = _host;
port = 80;
num_headers = 0;
contentType = "application/x-www-form-urlencoded"; // default
}
RestClient::RestClient(const char* _host, int _port){
host = _host;
port = _port;
num_headers = 0;
contentType = "application/x-www-form-urlencoded"; // default
}
void RestClient::dhcp(){
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
if (begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
}
//give it time to initialize
delay(1000);
}
int RestClient::begin(byte mac[]){
return Ethernet.begin(mac);
//give it time to initialize
delay(1000);
}
// GET path
int RestClient::get(const char* path){
return request("GET", path, NULL, NULL);
}
//GET path with response
int RestClient::get(const char* path, String* response){
return request("GET", path, NULL, response);
}
// POST path and body
int RestClient::post(const char* path, const char* body){
return request("POST", path, body, NULL);
}
// POST path and body with response
int RestClient::post(const char* path, const char* body, String* response){
return request("POST", path, body, response);
}
// PUT path and body
int RestClient::put(const char* path, const char* body){
return request("PUT", path, body, NULL);
}
// PUT path and body with response
int RestClient::put(const char* path, const char* body, String* response){
return request("PUT", path, body, response);
}
// DELETE path
int RestClient::del(const char* path){
return request("DELETE", path, NULL, NULL);
}
// DELETE path and response
int RestClient::del(const char* path, String* response){
return request("DELETE", path, NULL, response);
}
// DELETE path and body
int RestClient::del(const char* path, const char* body ){
return request("DELETE", path, body, NULL);
}
// DELETE path and body with response
int RestClient::del(const char* path, const char* body, String* response){
return request("DELETE", path, body, response);
}
void RestClient::write(const char* string){
HTTP_DEBUG_PRINT(string);
client.print(string);
}
void RestClient::setHeader(const char* header){
headers[num_headers] = header;
num_headers++;
}
void RestClient::setContentType(const char* contentTypeValue){
contentType = contentTypeValue;
}
// The mother- generic request method.
//
int RestClient::request(const char* method, const char* path,
const char* body, String* response){
HTTP_DEBUG_PRINT("HTTP: connect\n");
if(client.connect(host, port)){
HTTP_DEBUG_PRINT("HTTP: connected\n");
HTTP_DEBUG_PRINT("REQUEST: \n");
// Make a HTTP request line:
write(method);
write(" ");
write(path);
write(" HTTP/1.1\r\n");
for(int i=0; i<num_headers; i++){
write(headers[i]);
write("\r\n");
}
write("Host: ");
write(host);
write("\r\n");
write("Connection: close\r\n");
if(body != NULL){
char contentLength[30];
sprintf(contentLength, "Content-Length: %d\r\n", strlen(body));
write(contentLength);
write("Content-Type: ");
write(contentType);
write("\r\n");
}
write("\r\n");
if(body != NULL){
write(body);
write("\r\n");
write("\r\n");
}
//make sure you write all those bytes.
delay(100);
HTTP_DEBUG_PRINT("HTTP: call readResponse\n");
int statusCode = readResponse(response);
HTTP_DEBUG_PRINT("HTTP: return readResponse\n");
//cleanup
HTTP_DEBUG_PRINT("HTTP: stop client\n");
num_headers = 0;
client.stop();
delay(50);
HTTP_DEBUG_PRINT("HTTP: client stopped\n");
return statusCode;
}else{
HTTP_DEBUG_PRINT("HTTP Connection failed\n");
return 0;
}
}
int RestClient::readResponse(String* response) {
// an http request ends with a blank line
boolean currentLineIsBlank = true;
boolean httpBody = false;
boolean inStatus = false;
char statusCode[4];
int i = 0;
int code = 0;
if(response == NULL){
HTTP_DEBUG_PRINT("HTTP: NULL RESPONSE POINTER: \n");
}else{
HTTP_DEBUG_PRINT("HTTP: NON-NULL RESPONSE POINTER: \n");
}
HTTP_DEBUG_PRINT("HTTP: RESPONSE: \n");
while (client.connected()) {
HTTP_DEBUG_PRINT(".");
if (client.available()) {
HTTP_DEBUG_PRINT(",");
char c = client.read();
HTTP_DEBUG_PRINT(c);
if(c == ' ' && !inStatus){
inStatus = true;
}
if(inStatus && i < 3 && c != ' '){
statusCode[i] = c;
i++;
}
if(i == 3){
statusCode[i] = '\0';
code = atoi(statusCode);
}
if(httpBody){
//only write response if its not null
if(response != NULL) response->concat(c);
}
else
{
if (c == '\n' && currentLineIsBlank) {
httpBody = true;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
}
HTTP_DEBUG_PRINT("HTTP: return readResponse3\n");
return code;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <time.h>
#include <string>
#include <cassert>
#include "KDTree.hpp"
#include "KDTreeNode.hpp"
#include "Point.hpp"
#include "MWC.hpp"
using namespace std;
//#define VERBOSE
void BenchMark(const int numPoints, const int repetitions, ostream& out);
const Point& BruteForceNearestNeighbour(const vector<Point*>& pointList, const Point& point);
void InternetExample1(vector<Point*>& points);
//______________________________________________________________________________
int main(int argc, char **argv) {
ofstream out("benchmark_data.txt");
out << "Num Points" << "\t" << "Brute Force Time" << "\t" << "Tree Search Time" << "\t";
out << "Std Dev Brute Force" << "\t" << "Std Dev Tree Search" << endl;
BenchMark(10, 10, out);
BenchMark(100, 10, out);
BenchMark(1000, 10, out);
BenchMark(10000, 10, out);
BenchMark(100000, 10, out);
// BenchMark(1000000, 10, out);
// BenchMark(10000000, 10, out);
return 0;
}
//______________________________________________________________________________
void BenchMark(const int numPoints, const int repetitions, ostream& out) {
// -- Benchmark builds 'numPoints' random points, constructs a kd-tree of these points
// -- then tests how long it takes to calculate the nearest neighbour of some random search point
// -- against an brute-force search
#ifdef VERBOSE
cout << "Benchmarking kd-tree nearest neighbour search, against brute-force search" << endl;
#endif
//-----------------------------------------------------------
// -- Generate random points
MWC rng;
vector<Point*> points;
for (int i=0; i<numPoints; i++) {
points.push_back(new Point(rng.rnd(),rng.rnd(),rng.rnd()));
}
// Print points
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Input Points" << endl;
vector<Point*>::iterator it;
for (it = points.begin(); it != points.end(); it++) {
cout << it - points.begin() << "\t" << (*it)->ToString() << endl;
}
cout << "--------------------" << endl;
#endif
//-----------------------------------------------------------
// -- Build Tree
// Set up timing
clock_t start, end;
start = clock();
KDTree tree(points);
// Output time to build tree
end = clock();
const double treeBuildTime = (double)(end-start)/CLOCKS_PER_SEC;
cout << "--------------------" << endl;
cout << "Number of points in Tree: " << numPoints << endl;
cout << "Time required to build Tree: ";
cout << treeBuildTime;
cout << " seconds." << endl;
//-----------------------------------------------------------
// Repeat search for number of times defined by 'repetitions'
// Store all times in vector for averaging and std dev
double totBruteForceTime = 0.;
double totTreeSearchTime = 0.;
vector<double> bruteForceTimes;
vector<double> treeSearchTimes;
for (int iter = 0; iter < repetitions; iter++) {
Point searchPoint(rng.rnd(),rng.rnd(),rng.rnd());
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Search Point: " << searchPoint.ToString() << endl;
#endif
//-----------------------------------------------------------
// -- Perform Brute force search for point
// Set up timing
start = clock();
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Performing Brute Force Search..." << endl;
#endif
const Point& brutePoint = BruteForceNearestNeighbour(points, searchPoint);
// Output time to build tree
end = clock();
const double bruteForceTime = (double)(end-start)/CLOCKS_PER_SEC;
//-----------------------------------------------------------
// -- Perform Tree-based search for point
// Set up timing
start = clock();
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Performing Tree-based Search..." << endl;
#endif
const Point& treePoint = tree.NearestNeighbour(searchPoint);
// calculate time to build tree
end = clock();
const double treeSearchTime = (double)(end-start)/CLOCKS_PER_SEC;
//-----------------------------------------------------------
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Brute force solution: " << brutePoint.ToString() << endl;
cout << "Time required for Brute force search: ";
cout << bruteForceTime;
cout << " seconds." << endl;
cout << "--------------------" << endl;
cout << "Tree solution: " << treePoint.ToString() << endl;
cout << "Time required for Tree search: ";
cout << treeSearchTime;
cout << " seconds." << endl;
cout << "--------------------" << endl;
#endif
assert(treePoint == brutePoint);
bruteForceTimes.push_back(bruteForceTime);
treeSearchTimes.push_back(treeSearchTime);
totBruteForceTime += bruteForceTime;
totTreeSearchTime += treeSearchTime;
}
// Calculate mean search times
double avgBruteForceTime = totBruteForceTime/repetitions;
double avgTreeSearchTime = totTreeSearchTime/repetitions;
// Calculate Std Dev
double sumBrute = 0.;
double sumTree = 0.;
for (int iter = 0; iter < repetitions; iter++) {
sumBrute += pow((bruteForceTimes[iter] - avgBruteForceTime), 2.0);
sumTree += pow((treeSearchTimes[iter] - avgTreeSearchTime), 2.0);
}
double stdDevBrute = sqrt(sumBrute/(repetitions-1));
double stdDevTree = sqrt(sumTree/(repetitions-1));
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Average Time required for Brute force search: ";
cout << avgBruteForceTime;
cout << " seconds." << endl;
cout << "--------------------" << endl;
cout << "Average Time required for Tree search: ";
cout << avgTreeSearchTime;
cout << " seconds." << endl;
cout << "--------------------" << endl;
#endif
out << numPoints << "\t" << avgBruteForceTime << "\t" << avgTreeSearchTime << "\t";
out << stdDevBrute << "\t" << stdDevTree << endl;
return;
}
//______________________________________________________________________________
const Point& BruteForceNearestNeighbour(const vector<Point*>& pointList, const Point& point)
{
// Take list of points and do a brute force search to find the nearest neighbour
// Return nearest neighbour
double currentBestDist = 0.0;
int currentBestPoint = 0;
vector<Point*>::const_iterator it;
for (it = pointList.begin(); it != pointList.end(); it++) {
double dist = (*it)->DistanceTo(point);
#ifdef VERBOSE
cout << setfill(' ') << setw(20);
cout << (*it)->ToString();
cout << "\t" << dist << endl;
#endif
if (currentBestDist == 0.0 || dist < currentBestDist) {
currentBestDist = dist;
currentBestPoint = it - pointList.begin();
}
}
return *(pointList[currentBestPoint]);
}
//______________________________________________________________________________
void InternetExample1(vector<Point*>& points)
{
//http://syntaxandsemantic.blogspot.com/2010/03/knn-algorithm-and-kd-trees.html
points.push_back(new Point(5,9,10));
points.push_back(new Point(2,6,8));
points.push_back(new Point(14,3,7));
points.push_back(new Point(3,4,9));
points.push_back(new Point(4,13,5));
points.push_back(new Point(8,2,1));
points.push_back(new Point(7,9,6));
points.push_back(new Point(4,1,6));
points.push_back(new Point(2,2,10));
}
<commit_msg>Updated TestKDTree to use new nth-NN-search<commit_after>#include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <time.h>
#include <string>
#include <cassert>
#include "KDTree.hpp"
#include "KDTreeNode.hpp"
#include "Point.hpp"
#include "MWC.hpp"
using namespace std;
//#define VERBOSE
void BenchMark(const int numPoints, const int repetitions, const int numNeighbours, ostream& out);
NodeStack* BruteForceNearestNeighbours(const vector<Point*>& pointList, const Point& point, const int nearestNeighbours);
void InternetExample1(vector<Point*>& points);
//______________________________________________________________________________
int main(int argc, char **argv) {
ofstream out("benchmark_data.txt");
out << "Num Points" << "\t" << "Brute Force Time" << "\t" << "Tree Search Time" << "\t";
out << "Std Dev Brute Force" << "\t" << "Std Dev Tree Search" << endl;
const int repetitions = 10;
const int numNeighbours = 6;
BenchMark(10, repetitions, numNeighbours, out);
BenchMark(100, repetitions, numNeighbours, out);
BenchMark(1000, repetitions, numNeighbours, out);
BenchMark(10000, repetitions, numNeighbours, out);
BenchMark(100000, repetitions, numNeighbours, out);
BenchMark(1000000, repetitions, numNeighbours, out);
// BenchMark(10000000, repetitions, numNeighbours, out);
return 0;
}
//______________________________________________________________________________
void BenchMark(const int numPoints, const int repetitions, const int numNeighbours, ostream& out) {
// -- Benchmark builds 'numPoints' random points, constructs a kd-tree of these points
// -- then tests how long it takes to calculate the 'n' nearest neighbours of some random point
// -- against a brute-force search approach
#ifdef VERBOSE
cout << "Benchmarking kd-tree nearest neighbour search, against brute-force search" << endl;
#endif
//-----------------------------------------------------------
// -- Generate random points
MWC rng;
vector<Point*> points;
for (int i=0; i<numPoints; i++) {
points.push_back(new Point(rng.rnd(),rng.rnd(),rng.rnd()));
}
// Print points
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Input Points" << endl;
vector<Point*>::iterator it;
for (it = points.begin(); it != points.end(); it++) {
cout << it - points.begin() << "\t" << (*it)->ToString() << endl;
}
cout << "--------------------" << endl;
#endif
//-----------------------------------------------------------
// -- Build Tree
// Set up timing
clock_t start, end;
start = clock();
KDTree tree(points);
// Output time to build tree
end = clock();
const double treeBuildTime = (double)(end-start)/CLOCKS_PER_SEC;
cout << "--------------------" << endl;
cout << "Number of points in Tree: " << numPoints << endl;
cout << "Time required to build Tree: ";
cout << treeBuildTime;
cout << " seconds." << endl;
//-----------------------------------------------------------
// Repeat search for number of times defined by 'repetitions'
// Store all times in vector for averaging and std dev
double totBruteForceTime = 0.;
double totTreeSearchTime = 0.;
vector<double> bruteForceTimes;
vector<double> treeSearchTimes;
for (int iter = 0; iter < repetitions; iter++) {
Point searchPoint(rng.rnd(),rng.rnd(),rng.rnd());
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Search Point: " << searchPoint.ToString() << endl;
#endif
//-----------------------------------------------------------
// -- Perform Brute force search for point
// Set up timing
start = clock();
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Performing Brute Force Search..." << endl;
#endif
const NodeStack* bruteList = BruteForceNearestNeighbours(points, searchPoint, numNeighbours);
// Output time to build tree
end = clock();
const double bruteForceTime = (double)(end-start)/CLOCKS_PER_SEC;
//-----------------------------------------------------------
// -- Perform Tree-based search for point
// Set up timing
start = clock();
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Performing Tree-based Search..." << endl;
#endif
const NodeStack* treeList = tree.NearestNeighbours(searchPoint, numNeighbours);
// calculate time to build tree
end = clock();
const double treeSearchTime = (double)(end-start)/CLOCKS_PER_SEC;
//-----------------------------------------------------------
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Time required for Brute force search: ";
cout << bruteForceTime;
cout << " seconds." << endl;
cout << "--------------------" << endl;
cout << "Time required for Tree search: ";
cout << treeSearchTime;
cout << " seconds." << endl;
cout << "--------------------" << endl;
cout << "Nearest Neighbours found: " << endl;
cout << "Brute" << "\t";
cout << bruteList->size() << endl;
list<StackElement>::const_iterator stackIter;
for (stackIter = bruteList->begin(); stackIter != bruteList->end(); stackIter++) {
cout << setfill(' ') << setw(10) << stackIter->first->GetPoint().ToString() << endl;
}
cout << endl;
cout << "Tree" << "\t";
cout << treeList->size() << endl;
for (stackIter = treeList->begin(); stackIter != treeList->end(); stackIter++) {
cout << setfill(' ') << setw(10) << stackIter->first->GetPoint().ToString() << endl;
}
cout << "--------------------" << endl;
#endif
assert(*treeList == *bruteList);
bruteForceTimes.push_back(bruteForceTime);
treeSearchTimes.push_back(treeSearchTime);
totBruteForceTime += bruteForceTime;
totTreeSearchTime += treeSearchTime;
delete treeList;
delete bruteList;
}
// Calculate mean search times
double avgBruteForceTime = totBruteForceTime/repetitions;
double avgTreeSearchTime = totTreeSearchTime/repetitions;
// Calculate Std Dev
double sumBrute = 0.;
double sumTree = 0.;
for (int iter = 0; iter < repetitions; iter++) {
sumBrute += pow((bruteForceTimes[iter] - avgBruteForceTime), 2.0);
sumTree += pow((treeSearchTimes[iter] - avgTreeSearchTime), 2.0);
}
double stdDevBrute = sqrt(sumBrute/(repetitions-1));
double stdDevTree = sqrt(sumTree/(repetitions-1));
#ifdef VERBOSE
cout << "--------------------" << endl;
cout << "Average Time required for Brute force search: ";
cout << avgBruteForceTime;
cout << " seconds." << endl;
cout << "--------------------" << endl;
cout << "Average Time required for Tree search: ";
cout << avgTreeSearchTime;
cout << " seconds." << endl;
cout << "--------------------" << endl;
#endif
out << numPoints << "\t" << avgBruteForceTime << "\t" << avgTreeSearchTime << "\t";
out << stdDevBrute << "\t" << stdDevTree << endl;
return;
}
//______________________________________________________________________________
NodeStack* BruteForceNearestNeighbours(const vector<Point*>& pointList, const Point& point, const int nearestNeighbours)
{
// Take list of points and do a brute force search to find the nearest neighbour
// Return nearest neighbour
NodeStack* neighbours = new NodeStack(nearestNeighbours);
vector<Point*>::const_iterator it;
for (it = pointList.begin(); it != pointList.end(); it++) {
double dist = (*it)->DistanceTo(point);
#ifdef VERBOSE
cout << setfill(' ') << setw(20);
cout << (*it)->ToString();
cout << "\t" << dist << endl;
#endif
KDTreeNode* node = new KDTreeNode();
node->SetPoint(*it);
neighbours->AddNode(node,dist);
}
return neighbours;
}
/*
//______________________________________________________________________________
const Point& BruteForceNearestNeighbour(const vector<Point*>& pointList, const Point& point)
{
// Take list of points and do a brute force search to find the nearest neighbour
// Return nearest neighbour
double currentBestDist = 0.0;
int currentBestPoint = 0;
vector<Point*>::const_iterator it;
for (it = pointList.begin(); it != pointList.end(); it++) {
double dist = (*it)->DistanceTo(point);
#ifdef VERBOSE
cout << setfill(' ') << setw(20);
cout << (*it)->ToString();
cout << "\t" << dist << endl;
#endif
if (currentBestDist == 0.0 || dist < currentBestDist) {
currentBestDist = dist;
currentBestPoint = it - pointList.begin();
}
}
return *(pointList[currentBestPoint]);
}
*/
//______________________________________________________________________________
void InternetExample1(vector<Point*>& points)
{
//http://syntaxandsemantic.blogspot.com/2010/03/knn-algorithm-and-kd-trees.html
points.push_back(new Point(5,9,10));
points.push_back(new Point(2,6,8));
points.push_back(new Point(14,3,7));
points.push_back(new Point(3,4,9));
points.push_back(new Point(4,13,5));
points.push_back(new Point(8,2,1));
points.push_back(new Point(7,9,6));
points.push_back(new Point(4,1,6));
points.push_back(new Point(2,2,10));
}
<|endoftext|> |
<commit_before>// Copyright 2014 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/ui/app_list/speech_recognizer.h"
#include <algorithm>
#include "base/bind.h"
#include "base/strings/string16.h"
#include "base/timer/timer.h"
#include "chrome/browser/ui/app_list/speech_recognizer_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/speech_recognition_event_listener.h"
#include "content/public/browser/speech_recognition_manager.h"
#include "content/public/browser/speech_recognition_session_config.h"
#include "content/public/browser/speech_recognition_session_preamble.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/speech_recognition_error.h"
#include "net/url_request/url_request_context_getter.h"
#include "ui/app_list/speech_ui_model_observer.h"
namespace app_list {
// Length of timeout to cancel recognition if there's no speech heard.
static const int kNoSpeechTimeoutInSeconds = 5;
// Invalid speech session.
static const int kInvalidSessionId = -1;
// Speech recognizer listener. This is separate from SpeechRecognizer because
// the speech recognition engine must function from the IO thread. Because of
// this, the lifecycle of this class must be decoupled from the lifecycle of
// SpeechRecognizer. To avoid circular references, this class has no reference
// to SpeechRecognizer. Instead, it has a reference to the
// SpeechRecognizerDelegate via a weak pointer that is only ever referenced from
// the UI thread.
class SpeechRecognizer::EventListener
: public base::RefCountedThreadSafe<SpeechRecognizer::EventListener>,
public content::SpeechRecognitionEventListener {
public:
EventListener(const base::WeakPtr<SpeechRecognizerDelegate>& delegate,
net::URLRequestContextGetter* url_request_context_getter,
const std::string& locale);
void StartOnIOThread(
const std::string& auth_scope,
const std::string& auth_token,
const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble);
void StopOnIOThread();
private:
friend class base::RefCountedThreadSafe<SpeechRecognizer::EventListener>;
~EventListener() override;
void NotifyRecognitionStateChanged(SpeechRecognitionState new_state);
void StartSpeechTimeout();
void StopSpeechTimeout();
void SpeechTimeout();
// Overidden from content::SpeechRecognitionEventListener:
// These are always called on the IO thread.
void OnRecognitionStart(int session_id) override;
void OnRecognitionEnd(int session_id) override;
void OnRecognitionResults(
int session_id,
const content::SpeechRecognitionResults& results) override;
void OnRecognitionError(
int session_id, const content::SpeechRecognitionError& error) override;
void OnSoundStart(int session_id) override;
void OnSoundEnd(int session_id) override;
void OnAudioLevelsChange(
int session_id, float volume, float noise_volume) override;
void OnEnvironmentEstimationComplete(int session_id) override;
void OnAudioStart(int session_id) override;
void OnAudioEnd(int session_id) override;
// Only dereferenced from the UI thread, but copied on IO thread.
base::WeakPtr<SpeechRecognizerDelegate> delegate_;
// All remaining members only accessed from the IO thread.
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
std::string locale_;
base::Timer speech_timeout_;
int session_;
base::WeakPtrFactory<EventListener> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(EventListener);
};
SpeechRecognizer::EventListener::EventListener(
const base::WeakPtr<SpeechRecognizerDelegate>& delegate,
net::URLRequestContextGetter* url_request_context_getter,
const std::string& locale)
: delegate_(delegate),
url_request_context_getter_(url_request_context_getter),
locale_(locale),
speech_timeout_(false, false),
session_(kInvalidSessionId),
weak_factory_(this) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
SpeechRecognizer::EventListener::~EventListener() {
DCHECK(!speech_timeout_.IsRunning());
}
void SpeechRecognizer::EventListener::StartOnIOThread(
const std::string& auth_scope,
const std::string& auth_token,
const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (session_ != kInvalidSessionId)
StopOnIOThread();
content::SpeechRecognitionSessionConfig config;
config.language = locale_;
config.is_legacy_api = false;
config.continuous = true;
config.interim_results = true;
config.max_hypotheses = 1;
config.filter_profanities = true;
config.url_request_context_getter = url_request_context_getter_;
config.event_listener = weak_factory_.GetWeakPtr();
// kInvalidUniqueID is not a valid render process, so the speech permission
// check allows the request through.
config.initial_context.render_process_id =
content::ChildProcessHost::kInvalidUniqueID;
config.auth_scope = auth_scope;
config.auth_token = auth_token;
config.preamble = preamble;
auto speech_instance = content::SpeechRecognitionManager::GetInstance();
session_ = speech_instance->CreateSession(config);
speech_instance->StartSession(session_);
}
void SpeechRecognizer::EventListener::StopOnIOThread() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (session_ == kInvalidSessionId)
return;
// Prevent recursion.
int session = session_;
session_ = kInvalidSessionId;
StopSpeechTimeout();
content::SpeechRecognitionManager::GetInstance()->StopAudioCaptureForSession(
session);
}
void SpeechRecognizer::EventListener::NotifyRecognitionStateChanged(
SpeechRecognitionState new_state) {
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&SpeechRecognizerDelegate::OnSpeechRecognitionStateChanged,
delegate_,
new_state));
}
void SpeechRecognizer::EventListener::StartSpeechTimeout() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
speech_timeout_.Start(
FROM_HERE,
base::TimeDelta::FromSeconds(kNoSpeechTimeoutInSeconds),
base::Bind(&SpeechRecognizer::EventListener::SpeechTimeout, this));
}
void SpeechRecognizer::EventListener::StopSpeechTimeout() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
speech_timeout_.Stop();
}
void SpeechRecognizer::EventListener::SpeechTimeout() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
StopOnIOThread();
}
void SpeechRecognizer::EventListener::OnRecognitionStart(int session_id) {
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_RECOGNIZING);
}
void SpeechRecognizer::EventListener::OnRecognitionEnd(int session_id) {
StopOnIOThread();
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_READY);
}
void SpeechRecognizer::EventListener::OnRecognitionResults(
int session_id, const content::SpeechRecognitionResults& results) {
base::string16 result_str;
size_t final_count = 0;
for (const auto& result : results) {
if (!result.is_provisional)
final_count++;
result_str += result.hypotheses[0].utterance;
}
StopSpeechTimeout();
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&SpeechRecognizerDelegate::OnSpeechResult,
delegate_,
result_str,
final_count == results.size()));
// Stop the moment we have a final result.
if (final_count == results.size())
StopOnIOThread();
}
void SpeechRecognizer::EventListener::OnRecognitionError(
int session_id, const content::SpeechRecognitionError& error) {
StopOnIOThread();
if (error.code == content::SPEECH_RECOGNITION_ERROR_NETWORK) {
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_NETWORK_ERROR);
}
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_READY);
}
void SpeechRecognizer::EventListener::OnSoundStart(int session_id) {
StartSpeechTimeout();
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_IN_SPEECH);
}
void SpeechRecognizer::EventListener::OnSoundEnd(int session_id) {
StopOnIOThread();
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_RECOGNIZING);
}
void SpeechRecognizer::EventListener::OnAudioLevelsChange(
int session_id, float volume, float noise_volume) {
DCHECK_LE(0.0, volume);
DCHECK_GE(1.0, volume);
DCHECK_LE(0.0, noise_volume);
DCHECK_GE(1.0, noise_volume);
volume = std::max(0.0f, volume - noise_volume);
// Both |volume| and |noise_volume| are defined to be in the range [0.0, 1.0].
// See: content/public/browser/speech_recognition_event_listener.h
int16_t sound_level = static_cast<int16_t>(INT16_MAX * volume);
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&SpeechRecognizerDelegate::OnSpeechSoundLevelChanged,
delegate_,
sound_level));
}
void SpeechRecognizer::EventListener::OnEnvironmentEstimationComplete(
int session_id) {
}
void SpeechRecognizer::EventListener::OnAudioStart(int session_id) {
}
void SpeechRecognizer::EventListener::OnAudioEnd(int session_id) {
}
SpeechRecognizer::SpeechRecognizer(
const base::WeakPtr<SpeechRecognizerDelegate>& delegate,
net::URLRequestContextGetter* url_request_context_getter,
const std::string& locale)
: delegate_(delegate),
speech_event_listener_(new EventListener(
delegate, url_request_context_getter, locale)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
SpeechRecognizer::~SpeechRecognizer() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
Stop();
}
void SpeechRecognizer::Start(
const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::string auth_scope;
std::string auth_token;
delegate_->GetSpeechAuthParameters(&auth_scope, &auth_token);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&SpeechRecognizer::EventListener::StartOnIOThread,
speech_event_listener_,
auth_scope,
auth_token,
preamble));
}
void SpeechRecognizer::Stop() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&SpeechRecognizer::EventListener::StopOnIOThread,
speech_event_listener_));
}
} // namespace app_list
<commit_msg>Add a timeout for app list voice search for when the query doesn't change.<commit_after>// Copyright 2014 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/ui/app_list/speech_recognizer.h"
#include <algorithm>
#include "base/bind.h"
#include "base/strings/string16.h"
#include "base/timer/timer.h"
#include "chrome/browser/ui/app_list/speech_recognizer_delegate.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/speech_recognition_event_listener.h"
#include "content/public/browser/speech_recognition_manager.h"
#include "content/public/browser/speech_recognition_session_config.h"
#include "content/public/browser/speech_recognition_session_preamble.h"
#include "content/public/common/child_process_host.h"
#include "content/public/common/speech_recognition_error.h"
#include "net/url_request/url_request_context_getter.h"
#include "ui/app_list/speech_ui_model_observer.h"
namespace app_list {
// Length of timeout to cancel recognition if there's no speech heard.
static const int kNoSpeechTimeoutInSeconds = 5;
// Length of timeout to cancel recognition if no different results are received.
static const int kNoNewSpeechTimeoutInSeconds = 3;
// Invalid speech session.
static const int kInvalidSessionId = -1;
// Speech recognizer listener. This is separate from SpeechRecognizer because
// the speech recognition engine must function from the IO thread. Because of
// this, the lifecycle of this class must be decoupled from the lifecycle of
// SpeechRecognizer. To avoid circular references, this class has no reference
// to SpeechRecognizer. Instead, it has a reference to the
// SpeechRecognizerDelegate via a weak pointer that is only ever referenced from
// the UI thread.
class SpeechRecognizer::EventListener
: public base::RefCountedThreadSafe<SpeechRecognizer::EventListener>,
public content::SpeechRecognitionEventListener {
public:
EventListener(const base::WeakPtr<SpeechRecognizerDelegate>& delegate,
net::URLRequestContextGetter* url_request_context_getter,
const std::string& locale);
void StartOnIOThread(
const std::string& auth_scope,
const std::string& auth_token,
const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble);
void StopOnIOThread();
private:
friend class base::RefCountedThreadSafe<SpeechRecognizer::EventListener>;
~EventListener() override;
void NotifyRecognitionStateChanged(SpeechRecognitionState new_state);
// Starts a timer for |timeout_seconds|. When the timer expires, will stop
// capturing audio and get a final utterance from the recognition manager.
void StartSpeechTimeout(int timeout_seconds);
void StopSpeechTimeout();
void SpeechTimeout();
// Overidden from content::SpeechRecognitionEventListener:
// These are always called on the IO thread.
void OnRecognitionStart(int session_id) override;
void OnRecognitionEnd(int session_id) override;
void OnRecognitionResults(
int session_id,
const content::SpeechRecognitionResults& results) override;
void OnRecognitionError(
int session_id, const content::SpeechRecognitionError& error) override;
void OnSoundStart(int session_id) override;
void OnSoundEnd(int session_id) override;
void OnAudioLevelsChange(
int session_id, float volume, float noise_volume) override;
void OnEnvironmentEstimationComplete(int session_id) override;
void OnAudioStart(int session_id) override;
void OnAudioEnd(int session_id) override;
// Only dereferenced from the UI thread, but copied on IO thread.
base::WeakPtr<SpeechRecognizerDelegate> delegate_;
// All remaining members only accessed from the IO thread.
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_;
std::string locale_;
base::Timer speech_timeout_;
int session_;
base::string16 last_result_str_;
base::WeakPtrFactory<EventListener> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(EventListener);
};
SpeechRecognizer::EventListener::EventListener(
const base::WeakPtr<SpeechRecognizerDelegate>& delegate,
net::URLRequestContextGetter* url_request_context_getter,
const std::string& locale)
: delegate_(delegate),
url_request_context_getter_(url_request_context_getter),
locale_(locale),
speech_timeout_(false, false),
session_(kInvalidSessionId),
weak_factory_(this) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
SpeechRecognizer::EventListener::~EventListener() {
DCHECK(!speech_timeout_.IsRunning());
}
void SpeechRecognizer::EventListener::StartOnIOThread(
const std::string& auth_scope,
const std::string& auth_token,
const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (session_ != kInvalidSessionId)
StopOnIOThread();
content::SpeechRecognitionSessionConfig config;
config.language = locale_;
config.is_legacy_api = false;
config.continuous = true;
config.interim_results = true;
config.max_hypotheses = 1;
config.filter_profanities = true;
config.url_request_context_getter = url_request_context_getter_;
config.event_listener = weak_factory_.GetWeakPtr();
// kInvalidUniqueID is not a valid render process, so the speech permission
// check allows the request through.
config.initial_context.render_process_id =
content::ChildProcessHost::kInvalidUniqueID;
config.auth_scope = auth_scope;
config.auth_token = auth_token;
config.preamble = preamble;
auto speech_instance = content::SpeechRecognitionManager::GetInstance();
session_ = speech_instance->CreateSession(config);
speech_instance->StartSession(session_);
}
void SpeechRecognizer::EventListener::StopOnIOThread() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
if (session_ == kInvalidSessionId)
return;
// Prevent recursion.
int session = session_;
session_ = kInvalidSessionId;
StopSpeechTimeout();
content::SpeechRecognitionManager::GetInstance()->StopAudioCaptureForSession(
session);
}
void SpeechRecognizer::EventListener::NotifyRecognitionStateChanged(
SpeechRecognitionState new_state) {
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&SpeechRecognizerDelegate::OnSpeechRecognitionStateChanged,
delegate_,
new_state));
}
void SpeechRecognizer::EventListener::StartSpeechTimeout(int timeout_seconds) {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
speech_timeout_.Start(
FROM_HERE,
base::TimeDelta::FromSeconds(timeout_seconds),
base::Bind(&SpeechRecognizer::EventListener::SpeechTimeout, this));
}
void SpeechRecognizer::EventListener::StopSpeechTimeout() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
speech_timeout_.Stop();
}
void SpeechRecognizer::EventListener::SpeechTimeout() {
DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
StopOnIOThread();
}
void SpeechRecognizer::EventListener::OnRecognitionStart(int session_id) {
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_RECOGNIZING);
}
void SpeechRecognizer::EventListener::OnRecognitionEnd(int session_id) {
StopOnIOThread();
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_READY);
}
void SpeechRecognizer::EventListener::OnRecognitionResults(
int session_id, const content::SpeechRecognitionResults& results) {
base::string16 result_str;
size_t final_count = 0;
// The number of results with |is_provisional| false. If |final_count| ==
// results.size(), then all results are non-provisional and the recognition is
// complete.
for (const auto& result : results) {
if (!result.is_provisional)
final_count++;
result_str += result.hypotheses[0].utterance;
}
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&SpeechRecognizerDelegate::OnSpeechResult,
delegate_,
result_str,
final_count == results.size()));
// Stop the moment we have a final result. If we receive any new or changed
// text, restart the timer to give the user more time to speak. (The timer is
// recording the amount of time since the most recent utterance.)
if (final_count == results.size())
StopOnIOThread();
else if (result_str != last_result_str_)
StartSpeechTimeout(kNoNewSpeechTimeoutInSeconds);
last_result_str_ = result_str;
}
void SpeechRecognizer::EventListener::OnRecognitionError(
int session_id, const content::SpeechRecognitionError& error) {
StopOnIOThread();
if (error.code == content::SPEECH_RECOGNITION_ERROR_NETWORK) {
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_NETWORK_ERROR);
}
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_READY);
}
void SpeechRecognizer::EventListener::OnSoundStart(int session_id) {
StartSpeechTimeout(kNoSpeechTimeoutInSeconds);
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_IN_SPEECH);
}
void SpeechRecognizer::EventListener::OnSoundEnd(int session_id) {
StopOnIOThread();
NotifyRecognitionStateChanged(SPEECH_RECOGNITION_RECOGNIZING);
}
void SpeechRecognizer::EventListener::OnAudioLevelsChange(
int session_id, float volume, float noise_volume) {
DCHECK_LE(0.0, volume);
DCHECK_GE(1.0, volume);
DCHECK_LE(0.0, noise_volume);
DCHECK_GE(1.0, noise_volume);
volume = std::max(0.0f, volume - noise_volume);
// Both |volume| and |noise_volume| are defined to be in the range [0.0, 1.0].
// See: content/public/browser/speech_recognition_event_listener.h
int16_t sound_level = static_cast<int16_t>(INT16_MAX * volume);
content::BrowserThread::PostTask(
content::BrowserThread::UI,
FROM_HERE,
base::Bind(&SpeechRecognizerDelegate::OnSpeechSoundLevelChanged,
delegate_,
sound_level));
}
void SpeechRecognizer::EventListener::OnEnvironmentEstimationComplete(
int session_id) {
}
void SpeechRecognizer::EventListener::OnAudioStart(int session_id) {
}
void SpeechRecognizer::EventListener::OnAudioEnd(int session_id) {
}
SpeechRecognizer::SpeechRecognizer(
const base::WeakPtr<SpeechRecognizerDelegate>& delegate,
net::URLRequestContextGetter* url_request_context_getter,
const std::string& locale)
: delegate_(delegate),
speech_event_listener_(new EventListener(
delegate, url_request_context_getter, locale)) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
}
SpeechRecognizer::~SpeechRecognizer() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
Stop();
}
void SpeechRecognizer::Start(
const scoped_refptr<content::SpeechRecognitionSessionPreamble>& preamble) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
std::string auth_scope;
std::string auth_token;
delegate_->GetSpeechAuthParameters(&auth_scope, &auth_token);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&SpeechRecognizer::EventListener::StartOnIOThread,
speech_event_listener_,
auth_scope,
auth_token,
preamble));
}
void SpeechRecognizer::Stop() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
content::BrowserThread::PostTask(
content::BrowserThread::IO,
FROM_HERE,
base::Bind(&SpeechRecognizer::EventListener::StopOnIOThread,
speech_event_listener_));
}
} // namespace app_list
<|endoftext|> |
<commit_before>// 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 "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
class OptionsUITest : public UITest {
public:
OptionsUITest() {
dom_automation_enabled_ = true;
}
void AssertIsOptionsPage(TabProxy* tab) {
std::wstring title;
ASSERT_TRUE(tab->GetTabTitle(&title));
string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
// The only guarantee we can make about the title of a settings tab is that
// it should contain IDS_SETTINGS_TITLE somewhere.
ASSERT_FALSE(WideToUTF16Hack(title).find(expected_title) == string16::npos);
}
};
TEST_F(OptionsUITest, LoadOptionsByURL) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
NavigateToURL(GURL(chrome::kChromeUISettingsURL));
AssertIsOptionsPage(tab);
// Check navbar's existence.
bool navbar_exist = false;
ASSERT_TRUE(tab->ExecuteAndExtractBool(L"",
L"domAutomationController.send("
L"!!document.getElementById('navbar'))", &navbar_exist));
ASSERT_EQ(true, navbar_exist);
// Check section headers in navbar.
// For ChromeOS, there should be 1 + 7:
// Search, Basics, Personal, System, Internet, Under the Hood,
// Users and Extensions.
// For other platforms, there should 1 + 4:
// Search, Basics, Personal, Under the Hood and Extensions.
#if defined(OS_CHROMEOS)
const int kExpectedSections = 1 + 7;
#else
const int kExpectedSections = 1 + 4;
#endif
int num_of_sections = 0;
ASSERT_TRUE(tab->ExecuteAndExtractInt(L"",
L"domAutomationController.send("
L"document.getElementById('navbar').children.length)", &num_of_sections));
ASSERT_EQ(kExpectedSections, num_of_sections);
}
} // namespace
<commit_msg>[dom-ui options] Inline helper functions for OptionsUITest.LoadOptionsByURL.<commit_after>// 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 "base/string16.h"
#include "base/utf_string_conversions.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/automation/automation_proxy.h"
#include "chrome/test/automation/browser_proxy.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/ui/ui_test.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
class OptionsUITest : public UITest {
public:
OptionsUITest() {
dom_automation_enabled_ = true;
}
};
TEST_F(OptionsUITest, LoadOptionsByURL) {
scoped_refptr<BrowserProxy> browser(automation()->GetBrowserWindow(0));
ASSERT_TRUE(browser.get());
scoped_refptr<TabProxy> tab = browser->GetActiveTab();
ASSERT_TRUE(tab.get());
// Navigate to the settings tab and block until complete.
const GURL& url = GURL(chrome::kChromeUISettingsURL);
ASSERT_EQ(AUTOMATION_MSG_NAVIGATION_SUCCESS,
tab->NavigateToURLBlockUntilNavigationsComplete(url, 1)) << url.spec();
// Verify that the page title is correct.
// The only guarantee we can make about the title of a settings tab is that
// it should contain IDS_SETTINGS_TITLE somewhere.
std::wstring title;
EXPECT_TRUE(tab->GetTabTitle(&title));
string16 expected_title = l10n_util::GetStringUTF16(IDS_SETTINGS_TITLE);
EXPECT_NE(WideToUTF16Hack(title).find(expected_title), string16::npos);
// Check navbar's existence.
bool navbar_exist = false;
EXPECT_TRUE(tab->ExecuteAndExtractBool(L"",
L"domAutomationController.send("
L"!!document.getElementById('navbar'))", &navbar_exist));
EXPECT_EQ(true, navbar_exist);
// Check section headers in navbar.
// For ChromeOS, there should be 1 + 7:
// Search, Basics, Personal, System, Internet, Under the Hood,
// Users and Extensions.
// For other platforms, there should 1 + 4:
// Search, Basics, Personal, Under the Hood and Extensions.
#if defined(OS_CHROMEOS)
const int kExpectedSections = 1 + 7;
#else
const int kExpectedSections = 1 + 4;
#endif
int num_of_sections = 0;
EXPECT_TRUE(tab->ExecuteAndExtractInt(L"",
L"domAutomationController.send("
L"document.getElementById('navbar').children.length)", &num_of_sections));
EXPECT_EQ(kExpectedSections, num_of_sections);
}
} // namespace
<|endoftext|> |
<commit_before>// 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/renderer/renderer_webstoragenamespace_impl.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/renderer_webstoragearea_impl.h"
using WebKit::WebStorageArea;
using WebKit::WebStorageNamespace;
using WebKit::WebString;
RendererWebStorageNamespaceImpl::RendererWebStorageNamespaceImpl(
DOMStorageType storage_type)
: storage_type_(storage_type),
namespace_id_(kLocalStorageNamespaceId) {
DCHECK(storage_type == DOM_STORAGE_LOCAL);
}
RendererWebStorageNamespaceImpl::RendererWebStorageNamespaceImpl(
DOMStorageType storage_type, int64 namespace_id)
: storage_type_(storage_type),
namespace_id_(namespace_id) {
DCHECK(storage_type == DOM_STORAGE_SESSION);
}
RendererWebStorageNamespaceImpl::~RendererWebStorageNamespaceImpl() {
}
WebStorageArea* RendererWebStorageNamespaceImpl::createStorageArea(
const WebString& origin) {
// Ideally, we'd keep a hash map of origin to these objects. Unfortunately
// this doesn't seem practical because there's no good way to ref-count these
// objects, and it'd be unclear who owned them. So, instead, we'll pay the
// price in terms of wasted memory.
return new RendererWebStorageAreaImpl(namespace_id_, origin);
}
WebStorageNamespace* RendererWebStorageNamespaceImpl::copy() {
NOTREACHED(); // We shouldn't ever reach this code in Chromium.
return NULL;
}
void RendererWebStorageNamespaceImpl::close() {
// This is called only on LocalStorage namespaces when WebKit thinks its
// shutting down. This has no impact on Chromium.
}
<commit_msg>Remove a not-implemented and add a helpful comment.<commit_after>// 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/renderer_webstoragenamespace_impl.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#include "chrome/renderer/renderer_webstoragearea_impl.h"
using WebKit::WebStorageArea;
using WebKit::WebStorageNamespace;
using WebKit::WebString;
RendererWebStorageNamespaceImpl::RendererWebStorageNamespaceImpl(
DOMStorageType storage_type)
: storage_type_(storage_type),
namespace_id_(kLocalStorageNamespaceId) {
DCHECK(storage_type == DOM_STORAGE_LOCAL);
}
RendererWebStorageNamespaceImpl::RendererWebStorageNamespaceImpl(
DOMStorageType storage_type, int64 namespace_id)
: storage_type_(storage_type),
namespace_id_(namespace_id) {
DCHECK(storage_type == DOM_STORAGE_SESSION);
}
RendererWebStorageNamespaceImpl::~RendererWebStorageNamespaceImpl() {
}
WebStorageArea* RendererWebStorageNamespaceImpl::createStorageArea(
const WebString& origin) {
// Ideally, we'd keep a hash map of origin to these objects. Unfortunately
// this doesn't seem practical because there's no good way to ref-count these
// objects, and it'd be unclear who owned them. So, instead, we'll pay the
// price in terms of wasted memory.
return new RendererWebStorageAreaImpl(namespace_id_, origin);
}
WebStorageNamespace* RendererWebStorageNamespaceImpl::copy() {
// By returning NULL, we're telling WebKit to lazily fetch it the next time
// session storage is used. In the WebViewClient::createView, we do the
// book-keeping necessary to make it a true copy-on-write despite not doing
// anything here, now.
return NULL;
}
void RendererWebStorageNamespaceImpl::close() {
// This is called only on LocalStorage namespaces when WebKit thinks its
// shutting down. This has no impact on Chromium.
}
<|endoftext|> |
<commit_before>// 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 "views/controls/tabbed_pane/tabbed_pane.h"
#include "base/logging.h"
#include "views/controls/tabbed_pane/native_tabbed_pane_wrapper.h"
namespace views {
// static
const char TabbedPane::kViewClassName[] = "views/TabbedPane";
TabbedPane::TabbedPane() : native_tabbed_pane_(NULL), listener_(NULL) {
SetFocusable(true);
}
TabbedPane::~TabbedPane() {
}
void TabbedPane::SetListener(Listener* listener) {
listener_ = listener;
}
void TabbedPane::AddTab(const std::wstring& title, View* contents) {
native_tabbed_pane_->AddTab(title, contents);
}
void TabbedPane::AddTabAtIndex(int index,
const std::wstring& title,
View* contents,
bool select_if_first_tab) {
native_tabbed_pane_->AddTabAtIndex(index, title, contents,
select_if_first_tab);
}
int TabbedPane::GetSelectedTabIndex() {
return native_tabbed_pane_->GetSelectedTabIndex();
}
View* TabbedPane::GetSelectedTab() {
return native_tabbed_pane_->GetSelectedTab();
}
View* TabbedPane::RemoveTabAtIndex(int index) {
return native_tabbed_pane_->RemoveTabAtIndex(index);
}
void TabbedPane::SelectTabAt(int index) {
native_tabbed_pane_->SelectTabAt(index);
}
int TabbedPane::GetTabCount() {
return native_tabbed_pane_->GetTabCount();
}
void TabbedPane::CreateWrapper() {
native_tabbed_pane_ = NativeTabbedPaneWrapper::CreateNativeWrapper(this);
}
// View overrides:
std::string TabbedPane::GetClassName() const {
return kViewClassName;
}
void TabbedPane::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
if (is_add && !native_tabbed_pane_ && GetWidget()) {
CreateWrapper();
AddChildView(native_tabbed_pane_->GetView());
LoadAccelerators();
}
}
bool TabbedPane::AcceleratorPressed(const views::Accelerator& accelerator) {
// We only accept Ctrl+Tab keyboard events.
DCHECK(accelerator.GetKeyCode() == VK_TAB && accelerator.IsCtrlDown());
int tab_count = GetTabCount();
if (tab_count <= 1)
return false;
int selected_tab_index = GetSelectedTabIndex();
int next_tab_index = accelerator.IsShiftDown() ?
(selected_tab_index - 1) % tab_count :
(selected_tab_index + 1) % tab_count;
// Wrap around.
if (next_tab_index < 0)
next_tab_index += tab_count;
SelectTabAt(next_tab_index);
return true;
}
void TabbedPane::LoadAccelerators() {
// Ctrl+Shift+Tab
AddAccelerator(views::Accelerator(VK_TAB, true, true, false));
// Ctrl+Tab
AddAccelerator(views::Accelerator(VK_TAB, false, true, false));
}
void TabbedPane::Layout() {
if (native_tabbed_pane_) {
native_tabbed_pane_->GetView()->SetBounds(0, 0, width(), height());
native_tabbed_pane_->GetView()->Layout();
}
}
void TabbedPane::Focus() {
// Forward the focus to the wrapper.
if (native_tabbed_pane_)
native_tabbed_pane_->SetFocus();
else
View::Focus(); // Will focus the RootView window (so we still get keyboard
// messages).
}
} // namespace views
<commit_msg>Fixing a compilation error in toolkit_views.<commit_after>// 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 "views/controls/tabbed_pane/tabbed_pane.h"
#include "base/keyboard_codes.h"
#include "base/logging.h"
#include "views/controls/tabbed_pane/native_tabbed_pane_wrapper.h"
namespace views {
// static
const char TabbedPane::kViewClassName[] = "views/TabbedPane";
TabbedPane::TabbedPane() : native_tabbed_pane_(NULL), listener_(NULL) {
SetFocusable(true);
}
TabbedPane::~TabbedPane() {
}
void TabbedPane::SetListener(Listener* listener) {
listener_ = listener;
}
void TabbedPane::AddTab(const std::wstring& title, View* contents) {
native_tabbed_pane_->AddTab(title, contents);
}
void TabbedPane::AddTabAtIndex(int index,
const std::wstring& title,
View* contents,
bool select_if_first_tab) {
native_tabbed_pane_->AddTabAtIndex(index, title, contents,
select_if_first_tab);
}
int TabbedPane::GetSelectedTabIndex() {
return native_tabbed_pane_->GetSelectedTabIndex();
}
View* TabbedPane::GetSelectedTab() {
return native_tabbed_pane_->GetSelectedTab();
}
View* TabbedPane::RemoveTabAtIndex(int index) {
return native_tabbed_pane_->RemoveTabAtIndex(index);
}
void TabbedPane::SelectTabAt(int index) {
native_tabbed_pane_->SelectTabAt(index);
}
int TabbedPane::GetTabCount() {
return native_tabbed_pane_->GetTabCount();
}
void TabbedPane::CreateWrapper() {
native_tabbed_pane_ = NativeTabbedPaneWrapper::CreateNativeWrapper(this);
}
// View overrides:
std::string TabbedPane::GetClassName() const {
return kViewClassName;
}
void TabbedPane::ViewHierarchyChanged(bool is_add, View* parent, View* child) {
if (is_add && !native_tabbed_pane_ && GetWidget()) {
CreateWrapper();
AddChildView(native_tabbed_pane_->GetView());
LoadAccelerators();
}
}
bool TabbedPane::AcceleratorPressed(const views::Accelerator& accelerator) {
// We only accept Ctrl+Tab keyboard events.
DCHECK(accelerator.GetKeyCode() ==
base::VKEY_TAB && accelerator.IsCtrlDown());
int tab_count = GetTabCount();
if (tab_count <= 1)
return false;
int selected_tab_index = GetSelectedTabIndex();
int next_tab_index = accelerator.IsShiftDown() ?
(selected_tab_index - 1) % tab_count :
(selected_tab_index + 1) % tab_count;
// Wrap around.
if (next_tab_index < 0)
next_tab_index += tab_count;
SelectTabAt(next_tab_index);
return true;
}
void TabbedPane::LoadAccelerators() {
// Ctrl+Shift+Tab
AddAccelerator(views::Accelerator(base::VKEY_TAB, true, true, false));
// Ctrl+Tab
AddAccelerator(views::Accelerator(base::VKEY_TAB, false, true, false));
}
void TabbedPane::Layout() {
if (native_tabbed_pane_) {
native_tabbed_pane_->GetView()->SetBounds(0, 0, width(), height());
native_tabbed_pane_->GetView()->Layout();
}
}
void TabbedPane::Focus() {
// Forward the focus to the wrapper.
if (native_tabbed_pane_)
native_tabbed_pane_->SetFocus();
else
View::Focus(); // Will focus the RootView window (so we still get keyboard
// messages).
}
} // namespace views
<|endoftext|> |
<commit_before>// 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 "base/command_line.h"
#include "base/file_util.h"
#include "base/test_suite.h"
#include "chrome/test/mini_installer_test/mini_installer_test_constants.h"
#include "chrome_mini_installer.h"
void BackUpProfile() {
if (base::GetProcessCount(L"chrome.exe", NULL) > 0) {
printf("Chrome is currently running and cannot backup the profile."
"Please close Chrome and run the tests again.\n");
exit(1);
}
ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);
std::wstring path = installer.GetChromeInstallDirectoryLocation();
file_util::AppendToPath(&path, mini_installer_constants::kChromeAppDir);
file_util::UpOneDirectory(&path);
std::wstring backup_path = path;
// Will hold User Data path that needs to be backed-up.
file_util::AppendToPath(&path,
mini_installer_constants::kChromeUserDataDir);
// Will hold new backup path to save the profile.
file_util::AppendToPath(&backup_path,
mini_installer_constants::kChromeUserDataBackupDir);
// Will check if User Data profile is available.
if (file_util::PathExists(path)) {
// Will check if User Data is already backed up.
// If yes, will delete and create new one.
if (file_util::PathExists(backup_path))
file_util::Delete(backup_path.c_str(), true);
file_util::CopyDirectory(path, backup_path, true);
} else {
printf("Chrome is not installed. Will not take any backup\n");
}
}
int main(int argc, char** argv) {
// Check command line to decide if the tests should continue
// with cleaning the system or make a backup before continuing.
CommandLine::Init(argc, argv);
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(L"clean")) {
printf("Current version of Chrome will be uninstalled "
"from all levels before proceeding with tests.\n");
} else if (command_line.HasSwitch(L"backup")) {
BackUpProfile();
} else {
printf("This test needs command line Arguments.\n");
printf("Usage: mini_installer_tests.exe -{clean|backup}\n");
printf("Note: -clean arg will uninstall your chrome at all levels"
" and also delete profile.\n"
"-backup arg will make a copy of User Data before uninstalling"
" your chrome at all levels. The copy will be named as"
" User Data Copy.\n");
exit(1);
}
return TestSuite(argc, argv).Run();
}
<commit_msg>Fix a broken include in the mini installer tests<commit_after>// 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 "base/command_line.h"
#include "base/file_util.h"
#include "base/test/test_suite.h"
#include "chrome/test/mini_installer_test/mini_installer_test_constants.h"
#include "chrome_mini_installer.h"
void BackUpProfile() {
if (base::GetProcessCount(L"chrome.exe", NULL) > 0) {
printf("Chrome is currently running and cannot backup the profile."
"Please close Chrome and run the tests again.\n");
exit(1);
}
ChromeMiniInstaller installer(mini_installer_constants::kUserInstall);
std::wstring path = installer.GetChromeInstallDirectoryLocation();
file_util::AppendToPath(&path, mini_installer_constants::kChromeAppDir);
file_util::UpOneDirectory(&path);
std::wstring backup_path = path;
// Will hold User Data path that needs to be backed-up.
file_util::AppendToPath(&path,
mini_installer_constants::kChromeUserDataDir);
// Will hold new backup path to save the profile.
file_util::AppendToPath(&backup_path,
mini_installer_constants::kChromeUserDataBackupDir);
// Will check if User Data profile is available.
if (file_util::PathExists(path)) {
// Will check if User Data is already backed up.
// If yes, will delete and create new one.
if (file_util::PathExists(backup_path))
file_util::Delete(backup_path.c_str(), true);
file_util::CopyDirectory(path, backup_path, true);
} else {
printf("Chrome is not installed. Will not take any backup\n");
}
}
int main(int argc, char** argv) {
// Check command line to decide if the tests should continue
// with cleaning the system or make a backup before continuing.
CommandLine::Init(argc, argv);
const CommandLine& command_line = *CommandLine::ForCurrentProcess();
if (command_line.HasSwitch(L"clean")) {
printf("Current version of Chrome will be uninstalled "
"from all levels before proceeding with tests.\n");
} else if (command_line.HasSwitch(L"backup")) {
BackUpProfile();
} else {
printf("This test needs command line Arguments.\n");
printf("Usage: mini_installer_tests.exe -{clean|backup}\n");
printf("Note: -clean arg will uninstall your chrome at all levels"
" and also delete profile.\n"
"-backup arg will make a copy of User Data before uninstalling"
" your chrome at all levels. The copy will be named as"
" User Data Copy.\n");
exit(1);
}
return TestSuite(argc, argv).Run();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLIndexTabStopEntryContext.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2006-06-19 18:41:49 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _XMLOFF_XMLINDEXTABSTOPENTRYCONTEXT_HXX_
#define _XMLOFF_XMLINDEXTABSTOPENTRYCONTEXT_HXX_
#ifndef _XMLOFF_XMLINDEXSIMPLEENTRYCONTEXT_HXX_
#include "XMLIndexSimpleEntryContext.hxx"
#endif
#ifndef _RTL_USTRING_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
namespace com { namespace sun { namespace star {
namespace xml { namespace sax { class XAttributeList; } }
} } }
class XMLIndexTemplateContext;
/**
* Import index entry templates
*/
class XMLIndexTabStopEntryContext : public XMLIndexSimpleEntryContext
{
::rtl::OUString sLeaderChar; /// fill ("leader") character
sal_Int32 nTabPosition; /// tab position
sal_Bool bTabPositionOK; /// is tab right aligned?
sal_Bool bTabRightAligned; /// is nTabPosition valid?
sal_Bool bLeaderCharOK; /// is sLeaderChar valid?
sal_Bool bWithTab; /// is tab char present? #i21237#
public:
TYPEINFO();
XMLIndexTabStopEntryContext(
SvXMLImport& rImport,
XMLIndexTemplateContext& rTemplate,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLocalName );
~XMLIndexTabStopEntryContext();
protected:
virtual void StartElement(
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList> & xAttrList);
/** fill property values for this template entry */
virtual void FillPropertyValues(
::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue> & rValues);
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.5.330); FILE MERGED 2008/04/01 16:10:09 thb 1.5.330.3: #i85898# Stripping all external header guards 2008/04/01 13:05:26 thb 1.5.330.2: #i85898# Stripping all external header guards 2008/03/31 16:28:34 rt 1.5.330.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: XMLIndexTabStopEntryContext.hxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _XMLOFF_XMLINDEXTABSTOPENTRYCONTEXT_HXX_
#define _XMLOFF_XMLINDEXTABSTOPENTRYCONTEXT_HXX_
#include "XMLIndexSimpleEntryContext.hxx"
#include <rtl/ustring.hxx>
#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/Sequence.h>
#include <com/sun/star/beans/PropertyValue.hpp>
namespace com { namespace sun { namespace star {
namespace xml { namespace sax { class XAttributeList; } }
} } }
class XMLIndexTemplateContext;
/**
* Import index entry templates
*/
class XMLIndexTabStopEntryContext : public XMLIndexSimpleEntryContext
{
::rtl::OUString sLeaderChar; /// fill ("leader") character
sal_Int32 nTabPosition; /// tab position
sal_Bool bTabPositionOK; /// is tab right aligned?
sal_Bool bTabRightAligned; /// is nTabPosition valid?
sal_Bool bLeaderCharOK; /// is sLeaderChar valid?
sal_Bool bWithTab; /// is tab char present? #i21237#
public:
TYPEINFO();
XMLIndexTabStopEntryContext(
SvXMLImport& rImport,
XMLIndexTemplateContext& rTemplate,
sal_uInt16 nPrfx,
const ::rtl::OUString& rLocalName );
~XMLIndexTabStopEntryContext();
protected:
virtual void StartElement(
const ::com::sun::star::uno::Reference<
::com::sun::star::xml::sax::XAttributeList> & xAttrList);
/** fill property values for this template entry */
virtual void FillPropertyValues(
::com::sun::star::uno::Sequence<
::com::sun::star::beans::PropertyValue> & rValues);
};
#endif
<|endoftext|> |
<commit_before>/* ************************************************************************
* Copyright 2018 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "rocsparse.hpp"
#include <rocsparse.h>
namespace rocsparse {
template <>
rocsparse_status rocsparse_axpyi(rocsparse_handle handle,
rocsparse_int nnz,
const float* alpha,
const float* x_val,
const rocsparse_int* x_ind,
float* y,
rocsparse_index_base idx_base)
{
return rocsparse_saxpyi(handle, nnz, alpha, x_val, x_ind, y, idx_base);
}
template <>
rocsparse_status rocsparse_axpyi(rocsparse_handle handle,
rocsparse_int nnz,
const double* alpha,
const double* x_val,
const rocsparse_int* x_ind,
double* y,
rocsparse_index_base idx_base)
{
return rocsparse_daxpyi(handle, nnz, alpha, x_val, x_ind, y, idx_base);
}
template <>
rocsparse_status rocsparse_doti(rocsparse_handle handle,
rocsparse_int nnz,
const float* x_val,
const rocsparse_int* x_ind,
const float* y,
float* result,
rocsparse_index_base idx_base)
{
return rocsparse_sdoti(handle, nnz, x_val, x_ind, y, result, idx_base);
}
template <>
rocsparse_status rocsparse_doti(rocsparse_handle handle,
rocsparse_int nnz,
const double* x_val,
const rocsparse_int* x_ind,
const double* y,
double* result,
rocsparse_index_base idx_base)
{
return rocsparse_ddoti(handle, nnz, x_val, x_ind, y, result, idx_base);
}
template <>
rocsparse_status rocsparse_gthr(rocsparse_handle handle,
rocsparse_int nnz,
const float* y,
float* x_val,
const rocsparse_int* x_ind,
rocsparse_index_base idx_base)
{
return rocsparse_sgthr(handle, nnz, y, x_val, x_ind, idx_base);
}
template <>
rocsparse_status rocsparse_gthr(rocsparse_handle handle,
rocsparse_int nnz,
const double* y,
double* x_val,
const rocsparse_int* x_ind,
rocsparse_index_base idx_base)
{
return rocsparse_dgthr(handle, nnz, y, x_val, x_ind, idx_base);
}
template <>
rocsparse_status rocsparse_gthrz(rocsparse_handle handle,
rocsparse_int nnz,
float* y,
float* x_val,
const rocsparse_int* x_ind,
rocsparse_index_base idx_base)
{
return rocsparse_sgthrz(handle, nnz, y, x_val, x_ind, idx_base);
}
template <>
rocsparse_status rocsparse_gthrz(rocsparse_handle handle,
rocsparse_int nnz,
double* y,
double* x_val,
const rocsparse_int* x_ind,
rocsparse_index_base idx_base)
{
return rocsparse_dgthrz(handle, nnz, y, x_val, x_ind, idx_base);
}
template <>
rocsparse_status rocsparse_roti(rocsparse_handle handle,
rocsparse_int nnz,
float* x_val,
const rocsparse_int* x_ind,
float* y,
const float* c,
const float* s,
rocsparse_index_base idx_base)
{
return rocsparse_sroti(handle, nnz, x_val, x_ind, y, c, s, idx_base);
}
template <>
rocsparse_status rocsparse_roti(rocsparse_handle handle,
rocsparse_int nnz,
double* x_val,
const rocsparse_int* x_ind,
double* y,
const double* c,
const double* s,
rocsparse_index_base idx_base)
{
return rocsparse_droti(handle, nnz, x_val, x_ind, y, c, s, idx_base);
}
template <>
rocsparse_status rocsparse_sctr(rocsparse_handle handle,
rocsparse_int nnz,
const float* x_val,
const rocsparse_int* x_ind,
float* y,
rocsparse_index_base idx_base)
{
return rocsparse_ssctr(handle, nnz, x_val, x_ind, y, idx_base);
}
template <>
rocsparse_status rocsparse_sctr(rocsparse_handle handle,
rocsparse_int nnz,
const double* x_val,
const rocsparse_int* x_ind,
double* y,
rocsparse_index_base idx_base)
{
return rocsparse_dsctr(handle, nnz, x_val, x_ind, y, idx_base);
}
template <>
rocsparse_status rocsparse_coomv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const float* alpha,
const rocsparse_mat_descr descr,
const float* coo_val,
const rocsparse_int* coo_row_ind,
const rocsparse_int* coo_col_ind,
const float* x,
const float* beta,
float* y)
{
return rocsparse_scoomv(
handle, trans, m, n, nnz, alpha, descr, coo_val, coo_row_ind, coo_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparse_coomv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const double* alpha,
const rocsparse_mat_descr descr,
const double* coo_val,
const rocsparse_int* coo_row_ind,
const rocsparse_int* coo_col_ind,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dcoomv(
handle, trans, m, n, nnz, alpha, descr, coo_val, coo_row_ind, coo_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparse_csrmv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const float* alpha,
const rocsparse_mat_descr descr,
const float* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
const float* x,
const float* beta,
float* y)
{
return rocsparse_scsrmv(
handle, trans, m, n, nnz, alpha, descr, csr_val, csr_row_ptr, csr_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparse_csrmv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const double* alpha,
const rocsparse_mat_descr descr,
const double* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dcsrmv(
handle, trans, m, n, nnz, alpha, descr, csr_val, csr_row_ptr, csr_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparse_ellmv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
const float* alpha,
const rocsparse_mat_descr descr,
const float* ell_val,
const rocsparse_int* ell_col_ind,
rocsparse_int ell_width,
const float* x,
const float* beta,
float* y)
{
return rocsparse_sellmv(
handle, trans, m, n, alpha, descr, ell_val, ell_col_ind, ell_width, x, beta, y);
}
template <>
rocsparse_status rocsparse_ellmv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
const double* alpha,
const rocsparse_mat_descr descr,
const double* ell_val,
const rocsparse_int* ell_col_ind,
rocsparse_int ell_width,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dellmv(
handle, trans, m, n, alpha, descr, ell_val, ell_col_ind, ell_width, x, beta, y);
}
template <>
rocsparse_status rocsparse_hybmv(rocsparse_handle handle,
rocsparse_operation trans,
const float* alpha,
const rocsparse_mat_descr descr,
const rocsparse_hyb_mat hyb,
const float* x,
const float* beta,
float* y)
{
return rocsparse_shybmv(handle, trans, alpha, descr, hyb, x, beta, y);
}
template <>
rocsparse_status rocsparse_hybmv(rocsparse_handle handle,
rocsparse_operation trans,
const double* alpha,
const rocsparse_mat_descr descr,
const rocsparse_hyb_mat hyb,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dhybmv(handle, trans, alpha, descr, hyb, x, beta, y);
}
template <>
rocsparse_status rocsparse_csr2csc(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const float* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
float* csc_val,
rocsparse_int* csc_row_ind,
rocsparse_int* csc_col_ptr,
rocsparse_action copy_values,
rocsparse_index_base idx_base,
void* temp_buffer)
{
return rocsparse_scsr2csc(handle, m, n, nnz, csr_val, csr_row_ptr, csr_col_ind, csc_val, csc_row_ind, csc_col_ptr, copy_values, idx_base, temp_buffer);
}
template <>
rocsparse_status rocsparse_csr2csc(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const double* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
double* csc_val,
rocsparse_int* csc_row_ind,
rocsparse_int* csc_col_ptr,
rocsparse_action copy_values,
rocsparse_index_base idx_base,
void* temp_buffer)
{
return rocsparse_dcsr2csc(handle, m, n, nnz, csr_val, csr_row_ptr, csr_col_ind, csc_val, csc_row_ind, csc_col_ptr, copy_values, idx_base, temp_buffer);
}
template <>
rocsparse_status rocsparse_csr2ell(rocsparse_handle handle,
rocsparse_int m,
const rocsparse_mat_descr csr_descr,
const float* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
const rocsparse_mat_descr ell_descr,
rocsparse_int ell_width,
float* ell_val,
rocsparse_int* ell_col_ind)
{
return rocsparse_scsr2ell(handle,
m,
csr_descr,
csr_val,
csr_row_ptr,
csr_col_ind,
ell_descr,
ell_width,
ell_val,
ell_col_ind);
}
template <>
rocsparse_status rocsparse_csr2ell(rocsparse_handle handle,
rocsparse_int m,
const rocsparse_mat_descr csr_descr,
const double* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
const rocsparse_mat_descr ell_descr,
rocsparse_int ell_width,
double* ell_val,
rocsparse_int* ell_col_ind)
{
return rocsparse_dcsr2ell(handle,
m,
csr_descr,
csr_val,
csr_row_ptr,
csr_col_ind,
ell_descr,
ell_width,
ell_val,
ell_col_ind);
}
template <>
rocsparse_status rocsparse_csr2hyb(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
const rocsparse_mat_descr descr,
const float* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
rocsparse_hyb_mat hyb,
rocsparse_int user_ell_width,
rocsparse_hyb_partition partition_type)
{
return rocsparse_scsr2hyb(handle,
m,
n,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
hyb,
user_ell_width,
partition_type);
}
template <>
rocsparse_status rocsparse_csr2hyb(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
const rocsparse_mat_descr descr,
const double* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
rocsparse_hyb_mat hyb,
rocsparse_int user_ell_width,
rocsparse_hyb_partition partition_type)
{
return rocsparse_dcsr2hyb(handle,
m,
n,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
hyb,
user_ell_width,
partition_type);
}
} // namespace rocsparse
<commit_msg>clang-format<commit_after>/* ************************************************************************
* Copyright 2018 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "rocsparse.hpp"
#include <rocsparse.h>
namespace rocsparse {
template <>
rocsparse_status rocsparse_axpyi(rocsparse_handle handle,
rocsparse_int nnz,
const float* alpha,
const float* x_val,
const rocsparse_int* x_ind,
float* y,
rocsparse_index_base idx_base)
{
return rocsparse_saxpyi(handle, nnz, alpha, x_val, x_ind, y, idx_base);
}
template <>
rocsparse_status rocsparse_axpyi(rocsparse_handle handle,
rocsparse_int nnz,
const double* alpha,
const double* x_val,
const rocsparse_int* x_ind,
double* y,
rocsparse_index_base idx_base)
{
return rocsparse_daxpyi(handle, nnz, alpha, x_val, x_ind, y, idx_base);
}
template <>
rocsparse_status rocsparse_doti(rocsparse_handle handle,
rocsparse_int nnz,
const float* x_val,
const rocsparse_int* x_ind,
const float* y,
float* result,
rocsparse_index_base idx_base)
{
return rocsparse_sdoti(handle, nnz, x_val, x_ind, y, result, idx_base);
}
template <>
rocsparse_status rocsparse_doti(rocsparse_handle handle,
rocsparse_int nnz,
const double* x_val,
const rocsparse_int* x_ind,
const double* y,
double* result,
rocsparse_index_base idx_base)
{
return rocsparse_ddoti(handle, nnz, x_val, x_ind, y, result, idx_base);
}
template <>
rocsparse_status rocsparse_gthr(rocsparse_handle handle,
rocsparse_int nnz,
const float* y,
float* x_val,
const rocsparse_int* x_ind,
rocsparse_index_base idx_base)
{
return rocsparse_sgthr(handle, nnz, y, x_val, x_ind, idx_base);
}
template <>
rocsparse_status rocsparse_gthr(rocsparse_handle handle,
rocsparse_int nnz,
const double* y,
double* x_val,
const rocsparse_int* x_ind,
rocsparse_index_base idx_base)
{
return rocsparse_dgthr(handle, nnz, y, x_val, x_ind, idx_base);
}
template <>
rocsparse_status rocsparse_gthrz(rocsparse_handle handle,
rocsparse_int nnz,
float* y,
float* x_val,
const rocsparse_int* x_ind,
rocsparse_index_base idx_base)
{
return rocsparse_sgthrz(handle, nnz, y, x_val, x_ind, idx_base);
}
template <>
rocsparse_status rocsparse_gthrz(rocsparse_handle handle,
rocsparse_int nnz,
double* y,
double* x_val,
const rocsparse_int* x_ind,
rocsparse_index_base idx_base)
{
return rocsparse_dgthrz(handle, nnz, y, x_val, x_ind, idx_base);
}
template <>
rocsparse_status rocsparse_roti(rocsparse_handle handle,
rocsparse_int nnz,
float* x_val,
const rocsparse_int* x_ind,
float* y,
const float* c,
const float* s,
rocsparse_index_base idx_base)
{
return rocsparse_sroti(handle, nnz, x_val, x_ind, y, c, s, idx_base);
}
template <>
rocsparse_status rocsparse_roti(rocsparse_handle handle,
rocsparse_int nnz,
double* x_val,
const rocsparse_int* x_ind,
double* y,
const double* c,
const double* s,
rocsparse_index_base idx_base)
{
return rocsparse_droti(handle, nnz, x_val, x_ind, y, c, s, idx_base);
}
template <>
rocsparse_status rocsparse_sctr(rocsparse_handle handle,
rocsparse_int nnz,
const float* x_val,
const rocsparse_int* x_ind,
float* y,
rocsparse_index_base idx_base)
{
return rocsparse_ssctr(handle, nnz, x_val, x_ind, y, idx_base);
}
template <>
rocsparse_status rocsparse_sctr(rocsparse_handle handle,
rocsparse_int nnz,
const double* x_val,
const rocsparse_int* x_ind,
double* y,
rocsparse_index_base idx_base)
{
return rocsparse_dsctr(handle, nnz, x_val, x_ind, y, idx_base);
}
template <>
rocsparse_status rocsparse_coomv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const float* alpha,
const rocsparse_mat_descr descr,
const float* coo_val,
const rocsparse_int* coo_row_ind,
const rocsparse_int* coo_col_ind,
const float* x,
const float* beta,
float* y)
{
return rocsparse_scoomv(
handle, trans, m, n, nnz, alpha, descr, coo_val, coo_row_ind, coo_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparse_coomv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const double* alpha,
const rocsparse_mat_descr descr,
const double* coo_val,
const rocsparse_int* coo_row_ind,
const rocsparse_int* coo_col_ind,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dcoomv(
handle, trans, m, n, nnz, alpha, descr, coo_val, coo_row_ind, coo_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparse_csrmv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const float* alpha,
const rocsparse_mat_descr descr,
const float* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
const float* x,
const float* beta,
float* y)
{
return rocsparse_scsrmv(
handle, trans, m, n, nnz, alpha, descr, csr_val, csr_row_ptr, csr_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparse_csrmv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const double* alpha,
const rocsparse_mat_descr descr,
const double* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dcsrmv(
handle, trans, m, n, nnz, alpha, descr, csr_val, csr_row_ptr, csr_col_ind, x, beta, y);
}
template <>
rocsparse_status rocsparse_ellmv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
const float* alpha,
const rocsparse_mat_descr descr,
const float* ell_val,
const rocsparse_int* ell_col_ind,
rocsparse_int ell_width,
const float* x,
const float* beta,
float* y)
{
return rocsparse_sellmv(
handle, trans, m, n, alpha, descr, ell_val, ell_col_ind, ell_width, x, beta, y);
}
template <>
rocsparse_status rocsparse_ellmv(rocsparse_handle handle,
rocsparse_operation trans,
rocsparse_int m,
rocsparse_int n,
const double* alpha,
const rocsparse_mat_descr descr,
const double* ell_val,
const rocsparse_int* ell_col_ind,
rocsparse_int ell_width,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dellmv(
handle, trans, m, n, alpha, descr, ell_val, ell_col_ind, ell_width, x, beta, y);
}
template <>
rocsparse_status rocsparse_hybmv(rocsparse_handle handle,
rocsparse_operation trans,
const float* alpha,
const rocsparse_mat_descr descr,
const rocsparse_hyb_mat hyb,
const float* x,
const float* beta,
float* y)
{
return rocsparse_shybmv(handle, trans, alpha, descr, hyb, x, beta, y);
}
template <>
rocsparse_status rocsparse_hybmv(rocsparse_handle handle,
rocsparse_operation trans,
const double* alpha,
const rocsparse_mat_descr descr,
const rocsparse_hyb_mat hyb,
const double* x,
const double* beta,
double* y)
{
return rocsparse_dhybmv(handle, trans, alpha, descr, hyb, x, beta, y);
}
template <>
rocsparse_status rocsparse_csr2csc(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const float* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
float* csc_val,
rocsparse_int* csc_row_ind,
rocsparse_int* csc_col_ptr,
rocsparse_action copy_values,
rocsparse_index_base idx_base,
void* temp_buffer)
{
return rocsparse_scsr2csc(handle,
m,
n,
nnz,
csr_val,
csr_row_ptr,
csr_col_ind,
csc_val,
csc_row_ind,
csc_col_ptr,
copy_values,
idx_base,
temp_buffer);
}
template <>
rocsparse_status rocsparse_csr2csc(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
rocsparse_int nnz,
const double* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
double* csc_val,
rocsparse_int* csc_row_ind,
rocsparse_int* csc_col_ptr,
rocsparse_action copy_values,
rocsparse_index_base idx_base,
void* temp_buffer)
{
return rocsparse_dcsr2csc(handle,
m,
n,
nnz,
csr_val,
csr_row_ptr,
csr_col_ind,
csc_val,
csc_row_ind,
csc_col_ptr,
copy_values,
idx_base,
temp_buffer);
}
template <>
rocsparse_status rocsparse_csr2ell(rocsparse_handle handle,
rocsparse_int m,
const rocsparse_mat_descr csr_descr,
const float* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
const rocsparse_mat_descr ell_descr,
rocsparse_int ell_width,
float* ell_val,
rocsparse_int* ell_col_ind)
{
return rocsparse_scsr2ell(handle,
m,
csr_descr,
csr_val,
csr_row_ptr,
csr_col_ind,
ell_descr,
ell_width,
ell_val,
ell_col_ind);
}
template <>
rocsparse_status rocsparse_csr2ell(rocsparse_handle handle,
rocsparse_int m,
const rocsparse_mat_descr csr_descr,
const double* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
const rocsparse_mat_descr ell_descr,
rocsparse_int ell_width,
double* ell_val,
rocsparse_int* ell_col_ind)
{
return rocsparse_dcsr2ell(handle,
m,
csr_descr,
csr_val,
csr_row_ptr,
csr_col_ind,
ell_descr,
ell_width,
ell_val,
ell_col_ind);
}
template <>
rocsparse_status rocsparse_csr2hyb(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
const rocsparse_mat_descr descr,
const float* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
rocsparse_hyb_mat hyb,
rocsparse_int user_ell_width,
rocsparse_hyb_partition partition_type)
{
return rocsparse_scsr2hyb(handle,
m,
n,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
hyb,
user_ell_width,
partition_type);
}
template <>
rocsparse_status rocsparse_csr2hyb(rocsparse_handle handle,
rocsparse_int m,
rocsparse_int n,
const rocsparse_mat_descr descr,
const double* csr_val,
const rocsparse_int* csr_row_ptr,
const rocsparse_int* csr_col_ind,
rocsparse_hyb_mat hyb,
rocsparse_int user_ell_width,
rocsparse_hyb_partition partition_type)
{
return rocsparse_dcsr2hyb(handle,
m,
n,
descr,
csr_val,
csr_row_ptr,
csr_col_ind,
hyb,
user_ell_width,
partition_type);
}
} // namespace rocsparse
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "code/ylikuutio/geometry/line2D.hpp"
#include "code/ylikuutio/linear_algebra/matrix.hpp"
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <vector> // std::vector
TEST(line2D_must_be_defined_as_expected, line2D_std_vector_float_x1_0_y1_0_x2_1_y2_1)
{
std::vector<float> point1;
point1.push_back(0.0f); // x = 0.0
point1.push_back(0.0f); // y = 0.0
std::vector<float> point2;
point2.push_back(1.0f); // x = 1.0
point2.push_back(1.0f); // y = 1.0
geometry::Line2D line1 = geometry::Line2D(point1, point2);
ASSERT_EQ(line1.x1, 0.0f);
ASSERT_EQ(line1.y1, 0.0f);
ASSERT_EQ(line1.x2, 1.0f);
ASSERT_EQ(line1.y2, 1.0f);
ASSERT_EQ(line1.x1_minus_x2, -1.0f);
ASSERT_EQ(line1.y1_minus_y2, -1.0f);
ASSERT_EQ(line1.determinant, 0.0f);
geometry::Line2D line2 = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 1.0f });
ASSERT_EQ(line2.determinant, 0.0f);
}
TEST(line2D_must_be_defined_as_expected, line2D_glm_vec2_x1_0_y1_0_x2_1_y2_1)
{
glm::vec2 point1 = glm::vec2(0.0f, 0.0f); // x = 0.0, y = 0.0
glm::vec2 point2 = glm::vec2(1.0f, 1.0f); // x = 1.0, y = 1.0
geometry::Line2D line1 = geometry::Line2D(point1, point2);
ASSERT_EQ(line1.x1, 0.0f);
ASSERT_EQ(line1.y1, 0.0f);
ASSERT_EQ(line1.x2, 1.0f);
ASSERT_EQ(line1.y2, 1.0f);
ASSERT_EQ(line1.x1_minus_x2, -1.0f);
ASSERT_EQ(line1.y1_minus_y2, -1.0f);
ASSERT_EQ(line1.determinant, 0.0f);
}
TEST(lines2D_defined_with_std_vector_float_and_glm_vec2_must_be_identical, x1_0_y1_0_x2_1_y2_1)
{
geometry::Line2D line_std_vector_float = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 1.0f });
geometry::Line2D line_glm_vec2 = geometry::Line2D(glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 1.0f));
ASSERT_TRUE(line_std_vector_float.is_identical_with(&line_glm_vec2));
ASSERT_TRUE(line_glm_vec2.is_identical_with(&line_std_vector_float));
}
TEST(line2D_must_be_defined_as_expected, line2D_x1_340_y1_150_x2_100_y2_50)
{
std::vector<float> point1;
point1.push_back(340.0f); // x = 340.0
point1.push_back(150.0f); // y = 150.0
std::vector<float> point2;
point2.push_back(100.0f); // x = 100.0
point2.push_back(50.0f); // y = 50.0
geometry::Line2D* line1 = new geometry::Line2D(point1, point2);
ASSERT_EQ(line1->determinant, 2000.0f);
delete line1;
}
<commit_msg>Edited `TEST(line2D_must_be_defined_as_expected`.<commit_after>#include "gtest/gtest.h"
#include "code/ylikuutio/geometry/line2D.hpp"
#include "code/ylikuutio/linear_algebra/matrix.hpp"
// Include GLM
#ifndef __GLM_GLM_HPP_INCLUDED
#define __GLM_GLM_HPP_INCLUDED
#include <glm/glm.hpp> // glm
#endif
// Include standard headers
#include <iostream> // std::cout, std::cin, std::cerr
#include <vector> // std::vector
TEST(line2D_must_be_defined_as_expected, line2D_std_vector_float_x1_0_y1_0_x2_1_y2_1)
{
std::vector<float> point1;
point1.push_back(0.0f); // x = 0.0
point1.push_back(0.0f); // y = 0.0
std::vector<float> point2;
point2.push_back(1.0f); // x = 1.0
point2.push_back(1.0f); // y = 1.0
geometry::Line2D line1 = geometry::Line2D(point1, point2);
ASSERT_EQ(line1.x1, 0.0f);
ASSERT_EQ(line1.y1, 0.0f);
ASSERT_EQ(line1.x2, 1.0f);
ASSERT_EQ(line1.y2, 1.0f);
ASSERT_EQ(line1.x1_minus_x2, -1.0f);
ASSERT_EQ(line1.y1_minus_y2, -1.0f);
ASSERT_EQ(line1.determinant, 0.0f);
geometry::Line2D line2 = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 1.0f });
ASSERT_EQ(line2.determinant, 0.0f);
}
TEST(line2D_must_be_defined_as_expected, line2D_glm_vec2_x1_0_y1_0_x2_1_y2_1)
{
glm::vec2 point1 = glm::vec2(0.0f, 0.0f); // x = 0.0, y = 0.0
glm::vec2 point2 = glm::vec2(1.0f, 1.0f); // x = 1.0, y = 1.0
geometry::Line2D line1 = geometry::Line2D(point1, point2);
ASSERT_EQ(line1.x1, 0.0f);
ASSERT_EQ(line1.y1, 0.0f);
ASSERT_EQ(line1.x2, 1.0f);
ASSERT_EQ(line1.y2, 1.0f);
ASSERT_EQ(line1.x1_minus_x2, -1.0f);
ASSERT_EQ(line1.y1_minus_y2, -1.0f);
ASSERT_EQ(line1.determinant, 0.0f);
}
TEST(lines2D_defined_with_std_vector_float_and_glm_vec2_must_be_identical, x1_0_y1_0_x2_1_y2_1)
{
geometry::Line2D line_std_vector_float = geometry::Line2D(std::vector<float>{ 0.0f, 0.0f }, std::vector<float>{ 1.0f, 1.0f });
geometry::Line2D line_glm_vec2 = geometry::Line2D(glm::vec2(0.0f, 0.0f), glm::vec2(1.0f, 1.0f));
ASSERT_TRUE(line_std_vector_float.is_identical_with(&line_glm_vec2));
ASSERT_TRUE(line_glm_vec2.is_identical_with(&line_std_vector_float));
}
TEST(line2D_must_be_defined_as_expected, line2D_x1_340_y1_150_x2_100_y2_50)
{
std::vector<float> point1;
float x1 = 340.0f;
float y1 = 150.0f;
point1.push_back(x1); // x = 340.0
point1.push_back(y1); // y = 150.0
std::vector<float> point2;
float x2 = 100.0f;
float y2 = 50.0f;
point2.push_back(x2); // x = 100.0
point2.push_back(y2); // y = 50.0
geometry::Line2D* line1 = new geometry::Line2D(point1, point2);
geometry::Line2D* line2 = new geometry::Line2D(std::vector<float>{ x1, y1 }, std::vector<float>{ x2, y2 });
ASSERT_TRUE(line1->is_identical_with(line2));
ASSERT_EQ(line1->determinant, 2000.0f);
delete line1;
delete line2;
}
<|endoftext|> |
<commit_before>#include "kernel.h"
#include "raster.h"
#include "connectorinterface.h"
#include "symboltable.h"
#include "ilwisoperation.h"
using namespace Ilwis;
OperationHelper::OperationHelper()
{
}
Box3D<qint32> OperationHelper::initialize(const IGridCoverage &inputGC, IGridCoverage &outputGC, const Parameter& parm, quint64 what)
{
Resource resource(itGRIDCOVERAGE);
Size sz = inputGC->size();
Box3D<qint32> box(sz);
if ( what & itGRIDSIZE) {
resource.addProperty("size", IVARIANT(sz));
}
if ( what & itENVELOPE) {
if ( box.isNull() || !box.isValid()) {
sz = inputGC->size();
box = Box3D<qint32>(sz);
}
Box2D<double> bounds = inputGC->georeference()->pixel2Coord(box);
resource.addProperty("envelope", IVARIANT(bounds));
}
if ( what & itCOORDSYSTEM) {
resource.addProperty("coordinatesystem", IVARIANT(inputGC->coordinateSystem()));
}
if ( what & itGEOREF) {
if ( box.isNull() || !box.isValid()) {
sz = inputGC->size();
box = Box3D<qint32>(sz);
}
if ( sz.xsize() == box.xlength() && sz.ysize() == box.ylength())
resource.addProperty("georeference", IVARIANT(inputGC->georeference()));
}
if ( what & itDOMAIN) {
resource.addProperty("domain", IVARIANT(inputGC->datadef().domain()));
}
resource.prepare();
outputGC.prepare(resource);
if ( what & itTABLE) {
if ( inputGC->attributeTable(itGRIDCOVERAGE).isValid()) {
if ( inputGC->datadef().domain() == outputGC->datadef().domain()) {
if ( outputGC.isValid())
outputGC->attributeTable(itGRIDCOVERAGE,inputGC->attributeTable(itGRIDCOVERAGE));
}
}
}
return box;
}
IIlwisObject OperationHelper::initialize(const IIlwisObject &inputObject, IlwisTypes tp, const Parameter& parm, quint64 what)
{
Resource resource(tp);
if (inputObject->ilwisType() & itCOVERAGE) {
ICoverage covInput = inputObject.get<Coverage>();
if (inputObject->ilwisType() == itGRIDCOVERAGE) {
IGridCoverage gcInput = inputObject.get<GridCoverage>();
if ( what & itGRIDSIZE) {
Size sz = gcInput->size();
Box3D<qint32> box(sz);
resource.addProperty("size", IVARIANT(box.size()));
}
if ( what & itGEOREF) {
resource.addProperty("georeference", IVARIANT(gcInput->georeference()));
}
}
if ( what & itENVELOPE) {
Box2D<double> bounds = covInput->envelope();
resource.addProperty("envelope", IVARIANT(bounds));
}
if ( what & itCOORDSYSTEM) {
resource.addProperty("coordinatesystem", IVARIANT(covInput->coordinateSystem()));
}
if ( what & itDOMAIN) {
resource.addProperty("domain", IVARIANT(covInput->datadef().domain()));
}
}
resource.prepare();
IIlwisObject obj;
obj.prepare(resource);
if (inputObject->ilwisType() & itCOVERAGE) {
ICoverage covInput = inputObject.get<Coverage>();
ICoverage covOutput = inputObject.get<Coverage>();
if (inputObject->ilwisType() == itGRIDCOVERAGE) {
//IGridCoverage gcInput = inputObject.get<GridCoverage>();
}
if ( what & itTABLE) {
if ( covInput->attributeTable(itGRIDCOVERAGE).isValid()) {
if ( covInput->datadef().domain() == covOutput->datadef().domain()) {
if ( covOutput.isValid())
covOutput->attributeTable(tp,covInput->attributeTable(tp));
}
}
}
}
return obj;
}
int OperationHelper::subdivideTasks(ExecutionContext *ctx,const IGridCoverage& gcov, const Box3D<qint32> &bnds, std::vector<Box3D<qint32> > &boxes)
{
if ( !gcov.isValid() || gcov->size().isNull() || gcov->size().ysize() == 0) {
return ERROR1(ERR_NO_INITIALIZED_1, "Grid size");
return iUNDEF;
}
int cores = std::min(QThread::idealThreadCount(),gcov->size().ysize());
if (gcov->size().totalSize() < 10000)
cores = 1;
boxes.clear();
boxes.resize(cores);
Box3D<qint32> bounds = bnds;
if ( bounds.isNull())
bounds = Box3D<qint32>(gcov->size());
int left = 0; //bounds.min_corner().x();
int right = bounds.size().xsize();
int top = bounds.size().ysize();
int step = bounds.size().ysize() / cores;
int currentY = 0;
for(int i=0 ; i < cores; ++i){
Box3D<qint32> smallBox(Pixel(left, currentY), Pixel(right - 1, std::min(top - 1,currentY + step)) );
boxes[i] = smallBox;
currentY = currentY + step ;
}
return cores;
}
<commit_msg>support for disabling multithreading<commit_after>#include "kernel.h"
#include "raster.h"
#include "connectorinterface.h"
#include "symboltable.h"
#include "ilwisoperation.h"
using namespace Ilwis;
OperationHelper::OperationHelper()
{
}
Box3D<qint32> OperationHelper::initialize(const IGridCoverage &inputGC, IGridCoverage &outputGC, const Parameter& parm, quint64 what)
{
Resource resource(itGRIDCOVERAGE);
Size sz = inputGC->size();
Box3D<qint32> box(sz);
if ( what & itGRIDSIZE) {
resource.addProperty("size", IVARIANT(sz));
}
if ( what & itENVELOPE) {
if ( box.isNull() || !box.isValid()) {
sz = inputGC->size();
box = Box3D<qint32>(sz);
}
Box2D<double> bounds = inputGC->georeference()->pixel2Coord(box);
resource.addProperty("envelope", IVARIANT(bounds));
}
if ( what & itCOORDSYSTEM) {
resource.addProperty("coordinatesystem", IVARIANT(inputGC->coordinateSystem()));
}
if ( what & itGEOREF) {
if ( box.isNull() || !box.isValid()) {
sz = inputGC->size();
box = Box3D<qint32>(sz);
}
if ( sz.xsize() == box.xlength() && sz.ysize() == box.ylength())
resource.addProperty("georeference", IVARIANT(inputGC->georeference()));
}
if ( what & itDOMAIN) {
resource.addProperty("domain", IVARIANT(inputGC->datadef().domain()));
}
resource.prepare();
outputGC.prepare(resource);
if ( what & itTABLE) {
if ( inputGC->attributeTable(itGRIDCOVERAGE).isValid()) {
if ( inputGC->datadef().domain() == outputGC->datadef().domain()) {
if ( outputGC.isValid())
outputGC->attributeTable(itGRIDCOVERAGE,inputGC->attributeTable(itGRIDCOVERAGE));
}
}
}
return box;
}
IIlwisObject OperationHelper::initialize(const IIlwisObject &inputObject, IlwisTypes tp, const Parameter& parm, quint64 what)
{
Resource resource(tp);
if (inputObject->ilwisType() & itCOVERAGE) {
ICoverage covInput = inputObject.get<Coverage>();
if (inputObject->ilwisType() == itGRIDCOVERAGE) {
IGridCoverage gcInput = inputObject.get<GridCoverage>();
if ( what & itGRIDSIZE) {
Size sz = gcInput->size();
Box3D<qint32> box(sz);
resource.addProperty("size", IVARIANT(box.size()));
}
if ( what & itGEOREF) {
resource.addProperty("georeference", IVARIANT(gcInput->georeference()));
}
}
if ( what & itENVELOPE) {
Box2D<double> bounds = covInput->envelope();
resource.addProperty("envelope", IVARIANT(bounds));
}
if ( what & itCOORDSYSTEM) {
resource.addProperty("coordinatesystem", IVARIANT(covInput->coordinateSystem()));
}
if ( what & itDOMAIN) {
resource.addProperty("domain", IVARIANT(covInput->datadef().domain()));
}
}
resource.prepare();
IIlwisObject obj;
obj.prepare(resource);
if (inputObject->ilwisType() & itCOVERAGE) {
ICoverage covInput = inputObject.get<Coverage>();
ICoverage covOutput = inputObject.get<Coverage>();
if (inputObject->ilwisType() == itGRIDCOVERAGE) {
//IGridCoverage gcInput = inputObject.get<GridCoverage>();
}
if ( what & itTABLE) {
if ( covInput->attributeTable(itGRIDCOVERAGE).isValid()) {
if ( covInput->datadef().domain() == covOutput->datadef().domain()) {
if ( covOutput.isValid())
covOutput->attributeTable(tp,covInput->attributeTable(tp));
}
}
}
}
return obj;
}
int OperationHelper::subdivideTasks(ExecutionContext *ctx,const IGridCoverage& gcov, const Box3D<qint32> &bnds, std::vector<Box3D<qint32> > &boxes)
{
if ( !gcov.isValid() || gcov->size().isNull() || gcov->size().ysize() == 0) {
return ERROR1(ERR_NO_INITIALIZED_1, "Grid size");
return iUNDEF;
}
int cores = std::min(QThread::idealThreadCount(),gcov->size().ysize());
if (gcov->size().totalSize() < 10000 || ctx->_threaded == false)
cores = 1;
boxes.clear();
boxes.resize(cores);
Box3D<qint32> bounds = bnds;
if ( bounds.isNull())
bounds = Box3D<qint32>(gcov->size());
int left = 0; //bounds.min_corner().x();
int right = bounds.size().xsize();
int top = bounds.size().ysize();
int step = bounds.size().ysize() / cores;
int currentY = 0;
for(int i=0 ; i < cores; ++i){
Box3D<qint32> smallBox(Pixel(left, currentY), Pixel(right - 1, std::min(top - 1,currentY + step)) );
boxes[i] = smallBox;
currentY = currentY + step ;
}
return cores;
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// 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.
// This file tests the cpu_operations.cc DotProduct() function. First, it tests
// the functionality to ensure the dot product works properly by manually
// calculating the dot product and comparing it to the result of the function
// which calculated dot product with the Eigen built-in functionality. Then
// the two cases where incorrect function uses will result in fatal error are
// tested. This involves trying to calculate the dot product of two vectors of
// different size or trying to calculate the dot product of empty vectors.
#include <stdio.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/vector.h"
template<class T>
class DotProductTest : public ::testing::Test {
public:
Nice::Vector<T> vec1;
Nice::Vector<T> vec2;
T result;
void DotProd() {
result = Nice::CpuOperations<T>::DotProduct(this->vec1, this->vec2);
}
};
typedef ::testing::Types<int, float, double> MyTypes;
TYPED_TEST_CASE(DotProductTest, MyTypes);
TYPED_TEST(DotProductTest, DotProductFunctionality) {
int vec_size = 15;
this->vec1.setRandom(vec_size);
this->vec2.setRandom(vec_size);
TypeParam correct = 0;
for (int i = 0; i < vec_size; ++i)
correct += (this->vec1[i]*this->vec2[i]);
this->DotProd();
EXPECT_EQ(this->result, correct);
}
TYPED_TEST(DotProductTest, DifferentSizeVectors) {
this->vec1.setRandom(4);
this->vec2.setRandom(2);
ASSERT_DEATH(this->DotProd(), ".*");
}
TYPED_TEST(DotProductTest, EmptyVectors) {
ASSERT_DEATH(this->DotProd(), ".*");
}
<commit_msg>delete this-> for class member method<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2016 Northeastern University
//
// 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.
// This file tests the cpu_operations.cc DotProduct() function. First, it tests
// the functionality to ensure the dot product works properly by manually
// calculating the dot product and comparing it to the result of the function
// which calculated dot product with the Eigen built-in functionality. Then
// the two cases where incorrect function uses will result in fatal error are
// tested. This involves trying to calculate the dot product of two vectors of
// different size or trying to calculate the dot product of empty vectors.
#include <stdio.h>
#include <iostream>
#include "Eigen/Dense"
#include "gtest/gtest.h"
#include "include/cpu_operations.h"
#include "include/vector.h"
template<class T>
class DotProductTest : public ::testing::Test {
public:
Nice::Vector<T> vec1;
Nice::Vector<T> vec2;
T result;
void DotProd() {
result = Nice::CpuOperations<T>::DotProduct(vec1, vec2);
}
};
typedef ::testing::Types<int, float, double> MyTypes;
TYPED_TEST_CASE(DotProductTest, MyTypes);
TYPED_TEST(DotProductTest, DotProductFunctionality) {
int vec_size = 15;
this->vec1.setRandom(vec_size);
this->vec2.setRandom(vec_size);
TypeParam correct = 0;
for (int i = 0; i < vec_size; ++i)
correct += (this->vec1[i]*this->vec2[i]);
this->DotProd();
EXPECT_EQ(this->result, correct);
}
TYPED_TEST(DotProductTest, DifferentSizeVectors) {
this->vec1.setRandom(4);
this->vec2.setRandom(2);
ASSERT_DEATH(this->DotProd(), ".*");
}
TYPED_TEST(DotProductTest, EmptyVectors) {
ASSERT_DEATH(this->DotProd(), ".*");
}
<|endoftext|> |
<commit_before>/// COMPONENT
#include <csapex/model/node.h>
/// COMPONENT
#include <csapex_vision/roi_message.h>
#include <csapex_vision/cv_mat_message.h>
#include <csapex_core_plugins/vector_message.h>
/// PROJECT
#include <utils_param/range_parameter.h>
#include <utils_param/parameter_factory.h>
#include <csapex/msg/io.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
namespace csapex {
using namespace connection_types;
class GridArrangedRois : public csapex::Node
{
public:
GridArrangedRois()
{
}
public:
virtual void setup(csapex::NodeModifier& node_modifier) override
{
input_ = node_modifier.addInput<CvMatMessage>("Image");
output_ = node_modifier.addOutput<VectorMessage, RoiMessage>("ROIs");
}
virtual void setupParameters(Parameterizable ¶meters) override
{
parameters.addParameter(param::ParameterFactory::declareRange("dimension x", 1, 1000, 64, 1));
parameters.addParameter(param::ParameterFactory::declareRange("dimension y", 1, 1000, 48, 1));
parameters.addParameter(param::ParameterFactory::declareColorParameter("color", 255,0,0));
}
virtual void process() override
{
CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
VectorMessage::Ptr out(VectorMessage::make<RoiMessage>());
int dim_x = readParameter<int>("dimension x");
int dim_y = readParameter<int>("dimension y");
int cell_height = in->value.rows / dim_y;
int rest_height = in->value.rows % dim_y;
int cell_width = in->value.cols / dim_x;
int rest_witdh = in->value.cols % dim_x;
const std::vector<int>& c = readParameter<std::vector<int> >("color");
cv::Scalar color = cv::Scalar(c[2], c[1], c[0]);
cv::Rect rect;
for(int i = 0 ; i < dim_y ; ++i) {
for(int j = 0 ; j < dim_x ; ++j) {
RoiMessage::Ptr roi(new RoiMessage);
rect.x = cell_width * j;
rect.y = cell_height * i;
rect.width = cell_width + ((j == dim_x - 1) ? rest_witdh : 0);
rect.height = cell_height + ((i == dim_y - 1) ? rest_height : 0);
roi->value.setRect(rect);
roi->value.setColor(color);
out->value.push_back(roi);
}
}
msg::publish(output_, out);
}
private:
Input* input_;
Output* output_;
};
}
CSAPEX_REGISTER_CLASS(csapex::GridArrangedRois, csapex::Node)
<commit_msg>grid arranged roi class<commit_after>/// COMPONENT
#include <csapex/model/node.h>
/// COMPONENT
#include <csapex_vision/roi_message.h>
#include <csapex_vision/cv_mat_message.h>
#include <csapex_core_plugins/vector_message.h>
/// PROJECT
#include <utils_param/range_parameter.h>
#include <utils_param/parameter_factory.h>
#include <csapex/msg/io.h>
#include <csapex/model/node_modifier.h>
#include <csapex/utility/register_apex_plugin.h>
namespace csapex {
using namespace connection_types;
class GridArrangedRois : public csapex::Node
{
public:
GridArrangedRois()
{
}
public:
virtual void setup(csapex::NodeModifier& node_modifier) override
{
input_ = node_modifier.addInput<CvMatMessage>("Image");
output_ = node_modifier.addOutput<VectorMessage, RoiMessage>("ROIs");
}
virtual void setupParameters(Parameterizable ¶meters) override
{
parameters.addParameter(param::ParameterFactory::declareRange("dimension x", 1, 1000, 64, 1));
parameters.addParameter(param::ParameterFactory::declareRange("dimension y", 1, 1000, 48, 1));
parameters.addParameter(param::ParameterFactory::declareRange("class id", -1, 255, -1, 1));
parameters.addParameter(param::ParameterFactory::declareColorParameter("color", 255,0,0));
}
virtual void process() override
{
CvMatMessage::ConstPtr in = msg::getMessage<connection_types::CvMatMessage>(input_);
VectorMessage::Ptr out(VectorMessage::make<RoiMessage>());
int dim_x = readParameter<int>("dimension x");
int dim_y = readParameter<int>("dimension y");
int class_id = readParameter<int>("class id");
const std::vector<int>& c = readParameter<std::vector<int> >("color");
cv::Scalar color = cv::Scalar(c[2], c[1], c[0]);
int cell_height = in->value.rows / dim_y;
int rest_height = in->value.rows % dim_y;
int cell_width = in->value.cols / dim_x;
int rest_witdh = in->value.cols % dim_x;
cv::Rect rect;
for(int i = 0 ; i < dim_y ; ++i) {
for(int j = 0 ; j < dim_x ; ++j) {
RoiMessage::Ptr roi(new RoiMessage);
rect.x = cell_width * j;
rect.y = cell_height * i;
rect.width = cell_width + ((j == dim_x - 1) ? rest_witdh : 0);
rect.height = cell_height + ((i == dim_y - 1) ? rest_height : 0);
roi->value.setRect(rect);
roi->value.setColor(color);
roi->value.setClassification(class_id);
out->value.push_back(roi);
}
}
msg::publish(output_, out);
}
private:
Input* input_;
Output* output_;
};
}
CSAPEX_REGISTER_CLASS(csapex::GridArrangedRois, csapex::Node)
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// multibip32.cpp
//
// Copyright (c) 2014 Eric Lombrozo
//
// All Rights Reserved.
//
#include <CoinCore/hdkeys.h>
#include <CoinCore/Base58Check.h>
#include <CoinQ/CoinQ_script.h>
#include <stdutils/uchar_vector.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
using namespace Coin;
using namespace CoinQ::Script;
using namespace std;
const unsigned char ADDRESS_VERSIONS[] = { 0x00, 0x05 };
int main(int argc, char* argv[])
{
if (argc < 4 || argc % 2) // Parameter count must be even
{
cerr << "# Usage: " << argv[0] << " <minsigs> <master key 1> <path 1> ... [master key n] [path n]" << endl;
return -1;
}
try
{
uint32_t minsigs = strtoul(argv[1], NULL, 10);
vector<bytes_t> pubkeys;
for (size_t i = 2; i < argc; i+=2)
{
bytes_t extkey;
if (!fromBase58Check(string(argv[i]), extkey))
{
stringstream err;
err << "Invalid master key base58: " << argv[i];
throw runtime_error(err.str());
}
HDKeychain keychain(extkey);
keychain = keychain.getChild(string(argv[i+1]));
pubkeys.push_back(keychain.pubkey());
}
Script script(Script::PAY_TO_MULTISIG_SCRIPT_HASH, minsigs, pubkeys);
uchar_vector txoutscript = script.txoutscript();
cout << "TxOut script: " << txoutscript.getHex() << endl;
cout << "Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl;
}
catch (const exception& e)
{
cerr << "Error: " << e.what() << endl;
return -2;
}
return 0;
}
<commit_msg>Two usages for multibip32 tool - the first one just shows the address and pubkey for a single BIP32 master key child.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// multibip32.cpp
//
// Copyright (c) 2014 Eric Lombrozo
//
// All Rights Reserved.
//
#include <CoinCore/hdkeys.h>
#include <CoinCore/Base58Check.h>
#include <CoinQ/CoinQ_script.h>
#include <stdutils/uchar_vector.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
using namespace Coin;
using namespace CoinQ::Script;
using namespace std;
const unsigned char ADDRESS_VERSIONS[] = { 0x00, 0x05 };
void showUsage(char* argv[])
{
cerr << "# Usage 1: " << argv[0] << " <master key> <path>" << endl;
cerr << "# Usage 2: " << argv[0] << " <minsigs> <master key 1> <path 1> ... [master key n] [path n]" << endl;
}
int main(int argc, char* argv[])
{
if (argc < 3)
{
showUsage(argv);
return -1;
}
try
{
if (argc == 3)
{
bytes_t extkey;
if (!fromBase58Check(string(argv[1]), extkey)) throw runtime_error("Invalid master key base58.");
HDKeychain keychain(extkey);
keychain = keychain.getChild(string(argv[2]));
uchar_vector pubkey = keychain.pubkey();
vector<bytes_t> pubkeys;
pubkeys.push_back(pubkey);
Script script(Script::PAY_TO_PUBKEY_HASH, 1, pubkeys);
uchar_vector txoutscript = script.txoutscript();
cout << "TxOut script: " << txoutscript.getHex() << endl;
cout << "Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl;
cout << "Public key: " << pubkey.getHex() << endl;
return 0;
}
if (argc % 2)
{
showUsage(argv);
return -1;
}
uint32_t minsigs = strtoul(argv[1], NULL, 10);
vector<bytes_t> pubkeys;
for (size_t i = 2; i < argc; i+=2)
{
bytes_t extkey;
if (!fromBase58Check(string(argv[i]), extkey))
{
stringstream err;
err << "Invalid master key base58: " << argv[i];
throw runtime_error(err.str());
}
HDKeychain keychain(extkey);
keychain = keychain.getChild(string(argv[i+1]));
pubkeys.push_back(keychain.pubkey());
}
//sort(pubkeys.begin(), pubkeys.end());
Script script(Script::PAY_TO_MULTISIG_SCRIPT_HASH, minsigs, pubkeys);
uchar_vector txoutscript = script.txoutscript();
cout << "TxOut script: " << txoutscript.getHex() << endl;
cout << "Address: " << getAddressForTxOutScript(txoutscript, ADDRESS_VERSIONS) << endl;
}
catch (const exception& e)
{
cerr << "Error: " << e.what() << endl;
return -2;
}
return 0;
}
<|endoftext|> |
<commit_before>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
# define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING 0
#endif
#include <map>
#include <algorithm>
#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/la/solver.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/pymor/operators/base.hh>
#include <dune/pymor/operators/affine.hh>
#include <dune/pymor/functionals/affine.hh>
#include <dune/gdt/discretefunction/default.hh>
#include "interfaces.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Discretizations {
// forward
template< class ImpTraits >
class ContainerBasedDefault;
namespace internal {
template< class MatrixImp, class VectorImp >
class ContainerBasedDefaultTraits
{
public:
typedef MatrixImp MatrixType;
typedef VectorImp VectorType;
typedef Pymor::Operators::LinearAffinelyDecomposedContainerBased< MatrixType, VectorType > OperatorType;
typedef OperatorType ProductType;
typedef Pymor::Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType;
}; // class ContainerBasedDefaultTraits
} // namespace internal
template< class ImpTraits >
class CachedDefault
: public DiscretizationInterface< ImpTraits >
{
typedef DiscretizationInterface< ImpTraits > BaseType;
typedef CachedDefault< ImpTraits > ThisType;
public:
using typename BaseType::GridViewType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::ProblemType;
using typename BaseType::TestSpaceType;
using typename BaseType::AnsatzSpaceType;
using typename BaseType::VectorType;
private:
typedef Stuff::Grid::BoundaryInfoProvider< typename GridViewType::Intersection > BoundaryInfoProvider;
public:
static std::string static_id() { return "hdd.linearelliptic.discretizations.cached"; }
CachedDefault(TestSpaceType test_spc,
AnsatzSpaceType ansatz_spc,
Stuff::Common::Configuration bnd_inf_cfg,
const ProblemType& prb)
: BaseType(prb)
, test_space_(test_spc)
, ansatz_space_(ansatz_spc)
, boundary_info_cfg_(bnd_inf_cfg)
, boundary_info_(BoundaryInfoProvider::create(boundary_info_cfg_.get< std::string >("type"), boundary_info_cfg_))
, problem_(prb)
{}
CachedDefault(const ThisType& other) = default;
ThisType& operator=(const ThisType& other) = delete;
const TestSpaceType& test_space() const
{
return test_space_;
}
const AnsatzSpaceType& ansatz_space() const
{
return test_space_;
}
const GridViewType& grid_view() const
{
return test_space_.grid_view();
}
const Stuff::Common::Configuration& boundary_info_cfg() const
{
return boundary_info_cfg_;
}
const BoundaryInfoType& boundary_info() const
{
return *boundary_info_;
}
const ProblemType& problem() const
{
return problem_;
}
VectorType create_vector() const
{
return VectorType(ansatz_space_.mapper().size());
}
void visualize(const VectorType& vector,
const std::string filename,
const std::string name,
Pymor::Parameter mu = Pymor::Parameter()) const
{
VectorType tmp = vector.copy();
const auto vectors = this->available_vectors();
const auto result = std::find(vectors.begin(), vectors.end(), "dirichlet");
if (result != vectors.end()) {
const auto dirichlet_vector = this->get_vector("dirichlet");
if (dirichlet_vector.parametric()) {
const Pymor::Parameter mu_dirichlet = this->map_parameter(mu, "dirichlet");
if (mu_dirichlet.type() != dirichlet_vector.parameter_type())
DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,
mu_dirichlet.type() << " vs. " << dirichlet_vector.parameter_type());
tmp = dirichlet_vector.freeze_parameter(mu);
} else
tmp = *(dirichlet_vector.affine_part());
tmp += vector;
}
const GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType >function(ansatz_space_, tmp, name);
function.visualize(filename);
} // ... visualize(...)
using BaseType::solve;
void solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const
{
auto logger = DSC::TimedLogger().get(static_id());
#if !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
const auto options_in_cache = cache_.find(options);
bool exists = (options_in_cache != cache_.end());
typename std::map< Pymor::Parameter, std::shared_ptr< VectorType > >::const_iterator options_and_mu_in_cache;
if (exists) {
options_and_mu_in_cache = options_in_cache->second.find(mu);
exists = (options_and_mu_in_cache != options_in_cache->second.end());
}
if (!exists) {
#endif // !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
logger.info() << "solving";
if (options.has_key("type"))
logger.info() << " with '" << options.get< std::string >("type") << "'";
if (!mu.empty())
logger.info() << " for mu = " << mu;
logger.info() << "... " << std::endl;
uncached_solve(options, vector, mu);
#if !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
cache_[options][mu] = Stuff::Common::make_unique< VectorType >(vector.copy());
} else {
logger.info() << "retrieving solution ";
if (!mu.empty())
logger.info() << "for mu = " << mu << " ";
logger.info() << "from cache... " << std::endl;
const auto& result = *(options_and_mu_in_cache->second);
vector = result;
}
#endif // !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
} // ... solve(...)
void uncached_solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu) const
{
CHECK_AND_CALL_CRTP(this->as_imp().uncached_solve(options, vector, mu));
}
protected:
const TestSpaceType test_space_;
const AnsatzSpaceType ansatz_space_;
const Stuff::Common::Configuration boundary_info_cfg_;
const std::shared_ptr< const BoundaryInfoType > boundary_info_;
const ProblemType& problem_;
mutable std::map< DSC::Configuration, std::map< Pymor::Parameter, std::shared_ptr< VectorType > > > cache_;
}; // class CachedDefault
template< class ImpTraits >
class ContainerBasedDefault
: public CachedDefault< ImpTraits >
{
typedef CachedDefault< ImpTraits > BaseType;
typedef ContainerBasedDefault< ImpTraits > ThisType;
public:
typedef ImpTraits Traits;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::OperatorType OperatorType;
typedef typename Traits::ProductType ProductType;
typedef typename Traits::FunctionalType FunctionalType;
using typename BaseType::GridViewType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::ProblemType;
using typename BaseType::TestSpaceType;
using typename BaseType::AnsatzSpaceType;
using typename BaseType::VectorType;
typedef typename VectorType::ScalarType RangeFieldType;
protected:
typedef Pymor::LA::AffinelyDecomposedContainer< MatrixType > AffinelyDecomposedMatrixType;
typedef Pymor::LA::AffinelyDecomposedContainer< VectorType > AffinelyDecomposedVectorType;
typedef Stuff::LA::Solver< MatrixType > SolverType;
public:
static std::string static_id() { return "hdd.linearelliptic.discretizations.containerbased"; }
ContainerBasedDefault(TestSpaceType test_spc,
AnsatzSpaceType ansatz_spc,
const Stuff::Common::Configuration& bnd_inf_cfg,
const ProblemType& prb)
: BaseType(test_spc, ansatz_spc, bnd_inf_cfg, prb)
, container_based_initialized_(false)
, purely_neumann_(false)
, matrix_(std::make_shared< AffinelyDecomposedMatrixType >())
, rhs_(std::make_shared< AffinelyDecomposedVectorType >())
{}
ContainerBasedDefault(const ThisType& other) = default;
ThisType& operator=(const ThisType& other) = delete;
std::shared_ptr< AffinelyDecomposedMatrixType >& system_matrix()
{
return matrix_;
}
const std::shared_ptr< const AffinelyDecomposedMatrixType >& system_matrix() const
{
return matrix_;
}
std::shared_ptr< AffinelyDecomposedVectorType > rhs()
{
return rhs_;
}
const std::shared_ptr< const AffinelyDecomposedVectorType >& rhs() const
{
return rhs_;
}
OperatorType get_operator() const
{
assert_everything_is_ready();
return OperatorType(*matrix_);
}
FunctionalType get_rhs() const
{
assert_everything_is_ready();
return FunctionalType(*rhs_);
}
std::vector< std::string > available_products() const
{
if (products_.size() == 0)
return std::vector< std::string >();
std::vector< std::string > ret;
for (const auto& pair : products_)
ret.push_back(pair.first);
return ret;
} // ... available_products(...)
ProductType get_product(const std::string id) const
{
if (products_.size() == 0)
DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
"Do not call get_product() if available_products() is empty!");
const auto result = products_.find(id);
if (result == products_.end())
DUNE_THROW(Stuff::Exceptions::wrong_input_given, id);
return ProductType(*(result->second));
} // ... get_product(...)
std::vector< std::string > available_vectors() const
{
if (vectors_.size() == 0)
return std::vector< std::string >();
std::vector< std::string > ret;
for (const auto& pair : vectors_)
ret.push_back(pair.first);
return ret;
} // ... available_vectors(...)
AffinelyDecomposedVectorType get_vector(const std::string id) const
{
if (vectors_.size() == 0)
DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
"Do not call get_vector() if available_vectors() is empty!");
const auto result = vectors_.find(id);
if (result == vectors_.end())
DUNE_THROW(Stuff::Exceptions::wrong_input_given, id);
return *(result->second);
} // ... get_vector(...)
std::vector< std::string > solver_types() const
{
return SolverType::types();
}
DSC::Configuration solver_options(const std::string type = "") const
{
return SolverType::options(type);
}
/**
* \brief solves for u_0
*/
void uncached_solve(const DSC::Configuration options,
VectorType& vector,
const Pymor::Parameter mu = Pymor::Parameter()) const
{
auto logger = DSC::TimedLogger().get(static_id());
assert_everything_is_ready();
if (mu.type() != this->parameter_type())
DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, mu.type() << " vs. " << this->parameter_type());
const auto& rhs = *(this->rhs_);
const auto& matrix = *(this->matrix_);
if (purely_neumann_) {
VectorType tmp_rhs = rhs.parametric() ? rhs.freeze_parameter(this->map_parameter(mu, "rhs"))
: *(rhs.affine_part());
MatrixType tmp_system_matrix = matrix.parametric() ? matrix.freeze_parameter(this->map_parameter(mu, "lhs"))
: *(matrix.affine_part());
tmp_system_matrix.unit_row(0);
tmp_rhs.set_entry(0, 0.0);
SolverType(tmp_system_matrix).apply(tmp_rhs, vector, options);
vector -= vector.mean();
} else {
// compute right hand side vector
logger.debug() << "computing right hand side..." << std::endl;
std::shared_ptr< const VectorType > rhs_vector;
if (!rhs.parametric())
rhs_vector = rhs.affine_part();
else {
const Pymor::Parameter mu_rhs = this->map_parameter(mu, "rhs");
rhs_vector = std::make_shared< const VectorType >(rhs.freeze_parameter(mu_rhs));
}
logger.debug() << "computing system matrix..." << std::endl;
const OperatorType lhsOperator(matrix);
if (lhsOperator.parametric()) {
const Pymor::Parameter mu_lhs = this->map_parameter(mu, "lhs");
const auto frozenOperator = lhsOperator.freeze_parameter(mu_lhs);
frozenOperator.apply_inverse(*rhs_vector, vector, options);
} else {
const auto nonparametricOperator = lhsOperator.affine_part();
nonparametricOperator.apply_inverse(*rhs_vector, vector, options);
}
}
} // ... uncached_solve(...)
protected:
void assert_everything_is_ready() const
{
if (!container_based_initialized_)
DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
"The implemented discretization has to fill 'matrix_' and 'rhs_' during init() and set "
<< "container_based_initialized_ to true!\n"
<< "The user has to call init() before calling any other method!");
} // ... assert_everything_is_ready()
bool container_based_initialized_;
bool purely_neumann_;
std::shared_ptr< AffinelyDecomposedMatrixType > matrix_;
std::shared_ptr< AffinelyDecomposedVectorType > rhs_;
mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedMatrixType > > products_;
mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedVectorType > > vectors_;
}; // class ContainerBasedDefault
} // namespace Discretizations
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
<commit_msg>[linearelliptic.discretizations] add finalize_init()<commit_after>// This file is part of the dune-hdd project:
// http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
#define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
#ifndef DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
# define DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING 0
#endif
#include <map>
#include <algorithm>
#include <dune/stuff/common/crtp.hh>
#include <dune/stuff/common/exceptions.hh>
#include <dune/stuff/common/logging.hh>
#include <dune/stuff/la/solver.hh>
#include <dune/pymor/operators/base.hh>
#include <dune/pymor/operators/affine.hh>
#include <dune/pymor/functionals/affine.hh>
#include <dune/gdt/discretefunction/default.hh>
#include "interfaces.hh"
namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Discretizations {
// forward
template< class ImpTraits >
class ContainerBasedDefault;
namespace internal {
template< class MatrixImp, class VectorImp >
class ContainerBasedDefaultTraits
{
public:
typedef MatrixImp MatrixType;
typedef VectorImp VectorType;
typedef Pymor::Operators::LinearAffinelyDecomposedContainerBased< MatrixType, VectorType > OperatorType;
typedef OperatorType ProductType;
typedef Pymor::Functionals::LinearAffinelyDecomposedVectorBased< VectorType > FunctionalType;
}; // class ContainerBasedDefaultTraits
} // namespace internal
template< class ImpTraits >
class CachedDefault
: public DiscretizationInterface< ImpTraits >
{
typedef DiscretizationInterface< ImpTraits > BaseType;
typedef CachedDefault< ImpTraits > ThisType;
public:
using typename BaseType::GridViewType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::ProblemType;
using typename BaseType::TestSpaceType;
using typename BaseType::AnsatzSpaceType;
using typename BaseType::VectorType;
private:
typedef Stuff::Grid::BoundaryInfoProvider< typename GridViewType::Intersection > BoundaryInfoProvider;
public:
static std::string static_id() { return "hdd.linearelliptic.discretizations.cached"; }
CachedDefault(TestSpaceType test_spc,
AnsatzSpaceType ansatz_spc,
Stuff::Common::Configuration bnd_inf_cfg,
const ProblemType& prb)
: BaseType(prb)
, test_space_(test_spc)
, ansatz_space_(ansatz_spc)
, boundary_info_cfg_(bnd_inf_cfg)
, boundary_info_(BoundaryInfoProvider::create(boundary_info_cfg_.get< std::string >("type"), boundary_info_cfg_))
, problem_(prb)
{}
CachedDefault(const ThisType& other) = default;
ThisType& operator=(const ThisType& other) = delete;
const TestSpaceType& test_space() const
{
return test_space_;
}
const AnsatzSpaceType& ansatz_space() const
{
return test_space_;
}
const GridViewType& grid_view() const
{
return test_space_.grid_view();
}
const Stuff::Common::Configuration& boundary_info_cfg() const
{
return boundary_info_cfg_;
}
const BoundaryInfoType& boundary_info() const
{
return *boundary_info_;
}
const ProblemType& problem() const
{
return problem_;
}
VectorType create_vector() const
{
return VectorType(ansatz_space_.mapper().size());
}
void visualize(const VectorType& vector,
const std::string filename,
const std::string name,
Pymor::Parameter mu = Pymor::Parameter()) const
{
VectorType tmp = vector.copy();
const auto vectors = this->available_vectors();
const auto result = std::find(vectors.begin(), vectors.end(), "dirichlet");
if (result != vectors.end()) {
const auto dirichlet_vector = this->get_vector("dirichlet");
if (dirichlet_vector.parametric()) {
const Pymor::Parameter mu_dirichlet = this->map_parameter(mu, "dirichlet");
if (mu_dirichlet.type() != dirichlet_vector.parameter_type())
DUNE_THROW(Pymor::Exceptions::wrong_parameter_type,
mu_dirichlet.type() << " vs. " << dirichlet_vector.parameter_type());
tmp = dirichlet_vector.freeze_parameter(mu);
} else
tmp = *(dirichlet_vector.affine_part());
tmp += vector;
}
const GDT::ConstDiscreteFunction< AnsatzSpaceType, VectorType >function(ansatz_space_, tmp, name);
function.visualize(filename);
} // ... visualize(...)
using BaseType::solve;
void solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu = Pymor::Parameter()) const
{
auto logger = DSC::TimedLogger().get(static_id());
#if !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
const auto options_in_cache = cache_.find(options);
bool exists = (options_in_cache != cache_.end());
typename std::map< Pymor::Parameter, std::shared_ptr< VectorType > >::const_iterator options_and_mu_in_cache;
if (exists) {
options_and_mu_in_cache = options_in_cache->second.find(mu);
exists = (options_and_mu_in_cache != options_in_cache->second.end());
}
if (!exists) {
#endif // !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
logger.info() << "solving";
if (options.has_key("type"))
logger.info() << " with '" << options.get< std::string >("type") << "'";
if (!mu.empty())
logger.info() << " for mu = " << mu;
logger.info() << "... " << std::endl;
uncached_solve(options, vector, mu);
#if !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
cache_[options][mu] = Stuff::Common::make_unique< VectorType >(vector.copy());
} else {
logger.info() << "retrieving solution ";
if (!mu.empty())
logger.info() << "for mu = " << mu << " ";
logger.info() << "from cache... " << std::endl;
const auto& result = *(options_and_mu_in_cache->second);
vector = result;
}
#endif // !DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_BASE_DISABLE_CACHING
} // ... solve(...)
void uncached_solve(const DSC::Configuration options, VectorType& vector, const Pymor::Parameter mu) const
{
CHECK_AND_CALL_CRTP(this->as_imp().uncached_solve(options, vector, mu));
}
protected:
const TestSpaceType test_space_;
const AnsatzSpaceType ansatz_space_;
const Stuff::Common::Configuration boundary_info_cfg_;
const std::shared_ptr< const BoundaryInfoType > boundary_info_;
const ProblemType& problem_;
mutable std::map< DSC::Configuration, std::map< Pymor::Parameter, std::shared_ptr< VectorType > > > cache_;
}; // class CachedDefault
template< class ImpTraits >
class ContainerBasedDefault
: public CachedDefault< ImpTraits >
{
typedef CachedDefault< ImpTraits > BaseType;
typedef ContainerBasedDefault< ImpTraits > ThisType;
public:
typedef ImpTraits Traits;
typedef typename Traits::MatrixType MatrixType;
typedef typename Traits::OperatorType OperatorType;
typedef typename Traits::ProductType ProductType;
typedef typename Traits::FunctionalType FunctionalType;
using typename BaseType::GridViewType;
using typename BaseType::BoundaryInfoType;
using typename BaseType::ProblemType;
using typename BaseType::TestSpaceType;
using typename BaseType::AnsatzSpaceType;
using typename BaseType::VectorType;
typedef typename VectorType::ScalarType RangeFieldType;
protected:
typedef Pymor::LA::AffinelyDecomposedContainer< MatrixType > AffinelyDecomposedMatrixType;
typedef Pymor::LA::AffinelyDecomposedContainer< VectorType > AffinelyDecomposedVectorType;
typedef Stuff::LA::Solver< MatrixType > SolverType;
public:
static std::string static_id() { return "hdd.linearelliptic.discretizations.containerbased"; }
ContainerBasedDefault(TestSpaceType test_spc,
AnsatzSpaceType ansatz_spc,
const Stuff::Common::Configuration& bnd_inf_cfg,
const ProblemType& prb)
: BaseType(test_spc, ansatz_spc, bnd_inf_cfg, prb)
, container_based_initialized_(false)
, purely_neumann_(false)
, matrix_(std::make_shared< AffinelyDecomposedMatrixType >())
, rhs_(std::make_shared< AffinelyDecomposedVectorType >())
{}
ContainerBasedDefault(const ThisType& other) = default;
ThisType& operator=(const ThisType& other) = delete;
std::shared_ptr< AffinelyDecomposedMatrixType >& system_matrix()
{
return matrix_;
}
const std::shared_ptr< const AffinelyDecomposedMatrixType >& system_matrix() const
{
return matrix_;
}
std::shared_ptr< AffinelyDecomposedVectorType > rhs()
{
return rhs_;
}
const std::shared_ptr< const AffinelyDecomposedVectorType >& rhs() const
{
return rhs_;
}
OperatorType get_operator() const
{
assert_everything_is_ready();
return OperatorType(*matrix_);
}
FunctionalType get_rhs() const
{
assert_everything_is_ready();
return FunctionalType(*rhs_);
}
std::vector< std::string > available_products() const
{
if (products_.size() == 0)
return std::vector< std::string >();
std::vector< std::string > ret;
for (const auto& pair : products_)
ret.push_back(pair.first);
return ret;
} // ... available_products(...)
ProductType get_product(const std::string id) const
{
if (products_.size() == 0)
DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
"Do not call get_product() if available_products() is empty!");
const auto result = products_.find(id);
if (result == products_.end())
DUNE_THROW(Stuff::Exceptions::wrong_input_given, id);
return ProductType(*(result->second));
} // ... get_product(...)
std::vector< std::string > available_vectors() const
{
if (vectors_.size() == 0)
return std::vector< std::string >();
std::vector< std::string > ret;
for (const auto& pair : vectors_)
ret.push_back(pair.first);
return ret;
} // ... available_vectors(...)
AffinelyDecomposedVectorType get_vector(const std::string id) const
{
if (vectors_.size() == 0)
DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
"Do not call get_vector() if available_vectors() is empty!");
const auto result = vectors_.find(id);
if (result == vectors_.end())
DUNE_THROW(Stuff::Exceptions::wrong_input_given, id);
return *(result->second);
} // ... get_vector(...)
std::vector< std::string > solver_types() const
{
return SolverType::types();
}
DSC::Configuration solver_options(const std::string type = "") const
{
return SolverType::options(type);
}
/**
* \brief solves for u_0
*/
void uncached_solve(const DSC::Configuration options,
VectorType& vector,
const Pymor::Parameter mu = Pymor::Parameter()) const
{
auto logger = DSC::TimedLogger().get(static_id());
assert_everything_is_ready();
if (mu.type() != this->parameter_type())
DUNE_THROW(Pymor::Exceptions::wrong_parameter_type, mu.type() << " vs. " << this->parameter_type());
const auto& rhs = *(this->rhs_);
const auto& matrix = *(this->matrix_);
if (purely_neumann_) {
VectorType tmp_rhs = rhs.parametric() ? rhs.freeze_parameter(this->map_parameter(mu, "rhs"))
: *(rhs.affine_part());
MatrixType tmp_system_matrix = matrix.parametric() ? matrix.freeze_parameter(this->map_parameter(mu, "lhs"))
: *(matrix.affine_part());
tmp_system_matrix.unit_row(0);
tmp_rhs.set_entry(0, 0.0);
SolverType(tmp_system_matrix).apply(tmp_rhs, vector, options);
vector -= vector.mean();
} else {
// compute right hand side vector
logger.debug() << "computing right hand side..." << std::endl;
std::shared_ptr< const VectorType > rhs_vector;
if (!rhs.parametric())
rhs_vector = rhs.affine_part();
else {
const Pymor::Parameter mu_rhs = this->map_parameter(mu, "rhs");
rhs_vector = std::make_shared< const VectorType >(rhs.freeze_parameter(mu_rhs));
}
logger.debug() << "computing system matrix..." << std::endl;
const OperatorType lhsOperator(matrix);
if (lhsOperator.parametric()) {
const Pymor::Parameter mu_lhs = this->map_parameter(mu, "lhs");
const auto frozenOperator = lhsOperator.freeze_parameter(mu_lhs);
frozenOperator.apply_inverse(*rhs_vector, vector, options);
} else {
const auto nonparametricOperator = lhsOperator.affine_part();
nonparametricOperator.apply_inverse(*rhs_vector, vector, options);
}
}
} // ... uncached_solve(...)
protected:
void finalize_init()
{
if (!container_based_initialized_) {
if (!matrix_->parametric())
matrix_ = std::make_shared< AffinelyDecomposedMatrixType >(new MatrixType(matrix_->affine_part()->pruned()));
for (auto& element : products_)
if (!element.second->parametric())
element.second = std::make_shared< AffinelyDecomposedMatrixType >(new MatrixType(element.second->affine_part()->pruned()));
container_based_initialized_ = true;
}
} // ... finalize_init(...)
void assert_everything_is_ready() const
{
if (!container_based_initialized_)
DUNE_THROW(Stuff::Exceptions::you_are_using_this_wrong,
"The implemented discretization has to fill 'matrix_' and 'rhs_' during init() and set "
<< "container_based_initialized_ to true!\n"
<< "The user has to call init() before calling any other method!");
} // ... assert_everything_is_ready()
bool container_based_initialized_;
bool purely_neumann_;
std::shared_ptr< AffinelyDecomposedMatrixType > matrix_;
std::shared_ptr< AffinelyDecomposedVectorType > rhs_;
mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedMatrixType > > products_;
mutable std::map< std::string, std::shared_ptr< AffinelyDecomposedVectorType > > vectors_;
}; // class ContainerBasedDefault
} // namespace Discretizations
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune
#endif // DUNE_HDD_LINEARELLIPTIC_DISCRETIZATIONS_DEFAULT_HH
<|endoftext|> |
<commit_before>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkRandom.h"
#include "SkLineClipper.h"
#include "SkEdgeClipper.h"
#define AUTO_ANIMATE true
static int test0(SkPoint pts[], SkRect* clip) {
pts[0].set(200000, 140);
pts[1].set(-740000, 483);
pts[2].set(1.00000102e-06f, 9.10000017e-05f);
clip->set(0, 0, 640, 480);
return 2;
}
///////////////////////////////////////////////////////////////////////////////
static void drawQuad(SkCanvas* canvas, const SkPoint pts[3], const SkPaint& p) {
SkPath path;
path.moveTo(pts[0]);
path.quadTo(pts[1], pts[2]);
canvas->drawPath(path, p);
}
static void drawCubic(SkCanvas* canvas, const SkPoint pts[4], const SkPaint& p) {
SkPath path;
path.moveTo(pts[0]);
path.cubicTo(pts[1], pts[2], pts[3]);
canvas->drawPath(path, p);
}
typedef void (*clipper_proc)(const SkPoint src[], const SkRect& clip,
SkCanvas*, const SkPaint&, const SkPaint&);
static void check_clipper(int count, const SkPoint pts[], const SkRect& clip) {
for (int i = 0; i < count; i++) {
SkASSERT(pts[i].fX >= clip.fLeft);
SkASSERT(pts[i].fX <= clip.fRight);
SkASSERT(pts[i].fY >= clip.fTop);
SkASSERT(pts[i].fY <= clip.fBottom);
}
if (count > 1) {
sk_assert_monotonic_y(pts, count);
}
}
static void line_intersector(const SkPoint src[], const SkRect& clip,
SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, src, p1);
SkPoint dst[2];
if (SkLineClipper::IntersectLine(src, clip, dst)) {
check_clipper(2, dst, clip);
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, dst, p0);
}
}
static void line_clipper(const SkPoint src[], const SkRect& clip,
SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, src, p1);
SkPoint dst[SkLineClipper::kMaxPoints];
int count = SkLineClipper::ClipLine(src, clip, dst);
for (int i = 0; i < count; i++) {
check_clipper(2, &dst[i], clip);
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, &dst[i], p0);
}
}
static void quad_clipper(const SkPoint src[], const SkRect& clip,
SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
drawQuad(canvas, src, p1);
SkEdgeClipper clipper;
if (clipper.clipQuad(src, clip)) {
SkPoint pts[4];
SkPath::Verb verb;
while ((verb = clipper.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kLine_Verb:
check_clipper(2, pts, clip);
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p0);
break;
case SkPath::kQuad_Verb:
check_clipper(3, pts, clip);
drawQuad(canvas, pts, p0);
break;
default:
SkASSERT(!"unexpected verb");
}
}
}
}
static void cubic_clipper(const SkPoint src[], const SkRect& clip,
SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
drawCubic(canvas, src, p1);
SkEdgeClipper clipper;
if (clipper.clipCubic(src, clip)) {
SkPoint pts[4];
SkPath::Verb verb;
while ((verb = clipper.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kLine_Verb:
check_clipper(2, pts, clip);
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p0);
break;
case SkPath::kCubic_Verb:
// check_clipper(4, pts, clip);
drawCubic(canvas, pts, p0);
break;
default:
SkASSERT(!"unexpected verb");
}
}
}
}
static const clipper_proc gProcs[] = {
line_intersector,
line_clipper,
quad_clipper,
cubic_clipper
};
///////////////////////////////////////////////////////////////////////////////
enum {
W = 640/3,
H = 480/3
};
class LineClipperView : public SkView {
SkMSec fNow;
int fCounter;
int fProcIndex;
SkRect fClip;
SkRandom fRand;
SkPoint fPts[4];
void randPts() {
for (size_t i = 0; i < SK_ARRAY_COUNT(fPts); i++) {
fPts[i].set(fRand.nextUScalar1() * 640,
fRand.nextUScalar1() * 480);
}
fCounter += 1;
}
public:
LineClipperView() {
fProcIndex = 0;
fCounter = 0;
fNow = 0;
int x = (640 - W)/2;
int y = (480 - H)/2;
fClip.set(SkIntToScalar(x), SkIntToScalar(y),
SkIntToScalar(x + W), SkIntToScalar(y + H));
this->randPts();
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "LineClipper");
return true;
}
return this->INHERITED::onQuery(evt);
}
void drawBG(SkCanvas* canvas) {
canvas->drawColor(SK_ColorWHITE);
}
static void drawVLine(SkCanvas* canvas, SkScalar x, const SkPaint& paint) {
canvas->drawLine(x, -999, x, 999, paint);
}
static void drawHLine(SkCanvas* canvas, SkScalar y, const SkPaint& paint) {
canvas->drawLine(-999, y, 999, y, paint);
}
virtual void onDraw(SkCanvas* canvas) {
this->drawBG(canvas);
SkMSec now = SampleCode::GetAnimTime();
if (fNow != now) {
fNow = now;
this->randPts();
this->inval(NULL);
}
// fProcIndex = test0(fPts, &fClip);
SkPaint paint, paint1;
drawVLine(canvas, fClip.fLeft + SK_ScalarHalf, paint);
drawVLine(canvas, fClip.fRight - SK_ScalarHalf, paint);
drawHLine(canvas, fClip.fTop + SK_ScalarHalf, paint);
drawHLine(canvas, fClip.fBottom - SK_ScalarHalf, paint);
paint.setColor(SK_ColorLTGRAY);
canvas->drawRect(fClip, paint);
paint.setAntiAlias(true);
paint.setColor(SK_ColorBLUE);
paint.setStyle(SkPaint::kStroke_Style);
// paint.setStrokeWidth(SkIntToScalar(3));
paint.setStrokeCap(SkPaint::kRound_Cap);
paint1.setAntiAlias(true);
paint1.setColor(SK_ColorRED);
paint1.setStyle(SkPaint::kStroke_Style);
gProcs[fProcIndex](fPts, fClip, canvas, paint, paint1);
}
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
// fProcIndex = (fProcIndex + 1) % SK_ARRAY_COUNT(gProcs);
if (x < 50 && y < 50) {
this->randPts();
}
this->inval(NULL);
return NULL;
}
virtual bool onClick(Click* click) {
return false;
}
private:
typedef SkView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new LineClipperView; }
static SkViewRegister reg(MyFactory);
<commit_msg>inherit from SampleView<commit_after>#include "SampleCode.h"
#include "SkView.h"
#include "SkCanvas.h"
#include "SkGradientShader.h"
#include "SkGraphics.h"
#include "SkImageDecoder.h"
#include "SkPath.h"
#include "SkRegion.h"
#include "SkShader.h"
#include "SkUtils.h"
#include "SkXfermode.h"
#include "SkColorPriv.h"
#include "SkColorFilter.h"
#include "SkTime.h"
#include "SkRandom.h"
#include "SkLineClipper.h"
#include "SkEdgeClipper.h"
#define AUTO_ANIMATE true
static int test0(SkPoint pts[], SkRect* clip) {
pts[0].set(200000, 140);
pts[1].set(-740000, 483);
pts[2].set(1.00000102e-06f, 9.10000017e-05f);
clip->set(0, 0, 640, 480);
return 2;
}
///////////////////////////////////////////////////////////////////////////////
static void drawQuad(SkCanvas* canvas, const SkPoint pts[3], const SkPaint& p) {
SkPath path;
path.moveTo(pts[0]);
path.quadTo(pts[1], pts[2]);
canvas->drawPath(path, p);
}
static void drawCubic(SkCanvas* canvas, const SkPoint pts[4], const SkPaint& p) {
SkPath path;
path.moveTo(pts[0]);
path.cubicTo(pts[1], pts[2], pts[3]);
canvas->drawPath(path, p);
}
typedef void (*clipper_proc)(const SkPoint src[], const SkRect& clip,
SkCanvas*, const SkPaint&, const SkPaint&);
static void check_clipper(int count, const SkPoint pts[], const SkRect& clip) {
for (int i = 0; i < count; i++) {
SkASSERT(pts[i].fX >= clip.fLeft);
SkASSERT(pts[i].fX <= clip.fRight);
SkASSERT(pts[i].fY >= clip.fTop);
SkASSERT(pts[i].fY <= clip.fBottom);
}
if (count > 1) {
sk_assert_monotonic_y(pts, count);
}
}
static void line_intersector(const SkPoint src[], const SkRect& clip,
SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, src, p1);
SkPoint dst[2];
if (SkLineClipper::IntersectLine(src, clip, dst)) {
check_clipper(2, dst, clip);
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, dst, p0);
}
}
static void line_clipper(const SkPoint src[], const SkRect& clip,
SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, src, p1);
SkPoint dst[SkLineClipper::kMaxPoints];
int count = SkLineClipper::ClipLine(src, clip, dst);
for (int i = 0; i < count; i++) {
check_clipper(2, &dst[i], clip);
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, &dst[i], p0);
}
}
static void quad_clipper(const SkPoint src[], const SkRect& clip,
SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
drawQuad(canvas, src, p1);
SkEdgeClipper clipper;
if (clipper.clipQuad(src, clip)) {
SkPoint pts[4];
SkPath::Verb verb;
while ((verb = clipper.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kLine_Verb:
check_clipper(2, pts, clip);
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p0);
break;
case SkPath::kQuad_Verb:
check_clipper(3, pts, clip);
drawQuad(canvas, pts, p0);
break;
default:
SkASSERT(!"unexpected verb");
}
}
}
}
static void cubic_clipper(const SkPoint src[], const SkRect& clip,
SkCanvas* canvas, const SkPaint& p0, const SkPaint& p1) {
drawCubic(canvas, src, p1);
SkEdgeClipper clipper;
if (clipper.clipCubic(src, clip)) {
SkPoint pts[4];
SkPath::Verb verb;
while ((verb = clipper.next(pts)) != SkPath::kDone_Verb) {
switch (verb) {
case SkPath::kLine_Verb:
check_clipper(2, pts, clip);
canvas->drawPoints(SkCanvas::kLines_PointMode, 2, pts, p0);
break;
case SkPath::kCubic_Verb:
// check_clipper(4, pts, clip);
drawCubic(canvas, pts, p0);
break;
default:
SkASSERT(!"unexpected verb");
}
}
}
}
static const clipper_proc gProcs[] = {
line_intersector,
line_clipper,
quad_clipper,
cubic_clipper
};
///////////////////////////////////////////////////////////////////////////////
enum {
W = 640/3,
H = 480/3
};
class LineClipperView : public SampleView {
SkMSec fNow;
int fCounter;
int fProcIndex;
SkRect fClip;
SkRandom fRand;
SkPoint fPts[4];
void randPts() {
for (size_t i = 0; i < SK_ARRAY_COUNT(fPts); i++) {
fPts[i].set(fRand.nextUScalar1() * 640,
fRand.nextUScalar1() * 480);
}
fCounter += 1;
}
public:
LineClipperView() {
fProcIndex = 0;
fCounter = 0;
fNow = 0;
int x = (640 - W)/2;
int y = (480 - H)/2;
fClip.set(SkIntToScalar(x), SkIntToScalar(y),
SkIntToScalar(x + W), SkIntToScalar(y + H));
this->randPts();
}
protected:
// overrides from SkEventSink
virtual bool onQuery(SkEvent* evt) {
if (SampleCode::TitleQ(*evt)) {
SampleCode::TitleR(evt, "LineClipper");
return true;
}
return this->INHERITED::onQuery(evt);
}
static void drawVLine(SkCanvas* canvas, SkScalar x, const SkPaint& paint) {
canvas->drawLine(x, -999, x, 999, paint);
}
static void drawHLine(SkCanvas* canvas, SkScalar y, const SkPaint& paint) {
canvas->drawLine(-999, y, 999, y, paint);
}
virtual void onDrawContent(SkCanvas* canvas) {
SkMSec now = SampleCode::GetAnimTime();
if (fNow != now) {
fNow = now;
this->randPts();
this->inval(NULL);
}
// fProcIndex = test0(fPts, &fClip);
SkPaint paint, paint1;
drawVLine(canvas, fClip.fLeft + SK_ScalarHalf, paint);
drawVLine(canvas, fClip.fRight - SK_ScalarHalf, paint);
drawHLine(canvas, fClip.fTop + SK_ScalarHalf, paint);
drawHLine(canvas, fClip.fBottom - SK_ScalarHalf, paint);
paint.setColor(SK_ColorLTGRAY);
canvas->drawRect(fClip, paint);
paint.setAntiAlias(true);
paint.setColor(SK_ColorBLUE);
paint.setStyle(SkPaint::kStroke_Style);
// paint.setStrokeWidth(SkIntToScalar(3));
paint.setStrokeCap(SkPaint::kRound_Cap);
paint1.setAntiAlias(true);
paint1.setColor(SK_ColorRED);
paint1.setStyle(SkPaint::kStroke_Style);
gProcs[fProcIndex](fPts, fClip, canvas, paint, paint1);
this->inval(NULL);
}
virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) {
// fProcIndex = (fProcIndex + 1) % SK_ARRAY_COUNT(gProcs);
if (x < 50 && y < 50) {
this->randPts();
}
this->inval(NULL);
return NULL;
}
virtual bool onClick(Click* click) {
return false;
}
private:
typedef SampleView INHERITED;
};
//////////////////////////////////////////////////////////////////////////////
static SkView* MyFactory() { return new LineClipperView; }
static SkViewRegister reg(MyFactory);
<|endoftext|> |
<commit_before>/* +---------------------------------------------------------------------------+
| The Mobile Robot Programming Toolkit (MRPT) |
| |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |
| Copyright (c) 2005-2013, MAPIR group, University of Malaga |
| Copyright (c) 2012-2013, University of Almeria |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are |
| met: |
| * Redistributions of source code must retain the above copyright |
| notice, this list of conditions and the following disclaimer. |
| * Redistributions in binary form must reproduce the above copyright |
| notice, this list of conditions and the following disclaimer in the |
| documentation and/or other materials provided with the distribution. |
| * Neither the name of the copyright holders nor the |
| names of its contributors may be used to endorse or promote products |
| derived from this software without specific prior written permission.|
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |
| TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR|
| PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 <mrpt/hwdrivers/CInterfaceNI845x.h>
#include <mrpt/system.h>
using namespace std;
using namespace mrpt;
using namespace mrpt::hwdrivers;
// ------------------------------------------------------
// TestNI_USB_845x
// ------------------------------------------------------
void TestNI_USB_845x()
{
CInterfaceNI845x ni_usb;
// Open first connected device:
cout << "Openning device...\n";
ni_usb.open();
cout << "Done! Connected to: " << ni_usb.getDeviceDescriptor() << endl;
ni_usb.setIOVoltageLevel( 12 ); // 1.2 volts
#if 0
ni_usb.setIOPortDirection(0, 0xFF);
while (!mrpt::system::os::kbhit())
{
ni_usb.writeIOPort(0, 0xFF);
mrpt::system::sleep(500);
ni_usb.writeIOPort(0, 0x00);
mrpt::system::sleep(500);
}
#endif
#if 1
ni_usb.create_SPI_configurations(1);
ni_usb.set_SPI_configuration(0 /*idx*/, 0 /* CS */, 48 /* Khz */, true /* clock_polarity_idle_low */, false /* clock_phase_first_edge */ );
while (!mrpt::system::os::kbhit())
{
const uint8_t write[4] = { 0x11, 0x22, 0x33, 0x44 };
uint8_t read[4];
size_t nRead;
ni_usb.read_write_SPI(0, 4, write, nRead, read );
}
#endif
mrpt::system::pause();
}
// ------------------------------------------------------
// MAIN
// ------------------------------------------------------
int main()
{
try
{
TestNI_USB_845x();
return 0;
} catch (std::exception &e)
{
std::cout << "MRPT exception caught: " << e.what() << std::endl;
return -1;
}
}
<commit_msg>update of ni sample<commit_after>/* +---------------------------------------------------------------------------+
| The Mobile Robot Programming Toolkit (MRPT) |
| |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2013, Individual contributors, see AUTHORS file |
| Copyright (c) 2005-2013, MAPIR group, University of Malaga |
| Copyright (c) 2012-2013, University of Almeria |
| All rights reserved. |
| |
| Redistribution and use in source and binary forms, with or without |
| modification, are permitted provided that the following conditions are |
| met: |
| * Redistributions of source code must retain the above copyright |
| notice, this list of conditions and the following disclaimer. |
| * Redistributions in binary form must reproduce the above copyright |
| notice, this list of conditions and the following disclaimer in the |
| documentation and/or other materials provided with the distribution. |
| * Neither the name of the copyright holders nor the |
| names of its contributors may be used to endorse or promote products |
| derived from this software without specific prior written permission.|
| |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
| 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |
| TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR|
| PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 <mrpt/hwdrivers/CInterfaceNI845x.h>
#include <mrpt/system.h>
#include <mrpt/gui.h>
using namespace std;
using namespace mrpt;
using namespace mrpt::gui;
using namespace mrpt::hwdrivers;
// ------------------------------------------------------
// TestNI_USB_845x
// ------------------------------------------------------
void TestNI_USB_845x()
{
CInterfaceNI845x ni_usb;
// Open first connected device:
cout << "Openning device...\n";
ni_usb.open();
cout << "Done! Connected to: " << ni_usb.getDeviceDescriptor() << endl;
ni_usb.setIOVoltageLevel( 25 ); // 2.5 volts
#if 0
ni_usb.setIOPortDirection(0, 0xFF);
while (!mrpt::system::os::kbhit())
{
ni_usb.writeIOPort(0, 0xFF);
mrpt::system::sleep(500);
ni_usb.writeIOPort(0, 0x00);
mrpt::system::sleep(500);
}
#endif
#if 0
const size_t N=1000;
std::vector<double> d0(N),d1(N),d2(N);
ni_usb.setIOPortDirection(0, 0x00);
for (size_t i=0;i<N;i++)
{
uint8_t d = ni_usb.readIOPort(0);
mrpt::system::sleep(1);
d0[i]= (d & 0x01) ? 1.0 : 0.0;
d1[i]= (d & 0x02) ? 3.0 : 2.0;
d2[i]= (d & 0x04) ? 5.0 : 4.0;
}
CDisplayWindowPlots win("Signals",640,480);
win.hold_on();
win.plot(d0, "b-");
win.plot(d1, "r-");
win.plot(d2, "k-");
win.axis_fit();
win.waitForKey();
#endif
#if 1
ni_usb.create_SPI_configurations(1);
ni_usb.set_SPI_configuration(0 /*idx*/, 0 /* CS */, 1000 /* Khz */, false /* clock_polarity_idle_high */, false /* clock_phase_first_edge */ );
{
const uint8_t write[2] = { 0x20, 0xFF };
uint8_t read[2];
size_t nRead;
printf("TX: %02X %02X\n", write[0],write[1]);
ni_usb.read_write_SPI(0 /* config idx */, 2, write, nRead, read );
}
const uint8_t write[2] = { 0x80 | 0x28, 0x00 };
uint8_t read[2];
size_t nRead;
while (!mrpt::system::os::kbhit())
{
printf("TX: %02X %02X\n", write[0],write[1]);
ni_usb.read_write_SPI(0 /* config idx */, 2, write, nRead, read );
printf("RX: %02X %02X\n\n", read[0],read[1]);
mrpt::system::sleep(100);
}
#endif
mrpt::system::pause();
}
// ------------------------------------------------------
// MAIN
// ------------------------------------------------------
int main()
{
try
{
TestNI_USB_845x();
return 0;
} catch (std::exception &e)
{
std::cout << "MRPT exception caught: " << e.what() << std::endl;
return -1;
}
}
<|endoftext|> |
<commit_before><commit_msg>sandbox/linux/bpf_dsl: collapse similar ResultExprImpl subclasses<commit_after><|endoftext|> |
<commit_before><commit_msg>Remove stray fprintf<commit_after><|endoftext|> |
<commit_before>#include "Halide.h"
#include <stdio.h>
using namespace Halide;
#include "halide_image_io.h"
using namespace Halide::Tools;
Func rgb_to_grey(Image<uint8_t> input)
{
Var x("x"), y("y"), c("c"), d("d");
Func clamped("clamped");
clamped = BoundaryConditions::repeat_edge(input);
Func greyImg("greyImg");
greyImg(x,y,d) =
clamped(x,y,0) * 0.3f
+ clamped(x,y,1) * 0.59f
+ clamped(x,y,2) * 0.11f;
return greyImg;
}
void imwrite(std::string fname, int width, int height, Func continuation)
{
Image<uint8_t> result(width, height, 1);
continuation.realize(result);
save_image(result, fname);
}
Func blurX(Func continuation)
{
Var x("x"), y("y"), c("c");
Func input_16("input_16");
input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c));
Func blur_x("blur_x");
blur_x(x, y, c) = (input_16(x-1, y, c) +
2 * input_16(x, y, c) +
input_16(x+1, y, c)) / 4;
blur_x.vectorize(x, 8).parallel(y);
blur_x.compute_root();
Func output("outputBlurX");
output(x, y, c) = cast<uint8_t>(blur_x(x, y, c));
return output;
}
Func blurY(Func continuation)
{
Var x("x"), y("y"), c("c");
Func input_16("input_16");
input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c));
Func blur_y("blur_y");
blur_y(x, y, c) = (input_16(x, y-1, c) +
2 * input_16(x, y, c) +
input_16(x, y+1, c)) / 4;
blur_y.vectorize(y, 8).parallel(x);
blur_y.compute_root();
Func output("outputBlurY");
output(x, y, c) = cast<uint8_t>(blur_y(x, y, c));
return output;
}
Func brightenBy(int brightenByVal, Func continuation)
{
Func brighten("brighten");
Var x, y, c;
Expr value = continuation(x, y, c);
value = Halide::cast<float>(value);
value = value + brightenByVal;
value = Halide::min(value, 255.0f);
value = Halide::cast<uint8_t>(value);
brighten(x, y, c) = value;
brighten.vectorize(x, 8).parallel(y);
brighten.compute_root();
return brighten;
}
Func darkenBy(int darkenByVal, Func continuation)
{
Func darken("darken");
Var x, y, c;
Expr value = continuation(x, y, c);
value = Halide::cast<float>(value);
value = value - darkenByVal;
value = Halide::cast<uint8_t>(value);
darken(x, y, c) = value;
darken.vectorize(x, 8).parallel(y);
darken.compute_root();
return darken;
}
<commit_msg>(Halide) imwrite writes .realize(..) time to stdout in seconds<commit_after>#include "Halide.h"
#include <stdio.h>
using namespace Halide;
#include "halide_image_io.h"
using namespace Halide::Tools;
#include "clock.h"
Func rgb_to_grey(Image<uint8_t> input)
{
Var x("x"), y("y"), c("c"), d("d");
Func clamped("clamped");
clamped = BoundaryConditions::repeat_edge(input);
Func greyImg("greyImg");
greyImg(x,y,d) =
clamped(x,y,0) * 0.3f
+ clamped(x,y,1) * 0.59f
+ clamped(x,y,2) * 0.11f;
return greyImg;
}
void imwrite(std::string fname, int width, int height, Func continuation)
{
Image<uint8_t> result(width, height, 1);
double t1 = current_time();
continuation.realize(result);
double t2 = current_time();
std::cout << ((t2 - t1) / 1000.0) << "\n";
save_image(result, fname);
}
Func blurX(Func continuation)
{
Var x("x"), y("y"), c("c");
Func input_16("input_16");
input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c));
Func blur_x("blur_x");
blur_x(x, y, c) = (input_16(x-1, y, c) +
2 * input_16(x, y, c) +
input_16(x+1, y, c)) / 4;
blur_x.vectorize(x, 8).parallel(y);
blur_x.compute_root();
Func output("outputBlurX");
output(x, y, c) = cast<uint8_t>(blur_x(x, y, c));
return output;
}
Func blurY(Func continuation)
{
Var x("x"), y("y"), c("c");
Func input_16("input_16");
input_16(x, y, c) = cast<uint16_t>(continuation(x, y, c));
Func blur_y("blur_y");
blur_y(x, y, c) = (input_16(x, y-1, c) +
2 * input_16(x, y, c) +
input_16(x, y+1, c)) / 4;
blur_y.vectorize(y, 8).parallel(x);
blur_y.compute_root();
Func output("outputBlurY");
output(x, y, c) = cast<uint8_t>(blur_y(x, y, c));
return output;
}
Func brightenBy(int brightenByVal, Func continuation)
{
Func brighten("brighten");
Var x, y, c;
Expr value = continuation(x, y, c);
value = Halide::cast<float>(value);
value = value + brightenByVal;
value = Halide::min(value, 255.0f);
value = Halide::cast<uint8_t>(value);
brighten(x, y, c) = value;
brighten.vectorize(x, 8).parallel(y);
brighten.compute_root();
return brighten;
}
Func darkenBy(int darkenByVal, Func continuation)
{
Func darken("darken");
Var x, y, c;
Expr value = continuation(x, y, c);
value = Halide::cast<float>(value);
value = value - darkenByVal;
value = Halide::cast<uint8_t>(value);
darken(x, y, c) = value;
darken.vectorize(x, 8).parallel(y);
darken.compute_root();
return darken;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unitconv.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2007-03-05 14:42:10 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include "unitconv.hxx"
#include "global.hxx"
#include "viewopti.hxx" //! move ScLinkConfigItem to separate header!
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
// --------------------------------------------------------------------
const sal_Unicode cDelim = 0x01; // Delimiter zwischen From und To
// --- ScUnitConverterData --------------------------------------------
ScUnitConverterData::ScUnitConverterData( const String& rFromUnit,
const String& rToUnit, double fVal )
:
StrData( rFromUnit ),
fValue( fVal )
{
String aTmp;
ScUnitConverterData::BuildIndexString( aTmp, rFromUnit, rToUnit );
SetString( aTmp );
}
ScUnitConverterData::ScUnitConverterData( const ScUnitConverterData& r )
:
StrData( r ),
fValue( r.fValue )
{
}
DataObject* ScUnitConverterData::Clone() const
{
return new ScUnitConverterData( *this );
}
// static
void ScUnitConverterData::BuildIndexString( String& rStr,
const String& rFromUnit, const String& rToUnit )
{
#if 1
// case sensitive
rStr = rFromUnit;
rStr += cDelim;
rStr += rToUnit;
#else
// not case sensitive
rStr = rFromUnit;
String aTo( rToUnit );
ScGlobal::pCharClass->toUpper( rStr );
ScGlobal::pCharClass->toUpper( aTo );
rStr += cDelim;
rStr += aTo;
#endif
}
// --- ScUnitConverter ------------------------------------------------
#define CFGPATH_UNIT "Office.Calc/UnitConversion"
#define CFGSTR_UNIT_FROM "FromUnit"
#define CFGSTR_UNIT_TO "ToUnit"
#define CFGSTR_UNIT_FACTOR "Factor"
ScUnitConverter::ScUnitConverter( USHORT nInit, USHORT nDeltaP ) :
StrCollection( nInit, nDeltaP, FALSE )
{
// read from configuration - "convert.ini" is no longer used
//! config item as member to allow change of values
ScLinkConfigItem aConfigItem( OUString::createFromAscii( CFGPATH_UNIT ) );
// empty node name -> use the config item's path itself
OUString aEmptyString;
Sequence<OUString> aNodeNames = aConfigItem.GetNodeNames( aEmptyString );
long nNodeCount = aNodeNames.getLength();
if ( nNodeCount )
{
const OUString* pNodeArray = aNodeNames.getConstArray();
Sequence<OUString> aValNames( nNodeCount * 3 );
OUString* pValNameArray = aValNames.getArray();
const OUString sSlash('/');
long nIndex = 0;
for (long i=0; i<nNodeCount; i++)
{
OUString sPrefix = pNodeArray[i];
sPrefix += sSlash;
pValNameArray[nIndex] = sPrefix;
pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_FROM );
pValNameArray[nIndex] = sPrefix;
pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_TO );
pValNameArray[nIndex] = sPrefix;
pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_FACTOR );
}
Sequence<Any> aProperties = aConfigItem.GetProperties(aValNames);
if (aProperties.getLength() == aValNames.getLength())
{
const Any* pProperties = aProperties.getConstArray();
OUString sFromUnit;
OUString sToUnit;
double fFactor = 0;
nIndex = 0;
for (long i=0; i<nNodeCount; i++)
{
pProperties[nIndex++] >>= sFromUnit;
pProperties[nIndex++] >>= sToUnit;
pProperties[nIndex++] >>= fFactor;
ScUnitConverterData* pNew = new ScUnitConverterData( sFromUnit, sToUnit, fFactor );
if ( !Insert( pNew ) )
delete pNew;
}
}
}
}
BOOL ScUnitConverter::GetValue( double& fValue, const String& rFromUnit,
const String& rToUnit ) const
{
ScUnitConverterData aSearch( rFromUnit, rToUnit );
USHORT nIndex;
if ( Search( &aSearch, nIndex ) )
{
fValue = ((const ScUnitConverterData*)(At( nIndex )))->GetValue();
return TRUE;
}
fValue = 1.0;
return FALSE;
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.320); FILE MERGED 2008/03/31 17:14:19 rt 1.7.320.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: unitconv.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#include <com/sun/star/uno/Any.hxx>
#include <com/sun/star/uno/Sequence.hxx>
#include "unitconv.hxx"
#include "global.hxx"
#include "viewopti.hxx" //! move ScLinkConfigItem to separate header!
using namespace utl;
using namespace rtl;
using namespace com::sun::star::uno;
// --------------------------------------------------------------------
const sal_Unicode cDelim = 0x01; // Delimiter zwischen From und To
// --- ScUnitConverterData --------------------------------------------
ScUnitConverterData::ScUnitConverterData( const String& rFromUnit,
const String& rToUnit, double fVal )
:
StrData( rFromUnit ),
fValue( fVal )
{
String aTmp;
ScUnitConverterData::BuildIndexString( aTmp, rFromUnit, rToUnit );
SetString( aTmp );
}
ScUnitConverterData::ScUnitConverterData( const ScUnitConverterData& r )
:
StrData( r ),
fValue( r.fValue )
{
}
DataObject* ScUnitConverterData::Clone() const
{
return new ScUnitConverterData( *this );
}
// static
void ScUnitConverterData::BuildIndexString( String& rStr,
const String& rFromUnit, const String& rToUnit )
{
#if 1
// case sensitive
rStr = rFromUnit;
rStr += cDelim;
rStr += rToUnit;
#else
// not case sensitive
rStr = rFromUnit;
String aTo( rToUnit );
ScGlobal::pCharClass->toUpper( rStr );
ScGlobal::pCharClass->toUpper( aTo );
rStr += cDelim;
rStr += aTo;
#endif
}
// --- ScUnitConverter ------------------------------------------------
#define CFGPATH_UNIT "Office.Calc/UnitConversion"
#define CFGSTR_UNIT_FROM "FromUnit"
#define CFGSTR_UNIT_TO "ToUnit"
#define CFGSTR_UNIT_FACTOR "Factor"
ScUnitConverter::ScUnitConverter( USHORT nInit, USHORT nDeltaP ) :
StrCollection( nInit, nDeltaP, FALSE )
{
// read from configuration - "convert.ini" is no longer used
//! config item as member to allow change of values
ScLinkConfigItem aConfigItem( OUString::createFromAscii( CFGPATH_UNIT ) );
// empty node name -> use the config item's path itself
OUString aEmptyString;
Sequence<OUString> aNodeNames = aConfigItem.GetNodeNames( aEmptyString );
long nNodeCount = aNodeNames.getLength();
if ( nNodeCount )
{
const OUString* pNodeArray = aNodeNames.getConstArray();
Sequence<OUString> aValNames( nNodeCount * 3 );
OUString* pValNameArray = aValNames.getArray();
const OUString sSlash('/');
long nIndex = 0;
for (long i=0; i<nNodeCount; i++)
{
OUString sPrefix = pNodeArray[i];
sPrefix += sSlash;
pValNameArray[nIndex] = sPrefix;
pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_FROM );
pValNameArray[nIndex] = sPrefix;
pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_TO );
pValNameArray[nIndex] = sPrefix;
pValNameArray[nIndex++] += OUString::createFromAscii( CFGSTR_UNIT_FACTOR );
}
Sequence<Any> aProperties = aConfigItem.GetProperties(aValNames);
if (aProperties.getLength() == aValNames.getLength())
{
const Any* pProperties = aProperties.getConstArray();
OUString sFromUnit;
OUString sToUnit;
double fFactor = 0;
nIndex = 0;
for (long i=0; i<nNodeCount; i++)
{
pProperties[nIndex++] >>= sFromUnit;
pProperties[nIndex++] >>= sToUnit;
pProperties[nIndex++] >>= fFactor;
ScUnitConverterData* pNew = new ScUnitConverterData( sFromUnit, sToUnit, fFactor );
if ( !Insert( pNew ) )
delete pNew;
}
}
}
}
BOOL ScUnitConverter::GetValue( double& fValue, const String& rFromUnit,
const String& rToUnit ) const
{
ScUnitConverterData aSearch( rFromUnit, rToUnit );
USHORT nIndex;
if ( Search( &aSearch, nIndex ) )
{
fValue = ((const ScUnitConverterData*)(At( nIndex )))->GetValue();
return TRUE;
}
fValue = 1.0;
return FALSE;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docsh2.cxx,v $
*
* $Revision: 1.18 $
*
* last change: $Author: rt $ $Date: 2006-05-04 15:03:15 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifdef PCH
#include "ui_pch.hxx"
#endif
#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif
#pragma hdrstop
#include <svx/xtable.hxx>
#include "scitems.hxx"
#include <tools/gen.hxx>
#include <svtools/ctrltool.hxx>
#include <svx/flstitem.hxx>
#include <svx/drawitem.hxx>
#include <sfx2/printer.hxx>
#include <svtools/smplhint.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdoole2.hxx>
#include <vcl/svapp.hxx>
#include <svx/asiancfg.hxx>
#include <svx/forbiddencharacterstable.hxx>
#include <svx/unolingu.hxx>
#include <rtl/logfile.hxx>
// INCLUDE ---------------------------------------------------------------
/*
#include <svdrwetc.hxx>
#include <svdrwobx.hxx>
#include <sostor.hxx>
*/
#include "drwlayer.hxx"
#include "stlpool.hxx"
#include "docsh.hxx"
#include "docfunc.hxx"
#include "sc.hrc"
using namespace com::sun::star;
//------------------------------------------------------------------
BOOL __EXPORT ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
{
RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::InitNew" );
BOOL bRet = SfxObjectShell::InitNew( xStor );
aDocument.MakeTable(0);
// zusaetzliche Tabellen werden von der ersten View angelegt,
// wenn bIsEmpty dann noch TRUE ist
if( bRet )
{
Size aSize( (long) ( STD_COL_WIDTH * HMM_PER_TWIPS * OLE_STD_CELLS_X ),
(long) ( ScGlobal::nStdRowHeight * HMM_PER_TWIPS * OLE_STD_CELLS_Y ) );
// hier muss auch der Start angepasst werden
SetVisAreaOrSize( Rectangle( Point(), aSize ), TRUE );
}
// InitOptions sets the document languages, must be called before CreateStandardStyles
InitOptions();
aDocument.GetStyleSheetPool()->CreateStandardStyles();
aDocument.UpdStlShtPtrsFrmNms();
// SetDocumentModified ist in Load/InitNew nicht mehr erlaubt!
InitItems();
CalcOutputFactor();
return bRet;
}
//------------------------------------------------------------------
BOOL ScDocShell::IsEmpty() const
{
return bIsEmpty;
}
void ScDocShell::ResetEmpty()
{
bIsEmpty = FALSE;
}
//------------------------------------------------------------------
void ScDocShell::InitItems()
{
// AllItemSet fuer Controller mit benoetigten Items fuellen:
// if ( pFontList )
// delete pFontList;
// Druck-Optionen werden beim Drucken und evtl. in GetPrinter gesetzt
// pFontList = new FontList( GetPrinter(), Application::GetDefaultDevice() );
//PutItem( SvxFontListItem( pFontList, SID_ATTR_CHAR_FONTLIST ) );
UpdateFontList();
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (pDrawLayer)
{
PutItem( SvxColorTableItem ( pDrawLayer->GetColorTable() ) );
PutItem( SvxGradientListItem( pDrawLayer->GetGradientList() ) );
PutItem( SvxHatchListItem ( pDrawLayer->GetHatchList() ) );
PutItem( SvxBitmapListItem ( pDrawLayer->GetBitmapList() ) );
PutItem( SvxDashListItem ( pDrawLayer->GetDashList() ) );
PutItem( SvxLineEndListItem ( pDrawLayer->GetLineEndList() ) );
// andere Anpassungen nach dem Anlegen des DrawLayers
pDrawLayer->SetNotifyUndoActionHdl( LINK( pDocFunc, ScDocFunc, NotifyDrawUndo ) );
//if (SfxObjectShell::HasSbxObject())
pDrawLayer->UpdateBasic(); // DocShell-Basic in DrawPages setzen
}
else
{
// always use global color table instead of local copy
PutItem( SvxColorTableItem( XColorTable::GetStdColorTable() ) );
}
if ( !aDocument.GetForbiddenCharacters().isValid() ||
!aDocument.IsValidAsianCompression() || !aDocument.IsValidAsianKerning() )
{
// get settings from SvxAsianConfig
SvxAsianConfig aAsian( sal_False );
if ( !aDocument.GetForbiddenCharacters().isValid() )
{
// set forbidden characters if necessary
uno::Sequence<lang::Locale> aLocales = aAsian.GetStartEndCharLocales();
if (aLocales.getLength())
{
vos::ORef<SvxForbiddenCharactersTable> xForbiddenTable =
new SvxForbiddenCharactersTable( aDocument.GetServiceManager() );
const lang::Locale* pLocales = aLocales.getConstArray();
for (sal_Int32 i = 0; i < aLocales.getLength(); i++)
{
i18n::ForbiddenCharacters aForbidden;
aAsian.GetStartEndChars( pLocales[i], aForbidden.beginLine, aForbidden.endLine );
LanguageType eLang = SvxLocaleToLanguage(pLocales[i]);
//pDoc->SetForbiddenCharacters( eLang, aForbidden );
xForbiddenTable->SetForbiddenCharacters( eLang, aForbidden );
}
aDocument.SetForbiddenCharacters( xForbiddenTable );
}
}
if ( !aDocument.IsValidAsianCompression() )
{
// set compression mode from configuration if not already set (e.g. XML import)
aDocument.SetAsianCompression( aAsian.GetCharDistanceCompression() );
}
if ( !aDocument.IsValidAsianKerning() )
{
// set asian punctuation kerning from configuration if not already set (e.g. XML import)
aDocument.SetAsianKerning( !aAsian.IsKerningWesternTextOnly() ); // reversed
}
}
}
//------------------------------------------------------------------
void ScDocShell::ResetDrawObjectShell()
{
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (pDrawLayer)
pDrawLayer->SetObjectShell( NULL );
}
//------------------------------------------------------------------
void __EXPORT ScDocShell::Activate()
{
}
void __EXPORT ScDocShell::Deactivate()
{
}
//------------------------------------------------------------------
ScDrawLayer* ScDocShell::MakeDrawLayer()
{
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (!pDrawLayer)
{
RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::MakeDrawLayer" );
aDocument.InitDrawLayer(this);
pDrawLayer = aDocument.GetDrawLayer();
InitItems(); // incl. Undo und Basic
Broadcast( SfxSimpleHint( SC_HINT_DRWLAYER_NEW ) );
if (nDocumentLock)
pDrawLayer->setLock(TRUE);
}
return pDrawLayer;
}
//------------------------------------------------------------------
void ScDocShell::RemoveUnknownObjects()
{
// OLE-Objekte loeschen, wenn kein Drawing-Objekt dazu existiert
// Loeschen wie in SvPersist::CleanUp
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
uno::Sequence < rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
for( sal_Int32 i=0; i<aNames.getLength(); i++ )
{
String aObjName = aNames[i];
BOOL bFound = FALSE;
if ( pDrawLayer )
{
SCTAB nTabCount = static_cast<sal_Int16>(pDrawLayer->GetPageCount());
for (SCTAB nTab=0; nTab<nTabCount && !bFound; nTab++)
{
SdrPage* pPage = pDrawLayer->GetPage(static_cast<sal_uInt16>(nTab));
DBG_ASSERT(pPage,"Page ?");
if (pPage)
{
SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
SdrObject* pObject = aIter.Next();
while (pObject && !bFound)
{
// name from InfoObject is PersistName
if ( pObject->ISA(SdrOle2Obj) &&
static_cast<SdrOle2Obj*>(pObject)->GetPersistName() == aObjName )
bFound = TRUE;
pObject = aIter.Next();
}
}
}
}
if (!bFound)
{
//TODO/LATER: hacks not supported anymore
//DBG_ASSERT(pEle->GetRefCount()==2, "Loeschen von referenziertem Storage");
GetEmbeddedObjectContainer().RemoveEmbeddedObject( aObjName );
}
else
i++;
}
}
<commit_msg>INTEGRATION: CWS pchfix01 (1.18.58); FILE MERGED 2006/07/12 10:02:32 kaib 1.18.58.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: docsh2.cxx,v $
*
* $Revision: 1.19 $
*
* last change: $Author: kz $ $Date: 2006-07-21 13:37:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sc.hxx"
#ifndef _SVDPAGE_HXX //autogen
#include <svx/svdpage.hxx>
#endif
#include <svx/xtable.hxx>
#include "scitems.hxx"
#include <tools/gen.hxx>
#include <svtools/ctrltool.hxx>
#include <svx/flstitem.hxx>
#include <svx/drawitem.hxx>
#include <sfx2/printer.hxx>
#include <svtools/smplhint.hxx>
#include <svx/svditer.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdoole2.hxx>
#include <vcl/svapp.hxx>
#include <svx/asiancfg.hxx>
#include <svx/forbiddencharacterstable.hxx>
#include <svx/unolingu.hxx>
#include <rtl/logfile.hxx>
// INCLUDE ---------------------------------------------------------------
/*
#include <svdrwetc.hxx>
#include <svdrwobx.hxx>
#include <sostor.hxx>
*/
#include "drwlayer.hxx"
#include "stlpool.hxx"
#include "docsh.hxx"
#include "docfunc.hxx"
#include "sc.hrc"
using namespace com::sun::star;
//------------------------------------------------------------------
BOOL __EXPORT ScDocShell::InitNew( const uno::Reference < embed::XStorage >& xStor )
{
RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::InitNew" );
BOOL bRet = SfxObjectShell::InitNew( xStor );
aDocument.MakeTable(0);
// zusaetzliche Tabellen werden von der ersten View angelegt,
// wenn bIsEmpty dann noch TRUE ist
if( bRet )
{
Size aSize( (long) ( STD_COL_WIDTH * HMM_PER_TWIPS * OLE_STD_CELLS_X ),
(long) ( ScGlobal::nStdRowHeight * HMM_PER_TWIPS * OLE_STD_CELLS_Y ) );
// hier muss auch der Start angepasst werden
SetVisAreaOrSize( Rectangle( Point(), aSize ), TRUE );
}
// InitOptions sets the document languages, must be called before CreateStandardStyles
InitOptions();
aDocument.GetStyleSheetPool()->CreateStandardStyles();
aDocument.UpdStlShtPtrsFrmNms();
// SetDocumentModified ist in Load/InitNew nicht mehr erlaubt!
InitItems();
CalcOutputFactor();
return bRet;
}
//------------------------------------------------------------------
BOOL ScDocShell::IsEmpty() const
{
return bIsEmpty;
}
void ScDocShell::ResetEmpty()
{
bIsEmpty = FALSE;
}
//------------------------------------------------------------------
void ScDocShell::InitItems()
{
// AllItemSet fuer Controller mit benoetigten Items fuellen:
// if ( pFontList )
// delete pFontList;
// Druck-Optionen werden beim Drucken und evtl. in GetPrinter gesetzt
// pFontList = new FontList( GetPrinter(), Application::GetDefaultDevice() );
//PutItem( SvxFontListItem( pFontList, SID_ATTR_CHAR_FONTLIST ) );
UpdateFontList();
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (pDrawLayer)
{
PutItem( SvxColorTableItem ( pDrawLayer->GetColorTable() ) );
PutItem( SvxGradientListItem( pDrawLayer->GetGradientList() ) );
PutItem( SvxHatchListItem ( pDrawLayer->GetHatchList() ) );
PutItem( SvxBitmapListItem ( pDrawLayer->GetBitmapList() ) );
PutItem( SvxDashListItem ( pDrawLayer->GetDashList() ) );
PutItem( SvxLineEndListItem ( pDrawLayer->GetLineEndList() ) );
// andere Anpassungen nach dem Anlegen des DrawLayers
pDrawLayer->SetNotifyUndoActionHdl( LINK( pDocFunc, ScDocFunc, NotifyDrawUndo ) );
//if (SfxObjectShell::HasSbxObject())
pDrawLayer->UpdateBasic(); // DocShell-Basic in DrawPages setzen
}
else
{
// always use global color table instead of local copy
PutItem( SvxColorTableItem( XColorTable::GetStdColorTable() ) );
}
if ( !aDocument.GetForbiddenCharacters().isValid() ||
!aDocument.IsValidAsianCompression() || !aDocument.IsValidAsianKerning() )
{
// get settings from SvxAsianConfig
SvxAsianConfig aAsian( sal_False );
if ( !aDocument.GetForbiddenCharacters().isValid() )
{
// set forbidden characters if necessary
uno::Sequence<lang::Locale> aLocales = aAsian.GetStartEndCharLocales();
if (aLocales.getLength())
{
vos::ORef<SvxForbiddenCharactersTable> xForbiddenTable =
new SvxForbiddenCharactersTable( aDocument.GetServiceManager() );
const lang::Locale* pLocales = aLocales.getConstArray();
for (sal_Int32 i = 0; i < aLocales.getLength(); i++)
{
i18n::ForbiddenCharacters aForbidden;
aAsian.GetStartEndChars( pLocales[i], aForbidden.beginLine, aForbidden.endLine );
LanguageType eLang = SvxLocaleToLanguage(pLocales[i]);
//pDoc->SetForbiddenCharacters( eLang, aForbidden );
xForbiddenTable->SetForbiddenCharacters( eLang, aForbidden );
}
aDocument.SetForbiddenCharacters( xForbiddenTable );
}
}
if ( !aDocument.IsValidAsianCompression() )
{
// set compression mode from configuration if not already set (e.g. XML import)
aDocument.SetAsianCompression( aAsian.GetCharDistanceCompression() );
}
if ( !aDocument.IsValidAsianKerning() )
{
// set asian punctuation kerning from configuration if not already set (e.g. XML import)
aDocument.SetAsianKerning( !aAsian.IsKerningWesternTextOnly() ); // reversed
}
}
}
//------------------------------------------------------------------
void ScDocShell::ResetDrawObjectShell()
{
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (pDrawLayer)
pDrawLayer->SetObjectShell( NULL );
}
//------------------------------------------------------------------
void __EXPORT ScDocShell::Activate()
{
}
void __EXPORT ScDocShell::Deactivate()
{
}
//------------------------------------------------------------------
ScDrawLayer* ScDocShell::MakeDrawLayer()
{
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
if (!pDrawLayer)
{
RTL_LOGFILE_CONTEXT_AUTHOR ( aLog, "sc", "nn93723", "ScDocShell::MakeDrawLayer" );
aDocument.InitDrawLayer(this);
pDrawLayer = aDocument.GetDrawLayer();
InitItems(); // incl. Undo und Basic
Broadcast( SfxSimpleHint( SC_HINT_DRWLAYER_NEW ) );
if (nDocumentLock)
pDrawLayer->setLock(TRUE);
}
return pDrawLayer;
}
//------------------------------------------------------------------
void ScDocShell::RemoveUnknownObjects()
{
// OLE-Objekte loeschen, wenn kein Drawing-Objekt dazu existiert
// Loeschen wie in SvPersist::CleanUp
ScDrawLayer* pDrawLayer = aDocument.GetDrawLayer();
uno::Sequence < rtl::OUString > aNames = GetEmbeddedObjectContainer().GetObjectNames();
for( sal_Int32 i=0; i<aNames.getLength(); i++ )
{
String aObjName = aNames[i];
BOOL bFound = FALSE;
if ( pDrawLayer )
{
SCTAB nTabCount = static_cast<sal_Int16>(pDrawLayer->GetPageCount());
for (SCTAB nTab=0; nTab<nTabCount && !bFound; nTab++)
{
SdrPage* pPage = pDrawLayer->GetPage(static_cast<sal_uInt16>(nTab));
DBG_ASSERT(pPage,"Page ?");
if (pPage)
{
SdrObjListIter aIter( *pPage, IM_DEEPNOGROUPS );
SdrObject* pObject = aIter.Next();
while (pObject && !bFound)
{
// name from InfoObject is PersistName
if ( pObject->ISA(SdrOle2Obj) &&
static_cast<SdrOle2Obj*>(pObject)->GetPersistName() == aObjName )
bFound = TRUE;
pObject = aIter.Next();
}
}
}
}
if (!bFound)
{
//TODO/LATER: hacks not supported anymore
//DBG_ASSERT(pEle->GetRefCount()==2, "Loeschen von referenziertem Storage");
GetEmbeddedObjectContainer().RemoveEmbeddedObject( aObjName );
}
else
i++;
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_LINEARSOLVER_MinResLinearSolver_INL
#define SOFA_COMPONENT_LINEARSOLVER_MinResLinearSolver_INL
#include <sofa/component/linearsolver/MinResLinearSolver.h>
#include <sofa/core/visual/VisualParams.h>
#include <sofa/component/linearsolver/FullMatrix.h>
#include <sofa/component/linearsolver/SparseMatrix.h>
#include <sofa/component/linearsolver/CompressedRowSparseMatrix.h>
#include <sofa/simulation/common/MechanicalVisitor.h>
#include <sofa/helper/system/thread/CTime.h>
#include <sofa/helper/AdvancedTimer.h>
#include <sofa/core/ObjectFactory.h>
#include <iostream>
namespace sofa
{
namespace component
{
namespace linearsolver
{
using core::VecId;
using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
using namespace sofa::simulation;
/// Linear system solver using the conjugate gradient iterative algorithm
template<class TMatrix, class TVector>
MinResLinearSolver<TMatrix,TVector>::MinResLinearSolver()
: f_maxIter( initData(&f_maxIter,(unsigned)25,"iterations","maximum number of iterations of the Conjugate Gradient solution") )
, f_tolerance( initData(&f_tolerance,1e-5,"tolerance","desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)") )
, f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
, f_graph( initData(&f_graph,"graph","Graph of residuals at each iteration") )
{
f_graph.setWidget("graph");
// f_graph.setReadOnly(true);
}
template<class TMatrix, class TVector>
void MinResLinearSolver<TMatrix,TVector>::resetSystem()
{
f_graph.beginEdit()->clear();
f_graph.endEdit();
Inherit::resetSystem();
}
template<class TMatrix, class TVector>
void MinResLinearSolver<TMatrix,TVector>::setSystemMBKMatrix(const sofa::core::MechanicalParams* mparams)
{
Inherit::setSystemMBKMatrix(mparams);
}
/// Solve Ax=b
/// code issued (and modified) from tminres (https://code.google.com/p/tminres/)
// - Umberto Villa, Emory University - [email protected]
// - Michael Saunders, Stanford University
// - Santiago Akle, Stanford University
template<class TMatrix, class TVector>
void MinResLinearSolver<TMatrix,TVector>::solve(Matrix& A, Vector& x, Vector& b)
{
const double& tol = f_tolerance.getValue();
const unsigned& max_iter = f_maxIter.getValue();
double eps(std::numeric_limits<double>::epsilon());
int istop(0);
unsigned itn(0);
double Anorm(0.0), Acond(0.0)/*, Arnorm(0.0)*/;
double rnorm(0.0), ynorm(0.0);
bool done(false);
// Step 1
/*
* Set up y and v for the first Lanczos vector v1.
* y = beta1 P' v1, where P = C^(-1).
* v is really P'v1
*/
const core::ExecParams* params = core::ExecParams::defaultInstance();
typename Inherit::TempVectorContainer vtmp(this, params, A, x, b);
Vector& r1 = *vtmp.createTempVector();
Vector& y = *vtmp.createTempVector();
Vector& w = *vtmp.createTempVector();
Vector& w1 = *vtmp.createTempVector();
Vector& w2 = *vtmp.createTempVector();
Vector& r2 = *vtmp.createTempVector();
Vector& v = *vtmp.createTempVector();
r1 = A * x;
// r1 = b - r1;
r1 *= -1;
r1 += b;
y = r1;
double beta1(0.0);
beta1 = r1.dot( y );
// Test for an indefined preconditioner
// If b = 0 exactly stop with x = x0.
if(beta1 < 0.0)
{
istop = 9;
done = true;
}
else
{
if(beta1 == 0.0)
{
done = true;
}
else
beta1 = sqrt(beta1); // Normalize y to get v1 later
}
// TODO: port symmetry checks for A
// STEP 2
/* Initialize other quantities */
double oldb(0.0), beta(beta1), dbar(0.0), epsln(0.0), oldeps(0.0);
double qrnorm(beta1), phi(0.0), phibar(beta1), rhs1(beta1);
double rhs2(0.0), tnorm2(0.0), ynorm2(0.0);
double cs(-1.0), sn(0.0);
double gmax(0.0), gmin(std::numeric_limits<double>::max( ));
double alpha(0.0), gamma(0.0);
double delta(0.0), gbar(0.0);
double z(0.0);
// ( w ) = (* w1 ) = ( w2 ) = 0.0;
r2 = r1;
/* Main Iteration */
if(!done)
{
for(itn = 0; itn < max_iter; ++itn)
{
// STEP 3
/*
-----------------------------------------------------------------
Obtain quantities for the next Lanczos vector vk+1, k = 1, 2,...
The general iteration is similar to the case k = 1 with v0 = 0:
p1 = Operator * v1 - beta1 * v0,
alpha1 = v1'p1,
q2 = p2 - alpha1 * v1,
beta2^2 = q2'q2,
v2 = (1/beta2) q2.
Again, y = betak P vk, where P = C**(-1).
.... more description needed.
-----------------------------------------------------------------
*/
double s(1./beta); //Normalize previous vector (in y)
v = y;
v *= s; // v = vk if P = I
y = A * v;
if(itn) y.peq( r1, -beta/oldb );
alpha = v.dot( y ); // alphak
y.peq( r2, -alpha/beta ); // y += -a/b * r2
r1 = r2;
r2 = y;
y = r2;
oldb = beta; //oldb = betak
beta = r2.dot( y );
if(beta < 0)
{
istop = 9;
break;
}
beta = sqrt(beta);
tnorm2 += alpha*alpha + oldb*oldb + beta*beta;
if(itn == 0) //Initialize a few things
{
if(beta/beta1 < 10.0*eps)
istop = 10;
}
// Apply previous rotation Q_{k-1} to get
// [delta_k epsln_{k+1}] = [cs sn] [dbar_k 0]
// [gbar_k dbar_{k+1}] [sn -cs] [alpha_k beta_{k+1}].
oldeps = epsln;
delta = cs*dbar + sn*alpha;
gbar = sn*dbar - cs*alpha;
epsln = sn*beta;
dbar = - cs*beta;
double root(sqrt(gbar*gbar + dbar*dbar));
//Arnorm = phibar * root; // ||Ar_{k-1}||
// Compute next plane rotation Q_k
gamma = sqrt(gbar*gbar + beta*beta); // gamma_k
gamma = std::max(gamma, eps);
cs = gbar/gamma; // c_k
sn = beta/gamma; // s_k
phi = cs*phibar; // phi_k
phibar = sn*phibar; // phibar_{k+1}
// Update x
double denom(1./gamma);
w1 = w2;
w2 = w;
// add(-oldeps, w1, -delta, w2, w);
w = w1;
w *= -oldeps;
w.peq( w2, -delta );
// add(denom, v, w, w);
w *= denom;
w.peq( v, denom );
// add(x, phi, w, x);
x.peq( w, phi );
// go round again
gmax = std::max(gmax, gamma);
gmin = std::min(gmin, gamma);
z = rhs1/gamma;
rhs1 = rhs2 - delta*z;
rhs2 = - epsln*z;
// Estimate various norms
Anorm = sqrt(tnorm2);
ynorm2 = x.dot( x );
ynorm = sqrt(ynorm2);
double epsa(Anorm*eps);
double epsx(epsa*ynorm);
// double epsr(Anorm*ynorm*tol);
double diag(gbar);
if(0 == diag)
diag = epsa;
qrnorm = phibar;
rnorm = qrnorm;
double test1(0.0), test2(0.0);
test1 = rnorm/(Anorm*ynorm); // ||r||/(||A|| ||x||)
test2 = root/ Anorm; // ||A r_{k-1}|| / (||A|| ||r_{k-1}||)
// Estimate cond(A)
/*
In this version we look at the diagonals of R in the
factorization of the lower Hessenberg matrix, Q * H = R,
where H is the tridiagonal matrix from Lanczos with one
extra row, beta(k+1) e_k^T.
*/
Acond = gmax/gmin;
//See if any of the stopping criteria is satisfied
if(0 == istop)
{
double t1(1.0+test1), t2(1.0+test2); //This test work if tol < eps
if(t2 <= 1.) istop = 2;
if(t1 <= 1.) istop = 1;
if(itn >= max_iter-1) istop = 6;
if(Acond >= .1/eps) istop = 4;
if(epsx >= beta1) istop = 3;
if(test2 <= tol ) istop = 2;
if(test1 <= tol) istop = 1;
}
if(0 != istop)
break;
}
vtmp.deleteTempVector(&r1);
vtmp.deleteTempVector(&y);
vtmp.deleteTempVector(&w);
vtmp.deleteTempVector(&w1);
vtmp.deleteTempVector(&w2);
vtmp.deleteTempVector(&r2);
vtmp.deleteTempVector(&v);
}
}
} // namespace linearsolver
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_LINEARSOLVER_MinResLinearSolver_INL
<commit_msg>r9215/sofa : added convergence graph for MINRES<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_LINEARSOLVER_MinResLinearSolver_INL
#define SOFA_COMPONENT_LINEARSOLVER_MinResLinearSolver_INL
#include <sofa/component/linearsolver/MinResLinearSolver.h>
#include <sofa/core/visual/VisualParams.h>
#include <sofa/component/linearsolver/FullMatrix.h>
#include <sofa/component/linearsolver/SparseMatrix.h>
#include <sofa/component/linearsolver/CompressedRowSparseMatrix.h>
#include <sofa/simulation/common/MechanicalVisitor.h>
#include <sofa/helper/system/thread/CTime.h>
#include <sofa/helper/AdvancedTimer.h>
#include <sofa/core/ObjectFactory.h>
#include <iostream>
namespace sofa
{
namespace component
{
namespace linearsolver
{
using core::VecId;
using namespace sofa::defaulttype;
using namespace sofa::core::behavior;
using namespace sofa::simulation;
/// Linear system solver using the conjugate gradient iterative algorithm
template<class TMatrix, class TVector>
MinResLinearSolver<TMatrix,TVector>::MinResLinearSolver()
: f_maxIter( initData(&f_maxIter,(unsigned)25,"iterations","maximum number of iterations of the Conjugate Gradient solution") )
, f_tolerance( initData(&f_tolerance,1e-5,"tolerance","desired precision of the Conjugate Gradient Solution (ratio of current residual norm over initial residual norm)") )
, f_verbose( initData(&f_verbose,false,"verbose","Dump system state at each iteration") )
, f_graph( initData(&f_graph,"graph","Graph of residuals at each iteration") )
{
f_graph.setWidget("graph");
// f_graph.setReadOnly(true);
}
template<class TMatrix, class TVector>
void MinResLinearSolver<TMatrix,TVector>::resetSystem()
{
f_graph.beginEdit()->clear();
f_graph.endEdit();
Inherit::resetSystem();
}
template<class TMatrix, class TVector>
void MinResLinearSolver<TMatrix,TVector>::setSystemMBKMatrix(const sofa::core::MechanicalParams* mparams)
{
Inherit::setSystemMBKMatrix(mparams);
}
/// Solve Ax=b
/// code issued (and modified) from tminres (https://code.google.com/p/tminres/)
// - Umberto Villa, Emory University - [email protected]
// - Michael Saunders, Stanford University
// - Santiago Akle, Stanford University
template<class TMatrix, class TVector>
void MinResLinearSolver<TMatrix,TVector>::solve(Matrix& A, Vector& x, Vector& b)
{
const double& tol = f_tolerance.getValue();
const unsigned& max_iter = f_maxIter.getValue();
std::map < std::string, sofa::helper::vector<double> >& graph = *f_graph.beginEdit();
sofa::helper::vector<double>& graph_error = graph[(this->isMultiGroup()) ? this->currentNode->getName()+std::string("-Error") : std::string("Error")];
graph_error.clear();
graph_error.push_back(1);
double eps(std::numeric_limits<double>::epsilon());
int istop(0);
unsigned itn(0);
double Anorm(0.0), Acond(0.0)/*, Arnorm(0.0)*/;
double rnorm(0.0), ynorm(0.0);
bool done(false);
// Step 1
/*
* Set up y and v for the first Lanczos vector v1.
* y = beta1 P' v1, where P = C^(-1).
* v is really P'v1
*/
const core::ExecParams* params = core::ExecParams::defaultInstance();
typename Inherit::TempVectorContainer vtmp(this, params, A, x, b);
Vector& r1 = *vtmp.createTempVector();
Vector& y = *vtmp.createTempVector();
Vector& w = *vtmp.createTempVector();
Vector& w1 = *vtmp.createTempVector();
Vector& w2 = *vtmp.createTempVector();
Vector& r2 = *vtmp.createTempVector();
Vector& v = *vtmp.createTempVector();
r1 = A * x;
// r1 = b - r1;
r1 *= -1;
r1 += b;
y = r1;
double beta1(0.0);
beta1 = r1.dot( y );
// Test for an indefined preconditioner
// If b = 0 exactly stop with x = x0.
if(beta1 < 0.0)
{
istop = 9;
done = true;
}
else
{
if(beta1 == 0.0)
{
done = true;
}
else
beta1 = sqrt(beta1); // Normalize y to get v1 later
}
// TODO: port symmetry checks for A
// STEP 2
/* Initialize other quantities */
double oldb(0.0), beta(beta1), dbar(0.0), epsln(0.0), oldeps(0.0);
double qrnorm(beta1), phi(0.0), phibar(beta1), rhs1(beta1);
double rhs2(0.0), tnorm2(0.0), ynorm2(0.0);
double cs(-1.0), sn(0.0);
double gmax(0.0), gmin(std::numeric_limits<double>::max( ));
double alpha(0.0), gamma(0.0);
double delta(0.0), gbar(0.0);
double z(0.0);
// ( w ) = (* w1 ) = ( w2 ) = 0.0;
r2 = r1;
/* Main Iteration */
if(!done)
{
for(itn = 0; itn < max_iter; ++itn)
{
// STEP 3
/*
-----------------------------------------------------------------
Obtain quantities for the next Lanczos vector vk+1, k = 1, 2,...
The general iteration is similar to the case k = 1 with v0 = 0:
p1 = Operator * v1 - beta1 * v0,
alpha1 = v1'p1,
q2 = p2 - alpha1 * v1,
beta2^2 = q2'q2,
v2 = (1/beta2) q2.
Again, y = betak P vk, where P = C**(-1).
.... more description needed.
-----------------------------------------------------------------
*/
double s(1./beta); //Normalize previous vector (in y)
v = y;
v *= s; // v = vk if P = I
y = A * v;
if(itn) y.peq( r1, -beta/oldb );
alpha = v.dot( y ); // alphak
y.peq( r2, -alpha/beta ); // y += -a/b * r2
r1 = r2;
r2 = y;
y = r2;
oldb = beta; //oldb = betak
beta = r2.dot( y );
if(beta < 0)
{
istop = 9;
break;
}
beta = sqrt(beta);
tnorm2 += alpha*alpha + oldb*oldb + beta*beta;
if(itn == 0) //Initialize a few things
{
if(beta/beta1 < 10.0*eps)
istop = 10;
}
// Apply previous rotation Q_{k-1} to get
// [delta_k epsln_{k+1}] = [cs sn] [dbar_k 0]
// [gbar_k dbar_{k+1}] [sn -cs] [alpha_k beta_{k+1}].
oldeps = epsln;
delta = cs*dbar + sn*alpha;
gbar = sn*dbar - cs*alpha;
epsln = sn*beta;
dbar = - cs*beta;
double root(sqrt(gbar*gbar + dbar*dbar));
//Arnorm = phibar * root; // ||Ar_{k-1}||
// Compute next plane rotation Q_k
gamma = sqrt(gbar*gbar + beta*beta); // gamma_k
gamma = std::max(gamma, eps);
cs = gbar/gamma; // c_k
sn = beta/gamma; // s_k
phi = cs*phibar; // phi_k
phibar = sn*phibar; // phibar_{k+1}
// Update x
double denom(1./gamma);
w1 = w2;
w2 = w;
// add(-oldeps, w1, -delta, w2, w);
w = w1;
w *= -oldeps;
w.peq( w2, -delta );
// add(denom, v, w, w);
w *= denom;
w.peq( v, denom );
// add(x, phi, w, x);
x.peq( w, phi );
// go round again
gmax = std::max(gmax, gamma);
gmin = std::min(gmin, gamma);
z = rhs1/gamma;
rhs1 = rhs2 - delta*z;
rhs2 = - epsln*z;
// Estimate various norms
Anorm = sqrt(tnorm2);
ynorm2 = x.dot( x );
ynorm = sqrt(ynorm2);
double epsa(Anorm*eps);
double epsx(epsa*ynorm);
// double epsr(Anorm*ynorm*tol);
double diag(gbar);
if(0 == diag)
diag = epsa;
qrnorm = phibar;
rnorm = qrnorm;
double test1(0.0), test2(0.0);
test1 = rnorm/(Anorm*ynorm); // ||r||/(||A|| ||x||)
test2 = root/ Anorm; // ||A r_{k-1}|| / (||A|| ||r_{k-1}||)
graph_error.push_back(test1);
// Estimate cond(A)
/*
In this version we look at the diagonals of R in the
factorization of the lower Hessenberg matrix, Q * H = R,
where H is the tridiagonal matrix from Lanczos with one
extra row, beta(k+1) e_k^T.
*/
Acond = gmax/gmin;
//See if any of the stopping criteria is satisfied
if(0 == istop)
{
double t1(1.0+test1), t2(1.0+test2); //This test work if tol < eps
if(t2 <= 1.) istop = 2;
if(t1 <= 1.) istop = 1;
if(itn >= max_iter-1) istop = 6;
if(Acond >= .1/eps) istop = 4;
if(epsx >= beta1) istop = 3;
if(test2 <= tol ) istop = 2;
if(test1 <= tol) istop = 1;
}
if(0 != istop)
break;
}
vtmp.deleteTempVector(&r1);
vtmp.deleteTempVector(&y);
vtmp.deleteTempVector(&w);
vtmp.deleteTempVector(&w1);
vtmp.deleteTempVector(&w2);
vtmp.deleteTempVector(&r2);
vtmp.deleteTempVector(&v);
}
}
} // namespace linearsolver
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_LINEARSOLVER_MinResLinearSolver_INL
<|endoftext|> |
<commit_before>#include <Halide.h>
using namespace Halide;
Var x, y;
// Downsample with a 1 3 3 1 filter
Func downsample(Func f) {
Func downx, downy;
downx(x, y, _) = (f(2*x-1, y, _) + 3.0f * (f(2*x, y, _) + f(2*x+1, y, _)) + f(2*x+2, y, _)) / 8.0f;
downy(x, y, _) = (downx(x, 2*y-1, _) + 3.0f * (downx(x, 2*y, _) + downx(x, 2*y+1, _)) + downx(x, 2*y+2, _)) / 8.0f;
return downy;
}
// Upsample using bilinear interpolation
Func upsample(Func f) {
Func upx, upy;
upx(x, y, _) = 0.25f * f((x/2) - 1 + 2*(x % 2), y, _) + 0.75f * f(x/2, y, _);
upy(x, y, _) = 0.25f * upx(x, (y/2) - 1 + 2*(y % 2), _) + 0.75f * upx(x, y/2, _);
return upy;
}
int main(int argc, char **argv) {
/* THE ALGORITHM */
// Number of pyramid levels
const int J = 8;
// number of intensity levels
Param<int> levels;
// Parameters controlling the filter
Param<float> alpha, beta;
// Takes a 16-bit input
ImageParam input(UInt(16), 3);
// loop variables
Var c, k;
// Make the remapping function as a lookup table.
Func remap;
Expr fx = cast<float>(x) / 256.0f;
remap(x) = alpha*fx*exp(-fx*fx/2.0f);
// Convert to floating point
Func floating;
floating(x, y, c) = cast<float>(input(x, y, c)) / 65535.0f;
// Set a boundary condition
Func clamped;
clamped(x, y, c) = floating(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c);
// Get the luminance channel
Func gray;
gray(x, y) = 0.299f * clamped(x, y, 0) + 0.587f * clamped(x, y, 1) + 0.114f * clamped(x, y, 2);
// Make the processed Gaussian pyramid.
Func gPyramid[J];
// Do a lookup into a lut with 256 entires per intensity level
Expr level = k * (1.0f / (levels - 1));
Expr idx = gray(x, y)*cast<float>(levels-1)*256.0f;
idx = clamp(cast<int>(idx), 0, (levels-1)*256);
gPyramid[0](x, y, k) = beta*(gray(x, y) - level) + level + remap(idx - 256*k);
for (int j = 1; j < J; j++) {
gPyramid[j](x, y, k) = downsample(gPyramid[j-1])(x, y, k);
}
// Get its laplacian pyramid
Func lPyramid[J];
lPyramid[J-1](x, y, k) = gPyramid[J-1](x, y, k);
for (int j = J-2; j >= 0; j--) {
lPyramid[j](x, y, k) = gPyramid[j](x, y, k) - upsample(gPyramid[j+1])(x, y, k);
}
// Make the Gaussian pyramid of the input
Func inGPyramid[J];
inGPyramid[0](x, y) = gray(x, y);
for (int j = 1; j < J; j++) {
inGPyramid[j](x, y) = downsample(inGPyramid[j-1])(x, y);
}
// Make the laplacian pyramid of the output
Func outLPyramid[J];
for (int j = 0; j < J; j++) {
// Split input pyramid value into integer and floating parts
Expr level = inGPyramid[j](x, y) * cast<float>(levels-1);
Expr li = clamp(cast<int>(level), 0, levels-2);
Expr lf = level - cast<float>(li);
// Linearly interpolate between the nearest processed pyramid levels
outLPyramid[j](x, y) = (1.0f - lf) * lPyramid[j](x, y, li) + lf * lPyramid[j](x, y, li+1);
}
// Make the Gaussian pyramid of the output
Func outGPyramid[J];
outGPyramid[J-1](x, y) = outLPyramid[J-1](x, y);
for (int j = J-2; j >= 0; j--) {
outGPyramid[j](x, y) = upsample(outGPyramid[j+1])(x, y) + outLPyramid[j](x, y);
}
// Reintroduce color (Connelly: use eps to avoid scaling up noise w/ apollo3.png input)
Func color;
float eps = 0.01f;
color(x, y, c) = outGPyramid[0](x, y) * (clamped(x, y, c)+eps) / (gray(x, y)+eps);
Func output("local_laplacian");
// Convert back to 16-bit
output(x, y, c) = cast<uint16_t>(clamp(color(x, y, c), 0.0f, 1.0f) * 65535.0f);
/* THE SCHEDULE */
remap.compute_root();
Target target = get_target_from_environment();
if (target.has_gpu_feature()) {
// gpu schedule
output.compute_root().gpu_tile(x, y, 32, 16, GPU_Default);
for (int j = 0; j < J; j++) {
int blockw = 32, blockh = 16;
if (j > 3) {
blockw = 2;
blockh = 2;
}
if (j > 0) inGPyramid[j].compute_root().gpu_tile(x, y, blockw, blockh, GPU_Default);
if (j > 0) gPyramid[j].compute_root().reorder(k, x, y).gpu_tile(x, y, blockw, blockh, GPU_Default);
outGPyramid[j].compute_root().gpu_tile(x, y, blockw, blockh, GPU_Default);
}
} else {
// cpu schedule
Var yi;
output.parallel(y, 4).vectorize(x, 4);
gray.compute_root().parallel(y, 4).vectorize(x, 4);
for (int j = 0; j < 4; j++) {
if (j > 0) inGPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4);
if (j > 0) gPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4);
outGPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4);
}
for (int j = 4; j < J; j++) {
inGPyramid[j].compute_root().parallel(y);
gPyramid[j].compute_root().parallel(k);
outGPyramid[j].compute_root().parallel(y);
}
}
output.compile_to_file("local_laplacian", levels, alpha, beta, input, target);
return 0;
}
<commit_msg>Reduce block size for local laplacian for lesser gpus<commit_after>#include <Halide.h>
using namespace Halide;
Var x, y;
// Downsample with a 1 3 3 1 filter
Func downsample(Func f) {
Func downx, downy;
downx(x, y, _) = (f(2*x-1, y, _) + 3.0f * (f(2*x, y, _) + f(2*x+1, y, _)) + f(2*x+2, y, _)) / 8.0f;
downy(x, y, _) = (downx(x, 2*y-1, _) + 3.0f * (downx(x, 2*y, _) + downx(x, 2*y+1, _)) + downx(x, 2*y+2, _)) / 8.0f;
return downy;
}
// Upsample using bilinear interpolation
Func upsample(Func f) {
Func upx, upy;
upx(x, y, _) = 0.25f * f((x/2) - 1 + 2*(x % 2), y, _) + 0.75f * f(x/2, y, _);
upy(x, y, _) = 0.25f * upx(x, (y/2) - 1 + 2*(y % 2), _) + 0.75f * upx(x, y/2, _);
return upy;
}
int main(int argc, char **argv) {
/* THE ALGORITHM */
// Number of pyramid levels
const int J = 8;
// number of intensity levels
Param<int> levels;
// Parameters controlling the filter
Param<float> alpha, beta;
// Takes a 16-bit input
ImageParam input(UInt(16), 3);
// loop variables
Var c, k;
// Make the remapping function as a lookup table.
Func remap;
Expr fx = cast<float>(x) / 256.0f;
remap(x) = alpha*fx*exp(-fx*fx/2.0f);
// Convert to floating point
Func floating;
floating(x, y, c) = cast<float>(input(x, y, c)) / 65535.0f;
// Set a boundary condition
Func clamped;
clamped(x, y, c) = floating(clamp(x, 0, input.width()-1), clamp(y, 0, input.height()-1), c);
// Get the luminance channel
Func gray;
gray(x, y) = 0.299f * clamped(x, y, 0) + 0.587f * clamped(x, y, 1) + 0.114f * clamped(x, y, 2);
// Make the processed Gaussian pyramid.
Func gPyramid[J];
// Do a lookup into a lut with 256 entires per intensity level
Expr level = k * (1.0f / (levels - 1));
Expr idx = gray(x, y)*cast<float>(levels-1)*256.0f;
idx = clamp(cast<int>(idx), 0, (levels-1)*256);
gPyramid[0](x, y, k) = beta*(gray(x, y) - level) + level + remap(idx - 256*k);
for (int j = 1; j < J; j++) {
gPyramid[j](x, y, k) = downsample(gPyramid[j-1])(x, y, k);
}
// Get its laplacian pyramid
Func lPyramid[J];
lPyramid[J-1](x, y, k) = gPyramid[J-1](x, y, k);
for (int j = J-2; j >= 0; j--) {
lPyramid[j](x, y, k) = gPyramid[j](x, y, k) - upsample(gPyramid[j+1])(x, y, k);
}
// Make the Gaussian pyramid of the input
Func inGPyramid[J];
inGPyramid[0](x, y) = gray(x, y);
for (int j = 1; j < J; j++) {
inGPyramid[j](x, y) = downsample(inGPyramid[j-1])(x, y);
}
// Make the laplacian pyramid of the output
Func outLPyramid[J];
for (int j = 0; j < J; j++) {
// Split input pyramid value into integer and floating parts
Expr level = inGPyramid[j](x, y) * cast<float>(levels-1);
Expr li = clamp(cast<int>(level), 0, levels-2);
Expr lf = level - cast<float>(li);
// Linearly interpolate between the nearest processed pyramid levels
outLPyramid[j](x, y) = (1.0f - lf) * lPyramid[j](x, y, li) + lf * lPyramid[j](x, y, li+1);
}
// Make the Gaussian pyramid of the output
Func outGPyramid[J];
outGPyramid[J-1](x, y) = outLPyramid[J-1](x, y);
for (int j = J-2; j >= 0; j--) {
outGPyramid[j](x, y) = upsample(outGPyramid[j+1])(x, y) + outLPyramid[j](x, y);
}
// Reintroduce color (Connelly: use eps to avoid scaling up noise w/ apollo3.png input)
Func color;
float eps = 0.01f;
color(x, y, c) = outGPyramid[0](x, y) * (clamped(x, y, c)+eps) / (gray(x, y)+eps);
Func output("local_laplacian");
// Convert back to 16-bit
output(x, y, c) = cast<uint16_t>(clamp(color(x, y, c), 0.0f, 1.0f) * 65535.0f);
/* THE SCHEDULE */
remap.compute_root();
Target target = get_target_from_environment();
if (target.has_gpu_feature()) {
// gpu schedule
output.compute_root().gpu_tile(x, y, 16, 8, GPU_Default);
for (int j = 0; j < J; j++) {
int blockw = 16, blockh = 8;
if (j > 3) {
blockw = 2;
blockh = 2;
}
if (j > 0) inGPyramid[j].compute_root().gpu_tile(x, y, blockw, blockh, GPU_Default);
if (j > 0) gPyramid[j].compute_root().reorder(k, x, y).gpu_tile(x, y, blockw, blockh, GPU_Default);
outGPyramid[j].compute_root().gpu_tile(x, y, blockw, blockh, GPU_Default);
}
} else {
// cpu schedule
Var yi;
output.parallel(y, 4).vectorize(x, 4);
gray.compute_root().parallel(y, 4).vectorize(x, 4);
for (int j = 0; j < 4; j++) {
if (j > 0) inGPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4);
if (j > 0) gPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4);
outGPyramid[j].compute_root().parallel(y, 4).vectorize(x, 4);
}
for (int j = 4; j < J; j++) {
inGPyramid[j].compute_root().parallel(y);
gPyramid[j].compute_root().parallel(k);
outGPyramid[j].compute_root().parallel(y);
}
}
output.compile_to_file("local_laplacian", levels, alpha, beta, input, target);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include <pcl/apps/dominant_plane_segmentation.h>
#include <pcl/apps/impl/dominant_plane_segmentation.hpp>
// Instantiations of specific point types
PCL_INSTANTIATE(DominantPlaneSegmentation, PCL_XYZ_POINT_TYPES)
<commit_msg>Added PCL_ONLY_CORE_POINT_TYPES.<commit_after>/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <pcl/point_types.h>
#include <pcl/impl/instantiate.hpp>
#include <pcl/apps/dominant_plane_segmentation.h>
#include <pcl/apps/impl/dominant_plane_segmentation.hpp>
#ifdef PCL_ONLY_CORE_POINT_TYPES
PCL_INSTANTIATE(DominantPlaneSegmentation, (pcl::PointXYZ)(pcl::PointXYZI)(pcl::PointXYZRGBA)(pcl::PointXYZRGB))
#else
PCL_INSTANTIATE(DominantPlaneSegmentation, PCL_XYZ_POINT_TYPES)
#endif
<|endoftext|> |
<commit_before>#include "service_pool.h"
#include <sys/uio.h>
#include <sys/eventfd.h>
#include "sockets.h"
#include "loop.h"
#include "logging.h"
#include "redis_proxy.h"
namespace smart {
ServicePool& ServicePool::get_instance()
{
static ServicePool pool;
return pool;
}
ServProc::ServProc(int fd, MPMCQueue<Letter>& letters):
LoopThread("service_processor"),
_queue_read_io(new IO(fd, EV_READ, false)),
_letters(&letters)
{
}
bool ServProc::prepare()
{
_queue_read_io->on_read([this]() {
eventfd_t num = 0;
eventfd_read(_queue_read_io->fd(), &num);
for (auto i = 0; i < num; ++i) {
Letter letter;
if (!_letters->pop(&letter)) {
break;
}
SLOG(INFO) << "begin to parse:" << letter.second->content();
shared_json request;
shared_json response;
if (!letter.second->content().empty()) {
request = std::make_shared<json>(
json::parse(letter.second->content()));
} else {
request = std::make_shared<json>();
}
response = std::make_shared<json>();
std::shared_ptr<Control> ctrl = std::make_shared<Control>(letter, response);
SLOG(INFO) << "begin to call method: " << letter.second->get_service_name()
<< " " << letter.second->get_method_name();
ServicePool::get_instance()
.find_service(letter.second->get_service_name())
->find_method(letter.second->get_method_name())(request, response, ctrl);
}
});
return get_local_loop()->add_io(_queue_read_io);
}
void ServProc::process_end()
{
get_local_loop()->remove_io(_queue_read_io);
}
Service::Method Service::_default_method =
[](const shared_json&, shared_json& response, SControl&) {
(*response)["status"] = "fail";
(*response)["message"] = "method not found";
};
bool ServicePool::run()
{
_queue_write_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (_queue_write_fd < 0) {
SLOG(WARNING) << "get eventfd fail!";
return false;
}
for(int i = 0; i < std::thread::hardware_concurrency(); ++i) {
_proc_pool.emplace_back(new ServProc(_queue_write_fd, _letters));
if (!_proc_pool.back()->run()) {
return false;
}
}
return true;
}
void ServicePool::stop()
{
for (auto &proc : _proc_pool) {
proc->stop();
}
rpc::close(_queue_write_fd);
}
void ServicePool::send(Letter&& letter)
{
_letters.push(letter);
eventfd_write(_queue_write_fd, 1);
}
}
<commit_msg>add try catch codes<commit_after>#include "service_pool.h"
#include <sys/uio.h>
#include <sys/eventfd.h>
#include "sockets.h"
#include "loop.h"
#include "logging.h"
#include "redis_proxy.h"
namespace smart {
ServicePool& ServicePool::get_instance()
{
static ServicePool pool;
return pool;
}
ServProc::ServProc(int fd, MPMCQueue<Letter>& letters):
LoopThread("service_processor"),
_queue_read_io(new IO(fd, EV_READ, false)),
_letters(&letters)
{
}
bool ServProc::prepare()
{
_queue_read_io->on_read([this]() {
eventfd_t num = 0;
eventfd_read(_queue_read_io->fd(), &num);
for (auto i = 0; i < num; ++i) {
Letter letter;
if (!_letters->pop(&letter)) {
break;
}
SLOG(INFO) << "begin to parse:" << letter.second->content();
auto response = std::make_shared<json>();
auto ctrl = std::make_shared<Control>(letter, response);
try {
auto request = std::make_shared<json>(
json::parse(letter.second->content()));
SLOG(INFO) << "begin to call method: " << letter.second->get_service_name()
<< " " << letter.second->get_method_name();
ServicePool::get_instance()
.find_service(letter.second->get_service_name())
->find_method(letter.second->get_method_name())(request, response, ctrl);
} catch (std::exception& ex) {
LOG(WARNING) << "catch error:" << ex.what();
(*response)["code"] = static_cast<int>(ErrCode::PARAM_ERROR);
(*response)["message"] = ex.what();
}
}
});
return get_local_loop()->add_io(_queue_read_io);
}
void ServProc::process_end()
{
get_local_loop()->remove_io(_queue_read_io);
}
Service::Method Service::_default_method =
[](const shared_json&, shared_json& response, SControl&) {
(*response)["code"] = static_cast<int>(ErrCode::PARAM_ERROR);
(*response)["message"] = "method not found";
};
bool ServicePool::run()
{
_queue_write_fd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (_queue_write_fd < 0) {
SLOG(WARNING) << "get eventfd fail!";
return false;
}
for(int i = 0; i < std::thread::hardware_concurrency(); ++i) {
_proc_pool.emplace_back(new ServProc(_queue_write_fd, _letters));
if (!_proc_pool.back()->run()) {
return false;
}
}
return true;
}
void ServicePool::stop()
{
for (auto &proc : _proc_pool) {
proc->stop();
}
rpc::close(_queue_write_fd);
}
void ServicePool::send(Letter&& letter)
{
_letters.push(letter);
eventfd_write(_queue_write_fd, 1);
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Aaron McCarthy <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
** 2015.4.4
** Adapted for use with QGroundControl
**
** Gus Grubba <[email protected]>
**
****************************************************************************/
#include "QGCMapEngine.h"
#include "QGeoTiledMappingManagerEngineQGC.h"
#include "QGeoTileFetcherQGC.h"
#include <QtLocation/private/qgeocameracapabilities_p.h>
#include <QtLocation/private/qgeomaptype_p.h>
#if QT_VERSION < QT_VERSION_CHECK(5, 5, 0)
#include <QtLocation/private/qgeotiledmapdata_p.h>
#else
#include <QtLocation/private/qgeotiledmap_p.h>
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
#include <QtLocation/private/qgeofiletilecache_p.h>
#else
#include <QtLocation/private/qgeotilecache_p.h>
#endif
#endif
#include <QDir>
#include <QStandardPaths>
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
//-----------------------------------------------------------------------------
QGeoTiledMapQGC::QGeoTiledMapQGC(QGeoTiledMappingManagerEngine *engine, QObject *parent)
: QGeoTiledMap(engine, parent)
{
}
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
#define QGCGEOMAPTYPE(a,b,c,d,e,f) QGeoMapType(a,b,c,d,e,f,QByteArray("QGroundControl"), QGeoCameraCapabilities())
#elif QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
#define QGCGEOMAPTYPE(a,b,c,d,e,f) QGeoMapType(a,b,c,d,e,f,QByteArray("QGroundControl"))
#else
#define QGCGEOMAPTYPE(a,b,c,d,e,f) QGeoMapType(a,b,c,d,e,f)
#endif
//-----------------------------------------------------------------------------
QGeoTiledMappingManagerEngineQGC::QGeoTiledMappingManagerEngineQGC(const QVariantMap ¶meters, QGeoServiceProvider::Error *error, QString *errorString)
: QGeoTiledMappingManagerEngine()
{
QGeoCameraCapabilities cameraCaps;
cameraCaps.setMinimumZoomLevel(2.0);
cameraCaps.setMaximumZoomLevel(MAX_MAP_ZOOM);
cameraCaps.setSupportsBearing(true);
setCameraCapabilities(cameraCaps);
setTileSize(QSize(256, 256));
/*
* Google and Bing don't seem kosher at all. This was based on original code from OpenPilot and heavily modified to be used in QGC.
*/
//-- IMPORTANT
// Changes here must reflect those in QGCMapEngine.cpp
QList<QGeoMapType> mapTypes;
#ifndef QGC_NO_GOOGLE_MAPS
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Google Street Map", "Google street map", false, false, UrlFactory::GoogleMap);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "Google Satellite Map", "Google satellite map", false, false, UrlFactory::GoogleSatellite);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::TerrainMap, "Google Terrain Map", "Google terrain map", false, false, UrlFactory::GoogleTerrain);
#endif
/* TODO:
* Proper google hybrid maps requires collecting two separate bitmaps and overlaying them.
*
* mapTypes << QGCGEOMAPTYPE(QGeoMapType::HybridMap, "Google Hybrid Map", "Google hybrid map", false, false, UrlFactory::GoogleHybrid);
*
*/
// Bing
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Bing Street Map", "Bing street map", false, false, UrlFactory::BingMap);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "Bing Satellite Map", "Bing satellite map", false, false, UrlFactory::BingSatellite);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::HybridMap, "Bing Hybrid Map", "Bing hybrid map", false, false, UrlFactory::BingHybrid);
// Statkart
mapTypes << QGCGEOMAPTYPE(QGeoMapType::TerrainMap, "Statkart Terrain Map", "Statkart Terrain Map", false, false, UrlFactory::StatkartTopo);
// Eniro
mapTypes << QGCGEOMAPTYPE(QGeoMapType::TerrainMap, "Eniro Terrain Map", "Eniro Terrain Map", false, false, UrlFactory::EniroTopo);
// Esri
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Esri Street Map", "ArcGIS Online World Street Map", true, false, UrlFactory::EsriWorldStreet);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "Esri Satellite Map", "ArcGIS Online World Imagery", true, false, UrlFactory::EsriWorldSatellite);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::TerrainMap, "Esri Terrain Map", "World Terrain Base", false, false, UrlFactory::EsriTerrain);
/* See: https://wiki.openstreetmap.org/wiki/Tile_usage_policy
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Open Street Map", "Open Street map", false, false, UrlFactory::OpenStreetMap);
*/
// MapQuest
/*
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "MapQuest Street Map", "MapQuest street map", false, false, UrlFactory::MapQuestMap);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "MapQuest Satellite Map", "MapQuest satellite map", false, false, UrlFactory::MapQuestSat);
*/
/*
* These are OK as you need your own token for accessing it. Out-of-the box, QGC does not even offer these unless you enter a proper Mapbox token.
*/
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Mapbox Street Map", "Mapbox Street Map", false, false, UrlFactory::MapboxStreets);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "Mapbox Satellite Map", "Mapbox Satellite Map", false, false, UrlFactory::MapboxSatellite);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox High Contrast Map", "Mapbox High Contrast Map", false, false, UrlFactory::MapboxHighContrast);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Light Map", "Mapbox Light Map", false, false, UrlFactory::MapboxLight);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Dark Map", "Mapbox Dark Map", false, false, UrlFactory::MapboxDark);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::HybridMap, "Mapbox Hybrid Map", "Mapbox Hybrid Map", false, false, UrlFactory::MapboxHybrid);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Wheat Paste Map", "Mapbox Wheat Paste Map", false, false, UrlFactory::MapboxWheatPaste);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Mapbox Streets Basic Map", "Mapbox Streets Basic Map", false, false, UrlFactory::MapboxStreetsBasic);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Comic Map", "Mapbox Comic Map", false, false, UrlFactory::MapboxComic);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Outdoors Map", "Mapbox Outdoors Map", false, false, UrlFactory::MapboxOutdoors);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CycleMap, "Mapbox Run, Byke and Hike Map", "Mapbox Run, Byke and Hike Map", false, false, UrlFactory::MapboxRunBikeHike);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Pencil Map", "Mapbox Pencil Map", false, false, UrlFactory::MapboxPencil);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Pirates Map", "Mapbox Pirates Map", false, false, UrlFactory::MapboxPirates);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Emerald Map", "Mapbox Emerald Map", false, false, UrlFactory::MapboxEmerald);
setSupportedMapTypes(mapTypes);
//-- Users (QML code) can define a different user agent
if (parameters.contains(QStringLiteral("useragent"))) {
getQGCMapEngine()->setUserAgent(parameters.value(QStringLiteral("useragent")).toString().toLatin1());
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
_setCache(parameters);
#endif
setTileFetcher(new QGeoTileFetcherQGC(this));
*error = QGeoServiceProvider::NoError;
errorString->clear();
}
//-----------------------------------------------------------------------------
QGeoTiledMappingManagerEngineQGC::~QGeoTiledMappingManagerEngineQGC()
{
}
#if QT_VERSION < QT_VERSION_CHECK(5, 5, 0)
//-----------------------------------------------------------------------------
QGeoMapData *QGeoTiledMappingManagerEngineQGC::createMapData()
{
return new QGeoTiledMapData(this, 0);
}
#else
//-----------------------------------------------------------------------------
QGeoMap*
QGeoTiledMappingManagerEngineQGC::createMap()
{
return new QGeoTiledMapQGC(this);
}
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
//-----------------------------------------------------------------------------
void
QGeoTiledMappingManagerEngineQGC::_setCache(const QVariantMap ¶meters)
{
QString cacheDir;
if (parameters.contains(QStringLiteral("mapping.cache.directory")))
cacheDir = parameters.value(QStringLiteral("mapping.cache.directory")).toString();
else {
cacheDir = getQGCMapEngine()->getCachePath();
if(!QFileInfo(cacheDir).exists()) {
if(!QDir::root().mkpath(cacheDir)) {
qWarning() << "Could not create mapping disk cache directory: " << cacheDir;
cacheDir = QDir::homePath() + QLatin1String("/.qgcmapscache/");
}
}
}
if(!QFileInfo(cacheDir).exists()) {
if(!QDir::root().mkpath(cacheDir)) {
qWarning() << "Could not create mapping disk cache directory: " << cacheDir;
cacheDir.clear();
}
}
//-- Memory Cache
uint32_t memLimit = 0;
if (parameters.contains(QStringLiteral("mapping.cache.memory.size"))) {
bool ok = false;
memLimit = parameters.value(QStringLiteral("mapping.cache.memory.size")).toString().toUInt(&ok);
if (!ok)
memLimit = 0;
}
if(!memLimit)
{
//-- Value saved in MB
memLimit = getQGCMapEngine()->getMaxMemCache() * (1024 * 1024);
}
//-- It won't work with less than 1M of memory cache
if(memLimit < 1024 * 1024)
memLimit = 1024 * 1024;
//-- On the other hand, Qt uses signed 32-bit integers. Limit to 1G to round it down (you don't need more than that).
if(memLimit > 1024 * 1024 * 1024)
memLimit = 1024 * 1024 * 1024;
//-- Disable Qt's disk cache (sort of)
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
QAbstractGeoTileCache *pTileCache = new QGeoFileTileCache(cacheDir);
setTileCache(pTileCache);
#else
QGeoTileCache* pTileCache = createTileCacheWithDir(cacheDir);
#endif
if(pTileCache)
{
//-- We're basically telling it to use 100k of disk for cache. It doesn't like
// values smaller than that and I could not find a way to make it NOT cache.
// We handle our own disk caching elsewhere.
pTileCache->setMaxDiskUsage(1024 * 100);
pTileCache->setMaxMemoryUsage(memLimit);
}
}
#endif
<commit_msg>QGeoTiledMappingManagerEngineQGC: Use cameraCaps in QGeoMapType<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Aaron McCarthy <[email protected]>
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtLocation module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
** 2015.4.4
** Adapted for use with QGroundControl
**
** Gus Grubba <[email protected]>
**
****************************************************************************/
#include "QGCMapEngine.h"
#include "QGeoTiledMappingManagerEngineQGC.h"
#include "QGeoTileFetcherQGC.h"
#include <QtLocation/private/qgeocameracapabilities_p.h>
#include <QtLocation/private/qgeomaptype_p.h>
#if QT_VERSION < QT_VERSION_CHECK(5, 5, 0)
#include <QtLocation/private/qgeotiledmapdata_p.h>
#else
#include <QtLocation/private/qgeotiledmap_p.h>
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
#include <QtLocation/private/qgeofiletilecache_p.h>
#else
#include <QtLocation/private/qgeotilecache_p.h>
#endif
#endif
#include <QDir>
#include <QStandardPaths>
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
//-----------------------------------------------------------------------------
QGeoTiledMapQGC::QGeoTiledMapQGC(QGeoTiledMappingManagerEngine *engine, QObject *parent)
: QGeoTiledMap(engine, parent)
{
}
#endif
//-----------------------------------------------------------------------------
QGeoTiledMappingManagerEngineQGC::QGeoTiledMappingManagerEngineQGC(const QVariantMap ¶meters, QGeoServiceProvider::Error *error, QString *errorString)
: QGeoTiledMappingManagerEngine()
{
QGeoCameraCapabilities cameraCaps;
cameraCaps.setMinimumZoomLevel(2.0);
cameraCaps.setMaximumZoomLevel(MAX_MAP_ZOOM);
cameraCaps.setSupportsBearing(true);
setCameraCapabilities(cameraCaps);
setTileSize(QSize(256, 256));
// In Qt 5.10 QGeoMapType need QGeoCameraCapabilities as argument
// E.g: https://github.com/qt/qtlocation/blob/2b230b0a10d898979e9d5193f4da2e408b397fe3/src/plugins/geoservices/osm/qgeotiledmappingmanagerengineosm.cpp#L167
#if QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)
#define QGCGEOMAPTYPE(a,b,c,d,e,f) QGeoMapType(a,b,c,d,e,f,QByteArray("QGroundControl"), cameraCaps)
#elif QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
#define QGCGEOMAPTYPE(a,b,c,d,e,f) QGeoMapType(a,b,c,d,e,f,QByteArray("QGroundControl"))
#else
#define QGCGEOMAPTYPE(a,b,c,d,e,f) QGeoMapType(a,b,c,d,e,f)
#endif
/*
* Google and Bing don't seem kosher at all. This was based on original code from OpenPilot and heavily modified to be used in QGC.
*/
//-- IMPORTANT
// Changes here must reflect those in QGCMapEngine.cpp
QList<QGeoMapType> mapTypes;
#ifndef QGC_NO_GOOGLE_MAPS
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Google Street Map", "Google street map", false, false, UrlFactory::GoogleMap);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "Google Satellite Map", "Google satellite map", false, false, UrlFactory::GoogleSatellite);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::TerrainMap, "Google Terrain Map", "Google terrain map", false, false, UrlFactory::GoogleTerrain);
#endif
/* TODO:
* Proper google hybrid maps requires collecting two separate bitmaps and overlaying them.
*
* mapTypes << QGCGEOMAPTYPE(QGeoMapType::HybridMap, "Google Hybrid Map", "Google hybrid map", false, false, UrlFactory::GoogleHybrid);
*
*/
// Bing
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Bing Street Map", "Bing street map", false, false, UrlFactory::BingMap);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "Bing Satellite Map", "Bing satellite map", false, false, UrlFactory::BingSatellite);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::HybridMap, "Bing Hybrid Map", "Bing hybrid map", false, false, UrlFactory::BingHybrid);
// Statkart
mapTypes << QGCGEOMAPTYPE(QGeoMapType::TerrainMap, "Statkart Terrain Map", "Statkart Terrain Map", false, false, UrlFactory::StatkartTopo);
// Eniro
mapTypes << QGCGEOMAPTYPE(QGeoMapType::TerrainMap, "Eniro Terrain Map", "Eniro Terrain Map", false, false, UrlFactory::EniroTopo);
// Esri
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Esri Street Map", "ArcGIS Online World Street Map", true, false, UrlFactory::EsriWorldStreet);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "Esri Satellite Map", "ArcGIS Online World Imagery", true, false, UrlFactory::EsriWorldSatellite);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::TerrainMap, "Esri Terrain Map", "World Terrain Base", false, false, UrlFactory::EsriTerrain);
/* See: https://wiki.openstreetmap.org/wiki/Tile_usage_policy
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Open Street Map", "Open Street map", false, false, UrlFactory::OpenStreetMap);
*/
// MapQuest
/*
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "MapQuest Street Map", "MapQuest street map", false, false, UrlFactory::MapQuestMap);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "MapQuest Satellite Map", "MapQuest satellite map", false, false, UrlFactory::MapQuestSat);
*/
/*
* These are OK as you need your own token for accessing it. Out-of-the box, QGC does not even offer these unless you enter a proper Mapbox token.
*/
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Mapbox Street Map", "Mapbox Street Map", false, false, UrlFactory::MapboxStreets);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::SatelliteMapDay, "Mapbox Satellite Map", "Mapbox Satellite Map", false, false, UrlFactory::MapboxSatellite);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox High Contrast Map", "Mapbox High Contrast Map", false, false, UrlFactory::MapboxHighContrast);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Light Map", "Mapbox Light Map", false, false, UrlFactory::MapboxLight);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Dark Map", "Mapbox Dark Map", false, false, UrlFactory::MapboxDark);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::HybridMap, "Mapbox Hybrid Map", "Mapbox Hybrid Map", false, false, UrlFactory::MapboxHybrid);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Wheat Paste Map", "Mapbox Wheat Paste Map", false, false, UrlFactory::MapboxWheatPaste);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::StreetMap, "Mapbox Streets Basic Map", "Mapbox Streets Basic Map", false, false, UrlFactory::MapboxStreetsBasic);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Comic Map", "Mapbox Comic Map", false, false, UrlFactory::MapboxComic);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Outdoors Map", "Mapbox Outdoors Map", false, false, UrlFactory::MapboxOutdoors);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CycleMap, "Mapbox Run, Byke and Hike Map", "Mapbox Run, Byke and Hike Map", false, false, UrlFactory::MapboxRunBikeHike);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Pencil Map", "Mapbox Pencil Map", false, false, UrlFactory::MapboxPencil);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Pirates Map", "Mapbox Pirates Map", false, false, UrlFactory::MapboxPirates);
mapTypes << QGCGEOMAPTYPE(QGeoMapType::CustomMap, "Mapbox Emerald Map", "Mapbox Emerald Map", false, false, UrlFactory::MapboxEmerald);
setSupportedMapTypes(mapTypes);
//-- Users (QML code) can define a different user agent
if (parameters.contains(QStringLiteral("useragent"))) {
getQGCMapEngine()->setUserAgent(parameters.value(QStringLiteral("useragent")).toString().toLatin1());
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
_setCache(parameters);
#endif
setTileFetcher(new QGeoTileFetcherQGC(this));
*error = QGeoServiceProvider::NoError;
errorString->clear();
}
//-----------------------------------------------------------------------------
QGeoTiledMappingManagerEngineQGC::~QGeoTiledMappingManagerEngineQGC()
{
}
#if QT_VERSION < QT_VERSION_CHECK(5, 5, 0)
//-----------------------------------------------------------------------------
QGeoMapData *QGeoTiledMappingManagerEngineQGC::createMapData()
{
return new QGeoTiledMapData(this, 0);
}
#else
//-----------------------------------------------------------------------------
QGeoMap*
QGeoTiledMappingManagerEngineQGC::createMap()
{
return new QGeoTiledMapQGC(this);
}
#endif
#if QT_VERSION >= QT_VERSION_CHECK(5, 5, 0)
//-----------------------------------------------------------------------------
void
QGeoTiledMappingManagerEngineQGC::_setCache(const QVariantMap ¶meters)
{
QString cacheDir;
if (parameters.contains(QStringLiteral("mapping.cache.directory")))
cacheDir = parameters.value(QStringLiteral("mapping.cache.directory")).toString();
else {
cacheDir = getQGCMapEngine()->getCachePath();
if(!QFileInfo(cacheDir).exists()) {
if(!QDir::root().mkpath(cacheDir)) {
qWarning() << "Could not create mapping disk cache directory: " << cacheDir;
cacheDir = QDir::homePath() + QLatin1String("/.qgcmapscache/");
}
}
}
if(!QFileInfo(cacheDir).exists()) {
if(!QDir::root().mkpath(cacheDir)) {
qWarning() << "Could not create mapping disk cache directory: " << cacheDir;
cacheDir.clear();
}
}
//-- Memory Cache
uint32_t memLimit = 0;
if (parameters.contains(QStringLiteral("mapping.cache.memory.size"))) {
bool ok = false;
memLimit = parameters.value(QStringLiteral("mapping.cache.memory.size")).toString().toUInt(&ok);
if (!ok)
memLimit = 0;
}
if(!memLimit)
{
//-- Value saved in MB
memLimit = getQGCMapEngine()->getMaxMemCache() * (1024 * 1024);
}
//-- It won't work with less than 1M of memory cache
if(memLimit < 1024 * 1024)
memLimit = 1024 * 1024;
//-- On the other hand, Qt uses signed 32-bit integers. Limit to 1G to round it down (you don't need more than that).
if(memLimit > 1024 * 1024 * 1024)
memLimit = 1024 * 1024 * 1024;
//-- Disable Qt's disk cache (sort of)
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
QAbstractGeoTileCache *pTileCache = new QGeoFileTileCache(cacheDir);
setTileCache(pTileCache);
#else
QGeoTileCache* pTileCache = createTileCacheWithDir(cacheDir);
#endif
if(pTileCache)
{
//-- We're basically telling it to use 100k of disk for cache. It doesn't like
// values smaller than that and I could not find a way to make it NOT cache.
// We handle our own disk caching elsewhere.
pTileCache->setMaxDiskUsage(1024 * 100);
pTileCache->setMaxMemoryUsage(memLimit);
}
}
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
This source file is part of the TEM tomography project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "DataSource.h"
#include "OperatorPython.h"
#include "Utilities.h"
#include "vtkDataObject.h"
#include "vtkNew.h"
#include "vtkSmartPointer.h"
#include "vtkSMCoreUtilities.h"
#include "vtkSMParaViewPipelineController.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMTransferFunctionManager.h"
#include "vtkTrivialProducer.h"
#include <vtk_pugixml.h>
namespace TEM
{
class DataSource::DSInternals
{
public:
vtkSmartPointer<vtkSMSourceProxy> OriginalDataSource;
vtkWeakPointer<vtkSMSourceProxy> Producer;
QList<QSharedPointer<Operator> > Operators;
vtkSmartPointer<vtkSMProxy> ColorMap;
};
//-----------------------------------------------------------------------------
DataSource::DataSource(vtkSMSourceProxy* dataSource, QObject* parentObject)
: Superclass(parentObject),
Internals(new DataSource::DSInternals())
{
Q_ASSERT(dataSource);
this->Internals->OriginalDataSource = dataSource;
vtkNew<vtkSMParaViewPipelineController> controller;
vtkSMSessionProxyManager* pxm = dataSource->GetSessionProxyManager();
Q_ASSERT(pxm);
vtkSmartPointer<vtkSMProxy> source;
source.TakeReference(pxm->NewProxy("sources", "TrivialProducer"));
Q_ASSERT(source != NULL);
Q_ASSERT(vtkSMSourceProxy::SafeDownCast(source));
// We add an annotation to the proxy so that it'll be easier for code to
// locate registered pipeline proxies that are being treated as data sources.
TEM::annotateDataProducer(source,
vtkSMPropertyHelper(dataSource,
vtkSMCoreUtilities::GetFileNameProperty(dataSource)).GetAsString());
controller->RegisterPipelineProxy(source);
this->Internals->Producer = vtkSMSourceProxy::SafeDownCast(source);
// Setup color map for this data-source.
static unsigned int colorMapCounter=0;
colorMapCounter++;
vtkNew<vtkSMTransferFunctionManager> tfmgr;
this->Internals->ColorMap = tfmgr->GetColorTransferFunction(
QString("DataSourceColorMap%1").arg(colorMapCounter).toLatin1().data(), pxm);
// every time the data changes, we should update the color map.
this->connect(this, SIGNAL(dataChanged()), SLOT(updateColorMap()));
this->resetData();
}
//-----------------------------------------------------------------------------
DataSource::~DataSource()
{
if (this->Internals->Producer)
{
vtkNew<vtkSMParaViewPipelineController> controller;
controller->UnRegisterProxy(this->Internals->Producer);
}
}
//-----------------------------------------------------------------------------
QString DataSource::filename() const
{
vtkSMProxy* dataSource = this->originalDataSource();
return vtkSMPropertyHelper(dataSource,
vtkSMCoreUtilities::GetFileNameProperty(dataSource)).GetAsString();
}
//-----------------------------------------------------------------------------
bool DataSource::serialize(pugi::xml_node& ns) const
{
pugi::xml_node node = ns.append_child("ColorMap");
TEM::serialize(this->colorMap(), node);
node = ns.append_child("OpacityMap");
TEM::serialize(this->opacityMap(), node);
ns.append_attribute("number_of_operators").set_value(
static_cast<int>(this->Internals->Operators.size()));
foreach (QSharedPointer<Operator> op, this->Internals->Operators)
{
pugi::xml_node node = ns.append_child("Operator");
if (!op->serialize(node))
{
qWarning("failed to serialize Operator. Skipping it.");
ns.remove_child(node);
}
}
return true;
}
//-----------------------------------------------------------------------------
bool DataSource::deserialize(const pugi::xml_node& ns)
{
TEM::deserialize(this->colorMap(), ns.child("ColorMap"));
TEM::deserialize(this->opacityMap(), ns.child("OpacityMap"));
vtkSMPropertyHelper(this->colorMap(),
"ScalarOpacityFunction").Set(this->opacityMap());
this->colorMap()->UpdateVTKObjects();
int num_operators = ns.attribute("number_of_operators").as_int(-1);
if (num_operators < 0)
{
return false;
}
this->Internals->Operators.clear();
this->resetData();
for (pugi::xml_node node=ns.child("Operator"); node; node = node.next_sibling("Operator"))
{
QSharedPointer<OperatorPython> op (new OperatorPython());
if (op->deserialize(node))
{
this->addOperator(op);
}
}
return true;
}
//-----------------------------------------------------------------------------
DataSource* DataSource::clone(bool clone_operators) const
{
DataSource* newClone = new DataSource(this->Internals->OriginalDataSource);
if (clone_operators)
{
// now, clone the operators.
foreach (QSharedPointer<Operator> op, this->Internals->Operators)
{
QSharedPointer<Operator> opClone(op->clone());
newClone->addOperator(opClone);
}
}
return newClone;
}
//-----------------------------------------------------------------------------
vtkSMSourceProxy* DataSource::originalDataSource() const
{
return this->Internals->OriginalDataSource;
}
//-----------------------------------------------------------------------------
vtkSMSourceProxy* DataSource::producer() const
{
return this->Internals->Producer;
}
//-----------------------------------------------------------------------------
int DataSource::addOperator(const QSharedPointer<Operator>& op)
{
int index = this->Internals->Operators.count();
this->Internals->Operators.push_back(op);
this->connect(op.data(), SIGNAL(transformModified()),
SLOT(operatorTransformModified()));
emit this->operatorAdded(op.data());
this->operate(op.data());
return index;
}
//-----------------------------------------------------------------------------
void DataSource::operate(Operator* op)
{
Q_ASSERT(op);
vtkTrivialProducer* tp = vtkTrivialProducer::SafeDownCast(
this->Internals->Producer->GetClientSideObject());
Q_ASSERT(tp);
if (op->transform(tp->GetOutputDataObject(0)))
{
tp->Modified();
tp->GetOutputDataObject(0)->Modified();
this->Internals->Producer->MarkModified(NULL);
this->Internals->Producer->UpdatePipeline();
}
emit this->dataChanged();
}
//-----------------------------------------------------------------------------
const QList<QSharedPointer<Operator> >& DataSource::operators() const
{
return this->Internals->Operators;
}
//-----------------------------------------------------------------------------
void DataSource::resetData()
{
vtkSMSourceProxy* dataSource = this->Internals->OriginalDataSource;
Q_ASSERT(dataSource);
dataSource->UpdatePipeline();
vtkAlgorithm* vtkalgorithm = vtkAlgorithm::SafeDownCast(
dataSource->GetClientSideObject());
Q_ASSERT(vtkalgorithm);
vtkSMSourceProxy* source = this->Internals->Producer;
Q_ASSERT(source != NULL);
// Create a clone and release the reader data.
vtkDataObject* data = vtkalgorithm->GetOutputDataObject(0);
vtkDataObject* clone = data->NewInstance();
clone->DeepCopy(data);
//data->ReleaseData(); FIXME: how it this supposed to work? I get errors on
//attempting to re-execute the reader pipeline in clone().
vtkTrivialProducer* tp = vtkTrivialProducer::SafeDownCast(
source->GetClientSideObject());
Q_ASSERT(tp);
tp->SetOutput(clone);
clone->FastDelete();
emit this->dataChanged();
}
//-----------------------------------------------------------------------------
void DataSource::operatorTransformModified()
{
bool prev = this->blockSignals(true);
this->resetData();
foreach (QSharedPointer<Operator> op, this->Internals->Operators)
{
this->operate(op.data());
}
this->blockSignals(prev);
emit this->dataChanged();
}
//-----------------------------------------------------------------------------
vtkSMProxy* DataSource::colorMap() const
{
return this->Internals->ColorMap;
}
//-----------------------------------------------------------------------------
vtkSMProxy* DataSource::opacityMap() const
{
return this->Internals->ColorMap?
vtkSMPropertyHelper(this->Internals->ColorMap, "ScalarOpacityFunction").GetAsProxy() : NULL;
}
//-----------------------------------------------------------------------------
void DataSource::updateColorMap()
{
// rescale the color/opacity maps for the data source.
TEM::rescaleColorMap(this->colorMap(), this);
}
}
<commit_msg>Hack to ensure the extents are properly updated<commit_after>/******************************************************************************
This source file is part of the TEM tomography project.
Copyright Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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 "DataSource.h"
#include "OperatorPython.h"
#include "Utilities.h"
#include "vtkDataObject.h"
#include "vtkNew.h"
#include "vtkSmartPointer.h"
#include "vtkSMCoreUtilities.h"
#include "vtkSMParaViewPipelineController.h"
#include "vtkSMPropertyHelper.h"
#include "vtkSMSessionProxyManager.h"
#include "vtkSMSourceProxy.h"
#include "vtkSMTransferFunctionManager.h"
#include "vtkTrivialProducer.h"
#include <vtk_pugixml.h>
namespace TEM
{
class DataSource::DSInternals
{
public:
vtkSmartPointer<vtkSMSourceProxy> OriginalDataSource;
vtkWeakPointer<vtkSMSourceProxy> Producer;
QList<QSharedPointer<Operator> > Operators;
vtkSmartPointer<vtkSMProxy> ColorMap;
};
//-----------------------------------------------------------------------------
DataSource::DataSource(vtkSMSourceProxy* dataSource, QObject* parentObject)
: Superclass(parentObject),
Internals(new DataSource::DSInternals())
{
Q_ASSERT(dataSource);
this->Internals->OriginalDataSource = dataSource;
vtkNew<vtkSMParaViewPipelineController> controller;
vtkSMSessionProxyManager* pxm = dataSource->GetSessionProxyManager();
Q_ASSERT(pxm);
vtkSmartPointer<vtkSMProxy> source;
source.TakeReference(pxm->NewProxy("sources", "TrivialProducer"));
Q_ASSERT(source != NULL);
Q_ASSERT(vtkSMSourceProxy::SafeDownCast(source));
// We add an annotation to the proxy so that it'll be easier for code to
// locate registered pipeline proxies that are being treated as data sources.
TEM::annotateDataProducer(source,
vtkSMPropertyHelper(dataSource,
vtkSMCoreUtilities::GetFileNameProperty(dataSource)).GetAsString());
controller->RegisterPipelineProxy(source);
this->Internals->Producer = vtkSMSourceProxy::SafeDownCast(source);
// Setup color map for this data-source.
static unsigned int colorMapCounter=0;
colorMapCounter++;
vtkNew<vtkSMTransferFunctionManager> tfmgr;
this->Internals->ColorMap = tfmgr->GetColorTransferFunction(
QString("DataSourceColorMap%1").arg(colorMapCounter).toLatin1().data(), pxm);
// every time the data changes, we should update the color map.
this->connect(this, SIGNAL(dataChanged()), SLOT(updateColorMap()));
this->resetData();
}
//-----------------------------------------------------------------------------
DataSource::~DataSource()
{
if (this->Internals->Producer)
{
vtkNew<vtkSMParaViewPipelineController> controller;
controller->UnRegisterProxy(this->Internals->Producer);
}
}
//-----------------------------------------------------------------------------
QString DataSource::filename() const
{
vtkSMProxy* dataSource = this->originalDataSource();
return vtkSMPropertyHelper(dataSource,
vtkSMCoreUtilities::GetFileNameProperty(dataSource)).GetAsString();
}
//-----------------------------------------------------------------------------
bool DataSource::serialize(pugi::xml_node& ns) const
{
pugi::xml_node node = ns.append_child("ColorMap");
TEM::serialize(this->colorMap(), node);
node = ns.append_child("OpacityMap");
TEM::serialize(this->opacityMap(), node);
ns.append_attribute("number_of_operators").set_value(
static_cast<int>(this->Internals->Operators.size()));
foreach (QSharedPointer<Operator> op, this->Internals->Operators)
{
pugi::xml_node node = ns.append_child("Operator");
if (!op->serialize(node))
{
qWarning("failed to serialize Operator. Skipping it.");
ns.remove_child(node);
}
}
return true;
}
//-----------------------------------------------------------------------------
bool DataSource::deserialize(const pugi::xml_node& ns)
{
TEM::deserialize(this->colorMap(), ns.child("ColorMap"));
TEM::deserialize(this->opacityMap(), ns.child("OpacityMap"));
vtkSMPropertyHelper(this->colorMap(),
"ScalarOpacityFunction").Set(this->opacityMap());
this->colorMap()->UpdateVTKObjects();
int num_operators = ns.attribute("number_of_operators").as_int(-1);
if (num_operators < 0)
{
return false;
}
this->Internals->Operators.clear();
this->resetData();
for (pugi::xml_node node=ns.child("Operator"); node; node = node.next_sibling("Operator"))
{
QSharedPointer<OperatorPython> op (new OperatorPython());
if (op->deserialize(node))
{
this->addOperator(op);
}
}
return true;
}
//-----------------------------------------------------------------------------
DataSource* DataSource::clone(bool clone_operators) const
{
DataSource* newClone = new DataSource(this->Internals->OriginalDataSource);
if (clone_operators)
{
// now, clone the operators.
foreach (QSharedPointer<Operator> op, this->Internals->Operators)
{
QSharedPointer<Operator> opClone(op->clone());
newClone->addOperator(opClone);
}
}
return newClone;
}
//-----------------------------------------------------------------------------
vtkSMSourceProxy* DataSource::originalDataSource() const
{
return this->Internals->OriginalDataSource;
}
//-----------------------------------------------------------------------------
vtkSMSourceProxy* DataSource::producer() const
{
return this->Internals->Producer;
}
//-----------------------------------------------------------------------------
int DataSource::addOperator(const QSharedPointer<Operator>& op)
{
int index = this->Internals->Operators.count();
this->Internals->Operators.push_back(op);
this->connect(op.data(), SIGNAL(transformModified()),
SLOT(operatorTransformModified()));
emit this->operatorAdded(op.data());
this->operate(op.data());
return index;
}
//-----------------------------------------------------------------------------
void DataSource::operate(Operator* op)
{
Q_ASSERT(op);
vtkTrivialProducer* tp = vtkTrivialProducer::SafeDownCast(
this->Internals->Producer->GetClientSideObject());
Q_ASSERT(tp);
if (op->transform(tp->GetOutputDataObject(0)))
{
tp->Modified();
tp->GetOutputDataObject(0)->Modified();
this->Internals->Producer->MarkModified(NULL);
// This indirection is necessary to overcome a bug in VTK/ParaView when
// explicitly calling UpdatePipeline(). The extents don't reset to the whole
// extent. Until a proper fix makes it into VTK, this is needed.
vtkSMSessionProxyManager* pxm =
this->Internals->Producer->GetSessionProxyManager();
vtkSMSourceProxy* filter =
vtkSMSourceProxy::SafeDownCast(pxm->NewProxy("filters", "PassThrough"));
Q_ASSERT(filter);
vtkSMPropertyHelper(filter, "Input").Set(this->Internals->Producer, 0);
filter->UpdateVTKObjects();
filter->UpdatePipeline();
filter->Delete();
//this->Internals->Producer->UpdatePipeline();
}
emit this->dataChanged();
}
//-----------------------------------------------------------------------------
const QList<QSharedPointer<Operator> >& DataSource::operators() const
{
return this->Internals->Operators;
}
//-----------------------------------------------------------------------------
void DataSource::resetData()
{
vtkSMSourceProxy* dataSource = this->Internals->OriginalDataSource;
Q_ASSERT(dataSource);
dataSource->UpdatePipeline();
vtkAlgorithm* vtkalgorithm = vtkAlgorithm::SafeDownCast(
dataSource->GetClientSideObject());
Q_ASSERT(vtkalgorithm);
vtkSMSourceProxy* source = this->Internals->Producer;
Q_ASSERT(source != NULL);
// Create a clone and release the reader data.
vtkDataObject* data = vtkalgorithm->GetOutputDataObject(0);
vtkDataObject* clone = data->NewInstance();
clone->DeepCopy(data);
//data->ReleaseData(); FIXME: how it this supposed to work? I get errors on
//attempting to re-execute the reader pipeline in clone().
vtkTrivialProducer* tp = vtkTrivialProducer::SafeDownCast(
source->GetClientSideObject());
Q_ASSERT(tp);
tp->SetOutput(clone);
clone->FastDelete();
emit this->dataChanged();
}
//-----------------------------------------------------------------------------
void DataSource::operatorTransformModified()
{
bool prev = this->blockSignals(true);
this->resetData();
foreach (QSharedPointer<Operator> op, this->Internals->Operators)
{
this->operate(op.data());
}
this->blockSignals(prev);
emit this->dataChanged();
}
//-----------------------------------------------------------------------------
vtkSMProxy* DataSource::colorMap() const
{
return this->Internals->ColorMap;
}
//-----------------------------------------------------------------------------
vtkSMProxy* DataSource::opacityMap() const
{
return this->Internals->ColorMap?
vtkSMPropertyHelper(this->Internals->ColorMap, "ScalarOpacityFunction").GetAsProxy() : NULL;
}
//-----------------------------------------------------------------------------
void DataSource::updateColorMap()
{
// rescale the color/opacity maps for the data source.
TEM::rescaleColorMap(this->colorMap(), this);
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief batch request handler
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 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 triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "RestBatchHandler.h"
#include "Basics/StringUtils.h"
#include "Logger/Logger.h"
#include "HttpServer/HttpServer.h"
#include "Rest/HttpRequest.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::arango;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoDB
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////
RestBatchHandler::RestBatchHandler (HttpRequest* request, TRI_vocbase_t* vocbase)
: RestVocbaseBaseHandler(request, vocbase),
_partContentType(HttpRequest::getPartContentType()) {
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////
RestBatchHandler::~RestBatchHandler () {
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- Handler methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoDB
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool RestBatchHandler::isDirect () {
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
string const& RestBatchHandler::queue () {
static string const client = "STANDARD";
return client;
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
Handler::status_e RestBatchHandler::execute() {
// extract the request type
const HttpRequest::HttpRequestType type = _request->requestType();
if (type != HttpRequest::HTTP_REQUEST_POST && type != HttpRequest::HTTP_REQUEST_PUT) {
generateError(HttpResponse::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED);
return Handler::HANDLER_DONE;
}
string boundary;
if (! getBoundary(&boundary)) {
// invalid content-type or boundary sent
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid content-type or boundary received");
return Handler::HANDLER_FAILED;
}
size_t errors = 0;
// get authorization header. we will inject this into the subparts
string authorization = _request->header("authorization");
// create the response
_response = createResponse(HttpResponse::OK);
_response->setContentType(_request->header("content-type"));
// setup some auxiliary structures to parse the multipart message
MultipartMessage message(boundary.c_str(), boundary.size(), _request->body(), _request->body() + _request->bodySize());
SearchHelper helper;
helper.message = &message;
helper.searchStart = (char*) message.messageStart;
// iterate over all parts of the multipart message
while (true) {
// get the next part from the multipart message
if (! extractPart(&helper)) {
// error
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid multipart message received");
LOGGER_WARNING << "received a corrupted multipart message";
return Handler::HANDLER_FAILED;
}
// split part into header & body
const char* partStart = helper.foundStart;
const char* partEnd = partStart + helper.foundLength;
const size_t partLength = helper.foundLength;
const char* headerStart = partStart;
char* bodyStart = NULL;
size_t headerLength = 0;
size_t bodyLength = 0;
// assume Windows linebreak \r\n\r\n as delimiter
char* p = strstr((char*) headerStart, "\r\n\r\n");
if (p != NULL) {
headerLength = p - partStart;
bodyStart = p + 4;
bodyLength = partEnd - bodyStart;
}
else {
// test Unix linebreak
p = strstr((char*) headerStart, "\n\n");
if (p != NULL) {
headerLength = p - partStart;
bodyStart = p + 2;
bodyLength = partEnd - bodyStart;
}
else {
// no delimiter found, assume we have only a header
headerLength = partLength;
}
}
// set up request object for the part
LOGGER_TRACE << "part header is " << string(headerStart, headerLength);
HttpRequest* request = new HttpRequest(headerStart, headerLength);
if (bodyLength > 0) {
LOGGER_TRACE << "part body is " << string(bodyStart, bodyLength);
request->setBody(bodyStart, bodyLength);
}
if (authorization.size()) {
// inject Authorization header of multipart message into part message
request->setHeader("authorization", 13, authorization.c_str());
}
HttpHandler* handler = _server->createHandler(request);
if (! handler) {
delete request;
generateError(HttpResponse::BAD, TRI_ERROR_INTERNAL, "could not create handler for batch part processing");
return Handler::HANDLER_FAILED;
}
Handler::status_e status = Handler::HANDLER_FAILED;
do {
try {
status = handler->execute();
}
catch (triagens::basics::TriagensError const& ex) {
handler->handleError(ex);
}
catch (std::exception const& ex) {
triagens::basics::InternalError err(ex, __FILE__, __LINE__);
handler->handleError(err);
}
catch (...) {
triagens::basics::InternalError err("executeDirectHandler", __FILE__, __LINE__);
handler->handleError(err);
}
}
while (status == Handler::HANDLER_REQUEUE);
if (status == Handler::HANDLER_FAILED) {
// one of the handlers failed, we must exit now
delete handler;
generateError(HttpResponse::BAD, TRI_ERROR_INTERNAL, "executing a handler for batch part failed");
return Handler::HANDLER_FAILED;
}
HttpResponse* partResponse = handler->getResponse();
if (partResponse == 0) {
delete handler;
generateError(HttpResponse::BAD, TRI_ERROR_INTERNAL, "could not create a response for batch part request");
return Handler::HANDLER_FAILED;
}
const HttpResponse::HttpResponseCode code = partResponse->responseCode();
if (code >= 400) {
// error
++errors;
}
// append the boundary for this subpart
_response->body().appendText(boundary + "\r\nContent-Type: ");
_response->body().appendText(_partContentType);
if (helper.contentId != 0) {
// append content-id
_response->body().appendText("\r\nContent-Id: " + string(helper.contentId, helper.contentIdLength));
}
_response->body().appendText("\r\n\r\n", 4);
// append the response header
partResponse->writeHeader(&_response->body());
// append the response body
_response->body().appendText(partResponse->body());
_response->body().appendText("\r\n", 2);
delete handler;
if (! helper.containsMore) {
// we've read the last part
break;
}
} // next part
// append final boundary + "--"
_response->body().appendText(boundary + "--");
if (errors > 0) {
_response->setHeader(HttpResponse::getBatchErrorHeader(), StringUtils::itoa(errors));
}
// success
return Handler::HANDLER_DONE;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief extract the boundary of a multipart message
////////////////////////////////////////////////////////////////////////////////
bool RestBatchHandler::getBoundary (string* result) {
assert(_request);
// extract content type
string contentType = StringUtils::trim(_request->header("content-type"));
// content type is expect to contain a boundary like this:
// "Content-Type: multipart/form-data; boundary=<boundary goes here>"
vector<string> parts = StringUtils::split(contentType, ';');
if (parts.size() != 2 || parts[0] != HttpRequest::getMultipartContentType().c_str()) {
// content-type is not formatted as expected
return false;
}
static const size_t boundaryLength = 9; // strlen("boundary=");
// trim 2nd part and lowercase it
StringUtils::trimInPlace(parts[1]);
string p = parts[1].substr(0, boundaryLength);
StringUtils::tolowerInPlace(&p);
if (p != "boundary=") {
return false;
}
string boundary = "--" + parts[1].substr(boundaryLength);
if (boundary.size() < 5) {
// 3 bytes is min length for boundary (without "--")
return false;
}
LOGGER_TRACE << "boundary of multipart-message is " << boundary;
*result = boundary;
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief extract the next part from a multipart message
////////////////////////////////////////////////////////////////////////////////
bool RestBatchHandler::extractPart (SearchHelper* helper) {
assert(helper->searchStart != NULL);
// init the response
helper->foundStart = NULL;
helper->foundLength = 0;
helper->containsMore = false;
helper->contentId = 0;
helper->contentIdLength = 0;
const char* searchEnd = helper->message->messageEnd;
if (helper->searchStart >= searchEnd) {
// we're at the end already
return false;
}
// search for boundary
char* found = strstr(helper->searchStart, helper->message->boundary);
if (found == NULL) {
// not contained. this is an error
return false;
}
if (found != helper->searchStart) {
// boundary not located at beginning. this is an error
return false;
}
found += helper->message->boundaryLength;
if (found + 1 >= searchEnd) {
// we're outside the buffer. this is an error
return false;
}
while (found < searchEnd && *found == ' ') {
++found;
}
if (found + 2 >= searchEnd) {
// we're outside the buffer. this is an error
return false;
}
if (*found == '\r') {
++found;
}
if (*found != '\n') {
// no linebreak found
return false;
}
++found;
bool hasTypeHeader = false;
while (found < searchEnd) {
char* eol = strstr(found, "\r\n");
if (0 == eol || eol == found) {
break;
}
// split key/value of header
char* colon = (char*) memchr(found, (int) ':', eol - found);
if (0 == colon) {
// invalid header, not containing ':'
return false;
}
// set up key/value pair
string key(found, colon - found);
StringUtils::trimInPlace(key);
StringUtils::tolowerInPlace(&key);
// skip the colon itself
++colon;
// skip any whitespace
while (*colon == ' ') {
++colon;
}
string value(colon, eol - colon);
StringUtils::trimInPlace(value);
if ("content-type" == key) {
if (_partContentType == value) {
hasTypeHeader = true;
}
}
else if ("content-id" == key) {
helper->contentId = colon;
helper->contentIdLength = eol - colon;
}
else {
// ignore other headers
}
found = eol + 2;
}
found += 2; // for 2nd \r\n
if (!hasTypeHeader) {
// no Content-Type header. this is an error
return false;
}
// we're at the start of the body part. set the return value
helper->foundStart = found;
// search for the end of the boundary
found = strstr(helper->foundStart, helper->message->boundary);
if (found == NULL || found >= searchEnd) {
// did not find the end. this is an error
return false;
}
helper->foundLength = found - helper->foundStart;
char* p = found + helper->message->boundaryLength;
if (p + 2 >= searchEnd) {
// end of boundary is outside the buffer
return false;
}
if (*p != '-' || *(p + 1) != '-') {
// we've not reached the end yet
helper->containsMore = true;
helper->searchStart = found;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<commit_msg>remove unnecessary response headers in sub responses<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief batch request handler
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 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 triAGENS GmbH, Cologne, Germany
///
/// @author Jan Steemann
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "RestBatchHandler.h"
#include "Basics/StringUtils.h"
#include "Logger/Logger.h"
#include "HttpServer/HttpServer.h"
#include "Rest/HttpRequest.h"
using namespace std;
using namespace triagens::basics;
using namespace triagens::rest;
using namespace triagens::arango;
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoDB
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////
RestBatchHandler::RestBatchHandler (HttpRequest* request, TRI_vocbase_t* vocbase)
: RestVocbaseBaseHandler(request, vocbase),
_partContentType(HttpRequest::getPartContentType()) {
}
////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////
RestBatchHandler::~RestBatchHandler () {
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- Handler methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup ArangoDB
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
bool RestBatchHandler::isDirect () {
return false;
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
string const& RestBatchHandler::queue () {
static string const client = "STANDARD";
return client;
}
////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////
Handler::status_e RestBatchHandler::execute() {
// extract the request type
const HttpRequest::HttpRequestType type = _request->requestType();
if (type != HttpRequest::HTTP_REQUEST_POST && type != HttpRequest::HTTP_REQUEST_PUT) {
generateError(HttpResponse::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED);
return Handler::HANDLER_DONE;
}
string boundary;
if (! getBoundary(&boundary)) {
// invalid content-type or boundary sent
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid content-type or boundary received");
return Handler::HANDLER_FAILED;
}
size_t errors = 0;
// get authorization header. we will inject this into the subparts
string authorization = _request->header("authorization");
// create the response
_response = createResponse(HttpResponse::OK);
_response->setContentType(_request->header("content-type"));
// setup some auxiliary structures to parse the multipart message
MultipartMessage message(boundary.c_str(), boundary.size(), _request->body(), _request->body() + _request->bodySize());
SearchHelper helper;
helper.message = &message;
helper.searchStart = (char*) message.messageStart;
// iterate over all parts of the multipart message
while (true) {
// get the next part from the multipart message
if (! extractPart(&helper)) {
// error
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER, "invalid multipart message received");
LOGGER_WARNING << "received a corrupted multipart message";
return Handler::HANDLER_FAILED;
}
// split part into header & body
const char* partStart = helper.foundStart;
const char* partEnd = partStart + helper.foundLength;
const size_t partLength = helper.foundLength;
const char* headerStart = partStart;
char* bodyStart = NULL;
size_t headerLength = 0;
size_t bodyLength = 0;
// assume Windows linebreak \r\n\r\n as delimiter
char* p = strstr((char*) headerStart, "\r\n\r\n");
if (p != NULL) {
headerLength = p - partStart;
bodyStart = p + 4;
bodyLength = partEnd - bodyStart;
}
else {
// test Unix linebreak
p = strstr((char*) headerStart, "\n\n");
if (p != NULL) {
headerLength = p - partStart;
bodyStart = p + 2;
bodyLength = partEnd - bodyStart;
}
else {
// no delimiter found, assume we have only a header
headerLength = partLength;
}
}
// set up request object for the part
LOGGER_TRACE << "part header is " << string(headerStart, headerLength);
HttpRequest* request = new HttpRequest(headerStart, headerLength);
if (bodyLength > 0) {
LOGGER_TRACE << "part body is " << string(bodyStart, bodyLength);
request->setBody(bodyStart, bodyLength);
}
if (authorization.size()) {
// inject Authorization header of multipart message into part message
request->setHeader("authorization", 13, authorization.c_str());
}
HttpHandler* handler = _server->createHandler(request);
if (! handler) {
delete request;
generateError(HttpResponse::BAD, TRI_ERROR_INTERNAL, "could not create handler for batch part processing");
return Handler::HANDLER_FAILED;
}
Handler::status_e status = Handler::HANDLER_FAILED;
do {
try {
status = handler->execute();
}
catch (triagens::basics::TriagensError const& ex) {
handler->handleError(ex);
}
catch (std::exception const& ex) {
triagens::basics::InternalError err(ex, __FILE__, __LINE__);
handler->handleError(err);
}
catch (...) {
triagens::basics::InternalError err("executeDirectHandler", __FILE__, __LINE__);
handler->handleError(err);
}
}
while (status == Handler::HANDLER_REQUEUE);
if (status == Handler::HANDLER_FAILED) {
// one of the handlers failed, we must exit now
delete handler;
generateError(HttpResponse::BAD, TRI_ERROR_INTERNAL, "executing a handler for batch part failed");
return Handler::HANDLER_FAILED;
}
HttpResponse* partResponse = handler->getResponse();
if (partResponse == 0) {
delete handler;
generateError(HttpResponse::BAD, TRI_ERROR_INTERNAL, "could not create a response for batch part request");
return Handler::HANDLER_FAILED;
}
const HttpResponse::HttpResponseCode code = partResponse->responseCode();
if (code >= 400) {
// error
++errors;
}
// append the boundary for this subpart
_response->body().appendText(boundary + "\r\nContent-Type: ");
_response->body().appendText(_partContentType);
if (helper.contentId != 0) {
// append content-id
_response->body().appendText("\r\nContent-Id: " + string(helper.contentId, helper.contentIdLength));
}
_response->body().appendText("\r\n\r\n", 4);
// remove some headers we don't need
partResponse->setHeader("connection", 10, "");
partResponse->setHeader("server", 6, "");
// append the part response header
partResponse->writeHeader(&_response->body());
// append the part response body
_response->body().appendText(partResponse->body());
_response->body().appendText("\r\n", 2);
delete handler;
if (! helper.containsMore) {
// we've read the last part
break;
}
} // next part
// append final boundary + "--"
_response->body().appendText(boundary + "--");
if (errors > 0) {
_response->setHeader(HttpResponse::getBatchErrorHeader(), StringUtils::itoa(errors));
}
// success
return Handler::HANDLER_DONE;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief extract the boundary of a multipart message
////////////////////////////////////////////////////////////////////////////////
bool RestBatchHandler::getBoundary (string* result) {
assert(_request);
// extract content type
string contentType = StringUtils::trim(_request->header("content-type"));
// content type is expect to contain a boundary like this:
// "Content-Type: multipart/form-data; boundary=<boundary goes here>"
vector<string> parts = StringUtils::split(contentType, ';');
if (parts.size() != 2 || parts[0] != HttpRequest::getMultipartContentType().c_str()) {
// content-type is not formatted as expected
return false;
}
static const size_t boundaryLength = 9; // strlen("boundary=");
// trim 2nd part and lowercase it
StringUtils::trimInPlace(parts[1]);
string p = parts[1].substr(0, boundaryLength);
StringUtils::tolowerInPlace(&p);
if (p != "boundary=") {
return false;
}
string boundary = "--" + parts[1].substr(boundaryLength);
if (boundary.size() < 5) {
// 3 bytes is min length for boundary (without "--")
return false;
}
LOGGER_TRACE << "boundary of multipart-message is " << boundary;
*result = boundary;
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief extract the next part from a multipart message
////////////////////////////////////////////////////////////////////////////////
bool RestBatchHandler::extractPart (SearchHelper* helper) {
assert(helper->searchStart != NULL);
// init the response
helper->foundStart = NULL;
helper->foundLength = 0;
helper->containsMore = false;
helper->contentId = 0;
helper->contentIdLength = 0;
const char* searchEnd = helper->message->messageEnd;
if (helper->searchStart >= searchEnd) {
// we're at the end already
return false;
}
// search for boundary
char* found = strstr(helper->searchStart, helper->message->boundary);
if (found == NULL) {
// not contained. this is an error
return false;
}
if (found != helper->searchStart) {
// boundary not located at beginning. this is an error
return false;
}
found += helper->message->boundaryLength;
if (found + 1 >= searchEnd) {
// we're outside the buffer. this is an error
return false;
}
while (found < searchEnd && *found == ' ') {
++found;
}
if (found + 2 >= searchEnd) {
// we're outside the buffer. this is an error
return false;
}
if (*found == '\r') {
++found;
}
if (*found != '\n') {
// no linebreak found
return false;
}
++found;
bool hasTypeHeader = false;
while (found < searchEnd) {
char* eol = strstr(found, "\r\n");
if (0 == eol || eol == found) {
break;
}
// split key/value of header
char* colon = (char*) memchr(found, (int) ':', eol - found);
if (0 == colon) {
// invalid header, not containing ':'
return false;
}
// set up key/value pair
string key(found, colon - found);
StringUtils::trimInPlace(key);
StringUtils::tolowerInPlace(&key);
// skip the colon itself
++colon;
// skip any whitespace
while (*colon == ' ') {
++colon;
}
string value(colon, eol - colon);
StringUtils::trimInPlace(value);
if ("content-type" == key) {
if (_partContentType == value) {
hasTypeHeader = true;
}
}
else if ("content-id" == key) {
helper->contentId = colon;
helper->contentIdLength = eol - colon;
}
else {
// ignore other headers
}
found = eol + 2;
}
found += 2; // for 2nd \r\n
if (!hasTypeHeader) {
// no Content-Type header. this is an error
return false;
}
// we're at the start of the body part. set the return value
helper->foundStart = found;
// search for the end of the boundary
found = strstr(helper->foundStart, helper->message->boundary);
if (found == NULL || found >= searchEnd) {
// did not find the end. this is an error
return false;
}
helper->foundLength = found - helper->foundStart;
char* p = found + helper->message->boundaryLength;
if (p + 2 >= searchEnd) {
// end of boundary is outside the buffer
return false;
}
if (*p != '-' || *(p + 1) != '-') {
// we've not reached the end yet
helper->containsMore = true;
helper->searchStart = found;
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|// --SECTION--\\|/// @\\}\\)"
// End:
<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XALANVERSION_HEADER_GUARD_1357924680)
#define XALANVERSION_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// X A L A N V E R S I O N H E A D E R D O C U M E N T A T I O N
/**
* User Documentation for Xalan Version Values:
*
*
*
* Xalan Notes:
*
* Xalan Committers Documentation:
*
* Xalan committers normally only need to modify one or two of the
* following macros:
*
* XALAN_VERSION_MAJOR
* XALAN_VERSION_MINOR
* XALAN_VERSION_REVISION
*
* The integer values of these macros define the Xalan version number. All
* other constants and preprocessor macros are automatically generated from
* these three definitions.
*
* Xalan User Documentation:
*
* The following sections in the user documentation have examples based upon
* the following three version input values:
*
* #define XALAN_VERSION_MAJOR 19
* #define XALAN_VERSION_MINOR 3
* #define XALAN_VERSION_REVISION 74
*
* The minor and revision (patch level) numbers have two digits of resolution
* which means that '3' becomes '03' in this example. This policy guarantees
* that when using preprocessor macros, version 19.3.74 will be greater than
* version 1.94.74 since the first will expand to 190374 and the second to
* 19474.
*
* Preprocessor Macros:
*
* _XALAN_VERSION defines the primary preprocessor macro that users will
* introduce into their code to perform conditional compilation where the
* version of Xalan is detected in order to enable or disable version
* specific capabilities. The value of _XALAN_VERSION for the above example
* will be 190374. To use it a user would perform an operation such as the
* following:
*
* #if _XALAN_VERSION >= 190374
* // code specific to new version of Xalan...
* #else
* // old code here...
* #endif
*
* XALAN_FULLVERSIONSTR is a preprocessor macro that expands to a string
* constant whose value, for the above example, will be "19_3_74".
*
* XALAN_FULLVERSIONDOT is a preprocessor macro that expands to a string
* constant whose value, for the above example, will be "19.3.74".
*
* XALAN_VERSIONSTR is a preprocessor macro that expands to a string
* constant whose value, for the above example, will be "19374". This
* particular macro is very dangerous if it were to be used for comparing
* version numbers since ordering will not be guaranteed.
*
* Xalan_DLLVersionStr is a preprocessor macro that expands to a string
* constant whose value, for the above example, will be "19_3_74". This
* macro is provided for backwards compatibility to pre-1.7 versions of
* Xalan.
*
* String Constants:
*
* gXalanVersionStr is a global string constant whose value corresponds to
* the value "19_3" for the above example.
*
* gXalanFullVersionStr is a global string constant whose value corresponds
* to the value "19_3_74" for the above example.
*
* Numeric Constants:
*
* gXalanMajVersion is a global integer constant whose value corresponds to
* the major version number. For the above example its value will be 19.
*
* gXalanMinVersion is a global integer constant whose value corresponds to
* the minor version number. For the above example its value will be 3.
*
* gXalanRevision is a global integer constant whose value corresponds to
* the revision (patch) version number. For the above example its value will
* be 74.
*
*/
// ---------------------------------------------------------------------------
// X A L A N V E R S I O N S P E C I F I C A T I O N
/**
* MODIFY THESE NUMERIC VALUES TO COINCIDE WITH XALAN VERSION
* AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE
*/
#define XALAN_VERSION_MAJOR 1
#define XALAN_VERSION_MINOR 4
#define XALAN_VERSION_REVISION 0
/** DO NOT MODIFY BELOW THIS LINE */
/**
* MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:
*
* Xalan_DLLVersionStr, gXalanVersionStr, gXalanFullVersionStr,
* gXalanMajVersion, gXalanMinVersion, gXalanRevision
*/
// ---------------------------------------------------------------------------
// T W O A R G U M E N T C O N C A T E N A T I O N M A C R O S
// two argument concatenation routines
#define CAT2_SEP_UNDERSCORE(a, b) #a "_" #b
#define CAT2_SEP_PERIOD(a, b) #a "." #b
#define CAT2_SEP_NIL(a, b) #a #b
#define CAT2_RAW_NUMERIC(a, b) a ## b
// two argument macro invokers
#define INVK_CAT2_SEP_UNDERSCORE(a,b) CAT2_SEP_UNDERSCORE(a,b)
#define INVK_CAT2_SEP_PERIOD(a,b) CAT2_SEP_PERIOD(a,b)
#define INVK_CAT2_STR_SEP_NIL(a,b) CAT2_SEP_NIL(a,b)
#define INVK_CAT2_RAW_NUMERIC(a,b) CAT2_RAW_NUMERIC(a,b)
// ---------------------------------------------------------------------------
// T H R E E A R G U M E N T C O N C A T E N A T I O N M A C R O S
// three argument concatenation routines
#define CAT3_SEP_UNDERSCORE(a, b, c) #a "_" #b "_" #c
#define CAT3_SEP_PERIOD(a, b, c) #a "." #b "." #c
#define CAT3_SEP_NIL(a, b, c) #a #b #c
#define CAT3_RAW_NUMERIC(a, b, c) a ## b ## c
// three argument macro invokers
#define INVK_CAT3_SEP_UNDERSCORE(a,b,c) CAT3_SEP_UNDERSCORE(a,b,c)
#define INVK_CAT3_SEP_PERIOD(a,b,c) CAT3_SEP_PERIOD(a,b,c)
#define INVK_CAT3_SEP_NIL(a,b,c) CAT3_SEP_NIL(a,b,c)
#define INVK_CAT3_RAW_NUMERIC(a,b,c) CAT3_RAW_NUMERIC(a,b,c)
// ---------------------------------------------------------------------------
// C A L C U L A T E V E R S I O N - E X P A N D E D F O R M
#define MULTIPLY(factor,value) factor * value
#define CALC_EXPANDED_FORM(a,b,c) ( MULTIPLY(10000,a) + MULTIPLY(100,b) + MULTIPLY(1,c) )
// ---------------------------------------------------------------------------
// X A L A N V E R S I O N I N F O R M A T I O N
// Xalan version strings; these particular macros cannot be used for
// conditional compilation as they are not numeric constants
#define XALAN_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_VERSIONSTR INVK_CAT2_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR)
// original from Xalan header
#define Xalan_DLLVersionStr XALAN_FULLVERSIONSTR
const char* const gXalanVersionStr = XALAN_VERSIONSTR;
const char* const gXalanFullVersionStr = XALAN_FULLVERSIONSTR;
const unsigned int gXalanMajVersion = XALAN_VERSION_MAJOR;
const unsigned int gXalanMinVersion = XALAN_VERSION_MINOR;
const unsigned int gXalanRevision = XALAN_VERSION_REVISION;
// Xalan version numeric constants that can be used for conditional
// compilation purposes.
#define _XALAN_VERSION CALC_EXPANDED_FORM (XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#endif // XALANVERSION_HEADER_GUARD_1357924680
<commit_msg>Bumped minor version number.<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2002 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xalan" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
#if !defined(XALANVERSION_HEADER_GUARD_1357924680)
#define XALANVERSION_HEADER_GUARD_1357924680
// ---------------------------------------------------------------------------
// X A L A N V E R S I O N H E A D E R D O C U M E N T A T I O N
/**
* User Documentation for Xalan Version Values:
*
*
*
* Xalan Notes:
*
* Xalan Committers Documentation:
*
* Xalan committers normally only need to modify one or two of the
* following macros:
*
* XALAN_VERSION_MAJOR
* XALAN_VERSION_MINOR
* XALAN_VERSION_REVISION
*
* The integer values of these macros define the Xalan version number. All
* other constants and preprocessor macros are automatically generated from
* these three definitions.
*
* Xalan User Documentation:
*
* The following sections in the user documentation have examples based upon
* the following three version input values:
*
* #define XALAN_VERSION_MAJOR 19
* #define XALAN_VERSION_MINOR 3
* #define XALAN_VERSION_REVISION 74
*
* The minor and revision (patch level) numbers have two digits of resolution
* which means that '3' becomes '03' in this example. This policy guarantees
* that when using preprocessor macros, version 19.3.74 will be greater than
* version 1.94.74 since the first will expand to 190374 and the second to
* 19474.
*
* Preprocessor Macros:
*
* _XALAN_VERSION defines the primary preprocessor macro that users will
* introduce into their code to perform conditional compilation where the
* version of Xalan is detected in order to enable or disable version
* specific capabilities. The value of _XALAN_VERSION for the above example
* will be 190374. To use it a user would perform an operation such as the
* following:
*
* #if _XALAN_VERSION >= 190374
* // code specific to new version of Xalan...
* #else
* // old code here...
* #endif
*
* XALAN_FULLVERSIONSTR is a preprocessor macro that expands to a string
* constant whose value, for the above example, will be "19_3_74".
*
* XALAN_FULLVERSIONDOT is a preprocessor macro that expands to a string
* constant whose value, for the above example, will be "19.3.74".
*
* XALAN_VERSIONSTR is a preprocessor macro that expands to a string
* constant whose value, for the above example, will be "19374". This
* particular macro is very dangerous if it were to be used for comparing
* version numbers since ordering will not be guaranteed.
*
* Xalan_DLLVersionStr is a preprocessor macro that expands to a string
* constant whose value, for the above example, will be "19_3_74". This
* macro is provided for backwards compatibility to pre-1.7 versions of
* Xalan.
*
* String Constants:
*
* gXalanVersionStr is a global string constant whose value corresponds to
* the value "19_3" for the above example.
*
* gXalanFullVersionStr is a global string constant whose value corresponds
* to the value "19_3_74" for the above example.
*
* Numeric Constants:
*
* gXalanMajVersion is a global integer constant whose value corresponds to
* the major version number. For the above example its value will be 19.
*
* gXalanMinVersion is a global integer constant whose value corresponds to
* the minor version number. For the above example its value will be 3.
*
* gXalanRevision is a global integer constant whose value corresponds to
* the revision (patch) version number. For the above example its value will
* be 74.
*
*/
// ---------------------------------------------------------------------------
// X A L A N V E R S I O N S P E C I F I C A T I O N
/**
* MODIFY THESE NUMERIC VALUES TO COINCIDE WITH XALAN VERSION
* AND DO NOT MODIFY ANYTHING ELSE IN THIS VERSION HEADER FILE
*/
#define XALAN_VERSION_MAJOR 1
#define XALAN_VERSION_MINOR 5
#define XALAN_VERSION_REVISION 0
/** DO NOT MODIFY BELOW THIS LINE */
/**
* MAGIC THAT AUTOMATICALLY GENERATES THE FOLLOWING:
*
* Xalan_DLLVersionStr, gXalanVersionStr, gXalanFullVersionStr,
* gXalanMajVersion, gXalanMinVersion, gXalanRevision
*/
// ---------------------------------------------------------------------------
// T W O A R G U M E N T C O N C A T E N A T I O N M A C R O S
// two argument concatenation routines
#define CAT2_SEP_UNDERSCORE(a, b) #a "_" #b
#define CAT2_SEP_PERIOD(a, b) #a "." #b
#define CAT2_SEP_NIL(a, b) #a #b
#define CAT2_RAW_NUMERIC(a, b) a ## b
// two argument macro invokers
#define INVK_CAT2_SEP_UNDERSCORE(a,b) CAT2_SEP_UNDERSCORE(a,b)
#define INVK_CAT2_SEP_PERIOD(a,b) CAT2_SEP_PERIOD(a,b)
#define INVK_CAT2_STR_SEP_NIL(a,b) CAT2_SEP_NIL(a,b)
#define INVK_CAT2_RAW_NUMERIC(a,b) CAT2_RAW_NUMERIC(a,b)
// ---------------------------------------------------------------------------
// T H R E E A R G U M E N T C O N C A T E N A T I O N M A C R O S
// three argument concatenation routines
#define CAT3_SEP_UNDERSCORE(a, b, c) #a "_" #b "_" #c
#define CAT3_SEP_PERIOD(a, b, c) #a "." #b "." #c
#define CAT3_SEP_NIL(a, b, c) #a #b #c
#define CAT3_RAW_NUMERIC(a, b, c) a ## b ## c
// three argument macro invokers
#define INVK_CAT3_SEP_UNDERSCORE(a,b,c) CAT3_SEP_UNDERSCORE(a,b,c)
#define INVK_CAT3_SEP_PERIOD(a,b,c) CAT3_SEP_PERIOD(a,b,c)
#define INVK_CAT3_SEP_NIL(a,b,c) CAT3_SEP_NIL(a,b,c)
#define INVK_CAT3_RAW_NUMERIC(a,b,c) CAT3_RAW_NUMERIC(a,b,c)
// ---------------------------------------------------------------------------
// C A L C U L A T E V E R S I O N - E X P A N D E D F O R M
#define MULTIPLY(factor,value) factor * value
#define CALC_EXPANDED_FORM(a,b,c) ( MULTIPLY(10000,a) + MULTIPLY(100,b) + MULTIPLY(1,c) )
// ---------------------------------------------------------------------------
// X A L A N V E R S I O N I N F O R M A T I O N
// Xalan version strings; these particular macros cannot be used for
// conditional compilation as they are not numeric constants
#define XALAN_FULLVERSIONSTR INVK_CAT3_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_FULLVERSIONDOT INVK_CAT3_SEP_PERIOD(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_FULLVERSIONNUM INVK_CAT3_SEP_NIL(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#define XALAN_VERSIONSTR INVK_CAT2_SEP_UNDERSCORE(XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR)
// original from Xalan header
#define Xalan_DLLVersionStr XALAN_FULLVERSIONSTR
const char* const gXalanVersionStr = XALAN_VERSIONSTR;
const char* const gXalanFullVersionStr = XALAN_FULLVERSIONSTR;
const unsigned int gXalanMajVersion = XALAN_VERSION_MAJOR;
const unsigned int gXalanMinVersion = XALAN_VERSION_MINOR;
const unsigned int gXalanRevision = XALAN_VERSION_REVISION;
// Xalan version numeric constants that can be used for conditional
// compilation purposes.
#define _XALAN_VERSION CALC_EXPANDED_FORM (XALAN_VERSION_MAJOR,XALAN_VERSION_MINOR,XALAN_VERSION_REVISION)
#endif // XALANVERSION_HEADER_GUARD_1357924680
<|endoftext|> |
<commit_before>#include <node.h>
#include <nan.h>
#include <memory>
#define TYPECHK(expr, msg) if (! expr) { \
Nan::ThrowTypeError(msg); \
return; \
}
extern "C" {
#include "sss/sss.h"
}
class CreateSharesWorker : public Nan::AsyncWorker {
public:
CreateSharesWorker(char* data, uint8_t n, uint8_t k, Nan::Callback *callback)
: AsyncWorker(callback), n(n), k(k) {
Nan::HandleScope scope;
memcpy(this->data, data, sss_MLEN);
}
void Execute() {
this->output = std::unique_ptr<sss_Share[]>{ new sss_Share[n]() };
sss_create_shares(output.get(), (uint8_t*) data, n, k);
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// Copy the output to a list of node.js buffers
v8::Local<v8::Array> array = v8::Array::New(isolate, n);
for (size_t idx = 0; idx < n; ++idx) {
array->Set(idx, Nan::CopyBuffer((char*) output[idx],
sss_SHARE_LEN).ToLocalChecked());
}
v8::Local<v8::Value> argv[] = { array };
// Call the provided callback
Nan::Call(**callback, Nan::GetCurrentContext()->Global(), 1, argv);
}
private:
uint8_t n, k;
char data[sss_MLEN];
std::unique_ptr<sss_Share[]> output;
};
class CombineSharesWorker : public Nan::AsyncWorker {
public:
CombineSharesWorker(std::unique_ptr<v8::Local<v8::Object>[]> &shares,
uint8_t k, Nan::Callback *callback)
: AsyncWorker(callback), k(k) {
Nan::HandleScope scope;
this->input = std::unique_ptr<sss_Share[]>{ new sss_Share[k] };
for (auto idx = 0; idx < k; ++idx) {
memcpy(&this->input[idx], node::Buffer::Data(shares[idx]), sss_SHARE_LEN);
}
}
void Execute() {
status = sss_combine_shares((uint8_t*) data, input.get(), k);
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[1];
if (status == 0) {
// All went well, call the callback the restored buffer
argv[0] = Nan::CopyBuffer(data, sss_MLEN).ToLocalChecked();
} else {
// Some kind of error occurred, return null
argv[0] = Nan::Null();
}
Nan::Call(**callback, Nan::GetCurrentContext()->Global(), 1, argv);
}
private:
uint8_t k;
std::unique_ptr<sss_Share[]> input;
int status;
char data[sss_MLEN];
};
NAN_METHOD(CreateShares) {
Nan::HandleScope scope;
v8::Local<v8::Value> data_val = info[0];
v8::Local<v8::Value> n_val = info[1];
v8::Local<v8::Value> k_val = info[2];
v8::Local<v8::Value> callback_val = info[3];
// Type check the arguments
TYPECHK(!data_val->IsUndefined(), "`data` is not defined");
TYPECHK(!n_val->IsUndefined(), "`n` is not defined");
TYPECHK(!k_val->IsUndefined(), "`k` is not defined");
TYPECHK(!callback_val->IsUndefined(), "`callback` is not defined");
TYPECHK(data_val->IsObject(), "`data` is not an Object");
v8::Local<v8::Object> data = data_val->ToObject();
TYPECHK(node::Buffer::HasInstance(data), "`data` must be a Buffer")
TYPECHK(n_val->IsUint32(), "`n` is not a valid integer");
uint32_t n = n_val->Uint32Value();
TYPECHK(k_val->IsUint32(), "`k` is not a valid integer");
uint32_t k = k_val->Uint32Value();
TYPECHK(callback_val->IsFunction(), "`callback` must be a function");
Nan::Callback *callback = new Nan::Callback(callback_val.As<v8::Function>());
// Check if the buffers have the correct lengths
if (node::Buffer::Length(data) != sss_MLEN) {
Nan::ThrowRangeError("`data` buffer size must be exactly 64 bytes");
return;
};
// Check if n and k are correct
if (n < 1 || n > 255) {
Nan::ThrowRangeError("`n` must be between 1 and 255");
return;
}
if (k < 1 || k > n) {
Nan::ThrowRangeError("`k` must be between 1 and n");
return;
}
// Create worker
CreateSharesWorker* worker = new CreateSharesWorker(
node::Buffer::Data(data), n, k, callback);
AsyncQueueWorker(worker);
}
NAN_METHOD(CombineShares) {
Nan::HandleScope scope;
v8::Local<v8::Value> shares_val = info[0];
v8::Local<v8::Value> callback_val = info[1];
// Type check the argument `shares` and `callback`
TYPECHK(!shares_val->IsUndefined(), "`shares` is not defined");
TYPECHK(!callback_val->IsUndefined(), "`callback` is not defined");
TYPECHK(shares_val->IsObject(), "`shares` is not an initialized Object")
v8::Local<v8::Object> shares_obj = shares_val->ToObject();
TYPECHK(shares_val->IsArray(), "`shares` must be an array of buffers");
v8::Local<v8::Array> shares_arr = shares_obj.As<v8::Array>();
TYPECHK(callback_val->IsFunction(), "`callback` must be a function");
Nan::Callback *callback = new Nan::Callback(callback_val.As<v8::Function>());
// Extract all the share buffers
auto k = shares_arr->Length();
std::unique_ptr<v8::Local<v8::Object>[]> shares(new v8::Local<v8::Object>[k]);
for (auto idx = 0; idx < k; ++idx) {
shares[idx] = shares_arr->Get(idx)->ToObject();
}
// Check if all the elements in the array are buffers
for (auto idx = 0; idx < k; ++idx) {
if (!node::Buffer::HasInstance(shares[idx])) {
Nan::ThrowTypeError("array element is not a buffer");
return;
}
}
// Check if all the elements in the array are of the correct length
for (auto idx = 0; idx < k; ++idx) {
if (node::Buffer::Length(shares[idx]) != sss_SHARE_LEN) {
Nan::ThrowTypeError("array buffer element is not of the correct length");
return;
}
}
// Create worker
CombineSharesWorker* worker = new CombineSharesWorker(shares, k, callback);
AsyncQueueWorker(worker);
}
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
Nan::HandleScope scope;
Nan::SetMethod(exports, "createShares", CreateShares);
Nan::SetMethod(exports, "combineShares", CombineShares);
}
NODE_MODULE(shamirsecretsharing, Initialize)
<commit_msg>Implement hazmat functions in C++<commit_after>#include <node.h>
#include <nan.h>
#include <memory>
#define TYPECHK(expr, msg) if (! expr) { \
Nan::ThrowTypeError(msg); \
return; \
}
extern "C" {
#include "sss/sss.h"
}
class CreateSharesWorker : public Nan::AsyncWorker {
public:
CreateSharesWorker(char* data, uint8_t n, uint8_t k, Nan::Callback *callback)
: AsyncWorker(callback), n(n), k(k) {
Nan::HandleScope scope;
memcpy(this->data, data, sss_MLEN);
}
void Execute() {
this->output = std::unique_ptr<sss_Share[]>{ new sss_Share[n]() };
sss_create_shares(output.get(), (uint8_t*) data, n, k);
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// Copy the output to a list of node.js buffers
v8::Local<v8::Array> array = v8::Array::New(isolate, n);
for (size_t idx = 0; idx < n; ++idx) {
array->Set(idx, Nan::CopyBuffer((char*) output[idx],
sss_SHARE_LEN).ToLocalChecked());
}
v8::Local<v8::Value> argv[] = { array };
// Call the provided callback
Nan::Call(**callback, Nan::GetCurrentContext()->Global(), 1, argv);
}
private:
uint8_t n, k;
char data[sss_MLEN];
std::unique_ptr<sss_Share[]> output;
};
class CombineSharesWorker : public Nan::AsyncWorker {
public:
CombineSharesWorker(std::unique_ptr<v8::Local<v8::Object>[]> &shares,
uint8_t k, Nan::Callback *callback)
: AsyncWorker(callback), k(k) {
Nan::HandleScope scope;
this->input = std::unique_ptr<sss_Share[]>{ new sss_Share[k] };
for (auto idx = 0; idx < k; ++idx) {
memcpy(&this->input[idx], node::Buffer::Data(shares[idx]), sss_SHARE_LEN);
}
}
void Execute() {
status = sss_combine_shares((uint8_t*) data, input.get(), k);
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[1];
if (status == 0) {
// All went well, call the callback the restored buffer
argv[0] = Nan::CopyBuffer(data, sss_MLEN).ToLocalChecked();
} else {
// Some kind of error occurred, return null
argv[0] = Nan::Null();
}
Nan::Call(**callback, Nan::GetCurrentContext()->Global(), 1, argv);
}
private:
uint8_t k;
std::unique_ptr<sss_Share[]> input;
int status;
char data[sss_MLEN];
};
class CreateKeysharesWorker : public Nan::AsyncWorker {
public:
CreateKeysharesWorker(char* key, uint8_t n, uint8_t k, Nan::Callback *callback)
: AsyncWorker(callback), n(n), k(k) {
Nan::HandleScope scope;
memcpy(this->key, key, 32);
}
void Execute() {
this->output = std::unique_ptr<sss_Keyshare[]>{ new sss_Keyshare[n]() };
sss_create_keyshares(output.get(), (uint8_t*) key, n, k);
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Isolate* isolate = v8::Isolate::GetCurrent();
// Copy the output keyshares to a list of node.js buffers
v8::Local<v8::Array> array = v8::Array::New(isolate, n);
for (size_t idx = 0; idx < n; ++idx) {
array->Set(idx, Nan::CopyBuffer((char*) output[idx],
sss_KEYSHARE_LEN).ToLocalChecked());
}
v8::Local<v8::Value> argv[] = { array };
// Call the provided callback
Nan::Call(**callback, Nan::GetCurrentContext()->Global(), 1, argv);
}
private:
uint8_t n, k;
char key[32];
std::unique_ptr<sss_Keyshare[]> output;
};
class CombineKeysharesWorker : public Nan::AsyncWorker {
public:
CombineKeysharesWorker(std::unique_ptr<v8::Local<v8::Object>[]> &keyshares,
uint8_t k, Nan::Callback *callback)
: AsyncWorker(callback), k(k) {
Nan::HandleScope scope;
this->input = std::unique_ptr<sss_Keyshare[]>{ new sss_Keyshare[k] };
for (auto idx = 0; idx < k; ++idx) {
memcpy(&this->input[idx], node::Buffer::Data(keyshares[idx]),
sss_KEYSHARE_LEN);
}
}
void Execute() {
sss_combine_keyshares((uint8_t*) key, input.get(), k);
}
void HandleOKCallback() {
Nan::HandleScope scope;
v8::Local<v8::Value> argv[] = { Nan::CopyBuffer(key, 32).ToLocalChecked() };
Nan::Call(**callback, Nan::GetCurrentContext()->Global(), 1, argv);
}
private:
uint8_t k;
std::unique_ptr<sss_Keyshare[]> input;
char key[32];
};
NAN_METHOD(CreateShares) {
Nan::HandleScope scope;
v8::Local<v8::Value> data_val = info[0];
v8::Local<v8::Value> n_val = info[1];
v8::Local<v8::Value> k_val = info[2];
v8::Local<v8::Value> callback_val = info[3];
// Type check the arguments
TYPECHK(!data_val->IsUndefined(), "`data` is not defined");
TYPECHK(!n_val->IsUndefined(), "`n` is not defined");
TYPECHK(!k_val->IsUndefined(), "`k` is not defined");
TYPECHK(!callback_val->IsUndefined(), "`callback` is not defined");
TYPECHK(data_val->IsObject(), "`data` is not an Object");
v8::Local<v8::Object> data = data_val->ToObject();
TYPECHK(node::Buffer::HasInstance(data), "`data` must be a Buffer")
TYPECHK(n_val->IsUint32(), "`n` is not a valid integer");
uint32_t n = n_val->Uint32Value();
TYPECHK(k_val->IsUint32(), "`k` is not a valid integer");
uint32_t k = k_val->Uint32Value();
TYPECHK(callback_val->IsFunction(), "`callback` must be a function");
Nan::Callback *callback = new Nan::Callback(callback_val.As<v8::Function>());
// Check if the buffers have the correct lengths
if (node::Buffer::Length(data) != sss_MLEN) {
Nan::ThrowRangeError("`data` buffer size must be exactly 64 bytes");
return;
};
// Check if n and k are correct
if (n < 1 || n > 255) {
Nan::ThrowRangeError("`n` must be between 1 and 255");
return;
}
if (k < 1 || k > n) {
Nan::ThrowRangeError("`k` must be between 1 and n");
return;
}
// Create worker
CreateSharesWorker* worker = new CreateSharesWorker(
node::Buffer::Data(data), n, k, callback);
AsyncQueueWorker(worker);
}
NAN_METHOD(CombineShares) {
Nan::HandleScope scope;
v8::Local<v8::Value> shares_val = info[0];
v8::Local<v8::Value> callback_val = info[1];
// Type check the argument `shares` and `callback`
TYPECHK(!shares_val->IsUndefined(), "`shares` is not defined");
TYPECHK(!callback_val->IsUndefined(), "`callback` is not defined");
TYPECHK(shares_val->IsObject(), "`shares` is not an initialized Object")
v8::Local<v8::Object> shares_obj = shares_val->ToObject();
TYPECHK(shares_val->IsArray(), "`shares` must be an array of buffers");
v8::Local<v8::Array> shares_arr = shares_obj.As<v8::Array>();
TYPECHK(callback_val->IsFunction(), "`callback` must be a function");
Nan::Callback *callback = new Nan::Callback(callback_val.As<v8::Function>());
// Extract all the share buffers
auto k = shares_arr->Length();
std::unique_ptr<v8::Local<v8::Object>[]> shares(new v8::Local<v8::Object>[k]);
for (auto idx = 0; idx < k; ++idx) {
shares[idx] = shares_arr->Get(idx)->ToObject();
}
// Check if all the elements in the array are buffers
for (auto idx = 0; idx < k; ++idx) {
if (!node::Buffer::HasInstance(shares[idx])) {
Nan::ThrowTypeError("array element is not a buffer");
return;
}
}
// Check if all the elements in the array are of the correct length
for (auto idx = 0; idx < k; ++idx) {
if (node::Buffer::Length(shares[idx]) != sss_SHARE_LEN) {
Nan::ThrowTypeError("array buffer element is not of the correct length");
return;
}
}
// Create worker
CombineSharesWorker* worker = new CombineSharesWorker(shares, k, callback);
AsyncQueueWorker(worker);
}
NAN_METHOD(CreateKeyshares) {
Nan::HandleScope scope;
v8::Local<v8::Value> key_val = info[0];
v8::Local<v8::Value> n_val = info[1];
v8::Local<v8::Value> k_val = info[2];
v8::Local<v8::Value> callback_val = info[3];
// Type check the arguments
TYPECHK(!key_val->IsUndefined(), "`key` is not defined");
TYPECHK(!n_val->IsUndefined(), "`n` is not defined");
TYPECHK(!k_val->IsUndefined(), "`k` is not defined");
TYPECHK(!callback_val->IsUndefined(), "`callback` is not defined");
TYPECHK(key_val->IsObject(), "`key` is not an Object");
v8::Local<v8::Object> key = key_val->ToObject();
TYPECHK(node::Buffer::HasInstance(key), "`key` must be a Buffer")
TYPECHK(n_val->IsUint32(), "`n` is not a valid integer");
uint32_t n = n_val->Uint32Value();
TYPECHK(k_val->IsUint32(), "`k` is not a valid integer");
uint32_t k = k_val->Uint32Value();
TYPECHK(callback_val->IsFunction(), "`callback` must be a function");
Nan::Callback *callback = new Nan::Callback(callback_val.As<v8::Function>());
// Check if the buffers have the correct lengths
if (node::Buffer::Length(key) != 32) {
Nan::ThrowRangeError("`key` buffer size must be exactly 32 bytes");
return;
};
// Check if n and k are correct
if (n < 1 || n > 255) {
Nan::ThrowRangeError("`n` must be between 1 and 255");
return;
}
if (k < 1 || k > n) {
Nan::ThrowRangeError("`k` must be between 1 and n");
return;
}
// Create worker
CreateKeysharesWorker* worker = new CreateKeysharesWorker(
node::Buffer::Data(key), n, k, callback);
AsyncQueueWorker(worker);
}
NAN_METHOD(CombineKeyshares) {
Nan::HandleScope scope;
v8::Local<v8::Value> keyshares_val = info[0];
v8::Local<v8::Value> callback_val = info[1];
// Type check the argument `keyshares` and `callback`
TYPECHK(!keyshares_val->IsUndefined(), "`keyshares` is not defined");
TYPECHK(!callback_val->IsUndefined(), "`callback` is not defined");
TYPECHK(keyshares_val->IsObject(), "`keyshares` is not an initialized Object")
v8::Local<v8::Object> keyshares_obj = keyshares_val->ToObject();
TYPECHK(keyshares_val->IsArray(), "`keyshares` must be an array of buffers");
v8::Local<v8::Array> keyshares_arr = keyshares_obj.As<v8::Array>();
TYPECHK(callback_val->IsFunction(), "`callback` must be a function");
Nan::Callback *callback = new Nan::Callback(callback_val.As<v8::Function>());
// Extract all the share buffers
auto k = keyshares_arr->Length();
std::unique_ptr<v8::Local<v8::Object>[]> keyshares(new v8::Local<v8::Object>[k]);
for (auto idx = 0; idx < k; ++idx) {
keyshares[idx] = keyshares_arr->Get(idx)->ToObject();
}
// Check if all the elements in the array are buffers
for (auto idx = 0; idx < k; ++idx) {
if (!node::Buffer::HasInstance(keyshares[idx])) {
Nan::ThrowTypeError("array element is not a buffer");
return;
}
}
// Check if all the elements in the array are of the correct length
for (auto idx = 0; idx < k; ++idx) {
if (node::Buffer::Length(keyshares[idx]) != sss_KEYSHARE_LEN) {
Nan::ThrowTypeError("array buffer element is not of the correct length");
return;
}
}
// Create worker
CombineKeysharesWorker* worker = new CombineKeysharesWorker(keyshares, k, callback);
AsyncQueueWorker(worker);
}
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
Nan::HandleScope scope;
Nan::SetMethod(exports, "createShares", CreateShares);
Nan::SetMethod(exports, "combineShares", CombineShares);
Nan::SetMethod(exports, "createKeyshares", CreateKeyshares);
Nan::SetMethod(exports, "combineKeyshares", CombineKeyshares);
}
NODE_MODULE(shamirsecretsharing, Initialize)
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// 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 Michael Hackstein
////////////////////////////////////////////////////////////////////////////////
#include "RestEdgesHandler.h"
#include "Basics/ScopeGuard.h"
#include "Cluster/ClusterMethods.h"
#include "VocBase/Traverser.h"
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::rest;
RestEdgesHandler::RestEdgesHandler(HttpRequest* request)
: RestVocbaseBaseHandler(request) {}
HttpHandler::status_t RestEdgesHandler::execute() {
// extract the sub-request type
HttpRequest::HttpRequestType type = _request->requestType();
// execute one of the CRUD methods
switch (type) {
case HttpRequest::HTTP_REQUEST_GET: {
std::vector<traverser::TraverserExpression*> empty;
readEdges(empty);
break;
}
case HttpRequest::HTTP_REQUEST_PUT:
readFilteredEdges();
break;
case HttpRequest::HTTP_REQUEST_POST:
readEdgesForMultipleVertices();
break;
case HttpRequest::HTTP_REQUEST_HEAD:
case HttpRequest::HTTP_REQUEST_DELETE:
case HttpRequest::HTTP_REQUEST_ILLEGAL:
default: {
generateNotImplemented("ILLEGAL " + EDGES_PATH);
break;
}
}
// this handler is done
return status_t(HANDLER_DONE);
}
bool RestEdgesHandler::getEdgesForVertex(
std::string const& id,
std::vector<traverser::TraverserExpression*> const& expressions,
TRI_edge_direction_e direction, SingleCollectionReadOnlyTransaction& trx,
arangodb::basics::Json& result, size_t& scannedIndex, size_t& filtered) {
arangodb::traverser::VertexId start;
try {
start = arangodb::traverser::IdStringToVertexId(trx.resolver(), id);
} catch (arangodb::basics::Exception& e) {
handleError(e);
return false;
}
TRI_document_collection_t* docCol =
trx.trxCollection()->_collection->_collection;
std::vector<TRI_doc_mptr_copy_t>&& edges = TRI_LookupEdgesDocumentCollection(
&trx, docCol, direction, start.cid, const_cast<char*>(start.key));
// generate result
result.reserve(edges.size());
scannedIndex += edges.size();
if (expressions.empty()) {
for (auto& e : edges) {
DocumentAccessor da(trx.resolver(), docCol, &e);
result.add(da.toJson());
}
} else {
for (auto& e : edges) {
bool add = true;
// Expressions symbolize an and, so all have to be matched
for (auto& exp : expressions) {
if (exp->isEdgeAccess &&
!exp->matchesCheck(e, docCol, trx.resolver())) {
++filtered;
add = false;
break;
}
}
if (add) {
DocumentAccessor da(trx.resolver(), docCol, &e);
result.add(da.toJson());
}
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief was docuBlock API_EDGE_READINOUTBOUND
////////////////////////////////////////////////////////////////////////////////
bool RestEdgesHandler::readEdges(
std::vector<traverser::TraverserExpression*> const& expressions) {
std::vector<std::string> const& suffix = _request->suffix();
if (suffix.size() != 1) {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"expected GET " + EDGES_PATH +
"/<collection-identifier>?vertex=<vertex-handle>&"
"direction=<direction>");
return false;
}
std::string collectionName = suffix[0];
CollectionNameResolver resolver(_vocbase);
TRI_col_type_t colType = resolver.getCollectionTypeCluster(collectionName);
if (colType == TRI_COL_TYPE_UNKNOWN) {
generateError(HttpResponse::NOT_FOUND,
TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
return false;
} else if (colType != TRI_COL_TYPE_EDGE) {
generateError(HttpResponse::BAD, TRI_ERROR_ARANGO_COLLECTION_TYPE_INVALID);
return false;
}
bool found;
char const* dir = _request->value("direction", found);
if (!found || *dir == '\0') {
dir = "any";
}
std::string dirString(dir);
TRI_edge_direction_e direction;
if (dirString == "any") {
direction = TRI_EDGE_ANY;
} else if (dirString == "out" || dirString == "outbound") {
direction = TRI_EDGE_OUT;
} else if (dirString == "in" || dirString == "inbound") {
direction = TRI_EDGE_IN;
} else {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"<direction> must by any, in, or out, not: " + dirString);
return false;
}
char const* startVertex = _request->value("vertex", found);
if (!found || *startVertex == '\0') {
generateError(HttpResponse::BAD, TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD,
"illegal document handle");
return false;
}
if (ServerState::instance()->isCoordinator()) {
std::string vertexString(startVertex);
arangodb::rest::HttpResponse::HttpResponseCode responseCode;
std::string contentType;
arangodb::basics::Json resultDocument(arangodb::basics::Json::Object, 3);
int res = getFilteredEdgesOnCoordinator(
_vocbase->_name, collectionName, vertexString, direction, expressions,
responseCode, contentType, resultDocument);
if (res != TRI_ERROR_NO_ERROR) {
generateError(responseCode, res);
return false;
}
resultDocument.set("error", arangodb::basics::Json(false));
resultDocument.set("code", arangodb::basics::Json(200));
generateResult(resultDocument.json());
return true;
}
// find and load collection given by name or identifier
SingleCollectionReadOnlyTransaction trx(new StandaloneTransactionContext(),
_vocbase, collectionName);
// .............................................................................
// inside read transaction
// .............................................................................
int res = trx.begin();
if (res != TRI_ERROR_NO_ERROR) {
generateTransactionError(collectionName, res);
return false;
}
// If we are a DBserver, we want to use the cluster-wide collection
// name for error reporting:
if (ServerState::instance()->isDBServer()) {
collectionName = trx.resolver()->getCollectionName(trx.cid());
}
size_t filtered = 0;
size_t scannedIndex = 0;
arangodb::basics::Json documents(arangodb::basics::Json::Array);
bool ok = getEdgesForVertex(startVertex, expressions, direction, trx,
documents, scannedIndex, filtered);
res = trx.finish(res);
if (!ok) {
// Error has been built internally
return false;
}
if (res != TRI_ERROR_NO_ERROR) {
generateTransactionError(collectionName, res);
return false;
}
arangodb::basics::Json result(arangodb::basics::Json::Object, 4);
result("edges", documents);
result("error", arangodb::basics::Json(false));
result("code", arangodb::basics::Json(200));
arangodb::basics::Json stats(arangodb::basics::Json::Object, 2);
stats("scannedIndex",
arangodb::basics::Json(static_cast<int32_t>(scannedIndex)));
stats("filtered", arangodb::basics::Json(static_cast<int32_t>(filtered)));
result("stats", stats);
// and generate a response
generateResult(result.json());
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Internal function to receive all edges for a list of vertices
/// Not publicly documented on purpose.
/// NOTE: It ONLY except _id strings. Nothing else
////////////////////////////////////////////////////////////////////////////////
bool RestEdgesHandler::readEdgesForMultipleVertices() {
std::vector<std::string> const& suffix = _request->suffix();
if (suffix.size() != 1) {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"expected POST " + EDGES_PATH +
"/<collection-identifier>?direction=<direction>");
return false;
}
bool parseSuccess = true;
VPackOptions options;
std::shared_ptr<VPackBuilder> parsedBody =
parseVelocyPackBody(&options, parseSuccess);
if (!parseSuccess) {
// A body is required
return false;
}
VPackSlice body = parsedBody->slice();
if (!body.isArray()) {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"Expected an array of vertex _id's in body parameter");
return false;
}
std::string collectionName = suffix[0];
CollectionNameResolver resolver(_vocbase);
TRI_col_type_t colType = resolver.getCollectionTypeCluster(collectionName);
if (colType == TRI_COL_TYPE_UNKNOWN) {
generateError(HttpResponse::NOT_FOUND,
TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
return false;
} else if (colType != TRI_COL_TYPE_EDGE) {
generateError(HttpResponse::BAD, TRI_ERROR_ARANGO_COLLECTION_TYPE_INVALID);
return false;
}
bool found;
char const* dir = _request->value("direction", found);
if (!found || *dir == '\0') {
dir = "any";
}
std::string dirString(dir);
TRI_edge_direction_e direction;
if (dirString == "any") {
direction = TRI_EDGE_ANY;
} else if (dirString == "out" || dirString == "outbound") {
direction = TRI_EDGE_OUT;
} else if (dirString == "in" || dirString == "inbound") {
direction = TRI_EDGE_IN;
} else {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"<direction> must by any, in, or out, not: " + dirString);
return false;
}
if (ServerState::instance()->isCoordinator()) {
// This API is only for internal use on DB servers and is not (yet) allowed
// to
// be executed on the coordinator
return false;
}
// find and load collection given by name or identifier
SingleCollectionReadOnlyTransaction trx(new StandaloneTransactionContext(),
_vocbase, collectionName);
// .............................................................................
// inside read transaction
// .............................................................................
int res = trx.begin();
if (res != TRI_ERROR_NO_ERROR) {
generateTransactionError(collectionName, res);
return false;
}
// If we are a DBserver, we want to use the cluster-wide collection
// name for error reporting:
if (ServerState::instance()->isDBServer()) {
collectionName = trx.resolver()->getCollectionName(trx.cid());
}
size_t filtered = 0;
size_t scannedIndex = 0;
std::vector<traverser::TraverserExpression*> const expressions;
arangodb::basics::Json documents(arangodb::basics::Json::Array);
for (auto const& vertexSlice : VPackArrayIterator(body)) {
if (vertexSlice.isString()) {
std::string vertex = vertexSlice.copyString();
bool ok = getEdgesForVertex(vertex, expressions, direction, trx,
documents, scannedIndex, filtered);
if (!ok) {
// Ignore the error
}
}
}
res = trx.finish(res);
if (res != TRI_ERROR_NO_ERROR) {
generateTransactionError(collectionName, res);
return false;
}
arangodb::basics::Json result(arangodb::basics::Json::Object, 4);
result("edges", documents);
result("error", arangodb::basics::Json(false));
result("code", arangodb::basics::Json(200));
arangodb::basics::Json stats(arangodb::basics::Json::Object, 2);
stats("scannedIndex",
arangodb::basics::Json(static_cast<int32_t>(scannedIndex)));
stats("filtered", arangodb::basics::Json(static_cast<int32_t>(filtered)));
result("stats", stats);
// and generate a response
generateResult(result.json());
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Internal function for optimized edge retrieval.
/// Allows to send an TraverserExpression for filtering in the body
/// Not publicly documented on purpose.
////////////////////////////////////////////////////////////////////////////////
bool RestEdgesHandler::readFilteredEdges() {
std::vector<traverser::TraverserExpression*> expressions;
bool parseSuccess = true;
VPackOptions options;
std::shared_ptr<VPackBuilder> parsedBody =
parseVelocyPackBody(&options, parseSuccess);
if (!parseSuccess) {
// We continue unfiltered
// Filter could be done by caller
delete _response;
_response = nullptr;
return readEdges(expressions);
}
VPackSlice body = parsedBody->slice();
arangodb::basics::ScopeGuard guard{[]() -> void {},
[&expressions]() -> void {
for (auto& e : expressions) {
delete e;
}
}};
if (!body.isArray()) {
generateError(
HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"Expected an array of traverser expressions as body parameter");
return false;
}
expressions.reserve(body.length());
for (auto const& exp : VPackArrayIterator(body)) {
if (exp.isObject()) {
auto expression = std::make_unique<traverser::TraverserExpression>(exp);
expressions.emplace_back(expression.get());
expression.release();
}
}
return readEdges(expressions);
}
<commit_msg>order barriers while accessing edges<commit_after>////////////////////////////////////////////////////////////////////////////////
/// 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 Michael Hackstein
////////////////////////////////////////////////////////////////////////////////
#include "RestEdgesHandler.h"
#include "Basics/ScopeGuard.h"
#include "Cluster/ClusterMethods.h"
#include "VocBase/Traverser.h"
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::rest;
RestEdgesHandler::RestEdgesHandler(HttpRequest* request)
: RestVocbaseBaseHandler(request) {}
HttpHandler::status_t RestEdgesHandler::execute() {
// extract the sub-request type
HttpRequest::HttpRequestType type = _request->requestType();
// execute one of the CRUD methods
try {
switch (type) {
case HttpRequest::HTTP_REQUEST_GET: {
std::vector<traverser::TraverserExpression*> empty;
readEdges(empty);
break;
}
case HttpRequest::HTTP_REQUEST_PUT:
readFilteredEdges();
break;
case HttpRequest::HTTP_REQUEST_POST:
readEdgesForMultipleVertices();
break;
case HttpRequest::HTTP_REQUEST_HEAD:
case HttpRequest::HTTP_REQUEST_DELETE:
case HttpRequest::HTTP_REQUEST_ILLEGAL:
default: {
generateNotImplemented("ILLEGAL " + EDGES_PATH);
break;
}
}
} catch (arangodb::basics::Exception const& ex) {
generateError(HttpResponse::responseCode(ex.code()), ex.code(), ex.what());
}
catch (std::exception const& ex) {
generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL, ex.what());
}
catch (...) {
generateError(HttpResponse::SERVER_ERROR, TRI_ERROR_INTERNAL);
}
// this handler is done
return status_t(HANDLER_DONE);
}
bool RestEdgesHandler::getEdgesForVertex(
std::string const& id,
std::vector<traverser::TraverserExpression*> const& expressions,
TRI_edge_direction_e direction, SingleCollectionReadOnlyTransaction& trx,
arangodb::basics::Json& result, size_t& scannedIndex, size_t& filtered) {
arangodb::traverser::VertexId start;
try {
start = arangodb::traverser::IdStringToVertexId(trx.resolver(), id);
} catch (arangodb::basics::Exception& e) {
handleError(e);
return false;
}
TRI_document_collection_t* docCol =
trx.trxCollection()->_collection->_collection;
if (trx.orderDitch(trx.trxCollection()) == nullptr) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_OUT_OF_MEMORY);
}
std::vector<TRI_doc_mptr_copy_t>&& edges = TRI_LookupEdgesDocumentCollection(
&trx, docCol, direction, start.cid, const_cast<char*>(start.key));
// generate result
result.reserve(edges.size());
scannedIndex += edges.size();
if (expressions.empty()) {
for (auto& e : edges) {
DocumentAccessor da(trx.resolver(), docCol, &e);
result.add(da.toJson());
}
} else {
for (auto& e : edges) {
bool add = true;
// Expressions symbolize an and, so all have to be matched
for (auto& exp : expressions) {
if (exp->isEdgeAccess &&
!exp->matchesCheck(e, docCol, trx.resolver())) {
++filtered;
add = false;
break;
}
}
if (add) {
DocumentAccessor da(trx.resolver(), docCol, &e);
result.add(da.toJson());
}
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief was docuBlock API_EDGE_READINOUTBOUND
////////////////////////////////////////////////////////////////////////////////
bool RestEdgesHandler::readEdges(
std::vector<traverser::TraverserExpression*> const& expressions) {
std::vector<std::string> const& suffix = _request->suffix();
if (suffix.size() != 1) {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"expected GET " + EDGES_PATH +
"/<collection-identifier>?vertex=<vertex-handle>&"
"direction=<direction>");
return false;
}
std::string collectionName = suffix[0];
CollectionNameResolver resolver(_vocbase);
TRI_col_type_t colType = resolver.getCollectionTypeCluster(collectionName);
if (colType == TRI_COL_TYPE_UNKNOWN) {
generateError(HttpResponse::NOT_FOUND,
TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
return false;
} else if (colType != TRI_COL_TYPE_EDGE) {
generateError(HttpResponse::BAD, TRI_ERROR_ARANGO_COLLECTION_TYPE_INVALID);
return false;
}
bool found;
char const* dir = _request->value("direction", found);
if (!found || *dir == '\0') {
dir = "any";
}
std::string dirString(dir);
TRI_edge_direction_e direction;
if (dirString == "any") {
direction = TRI_EDGE_ANY;
} else if (dirString == "out" || dirString == "outbound") {
direction = TRI_EDGE_OUT;
} else if (dirString == "in" || dirString == "inbound") {
direction = TRI_EDGE_IN;
} else {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"<direction> must by any, in, or out, not: " + dirString);
return false;
}
char const* startVertex = _request->value("vertex", found);
if (!found || *startVertex == '\0') {
generateError(HttpResponse::BAD, TRI_ERROR_ARANGO_DOCUMENT_HANDLE_BAD,
"illegal document handle");
return false;
}
if (ServerState::instance()->isCoordinator()) {
std::string vertexString(startVertex);
arangodb::rest::HttpResponse::HttpResponseCode responseCode;
std::string contentType;
arangodb::basics::Json resultDocument(arangodb::basics::Json::Object, 3);
int res = getFilteredEdgesOnCoordinator(
_vocbase->_name, collectionName, vertexString, direction, expressions,
responseCode, contentType, resultDocument);
if (res != TRI_ERROR_NO_ERROR) {
generateError(responseCode, res);
return false;
}
resultDocument.set("error", arangodb::basics::Json(false));
resultDocument.set("code", arangodb::basics::Json(200));
generateResult(resultDocument.json());
return true;
}
// find and load collection given by name or identifier
SingleCollectionReadOnlyTransaction trx(new StandaloneTransactionContext(),
_vocbase, collectionName);
// .............................................................................
// inside read transaction
// .............................................................................
int res = trx.begin();
if (res != TRI_ERROR_NO_ERROR) {
generateTransactionError(collectionName, res);
return false;
}
// If we are a DBserver, we want to use the cluster-wide collection
// name for error reporting:
if (ServerState::instance()->isDBServer()) {
collectionName = trx.resolver()->getCollectionName(trx.cid());
}
size_t filtered = 0;
size_t scannedIndex = 0;
arangodb::basics::Json documents(arangodb::basics::Json::Array);
bool ok = getEdgesForVertex(startVertex, expressions, direction, trx,
documents, scannedIndex, filtered);
res = trx.finish(res);
if (!ok) {
// Error has been built internally
return false;
}
if (res != TRI_ERROR_NO_ERROR) {
generateTransactionError(collectionName, res);
return false;
}
arangodb::basics::Json result(arangodb::basics::Json::Object, 4);
result("edges", documents);
result("error", arangodb::basics::Json(false));
result("code", arangodb::basics::Json(200));
arangodb::basics::Json stats(arangodb::basics::Json::Object, 2);
stats("scannedIndex",
arangodb::basics::Json(static_cast<int32_t>(scannedIndex)));
stats("filtered", arangodb::basics::Json(static_cast<int32_t>(filtered)));
result("stats", stats);
// and generate a response
generateResult(result.json());
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Internal function to receive all edges for a list of vertices
/// Not publicly documented on purpose.
/// NOTE: It ONLY except _id strings. Nothing else
////////////////////////////////////////////////////////////////////////////////
bool RestEdgesHandler::readEdgesForMultipleVertices() {
std::vector<std::string> const& suffix = _request->suffix();
if (suffix.size() != 1) {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"expected POST " + EDGES_PATH +
"/<collection-identifier>?direction=<direction>");
return false;
}
bool parseSuccess = true;
VPackOptions options;
std::shared_ptr<VPackBuilder> parsedBody =
parseVelocyPackBody(&options, parseSuccess);
if (!parseSuccess) {
// A body is required
return false;
}
VPackSlice body = parsedBody->slice();
if (!body.isArray()) {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"Expected an array of vertex _id's in body parameter");
return false;
}
std::string collectionName = suffix[0];
CollectionNameResolver resolver(_vocbase);
TRI_col_type_t colType = resolver.getCollectionTypeCluster(collectionName);
if (colType == TRI_COL_TYPE_UNKNOWN) {
generateError(HttpResponse::NOT_FOUND,
TRI_ERROR_ARANGO_COLLECTION_NOT_FOUND);
return false;
} else if (colType != TRI_COL_TYPE_EDGE) {
generateError(HttpResponse::BAD, TRI_ERROR_ARANGO_COLLECTION_TYPE_INVALID);
return false;
}
bool found;
char const* dir = _request->value("direction", found);
if (!found || *dir == '\0') {
dir = "any";
}
std::string dirString(dir);
TRI_edge_direction_e direction;
if (dirString == "any") {
direction = TRI_EDGE_ANY;
} else if (dirString == "out" || dirString == "outbound") {
direction = TRI_EDGE_OUT;
} else if (dirString == "in" || dirString == "inbound") {
direction = TRI_EDGE_IN;
} else {
generateError(HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"<direction> must by any, in, or out, not: " + dirString);
return false;
}
if (ServerState::instance()->isCoordinator()) {
// This API is only for internal use on DB servers and is not (yet) allowed
// to
// be executed on the coordinator
return false;
}
// find and load collection given by name or identifier
SingleCollectionReadOnlyTransaction trx(new StandaloneTransactionContext(),
_vocbase, collectionName);
// .............................................................................
// inside read transaction
// .............................................................................
int res = trx.begin();
if (res != TRI_ERROR_NO_ERROR) {
generateTransactionError(collectionName, res);
return false;
}
// If we are a DBserver, we want to use the cluster-wide collection
// name for error reporting:
if (ServerState::instance()->isDBServer()) {
collectionName = trx.resolver()->getCollectionName(trx.cid());
}
size_t filtered = 0;
size_t scannedIndex = 0;
std::vector<traverser::TraverserExpression*> const expressions;
arangodb::basics::Json documents(arangodb::basics::Json::Array);
for (auto const& vertexSlice : VPackArrayIterator(body)) {
if (vertexSlice.isString()) {
std::string vertex = vertexSlice.copyString();
bool ok = getEdgesForVertex(vertex, expressions, direction, trx,
documents, scannedIndex, filtered);
if (!ok) {
// Ignore the error
}
}
}
res = trx.finish(res);
if (res != TRI_ERROR_NO_ERROR) {
generateTransactionError(collectionName, res);
return false;
}
arangodb::basics::Json result(arangodb::basics::Json::Object, 4);
result("edges", documents);
result("error", arangodb::basics::Json(false));
result("code", arangodb::basics::Json(200));
arangodb::basics::Json stats(arangodb::basics::Json::Object, 2);
stats("scannedIndex",
arangodb::basics::Json(static_cast<int32_t>(scannedIndex)));
stats("filtered", arangodb::basics::Json(static_cast<int32_t>(filtered)));
result("stats", stats);
// and generate a response
generateResult(result.json());
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// Internal function for optimized edge retrieval.
/// Allows to send an TraverserExpression for filtering in the body
/// Not publicly documented on purpose.
////////////////////////////////////////////////////////////////////////////////
bool RestEdgesHandler::readFilteredEdges() {
std::vector<traverser::TraverserExpression*> expressions;
bool parseSuccess = true;
VPackOptions options;
std::shared_ptr<VPackBuilder> parsedBody =
parseVelocyPackBody(&options, parseSuccess);
if (!parseSuccess) {
// We continue unfiltered
// Filter could be done by caller
delete _response;
_response = nullptr;
return readEdges(expressions);
}
VPackSlice body = parsedBody->slice();
arangodb::basics::ScopeGuard guard{[]() -> void {},
[&expressions]() -> void {
for (auto& e : expressions) {
delete e;
}
}};
if (!body.isArray()) {
generateError(
HttpResponse::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
"Expected an array of traverser expressions as body parameter");
return false;
}
expressions.reserve(body.length());
for (auto const& exp : VPackArrayIterator(body)) {
if (exp.isObject()) {
auto expression = std::make_unique<traverser::TraverserExpression>(exp);
expressions.emplace_back(expression.get());
expression.release();
}
}
return readEdges(expressions);
}
<|endoftext|> |
<commit_before>
/*
* Copyright (C) 2010, Victor Semionov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include <climits>
#include <string>
#include <vector>
#include <set>
#include <ostream>
#include <iostream>
#include "Poco/Util/ServerApplication.h"
#include "Poco/URI.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/NumberFormatter.h"
#include "IndigoRequestHandler.h"
#include "IndigoConfiguration.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace Poco::Net;
POCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)
POCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, "ShareNotFoundException")
IndigoRequestHandler::IndigoRequestHandler()
{
}
void IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)
{
logRequest(request);
const string &method = request.getMethod();
if (method != HTTPRequest::HTTP_GET)
{
sendMethodNotAllowed(response);
return;
}
const string &uri = request.getURI();
Path uriPath(URI(uri).getPath(), Path::PATH_UNIX);
if (!uriPath.isAbsolute())
{
sendBadRequest(response);
return;
}
const IndigoConfiguration &configuration = IndigoConfiguration::get();
if (uriPath.isDirectory() && uriPath.depth() == 0)
{
if (configuration.getRoot().empty())
{
sendVirtualRootDirectory(response);
return;
}
}
try
{
const Path &fsPath = resolveFSPath(uriPath);
const string &target = fsPath.toString();
File f(target);
if (f.isDirectory())
{
if (uriPath.isDirectory())
{
sendDirectory(response, target, uriPath.toString(Path::PATH_UNIX));
}
else
{
Path uriDirPath = uriPath;
uriDirPath.makeDirectory();
redirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);
}
}
else
{
const string &ext = fsPath.getExtension();
const string &mediaType = configuration.getMimeType(ext);
response.sendFile(target, mediaType);
}
}
catch (ShareNotFoundException &snfe)
{
sendNotFound(response);
}
catch (FileNotFoundException &fnfe)
{
sendNotFound(response);
}
catch (FileAccessDeniedException &fade)
{
sendForbidden(response);
}
catch (FileException &fe)
{
sendInternalServerError(response);
}
catch (PathSyntaxException &pse)
{
sendNotImplemented(response);
}
catch (...)
{
sendInternalServerError(response);
}
}
Path IndigoRequestHandler::resolveFSPath(const Path &uriPath)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &shareName = uriPath[0];
string base = configuration.getSharePath(shareName);
bool share = true;
if (base.empty())
{
base = configuration.getRoot();
if (base.empty())
throw ShareNotFoundException();
share = false;
}
Path fsPath(base);
if (share)
{
fsPath.makeDirectory();
const int d = uriPath.depth();
for (int i = 1; i <= d; i++)
fsPath.pushDirectory(uriPath[i]);
}
else
{
fsPath.append(uriPath);
}
fsPath.makeFile();
return fsPath;
}
void IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)
{
bool root = (dirURI == "/");
ostream &out = response.send();
out << "<html>" << endl;
out << "<head>" << endl;
out << "<title>";
out << "Index of " << dirURI;
out << "</title>" << endl;
out << "</head>" << endl;
out << "<body>" << endl;
out << "<h1>";
out << "Index of " << dirURI;
out << "</h1>" << endl;
if (!root)
{
out << "<a href=\"../\"><Parent Directory></a><br>" << endl;
}
const int l = entries.size();
for (int i = 0; i < l; i++)
{
out << "<a href=\"" << entries[i] << "\">" << entries[i] << "</a>" << "<br>" << endl;
}
out << "</body>" << endl;
out << "</html>" << endl;
}
void IndigoRequestHandler::sendVirtualRootDirectory(HTTPServerResponse &response)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const set<string> &shares = configuration.getShares();
vector<string> entries;
set<string>::const_iterator it;
const set<string>::const_iterator &end = shares.end();
for (it = shares.begin(); it != end; ++it)
{
const string &shareName = *it;
try
{
const Path &fsPath = resolveFSPath(Path("/" + shareName, Path::PATH_UNIX));
File f(fsPath);
if (!f.isHidden())
{
string entry = shareName;
if (f.isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (ShareNotFoundException &snfe)
{
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
sendDirectoryListing(response, "/", entries);
}
void IndigoRequestHandler::sendDirectory(HTTPServerResponse &response, const string &path, const string &dirURI)
{
vector<string> entries;
DirectoryIterator it(path);
DirectoryIterator end;
while (it != end)
{
try
{
if (!it->isHidden())
{
string entry = it.name();
if (it->isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
++it;
}
sendDirectoryListing(response, dirURI, entries);
}
void IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)
{
if (!permanent)
{
response.redirect(dirURI);
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);
response.setContentLength(0);
response.setChunkedTransferEncoding(false);
response.set("Location", dirURI);
response.send();
}
}
void IndigoRequestHandler::logRequest(const HTTPServerRequest &request)
{
const ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());
if (app.isInteractive())
{
const string &method = request.getMethod();
const string &uri = request.getURI();
const string &host = request.clientAddress().host().toString();
string logString = host + " - " + method + " " + uri;
app.logger().information(logString);
}
}
void IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)
{
if (response.sent())
return;
response.setStatusAndReason(HTTPResponse::HTTPStatus(code));
response.setChunkedTransferEncoding(true);
response.setContentType("text/html");
const string &reason = response.getReason();
ostream &out = response.send();
out << "<html>";
out << "<head><title>" + NumberFormatter::format(code) + " " + reason + "</title></head>";
out << "<body><h1>" + reason + "</h1></body>";
out << "</html>";
}
void IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);
}
void IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);
}
void IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_BAD_REQUEST);
}
void IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);
}
void IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_FOUND);
}
void IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_FORBIDDEN);
}
void IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
<commit_msg>Check for syntax errors in the URI.<commit_after>
/*
* Copyright (C) 2010, Victor Semionov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
#include <climits>
#include <string>
#include <vector>
#include <set>
#include <ostream>
#include <iostream>
#include "Poco/Util/ServerApplication.h"
#include "Poco/URI.h"
#include "Poco/File.h"
#include "Poco/DirectoryIterator.h"
#include "Poco/NumberFormatter.h"
#include "IndigoRequestHandler.h"
#include "IndigoConfiguration.h"
using namespace std;
using namespace Poco;
using namespace Poco::Util;
using namespace Poco::Net;
POCO_DECLARE_EXCEPTION(, ShareNotFoundException, ApplicationException)
POCO_IMPLEMENT_EXCEPTION(ShareNotFoundException, ApplicationException, "ShareNotFoundException")
IndigoRequestHandler::IndigoRequestHandler()
{
}
void IndigoRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response)
{
logRequest(request);
const string &method = request.getMethod();
if (method != HTTPRequest::HTTP_GET)
{
sendMethodNotAllowed(response);
return;
}
URI uri;
try
{
uri = request.getURI();
}
catch (SyntaxException &se)
{
sendBadRequest(response);
return;
}
Path uriPath(uri.getPath(), Path::PATH_UNIX);
if (!uriPath.isAbsolute())
{
sendBadRequest(response);
return;
}
const IndigoConfiguration &configuration = IndigoConfiguration::get();
if (uriPath.isDirectory() && uriPath.depth() == 0)
{
if (configuration.getRoot().empty())
{
sendVirtualRootDirectory(response);
return;
}
}
try
{
const Path &fsPath = resolveFSPath(uriPath);
const string &target = fsPath.toString();
File f(target);
if (f.isDirectory())
{
if (uriPath.isDirectory())
{
sendDirectory(response, target, uriPath.toString(Path::PATH_UNIX));
}
else
{
Path uriDirPath = uriPath;
uriDirPath.makeDirectory();
redirectToDirectory(response, uriDirPath.toString(Path::PATH_UNIX), false);
}
}
else
{
const string &ext = fsPath.getExtension();
const string &mediaType = configuration.getMimeType(ext);
response.sendFile(target, mediaType);
}
}
catch (ShareNotFoundException &snfe)
{
sendNotFound(response);
}
catch (FileNotFoundException &fnfe)
{
sendNotFound(response);
}
catch (FileAccessDeniedException &fade)
{
sendForbidden(response);
}
catch (FileException &fe)
{
sendInternalServerError(response);
}
catch (PathSyntaxException &pse)
{
sendNotImplemented(response);
}
catch (...)
{
sendInternalServerError(response);
}
}
Path IndigoRequestHandler::resolveFSPath(const Path &uriPath)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const string &shareName = uriPath[0];
string base = configuration.getSharePath(shareName);
bool share = true;
if (base.empty())
{
base = configuration.getRoot();
if (base.empty())
throw ShareNotFoundException();
share = false;
}
Path fsPath(base);
if (share)
{
fsPath.makeDirectory();
const int d = uriPath.depth();
for (int i = 1; i <= d; i++)
fsPath.pushDirectory(uriPath[i]);
}
else
{
fsPath.append(uriPath);
}
fsPath.makeFile();
return fsPath;
}
void IndigoRequestHandler::sendDirectoryListing(HTTPServerResponse &response, const string &dirURI, const vector<string> &entries)
{
bool root = (dirURI == "/");
ostream &out = response.send();
out << "<html>" << endl;
out << "<head>" << endl;
out << "<title>";
out << "Index of " << dirURI;
out << "</title>" << endl;
out << "</head>" << endl;
out << "<body>" << endl;
out << "<h1>";
out << "Index of " << dirURI;
out << "</h1>" << endl;
if (!root)
{
out << "<a href=\"../\"><Parent Directory></a><br>" << endl;
}
const int l = entries.size();
for (int i = 0; i < l; i++)
{
out << "<a href=\"" << entries[i] << "\">" << entries[i] << "</a>" << "<br>" << endl;
}
out << "</body>" << endl;
out << "</html>" << endl;
}
void IndigoRequestHandler::sendVirtualRootDirectory(HTTPServerResponse &response)
{
const IndigoConfiguration &configuration = IndigoConfiguration::get();
const set<string> &shares = configuration.getShares();
vector<string> entries;
set<string>::const_iterator it;
const set<string>::const_iterator &end = shares.end();
for (it = shares.begin(); it != end; ++it)
{
const string &shareName = *it;
try
{
const Path &fsPath = resolveFSPath(Path("/" + shareName, Path::PATH_UNIX));
File f(fsPath);
if (!f.isHidden())
{
string entry = shareName;
if (f.isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (ShareNotFoundException &snfe)
{
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
}
sendDirectoryListing(response, "/", entries);
}
void IndigoRequestHandler::sendDirectory(HTTPServerResponse &response, const string &path, const string &dirURI)
{
vector<string> entries;
DirectoryIterator it(path);
DirectoryIterator end;
while (it != end)
{
try
{
if (!it->isHidden())
{
string entry = it.name();
if (it->isDirectory())
entry += '/';
entries.push_back(entry);
}
}
catch (FileException &fe)
{
}
catch (PathSyntaxException &pse)
{
}
++it;
}
sendDirectoryListing(response, dirURI, entries);
}
void IndigoRequestHandler::redirectToDirectory(HTTPServerResponse &response, const string &dirURI, bool permanent)
{
if (!permanent)
{
response.redirect(dirURI);
}
else
{
response.setStatusAndReason(HTTPResponse::HTTP_MOVED_PERMANENTLY);
response.setContentLength(0);
response.setChunkedTransferEncoding(false);
response.set("Location", dirURI);
response.send();
}
}
void IndigoRequestHandler::logRequest(const HTTPServerRequest &request)
{
const ServerApplication &app = dynamic_cast<ServerApplication &>(Application::instance());
if (app.isInteractive())
{
const string &method = request.getMethod();
const string &uri = request.getURI();
const string &host = request.clientAddress().host().toString();
string logString = host + " - " + method + " " + uri;
app.logger().information(logString);
}
}
void IndigoRequestHandler::sendError(HTTPServerResponse &response, int code)
{
if (response.sent())
return;
response.setStatusAndReason(HTTPResponse::HTTPStatus(code));
response.setChunkedTransferEncoding(true);
response.setContentType("text/html");
const string &reason = response.getReason();
ostream &out = response.send();
out << "<html>";
out << "<head><title>" + NumberFormatter::format(code) + " " + reason + "</title></head>";
out << "<body><h1>" + reason + "</h1></body>";
out << "</html>";
}
void IndigoRequestHandler::sendMethodNotAllowed(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_METHOD_NOT_ALLOWED);
}
void IndigoRequestHandler::sendRequestURITooLong(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_REQUESTURITOOLONG);
}
void IndigoRequestHandler::sendBadRequest(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_BAD_REQUEST);
}
void IndigoRequestHandler::sendNotImplemented(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_IMPLEMENTED);
}
void IndigoRequestHandler::sendNotFound(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_NOT_FOUND);
}
void IndigoRequestHandler::sendForbidden(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_FORBIDDEN);
}
void IndigoRequestHandler::sendInternalServerError(HTTPServerResponse &response)
{
sendError(response, HTTPResponse::HTTP_INTERNAL_SERVER_ERROR);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2006 - 2007 Volker Krause <[email protected]>
Copyright (c) 2008 Stephen Kelly <[email protected]>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "entitytreeview.h"
#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QDragMoveEvent>
#include <QtGui/QHeaderView>
#include <QtGui/QMenu>
#include <KAction>
#include <KLocale>
#include <KMessageBox>
#include <KUrl>
#include <KXMLGUIFactory>
#include <kxmlguiclient.h>
#include <akonadi/collection.h>
#include <akonadi/control.h>
#include <akonadi/item.h>
#include <akonadi/entitytreemodel.h>
#include <kdebug.h>
using namespace Akonadi;
/**
* @internal
*/
class EntityTreeView::Private
{
public:
Private( EntityTreeView *parent )
: mParent( parent ),
xmlGuiClient( 0 )
{
}
void init();
void dragExpand();
void itemClicked( const QModelIndex& );
void itemDoubleClicked( const QModelIndex& );
void itemCurrentChanged( const QModelIndex& );
bool hasParent( const QModelIndex& idx, Collection::Id parentId );
EntityTreeView *mParent;
QModelIndex dragOverIndex;
QTimer dragExpandTimer;
KXMLGUIClient *xmlGuiClient;
};
void EntityTreeView::Private::init()
{
mParent->header()->setClickable( true );
mParent->header()->setStretchLastSection( false );
// mParent->setRootIsDecorated( false );
// mParent->setAutoExpandDelay ( QApplication::startDragTime() );
mParent->setSortingEnabled( true );
mParent->sortByColumn( 0, Qt::AscendingOrder );
mParent->setEditTriggers( QAbstractItemView::EditKeyPressed );
mParent->setAcceptDrops( true );
mParent->setDropIndicatorShown( true );
mParent->setDragDropMode( DragDrop );
mParent->setDragEnabled( true );
dragExpandTimer.setSingleShot( true );
mParent->connect( &dragExpandTimer, SIGNAL( timeout() ), SLOT( dragExpand() ) );
mParent->connect( mParent, SIGNAL( clicked( const QModelIndex& ) ),
mParent, SLOT( itemClicked( const QModelIndex& ) ) );
mParent->connect( mParent, SIGNAL( doubleClicked( const QModelIndex& ) ),
mParent, SLOT( itemDoubleClicked( const QModelIndex& ) ) );
Control::widgetNeedsAkonadi( mParent );
}
bool EntityTreeView::Private::hasParent( const QModelIndex& idx, Collection::Id parentId )
{
QModelIndex idx2 = idx;
while ( idx2.isValid() ) {
if ( mParent->model()->data( idx2, EntityTreeModel::CollectionIdRole ).toLongLong() == parentId )
return true;
idx2 = idx2.parent();
}
return false;
}
void EntityTreeView::Private::dragExpand()
{
mParent->setExpanded( dragOverIndex, true );
dragOverIndex = QModelIndex();
}
void EntityTreeView::Private::itemClicked( const QModelIndex &index )
{
if ( !index.isValid() )
return;
const Collection collection = index.model()->data( index, EntityTreeModel::CollectionRole ).value<Collection>();
if ( collection.isValid() ) {
emit mParent->clicked( collection );
} else {
const Item item = index.model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if ( item.isValid() )
emit mParent->clicked( item );
}
}
void EntityTreeView::Private::itemDoubleClicked( const QModelIndex &index )
{
if ( !index.isValid() )
return;
const Collection collection = index.model()->data( index, EntityTreeModel::CollectionRole ).value<Collection>();
if ( collection.isValid() ) {
emit mParent->doubleClicked( collection );
} else {
const Item item = index.model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if ( item.isValid() )
emit mParent->doubleClicked( item );
}
}
void EntityTreeView::Private::itemCurrentChanged( const QModelIndex &index )
{
if ( !index.isValid() )
return;
const Collection collection = index.model()->data( index, EntityTreeModel::CollectionRole ).value<Collection>();
if ( collection.isValid() ) {
emit mParent->currentChanged( collection );
} else {
const Item item = index.model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if ( item.isValid() )
emit mParent->currentChanged( item );
}
}
EntityTreeView::EntityTreeView( QWidget * parent ) :
QTreeView( parent ),
d( new Private( this ) )
{
setSelectionMode( QAbstractItemView::SingleSelection );
d->init();
}
EntityTreeView::EntityTreeView( KXMLGUIClient *xmlGuiClient, QWidget * parent ) :
QTreeView( parent ),
d( new Private( this ) )
{
d->xmlGuiClient = xmlGuiClient;
d->init();
}
EntityTreeView::~EntityTreeView()
{
delete d;
}
void EntityTreeView::setModel( QAbstractItemModel * model )
{
QTreeView::setModel( model );
header()->setStretchLastSection( true );
connect( selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ),
this, SLOT( itemCurrentChanged( const QModelIndex& ) ) );
}
void EntityTreeView::dragMoveEvent( QDragMoveEvent * event )
{
QModelIndex index = indexAt( event->pos() );
if ( d->dragOverIndex != index ) {
d->dragExpandTimer.stop();
if ( index.isValid() && !isExpanded( index ) && itemsExpandable() ) {
d->dragExpandTimer.start( QApplication::startDragTime() );
d->dragOverIndex = index;
}
}
// Check if the collection under the cursor accepts this data type
Collection col = model()->data( index, EntityTreeModel::CollectionRole ).value<Collection>();
if (!col.isValid())
{
Item item = model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if (item.isValid())
{
col = model()->data( index.parent(), EntityTreeModel::CollectionRole ).value<Collection>();
}
}
if ( col.isValid() )
{
QStringList supportedContentTypes = col.contentMimeTypes();
const QMimeData *data = event->mimeData();
KUrl::List urls = KUrl::List::fromMimeData( data );
foreach( const KUrl &url, urls ) {
const Collection collection = Collection::fromUrl( url );
if ( collection.isValid() ) {
if ( !supportedContentTypes.contains( Collection::mimeType() ) )
break;
// Check if we don't try to drop on one of the children
if ( d->hasParent( index, collection.id() ) )
break;
} else { // This is an item.
QString type = url.queryItems()[ QString::fromLatin1( "type" )];
if ( !supportedContentTypes.contains( type ) )
break;
}
// All urls are supported. process the event.
QTreeView::dragMoveEvent( event );
return;
}
}
event->setDropAction( Qt::IgnoreAction );
return;
}
void EntityTreeView::dragLeaveEvent( QDragLeaveEvent * event )
{
d->dragExpandTimer.stop();
d->dragOverIndex = QModelIndex();
QTreeView::dragLeaveEvent( event );
}
void EntityTreeView::dropEvent( QDropEvent * event )
{
d->dragExpandTimer.stop();
d->dragOverIndex = QModelIndex();
QModelIndexList idxs = selectedIndexes();
QMenu popup( this );
QAction* moveDropAction;
// TODO If possible, hide unavailable actions ...
// Use the model to determine if a move is ok.
// if (...)
// {
moveDropAction = popup.addAction( KIcon( QString::fromLatin1( "edit-rename" ) ), i18n( "&Move here" ) );
// }
//TODO: If dropping on one of the selectedIndexes, just return.
// open a context menu offering different drop actions (move, copy and cancel)
QAction* copyDropAction = popup.addAction( KIcon( QString::fromLatin1( "edit-copy" ) ), i18n( "&Copy here" ) );
popup.addSeparator();
popup.addAction( KIcon( QString::fromLatin1( "process-stop" ) ), i18n( "Cancel" ) );
QAction *activatedAction = popup.exec( QCursor::pos() );
if ( activatedAction == moveDropAction ) {
event->setDropAction( Qt::MoveAction );
} else if ( activatedAction == copyDropAction ) {
event->setDropAction( Qt::CopyAction );
}
// TODO: Handle link action.
else return;
QTreeView::dropEvent( event );
}
void EntityTreeView::contextMenuEvent( QContextMenuEvent * event )
{
if ( !d->xmlGuiClient )
return;
const QModelIndex index = indexAt( event->pos() );
QMenu *popup = 0;
// check if the index under the cursor is a collection or item
const Item item = model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if ( item.isValid() )
popup = static_cast<QMenu*>( d->xmlGuiClient->factory()->container(
QLatin1String( "akonadi_itemview_contextmenu" ), d->xmlGuiClient ) );
else
popup = static_cast<QMenu*>( d->xmlGuiClient->factory()->container(
QLatin1String( "akonadi_collectionview_contextmenu" ), d->xmlGuiClient ) );
if ( popup )
popup->exec( event->globalPos() );
}
void EntityTreeView::setXmlGuiClient( KXMLGUIClient * xmlGuiClient )
{
d->xmlGuiClient = xmlGuiClient;
}
#include "entitytreeview.moc"
<commit_msg>Try to fetch more items on click.<commit_after>/*
Copyright (c) 2006 - 2007 Volker Krause <[email protected]>
Copyright (c) 2008 Stephen Kelly <[email protected]>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "entitytreeview.h"
#include <QtCore/QDebug>
#include <QtCore/QTimer>
#include <QtGui/QApplication>
#include <QtGui/QDragMoveEvent>
#include <QtGui/QHeaderView>
#include <QtGui/QMenu>
#include <KAction>
#include <KLocale>
#include <KMessageBox>
#include <KUrl>
#include <KXMLGUIFactory>
#include <kxmlguiclient.h>
#include <akonadi/collection.h>
#include <akonadi/control.h>
#include <akonadi/item.h>
#include <akonadi/entitytreemodel.h>
#include <kdebug.h>
using namespace Akonadi;
/**
* @internal
*/
class EntityTreeView::Private
{
public:
Private( EntityTreeView *parent )
: mParent( parent ),
xmlGuiClient( 0 )
{
}
void init();
void dragExpand();
void itemClicked( const QModelIndex& );
void itemDoubleClicked( const QModelIndex& );
void itemCurrentChanged( const QModelIndex& );
bool hasParent( const QModelIndex& idx, Collection::Id parentId );
EntityTreeView *mParent;
QModelIndex dragOverIndex;
QTimer dragExpandTimer;
KXMLGUIClient *xmlGuiClient;
};
void EntityTreeView::Private::init()
{
mParent->header()->setClickable( true );
mParent->header()->setStretchLastSection( false );
// mParent->setRootIsDecorated( false );
// mParent->setAutoExpandDelay ( QApplication::startDragTime() );
mParent->setSortingEnabled( true );
mParent->sortByColumn( 0, Qt::AscendingOrder );
mParent->setEditTriggers( QAbstractItemView::EditKeyPressed );
mParent->setAcceptDrops( true );
mParent->setDropIndicatorShown( true );
mParent->setDragDropMode( DragDrop );
mParent->setDragEnabled( true );
dragExpandTimer.setSingleShot( true );
mParent->connect( &dragExpandTimer, SIGNAL( timeout() ), SLOT( dragExpand() ) );
mParent->connect( mParent, SIGNAL( clicked( const QModelIndex& ) ),
mParent, SLOT( itemClicked( const QModelIndex& ) ) );
mParent->connect( mParent, SIGNAL( doubleClicked( const QModelIndex& ) ),
mParent, SLOT( itemDoubleClicked( const QModelIndex& ) ) );
Control::widgetNeedsAkonadi( mParent );
}
bool EntityTreeView::Private::hasParent( const QModelIndex& idx, Collection::Id parentId )
{
QModelIndex idx2 = idx;
while ( idx2.isValid() ) {
if ( mParent->model()->data( idx2, EntityTreeModel::CollectionIdRole ).toLongLong() == parentId )
return true;
idx2 = idx2.parent();
}
return false;
}
void EntityTreeView::Private::dragExpand()
{
mParent->setExpanded( dragOverIndex, true );
dragOverIndex = QModelIndex();
}
void EntityTreeView::Private::itemClicked( const QModelIndex &index )
{
if ( !index.isValid() )
return;
if (mParent->model()->canFetchMore(index))
mParent->model()->fetchMore(index);
const Collection collection = index.model()->data( index, EntityTreeModel::CollectionRole ).value<Collection>();
if ( collection.isValid() ) {
emit mParent->clicked( collection );
} else {
const Item item = index.model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if ( item.isValid() )
emit mParent->clicked( item );
}
}
void EntityTreeView::Private::itemDoubleClicked( const QModelIndex &index )
{
if ( !index.isValid() )
return;
const Collection collection = index.model()->data( index, EntityTreeModel::CollectionRole ).value<Collection>();
if ( collection.isValid() ) {
emit mParent->doubleClicked( collection );
} else {
const Item item = index.model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if ( item.isValid() )
emit mParent->doubleClicked( item );
}
}
void EntityTreeView::Private::itemCurrentChanged( const QModelIndex &index )
{
if ( !index.isValid() )
return;
const Collection collection = index.model()->data( index, EntityTreeModel::CollectionRole ).value<Collection>();
if ( collection.isValid() ) {
emit mParent->currentChanged( collection );
} else {
const Item item = index.model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if ( item.isValid() )
emit mParent->currentChanged( item );
}
}
EntityTreeView::EntityTreeView( QWidget * parent ) :
QTreeView( parent ),
d( new Private( this ) )
{
setSelectionMode( QAbstractItemView::SingleSelection );
d->init();
}
EntityTreeView::EntityTreeView( KXMLGUIClient *xmlGuiClient, QWidget * parent ) :
QTreeView( parent ),
d( new Private( this ) )
{
d->xmlGuiClient = xmlGuiClient;
d->init();
}
EntityTreeView::~EntityTreeView()
{
delete d;
}
void EntityTreeView::setModel( QAbstractItemModel * model )
{
QTreeView::setModel( model );
header()->setStretchLastSection( true );
connect( selectionModel(), SIGNAL( currentChanged( const QModelIndex&, const QModelIndex& ) ),
this, SLOT( itemCurrentChanged( const QModelIndex& ) ) );
}
void EntityTreeView::dragMoveEvent( QDragMoveEvent * event )
{
QModelIndex index = indexAt( event->pos() );
if ( d->dragOverIndex != index ) {
d->dragExpandTimer.stop();
if ( index.isValid() && !isExpanded( index ) && itemsExpandable() ) {
d->dragExpandTimer.start( QApplication::startDragTime() );
d->dragOverIndex = index;
}
}
// Check if the collection under the cursor accepts this data type
Collection col = model()->data( index, EntityTreeModel::CollectionRole ).value<Collection>();
if (!col.isValid())
{
Item item = model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if (item.isValid())
{
col = model()->data( index.parent(), EntityTreeModel::CollectionRole ).value<Collection>();
}
}
if ( col.isValid() )
{
QStringList supportedContentTypes = col.contentMimeTypes();
const QMimeData *data = event->mimeData();
KUrl::List urls = KUrl::List::fromMimeData( data );
foreach( const KUrl &url, urls ) {
const Collection collection = Collection::fromUrl( url );
if ( collection.isValid() ) {
if ( !supportedContentTypes.contains( Collection::mimeType() ) )
break;
// Check if we don't try to drop on one of the children
if ( d->hasParent( index, collection.id() ) )
break;
} else { // This is an item.
QString type = url.queryItems()[ QString::fromLatin1( "type" )];
if ( !supportedContentTypes.contains( type ) )
break;
}
// All urls are supported. process the event.
QTreeView::dragMoveEvent( event );
return;
}
}
event->setDropAction( Qt::IgnoreAction );
return;
}
void EntityTreeView::dragLeaveEvent( QDragLeaveEvent * event )
{
d->dragExpandTimer.stop();
d->dragOverIndex = QModelIndex();
QTreeView::dragLeaveEvent( event );
}
void EntityTreeView::dropEvent( QDropEvent * event )
{
d->dragExpandTimer.stop();
d->dragOverIndex = QModelIndex();
QModelIndexList idxs = selectedIndexes();
QMenu popup( this );
QAction* moveDropAction;
// TODO If possible, hide unavailable actions ...
// Use the model to determine if a move is ok.
// if (...)
// {
moveDropAction = popup.addAction( KIcon( QString::fromLatin1( "edit-rename" ) ), i18n( "&Move here" ) );
// }
//TODO: If dropping on one of the selectedIndexes, just return.
// open a context menu offering different drop actions (move, copy and cancel)
QAction* copyDropAction = popup.addAction( KIcon( QString::fromLatin1( "edit-copy" ) ), i18n( "&Copy here" ) );
popup.addSeparator();
popup.addAction( KIcon( QString::fromLatin1( "process-stop" ) ), i18n( "Cancel" ) );
QAction *activatedAction = popup.exec( QCursor::pos() );
if ( activatedAction == moveDropAction ) {
event->setDropAction( Qt::MoveAction );
} else if ( activatedAction == copyDropAction ) {
event->setDropAction( Qt::CopyAction );
}
// TODO: Handle link action.
else return;
QTreeView::dropEvent( event );
}
void EntityTreeView::contextMenuEvent( QContextMenuEvent * event )
{
if ( !d->xmlGuiClient )
return;
const QModelIndex index = indexAt( event->pos() );
QMenu *popup = 0;
// check if the index under the cursor is a collection or item
const Item item = model()->data( index, EntityTreeModel::ItemRole ).value<Item>();
if ( item.isValid() )
popup = static_cast<QMenu*>( d->xmlGuiClient->factory()->container(
QLatin1String( "akonadi_itemview_contextmenu" ), d->xmlGuiClient ) );
else
popup = static_cast<QMenu*>( d->xmlGuiClient->factory()->container(
QLatin1String( "akonadi_collectionview_contextmenu" ), d->xmlGuiClient ) );
if ( popup )
popup->exec( event->globalPos() );
}
void EntityTreeView::setXmlGuiClient( KXMLGUIClient * xmlGuiClient )
{
d->xmlGuiClient = xmlGuiClient;
}
#include "entitytreeview.moc"
<|endoftext|> |
<commit_before>/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __MEM_RUBY_SLICC_INTERFACE_RUBYSLICC_COMPONENTMAPPINGS_HH__
#define __MEM_RUBY_SLICC_INTERFACE_RUBYSLICC_COMPONENTMAPPINGS_HH__
#include "mem/protocol/GenericMachineType.hh"
#include "mem/protocol/MachineType.hh"
#include "mem/ruby/common/Address.hh"
#include "mem/ruby/common/Global.hh"
#include "mem/ruby/common/NetDest.hh"
#include "mem/ruby/common/Set.hh"
#include "mem/ruby/system/DirectoryMemory.hh"
#include "mem/ruby/system/MachineID.hh"
#include "mem/ruby/system/NodeID.hh"
#ifdef MACHINETYPE_L1Cache
#define MACHINETYPE_L1CACHE_ENUM MachineType_L1Cache
#else
#define MACHINETYPE_L1CACHE_ENUM MachineType_NUM
#endif
#ifdef MACHINETYPE_L2Cache
#define MACHINETYPE_L2CACHE_ENUM MachineType_L2Cache
#else
#define MACHINETYPE_L2CACHE_ENUM MachineType_NUM
#endif
#ifdef MACHINETYPE_L3Cache
#define MACHINETYPE_L3CACHE_ENUM MachineType_L3Cache
#else
#define MACHINETYPE_L3CACHE_ENUM MachineType_NUM
#endif
#ifdef MACHINETYPE_DMA
#define MACHINETYPE_DMA_ENUM MachineType_DMA
#else
#define MACHINETYPE_DMA_ENUM MachineType_NUM
#endif
// used to determine the home directory
// returns a value between 0 and total_directories_within_the_system
inline NodeID
map_Address_to_DirectoryNode(const Address& addr)
{
return DirectoryMemory::mapAddressToDirectoryVersion(addr);
}
// used to determine the home directory
// returns a value between 0 and total_directories_within_the_system
inline MachineID
map_Address_to_Directory(const Address &addr)
{
MachineID mach =
{MachineType_Directory, map_Address_to_DirectoryNode(addr)};
return mach;
}
inline MachineID
map_Address_to_DMA(const Address & addr)
{
MachineID dma = {MACHINETYPE_DMA_ENUM, 0};
return dma;
}
inline NetDest
broadcast(MachineType type)
{
NetDest dest;
for (int i = 0; i < MachineType_base_count(type); i++) {
MachineID mach = {type, i};
dest.add(mach);
}
return dest;
}
inline MachineID
mapAddressToRange(const Address & addr, MachineType type, int low_bit,
int num_bits)
{
MachineID mach = {type, 0};
if (num_bits == 0)
return mach;
mach.num = addr.bitSelect(low_bit, low_bit + num_bits - 1);
return mach;
}
inline NodeID
machineIDToNodeID(MachineID machID)
{
return machID.num;
}
inline MachineType
machineIDToMachineType(MachineID machID)
{
return machID.type;
}
inline NodeID
L1CacheMachIDToProcessorNum(MachineID machID)
{
assert(machID.type == MachineType_L1Cache);
return machID.num;
}
inline MachineID
getL1MachineID(NodeID L1RubyNode)
{
MachineID mach = {MACHINETYPE_L1CACHE_ENUM, L1RubyNode};
return mach;
}
inline GenericMachineType
ConvertMachToGenericMach(MachineType machType)
{
if (machType == MACHINETYPE_L1CACHE_ENUM)
return GenericMachineType_L1Cache;
if (machType == MACHINETYPE_L2CACHE_ENUM)
return GenericMachineType_L2Cache;
if (machType == MACHINETYPE_L3CACHE_ENUM)
return GenericMachineType_L3Cache;
if (machType == MachineType_Directory)
return GenericMachineType_Directory;
panic("cannot convert to a GenericMachineType");
}
inline int
machineCount(MachineType machType)
{
return MachineType_base_count(machType);
}
#endif // __MEM_RUBY_SLICC_INTERFACE_COMPONENTMAPPINGS_HH__
<commit_msg>Ruby: minor bugfix, line did not adhere to some macro usage conventions.<commit_after>/*
* Copyright (c) 1999-2008 Mark D. Hill and David A. Wood
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __MEM_RUBY_SLICC_INTERFACE_RUBYSLICC_COMPONENTMAPPINGS_HH__
#define __MEM_RUBY_SLICC_INTERFACE_RUBYSLICC_COMPONENTMAPPINGS_HH__
#include "mem/protocol/GenericMachineType.hh"
#include "mem/protocol/MachineType.hh"
#include "mem/ruby/common/Address.hh"
#include "mem/ruby/common/Global.hh"
#include "mem/ruby/common/NetDest.hh"
#include "mem/ruby/common/Set.hh"
#include "mem/ruby/system/DirectoryMemory.hh"
#include "mem/ruby/system/MachineID.hh"
#include "mem/ruby/system/NodeID.hh"
#ifdef MACHINETYPE_L1Cache
#define MACHINETYPE_L1CACHE_ENUM MachineType_L1Cache
#else
#define MACHINETYPE_L1CACHE_ENUM MachineType_NUM
#endif
#ifdef MACHINETYPE_L2Cache
#define MACHINETYPE_L2CACHE_ENUM MachineType_L2Cache
#else
#define MACHINETYPE_L2CACHE_ENUM MachineType_NUM
#endif
#ifdef MACHINETYPE_L3Cache
#define MACHINETYPE_L3CACHE_ENUM MachineType_L3Cache
#else
#define MACHINETYPE_L3CACHE_ENUM MachineType_NUM
#endif
#ifdef MACHINETYPE_DMA
#define MACHINETYPE_DMA_ENUM MachineType_DMA
#else
#define MACHINETYPE_DMA_ENUM MachineType_NUM
#endif
// used to determine the home directory
// returns a value between 0 and total_directories_within_the_system
inline NodeID
map_Address_to_DirectoryNode(const Address& addr)
{
return DirectoryMemory::mapAddressToDirectoryVersion(addr);
}
// used to determine the home directory
// returns a value between 0 and total_directories_within_the_system
inline MachineID
map_Address_to_Directory(const Address &addr)
{
MachineID mach =
{MachineType_Directory, map_Address_to_DirectoryNode(addr)};
return mach;
}
inline MachineID
map_Address_to_DMA(const Address & addr)
{
MachineID dma = {MACHINETYPE_DMA_ENUM, 0};
return dma;
}
inline NetDest
broadcast(MachineType type)
{
NetDest dest;
for (int i = 0; i < MachineType_base_count(type); i++) {
MachineID mach = {type, i};
dest.add(mach);
}
return dest;
}
inline MachineID
mapAddressToRange(const Address & addr, MachineType type, int low_bit,
int num_bits)
{
MachineID mach = {type, 0};
if (num_bits == 0)
return mach;
mach.num = addr.bitSelect(low_bit, low_bit + num_bits - 1);
return mach;
}
inline NodeID
machineIDToNodeID(MachineID machID)
{
return machID.num;
}
inline MachineType
machineIDToMachineType(MachineID machID)
{
return machID.type;
}
inline NodeID
L1CacheMachIDToProcessorNum(MachineID machID)
{
assert(machID.type == MACHINETYPE_L1CACHE_ENUM);
return machID.num;
}
inline MachineID
getL1MachineID(NodeID L1RubyNode)
{
MachineID mach = {MACHINETYPE_L1CACHE_ENUM, L1RubyNode};
return mach;
}
inline GenericMachineType
ConvertMachToGenericMach(MachineType machType)
{
if (machType == MACHINETYPE_L1CACHE_ENUM)
return GenericMachineType_L1Cache;
if (machType == MACHINETYPE_L2CACHE_ENUM)
return GenericMachineType_L2Cache;
if (machType == MACHINETYPE_L3CACHE_ENUM)
return GenericMachineType_L3Cache;
if (machType == MachineType_Directory)
return GenericMachineType_Directory;
panic("cannot convert to a GenericMachineType");
}
inline int
machineCount(MachineType machType)
{
return MachineType_base_count(machType);
}
#endif // __MEM_RUBY_SLICC_INTERFACE_COMPONENTMAPPINGS_HH__
<|endoftext|> |
<commit_before>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
// construct an automated code emitter: a function that, given a MachineInstr,
// returns the (currently, 32-bit unsigned) value of the instruction.
//
//===----------------------------------------------------------------------===//
#include "CodeEmitterGen.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <map>
using namespace llvm;
// FIXME: Somewhat hackish to use a command line option for this. There should
// be a CodeEmitter class in the Target.td that controls this sort of thing
// instead.
static cl::opt<bool>
MCEmitter("mc-emitter",
cl::desc("Generate CodeEmitter for use with the MC library."),
cl::init(false));
void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
I != E; ++I) {
Record *R = *I;
if (R->getValueAsString("Namespace") == "TargetOpcode")
continue;
BitsInit *BI = R->getValueAsBitsInit("Inst");
unsigned numBits = BI->getNumBits();
BitsInit *NewBI = new BitsInit(numBits);
for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
unsigned bitSwapIdx = numBits - bit - 1;
Init *OrigBit = BI->getBit(bit);
Init *BitSwap = BI->getBit(bitSwapIdx);
NewBI->setBit(bit, BitSwap);
NewBI->setBit(bitSwapIdx, OrigBit);
}
if (numBits % 2) {
unsigned middle = (numBits + 1) / 2;
NewBI->setBit(middle, BI->getBit(middle));
}
// Update the bits in reversed order so that emitInstrOpBits will get the
// correct endianness.
R->getValue("Inst")->setValue(NewBI);
}
}
// If the VarBitInit at position 'bit' matches the specified variable then
// return the variable bit position. Otherwise return -1.
int CodeEmitterGen::getVariableBit(const std::string &VarName,
BitsInit *BI, int bit) {
if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit)))
if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
if (VI->getName() == VarName)
return VBI->getBitNum();
return -1;
}
void CodeEmitterGen::
AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
unsigned &NumberedOp,
std::string &Case, CodeGenTarget &Target) {
CodeGenInstruction &CGI = Target.getInstruction(R);
// Determine if VarName actually contributes to the Inst encoding.
int bit = BI->getNumBits()-1;
// Scan for a bit that this contributed to.
for (; bit >= 0; ) {
if (getVariableBit(VarName, BI, bit) != -1)
break;
--bit;
}
// If we found no bits, ignore this value, otherwise emit the call to get the
// operand encoding.
if (bit < 0) return;
// If the operand matches by name, reference according to that
// operand number. Non-matching operands are assumed to be in
// order.
unsigned OpIdx;
if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
// Get the machine operand number for the indicated operand.
OpIdx = CGI.Operands[OpIdx].MIOperandNo;
assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
"Explicitly used operand also marked as not emitted!");
} else {
/// If this operand is not supposed to be emitted by the
/// generated emitter, skip it.
while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
++NumberedOp;
OpIdx = NumberedOp++;
}
std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
// If the source operand has a custom encoder, use it. This will
// get the encoding for all of the suboperands.
if (!EncoderMethodName.empty()) {
// A custom encoder has all of the information for the
// sub-operands, if there are more than one, so only
// query the encoder once per source operand.
if (SO.second == 0) {
Case += " // op: " + VarName + "\n" +
" op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
} else {
Case += " // op: " + VarName + "\n" +
" op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
for (; bit >= 0; ) {
int varBit = getVariableBit(VarName, BI, bit);
// If this bit isn't from a variable, skip it.
if (varBit == -1) {
--bit;
continue;
}
// Figure out the consecutive range of bits covered by this operand, in
// order to generate better encoding code.
int beginInstBit = bit;
int beginVarBit = varBit;
int N = 1;
for (--bit; bit >= 0;) {
varBit = getVariableBit(VarName, BI, bit);
if (varBit == -1 || varBit != (beginVarBit - N)) break;
++N;
--bit;
}
unsigned opMask = ~0U >> (32-N);
int opShift = beginVarBit - N + 1;
opMask <<= opShift;
opShift = beginInstBit - beginVarBit;
if (opShift > 0) {
Case += " Value |= (op & " + utostr(opMask) + "U) << " +
itostr(opShift) + ";\n";
} else if (opShift < 0) {
Case += " Value |= (op & " + utostr(opMask) + "U) >> " +
itostr(-opShift) + ";\n";
} else {
Case += " Value |= op & " + utostr(opMask) + "U;\n";
}
}
}
std::string CodeEmitterGen::getInstructionCase(Record *R,
CodeGenTarget &Target) {
std::string Case;
BitsInit *BI = R->getValueAsBitsInit("Inst");
const std::vector<RecordVal> &Vals = R->getValues();
unsigned NumberedOp = 0;
// Loop over all of the fields in the instruction, determining which are the
// operands to the instruction.
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
// Ignore fixed fields in the record, we're looking for values like:
// bits<5> RST = { ?, ?, ?, ?, ? };
if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
continue;
AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
}
std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
if (!PostEmitter.empty())
Case += " Value = " + PostEmitter + "(MI, Value);\n";
return Case;
}
void CodeEmitterGen::run(raw_ostream &o) {
CodeGenTarget Target(Records);
std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
// For little-endian instruction bit encodings, reverse the bit order
if (Target.isLittleEndianEncoding()) reverseBits(Insts);
EmitSourceFileHeader("Machine Code Emitter", o);
std::string Namespace = Insts[0]->getValueAsString("Namespace") + "::";
const std::vector<const CodeGenInstruction*> &NumberedInstructions =
Target.getInstructionsByEnumValue();
// Emit function declaration
o << "unsigned " << Target.getName();
if (MCEmitter)
o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
<< " SmallVectorImpl<MCFixup> &Fixups) const {\n";
else
o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
// Emit instruction base values
o << " static const unsigned InstBits[] = {\n";
for (std::vector<const CodeGenInstruction*>::const_iterator
IN = NumberedInstructions.begin(),
EN = NumberedInstructions.end();
IN != EN; ++IN) {
const CodeGenInstruction *CGI = *IN;
Record *R = CGI->TheDef;
if (R->getValueAsString("Namespace") == "TargetOpcode") {
o << " 0U,\n";
continue;
}
BitsInit *BI = R->getValueAsBitsInit("Inst");
// Start by filling in fixed values.
unsigned Value = 0;
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
Value |= B->getValue() << (e-i-1);
}
o << " " << Value << "U," << '\t' << "// " << R->getName() << "\n";
}
o << " 0U\n };\n";
// Map to accumulate all the cases.
std::map<std::string, std::vector<std::string> > CaseMap;
// Construct all cases statement for each opcode
for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
IC != EC; ++IC) {
Record *R = *IC;
if (R->getValueAsString("Namespace") == "TargetOpcode")
continue;
const std::string &InstName = R->getName();
std::string Case = getInstructionCase(R, Target);
CaseMap[Case].push_back(InstName);
}
// Emit initial function code
o << " const unsigned opcode = MI.getOpcode();\n"
<< " unsigned Value = InstBits[opcode];\n"
<< " unsigned op = 0;\n"
<< " (void)op; // suppress warning\n"
<< " switch (opcode) {\n";
// Emit each case statement
std::map<std::string, std::vector<std::string> >::iterator IE, EE;
for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
const std::string &Case = IE->first;
std::vector<std::string> &InstList = IE->second;
for (int i = 0, N = InstList.size(); i < N; i++) {
if (i) o << "\n";
o << " case " << Namespace << InstList[i] << ":";
}
o << " {\n";
o << Case;
o << " break;\n"
<< " }\n";
}
// Default case: unhandled opcode
o << " default:\n"
<< " std::string msg;\n"
<< " raw_string_ostream Msg(msg);\n"
<< " Msg << \"Not supported instr: \" << MI;\n"
<< " report_fatal_error(Msg.str());\n"
<< " }\n"
<< " return Value;\n"
<< "}\n\n";
}
<commit_msg>Tidy up a bit.<commit_after>//===- CodeEmitterGen.cpp - Code Emitter Generator ------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// CodeEmitterGen uses the descriptions of instructions and their fields to
// construct an automated code emitter: a function that, given a MachineInstr,
// returns the (currently, 32-bit unsigned) value of the instruction.
//
//===----------------------------------------------------------------------===//
#include "CodeEmitterGen.h"
#include "CodeGenTarget.h"
#include "Record.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include <map>
using namespace llvm;
// FIXME: Somewhat hackish to use a command line option for this. There should
// be a CodeEmitter class in the Target.td that controls this sort of thing
// instead.
static cl::opt<bool>
MCEmitter("mc-emitter",
cl::desc("Generate CodeEmitter for use with the MC library."),
cl::init(false));
void CodeEmitterGen::reverseBits(std::vector<Record*> &Insts) {
for (std::vector<Record*>::iterator I = Insts.begin(), E = Insts.end();
I != E; ++I) {
Record *R = *I;
if (R->getValueAsString("Namespace") == "TargetOpcode")
continue;
BitsInit *BI = R->getValueAsBitsInit("Inst");
unsigned numBits = BI->getNumBits();
BitsInit *NewBI = new BitsInit(numBits);
for (unsigned bit = 0, end = numBits / 2; bit != end; ++bit) {
unsigned bitSwapIdx = numBits - bit - 1;
Init *OrigBit = BI->getBit(bit);
Init *BitSwap = BI->getBit(bitSwapIdx);
NewBI->setBit(bit, BitSwap);
NewBI->setBit(bitSwapIdx, OrigBit);
}
if (numBits % 2) {
unsigned middle = (numBits + 1) / 2;
NewBI->setBit(middle, BI->getBit(middle));
}
// Update the bits in reversed order so that emitInstrOpBits will get the
// correct endianness.
R->getValue("Inst")->setValue(NewBI);
}
}
// If the VarBitInit at position 'bit' matches the specified variable then
// return the variable bit position. Otherwise return -1.
int CodeEmitterGen::getVariableBit(const std::string &VarName,
BitsInit *BI, int bit) {
if (VarBitInit *VBI = dynamic_cast<VarBitInit*>(BI->getBit(bit)))
if (VarInit *VI = dynamic_cast<VarInit*>(VBI->getVariable()))
if (VI->getName() == VarName)
return VBI->getBitNum();
return -1;
}
void CodeEmitterGen::
AddCodeToMergeInOperand(Record *R, BitsInit *BI, const std::string &VarName,
unsigned &NumberedOp,
std::string &Case, CodeGenTarget &Target) {
CodeGenInstruction &CGI = Target.getInstruction(R);
// Determine if VarName actually contributes to the Inst encoding.
int bit = BI->getNumBits()-1;
// Scan for a bit that this contributed to.
for (; bit >= 0; ) {
if (getVariableBit(VarName, BI, bit) != -1)
break;
--bit;
}
// If we found no bits, ignore this value, otherwise emit the call to get the
// operand encoding.
if (bit < 0) return;
// If the operand matches by name, reference according to that
// operand number. Non-matching operands are assumed to be in
// order.
unsigned OpIdx;
if (CGI.Operands.hasOperandNamed(VarName, OpIdx)) {
// Get the machine operand number for the indicated operand.
OpIdx = CGI.Operands[OpIdx].MIOperandNo;
assert(!CGI.Operands.isFlatOperandNotEmitted(OpIdx) &&
"Explicitly used operand also marked as not emitted!");
} else {
/// If this operand is not supposed to be emitted by the
/// generated emitter, skip it.
while (CGI.Operands.isFlatOperandNotEmitted(NumberedOp))
++NumberedOp;
OpIdx = NumberedOp++;
}
std::pair<unsigned, unsigned> SO = CGI.Operands.getSubOperandNumber(OpIdx);
std::string &EncoderMethodName = CGI.Operands[SO.first].EncoderMethodName;
// If the source operand has a custom encoder, use it. This will
// get the encoding for all of the suboperands.
if (!EncoderMethodName.empty()) {
// A custom encoder has all of the information for the
// sub-operands, if there are more than one, so only
// query the encoder once per source operand.
if (SO.second == 0) {
Case += " // op: " + VarName + "\n" +
" op = " + EncoderMethodName + "(MI, " + utostr(OpIdx);
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
} else {
Case += " // op: " + VarName + "\n" +
" op = getMachineOpValue(MI, MI.getOperand(" + utostr(OpIdx) + ")";
if (MCEmitter)
Case += ", Fixups";
Case += ");\n";
}
for (; bit >= 0; ) {
int varBit = getVariableBit(VarName, BI, bit);
// If this bit isn't from a variable, skip it.
if (varBit == -1) {
--bit;
continue;
}
// Figure out the consecutive range of bits covered by this operand, in
// order to generate better encoding code.
int beginInstBit = bit;
int beginVarBit = varBit;
int N = 1;
for (--bit; bit >= 0;) {
varBit = getVariableBit(VarName, BI, bit);
if (varBit == -1 || varBit != (beginVarBit - N)) break;
++N;
--bit;
}
unsigned opMask = ~0U >> (32-N);
int opShift = beginVarBit - N + 1;
opMask <<= opShift;
opShift = beginInstBit - beginVarBit;
if (opShift > 0) {
Case += " Value |= (op & " + utostr(opMask) + "U) << " +
itostr(opShift) + ";\n";
} else if (opShift < 0) {
Case += " Value |= (op & " + utostr(opMask) + "U) >> " +
itostr(-opShift) + ";\n";
} else {
Case += " Value |= op & " + utostr(opMask) + "U;\n";
}
}
}
std::string CodeEmitterGen::getInstructionCase(Record *R,
CodeGenTarget &Target) {
std::string Case;
BitsInit *BI = R->getValueAsBitsInit("Inst");
const std::vector<RecordVal> &Vals = R->getValues();
unsigned NumberedOp = 0;
// Loop over all of the fields in the instruction, determining which are the
// operands to the instruction.
for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
// Ignore fixed fields in the record, we're looking for values like:
// bits<5> RST = { ?, ?, ?, ?, ? };
if (Vals[i].getPrefix() || Vals[i].getValue()->isComplete())
continue;
AddCodeToMergeInOperand(R, BI, Vals[i].getName(), NumberedOp, Case, Target);
}
std::string PostEmitter = R->getValueAsString("PostEncoderMethod");
if (!PostEmitter.empty())
Case += " Value = " + PostEmitter + "(MI, Value);\n";
return Case;
}
void CodeEmitterGen::run(raw_ostream &o) {
CodeGenTarget Target(Records);
std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
// For little-endian instruction bit encodings, reverse the bit order
if (Target.isLittleEndianEncoding()) reverseBits(Insts);
EmitSourceFileHeader("Machine Code Emitter", o);
const std::vector<const CodeGenInstruction*> &NumberedInstructions =
Target.getInstructionsByEnumValue();
// Emit function declaration
o << "unsigned " << Target.getName();
if (MCEmitter)
o << "MCCodeEmitter::getBinaryCodeForInstr(const MCInst &MI,\n"
<< " SmallVectorImpl<MCFixup> &Fixups) const {\n";
else
o << "CodeEmitter::getBinaryCodeForInstr(const MachineInstr &MI) const {\n";
// Emit instruction base values
o << " static const unsigned InstBits[] = {\n";
for (std::vector<const CodeGenInstruction*>::const_iterator
IN = NumberedInstructions.begin(),
EN = NumberedInstructions.end();
IN != EN; ++IN) {
const CodeGenInstruction *CGI = *IN;
Record *R = CGI->TheDef;
if (R->getValueAsString("Namespace") == "TargetOpcode") {
o << " 0U,\n";
continue;
}
BitsInit *BI = R->getValueAsBitsInit("Inst");
// Start by filling in fixed values.
unsigned Value = 0;
for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i) {
if (BitInit *B = dynamic_cast<BitInit*>(BI->getBit(e-i-1)))
Value |= B->getValue() << (e-i-1);
}
o << " " << Value << "U," << '\t' << "// " << R->getName() << "\n";
}
o << " 0U\n };\n";
// Map to accumulate all the cases.
std::map<std::string, std::vector<std::string> > CaseMap;
// Construct all cases statement for each opcode
for (std::vector<Record*>::iterator IC = Insts.begin(), EC = Insts.end();
IC != EC; ++IC) {
Record *R = *IC;
if (R->getValueAsString("Namespace") == "TargetOpcode")
continue;
const std::string &InstName = R->getValueAsString("Namespace") + "::"
+ R->getName();
std::string Case = getInstructionCase(R, Target);
CaseMap[Case].push_back(InstName);
}
// Emit initial function code
o << " const unsigned opcode = MI.getOpcode();\n"
<< " unsigned Value = InstBits[opcode];\n"
<< " unsigned op = 0;\n"
<< " (void)op; // suppress warning\n"
<< " switch (opcode) {\n";
// Emit each case statement
std::map<std::string, std::vector<std::string> >::iterator IE, EE;
for (IE = CaseMap.begin(), EE = CaseMap.end(); IE != EE; ++IE) {
const std::string &Case = IE->first;
std::vector<std::string> &InstList = IE->second;
for (int i = 0, N = InstList.size(); i < N; i++) {
if (i) o << "\n";
o << " case " << InstList[i] << ":";
}
o << " {\n";
o << Case;
o << " break;\n"
<< " }\n";
}
// Default case: unhandled opcode
o << " default:\n"
<< " std::string msg;\n"
<< " raw_string_ostream Msg(msg);\n"
<< " Msg << \"Not supported instr: \" << MI;\n"
<< " report_fatal_error(Msg.str());\n"
<< " }\n"
<< " return Value;\n"
<< "}\n\n";
}
<|endoftext|> |
<commit_before>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
extern "C"
{
#include "q_shared.h"
#include "qcommon.h"
#include "../../libs/findlocale/findlocale.h"
}
#include "../../libs/tinygettext/tinygettext.hpp"
#include <sstream>
using namespace tinygettext;
DictionaryManager trans_manager;
DictionaryManager trans_managergame;
Dictionary trans_dict;
Dictionary trans_dictgame;
cvar_t *language;
cvar_t *trans_encodings;
cvar_t *trans_languages;
bool enabled = false;
int modificationCount=0;
#define _(x) Trans_Gettext(x)
/*
====================
Trans_ReturnLanguage
Return a loaded language. If desired language, return closest match.
If no languages are close, force English.
====================
*/
Language Trans_ReturnLanguage( const char *lang )
{
int bestScore = 0;
Language bestLang, language = Language::from_env( std::string( lang ) );
std::set<Language> langs = trans_manager.get_languages();
for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
{
int score = Language::match( language, *i );
if( score > bestScore )
{
bestScore = score;
bestLang = *i;
}
}
// Return "en" if language not found
if( !bestLang )
{
Com_Printf( _("^3WARNING:^7 Language \"%s\" (%s) not found. Default to \"English\" (en)\n"),
language.get_name().empty() ? _("Unknown Language") : language.get_name().c_str(),
lang );
bestLang = Language::from_env( "en" );
}
return bestLang;
}
extern "C" void Trans_UpdateLanguage_f( void )
{
Language lang = Trans_ReturnLanguage( language->string );
trans_dict = trans_manager.get_dictionary( lang );
trans_dictgame = trans_managergame.get_dictionary( lang );
Com_Printf(_( "Switched language to %s\n"), lang.get_name().c_str() );
}
/*
============
Trans_Init
============
*/
extern "C" void Trans_Init( void )
{
char **poFiles, langList[ MAX_TOKEN_CHARS ], encList[ MAX_TOKEN_CHARS ];
int numPoFiles, i;
FL_Locale *locale;
std::set<Language> langs;
Language lang;
language = Cvar_Get( "language", "", CVAR_ARCHIVE );
trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
trans_encodings = Cvar_Get( "trans_languages", "", CVAR_ROM );
// Only detect locale if no previous language set.
if( !language->string[0] )
{
FL_FindLocale( &locale, FL_MESSAGES );
// Invalid or not found. Just use builtin language.
if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
{
Cvar_Set( "language", "en" );
}
else
{
Cvar_Set( "language", va( "%s_%s", locale->lang, locale->country ) );
}
}
poFiles = FS_ListFiles( "translation/client", ".po", &numPoFiles );
// This assumes that the filenames in both folders are the same
for( i = 0; i < numPoFiles; i++ )
{
int ret;
Dictionary *dict1;
Dictionary *dict2;
char *buffer, language[ 6 ];
if( FS_ReadFile( va( "translation/client/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
{
dict1 = new Dictionary();
COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
std::stringstream ss( buffer );
trans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
FS_FreeFile( buffer );
}
else
{
Com_Printf(_( "^1ERROR: Could not open client translation: %s\n"), poFiles[ i ] );
}
if( FS_ReadFile( va( "translation/game/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
{
dict2 = new Dictionary();
COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
std::stringstream ss( buffer );
trans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
FS_FreeFile( buffer );
}
else
{
Com_Printf(_( "^1ERROR: Could not open game translation: %s\n"), poFiles[ i ] );
}
}
FS_FreeFileList( poFiles );
langs = trans_manager.get_languages();
for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
{
Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
Q_strcat( encList, sizeof( encList ), va( "\"%s%s%s\" ", p->get_language().c_str(),
p->get_country().c_str()[0] ? "_" : "",
p->get_country().c_str() ) );
}
Cvar_Set( "trans_languages", langList );
Cvar_Set( "trans_encodings", encList );
Com_Printf(_( "Loaded %lu language(s)\n"), langs.size() );
Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );
lang = Trans_ReturnLanguage( language->string );
trans_dict = trans_manager.get_dictionary( lang );
trans_dictgame = trans_managergame.get_dictionary( lang );
enabled = true;
}
extern "C" const char* Trans_Gettext( const char *msgid )
{
if( !enabled ) { return msgid; }
return trans_dict.translate( std::string( msgid ) ).c_str();
}
extern "C" const char* Trans_GettextGame( const char *msgid )
{
if( !enabled ) { return msgid; }
return trans_dictgame.translate( std::string( msgid ) ).c_str();
}
extern "C" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
return trans_dict.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
extern "C" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
return trans_dictgame.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
<commit_msg>Fix case where only a language is detected, but no country<commit_after>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
extern "C"
{
#include "q_shared.h"
#include "qcommon.h"
#include "../../libs/findlocale/findlocale.h"
}
#include "../../libs/tinygettext/tinygettext.hpp"
#include <sstream>
using namespace tinygettext;
DictionaryManager trans_manager;
DictionaryManager trans_managergame;
Dictionary trans_dict;
Dictionary trans_dictgame;
cvar_t *language;
cvar_t *trans_encodings;
cvar_t *trans_languages;
bool enabled = false;
int modificationCount=0;
#define _(x) Trans_Gettext(x)
/*
====================
Trans_ReturnLanguage
Return a loaded language. If desired language, return closest match.
If no languages are close, force English.
====================
*/
Language Trans_ReturnLanguage( const char *lang )
{
int bestScore = 0;
Language bestLang, language = Language::from_env( std::string( lang ) );
std::set<Language> langs = trans_manager.get_languages();
for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
{
int score = Language::match( language, *i );
if( score > bestScore )
{
bestScore = score;
bestLang = *i;
}
}
// Return "en" if language not found
if( !bestLang )
{
Com_Printf( _("^3WARNING:^7 Language \"%s\" (%s) not found. Default to \"English\" (en)\n"),
language.get_name().empty() ? _("Unknown Language") : language.get_name().c_str(),
lang );
bestLang = Language::from_env( "en" );
}
return bestLang;
}
extern "C" void Trans_UpdateLanguage_f( void )
{
Language lang = Trans_ReturnLanguage( language->string );
trans_dict = trans_manager.get_dictionary( lang );
trans_dictgame = trans_managergame.get_dictionary( lang );
Com_Printf(_( "Switched language to %s\n"), lang.get_name().c_str() );
}
/*
============
Trans_Init
============
*/
extern "C" void Trans_Init( void )
{
char **poFiles, langList[ MAX_TOKEN_CHARS ], encList[ MAX_TOKEN_CHARS ];
int numPoFiles, i;
FL_Locale *locale;
std::set<Language> langs;
Language lang;
language = Cvar_Get( "language", "", CVAR_ARCHIVE );
trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
trans_encodings = Cvar_Get( "trans_languages", "", CVAR_ROM );
// Only detect locale if no previous language set.
if( !language->string[0] )
{
FL_FindLocale( &locale, FL_MESSAGES );
// Invalid or not found. Just use builtin language.
if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
{
Cvar_Set( "language", "en" );
}
else
{
Cvar_Set( "language", va( "%s%s%s", locale->lang,
locale->country[0] ? "_" : "",
locale->country ) );
}
}
poFiles = FS_ListFiles( "translation/client", ".po", &numPoFiles );
// This assumes that the filenames in both folders are the same
for( i = 0; i < numPoFiles; i++ )
{
int ret;
Dictionary *dict1;
Dictionary *dict2;
char *buffer, language[ 6 ];
if( FS_ReadFile( va( "translation/client/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
{
dict1 = new Dictionary();
COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
std::stringstream ss( buffer );
trans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
FS_FreeFile( buffer );
}
else
{
Com_Printf(_( "^1ERROR: Could not open client translation: %s\n"), poFiles[ i ] );
}
if( FS_ReadFile( va( "translation/game/%s", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )
{
dict2 = new Dictionary();
COM_StripExtension2( poFiles[ i ], language, sizeof( language ) );
std::stringstream ss( buffer );
trans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );
FS_FreeFile( buffer );
}
else
{
Com_Printf(_( "^1ERROR: Could not open game translation: %s\n"), poFiles[ i ] );
}
}
FS_FreeFileList( poFiles );
langs = trans_manager.get_languages();
for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
{
Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
Q_strcat( encList, sizeof( encList ), va( "\"%s%s%s\" ", p->get_language().c_str(),
p->get_country().c_str()[0] ? "_" : "",
p->get_country().c_str() ) );
}
Cvar_Set( "trans_languages", langList );
Cvar_Set( "trans_encodings", encList );
Com_Printf(_( "Loaded %lu language(s)\n"), langs.size() );
Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );
lang = Trans_ReturnLanguage( language->string );
trans_dict = trans_manager.get_dictionary( lang );
trans_dictgame = trans_managergame.get_dictionary( lang );
enabled = true;
}
extern "C" const char* Trans_Gettext( const char *msgid )
{
if( !enabled ) { return msgid; }
return trans_dict.translate( std::string( msgid ) ).c_str();
}
extern "C" const char* Trans_GettextGame( const char *msgid )
{
if( !enabled ) { return msgid; }
return trans_dictgame.translate( std::string( msgid ) ).c_str();
}
extern "C" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
return trans_dict.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
extern "C" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
if( !enabled ) { return num == 1 ? msgid : msgid_plural; }
return trans_dictgame.translate_plural( std::string( msgid ), std::string( msgid_plural ), num ).c_str();
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (c) Yorik van Havre ([email protected]) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/MainWindow.h>
#include <Gui/Command.h>
#include <Gui/Selection.h>
#include <Gui/SelectionFilter.h>
#include <Gui/Document.h>
#include <Gui/Control.h>
#include <Mod/Path/App/FeaturePath.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include <Mod/Path/App/FeaturePathShape.h>
#include <Mod/Part/App/PartFeature.h>
// Path compound #####################################################################################################
DEF_STD_CMD_A(CmdPathCompound);
CmdPathCompound::CmdPathCompound()
:Command("Path_Compound")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("Compound");
sToolTipText = QT_TR_NOOP("Creates a compound from selected paths");
sWhatsThis = "Path_Compound";
sStatusTip = sToolTipText;
sPixmap = "Path-Compound";
sAccel = "P,C";
}
void CmdPathCompound::activated(int iMsg)
{
std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
if (Sel.size() > 0) {
std::ostringstream cmd;
cmd << "[";
Path::Feature *pcPathObject;
for (std::vector<Gui::SelectionSingleton::SelObj>::const_iterator it=Sel.begin();it!=Sel.end();++it) {
if ((*it).pObject->getTypeId().isDerivedFrom(Path::Feature::getClassTypeId())) {
pcPathObject = dynamic_cast<Path::Feature*>((*it).pObject);
cmd << "FreeCAD.activeDocument()." << pcPathObject->getNameInDocument() << ",";
} else {
Base::Console().Error("Only Path objects must be selected before running this command\n");
return;
}
}
cmd << "]";
std::string FeatName = getUniqueObjectName("PathCompound");
openCommand("Create Path Compound");
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureCompound','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Group = %s",FeatName.c_str(),cmd.str().c_str());
commitCommand();
updateActive();
} else {
Base::Console().Error("At least one Path object must be selected\n");
return;
}
}
bool CmdPathCompound::isActive(void)
{
return hasActiveDocument();
}
// Path Shape #####################################################################################################
DEF_STD_CMD_A(CmdPathShape);
CmdPathShape::CmdPathShape()
:Command("Path_Shape")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("From Shape");
sToolTipText = QT_TR_NOOP("Creates a path from a selected shape");
sWhatsThis = "Path_Shape";
sStatusTip = sToolTipText;
sPixmap = "Path-Shape";
sAccel = "P,S";
}
void CmdPathShape::activated(int iMsg)
{
std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
if (Sel.size() == 1) {
if (Sel[0].pObject->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
Part::Feature *pcPartObject = dynamic_cast<Part::Feature*>(Sel[0].pObject);
std::string FeatName = getUniqueObjectName("PathShape");
openCommand("Create Path Compound");
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureShape','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Shape = FreeCAD.activeDocument().%s.Shape.copy()",FeatName.c_str(),pcPartObject->getNameInDocument());
commitCommand();
updateActive();
} else {
Base::Console().Error("Exactly one shape object must be selected\n");
return;
}
} else {
Base::Console().Error("Exactly one shape object must be selected\n");
return;
}
}
bool CmdPathShape::isActive(void)
{
return hasActiveDocument();
}
void CreatePathCommands(void)
{
Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
rcCmdMgr.addCommand(new CmdPathCompound());
rcCmdMgr.addCommand(new CmdPathShape());
}
<commit_msg>fix Coverity issues<commit_after>/***************************************************************************
* Copyright (c) Yorik van Havre ([email protected]) 2014 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
#endif
#include <Base/Console.h>
#include <App/Application.h>
#include <Gui/Application.h>
#include <Gui/MainWindow.h>
#include <Gui/Command.h>
#include <Gui/Selection.h>
#include <Gui/SelectionFilter.h>
#include <Gui/Document.h>
#include <Gui/Control.h>
#include <Mod/Path/App/FeaturePath.h>
#include <Mod/Path/App/FeaturePathCompound.h>
#include <Mod/Path/App/FeaturePathShape.h>
#include <Mod/Part/App/PartFeature.h>
// Path compound #####################################################################################################
DEF_STD_CMD_A(CmdPathCompound)
CmdPathCompound::CmdPathCompound()
:Command("Path_Compound")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("Compound");
sToolTipText = QT_TR_NOOP("Creates a compound from selected paths");
sWhatsThis = "Path_Compound";
sStatusTip = sToolTipText;
sPixmap = "Path-Compound";
sAccel = "P,C";
}
void CmdPathCompound::activated(int iMsg)
{
std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
if (Sel.size() > 0) {
std::ostringstream cmd;
cmd << "[";
Path::Feature *pcPathObject;
for (std::vector<Gui::SelectionSingleton::SelObj>::const_iterator it=Sel.begin();it!=Sel.end();++it) {
if ((*it).pObject->getTypeId().isDerivedFrom(Path::Feature::getClassTypeId())) {
pcPathObject = static_cast<Path::Feature*>((*it).pObject);
cmd << "FreeCAD.activeDocument()." << pcPathObject->getNameInDocument() << ",";
} else {
Base::Console().Error("Only Path objects must be selected before running this command\n");
return;
}
}
cmd << "]";
std::string FeatName = getUniqueObjectName("PathCompound");
openCommand("Create Path Compound");
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureCompound','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Group = %s",FeatName.c_str(),cmd.str().c_str());
commitCommand();
updateActive();
} else {
Base::Console().Error("At least one Path object must be selected\n");
return;
}
}
bool CmdPathCompound::isActive(void)
{
return hasActiveDocument();
}
// Path Shape #####################################################################################################
DEF_STD_CMD_A(CmdPathShape)
CmdPathShape::CmdPathShape()
:Command("Path_Shape")
{
sAppModule = "Path";
sGroup = QT_TR_NOOP("Path");
sMenuText = QT_TR_NOOP("From Shape");
sToolTipText = QT_TR_NOOP("Creates a path from a selected shape");
sWhatsThis = "Path_Shape";
sStatusTip = sToolTipText;
sPixmap = "Path-Shape";
sAccel = "P,S";
}
void CmdPathShape::activated(int iMsg)
{
std::vector<Gui::SelectionSingleton::SelObj> Sel = getSelection().getSelection();
if (Sel.size() == 1) {
if (Sel[0].pObject->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())) {
Part::Feature *pcPartObject = static_cast<Part::Feature*>(Sel[0].pObject);
std::string FeatName = getUniqueObjectName("PathShape");
openCommand("Create Path Compound");
doCommand(Doc,"FreeCAD.activeDocument().addObject('Path::FeatureShape','%s')",FeatName.c_str());
doCommand(Doc,"FreeCAD.activeDocument().%s.Shape = FreeCAD.activeDocument().%s.Shape.copy()",FeatName.c_str(),pcPartObject->getNameInDocument());
commitCommand();
updateActive();
} else {
Base::Console().Error("Exactly one shape object must be selected\n");
return;
}
} else {
Base::Console().Error("Exactly one shape object must be selected\n");
return;
}
}
bool CmdPathShape::isActive(void)
{
return hasActiveDocument();
}
void CreatePathCommands(void)
{
Gui::CommandManager &rcCmdMgr = Gui::Application::Instance->commandManager();
rcCmdMgr.addCommand(new CmdPathCompound());
rcCmdMgr.addCommand(new CmdPathShape());
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TableConnectionData.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2006-06-20 03:28:01 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
using namespace dbaui;
using namespace comphelper;
//==================================================================
// class OTableConnectionData
//==================================================================
DBG_NAME(OTableConnectionData)
TYPEINIT0(OTableConnectionData);
//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData()
{
DBG_CTOR(OTableConnectionData,NULL);
Init();
}
//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData( const String& rSourceWinName, const String& rDestWinName, const String& rConnName )
:m_aSourceWinName( rSourceWinName )
,m_aDestWinName( rDestWinName )
,m_aConnName( rConnName )
{
DBG_CTOR(OTableConnectionData,NULL);
Init();
}
//------------------------------------------------------------------------
void OTableConnectionData::Init()
{
//////////////////////////////////////////////////////////////////////
// LineDataList mit Defaults initialisieren
DBG_ASSERT(m_vConnLineData.size() == 0, "OTableConnectionData::Init() : nur mit leere Linienliste aufzurufen !");
ResetConnLines(TRUE);
// das legt Defaults an
}
//------------------------------------------------------------------------
void OTableConnectionData::Init(const String& rSourceWinName, const String& rDestWinName, const String& rConnName)
{
// erst mal alle LineDatas loeschen
OConnectionLineDataVec().swap(m_vConnLineData);
// dann die Strings
m_aSourceWinName = rSourceWinName;
m_aDestWinName = rDestWinName;
m_aConnName = rConnName;
// den Rest erledigt das andere Init
Init();
}
//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData( const OTableConnectionData& rConnData )
{
DBG_CTOR(OTableConnectionData,NULL);
*this = rConnData;
}
//------------------------------------------------------------------------
void OTableConnectionData::CopyFrom(const OTableConnectionData& rSource)
{
*this = rSource;
// hier ziehe ich mich auf das (nicht-virtuelle) operator= zurueck, das nur meine Members kopiert
}
//------------------------------------------------------------------------
OTableConnectionData::~OTableConnectionData()
{
DBG_DTOR(OTableConnectionData,NULL);
// LineDataList loeschen
ResetConnLines(FALSE);
}
//------------------------------------------------------------------------
OTableConnectionData& OTableConnectionData::operator=( const OTableConnectionData& rConnData )
{
if (&rConnData == this)
return *this;
m_aSourceWinName = rConnData.GetSourceWinName();
m_aDestWinName = rConnData.GetDestWinName();
m_aConnName = rConnData.GetConnName();
// clear line list
ResetConnLines(FALSE);
// und kopieren
OConnectionLineDataVec* pLineData = const_cast<OTableConnectionData*>(&rConnData)->GetConnLineDataList();
OConnectionLineDataVec::const_iterator aIter = pLineData->begin();
for(;aIter != pLineData->end();++aIter)
m_vConnLineData.push_back(new OConnectionLineData(**aIter));
return *this;
}
//------------------------------------------------------------------------
BOOL OTableConnectionData::SetConnLine( USHORT nIndex, const String& rSourceFieldName, const String& rDestFieldName )
{
if (USHORT(m_vConnLineData.size()) < nIndex)
return FALSE;
// == ist noch erlaubt, das entspricht einem Append
if (m_vConnLineData.size() == nIndex)
return AppendConnLine(rSourceFieldName, rDestFieldName);
OConnectionLineDataRef pConnLineData = m_vConnLineData[nIndex];
DBG_ASSERT(pConnLineData != NULL, "OTableConnectionData::SetConnLine : habe ungueltiges LineData-Objekt");
pConnLineData->SetSourceFieldName( rSourceFieldName );
pConnLineData->SetDestFieldName( rDestFieldName );
return TRUE;
}
//------------------------------------------------------------------------
BOOL OTableConnectionData::AppendConnLine( const ::rtl::OUString& rSourceFieldName, const ::rtl::OUString& rDestFieldName )
{
OConnectionLineDataVec::iterator aIter = m_vConnLineData.begin();
for(;aIter != m_vConnLineData.end();++aIter)
{
if((*aIter)->GetDestFieldName() == rDestFieldName && (*aIter)->GetSourceFieldName() == rSourceFieldName)
break;
}
if(aIter == m_vConnLineData.end())
{
OConnectionLineDataRef pNew = new OConnectionLineData(rSourceFieldName, rDestFieldName);
if (!pNew.isValid())
return FALSE;
m_vConnLineData.push_back(pNew);
}
return TRUE;
}
//------------------------------------------------------------------------
void OTableConnectionData::ResetConnLines( BOOL bUseDefaults )
{
OConnectionLineDataVec().swap(m_vConnLineData);
if (bUseDefaults)
{
for (USHORT i=0; i<MAX_CONN_COUNT; i++)
m_vConnLineData.push_back( new OConnectionLineData());
}
}
//------------------------------------------------------------------------
OConnectionLineDataRef OTableConnectionData::CreateLineDataObj()
{
return new OConnectionLineData();
}
//------------------------------------------------------------------------
OConnectionLineDataRef OTableConnectionData::CreateLineDataObj( const OConnectionLineData& rConnLineData )
{
return new OConnectionLineData( rConnLineData );
}
// -----------------------------------------------------------------------------
OTableConnectionData* OTableConnectionData::NewInstance() const
{
return new OTableConnectionData();
}
// -----------------------------------------------------------------------------
void OTableConnectionData::normalizeLines()
{
// noch ein wenig Normalisierung auf den LineDatas : leere Lines vom Anfang an das Ende verschieben
sal_Int32 nCount = m_vConnLineData.size();
for(sal_Int32 i=0;i<nCount;)
{
if(!m_vConnLineData[i]->GetSourceFieldName().getLength() && !m_vConnLineData[i]->GetDestFieldName().getLength())
{
OConnectionLineDataRef pData = m_vConnLineData[i];
m_vConnLineData.erase(m_vConnLineData.begin()+i);
m_vConnLineData.push_back(pData);
--nCount;
}
else
++i;
}
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS dba204b (1.7.12); FILE MERGED 2006/07/11 05:26:26 oj 1.7.12.1: #i67034# call swap directly<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TableConnectionData.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2006-07-26 07:49:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef DBAUI_TABLECONNECTIONDATA_HXX
#include "TableConnectionData.hxx"
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COMPHELPER_STLTYPES_HXX_
#include <comphelper/stl_types.hxx>
#endif
using namespace dbaui;
using namespace comphelper;
//==================================================================
// class OTableConnectionData
//==================================================================
DBG_NAME(OTableConnectionData)
TYPEINIT0(OTableConnectionData);
//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData()
{
DBG_CTOR(OTableConnectionData,NULL);
Init();
}
//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData( const String& rSourceWinName, const String& rDestWinName, const String& rConnName )
:m_aSourceWinName( rSourceWinName )
,m_aDestWinName( rDestWinName )
,m_aConnName( rConnName )
{
DBG_CTOR(OTableConnectionData,NULL);
Init();
}
//------------------------------------------------------------------------
void OTableConnectionData::Init()
{
//////////////////////////////////////////////////////////////////////
// LineDataList mit Defaults initialisieren
DBG_ASSERT(m_vConnLineData.size() == 0, "OTableConnectionData::Init() : nur mit leere Linienliste aufzurufen !");
ResetConnLines(TRUE);
// das legt Defaults an
}
//------------------------------------------------------------------------
void OTableConnectionData::Init(const String& rSourceWinName, const String& rDestWinName, const String& rConnName)
{
// erst mal alle LineDatas loeschen
OConnectionLineDataVec().swap(m_vConnLineData);
// dann die Strings
m_aSourceWinName = rSourceWinName;
m_aDestWinName = rDestWinName;
m_aConnName = rConnName;
// den Rest erledigt das andere Init
Init();
}
//------------------------------------------------------------------------
OTableConnectionData::OTableConnectionData( const OTableConnectionData& rConnData )
{
DBG_CTOR(OTableConnectionData,NULL);
*this = rConnData;
}
//------------------------------------------------------------------------
void OTableConnectionData::CopyFrom(const OTableConnectionData& rSource)
{
*this = rSource;
// hier ziehe ich mich auf das (nicht-virtuelle) operator= zurueck, das nur meine Members kopiert
}
//------------------------------------------------------------------------
OTableConnectionData::~OTableConnectionData()
{
DBG_DTOR(OTableConnectionData,NULL);
// LineDataList loeschen
OConnectionLineDataVec().swap(m_vConnLineData);
//ResetConnLines(FALSE);
}
//------------------------------------------------------------------------
OTableConnectionData& OTableConnectionData::operator=( const OTableConnectionData& rConnData )
{
if (&rConnData == this)
return *this;
m_aSourceWinName = rConnData.GetSourceWinName();
m_aDestWinName = rConnData.GetDestWinName();
m_aConnName = rConnData.GetConnName();
// clear line list
ResetConnLines(FALSE);
// und kopieren
OConnectionLineDataVec* pLineData = const_cast<OTableConnectionData*>(&rConnData)->GetConnLineDataList();
OConnectionLineDataVec::const_iterator aIter = pLineData->begin();
for(;aIter != pLineData->end();++aIter)
m_vConnLineData.push_back(new OConnectionLineData(**aIter));
return *this;
}
//------------------------------------------------------------------------
BOOL OTableConnectionData::SetConnLine( USHORT nIndex, const String& rSourceFieldName, const String& rDestFieldName )
{
if (USHORT(m_vConnLineData.size()) < nIndex)
return FALSE;
// == ist noch erlaubt, das entspricht einem Append
if (m_vConnLineData.size() == nIndex)
return AppendConnLine(rSourceFieldName, rDestFieldName);
OConnectionLineDataRef pConnLineData = m_vConnLineData[nIndex];
DBG_ASSERT(pConnLineData != NULL, "OTableConnectionData::SetConnLine : habe ungueltiges LineData-Objekt");
pConnLineData->SetSourceFieldName( rSourceFieldName );
pConnLineData->SetDestFieldName( rDestFieldName );
return TRUE;
}
//------------------------------------------------------------------------
BOOL OTableConnectionData::AppendConnLine( const ::rtl::OUString& rSourceFieldName, const ::rtl::OUString& rDestFieldName )
{
OConnectionLineDataVec::iterator aIter = m_vConnLineData.begin();
for(;aIter != m_vConnLineData.end();++aIter)
{
if((*aIter)->GetDestFieldName() == rDestFieldName && (*aIter)->GetSourceFieldName() == rSourceFieldName)
break;
}
if(aIter == m_vConnLineData.end())
{
OConnectionLineDataRef pNew = new OConnectionLineData(rSourceFieldName, rDestFieldName);
if (!pNew.isValid())
return FALSE;
m_vConnLineData.push_back(pNew);
}
return TRUE;
}
//------------------------------------------------------------------------
void OTableConnectionData::ResetConnLines( BOOL bUseDefaults )
{
OConnectionLineDataVec().swap(m_vConnLineData);
if (bUseDefaults)
{
for (USHORT i=0; i<MAX_CONN_COUNT; i++)
m_vConnLineData.push_back( new OConnectionLineData());
}
}
//------------------------------------------------------------------------
OConnectionLineDataRef OTableConnectionData::CreateLineDataObj()
{
return new OConnectionLineData();
}
//------------------------------------------------------------------------
OConnectionLineDataRef OTableConnectionData::CreateLineDataObj( const OConnectionLineData& rConnLineData )
{
return new OConnectionLineData( rConnLineData );
}
// -----------------------------------------------------------------------------
OTableConnectionData* OTableConnectionData::NewInstance() const
{
return new OTableConnectionData();
}
// -----------------------------------------------------------------------------
void OTableConnectionData::normalizeLines()
{
// noch ein wenig Normalisierung auf den LineDatas : leere Lines vom Anfang an das Ende verschieben
sal_Int32 nCount = m_vConnLineData.size();
for(sal_Int32 i=0;i<nCount;)
{
if(!m_vConnLineData[i]->GetSourceFieldName().getLength() && !m_vConnLineData[i]->GetDestFieldName().getLength())
{
OConnectionLineDataRef pData = m_vConnLineData[i];
m_vConnLineData.erase(m_vConnLineData.begin()+i);
m_vConnLineData.push_back(pData);
--nCount;
}
else
++i;
}
}
// -----------------------------------------------------------------------------
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow 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 "tensorflow_lite_support/cc/task/vision/image_classifier_c_api.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils_c.h"
#include "tensorflow_lite_support/cc/task/vision/classification_result_c_api.h"
#include "tensorflow_lite_support/cc/task/vision/image_classifier_c_api.h"
#include "tensorflow_lite_support/cc/task/vision/core/frame_buffer_c_api.h"
namespace tflite {
namespace task {
namespace vision {
namespace {
using ::tflite::task::JoinPath;
constexpr char kTestDataDirectory[] =
"tensorflow_lite_support/cc/test/testdata/task/vision/";
// Float model.
constexpr char kMobileNetFloatWithMetadata[] = "mobilenet_v2_1.0_224.tflite";
// Quantized model.
constexpr char kMobileNetQuantizedWithMetadata[] =
"mobilenet_v1_0.25_224_quant.tflite";
// Hello world flowers classifier supporting 5 classes (quantized model).
constexpr char kAutoMLModelWithMetadata[] = "automl_labeler_model.tflite";
ImageData LoadImage(const char* image_name) {
return DecodeImageFromFile(JoinPath("./" /*test src dir*/,
kTestDataDirectory, image_name).data());
}
TEST(ImageClassifierFromFileTest, FailsWithMissingModelPath) {
// ImageClassifierOptions *options = ImageClassifierOptionsCreate();
ImageClassifier *image_classifier = ImageClassifierFromFile("");
ASSERT_EQ(image_classifier, nullptr);
}
TEST(ImageClassifierFromFileTest, SucceedsWithModelPath) {
ImageClassifier *image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data());
EXPECT_NE(image_classifier, nullptr);
ImageClassifierDelete(image_classifier);
}
TEST(ImageClassifierFromOptionsTest, FailsWithMissingModelPath) {
ImageClassifierOptions *options = ImageClassifierOptionsCreate();
ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
ASSERT_EQ(image_classifier, nullptr);
}
TEST(ImageClassifierFromOptionsTest, SucceedsWithModelPath) {
ImageClassifierOptions *options = ImageClassifierOptionsCreate();
const char *model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data();
ImageClassifierOptionsSetModelFilePath(options, model_path);
ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
EXPECT_NE(image_classifier, nullptr);
ImageClassifierDelete(image_classifier);
}
class ImageClassifierClassifyTest : public ::testing::Test {
protected:
void SetUp() override {
image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data());
ASSERT_NE(image_classifier, nullptr);
}
void TearDown() override {
ImageClassifierDelete(image_classifier);
}
ImageClassifier *image_classifier;
};
TEST_F(ImageClassifierClassifyTest, SucceedsWithModelPath) {
struct ImageData image_data = LoadImage("burger-224.png");
struct FrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.width,
.plane.buffer = image_data.pixel_data,
.plane.stride.row_stride_bytes = image_data.width * image_data.channels,
.plane.stride.pixel_stride_bytes = image_data.channels,
.format = kRGB};
struct ClassificationResult *classification_result = ImageClassifierClassify(image_classifier, &frame_buffer);
ImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1) << "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr) << "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1) << "Classification Result Classifications Size is NULL";
EXPECT_NE(classification_result->classifications->classes, nullptr) << "Classification Result Classifications Classes is NULL";
ImageClassifierClassificationResultDelete(classification_result);
}
} // namespace
} // namespace vision
} // namespace task
} // namespace tflite
<commit_msg>Fixed Typo in code<commit_after>/* Copyright 2020 The TensorFlow 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 "tensorflow_lite_support/cc/task/vision/image_classifier_c_api.h"
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils_c.h"
#include "tensorflow_lite_support/cc/task/vision/classification_result_c_api.h"
#include "tensorflow_lite_support/cc/task/vision/image_classifier_c_api.h"
#include "tensorflow_lite_support/cc/task/vision/core/frame_buffer_c_api.h"
namespace tflite {
namespace task {
namespace vision {
namespace {
using ::tflite::task::JoinPath;
constexpr char kTestDataDirectory[] =
"tensorflow_lite_support/cc/test/testdata/task/vision/";
// Float model.
constexpr char kMobileNetFloatWithMetadata[] = "mobilenet_v2_1.0_224.tflite";
// Quantized model.
constexpr char kMobileNetQuantizedWithMetadata[] =
"mobilenet_v1_0.25_224_quant.tflite";
// Hello world flowers classifier supporting 5 classes (quantized model).
constexpr char kAutoMLModelWithMetadata[] = "automl_labeler_model.tflite";
ImageData LoadImage(const char* image_name) {
return DecodeImageFromFile(JoinPath("./" /*test src dir*/,
kTestDataDirectory, image_name).data());
}
TEST(ImageClassifierFromFileTest, FailsWithMissingModelPath) {
// ImageClassifierOptions *options = ImageClassifierOptionsCreate();
ImageClassifier *image_classifier = ImageClassifierFromFile("");
ASSERT_EQ(image_classifier, nullptr);
}
TEST(ImageClassifierFromFileTest, SucceedsWithModelPath) {
ImageClassifier *image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data());
EXPECT_NE(image_classifier, nullptr);
ImageClassifierDelete(image_classifier);
}
TEST(ImageClassifierFromOptionsTest, FailsWithMissingModelPath) {
ImageClassifierOptions *options = ImageClassifierOptionsCreate();
ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
ASSERT_EQ(image_classifier, nullptr);
}
TEST(ImageClassifierFromOptionsTest, SucceedsWithModelPath) {
ImageClassifierOptions *options = ImageClassifierOptionsCreate();
const char *model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data();
ImageClassifierOptionsSetModelFilePath(options, model_path);
ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
EXPECT_NE(image_classifier, nullptr);
ImageClassifierDelete(image_classifier);
}
class ImageClassifierClassifyTest : public ::testing::Test {
protected:
void SetUp() override {
image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data());
ASSERT_NE(image_classifier, nullptr);
}
void TearDown() override {
ImageClassifierDelete(image_classifier);
}
ImageClassifier *image_classifier;
};
TEST_F(ImageClassifierClassifyTest, SucceedsWithModelPath) {
struct ImageData image_data = LoadImage("burger-224.png");
struct FrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.plane.buffer = image_data.pixel_data,
.plane.stride.row_stride_bytes = image_data.width * image_data.channels,
.plane.stride.pixel_stride_bytes = image_data.channels,
.format = kRGB};
struct ClassificationResult *classification_result = ImageClassifierClassify(image_classifier, &frame_buffer);
ImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1) << "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr) << "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1) << "Classification Result Classifications Size is NULL";
EXPECT_NE(classification_result->classifications->classes, nullptr) << "Classification Result Classifications Classes is NULL";
ImageClassifierClassificationResultDelete(classification_result);
}
} // namespace
} // namespace vision
} // namespace task
} // namespace tflite
<|endoftext|> |
<commit_before>#ifndef MeanshiftClusteringFilter_hxx_
#define MeanshiftClusteringFilter_hxx_
#include "itkNumericTraits.h"
#include "MeanshiftClusteringFilter.h"
namespace gth818n
{
template< typename TCoordRep, unsigned int NPointDimension >
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::MeanshiftClusteringFilter()
{
m_epoch = 2;
m_inputPointSet = 0;
m_seedPoints = 0;
m_numberOfMSIteration = 100;
m_radius = 3.0;
m_allDone = false;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::update()
{
// //dbg
// std::cout<<"_constructKdTree..."<<std::flush;
// //dbg, end
_constructKdTree();
// //dbg
// std::cout<<"done"<<std::endl<<std::flush;
// //dbg, end
if (!m_seedPoints)
{
_constructSeedPoints();
}
_meanshiftIteration();
_findUniqueCenters();
_findLabelOfPoints();
m_allDone = true;
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::setRadius(RealType rad)
{
if (rad <= 0.0)
{
std::cerr<<"Error: rad should > 0, but got "<<rad<<std::endl;
abort();
}
m_radius = rad;
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::setEpoch(int epoch)
{
if (epoch < 0)
{
std::cerr<<"Error: epoch should >= 0, but got "<<epoch<<std::endl;
abort();
}
m_epoch = epoch;
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_constructKdTree()
{
m_treeGenerator = TreeGeneratorType::New();
m_treeGenerator->SetSample( m_inputPointSet );
m_treeGenerator->SetBucketSize( 16 );
m_treeGenerator->Update();
m_tree = m_treeGenerator->GetOutput();
// VectorType queryPoint;
// queryPoint[0] = 10.0;
// queryPoint[1] = 7.0;
// // K-Neighbor search
// std::cout << "K-Neighbor search:" << std::endl;
// unsigned int numberOfNeighbors = 3;
// typename TreeType::InstanceIdentifierVectorType neighbors;
// m_tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
// for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
// {
// std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
// }
// // Radius search
// std::cout << "Radius search:" << std::endl;
// double radius = 4.0;
// m_tree->Search( queryPoint, radius, neighbors ) ;
// std::cout << "There are " << neighbors.size() << " neighbors." << std::endl;
// for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
// {
// std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
// }
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_computeInputPointRange()
{
VectorType inputPointSetMin;
inputPointSetMin.Fill(itk::NumericTraits< RealType >::max());
VectorType inputPointSetMax;
inputPointSetMax.Fill(itk::NumericTraits< RealType >::min());
for (long itp = 0; itp < m_inputPointSet->Size(); ++itp)
{
VectorType thisPoint = m_inputPointSet->GetMeasurementVector(itp);
for (unsigned int idim = 0; idim < NPointDimension; ++idim)
{
inputPointSetMin[idim] = inputPointSetMin[idim]<thisPoint[idim]?inputPointSetMin[idim]:thisPoint[idim];
inputPointSetMax[idim] = inputPointSetMax[idim]<thisPoint[idim]?inputPointSetMax[idim]:thisPoint[idim];
}
}
m_inputPointSetRange = inputPointSetMax - inputPointSetMin;
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_meanshiftIteration()
{
VectorType queryPoint;
typename TreeType::InstanceIdentifierVectorType neighbors;
for (long it = 0; it < m_numberOfMSIteration; ++it)
{
for (long itp = 0; itp < m_seedPoints->Size(); ++itp)
{
queryPoint = m_seedPoints->GetMeasurementVector(itp);
m_tree->Search( queryPoint, m_radius, neighbors ) ;
VectorType newPosition;
newPosition.Fill(0);
for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
{
newPosition += m_tree->GetMeasurementVector( neighbors[i] );
//std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
}
newPosition /= static_cast<RealType>(neighbors.size());
m_seedPoints->SetMeasurementVector(itp, newPosition);
/// If relative increamental is small enough, break
VectorType del = queryPoint - newPosition;
for (unsigned int idim = 0; idim < NPointDimension; ++idim)
{
del[idim] /= m_inputPointSetRange[idim];
}
if (del.GetNorm() < 1e-1)
{
break;
}
}
}
if (m_epoch)
{
MeanshiftClusteringFilter<TCoordRep, NPointDimension> ms;
ms.setInputPointSet(m_seedPoints);
ms.setEpoch(--m_epoch);
ms.update();
m_seedPoints = ms._getSeedPoints();
}
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
typename MeanshiftClusteringFilter<TCoordRep, NPointDimension>::VectorSampleType::Pointer
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_getSeedPoints()
{
if (!m_allDone)
{
std::cerr<<"Error: not done.\n";
}
return m_seedPoints;
}
template< typename TCoordRep, unsigned int NPointDimension >
typename MeanshiftClusteringFilter<TCoordRep, NPointDimension>::VectorSampleType::Pointer
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::getCenters()
{
if (!m_allDone)
{
std::cerr<<"Error: not done.\n";
}
return m_centers;
}
template< typename TCoordRep, unsigned int NPointDimension >
void
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_findUniqueCenters()
{
m_centers = VectorSampleType::New();
m_centers->PushBack( m_seedPoints->GetMeasurementVector(0) );
for (unsigned int i = 1 ; i < m_seedPoints->Size() ; ++i )
{
const VectorType& newCenterCandidate = m_seedPoints->GetMeasurementVector(i);
bool IAmNotCloseToAnyExistingCenter = true;
for (unsigned int ii = 0 ; ii < m_centers->Size() ; ++ii )
{
VectorType distVector = newCenterCandidate - m_centers->GetMeasurementVector(ii);
if (distVector.GetNorm() < m_radius )
{
IAmNotCloseToAnyExistingCenter = false;
break;
}
}
if (IAmNotCloseToAnyExistingCenter)
{
m_centers->PushBack( newCenterCandidate );
}
}
m_numberOfModes = m_centers->Size();
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
std::vector<long>
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::getLabelOfPoints()
{
if (!m_allDone)
{
std::cerr<<"Error: not done.\n";
}
return m_labelOfPoints;
}
template< typename TCoordRep, unsigned int NPointDimension >
void
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_findLabelOfPoints()
{
typename TreeGeneratorType::Pointer newTreeGen = TreeGeneratorType::New();
newTreeGen->SetSample( m_centers );
newTreeGen->SetBucketSize( 16 );
newTreeGen->Update();
typename TreeType::Pointer newTree = newTreeGen->GetOutput();
m_labelOfPoints.resize(m_inputPointSet->Size());
// K-Neighbor search
//std::cout << "K-Neighbor search:" << std::endl;
unsigned int numberOfNeighbors = 1;
typename TreeType::InstanceIdentifierVectorType neighbors;
for (unsigned int i = 0 ; i < m_seedPoints->Size() ; ++i )
{
const VectorType& queryPoint = m_seedPoints->GetMeasurementVector(i);
newTree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
m_labelOfPoints[i] = static_cast<long>(neighbors[0]);
}
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_constructSeedPoints()
{
/// Duplicate input points as seed points
m_seedPoints = VectorSampleType::New();
m_seedPoints->Resize(m_inputPointSet->Size() );
for (unsigned int i = 0 ; i < m_inputPointSet->Size() ; ++i )
{
m_seedPoints->SetMeasurementVector( i, m_inputPointSet->GetMeasurementVector(i) );
}
return;
}
}// namespace gth818n
#endif
<commit_msg>Fixed signed/unsigned comparison warning Merge branch 'develop'<commit_after>#ifndef MeanshiftClusteringFilter_hxx_
#define MeanshiftClusteringFilter_hxx_
#include "itkNumericTraits.h"
#include "MeanshiftClusteringFilter.h"
namespace gth818n
{
template< typename TCoordRep, unsigned int NPointDimension >
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::MeanshiftClusteringFilter()
{
m_epoch = 2;
m_inputPointSet = 0;
m_seedPoints = 0;
m_numberOfMSIteration = 100;
m_radius = 3.0;
m_allDone = false;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::update()
{
// //dbg
// std::cout<<"_constructKdTree..."<<std::flush;
// //dbg, end
_constructKdTree();
// //dbg
// std::cout<<"done"<<std::endl<<std::flush;
// //dbg, end
if (!m_seedPoints)
{
_constructSeedPoints();
}
_meanshiftIteration();
_findUniqueCenters();
_findLabelOfPoints();
m_allDone = true;
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::setRadius(RealType rad)
{
if (rad <= 0.0)
{
std::cerr<<"Error: rad should > 0, but got "<<rad<<std::endl;
abort();
}
m_radius = rad;
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::setEpoch(int epoch)
{
if (epoch < 0)
{
std::cerr<<"Error: epoch should >= 0, but got "<<epoch<<std::endl;
abort();
}
m_epoch = epoch;
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_constructKdTree()
{
m_treeGenerator = TreeGeneratorType::New();
m_treeGenerator->SetSample( m_inputPointSet );
m_treeGenerator->SetBucketSize( 16 );
m_treeGenerator->Update();
m_tree = m_treeGenerator->GetOutput();
// VectorType queryPoint;
// queryPoint[0] = 10.0;
// queryPoint[1] = 7.0;
// // K-Neighbor search
// std::cout << "K-Neighbor search:" << std::endl;
// unsigned int numberOfNeighbors = 3;
// typename TreeType::InstanceIdentifierVectorType neighbors;
// m_tree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
// for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
// {
// std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
// }
// // Radius search
// std::cout << "Radius search:" << std::endl;
// double radius = 4.0;
// m_tree->Search( queryPoint, radius, neighbors ) ;
// std::cout << "There are " << neighbors.size() << " neighbors." << std::endl;
// for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
// {
// std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
// }
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_computeInputPointRange()
{
VectorType inputPointSetMin;
inputPointSetMin.Fill(itk::NumericTraits< RealType >::max());
VectorType inputPointSetMax;
inputPointSetMax.Fill(itk::NumericTraits< RealType >::min());
for (long itp = 0; itp < m_inputPointSet->Size(); ++itp)
{
VectorType thisPoint = m_inputPointSet->GetMeasurementVector(itp);
for (unsigned int idim = 0; idim < NPointDimension; ++idim)
{
inputPointSetMin[idim] = inputPointSetMin[idim]<thisPoint[idim]?inputPointSetMin[idim]:thisPoint[idim];
inputPointSetMax[idim] = inputPointSetMax[idim]<thisPoint[idim]?inputPointSetMax[idim]:thisPoint[idim];
}
}
m_inputPointSetRange = inputPointSetMax - inputPointSetMin;
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_meanshiftIteration()
{
VectorType queryPoint;
typename TreeType::InstanceIdentifierVectorType neighbors;
for (long it = 0; it < m_numberOfMSIteration; ++it)
{
for (unsigned int itp = 0; itp < m_seedPoints->Size(); ++itp)
{
queryPoint = m_seedPoints->GetMeasurementVector(itp);
m_tree->Search( queryPoint, m_radius, neighbors ) ;
VectorType newPosition;
newPosition.Fill(0);
for ( unsigned int i = 0 ; i < neighbors.size() ; ++i )
{
newPosition += m_tree->GetMeasurementVector( neighbors[i] );
//std::cout << m_tree->GetMeasurementVector( neighbors[i] ) << std::endl;
}
newPosition /= static_cast<RealType>(neighbors.size());
m_seedPoints->SetMeasurementVector(itp, newPosition);
/// If relative increamental is small enough, break
VectorType del = queryPoint - newPosition;
for (unsigned int idim = 0; idim < NPointDimension; ++idim)
{
del[idim] /= m_inputPointSetRange[idim];
}
if (del.GetNorm() < 1e-1)
{
break;
}
}
}
if (m_epoch)
{
MeanshiftClusteringFilter<TCoordRep, NPointDimension> ms;
ms.setInputPointSet(m_seedPoints);
ms.setEpoch(--m_epoch);
ms.update();
m_seedPoints = ms._getSeedPoints();
}
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
typename MeanshiftClusteringFilter<TCoordRep, NPointDimension>::VectorSampleType::Pointer
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_getSeedPoints()
{
if (!m_allDone)
{
std::cerr<<"Error: not done.\n";
}
return m_seedPoints;
}
template< typename TCoordRep, unsigned int NPointDimension >
typename MeanshiftClusteringFilter<TCoordRep, NPointDimension>::VectorSampleType::Pointer
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::getCenters()
{
if (!m_allDone)
{
std::cerr<<"Error: not done.\n";
}
return m_centers;
}
template< typename TCoordRep, unsigned int NPointDimension >
void
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_findUniqueCenters()
{
m_centers = VectorSampleType::New();
m_centers->PushBack( m_seedPoints->GetMeasurementVector(0) );
for (unsigned int i = 1 ; i < m_seedPoints->Size() ; ++i )
{
const VectorType& newCenterCandidate = m_seedPoints->GetMeasurementVector(i);
bool IAmNotCloseToAnyExistingCenter = true;
for (unsigned int ii = 0 ; ii < m_centers->Size() ; ++ii )
{
VectorType distVector = newCenterCandidate - m_centers->GetMeasurementVector(ii);
if (distVector.GetNorm() < m_radius )
{
IAmNotCloseToAnyExistingCenter = false;
break;
}
}
if (IAmNotCloseToAnyExistingCenter)
{
m_centers->PushBack( newCenterCandidate );
}
}
m_numberOfModes = m_centers->Size();
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
std::vector<long>
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::getLabelOfPoints()
{
if (!m_allDone)
{
std::cerr<<"Error: not done.\n";
}
return m_labelOfPoints;
}
template< typename TCoordRep, unsigned int NPointDimension >
void
MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_findLabelOfPoints()
{
typename TreeGeneratorType::Pointer newTreeGen = TreeGeneratorType::New();
newTreeGen->SetSample( m_centers );
newTreeGen->SetBucketSize( 16 );
newTreeGen->Update();
typename TreeType::Pointer newTree = newTreeGen->GetOutput();
m_labelOfPoints.resize(m_inputPointSet->Size());
// K-Neighbor search
//std::cout << "K-Neighbor search:" << std::endl;
unsigned int numberOfNeighbors = 1;
typename TreeType::InstanceIdentifierVectorType neighbors;
for (unsigned int i = 0 ; i < m_seedPoints->Size() ; ++i )
{
const VectorType& queryPoint = m_seedPoints->GetMeasurementVector(i);
newTree->Search( queryPoint, numberOfNeighbors, neighbors ) ;
m_labelOfPoints[i] = static_cast<long>(neighbors[0]);
}
return;
}
template< typename TCoordRep, unsigned int NPointDimension >
void MeanshiftClusteringFilter<TCoordRep, NPointDimension>::_constructSeedPoints()
{
/// Duplicate input points as seed points
m_seedPoints = VectorSampleType::New();
m_seedPoints->Resize(m_inputPointSet->Size() );
for (unsigned int i = 0 ; i < m_inputPointSet->Size() ; ++i )
{
m_seedPoints->SetMeasurementVector( i, m_inputPointSet->GetMeasurementVector(i) );
}
return;
}
}// namespace gth818n
#endif
<|endoftext|> |
<commit_before>#include "config.h"
#include <iostream>
#include <algorithm>
#include <map>
#include "clotho/utility/log_helper.hpp"
#include "common_commandline.h"
#include "clotho/genetics/qtl_allele.h"
#include "clotho/utility/timer.hpp"
#include "simulate_engine.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
//#include <boost/foreach.hpp>
//
//#include "clotho/powerset/variable_subset_iterator.hpp"
//#include "clotho/genetics/individual_phenotyper.hpp"
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/weighted_mean.hpp>
#include <boost/accumulators/statistics/weighted_median.hpp>
#include <boost/accumulators/statistics/weighted_variance.hpp>
#include "clotho/genetics/fitness_toolkit.hpp"
namespace accum=boost::accumulators;
typedef boost::random::mt19937 rng_type;
typedef qtl_allele allele_type;
typedef boost::property_tree::ptree log_type;
typedef clotho::utility::timer timer_type;
typedef simulate_engine< rng_type, allele_type, log_type, timer_type > simulate_type;
// allele set typedef
typedef typename simulate_type::sequence_type sequence_type;
typedef typename simulate_type::sequence_pointer sequence_pointer;
typedef typename simulate_type::allele_set_type allele_set_type;
// population typedefs
typedef typename simulate_type::individual_type individual_type;
typedef typename simulate_type::population_type population_type;
typedef typename population_type::iterator population_iterator;
typedef std::map< sequence_pointer, unsigned int > ref_map_type;
typedef typename ref_map_type::iterator ref_map_iterator;
typedef std::vector< unsigned int > allele_dist_type;
const string BASE_SEQUENCE_BIAS_K = "base_bias";
const string TRAIT_BLOCK_K = "traits";
const string ALLELE_BLOCK_K = "allele";
const string NEUTRAL_P_K = "neutral.p";
const string SAMPLING_K = "sampling_size";
//const string FITNESS_BLOCK_K = "fitness";
const string QUADRATIC_SCALE_K = "quadratic.scale";
const string CONSTANT_K = "constant";
const string SIZE_K = "size";
const string PAIRWISE_K = "pairwise";
int main( int argc, char ** argv ) {
log_type config;
int res = parse_commandline(argc, argv, config);
if( res ) {
return res;
}
log_type conf_child = ( (config.get_child_optional( CONFIG_BLOCK_K) == boost::none) ? config : config.get_child( CONFIG_BLOCK_K ));
const unsigned int nRep = conf_child.get< unsigned int >( REPEAT_K, 1 );
const unsigned int nGen = conf_child.get< unsigned int >( GEN_BLOCK_K + "." + SIZE_K, 1);
const unsigned int nLog = conf_child.get< unsigned int >( LOG_BLOCK_K + "." + PERIOD_K, -1);
const unsigned int seed = conf_child.get< unsigned int >( RNG_BLOCK_K + "." + SEED_K, 0 );
string out_path = conf_child.get<string>( OUTPUT_K, "");
rng_type rng(seed);
for( unsigned int i = 0; i < nRep; ++i ) {
// change the seed value of the random number generator
rng.discard( 15 );
const unsigned int tmp_seed = rng();
log_type rep_child_conf = conf_child;
rep_child_conf.put( RNG_BLOCK_K + "." + SEED_K, tmp_seed );
simulate_type sim( rep_child_conf );
if( nGen == 0 ) {
fitness_toolkit::getInstance()->tool_configurations( rep_child_conf );
log_type tmp;
tmp.add_child( CONFIG_BLOCK_K, rep_child_conf );
boost::property_tree::write_json( std::cerr, tmp );
}
unsigned int log_period = ((nGen < nLog) ? nGen : nLog);
for( unsigned int j = 0; j < nGen; ++j ) {
sim.simulate();
sim.reset_parent();
if( !(--log_period) ) {
log_type stat_log;
sim.computeStats( stat_log );
// combine simulation log and configuration log into single object
BOOST_FOREACH( auto& upd, sim.getLog() ) {
stat_log.put_child( upd.first, upd.second );
}
sim.clearLog();
// BOOST_FOREACH( auto& upd, config ) {
// stat_log.put_child(upd.first, upd.second );
// }
stat_log.put_child( CONFIG_BLOCK_K, rep_child_conf);
log_period = ((j + log_period < nGen) ? nLog : (nGen - j - 1) );
if( !stat_log.empty() ) {
if( out_path.empty() ) {
boost::property_tree::write_json( std::cout, stat_log );
} else {
std::ostringstream oss;
oss << out_path << "." << i << "." << j << ".json";
boost::property_tree::write_json( oss.str(), stat_log );
}
}
}
}
}
return 0;
}
<commit_msg>Added performance tracking amounts<commit_after>#include "config.h"
#include <iostream>
#include <algorithm>
#include <map>
#include "clotho/utility/log_helper.hpp"
#include "common_commandline.h"
#include "clotho/genetics/qtl_allele.h"
#include "clotho/utility/timer.hpp"
#include "simulate_engine.hpp"
#include <boost/random/mersenne_twister.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
//#include <boost/foreach.hpp>
//
//#include "clotho/powerset/variable_subset_iterator.hpp"
//#include "clotho/genetics/individual_phenotyper.hpp"
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/weighted_mean.hpp>
#include <boost/accumulators/statistics/weighted_median.hpp>
#include <boost/accumulators/statistics/weighted_variance.hpp>
#include "clotho/genetics/fitness_toolkit.hpp"
namespace accum=boost::accumulators;
typedef boost::random::mt19937 rng_type;
typedef qtl_allele allele_type;
typedef boost::property_tree::ptree log_type;
typedef clotho::utility::timer timer_type;
typedef simulate_engine< rng_type, allele_type, log_type, timer_type > simulate_type;
// allele set typedef
typedef typename simulate_type::sequence_type sequence_type;
typedef typename simulate_type::sequence_pointer sequence_pointer;
typedef typename simulate_type::allele_set_type allele_set_type;
// population typedefs
typedef typename simulate_type::individual_type individual_type;
typedef typename simulate_type::population_type population_type;
typedef typename population_type::iterator population_iterator;
typedef std::map< sequence_pointer, unsigned int > ref_map_type;
typedef typename ref_map_type::iterator ref_map_iterator;
typedef std::vector< unsigned int > allele_dist_type;
const string BASE_SEQUENCE_BIAS_K = "base_bias";
const string TRAIT_BLOCK_K = "traits";
const string ALLELE_BLOCK_K = "allele";
const string NEUTRAL_P_K = "neutral.p";
const string SAMPLING_K = "sampling_size";
//const string FITNESS_BLOCK_K = "fitness";
const string QUADRATIC_SCALE_K = "quadratic.scale";
const string CONSTANT_K = "constant";
const string SIZE_K = "size";
const string PAIRWISE_K = "pairwise";
int main( int argc, char ** argv ) {
log_type config;
int res = parse_commandline(argc, argv, config);
if( res ) {
return res;
}
log_type conf_child = ( (config.get_child_optional( CONFIG_BLOCK_K) == boost::none) ? config : config.get_child( CONFIG_BLOCK_K ));
const unsigned int nRep = conf_child.get< unsigned int >( REPEAT_K, 1 );
const unsigned int nGen = conf_child.get< unsigned int >( GEN_BLOCK_K + "." + SIZE_K, 1);
const unsigned int nLog = conf_child.get< unsigned int >( LOG_BLOCK_K + "." + PERIOD_K, -1);
const unsigned int seed = conf_child.get< unsigned int >( RNG_BLOCK_K + "." + SEED_K, 0 );
string out_path = conf_child.get<string>( OUTPUT_K, "");
rng_type rng(seed);
for( unsigned int i = 0; i < nRep; ++i ) {
// change the seed value of the random number generator
rng.discard( 15 );
const unsigned int tmp_seed = rng();
log_type rep_child_conf = conf_child;
rep_child_conf.put( RNG_BLOCK_K + "." + SEED_K, tmp_seed );
simulate_type sim( rep_child_conf );
if( nGen == 0 ) {
fitness_toolkit::getInstance()->tool_configurations( rep_child_conf );
log_type tmp;
tmp.add_child( CONFIG_BLOCK_K, rep_child_conf );
boost::property_tree::write_json( std::cerr, tmp );
continue;
}
unsigned int log_period = ((nGen < nLog) ? nGen : nLog);
log_type sim_times, stat_times;
timer_type rep_time;
for( unsigned int j = 0; j < nGen; ++j ) {
timer_type sim_time;
sim.simulate();
sim_time.stop();
clotho::utility::add_value_array( sim_times, sim_time );
sim.reset_parent();
if( !(--log_period) ) {
timer_type stat_time;
log_type stat_log;
sim.computeStats( stat_log );
// combine simulation log and configuration log into single object
BOOST_FOREACH( auto& upd, sim.getLog() ) {
stat_log.put_child( upd.first, upd.second );
}
sim.clearLog();
// BOOST_FOREACH( auto& upd, config ) {
// stat_log.put_child(upd.first, upd.second );
// }
stat_log.put_child( CONFIG_BLOCK_K, rep_child_conf);
log_period = ((j + log_period < nGen) ? nLog : (nGen - j - 1) );
if( !stat_log.empty() ) {
if( out_path.empty() ) {
boost::property_tree::write_json( std::cout, stat_log );
} else {
std::ostringstream oss;
oss << out_path << "." << i << "." << j << ".json";
boost::property_tree::write_json( oss.str(), stat_log );
}
}
stat_time.stop();
clotho::utility::add_value_array( stat_times, stat_time );
}
}
rep_time.stop();
log_type perform_log;
perform_log.add( "performance.runtime", rep_time.elapsed().count() );
perform_log.put_child( "performance.simulate", sim_times );
perform_log.put_child( "performance.stats", stat_times );
if( out_path.empty() ) {
boost::property_tree::write_json( std::cout, perform_log );
} else {
std::ostringstream oss;
oss << out_path << "." << i << ".performance.json";
boost::property_tree::write_json( oss.str(), perform_log );
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include "inspector_entity.h"
#include "inspectors.h"
struct Inspector_Entity::component
{
struct instance
{
PathNameTagTree _tree;
std::vector<runtime::CHandle<runtime::Component>> _list;
instance();
void setup(const std::vector<runtime::CHandle<runtime::Component>>& list);
void inspect(bool& changed);
};
struct type
{
PathNameTagTree _tree;
PathNameTagTree::iterator _itor;
std::vector<rttr::type*> _list;
type();
void inspect(ImGuiTextFilter& filter, runtime::Entity data);
};
instance _instance;
type _type;
};
Inspector_Entity::component::instance::instance() :
_tree('/', -1)
{ }
void Inspector_Entity::component::instance::setup(const std::vector<runtime::CHandle<runtime::Component>>& list)
{
_list = list;
_tree.reset();
{
size_t i = 0;
for (auto& ptr : _list)
{
auto component = ptr.lock().get();
auto info = rttr::type::get(*component);
auto meta_category = info.get_metadata("Category");
auto meta_id = info.get_metadata("Id");
std::string name = info.get_name();
if (meta_id)
{
name = meta_id.to_string();
}
if (meta_category)
{
std::string category = meta_category.to_string();
name = category + "/" + name;
}
_tree.set(name, i++);
}
}
}
void Inspector_Entity::component::instance::inspect(bool& changed)
{
struct TreeScoped
{
TreeScoped(const char* id) { gui::TreePush(id); }
~TreeScoped() { gui::TreePop(); }
};
bool opened = true;
auto it = _tree.create_iterator();
while (it.steps())
{
while (it.steping())
{
const char* name = it.name().data();
if (it.is_leaf() ? it.tag() < _list.size() : it.tag() > 0)
{
bool remove = false;
if (opened)
{
gui::SetNextTreeNodeOpen(true, ImGuiSetCond_FirstUseEver);
if (gui::CollapsingHeader(name, &opened))
{
gui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 8.0f);
TreeScoped t(name);
gui::PopStyleVar();
if (it.step_in())
{
continue;
}
else
{
rttr::variant componentVar = _list[it.tag()].lock().get();
changed |= inspect_var(componentVar);
}
}
if (!opened && it.is_leaf())
{
opened = remove = true;
}
}
else
{
if (it.step_in())
{
continue;
}
else
{
remove = true;
}
}
if (remove)
{
auto& component_ptr = _list[it.tag()];
auto component = component_ptr.lock().get();
component->get_entity().remove(component_ptr.lock());
}
}
it.step();
}
if (it.step_out())
{
it.step();
}
}
}
Inspector_Entity::component::type::type() :
_tree('/', -1)
{
auto types = rttr::type::get<runtime::Component>().get_derived_classes();
for (auto& info : types)
{
auto meta_category = info.get_metadata("Category");
auto meta_id = info.get_metadata("Id");
std::string name = info.get_name();
if (meta_id)
{
name = meta_id.to_string();
}
if (meta_category)
{
std::string category = meta_category.to_string();
name = category + "/" + name;
}
_tree.set(name, _list.size());
_list.push_back(&info);
}
_tree.setup_iterator(_itor);
}
void Inspector_Entity::component::type::inspect(ImGuiTextFilter& filter, runtime::Entity data)
{
gui::Separator();
std::string path = "<";
if (gui::ButtonEx(path.data(), ImVec2(0, 0), _itor.steps() > 1 ? 0 : ImGuiButtonFlags_Disabled))
{
_itor.step_out();
}
gui::Separator();
if (_itor.step_stack_pop())
{
_itor.step_in();
}
else
{
_itor.step_reset();
}
while (_itor.steping())
{
std::string name = _itor.name();
auto component_type = _list[_itor.tag()];
if (filter.PassFilter(name.c_str()))
{
if (!_itor.is_leaf())
{
name += " >";
}
if (gui::Selectable(name.c_str()))
{
if (_itor.is_leaf())
{
auto cstructor = component_type->get_constructor();
auto c = cstructor.invoke();
auto c_ptr = c.get_value<std::shared_ptr<runtime::Component>>();
if (c_ptr)
data.assign(c_ptr);
gui::CloseCurrentPopup();
}
else
{
_itor.step_stack_push();
}
}
}
_itor.step();
}
}
Inspector_Entity::Inspector_Entity()
: _component(std::make_unique<component>())
{ }
Inspector_Entity::Inspector_Entity(const Inspector_Entity& other)
: _component(std::make_unique<component>())
{ }
Inspector_Entity::~Inspector_Entity()
{
}
bool Inspector_Entity::inspect(rttr::variant& var, bool readOnly, std::function<rttr::variant(const rttr::variant&)> get_metadata)
{
auto data = var.get_value<runtime::Entity>();
if (!data)
return false;
bool changed = false;
{
PropertyLayout propName("Name");
rttr::variant varName = data.to_string();
changed |= inspect_var(varName);
if(changed)
{
data.set_name(varName.to_string());
}
}
_component->_instance.setup(data.all_components());
_component->_instance.inspect(changed);
gui::Separator();
if (gui::Button("+Component"))
{
gui::OpenPopup("ComponentMenu");
}
if (gui::BeginPopup("ComponentMenu"))
{
static ImGuiTextFilter filter;
filter.Draw("Filter", 180);
gui::Separator();
gui::BeginChild("ComponentMenuContent", ImVec2(gui::GetContentRegionAvailWidth(), 200.0f));
_component->_type.inspect(filter, data);
gui::EndChild();
gui::EndPopup();
}
if (changed)
{
var = data;
return true;
}
return false;
}<commit_msg>cleanup<commit_after>#include "inspector_entity.h"
#include "inspectors.h"
struct Inspector_Entity::component
{
struct instance
{
PathNameTagTree _tree;
std::vector<runtime::CHandle<runtime::Component>> _list;
instance();
void setup(const std::vector<runtime::CHandle<runtime::Component>>& list);
void inspect(bool& changed);
};
struct type
{
PathNameTagTree _tree;
PathNameTagTree::iterator _itor;
std::vector<rttr::type> _list;
type();
void inspect(ImGuiTextFilter& filter, runtime::Entity data);
};
instance _instance;
type _type;
};
Inspector_Entity::component::instance::instance() :
_tree('/', -1)
{ }
void Inspector_Entity::component::instance::setup(const std::vector<runtime::CHandle<runtime::Component>>& list)
{
_list = list;
_tree.reset();
{
size_t i = 0;
for (auto& ptr : _list)
{
auto component = ptr.lock().get();
auto info = rttr::type::get(*component);
auto meta_category = info.get_metadata("Category");
auto meta_id = info.get_metadata("Id");
std::string name = info.get_name();
if (meta_id)
{
name = meta_id.to_string();
}
if (meta_category)
{
std::string category = meta_category.to_string();
name = category + "/" + name;
}
_tree.set(name, i++);
}
}
}
void Inspector_Entity::component::instance::inspect(bool& changed)
{
bool opened = true;
auto it = _tree.create_iterator();
while (it.steps())
{
while (it.steping())
{
const char* name = it.name().data();
if (it.is_leaf() ? it.tag() < _list.size() : it.tag() > 0)
{
bool remove = false;
if (opened)
{
gui::SetNextTreeNodeOpen(true, ImGuiSetCond_FirstUseEver);
if (gui::CollapsingHeader(name, &opened))
{
gui::PushStyleVar(ImGuiStyleVar_IndentSpacing, 8.0f);
gui::TreePush(name);
if (it.step_in())
{
continue;
}
else
{
rttr::variant var = _list[it.tag()].lock().get();
changed |= inspect_var(var);
gui::TreePop();
gui::PopStyleVar();
}
}
if (!opened && it.is_leaf())
{
opened = remove = true;
}
}
else
{
if (it.step_in())
{
continue;
}
else
{
remove = true;
}
}
if (remove)
{
auto& component_ptr = _list[it.tag()];
auto component = component_ptr.lock().get();
component->get_entity().remove(component_ptr.lock());
}
}
it.step();
}
if (it.step_out())
{
opened = it.step();
gui::TreePop();
gui::PopStyleVar();
}
}
}
Inspector_Entity::component::type::type() :
_tree('/', -1)
{
auto types = rttr::type::get<runtime::Component>().get_derived_classes();
for (auto& info : types)
{
auto meta_category = info.get_metadata("Category");
auto meta_id = info.get_metadata("Id");
std::string name = info.get_name();
if (meta_id)
{
name = meta_id.to_string();
}
if (meta_category)
{
std::string category = meta_category.to_string();
name = category + "/" + name;
}
_tree.set(name, _list.size());
_list.push_back(info);
}
_tree.setup_iterator(_itor);
}
void Inspector_Entity::component::type::inspect(ImGuiTextFilter& filter, runtime::Entity data)
{
gui::Separator();
std::string path = "<";
if (gui::ButtonEx(path.data(), ImVec2(0, 0), _itor.steps() > 1 ? 0 : ImGuiButtonFlags_Disabled))
{
_itor.step_out();
}
gui::Separator();
if (_itor.step_stack_pop())
{
_itor.step_in();
}
else
{
_itor.step_reset();
}
while (_itor.steping())
{
std::string name = _itor.name();
auto component_type = _list[_itor.tag()];
if (filter.PassFilter(name.c_str()))
{
if (gui::Selectable(name.c_str()))
{
if (_itor.is_leaf())
{
auto cstructor = component_type.get_constructor();
auto c = cstructor.invoke();
auto c_ptr = c.get_value<std::shared_ptr<runtime::Component>>();
if (c_ptr)
data.assign(c_ptr);
gui::CloseCurrentPopup();
}
else
{
_itor.step_stack_push();
}
}
}
_itor.step();
}
}
Inspector_Entity::Inspector_Entity()
: _component(std::make_unique<component>())
{ }
Inspector_Entity::Inspector_Entity(const Inspector_Entity& other)
: _component(std::make_unique<component>())
{ }
Inspector_Entity::~Inspector_Entity()
{
}
bool Inspector_Entity::inspect(rttr::variant& var, bool readOnly, std::function<rttr::variant(const rttr::variant&)> get_metadata)
{
auto data = var.get_value<runtime::Entity>();
if (!data)
return false;
bool changed = false;
{
PropertyLayout propName("Name");
rttr::variant varName = data.to_string();
changed |= inspect_var(varName);
if(changed)
{
data.set_name(varName.to_string());
}
}
_component->_instance.setup(data.all_components());
_component->_instance.inspect(changed);
gui::Separator();
if (gui::Button("+Component"))
{
gui::OpenPopup("ComponentMenu");
}
if (gui::BeginPopup("ComponentMenu"))
{
static ImGuiTextFilter filter;
filter.Draw("Filter", 180);
gui::Separator();
gui::BeginChild("ComponentMenuContent", ImVec2(gui::GetContentRegionAvailWidth(), 200.0f));
_component->_type.inspect(filter, data);
gui::EndChild();
gui::EndPopup();
}
if (changed)
{
var = data;
return true;
}
return false;
}<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited
//
// 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.
//
// Interface header.
#include "entitybrowser.h"
// appleseed.renderer headers.
#include "renderer/api/bsdf.h"
#include "renderer/api/color.h"
#include "renderer/api/edf.h"
#include "renderer/api/environmentedf.h"
#include "renderer/api/environmentshader.h"
#include "renderer/api/material.h"
#include "renderer/api/scene.h"
#include "renderer/api/surfaceshader.h"
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/foreach.h"
using namespace foundation;
using namespace renderer;
using namespace std;
namespace appleseed {
namespace studio {
namespace
{
template <typename EntityContainer>
StringDictionary build_entity_dictionary(const EntityContainer& entities)
{
StringDictionary result;
for (const_each<EntityContainer> i = entities; i; ++i)
result.insert(i->get_name(), i->get_name());
return result;
}
void merge_dictionary(StringDictionary& dest, const StringDictionary& other)
{
for (const_each<StringDictionary> i = other; i; ++i)
dest.insert(i->name(), i->value());
}
}
//
// EntityBrowser<BaseGroup> class implementation.
//
EntityBrowser<BaseGroup>::EntityBrowser(const BaseGroup& base_group)
: m_base_group(base_group)
{
}
StringDictionary EntityBrowser<BaseGroup>::get_entities(const string& type) const
{
if (type == "color")
{
return build_entity_dictionary(m_base_group.colors());
}
else if (type == "texture_instance")
{
return build_entity_dictionary(m_base_group.texture_instances());
}
else
{
return StringDictionary();
}
}
//
// EntityBrowser<Scene> class implementation.
//
EntityBrowser<Scene>::EntityBrowser(const Scene& scene)
: EntityBrowser<BaseGroup>(scene)
, m_scene(scene)
{
}
StringDictionary EntityBrowser<Scene>::get_entities(const string& type) const
{
if (type == "environment_edf")
{
return build_entity_dictionary(m_scene.environment_edfs());
}
else if (type == "environment_shader")
{
return build_entity_dictionary(m_scene.environment_shaders());
}
else
{
return EntityBrowser<BaseGroup>::get_entities(type);
}
}
//
// EntityBrowser<Assembly> class implementation.
//
EntityBrowser<Assembly>::EntityBrowser(const Assembly& assembly)
: EntityBrowser<BaseGroup>(assembly)
, m_assembly(assembly)
{
}
StringDictionary EntityBrowser<Assembly>::get_entities(const string& type) const
{
return get_entities(m_assembly, type);
}
StringDictionary EntityBrowser<Assembly>::get_entities(const Assembly& assembly, const string& type) const
{
StringDictionary entities;
if (type == "bsdf")
{
entities = build_entity_dictionary(assembly.bsdfs());
}
else if (type == "edf")
{
entities = build_entity_dictionary(assembly.edfs());
}
else if (type == "material")
{
entities = build_entity_dictionary(assembly.materials());
}
else if (type == "surface_shader")
{
entities = build_entity_dictionary(assembly.surface_shaders());
}
else
{
return EntityBrowser<BaseGroup>::get_entities(type);
}
if (assembly.get_parent())
{
const Assembly& parent = *static_cast<Assembly*>(assembly.get_parent());
merge_dictionary(entities, get_entities(parent, type));
}
return entities;
}
} // namespace studio
} // namespace appleseed
<commit_msg>fixed regression introduced with support for nested assemblies: appleseed.studio would crash when browsing for an entity (e.g. a BSDF) during the edition of another entity (e.g. a material).<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited
//
// 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.
//
// Interface header.
#include "entitybrowser.h"
// appleseed.renderer headers.
#include "renderer/api/bsdf.h"
#include "renderer/api/color.h"
#include "renderer/api/edf.h"
#include "renderer/api/environmentedf.h"
#include "renderer/api/environmentshader.h"
#include "renderer/api/material.h"
#include "renderer/api/scene.h"
#include "renderer/api/surfaceshader.h"
// appleseed.foundation headers.
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/foreach.h"
using namespace foundation;
using namespace renderer;
using namespace std;
namespace appleseed {
namespace studio {
namespace
{
template <typename EntityContainer>
StringDictionary build_entity_dictionary(const EntityContainer& entities)
{
StringDictionary result;
for (const_each<EntityContainer> i = entities; i; ++i)
result.insert(i->get_name(), i->get_name());
return result;
}
void merge_dictionary(StringDictionary& dest, const StringDictionary& other)
{
for (const_each<StringDictionary> i = other; i; ++i)
dest.insert(i->name(), i->value());
}
}
//
// EntityBrowser<BaseGroup> class implementation.
//
EntityBrowser<BaseGroup>::EntityBrowser(const BaseGroup& base_group)
: m_base_group(base_group)
{
}
StringDictionary EntityBrowser<BaseGroup>::get_entities(const string& type) const
{
if (type == "color")
{
return build_entity_dictionary(m_base_group.colors());
}
else if (type == "texture_instance")
{
return build_entity_dictionary(m_base_group.texture_instances());
}
else
{
return StringDictionary();
}
}
//
// EntityBrowser<Scene> class implementation.
//
EntityBrowser<Scene>::EntityBrowser(const Scene& scene)
: EntityBrowser<BaseGroup>(scene)
, m_scene(scene)
{
}
StringDictionary EntityBrowser<Scene>::get_entities(const string& type) const
{
if (type == "environment_edf")
{
return build_entity_dictionary(m_scene.environment_edfs());
}
else if (type == "environment_shader")
{
return build_entity_dictionary(m_scene.environment_shaders());
}
else
{
return EntityBrowser<BaseGroup>::get_entities(type);
}
}
//
// EntityBrowser<Assembly> class implementation.
//
EntityBrowser<Assembly>::EntityBrowser(const Assembly& assembly)
: EntityBrowser<BaseGroup>(assembly)
, m_assembly(assembly)
{
}
StringDictionary EntityBrowser<Assembly>::get_entities(const string& type) const
{
return get_entities(m_assembly, type);
}
StringDictionary EntityBrowser<Assembly>::get_entities(const Assembly& assembly, const string& type) const
{
StringDictionary entities;
if (type == "bsdf")
{
entities = build_entity_dictionary(assembly.bsdfs());
}
else if (type == "edf")
{
entities = build_entity_dictionary(assembly.edfs());
}
else if (type == "material")
{
entities = build_entity_dictionary(assembly.materials());
}
else if (type == "surface_shader")
{
entities = build_entity_dictionary(assembly.surface_shaders());
}
else
{
return EntityBrowser<BaseGroup>::get_entities(type);
}
if (assembly.get_parent())
{
const Assembly* parent = dynamic_cast<const Assembly*>(assembly.get_parent());
if (parent)
merge_dictionary(entities, get_entities(*parent, type));
}
return entities;
}
} // namespace studio
} // namespace appleseed
<|endoftext|> |
<commit_before>// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "client/windows/crash_generation/minidump_generator.h"
#include <cassert>
#include "client/windows/common/auto_critical_section.h"
#include "common/windows/guid_string.h"
using std::wstring;
namespace google_breakpad {
MinidumpGenerator::MinidumpGenerator(const wstring& dump_path)
: dbghelp_module_(NULL),
rpcrt4_module_(NULL),
dump_path_(dump_path),
write_dump_(NULL),
create_uuid_(NULL) {
InitializeCriticalSection(&module_load_sync_);
InitializeCriticalSection(&get_proc_address_sync_);
}
MinidumpGenerator::~MinidumpGenerator() {
if (dbghelp_module_) {
FreeLibrary(dbghelp_module_);
}
if (rpcrt4_module_) {
FreeLibrary(rpcrt4_module_);
}
DeleteCriticalSection(&get_proc_address_sync_);
DeleteCriticalSection(&module_load_sync_);
}
bool MinidumpGenerator::WriteMinidump(HANDLE process_handle,
DWORD process_id,
DWORD thread_id,
DWORD requesting_thread_id,
EXCEPTION_POINTERS* exception_pointers,
MDRawAssertionInfo* assert_info,
MINIDUMP_TYPE dump_type,
bool is_client_pointers,
wstring* dump_path) {
MiniDumpWriteDumpType write_dump = GetWriteDump();
if (!write_dump) {
return false;
}
wstring dump_file_path;
if (!GenerateDumpFilePath(&dump_file_path)) {
return false;
}
HANDLE dump_file = CreateFile(dump_file_path.c_str(),
GENERIC_WRITE,
0,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (dump_file == INVALID_HANDLE_VALUE) {
return false;
}
MINIDUMP_EXCEPTION_INFORMATION* dump_exception_pointers = NULL;
MINIDUMP_EXCEPTION_INFORMATION dump_exception_info;
// Setup the exception information object only if it's a dump
// due to an exception.
if (exception_pointers) {
dump_exception_pointers = &dump_exception_info;
dump_exception_info.ThreadId = thread_id;
dump_exception_info.ExceptionPointers = exception_pointers;
dump_exception_info.ClientPointers = is_client_pointers;
}
// Add an MDRawBreakpadInfo stream to the minidump, to provide additional
// information about the exception handler to the Breakpad processor.
// The information will help the processor determine which threads are
// relevant. The Breakpad processor does not require this information but
// can function better with Breakpad-generated dumps when it is present.
// The native debugger is not harmed by the presence of this information.
MDRawBreakpadInfo breakpad_info;
breakpad_info.validity = MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID |
MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID;
breakpad_info.dump_thread_id = thread_id;
breakpad_info.requesting_thread_id = requesting_thread_id;
// Leave room in user_stream_array for a possible assertion info stream.
MINIDUMP_USER_STREAM user_stream_array[2];
user_stream_array[0].Type = MD_BREAKPAD_INFO_STREAM;
user_stream_array[0].BufferSize = sizeof(breakpad_info);
user_stream_array[0].Buffer = &breakpad_info;
MINIDUMP_USER_STREAM_INFORMATION user_streams;
user_streams.UserStreamCount = 1;
user_streams.UserStreamArray = user_stream_array;
MDRawAssertionInfo* actual_assert_info = assert_info;
MDRawAssertionInfo client_assert_info = {0};
if (assert_info) {
// If the assertion info object lives in the client process,
// read the memory of the client process.
if (is_client_pointers) {
SIZE_T bytes_read = 0;
if (!ReadProcessMemory(process_handle,
assert_info,
&client_assert_info,
sizeof(client_assert_info),
&bytes_read)) {
CloseHandle(dump_file);
return false;
}
if (bytes_read != sizeof(client_assert_info)) {
CloseHandle(dump_file);
return false;
}
actual_assert_info = &client_assert_info;
}
user_stream_array[1].Type = MD_ASSERTION_INFO_STREAM;
user_stream_array[1].BufferSize = sizeof(MDRawAssertionInfo);
user_stream_array[1].Buffer = actual_assert_info;
++user_streams.UserStreamCount;
}
bool result = write_dump(process_handle,
process_id,
dump_file,
dump_type,
exception_pointers ? &dump_exception_info : NULL,
&user_streams,
NULL) != FALSE;
CloseHandle(dump_file);
// Store the path of the dump file in the out parameter if dump generation
// succeeded.
if (result && dump_path) {
*dump_path = dump_file_path;
}
return result;
}
HMODULE MinidumpGenerator::GetDbghelpModule() {
AutoCriticalSection lock(&module_load_sync_);
if (!dbghelp_module_) {
dbghelp_module_ = LoadLibrary(TEXT("dbghelp.dll"));
}
return dbghelp_module_;
}
MinidumpGenerator::MiniDumpWriteDumpType MinidumpGenerator::GetWriteDump() {
AutoCriticalSection lock(&get_proc_address_sync_);
if (!write_dump_) {
HMODULE module = GetDbghelpModule();
if (module) {
FARPROC proc = GetProcAddress(module, "MiniDumpWriteDump");
write_dump_ = reinterpret_cast<MiniDumpWriteDumpType>(proc);
}
}
return write_dump_;
}
HMODULE MinidumpGenerator::GetRpcrt4Module() {
AutoCriticalSection lock(&module_load_sync_);
if (!rpcrt4_module_) {
rpcrt4_module_ = LoadLibrary(TEXT("rpcrt4.dll"));
}
return rpcrt4_module_;
}
MinidumpGenerator::UuidCreateType MinidumpGenerator::GetCreateUuid() {
AutoCriticalSection lock(&module_load_sync_);
if (!create_uuid_) {
HMODULE module = GetRpcrt4Module();
if (module) {
FARPROC proc = GetProcAddress(module, "UuidCreate");
create_uuid_ = reinterpret_cast<UuidCreateType>(proc);
}
}
return create_uuid_;
}
bool MinidumpGenerator::GenerateDumpFilePath(wstring* file_path) {
UUID id = {0};
UuidCreateType create_uuid = GetCreateUuid();
if(!create_uuid) {
return false;
}
create_uuid(&id);
wstring id_str = GUIDString::GUIDToWString(&id);
*file_path = dump_path_ + TEXT("\\") + id_str + TEXT(".dmp");
return true;
}
} // namespace google_breakpad
<commit_msg><commit_after>// Copyright (c) 2008, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "client/windows/crash_generation/minidump_generator.h"
#include <cassert>
#include "client/windows/common/auto_critical_section.h"
#include "common/windows/guid_string.h"
using std::wstring;
namespace google_breakpad {
MinidumpGenerator::MinidumpGenerator(const wstring& dump_path)
: dbghelp_module_(NULL),
rpcrt4_module_(NULL),
dump_path_(dump_path),
write_dump_(NULL),
create_uuid_(NULL) {
InitializeCriticalSection(&module_load_sync_);
InitializeCriticalSection(&get_proc_address_sync_);
}
MinidumpGenerator::~MinidumpGenerator() {
if (dbghelp_module_) {
FreeLibrary(dbghelp_module_);
}
if (rpcrt4_module_) {
FreeLibrary(rpcrt4_module_);
}
DeleteCriticalSection(&get_proc_address_sync_);
DeleteCriticalSection(&module_load_sync_);
}
bool MinidumpGenerator::WriteMinidump(HANDLE process_handle,
DWORD process_id,
DWORD thread_id,
DWORD requesting_thread_id,
EXCEPTION_POINTERS* exception_pointers,
MDRawAssertionInfo* assert_info,
MINIDUMP_TYPE dump_type,
bool is_client_pointers,
wstring* dump_path) {
MiniDumpWriteDumpType write_dump = GetWriteDump();
if (!write_dump) {
return false;
}
wstring dump_file_path;
if (!GenerateDumpFilePath(&dump_file_path)) {
return false;
}
HANDLE dump_file = CreateFile(dump_file_path.c_str(),
GENERIC_WRITE,
0,
NULL,
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (dump_file == INVALID_HANDLE_VALUE) {
return false;
}
MINIDUMP_EXCEPTION_INFORMATION* dump_exception_pointers = NULL;
MINIDUMP_EXCEPTION_INFORMATION dump_exception_info;
// Setup the exception information object only if it's a dump
// due to an exception.
if (exception_pointers) {
dump_exception_pointers = &dump_exception_info;
dump_exception_info.ThreadId = thread_id;
dump_exception_info.ExceptionPointers = exception_pointers;
dump_exception_info.ClientPointers = is_client_pointers;
}
// Add an MDRawBreakpadInfo stream to the minidump, to provide additional
// information about the exception handler to the Breakpad processor.
// The information will help the processor determine which threads are
// relevant. The Breakpad processor does not require this information but
// can function better with Breakpad-generated dumps when it is present.
// The native debugger is not harmed by the presence of this information.
MDRawBreakpadInfo breakpad_info = {0};
if (!is_client_pointers) {
// Set the dump thread id and requesting thread id only in case of
// in-process dump generation.
breakpad_info.validity = MD_BREAKPAD_INFO_VALID_DUMP_THREAD_ID |
MD_BREAKPAD_INFO_VALID_REQUESTING_THREAD_ID;
breakpad_info.dump_thread_id = thread_id;
breakpad_info.requesting_thread_id = requesting_thread_id;
}
// Leave room in user_stream_array for a possible assertion info stream.
MINIDUMP_USER_STREAM user_stream_array[2];
user_stream_array[0].Type = MD_BREAKPAD_INFO_STREAM;
user_stream_array[0].BufferSize = sizeof(breakpad_info);
user_stream_array[0].Buffer = &breakpad_info;
MINIDUMP_USER_STREAM_INFORMATION user_streams;
user_streams.UserStreamCount = 1;
user_streams.UserStreamArray = user_stream_array;
MDRawAssertionInfo* actual_assert_info = assert_info;
MDRawAssertionInfo client_assert_info = {0};
if (assert_info) {
// If the assertion info object lives in the client process,
// read the memory of the client process.
if (is_client_pointers) {
SIZE_T bytes_read = 0;
if (!ReadProcessMemory(process_handle,
assert_info,
&client_assert_info,
sizeof(client_assert_info),
&bytes_read)) {
CloseHandle(dump_file);
return false;
}
if (bytes_read != sizeof(client_assert_info)) {
CloseHandle(dump_file);
return false;
}
actual_assert_info = &client_assert_info;
}
user_stream_array[1].Type = MD_ASSERTION_INFO_STREAM;
user_stream_array[1].BufferSize = sizeof(MDRawAssertionInfo);
user_stream_array[1].Buffer = actual_assert_info;
++user_streams.UserStreamCount;
}
bool result = write_dump(process_handle,
process_id,
dump_file,
dump_type,
exception_pointers ? &dump_exception_info : NULL,
&user_streams,
NULL) != FALSE;
CloseHandle(dump_file);
// Store the path of the dump file in the out parameter if dump generation
// succeeded.
if (result && dump_path) {
*dump_path = dump_file_path;
}
return result;
}
HMODULE MinidumpGenerator::GetDbghelpModule() {
AutoCriticalSection lock(&module_load_sync_);
if (!dbghelp_module_) {
dbghelp_module_ = LoadLibrary(TEXT("dbghelp.dll"));
}
return dbghelp_module_;
}
MinidumpGenerator::MiniDumpWriteDumpType MinidumpGenerator::GetWriteDump() {
AutoCriticalSection lock(&get_proc_address_sync_);
if (!write_dump_) {
HMODULE module = GetDbghelpModule();
if (module) {
FARPROC proc = GetProcAddress(module, "MiniDumpWriteDump");
write_dump_ = reinterpret_cast<MiniDumpWriteDumpType>(proc);
}
}
return write_dump_;
}
HMODULE MinidumpGenerator::GetRpcrt4Module() {
AutoCriticalSection lock(&module_load_sync_);
if (!rpcrt4_module_) {
rpcrt4_module_ = LoadLibrary(TEXT("rpcrt4.dll"));
}
return rpcrt4_module_;
}
MinidumpGenerator::UuidCreateType MinidumpGenerator::GetCreateUuid() {
AutoCriticalSection lock(&module_load_sync_);
if (!create_uuid_) {
HMODULE module = GetRpcrt4Module();
if (module) {
FARPROC proc = GetProcAddress(module, "UuidCreate");
create_uuid_ = reinterpret_cast<UuidCreateType>(proc);
}
}
return create_uuid_;
}
bool MinidumpGenerator::GenerateDumpFilePath(wstring* file_path) {
UUID id = {0};
UuidCreateType create_uuid = GetCreateUuid();
if(!create_uuid) {
return false;
}
create_uuid(&id);
wstring id_str = GUIDString::GUIDToWString(&id);
*file_path = dump_path_ + TEXT("\\") + id_str + TEXT(".dmp");
return true;
}
} // namespace google_breakpad
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include "Communicator.h"
#include "Message.h"
#include "Resource.h"
#include "GenericResource.h"
#include "CycException.h"
#include <string>
#include <vector>
using namespace std;
class TrackerMessage : public Message {
public:
TrackerMessage(Communicator* originator) : Message(originator) { }
vector<string> dest_list_;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class TestCommunicator : public Communicator {
public:
TestCommunicator(string name) {
msg_ = new TrackerMessage(this);
name_ = name;
stop_at_return_ = true;
flip_at_receive_ = false;
flip_down_to_up_ = false;
forget_set_dest_ = false;
down_up_count_ = 0;
}
~TestCommunicator() {
delete msg_;
}
Communicator* parent_;
TrackerMessage* msg_;
string name_;
bool stop_at_return_, flip_at_receive_, forget_set_dest_;
bool flip_down_to_up_;
int down_up_count_;
void startMessage() {
msg_->dest_list_.push_back(name_);
msg_->setNextDest(parent_);
msg_->sendOn();
}
private:
void receiveMessage(msg_ptr msg) {
boost::intrusive_ptr<TrackerMessage> ptr;
ptr = boost::intrusive_ptr<TrackerMessage>(dynamic_cast<TrackerMessage*>(msg.get()));
ptr->dest_list_.push_back(name_);
if (stop_at_return_ && this == msg->sender()) {
return;
} else if (flip_at_receive_) {
msg->setDir(DOWN_MSG);
} else if (flip_down_to_up_) {
int max_num_flips = 2;
if (msg->dir() == DOWN_MSG && down_up_count_ < max_num_flips) {
msg->setDir(UP_MSG);
down_up_count_++;
}
}
if ( !forget_set_dest_ ) {
msg->setNextDest(parent_);
}
msg->sendOn();
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class MessagePassingTest : public ::testing::Test {
protected:
TestCommunicator* comm1;
TestCommunicator* comm2;
TestCommunicator* comm3;
TestCommunicator* comm4;
virtual void SetUp(){
comm1 = new TestCommunicator("comm1");
comm2 = new TestCommunicator("comm2");
comm3 = new TestCommunicator("comm3");
comm4 = new TestCommunicator("comm4");
comm1->parent_ = comm2;
comm2->parent_ = comm3;
comm3->parent_ = comm4;
comm4->flip_at_receive_ = true;
};
virtual void TearDown() {
delete comm1;
delete comm2;
delete comm3;
delete comm4;
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, CleanThrough) {
ASSERT_NO_THROW(comm1->startMessage());
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 7;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm1");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, PassBeyondOrigin) {
comm1->stop_at_return_ = false;
ASSERT_THROW(comm1->startMessage(), CycException);
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 7;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm1");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, ForgetToSetDest) {
comm3->forget_set_dest_ = true;
ASSERT_THROW(comm1->startMessage(), CycException);
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 3;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, SendToSelf) {
comm3->parent_ = comm3;
ASSERT_THROW(comm1->startMessage(), CycException);
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 3;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, YoYo) {
comm2->flip_down_to_up_ = true;
ASSERT_NO_THROW(comm1->startMessage());
vector<string> stops = comm1->msg_->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 15;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm3");
EXPECT_EQ(stops[7], "comm4");
EXPECT_EQ(stops[8], "comm3");
EXPECT_EQ(stops[9], "comm2");
EXPECT_EQ(stops[10], "comm3");
EXPECT_EQ(stops[11], "comm4");
EXPECT_EQ(stops[12], "comm3");
EXPECT_EQ(stops[13], "comm2");
EXPECT_EQ(stops[14], "comm1");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - -Message Public Interface Testing - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class MessagePublicInterfaceTest : public ::testing::Test {
protected:
Resource* resource;
double quantity1, quantity2;
TestCommunicator* comm1;
msg_ptr msg1;
virtual void SetUp(){
quantity1 = 1.0;
quantity2 = 2.0;
resource = new GenericResource("kg", "bananas", quantity1);
comm1 = new TestCommunicator("comm1");
msg1 = msg_ptr(new Message(comm1));
};
virtual void TearDown() {
delete comm1;
delete resource;
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - -Constructors and Cloning - - - - - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, DISABLED_ConstructorOne) {
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, DISABLED_ConstructorTwo) {
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, DISABLED_ConstructorThree) {
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, Cloning) {
msg1->setResource(resource);
msg_ptr msg2 = msg1->clone();
// check proper cloning of message members
EXPECT_EQ(msg1->sender(), msg2->sender());
// check proper cloning of message's resource
Resource* resource2 = msg2->resource();
resource2->setQuantity(quantity2);
ASSERT_DOUBLE_EQ(msg2->resource()->quantity(), quantity2);
ASSERT_DOUBLE_EQ(msg2->resource()->quantity(), quantity2);
ASSERT_NE(resource, msg1->resource());
ASSERT_NE(resource, resource2);
EXPECT_DOUBLE_EQ(resource->quantity(), quantity1);
EXPECT_DOUBLE_EQ(resource2->quantity(), quantity2);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - - Getters and Setters - - - - - - - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, GetSetResource) {
ASSERT_DOUBLE_EQ(resource->quantity(), quantity1);
msg1->setResource(resource);
ASSERT_NE(resource, msg1->resource());
msg1->resource()->setQuantity(quantity2);
ASSERT_DOUBLE_EQ(resource->quantity(), quantity1);
ASSERT_DOUBLE_EQ(msg1->resource()->quantity(), quantity2);
}
<commit_msg>fixed Message tests to use the new intrusive pointer paradigm (closes #6).<commit_after>#include <gtest/gtest.h>
#include "Communicator.h"
#include "Message.h"
#include "Resource.h"
#include "GenericResource.h"
#include "CycException.h"
#include <string>
#include <vector>
using namespace std;
class TrackerMessage : public Message {
public:
TrackerMessage(Communicator* originator) : Message(originator) { }
vector<string> dest_list_;
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class TestCommunicator : public Communicator {
public:
TestCommunicator(string name) {
msg_ = msg_ptr(new TrackerMessage(this));
name_ = name;
stop_at_return_ = true;
flip_at_receive_ = false;
flip_down_to_up_ = false;
forget_set_dest_ = false;
down_up_count_ = 0;
}
~TestCommunicator() { }
Communicator* parent_;
msg_ptr msg_;
string name_;
bool stop_at_return_, flip_at_receive_, forget_set_dest_;
bool flip_down_to_up_;
int down_up_count_;
void startMessage() {
dynamic_cast<TrackerMessage*>(msg_.get())->dest_list_.push_back(name_);
msg_->setNextDest(parent_);
msg_->sendOn();
}
private:
void receiveMessage(msg_ptr msg) {
boost::intrusive_ptr<TrackerMessage> ptr;
ptr = boost::intrusive_ptr<TrackerMessage>(dynamic_cast<TrackerMessage*>(msg.get()));
ptr->dest_list_.push_back(name_);
if (stop_at_return_ && this == msg->sender()) {
return;
} else if (flip_at_receive_) {
msg->setDir(DOWN_MSG);
} else if (flip_down_to_up_) {
int max_num_flips = 2;
if (msg->dir() == DOWN_MSG && down_up_count_ < max_num_flips) {
msg->setDir(UP_MSG);
down_up_count_++;
}
}
if ( !forget_set_dest_ ) {
msg->setNextDest(parent_);
}
msg->sendOn();
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class MessagePassingTest : public ::testing::Test {
protected:
TestCommunicator* comm1;
TestCommunicator* comm2;
TestCommunicator* comm3;
TestCommunicator* comm4;
virtual void SetUp(){
comm1 = new TestCommunicator("comm1");
comm2 = new TestCommunicator("comm2");
comm3 = new TestCommunicator("comm3");
comm4 = new TestCommunicator("comm4");
comm1->parent_ = comm2;
comm2->parent_ = comm3;
comm3->parent_ = comm4;
comm4->flip_at_receive_ = true;
};
virtual void TearDown() {
delete comm1;
delete comm2;
delete comm3;
delete comm4;
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, CleanThrough) {
ASSERT_NO_THROW(comm1->startMessage());
vector<string> stops = dynamic_cast<TrackerMessage*>(comm1->msg_.get())->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 7;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm1");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, PassBeyondOrigin) {
comm1->stop_at_return_ = false;
ASSERT_THROW(comm1->startMessage(), CycException);
vector<string> stops = dynamic_cast<TrackerMessage*>(comm1->msg_.get())->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 7;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm1");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, ForgetToSetDest) {
comm3->forget_set_dest_ = true;
ASSERT_THROW(comm1->startMessage(), CycException);
vector<string> stops = dynamic_cast<TrackerMessage*>(comm1->msg_.get())->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 3;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, SendToSelf) {
comm3->parent_ = comm3;
ASSERT_THROW(comm1->startMessage(), CycException);
vector<string> stops = dynamic_cast<TrackerMessage*>(comm1->msg_.get())->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 3;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePassingTest, YoYo) {
comm2->flip_down_to_up_ = true;
ASSERT_NO_THROW(comm1->startMessage());
vector<string> stops = dynamic_cast<TrackerMessage*>(comm1->msg_.get())->dest_list_;
int num_stops = stops.size();
int expected_num_stops = 15;
ASSERT_EQ(num_stops, expected_num_stops);
EXPECT_EQ(stops[0], "comm1");
EXPECT_EQ(stops[1], "comm2");
EXPECT_EQ(stops[2], "comm3");
EXPECT_EQ(stops[3], "comm4");
EXPECT_EQ(stops[4], "comm3");
EXPECT_EQ(stops[5], "comm2");
EXPECT_EQ(stops[6], "comm3");
EXPECT_EQ(stops[7], "comm4");
EXPECT_EQ(stops[8], "comm3");
EXPECT_EQ(stops[9], "comm2");
EXPECT_EQ(stops[10], "comm3");
EXPECT_EQ(stops[11], "comm4");
EXPECT_EQ(stops[12], "comm3");
EXPECT_EQ(stops[13], "comm2");
EXPECT_EQ(stops[14], "comm1");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - -Message Public Interface Testing - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
class MessagePublicInterfaceTest : public ::testing::Test {
protected:
Resource* resource;
double quantity1, quantity2;
TestCommunicator* comm1;
msg_ptr msg1;
virtual void SetUp(){
quantity1 = 1.0;
quantity2 = 2.0;
resource = new GenericResource("kg", "bananas", quantity1);
comm1 = new TestCommunicator("comm1");
msg1 = msg_ptr(new Message(comm1));
};
virtual void TearDown() {
delete comm1;
delete resource;
}
};
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - -Constructors and Cloning - - - - - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, DISABLED_ConstructorOne) {
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, DISABLED_ConstructorTwo) {
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, DISABLED_ConstructorThree) {
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, Cloning) {
msg1->setResource(resource);
msg_ptr msg2 = msg1->clone();
// check proper cloning of message members
EXPECT_EQ(msg1->sender(), msg2->sender());
// check proper cloning of message's resource
Resource* resource2 = msg2->resource();
resource2->setQuantity(quantity2);
ASSERT_DOUBLE_EQ(msg2->resource()->quantity(), quantity2);
ASSERT_DOUBLE_EQ(msg2->resource()->quantity(), quantity2);
ASSERT_NE(resource, msg1->resource());
ASSERT_NE(resource, resource2);
EXPECT_DOUBLE_EQ(resource->quantity(), quantity1);
EXPECT_DOUBLE_EQ(resource2->quantity(), quantity2);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//- - - - - - - - - Getters and Setters - - - - - - - - - - - - - - - - - -
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TEST_F(MessagePublicInterfaceTest, GetSetResource) {
ASSERT_DOUBLE_EQ(resource->quantity(), quantity1);
msg1->setResource(resource);
ASSERT_NE(resource, msg1->resource());
msg1->resource()->setQuantity(quantity2);
ASSERT_DOUBLE_EQ(resource->quantity(), quantity1);
ASSERT_DOUBLE_EQ(msg1->resource()->quantity(), quantity2);
}
<|endoftext|> |
<commit_before>#include "BetaRand.h"
#include "../discrete/BernoulliRand.h"
BetaRand::BetaRand(double shape1, double shape2)
{
setParameters(shape1, shape2);
}
std::string BetaRand::name()
{
return "Beta(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")";
}
void BetaRand::setParameters(double shape1, double shape2)
{
alpha = shape1;
if (alpha <= 0)
alpha = 1.0;
X.setParameters(alpha, 1);
beta = shape2;
if (beta <= 0)
beta = 1.0;
Y.setParameters(beta, 1);
if (alpha + beta > 30)
{
/// we use log(Gamma(x)) in order to avoid too big numbers
double logGammaX = std::log(X.getInverseGammaFunction());
double logGammaY = std::log(Y.getInverseGammaFunction());
pdfCoef = std::lgamma(alpha + beta) + logGammaX + logGammaY;
pdfCoef = std::exp(pdfCoef);
}
else {
pdfCoef = std::tgamma(alpha + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
}
setVariateConstants();
}
void BetaRand::setAlpha(double shape1)
{
alpha = shape1;
if (alpha <= 0)
alpha = 1.0;
X.setParameters(alpha, 1);
pdfCoef = std::tgamma(alpha + Y.getShape()) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
setVariateConstants();
}
void BetaRand::setBeta(double shape2)
{
beta = shape2;
if (beta <= 0)
beta = 1.0;
Y.setParameters(beta, 1);
pdfCoef = std::tgamma(X.getShape() + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
setVariateConstants();
}
double BetaRand::f(double x) const
{
if (x < 0 || x > 1)
return 0;
if (RandMath::areEqual(alpha, beta))
return pdfCoef * std::pow(x - x * x, alpha - 1);
double rv = std::pow(x, alpha - 1);
rv *= std::pow(1 - x, beta - 1);
return pdfCoef * rv;
}
double BetaRand::F(double x) const
{
if (x <= 0)
return 0;
if (x >= 1)
return 1;
return pdfCoef * RandMath::incompleteBetaFun(x, alpha, beta);
}
double BetaRand::variateArcsine() const
{
double x = std::sin(UniformRand::variate(-M_PI, M_PI));
return x * x;
}
double BetaRand::variateForSmallEqualParameters() const
{
int iter = 0;
do {
double u1 = UniformRand::standardVariate();
double u2 = UniformRand::standardVariate();
if (u2 <= std::pow(4 * u1 * (1 - u1), alpha - 1))
return u1;
} while (++iter <= 1e9); /// one billion should be enough
return NAN; /// fail
}
double BetaRand::variateForLargeEqualParameters() const
{
int iter = 0;
do {
double n = N.variate();
if (n < 0 || n > 1)
continue;
double u = UniformRand::standardVariate();
if (u < N.f(n) / (variateCoef * f(n)))
return n;
} while (++iter <= 1e9); /// one billion should be enough
return NAN; /// fail
}
double BetaRand::variateForDifferentParameters() const
{
double x = X.variate();
return x / (x + Y.variate());
}
void BetaRand::setVariateConstants()
{
/// We need to storage variate coefficient only if alpha = beta and large enough
if (alpha > edgeForGenerators && RandMath::areEqual(alpha, beta))
{
double t = 1.0 / (alpha + alpha + 1);
variateCoef = M_E * std::sqrt(0.5 * M_PI * M_E * t);
variateCoef *= std::pow(0.25 - 0.75 * t, alpha - 1);
variateCoef *= pdfCoef; /// /= Beta(alpha, alpha)
N.setMean(0.5);
N.setVariance(0.25 * t);
}
}
double BetaRand::variate() const
{
if (RandMath::areEqual(alpha, beta) && alpha == 0.5)
return variateArcsine();
if (!RandMath::areEqual(alpha, beta) || alpha < 1)
return variateForDifferentParameters();
if (alpha == 1)
return UniformRand::standardVariate();
if (alpha <= edgeForGenerators)
return variateForSmallEqualParameters();
return variateForLargeEqualParameters();
}
void BetaRand::sample(QVector<double> &outputData) const
{
if (RandMath::areEqual(alpha, beta) && alpha == 0.5) {
for (double &var : outputData)
var = variateArcsine();
}
else if (!RandMath::areEqual(alpha, beta) || alpha < 1) {
for (double &var : outputData)
var = variateForDifferentParameters();
}
else if (alpha == 1) {
for (double &var : outputData)
var = UniformRand::standardVariate();
}
else if (alpha <= edgeForGenerators) {
for (double &var : outputData)
var = variateForSmallEqualParameters();
}
else {
for (double &var : outputData)
var = variateForLargeEqualParameters();
}
}
double BetaRand::Mean() const
{
return alpha / (alpha + beta);
}
double BetaRand::Variance() const
{
double denominator = alpha + beta;
denominator *= denominator * (denominator + 1);
return alpha * beta / denominator;
}
double BetaRand::Quantile(double p) const
{
if (p < 0 || p > 1)
return NAN;
double root = p;
if (RandMath::findRoot([this, p] (double x)
{
return BetaRand::F(x) - p;
},
0, 1, root))
return root;
return NAN;
}
double BetaRand::Median() const
{
if (RandMath::areEqual(alpha, beta))
return 0.5;
return Quantile(0.5);
}
double BetaRand::Mode() const
{
if (alpha > 1)
{
if (beta > 1)
return (alpha - 1) / (alpha + beta - 2);
return 1.0;
}
if (beta > 1)
return 0.0;
return BernoulliRand::standardVariate();
}
double BetaRand::Skewness() const
{
double skewness = (alpha + beta + 1) / (alpha * beta);
skewness = std::sqrt(skewness);
skewness *= (alpha - beta);
skewness /= (alpha + beta + 2);
return skewness + skewness;
}
double BetaRand::ExcessKurtosis() const
{
double sum = alpha + beta;
double kurtosis = alpha - beta;
kurtosis *= kurtosis;
kurtosis *= (sum + 1);
kurtosis /= (alpha * beta * (sum + 2));
--kurtosis;
kurtosis /= (sum + 3);
return 6 * kurtosis;
}
BaldingNicholsRand::BaldingNicholsRand(double fixatingIndex, double frequency)
{
setParameters(fixatingIndex, frequency);
}
std::string BaldingNicholsRand::name()
{
return "Balding-Nichols(" + toStringWithPrecision(getFixatingIndex()) + ", " + toStringWithPrecision(getFrequency()) + ")";
}
void BaldingNicholsRand::setParameters(double fixatingIndex, double frequency)
{
F = fixatingIndex;
if (F <= 0 || F >= 1)
F = 0.5;
p = frequency;
if (p <= 0 || p >= 1)
p = 0.5;
double frac = (1.0 - F) / F;
BetaRand::setParameters(frac * p, frac * (1 - p));
}
<commit_msg>Update BetaRand.cpp<commit_after>#include "BetaRand.h"
#include "../discrete/BernoulliRand.h"
BetaRand::BetaRand(double shape1, double shape2)
{
setParameters(shape1, shape2);
}
std::string BetaRand::name()
{
return "Beta(" + toStringWithPrecision(getAlpha()) + ", " + toStringWithPrecision(getBeta()) + ")";
}
void BetaRand::setParameters(double shape1, double shape2)
{
alpha = shape1;
if (alpha <= 0)
alpha = 1.0;
X.setParameters(alpha, 1);
beta = shape2;
if (beta <= 0)
beta = 1.0;
Y.setParameters(beta, 1);
if (alpha + beta > 30)
{
/// we use log(Gamma(x)) in order to avoid too big numbers
double logGammaX = std::log(X.getInverseGammaFunction());
double logGammaY = std::log(Y.getInverseGammaFunction());
pdfCoef = std::lgamma(alpha + beta) + logGammaX + logGammaY;
pdfCoef = std::exp(pdfCoef);
}
else {
pdfCoef = std::tgamma(alpha + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
}
setVariateConstants();
}
void BetaRand::setAlpha(double shape1)
{
alpha = shape1;
if (alpha <= 0)
alpha = 1.0;
X.setParameters(alpha, 1);
pdfCoef = std::tgamma(alpha + Y.getShape()) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
setVariateConstants();
}
void BetaRand::setBeta(double shape2)
{
beta = shape2;
if (beta <= 0)
beta = 1.0;
Y.setParameters(beta, 1);
pdfCoef = std::tgamma(X.getShape() + beta) * X.getInverseGammaFunction() * Y.getInverseGammaFunction();
setVariateConstants();
}
double BetaRand::f(double x) const
{
if (x < 0 || x > 1)
return 0;
if (RandMath::areEqual(alpha, beta))
return pdfCoef * std::pow(x - x * x, alpha - 1);
double rv = std::pow(x, alpha - 1);
rv *= std::pow(1 - x, beta - 1);
return pdfCoef * rv;
}
double BetaRand::F(double x) const
{
if (x <= 0)
return 0;
if (x >= 1)
return 1;
return pdfCoef * RandMath::incompleteBetaFun(x, alpha, beta);
}
double BetaRand::variateArcsine() const
{
double x = std::sin(UniformRand::variate(-M_PI, M_PI));
return x * x;
}
double BetaRand::variateForSmallEqualParameters() const
{
int iter = 0;
do {
double u1 = UniformRand::standardVariate();
double u2 = UniformRand::standardVariate();
if (u2 <= std::pow(4 * u1 * (1 - u1), alpha - 1))
return u1;
} while (++iter <= 1e9); /// one billion should be enough
return NAN; /// fail
}
double BetaRand::variateForLargeEqualParameters() const
{
int iter = 0;
do {
double n = N.variate();
if (n < 0 || n > 1)
continue;
double u = UniformRand::standardVariate();
if (u < N.f(n) / (variateCoef * f(n)))
return n;
} while (++iter <= 1e9); /// one billion should be enough
return NAN; /// fail
}
double BetaRand::variateForDifferentParameters() const
{
double x = X.variate();
return x / (x + Y.variate());
}
void BetaRand::setVariateConstants()
{
/// We need to storage variate coefficient only if alpha = beta and large enough
if (alpha > edgeForGenerators && RandMath::areEqual(alpha, beta))
{
double t = 1.0 / (alpha + alpha + 1);
variateCoef = M_E * std::sqrt(0.5 * M_PI * M_E * t);
variateCoef *= std::pow(0.25 - 0.75 * t, alpha - 1);
variateCoef *= pdfCoef; /// /= Beta(alpha, alpha)
N.setMean(0.5);
N.setVariance(0.25 * t);
}
}
double BetaRand::variate() const
{
if (RandMath::areEqual(alpha, beta) && alpha == 0.5)
return variateArcsine();
if (!RandMath::areEqual(alpha, beta) || alpha < 1)
return variateForDifferentParameters();
if (alpha == 1)
return UniformRand::standardVariate();
if (alpha <= edgeForGenerators)
return variateForSmallEqualParameters();
return variateForLargeEqualParameters();
}
void BetaRand::sample(QVector<double> &outputData) const
{
if (RandMath::areEqual(alpha, beta) && alpha == 0.5) {
for (double &var : outputData)
var = variateArcsine();
}
else if (!RandMath::areEqual(alpha, beta) || alpha < 1) {
for (double &var : outputData)
var = variateForDifferentParameters();
}
else if (alpha == 1) {
for (double &var : outputData)
var = UniformRand::standardVariate();
}
else if (alpha <= edgeForGenerators) {
for (double &var : outputData)
var = variateForSmallEqualParameters();
}
else {
for (double &var : outputData)
var = variateForLargeEqualParameters();
}
}
double BetaRand::Mean() const
{
return alpha / (alpha + beta);
}
double BetaRand::Variance() const
{
double denominator = alpha + beta;
denominator *= denominator * (denominator + 1);
return alpha * beta / denominator;
}
double BetaRand::Quantile(double p) const
{
if (p < 0 || p > 1)
return NAN;
double root = p;
if (RandMath::findRoot([this, p] (double x)
{
return BetaRand::F(x) - p;
},
0, 1, root))
return root;
return NAN;
}
double BetaRand::Median() const
{
if (RandMath::areEqual(alpha, beta))
return 0.5;
return Quantile(0.5);
}
double BetaRand::Mode() const
{
if (alpha > 1)
{
if (beta > 1)
return (alpha - 1) / (alpha + beta - 2);
return 1.0;
}
if (beta > 1)
return 0.0;
return BernoulliRand::standardVariate();
}
double BetaRand::Skewness() const
{
double skewness = (alpha + beta + 1) / (alpha * beta);
skewness = std::sqrt(skewness);
skewness *= (alpha - beta);
skewness /= (alpha + beta + 2);
return skewness + skewness;
}
double BetaRand::ExcessKurtosis() const
{
double sum = alpha + beta;
double kurtosis = alpha - beta;
kurtosis *= kurtosis;
kurtosis *= (sum + 1);
kurtosis /= (alpha * beta * (sum + 2));
--kurtosis;
kurtosis /= (sum + 3);
return 6 * kurtosis;
}
BaldingNicholsRand::BaldingNicholsRand(double fixatingIndex, double frequency)
{
setParameters(fixatingIndex, frequency);
}
std::string BaldingNicholsRand::name()
{
return "Balding-Nichols(" + toStringWithPrecision(getFixatingIndex()) + ", " + toStringWithPrecision(getFrequency()) + ")";
}
void BaldingNicholsRand::setParameters(double fixatingIndex, double frequency)
{
F = fixatingIndex;
if (F <= 0 || F >= 1)
F = 0.5;
p = frequency;
if (p <= 0 || p >= 1)
p = 0.5;
double frac = (1.0 - F) / F, fracP = frac * p;
BetaRand::setParameters(fracP, frac - fracP);
}
<|endoftext|> |
<commit_before>#include "ffmpeg_video_target.h"
#include "except.h"
#ifdef GENERATE_PERFORMANCE_OUTPUT
#include <boost/timer/timer.hpp>
#endif
namespace gg
{
VideoTargetFFmpeg::VideoTargetFFmpeg(const std::string codec) :
_codec(NULL),
_codec_name(""),
_frame(NULL),
_framerate(-1),
_sws_context(NULL),
_format_context(NULL),
_stream(NULL),
_frame_index(0)
{
if (codec != "H265")
{
std::string msg;
msg.append("Codec ")
.append(codec)
.append(" not recognised");
throw VideoTargetError(msg);
}
#ifdef FFMPEG_HWACCEL
_codec_name = "nvenc_hevc";
#else
_codec_name = "libx265";
#endif
av_register_all();
}
void VideoTargetFFmpeg::init(const std::string filepath, const float framerate)
{
if (framerate <= 0)
throw VideoTargetError("Negative fps does not make sense");
if (framerate - (int) framerate > 0)
throw VideoTargetError("Only integer framerates are supported");
_framerate = (int) framerate;
check_filetype_support(filepath, "mp4");
_filepath = filepath;
/* allocate the output media context */
avformat_alloc_output_context2(&_format_context, NULL, NULL, _filepath.c_str());
if (_format_context == NULL)
// Use MP4 as default if context cannot be deduced from file extension
avformat_alloc_output_context2(&_format_context, NULL, "mp4", NULL);
if (_format_context == NULL)
throw VideoTargetError("Could not allocate output media context");
_codec = avcodec_find_encoder_by_name(_codec_name.c_str());
if (not _codec)
throw VideoTargetError("Codec not found");
_stream = avformat_new_stream(_format_context, _codec);
if (_stream == NULL)
throw VideoTargetError("Could not allocate stream");
_stream->id = _format_context->nb_streams-1; // TODO isn't this wrong?
}
void VideoTargetFFmpeg::append(const VideoFrame_BGRA & frame)
{
if (_framerate <= 0)
throw VideoTargetError("Video target not initialised");
// return value buffers
int ret, got_output;
// if first frame, initialise
if (_frame == NULL)
{
#ifdef GENERATE_PERFORMANCE_OUTPUT
#ifndef timer_format_str
#define timer_format_str \
std::string(", %w, %u, %s, %t, %p" \
", wall (s), user (s), system (s), user+system (s), CPU (\%)\n")
#endif
#ifndef this_class_str
#define this_class_str std::string("VideoTargetFFmpeg-")
#endif
boost::timer::auto_cpu_timer t(this_class_str + "first-frame" + timer_format_str);
#endif
// TODO - is _codec_context ever being modified after first frame?
/* TODO: using default reduces filesize
* but should we set it nonetheless?
*/
// _stream->codec->bit_rate = 400000;
_stream->codec->width = frame.cols();
_stream->codec->height = frame.rows();
_stream->time_base = (AVRational){ 1, _framerate };
_stream->codec->time_base = _stream->time_base;
_stream->codec->gop_size = 12;
/* TODO emit one intra frame every twelve frames at most */
_stream->codec->pix_fmt = AV_PIX_FMT_YUV420P;
/* Some formats want stream headers to be separate. */
if (_format_context->oformat->flags & AVFMT_GLOBALHEADER)
_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
switch (_stream->codec->codec_id)
{
case AV_CODEC_ID_H264:
case AV_CODEC_ID_HEVC:
#ifdef FFMPEG_HWACCEL
// nop
ret = 0;
#else
/* TODO will this work in real-time with a framegrabber ?
* "slow" produces 2x larger file compared to "ultrafast",
* but with a substantial visual quality degradation
* (judged using the coloured chessboard pattern)
* "fast" is a trade-off: visual quality looks similar
* while file size is reasonable
*/
ret = av_opt_set(_stream->codec->priv_data, "preset", "fast", 0);
#endif
if (ret != 0)
throw VideoTargetError("Could not set codec-specific options");
/* Resolution must be a multiple of two, as required
* by H264 and H265. Introduce a one-pixel padding for
* non-complying dimension(s).
*/
_stream->codec->width +=
_stream->codec->width % 2 == 0 ? 0 : 1;
_stream->codec->height +=
_stream->codec->height % 2 == 0 ? 0 : 1;
break;
default:
// nop
break;
}
/* open it */
if (avcodec_open2(_stream->codec, _codec, NULL) < 0)
throw VideoTargetError("Could not open codec");
_frame = av_frame_alloc();
if (not _frame)
throw VideoTargetError("Could not allocate video frame");
_frame->format = _stream->codec->pix_fmt;
_frame->width = _stream->codec->width;
_frame->height = _stream->codec->height;
/* allocate the buffers for the frame data */
// TODO #25 what influence does 32 have on performance?
ret = av_frame_get_buffer(_frame, 32);
if (ret < 0)
throw VideoTargetError("Could not allocate frame data");
/* Now that all the parameters are set, we can open the audio and
* video codecs and allocate the necessary encode buffers. */
av_dump_format(_format_context, 0, _filepath.c_str(), 1);
/* open the output file, if needed */
if (!(_format_context->oformat->flags & AVFMT_NOFILE))
{
ret = avio_open(&_format_context->pb, _filepath.c_str(), AVIO_FLAG_WRITE);
if (ret < 0)
{
std::string msg;
msg.append("File ")
.append(_filepath)
.append(" could not be opened");
throw VideoTargetError(msg);
}
}
/* Write the stream header, if any. */
ret = avformat_write_header(_format_context, NULL);
if (ret < 0)
throw VideoTargetError("Could not write header to file");
/* Open context for converting BGRA pixels to YUV420p */
_sws_context = sws_getContext(
frame.cols(), frame.rows(), AV_PIX_FMT_BGRA,
frame.cols(), frame.rows(), _stream->codec->pix_fmt,
0, NULL, NULL, NULL);
if (_sws_context == NULL)
throw VideoTargetError("Could not allocate Sws context");
// To be incremented for each frame, used as pts
_frame_index = 0;
// Packet to be used when writing frames
av_init_packet(&_packet);
// TODO #25 data gets allocated each time?
_packet.data = NULL; // packet data will be allocated by the encoder
_packet.size = 0;
_bgra_stride[0] = 4*frame.cols();
}
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-av_frame_make_writable" + timer_format_str);
#endif
/* when we pass a frame to the encoder, it may keep a reference to it
* internally;
* make sure we do not overwrite it here
*/
// TODO #25 why not only once?
ret = av_frame_make_writable(_frame);
if (ret < 0)
throw VideoTargetError("Could not make frame writeable");
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-sws_scale" + timer_format_str);
#endif
/* convert pixel format */
_src_data_ptr[0] = frame.data();
sws_scale(_sws_context,
_src_data_ptr, _bgra_stride, // BGRA has one plane
0, frame.rows(),
_frame->data, _frame->linesize
);
_frame->pts = _frame_index++;
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-encode_and_write" + timer_format_str);
#endif
/* encode the image */
encode_and_write(_frame, got_output);
} // END auto_cpu_timer scope
}
void VideoTargetFFmpeg::encode_and_write(AVFrame * frame, int & got_output)
{
int ret;
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-avcodec_encode_video2" + timer_format_str);
#endif
ret = avcodec_encode_video2(_stream->codec, &_packet, frame, &got_output);
} // END auto_cpu_timer scope
if (ret < 0)
throw VideoTargetError("Error encoding frame");
if (got_output)
{
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-av_packet_rescale_ts" + timer_format_str);
#endif
/* rescale output packet timestamp values from codec to stream timebase */
av_packet_rescale_ts(&_packet, _stream->codec->time_base, _stream->time_base);
// TODO - above time bases are the same, or not?
_packet.stream_index = _stream->index;
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-av_interleaved_write_frame" + timer_format_str);
#endif
/* Write the compressed frame to the media file. */
int ret = av_interleaved_write_frame(_format_context, &_packet);
}
if (ret < 0)
throw VideoTargetError("Could not interleaved write frame");
// av_packet_unref(&packet); taken care of by av_interleaved_write_frame
}
}
void VideoTargetFFmpeg::finalise()
{
/* get the delayed frames */
for (int got_output = 1; got_output; )
encode_and_write(NULL, got_output);
/* Write the trailer, if any. The trailer must be written before you
* close the CodecContexts open when you wrote the header; otherwise
* av_write_trailer() may try to use memory that was freed on
* av_codec_close(). */
av_write_trailer(_format_context);
if (_stream->codec) avcodec_close(_stream->codec);
if (_frame) av_frame_free(&_frame);
// av_freep(&_frame->data[0]); no need for this because _frame never manages its own data
if (_sws_context) sws_freeContext(_sws_context);
if (!(_format_context->oformat->flags & AVFMT_NOFILE))
/* Close the output file. */
avio_closep(&_format_context->pb);
/* free the stream */
avformat_free_context(_format_context);
// default values, for next init
_codec = NULL;
_frame = NULL;
_framerate = -1;
_sws_context = NULL;
_format_context = NULL;
_stream = NULL;
_frame_index = 0;
}
}
<commit_msg>Issue #36: when finalising FFmpeg target, checking whether append has been called at least once<commit_after>#include "ffmpeg_video_target.h"
#include "except.h"
#ifdef GENERATE_PERFORMANCE_OUTPUT
#include <boost/timer/timer.hpp>
#endif
namespace gg
{
VideoTargetFFmpeg::VideoTargetFFmpeg(const std::string codec) :
_codec(NULL),
_codec_name(""),
_frame(NULL),
_framerate(-1),
_sws_context(NULL),
_format_context(NULL),
_stream(NULL),
_frame_index(0)
{
if (codec != "H265")
{
std::string msg;
msg.append("Codec ")
.append(codec)
.append(" not recognised");
throw VideoTargetError(msg);
}
#ifdef FFMPEG_HWACCEL
_codec_name = "nvenc_hevc";
#else
_codec_name = "libx265";
#endif
av_register_all();
}
void VideoTargetFFmpeg::init(const std::string filepath, const float framerate)
{
if (framerate <= 0)
throw VideoTargetError("Negative fps does not make sense");
if (framerate - (int) framerate > 0)
throw VideoTargetError("Only integer framerates are supported");
_framerate = (int) framerate;
check_filetype_support(filepath, "mp4");
_filepath = filepath;
/* allocate the output media context */
avformat_alloc_output_context2(&_format_context, NULL, NULL, _filepath.c_str());
if (_format_context == NULL)
// Use MP4 as default if context cannot be deduced from file extension
avformat_alloc_output_context2(&_format_context, NULL, "mp4", NULL);
if (_format_context == NULL)
throw VideoTargetError("Could not allocate output media context");
_codec = avcodec_find_encoder_by_name(_codec_name.c_str());
if (not _codec)
throw VideoTargetError("Codec not found");
_stream = avformat_new_stream(_format_context, _codec);
if (_stream == NULL)
throw VideoTargetError("Could not allocate stream");
_stream->id = _format_context->nb_streams-1; // TODO isn't this wrong?
}
void VideoTargetFFmpeg::append(const VideoFrame_BGRA & frame)
{
if (_framerate <= 0)
throw VideoTargetError("Video target not initialised");
// return value buffers
int ret, got_output;
// if first frame, initialise
if (_frame == NULL)
{
#ifdef GENERATE_PERFORMANCE_OUTPUT
#ifndef timer_format_str
#define timer_format_str \
std::string(", %w, %u, %s, %t, %p" \
", wall (s), user (s), system (s), user+system (s), CPU (\%)\n")
#endif
#ifndef this_class_str
#define this_class_str std::string("VideoTargetFFmpeg-")
#endif
boost::timer::auto_cpu_timer t(this_class_str + "first-frame" + timer_format_str);
#endif
// TODO - is _codec_context ever being modified after first frame?
/* TODO: using default reduces filesize
* but should we set it nonetheless?
*/
// _stream->codec->bit_rate = 400000;
_stream->codec->width = frame.cols();
_stream->codec->height = frame.rows();
_stream->time_base = (AVRational){ 1, _framerate };
_stream->codec->time_base = _stream->time_base;
_stream->codec->gop_size = 12;
/* TODO emit one intra frame every twelve frames at most */
_stream->codec->pix_fmt = AV_PIX_FMT_YUV420P;
/* Some formats want stream headers to be separate. */
if (_format_context->oformat->flags & AVFMT_GLOBALHEADER)
_stream->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
switch (_stream->codec->codec_id)
{
case AV_CODEC_ID_H264:
case AV_CODEC_ID_HEVC:
#ifdef FFMPEG_HWACCEL
// nop
ret = 0;
#else
/* TODO will this work in real-time with a framegrabber ?
* "slow" produces 2x larger file compared to "ultrafast",
* but with a substantial visual quality degradation
* (judged using the coloured chessboard pattern)
* "fast" is a trade-off: visual quality looks similar
* while file size is reasonable
*/
ret = av_opt_set(_stream->codec->priv_data, "preset", "fast", 0);
#endif
if (ret != 0)
throw VideoTargetError("Could not set codec-specific options");
/* Resolution must be a multiple of two, as required
* by H264 and H265. Introduce a one-pixel padding for
* non-complying dimension(s).
*/
_stream->codec->width +=
_stream->codec->width % 2 == 0 ? 0 : 1;
_stream->codec->height +=
_stream->codec->height % 2 == 0 ? 0 : 1;
break;
default:
// nop
break;
}
/* open it */
if (avcodec_open2(_stream->codec, _codec, NULL) < 0)
throw VideoTargetError("Could not open codec");
_frame = av_frame_alloc();
if (not _frame)
throw VideoTargetError("Could not allocate video frame");
_frame->format = _stream->codec->pix_fmt;
_frame->width = _stream->codec->width;
_frame->height = _stream->codec->height;
/* allocate the buffers for the frame data */
// TODO #25 what influence does 32 have on performance?
ret = av_frame_get_buffer(_frame, 32);
if (ret < 0)
throw VideoTargetError("Could not allocate frame data");
/* Now that all the parameters are set, we can open the audio and
* video codecs and allocate the necessary encode buffers. */
av_dump_format(_format_context, 0, _filepath.c_str(), 1);
/* open the output file, if needed */
if (!(_format_context->oformat->flags & AVFMT_NOFILE))
{
ret = avio_open(&_format_context->pb, _filepath.c_str(), AVIO_FLAG_WRITE);
if (ret < 0)
{
std::string msg;
msg.append("File ")
.append(_filepath)
.append(" could not be opened");
throw VideoTargetError(msg);
}
}
/* Write the stream header, if any. */
ret = avformat_write_header(_format_context, NULL);
if (ret < 0)
throw VideoTargetError("Could not write header to file");
/* Open context for converting BGRA pixels to YUV420p */
_sws_context = sws_getContext(
frame.cols(), frame.rows(), AV_PIX_FMT_BGRA,
frame.cols(), frame.rows(), _stream->codec->pix_fmt,
0, NULL, NULL, NULL);
if (_sws_context == NULL)
throw VideoTargetError("Could not allocate Sws context");
// To be incremented for each frame, used as pts
_frame_index = 0;
// Packet to be used when writing frames
av_init_packet(&_packet);
// TODO #25 data gets allocated each time?
_packet.data = NULL; // packet data will be allocated by the encoder
_packet.size = 0;
_bgra_stride[0] = 4*frame.cols();
}
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-av_frame_make_writable" + timer_format_str);
#endif
/* when we pass a frame to the encoder, it may keep a reference to it
* internally;
* make sure we do not overwrite it here
*/
// TODO #25 why not only once?
ret = av_frame_make_writable(_frame);
if (ret < 0)
throw VideoTargetError("Could not make frame writeable");
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-sws_scale" + timer_format_str);
#endif
/* convert pixel format */
_src_data_ptr[0] = frame.data();
sws_scale(_sws_context,
_src_data_ptr, _bgra_stride, // BGRA has one plane
0, frame.rows(),
_frame->data, _frame->linesize
);
_frame->pts = _frame_index++;
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "1-encode_and_write" + timer_format_str);
#endif
/* encode the image */
encode_and_write(_frame, got_output);
} // END auto_cpu_timer scope
}
void VideoTargetFFmpeg::encode_and_write(AVFrame * frame, int & got_output)
{
int ret;
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-avcodec_encode_video2" + timer_format_str);
#endif
ret = avcodec_encode_video2(_stream->codec, &_packet, frame, &got_output);
} // END auto_cpu_timer scope
if (ret < 0)
throw VideoTargetError("Error encoding frame");
if (got_output)
{
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-av_packet_rescale_ts" + timer_format_str);
#endif
/* rescale output packet timestamp values from codec to stream timebase */
av_packet_rescale_ts(&_packet, _stream->codec->time_base, _stream->time_base);
// TODO - above time bases are the same, or not?
_packet.stream_index = _stream->index;
} // END auto_cpu_timer scope
{ // START auto_cpu_timer scope
#ifdef GENERATE_PERFORMANCE_OUTPUT
boost::timer::auto_cpu_timer t(this_class_str + "2-av_interleaved_write_frame" + timer_format_str);
#endif
/* Write the compressed frame to the media file. */
int ret = av_interleaved_write_frame(_format_context, &_packet);
}
if (ret < 0)
throw VideoTargetError("Could not interleaved write frame");
// av_packet_unref(&packet); taken care of by av_interleaved_write_frame
}
}
void VideoTargetFFmpeg::finalise()
{
/* This condition means that append
* has been called at least once
* successfully (see Issue#36)
*/
if (_frame)
{
/* get the delayed frames */
for (int got_output = 1; got_output; )
encode_and_write(NULL, got_output);
/* Write the trailer, if any. The trailer must be written before you
* close the CodecContexts open when you wrote the header; otherwise
* av_write_trailer() may try to use memory that was freed on
* av_codec_close(). */
av_write_trailer(_format_context);
}
if (_stream->codec) avcodec_close(_stream->codec);
if (_frame) av_frame_free(&_frame);
// av_freep(&_frame->data[0]); no need for this because _frame never manages its own data
if (_sws_context) sws_freeContext(_sws_context);
if (!(_format_context->oformat->flags & AVFMT_NOFILE))
if (_format_context->pb)
/* Close the output file. */
avio_closep(&_format_context->pb);
/* free the stream */
avformat_free_context(_format_context);
// default values, for next init
_codec = NULL;
_frame = NULL;
_framerate = -1;
_sws_context = NULL;
_format_context = NULL;
_stream = NULL;
_frame_index = 0;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salobj.cxx,v $
* $Revision: 1.14 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <string.h>
#include "saldata.hxx"
#include "salobj.h"
#include "salframe.h"
// get QTMovieView
#include "premac.h"
#include <QTKit/QTMovieView.h>
#include "postmac.h"
// =======================================================================
AquaSalObject::AquaSalObject( AquaSalFrame* pFrame ) :
mpFrame( pFrame ),
mnClipX( -1 ),
mnClipY( -1 ),
mnClipWidth( -1 ),
mnClipHeight( -1 ),
mbClip( false ),
mnX( 0 ),
mnY( 0 ),
mnWidth( 20 ),
mnHeight( 20 )
{
maSysData.nSize = sizeof( maSysData );
maSysData.pView = NULL;
NSRect aInitFrame = { { 0, 0 }, { 20, 20 } };
mpClipView = [[NSClipView alloc] initWithFrame: aInitFrame ];
if( mpClipView )
{
[mpFrame->getView() addSubview: mpClipView];
[mpClipView setHidden: YES];
}
maSysData.pView = [[QTMovieView alloc] initWithFrame: aInitFrame];
if( maSysData.pView )
{
if( mpClipView )
[mpClipView setDocumentView: maSysData.pView];
}
}
// -----------------------------------------------------------------------
AquaSalObject::~AquaSalObject()
{
if( maSysData.pView )
{
[maSysData.pView removeFromSuperview];
[maSysData.pView release];
}
if( mpClipView )
{
[mpClipView removeFromSuperview];
[mpClipView release];
}
}
/*
sadly there seems to be no way to impose clipping on a child view,
especially a QTMovieView which seems to ignore the current context
completely. Also there is no real way to shape a window; on Aqua a
similar effect to non-rectangular windows is achieved by using a
non-opaque window and not painting where one wants the background
to shine through.
With respect to SalObject this leaves us to having an NSClipView
containing the child view. Even a QTMovieView respects the boundaries of
that, which gives us a clip "region" consisting of one rectangle.
This is gives us an 80% solution only, though.
*/
// -----------------------------------------------------------------------
void AquaSalObject::ResetClipRegion()
{
mbClip = false;
setClippedPosSize();
}
// -----------------------------------------------------------------------
USHORT AquaSalObject::GetClipRegionType()
{
return SAL_OBJECT_CLIP_INCLUDERECTS;
}
// -----------------------------------------------------------------------
void AquaSalObject::BeginSetClipRegion( ULONG nRectCount )
{
mbClip = false;
}
// -----------------------------------------------------------------------
void AquaSalObject::UnionClipRegion( long nX, long nY, long nWidth, long nHeight )
{
if( mbClip )
{
if( nX < mnClipX )
{
mnClipWidth += mnClipX - nX;
mnClipX = nX;
}
if( nX + nWidth > mnClipX + mnClipWidth )
mnClipWidth = nX + nWidth - mnClipX;
if( nY < mnClipY )
{
mnClipHeight += mnClipY - nY;
mnClipY = nY;
}
if( nY + nHeight > mnClipY + mnClipHeight )
mnClipHeight = nY + nHeight - mnClipY;
}
else
{
mnClipX = nX;
mnClipY = nY;
mnClipWidth = nWidth;
mnClipHeight = nHeight;
mbClip = true;
}
}
// -----------------------------------------------------------------------
void AquaSalObject::EndSetClipRegion()
{
setClippedPosSize();
}
// -----------------------------------------------------------------------
void AquaSalObject::SetPosSize( long nX, long nY, long nWidth, long nHeight )
{
mnX = nX;
mnY = nY;
mnWidth = nWidth;
mnHeight = nHeight;
setClippedPosSize();
}
// -----------------------------------------------------------------------
void AquaSalObject::setClippedPosSize()
{
NSRect aViewRect = { { 0, 0 }, { mnWidth, mnHeight } };
if( maSysData.pView )
[maSysData.pView setFrame: aViewRect];
NSRect aClipViewRect = { { mnX, mnY }, { mnWidth, mnHeight } };
NSPoint aClipPt = { 0, 0 };
if( mbClip )
{
aClipViewRect.origin.x += mnClipX;
aClipViewRect.origin.y += mnClipY;
aClipViewRect.size.width = mnClipWidth;
aClipViewRect.size.height = mnClipHeight;
aClipPt.x = mnClipX;
if( mnClipY == 0 )
aClipPt.y = mnHeight - mnClipHeight;;
}
mpFrame->VCLToCocoa( aClipViewRect, false );
[mpClipView setFrame: aClipViewRect];
[mpClipView scrollToPoint: aClipPt];
}
// -----------------------------------------------------------------------
void AquaSalObject::Show( BOOL bVisible )
{
if( mpClipView )
[mpClipView setHidden: (bVisible ? NO : YES)];
}
// -----------------------------------------------------------------------
void AquaSalObject::Enable( BOOL bEnable )
{
}
// -----------------------------------------------------------------------
void AquaSalObject::GrabFocus()
{
}
// -----------------------------------------------------------------------
void AquaSalObject::SetBackground()
{
}
// -----------------------------------------------------------------------
void AquaSalObject::SetBackground( SalColor nSalColor )
{
}
// -----------------------------------------------------------------------
const SystemEnvData* AquaSalObject::GetSystemData() const
{
return &maSysData;
}
<commit_msg>INTEGRATION: CWS canvas05 (1.13.60); FILE MERGED 2008/04/29 05:33:46 mox 1.13.60.3: Remove the now-unnecessary casts of (NSView*). 2008/04/21 07:47:27 thb 1.13.60.2: RESYNC: (1.13-1.14); FILE MERGED 2008/04/06 19:35:18 mox 1.13.60.1: Change headers to GetGraphicsData() const, Build fixes for VCL aqua<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: salobj.cxx,v $
* $Revision: 1.15 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_vcl.hxx"
#include <string.h>
#include "saldata.hxx"
#include "salobj.h"
#include "salframe.h"
// get QTMovieView
#include "premac.h"
#include <QTKit/QTMovieView.h>
#include "postmac.h"
// =======================================================================
AquaSalObject::AquaSalObject( AquaSalFrame* pFrame ) :
mpFrame( pFrame ),
mnClipX( -1 ),
mnClipY( -1 ),
mnClipWidth( -1 ),
mnClipHeight( -1 ),
mbClip( false ),
mnX( 0 ),
mnY( 0 ),
mnWidth( 20 ),
mnHeight( 20 )
{
maSysData.nSize = sizeof( maSysData );
maSysData.pView = NULL;
NSRect aInitFrame = { { 0, 0 }, { 20, 20 } };
mpClipView = [[NSClipView alloc] initWithFrame: aInitFrame ];
if( mpClipView )
{
[mpFrame->getView() addSubview: mpClipView];
[mpClipView setHidden: YES];
}
maSysData.pView = [[QTMovieView alloc] initWithFrame: aInitFrame];
if( maSysData.pView )
{
if( mpClipView )
[mpClipView setDocumentView: maSysData.pView];
}
}
// -----------------------------------------------------------------------
AquaSalObject::~AquaSalObject()
{
if( maSysData.pView )
{
NSView *pView = maSysData.pView;
[pView removeFromSuperview];
[pView release];
}
if( mpClipView )
{
[mpClipView removeFromSuperview];
[mpClipView release];
}
}
/*
sadly there seems to be no way to impose clipping on a child view,
especially a QTMovieView which seems to ignore the current context
completely. Also there is no real way to shape a window; on Aqua a
similar effect to non-rectangular windows is achieved by using a
non-opaque window and not painting where one wants the background
to shine through.
With respect to SalObject this leaves us to having an NSClipView
containing the child view. Even a QTMovieView respects the boundaries of
that, which gives us a clip "region" consisting of one rectangle.
This is gives us an 80% solution only, though.
*/
// -----------------------------------------------------------------------
void AquaSalObject::ResetClipRegion()
{
mbClip = false;
setClippedPosSize();
}
// -----------------------------------------------------------------------
USHORT AquaSalObject::GetClipRegionType()
{
return SAL_OBJECT_CLIP_INCLUDERECTS;
}
// -----------------------------------------------------------------------
void AquaSalObject::BeginSetClipRegion( ULONG nRectCount )
{
mbClip = false;
}
// -----------------------------------------------------------------------
void AquaSalObject::UnionClipRegion( long nX, long nY, long nWidth, long nHeight )
{
if( mbClip )
{
if( nX < mnClipX )
{
mnClipWidth += mnClipX - nX;
mnClipX = nX;
}
if( nX + nWidth > mnClipX + mnClipWidth )
mnClipWidth = nX + nWidth - mnClipX;
if( nY < mnClipY )
{
mnClipHeight += mnClipY - nY;
mnClipY = nY;
}
if( nY + nHeight > mnClipY + mnClipHeight )
mnClipHeight = nY + nHeight - mnClipY;
}
else
{
mnClipX = nX;
mnClipY = nY;
mnClipWidth = nWidth;
mnClipHeight = nHeight;
mbClip = true;
}
}
// -----------------------------------------------------------------------
void AquaSalObject::EndSetClipRegion()
{
setClippedPosSize();
}
// -----------------------------------------------------------------------
void AquaSalObject::SetPosSize( long nX, long nY, long nWidth, long nHeight )
{
mnX = nX;
mnY = nY;
mnWidth = nWidth;
mnHeight = nHeight;
setClippedPosSize();
}
// -----------------------------------------------------------------------
void AquaSalObject::setClippedPosSize()
{
NSRect aViewRect = { { 0, 0 }, { mnWidth, mnHeight } };
if( maSysData.pView )
{
NSView *pView = maSysData.pView;
[pView setFrame: aViewRect];
}
NSRect aClipViewRect = { { mnX, mnY }, { mnWidth, mnHeight } };
NSPoint aClipPt = { 0, 0 };
if( mbClip )
{
aClipViewRect.origin.x += mnClipX;
aClipViewRect.origin.y += mnClipY;
aClipViewRect.size.width = mnClipWidth;
aClipViewRect.size.height = mnClipHeight;
aClipPt.x = mnClipX;
if( mnClipY == 0 )
aClipPt.y = mnHeight - mnClipHeight;;
}
mpFrame->VCLToCocoa( aClipViewRect, false );
[mpClipView setFrame: aClipViewRect];
[mpClipView scrollToPoint: aClipPt];
}
// -----------------------------------------------------------------------
void AquaSalObject::Show( BOOL bVisible )
{
if( mpClipView )
[mpClipView setHidden: (bVisible ? NO : YES)];
}
// -----------------------------------------------------------------------
void AquaSalObject::Enable( BOOL bEnable )
{
}
// -----------------------------------------------------------------------
void AquaSalObject::GrabFocus()
{
}
// -----------------------------------------------------------------------
void AquaSalObject::SetBackground()
{
}
// -----------------------------------------------------------------------
void AquaSalObject::SetBackground( SalColor nSalColor )
{
}
// -----------------------------------------------------------------------
const SystemEnvData* AquaSalObject::GetSystemData() const
{
return &maSysData;
}
<|endoftext|> |
<commit_before>/*===-- int128_builtins.cpp - Implement __muloti4 --------------------------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
* ===----------------------------------------------------------------------===
*
* This file implements __muloti4, and is stolen from the compiler_rt library.
*
* FIXME: we steal and re-compile it into filesystem, which uses __int128_t,
* and requires this builtin when sanitized. See llvm.org/PR30643
*
* ===----------------------------------------------------------------------===
*/
#include "__config"
#include "climits"
#if !defined(_LIBCPP_HAS_NO_INT128)
extern "C" __attribute__((no_sanitize("undefined")))
__int128_t __muloti4(__int128_t a, __int128_t b, int* overflow) {
const int N = (int)(sizeof(__int128_t) * CHAR_BIT);
const __int128_t MIN = (__int128_t)1 << (N - 1);
const __int128_t MAX = ~MIN;
*overflow = 0;
__int128_t result = a * b;
if (a == MIN) {
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN) {
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
__int128_t sa = a >> (N - 1);
__int128_t abs_a = (a ^ sa) - sa;
__int128_t sb = b >> (N - 1);
__int128_t abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb) {
if (abs_a > MAX / abs_b)
*overflow = 1;
} else {
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
<commit_msg>Fix missing __muloti4 function with UBSAN<commit_after>/*===-- int128_builtins.cpp - Implement __muloti4 --------------------------===
*
* Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
* See https://llvm.org/LICENSE.txt for license information.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*
* ===----------------------------------------------------------------------===
*
* This file implements __muloti4, and is stolen from the compiler_rt library.
*
* FIXME: we steal and re-compile it into filesystem, which uses __int128_t,
* and requires this builtin when sanitized. See llvm.org/PR30643
*
* ===----------------------------------------------------------------------===
*/
#include "__config"
#include "climits"
#if !defined(_LIBCPP_HAS_NO_INT128)
extern "C" __attribute__((no_sanitize("undefined"))) _LIBCPP_FUNC_VIS
__int128_t __muloti4(__int128_t a, __int128_t b, int* overflow) {
const int N = (int)(sizeof(__int128_t) * CHAR_BIT);
const __int128_t MIN = (__int128_t)1 << (N - 1);
const __int128_t MAX = ~MIN;
*overflow = 0;
__int128_t result = a * b;
if (a == MIN) {
if (b != 0 && b != 1)
*overflow = 1;
return result;
}
if (b == MIN) {
if (a != 0 && a != 1)
*overflow = 1;
return result;
}
__int128_t sa = a >> (N - 1);
__int128_t abs_a = (a ^ sa) - sa;
__int128_t sb = b >> (N - 1);
__int128_t abs_b = (b ^ sb) - sb;
if (abs_a < 2 || abs_b < 2)
return result;
if (sa == sb) {
if (abs_a > MAX / abs_b)
*overflow = 1;
} else {
if (abs_a > MIN / -abs_b)
*overflow = 1;
}
return result;
}
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "decode.hxx"
struct GIFLZWTableEntry
{
GIFLZWTableEntry* pPrev;
GIFLZWTableEntry* pFirst;
sal_uInt8 nData;
};
GIFLZWDecompressor::GIFLZWDecompressor(sal_uInt8 cDataSize)
: pBlockBuf(NULL)
, nInputBitsBuf(0)
, nOutBufDataLen(0)
, nInputBitsBufSize(0)
, bEOIFound(false)
, nDataSize(cDataSize)
, nBlockBufSize(0)
, nBlockBufPos(0)
{
pOutBuf = new sal_uInt8[ 4096 ];
nClearCode = 1 << nDataSize;
nEOICode = nClearCode + 1;
nTableSize = nEOICode + 1;
nCodeSize = nDataSize + 1;
nOldCode = 0xffff;
pOutBufData = pOutBuf + 4096;
pTable = new GIFLZWTableEntry[ 4098 ];
for (sal_uInt16 i = 0; i < nTableSize; ++i)
{
pTable[i].pPrev = NULL;
pTable[i].pFirst = pTable + i;
pTable[i].nData = (sal_uInt8) i;
}
memset(pTable + nTableSize, 0, sizeof(GIFLZWTableEntry) * (4098 - nTableSize));
}
GIFLZWDecompressor::~GIFLZWDecompressor()
{
delete[] pOutBuf;
delete[] pTable;
}
HPBYTE GIFLZWDecompressor::DecompressBlock( HPBYTE pSrc, sal_uInt8 cBufSize,
sal_uLong& rCount, bool& rEOI )
{
sal_uLong nTargetSize = 4096;
sal_uLong nCount = 0;
HPBYTE pTarget = static_cast<HPBYTE>(rtl_allocateMemory( nTargetSize ));
HPBYTE pTmpTarget = pTarget;
nBlockBufSize = cBufSize;
nBlockBufPos = 0;
pBlockBuf = pSrc;
while( ProcessOneCode() )
{
nCount += nOutBufDataLen;
if( nCount > nTargetSize )
{
sal_uLong nNewSize = nTargetSize << 1;
sal_uLong nOffset = pTmpTarget - pTarget;
HPBYTE pTmp = static_cast<HPBYTE>(rtl_allocateMemory( nNewSize ));
memcpy( pTmp, pTarget, nTargetSize );
rtl_freeMemory( pTarget );
nTargetSize = nNewSize;
pTmpTarget = ( pTarget = pTmp ) + nOffset;
}
memcpy( pTmpTarget, pOutBufData, nOutBufDataLen );
pTmpTarget += nOutBufDataLen;
pOutBufData += nOutBufDataLen;
nOutBufDataLen = 0;
if ( bEOIFound )
break;
}
rCount = nCount;
rEOI = bEOIFound;
return pTarget;
}
bool GIFLZWDecompressor::AddToTable( sal_uInt16 nPrevCode, sal_uInt16 nCodeFirstData )
{
GIFLZWTableEntry* pE;
if( nTableSize < 4096 )
{
pE = pTable + nTableSize;
pE->pPrev = pTable + nPrevCode;
pE->pFirst = pE->pPrev->pFirst;
GIFLZWTableEntry *pEntry = pTable[nCodeFirstData].pFirst;
if (!pEntry)
return false;
pE->nData = pEntry->nData;
nTableSize++;
if ( ( nTableSize == (sal_uInt16) (1 << nCodeSize) ) && ( nTableSize < 4096 ) )
nCodeSize++;
}
return true;
}
bool GIFLZWDecompressor::ProcessOneCode()
{
GIFLZWTableEntry* pE;
sal_uInt16 nCode;
bool bRet = false;
bool bEndOfBlock = false;
while( nInputBitsBufSize < nCodeSize )
{
if( nBlockBufPos >= nBlockBufSize )
{
bEndOfBlock = true;
break;
}
nInputBitsBuf |= ( (sal_uLong) pBlockBuf[ nBlockBufPos++ ] ) << nInputBitsBufSize;
nInputBitsBufSize += 8;
}
if ( !bEndOfBlock )
{
// fetch code from input buffer
nCode = sal::static_int_cast< sal_uInt16 >(
( (sal_uInt16) nInputBitsBuf ) & ( ~( 0xffff << nCodeSize ) ));
nInputBitsBuf >>= nCodeSize;
nInputBitsBufSize = nInputBitsBufSize - nCodeSize;
if ( nCode < nClearCode )
{
bool bOk = true;
if ( nOldCode != 0xffff )
bOk = AddToTable(nOldCode, nCode);
if (!bOk)
return false;
}
else if ( ( nCode > nEOICode ) && ( nCode <= nTableSize ) )
{
if ( nOldCode != 0xffff )
{
bool bOk;
if ( nCode == nTableSize )
bOk = AddToTable( nOldCode, nOldCode );
else
bOk = AddToTable( nOldCode, nCode );
if (!bOk)
return false;
}
}
else
{
if ( nCode == nClearCode )
{
nTableSize = nEOICode + 1;
nCodeSize = nDataSize + 1;
nOldCode = 0xffff;
nOutBufDataLen = 0;
}
else
bEOIFound = true;
return true;
}
nOldCode = nCode;
if (nCode > 4096)
return false;
// write character(/-sequence) of code nCode in the output buffer:
pE = pTable + nCode;
do
{
if (pOutBufData == pOutBuf) //can't go back past start
return false;
nOutBufDataLen++;
*(--pOutBufData) = pE->nData;
pE = pE->pPrev;
}
while( pE );
bRet = true;
}
return bRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>use same limit in ProcessOneCode as AddToTable<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#include "decode.hxx"
struct GIFLZWTableEntry
{
GIFLZWTableEntry* pPrev;
GIFLZWTableEntry* pFirst;
sal_uInt8 nData;
};
GIFLZWDecompressor::GIFLZWDecompressor(sal_uInt8 cDataSize)
: pBlockBuf(NULL)
, nInputBitsBuf(0)
, nOutBufDataLen(0)
, nInputBitsBufSize(0)
, bEOIFound(false)
, nDataSize(cDataSize)
, nBlockBufSize(0)
, nBlockBufPos(0)
{
pOutBuf = new sal_uInt8[ 4096 ];
nClearCode = 1 << nDataSize;
nEOICode = nClearCode + 1;
nTableSize = nEOICode + 1;
nCodeSize = nDataSize + 1;
nOldCode = 0xffff;
pOutBufData = pOutBuf + 4096;
pTable = new GIFLZWTableEntry[ 4098 ];
for (sal_uInt16 i = 0; i < nTableSize; ++i)
{
pTable[i].pPrev = NULL;
pTable[i].pFirst = pTable + i;
pTable[i].nData = (sal_uInt8) i;
}
memset(pTable + nTableSize, 0, sizeof(GIFLZWTableEntry) * (4098 - nTableSize));
}
GIFLZWDecompressor::~GIFLZWDecompressor()
{
delete[] pOutBuf;
delete[] pTable;
}
HPBYTE GIFLZWDecompressor::DecompressBlock( HPBYTE pSrc, sal_uInt8 cBufSize,
sal_uLong& rCount, bool& rEOI )
{
sal_uLong nTargetSize = 4096;
sal_uLong nCount = 0;
HPBYTE pTarget = static_cast<HPBYTE>(rtl_allocateMemory( nTargetSize ));
HPBYTE pTmpTarget = pTarget;
nBlockBufSize = cBufSize;
nBlockBufPos = 0;
pBlockBuf = pSrc;
while( ProcessOneCode() )
{
nCount += nOutBufDataLen;
if( nCount > nTargetSize )
{
sal_uLong nNewSize = nTargetSize << 1;
sal_uLong nOffset = pTmpTarget - pTarget;
HPBYTE pTmp = static_cast<HPBYTE>(rtl_allocateMemory( nNewSize ));
memcpy( pTmp, pTarget, nTargetSize );
rtl_freeMemory( pTarget );
nTargetSize = nNewSize;
pTmpTarget = ( pTarget = pTmp ) + nOffset;
}
memcpy( pTmpTarget, pOutBufData, nOutBufDataLen );
pTmpTarget += nOutBufDataLen;
pOutBufData += nOutBufDataLen;
nOutBufDataLen = 0;
if ( bEOIFound )
break;
}
rCount = nCount;
rEOI = bEOIFound;
return pTarget;
}
bool GIFLZWDecompressor::AddToTable( sal_uInt16 nPrevCode, sal_uInt16 nCodeFirstData )
{
if( nTableSize < 4096 )
{
GIFLZWTableEntry* pE = pTable + nTableSize;
pE->pPrev = pTable + nPrevCode;
pE->pFirst = pE->pPrev->pFirst;
GIFLZWTableEntry *pEntry = pTable[nCodeFirstData].pFirst;
if (!pEntry)
return false;
pE->nData = pEntry->nData;
nTableSize++;
if ( ( nTableSize == (sal_uInt16) (1 << nCodeSize) ) && ( nTableSize < 4096 ) )
nCodeSize++;
}
return true;
}
bool GIFLZWDecompressor::ProcessOneCode()
{
sal_uInt16 nCode;
bool bRet = false;
bool bEndOfBlock = false;
while( nInputBitsBufSize < nCodeSize )
{
if( nBlockBufPos >= nBlockBufSize )
{
bEndOfBlock = true;
break;
}
nInputBitsBuf |= ( (sal_uLong) pBlockBuf[ nBlockBufPos++ ] ) << nInputBitsBufSize;
nInputBitsBufSize += 8;
}
if ( !bEndOfBlock )
{
// fetch code from input buffer
nCode = sal::static_int_cast< sal_uInt16 >(
( (sal_uInt16) nInputBitsBuf ) & ( ~( 0xffff << nCodeSize ) ));
nInputBitsBuf >>= nCodeSize;
nInputBitsBufSize = nInputBitsBufSize - nCodeSize;
if ( nCode < nClearCode )
{
bool bOk = true;
if ( nOldCode != 0xffff )
bOk = AddToTable(nOldCode, nCode);
if (!bOk)
return false;
}
else if ( ( nCode > nEOICode ) && ( nCode <= nTableSize ) )
{
if ( nOldCode != 0xffff )
{
bool bOk;
if ( nCode == nTableSize )
bOk = AddToTable( nOldCode, nOldCode );
else
bOk = AddToTable( nOldCode, nCode );
if (!bOk)
return false;
}
}
else
{
if ( nCode == nClearCode )
{
nTableSize = nEOICode + 1;
nCodeSize = nDataSize + 1;
nOldCode = 0xffff;
nOutBufDataLen = 0;
}
else
bEOIFound = true;
return true;
}
nOldCode = nCode;
if (nCode >= 4096)
return false;
// write character(/-sequence) of code nCode in the output buffer:
GIFLZWTableEntry* pE = pTable + nCode;
do
{
if (pOutBufData == pOutBuf) //can't go back past start
return false;
nOutBufDataLen++;
*(--pOutBufData) = pE->nData;
pE = pE->pPrev;
}
while( pE );
bRet = true;
}
return bRet;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>#include "ZambeziMiningTask.h"
#include <la-manager/AttrTokenizeWrapper.h>
#include <configuration-manager/ZambeziConfig.h>
#include <document-manager/DocumentManager.h>
#include <common/ResourceManager.h>
#include <glog/logging.h>
#include <fstream>
using namespace sf1r;
ZambeziMiningTask::ZambeziMiningTask(
const ZambeziConfig& config,
DocumentManager& documentManager,
izenelib::ir::Zambezi::NewInvertedIndex& indexer)
: config_(config)
, documentManager_(documentManager)
, indexer_(indexer)
, startDocId_(0)
{
if (config_.isDebug)
{
ofs_debug_.open((config_.indexFilePath + "debug").c_str(), ios::app);
}
}
bool ZambeziMiningTask::buildDocument(docid_t docID, const Document& doc)
{
std::vector<std::string> propNameList;
std::vector<std::string> propValueList;
propNameList.push_back("Title");
propNameList.push_back("Attribute");
propNameList.push_back("Category");
propNameList.push_back("OriginalCategory");
propNameList.push_back("Source");
for (std::vector<std::string>::iterator i = propNameList.begin(); i != propNameList.end(); ++i)
{
std::string propValue;
doc.getProperty(*i, propValue);
propValueList.push_back(propValue);
}
std::vector<std::pair<std::string, double> > tokenScoreList;
tokenScoreList = AttrTokenizeWrapper::get()->attr_tokenize_index(propValueList[0]
, propValueList[1]
, propValueList[2]
, propValueList[3]
, propValueList[4]);
std::vector<std::string> tokenList;
std::vector<uint32_t> scoreList;
for (std::vector<std::pair<std::string, double> >::const_iterator it =
tokenScoreList.begin(); it != tokenScoreList.end(); ++it)
{
tokenList.push_back(it->first);
scoreList.push_back(uint32_t(it->second));
}
if (config_.isDebug)
{
ofs_debug_ << docID << '\t' ;
for (unsigned int i = 0; i < tokenList.size(); ++i)
{
ofs_debug_ << tokenList[i] << " " << scoreList[i] << " ; ";
}
ofs_debug_ << std::endl;
}
indexer_.insertDoc(docID, tokenList, scoreList);
return true;
}
bool ZambeziMiningTask::preProcess(int64_t timestamp)
{
startDocId_ = indexer_.totalDocNum() + 1;
const docid_t endDocId = documentManager_.getMaxDocId();
LOG(INFO) << "zambezi mining task"
<< ", start docid: " << startDocId_
<< ", end docid: " << endDocId;
return startDocId_ <= endDocId;
}
bool ZambeziMiningTask::postProcess()
{
indexer_.flush();
std::ofstream ofs(config_.indexFilePath.c_str(), std::ios_base::binary);
if (! ofs)
{
LOG(ERROR) << "failed opening file " << config_.indexFilePath;
return false;
}
try
{
indexer_.save(ofs);
}
catch (const std::exception& e)
{
LOG(ERROR) << "exception in writing file: " << e.what()
<< ", path: " << config_.indexFilePath;
return false;
}
return true;
}
<commit_msg>Rename zambezi debug file to "index.bin.debug".<commit_after>#include "ZambeziMiningTask.h"
#include <la-manager/AttrTokenizeWrapper.h>
#include <configuration-manager/ZambeziConfig.h>
#include <document-manager/DocumentManager.h>
#include <common/ResourceManager.h>
#include <glog/logging.h>
#include <fstream>
using namespace sf1r;
ZambeziMiningTask::ZambeziMiningTask(
const ZambeziConfig& config,
DocumentManager& documentManager,
izenelib::ir::Zambezi::NewInvertedIndex& indexer)
: config_(config)
, documentManager_(documentManager)
, indexer_(indexer)
, startDocId_(0)
{
if (config_.isDebug)
{
ofs_debug_.open((config_.indexFilePath + ".debug").c_str(), ios::app);
}
}
bool ZambeziMiningTask::buildDocument(docid_t docID, const Document& doc)
{
std::vector<std::string> propNameList;
std::vector<std::string> propValueList;
propNameList.push_back("Title");
propNameList.push_back("Attribute");
propNameList.push_back("Category");
propNameList.push_back("OriginalCategory");
propNameList.push_back("Source");
for (std::vector<std::string>::iterator i = propNameList.begin(); i != propNameList.end(); ++i)
{
std::string propValue;
doc.getProperty(*i, propValue);
propValueList.push_back(propValue);
}
std::vector<std::pair<std::string, double> > tokenScoreList;
tokenScoreList = AttrTokenizeWrapper::get()->attr_tokenize_index(propValueList[0]
, propValueList[1]
, propValueList[2]
, propValueList[3]
, propValueList[4]);
std::vector<std::string> tokenList;
std::vector<uint32_t> scoreList;
for (std::vector<std::pair<std::string, double> >::const_iterator it =
tokenScoreList.begin(); it != tokenScoreList.end(); ++it)
{
tokenList.push_back(it->first);
scoreList.push_back(uint32_t(it->second));
}
if (config_.isDebug)
{
ofs_debug_ << docID << '\t' ;
for (unsigned int i = 0; i < tokenList.size(); ++i)
{
ofs_debug_ << tokenList[i] << " " << scoreList[i] << " ; ";
}
ofs_debug_ << std::endl;
}
indexer_.insertDoc(docID, tokenList, scoreList);
return true;
}
bool ZambeziMiningTask::preProcess(int64_t timestamp)
{
startDocId_ = indexer_.totalDocNum() + 1;
const docid_t endDocId = documentManager_.getMaxDocId();
LOG(INFO) << "zambezi mining task"
<< ", start docid: " << startDocId_
<< ", end docid: " << endDocId;
return startDocId_ <= endDocId;
}
bool ZambeziMiningTask::postProcess()
{
indexer_.flush();
std::ofstream ofs(config_.indexFilePath.c_str(), std::ios_base::binary);
if (! ofs)
{
LOG(ERROR) << "failed opening file " << config_.indexFilePath;
return false;
}
try
{
indexer_.save(ofs);
}
catch (const std::exception& e)
{
LOG(ERROR) << "exception in writing file: " << e.what()
<< ", path: " << config_.indexFilePath;
return false;
}
return true;
}
<|endoftext|> |
<commit_before>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include "q_shared.h"
#include "qcommon.h"
extern "C" {
#include "findlocale/findlocale.h"
}
#include "tinygettext/log.hpp"
#include "tinygettext/tinygettext.hpp"
#include "tinygettext/file_system.hpp"
using namespace tinygettext;
// Ugly char buffer
static std::string gettextbuffer[ 4 ];
static int num = -1;
DictionaryManager trans_manager;
DictionaryManager trans_managergame;
cvar_t *language;
cvar_t *trans_debug;
cvar_t *trans_encodings;
cvar_t *trans_languages;
#ifndef BUILD_SERVER
extern cvar_t *cl_consoleKeys; // should really #include client.h
#endif
/*
====================
DaemonInputbuf
Streambuf based class that uses the engine's File I/O functions for input
====================
*/
class DaemonInputbuf : public std::streambuf
{
private:
static const size_t BUFFER_SIZE = 8192;
fileHandle_t fileHandle;
char buffer[ BUFFER_SIZE ];
size_t putBack;
public:
DaemonInputbuf( const std::string& filename ) : putBack( 1 )
{
char *end;
end = buffer + BUFFER_SIZE - putBack;
setg( end, end, end );
FS_FOpenFileRead( filename.c_str(), &fileHandle, false );
}
~DaemonInputbuf()
{
if( fileHandle )
{
FS_FCloseFile( fileHandle );
}
}
// Unused
int underflow()
{
if( gptr() < egptr() ) // buffer not exhausted
{
return traits_type::to_int_type( *gptr() );
}
if( !fileHandle )
{
return traits_type::eof();
}
char *base = buffer;
char *start = base;
if( eback() == base )
{
// Make arrangements for putback characters
memmove( base, egptr() - putBack, putBack );
start += putBack;
}
size_t n = FS_Read( start, BUFFER_SIZE - ( start - base ), fileHandle );
if( n == 0 )
{
return traits_type::eof();
}
// Set buffer pointers
setg( base, start, start + n );
return traits_type::to_int_type( *gptr() );
}
};
/*
====================
DaemonIstream
Simple istream based class that takes ownership of the streambuf
====================
*/
class DaemonIstream : public std::istream
{
public:
DaemonIstream( const std::string& filename ) : std::istream( new DaemonInputbuf( filename ) ) {}
~DaemonIstream()
{
delete rdbuf();
}
};
/*
====================
DaemonFileSystem
Class used by tinygettext to read files and directorys
Uses the engine's File I/O functions for this purpose
====================
*/
class DaemonFileSystem : public FileSystem
{
public:
DaemonFileSystem() {}
std::vector<std::string> open_directory( const std::string& pathname )
{
int numFiles;
char **files;
std::vector<std::string> ret;
files = FS_ListFiles( pathname.c_str(), nullptr, &numFiles );
for( int i = 0; i < numFiles; i++ )
{
ret.push_back( std::string( files[ i ] ) );
}
FS_FreeFileList( files );
return ret;
}
std::unique_ptr<std::istream> open_file( const std::string& filename )
{
return std::unique_ptr<std::istream>( new DaemonIstream( filename ) );
}
};
/*
====================
Logging functions used by tinygettext
====================
*/
void Trans_Error( const std::string& str )
{
Com_Printf( "^1%s^7", str.c_str() );
}
void Trans_Warning( const std::string& str )
{
if( trans_debug->integer != 0 )
{
Com_Printf( "^3%s^7", str.c_str() );
}
}
void Trans_Info( const std::string& str )
{
if( trans_debug->integer != 0 )
{
Com_Printf( "%s", str.c_str() );
}
}
/*
====================
Trans_SetLanguage
Sets a loaded language. If desired language is not found, set closest match.
If no languages are close, force English.
====================
*/
void Trans_SetLanguage( const char* lang )
{
Language requestLang = Language::from_env( std::string( lang ) );
// default to english
Language bestLang = Language::from_env( "en" );
int bestScore = Language::match( requestLang, bestLang );
std::set<Language> langs = trans_manager.get_languages();
for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
{
int score = Language::match( requestLang, *i );
if( score > bestScore )
{
bestScore = score;
bestLang = *i;
}
}
// language not found, display warning
if( bestScore == 0 )
{
Com_Printf( S_WARNING "Language \"%s\" (%s) not found. Default to \"English\" (en)\n",
requestLang.get_name().empty() ? "Unknown Language" : requestLang.get_name().c_str(),
lang );
}
trans_manager.set_language( bestLang );
trans_managergame.set_language( bestLang );
Cvar_Set( "language", bestLang.str().c_str() );
Com_Printf( "Set language to %s" , bestLang.get_name().c_str() );
}
void Trans_UpdateLanguage_f()
{
Trans_SetLanguage( language->string );
#ifndef BUILD_SERVER
// update the default console keys string
Z_Free( cl_consoleKeys->resetString );
cl_consoleKeys->resetString = CopyString( _("~ ` 0x7e 0x60") );
#endif
}
/*
============
Trans_Init
============
*/
void Trans_Init()
{
char langList[ MAX_TOKEN_CHARS ] = "";
char encList[ MAX_TOKEN_CHARS ] = "";
std::set<Language> langs;
Language lang;
Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );
language = Cvar_Get( "language", "", CVAR_ARCHIVE );
trans_debug = Cvar_Get( "trans_debug", "0", 0 );
trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
trans_encodings = Cvar_Get( "trans_encodings", "", CVAR_ROM );
// set tinygettext log callbacks
tinygettext::Log::set_log_error_callback( &Trans_Error );
tinygettext::Log::set_log_warning_callback( &Trans_Warning );
tinygettext::Log::set_log_info_callback( &Trans_Info );
trans_manager.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
trans_managergame.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
trans_manager.add_directory( "translation/client" );
trans_managergame.add_directory( "translation/game" );
langs = trans_manager.get_languages();
for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
{
Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
Q_strcat( encList, sizeof( encList ), va( "\"%s\" ", p->str().c_str() ) );
}
Cvar_Set( "trans_languages", langList );
Cvar_Set( "trans_encodings", encList );
Com_Printf( "Loaded %lu language%s\n", ( unsigned long ) langs.size(), ( langs.size() == 1 ? "" : "s" ) );
}
void Trans_LoadDefaultLanguage()
{
FL_Locale *locale;
// Only detect locale if no previous language set.
if( !language->string[0] )
{
FL_FindLocale( &locale, FL_MESSAGES );
// Invalid or not found. Just use builtin language.
if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
{
Cvar_Set( "language", "en" );
}
else
{
Cvar_Set( "language", va( "%s%s%s", locale->lang,
locale->country[0] ? "_" : "",
locale->country ) );
}
FL_FreeLocale( &locale );
}
Trans_SetLanguage( language->string );
}
const char* Trans_Gettext_Internal( const char *msgid, DictionaryManager& manager )
{
if ( !msgid )
{
return msgid;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate( msgid );
return gettextbuffer[ num ].c_str();
}
const char* Trans_Pgettext_Internal( const char *ctxt, const char *msgid, DictionaryManager& manager )
{
if ( !ctxt || !msgid )
{
return msgid;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate_ctxt( ctxt, msgid );
return gettextbuffer[ num ].c_str();
}
const char* Trans_GettextPlural_Internal( const char *msgid, const char *msgid_plural, int number, DictionaryManager& manager )
{
if ( !msgid || !msgid_plural )
{
if ( msgid )
{
return msgid;
}
if ( msgid_plural )
{
return msgid_plural;
}
return nullptr;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate_plural( msgid, msgid_plural, number );
return gettextbuffer[ num ].c_str();
}
const char* Trans_Gettext( const char *msgid )
{
return Trans_Gettext_Internal( msgid, trans_manager );
}
// Unused
const char* Trans_Pgettext( const char *ctxt, const char *msgid )
{
return Trans_Pgettext_Internal( ctxt, msgid, trans_manager );
}
// Unused
const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_manager );
}
const char* Trans_GettextGame( const char *msgid )
{
return Trans_Gettext_Internal( msgid, trans_managergame );
}
const char* Trans_PgettextGame( const char *ctxt, const char *msgid )
{
return Trans_Pgettext_Internal( ctxt, msgid, trans_managergame );
}
const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_managergame );
}
<commit_msg>Remove one more function<commit_after>/*
===========================================================================
Daemon GPL Source Code
Copyright (C) 2012 Unvanquished Developers
This file is part of the Daemon GPL Source Code (Daemon Source Code).
Daemon Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Daemon Source Code 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 Daemon Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Daemon Source Code is also subject to certain additional terms.
You should have received a copy of these additional terms immediately following the
terms and conditions of the GNU General Public License which accompanied the Daemon
Source Code. If not, please request a copy in writing from id Software at the address
below.
If you have questions concerning this license or the applicable additional terms, you
may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville,
Maryland 20850 USA.
===========================================================================
*/
#include "q_shared.h"
#include "qcommon.h"
extern "C" {
#include "findlocale/findlocale.h"
}
#include "tinygettext/log.hpp"
#include "tinygettext/tinygettext.hpp"
#include "tinygettext/file_system.hpp"
using namespace tinygettext;
// Ugly char buffer
static std::string gettextbuffer[ 4 ];
static int num = -1;
DictionaryManager trans_manager;
DictionaryManager trans_managergame;
cvar_t *language;
cvar_t *trans_debug;
cvar_t *trans_encodings;
cvar_t *trans_languages;
#ifndef BUILD_SERVER
extern cvar_t *cl_consoleKeys; // should really #include client.h
#endif
/*
====================
DaemonInputbuf
Streambuf based class that uses the engine's File I/O functions for input
====================
*/
class DaemonInputbuf : public std::streambuf
{
private:
static const size_t BUFFER_SIZE = 8192;
fileHandle_t fileHandle;
char buffer[ BUFFER_SIZE ];
size_t putBack;
public:
DaemonInputbuf( const std::string& filename ) : putBack( 1 )
{
char *end;
end = buffer + BUFFER_SIZE - putBack;
setg( end, end, end );
FS_FOpenFileRead( filename.c_str(), &fileHandle, false );
}
~DaemonInputbuf()
{
if( fileHandle )
{
FS_FCloseFile( fileHandle );
}
}
};
/*
====================
DaemonIstream
Simple istream based class that takes ownership of the streambuf
====================
*/
class DaemonIstream : public std::istream
{
public:
DaemonIstream( const std::string& filename ) : std::istream( new DaemonInputbuf( filename ) ) {}
~DaemonIstream()
{
delete rdbuf();
}
};
/*
====================
DaemonFileSystem
Class used by tinygettext to read files and directorys
Uses the engine's File I/O functions for this purpose
====================
*/
class DaemonFileSystem : public FileSystem
{
public:
DaemonFileSystem() {}
std::vector<std::string> open_directory( const std::string& pathname )
{
int numFiles;
char **files;
std::vector<std::string> ret;
files = FS_ListFiles( pathname.c_str(), nullptr, &numFiles );
for( int i = 0; i < numFiles; i++ )
{
ret.push_back( std::string( files[ i ] ) );
}
FS_FreeFileList( files );
return ret;
}
std::unique_ptr<std::istream> open_file( const std::string& filename )
{
return std::unique_ptr<std::istream>( new DaemonIstream( filename ) );
}
};
/*
====================
Logging functions used by tinygettext
====================
*/
void Trans_Error( const std::string& str )
{
Com_Printf( "^1%s^7", str.c_str() );
}
void Trans_Warning( const std::string& str )
{
if( trans_debug->integer != 0 )
{
Com_Printf( "^3%s^7", str.c_str() );
}
}
void Trans_Info( const std::string& str )
{
if( trans_debug->integer != 0 )
{
Com_Printf( "%s", str.c_str() );
}
}
/*
====================
Trans_SetLanguage
Sets a loaded language. If desired language is not found, set closest match.
If no languages are close, force English.
====================
*/
void Trans_SetLanguage( const char* lang )
{
Language requestLang = Language::from_env( std::string( lang ) );
// default to english
Language bestLang = Language::from_env( "en" );
int bestScore = Language::match( requestLang, bestLang );
std::set<Language> langs = trans_manager.get_languages();
for( std::set<Language>::iterator i = langs.begin(); i != langs.end(); i++ )
{
int score = Language::match( requestLang, *i );
if( score > bestScore )
{
bestScore = score;
bestLang = *i;
}
}
// language not found, display warning
if( bestScore == 0 )
{
Com_Printf( S_WARNING "Language \"%s\" (%s) not found. Default to \"English\" (en)\n",
requestLang.get_name().empty() ? "Unknown Language" : requestLang.get_name().c_str(),
lang );
}
trans_manager.set_language( bestLang );
trans_managergame.set_language( bestLang );
Cvar_Set( "language", bestLang.str().c_str() );
Com_Printf( "Set language to %s" , bestLang.get_name().c_str() );
}
void Trans_UpdateLanguage_f()
{
Trans_SetLanguage( language->string );
#ifndef BUILD_SERVER
// update the default console keys string
Z_Free( cl_consoleKeys->resetString );
cl_consoleKeys->resetString = CopyString( _("~ ` 0x7e 0x60") );
#endif
}
/*
============
Trans_Init
============
*/
void Trans_Init()
{
char langList[ MAX_TOKEN_CHARS ] = "";
char encList[ MAX_TOKEN_CHARS ] = "";
std::set<Language> langs;
Language lang;
Cmd_AddCommand( "updatelanguage", Trans_UpdateLanguage_f );
language = Cvar_Get( "language", "", CVAR_ARCHIVE );
trans_debug = Cvar_Get( "trans_debug", "0", 0 );
trans_languages = Cvar_Get( "trans_languages", "", CVAR_ROM );
trans_encodings = Cvar_Get( "trans_encodings", "", CVAR_ROM );
// set tinygettext log callbacks
tinygettext::Log::set_log_error_callback( &Trans_Error );
tinygettext::Log::set_log_warning_callback( &Trans_Warning );
tinygettext::Log::set_log_info_callback( &Trans_Info );
trans_manager.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
trans_managergame.set_filesystem( std::unique_ptr<FileSystem>( new DaemonFileSystem ) );
trans_manager.add_directory( "translation/client" );
trans_managergame.add_directory( "translation/game" );
langs = trans_manager.get_languages();
for( std::set<Language>::iterator p = langs.begin(); p != langs.end(); p++ )
{
Q_strcat( langList, sizeof( langList ), va( "\"%s\" ", p->get_name().c_str() ) );
Q_strcat( encList, sizeof( encList ), va( "\"%s\" ", p->str().c_str() ) );
}
Cvar_Set( "trans_languages", langList );
Cvar_Set( "trans_encodings", encList );
Com_Printf( "Loaded %lu language%s\n", ( unsigned long ) langs.size(), ( langs.size() == 1 ? "" : "s" ) );
}
void Trans_LoadDefaultLanguage()
{
FL_Locale *locale;
// Only detect locale if no previous language set.
if( !language->string[0] )
{
FL_FindLocale( &locale, FL_MESSAGES );
// Invalid or not found. Just use builtin language.
if( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] )
{
Cvar_Set( "language", "en" );
}
else
{
Cvar_Set( "language", va( "%s%s%s", locale->lang,
locale->country[0] ? "_" : "",
locale->country ) );
}
FL_FreeLocale( &locale );
}
Trans_SetLanguage( language->string );
}
const char* Trans_Gettext_Internal( const char *msgid, DictionaryManager& manager )
{
if ( !msgid )
{
return msgid;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate( msgid );
return gettextbuffer[ num ].c_str();
}
const char* Trans_Pgettext_Internal( const char *ctxt, const char *msgid, DictionaryManager& manager )
{
if ( !ctxt || !msgid )
{
return msgid;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate_ctxt( ctxt, msgid );
return gettextbuffer[ num ].c_str();
}
const char* Trans_GettextPlural_Internal( const char *msgid, const char *msgid_plural, int number, DictionaryManager& manager )
{
if ( !msgid || !msgid_plural )
{
if ( msgid )
{
return msgid;
}
if ( msgid_plural )
{
return msgid_plural;
}
return nullptr;
}
num = ( num + 1 ) & 3;
gettextbuffer[ num ] = manager.get_dictionary().translate_plural( msgid, msgid_plural, number );
return gettextbuffer[ num ].c_str();
}
const char* Trans_Gettext( const char *msgid )
{
return Trans_Gettext_Internal( msgid, trans_manager );
}
// Unused
const char* Trans_Pgettext( const char *ctxt, const char *msgid )
{
return Trans_Pgettext_Internal( ctxt, msgid, trans_manager );
}
// Unused
const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )
{
return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_manager );
}
const char* Trans_GettextGame( const char *msgid )
{
return Trans_Gettext_Internal( msgid, trans_managergame );
}
const char* Trans_PgettextGame( const char *ctxt, const char *msgid )
{
return Trans_Pgettext_Internal( ctxt, msgid, trans_managergame );
}
const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )
{
return Trans_GettextPlural_Internal( msgid, msgid_plural, num, trans_managergame );
}
<|endoftext|> |
<commit_before>/*
-----------------------------------------------------------------------------
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 "OgreShaderPrecompiledHeaders.h"
namespace Ogre {
namespace RTShader {
//-----------------------------------------------------------------------------
Program::Program(GpuProgramType type)
{
mType = type;
mEntryPointFunction = NULL;
mSkeletalAnimation = false;
mColumnMajorMatrices = true;
}
//-----------------------------------------------------------------------------
Program::~Program()
{
destroyParameters();
destroyFunctions();
}
//-----------------------------------------------------------------------------
void Program::destroyParameters()
{
mParameters.clear();
}
//-----------------------------------------------------------------------------
void Program::destroyFunctions()
{
ShaderFunctionIterator it;
for (it = mFunctions.begin(); it != mFunctions.end(); ++it)
{
OGRE_DELETE *it;
}
mFunctions.clear();
}
//-----------------------------------------------------------------------------
GpuProgramType Program::getType() const
{
return mType;
}
//-----------------------------------------------------------------------------
void Program::addParameter(UniformParameterPtr parameter)
{
if (getParameterByName(parameter->getName()).get() != NULL)
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
"Parameter <" + parameter->getName() + "> already declared in program.",
"Program::addParameter" );
}
mParameters.push_back(parameter);
}
//-----------------------------------------------------------------------------
void Program::removeParameter(UniformParameterPtr parameter)
{
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it) == parameter)
{
(*it).reset();
mParameters.erase(it);
break;
}
}
}
//-----------------------------------------------------------------------------
static bool isArray(GpuProgramParameters::AutoConstantType autoType)
{
switch (autoType)
{
case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4:
case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY:
case GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4:
case GpuProgramParameters::ACT_WORLD_SCALE_SHEAR_MATRIX_ARRAY_3x4:
case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_ARRAY:
case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY:
case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY:
case GpuProgramParameters::ACT_LIGHT_ATTENUATION_ARRAY:
case GpuProgramParameters::ACT_LIGHT_POSITION_ARRAY:
case GpuProgramParameters::ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DIRECTION_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_POWER_SCALE_ARRAY:
case GpuProgramParameters::ACT_SPOTLIGHT_PARAMS_ARRAY:
case GpuProgramParameters::ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY:
case GpuProgramParameters::ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY:
case GpuProgramParameters::ACT_LIGHT_CASTS_SHADOWS_ARRAY:
case GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY:
case GpuProgramParameters::ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY:
case GpuProgramParameters::ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY:
case GpuProgramParameters::ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY:
case GpuProgramParameters::ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY:
return true;
default:
return false;
}
}
UniformParameterPtr Program::resolveParameter(GpuProgramParameters::AutoConstantType autoType, size_t data)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param)
{
return param;
}
// Create new parameter
size_t size = 0;
if(isArray(autoType)) std::swap(size, data); // for array autotypes the extra parameter is the size
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
addParameter(param);
return param;
}
UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType,
Real data, size_t size)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param.get() != NULL)
{
if (param->isAutoConstantRealParameter() &&
param->getAutoConstantRealData() == data)
{
param->setSize(std::max(size, param->getSize()));
return param;
}
}
// Create new parameter.
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type,
Real data, size_t size)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param.get() != NULL)
{
if (param->isAutoConstantRealParameter() &&
param->getAutoConstantRealData() == data)
{
param->setSize(std::max(size, param->getSize()));
return param;
}
}
// Create new parameter.
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size, type));
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType,
size_t data, size_t size)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param.get() != NULL)
{
if (param->isAutoConstantIntParameter() &&
param->getAutoConstantIntData() == data)
{
param->setSize(std::max(size, param->getSize()));
return param;
}
}
// Create new parameter.
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type,
size_t data, size_t size)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param.get() != NULL)
{
if (param->isAutoConstantIntParameter() &&
param->getAutoConstantIntData() == data)
{
param->setSize(std::max(size, param->getSize()));
return param;
}
}
// Create new parameter.
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size, type));
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveParameter(GpuConstantType type,
int index, uint16 variability,
const String& suggestedName,
size_t size)
{
UniformParameterPtr param;
if (index == -1)
{
index = 0;
// Find the next available index of the target type.
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it)->getType() == type &&
(*it)->isAutoConstantParameter() == false)
{
index++;
}
}
}
else
{
// Check if parameter already exists.
param = getParameterByType(type, index);
if (param.get() != NULL)
{
return param;
}
}
// Create new parameter.
param = ParameterFactory::createUniform(type, index, variability, suggestedName, size);
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByName(const String& name)
{
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it)->getName() == name)
{
return *it;
}
}
return UniformParameterPtr();
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByType(GpuConstantType type, int index)
{
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it)->getType() == type &&
(*it)->getIndex() == index)
{
return *it;
}
}
return UniformParameterPtr();
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByAutoType(GpuProgramParameters::AutoConstantType autoType)
{
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it)->isAutoConstantParameter() && (*it)->getAutoConstantType() == autoType)
{
return *it;
}
}
return UniformParameterPtr();
}
//-----------------------------------------------------------------------------
Function* Program::createFunction(const String& name, const String& desc, const Function::FunctionType functionType)
{
Function* shaderFunction;
shaderFunction = getFunctionByName(name);
if (shaderFunction != NULL)
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
"Function " + name + " already declared in program.",
"Program::createFunction" );
}
shaderFunction = OGRE_NEW Function(name, desc, functionType);
mFunctions.push_back(shaderFunction);
return shaderFunction;
}
//-----------------------------------------------------------------------------
Function* Program::getFunctionByName(const String& name)
{
ShaderFunctionIterator it;
for (it = mFunctions.begin(); it != mFunctions.end(); ++it)
{
if ((*it)->getName() == name)
{
return *it;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
void Program::addDependency(const String& libFileName)
{
for (unsigned int i=0; i < mDependencies.size(); ++i)
{
if (mDependencies[i] == libFileName)
{
return;
}
}
mDependencies.push_back(libFileName);
}
void Program::addPreprocessorDefines(const String& defines)
{
mPreprocessorDefines +=
mPreprocessorDefines.empty() ? defines : ("," + defines);
}
//-----------------------------------------------------------------------------
size_t Program::getDependencyCount() const
{
return mDependencies.size();
}
//-----------------------------------------------------------------------------
const String& Program::getDependency(unsigned int index) const
{
return mDependencies[index];
}
}
}
<commit_msg>RTSS: fix resolving params with autoConstantIntData != 0<commit_after>/*
-----------------------------------------------------------------------------
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 "OgreShaderPrecompiledHeaders.h"
namespace Ogre {
namespace RTShader {
//-----------------------------------------------------------------------------
Program::Program(GpuProgramType type)
{
mType = type;
mEntryPointFunction = NULL;
mSkeletalAnimation = false;
mColumnMajorMatrices = true;
}
//-----------------------------------------------------------------------------
Program::~Program()
{
destroyParameters();
destroyFunctions();
}
//-----------------------------------------------------------------------------
void Program::destroyParameters()
{
mParameters.clear();
}
//-----------------------------------------------------------------------------
void Program::destroyFunctions()
{
ShaderFunctionIterator it;
for (it = mFunctions.begin(); it != mFunctions.end(); ++it)
{
OGRE_DELETE *it;
}
mFunctions.clear();
}
//-----------------------------------------------------------------------------
GpuProgramType Program::getType() const
{
return mType;
}
//-----------------------------------------------------------------------------
void Program::addParameter(UniformParameterPtr parameter)
{
if (getParameterByName(parameter->getName()).get() != NULL)
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
"Parameter <" + parameter->getName() + "> already declared in program.",
"Program::addParameter" );
}
mParameters.push_back(parameter);
}
//-----------------------------------------------------------------------------
void Program::removeParameter(UniformParameterPtr parameter)
{
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it) == parameter)
{
(*it).reset();
mParameters.erase(it);
break;
}
}
}
//-----------------------------------------------------------------------------
static bool isArray(GpuProgramParameters::AutoConstantType autoType)
{
switch (autoType)
{
case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY_3x4:
case GpuProgramParameters::ACT_WORLD_MATRIX_ARRAY:
case GpuProgramParameters::ACT_WORLD_DUALQUATERNION_ARRAY_2x4:
case GpuProgramParameters::ACT_WORLD_SCALE_SHEAR_MATRIX_ARRAY_3x4:
case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_ARRAY:
case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DIFFUSE_COLOUR_POWER_SCALED_ARRAY:
case GpuProgramParameters::ACT_LIGHT_SPECULAR_COLOUR_POWER_SCALED_ARRAY:
case GpuProgramParameters::ACT_LIGHT_ATTENUATION_ARRAY:
case GpuProgramParameters::ACT_LIGHT_POSITION_ARRAY:
case GpuProgramParameters::ACT_LIGHT_POSITION_OBJECT_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_POSITION_VIEW_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DIRECTION_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DIRECTION_OBJECT_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DIRECTION_VIEW_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_DISTANCE_OBJECT_SPACE_ARRAY:
case GpuProgramParameters::ACT_LIGHT_POWER_SCALE_ARRAY:
case GpuProgramParameters::ACT_SPOTLIGHT_PARAMS_ARRAY:
case GpuProgramParameters::ACT_DERIVED_LIGHT_DIFFUSE_COLOUR_ARRAY:
case GpuProgramParameters::ACT_DERIVED_LIGHT_SPECULAR_COLOUR_ARRAY:
case GpuProgramParameters::ACT_LIGHT_CASTS_SHADOWS_ARRAY:
case GpuProgramParameters::ACT_TEXTURE_VIEWPROJ_MATRIX_ARRAY:
case GpuProgramParameters::ACT_TEXTURE_WORLDVIEWPROJ_MATRIX_ARRAY:
case GpuProgramParameters::ACT_SPOTLIGHT_VIEWPROJ_MATRIX_ARRAY:
case GpuProgramParameters::ACT_SPOTLIGHT_WORLDVIEWPROJ_MATRIX_ARRAY:
case GpuProgramParameters::ACT_SHADOW_SCENE_DEPTH_RANGE_ARRAY:
return true;
default:
return false;
}
}
UniformParameterPtr Program::resolveParameter(GpuProgramParameters::AutoConstantType autoType, size_t data)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
size_t size = 0;
if(isArray(autoType)) std::swap(size, data); // for array autotypes the extra parameter is the size
if (param && param->getAutoConstantIntData() == data)
{
return param;
}
// Create new parameter
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
addParameter(param);
return param;
}
UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType,
Real data, size_t size)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param.get() != NULL)
{
if (param->isAutoConstantRealParameter() &&
param->getAutoConstantRealData() == data)
{
param->setSize(std::max(size, param->getSize()));
return param;
}
}
// Create new parameter.
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterReal(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type,
Real data, size_t size)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param.get() != NULL)
{
if (param->isAutoConstantRealParameter() &&
param->getAutoConstantRealData() == data)
{
param->setSize(std::max(size, param->getSize()));
return param;
}
}
// Create new parameter.
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size, type));
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType,
size_t data, size_t size)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param.get() != NULL)
{
if (param->isAutoConstantIntParameter() &&
param->getAutoConstantIntData() == data)
{
param->setSize(std::max(size, param->getSize()));
return param;
}
}
// Create new parameter.
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size));
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveAutoParameterInt(GpuProgramParameters::AutoConstantType autoType, GpuConstantType type,
size_t data, size_t size)
{
UniformParameterPtr param;
// Check if parameter already exists.
param = getParameterByAutoType(autoType);
if (param.get() != NULL)
{
if (param->isAutoConstantIntParameter() &&
param->getAutoConstantIntData() == data)
{
param->setSize(std::max(size, param->getSize()));
return param;
}
}
// Create new parameter.
param = UniformParameterPtr(OGRE_NEW UniformParameter(autoType, data, size, type));
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::resolveParameter(GpuConstantType type,
int index, uint16 variability,
const String& suggestedName,
size_t size)
{
UniformParameterPtr param;
if (index == -1)
{
index = 0;
// Find the next available index of the target type.
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it)->getType() == type &&
(*it)->isAutoConstantParameter() == false)
{
index++;
}
}
}
else
{
// Check if parameter already exists.
param = getParameterByType(type, index);
if (param.get() != NULL)
{
return param;
}
}
// Create new parameter.
param = ParameterFactory::createUniform(type, index, variability, suggestedName, size);
addParameter(param);
return param;
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByName(const String& name)
{
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it)->getName() == name)
{
return *it;
}
}
return UniformParameterPtr();
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByType(GpuConstantType type, int index)
{
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it)->getType() == type &&
(*it)->getIndex() == index)
{
return *it;
}
}
return UniformParameterPtr();
}
//-----------------------------------------------------------------------------
UniformParameterPtr Program::getParameterByAutoType(GpuProgramParameters::AutoConstantType autoType)
{
UniformParameterIterator it;
for (it = mParameters.begin(); it != mParameters.end(); ++it)
{
if ((*it)->isAutoConstantParameter() && (*it)->getAutoConstantType() == autoType)
{
return *it;
}
}
return UniformParameterPtr();
}
//-----------------------------------------------------------------------------
Function* Program::createFunction(const String& name, const String& desc, const Function::FunctionType functionType)
{
Function* shaderFunction;
shaderFunction = getFunctionByName(name);
if (shaderFunction != NULL)
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS,
"Function " + name + " already declared in program.",
"Program::createFunction" );
}
shaderFunction = OGRE_NEW Function(name, desc, functionType);
mFunctions.push_back(shaderFunction);
return shaderFunction;
}
//-----------------------------------------------------------------------------
Function* Program::getFunctionByName(const String& name)
{
ShaderFunctionIterator it;
for (it = mFunctions.begin(); it != mFunctions.end(); ++it)
{
if ((*it)->getName() == name)
{
return *it;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
void Program::addDependency(const String& libFileName)
{
for (unsigned int i=0; i < mDependencies.size(); ++i)
{
if (mDependencies[i] == libFileName)
{
return;
}
}
mDependencies.push_back(libFileName);
}
void Program::addPreprocessorDefines(const String& defines)
{
mPreprocessorDefines +=
mPreprocessorDefines.empty() ? defines : ("," + defines);
}
//-----------------------------------------------------------------------------
size_t Program::getDependencyCount() const
{
return mDependencies.size();
}
//-----------------------------------------------------------------------------
const String& Program::getDependency(unsigned int index) const
{
return mDependencies[index];
}
}
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mpageswitchslideanimation.h"
#include "mpageswitchslideanimation_p.h"
#include "mscenewindow.h"
#include "mscenemanager.h"
#include "manimationcreator.h"
#include <QPropertyAnimation>
MPageSwitchSlideAnimationPrivate::MPageSwitchSlideAnimationPrivate()
: MPageSwitchAnimationPrivate(),
positionNewPageAnimation(NULL),
positionOldPageAnimation(NULL)
{
}
MPageSwitchSlideAnimationPrivate::~MPageSwitchSlideAnimationPrivate()
{
}
MPageSwitchSlideAnimation::MPageSwitchSlideAnimation(QObject *parent) :
MPageSwitchAnimation(new MPageSwitchSlideAnimationPrivate, parent)
{
Q_D(MPageSwitchSlideAnimation);
d->positionNewPageAnimation = new QPropertyAnimation;
d->positionNewPageAnimation->setPropertyName("pos");
d->positionNewPageAnimation->setEasingCurve(style()->easingCurve());
d->positionNewPageAnimation->setDuration(style()->duration());
d->positionNewPageAnimation->setEndValue(QPointF(0, 0));
addAnimation(d->positionNewPageAnimation);
d->positionOldPageAnimation = new QPropertyAnimation;
d->positionOldPageAnimation->setPropertyName("pos");
d->positionOldPageAnimation->setEasingCurve(style()->easingCurve());
d->positionOldPageAnimation->setDuration(style()->duration());
d->positionOldPageAnimation->setStartValue(QPointF(0, 0));
addAnimation(d->positionOldPageAnimation);
}
MPageSwitchSlideAnimation::MPageSwitchSlideAnimation(MPageSwitchSlideAnimationPrivate *dd, QObject *parent) :
MPageSwitchAnimation(dd, parent)
{
}
void MPageSwitchSlideAnimation::updateState(QAbstractAnimation::State newState,
QAbstractAnimation::State oldState)
{
Q_D(MPageSwitchSlideAnimation);
Q_UNUSED(oldState);
if (newState != Running)
return;
d->positionNewPageAnimation->setTargetObject(newPage());
d->positionOldPageAnimation->setTargetObject(oldPage());
if (newPage()) {
if (transitionDirection() == ToParentPage)
d->positionNewPageAnimation->setStartValue(QPointF(newPage()->boundingRect().width(), 0));
else
d->positionNewPageAnimation->setStartValue(QPointF(-newPage()->boundingRect().width(), 0));
}
if (oldPage()) {
if (transitionDirection() == ToParentPage)
d->positionOldPageAnimation->setEndValue(QPointF(-oldPage()->boundingRect().width(), 0));
else
d->positionOldPageAnimation->setEndValue(QPointF(oldPage()->boundingRect().width(), 0));
}
}
M_REGISTER_ANIMATION(MPageSwitchSlideAnimation)
<commit_msg>Changes: fixing coverity error CID#1131 RevBy: Matusz<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mpageswitchslideanimation.h"
#include "mpageswitchslideanimation_p.h"
#include "mscenewindow.h"
#include "mscenemanager.h"
#include "manimationcreator.h"
#include <QPropertyAnimation>
MPageSwitchSlideAnimationPrivate::MPageSwitchSlideAnimationPrivate()
: MPageSwitchAnimationPrivate(),
sceneWindow(NULL),
positionNewPageAnimation(NULL),
positionOldPageAnimation(NULL)
{
}
MPageSwitchSlideAnimationPrivate::~MPageSwitchSlideAnimationPrivate()
{
}
MPageSwitchSlideAnimation::MPageSwitchSlideAnimation(QObject *parent) :
MPageSwitchAnimation(new MPageSwitchSlideAnimationPrivate, parent)
{
Q_D(MPageSwitchSlideAnimation);
d->positionNewPageAnimation = new QPropertyAnimation;
d->positionNewPageAnimation->setPropertyName("pos");
d->positionNewPageAnimation->setEasingCurve(style()->easingCurve());
d->positionNewPageAnimation->setDuration(style()->duration());
d->positionNewPageAnimation->setEndValue(QPointF(0, 0));
addAnimation(d->positionNewPageAnimation);
d->positionOldPageAnimation = new QPropertyAnimation;
d->positionOldPageAnimation->setPropertyName("pos");
d->positionOldPageAnimation->setEasingCurve(style()->easingCurve());
d->positionOldPageAnimation->setDuration(style()->duration());
d->positionOldPageAnimation->setStartValue(QPointF(0, 0));
addAnimation(d->positionOldPageAnimation);
}
MPageSwitchSlideAnimation::MPageSwitchSlideAnimation(MPageSwitchSlideAnimationPrivate *dd, QObject *parent) :
MPageSwitchAnimation(dd, parent)
{
}
void MPageSwitchSlideAnimation::updateState(QAbstractAnimation::State newState,
QAbstractAnimation::State oldState)
{
Q_D(MPageSwitchSlideAnimation);
Q_UNUSED(oldState);
if (newState != Running)
return;
d->positionNewPageAnimation->setTargetObject(newPage());
d->positionOldPageAnimation->setTargetObject(oldPage());
if (newPage()) {
if (transitionDirection() == ToParentPage)
d->positionNewPageAnimation->setStartValue(QPointF(newPage()->boundingRect().width(), 0));
else
d->positionNewPageAnimation->setStartValue(QPointF(-newPage()->boundingRect().width(), 0));
}
if (oldPage()) {
if (transitionDirection() == ToParentPage)
d->positionOldPageAnimation->setEndValue(QPointF(-oldPage()->boundingRect().width(), 0));
else
d->positionOldPageAnimation->setEndValue(QPointF(oldPage()->boundingRect().width(), 0));
}
}
M_REGISTER_ANIMATION(MPageSwitchSlideAnimation)
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
**************************************************************************/
#include "cmakeopenprojectwizard.h"
#include "cmakeprojectmanager.h"
#include <utils/pathchooser.h>
#include <projectexplorer/environment.h>
#include <QtGui/QVBoxLayout>
#include <QtGui/QFormLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QPlainTextEdit>
#include <QtCore/QDateTime>
#include <QtCore/QStringList>
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
///////
// Page Flow:
// Start (No .user file)
// |
// |---> In Source Build --> Page: Tell the user about that
// |--> Already existing cbp file (and new enough) --> Page: Ready to load the project
// |--> Page: Ask for cmd options, run generator
// |---> No in source Build --> Page: Ask the user for the build directory
// |--> Already existing cbp file (and new enough) --> Page: Ready to load the project
// |--> Page: Ask for cmd options, run generator
CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory)
: m_cmakeManager(cmakeManager),
m_sourceDirectory(sourceDirectory),
m_creatingCbpFiles(false)
{
int startid;
if (hasInSourceBuild()) {
startid = InSourcePageId;
m_buildDirectory = m_sourceDirectory;
} else {
startid = ShadowBuildPageId;
m_buildDirectory = m_sourceDirectory + "/qtcreator-build";
}
setPage(InSourcePageId, new InSourceBuildPage(this));
setPage(ShadowBuildPageId, new ShadowBuildPage(this));
setPage(XmlFileUpToDatePageId, new XmlFileUpToDatePage(this));
setPage(CMakeRunPageId, new CMakeRunPage(this));
setStartId(startid);
}
CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory,
const QStringList &needToCreate, const QStringList &needToUpdate)
: m_cmakeManager(cmakeManager),
m_sourceDirectory(sourceDirectory),
m_creatingCbpFiles(true)
{
foreach(const QString &buildDirectory, needToCreate)
addPage(new CMakeRunPage(this, buildDirectory, false));
foreach(const QString &buildDirectory, needToUpdate)
addPage(new CMakeRunPage(this, buildDirectory, true));
}
CMakeManager *CMakeOpenProjectWizard::cmakeManager() const
{
return m_cmakeManager;
}
int CMakeOpenProjectWizard::nextId() const
{
if (m_creatingCbpFiles)
return QWizard::nextId();
int cid = currentId();
if (cid == InSourcePageId) {
if (existsUpToDateXmlFile())
return XmlFileUpToDatePageId;
else
return CMakeRunPageId;
} else if (cid == ShadowBuildPageId) {
if (existsUpToDateXmlFile())
return XmlFileUpToDatePageId;
else
return CMakeRunPageId;
}
return -1;
}
bool CMakeOpenProjectWizard::hasInSourceBuild() const
{
QFileInfo fi(m_sourceDirectory + "/CMakeCache.txt");
if (fi.exists())
return true;
return false;
}
bool CMakeOpenProjectWizard::existsUpToDateXmlFile() const
{
QString cbpFile = CMakeManager::findCbpFile(QDir(buildDirectory()));
if (!cbpFile.isEmpty()) {
// We already have a cbp file
QFileInfo cbpFileInfo(cbpFile);
QFileInfo cmakeListsFileInfo(sourceDirectory() + "/CMakeLists.txt");
if (cbpFileInfo.lastModified() > cmakeListsFileInfo.lastModified())
return true;
}
return false;
}
QString CMakeOpenProjectWizard::buildDirectory() const
{
return m_buildDirectory;
}
QString CMakeOpenProjectWizard::sourceDirectory() const
{
return m_sourceDirectory;
}
void CMakeOpenProjectWizard::setBuildDirectory(const QString &directory)
{
m_buildDirectory = directory;
}
QStringList CMakeOpenProjectWizard::arguments() const
{
return m_arguments;
}
void CMakeOpenProjectWizard::setArguments(const QStringList &args)
{
m_arguments = args;
}
InSourceBuildPage::InSourceBuildPage(CMakeOpenProjectWizard *cmakeWizard)
: QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
setLayout(new QVBoxLayout);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("Qt Creator has detected an in source build. "
"This prevents out of souce builds, Qt Creator won't allow you to change the build directory. "
"If you want a out of source build, clean your source directory and open the project again"));
layout()->addWidget(label);
}
XmlFileUpToDatePage::XmlFileUpToDatePage(CMakeOpenProjectWizard *cmakeWizard)
: QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
setLayout(new QVBoxLayout);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("Qt Creator has found a recent cbp file, which Qt Creator parses to gather information about the project. "
"You can change the command line arguments used to create this file in the project mode. "
"Click finish to load the project"));
layout()->addWidget(label);
}
ShadowBuildPage::ShadowBuildPage(CMakeOpenProjectWizard *cmakeWizard)
: QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
QFormLayout *fl = new QFormLayout;
this->setLayout(fl);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("Please enter the directory in which you want to build your project. "
"Qt Creator recommends to not use the source directory for building. "
"This ensures that the source directory remains clean and enables multiple builds "
"with different settings."));
fl->addWidget(label);
m_pc = new Core::Utils::PathChooser(this);
m_pc->setPath(m_cmakeWizard->buildDirectory());
connect(m_pc, SIGNAL(changed()), this, SLOT(buildDirectoryChanged()));
fl->addRow("Build directory:", m_pc);
}
void ShadowBuildPage::buildDirectoryChanged()
{
m_cmakeWizard->setBuildDirectory(m_pc->path());
}
CMakeRunPage::CMakeRunPage(CMakeOpenProjectWizard *cmakeWizard)
: QWizardPage(cmakeWizard),
m_cmakeWizard(cmakeWizard),
m_complete(false)
{
initWidgets();
}
CMakeRunPage::CMakeRunPage(CMakeOpenProjectWizard *cmakeWizard, const QString &buildDirectory, bool update)
: QWizardPage(cmakeWizard),
m_cmakeWizard(cmakeWizard),
m_complete(false),
m_update(update),
m_presetBuildDirectory(buildDirectory)
{
initWidgets();
}
void CMakeRunPage::initWidgets()
{
QFormLayout *fl = new QFormLayout;
setLayout(fl);
m_descriptionLabel = new QLabel(this);
m_descriptionLabel->setWordWrap(true);
fl->addRow(m_descriptionLabel);
m_argumentsLineEdit = new QLineEdit(this);
//fl->addRow(tr("Arguments:"), m_argumentsLineEdit);
m_runCMake = new QPushButton(this);
m_runCMake->setText(tr("Run CMake"));
connect(m_runCMake, SIGNAL(clicked()), this, SLOT(runCMake()));
//fl->addWidget(m_runCMake);
QHBoxLayout *hbox = new QHBoxLayout;
hbox->addWidget(m_argumentsLineEdit);
hbox->addWidget(m_runCMake);
fl->addRow(tr("Arguments"), hbox);
m_output = new QPlainTextEdit(this);
m_output->setReadOnly(true);
fl->addRow(m_output);
}
void CMakeRunPage::initializePage()
{
if (m_presetBuildDirectory.isEmpty()) {
m_buildDirectory = m_cmakeWizard->buildDirectory();
m_descriptionLabel->setText(
tr("The directory %1 does not contain a cbp file. Qt Creator needs to create this file, by running cmake. "
"Some projects require command line arguments to the initial cmake call.").arg(m_buildDirectory));
} else {
m_buildDirectory = m_presetBuildDirectory;
// TODO tell the user more?
if (m_update)
m_descriptionLabel->setText(tr("The directory %1 contains an outdated .cbp file. Qt "
"Creator needs to update this file by running cmake. "
"If you want to add additional command line arguments, "
"add them in the below.").arg(m_buildDirectory));
else
m_descriptionLabel->setText(tr("The directory %1, specified in a buildconfiguration, "
"does not contain a cbp file. Qt Creator needs to "
"recreate this file, by running cmake. "
"Some projects require command line arguments to "
"the initial cmake call.").arg(m_buildDirectory));
}
}
void CMakeRunPage::runCMake()
{
m_runCMake->setEnabled(false);
m_argumentsLineEdit->setEnabled(false);
QStringList arguments = ProjectExplorer::Environment::parseCombinedArgString(m_argumentsLineEdit->text());
CMakeManager *cmakeManager = m_cmakeWizard->cmakeManager();
m_cmakeProcess = cmakeManager->createXmlFile(arguments, m_cmakeWizard->sourceDirectory(), m_buildDirectory);
connect(m_cmakeProcess, SIGNAL(readyRead()), this, SLOT(cmakeReadyRead()));
connect(m_cmakeProcess, SIGNAL(finished(int)), this, SLOT(cmakeFinished()));
}
void CMakeRunPage::cmakeReadyRead()
{
m_output->appendPlainText(m_cmakeProcess->readAll());
}
void CMakeRunPage::cmakeFinished()
{
m_runCMake->setEnabled(true);
m_argumentsLineEdit->setEnabled(true);
m_cmakeProcess->deleteLater();
m_cmakeProcess = 0;
m_cmakeWizard->setArguments(ProjectExplorer::Environment::parseCombinedArgString(m_argumentsLineEdit->text()));
//TODO Actually test that running cmake was finished, for setting this bool
m_complete = true;
emit completeChanged();
}
void CMakeRunPage::cleanupPage()
{
m_output->clear();
m_complete = false;
emit completeChanged();
}
bool CMakeRunPage::isComplete() const
{
return m_complete;
}
<commit_msg>Typo fixes for cmake wizard pages.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
**************************************************************************/
#include "cmakeopenprojectwizard.h"
#include "cmakeprojectmanager.h"
#include <utils/pathchooser.h>
#include <projectexplorer/environment.h>
#include <QtGui/QVBoxLayout>
#include <QtGui/QFormLayout>
#include <QtGui/QLabel>
#include <QtGui/QPushButton>
#include <QtGui/QPlainTextEdit>
#include <QtCore/QDateTime>
#include <QtCore/QStringList>
using namespace CMakeProjectManager;
using namespace CMakeProjectManager::Internal;
///////
// Page Flow:
// Start (No .user file)
// |
// |---> In Source Build --> Page: Tell the user about that
// |--> Already existing cbp file (and new enough) --> Page: Ready to load the project
// |--> Page: Ask for cmd options, run generator
// |---> No in source Build --> Page: Ask the user for the build directory
// |--> Already existing cbp file (and new enough) --> Page: Ready to load the project
// |--> Page: Ask for cmd options, run generator
CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory)
: m_cmakeManager(cmakeManager),
m_sourceDirectory(sourceDirectory),
m_creatingCbpFiles(false)
{
int startid;
if (hasInSourceBuild()) {
startid = InSourcePageId;
m_buildDirectory = m_sourceDirectory;
} else {
startid = ShadowBuildPageId;
m_buildDirectory = m_sourceDirectory + "/qtcreator-build";
}
setPage(InSourcePageId, new InSourceBuildPage(this));
setPage(ShadowBuildPageId, new ShadowBuildPage(this));
setPage(XmlFileUpToDatePageId, new XmlFileUpToDatePage(this));
setPage(CMakeRunPageId, new CMakeRunPage(this));
setStartId(startid);
}
CMakeOpenProjectWizard::CMakeOpenProjectWizard(CMakeManager *cmakeManager, const QString &sourceDirectory,
const QStringList &needToCreate, const QStringList &needToUpdate)
: m_cmakeManager(cmakeManager),
m_sourceDirectory(sourceDirectory),
m_creatingCbpFiles(true)
{
foreach(const QString &buildDirectory, needToCreate)
addPage(new CMakeRunPage(this, buildDirectory, false));
foreach(const QString &buildDirectory, needToUpdate)
addPage(new CMakeRunPage(this, buildDirectory, true));
}
CMakeManager *CMakeOpenProjectWizard::cmakeManager() const
{
return m_cmakeManager;
}
int CMakeOpenProjectWizard::nextId() const
{
if (m_creatingCbpFiles)
return QWizard::nextId();
int cid = currentId();
if (cid == InSourcePageId) {
if (existsUpToDateXmlFile())
return XmlFileUpToDatePageId;
else
return CMakeRunPageId;
} else if (cid == ShadowBuildPageId) {
if (existsUpToDateXmlFile())
return XmlFileUpToDatePageId;
else
return CMakeRunPageId;
}
return -1;
}
bool CMakeOpenProjectWizard::hasInSourceBuild() const
{
QFileInfo fi(m_sourceDirectory + "/CMakeCache.txt");
if (fi.exists())
return true;
return false;
}
bool CMakeOpenProjectWizard::existsUpToDateXmlFile() const
{
QString cbpFile = CMakeManager::findCbpFile(QDir(buildDirectory()));
if (!cbpFile.isEmpty()) {
// We already have a cbp file
QFileInfo cbpFileInfo(cbpFile);
QFileInfo cmakeListsFileInfo(sourceDirectory() + "/CMakeLists.txt");
if (cbpFileInfo.lastModified() > cmakeListsFileInfo.lastModified())
return true;
}
return false;
}
QString CMakeOpenProjectWizard::buildDirectory() const
{
return m_buildDirectory;
}
QString CMakeOpenProjectWizard::sourceDirectory() const
{
return m_sourceDirectory;
}
void CMakeOpenProjectWizard::setBuildDirectory(const QString &directory)
{
m_buildDirectory = directory;
}
QStringList CMakeOpenProjectWizard::arguments() const
{
return m_arguments;
}
void CMakeOpenProjectWizard::setArguments(const QStringList &args)
{
m_arguments = args;
}
InSourceBuildPage::InSourceBuildPage(CMakeOpenProjectWizard *cmakeWizard)
: QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
setLayout(new QVBoxLayout);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("Qt Creator has detected an in source build. "
"This prevents shadow builds, Qt Creator won't allow you to change the build directory. "
"If you want a shadow build, clean your source directory and open the project again."));
layout()->addWidget(label);
}
XmlFileUpToDatePage::XmlFileUpToDatePage(CMakeOpenProjectWizard *cmakeWizard)
: QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
setLayout(new QVBoxLayout);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("Qt Creator has found a recent cbp file, which Qt Creator will parse to gather information about the project. "
"You can change the command line arguments used to create this file in the project mode. "
"Click finish to load the project"));
layout()->addWidget(label);
}
ShadowBuildPage::ShadowBuildPage(CMakeOpenProjectWizard *cmakeWizard)
: QWizardPage(cmakeWizard), m_cmakeWizard(cmakeWizard)
{
QFormLayout *fl = new QFormLayout;
this->setLayout(fl);
QLabel *label = new QLabel(this);
label->setWordWrap(true);
label->setText(tr("Please enter the directory in which you want to build your project. "
"Qt Creator recommends to not use the source directory for building. "
"This ensures that the source directory remains clean and enables multiple builds "
"with different settings."));
fl->addWidget(label);
m_pc = new Core::Utils::PathChooser(this);
m_pc->setPath(m_cmakeWizard->buildDirectory());
connect(m_pc, SIGNAL(changed()), this, SLOT(buildDirectoryChanged()));
fl->addRow("Build directory:", m_pc);
}
void ShadowBuildPage::buildDirectoryChanged()
{
m_cmakeWizard->setBuildDirectory(m_pc->path());
}
CMakeRunPage::CMakeRunPage(CMakeOpenProjectWizard *cmakeWizard)
: QWizardPage(cmakeWizard),
m_cmakeWizard(cmakeWizard),
m_complete(false)
{
initWidgets();
}
CMakeRunPage::CMakeRunPage(CMakeOpenProjectWizard *cmakeWizard, const QString &buildDirectory, bool update)
: QWizardPage(cmakeWizard),
m_cmakeWizard(cmakeWizard),
m_complete(false),
m_update(update),
m_presetBuildDirectory(buildDirectory)
{
initWidgets();
}
void CMakeRunPage::initWidgets()
{
QFormLayout *fl = new QFormLayout;
setLayout(fl);
m_descriptionLabel = new QLabel(this);
m_descriptionLabel->setWordWrap(true);
fl->addRow(m_descriptionLabel);
m_argumentsLineEdit = new QLineEdit(this);
//fl->addRow(tr("Arguments:"), m_argumentsLineEdit);
m_runCMake = new QPushButton(this);
m_runCMake->setText(tr("Run CMake"));
connect(m_runCMake, SIGNAL(clicked()), this, SLOT(runCMake()));
//fl->addWidget(m_runCMake);
QHBoxLayout *hbox = new QHBoxLayout;
hbox->addWidget(m_argumentsLineEdit);
hbox->addWidget(m_runCMake);
fl->addRow(tr("Arguments"), hbox);
m_output = new QPlainTextEdit(this);
m_output->setReadOnly(true);
fl->addRow(m_output);
}
void CMakeRunPage::initializePage()
{
if (m_presetBuildDirectory.isEmpty()) {
m_buildDirectory = m_cmakeWizard->buildDirectory();
m_descriptionLabel->setText(
tr("The directory %1 does not contain a cbp file. Qt Creator needs to create this file by running cmake. "
"Some projects require command line arguments to the initial cmake call.").arg(m_buildDirectory));
} else {
m_buildDirectory = m_presetBuildDirectory;
if (m_update)
m_descriptionLabel->setText(tr("The directory %1 contains an outdated .cbp file. Qt "
"Creator needs to update this file by running cmake. "
"If you want to add additional command line arguments, "
"add them in the below. Note, that cmake remembers command "
"line arguments from the former runs.").arg(m_buildDirectory));
else
m_descriptionLabel->setText(tr("The directory %1 specified in a buildconfiguration, "
"does not contain a cbp file. Qt Creator needs to "
"recreate this file, by running cmake. "
"Some projects require command line arguments to "
"the initial cmake call. Note, that cmake remembers command "
"line arguments from the former runs.").arg(m_buildDirectory));
}
}
void CMakeRunPage::runCMake()
{
m_runCMake->setEnabled(false);
m_argumentsLineEdit->setEnabled(false);
QStringList arguments = ProjectExplorer::Environment::parseCombinedArgString(m_argumentsLineEdit->text());
CMakeManager *cmakeManager = m_cmakeWizard->cmakeManager();
m_cmakeProcess = cmakeManager->createXmlFile(arguments, m_cmakeWizard->sourceDirectory(), m_buildDirectory);
connect(m_cmakeProcess, SIGNAL(readyRead()), this, SLOT(cmakeReadyRead()));
connect(m_cmakeProcess, SIGNAL(finished(int)), this, SLOT(cmakeFinished()));
}
void CMakeRunPage::cmakeReadyRead()
{
m_output->appendPlainText(m_cmakeProcess->readAll());
}
void CMakeRunPage::cmakeFinished()
{
m_runCMake->setEnabled(true);
m_argumentsLineEdit->setEnabled(true);
m_cmakeProcess->deleteLater();
m_cmakeProcess = 0;
m_cmakeWizard->setArguments(ProjectExplorer::Environment::parseCombinedArgString(m_argumentsLineEdit->text()));
//TODO Actually test that running cmake was finished, for setting this bool
m_complete = true;
emit completeChanged();
}
void CMakeRunPage::cleanupPage()
{
m_output->clear();
m_complete = false;
emit completeChanged();
}
bool CMakeRunPage::isComplete() const
{
return m_complete;
}
<|endoftext|> |
<commit_before>
/*
* 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 "GrSoftwarePathRenderer.h"
#include "GrPaint.h"
#include "SkPaint.h"
#include "GrRenderTarget.h"
#include "GrContext.h"
#include "SkDraw.h"
#include "SkRasterClip.h"
#include "GrGpu.h"
////////////////////////////////////////////////////////////////////////////////
bool GrSoftwarePathRenderer::canDrawPath(const SkPath& path,
GrPathFill fill,
const GrDrawTarget* target,
bool antiAlias) const {
if (!antiAlias || NULL == fContext) {
// TODO: We could allow the SW path to also handle non-AA paths but
// this would mean that GrDefaultPathRenderer would never be called
// (since it appears after the SW renderer in the path renderer
// chain). Some testing would need to be done r.e. performance
// and consistency of the resulting images before removing
// the "!antiAlias" clause from the above test
return false;
}
return true;
}
namespace {
////////////////////////////////////////////////////////////////////////////////
SkPath::FillType gr_fill_to_sk_fill(GrPathFill fill) {
switch (fill) {
case kWinding_GrPathFill:
return SkPath::kWinding_FillType;
case kEvenOdd_GrPathFill:
return SkPath::kEvenOdd_FillType;
case kInverseWinding_GrPathFill:
return SkPath::kInverseWinding_FillType;
case kInverseEvenOdd_GrPathFill:
return SkPath::kInverseEvenOdd_FillType;
default:
GrCrash("Unexpected fill.");
return SkPath::kWinding_FillType;
}
}
////////////////////////////////////////////////////////////////////////////////
// gets device coord bounds of path (not considering the fill) and clip. The
// path bounds will be a subset of the clip bounds. returns false if
// path bounds would be empty.
bool get_path_and_clip_bounds(const GrDrawTarget* target,
const SkPath& path,
const GrVec* translate,
GrIRect* pathBounds,
GrIRect* clipBounds) {
// compute bounds as intersection of rt size, clip, and path
const GrRenderTarget* rt = target->getDrawState().getRenderTarget();
if (NULL == rt) {
return false;
}
*pathBounds = GrIRect::MakeWH(rt->width(), rt->height());
const GrClip& clip = target->getClip();
if (clip.hasConservativeBounds()) {
clip.getConservativeBounds().roundOut(clipBounds);
if (!pathBounds->intersect(*clipBounds)) {
return false;
}
} else {
// pathBounds is currently the rt extent, set clip bounds to that rect.
*clipBounds = *pathBounds;
}
GrRect pathSBounds = path.getBounds();
if (!pathSBounds.isEmpty()) {
if (NULL != translate) {
pathSBounds.offset(*translate);
}
target->getDrawState().getViewMatrix().mapRect(&pathSBounds,
pathSBounds);
GrIRect pathIBounds;
pathSBounds.roundOut(&pathIBounds);
if (!pathBounds->intersect(pathIBounds)) {
// set the correct path bounds, as this would be used later.
*pathBounds = pathIBounds;
return false;
}
} else {
*pathBounds = GrIRect::EmptyIRect();
return false;
}
return true;
}
/*
* Convert a boolean operation into a transfer mode code
*/
SkXfermode::Mode op_to_mode(SkRegion::Op op) {
static const SkXfermode::Mode modeMap[] = {
SkXfermode::kDstOut_Mode, // kDifference_Op
SkXfermode::kMultiply_Mode, // kIntersect_Op
SkXfermode::kSrcOver_Mode, // kUnion_Op
SkXfermode::kXor_Mode, // kXOR_Op
SkXfermode::kClear_Mode, // kReverseDifference_Op
SkXfermode::kSrc_Mode, // kReplace_Op
};
return modeMap[op];
}
}
/**
* Draw a single rect element of the clip stack into the accumulation bitmap
*/
void GrSWMaskHelper::draw(const GrRect& clientRect, SkRegion::Op op,
bool antiAlias, GrColor color) {
SkPaint paint;
SkXfermode* mode = SkXfermode::Create(op_to_mode(op));
paint.setXfermode(mode);
paint.setAntiAlias(antiAlias);
paint.setColor(color);
fDraw.drawRect(clientRect, paint);
SkSafeUnref(mode);
}
/**
* Draw a single path element of the clip stack into the accumulation bitmap
*/
void GrSWMaskHelper::draw(const SkPath& clientPath, SkRegion::Op op,
GrPathFill fill, bool antiAlias, GrColor color) {
SkPaint paint;
SkPath tmpPath;
const SkPath* pathToDraw = &clientPath;
if (kHairLine_GrPathFill == fill) {
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SK_Scalar1);
} else {
paint.setStyle(SkPaint::kFill_Style);
SkPath::FillType skfill = gr_fill_to_sk_fill(fill);
if (skfill != pathToDraw->getFillType()) {
tmpPath = *pathToDraw;
tmpPath.setFillType(skfill);
pathToDraw = &tmpPath;
}
}
SkXfermode* mode = SkXfermode::Create(op_to_mode(op));
paint.setXfermode(mode);
paint.setAntiAlias(antiAlias);
paint.setColor(color);
fDraw.drawPath(*pathToDraw, paint);
SkSafeUnref(mode);
}
bool GrSWMaskHelper::init(const GrIRect& pathDevBounds,
const GrPoint* translate,
bool useMatrix) {
if (useMatrix) {
fMatrix = fContext->getMatrix();
} else {
fMatrix.setIdentity();
}
if (NULL != translate) {
fMatrix.postTranslate(translate->fX, translate->fY);
}
fMatrix.postTranslate(-pathDevBounds.fLeft * SK_Scalar1,
-pathDevBounds.fTop * SK_Scalar1);
GrIRect bounds = GrIRect::MakeWH(pathDevBounds.width(),
pathDevBounds.height());
fBM.setConfig(SkBitmap::kA8_Config, bounds.fRight, bounds.fBottom);
if (!fBM.allocPixels()) {
return false;
}
sk_bzero(fBM.getPixels(), fBM.getSafeSize());
sk_bzero(&fDraw, sizeof(fDraw));
fRasterClip.setRect(bounds);
fDraw.fRC = &fRasterClip;
fDraw.fClip = &fRasterClip.bwRgn();
fDraw.fMatrix = &fMatrix;
fDraw.fBitmap = &fBM;
return true;
}
/**
* Get a texture (from the texture cache) of the correct size & format
*/
bool GrSWMaskHelper::getTexture(GrAutoScratchTexture* tex) {
GrTextureDesc desc;
desc.fWidth = fBM.width();
desc.fHeight = fBM.height();
desc.fConfig = kAlpha_8_GrPixelConfig;
tex->set(fContext, desc);
GrTexture* texture = tex->texture();
if (NULL == texture) {
return false;
}
return true;
}
/**
* Move the result of the software mask generation back to the gpu
*/
void GrSWMaskHelper::toTexture(GrTexture *texture, bool clearToWhite) {
SkAutoLockPixels alp(fBM);
// The destination texture is almost always larger than "fBM". Clear
// it appropriately so we don't get mask artifacts outside of the path's
// bounding box
// "texture" needs to be installed as the render target for the clear
// and the texture upload but cannot remain the render target upon
// returned. Callers typically use it as a texture and it would then
// be both source and dest.
GrDrawState::AutoRenderTargetRestore artr(fContext->getGpu()->drawState(),
texture->asRenderTarget());
if (clearToWhite) {
fContext->getGpu()->clear(NULL, SK_ColorWHITE);
} else {
fContext->getGpu()->clear(NULL, 0x00000000);
}
texture->writePixels(0, 0, fBM.width(), fBM.height(),
kAlpha_8_GrPixelConfig,
fBM.getPixels(), fBM.rowBytes());
}
namespace {
////////////////////////////////////////////////////////////////////////////////
/**
* sw rasterizes path to A8 mask using the context's matrix and uploads to a
* scratch texture.
*/
bool sw_draw_path_to_mask_texture(const SkPath& clientPath,
const GrIRect& pathDevBounds,
GrPathFill fill,
GrContext* context,
const GrPoint* translate,
GrAutoScratchTexture* tex,
bool antiAlias) {
GrSWMaskHelper helper(context);
if (!helper.init(pathDevBounds, translate, true)) {
return false;
}
helper.draw(clientPath, SkRegion::kReplace_Op,
fill, antiAlias, SK_ColorWHITE);
if (!helper.getTexture(tex)) {
return false;
}
helper.toTexture(tex->texture(), false);
return true;
}
////////////////////////////////////////////////////////////////////////////////
void draw_around_inv_path(GrDrawTarget* target,
GrDrawState::StageMask stageMask,
const GrIRect& clipBounds,
const GrIRect& pathBounds) {
GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask);
GrRect rect;
if (clipBounds.fTop < pathBounds.fTop) {
rect.iset(clipBounds.fLeft, clipBounds.fTop,
clipBounds.fRight, pathBounds.fTop);
target->drawSimpleRect(rect, NULL, stageMask);
}
if (clipBounds.fLeft < pathBounds.fLeft) {
rect.iset(clipBounds.fLeft, pathBounds.fTop,
pathBounds.fLeft, pathBounds.fBottom);
target->drawSimpleRect(rect, NULL, stageMask);
}
if (clipBounds.fRight > pathBounds.fRight) {
rect.iset(pathBounds.fRight, pathBounds.fTop,
clipBounds.fRight, pathBounds.fBottom);
target->drawSimpleRect(rect, NULL, stageMask);
}
if (clipBounds.fBottom > pathBounds.fBottom) {
rect.iset(clipBounds.fLeft, pathBounds.fBottom,
clipBounds.fRight, clipBounds.fBottom);
target->drawSimpleRect(rect, NULL, stageMask);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// return true on success; false on failure
bool GrSoftwarePathRenderer::onDrawPath(const SkPath& path,
GrPathFill fill,
const GrVec* translate,
GrDrawTarget* target,
GrDrawState::StageMask stageMask,
bool antiAlias) {
if (NULL == fContext) {
return false;
}
GrAutoScratchTexture ast;
GrIRect pathBounds, clipBounds;
if (!get_path_and_clip_bounds(target, path, translate,
&pathBounds, &clipBounds)) {
if (GrIsFillInverted(fill)) {
draw_around_inv_path(target, stageMask,
clipBounds, pathBounds);
}
return true;
}
if (sw_draw_path_to_mask_texture(path, pathBounds,
fill, fContext,
translate, &ast, antiAlias)) {
SkAutoTUnref<GrTexture> texture(ast.detach());
GrAssert(NULL != texture);
GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask);
enum {
// the SW path renderer shares this stage with glyph
// rendering (kGlyphMaskStage in GrBatchedTextContext)
kPathMaskStage = GrPaint::kTotalStages,
};
GrAssert(NULL == target->drawState()->getTexture(kPathMaskStage));
target->drawState()->setTexture(kPathMaskStage, texture);
target->drawState()->sampler(kPathMaskStage)->reset();
GrScalar w = GrIntToScalar(pathBounds.width());
GrScalar h = GrIntToScalar(pathBounds.height());
GrRect maskRect = GrRect::MakeWH(w / texture->width(),
h / texture->height());
const GrRect* srcRects[GrDrawState::kNumStages] = {NULL};
srcRects[kPathMaskStage] = &maskRect;
stageMask |= 1 << kPathMaskStage;
GrRect dstRect = GrRect::MakeLTRB(
SK_Scalar1* pathBounds.fLeft,
SK_Scalar1* pathBounds.fTop,
SK_Scalar1* pathBounds.fRight,
SK_Scalar1* pathBounds.fBottom);
target->drawRect(dstRect, NULL, stageMask, srcRects, NULL);
target->drawState()->setTexture(kPathMaskStage, NULL);
if (GrIsFillInverted(fill)) {
draw_around_inv_path(target, stageMask,
clipBounds, pathBounds);
}
return true;
}
return false;
}
<commit_msg>Reverting r4319<commit_after>
/*
* 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 "GrSoftwarePathRenderer.h"
#include "GrPaint.h"
#include "SkPaint.h"
#include "GrRenderTarget.h"
#include "GrContext.h"
#include "SkDraw.h"
#include "SkRasterClip.h"
#include "GrGpu.h"
////////////////////////////////////////////////////////////////////////////////
bool GrSoftwarePathRenderer::canDrawPath(const SkPath& path,
GrPathFill fill,
const GrDrawTarget* target,
bool antiAlias) const {
if (!antiAlias || NULL == fContext) {
// TODO: We could allow the SW path to also handle non-AA paths but
// this would mean that GrDefaultPathRenderer would never be called
// (since it appears after the SW renderer in the path renderer
// chain). Some testing would need to be done r.e. performance
// and consistency of the resulting images before removing
// the "!antiAlias" clause from the above test
return false;
}
return true;
}
namespace {
////////////////////////////////////////////////////////////////////////////////
SkPath::FillType gr_fill_to_sk_fill(GrPathFill fill) {
switch (fill) {
case kWinding_GrPathFill:
return SkPath::kWinding_FillType;
case kEvenOdd_GrPathFill:
return SkPath::kEvenOdd_FillType;
case kInverseWinding_GrPathFill:
return SkPath::kInverseWinding_FillType;
case kInverseEvenOdd_GrPathFill:
return SkPath::kInverseEvenOdd_FillType;
default:
GrCrash("Unexpected fill.");
return SkPath::kWinding_FillType;
}
}
////////////////////////////////////////////////////////////////////////////////
// gets device coord bounds of path (not considering the fill) and clip. The
// path bounds will be a subset of the clip bounds. returns false if
// path bounds would be empty.
bool get_path_and_clip_bounds(const GrDrawTarget* target,
const SkPath& path,
const GrVec* translate,
GrIRect* pathBounds,
GrIRect* clipBounds) {
// compute bounds as intersection of rt size, clip, and path
const GrRenderTarget* rt = target->getDrawState().getRenderTarget();
if (NULL == rt) {
return false;
}
*pathBounds = GrIRect::MakeWH(rt->width(), rt->height());
const GrClip& clip = target->getClip();
if (clip.hasConservativeBounds()) {
clip.getConservativeBounds().roundOut(clipBounds);
if (!pathBounds->intersect(*clipBounds)) {
return false;
}
} else {
// pathBounds is currently the rt extent, set clip bounds to that rect.
*clipBounds = *pathBounds;
}
GrRect pathSBounds = path.getBounds();
if (!pathSBounds.isEmpty()) {
if (NULL != translate) {
pathSBounds.offset(*translate);
}
target->getDrawState().getViewMatrix().mapRect(&pathSBounds,
pathSBounds);
GrIRect pathIBounds;
pathSBounds.roundOut(&pathIBounds);
if (!pathBounds->intersect(pathIBounds)) {
// set the correct path bounds, as this would be used later.
*pathBounds = pathIBounds;
return false;
}
} else {
*pathBounds = GrIRect::EmptyIRect();
return false;
}
return true;
}
/*
* Convert a boolean operation into a transfer mode code
*/
SkXfermode::Mode op_to_mode(SkRegion::Op op) {
static const SkXfermode::Mode modeMap[] = {
SkXfermode::kDstOut_Mode, // kDifference_Op
SkXfermode::kMultiply_Mode, // kIntersect_Op
SkXfermode::kSrcOver_Mode, // kUnion_Op
SkXfermode::kXor_Mode, // kXOR_Op
SkXfermode::kClear_Mode, // kReverseDifference_Op
SkXfermode::kSrc_Mode, // kReplace_Op
};
return modeMap[op];
}
}
/**
* Draw a single rect element of the clip stack into the accumulation bitmap
*/
void GrSWMaskHelper::draw(const GrRect& clientRect, SkRegion::Op op,
bool antiAlias, GrColor color) {
SkPaint paint;
SkXfermode* mode = SkXfermode::Create(op_to_mode(op));
paint.setXfermode(mode);
paint.setAntiAlias(antiAlias);
paint.setColor(color);
fDraw.drawRect(clientRect, paint);
SkSafeUnref(mode);
}
/**
* Draw a single path element of the clip stack into the accumulation bitmap
*/
void GrSWMaskHelper::draw(const SkPath& clientPath, SkRegion::Op op,
GrPathFill fill, bool antiAlias, GrColor color) {
SkPaint paint;
SkPath tmpPath;
const SkPath* pathToDraw = &clientPath;
if (kHairLine_GrPathFill == fill) {
paint.setStyle(SkPaint::kStroke_Style);
paint.setStrokeWidth(SK_Scalar1);
} else {
paint.setStyle(SkPaint::kFill_Style);
SkPath::FillType skfill = gr_fill_to_sk_fill(fill);
if (skfill != pathToDraw->getFillType()) {
tmpPath = *pathToDraw;
tmpPath.setFillType(skfill);
pathToDraw = &tmpPath;
}
}
SkXfermode* mode = SkXfermode::Create(op_to_mode(op));
paint.setXfermode(mode);
paint.setAntiAlias(antiAlias);
paint.setColor(color);
fDraw.drawPath(*pathToDraw, paint);
SkSafeUnref(mode);
}
bool GrSWMaskHelper::init(const GrIRect& pathDevBounds,
const GrPoint* translate,
bool useMatrix) {
if (useMatrix) {
fMatrix = fContext->getMatrix();
} else {
fMatrix.setIdentity();
}
if (NULL != translate) {
fMatrix.postTranslate(translate->fX, translate->fY);
}
fMatrix.postTranslate(-pathDevBounds.fLeft * SK_Scalar1,
-pathDevBounds.fTop * SK_Scalar1);
GrIRect bounds = GrIRect::MakeWH(pathDevBounds.width(),
pathDevBounds.height());
fBM.setConfig(SkBitmap::kA8_Config, bounds.fRight, bounds.fBottom);
if (!fBM.allocPixels()) {
return false;
}
sk_bzero(fBM.getPixels(), fBM.getSafeSize());
sk_bzero(&fDraw, sizeof(fDraw));
fRasterClip.setRect(bounds);
fDraw.fRC = &fRasterClip;
fDraw.fClip = &fRasterClip.bwRgn();
fDraw.fMatrix = &fMatrix;
fDraw.fBitmap = &fBM;
return true;
}
/**
* Get a texture (from the texture cache) of the correct size & format
*/
bool GrSWMaskHelper::getTexture(GrAutoScratchTexture* tex) {
GrTextureDesc desc;
desc.fWidth = fBM.width();
desc.fHeight = fBM.height();
desc.fConfig = kAlpha_8_GrPixelConfig;
tex->set(fContext, desc);
GrTexture* texture = tex->texture();
if (NULL == texture) {
return false;
}
return true;
}
/**
* Move the result of the software mask generation back to the gpu
*/
void GrSWMaskHelper::toTexture(GrTexture *texture, bool clearToWhite) {
SkAutoLockPixels alp(fBM);
// The destination texture is almost always larger than "fBM". Clear
// it appropriately so we don't get mask artifacts outside of the path's
// bounding box
// "texture" needs to be installed as the render target for the clear
// and the texture upload but cannot remain the render target upon
// returned. Callers typically use it as a texture and it would then
// be both source and dest.
GrDrawState::AutoRenderTargetRestore artr(fContext->getGpu()->drawState(),
texture->asRenderTarget());
if (clearToWhite) {
fContext->getGpu()->clear(NULL, SK_ColorWHITE);
} else {
fContext->getGpu()->clear(NULL, 0x00000000);
}
texture->writePixels(0, 0, fBM.width(), fBM.height(),
kAlpha_8_GrPixelConfig,
fBM.getPixels(), fBM.rowBytes());
}
namespace {
////////////////////////////////////////////////////////////////////////////////
/**
* sw rasterizes path to A8 mask using the context's matrix and uploads to a
* scratch texture.
*/
bool sw_draw_path_to_mask_texture(const SkPath& clientPath,
const GrIRect& pathDevBounds,
GrPathFill fill,
GrContext* context,
const GrPoint* translate,
GrAutoScratchTexture* tex,
bool antiAlias) {
GrSWMaskHelper helper(context);
if (!helper.init(pathDevBounds, translate, true)) {
return false;
}
helper.draw(clientPath, SkRegion::kReplace_Op,
fill, antiAlias, SK_ColorWHITE);
if (!helper.getTexture(tex)) {
return false;
}
helper.toTexture(tex->texture(), false);
return true;
}
////////////////////////////////////////////////////////////////////////////////
void draw_around_inv_path(GrDrawTarget* target,
GrDrawState::StageMask stageMask,
const GrIRect& clipBounds,
const GrIRect& pathBounds) {
GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask);
GrRect rect;
if (clipBounds.fTop < pathBounds.fTop) {
rect.iset(clipBounds.fLeft, clipBounds.fTop,
clipBounds.fRight, pathBounds.fTop);
target->drawSimpleRect(rect, NULL, stageMask);
}
if (clipBounds.fLeft < pathBounds.fLeft) {
rect.iset(clipBounds.fLeft, pathBounds.fTop,
pathBounds.fLeft, pathBounds.fBottom);
target->drawSimpleRect(rect, NULL, stageMask);
}
if (clipBounds.fRight > pathBounds.fRight) {
rect.iset(pathBounds.fRight, pathBounds.fTop,
clipBounds.fRight, pathBounds.fBottom);
target->drawSimpleRect(rect, NULL, stageMask);
}
if (clipBounds.fBottom > pathBounds.fBottom) {
rect.iset(clipBounds.fLeft, pathBounds.fBottom,
clipBounds.fRight, clipBounds.fBottom);
target->drawSimpleRect(rect, NULL, stageMask);
}
}
}
////////////////////////////////////////////////////////////////////////////////
// return true on success; false on failure
bool GrSoftwarePathRenderer::onDrawPath(const SkPath& path,
GrPathFill fill,
const GrVec* translate,
GrDrawTarget* target,
GrDrawState::StageMask stageMask,
bool antiAlias) {
if (NULL == fContext) {
return false;
}
GrAutoScratchTexture ast;
GrIRect pathBounds, clipBounds;
if (!get_path_and_clip_bounds(target, path, translate,
&pathBounds, &clipBounds)) {
if (GrIsFillInverted(fill)) {
draw_around_inv_path(target, stageMask,
clipBounds, pathBounds);
}
return true;
}
if (sw_draw_path_to_mask_texture(path, pathBounds,
fill, fContext,
translate, &ast, antiAlias)) {
#if 1
GrTexture* texture = ast.texture();
#else
SkAutoTUnref<GrTexture> texture(ast.detach());
#endif
GrAssert(NULL != texture);
GrDrawTarget::AutoDeviceCoordDraw adcd(target, stageMask);
enum {
// the SW path renderer shares this stage with glyph
// rendering (kGlyphMaskStage in GrBatchedTextContext)
kPathMaskStage = GrPaint::kTotalStages,
};
GrAssert(NULL == target->drawState()->getTexture(kPathMaskStage));
target->drawState()->setTexture(kPathMaskStage, texture);
target->drawState()->sampler(kPathMaskStage)->reset();
GrScalar w = GrIntToScalar(pathBounds.width());
GrScalar h = GrIntToScalar(pathBounds.height());
GrRect maskRect = GrRect::MakeWH(w / texture->width(),
h / texture->height());
const GrRect* srcRects[GrDrawState::kNumStages] = {NULL};
srcRects[kPathMaskStage] = &maskRect;
stageMask |= 1 << kPathMaskStage;
GrRect dstRect = GrRect::MakeLTRB(
SK_Scalar1* pathBounds.fLeft,
SK_Scalar1* pathBounds.fTop,
SK_Scalar1* pathBounds.fRight,
SK_Scalar1* pathBounds.fBottom);
target->drawRect(dstRect, NULL, stageMask, srcRects, NULL);
target->drawState()->setTexture(kPathMaskStage, NULL);
if (GrIsFillInverted(fill)) {
draw_around_inv_path(target, stageMask,
clipBounds, pathBounds);
}
return true;
}
return false;
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2005-2017 by the FIFE team *
* http://www.fifengine.net *
* This file is part of FIFE. *
* *
* FIFE is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
#if defined( WIN32 )
#include <windows.h>
#include <SDL.h>
#endif
#if defined( __unix__ )
#include <X11/Xcursor/Xcursor.h>
#endif
// 3rd party library includes
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "util/structures/rect.h"
#include "util/time/timemanager.h"
#include "util/log/logger.h"
#include "video/imagemanager.h"
#include "animation.h"
#include "image.h"
#include "renderbackend.h"
#include "cursor.h"
#if defined( WIN32 )
// From SDL_sysmouse.c
struct WMcursor {
HCURSOR curs;
#ifndef _WIN32_WCE
Uint8 *ands;
Uint8 *xors;
#endif
};
#endif
#if defined( __unix__ )
// Stops the compiler from confusing it with FIFE:Cursor
typedef Cursor XCursor;
// From SDL_x11mouse.c
struct WMcursor {
Cursor x_cursor;
};
#endif
namespace FIFE {
/** Logger to use for this source file.
* @relates Logger
*/
static Logger _log(LM_GUI); //@todo We should have a log module for cursor
Cursor::Cursor(RenderBackend* renderbackend):
m_cursor_id(NC_ARROW),
m_cursor_type(CURSOR_NATIVE),
m_drag_type(CURSOR_NONE),
m_native_cursor(NULL),
m_renderbackend(renderbackend),
m_animtime(0),
m_drag_animtime(0),
m_drag_offset_x(0),
m_drag_offset_y(0),
m_mx(0),
m_my(0),
m_timemanager(TimeManager::instance()),
m_invalidated(false) {
assert(m_timemanager);
set(m_cursor_id);
}
void Cursor::set(uint32_t cursor_id) {
m_cursor_type = CURSOR_NATIVE;
if (!SDL_ShowCursor(1)) {
SDL_PumpEvents();
}
setNativeCursor(cursor_id);
m_cursor_image.reset();
m_cursor_animation.reset();
}
void Cursor::set(ImagePtr image) {
assert(image != 0);
m_cursor_image = image;
m_cursor_type = CURSOR_IMAGE;
if (SDL_ShowCursor(0)) {
SDL_PumpEvents();
}
m_cursor_id = NC_ARROW;
m_cursor_animation.reset();
}
void Cursor::set(AnimationPtr anim) {
assert(anim != 0);
m_cursor_animation = anim;
m_cursor_type = CURSOR_ANIMATION;
if (SDL_ShowCursor(0)) {
SDL_PumpEvents();
}
m_animtime = m_timemanager->getTime();
m_cursor_id = NC_ARROW;
m_cursor_image.reset();
}
void Cursor::setDrag(ImagePtr image, int32_t drag_offset_x, int32_t drag_offset_y) {
assert(image != 0);
m_cursor_drag_image = image;
m_drag_type = CURSOR_IMAGE;
m_drag_offset_x = drag_offset_x;
m_drag_offset_y = drag_offset_y;
m_cursor_drag_animation.reset();
}
void Cursor::setDrag(AnimationPtr anim, int32_t drag_offset_x, int32_t drag_offset_y) {
assert(anim != 0);
m_cursor_drag_animation = anim;
m_drag_type = CURSOR_ANIMATION;
m_drag_offset_x = drag_offset_x;
m_drag_offset_y = drag_offset_y;
m_drag_animtime = m_timemanager->getTime();
m_cursor_drag_image.reset();
}
void Cursor::resetDrag() {
m_drag_type = CURSOR_NONE;
m_drag_animtime = 0;
m_drag_offset_x = 0;
m_drag_offset_y = 0;
m_cursor_drag_animation.reset();
m_cursor_drag_image.reset();
}
void Cursor::setPosition(uint32_t x, uint32_t y) {
m_mx = x;
m_my = y;
SDL_WarpMouseInWindow(RenderBackend::instance()->getWindow(), m_mx, m_my);
}
void Cursor::getPosition(int32_t* x, int32_t* y) {
*x = m_mx;
*y = m_my;
}
void Cursor::invalidate() {
if (m_native_cursor != NULL) {
SDL_FreeCursor(m_native_cursor);
m_native_cursor = NULL;
m_invalidated = true;
}
}
void Cursor::draw() {
if (m_invalidated) {
if (m_cursor_type != CURSOR_ANIMATION || m_cursor_type == CURSOR_IMAGE ) {
set(m_cursor_id);
}
m_invalidated = false;
}
SDL_GetMouseState(&m_mx, &m_my);
if ((m_cursor_type == CURSOR_NATIVE) && (m_drag_type == CURSOR_NONE)) {
return;
}
// render possible drag image
ImagePtr img;
if (m_drag_type == CURSOR_IMAGE) {
img = m_cursor_drag_image;
}
else if (m_drag_type == CURSOR_ANIMATION) {
int32_t animtime = (m_timemanager->getTime() - m_drag_animtime) % m_cursor_drag_animation->getDuration();
img = m_cursor_drag_animation->getFrameByTimestamp(animtime);
}
if (img != 0) {
Rect area(m_mx + m_drag_offset_x + img->getXShift(), m_my + m_drag_offset_y + img->getYShift(), img->getWidth(), img->getHeight());
m_renderbackend->pushClipArea(area, false);
img->render(area);
m_renderbackend->renderVertexArrays();
m_renderbackend->popClipArea();
}
ImagePtr img2;
// render possible cursor image
if (m_cursor_type == CURSOR_IMAGE) {
img2 = m_cursor_image;
}
else if (m_cursor_type == CURSOR_ANIMATION) {
int32_t animtime = (m_timemanager->getTime() - m_animtime) % m_cursor_animation->getDuration();
img2 = m_cursor_animation->getFrameByTimestamp(animtime);
}
if (img2 != 0) {
Rect area(m_mx + img2->getXShift(), m_my + img2->getYShift(), img2->getWidth(), img2->getHeight());
m_renderbackend->pushClipArea(area, false);
img2->render(area);
m_renderbackend->renderVertexArrays();
m_renderbackend->popClipArea();
}
}
uint32_t Cursor::getNativeId(uint32_t cursor_id) {
switch (cursor_id) {
case NC_ARROW:
return SDL_SYSTEM_CURSOR_ARROW;
case NC_IBEAM:
return SDL_SYSTEM_CURSOR_IBEAM;
case NC_WAIT:
return SDL_SYSTEM_CURSOR_WAIT;
case NC_CROSS:
return SDL_SYSTEM_CURSOR_CROSSHAIR;
case NC_WAITARROW:
return SDL_SYSTEM_CURSOR_WAITARROW;
case NC_RESIZENWSE:
return SDL_SYSTEM_CURSOR_SIZENWSE;
case NC_RESIZENESW:
return SDL_SYSTEM_CURSOR_SIZENESW;
case NC_RESIZEWE:
return SDL_SYSTEM_CURSOR_SIZEWE;
case NC_RESIZENS:
return SDL_SYSTEM_CURSOR_SIZENS;
case NC_RESIZEALL:
return SDL_SYSTEM_CURSOR_SIZEALL;
case NC_NO:
return SDL_SYSTEM_CURSOR_NO;
case NC_HAND:
return SDL_SYSTEM_CURSOR_HAND;
}
return cursor_id;
}
void Cursor::setNativeCursor(uint32_t cursor_id) {
cursor_id = getNativeId(cursor_id);
SDL_Cursor* cursor = SDL_CreateSystemCursor(static_cast<SDL_SystemCursor>(cursor_id));
if (!cursor) {
FL_WARN(_log, "Cursor: No cursor matching cursor_id was found.");
return;
}
m_native_cursor = cursor;
SDL_SetCursor(cursor);
}
}
<commit_msg>Removed leftover stuff from Cursor. Refs #991 I see no reason to keep XCursor and WMCursor around. Cursor only needs SDL.<commit_after>/***************************************************************************
* Copyright (C) 2005-2017 by the FIFE team *
* http://www.fifengine.net *
* This file is part of FIFE. *
* *
* FIFE is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public *
* License along with this library; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
// Standard C++ library includes
// 3rd party library includes
#include <SDL.h>
// FIFE includes
// These includes are split up in two parts, separated by one empty line
// First block: files included from the FIFE root src directory
// Second block: files included from the same folder
#include "util/structures/rect.h"
#include "util/time/timemanager.h"
#include "util/log/logger.h"
#include "video/imagemanager.h"
#include "animation.h"
#include "image.h"
#include "renderbackend.h"
#include "cursor.h"
namespace FIFE {
/** Logger to use for this source file.
* @relates Logger
*/
static Logger _log(LM_GUI); //@todo We should have a log module for cursor
Cursor::Cursor(RenderBackend* renderbackend):
m_cursor_id(NC_ARROW),
m_cursor_type(CURSOR_NATIVE),
m_drag_type(CURSOR_NONE),
m_native_cursor(NULL),
m_renderbackend(renderbackend),
m_animtime(0),
m_drag_animtime(0),
m_drag_offset_x(0),
m_drag_offset_y(0),
m_mx(0),
m_my(0),
m_timemanager(TimeManager::instance()),
m_invalidated(false) {
assert(m_timemanager);
set(m_cursor_id);
}
void Cursor::set(uint32_t cursor_id) {
m_cursor_type = CURSOR_NATIVE;
if (!SDL_ShowCursor(1)) {
SDL_PumpEvents();
}
setNativeCursor(cursor_id);
m_cursor_image.reset();
m_cursor_animation.reset();
}
void Cursor::set(ImagePtr image) {
assert(image != 0);
m_cursor_image = image;
m_cursor_type = CURSOR_IMAGE;
if (SDL_ShowCursor(0)) {
SDL_PumpEvents();
}
m_cursor_id = NC_ARROW;
m_cursor_animation.reset();
}
void Cursor::set(AnimationPtr anim) {
assert(anim != 0);
m_cursor_animation = anim;
m_cursor_type = CURSOR_ANIMATION;
if (SDL_ShowCursor(0)) {
SDL_PumpEvents();
}
m_animtime = m_timemanager->getTime();
m_cursor_id = NC_ARROW;
m_cursor_image.reset();
}
void Cursor::setDrag(ImagePtr image, int32_t drag_offset_x, int32_t drag_offset_y) {
assert(image != 0);
m_cursor_drag_image = image;
m_drag_type = CURSOR_IMAGE;
m_drag_offset_x = drag_offset_x;
m_drag_offset_y = drag_offset_y;
m_cursor_drag_animation.reset();
}
void Cursor::setDrag(AnimationPtr anim, int32_t drag_offset_x, int32_t drag_offset_y) {
assert(anim != 0);
m_cursor_drag_animation = anim;
m_drag_type = CURSOR_ANIMATION;
m_drag_offset_x = drag_offset_x;
m_drag_offset_y = drag_offset_y;
m_drag_animtime = m_timemanager->getTime();
m_cursor_drag_image.reset();
}
void Cursor::resetDrag() {
m_drag_type = CURSOR_NONE;
m_drag_animtime = 0;
m_drag_offset_x = 0;
m_drag_offset_y = 0;
m_cursor_drag_animation.reset();
m_cursor_drag_image.reset();
}
void Cursor::setPosition(uint32_t x, uint32_t y) {
m_mx = x;
m_my = y;
SDL_WarpMouseInWindow(RenderBackend::instance()->getWindow(), m_mx, m_my);
}
void Cursor::getPosition(int32_t* x, int32_t* y) {
*x = m_mx;
*y = m_my;
}
void Cursor::invalidate() {
if (m_native_cursor != NULL) {
SDL_FreeCursor(m_native_cursor);
m_native_cursor = NULL;
m_invalidated = true;
}
}
void Cursor::draw() {
if (m_invalidated) {
if (m_cursor_type != CURSOR_ANIMATION || m_cursor_type == CURSOR_IMAGE ) {
set(m_cursor_id);
}
m_invalidated = false;
}
SDL_GetMouseState(&m_mx, &m_my);
if ((m_cursor_type == CURSOR_NATIVE) && (m_drag_type == CURSOR_NONE)) {
return;
}
// render possible drag image
ImagePtr img;
if (m_drag_type == CURSOR_IMAGE) {
img = m_cursor_drag_image;
}
else if (m_drag_type == CURSOR_ANIMATION) {
int32_t animtime = (m_timemanager->getTime() - m_drag_animtime) % m_cursor_drag_animation->getDuration();
img = m_cursor_drag_animation->getFrameByTimestamp(animtime);
}
if (img != 0) {
Rect area(m_mx + m_drag_offset_x + img->getXShift(), m_my + m_drag_offset_y + img->getYShift(), img->getWidth(), img->getHeight());
m_renderbackend->pushClipArea(area, false);
img->render(area);
m_renderbackend->renderVertexArrays();
m_renderbackend->popClipArea();
}
ImagePtr img2;
// render possible cursor image
if (m_cursor_type == CURSOR_IMAGE) {
img2 = m_cursor_image;
}
else if (m_cursor_type == CURSOR_ANIMATION) {
int32_t animtime = (m_timemanager->getTime() - m_animtime) % m_cursor_animation->getDuration();
img2 = m_cursor_animation->getFrameByTimestamp(animtime);
}
if (img2 != 0) {
Rect area(m_mx + img2->getXShift(), m_my + img2->getYShift(), img2->getWidth(), img2->getHeight());
m_renderbackend->pushClipArea(area, false);
img2->render(area);
m_renderbackend->renderVertexArrays();
m_renderbackend->popClipArea();
}
}
uint32_t Cursor::getNativeId(uint32_t cursor_id) {
switch (cursor_id) {
case NC_ARROW:
return SDL_SYSTEM_CURSOR_ARROW;
case NC_IBEAM:
return SDL_SYSTEM_CURSOR_IBEAM;
case NC_WAIT:
return SDL_SYSTEM_CURSOR_WAIT;
case NC_CROSS:
return SDL_SYSTEM_CURSOR_CROSSHAIR;
case NC_WAITARROW:
return SDL_SYSTEM_CURSOR_WAITARROW;
case NC_RESIZENWSE:
return SDL_SYSTEM_CURSOR_SIZENWSE;
case NC_RESIZENESW:
return SDL_SYSTEM_CURSOR_SIZENESW;
case NC_RESIZEWE:
return SDL_SYSTEM_CURSOR_SIZEWE;
case NC_RESIZENS:
return SDL_SYSTEM_CURSOR_SIZENS;
case NC_RESIZEALL:
return SDL_SYSTEM_CURSOR_SIZEALL;
case NC_NO:
return SDL_SYSTEM_CURSOR_NO;
case NC_HAND:
return SDL_SYSTEM_CURSOR_HAND;
}
return cursor_id;
}
void Cursor::setNativeCursor(uint32_t cursor_id) {
cursor_id = getNativeId(cursor_id);
SDL_Cursor* cursor = SDL_CreateSystemCursor(static_cast<SDL_SystemCursor>(cursor_id));
if (!cursor) {
FL_WARN(_log, "Cursor: No cursor matching cursor_id was found.");
return;
}
m_native_cursor = cursor;
SDL_SetCursor(cursor);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: PageMasterPropHdl.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: th $ $Date: 2001-05-11 10:52:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_
#include "PageMasterPropHdl.hxx"
#endif
#ifndef _XMLOFF_XMLKYWD_HXX
#include "xmlkywd.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLNUMI_HXX
#include "xmlnumi.hxx"
#endif
#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::comphelper;
//______________________________________________________________________________
#define DEFAULT_PAPERTRAY (sal_Int32(-1))
//______________________________________________________________________________
// property handler for style:page-usage (style::PageStyleLayout)
XMLPMPropHdl_PageStyleLayout::~XMLPMPropHdl_PageStyleLayout()
{
}
sal_Bool XMLPMPropHdl_PageStyleLayout::equals( const Any& rAny1, const Any& rAny2 ) const
{
style::PageStyleLayout eLayout1, eLayout2;
return ((rAny1 >>= eLayout1) && (rAny2 >>= eLayout2)) ? (eLayout1 == eLayout2) : sal_False;
}
sal_Bool XMLPMPropHdl_PageStyleLayout::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_True;
if( rStrImpValue.compareToAscii( sXML_all ) == 0 )
rValue <<= PageStyleLayout_ALL;
else if( rStrImpValue.compareToAscii( sXML_left ) == 0 )
rValue <<= PageStyleLayout_LEFT;
else if( rStrImpValue.compareToAscii( sXML_right ) == 0 )
rValue <<= PageStyleLayout_RIGHT;
else if( rStrImpValue.compareToAscii( sXML_mirrored ) == 0 )
rValue <<= PageStyleLayout_MIRRORED;
else
bRet = sal_False;
return bRet;
}
sal_Bool XMLPMPropHdl_PageStyleLayout::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
PageStyleLayout eLayout;
if( rValue >>= eLayout )
{
bRet = sal_True;
switch( eLayout )
{
case PageStyleLayout_ALL:
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_all ) );
break;
case PageStyleLayout_LEFT:
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_left ) );
break;
case PageStyleLayout_RIGHT:
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_right ) );
break;
case PageStyleLayout_MIRRORED:
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_mirrored ) );
break;
default:
bRet = sal_False;
}
}
return bRet;
}
//______________________________________________________________________________
// property handler for style:num-format (style::NumberingType)
XMLPMPropHdl_NumFormat::~XMLPMPropHdl_NumFormat()
{
}
sal_Bool XMLPMPropHdl_NumFormat::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Int16 nSync;
sal_Int16 nNumType = NumberingType::NUMBER_NONE;
rUnitConverter.convertNumFormat( nNumType, rStrImpValue, OUString(),
sal_True );
if( !(rValue >>= nSync) )
nSync = NumberingType::NUMBER_NONE;
// if num-letter-sync appears before num-format, the function
// XMLPMPropHdl_NumLetterSync::importXML() sets the value
// NumberingType::CHARS_LOWER_LETTER_N
if( nSync == NumberingType::CHARS_LOWER_LETTER_N )
{
switch( nNumType )
{
case NumberingType::CHARS_LOWER_LETTER:
nNumType = NumberingType::CHARS_LOWER_LETTER_N;
break;
case NumberingType::CHARS_UPPER_LETTER:
nNumType = NumberingType::CHARS_UPPER_LETTER_N;
break;
}
}
rValue <<= nNumType;
return sal_True;
}
sal_Bool XMLPMPropHdl_NumFormat::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_Int16 nNumType;
if( rValue >>= nNumType )
{
OUStringBuffer aBuffer( 10 );
rUnitConverter.convertNumFormat( aBuffer, nNumType );
rStrExpValue = aBuffer.makeStringAndClear();
bRet = rStrExpValue.getLength() > 0;
}
return bRet;
}
//______________________________________________________________________________
// property handler for style:num-letter-sync (style::NumberingType)
XMLPMPropHdl_NumLetterSync::~XMLPMPropHdl_NumLetterSync()
{
}
sal_Bool XMLPMPropHdl_NumLetterSync::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Int16 nNumType;
sal_Int16 nSync = NumberingType::NUMBER_NONE;
rUnitConverter.convertNumFormat( nSync, rStrImpValue,
OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_a ) ),
sal_True );
if( !(rValue >>= nNumType) )
nNumType = NumberingType::NUMBER_NONE;
if( nSync == NumberingType::CHARS_LOWER_LETTER_N )
{
switch( nNumType )
{
case NumberingType::CHARS_LOWER_LETTER:
nNumType = NumberingType::CHARS_LOWER_LETTER_N;
break;
case NumberingType::CHARS_UPPER_LETTER:
nNumType = NumberingType::CHARS_UPPER_LETTER_N;
break;
}
}
rValue <<= nNumType;
return sal_True;
}
sal_Bool XMLPMPropHdl_NumLetterSync::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_Int16 nNumType;
if( rValue >>= nNumType )
{
OUStringBuffer aBuffer( 5 );
rUnitConverter.convertNumLetterSync( aBuffer, nNumType );
rStrExpValue = aBuffer.makeStringAndClear();
bRet = rStrExpValue.getLength() > 0;
}
return bRet;
}
//______________________________________________________________________________
// property handler for style:paper-tray-number
XMLPMPropHdl_PaperTrayNumber::~XMLPMPropHdl_PaperTrayNumber()
{
}
sal_Bool XMLPMPropHdl_PaperTrayNumber::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if( rStrImpValue.compareToAscii( sXML_default ) == 0 )
{
rValue <<= DEFAULT_PAPERTRAY;
bRet = sal_True;
}
else
{
sal_Int32 nPaperTray;
if( SvXMLUnitConverter::convertNumber( nPaperTray, rStrImpValue, 0 ) )
{
rValue <<= nPaperTray;
bRet = sal_True;
}
}
return bRet;
}
sal_Bool XMLPMPropHdl_PaperTrayNumber::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_Int32 nPaperTray;
if( rValue >>= nPaperTray )
{
if( nPaperTray == DEFAULT_PAPERTRAY )
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_default ) );
else
{
OUStringBuffer aBuffer;
SvXMLUnitConverter::convertNumber( aBuffer, nPaperTray );
rStrExpValue = aBuffer.makeStringAndClear();
}
bRet = sal_True;
}
return bRet;
}
//______________________________________________________________________________
// property handler for style:print
XMLPMPropHdl_Print::XMLPMPropHdl_Print( const sal_Char* sValue ) :
sAttrValue( OUString::createFromAscii( sValue ) )
{
}
XMLPMPropHdl_Print::~XMLPMPropHdl_Print()
{
}
sal_Bool XMLPMPropHdl_Print::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Unicode cToken = ' ';
sal_Int32 nTokenIndex = 0;
sal_Bool bFound = sal_False;
do
{
bFound = (sAttrValue == rStrImpValue.getToken( 0, cToken, nTokenIndex ));
}
while ( (nTokenIndex >= 0) && !bFound );
setBOOL( rValue, bFound );
return sal_True;
}
sal_Bool XMLPMPropHdl_Print::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
if( getBOOL( rValue ) )
{
if( rStrExpValue.getLength() )
rStrExpValue += OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
rStrExpValue += sAttrValue;
}
return sal_True;
}
//______________________________________________________________________________
// property handler for style:table-centering
XMLPMPropHdl_CenterHorizontal::~XMLPMPropHdl_CenterHorizontal()
{
}
sal_Bool XMLPMPropHdl_CenterHorizontal::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if (rStrImpValue.getLength())
if ((rStrImpValue.compareToAscii(sXML_both) == 0) ||
(rStrImpValue.compareToAscii(sXML_horizontal) == 0))
{
rValue = ::cppu::bool2any(sal_True);
bRet = sal_True;
}
return bRet;
}
sal_Bool XMLPMPropHdl_CenterHorizontal::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if ( ::cppu::any2bool( rValue ) )
{
bRet = sal_True;
if (rStrExpValue.getLength())
rStrExpValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_both));
else
rStrExpValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_horizontal));
}
return bRet;
}
XMLPMPropHdl_CenterVertical::~XMLPMPropHdl_CenterVertical()
{
}
sal_Bool XMLPMPropHdl_CenterVertical::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if (rStrImpValue.getLength())
if ((rStrImpValue.compareToAscii(sXML_both) == 0) ||
(rStrImpValue.compareToAscii(sXML_vertical) == 0))
{
rValue = ::cppu::bool2any(sal_True);
bRet = sal_True;
}
return bRet;
}
sal_Bool XMLPMPropHdl_CenterVertical::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if ( ::cppu::any2bool( rValue ) )
{
bRet = sal_True;
if (rStrExpValue.getLength())
rStrExpValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_both));
else
rStrExpValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_vertical));
}
return bRet;
}
<commit_msg>#88948#: page number setting 'none'<commit_after>/*************************************************************************
*
* $RCSfile: PageMasterPropHdl.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: mib $ $Date: 2001-06-29 11:18:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _XMLOFF_PAGEMASTERPROPHDL_HXX_
#include "PageMasterPropHdl.hxx"
#endif
#ifndef _XMLOFF_XMLKYWD_HXX
#include "xmlkywd.hxx"
#endif
#ifndef _XMLOFF_XMLUCONV_HXX
#include "xmluconv.hxx"
#endif
#ifndef _XMLOFF_XMLNUMI_HXX
#include "xmlnumi.hxx"
#endif
#ifndef _XMLOFF_XMLNUME_HXX
#include "xmlnume.hxx"
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_PAGESTYLELAYOUT_HPP_
#include <com/sun/star/style/PageStyleLayout.hpp>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _COMPHELPER_EXTRACT_HXX_
#include <comphelper/extract.hxx>
#endif
using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::style;
using namespace ::comphelper;
//______________________________________________________________________________
#define DEFAULT_PAPERTRAY (sal_Int32(-1))
//______________________________________________________________________________
// property handler for style:page-usage (style::PageStyleLayout)
XMLPMPropHdl_PageStyleLayout::~XMLPMPropHdl_PageStyleLayout()
{
}
sal_Bool XMLPMPropHdl_PageStyleLayout::equals( const Any& rAny1, const Any& rAny2 ) const
{
style::PageStyleLayout eLayout1, eLayout2;
return ((rAny1 >>= eLayout1) && (rAny2 >>= eLayout2)) ? (eLayout1 == eLayout2) : sal_False;
}
sal_Bool XMLPMPropHdl_PageStyleLayout::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_True;
if( rStrImpValue.compareToAscii( sXML_all ) == 0 )
rValue <<= PageStyleLayout_ALL;
else if( rStrImpValue.compareToAscii( sXML_left ) == 0 )
rValue <<= PageStyleLayout_LEFT;
else if( rStrImpValue.compareToAscii( sXML_right ) == 0 )
rValue <<= PageStyleLayout_RIGHT;
else if( rStrImpValue.compareToAscii( sXML_mirrored ) == 0 )
rValue <<= PageStyleLayout_MIRRORED;
else
bRet = sal_False;
return bRet;
}
sal_Bool XMLPMPropHdl_PageStyleLayout::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
PageStyleLayout eLayout;
if( rValue >>= eLayout )
{
bRet = sal_True;
switch( eLayout )
{
case PageStyleLayout_ALL:
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_all ) );
break;
case PageStyleLayout_LEFT:
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_left ) );
break;
case PageStyleLayout_RIGHT:
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_right ) );
break;
case PageStyleLayout_MIRRORED:
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_mirrored ) );
break;
default:
bRet = sal_False;
}
}
return bRet;
}
//______________________________________________________________________________
// property handler for style:num-format (style::NumberingType)
XMLPMPropHdl_NumFormat::~XMLPMPropHdl_NumFormat()
{
}
sal_Bool XMLPMPropHdl_NumFormat::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Int16 nSync;
sal_Int16 nNumType = NumberingType::NUMBER_NONE;
rUnitConverter.convertNumFormat( nNumType, rStrImpValue, OUString(),
sal_True );
if( !(rValue >>= nSync) )
nSync = NumberingType::NUMBER_NONE;
// if num-letter-sync appears before num-format, the function
// XMLPMPropHdl_NumLetterSync::importXML() sets the value
// NumberingType::CHARS_LOWER_LETTER_N
if( nSync == NumberingType::CHARS_LOWER_LETTER_N )
{
switch( nNumType )
{
case NumberingType::CHARS_LOWER_LETTER:
nNumType = NumberingType::CHARS_LOWER_LETTER_N;
break;
case NumberingType::CHARS_UPPER_LETTER:
nNumType = NumberingType::CHARS_UPPER_LETTER_N;
break;
}
}
rValue <<= nNumType;
return sal_True;
}
sal_Bool XMLPMPropHdl_NumFormat::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_Int16 nNumType;
if( rValue >>= nNumType )
{
OUStringBuffer aBuffer( 10 );
rUnitConverter.convertNumFormat( aBuffer, nNumType );
rStrExpValue = aBuffer.makeStringAndClear();
bRet = sal_True;
}
return bRet;
}
//______________________________________________________________________________
// property handler for style:num-letter-sync (style::NumberingType)
XMLPMPropHdl_NumLetterSync::~XMLPMPropHdl_NumLetterSync()
{
}
sal_Bool XMLPMPropHdl_NumLetterSync::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Int16 nNumType;
sal_Int16 nSync = NumberingType::NUMBER_NONE;
rUnitConverter.convertNumFormat( nSync, rStrImpValue,
OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_a ) ),
sal_True );
if( !(rValue >>= nNumType) )
nNumType = NumberingType::NUMBER_NONE;
if( nSync == NumberingType::CHARS_LOWER_LETTER_N )
{
switch( nNumType )
{
case NumberingType::CHARS_LOWER_LETTER:
nNumType = NumberingType::CHARS_LOWER_LETTER_N;
break;
case NumberingType::CHARS_UPPER_LETTER:
nNumType = NumberingType::CHARS_UPPER_LETTER_N;
break;
}
}
rValue <<= nNumType;
return sal_True;
}
sal_Bool XMLPMPropHdl_NumLetterSync::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_Int16 nNumType;
if( rValue >>= nNumType )
{
OUStringBuffer aBuffer( 5 );
rUnitConverter.convertNumLetterSync( aBuffer, nNumType );
rStrExpValue = aBuffer.makeStringAndClear();
bRet = rStrExpValue.getLength() > 0;
}
return bRet;
}
//______________________________________________________________________________
// property handler for style:paper-tray-number
XMLPMPropHdl_PaperTrayNumber::~XMLPMPropHdl_PaperTrayNumber()
{
}
sal_Bool XMLPMPropHdl_PaperTrayNumber::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if( rStrImpValue.compareToAscii( sXML_default ) == 0 )
{
rValue <<= DEFAULT_PAPERTRAY;
bRet = sal_True;
}
else
{
sal_Int32 nPaperTray;
if( SvXMLUnitConverter::convertNumber( nPaperTray, rStrImpValue, 0 ) )
{
rValue <<= nPaperTray;
bRet = sal_True;
}
}
return bRet;
}
sal_Bool XMLPMPropHdl_PaperTrayNumber::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
sal_Int32 nPaperTray;
if( rValue >>= nPaperTray )
{
if( nPaperTray == DEFAULT_PAPERTRAY )
rStrExpValue = OUString( RTL_CONSTASCII_USTRINGPARAM( sXML_default ) );
else
{
OUStringBuffer aBuffer;
SvXMLUnitConverter::convertNumber( aBuffer, nPaperTray );
rStrExpValue = aBuffer.makeStringAndClear();
}
bRet = sal_True;
}
return bRet;
}
//______________________________________________________________________________
// property handler for style:print
XMLPMPropHdl_Print::XMLPMPropHdl_Print( const sal_Char* sValue ) :
sAttrValue( OUString::createFromAscii( sValue ) )
{
}
XMLPMPropHdl_Print::~XMLPMPropHdl_Print()
{
}
sal_Bool XMLPMPropHdl_Print::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Unicode cToken = ' ';
sal_Int32 nTokenIndex = 0;
sal_Bool bFound = sal_False;
do
{
bFound = (sAttrValue == rStrImpValue.getToken( 0, cToken, nTokenIndex ));
}
while ( (nTokenIndex >= 0) && !bFound );
setBOOL( rValue, bFound );
return sal_True;
}
sal_Bool XMLPMPropHdl_Print::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
if( getBOOL( rValue ) )
{
if( rStrExpValue.getLength() )
rStrExpValue += OUString( RTL_CONSTASCII_USTRINGPARAM( " " ) );
rStrExpValue += sAttrValue;
}
return sal_True;
}
//______________________________________________________________________________
// property handler for style:table-centering
XMLPMPropHdl_CenterHorizontal::~XMLPMPropHdl_CenterHorizontal()
{
}
sal_Bool XMLPMPropHdl_CenterHorizontal::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if (rStrImpValue.getLength())
if ((rStrImpValue.compareToAscii(sXML_both) == 0) ||
(rStrImpValue.compareToAscii(sXML_horizontal) == 0))
{
rValue = ::cppu::bool2any(sal_True);
bRet = sal_True;
}
return bRet;
}
sal_Bool XMLPMPropHdl_CenterHorizontal::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if ( ::cppu::any2bool( rValue ) )
{
bRet = sal_True;
if (rStrExpValue.getLength())
rStrExpValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_both));
else
rStrExpValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_horizontal));
}
return bRet;
}
XMLPMPropHdl_CenterVertical::~XMLPMPropHdl_CenterVertical()
{
}
sal_Bool XMLPMPropHdl_CenterVertical::importXML(
const OUString& rStrImpValue,
Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if (rStrImpValue.getLength())
if ((rStrImpValue.compareToAscii(sXML_both) == 0) ||
(rStrImpValue.compareToAscii(sXML_vertical) == 0))
{
rValue = ::cppu::bool2any(sal_True);
bRet = sal_True;
}
return bRet;
}
sal_Bool XMLPMPropHdl_CenterVertical::exportXML(
OUString& rStrExpValue,
const Any& rValue,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
if ( ::cppu::any2bool( rValue ) )
{
bRet = sal_True;
if (rStrExpValue.getLength())
rStrExpValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_both));
else
rStrExpValue = rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(sXML_vertical));
}
return bRet;
}
<|endoftext|> |
<commit_before>#include <QCoreApplication>
#include <QtDebug>
#include <iostream>
#include <fstream>
//#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cerrno>
#include <cmath>
#include <thread>
#include <mutex>
#define OUTPUT_FILE "./trials.csv"
#define NUMBER_THREADS 7
#define USE_MULTIPLE_THREADS
// create a mutex that is used to protect the writing of the data to
// the file.
std::mutex writeToFile;
#ifndef M_PI
#define M_PI 3.14159265359
#endif
#define SHOW_PROGRESS
//#define SHOW_INTERMEDIATE
#define BASE_DT 0.0001
double drand48()
{
return((double)(rand())/((double)RAND_MAX));
}
void normalDistRand(double stdDev,double* randomNumbers)
{
/* Generate a random number in polar coordinates */
double radius = sqrt(-2.0*log(drand48()));
double angle = 2.0*M_PI*drand48();
/* transform the number back into cartesian coordinates */
randomNumbers[0] = stdDev*radius*sin(angle);
randomNumbers[1] = stdDev*radius*cos(angle);
}
void printToCSVFile(double dt, double beta, double g,double tau,
double q, double theta, double h,double s,
double *x,std::ofstream *fp)
{
std::lock_guard<std::mutex> guard(writeToFile); // Make sure that
// this routine
// can only
// access the file once
// at any one time.
*fp << dt << ","
<< beta << ","
<< g << ","
<< tau << ","
<< q+1 << ","
<< theta << ","
<< h << ","
<< s << ","
<< 1-h-s << ","
<< x[0] << ","
<< x[1] << ","
<< 1-x[0]-x[1] << ","
<< x[2] << ","
<< x[3] << ","
<< 1-x[2]-x[3]
<< std::endl;
(*fp).flush();
}
void linear(long steps,
double a,double gamma,double r,double d,double g,
double *x,double *y,double *z, double dt,
int n,
double beta,double tau,
std::ofstream *fp,
int q,
double h,double s,double *v,double *w, double theta)
{
long m=n-1;
long p=0;
double B[2];
int calcRandom=0;
// Step through every time step.
for (long k=0;k<steps;k++)
{
// Calculate a new set of random numbers if necessary.
if(calcRandom==0)
normalDistRand(sqrt(dt),B); //noise in most recent time step
//x[0]=y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt
//x[0]=x[0]+beta*y[m]*(1-y[m])+0.5*beta*y[m]*(1-y[m])*beta*(1-2*y[m])*(B[calcRandom]*B[calcRandom]-dt);
//Computes the deterministic component for Macroalgae
x[0] = y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt;
//Adds in the noise
//x[0]=x[0]+beta*y[m]*B[calcRandom]+0.5*beta*y[m]*beta*(B[calcRandom]*B[calcRandom]-dt);
x[0] += beta*y[m]*B[calcRandom]+0.5*beta*beta*y[m]*(B[calcRandom]*B[calcRandom]-dt);
//Computes the deterministic component for Coral
x[1] = z[m]+(z[m]*(r-d-(a+r)*y[m]-r*z[m]))*dt;
x[2] = v[m]+(v[m]*(gamma-gamma*v[m]+(a-gamma)*w[m])-(g*v[p]/(1-w[p])))*dt;
x[2] += beta*v[m]*(1-v[m])*B[calcRandom]+0.5*beta*(1-2*v[m])*beta*v[m]*(1-v[m])*(B[calcRandom]*B[calcRandom]-dt);
x[3] = w[m]+(w[m]*(r-d-(a+r)*v[m]-r*w[m]))*dt;
/****************************************************************
Account for extinction and overgrowing!!
****************************************************************/
for(int i=0;i<4;++i)
{
if(x[i]<0.0)
x[i] = 0.0;
else if (x[i]>1.0)
x[i] = 1.0;
}
//Updates delay and cell index
m=(m+1)%n;
p=(p+1)%n;
y[m]=x[0];
z[m]=x[1];
v[m]=x[2];
w[m]=x[3];
calcRandom = (calcRandom+1)%2; // update which random number to use.
}
//printf("%f\t%f\t%f\t%f\t%f\n",dt,beta,tau,x[0],x[1]);
printToCSVFile(dt,beta,g,tau,q,theta,h,s,x,fp);
#ifdef SHOW_INTERMEDIATE
qDebug() << dt << ","
<< beta << ","
<< g << ","
<< tau << ","
<< q+1 << ","
<< h << ","
<< s << ","
<< 1-h-s << ","
<< x[0] << ","
<< x[1] << ","
<< 1-x[0]-x[1] << ","
<< x[2] << ","
<< x[3] << ","
<< 1-x[2]-x[3];
qDebug() << errno << EDOM << ERANGE;
#endif
}
/* ****************************************************************
main
The main function. Called at the start of the program.
**************************************************************** */
int main(int argc, char *argv[])
{
QCoreApplication b(argc, argv);
long steps; // The number of steps to take in a single simulation.
double *v,*w,*x,*y,*z; // The variables used for the state of the system.
/*
Define the constants.
These are the parameters that are used in the operator for the
differential equations.
*/
double a = 0.1;
double g = 0.3;
double gamma = 0.8;
double r = 1.0;
double d = 0.44;
// double tau = 0.5;
double beta // = .5;
double chi = r*gamma/(r+a)-gamma+a; //Intermediate Step
double xi = -(d*gamma/(r+a)+a); //Intermediate Step
double cbar = (-xi-sqrt(xi*xi-4*chi*g))/(2*chi); //Intermediate Step
double coralSaddle = 1-cbar; //Saddle point value for coral
double macroSaddle = (r-r*coralSaddle-d)/(r+a); //Saddle point value for macroalgae
double gZero = ((d*a*r+d*d)*(gamma-a))/(r*r);
double gOne = (gamma*(a+d))/(a+r);
double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d));
double tauZero = (1/omega)*acos(gZero/g);
double dt = .0001; // Set the initial time step
long numberDT; // The current iteration for the number assocated with the value of dt.
double final; // The final time for each simulation.
long trials; // The number of simulations to make.
<<<<<<< HEAD
final=50; // Set the final time.
trials=400; // Set the number of trials to perform.
=======
final=50.0; // Set the final time.
trials=50; // Set the number of trials to perform.
>>>>>>> afa3c18ff2f48dc4ee88e7e8158f5b78dae8cb48
// Set the time delay, tau
double tau = 0.5;
// set up the variables for using different approximations on different threads.
std::thread simulation[NUMBER_THREADS];
int numberThreads = 0;
// Sets the seed for the random numbers
srand(time(NULL));
// Create a CSV File
std::ofstream fp;
//String fileName = "trials-g" + std::toString(g) + "-tau" + std::toString(tau);
fp.open(OUTPUT_FILE,std::ios::out | std::ios::trunc);
fp << "dt,beta,g,tau,trial,theta,initMacro,initCoral,initTurf,macroalgae,coral,turf,lgMacro,lgCoral,lgTurf" << std::endl;
/* for (g=0.1;g<=0.8;g=g+0.02)
{
//Redefine initial conditions and critical points for varying g
cbar = (-xi-sqrt(xi*xi-4*chi*g))/(2*chi);
coralSaddle = 1-cbar;
macroSaddle = (r-r*coralSaddle-d)/(r+a);
omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d));
tauZero = (1/omega)*acos(gZero/g);
if (coralSaddle>0 && coralSaddle<1 && macroSaddle>0 && macroSaddle<1 && tauZero>0)
for (double aleph=0;aleph<=5;aleph=aleph+1)
{
tau=.3*(1+aleph)*tauZero;
dt=0.0001;
*/
// Determine the number of time steps required to move back to the delay in time.
// The number of cells needed for the delay (changes with dt)
int n;
n=(int)(tau/BASE_DT+0.5);
// Allocate the space for the states of the system
x=(double *) calloc(4,sizeof(double));
y=(double *) calloc(n,sizeof(double)); //macroalgae for multiplicative noise
z=(double *) calloc(n,sizeof(double)); //coral for multiplicative noise
v=(double *) calloc(n,sizeof(double)); //macroalgae for logistic noise
w=(double *) calloc(n,sizeof(double)); //coral for logistic noise
<<<<<<< HEAD
//for(numberDT=1;numberDT<5;++numberDT)
dt = BASE_DT; //(double)numberDT;
//printf("%f\t%f\n",dt,fmod(tau,dt));
=======
// Make different approximations for different values for the time steps.
for(beta=.1;beta<=.45; beta += .05)
{
//dt = BASE_DT*(double)numberDT;
>>>>>>> afa3c18ff2f48dc4ee88e7e8158f5b78dae8cb48
#ifdef SHOW_PROGRESS
std::cout << "dt = " << dt << std::endl;
#endif
if ((int)(10000.0*tau+.5)%(int)(dt*10000.0+.5)==0)
{
//index = tau/dt;
n=(int)(tau/dt+.5);
//printf("%i\n",n);
steps=(long)(final/dt);
<<<<<<< HEAD
for (double theta=0;theta<=M_PI/2;theta+=(M_PI*0.5)*0.025)
=======
// Make an approximation for different initial conditions.
// Make an arc through 0 to pi/2 radians from the origin.
for (double theta=0;theta<=M_PI/2;theta+=(M_PI*0.5)*0.05)
>>>>>>> afa3c18ff2f48dc4ee88e7e8158f5b78dae8cb48
{
for (int k=0;k<trials;k++)
{
y[0]=0.06*cos(theta); //initial Macroalgae level
z[0]=0.06*sin(theta); //initial Coral level
v[0]=0.06*cos(theta);
w[0]=0.06*sin(theta);
for (int l=1;l<n;l++) //fills in the past times for y, z, v, and w
{
y[l]=y[0];
z[l]=z[0];
v[l]=v[0];
w[l]=w[0];
}
//fprintf(fp,"%f,%f,%f,%f,%f,%f\n",y[0],z[0],1-y[0]-z[0],v[0],w[0],1-v[0]-w[0]);
#ifdef USE_MULTIPLE_THREADS
// Make a simulation for each of the available threads.
// First check to see how many threads are running.
if(numberThreads >= NUMBER_THREADS)
{
// There are too many threads. Wait for each run to end.
while(numberThreads>0)
{
#ifdef THREAD_DEBUG
std::cout << "Waiting on thread "
<< simulation[numberThreads-1].get_id()
<< std::endl;
#endif
simulation[--numberThreads].join();
}
}
// Make a run in a separate thread.
simulation[numberThreads++] = std::thread(linear,
steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta);
#else
// Ignore the different threads. Just make one approximation in this one thread.
linear(steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta);
#endif
#ifdef SHOW_PROGRESS
if(k%20 == 0)
std::cout << " Simulation number " << k << std::endl;
#endif
}
}
}
// Free up the allocated memory.
free(x);
free(y);
free(z);
free(v);
free(w);
//}
//}
fp.close();
#ifdef SHOW_PROGRESS
std::cout << "all done" << std::endl;
#endif
return b.exec();
}
<commit_msg>I think I fixed the merging problems(?)<commit_after>#include <QCoreApplication>
#include <QtDebug>
#include <iostream>
#include <fstream>
//#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cerrno>
#include <cmath>
#include <thread>
#include <mutex>
#define OUTPUT_FILE "./trials.csv"
#define NUMBER_THREADS 7
#define USE_MULTIPLE_THREADS
// create a mutex that is used to protect the writing of the data to
// the file.
std::mutex writeToFile;
#ifndef M_PI
#define M_PI 3.14159265359
#endif
#define SHOW_PROGRESS
//#define SHOW_INTERMEDIATE
#define BASE_DT 0.0001
double drand48()
{
return((double)(rand())/((double)RAND_MAX));
}
void normalDistRand(double stdDev,double* randomNumbers)
{
/* Generate a random number in polar coordinates */
double radius = sqrt(-2.0*log(drand48()));
double angle = 2.0*M_PI*drand48();
/* transform the number back into cartesian coordinates */
randomNumbers[0] = stdDev*radius*sin(angle);
randomNumbers[1] = stdDev*radius*cos(angle);
}
void printToCSVFile(double dt, double beta, double g,double tau,
double q, double theta, double h,double s,
double *x,std::ofstream *fp)
{
std::lock_guard<std::mutex> guard(writeToFile); // Make sure that
// this routine
// can only
// access the file once
// at any one time.
*fp << dt << ","
<< beta << ","
<< g << ","
<< tau << ","
<< q+1 << ","
<< theta << ","
<< h << ","
<< s << ","
<< 1-h-s << ","
<< x[0] << ","
<< x[1] << ","
<< 1-x[0]-x[1] << ","
<< x[2] << ","
<< x[3] << ","
<< 1-x[2]-x[3]
<< std::endl;
(*fp).flush();
}
void linear(long steps,
double a,double gamma,double r,double d,double g,
double *x,double *y,double *z, double dt,
int n,
double beta,double tau,
std::ofstream *fp,
int q,
double h,double s,double *v,double *w, double theta)
{
long m=n-1;
long p=0;
double B[2];
int calcRandom=0;
// Step through every time step.
for (long k=0;k<steps;k++)
{
// Calculate a new set of random numbers if necessary.
if(calcRandom==0)
normalDistRand(sqrt(dt),B); //noise in most recent time step
//x[0]=y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt
//x[0]=x[0]+beta*y[m]*(1-y[m])+0.5*beta*y[m]*(1-y[m])*beta*(1-2*y[m])*(B[calcRandom]*B[calcRandom]-dt);
//Computes the deterministic component for Macroalgae
x[0] = y[m]+(y[m]*(gamma-gamma*y[m]+(a-gamma)*z[m])-(g*y[p]/(1-z[p])))*dt;
//Adds in the noise
//x[0]=x[0]+beta*y[m]*B[calcRandom]+0.5*beta*y[m]*beta*(B[calcRandom]*B[calcRandom]-dt);
x[0] += beta*y[m]*B[calcRandom]+0.5*beta*beta*y[m]*(B[calcRandom]*B[calcRandom]-dt);
//Computes the deterministic component for Coral
x[1] = z[m]+(z[m]*(r-d-(a+r)*y[m]-r*z[m]))*dt;
x[2] = v[m]+(v[m]*(gamma-gamma*v[m]+(a-gamma)*w[m])-(g*v[p]/(1-w[p])))*dt;
x[2] += beta*v[m]*(1-v[m])*B[calcRandom]+0.5*beta*(1-2*v[m])*beta*v[m]*(1-v[m])*(B[calcRandom]*B[calcRandom]-dt);
x[3] = w[m]+(w[m]*(r-d-(a+r)*v[m]-r*w[m]))*dt;
/****************************************************************
Account for extinction and overgrowing!!
****************************************************************/
for(int i=0;i<4;++i)
{
if(x[i]<0.0)
x[i] = 0.0;
else if (x[i]>1.0)
x[i] = 1.0;
}
//Updates delay and cell index
m=(m+1)%n;
p=(p+1)%n;
y[m]=x[0];
z[m]=x[1];
v[m]=x[2];
w[m]=x[3];
calcRandom = (calcRandom+1)%2; // update which random number to use.
}
//printf("%f\t%f\t%f\t%f\t%f\n",dt,beta,tau,x[0],x[1]);
printToCSVFile(dt,beta,g,tau,q,theta,h,s,x,fp);
#ifdef SHOW_INTERMEDIATE
qDebug() << dt << ","
<< beta << ","
<< g << ","
<< tau << ","
<< q+1 << ","
<< h << ","
<< s << ","
<< 1-h-s << ","
<< x[0] << ","
<< x[1] << ","
<< 1-x[0]-x[1] << ","
<< x[2] << ","
<< x[3] << ","
<< 1-x[2]-x[3];
qDebug() << errno << EDOM << ERANGE;
#endif
}
/* ****************************************************************
main
The main function. Called at the start of the program.
**************************************************************** */
int main(int argc, char *argv[])
{
QCoreApplication b(argc, argv);
long steps; // The number of steps to take in a single simulation.
double *v,*w,*x,*y,*z; // The variables used for the state of the system.
/*
Define the constants.
These are the parameters that are used in the operator for the
differential equations.
*/
double a = 0.1;
double g = 0.3;
double gamma = 0.8;
double r = 1.0;
double d = 0.44;
// double tau = 0.5;
double beta // = .5;
double chi = r*gamma/(r+a)-gamma+a; //Intermediate Step
double xi = -(d*gamma/(r+a)+a); //Intermediate Step
double cbar = (-xi-sqrt(xi*xi-4*chi*g))/(2*chi); //Intermediate Step
double coralSaddle = 1-cbar; //Saddle point value for coral
double macroSaddle = (r-r*coralSaddle-d)/(r+a); //Saddle point value for macroalgae
double gZero = ((d*a*r+d*d)*(gamma-a))/(r*r);
double gOne = (gamma*(a+d))/(a+r);
double omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d));
double tauZero = (1/omega)*acos(gZero/g);
double dt = .0001; // Set the initial time step
long numberDT; // The current iteration for the number assocated with the value of dt.
double final; // The final time for each simulation.
long trials; // The number of simulations to make.
final=50; // Set the final time.
trials=400; // Set the number of trials to perform.
// Set the time delay, tau
double tau = 0.5;
// set up the variables for using different approximations on different threads.
std::thread simulation[NUMBER_THREADS];
int numberThreads = 0;
// Sets the seed for the random numbers
srand(time(NULL));
// Create a CSV File
std::ofstream fp;
//String fileName = "trials-g" + std::toString(g) + "-tau" + std::toString(tau);
fp.open(OUTPUT_FILE,std::ios::out | std::ios::trunc);
fp << "dt,beta,g,tau,trial,theta,initMacro,initCoral,initTurf,macroalgae,coral,turf,lgMacro,lgCoral,lgTurf" << std::endl;
/* for (g=0.1;g<=0.8;g=g+0.02)
{
//Redefine initial conditions and critical points for varying g
cbar = (-xi-sqrt(xi*xi-4*chi*g))/(2*chi);
coralSaddle = 1-cbar;
macroSaddle = (r-r*coralSaddle-d)/(r+a);
omega = sqrt((r*r*(g*g-gZero*gZero))/(d*d));
tauZero = (1/omega)*acos(gZero/g);
if (coralSaddle>0 && coralSaddle<1 && macroSaddle>0 && macroSaddle<1 && tauZero>0)
for (double aleph=0;aleph<=5;aleph=aleph+1)
{
tau=.3*(1+aleph)*tauZero;
dt=0.0001;
*/
// Determine the number of time steps required to move back to the delay in time.
// The number of cells needed for the delay (changes with dt)
int n;
n=(int)(tau/BASE_DT+0.5);
// Allocate the space for the states of the system
x=(double *) calloc(4,sizeof(double));
y=(double *) calloc(n,sizeof(double)); //macroalgae for multiplicative noise
z=(double *) calloc(n,sizeof(double)); //coral for multiplicative noise
v=(double *) calloc(n,sizeof(double)); //macroalgae for logistic noise
w=(double *) calloc(n,sizeof(double)); //coral for logistic noise
//for(numberDT=1;numberDT<5;++numberDT)
dt = BASE_DT; //(double)numberDT;
//printf("%f\t%f\n",dt,fmod(tau,dt));
// Make different approximations for different values for the time steps.
for(beta=.1;beta<=.45; beta += .05)
{
//dt = BASE_DT*(double)numberDT;
#ifdef SHOW_PROGRESS
std::cout << "dt = " << dt << std::endl;
#endif
if ((int)(10000.0*tau+.5)%(int)(dt*10000.0+.5)==0)
{
//index = tau/dt;
n=(int)(tau/dt+.5);
//printf("%i\n",n);
steps=(long)(final/dt);
// Make an approximation for different initial conditions.
// Make an arc through 0 to pi/2 radians from the origin.
for (double theta=0;theta<=M_PI/2;theta+=(M_PI*0.5)*0.05)
{
for (int k=0;k<trials;k++)
{
y[0]=0.06*cos(theta); //initial Macroalgae level
z[0]=0.06*sin(theta); //initial Coral level
v[0]=0.06*cos(theta);
w[0]=0.06*sin(theta);
for (int l=1;l<n;l++) //fills in the past times for y, z, v, and w
{
y[l]=y[0];
z[l]=z[0];
v[l]=v[0];
w[l]=w[0];
}
//fprintf(fp,"%f,%f,%f,%f,%f,%f\n",y[0],z[0],1-y[0]-z[0],v[0],w[0],1-v[0]-w[0]);
#ifdef USE_MULTIPLE_THREADS
// Make a simulation for each of the available threads.
// First check to see how many threads are running.
if(numberThreads >= NUMBER_THREADS)
{
// There are too many threads. Wait for each run to end.
while(numberThreads>0)
{
#ifdef THREAD_DEBUG
std::cout << "Waiting on thread "
<< simulation[numberThreads-1].get_id()
<< std::endl;
#endif
simulation[--numberThreads].join();
}
}
// Make a run in a separate thread.
simulation[numberThreads++] = std::thread(linear,
steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta);
#else
// Ignore the different threads. Just make one approximation in this one thread.
linear(steps,a,gamma,r,d,g,x,y,z,dt,n,beta,tau,&fp,k,y[0],z[0],v,w,theta);
#endif
#ifdef SHOW_PROGRESS
if(k%20 == 0)
std::cout << " Simulation number " << k << std::endl;
#endif
}
}
}
// Free up the allocated memory.
free(x);
free(y);
free(z);
free(v);
free(w);
//}
//}
fp.close();
#ifdef SHOW_PROGRESS
std::cout << "all done" << std::endl;
#endif
return b.exec();
}
<|endoftext|> |
<commit_before>/*
* ConnectionHistory.cpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "ConnectionHistory.hpp"
#include <core/FileSerializer.hpp>
#include <session/SessionModuleContext.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace connections {
namespace {
bool isConnection(const ConnectionId& id, json::Value valueJson)
{
if (!json::isType<json::Object>(valueJson))
{
LOG_WARNING_MESSAGE("Connection JSON has unexpected format");
return false;
}
const json::Object& connJson = valueJson.getObject();
return hasConnectionId(id, connJson);
}
} // anonymous namespace
ConnectionHistory& connectionHistory()
{
static ConnectionHistory instance;
return instance;
}
ConnectionHistory::ConnectionHistory()
{
}
Error ConnectionHistory::initialize()
{
// register to be notified when connections are changed
connectionsDir_ = module_context::registerMonitoredUserScratchDir(
"connection_history",
boost::bind(&ConnectionHistory::onConnectionsChanged, this));
return Success();
}
void ConnectionHistory::update(const Connection& connection)
{
// read existing connections
json::Array connectionsJson;
Error error = readConnections(&connectionsJson);
if (error)
{
LOG_ERROR(error);
return;
}
// look for a matching connection and update it
bool foundConnection = false;
for (size_t i = 0; i<connectionsJson.getSize(); i++)
{
json::Value valueJson = connectionsJson[i];
if (isConnection(connection.id, valueJson))
{
connectionsJson[i] = connectionJson(connection);
foundConnection = true;
break;
}
}
// if we didn't find a connection then append
if (!foundConnection)
connectionsJson.push_back(connectionJson(connection));
// write out the connections
error = writeConnections(connectionsJson);
if (error)
LOG_ERROR(error);
// fire event
onConnectionsChanged();
}
void ConnectionHistory::remove(const ConnectionId &id)
{
// read existing connections
json::Array connectionsJson;
Error error = readConnections(&connectionsJson);
if (error)
{
LOG_ERROR(error);
return;
}
// remove matching connection
connectionsJson.erase(std::remove_if(connectionsJson.begin(),
connectionsJson.end(),
boost::bind(isConnection, id, _1)),
connectionsJson.end());
// write out the connections
error = writeConnections(connectionsJson);
if (error)
LOG_ERROR(error);
}
json::Array ConnectionHistory::connectionsAsJson()
{
json::Array connectionsJson;
Error error = readConnections(&connectionsJson);
if (error)
LOG_ERROR(error);
return connectionsJson;
}
void ConnectionHistory::onConnectionsChanged()
{
ClientEvent event(client_events::kConnectionListChanged,
connectionsAsJson());
module_context::enqueClientEvent(event);
}
const char* const kConnectionListFile = "connection-history-database.json";
Error ConnectionHistory::readConnections(json::Array* pConnections)
{
FilePath connectionListFile = connectionsDir_.completeChildPath(kConnectionListFile);
if (!connectionListFile.exists())
return Success();
std::string contents;
Error error = core::readStringFromFile(connectionListFile, &contents);
if (error)
return error;
json::Value parsedJson;
if (parsedJson.parse(contents) || !json::isType<json::Array>(parsedJson))
{
return systemError(boost::system::errc::protocol_error,
"Error parsing connections json file",
ERROR_LOCATION);
}
json::Array connections = parsedJson.getArray();
for (auto&& connection : connections)
if (connection.isObject())
pConnections->push_back(connection);
return Success();
}
Error ConnectionHistory::writeConnections(const json::Array& connectionsJson)
{
FilePath connectionListFile = connectionsDir_.completeChildPath(kConnectionListFile);
std::shared_ptr<std::ostream> pStream;
Error error = connectionListFile.openForWrite(pStream);
if (error)
return error;
connectionsJson.writeFormatted(*pStream);
return Success();
}
} // namespace connections
} // namespace modules
} // namespace session
} // namespace rstudio
<commit_msg>accept JSON by reference (#8205)<commit_after>/*
* ConnectionHistory.cpp
*
* Copyright (C) 2020 by RStudio, PBC
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "ConnectionHistory.hpp"
#include <core/FileSerializer.hpp>
#include <session/SessionModuleContext.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace connections {
namespace {
bool isConnection(const ConnectionId& id, const json::Value& valueJson)
{
if (!json::isType<json::Object>(valueJson))
{
LOG_WARNING_MESSAGE("Connection JSON has unexpected format");
return false;
}
const json::Object& connJson = valueJson.getObject();
return hasConnectionId(id, connJson);
}
} // anonymous namespace
ConnectionHistory& connectionHistory()
{
static ConnectionHistory instance;
return instance;
}
ConnectionHistory::ConnectionHistory()
{
}
Error ConnectionHistory::initialize()
{
// register to be notified when connections are changed
connectionsDir_ = module_context::registerMonitoredUserScratchDir(
"connection_history",
boost::bind(&ConnectionHistory::onConnectionsChanged, this));
return Success();
}
void ConnectionHistory::update(const Connection& connection)
{
// read existing connections
json::Array connectionsJson;
Error error = readConnections(&connectionsJson);
if (error)
{
LOG_ERROR(error);
return;
}
// look for a matching connection and update it
bool foundConnection = false;
for (size_t i = 0; i<connectionsJson.getSize(); i++)
{
json::Value valueJson = connectionsJson[i];
if (isConnection(connection.id, valueJson))
{
connectionsJson[i] = connectionJson(connection);
foundConnection = true;
break;
}
}
// if we didn't find a connection then append
if (!foundConnection)
connectionsJson.push_back(connectionJson(connection));
// write out the connections
error = writeConnections(connectionsJson);
if (error)
LOG_ERROR(error);
// fire event
onConnectionsChanged();
}
void ConnectionHistory::remove(const ConnectionId &id)
{
// read existing connections
json::Array connectionsJson;
Error error = readConnections(&connectionsJson);
if (error)
{
LOG_ERROR(error);
return;
}
// remove matching connection
connectionsJson.erase(std::remove_if(connectionsJson.begin(),
connectionsJson.end(),
boost::bind(isConnection, id, _1)),
connectionsJson.end());
// write out the connections
error = writeConnections(connectionsJson);
if (error)
LOG_ERROR(error);
}
json::Array ConnectionHistory::connectionsAsJson()
{
json::Array connectionsJson;
Error error = readConnections(&connectionsJson);
if (error)
LOG_ERROR(error);
return connectionsJson;
}
void ConnectionHistory::onConnectionsChanged()
{
ClientEvent event(client_events::kConnectionListChanged,
connectionsAsJson());
module_context::enqueClientEvent(event);
}
const char* const kConnectionListFile = "connection-history-database.json";
Error ConnectionHistory::readConnections(json::Array* pConnections)
{
FilePath connectionListFile = connectionsDir_.completeChildPath(kConnectionListFile);
if (!connectionListFile.exists())
return Success();
std::string contents;
Error error = core::readStringFromFile(connectionListFile, &contents);
if (error)
return error;
json::Value parsedJson;
if (parsedJson.parse(contents) || !json::isType<json::Array>(parsedJson))
{
return systemError(boost::system::errc::protocol_error,
"Error parsing connections json file",
ERROR_LOCATION);
}
json::Array connections = parsedJson.getArray();
for (auto&& connection : connections)
if (connection.isObject())
pConnections->push_back(connection);
return Success();
}
Error ConnectionHistory::writeConnections(const json::Array& connectionsJson)
{
FilePath connectionListFile = connectionsDir_.completeChildPath(kConnectionListFile);
std::shared_ptr<std::ostream> pStream;
Error error = connectionListFile.openForWrite(pStream);
if (error)
return error;
connectionsJson.writeFormatted(*pStream);
return Success();
}
} // namespace connections
} // namespace modules
} // namespace session
} // namespace rstudio
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "genericprojectwizard.h"
#include "filesselectionwizardpage.h"
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/customwizard/customwizard.h>
#include <utils/filewizardpage.h>
#include <QtGui/QIcon>
#include <QtGui/QApplication>
#include <QtGui/QStyle>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QtDebug>
#include <QtCore/QCoreApplication>
using namespace GenericProjectManager::Internal;
using namespace Utils;
//////////////////////////////////////////////////////////////////////////////
// GenericProjectWizardDialog
//////////////////////////////////////////////////////////////////////////////
GenericProjectWizardDialog::GenericProjectWizardDialog(QWidget *parent)
: Utils::Wizard(parent)
{
setWindowTitle(tr("Import Existing Project"));
// first page
m_firstPage = new FileWizardPage;
m_firstPage->setTitle(tr("Project Name and Location"));
m_firstPage->setFileNameLabel(tr("Project name:"));
m_firstPage->setPathLabel(tr("Location:"));
// second page
m_secondPage = new FilesSelectionWizardPage(this);
m_secondPage->setTitle(tr("File Selection"));
const int firstPageId = addPage(m_firstPage);
wizardProgress()->item(firstPageId)->setTitle(tr("Location"));
const int secondPageId = addPage(m_secondPage);
wizardProgress()->item(secondPageId)->setTitle(tr("Files"));
}
GenericProjectWizardDialog::~GenericProjectWizardDialog()
{ }
QString GenericProjectWizardDialog::path() const
{
return m_firstPage->path();
}
QStringList GenericProjectWizardDialog::selectedPaths() const
{
return m_secondPage->selectedPaths();
}
QStringList GenericProjectWizardDialog::selectedFiles() const
{
return m_secondPage->selectedFiles();
}
void GenericProjectWizardDialog::setPath(const QString &path)
{
m_firstPage->setPath(path);
}
QString GenericProjectWizardDialog::projectName() const
{
return m_firstPage->fileName();
}
GenericProjectWizard::GenericProjectWizard()
: Core::BaseFileWizard(parameters())
{ }
GenericProjectWizard::~GenericProjectWizard()
{ }
Core::BaseFileWizardParameters GenericProjectWizard::parameters()
{
Core::BaseFileWizardParameters parameters(ProjectWizard);
// TODO do something about the ugliness of standard icons in sizes different than 16, 32, 64, 128
{
QPixmap icon(22, 22);
icon.fill(Qt::transparent);
QPainter p(&icon);
p.drawPixmap(3, 3, 16, 16, qApp->style()->standardIcon(QStyle::SP_DirIcon).pixmap(16));
parameters.setIcon(icon);
}
parameters.setDisplayName(tr("Import Existing Project"));
parameters.setId(QLatin1String("Z.Makefile"));
parameters.setDescription(tr("Imports existing projects that do not use qmake or CMake. "
"This allows you to use Qt Creator as a code editor."));
parameters.setCategory(QLatin1String(ProjectExplorer::Constants::PROJECT_WIZARD_CATEGORY));
parameters.setDisplayCategory(QCoreApplication::translate("ProjectExplorer", ProjectExplorer::Constants::PROJECT_WIZARD_TR_CATEGORY));
return parameters;
}
QWizard *GenericProjectWizard::createWizardDialog(QWidget *parent,
const QString &defaultPath,
const WizardPageList &extensionPages) const
{
GenericProjectWizardDialog *wizard = new GenericProjectWizardDialog(parent);
setupWizard(wizard);
wizard->setPath(defaultPath);
foreach (QWizardPage *p, extensionPages)
BaseFileWizard::applyExtensionPageShortTitle(wizard, wizard->addPage(p));
return wizard;
}
void GenericProjectWizard::getFileList(const QDir &dir, const QString &projectRoot,
const QStringList &suffixes,
QStringList *files, QStringList *paths) const
{
const QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files |
QDir::Dirs |
QDir::NoDotAndDotDot |
QDir::NoSymLinks);
foreach (const QFileInfo &fileInfo, fileInfoList) {
QString filePath = fileInfo.absoluteFilePath();
filePath = filePath.mid(projectRoot.length() + 1);
if (fileInfo.isDir() && isValidDir(fileInfo)) {
getFileList(QDir(fileInfo.absoluteFilePath()), projectRoot,
suffixes, files, paths);
if (! paths->contains(filePath))
paths->append(filePath);
}
else if (suffixes.contains(fileInfo.suffix()))
files->append(filePath);
}
}
bool GenericProjectWizard::isValidDir(const QFileInfo &fileInfo) const
{
const QString fileName = fileInfo.fileName();
const QString suffix = fileInfo.suffix();
if (fileName.startsWith(QLatin1Char('.')))
return false;
else if (fileName == QLatin1String("CVS"))
return false;
// ### user include/exclude
return true;
}
Core::GeneratedFiles GenericProjectWizard::generateFiles(const QWizard *w,
QString *errorMessage) const
{
Q_UNUSED(errorMessage)
const GenericProjectWizardDialog *wizard = qobject_cast<const GenericProjectWizardDialog *>(w);
const QString projectPath = wizard->path();
const QDir dir(projectPath);
const QString projectName = wizard->projectName();
const QString creatorFileName = QFileInfo(dir, projectName + QLatin1String(".creator")).absoluteFilePath();
const QString filesFileName = QFileInfo(dir, projectName + QLatin1String(".files")).absoluteFilePath();
const QString includesFileName = QFileInfo(dir, projectName + QLatin1String(".includes")).absoluteFilePath();
const QString configFileName = QFileInfo(dir, projectName + QLatin1String(".config")).absoluteFilePath();
const QStringList sources = wizard->selectedFiles();
const QStringList paths = wizard->selectedPaths();
Core::ICore *core = Core::ICore::instance();
Core::MimeDatabase *mimeDatabase = core->mimeDatabase();
Core::MimeType headerTy = mimeDatabase->findByType(QLatin1String("text/x-chdr"));
QStringList nameFilters;
foreach (const Core::MimeGlobPattern &gp, headerTy.globPatterns())
nameFilters.append(gp.regExp().pattern());
QStringList includePaths;
foreach (const QString &path, paths) {
QFileInfo fileInfo(dir, path);
QDir thisDir(fileInfo.absoluteFilePath());
if (! thisDir.entryList(nameFilters, QDir::Files).isEmpty())
includePaths.append(path);
}
Core::GeneratedFile generatedCreatorFile(creatorFileName);
generatedCreatorFile.setContents(QLatin1String("[General]\n"));
generatedCreatorFile.setAttributes(Core::GeneratedFile::OpenProjectAttribute);
Core::GeneratedFile generatedFilesFile(filesFileName);
generatedFilesFile.setContents(sources.join(QLatin1String("\n")));
Core::GeneratedFile generatedIncludesFile(includesFileName);
generatedIncludesFile.setContents(includePaths.join(QLatin1String("\n")));
Core::GeneratedFile generatedConfigFile(configFileName);
generatedConfigFile.setContents(QLatin1String("// ADD PREDEFINED MACROS HERE!\n"));
Core::GeneratedFiles files;
files.append(generatedFilesFile);
files.append(generatedIncludesFile);
files.append(generatedConfigFile);
files.append(generatedCreatorFile);
return files;
}
bool GenericProjectWizard::postGenerateFiles(const QWizard *w, const Core::GeneratedFiles &l, QString *errorMessage)
{
Q_UNUSED(w);
return ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);
}
<commit_msg>Generic Project Wizard adds files with relative path.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**************************************************************************/
#include "genericprojectwizard.h"
#include "filesselectionwizardpage.h"
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <projectexplorer/projectexplorerconstants.h>
#include <projectexplorer/customwizard/customwizard.h>
#include <utils/filewizardpage.h>
#include <QtGui/QIcon>
#include <QtGui/QApplication>
#include <QtGui/QStyle>
#include <QtGui/QPainter>
#include <QtGui/QPixmap>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QtDebug>
#include <QtCore/QCoreApplication>
using namespace GenericProjectManager::Internal;
using namespace Utils;
//////////////////////////////////////////////////////////////////////////////
// GenericProjectWizardDialog
//////////////////////////////////////////////////////////////////////////////
GenericProjectWizardDialog::GenericProjectWizardDialog(QWidget *parent)
: Utils::Wizard(parent)
{
setWindowTitle(tr("Import Existing Project"));
// first page
m_firstPage = new FileWizardPage;
m_firstPage->setTitle(tr("Project Name and Location"));
m_firstPage->setFileNameLabel(tr("Project name:"));
m_firstPage->setPathLabel(tr("Location:"));
// second page
m_secondPage = new FilesSelectionWizardPage(this);
m_secondPage->setTitle(tr("File Selection"));
const int firstPageId = addPage(m_firstPage);
wizardProgress()->item(firstPageId)->setTitle(tr("Location"));
const int secondPageId = addPage(m_secondPage);
wizardProgress()->item(secondPageId)->setTitle(tr("Files"));
}
GenericProjectWizardDialog::~GenericProjectWizardDialog()
{ }
QString GenericProjectWizardDialog::path() const
{
return m_firstPage->path();
}
QStringList GenericProjectWizardDialog::selectedPaths() const
{
return m_secondPage->selectedPaths();
}
QStringList GenericProjectWizardDialog::selectedFiles() const
{
return m_secondPage->selectedFiles();
}
void GenericProjectWizardDialog::setPath(const QString &path)
{
m_firstPage->setPath(path);
}
QString GenericProjectWizardDialog::projectName() const
{
return m_firstPage->fileName();
}
GenericProjectWizard::GenericProjectWizard()
: Core::BaseFileWizard(parameters())
{ }
GenericProjectWizard::~GenericProjectWizard()
{ }
Core::BaseFileWizardParameters GenericProjectWizard::parameters()
{
Core::BaseFileWizardParameters parameters(ProjectWizard);
// TODO do something about the ugliness of standard icons in sizes different than 16, 32, 64, 128
{
QPixmap icon(22, 22);
icon.fill(Qt::transparent);
QPainter p(&icon);
p.drawPixmap(3, 3, 16, 16, qApp->style()->standardIcon(QStyle::SP_DirIcon).pixmap(16));
parameters.setIcon(icon);
}
parameters.setDisplayName(tr("Import Existing Project"));
parameters.setId(QLatin1String("Z.Makefile"));
parameters.setDescription(tr("Imports existing projects that do not use qmake or CMake. "
"This allows you to use Qt Creator as a code editor."));
parameters.setCategory(QLatin1String(ProjectExplorer::Constants::PROJECT_WIZARD_CATEGORY));
parameters.setDisplayCategory(QCoreApplication::translate("ProjectExplorer", ProjectExplorer::Constants::PROJECT_WIZARD_TR_CATEGORY));
return parameters;
}
QWizard *GenericProjectWizard::createWizardDialog(QWidget *parent,
const QString &defaultPath,
const WizardPageList &extensionPages) const
{
GenericProjectWizardDialog *wizard = new GenericProjectWizardDialog(parent);
setupWizard(wizard);
wizard->setPath(defaultPath);
foreach (QWizardPage *p, extensionPages)
BaseFileWizard::applyExtensionPageShortTitle(wizard, wizard->addPage(p));
return wizard;
}
void GenericProjectWizard::getFileList(const QDir &dir, const QString &projectRoot,
const QStringList &suffixes,
QStringList *files, QStringList *paths) const
{
const QFileInfoList fileInfoList = dir.entryInfoList(QDir::Files |
QDir::Dirs |
QDir::NoDotAndDotDot |
QDir::NoSymLinks);
foreach (const QFileInfo &fileInfo, fileInfoList) {
QString filePath = fileInfo.absoluteFilePath();
filePath = filePath.mid(projectRoot.length() + 1);
if (fileInfo.isDir() && isValidDir(fileInfo)) {
getFileList(QDir(fileInfo.absoluteFilePath()), projectRoot,
suffixes, files, paths);
if (! paths->contains(filePath))
paths->append(filePath);
}
else if (suffixes.contains(fileInfo.suffix()))
files->append(filePath);
}
}
bool GenericProjectWizard::isValidDir(const QFileInfo &fileInfo) const
{
const QString fileName = fileInfo.fileName();
const QString suffix = fileInfo.suffix();
if (fileName.startsWith(QLatin1Char('.')))
return false;
else if (fileName == QLatin1String("CVS"))
return false;
// ### user include/exclude
return true;
}
Core::GeneratedFiles GenericProjectWizard::generateFiles(const QWizard *w,
QString *errorMessage) const
{
Q_UNUSED(errorMessage)
const GenericProjectWizardDialog *wizard = qobject_cast<const GenericProjectWizardDialog *>(w);
const QString projectPath = wizard->path();
const QDir dir(projectPath);
const QString projectName = wizard->projectName();
const QString creatorFileName = QFileInfo(dir, projectName + QLatin1String(".creator")).absoluteFilePath();
const QString filesFileName = QFileInfo(dir, projectName + QLatin1String(".files")).absoluteFilePath();
const QString includesFileName = QFileInfo(dir, projectName + QLatin1String(".includes")).absoluteFilePath();
const QString configFileName = QFileInfo(dir, projectName + QLatin1String(".config")).absoluteFilePath();
const QStringList paths = wizard->selectedPaths();
Core::ICore *core = Core::ICore::instance();
Core::MimeDatabase *mimeDatabase = core->mimeDatabase();
Core::MimeType headerTy = mimeDatabase->findByType(QLatin1String("text/x-chdr"));
QStringList nameFilters;
foreach (const Core::MimeGlobPattern &gp, headerTy.globPatterns())
nameFilters.append(gp.regExp().pattern());
QStringList includePaths;
foreach (const QString &path, paths) {
QFileInfo fileInfo(dir, path);
QDir thisDir(fileInfo.absoluteFilePath());
if (! thisDir.entryList(nameFilters, QDir::Files).isEmpty())
includePaths.append(path);
}
Core::GeneratedFile generatedCreatorFile(creatorFileName);
generatedCreatorFile.setContents(QLatin1String("[General]\n"));
generatedCreatorFile.setAttributes(Core::GeneratedFile::OpenProjectAttribute);
QStringList sources = wizard->selectedFiles();
for (int i = 0; i < sources.length(); ++i)
sources[i] = dir.relativeFilePath(sources[i]);
Core::GeneratedFile generatedFilesFile(filesFileName);
generatedFilesFile.setContents(sources.join(QLatin1String("\n")));
Core::GeneratedFile generatedIncludesFile(includesFileName);
generatedIncludesFile.setContents(includePaths.join(QLatin1String("\n")));
Core::GeneratedFile generatedConfigFile(configFileName);
generatedConfigFile.setContents(QLatin1String("// ADD PREDEFINED MACROS HERE!\n"));
Core::GeneratedFiles files;
files.append(generatedFilesFile);
files.append(generatedIncludesFile);
files.append(generatedConfigFile);
files.append(generatedCreatorFile);
return files;
}
bool GenericProjectWizard::postGenerateFiles(const QWizard *w, const Core::GeneratedFiles &l, QString *errorMessage)
{
Q_UNUSED(w);
return ProjectExplorer::CustomProjectWizard::postGenerateOpen(l, errorMessage);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrCCPathProcessor.h"
#include "GrGpuCommandBuffer.h"
#include "GrOnFlushResourceProvider.h"
#include "GrTexture.h"
#include "ccpr/GrCCPerFlushResources.h"
#include "glsl/GrGLSLFragmentShaderBuilder.h"
#include "glsl/GrGLSLGeometryProcessor.h"
#include "glsl/GrGLSLProgramBuilder.h"
#include "glsl/GrGLSLVarying.h"
// Slightly undershoot an AA bloat radius of 0.5 so vertices that fall on integer boundaries don't
// accidentally reach into neighboring path masks within the atlas.
constexpr float kAABloatRadius = 0.491111f;
// Paths are drawn as octagons. Each point on the octagon is the intersection of two lines: one edge
// from the path's bounding box and one edge from its 45-degree bounding box. The below inputs
// define a vertex by the two edges that need to be intersected. Normals point out of the octagon,
// and the bounding boxes are sent in as instance attribs.
static constexpr float kOctoEdgeNorms[8 * 4] = {
// bbox // bbox45
-1, 0, -1,+1,
-1, 0, -1,-1,
0,-1, -1,-1,
0,-1, +1,-1,
+1, 0, +1,-1,
+1, 0, +1,+1,
0,+1, +1,+1,
0,+1, -1,+1,
};
GR_DECLARE_STATIC_UNIQUE_KEY(gVertexBufferKey);
sk_sp<const GrBuffer> GrCCPathProcessor::FindVertexBuffer(GrOnFlushResourceProvider* onFlushRP) {
GR_DEFINE_STATIC_UNIQUE_KEY(gVertexBufferKey);
return onFlushRP->findOrMakeStaticBuffer(kVertex_GrBufferType, sizeof(kOctoEdgeNorms),
kOctoEdgeNorms, gVertexBufferKey);
}
static constexpr uint16_t kRestartStrip = 0xffff;
static constexpr uint16_t kOctoIndicesAsStrips[] = {
1, 0, 2, 4, 3, kRestartStrip, // First half.
5, 4, 6, 0, 7 // Second half.
};
static constexpr uint16_t kOctoIndicesAsTris[] = {
// First half.
1, 0, 2,
0, 4, 2,
2, 4, 3,
// Second half.
5, 4, 6,
4, 0, 6,
6, 0, 7,
};
GR_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kInstanceAttribs[];
constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kEdgeNormsAttrib;
sk_sp<const GrBuffer> GrCCPathProcessor::FindIndexBuffer(GrOnFlushResourceProvider* onFlushRP) {
GR_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
if (onFlushRP->caps()->usePrimitiveRestart()) {
return onFlushRP->findOrMakeStaticBuffer(kIndex_GrBufferType, sizeof(kOctoIndicesAsStrips),
kOctoIndicesAsStrips, gIndexBufferKey);
} else {
return onFlushRP->findOrMakeStaticBuffer(kIndex_GrBufferType, sizeof(kOctoIndicesAsTris),
kOctoIndicesAsTris, gIndexBufferKey);
}
}
GrCCPathProcessor::GrCCPathProcessor(const GrTextureProxy* atlas,
const SkMatrix& viewMatrixIfUsingLocalCoords)
: INHERITED(kGrCCPathProcessor_ClassID)
, fAtlasAccess(atlas->textureType(), atlas->config(), GrSamplerState::Filter::kNearest,
GrSamplerState::WrapMode::kClamp)
, fAtlasSize(atlas->isize())
, fAtlasOrigin(atlas->origin()) {
// TODO: Can we just assert that atlas has GrCCAtlas::kTextureOrigin and remove fAtlasOrigin?
this->setInstanceAttributeCnt(kNumInstanceAttribs);
// Check that instance attributes exactly match Instance struct layout.
SkASSERT(!strcmp(this->instanceAttribute(0).name(), "devbounds"));
SkASSERT(!strcmp(this->instanceAttribute(1).name(), "devbounds45"));
SkASSERT(!strcmp(this->instanceAttribute(2).name(), "dev_to_atlas_offset"));
SkASSERT(!strcmp(this->instanceAttribute(3).name(), "color"));
SkASSERT(this->debugOnly_instanceAttributeOffset(0) == offsetof(Instance, fDevBounds));
SkASSERT(this->debugOnly_instanceAttributeOffset(1) == offsetof(Instance, fDevBounds45));
SkASSERT(this->debugOnly_instanceAttributeOffset(2) == offsetof(Instance, fDevToAtlasOffset));
SkASSERT(this->debugOnly_instanceAttributeOffset(3) == offsetof(Instance, fColor));
SkASSERT(this->debugOnly_instanceStride() == sizeof(Instance));
this->setVertexAttributeCnt(1);
this->setTextureSamplerCnt(1);
if (!viewMatrixIfUsingLocalCoords.invert(&fLocalMatrix)) {
fLocalMatrix.setIdentity();
}
}
class GLSLPathProcessor : public GrGLSLGeometryProcessor {
public:
void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override;
private:
void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor& primProc,
FPCoordTransformIter&& transformIter) override {
const GrCCPathProcessor& proc = primProc.cast<GrCCPathProcessor>();
pdman.set2f(fAtlasAdjustUniform, 1.0f / proc.atlasSize().fWidth,
1.0f / proc.atlasSize().fHeight);
this->setTransformDataHelper(proc.localMatrix(), pdman, &transformIter);
}
GrGLSLUniformHandler::UniformHandle fAtlasAdjustUniform;
typedef GrGLSLGeometryProcessor INHERITED;
};
GrGLSLPrimitiveProcessor* GrCCPathProcessor::createGLSLInstance(const GrShaderCaps&) const {
return new GLSLPathProcessor();
}
void GrCCPathProcessor::drawPaths(GrOpFlushState* flushState, const GrPipeline& pipeline,
const GrPipeline::FixedDynamicState* fixedDynamicState,
const GrCCPerFlushResources& resources, int baseInstance,
int endInstance, const SkRect& bounds) const {
const GrCaps& caps = flushState->caps();
GrPrimitiveType primitiveType = caps.usePrimitiveRestart()
? GrPrimitiveType::kTriangleStrip
: GrPrimitiveType::kTriangles;
int numIndicesPerInstance = caps.usePrimitiveRestart()
? SK_ARRAY_COUNT(kOctoIndicesAsStrips)
: SK_ARRAY_COUNT(kOctoIndicesAsTris);
GrMesh mesh(primitiveType);
auto enablePrimitiveRestart = GrPrimitiveRestart(flushState->caps().usePrimitiveRestart());
mesh.setIndexedInstanced(resources.indexBuffer(), numIndicesPerInstance,
resources.instanceBuffer(), endInstance - baseInstance, baseInstance,
enablePrimitiveRestart);
mesh.setVertexData(resources.vertexBuffer());
flushState->rtCommandBuffer()->draw(*this, pipeline, fixedDynamicState, nullptr, &mesh, 1,
bounds);
}
void GLSLPathProcessor::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
using InstanceAttribs = GrCCPathProcessor::InstanceAttribs;
using Interpolation = GrGLSLVaryingHandler::Interpolation;
const GrCCPathProcessor& proc = args.fGP.cast<GrCCPathProcessor>();
GrGLSLUniformHandler* uniHandler = args.fUniformHandler;
GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
const char* atlasAdjust;
fAtlasAdjustUniform = uniHandler->addUniform(
kVertex_GrShaderFlag,
kFloat2_GrSLType, "atlas_adjust", &atlasAdjust);
varyingHandler->emitAttributes(proc);
GrGLSLVarying texcoord(kFloat3_GrSLType);
GrGLSLVarying color(kHalf4_GrSLType);
varyingHandler->addVarying("texcoord", &texcoord);
varyingHandler->addPassThroughAttribute(proc.getInstanceAttrib(InstanceAttribs::kColor),
args.fOutputColor, Interpolation::kCanBeFlat);
// The vertex shader bloats and intersects the devBounds and devBounds45 rectangles, in order to
// find an octagon that circumscribes the (bloated) path.
GrGLSLVertexBuilder* v = args.fVertBuilder;
// Each vertex is the intersection of one edge from devBounds and one from devBounds45.
// 'N' holds the normals to these edges as column vectors.
//
// NOTE: "float2x2(float4)" is valid and equivalent to "float2x2(float4.xy, float4.zw)",
// however Intel compilers crash when we use the former syntax in this shader.
v->codeAppendf("float2x2 N = float2x2(%s.xy, %s.zw);", proc.getEdgeNormsAttrib().name(),
proc.getEdgeNormsAttrib().name());
// N[0] is the normal for the edge we are intersecting from the regular bounding box, pointing
// out of the octagon.
v->codeAppendf("float4 devbounds = %s;",
proc.getInstanceAttrib(InstanceAttribs::kDevBounds).name());
v->codeAppend ("float2 refpt = (0 == sk_VertexID >> 2)"
"? float2(min(devbounds.x, devbounds.z), devbounds.y)"
": float2(max(devbounds.x, devbounds.z), devbounds.w);");
v->codeAppendf("refpt += N[0] * %f;", kAABloatRadius); // bloat for AA.
// N[1] is the normal for the edge we are intersecting from the 45-degree bounding box, pointing
// out of the octagon.
v->codeAppendf("float2 refpt45 = (0 == ((sk_VertexID + 1) & (1 << 2))) ? %s.xy : %s.zw;",
proc.getInstanceAttrib(InstanceAttribs::kDevBounds45).name(),
proc.getInstanceAttrib(InstanceAttribs::kDevBounds45).name());
v->codeAppendf("refpt45 *= float2x2(.5,.5,-.5,.5);"); // transform back to device space.
v->codeAppendf("refpt45 += N[1] * %f;", kAABloatRadius); // bloat for AA.
v->codeAppend ("float2 K = float2(dot(N[0], refpt), dot(N[1], refpt45));");
v->codeAppendf("float2 octocoord = K * inverse(N);");
gpArgs->fPositionVar.set(kFloat2_GrSLType, "octocoord");
// Convert to atlas coordinates in order to do our texture lookup.
v->codeAppendf("float2 atlascoord = octocoord + float2(%s);",
proc.getInstanceAttrib(InstanceAttribs::kDevToAtlasOffset).name());
if (kTopLeft_GrSurfaceOrigin == proc.atlasOrigin()) {
v->codeAppendf("%s.xy = atlascoord * %s;", texcoord.vsOut(), atlasAdjust);
} else {
SkASSERT(kBottomLeft_GrSurfaceOrigin == proc.atlasOrigin());
v->codeAppendf("%s.xy = float2(atlascoord.x * %s.x, 1 - atlascoord.y * %s.y);",
texcoord.vsOut(), atlasAdjust, atlasAdjust);
}
// The third texture coordinate is -.5 for even-odd paths and +.5 for winding ones.
// ("right < left" indicates even-odd fill type.)
v->codeAppendf("%s.z = sign(devbounds.z - devbounds.x) * .5;", texcoord.vsOut());
this->emitTransforms(v, varyingHandler, uniHandler, GrShaderVar("octocoord", kFloat2_GrSLType),
proc.localMatrix(), args.fFPCoordTransformHandler);
// Fragment shader.
GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
// Look up coverage count in the atlas.
f->codeAppend ("half coverage = ");
f->appendTextureLookup(args.fTexSamplers[0], SkStringPrintf("%s.xy", texcoord.fsIn()).c_str(),
kFloat2_GrSLType);
f->codeAppend (".a;");
// Scale coverage count by .5. Make it negative for even-odd paths and positive for winding
// ones. Clamp winding coverage counts at 1.0 (i.e. min(coverage/2, .5)).
f->codeAppendf("coverage = min(abs(coverage) * %s.z, .5);", texcoord.fsIn());
// For negative values, this finishes the even-odd sawtooth function. Since positive (winding)
// values were clamped at "coverage/2 = .5", this only undoes the previous multiply by .5.
f->codeAppend ("coverage = 1 - abs(fract(coverage) * 2 - 1);");
f->codeAppendf("%s = half4(coverage);", args.fOutputCoverage);
}
<commit_msg>ccpr: Use ceil/floor to round out path cover octagons<commit_after>/*
* Copyright 2017 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrCCPathProcessor.h"
#include "GrGpuCommandBuffer.h"
#include "GrOnFlushResourceProvider.h"
#include "GrTexture.h"
#include "ccpr/GrCCPerFlushResources.h"
#include "glsl/GrGLSLFragmentShaderBuilder.h"
#include "glsl/GrGLSLGeometryProcessor.h"
#include "glsl/GrGLSLProgramBuilder.h"
#include "glsl/GrGLSLVarying.h"
// Paths are drawn as octagons. Each point on the octagon is the intersection of two lines: one edge
// from the path's bounding box and one edge from its 45-degree bounding box. The below inputs
// define a vertex by the two edges that need to be intersected. Normals point out of the octagon,
// and the bounding boxes are sent in as instance attribs.
static constexpr float kOctoEdgeNorms[8 * 4] = {
// bbox // bbox45
-1, 0, -1,+1,
-1, 0, -1,-1,
0,-1, -1,-1,
0,-1, +1,-1,
+1, 0, +1,-1,
+1, 0, +1,+1,
0,+1, +1,+1,
0,+1, -1,+1,
};
GR_DECLARE_STATIC_UNIQUE_KEY(gVertexBufferKey);
sk_sp<const GrBuffer> GrCCPathProcessor::FindVertexBuffer(GrOnFlushResourceProvider* onFlushRP) {
GR_DEFINE_STATIC_UNIQUE_KEY(gVertexBufferKey);
return onFlushRP->findOrMakeStaticBuffer(kVertex_GrBufferType, sizeof(kOctoEdgeNorms),
kOctoEdgeNorms, gVertexBufferKey);
}
static constexpr uint16_t kRestartStrip = 0xffff;
static constexpr uint16_t kOctoIndicesAsStrips[] = {
1, 0, 2, 4, 3, kRestartStrip, // First half.
5, 4, 6, 0, 7 // Second half.
};
static constexpr uint16_t kOctoIndicesAsTris[] = {
// First half.
1, 0, 2,
0, 4, 2,
2, 4, 3,
// Second half.
5, 4, 6,
4, 0, 6,
6, 0, 7,
};
GR_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kInstanceAttribs[];
constexpr GrPrimitiveProcessor::Attribute GrCCPathProcessor::kEdgeNormsAttrib;
sk_sp<const GrBuffer> GrCCPathProcessor::FindIndexBuffer(GrOnFlushResourceProvider* onFlushRP) {
GR_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
if (onFlushRP->caps()->usePrimitiveRestart()) {
return onFlushRP->findOrMakeStaticBuffer(kIndex_GrBufferType, sizeof(kOctoIndicesAsStrips),
kOctoIndicesAsStrips, gIndexBufferKey);
} else {
return onFlushRP->findOrMakeStaticBuffer(kIndex_GrBufferType, sizeof(kOctoIndicesAsTris),
kOctoIndicesAsTris, gIndexBufferKey);
}
}
GrCCPathProcessor::GrCCPathProcessor(const GrTextureProxy* atlas,
const SkMatrix& viewMatrixIfUsingLocalCoords)
: INHERITED(kGrCCPathProcessor_ClassID)
, fAtlasAccess(atlas->textureType(), atlas->config(), GrSamplerState::Filter::kNearest,
GrSamplerState::WrapMode::kClamp)
, fAtlasSize(atlas->isize())
, fAtlasOrigin(atlas->origin()) {
// TODO: Can we just assert that atlas has GrCCAtlas::kTextureOrigin and remove fAtlasOrigin?
this->setInstanceAttributeCnt(kNumInstanceAttribs);
// Check that instance attributes exactly match Instance struct layout.
SkASSERT(!strcmp(this->instanceAttribute(0).name(), "devbounds"));
SkASSERT(!strcmp(this->instanceAttribute(1).name(), "devbounds45"));
SkASSERT(!strcmp(this->instanceAttribute(2).name(), "dev_to_atlas_offset"));
SkASSERT(!strcmp(this->instanceAttribute(3).name(), "color"));
SkASSERT(this->debugOnly_instanceAttributeOffset(0) == offsetof(Instance, fDevBounds));
SkASSERT(this->debugOnly_instanceAttributeOffset(1) == offsetof(Instance, fDevBounds45));
SkASSERT(this->debugOnly_instanceAttributeOffset(2) == offsetof(Instance, fDevToAtlasOffset));
SkASSERT(this->debugOnly_instanceAttributeOffset(3) == offsetof(Instance, fColor));
SkASSERT(this->debugOnly_instanceStride() == sizeof(Instance));
this->setVertexAttributeCnt(1);
this->setTextureSamplerCnt(1);
if (!viewMatrixIfUsingLocalCoords.invert(&fLocalMatrix)) {
fLocalMatrix.setIdentity();
}
}
class GLSLPathProcessor : public GrGLSLGeometryProcessor {
public:
void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override;
private:
void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor& primProc,
FPCoordTransformIter&& transformIter) override {
const GrCCPathProcessor& proc = primProc.cast<GrCCPathProcessor>();
pdman.set2f(fAtlasAdjustUniform, 1.0f / proc.atlasSize().fWidth,
1.0f / proc.atlasSize().fHeight);
this->setTransformDataHelper(proc.localMatrix(), pdman, &transformIter);
}
GrGLSLUniformHandler::UniformHandle fAtlasAdjustUniform;
typedef GrGLSLGeometryProcessor INHERITED;
};
GrGLSLPrimitiveProcessor* GrCCPathProcessor::createGLSLInstance(const GrShaderCaps&) const {
return new GLSLPathProcessor();
}
void GrCCPathProcessor::drawPaths(GrOpFlushState* flushState, const GrPipeline& pipeline,
const GrPipeline::FixedDynamicState* fixedDynamicState,
const GrCCPerFlushResources& resources, int baseInstance,
int endInstance, const SkRect& bounds) const {
const GrCaps& caps = flushState->caps();
GrPrimitiveType primitiveType = caps.usePrimitiveRestart()
? GrPrimitiveType::kTriangleStrip
: GrPrimitiveType::kTriangles;
int numIndicesPerInstance = caps.usePrimitiveRestart()
? SK_ARRAY_COUNT(kOctoIndicesAsStrips)
: SK_ARRAY_COUNT(kOctoIndicesAsTris);
GrMesh mesh(primitiveType);
auto enablePrimitiveRestart = GrPrimitiveRestart(flushState->caps().usePrimitiveRestart());
mesh.setIndexedInstanced(resources.indexBuffer(), numIndicesPerInstance,
resources.instanceBuffer(), endInstance - baseInstance, baseInstance,
enablePrimitiveRestart);
mesh.setVertexData(resources.vertexBuffer());
flushState->rtCommandBuffer()->draw(*this, pipeline, fixedDynamicState, nullptr, &mesh, 1,
bounds);
}
void GLSLPathProcessor::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
using InstanceAttribs = GrCCPathProcessor::InstanceAttribs;
using Interpolation = GrGLSLVaryingHandler::Interpolation;
const GrCCPathProcessor& proc = args.fGP.cast<GrCCPathProcessor>();
GrGLSLUniformHandler* uniHandler = args.fUniformHandler;
GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
const char* atlasAdjust;
fAtlasAdjustUniform = uniHandler->addUniform(
kVertex_GrShaderFlag,
kFloat2_GrSLType, "atlas_adjust", &atlasAdjust);
varyingHandler->emitAttributes(proc);
GrGLSLVarying texcoord(kFloat3_GrSLType);
GrGLSLVarying color(kHalf4_GrSLType);
varyingHandler->addVarying("texcoord", &texcoord);
varyingHandler->addPassThroughAttribute(proc.getInstanceAttrib(InstanceAttribs::kColor),
args.fOutputColor, Interpolation::kCanBeFlat);
// The vertex shader bloats and intersects the devBounds and devBounds45 rectangles, in order to
// find an octagon that circumscribes the (bloated) path.
GrGLSLVertexBuilder* v = args.fVertBuilder;
// Each vertex is the intersection of one edge from devBounds and one from devBounds45.
// 'N' holds the normals to these edges as column vectors.
//
// NOTE: "float2x2(float4)" is valid and equivalent to "float2x2(float4.xy, float4.zw)",
// however Intel compilers crash when we use the former syntax in this shader.
v->codeAppendf("float2x2 N = float2x2(%s.xy, %s.zw);", proc.getEdgeNormsAttrib().name(),
proc.getEdgeNormsAttrib().name());
// N[0] is the normal for the edge we are intersecting from the regular bounding box, pointing
// out of the octagon.
v->codeAppendf("float4 devbounds = %s;",
proc.getInstanceAttrib(InstanceAttribs::kDevBounds).name());
v->codeAppend ("float2 refpt = (0 == sk_VertexID >> 2)"
"? float2(min(devbounds.x, devbounds.z), devbounds.y)"
": float2(max(devbounds.x, devbounds.z), devbounds.w);");
// N[1] is the normal for the edge we are intersecting from the 45-degree bounding box, pointing
// out of the octagon.
v->codeAppendf("float2 refpt45 = (0 == ((sk_VertexID + 1) & (1 << 2))) ? %s.xy : %s.zw;",
proc.getInstanceAttrib(InstanceAttribs::kDevBounds45).name(),
proc.getInstanceAttrib(InstanceAttribs::kDevBounds45).name());
v->codeAppendf("refpt45 *= float2x2(.5,.5,-.5,.5);"); // transform back to device space.
v->codeAppend ("float2 K = float2(dot(N[0], refpt), dot(N[1], refpt45));");
v->codeAppendf("float2 octocoord = K * inverse(N);");
// Round the octagon out to ensure we rasterize every pixel the path might touch. (Positive
// bloatdir means we should take the "ceil" and negative means to take the "floor".)
//
// NOTE: If we were just drawing a rect, ceil/floor would be enough. But since there are also
// diagonals in the octagon that cross through pixel centers, we need to outset by another
// quarter px to ensure those pixels get rasterized.
v->codeAppend ("float2 bloatdir = (0 != N[0].x) "
"? half2(N[0].x, N[1].y) : half2(N[1].x, N[0].y);");
v->codeAppend ("octocoord = (ceil(octocoord * bloatdir - 1e-4) + 0.25) * bloatdir;");
gpArgs->fPositionVar.set(kFloat2_GrSLType, "octocoord");
// Convert to atlas coordinates in order to do our texture lookup.
v->codeAppendf("float2 atlascoord = octocoord + float2(%s);",
proc.getInstanceAttrib(InstanceAttribs::kDevToAtlasOffset).name());
if (kTopLeft_GrSurfaceOrigin == proc.atlasOrigin()) {
v->codeAppendf("%s.xy = atlascoord * %s;", texcoord.vsOut(), atlasAdjust);
} else {
SkASSERT(kBottomLeft_GrSurfaceOrigin == proc.atlasOrigin());
v->codeAppendf("%s.xy = float2(atlascoord.x * %s.x, 1 - atlascoord.y * %s.y);",
texcoord.vsOut(), atlasAdjust, atlasAdjust);
}
// The third texture coordinate is -.5 for even-odd paths and +.5 for winding ones.
// ("right < left" indicates even-odd fill type.)
v->codeAppendf("%s.z = sign(devbounds.z - devbounds.x) * .5;", texcoord.vsOut());
this->emitTransforms(v, varyingHandler, uniHandler, GrShaderVar("octocoord", kFloat2_GrSLType),
proc.localMatrix(), args.fFPCoordTransformHandler);
// Fragment shader.
GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
// Look up coverage count in the atlas.
f->codeAppend ("half coverage = ");
f->appendTextureLookup(args.fTexSamplers[0], SkStringPrintf("%s.xy", texcoord.fsIn()).c_str(),
kFloat2_GrSLType);
f->codeAppend (".a;");
// Scale coverage count by .5. Make it negative for even-odd paths and positive for winding
// ones. Clamp winding coverage counts at 1.0 (i.e. min(coverage/2, .5)).
f->codeAppendf("coverage = min(abs(coverage) * %s.z, .5);", texcoord.fsIn());
// For negative values, this finishes the even-odd sawtooth function. Since positive (winding)
// values were clamped at "coverage/2 = .5", this only undoes the previous multiply by .5.
f->codeAppend ("coverage = 1 - abs(fract(coverage) * 2 - 1);");
f->codeAppendf("%s = half4(coverage);", args.fOutputCoverage);
}
<|endoftext|> |
<commit_before>#include "webstack/SessionRequestHandler.h"
void Susi::SessionRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& request,
Poco::Net::HTTPServerResponse& response ) {
std::string id = "";
Susi::Logger::debug( "starting SessionRequestHandler" );
try {
Poco::Net::NameValueCollection cookies;
request.getCookies( cookies );
id = cookies["susisession"];
Susi::Logger::debug( "sessionid: "+id );
if( !_sessionManager->checkSession( id ) ) {
Susi::Logger::debug( "No valid session" );
auto oldCookie = Poco::Net::HTTPCookie {"susisession",id};
oldCookie.setMaxAge( 0 );
response.addCookie( oldCookie );
Poco::Timestamp now;
id = std::to_string( now.epochMicroseconds() );
_sessionManager->updateSession( id );
auto cookie = Poco::Net::HTTPCookie {"susisession",id};
cookie.setPath( "/" );
response.addCookie( cookie );
}
}
catch( const std::exception & e ) {
Susi::Logger::debug( "no session found, add new one" );
Poco::Timestamp now;
id = std::to_string( now.epochMicroseconds() );
_sessionManager->updateSession( id );
auto cookie = Poco::Net::HTTPCookie {"susisession",id};
cookie.setPath( "/" );
response.addCookie( cookie );
Poco::Net::NameValueCollection cookies;
request.getCookies( cookies );
cookies.add( "susisession",id );
request.setCookies( cookies );
}
try {
defaultHandler->handleRequest( request,response );
}
catch( const std::exception & e ) {
std::string msg = "error in http handler: ";
msg += e.what();
Susi::Logger::error( msg );
}
Susi::Logger::debug( "finished in SessionRequestHandler" );
}
<commit_msg>[http stack] added flush after processing;<commit_after>#include "webstack/SessionRequestHandler.h"
void Susi::SessionRequestHandler::handleRequest( Poco::Net::HTTPServerRequest& request,
Poco::Net::HTTPServerResponse& response ) {
std::string id = "";
Susi::Logger::debug( "starting SessionRequestHandler" );
try {
Poco::Net::NameValueCollection cookies;
request.getCookies( cookies );
id = cookies["susisession"];
Susi::Logger::debug( "sessionid: "+id );
if( !_sessionManager->checkSession( id ) ) {
Susi::Logger::debug( "No valid session" );
auto oldCookie = Poco::Net::HTTPCookie {"susisession",id};
oldCookie.setMaxAge( 0 );
response.addCookie( oldCookie );
Poco::Timestamp now;
id = std::to_string( now.epochMicroseconds() );
_sessionManager->updateSession( id );
auto cookie = Poco::Net::HTTPCookie {"susisession",id};
cookie.setPath( "/" );
response.addCookie( cookie );
}
}
catch( const std::exception & e ) {
Susi::Logger::debug( "no session found, add new one" );
Poco::Timestamp now;
id = std::to_string( now.epochMicroseconds() );
_sessionManager->updateSession( id );
auto cookie = Poco::Net::HTTPCookie {"susisession",id};
cookie.setPath( "/" );
response.addCookie( cookie );
Poco::Net::NameValueCollection cookies;
request.getCookies( cookies );
cookies.add( "susisession",id );
request.setCookies( cookies );
}
try {
defaultHandler->handleRequest( request,response );
response.send().flush();
}
catch( const std::exception & e ) {
std::string msg = "error in http handler: ";
msg += e.what();
Susi::Logger::error( msg );
}
Susi::Logger::debug( "finished in SessionRequestHandler" );
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016-2017, Loic Blot <[email protected]>
* 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 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 "elasticsearchclient.h"
#include <cassert>
#include <iostream>
#include <core/http/query.h>
namespace winterwind
{
using namespace http;
namespace extras
{
#define ES_URL_CLUSTER_STATE "/_cluster/state"
#define ES_URL_NODES "/_nodes"
#define ES_BULK "/_bulk"
#define ES_ANALYZE "/_analyze"
ElasticsearchClient::ElasticsearchClient(const std::string &url)
: HTTPClient(100 * 1024), m_init_url(url)
{
discover_cluster();
}
ElasticsearchClient::~ElasticsearchClient()
{
while (!m_bulk_queue.empty()) {
m_bulk_queue.pop();
}
}
void ElasticsearchClient::discover_cluster()
{
Json::Value res;
Query query(m_init_url + ES_URL_CLUSTER_STATE);
if (!_get_json(query, res) ||
!res.isMember("cluster_name") ||
!res["cluster_name"].isString()) {
throw ElasticsearchException("Unable to parse Elasticsearch cluster state");
}
m_cluster_name = res["cluster_name"].asString();
if (!_get_json(query, res) || !res.isMember("nodes") ||
!res["nodes"].isObject()) {
throw ElasticsearchException("Unable to parse Elasticsearch nodes");
}
Json::Value::Members cluster_members = res["nodes"].getMemberNames();
for (const auto &member : cluster_members) {
ElasticsearchNode node(member);
const Json::Value &member_obj = res["nodes"][member];
if (member_obj.isMember("http_address") &&
member_obj["http_address"].isString()) {
node.http_addr = "http://" + member_obj["http_address"].asString();
} else if (member_obj.isMember("http") &&
member_obj["http"].isObject() &&
member_obj["http"].isMember("publish_address") &&
member_obj["http"]["publish_address"].isString()) {
node.http_addr =
"http://" + member_obj["http"]["publish_address"].asString();
}
// If node HTTP_ADDR is empty, try nodes API
if (node.http_addr.empty()) {
Json::Value res_http;
Query query_http(m_init_url + ES_URL_NODES + "/" + member + "/http");
if (_get_json(query_http, res_http) &&
res_http.isMember("cluster_name") &&
res_http["cluster_name"].isString() &&
res_http["cluster_name"].asString() == m_cluster_name &&
res_http.isMember("nodes") &&
res_http["nodes"].isObject() &&
res_http["nodes"].isMember(member) &&
res_http["nodes"][member].isObject() &&
res_http["nodes"][member].isMember("http") &&
res_http["nodes"][member]["http"].isObject() &&
res_http["nodes"][member]["http"].isMember("publish_address") &&
res_http["nodes"][member]["http"]["publish_address"].isString()) {
const Json::Value &http_member_obj = res_http["nodes"][member];
node.http_addr =
"http://" + http_member_obj["http"]["publish_address"].asString();
}
}
if (member_obj.isMember("version") && member_obj["version"].isString()) {
node.version = member_obj["version"].asString();
}
if (member_obj.isMember("attributes") && member_obj["attributes"].isObject()) {
Json::Value member_attrs = member_obj["attributes"];
// Master attribute is a string, not a bool
if (member_attrs.isMember("master") && member_attrs["master"].isString()) {
node.is_master =
member_attrs["master"].asString() == "true";
}
}
m_nodes.push_back(node);
}
m_last_discovery_time = std::chrono::system_clock::now();
}
const ElasticsearchNode &ElasticsearchClient::get_fresh_node()
{
// Rediscover cluster after 1 min
const auto freshness = std::chrono::system_clock::now() - m_last_discovery_time;
if (freshness.count() > 60000) {
discover_cluster();
}
return m_nodes[0];
}
void ElasticsearchClient::create_doc(const std::string &index, const std::string &type,
const Json::Value &doc)
{
const ElasticsearchNode &node = get_fresh_node();
std::string res;
Json::FastWriter writer;
std::string post_data = writer.write(doc);
Query query(node.http_addr + "/" + index + "/" + type + "/", post_data);
request(query, post_data);
}
void ElasticsearchClient::insert_doc(const std::string &index, const std::string &type,
const std::string &doc_id, const Json::Value &doc)
{
const ElasticsearchNode &node = get_fresh_node();
std::string res;
Json::FastWriter writer;
std::string post_data = writer.write(doc);
Query query(node.http_addr + "/" + index + "/" + type + "/" + doc_id, post_data, PUT);
request(query, res);
}
void ElasticsearchClient::delete_doc(const std::string &index, const std::string &type,
const std::string &doc_id)
{
const ElasticsearchNode &node = get_fresh_node();
std::string res;
request(Query(node.http_addr + "/" + index + "/" + type + "/" + doc_id, DELETE), res);
}
// related to ElasticsearchBulkActionType
static const std::string bulkaction_str_mapping[ESBULK_AT_MAX] = {
"create",
"delete",
"index",
"update"};
void ElasticsearchBulkAction::toJson(Json::FastWriter &writer, std::string &res)
{
// This should not happen
assert(action < ESBULK_AT_MAX);
Json::Value action_res;
std::string action_type = bulkaction_str_mapping[action];
action_res[action_type] = Json::Value();
if (!index.empty()) {
action_res[action_type]["_index"] = index;
}
if (!type.empty()) {
action_res[action_type]["_type"] = type;
}
if (!doc_id.empty()) {
action_res[action_type]["_id"] = doc_id;
}
res += writer.write(action_res);
if (action == ESBULK_AT_CREATE || action == ESBULK_AT_INDEX) {
res += writer.write(doc);
} else if (action == ESBULK_AT_UPDATE) {
Json::Value update;
update["doc"] = doc;
res += writer.write(update);
}
}
void ElasticsearchClient::process_bulkaction_queue(std::string &res,
uint32_t actions_limit)
{
const ElasticsearchNode &node = get_fresh_node();
std::string post_data;
uint32_t processed_actions = 0;
Json::FastWriter writer;
while (!m_bulk_queue.empty() &&
(actions_limit == 0 || processed_actions < actions_limit)) {
processed_actions++;
const ElasticsearchBulkActionPtr &action = m_bulk_queue.front();
action->toJson(writer, post_data);
m_bulk_queue.pop();
}
Query query(node.http_addr + ES_BULK, post_data, POST);
request(query, res);
}
bool ElasticsearchClient::analyze(const std::string &index, const std::string &analyzer,
const std::string &str, Json::Value &res)
{
const ElasticsearchNode &node = get_fresh_node();
Json::Value request;
request["analyzer"] = analyzer;
request["text"] = str;
Query query(node.http_addr + "/" + index + ES_ANALYZE);
return _get_json(query, request, res);
}
namespace elasticsearch {
Index::Index(const std::string &name, ElasticsearchClient *es_client):
m_name(name), m_es_client(es_client)
{
}
bool Index::exists()
{
Json::Value res;
Query query(m_es_client->get_node_addr() + "/" + m_name);
if (!m_es_client->_get_json(query, res)) {
return false;
}
return !res.isMember("error") && res.isMember(m_name) ||
!(res.isMember("status") && res["status"].isInt() &&
res["status"].asInt() == 404);
}
bool Index::create()
{
if (exists()) {
return true;
}
Json::Value req, res;
req["settings"] = Json::objectValue;
if (m_shard_count > 0) {
req["settings"]["number_of_shards"] = m_shard_count;
}
if (!m_analyzers.empty()) {
req["settings"]["analysis"] = Json::objectValue;
req["settings"]["analysis"]["analyzer"] = Json::objectValue;
for (const auto &analyzer: m_analyzers) {
req["settings"]["analysis"]["analyzer"][analyzer.first] =
analyzer.second->to_json();
}
}
Query query(m_es_client->get_node_addr() + "/" + m_name, PUT);
if (!m_es_client->_put_json(query, req, res)) {
return false;
}
if (res.isMember("error")) {
if (res["error"].isObject() && res["error"].isMember("reason")) {
std::cerr << "Elasticsearch index removal error: "
<< res["error"]["reason"] << std::endl;
}
return false;
}
return res.isMember("acknowledged") && res["acknowledged"].isBool()
&& res["acknowledged"].asBool();
}
bool Index::remove()
{
if (!exists()) {
return true;
}
Json::Value res;
if (!m_es_client->_delete(m_es_client->get_node_addr() + "/" + m_name, res)) {
return false;
}
if (res.isMember("error")) {
if (res["error"].isObject() && res["error"].isMember("reason")) {
std::cerr << "Elasticsearch index removal error: "
<< res["error"]["reason"] << std::endl;
}
return false;
}
return res.isMember("acknowledged") && res["acknowledged"].asBool();
}
bool Index::set_shard_count(uint16_t count)
{
if (exists()) {
std::cerr << "Unable to set shard count on an existing index" << std::endl;
return false;
}
m_shard_count = count;
return true;
}
Json::Value Analyzer::to_json() const
{
Json::Value result;
switch (m_type) {
case CUSTOM: result["type"] = "custom"; break;
default: assert(false);
}
result["tokenizer"] = m_tokenizer;
result["filter"] = Json::arrayValue;
for (const auto &filter: m_filters) {
result["filter"].append(filter);
}
return result;
}
}
}
}
<commit_msg>ES: fix create_doc<commit_after>/*
* Copyright (c) 2016-2017, Loic Blot <[email protected]>
* 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 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 "elasticsearchclient.h"
#include <cassert>
#include <iostream>
#include <core/http/query.h>
namespace winterwind
{
using namespace http;
namespace extras
{
#define ES_URL_CLUSTER_STATE "/_cluster/state"
#define ES_URL_NODES "/_nodes"
#define ES_BULK "/_bulk"
#define ES_ANALYZE "/_analyze"
ElasticsearchClient::ElasticsearchClient(const std::string &url)
: HTTPClient(100 * 1024), m_init_url(url)
{
discover_cluster();
}
ElasticsearchClient::~ElasticsearchClient()
{
while (!m_bulk_queue.empty()) {
m_bulk_queue.pop();
}
}
void ElasticsearchClient::discover_cluster()
{
Json::Value res;
Query query(m_init_url + ES_URL_CLUSTER_STATE);
if (!_get_json(query, res) ||
!res.isMember("cluster_name") ||
!res["cluster_name"].isString()) {
throw ElasticsearchException("Unable to parse Elasticsearch cluster state");
}
m_cluster_name = res["cluster_name"].asString();
if (!_get_json(query, res) || !res.isMember("nodes") ||
!res["nodes"].isObject()) {
throw ElasticsearchException("Unable to parse Elasticsearch nodes");
}
Json::Value::Members cluster_members = res["nodes"].getMemberNames();
for (const auto &member : cluster_members) {
ElasticsearchNode node(member);
const Json::Value &member_obj = res["nodes"][member];
if (member_obj.isMember("http_address") &&
member_obj["http_address"].isString()) {
node.http_addr = "http://" + member_obj["http_address"].asString();
} else if (member_obj.isMember("http") &&
member_obj["http"].isObject() &&
member_obj["http"].isMember("publish_address") &&
member_obj["http"]["publish_address"].isString()) {
node.http_addr =
"http://" + member_obj["http"]["publish_address"].asString();
}
// If node HTTP_ADDR is empty, try nodes API
if (node.http_addr.empty()) {
Json::Value res_http;
Query query_http(m_init_url + ES_URL_NODES + "/" + member + "/http");
if (_get_json(query_http, res_http) &&
res_http.isMember("cluster_name") &&
res_http["cluster_name"].isString() &&
res_http["cluster_name"].asString() == m_cluster_name &&
res_http.isMember("nodes") &&
res_http["nodes"].isObject() &&
res_http["nodes"].isMember(member) &&
res_http["nodes"][member].isObject() &&
res_http["nodes"][member].isMember("http") &&
res_http["nodes"][member]["http"].isObject() &&
res_http["nodes"][member]["http"].isMember("publish_address") &&
res_http["nodes"][member]["http"]["publish_address"].isString()) {
const Json::Value &http_member_obj = res_http["nodes"][member];
node.http_addr =
"http://" + http_member_obj["http"]["publish_address"].asString();
}
}
if (member_obj.isMember("version") && member_obj["version"].isString()) {
node.version = member_obj["version"].asString();
}
if (member_obj.isMember("attributes") && member_obj["attributes"].isObject()) {
Json::Value member_attrs = member_obj["attributes"];
// Master attribute is a string, not a bool
if (member_attrs.isMember("master") && member_attrs["master"].isString()) {
node.is_master =
member_attrs["master"].asString() == "true";
}
}
m_nodes.push_back(node);
}
m_last_discovery_time = std::chrono::system_clock::now();
}
const ElasticsearchNode &ElasticsearchClient::get_fresh_node()
{
// Rediscover cluster after 1 min
const auto freshness = std::chrono::system_clock::now() - m_last_discovery_time;
if (freshness.count() > 60000) {
discover_cluster();
}
return m_nodes[0];
}
void ElasticsearchClient::create_doc(const std::string &index, const std::string &type,
const Json::Value &doc)
{
const ElasticsearchNode &node = get_fresh_node();
std::string res;
Json::FastWriter writer;
std::string post_data = writer.write(doc);
Query query(node.http_addr + "/" + index + "/" + type + "/", post_data);
request(query, res);
}
void ElasticsearchClient::insert_doc(const std::string &index, const std::string &type,
const std::string &doc_id, const Json::Value &doc)
{
const ElasticsearchNode &node = get_fresh_node();
std::string res;
Json::FastWriter writer;
std::string post_data = writer.write(doc);
Query query(node.http_addr + "/" + index + "/" + type + "/" + doc_id, post_data, PUT);
request(query, res);
}
void ElasticsearchClient::delete_doc(const std::string &index, const std::string &type,
const std::string &doc_id)
{
const ElasticsearchNode &node = get_fresh_node();
std::string res;
request(Query(node.http_addr + "/" + index + "/" + type + "/" + doc_id, DELETE), res);
}
// related to ElasticsearchBulkActionType
static const std::string bulkaction_str_mapping[ESBULK_AT_MAX] = {
"create",
"delete",
"index",
"update"};
void ElasticsearchBulkAction::toJson(Json::FastWriter &writer, std::string &res)
{
// This should not happen
assert(action < ESBULK_AT_MAX);
Json::Value action_res;
std::string action_type = bulkaction_str_mapping[action];
action_res[action_type] = Json::Value();
if (!index.empty()) {
action_res[action_type]["_index"] = index;
}
if (!type.empty()) {
action_res[action_type]["_type"] = type;
}
if (!doc_id.empty()) {
action_res[action_type]["_id"] = doc_id;
}
res += writer.write(action_res);
if (action == ESBULK_AT_CREATE || action == ESBULK_AT_INDEX) {
res += writer.write(doc);
} else if (action == ESBULK_AT_UPDATE) {
Json::Value update;
update["doc"] = doc;
res += writer.write(update);
}
}
void ElasticsearchClient::process_bulkaction_queue(std::string &res,
uint32_t actions_limit)
{
const ElasticsearchNode &node = get_fresh_node();
std::string post_data;
uint32_t processed_actions = 0;
Json::FastWriter writer;
while (!m_bulk_queue.empty() &&
(actions_limit == 0 || processed_actions < actions_limit)) {
processed_actions++;
const ElasticsearchBulkActionPtr &action = m_bulk_queue.front();
action->toJson(writer, post_data);
m_bulk_queue.pop();
}
Query query(node.http_addr + ES_BULK, post_data, POST);
request(query, res);
}
bool ElasticsearchClient::analyze(const std::string &index, const std::string &analyzer,
const std::string &str, Json::Value &res)
{
const ElasticsearchNode &node = get_fresh_node();
Json::Value request;
request["analyzer"] = analyzer;
request["text"] = str;
Query query(node.http_addr + "/" + index + ES_ANALYZE);
return _get_json(query, request, res);
}
namespace elasticsearch {
Index::Index(const std::string &name, ElasticsearchClient *es_client):
m_name(name), m_es_client(es_client)
{
}
bool Index::exists()
{
Json::Value res;
Query query(m_es_client->get_node_addr() + "/" + m_name);
if (!m_es_client->_get_json(query, res)) {
return false;
}
return !res.isMember("error") && res.isMember(m_name) ||
!(res.isMember("status") && res["status"].isInt() &&
res["status"].asInt() == 404);
}
bool Index::create()
{
if (exists()) {
return true;
}
Json::Value req, res;
req["settings"] = Json::objectValue;
if (m_shard_count > 0) {
req["settings"]["number_of_shards"] = m_shard_count;
}
if (!m_analyzers.empty()) {
req["settings"]["analysis"] = Json::objectValue;
req["settings"]["analysis"]["analyzer"] = Json::objectValue;
for (const auto &analyzer: m_analyzers) {
req["settings"]["analysis"]["analyzer"][analyzer.first] =
analyzer.second->to_json();
}
}
Query query(m_es_client->get_node_addr() + "/" + m_name, PUT);
if (!m_es_client->_put_json(query, req, res)) {
return false;
}
if (res.isMember("error")) {
if (res["error"].isObject() && res["error"].isMember("reason")) {
std::cerr << "Elasticsearch index removal error: "
<< res["error"]["reason"] << std::endl;
}
return false;
}
return res.isMember("acknowledged") && res["acknowledged"].isBool()
&& res["acknowledged"].asBool();
}
bool Index::remove()
{
if (!exists()) {
return true;
}
Json::Value res;
if (!m_es_client->_delete(m_es_client->get_node_addr() + "/" + m_name, res)) {
return false;
}
if (res.isMember("error")) {
if (res["error"].isObject() && res["error"].isMember("reason")) {
std::cerr << "Elasticsearch index removal error: "
<< res["error"]["reason"] << std::endl;
}
return false;
}
return res.isMember("acknowledged") && res["acknowledged"].asBool();
}
bool Index::set_shard_count(uint16_t count)
{
if (exists()) {
std::cerr << "Unable to set shard count on an existing index" << std::endl;
return false;
}
m_shard_count = count;
return true;
}
Json::Value Analyzer::to_json() const
{
Json::Value result;
switch (m_type) {
case CUSTOM: result["type"] = "custom"; break;
default: assert(false);
}
result["tokenizer"] = m_tokenizer;
result["filter"] = Json::arrayValue;
for (const auto &filter: m_filters) {
result["filter"].append(filter);
}
return result;
}
}
}
}
<|endoftext|> |
<commit_before>#include "util.h"
#include "camera.h"
static const float SPEED = 50.0f;
static const float MOUSE_SPEED = 0.025f;
static Camera* camera;
static void error_callback(int error, const char* description)
{
std::cerr << description << std::endl;
}
GLFWwindow* init(const char* exampleName, int width, int height)
{
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if(!glfwInit())
{
return 0;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // OS X
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(width, height, exampleName, NULL, NULL);
if(!window)
{
glfwTerminate();
return 0;
}
glfwMakeContextCurrent(window);
std::cout << "Using OpenGL version " << glGetString(GL_VERSION) << std::endl;
return window;
}
GLuint loadImage(const char* fileName, int* w, int* h, int index)
{
GLuint tex;
unsigned char* img = SOIL_load_image(fileName, w, h, NULL, SOIL_LOAD_RGB);
if(!img)
{
std::cerr << "Error loading image " << fileName << ": " << SOIL_last_result() << std::endl;
return 0;
}
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0 + index);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, *w, *h, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
SOIL_free_image_data(img);
return tex;
}
GLuint loadCubeMap(const char* posX, const char* negX, const char* posY,
const char* negY, const char* posZ, const char* negZ)
{
static const GLenum textureTypes[] =
{
GL_TEXTURE_CUBE_MAP_POSITIVE_X,
GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
};
const char* names[] =
{
posX,
negX,
posY,
negY,
posZ,
negZ
};
GLuint tex;
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
for(int i = 0; i < 6; ++i)
{
int w, h;
unsigned char* img = SOIL_load_image(names[i], &w, &h, NULL, SOIL_LOAD_RGBA);
if(!img)
{
std::cerr << "Could not load image " << names[i] << " for cubemap: " << SOIL_last_result() << std::endl;
glDeleteTextures(1, &tex);
return 0;
}
glTexImage2D(textureTypes[i], 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, img);
SOIL_free_image_data(img);
}
return tex;
}
void setCamera(Camera* cam)
{
camera = cam;
}
void updateCamera(int width, int height, GLFWwindow* window)
{
float deltaTime = (float)glfwGetTime();
glfwSetTime(0.0);
// Get mouse position
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
glfwSetCursorPos(window, width / 2, height / 2);
float horizontalAngle = camera->getHorizontalAngle();
float verticalAngle = camera->getVerticalAngle();
horizontalAngle += MOUSE_SPEED * deltaTime * (float)(width / 2 - xpos);
verticalAngle += MOUSE_SPEED * deltaTime * (float)(height / 2 - ypos);
camera->setHorizontalAngle(horizontalAngle);
camera->setVerticalAngle(verticalAngle);
// Get key input
glm::vec3 direction = camera->getDirectionVector();
glm::vec3 position = camera->getPosition();
glm::vec3 right = camera->getRightVector();
if(glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
{
position += direction * deltaTime * SPEED;
}
if(glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
{
position -= direction * deltaTime * SPEED;
}
if(glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)
{
position -= right * deltaTime * SPEED;
}
else if(glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)
{
position += right * deltaTime * SPEED;
}
camera->setPosition(position.x, position.y, position.z);
}
<commit_msg>Skybox rendering<commit_after>#include "util.h"
#include "camera.h"
static const float SPEED = 50.0f;
static const float MOUSE_SPEED = 0.025f;
static Camera* camera;
static void error_callback(int error, const char* description)
{
std::cerr << description << std::endl;
}
GLFWwindow* init(const char* exampleName, int width, int height)
{
GLFWwindow* window;
glfwSetErrorCallback(error_callback);
if(!glfwInit())
{
return 0;
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // OS X
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(width, height, exampleName, NULL, NULL);
if(!window)
{
glfwTerminate();
return 0;
}
glfwMakeContextCurrent(window);
std::cout << "Using OpenGL version " << glGetString(GL_VERSION) << std::endl;
return window;
}
GLuint loadImage(const char* fileName, int* w, int* h, int index)
{
GLuint tex;
unsigned char* img = SOIL_load_image(fileName, w, h, NULL, SOIL_LOAD_RGB);
if(!img)
{
std::cerr << "Error loading image " << fileName << ": " << SOIL_last_result() << std::endl;
return 0;
}
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0 + index);
glBindTexture(GL_TEXTURE_2D, tex);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, *w, *h, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
SOIL_free_image_data(img);
return tex;
}
GLuint loadCubeMap(const char* posX, const char* negX, const char* posY,
const char* negY, const char* posZ, const char* negZ)
{
static const GLenum textureTypes[] =
{
GL_TEXTURE_CUBE_MAP_POSITIVE_X,
GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
GL_TEXTURE_CUBE_MAP_NEGATIVE_Z
};
const char* names[] =
{
posX,
negX,
posY,
negY,
posZ,
negZ
};
GLuint tex;
glGenTextures(1, &tex);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, tex);
for(int i = 0; i < 6; ++i)
{
int w, h;
unsigned char* img = SOIL_load_image(names[i], &w, &h, NULL, SOIL_LOAD_RGBA);
if(!img)
{
std::cerr << "Could not load image " << names[i] << " for cubemap: " << SOIL_last_result() << std::endl;
glDeleteTextures(1, &tex);
return 0;
}
glTexImage2D(textureTypes[i], 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, img);
SOIL_free_image_data(img);
}
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
return tex;
}
void setCamera(Camera* cam)
{
camera = cam;
}
void updateCamera(int width, int height, GLFWwindow* window)
{
float deltaTime = (float)glfwGetTime();
glfwSetTime(0.0);
// Get mouse position
double xpos, ypos;
glfwGetCursorPos(window, &xpos, &ypos);
glfwSetCursorPos(window, width / 2, height / 2);
float horizontalAngle = camera->getHorizontalAngle();
float verticalAngle = camera->getVerticalAngle();
horizontalAngle += MOUSE_SPEED * deltaTime * (float)(width / 2 - xpos);
verticalAngle += MOUSE_SPEED * deltaTime * (float)(height / 2 - ypos);
camera->setHorizontalAngle(horizontalAngle);
camera->setVerticalAngle(verticalAngle);
// Get key input
glm::vec3 direction = camera->getDirectionVector();
glm::vec3 position = camera->getPosition();
glm::vec3 right = camera->getRightVector();
if(glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS)
{
position += direction * deltaTime * SPEED;
}
if(glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS)
{
position -= direction * deltaTime * SPEED;
}
if(glfwGetKey(window, GLFW_KEY_LEFT) == GLFW_PRESS)
{
position -= right * deltaTime * SPEED;
}
else if(glfwGetKey(window, GLFW_KEY_RIGHT) == GLFW_PRESS)
{
position += right * deltaTime * SPEED;
}
camera->setPosition(position.x, position.y, position.z);
}
<|endoftext|> |
<commit_before>/*
* ZoteroCollectionsLocal.cpp
*
* Copyright (C) 2009-20 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "ZoteroCollectionsLocal.hpp"
#include <boost/bind.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>
#include <core/FileSerializer.hpp>
#include <core/Database.hpp>
#include <core/system/Process.hpp>
#include <r/RExec.hpp>
#include <session/prefs/UserState.hpp>
#include <session/SessionModuleContext.hpp>
#include "session-config.h"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace zotero {
namespace collections {
namespace {
SEXP createCacheSpecSEXP( ZoteroCollectionSpec cacheSpec, r::sexp::Protect* pProtect)
{
std::vector<std::string> names;
names.push_back(kName);
names.push_back(kVersion);
SEXP cacheSpecSEXP = r::sexp::createList(names, pProtect);
r::sexp::setNamedListElement(cacheSpecSEXP, kName, cacheSpec.name);
r::sexp::setNamedListElement(cacheSpecSEXP, kVersion, cacheSpec.version);
return cacheSpecSEXP;
}
void testZoteroSQLite(std::string dataDir)
{
// connect to sqlite
std::string db = dataDir + "/zotero.sqlite";
database::SqliteConnectionOptions options = { db };
boost::shared_ptr<database::IConnection> pConnection;
Error error = database::connect(options, &pConnection);
if (error)
{
LOG_ERROR(error);
return;
}
database::Rowset rows;
database::Query query = pConnection->query("select collectionName, version from collections");
error = pConnection->execute(query, rows);
if (error)
{
LOG_ERROR(error);
return;
}
for (database::RowsetIterator it = rows.begin(); it != rows.end(); ++it)
{
database::Row& row = *it;
std::string name = row.get<std::string>("collectionName");
int version = row.get<int>("version");
std::cerr << name << " - " << version << std::endl;
}
}
void getLocalLibrary(std::string key,
ZoteroCollectionSpec cacheSpec,
ZoteroCollectionsHandler handler)
{
r::sexp::Protect protect;
std::string libraryJsonStr;
Error error = r::exec::RFunction(".rs.zoteroGetLibrary", key,
createCacheSpecSEXP(cacheSpec, &protect)).call(&libraryJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
json::Object libraryJson;
error = libraryJson.parse(libraryJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
ZoteroCollection collection;
collection.name = libraryJson[kName].getString();
collection.version = libraryJson[kVersion].getInt();
collection.items = libraryJson[kItems].getArray();
handler(Success(), std::vector<ZoteroCollection>{ collection });
}
}
}
void getLocalCollections(std::string key,
std::vector<std::string> collections,
ZoteroCollectionSpecs cacheSpecs,
ZoteroCollectionsHandler handler)
{
json::Array cacheSpecsJson;
std::transform(cacheSpecs.begin(), cacheSpecs.end(), std::back_inserter(cacheSpecsJson), [](ZoteroCollectionSpec spec) {
json::Object specJson;
specJson[kName] = spec.name;
specJson[kVersion] = spec.version;
return specJson;
});
r::sexp::Protect protect;
std::string collectionJsonStr;
Error error = r::exec::RFunction(".rs.zoteroGetCollections", key, collections, cacheSpecsJson)
.call(&collectionJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
json::Array collectionsJson;
error = collectionsJson.parse(collectionJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
ZoteroCollections collections;
std::transform(collectionsJson.begin(), collectionsJson.end(), std::back_inserter(collections), [](json::Value json) {
ZoteroCollection collection;
json::Object collectionJson = json.getObject();
collection.name = collectionJson[kName].getString();
collection.version = collectionJson[kVersion].getInt();
collection.items = collectionJson[kItems].getArray();
return collection;
});
handler(Success(), collections);
}
}
}
FilePath userHomeDir()
{
std::string homeEnv;
#ifdef _WIN32
homeEnv = "USERPROFILE";
#else
homeEnv = "HOME";
#endif
return FilePath(string_utils::systemToUtf8(core::system::getenv(homeEnv)));
}
// https://www.zotero.org/support/kb/profile_directory
FilePath zoteroProfilesDir()
{
FilePath homeDir = userHomeDir();
std::string profilesDir;
#if defined(_WIN32)
profilesDir = "AppData\\Roaming\\Zotero\\Zotero\\Profiles";
#elif defined(__APPLE__)
profilesDir = "Library/Application Support/Zotero/Profiles";
#else
profilesDir = ".zotero/zotero";
#endif
return homeDir.completeChildPath(profilesDir);
}
// https://www.zotero.org/support/zotero_data
FilePath defaultZoteroDataDir()
{
FilePath homeDir = userHomeDir();
return homeDir.completeChildPath("Zotero");
}
FilePath detectZoteroDataDir()
{
// we'll fall back to the default if we can't find another dir in the profile
FilePath dataDir = defaultZoteroDataDir();
// find the zotero profiles dir
FilePath profilesDir = zoteroProfilesDir();
if (profilesDir.exists())
{
// there will be one path in the directory
std::vector<FilePath> children;
Error error = profilesDir.getChildren(children);
if (error)
LOG_ERROR(error);
if (children.size() > 0)
{
// there will be a single directory inside the profiles dir
FilePath profileDir = children[0];
FilePath prefsFile = profileDir.completeChildPath("prefs.js");
if (prefsFile.exists())
{
// read the prefs.js file
std::string prefs;
error = core::readStringFromFile(prefsFile, &prefs);
if (error)
LOG_ERROR(error);
// look for the zotero.dataDir pref
boost::smatch match;
boost::regex regex("user_pref\\(\"extensions.zotero.dataDir\",\\s*\"([^\"]+)\"\\);");
if (boost::regex_search(prefs, match, regex))
{
// set dataDiroly if the path exists
FilePath profileDataDir(match[1]);
if (profileDataDir.exists())
dataDir = profileDataDir;
}
}
}
}
// return the data dir
return dataDir;
}
} // end anonymous namespace
bool localZoteroAvailable()
{
// availability based on server vs. desktop
#ifdef RSTUDIO_SERVER
bool local = false;
#else
bool local = true;
#endif
// however, also make it available in debug mode for local dev/test
#ifndef NDEBUG
local = true;
#endif
return local;
}
// Detect the Zotero data directory and return it if it exists
FilePath detectedZoteroDataDirectory()
{
if (localZoteroAvailable())
{
FilePath dataDir = detectZoteroDataDir();
if (dataDir.exists())
return dataDir;
else
return FilePath();
}
else
{
return FilePath();
}
}
// Returns the zoteroDataDirectory (if any). This will return a valid FilePath
// if the user has specified a zotero data dir in the preferences; OR if
// a zotero data dir was detected on the system. In the former case the
// path may not exist (and this should be logged as an error)
FilePath zoteroDataDirectory()
{
std::string dataDir = prefs::userState().zoteroDataDir();
if (!dataDir.empty())
return module_context::resolveAliasedPath(dataDir);
else
return detectedZoteroDataDirectory();
}
ZoteroCollectionSource localCollections()
{
ZoteroCollectionSource source;
source.getLibrary = getLocalLibrary;
source.getCollections = getLocalCollections;
return source;
}
} // end namespace collections
} // end namespace zotero
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>some initial sqlite wrapper functions<commit_after>/*
* ZoteroCollectionsLocal.cpp
*
* Copyright (C) 2009-20 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "ZoteroCollectionsLocal.hpp"
#include <boost/bind.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>
#include <core/FileSerializer.hpp>
#include <core/Database.hpp>
#include <core/system/Process.hpp>
#include <r/RExec.hpp>
#include <session/prefs/UserState.hpp>
#include <session/SessionModuleContext.hpp>
#include "session-config.h"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace zotero {
namespace collections {
namespace {
SEXP createCacheSpecSEXP( ZoteroCollectionSpec cacheSpec, r::sexp::Protect* pProtect)
{
std::vector<std::string> names;
names.push_back(kName);
names.push_back(kVersion);
SEXP cacheSpecSEXP = r::sexp::createList(names, pProtect);
r::sexp::setNamedListElement(cacheSpecSEXP, kName, cacheSpec.name);
r::sexp::setNamedListElement(cacheSpecSEXP, kVersion, cacheSpec.version);
return cacheSpecSEXP;
}
void execQuery(boost::shared_ptr<database::IConnection> pConnection,
const std::string& sql,
boost::function<void(const database::Row&)> rowHandler)
{
database::Rowset rows;
database::Query query = pConnection->query(sql);
Error error = pConnection->execute(query, rows);
if (error)
{
LOG_ERROR(error);
return;
}
for (database::RowsetIterator it = rows.begin(); it != rows.end(); ++it)
{
const database::Row& row = *it;
rowHandler(row);
}
}
ZoteroCollectionSpecs getCollections(boost::shared_ptr<database::IConnection> pConnection)
{
ZoteroCollectionSpecs specs;
execQuery(pConnection, "select collectionName, version from collections", [&specs](const database::Row& row) {
ZoteroCollectionSpec spec;
spec.name = row.get<std::string>("collectionName");
spec.version = row.get<int>("version");
specs.push_back(spec);
});
return specs;
}
int getLibraryVersion(boost::shared_ptr<database::IConnection> pConnection)
{
int version = 0;
execQuery(pConnection, "SELECT MAX(version) AS version from items", [&version](const database::Row& row) {
std::string versionStr = row.get<std::string>("version");
version = safe_convert::stringTo<int>(versionStr, 0);
});
return version;
}
void testZoteroSQLite(std::string dataDir)
{
// connect to sqlite
std::string db = dataDir + "/zotero.sqlite";
database::SqliteConnectionOptions options = { db };
boost::shared_ptr<database::IConnection> pConnection;
Error error = database::connect(options, &pConnection);
if (error)
{
LOG_ERROR(error);
return;
}
std::cerr << "library: " << getLibraryVersion(pConnection) << std::endl;
ZoteroCollectionSpecs specs = getCollections(pConnection);
for (auto spec : specs)
std::cerr << spec.name << ": " << spec.version << std::endl;
}
void getLocalLibrary(std::string key,
ZoteroCollectionSpec cacheSpec,
ZoteroCollectionsHandler handler)
{
testZoteroSQLite(key);
r::sexp::Protect protect;
std::string libraryJsonStr;
Error error = r::exec::RFunction(".rs.zoteroGetLibrary", key,
createCacheSpecSEXP(cacheSpec, &protect)).call(&libraryJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
json::Object libraryJson;
error = libraryJson.parse(libraryJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
ZoteroCollection collection;
collection.name = libraryJson[kName].getString();
collection.version = libraryJson[kVersion].getInt();
collection.items = libraryJson[kItems].getArray();
handler(Success(), std::vector<ZoteroCollection>{ collection });
}
}
}
void getLocalCollections(std::string key,
std::vector<std::string> collections,
ZoteroCollectionSpecs cacheSpecs,
ZoteroCollectionsHandler handler)
{
json::Array cacheSpecsJson;
std::transform(cacheSpecs.begin(), cacheSpecs.end(), std::back_inserter(cacheSpecsJson), [](ZoteroCollectionSpec spec) {
json::Object specJson;
specJson[kName] = spec.name;
specJson[kVersion] = spec.version;
return specJson;
});
r::sexp::Protect protect;
std::string collectionJsonStr;
Error error = r::exec::RFunction(".rs.zoteroGetCollections", key, collections, cacheSpecsJson)
.call(&collectionJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
json::Array collectionsJson;
error = collectionsJson.parse(collectionJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
ZoteroCollections collections;
std::transform(collectionsJson.begin(), collectionsJson.end(), std::back_inserter(collections), [](json::Value json) {
ZoteroCollection collection;
json::Object collectionJson = json.getObject();
collection.name = collectionJson[kName].getString();
collection.version = collectionJson[kVersion].getInt();
collection.items = collectionJson[kItems].getArray();
return collection;
});
handler(Success(), collections);
}
}
}
FilePath userHomeDir()
{
std::string homeEnv;
#ifdef _WIN32
homeEnv = "USERPROFILE";
#else
homeEnv = "HOME";
#endif
return FilePath(string_utils::systemToUtf8(core::system::getenv(homeEnv)));
}
// https://www.zotero.org/support/kb/profile_directory
FilePath zoteroProfilesDir()
{
FilePath homeDir = userHomeDir();
std::string profilesDir;
#if defined(_WIN32)
profilesDir = "AppData\\Roaming\\Zotero\\Zotero\\Profiles";
#elif defined(__APPLE__)
profilesDir = "Library/Application Support/Zotero/Profiles";
#else
profilesDir = ".zotero/zotero";
#endif
return homeDir.completeChildPath(profilesDir);
}
// https://www.zotero.org/support/zotero_data
FilePath defaultZoteroDataDir()
{
FilePath homeDir = userHomeDir();
return homeDir.completeChildPath("Zotero");
}
FilePath detectZoteroDataDir()
{
// we'll fall back to the default if we can't find another dir in the profile
FilePath dataDir = defaultZoteroDataDir();
// find the zotero profiles dir
FilePath profilesDir = zoteroProfilesDir();
if (profilesDir.exists())
{
// there will be one path in the directory
std::vector<FilePath> children;
Error error = profilesDir.getChildren(children);
if (error)
LOG_ERROR(error);
if (children.size() > 0)
{
// there will be a single directory inside the profiles dir
FilePath profileDir = children[0];
FilePath prefsFile = profileDir.completeChildPath("prefs.js");
if (prefsFile.exists())
{
// read the prefs.js file
std::string prefs;
error = core::readStringFromFile(prefsFile, &prefs);
if (error)
LOG_ERROR(error);
// look for the zotero.dataDir pref
boost::smatch match;
boost::regex regex("user_pref\\(\"extensions.zotero.dataDir\",\\s*\"([^\"]+)\"\\);");
if (boost::regex_search(prefs, match, regex))
{
// set dataDiroly if the path exists
FilePath profileDataDir(match[1]);
if (profileDataDir.exists())
dataDir = profileDataDir;
}
}
}
}
// return the data dir
return dataDir;
}
} // end anonymous namespace
bool localZoteroAvailable()
{
// availability based on server vs. desktop
#ifdef RSTUDIO_SERVER
bool local = false;
#else
bool local = true;
#endif
// however, also make it available in debug mode for local dev/test
#ifndef NDEBUG
local = true;
#endif
return local;
}
// Detect the Zotero data directory and return it if it exists
FilePath detectedZoteroDataDirectory()
{
if (localZoteroAvailable())
{
FilePath dataDir = detectZoteroDataDir();
if (dataDir.exists())
return dataDir;
else
return FilePath();
}
else
{
return FilePath();
}
}
// Returns the zoteroDataDirectory (if any). This will return a valid FilePath
// if the user has specified a zotero data dir in the preferences; OR if
// a zotero data dir was detected on the system. In the former case the
// path may not exist (and this should be logged as an error)
FilePath zoteroDataDirectory()
{
std::string dataDir = prefs::userState().zoteroDataDir();
if (!dataDir.empty())
return module_context::resolveAliasedPath(dataDir);
else
return detectedZoteroDataDirectory();
}
ZoteroCollectionSource localCollections()
{
ZoteroCollectionSource source;
source.getLibrary = getLocalLibrary;
source.getCollections = getLocalCollections;
return source;
}
} // end namespace collections
} // end namespace zotero
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|> |
<commit_before>// Copyright 2019 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 "google/cloud/spanner/client.h"
#include "google/cloud/spanner/database.h"
#include "google/cloud/spanner/database_admin_client.h"
#include "google/cloud/spanner/instance_admin_client.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include <functional>
namespace spanner = google::cloud::spanner;
std::function<void()> drop_database = [] {};
int main(int argc, char* argv[]) try {
if (argc != 1) {
std::string const cmd = argv[0];
auto last_slash = std::string(argv[0]).find_last_of('/');
std::cerr << "Usage: " << cmd.substr(last_slash + 1) << "\n";
return 1;
}
auto project_id =
google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value_or("");
if (project_id.empty()) {
throw std::runtime_error(
"The GOOGLE_CLOUD_PROJECT environment variable should be set to a "
"non-empty value");
}
// This program is used to test the libraries after they are installed. We
// cannot use any of the functions in the testing support libraries as those
// do not get installed.
spanner::DatabaseAdminClient admin_client;
auto generator = google::cloud::internal::MakeDefaultPRNG();
auto instance_id = [&project_id, &generator] {
spanner::InstanceAdminClient instance_admin{
spanner::MakeInstanceAdminConnection()};
std::vector<std::string> names;
for (auto const& instance : instance_admin.ListInstances(project_id, {})) {
if (!instance) throw std::runtime_error("Error reading instance list");
auto full_name = instance->name();
names.push_back(full_name.substr(full_name.rfind('/') + 1));
}
if (names.empty()) throw std::runtime_error("No instances in the project");
return names[std::uniform_int_distribution<std::size_t>(
0, names.size() - 1)(generator)];
}();
auto database_id =
"db-" + google::cloud::internal::Sample(
generator, 20, "abcdefghijlkmnopqrstuvwxyz0123456789");
spanner::Database const database(project_id, instance_id, database_id);
std::cout << "Will run the test in database: " << database.FullName() << "\n";
using google::cloud::future;
using google::cloud::StatusOr;
std::cout << "Creating database [" << database_id << "] " << std::flush;
future<StatusOr<google::spanner::admin::database::v1::Database>>
created_database =
admin_client.CreateDatabase(database, {R"""(
CREATE TABLE Singers (
SingerId INT64 NOT NULL,
FirstName STRING(1024),
LastName STRING(1024),
SingerInfo BYTES(MAX)
) PRIMARY KEY (SingerId))""",
R"""(CREATE TABLE Albums (
SingerId INT64 NOT NULL,
AlbumId INT64 NOT NULL,
AlbumTitle STRING(MAX)
) PRIMARY KEY (SingerId, AlbumId),
INTERLEAVE IN PARENT Singers ON DELETE CASCADE)"""});
for (;;) {
auto status = created_database.wait_for(std::chrono::seconds(1));
if (status == std::future_status::ready) break;
std::cout << '.' << std::flush;
}
std::cout << " DONE\n";
auto db = created_database.get();
if (!db) throw std::runtime_error(db.status().message());
drop_database = [admin_client, database]() mutable {
auto drop = admin_client.DropDatabase(database);
if (!drop.ok()) throw std::runtime_error(drop.message());
std::cout << "Database dropped\n";
};
spanner::Client client(spanner::MakeConnection(database));
auto rows =
client.ExecuteQuery(spanner::SqlStatement("SELECT 'Hello World'"));
for (auto const& row : spanner::StreamOf<std::tuple<std::string>>(rows)) {
if (!row) throw std::runtime_error(row.status().message());
std::cout << std::get<0>(*row) << "\n";
}
drop_database();
return 0;
} catch (std::exception const& ex) {
std::cerr << "Standard exception raised: " << ex.what() << "\n";
drop_database();
return 1;
}
<commit_msg>bug: skip non-testing instances in install test (googleapis/google-cloud-cpp-spanner#991)<commit_after>// Copyright 2019 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 "google/cloud/spanner/client.h"
#include "google/cloud/spanner/database.h"
#include "google/cloud/spanner/database_admin_client.h"
#include "google/cloud/spanner/instance_admin_client.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/internal/random.h"
#include <functional>
namespace spanner = google::cloud::spanner;
std::function<void()> drop_database = [] {};
int main(int argc, char* argv[]) try {
if (argc != 1) {
std::string const cmd = argv[0];
auto last_slash = std::string(argv[0]).find_last_of('/');
std::cerr << "Usage: " << cmd.substr(last_slash + 1) << "\n";
return 1;
}
auto project_id =
google::cloud::internal::GetEnv("GOOGLE_CLOUD_PROJECT").value_or("");
if (project_id.empty()) {
throw std::runtime_error(
"The GOOGLE_CLOUD_PROJECT environment variable should be set to a "
"non-empty value");
}
// This program is used to test the libraries after they are installed. We
// cannot use any of the functions in the testing support libraries as those
// do not get installed.
spanner::DatabaseAdminClient admin_client;
auto generator = google::cloud::internal::MakeDefaultPRNG();
auto instance_id = [&project_id, &generator] {
spanner::InstanceAdminClient instance_admin{
spanner::MakeInstanceAdminConnection()};
std::vector<std::string> names;
// All the test instances in the projects used for integration tests start
// with this prefix. The projects sometimes have other (often transient)
// instances that we should not use.
std::string const testing_prefix = "test-instance-";
std::string const substr = "/instances/" + testing_prefix;
for (auto const& instance : instance_admin.ListInstances(project_id, {})) {
if (!instance) throw std::runtime_error("Error reading instance list");
auto full_name = instance->name();
// Skip non-testing instances.
if (full_name.find(substr) == std::string::npos) continue;
names.push_back(full_name.substr(full_name.rfind('/') + 1));
}
if (names.empty()) throw std::runtime_error("No instances in the project");
return names[std::uniform_int_distribution<std::size_t>(
0, names.size() - 1)(generator)];
}();
auto database_id =
"db-" + google::cloud::internal::Sample(
generator, 20, "abcdefghijlkmnopqrstuvwxyz0123456789");
spanner::Database const database(project_id, instance_id, database_id);
std::cout << "Will run the test in database: " << database.FullName() << "\n";
using google::cloud::future;
using google::cloud::StatusOr;
std::cout << "Creating database [" << database_id << "] " << std::flush;
future<StatusOr<google::spanner::admin::database::v1::Database>>
created_database =
admin_client.CreateDatabase(database, {R"""(
CREATE TABLE Singers (
SingerId INT64 NOT NULL,
FirstName STRING(1024),
LastName STRING(1024),
SingerInfo BYTES(MAX)
) PRIMARY KEY (SingerId))""",
R"""(CREATE TABLE Albums (
SingerId INT64 NOT NULL,
AlbumId INT64 NOT NULL,
AlbumTitle STRING(MAX)
) PRIMARY KEY (SingerId, AlbumId),
INTERLEAVE IN PARENT Singers ON DELETE CASCADE)"""});
for (;;) {
auto status = created_database.wait_for(std::chrono::seconds(1));
if (status == std::future_status::ready) break;
std::cout << '.' << std::flush;
}
std::cout << " DONE\n";
auto db = created_database.get();
if (!db) throw std::runtime_error(db.status().message());
drop_database = [admin_client, database]() mutable {
auto drop = admin_client.DropDatabase(database);
if (!drop.ok()) throw std::runtime_error(drop.message());
std::cout << "Database dropped\n";
};
spanner::Client client(spanner::MakeConnection(database));
auto rows =
client.ExecuteQuery(spanner::SqlStatement("SELECT 'Hello World'"));
for (auto const& row : spanner::StreamOf<std::tuple<std::string>>(rows)) {
if (!row) throw std::runtime_error(row.status().message());
std::cout << std::get<0>(*row) << "\n";
}
drop_database();
return 0;
} catch (std::exception const& ex) {
std::cerr << "Standard exception raised: " << ex.what() << "\n";
drop_database();
return 1;
}
<|endoftext|> |
<commit_before>/*
* ZoteroCollectionsLocal.cpp
*
* Copyright (C) 2009-20 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "ZoteroCollectionsLocal.hpp"
#include <boost/bind.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>
#include <core/system/Process.hpp>
#include <r/RExec.hpp>
#include <session/prefs/UserState.hpp>
#include <session/SessionModuleContext.hpp>
#include "session-config.h"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace zotero {
namespace collections {
namespace {
SEXP createCacheSpecSEXP( ZoteroCollectionSpec cacheSpec, r::sexp::Protect* pProtect)
{
std::vector<std::string> names;
names.push_back(kName);
names.push_back(kVersion);
SEXP cacheSpecSEXP = r::sexp::createList(names, pProtect);
r::sexp::setNamedListElement(cacheSpecSEXP, kName, cacheSpec.name);
r::sexp::setNamedListElement(cacheSpecSEXP, kVersion, cacheSpec.version);
return cacheSpecSEXP;
}
void getLocalLibrary(std::string key,
ZoteroCollectionSpec cacheSpec,
ZoteroCollectionsHandler handler)
{
r::sexp::Protect protect;
std::string libraryJsonStr;
Error error = r::exec::RFunction(".rs.zoteroGetLibrary", key,
createCacheSpecSEXP(cacheSpec, &protect)).call(&libraryJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
json::Object libraryJson;
error = libraryJson.parse(libraryJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
ZoteroCollection collection;
collection.name = libraryJson[kName].getString();
collection.version = libraryJson[kVersion].getInt();
collection.items = libraryJson[kItems].getArray();
handler(Success(), std::vector<ZoteroCollection>{ collection });
}
}
}
void getLocalCollections(std::string key,
std::vector<std::string> collections,
ZoteroCollectionSpecs cacheSpecs,
ZoteroCollectionsHandler handler)
{
json::Array cacheSpecsJson;
std::transform(cacheSpecs.begin(), cacheSpecs.end(), std::back_inserter(cacheSpecsJson), [](ZoteroCollectionSpec spec) {
json::Object specJson;
specJson[kName] = spec.name;
specJson[kVersion] = spec.version;
return specJson;
});
r::sexp::Protect protect;
std::string collectionJsonStr;
Error error = r::exec::RFunction(".rs.zoteroGetCollections", key, collections, cacheSpecsJson)
.call(&collectionJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
json::Array collectionsJson;
error = collectionsJson.parse(collectionJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
ZoteroCollections collections;
std::transform(collectionsJson.begin(), collectionsJson.end(), std::back_inserter(collections), [](json::Value json) {
ZoteroCollection collection;
json::Object collectionJson = json.getObject();
collection.name = collectionJson[kName].getString();
collection.version = collectionJson[kVersion].getInt();
collection.items = collectionJson[kItems].getArray();
return collection;
});
handler(Success(), collections);
}
}
}
} // end anonymous namespace
bool localZoteroAvailable()
{
// availability based on server vs. desktop
#ifdef RSTUDIO_SERVER
bool local = false;
#else
bool local = true;
#endif
// however, also make it available in debug mode for local dev/test
#ifndef NDEBUG
local = true;
#endif
return local;
}
// Returns the zoteroDataDirectory (if any). This will return a valid FilePath
// if the user has specified a zotero data dir in the preferences; OR if
// a zotero data dir was detected on the system. In the former case the
// path may not exist (and this should be logged as an error)
FilePath zoteroDataDirectory()
{
std::string dataDir = prefs::userState().zoteroDataDir();
if (!dataDir.empty())
return module_context::resolveAliasedPath(dataDir);
else
return detectedZoteroDataDirectory();
}
// Automatically detect the Zotero data directory and return it if it exists
FilePath detectedZoteroDataDirectory()
{
if (localZoteroAvailable())
{
std::string homeEnv;
#ifdef _WIN32
homeEnv = "USERPROFILE";
#else
homeEnv = "HOME";
#endif
FilePath homeDir = FilePath(string_utils::systemToUtf8(core::system::getenv(homeEnv)));
FilePath zoteroPath = homeDir.completeChildPath("Zotero");
if (zoteroPath.exists())
return zoteroPath;
else
return FilePath();
}
else
{
return FilePath();
}
}
ZoteroCollectionSource localCollections()
{
ZoteroCollectionSource source;
source.getLibrary = getLocalLibrary;
source.getCollections = getLocalCollections;
return source;
}
} // end namespace collections
} // end namespace zotero
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>detect zotero data dir based on user prefs (w/ default location as fallback)<commit_after>/*
* ZoteroCollectionsLocal.cpp
*
* Copyright (C) 2009-20 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "ZoteroCollectionsLocal.hpp"
#include <boost/bind.hpp>
#include <boost/algorithm/algorithm.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <shared_core/Error.hpp>
#include <shared_core/json/Json.hpp>
#include <core/FileSerializer.hpp>
#include <core/system/Process.hpp>
#include <r/RExec.hpp>
#include <session/prefs/UserState.hpp>
#include <session/SessionModuleContext.hpp>
#include "session-config.h"
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace zotero {
namespace collections {
namespace {
SEXP createCacheSpecSEXP( ZoteroCollectionSpec cacheSpec, r::sexp::Protect* pProtect)
{
std::vector<std::string> names;
names.push_back(kName);
names.push_back(kVersion);
SEXP cacheSpecSEXP = r::sexp::createList(names, pProtect);
r::sexp::setNamedListElement(cacheSpecSEXP, kName, cacheSpec.name);
r::sexp::setNamedListElement(cacheSpecSEXP, kVersion, cacheSpec.version);
return cacheSpecSEXP;
}
void getLocalLibrary(std::string key,
ZoteroCollectionSpec cacheSpec,
ZoteroCollectionsHandler handler)
{
r::sexp::Protect protect;
std::string libraryJsonStr;
Error error = r::exec::RFunction(".rs.zoteroGetLibrary", key,
createCacheSpecSEXP(cacheSpec, &protect)).call(&libraryJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
json::Object libraryJson;
error = libraryJson.parse(libraryJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
ZoteroCollection collection;
collection.name = libraryJson[kName].getString();
collection.version = libraryJson[kVersion].getInt();
collection.items = libraryJson[kItems].getArray();
handler(Success(), std::vector<ZoteroCollection>{ collection });
}
}
}
void getLocalCollections(std::string key,
std::vector<std::string> collections,
ZoteroCollectionSpecs cacheSpecs,
ZoteroCollectionsHandler handler)
{
json::Array cacheSpecsJson;
std::transform(cacheSpecs.begin(), cacheSpecs.end(), std::back_inserter(cacheSpecsJson), [](ZoteroCollectionSpec spec) {
json::Object specJson;
specJson[kName] = spec.name;
specJson[kVersion] = spec.version;
return specJson;
});
r::sexp::Protect protect;
std::string collectionJsonStr;
Error error = r::exec::RFunction(".rs.zoteroGetCollections", key, collections, cacheSpecsJson)
.call(&collectionJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
json::Array collectionsJson;
error = collectionsJson.parse(collectionJsonStr);
if (error)
{
handler(error, std::vector<ZoteroCollection>());
}
else
{
ZoteroCollections collections;
std::transform(collectionsJson.begin(), collectionsJson.end(), std::back_inserter(collections), [](json::Value json) {
ZoteroCollection collection;
json::Object collectionJson = json.getObject();
collection.name = collectionJson[kName].getString();
collection.version = collectionJson[kVersion].getInt();
collection.items = collectionJson[kItems].getArray();
return collection;
});
handler(Success(), collections);
}
}
}
FilePath userHomeDir()
{
std::string homeEnv;
#ifdef _WIN32
homeEnv = "USERPROFILE";
#else
homeEnv = "HOME";
#endif
return FilePath(string_utils::systemToUtf8(core::system::getenv(homeEnv)));
}
// https://www.zotero.org/support/kb/profile_directory
FilePath zoteroProfilesDir()
{
FilePath homeDir = userHomeDir();
std::string profilesDir;
#if defined(_WIN32)
profilesDir = "AppData\\Roaming\\Zotero\\Zotero\\Profiles";
#elif defined(__APPLE__)
profilesDir = "Library/Application Support/Zotero/Profiles";
#else
profilesDir = ".zotero/zotero";
#endif
return homeDir.completeChildPath(profilesDir);
}
// https://www.zotero.org/support/zotero_data
FilePath defaultZoteroDataDir()
{
FilePath homeDir = userHomeDir();
return homeDir.completeChildPath("Zotero");
}
FilePath detectZoteroDataDir()
{
// we'll fall back to the default if we can't find another dir in the profile
FilePath dataDir = defaultZoteroDataDir();
// find the zotero profiles dir
FilePath profilesDir = zoteroProfilesDir();
if (profilesDir.exists())
{
// there will be one path in the directory
std::vector<FilePath> children;
Error error = profilesDir.getChildren(children);
if (error)
LOG_ERROR(error);
if (children.size() > 0)
{
// there will be a single directory inside the profiles dir
FilePath profileDir = children[0];
FilePath prefsFile = profileDir.completeChildPath("prefs.js");
if (prefsFile.exists())
{
// read the prefs.js file
std::string prefs;
error = core::readStringFromFile(prefsFile, &prefs);
if (error)
LOG_ERROR(error);
// look for the zotero.dataDir pref
boost::smatch match;
boost::regex regex("user_pref\\(\"extensions.zotero.dataDir\",\\s*\"([^\"]+)\"\\);");
if (boost::regex_search(prefs, match, regex))
{
// set dataDiroly if the path exists
FilePath profileDataDir(match[1]);
if (profileDataDir.exists())
dataDir = profileDataDir;
}
}
}
}
// return the data dir
return dataDir;
}
} // end anonymous namespace
bool localZoteroAvailable()
{
// availability based on server vs. desktop
#ifdef RSTUDIO_SERVER
bool local = false;
#else
bool local = true;
#endif
// however, also make it available in debug mode for local dev/test
#ifndef NDEBUG
local = true;
#endif
return local;
}
// Detect the Zotero data directory and return it if it exists
FilePath detectedZoteroDataDirectory()
{
if (localZoteroAvailable())
{
FilePath dataDir = detectZoteroDataDir();
if (dataDir.exists())
return dataDir;
else
return FilePath();
}
else
{
return FilePath();
}
}
// Returns the zoteroDataDirectory (if any). This will return a valid FilePath
// if the user has specified a zotero data dir in the preferences; OR if
// a zotero data dir was detected on the system. In the former case the
// path may not exist (and this should be logged as an error)
FilePath zoteroDataDirectory()
{
std::string dataDir = prefs::userState().zoteroDataDir();
if (!dataDir.empty())
return module_context::resolveAliasedPath(dataDir);
else
return detectedZoteroDataDirectory();
}
ZoteroCollectionSource localCollections()
{
ZoteroCollectionSource source;
source.getLibrary = getLocalLibrary;
source.getCollections = getLocalCollections;
return source;
}
} // end namespace collections
} // end namespace zotero
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_ALGORITHM_GEOMETRY_HPP
#define VIENNAGRID_ALGORITHM_GEOMETRY_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <limits>
#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/algorithm/cross_prod.hpp"
#include "viennagrid/algorithm/detail/numeric.hpp"
#include "viennagrid/algorithm/intersect.hpp"
/** @file viennagrid/algorithm/geometry.hpp
@brief Contains various functions for computing geometric quantities
*/
namespace viennagrid
{
template<typename ElementT, typename PointAccessorT>
typename PointAccessorT::value_type normal_vector( PointAccessorT const point_accessor, ElementT const & element )
{
typedef typename PointAccessorT::value_type point_type;
point_type const & p0 = point_accessor( viennagrid::vertices(element)[0] );
point_type const & p1 = point_accessor( viennagrid::vertices(element)[1] );
point_type const & p2 = point_accessor( viennagrid::vertices(element)[2] );
return viennagrid::cross_prod( p1-p0, p2-p0 );
}
template<typename ElementT>
typename viennagrid::result_of::point<ElementT>::type normal_vector( ElementT const & element )
{
return normal_vector( default_point_accessor(element), element );
}
//namespace geometry
//{
template<typename PointT>
typename viennagrid::result_of::coord<PointT>::type determinant( PointT const & p0, PointT const & p1, PointT const & p2 )
{
return p0[0]*p1[1]*p2[2] + p1[0]*p2[1]*p0[2] + p2[0]*p0[1]*p1[2] - p0[2]*p1[1]*p2[0] - p1[2]*p2[1]*p0[0] - p2[2]*p0[1]*p1[0];
}
template<typename PointIteratorT>
std::pair<
typename std::iterator_traits<PointIteratorT>::value_type,
typename std::iterator_traits<PointIteratorT>::value_type
> bounding_box( PointIteratorT it, PointIteratorT const & it_end )
{
typedef typename std::iterator_traits<PointIteratorT>::value_type PointType;
typedef typename viennagrid::result_of::coord<PointType>::type NumericType;
PointType lower_left;
PointType upper_right;
std::fill( lower_left.begin(), lower_left.end(), std::numeric_limits<NumericType>::max() );
std::fill( upper_right.begin(), upper_right.end(), - std::numeric_limits<NumericType>::max() );
//std::fill( upper_right.begin(), upper_right.end(), std::numeric_limits<NumericType>::lowest() ); C++11
for (; it != it_end; ++it )
{
lower_left = viennagrid::min( lower_left, *it );
upper_right = viennagrid::max( upper_right, *it );
}
return std::make_pair( lower_left, upper_right );
}
template<typename IteratorT>
IteratorT circular_next(IteratorT it, IteratorT const & start_it, IteratorT const & end_it)
{
if (++it == end_it)
return start_it;
else
return it;
}
template<typename IteratorT>
IteratorT circular_prev(IteratorT it, IteratorT const & start_it, IteratorT const & end_it)
{
if (it == start_it)
it = end_it;
return --it;
}
// template<typename point_iterator_type, typename polygon_tag_type, typename point, typename numeric_config>
// bool is_inside( point_iterator_type const & it_start, point_iterator_type it_end, polygon_tag_type polygon_tag,
// point const & point_to_test,
// numeric_config nc)
// {
// typedef typename std::iterator_traits<point_iterator_type>::value_type PolygonPointType;
// std::pair<PolygonPointType, PolygonPointType> poly_bounding_box = bounding_box(it_start, it_end);
//
// PolygonPointType outer_point;
// outer_point[0] = point_to_test[0];
// outer_point[1] = poly_bounding_box.first[1] - 1;
// bool is_inside = false;
//
// point_iterator_type it_prev = it_end; --it_prev;
// point_iterator_type it_cur = it_start;
//
// for ( ;it_cur != it_end ; ++it_cur, it_prev = circular_next(it_prev, it_start, it_end) )
// {
// PolygonPointType const & q0 = *it_prev;
// PolygonPointType const & q1 = *it_cur;
//
// // is inner point on polygon line?
// if ( point_line_intersect( point_to_test, q0, q1, interval::closed_open_tag(), nc ) )
// return !is_open(polygon_tag);
//
//
// // is current line on test line?
// if ( !detail::is_equal(nc, q0[0], point_to_test[0]) || !detail::is_equal(nc, q1[0], point_to_test[0]) )
// {
// if ( line_line_intersect( q0, q1, interval::open_open_tag(), point_to_test, outer_point, interval::open_open_tag(), nc ) )
// {
// is_inside = !is_inside;
// }
// }
// }
//
//
// // find point which is not on the testing line
// point_iterator_type it = it_start;
// while ( point_line_intersect( *it, point_to_test, outer_point, interval::open_open_tag(), nc ) )
// {
// it = circular_prev(it, it_start, it_end);
// if (it == it_start)
// break;
// }
//
// // no point found -> no intersection
// if ( point_line_intersect( *it, point_to_test, outer_point, interval::open_open_tag(), nc ) )
// return false;
//
//
// point_iterator_type circular_start_it = it;
// it_prev = it;
// it = circular_next(it, it_start, it_end);
//
// // iterating over all points
// while (it != circular_start_it)
// {
// // is point on testing line?
// if ( point_line_intersect( *it, point_to_test, outer_point, interval::open_open_tag(), nc ) )
// {
// // find next point which is not on testing line
// point_iterator_type it_next = circular_next(it, it_start, it_end);
// while ( point_line_intersect( *it_next, point_to_test, outer_point, interval::open_open_tag(), nc ) )
// it_next = circular_next(it_next, it_start, it_end);
//
// // check if the the lines/points are an ear
// if ( ((*it_prev)[0] - (*it)[0]) * ((*it_next)[0] - (*it)[0]) < 0 )
// {
// is_inside = !is_inside;
// }
//
// it_prev = it;
// it = it_next;
// }
// else
// {
// it_prev = it;
// it = circular_next(it, it_start, it_end);
// }
// }
//
// return is_inside;
// }
template<typename IteratorT, typename VectorT>
VectorT orthogonalize_one_vector( IteratorT it, const IteratorT & end, VectorT vec )
{
for (; it != end; ++it)
vec -= viennagrid::inner_prod( vec, *it ) / viennagrid::inner_prod( *it, *it ) * (*it);
return vec;
}
template<typename IteratorT, typename NumericConfigT>
bool orthogonalize( IteratorT start, IteratorT end, NumericConfigT nc )
{
typedef typename std::iterator_traits<IteratorT>::value_type vector_type;
typedef typename viennagrid::result_of::coord<vector_type>::type coord_type;
for (IteratorT n = start; n != end; ++n)
{
*n = orthogonalize_one_vector(start, n, *n);
if ( viennagrid::norm_1(*n) < detail::absolute_tolerance<coord_type>(nc) )
return false;
}
return true;
}
template<typename PointIteratorT, typename NumericConfigT, typename OutPointT, typename OutPointIteratorT>
bool projection_matrix(const PointIteratorT & start, const PointIteratorT & end, NumericConfigT nc,
OutPointT & center, OutPointIteratorT projection_matrix_start)
{
typedef typename std::iterator_traits<PointIteratorT>::value_type point_type;
typedef typename viennagrid::result_of::coord<point_type>::type coord_type;
typedef typename detail::result_of::numeric_type<NumericConfigT, coord_type>::type numeric_type;
OutPointIteratorT projection_matrix_end = projection_matrix_start;
++projection_matrix_end; ++projection_matrix_end;
std::fill( projection_matrix_start, projection_matrix_end, point_type() );
if (start == end) return false; // too few points
PointIteratorT pit;
// calculating the center
pit = start;
unsigned int num_points = 1;
center = *pit; ++pit;
for (; pit != end; ++pit)
{
center += *pit;
++num_points;
}
if (num_points < 3) return false; // too few points
center /= num_points;
// setting up a map of vectors from the center to all points, sorted descending by the length of that vector
typedef std::multimap<numeric_type, point_type, std::greater<numeric_type> > vector_map_type;
vector_map_type sorted_vectors;
pit = start;
for (; pit != end; ++pit)
{
point_type vector = center - *pit;
typename vector_map_type::iterator it = sorted_vectors.insert( std::make_pair( viennagrid::norm_2( vector ), vector ) );
it->second /= it->first; // normalizing the vector
}
// finding 2 non-liner dependent vectors
unsigned int projection_matrix_index = 0;
typename vector_map_type::iterator it = sorted_vectors.begin();
while (projection_matrix_index < 2)
{
if ( it->first < detail::absolute_tolerance<coord_type>(nc) )
return false; // points are too close together
// check linear dependency with other vectors in projection matrix
unsigned int index = 0;
OutPointIteratorT pmit = projection_matrix_start;
for (; index < projection_matrix_index; ++index, ++pmit)
{
numeric_type angle_cos = viennagrid::inner_prod( it->second, *pmit );
if ( std::abs(angle_cos) > 1 - detail::absolute_tolerance<coord_type>(nc))
break;
}
if ( index == projection_matrix_index)
{
*pmit = it->second;
++projection_matrix_index;
}
++it;
}
// orthogonalize vectors
orthogonalize( projection_matrix_start, projection_matrix_end, nc );
// normalize vectors
for (OutPointIteratorT it = projection_matrix_start; it != projection_matrix_end; ++it)
*it /= viennagrid::norm_2(*it);
return true;
}
template<typename PointIteratorT, typename OutPointIteratorT, typename point_type, typename ProjectionPointIteratorT>
void project(PointIteratorT in, const PointIteratorT & in_end,
OutPointIteratorT out,
point_type center,
ProjectionPointIteratorT const & proj_start, ProjectionPointIteratorT const & proj_end)
{
for ( ; in != in_end; ++in, ++out)
{
point_type tmp = *in - center;
size_t index = 0;
for (ProjectionPointIteratorT it = proj_start; it != proj_end; ++it, ++index)
(*out)[index] = viennagrid::inner_prod( tmp, *it );
}
}
template<typename PointIteratorT, typename OutPointIteratorT, typename NumericConfigT>
bool project_onto_2dplane(PointIteratorT in, const PointIteratorT & in_end,
OutPointIteratorT out,
NumericConfigT nc)
{
typedef typename std::iterator_traits<PointIteratorT>::value_type InPointType;
size_t dimension = (*in).size();
std::vector<InPointType> projection_matrix(dimension);
InPointType center;
if (!projection_matrix(in, in_end, projection_matrix.begin(), center, nc))
return false;
project(in, in_end, out, center, projection_matrix.begin(), projection_matrix.begin() + 2);
}
//} // namespace geometry
}
#endif
<commit_msg>added determinant for 2 points<commit_after>#ifndef VIENNAGRID_ALGORITHM_GEOMETRY_HPP
#define VIENNAGRID_ALGORITHM_GEOMETRY_HPP
/* =======================================================================
Copyright (c) 2011-2013, Institute for Microelectronics,
Institute for Analysis and Scientific Computing,
TU Wien.
-----------------
ViennaGrid - The Vienna Grid Library
-----------------
License: MIT (X11), see file LICENSE in the base directory
======================================================================= */
#include <limits>
#include "viennagrid/mesh/mesh.hpp"
#include "viennagrid/algorithm/cross_prod.hpp"
#include "viennagrid/algorithm/detail/numeric.hpp"
#include "viennagrid/algorithm/intersect.hpp"
/** @file viennagrid/algorithm/geometry.hpp
@brief Contains various functions for computing geometric quantities
*/
namespace viennagrid
{
template<typename ElementT, typename PointAccessorT>
typename PointAccessorT::value_type normal_vector( PointAccessorT const point_accessor, ElementT const & element )
{
typedef typename PointAccessorT::value_type point_type;
point_type const & p0 = point_accessor( viennagrid::vertices(element)[0] );
point_type const & p1 = point_accessor( viennagrid::vertices(element)[1] );
point_type const & p2 = point_accessor( viennagrid::vertices(element)[2] );
return viennagrid::cross_prod( p1-p0, p2-p0 );
}
template<typename ElementT>
typename viennagrid::result_of::point<ElementT>::type normal_vector( ElementT const & element )
{
return normal_vector( default_point_accessor(element), element );
}
//namespace geometry
//{
template<typename PointT>
typename viennagrid::result_of::coord<PointT>::type determinant( PointT const & p0, PointT const & p1 )
{
return p0[0]*p1[1] - p0[1]*p1[0];
}
template<typename PointT>
typename viennagrid::result_of::coord<PointT>::type determinant( PointT const & p0, PointT const & p1, PointT const & p2 )
{
return p0[0]*p1[1]*p2[2] + p1[0]*p2[1]*p0[2] + p2[0]*p0[1]*p1[2] - p0[2]*p1[1]*p2[0] - p1[2]*p2[1]*p0[0] - p2[2]*p0[1]*p1[0];
}
template<typename PointIteratorT>
std::pair<
typename std::iterator_traits<PointIteratorT>::value_type,
typename std::iterator_traits<PointIteratorT>::value_type
> bounding_box( PointIteratorT it, PointIteratorT const & it_end )
{
typedef typename std::iterator_traits<PointIteratorT>::value_type PointType;
typedef typename viennagrid::result_of::coord<PointType>::type NumericType;
PointType lower_left;
PointType upper_right;
std::fill( lower_left.begin(), lower_left.end(), std::numeric_limits<NumericType>::max() );
std::fill( upper_right.begin(), upper_right.end(), - std::numeric_limits<NumericType>::max() );
//std::fill( upper_right.begin(), upper_right.end(), std::numeric_limits<NumericType>::lowest() ); C++11
for (; it != it_end; ++it )
{
lower_left = viennagrid::min( lower_left, *it );
upper_right = viennagrid::max( upper_right, *it );
}
return std::make_pair( lower_left, upper_right );
}
template<typename IteratorT>
IteratorT circular_next(IteratorT it, IteratorT const & start_it, IteratorT const & end_it)
{
if (++it == end_it)
return start_it;
else
return it;
}
template<typename IteratorT>
IteratorT circular_prev(IteratorT it, IteratorT const & start_it, IteratorT const & end_it)
{
if (it == start_it)
it = end_it;
return --it;
}
// template<typename point_iterator_type, typename polygon_tag_type, typename point, typename numeric_config>
// bool is_inside( point_iterator_type const & it_start, point_iterator_type it_end, polygon_tag_type polygon_tag,
// point const & point_to_test,
// numeric_config nc)
// {
// typedef typename std::iterator_traits<point_iterator_type>::value_type PolygonPointType;
// std::pair<PolygonPointType, PolygonPointType> poly_bounding_box = bounding_box(it_start, it_end);
//
// PolygonPointType outer_point;
// outer_point[0] = point_to_test[0];
// outer_point[1] = poly_bounding_box.first[1] - 1;
// bool is_inside = false;
//
// point_iterator_type it_prev = it_end; --it_prev;
// point_iterator_type it_cur = it_start;
//
// for ( ;it_cur != it_end ; ++it_cur, it_prev = circular_next(it_prev, it_start, it_end) )
// {
// PolygonPointType const & q0 = *it_prev;
// PolygonPointType const & q1 = *it_cur;
//
// // is inner point on polygon line?
// if ( point_line_intersect( point_to_test, q0, q1, interval::closed_open_tag(), nc ) )
// return !is_open(polygon_tag);
//
//
// // is current line on test line?
// if ( !detail::is_equal(nc, q0[0], point_to_test[0]) || !detail::is_equal(nc, q1[0], point_to_test[0]) )
// {
// if ( line_line_intersect( q0, q1, interval::open_open_tag(), point_to_test, outer_point, interval::open_open_tag(), nc ) )
// {
// is_inside = !is_inside;
// }
// }
// }
//
//
// // find point which is not on the testing line
// point_iterator_type it = it_start;
// while ( point_line_intersect( *it, point_to_test, outer_point, interval::open_open_tag(), nc ) )
// {
// it = circular_prev(it, it_start, it_end);
// if (it == it_start)
// break;
// }
//
// // no point found -> no intersection
// if ( point_line_intersect( *it, point_to_test, outer_point, interval::open_open_tag(), nc ) )
// return false;
//
//
// point_iterator_type circular_start_it = it;
// it_prev = it;
// it = circular_next(it, it_start, it_end);
//
// // iterating over all points
// while (it != circular_start_it)
// {
// // is point on testing line?
// if ( point_line_intersect( *it, point_to_test, outer_point, interval::open_open_tag(), nc ) )
// {
// // find next point which is not on testing line
// point_iterator_type it_next = circular_next(it, it_start, it_end);
// while ( point_line_intersect( *it_next, point_to_test, outer_point, interval::open_open_tag(), nc ) )
// it_next = circular_next(it_next, it_start, it_end);
//
// // check if the the lines/points are an ear
// if ( ((*it_prev)[0] - (*it)[0]) * ((*it_next)[0] - (*it)[0]) < 0 )
// {
// is_inside = !is_inside;
// }
//
// it_prev = it;
// it = it_next;
// }
// else
// {
// it_prev = it;
// it = circular_next(it, it_start, it_end);
// }
// }
//
// return is_inside;
// }
template<typename IteratorT, typename VectorT>
VectorT orthogonalize_one_vector( IteratorT it, const IteratorT & end, VectorT vec )
{
for (; it != end; ++it)
vec -= viennagrid::inner_prod( vec, *it ) / viennagrid::inner_prod( *it, *it ) * (*it);
return vec;
}
template<typename IteratorT, typename NumericConfigT>
bool orthogonalize( IteratorT start, IteratorT end, NumericConfigT nc )
{
typedef typename std::iterator_traits<IteratorT>::value_type vector_type;
typedef typename viennagrid::result_of::coord<vector_type>::type coord_type;
for (IteratorT n = start; n != end; ++n)
{
*n = orthogonalize_one_vector(start, n, *n);
if ( viennagrid::norm_1(*n) < detail::absolute_tolerance<coord_type>(nc) )
return false;
}
return true;
}
template<typename PointIteratorT, typename NumericConfigT, typename OutPointT, typename OutPointIteratorT>
bool projection_matrix(const PointIteratorT & start, const PointIteratorT & end, NumericConfigT nc,
OutPointT & center, OutPointIteratorT projection_matrix_start)
{
typedef typename std::iterator_traits<PointIteratorT>::value_type point_type;
typedef typename viennagrid::result_of::coord<point_type>::type coord_type;
typedef typename detail::result_of::numeric_type<NumericConfigT, coord_type>::type numeric_type;
OutPointIteratorT projection_matrix_end = projection_matrix_start;
++projection_matrix_end; ++projection_matrix_end;
std::fill( projection_matrix_start, projection_matrix_end, point_type() );
if (start == end) return false; // too few points
PointIteratorT pit;
// calculating the center
pit = start;
unsigned int num_points = 1;
center = *pit; ++pit;
for (; pit != end; ++pit)
{
center += *pit;
++num_points;
}
if (num_points < 3) return false; // too few points
center /= num_points;
// setting up a map of vectors from the center to all points, sorted descending by the length of that vector
typedef std::multimap<numeric_type, point_type, std::greater<numeric_type> > vector_map_type;
vector_map_type sorted_vectors;
pit = start;
for (; pit != end; ++pit)
{
point_type vector = center - *pit;
typename vector_map_type::iterator it = sorted_vectors.insert( std::make_pair( viennagrid::norm_2( vector ), vector ) );
it->second /= it->first; // normalizing the vector
}
// finding 2 non-liner dependent vectors
unsigned int projection_matrix_index = 0;
typename vector_map_type::iterator it = sorted_vectors.begin();
while (projection_matrix_index < 2)
{
if ( it->first < detail::absolute_tolerance<coord_type>(nc) )
return false; // points are too close together
// check linear dependency with other vectors in projection matrix
unsigned int index = 0;
OutPointIteratorT pmit = projection_matrix_start;
for (; index < projection_matrix_index; ++index, ++pmit)
{
numeric_type angle_cos = viennagrid::inner_prod( it->second, *pmit );
if ( std::abs(angle_cos) > 1 - detail::absolute_tolerance<coord_type>(nc))
break;
}
if ( index == projection_matrix_index)
{
*pmit = it->second;
++projection_matrix_index;
}
++it;
}
// orthogonalize vectors
orthogonalize( projection_matrix_start, projection_matrix_end, nc );
// normalize vectors
for (OutPointIteratorT it = projection_matrix_start; it != projection_matrix_end; ++it)
*it /= viennagrid::norm_2(*it);
return true;
}
template<typename PointIteratorT, typename OutPointIteratorT, typename point_type, typename ProjectionPointIteratorT>
void project(PointIteratorT in, const PointIteratorT & in_end,
OutPointIteratorT out,
point_type center,
ProjectionPointIteratorT const & proj_start, ProjectionPointIteratorT const & proj_end)
{
for ( ; in != in_end; ++in, ++out)
{
point_type tmp = *in - center;
size_t index = 0;
for (ProjectionPointIteratorT it = proj_start; it != proj_end; ++it, ++index)
(*out)[index] = viennagrid::inner_prod( tmp, *it );
}
}
template<typename PointIteratorT, typename OutPointIteratorT, typename NumericConfigT>
bool project_onto_2dplane(PointIteratorT in, const PointIteratorT & in_end,
OutPointIteratorT out,
NumericConfigT nc)
{
typedef typename std::iterator_traits<PointIteratorT>::value_type InPointType;
size_t dimension = (*in).size();
std::vector<InPointType> projection_matrix(dimension);
InPointType center;
if (!projection_matrix(in, in_end, projection_matrix.begin(), center, nc))
return false;
project(in, in_end, out, center, projection_matrix.begin(), projection_matrix.begin() + 2);
}
//} // namespace geometry
}
#endif
<|endoftext|> |
<commit_before>/*
* 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 "SkFontMgr.h"
#include "SkFontStyle.h"
#include "SkFontConfigInterface.h"
#include "SkFontConfigTypeface.h"
#include "SkMath.h"
#include "SkString.h"
#include "SkTDArray.h"
// for now we pull these in directly. eventually we will solely rely on the
// SkFontConfigInterface instance.
#include <fontconfig/fontconfig.h>
#include <unistd.h>
// Defined in SkFontHost_FreeType.cpp
bool find_name_and_attributes(SkStream* stream, SkString* name,
SkTypeface::Style* style, bool* isFixedWidth);
// borrow this global from SkFontHost_fontconfig. eventually that file should
// go away, and be replaced with this one.
extern SkFontConfigInterface* SkFontHost_fontconfig_ref_global();
static SkFontConfigInterface* RefFCI() {
return SkFontHost_fontconfig_ref_global();
}
// look for the last substring after a '/' and return that, or return null.
static const char* find_just_name(const char* str) {
const char* last = strrchr(str, '/');
return last ? last + 1 : NULL;
}
static bool is_lower(char c) {
return c >= 'a' && c <= 'z';
}
static int get_int(FcPattern* pattern, const char field[]) {
int value;
if (FcPatternGetInteger(pattern, field, 0, &value) != FcResultMatch) {
value = SK_MinS32;
}
return value;
}
static const char* get_name(FcPattern* pattern, const char field[]) {
const char* name;
if (FcPatternGetString(pattern, field, 0, (FcChar8**)&name) != FcResultMatch) {
name = "";
}
return name;
}
static bool valid_pattern(FcPattern* pattern) {
FcBool is_scalable;
if (FcPatternGetBool(pattern, FC_SCALABLE, 0, &is_scalable) != FcResultMatch || !is_scalable) {
return false;
}
// fontconfig can also return fonts which are unreadable
const char* c_filename = get_name(pattern, FC_FILE);
if (0 == *c_filename) {
return false;
}
if (access(c_filename, R_OK) != 0) {
return false;
}
return true;
}
static bool match_name(FcPattern* pattern, const char family_name[]) {
return !strcasecmp(family_name, get_name(pattern, FC_FAMILY));
}
static FcPattern** MatchFont(FcFontSet* font_set,
const char post_config_family[],
int* count) {
// Older versions of fontconfig have a bug where they cannot select
// only scalable fonts so we have to manually filter the results.
FcPattern** iter = font_set->fonts;
FcPattern** stop = iter + font_set->nfont;
// find the first good match
for (; iter < stop; ++iter) {
if (valid_pattern(*iter)) {
break;
}
}
if (iter == stop || !match_name(*iter, post_config_family)) {
return NULL;
}
FcPattern** firstIter = iter++;
for (; iter < stop; ++iter) {
if (!valid_pattern(*iter) || !match_name(*iter, post_config_family)) {
break;
}
}
*count = iter - firstIter;
return firstIter;
}
class SkFontStyleSet_FC : public SkFontStyleSet {
public:
SkFontStyleSet_FC(FcPattern** matches, int count);
virtual ~SkFontStyleSet_FC();
virtual int count() SK_OVERRIDE { return fRecCount; }
virtual void getStyle(int index, SkFontStyle*, SkString* style) SK_OVERRIDE;
virtual SkTypeface* createTypeface(int index) SK_OVERRIDE;
virtual SkTypeface* matchStyle(const SkFontStyle& pattern) SK_OVERRIDE;
private:
struct Rec {
SkString fStyleName;
SkString fFileName;
SkFontStyle fStyle;
};
Rec* fRecs;
int fRecCount;
};
static int map_range(int value,
int old_min, int old_max, int new_min, int new_max) {
SkASSERT(old_min < old_max);
SkASSERT(new_min < new_max);
return new_min + SkMulDiv(value - old_min,
new_max - new_min, old_max - old_min);
}
static SkFontStyle make_fontconfig_style(FcPattern* match) {
int weight = get_int(match, FC_WEIGHT);
int width = get_int(match, FC_WIDTH);
int slant = get_int(match, FC_SLANT);
// SkDebugf("old weight %d new weight %d\n", weight, map_range(weight, 0, 80, 0, 400));
// fontconfig weight seems to be 0..200 or so, so we remap it here
weight = map_range(weight, 0, 80, 0, 400);
width = map_range(width, 0, 200, 0, 9);
return SkFontStyle(weight, width, slant > 0 ? SkFontStyle::kItalic_Slant
: SkFontStyle::kUpright_Slant);
}
SkFontStyleSet_FC::SkFontStyleSet_FC(FcPattern** matches, int count) {
fRecCount = count;
fRecs = SkNEW_ARRAY(Rec, count);
for (int i = 0; i < count; ++i) {
fRecs[i].fStyleName.set(get_name(matches[i], FC_STYLE));
fRecs[i].fFileName.set(get_name(matches[i], FC_FILE));
fRecs[i].fStyle = make_fontconfig_style(matches[i]);
}
}
SkFontStyleSet_FC::~SkFontStyleSet_FC() {
SkDELETE_ARRAY(fRecs);
}
void SkFontStyleSet_FC::getStyle(int index, SkFontStyle* style,
SkString* styleName) {
SkASSERT((unsigned)index < (unsigned)fRecCount);
if (style) {
*style = fRecs[index].fStyle;
}
if (styleName) {
*styleName = fRecs[index].fStyleName;
}
}
SkTypeface* SkFontStyleSet_FC::createTypeface(int index) {
return NULL;
}
SkTypeface* SkFontStyleSet_FC::matchStyle(const SkFontStyle& pattern) {
return NULL;
}
class SkFontMgr_fontconfig : public SkFontMgr {
SkAutoTUnref<SkFontConfigInterface> fFCI;
SkDataTable* fFamilyNames;
public:
SkFontMgr_fontconfig(SkFontConfigInterface* fci)
: fFCI(fci)
, fFamilyNames(fFCI->getFamilyNames()) {}
virtual ~SkFontMgr_fontconfig() {
SkSafeUnref(fFamilyNames);
}
protected:
virtual int onCountFamilies() const SK_OVERRIDE {
return fFamilyNames->count();
}
virtual void onGetFamilyName(int index, SkString* familyName) const SK_OVERRIDE {
familyName->set(fFamilyNames->atStr(index));
}
virtual SkFontStyleSet* onCreateStyleSet(int index) const SK_OVERRIDE {
return this->onMatchFamily(fFamilyNames->atStr(index));
}
virtual SkFontStyleSet* onMatchFamily(const char familyName[]) const SK_OVERRIDE {
FcPattern* pattern = FcPatternCreate();
FcPatternAddString(pattern, FC_FAMILY, (FcChar8*)familyName);
#if 0
FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
#endif
FcConfigSubstitute(NULL, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
const char* post_config_family = get_name(pattern, FC_FAMILY);
FcResult result;
FcFontSet* font_set = FcFontSort(0, pattern, 0, 0, &result);
if (!font_set) {
FcPatternDestroy(pattern);
return NULL;
}
int count;
FcPattern** match = MatchFont(font_set, post_config_family, &count);
if (!match) {
FcPatternDestroy(pattern);
FcFontSetDestroy(font_set);
return NULL;
}
FcPatternDestroy(pattern);
SkTDArray<FcPattern*> trimmedMatches;
for (int i = 0; i < count; ++i) {
const char* justName = find_just_name(get_name(match[i], FC_FILE));
if (!is_lower(*justName)) {
*trimmedMatches.append() = match[i];
}
}
SkFontStyleSet_FC* sset = SkNEW_ARGS(SkFontStyleSet_FC,
(trimmedMatches.begin(),
trimmedMatches.count()));
return sset;
}
virtual SkTypeface* onMatchFamilyStyle(const char familyName[],
const SkFontStyle&) const SK_OVERRIDE { return NULL; }
virtual SkTypeface* onMatchFaceStyle(const SkTypeface*,
const SkFontStyle&) const SK_OVERRIDE { return NULL; }
virtual SkTypeface* onCreateFromData(SkData*, int ttcIndex) const SK_OVERRIDE { return NULL; }
virtual SkTypeface* onCreateFromStream(SkStream* stream, int ttcIndex) const SK_OVERRIDE {
const size_t length = stream->getLength();
if (!length) {
return NULL;
}
if (length >= 1024 * 1024 * 1024) {
return NULL; // don't accept too large fonts (>= 1GB) for safety.
}
// TODO should the caller give us the style or should we get it from freetype?
SkTypeface::Style style = SkTypeface::kNormal;
bool isFixedWidth = false;
if (!find_name_and_attributes(stream, NULL, &style, &isFixedWidth)) {
return NULL;
}
SkTypeface* face = SkNEW_ARGS(FontConfigTypeface, (style, isFixedWidth, stream));
return face;
}
virtual SkTypeface* onCreateFromFile(const char path[], int ttcIndex) const SK_OVERRIDE {
SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path));
return stream.get() ? this->createFromStream(stream, ttcIndex) : NULL;
}
virtual SkTypeface* onLegacyCreateTypeface(const char familyName[],
unsigned styleBits) const SK_OVERRIDE {
return FontConfigTypeface::LegacyCreateTypeface(NULL, familyName,
(SkTypeface::Style)styleBits);
}
};
SkFontMgr* SkFontMgr::Factory() {
SkFontConfigInterface* fci = RefFCI();
return fci ? SkNEW_ARGS(SkFontMgr_fontconfig, (fci)) : NULL;
}
<commit_msg>Add global fontconfig lock.<commit_after>/*
* 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 "SkFontMgr.h"
#include "SkFontStyle.h"
#include "SkFontConfigInterface.h"
#include "SkFontConfigTypeface.h"
#include "SkMath.h"
#include "SkString.h"
#include "SkTDArray.h"
#include "SkThread.h"
// for now we pull these in directly. eventually we will solely rely on the
// SkFontConfigInterface instance.
#include <fontconfig/fontconfig.h>
#include <unistd.h>
namespace {
// Fontconfig is not threadsafe before 2.10.91. Before that, we lock with a global mutex.
// See skia:1497 for background.
SK_DECLARE_STATIC_MUTEX(gFCMutex);
static bool gFCSafeToUse;
struct FCLocker {
FCLocker() {
if (FcGetVersion() < 21091) { // We assume FcGetVersion() has always been thread safe.
gFCMutex.acquire();
fUnlock = true;
} else {
fUnlock = false;
}
gFCSafeToUse = true;
}
~FCLocker() {
gFCSafeToUse = false;
if (fUnlock) {
gFCMutex.release();
}
}
private:
bool fUnlock;
};
} // namespace
// Defined in SkFontHost_FreeType.cpp
bool find_name_and_attributes(SkStream* stream, SkString* name,
SkTypeface::Style* style, bool* isFixedWidth);
// borrow this global from SkFontHost_fontconfig. eventually that file should
// go away, and be replaced with this one.
extern SkFontConfigInterface* SkFontHost_fontconfig_ref_global();
static SkFontConfigInterface* RefFCI() {
return SkFontHost_fontconfig_ref_global();
}
// look for the last substring after a '/' and return that, or return null.
static const char* find_just_name(const char* str) {
const char* last = strrchr(str, '/');
return last ? last + 1 : NULL;
}
static bool is_lower(char c) {
return c >= 'a' && c <= 'z';
}
static int get_int(FcPattern* pattern, const char field[]) {
SkASSERT(gFCSafeToUse);
int value;
if (FcPatternGetInteger(pattern, field, 0, &value) != FcResultMatch) {
value = SK_MinS32;
}
return value;
}
static const char* get_name(FcPattern* pattern, const char field[]) {
SkASSERT(gFCSafeToUse);
const char* name;
if (FcPatternGetString(pattern, field, 0, (FcChar8**)&name) != FcResultMatch) {
name = "";
}
return name;
}
static bool valid_pattern(FcPattern* pattern) {
SkASSERT(gFCSafeToUse);
FcBool is_scalable;
if (FcPatternGetBool(pattern, FC_SCALABLE, 0, &is_scalable) != FcResultMatch || !is_scalable) {
return false;
}
// fontconfig can also return fonts which are unreadable
const char* c_filename = get_name(pattern, FC_FILE);
if (0 == *c_filename) {
return false;
}
if (access(c_filename, R_OK) != 0) {
return false;
}
return true;
}
static bool match_name(FcPattern* pattern, const char family_name[]) {
return !strcasecmp(family_name, get_name(pattern, FC_FAMILY));
}
static FcPattern** MatchFont(FcFontSet* font_set,
const char post_config_family[],
int* count) {
// Older versions of fontconfig have a bug where they cannot select
// only scalable fonts so we have to manually filter the results.
FcPattern** iter = font_set->fonts;
FcPattern** stop = iter + font_set->nfont;
// find the first good match
for (; iter < stop; ++iter) {
if (valid_pattern(*iter)) {
break;
}
}
if (iter == stop || !match_name(*iter, post_config_family)) {
return NULL;
}
FcPattern** firstIter = iter++;
for (; iter < stop; ++iter) {
if (!valid_pattern(*iter) || !match_name(*iter, post_config_family)) {
break;
}
}
*count = iter - firstIter;
return firstIter;
}
class SkFontStyleSet_FC : public SkFontStyleSet {
public:
SkFontStyleSet_FC(FcPattern** matches, int count);
virtual ~SkFontStyleSet_FC();
virtual int count() SK_OVERRIDE { return fRecCount; }
virtual void getStyle(int index, SkFontStyle*, SkString* style) SK_OVERRIDE;
virtual SkTypeface* createTypeface(int index) SK_OVERRIDE;
virtual SkTypeface* matchStyle(const SkFontStyle& pattern) SK_OVERRIDE;
private:
struct Rec {
SkString fStyleName;
SkString fFileName;
SkFontStyle fStyle;
};
Rec* fRecs;
int fRecCount;
};
static int map_range(int value,
int old_min, int old_max, int new_min, int new_max) {
SkASSERT(old_min < old_max);
SkASSERT(new_min < new_max);
return new_min + SkMulDiv(value - old_min,
new_max - new_min, old_max - old_min);
}
static SkFontStyle make_fontconfig_style(FcPattern* match) {
int weight = get_int(match, FC_WEIGHT);
int width = get_int(match, FC_WIDTH);
int slant = get_int(match, FC_SLANT);
// SkDebugf("old weight %d new weight %d\n", weight, map_range(weight, 0, 80, 0, 400));
// fontconfig weight seems to be 0..200 or so, so we remap it here
weight = map_range(weight, 0, 80, 0, 400);
width = map_range(width, 0, 200, 0, 9);
return SkFontStyle(weight, width, slant > 0 ? SkFontStyle::kItalic_Slant
: SkFontStyle::kUpright_Slant);
}
SkFontStyleSet_FC::SkFontStyleSet_FC(FcPattern** matches, int count) {
fRecCount = count;
fRecs = SkNEW_ARRAY(Rec, count);
for (int i = 0; i < count; ++i) {
fRecs[i].fStyleName.set(get_name(matches[i], FC_STYLE));
fRecs[i].fFileName.set(get_name(matches[i], FC_FILE));
fRecs[i].fStyle = make_fontconfig_style(matches[i]);
}
}
SkFontStyleSet_FC::~SkFontStyleSet_FC() {
SkDELETE_ARRAY(fRecs);
}
void SkFontStyleSet_FC::getStyle(int index, SkFontStyle* style,
SkString* styleName) {
SkASSERT((unsigned)index < (unsigned)fRecCount);
if (style) {
*style = fRecs[index].fStyle;
}
if (styleName) {
*styleName = fRecs[index].fStyleName;
}
}
SkTypeface* SkFontStyleSet_FC::createTypeface(int index) {
return NULL;
}
SkTypeface* SkFontStyleSet_FC::matchStyle(const SkFontStyle& pattern) {
return NULL;
}
class SkFontMgr_fontconfig : public SkFontMgr {
SkAutoTUnref<SkFontConfigInterface> fFCI;
SkDataTable* fFamilyNames;
public:
SkFontMgr_fontconfig(SkFontConfigInterface* fci)
: fFCI(fci)
, fFamilyNames(fFCI->getFamilyNames()) {}
virtual ~SkFontMgr_fontconfig() {
SkSafeUnref(fFamilyNames);
}
protected:
virtual int onCountFamilies() const SK_OVERRIDE {
return fFamilyNames->count();
}
virtual void onGetFamilyName(int index, SkString* familyName) const SK_OVERRIDE {
familyName->set(fFamilyNames->atStr(index));
}
virtual SkFontStyleSet* onCreateStyleSet(int index) const SK_OVERRIDE {
return this->onMatchFamily(fFamilyNames->atStr(index));
}
virtual SkFontStyleSet* onMatchFamily(const char familyName[]) const SK_OVERRIDE {
FCLocker lock;
FcPattern* pattern = FcPatternCreate();
FcPatternAddString(pattern, FC_FAMILY, (FcChar8*)familyName);
#if 0
FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
#endif
FcConfigSubstitute(NULL, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
const char* post_config_family = get_name(pattern, FC_FAMILY);
FcResult result;
FcFontSet* font_set = FcFontSort(0, pattern, 0, 0, &result);
if (!font_set) {
FcPatternDestroy(pattern);
return NULL;
}
int count;
FcPattern** match = MatchFont(font_set, post_config_family, &count);
if (!match) {
FcPatternDestroy(pattern);
FcFontSetDestroy(font_set);
return NULL;
}
FcPatternDestroy(pattern);
SkTDArray<FcPattern*> trimmedMatches;
for (int i = 0; i < count; ++i) {
const char* justName = find_just_name(get_name(match[i], FC_FILE));
if (!is_lower(*justName)) {
*trimmedMatches.append() = match[i];
}
}
SkFontStyleSet_FC* sset = SkNEW_ARGS(SkFontStyleSet_FC,
(trimmedMatches.begin(),
trimmedMatches.count()));
return sset;
}
virtual SkTypeface* onMatchFamilyStyle(const char familyName[],
const SkFontStyle&) const SK_OVERRIDE { return NULL; }
virtual SkTypeface* onMatchFaceStyle(const SkTypeface*,
const SkFontStyle&) const SK_OVERRIDE { return NULL; }
virtual SkTypeface* onCreateFromData(SkData*, int ttcIndex) const SK_OVERRIDE { return NULL; }
virtual SkTypeface* onCreateFromStream(SkStream* stream, int ttcIndex) const SK_OVERRIDE {
const size_t length = stream->getLength();
if (!length) {
return NULL;
}
if (length >= 1024 * 1024 * 1024) {
return NULL; // don't accept too large fonts (>= 1GB) for safety.
}
// TODO should the caller give us the style or should we get it from freetype?
SkTypeface::Style style = SkTypeface::kNormal;
bool isFixedWidth = false;
if (!find_name_and_attributes(stream, NULL, &style, &isFixedWidth)) {
return NULL;
}
SkTypeface* face = SkNEW_ARGS(FontConfigTypeface, (style, isFixedWidth, stream));
return face;
}
virtual SkTypeface* onCreateFromFile(const char path[], int ttcIndex) const SK_OVERRIDE {
SkAutoTUnref<SkStream> stream(SkStream::NewFromFile(path));
return stream.get() ? this->createFromStream(stream, ttcIndex) : NULL;
}
virtual SkTypeface* onLegacyCreateTypeface(const char familyName[],
unsigned styleBits) const SK_OVERRIDE {
FCLocker lock;
return FontConfigTypeface::LegacyCreateTypeface(NULL, familyName,
(SkTypeface::Style)styleBits);
}
};
SkFontMgr* SkFontMgr::Factory() {
SkFontConfigInterface* fci = RefFCI();
return fci ? SkNEW_ARGS(SkFontMgr_fontconfig, (fci)) : NULL;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* PokerTH - The open source texas holdem engine *
* Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*****************************************************************************/
#include "chattools.h"
#include "session.h"
#include "configfile.h"
#include "gametablestylereader.h"
#include "gamelobbydialogimpl.h"
#include <iostream>
using namespace std;
ChatTools::ChatTools(QLineEdit* l, ConfigFile *c, ChatType ct, QTextBrowser *b, QStandardItemModel *m, gameLobbyDialogImpl *lo) : nickAutoCompletitionCounter(0), myLineEdit(l), myNickListModel(m), myNickStringList(NULL), myTextBrowser(b), myChatType(ct), myConfig(c), myNick(""), myLobby(lo)
{
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
}
ChatTools::~ChatTools()
{
}
void ChatTools::sendMessage()
{
if(myLineEdit->text().size() && mySession) {
fillChatLinesHistory(myLineEdit->text());
QString chatText(myLineEdit->text());
if(myChatType == INGAME_CHAT) {
mySession->sendGameChatMessage(chatText.toUtf8().constData());
} else {
// Parse user name for private messages.
if(chatText.indexOf(QString("/msg ")) == 0) {
chatText.remove(0, 5);
unsigned playerId = parsePrivateMessageTarget(chatText);
if (playerId) {
mySession->sendPrivateChatMessage(playerId, chatText.toUtf8().constData());
QString tmp = tr("private message sent to player: %1");
myTextBrowser->append("<i>"+tmp.arg(QString::fromUtf8(mySession->getClientPlayerInfo(playerId).playerName.c_str()))+"</i>");
}
} else {
mySession->sendLobbyChatMessage(chatText.toUtf8().constData());
}
}
myLineEdit->setText("");
}
}
void ChatTools::receiveMessage(QString playerName, QString message, bool pm)
{
if(myTextBrowser) {
message = message.replace("<","<");
message = message.replace(">",">");
//doing the links
message = message.replace(QRegExp("((?:https?)://\\S+)"), "<a href=\"\\1\">\\1</a>");
//refresh myNick if it was changed during runtime
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
QString tempMsg;
if(myChatType == INET_LOBBY_CHAT && playerName == "(chat bot)" && message.startsWith(myNick)) {
tempMsg = QString("<span style=\"font-weight:bold; color:red;\">"+message+"</span>");
//play beep sound only in INET-lobby-chat
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
}
} else if(message.contains(myNick, Qt::CaseInsensitive)) {
switch (myChatType) {
case INET_LOBBY_CHAT: {
tempMsg = QString("<span style=\"font-weight:bold; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
//play beep sound only in INET-lobby-chat
// TODO dont play when message is from yourself
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
}
}
break;
case LAN_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:bold;\">"+message+"</span>");
break;
case INGAME_CHAT: {
message = message.replace("<a href","<a style=\"color:#"+myStyle->getChatLogTextColor()+"; text-decoration: underline;\" href");
tempMsg = QString("<span style=\"color:#"+myStyle->getChatTextNickNotifyColor()+";\">"+message+"</span>");
}
break;
default:
tempMsg = message;
}
} else if(playerName == myNick) {
switch (myChatType) {
case INET_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
break;
case LAN_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT: {
message = message.replace("<a href","<a style=\"color:#"+myStyle->getChatTextNickNotifyColor()+"; text-decoration: underline;\" href");
tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
}
break;
default:
tempMsg = message;
}
} else {
switch (myChatType) {
case INET_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().text().color().name()+";\">"+message+"</span>");
break;
case LAN_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT: {
message = message.replace("<a href","<a style=\"color:#"+myStyle->getChatTextNickNotifyColor()+"; text-decoration: underline;\" href");
tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
}
break;
default:
tempMsg = message;
}
}
bool nickFoundOnIgnoreList = false;
list<std::string>::iterator it1;
for(it1=ignoreList.begin(); it1 != ignoreList.end(); ++it1) {
if(playerName == QString::fromUtf8(it1->c_str())) {
nickFoundOnIgnoreList = true;
}
}
if(!nickFoundOnIgnoreList) {
tempMsg = checkForEmotes(tempMsg);
if(message.indexOf(QString("/me "))==0) {
myTextBrowser->append(tempMsg.replace("/me ","<i>*"+playerName+" ")+"</i>");
} else if(pm == true) {
myTextBrowser->append("<i>"+playerName+"(pm): " + tempMsg+"</i>");
} else {
myTextBrowser->append(playerName + ": " + tempMsg);
}
}
}
}
void ChatTools::privateMessage(QString playerName, QString message)
{
bool pm=true;
receiveMessage(playerName, message, pm);
}
void ChatTools::clearChat()
{
if(myTextBrowser)
myTextBrowser->clear();
}
void ChatTools::checkInputLength(QString string)
{
if(string.toUtf8().length() > 120) myLineEdit->setMaxLength(string.length());
}
void ChatTools::fillChatLinesHistory(QString fillString)
{
chatLinesHistory << fillString;
if(chatLinesHistory.size() > 50) chatLinesHistory.removeFirst();
}
void ChatTools::showChatHistoryIndex(int index)
{
if(index <= chatLinesHistory.size()) {
// cout << chatLinesHistory.size() << " : " << index << endl;
if(index > 0)
myLineEdit->setText(chatLinesHistory.at(chatLinesHistory.size()-(index)));
else
myLineEdit->setText("");
}
}
void ChatTools::nickAutoCompletition()
{
QString myChatString = myLineEdit->text();
QStringList myChatStringList = myChatString.split(" ");
QStringList matchStringList;
if(nickAutoCompletitionCounter == 0) {
if(myNickListModel) {
int it = 0;
while (myNickListModel->item(it)) {
QString text = myNickListModel->item(it, 0)->data(Qt::DisplayRole).toString();
if(text.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "") {
matchStringList << text;
}
++it;
}
}
if(!myNickStringList.isEmpty()) {
QStringListIterator it(myNickStringList);
while (it.hasNext()) {
QString next = it.next();
if (next.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "")
matchStringList << next;
}
}
}
if(!matchStringList.isEmpty() || nickAutoCompletitionCounter > 0) {
myChatStringList.removeLast();
// cout << nickAutoCompletitionCounter << endl;
if(nickAutoCompletitionCounter == 0) {
//first one
lastChatString = myChatStringList.join(" ");
lastMatchStringList = matchStringList;
}
if(nickAutoCompletitionCounter == lastMatchStringList.size()) nickAutoCompletitionCounter = 0;
// cout << nickAutoCompletitionCounter << "\n";
if(lastChatString == "") {
myLineEdit->setText(lastMatchStringList.at(nickAutoCompletitionCounter)+": ");
} else {
//check if lastChatString is pm-code
if((lastChatString == "/msg" || lastChatString == "/msg ") && lastMatchStringList.at(nickAutoCompletitionCounter).contains(" ")) {
myLineEdit->setText(lastChatString+" \""+lastMatchStringList.at(nickAutoCompletitionCounter)+"\" ");
} else {
myLineEdit->setText(lastChatString+" "+lastMatchStringList.at(nickAutoCompletitionCounter)+" ");
}
}
nickAutoCompletitionCounter++;
}
}
void ChatTools::setChatTextEdited()
{
nickAutoCompletitionCounter = 0;
}
void ChatTools::refreshIgnoreList()
{
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
}
unsigned ChatTools::parsePrivateMessageTarget(QString &chatText)
{
QString playerName;
int endPosName = -1;
// Target player is either in the format "this is a user" or singlename.
if (chatText.startsWith('"')) {
chatText.remove(0, 1);
endPosName = chatText.indexOf('"');
} else {
endPosName = chatText.indexOf(' ');
}
if (endPosName > 0) {
playerName = chatText.left(endPosName);
chatText.remove(0, endPosName + 1);
}
chatText = chatText.trimmed();
unsigned playerId = 0;
if (!playerName.isEmpty() && !chatText.isEmpty()) {
if(myNickListModel) {
int it = 0;
while (myNickListModel->item(it)) {
QString text = myNickListModel->item(it, 0)->data(Qt::DisplayRole).toString();
if(text == playerName) {
playerId = myNickListModel->item(it, 0)->data(Qt::UserRole).toUInt();
break;
}
++it;
}
}
}
return playerId;
}
QString ChatTools::checkForEmotes(QString msg) {
qDebug() << msg;
msg.replace("0:-)", "<img src=\":emotes/emotes/face-angel.png\" />");
msg.replace("X-(", "<img src=\":emotes/emotes/face-angry.png\" />");
msg.replace("B-)", "<img src=\":emotes/emotes/face-cool.png\" />");
msg.replace("8-)", "<img src=\":emotes/emotes/face-cool.png\" />");
msg.replace(":'(", "<img src=\":emotes/emotes/face-crying.png\" />");
msg.replace(">:-)", "<img src=\":emotes/emotes/face-devilish.png\" />");
msg.replace(":-[", "<img src=\":emotes/emotes/face-embarrassed.png\" />");
msg.replace(":-*", "<img src=\":emotes/emotes/face-kiss.png\" />");
msg.replace(":-))", "<img src=\":emotes/emotes/face-laugh.png\" />");
msg.replace(":))", "<img src=\":emotes/emotes/face-laugh.png\" />");
msg.replace(":-|", "<img src=\":emotes/emotes/face-plain.png\" />");
msg.replace(":-P", "<img src=\":emotes/emotes/face-raspberry.png\" />");
msg.replace(":-p", "<img src=\":emotes/emotes/face-raspberry.png\" />");
msg.replace(":-(", "<img src=\":emotes/emotes/face-sad.png\" />");
msg.replace(":(", "<img src=\":emotes/emotes/face-sad.png\" />");
msg.replace(":-&", "<img src=\":emotes/emotes/face-sick.png\" />");
msg.replace(":-D", "<img src=\":emotes/emotes/face-smile-big.png\" />");
msg.replace(":D", "<img src=\":emotes/emotes/face-smile-big.png\" />");
msg.replace(":-!", "<img src=\":emotes/emotes/face-smirk.png\" />");
msg.replace(":-0", "<img src=\":emotes/emotes/face-surprise.png\" />");
msg.replace(":-O", "<img src=\":emotes/emotes/face-surprise.png\" />");
msg.replace(":-o", "<img src=\":emotes/emotes/face-surprise.png\" />");
msg.replace(":-/", "<img src=\":emotes/emotes/face-uncertain.png\" />");
msg.replace(":/", "<img src=\":emotes/emotes/face-uncertain.png\" />");
msg.replace(";-)", "<img src=\":emotes/emotes/face-wink.png\" />");
msg.replace(";)", "<img src=\":emotes/emotes/face-wink.png\" />");
msg.replace(":-S", "<img src=\":emotes/emotes/face-worried.png\" />");
msg.replace(":-s", "<img src=\":emotes/emotes/face-worried.png\" />");
msg.replace(":-)", "<img src=\":emotes/emotes/face-smile.png\" />");
msg.replace(":)", "<img src=\":emotes/emotes/face-smile.png\" />");
return msg;
}
<commit_msg>remove debug msg<commit_after>/*****************************************************************************
* PokerTH - The open source texas holdem engine *
* Copyright (C) 2006-2011 Felix Hammer, Florian Thauer, Lothar May *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Affero General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (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 Affero General Public License for more details. *
* *
* You should have received a copy of the GNU Affero General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
*****************************************************************************/
#include "chattools.h"
#include "session.h"
#include "configfile.h"
#include "gametablestylereader.h"
#include "gamelobbydialogimpl.h"
#include <iostream>
using namespace std;
ChatTools::ChatTools(QLineEdit* l, ConfigFile *c, ChatType ct, QTextBrowser *b, QStandardItemModel *m, gameLobbyDialogImpl *lo) : nickAutoCompletitionCounter(0), myLineEdit(l), myNickListModel(m), myNickStringList(NULL), myTextBrowser(b), myChatType(ct), myConfig(c), myNick(""), myLobby(lo)
{
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
}
ChatTools::~ChatTools()
{
}
void ChatTools::sendMessage()
{
if(myLineEdit->text().size() && mySession) {
fillChatLinesHistory(myLineEdit->text());
QString chatText(myLineEdit->text());
if(myChatType == INGAME_CHAT) {
mySession->sendGameChatMessage(chatText.toUtf8().constData());
} else {
// Parse user name for private messages.
if(chatText.indexOf(QString("/msg ")) == 0) {
chatText.remove(0, 5);
unsigned playerId = parsePrivateMessageTarget(chatText);
if (playerId) {
mySession->sendPrivateChatMessage(playerId, chatText.toUtf8().constData());
QString tmp = tr("private message sent to player: %1");
myTextBrowser->append("<i>"+tmp.arg(QString::fromUtf8(mySession->getClientPlayerInfo(playerId).playerName.c_str()))+"</i>");
}
} else {
mySession->sendLobbyChatMessage(chatText.toUtf8().constData());
}
}
myLineEdit->setText("");
}
}
void ChatTools::receiveMessage(QString playerName, QString message, bool pm)
{
if(myTextBrowser) {
message = message.replace("<","<");
message = message.replace(">",">");
//doing the links
message = message.replace(QRegExp("((?:https?)://\\S+)"), "<a href=\"\\1\">\\1</a>");
//refresh myNick if it was changed during runtime
myNick = QString::fromUtf8(myConfig->readConfigString("MyName").c_str());
QString tempMsg;
if(myChatType == INET_LOBBY_CHAT && playerName == "(chat bot)" && message.startsWith(myNick)) {
tempMsg = QString("<span style=\"font-weight:bold; color:red;\">"+message+"</span>");
//play beep sound only in INET-lobby-chat
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
}
} else if(message.contains(myNick, Qt::CaseInsensitive)) {
switch (myChatType) {
case INET_LOBBY_CHAT: {
tempMsg = QString("<span style=\"font-weight:bold; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
//play beep sound only in INET-lobby-chat
// TODO dont play when message is from yourself
if(myLobby->isVisible() && myConfig->readConfigInt("PlayLobbyChatNotification")) {
myLobby->getMyW()->getMySDLPlayer()->playSound("lobbychatnotify",0);
}
}
break;
case LAN_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:bold;\">"+message+"</span>");
break;
case INGAME_CHAT: {
message = message.replace("<a href","<a style=\"color:#"+myStyle->getChatLogTextColor()+"; text-decoration: underline;\" href");
tempMsg = QString("<span style=\"color:#"+myStyle->getChatTextNickNotifyColor()+";\">"+message+"</span>");
}
break;
default:
tempMsg = message;
}
} else if(playerName == myNick) {
switch (myChatType) {
case INET_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().link().color().name()+";\">"+message+"</span>");
break;
case LAN_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT: {
message = message.replace("<a href","<a style=\"color:#"+myStyle->getChatTextNickNotifyColor()+"; text-decoration: underline;\" href");
tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
}
break;
default:
tempMsg = message;
}
} else {
switch (myChatType) {
case INET_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal; color:"+myLobby->palette().text().color().name()+";\">"+message+"</span>");
break;
case LAN_LOBBY_CHAT:
tempMsg = QString("<span style=\"font-weight:normal;\">"+message+"</span>");
break;
case INGAME_CHAT: {
message = message.replace("<a href","<a style=\"color:#"+myStyle->getChatTextNickNotifyColor()+"; text-decoration: underline;\" href");
tempMsg = QString("<span style=\"color:#"+myStyle->getChatLogTextColor()+";\">"+message+"</span>");
}
break;
default:
tempMsg = message;
}
}
bool nickFoundOnIgnoreList = false;
list<std::string>::iterator it1;
for(it1=ignoreList.begin(); it1 != ignoreList.end(); ++it1) {
if(playerName == QString::fromUtf8(it1->c_str())) {
nickFoundOnIgnoreList = true;
}
}
if(!nickFoundOnIgnoreList) {
tempMsg = checkForEmotes(tempMsg);
if(message.indexOf(QString("/me "))==0) {
myTextBrowser->append(tempMsg.replace("/me ","<i>*"+playerName+" ")+"</i>");
} else if(pm == true) {
myTextBrowser->append("<i>"+playerName+"(pm): " + tempMsg+"</i>");
} else {
myTextBrowser->append(playerName + ": " + tempMsg);
}
}
}
}
void ChatTools::privateMessage(QString playerName, QString message)
{
bool pm=true;
receiveMessage(playerName, message, pm);
}
void ChatTools::clearChat()
{
if(myTextBrowser)
myTextBrowser->clear();
}
void ChatTools::checkInputLength(QString string)
{
if(string.toUtf8().length() > 120) myLineEdit->setMaxLength(string.length());
}
void ChatTools::fillChatLinesHistory(QString fillString)
{
chatLinesHistory << fillString;
if(chatLinesHistory.size() > 50) chatLinesHistory.removeFirst();
}
void ChatTools::showChatHistoryIndex(int index)
{
if(index <= chatLinesHistory.size()) {
// cout << chatLinesHistory.size() << " : " << index << endl;
if(index > 0)
myLineEdit->setText(chatLinesHistory.at(chatLinesHistory.size()-(index)));
else
myLineEdit->setText("");
}
}
void ChatTools::nickAutoCompletition()
{
QString myChatString = myLineEdit->text();
QStringList myChatStringList = myChatString.split(" ");
QStringList matchStringList;
if(nickAutoCompletitionCounter == 0) {
if(myNickListModel) {
int it = 0;
while (myNickListModel->item(it)) {
QString text = myNickListModel->item(it, 0)->data(Qt::DisplayRole).toString();
if(text.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "") {
matchStringList << text;
}
++it;
}
}
if(!myNickStringList.isEmpty()) {
QStringListIterator it(myNickStringList);
while (it.hasNext()) {
QString next = it.next();
if (next.startsWith(myChatStringList.last(), Qt::CaseInsensitive) && myChatStringList.last() != "")
matchStringList << next;
}
}
}
if(!matchStringList.isEmpty() || nickAutoCompletitionCounter > 0) {
myChatStringList.removeLast();
// cout << nickAutoCompletitionCounter << endl;
if(nickAutoCompletitionCounter == 0) {
//first one
lastChatString = myChatStringList.join(" ");
lastMatchStringList = matchStringList;
}
if(nickAutoCompletitionCounter == lastMatchStringList.size()) nickAutoCompletitionCounter = 0;
// cout << nickAutoCompletitionCounter << "\n";
if(lastChatString == "") {
myLineEdit->setText(lastMatchStringList.at(nickAutoCompletitionCounter)+": ");
} else {
//check if lastChatString is pm-code
if((lastChatString == "/msg" || lastChatString == "/msg ") && lastMatchStringList.at(nickAutoCompletitionCounter).contains(" ")) {
myLineEdit->setText(lastChatString+" \""+lastMatchStringList.at(nickAutoCompletitionCounter)+"\" ");
} else {
myLineEdit->setText(lastChatString+" "+lastMatchStringList.at(nickAutoCompletitionCounter)+" ");
}
}
nickAutoCompletitionCounter++;
}
}
void ChatTools::setChatTextEdited()
{
nickAutoCompletitionCounter = 0;
}
void ChatTools::refreshIgnoreList()
{
ignoreList = myConfig->readConfigStringList("PlayerIgnoreList");
}
unsigned ChatTools::parsePrivateMessageTarget(QString &chatText)
{
QString playerName;
int endPosName = -1;
// Target player is either in the format "this is a user" or singlename.
if (chatText.startsWith('"')) {
chatText.remove(0, 1);
endPosName = chatText.indexOf('"');
} else {
endPosName = chatText.indexOf(' ');
}
if (endPosName > 0) {
playerName = chatText.left(endPosName);
chatText.remove(0, endPosName + 1);
}
chatText = chatText.trimmed();
unsigned playerId = 0;
if (!playerName.isEmpty() && !chatText.isEmpty()) {
if(myNickListModel) {
int it = 0;
while (myNickListModel->item(it)) {
QString text = myNickListModel->item(it, 0)->data(Qt::DisplayRole).toString();
if(text == playerName) {
playerId = myNickListModel->item(it, 0)->data(Qt::UserRole).toUInt();
break;
}
++it;
}
}
}
return playerId;
}
QString ChatTools::checkForEmotes(QString msg) {
msg.replace("0:-)", "<img src=\":emotes/emotes/face-angel.png\" />");
msg.replace("X-(", "<img src=\":emotes/emotes/face-angry.png\" />");
msg.replace("B-)", "<img src=\":emotes/emotes/face-cool.png\" />");
msg.replace("8-)", "<img src=\":emotes/emotes/face-cool.png\" />");
msg.replace(":'(", "<img src=\":emotes/emotes/face-crying.png\" />");
msg.replace(">:-)", "<img src=\":emotes/emotes/face-devilish.png\" />");
msg.replace(":-[", "<img src=\":emotes/emotes/face-embarrassed.png\" />");
msg.replace(":-*", "<img src=\":emotes/emotes/face-kiss.png\" />");
msg.replace(":-))", "<img src=\":emotes/emotes/face-laugh.png\" />");
msg.replace(":))", "<img src=\":emotes/emotes/face-laugh.png\" />");
msg.replace(":-|", "<img src=\":emotes/emotes/face-plain.png\" />");
msg.replace(":-P", "<img src=\":emotes/emotes/face-raspberry.png\" />");
msg.replace(":-p", "<img src=\":emotes/emotes/face-raspberry.png\" />");
msg.replace(":-(", "<img src=\":emotes/emotes/face-sad.png\" />");
msg.replace(":(", "<img src=\":emotes/emotes/face-sad.png\" />");
msg.replace(":-&", "<img src=\":emotes/emotes/face-sick.png\" />");
msg.replace(":-D", "<img src=\":emotes/emotes/face-smile-big.png\" />");
msg.replace(":D", "<img src=\":emotes/emotes/face-smile-big.png\" />");
msg.replace(":-!", "<img src=\":emotes/emotes/face-smirk.png\" />");
msg.replace(":-0", "<img src=\":emotes/emotes/face-surprise.png\" />");
msg.replace(":-O", "<img src=\":emotes/emotes/face-surprise.png\" />");
msg.replace(":-o", "<img src=\":emotes/emotes/face-surprise.png\" />");
msg.replace(":-/", "<img src=\":emotes/emotes/face-uncertain.png\" />");
msg.replace(":/", "<img src=\":emotes/emotes/face-uncertain.png\" />");
msg.replace(";-)", "<img src=\":emotes/emotes/face-wink.png\" />");
msg.replace(";)", "<img src=\":emotes/emotes/face-wink.png\" />");
msg.replace(":-S", "<img src=\":emotes/emotes/face-worried.png\" />");
msg.replace(":-s", "<img src=\":emotes/emotes/face-worried.png\" />");
msg.replace(":-)", "<img src=\":emotes/emotes/face-smile.png\" />");
msg.replace(":)", "<img src=\":emotes/emotes/face-smile.png\" />");
return msg;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdlib.h> /* exit */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
struct termios orig;
int filedesc;
int fd;
unsigned char serialBuffer[16]; // Serial buffer to store data for I/O
int openSerialPort(const char * device, int bps)
{
struct termios neu;
char buf[128];
fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (fd == -1)
{
sprintf(buf, "openSerialPort %s error", device);
perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
//fprintf(stderr, "speed=%d\n", bps);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
//write(fd,serialBuffer, count);
}
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void read_MD49_Data (void){
serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
writeBytes(fd, 1);
//usleep(400000);
//Daten lesen und in Array schreiben
readBytes(fd, 18);
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
printf("Encoder1 Byte1: %i ",serialBuffer[0]);
printf("Byte2: %i ",serialBuffer[1]);
printf("Byte3: % i ",serialBuffer[2]);
printf("Byte4: %i \n",serialBuffer[3]);
printf("Encoder2 Byte1: %i ",serialBuffer[4]);
printf("Byte2: %i ",serialBuffer[5]);
printf("Byte3: %i ",serialBuffer[6]);
printf("Byte4: %i \n",serialBuffer[7]);
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
printf("Speed2: %i \n",serialBuffer[9]);
printf("Volts: %i \n",serialBuffer[10]);
printf("Current1: %i ",serialBuffer[11]);
printf("Current2: %i \n",serialBuffer[12]);
printf("Error: %i \n",serialBuffer[13]);
printf("Acceleration: %i \n",serialBuffer[14]);
printf("Mode: %i \n",serialBuffer[15]);
printf("Regulator: %i \n",serialBuffer[16]);
printf("Timeout: %i \n",serialBuffer[17]);
}
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd)
{
ROS_INFO("I heard: [%f]", vel_cmd.linear.y);
std::cout << "Twist Received " << std::endl;
//hier code um msg in seriellen Befehl umzuwandeln
//code
//
}
int main( int argc, char* argv[] )
{
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 1000, cmd_vel_callback);
filedesc = openSerialPort("/dev/ttyAMA0", B38400);
if (filedesc == -1) exit(1);
usleep(40000); // Sleep for UART to power up and set options
ROS_INFO_STREAM("serial Port opened \n");
while( n.ok() )
{
//read_MD49_Data();
//usleep(100000);
ROS_INFO_STREAM("cycle? \n");
ros::spin();
//hier code/funktion um md49 daten zu lesen und und auszugeben in konsole und /odom später
}
return 1;
}
<commit_msg>Update code<commit_after>#include <iostream>
#include <stdio.h> /* Standard input/output definitions */
#include <stdlib.h> /* exit */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <ctype.h> /* isxxx() */
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
struct termios orig;
int filedesc;
int fd;
unsigned char serialBuffer[16]; // Serial buffer to store data for I/O
int openSerialPort(const char * device, int bps)
{
struct termios neu;
char buf[128];
fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (fd == -1)
{
sprintf(buf, "openSerialPort %s error", device);
perror(buf);
}
else
{
tcgetattr(fd, &orig); /* save current serial settings */
tcgetattr(fd, &neu);
cfmakeraw(&neu);
//fprintf(stderr, "speed=%d\n", bps);
cfsetispeed(&neu, bps);
cfsetospeed(&neu, bps);
tcsetattr(fd, TCSANOW, &neu); /* set new serial settings */
fcntl (fd, F_SETFL, O_RDWR);
}
return fd;
}
void writeBytes(int descriptor, int count) {
if ((write(descriptor, serialBuffer, count)) == -1) { // Send data out
perror("Error writing");
close(descriptor); // Close port if there is an error
exit(1);
}
//write(fd,serialBuffer, count);
}
void readBytes(int descriptor, int count) {
if (read(descriptor, serialBuffer, count) == -1) { // Read back data into buf[]
perror("Error reading ");
close(descriptor); // Close port if there is an error
exit(1);
}
}
void read_MD49_Data (void){
serialBuffer[0] = 82; // 82=R Steuerbyte um alle Daten vom MD49 zu lesen
writeBytes(fd, 1);
//usleep(400000);
//Daten lesen und in Array schreiben
readBytes(fd, 18);
printf("\033[2J"); /* clear the screen */
printf("\033[H"); /* position cursor at top-left corner */
printf ("MD49-Data read from AVR-Master: \n");
printf("====================================================== \n");
printf("Encoder1 Byte1: %i ",serialBuffer[0]);
printf("Byte2: %i ",serialBuffer[1]);
printf("Byte3: % i ",serialBuffer[2]);
printf("Byte4: %i \n",serialBuffer[3]);
printf("Encoder2 Byte1: %i ",serialBuffer[4]);
printf("Byte2: %i ",serialBuffer[5]);
printf("Byte3: %i ",serialBuffer[6]);
printf("Byte4: %i \n",serialBuffer[7]);
printf("====================================================== \n");
printf("Speed1: %i ",serialBuffer[8]);
printf("Speed2: %i \n",serialBuffer[9]);
printf("Volts: %i \n",serialBuffer[10]);
printf("Current1: %i ",serialBuffer[11]);
printf("Current2: %i \n",serialBuffer[12]);
printf("Error: %i \n",serialBuffer[13]);
printf("Acceleration: %i \n",serialBuffer[14]);
printf("Mode: %i \n",serialBuffer[15]);
printf("Regulator: %i \n",serialBuffer[16]);
printf("Timeout: %i \n",serialBuffer[17]);
}
void cmd_vel_callback(const geometry_msgs::Twist& vel_cmd)
{
ROS_INFO("I heard: [%f]", vel_cmd.linear.y);
std::cout << "Twist Received " << std::endl;
//hier code um msg in seriellen Befehl umzuwandeln
//code
//
}
int main( int argc, char* argv[] )
{
ros::init(argc, argv, "base_controller" );
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("/cmd_vel", 1000, cmd_vel_callback);
filedesc = openSerialPort("/dev/ttyAMA0", B38400);
if (filedesc == -1) exit(1);
usleep(40000); // Sleep for UART to power up and set options
ROS_INFO_STREAM("serial Port opened \n");
while( n.ok() )
{
while(1){
read_MD49_Data();
usleep(100000);
ros::spin();
}
}
return 1;
}
<|endoftext|> |
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2014
* Solidity AST to EVM bytecode compiler for expressions.
*/
#include <cassert>
#include <utility>
#include <numeric>
#include <libsolidity/AST.h>
#include <libsolidity/ExpressionCompiler.h>
#include <libsolidity/CompilerContext.h>
using namespace std;
namespace dev {
namespace solidity {
void ExpressionCompiler::compileExpression(CompilerContext& _context, Expression& _expression)
{
ExpressionCompiler compiler(_context);
_expression.accept(compiler);
}
bool ExpressionCompiler::visit(Assignment& _assignment)
{
m_currentLValue = nullptr;
Expression& rightHandSide = _assignment.getRightHandSide();
rightHandSide.accept(*this);
Type const& resultType = *_assignment.getType();
cleanHigherOrderBitsIfNeeded(*rightHandSide.getType(), resultType);
_assignment.getLeftHandSide().accept(*this);
Token::Value op = _assignment.getAssignmentOperator();
if (op != Token::ASSIGN)
{
// compound assignment
m_context << eth::Instruction::SWAP1;
appendOrdinaryBinaryOperatorCode(Token::AssignmentToBinaryOp(op), resultType);
}
else
m_context << eth::Instruction::POP; //@todo do not retrieve the value in the first place
storeInLValue(_assignment);
return false;
}
void ExpressionCompiler::endVisit(UnaryOperation& _unaryOperation)
{
//@todo type checking and creating code for an operator should be in the same place:
// the operator should know how to convert itself and to which types it applies, so
// put this code together with "Type::acceptsBinary/UnaryOperator" into a class that
// represents the operator
switch (_unaryOperation.getOperator())
{
case Token::NOT: // !
m_context << eth::Instruction::ISZERO;
break;
case Token::BIT_NOT: // ~
m_context << eth::Instruction::NOT;
break;
case Token::DELETE: // delete
{
// a -> a xor a (= 0).
// @todo semantics change for complex types
m_context << eth::Instruction::DUP1 << eth::Instruction::XOR;
storeInLValue(_unaryOperation);
break;
}
case Token::INC: // ++ (pre- or postfix)
case Token::DEC: // -- (pre- or postfix)
if (!_unaryOperation.isPrefixOperation())
m_context << eth::Instruction::DUP1;
m_context << u256(1);
if (_unaryOperation.getOperator() == Token::INC)
m_context << eth::Instruction::ADD;
else
m_context << eth::Instruction::SWAP1 << eth::Instruction::SUB; // @todo avoid the swap
if (_unaryOperation.isPrefixOperation())
storeInLValue(_unaryOperation);
else
moveToLValue(_unaryOperation);
break;
case Token::ADD: // +
// unary add, so basically no-op
break;
case Token::SUB: // -
m_context << u256(0) << eth::Instruction::SUB;
break;
default:
assert(false); // invalid operation
}
}
bool ExpressionCompiler::visit(BinaryOperation& _binaryOperation)
{
Expression& leftExpression = _binaryOperation.getLeftExpression();
Expression& rightExpression = _binaryOperation.getRightExpression();
Type const& resultType = *_binaryOperation.getType();
Token::Value const op = _binaryOperation.getOperator();
if (op == Token::AND || op == Token::OR)
{
// special case: short-circuiting
appendAndOrOperatorCode(_binaryOperation);
}
else if (Token::isCompareOp(op))
{
leftExpression.accept(*this);
rightExpression.accept(*this);
// the types to compare have to be the same, but the resulting type is always bool
assert(*leftExpression.getType() == *rightExpression.getType());
appendCompareOperatorCode(op, *leftExpression.getType());
}
else
{
leftExpression.accept(*this);
cleanHigherOrderBitsIfNeeded(*leftExpression.getType(), resultType);
rightExpression.accept(*this);
cleanHigherOrderBitsIfNeeded(*rightExpression.getType(), resultType);
appendOrdinaryBinaryOperatorCode(op, resultType);
}
// do not visit the child nodes, we already did that explicitly
return false;
}
bool ExpressionCompiler::visit(FunctionCall& _functionCall)
{
if (_functionCall.isTypeConversion())
{
//@todo we only have integers and bools for now which cannot be explicitly converted
assert(_functionCall.getArguments().size() == 1);
Expression& firstArgument = *_functionCall.getArguments().front();
firstArgument.accept(*this);
cleanHigherOrderBitsIfNeeded(*firstArgument.getType(), *_functionCall.getType());
}
else
{
// Calling convention: Caller pushes return address and arguments
// Callee removes them and pushes return values
m_currentLValue = nullptr;
_functionCall.getExpression().accept(*this);
FunctionDefinition const* function = dynamic_cast<FunctionDefinition*>(m_currentLValue);
assert(function);
eth::AssemblyItem returnLabel = m_context.pushNewTag();
std::vector<ASTPointer<Expression>> const& arguments = _functionCall.getArguments();
assert(arguments.size() == function->getParameters().size());
for (unsigned i = 0; i < arguments.size(); ++i)
{
arguments[i]->accept(*this);
cleanHigherOrderBitsIfNeeded(*arguments[i]->getType(),
*function->getParameters()[i]->getType());
}
m_context.appendJumpTo(m_context.getFunctionEntryLabel(*function));
m_context << returnLabel;
// callee adds return parameters, but removes arguments and return label
m_context.adjustStackOffset(function->getReturnParameters().size() - arguments.size() - 1);
// @todo for now, the return value of a function is its first return value, so remove
// all others
for (unsigned i = 1; i < function->getReturnParameters().size(); ++i)
m_context << eth::Instruction::POP;
}
return false;
}
void ExpressionCompiler::endVisit(MemberAccess&)
{
}
void ExpressionCompiler::endVisit(IndexAccess&)
{
}
void ExpressionCompiler::endVisit(Identifier& _identifier)
{
m_currentLValue = _identifier.getReferencedDeclaration();
switch (_identifier.getType()->getCategory())
{
case Type::Category::BOOL:
case Type::Category::INTEGER:
case Type::Category::REAL:
{
//@todo we also have to check where to retrieve them from once we add storage variables
unsigned stackPos = stackPositionOfLValue();
if (stackPos >= 15) //@todo correct this by fetching earlier or moving to memory
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_identifier.getLocation())
<< errinfo_comment("Stack too deep."));
m_context << eth::dupInstruction(stackPos + 1);
break;
}
default:
break;
}
}
void ExpressionCompiler::endVisit(Literal& _literal)
{
switch (_literal.getType()->getCategory())
{
case Type::Category::INTEGER:
case Type::Category::BOOL:
m_context << _literal.getType()->literalValue(_literal);
break;
default:
assert(false); // @todo
}
}
void ExpressionCompiler::cleanHigherOrderBitsIfNeeded(Type const& _typeOnStack, Type const& _targetType)
{
// If the type of one of the operands is extended, we need to remove all
// higher-order bits that we might have ignored in previous operations.
// @todo: store in the AST whether the operand might have "dirty" higher
// order bits
if (_typeOnStack == _targetType)
return;
if (_typeOnStack.getCategory() == Type::Category::INTEGER &&
_targetType.getCategory() == Type::Category::INTEGER)
{
//@todo
}
else
{
// If we get here, there is either an implementation missing to clean higher oder bits
// for non-integer types that are explicitly convertible or we got here in error.
assert(!_typeOnStack.isExplicitlyConvertibleTo(_targetType));
assert(false); // these types should not be convertible.
}
}
void ExpressionCompiler::appendAndOrOperatorCode(BinaryOperation& _binaryOperation)
{
Token::Value const op = _binaryOperation.getOperator();
assert(op == Token::OR || op == Token::AND);
_binaryOperation.getLeftExpression().accept(*this);
m_context << eth::Instruction::DUP1;
if (op == Token::AND)
m_context << eth::Instruction::ISZERO;
eth::AssemblyItem endLabel = m_context.appendConditionalJump();
_binaryOperation.getRightExpression().accept(*this);
m_context << endLabel;
}
void ExpressionCompiler::appendCompareOperatorCode(Token::Value _operator, Type const& _type)
{
if (_operator == Token::EQ || _operator == Token::NE)
{
m_context << eth::Instruction::EQ;
if (_operator == Token::NE)
m_context << eth::Instruction::ISZERO;
}
else
{
IntegerType const* type = dynamic_cast<IntegerType const*>(&_type);
assert(type);
bool const isSigned = type->isSigned();
// note that EVM opcodes compare like "stack[0] < stack[1]",
// but our left value is at stack[1], so everyhing is reversed.
switch (_operator)
{
case Token::GTE:
m_context << (isSigned ? eth::Instruction::SGT : eth::Instruction::GT)
<< eth::Instruction::ISZERO;
break;
case Token::LTE:
m_context << (isSigned ? eth::Instruction::SLT : eth::Instruction::LT)
<< eth::Instruction::ISZERO;
break;
case Token::GT:
m_context << (isSigned ? eth::Instruction::SLT : eth::Instruction::LT);
break;
case Token::LT:
m_context << (isSigned ? eth::Instruction::SGT : eth::Instruction::GT);
break;
default:
assert(false);
}
}
}
void ExpressionCompiler::appendOrdinaryBinaryOperatorCode(Token::Value _operator, Type const& _type)
{
if (Token::isArithmeticOp(_operator))
appendArithmeticOperatorCode(_operator, _type);
else if (Token::isBitOp(_operator))
appendBitOperatorCode(_operator);
else if (Token::isShiftOp(_operator))
appendShiftOperatorCode(_operator);
else
assert(false); // unknown binary operator
}
void ExpressionCompiler::appendArithmeticOperatorCode(Token::Value _operator, Type const& _type)
{
IntegerType const* type = dynamic_cast<IntegerType const*>(&_type);
assert(type);
bool const isSigned = type->isSigned();
switch (_operator)
{
case Token::ADD:
m_context << eth::Instruction::ADD;
break;
case Token::SUB:
m_context << eth::Instruction::SWAP1 << eth::Instruction::SUB;
break;
case Token::MUL:
m_context << eth::Instruction::MUL;
break;
case Token::DIV:
m_context << (isSigned ? eth::Instruction::SDIV : eth::Instruction::DIV);
break;
case Token::MOD:
m_context << (isSigned ? eth::Instruction::SMOD : eth::Instruction::MOD);
break;
default:
assert(false);
}
}
void ExpressionCompiler::appendBitOperatorCode(Token::Value _operator)
{
switch (_operator)
{
case Token::BIT_OR:
m_context << eth::Instruction::OR;
break;
case Token::BIT_AND:
m_context << eth::Instruction::AND;
break;
case Token::BIT_XOR:
m_context << eth::Instruction::XOR;
break;
default:
assert(false);
}
}
void ExpressionCompiler::appendShiftOperatorCode(Token::Value _operator)
{
switch (_operator)
{
case Token::SHL:
assert(false); //@todo
break;
case Token::SAR:
assert(false); //@todo
break;
default:
assert(false);
}
}
void ExpressionCompiler::storeInLValue(Expression const& _expression)
{
moveToLValue(_expression);
unsigned stackPos = stackPositionOfLValue();
if (stackPos > 16)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Stack too deep."));
m_context << eth::dupInstruction(stackPos + 1);
}
void ExpressionCompiler::moveToLValue(Expression const& _expression)
{
unsigned stackPos = stackPositionOfLValue();
if (stackPos > 16)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Stack too deep."));
else if (stackPos > 0)
m_context << eth::swapInstruction(stackPos) << eth::Instruction::POP;
}
unsigned ExpressionCompiler::stackPositionOfLValue() const
{
assert(m_currentLValue);
return m_context.getStackPositionOfVariable(*m_currentLValue);
}
}
}
<commit_msg>Bugfix: Swap before mod and div.<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2014
* Solidity AST to EVM bytecode compiler for expressions.
*/
#include <cassert>
#include <utility>
#include <numeric>
#include <libsolidity/AST.h>
#include <libsolidity/ExpressionCompiler.h>
#include <libsolidity/CompilerContext.h>
using namespace std;
namespace dev {
namespace solidity {
void ExpressionCompiler::compileExpression(CompilerContext& _context, Expression& _expression)
{
ExpressionCompiler compiler(_context);
_expression.accept(compiler);
}
bool ExpressionCompiler::visit(Assignment& _assignment)
{
m_currentLValue = nullptr;
Expression& rightHandSide = _assignment.getRightHandSide();
rightHandSide.accept(*this);
Type const& resultType = *_assignment.getType();
cleanHigherOrderBitsIfNeeded(*rightHandSide.getType(), resultType);
_assignment.getLeftHandSide().accept(*this);
Token::Value op = _assignment.getAssignmentOperator();
if (op != Token::ASSIGN)
{
// compound assignment
m_context << eth::Instruction::SWAP1;
appendOrdinaryBinaryOperatorCode(Token::AssignmentToBinaryOp(op), resultType);
}
else
m_context << eth::Instruction::POP; //@todo do not retrieve the value in the first place
storeInLValue(_assignment);
return false;
}
void ExpressionCompiler::endVisit(UnaryOperation& _unaryOperation)
{
//@todo type checking and creating code for an operator should be in the same place:
// the operator should know how to convert itself and to which types it applies, so
// put this code together with "Type::acceptsBinary/UnaryOperator" into a class that
// represents the operator
switch (_unaryOperation.getOperator())
{
case Token::NOT: // !
m_context << eth::Instruction::ISZERO;
break;
case Token::BIT_NOT: // ~
m_context << eth::Instruction::NOT;
break;
case Token::DELETE: // delete
{
// a -> a xor a (= 0).
// @todo semantics change for complex types
m_context << eth::Instruction::DUP1 << eth::Instruction::XOR;
storeInLValue(_unaryOperation);
break;
}
case Token::INC: // ++ (pre- or postfix)
case Token::DEC: // -- (pre- or postfix)
if (!_unaryOperation.isPrefixOperation())
m_context << eth::Instruction::DUP1;
m_context << u256(1);
if (_unaryOperation.getOperator() == Token::INC)
m_context << eth::Instruction::ADD;
else
m_context << eth::Instruction::SWAP1 << eth::Instruction::SUB; // @todo avoid the swap
if (_unaryOperation.isPrefixOperation())
storeInLValue(_unaryOperation);
else
moveToLValue(_unaryOperation);
break;
case Token::ADD: // +
// unary add, so basically no-op
break;
case Token::SUB: // -
m_context << u256(0) << eth::Instruction::SUB;
break;
default:
assert(false); // invalid operation
}
}
bool ExpressionCompiler::visit(BinaryOperation& _binaryOperation)
{
Expression& leftExpression = _binaryOperation.getLeftExpression();
Expression& rightExpression = _binaryOperation.getRightExpression();
Type const& resultType = *_binaryOperation.getType();
Token::Value const op = _binaryOperation.getOperator();
if (op == Token::AND || op == Token::OR)
{
// special case: short-circuiting
appendAndOrOperatorCode(_binaryOperation);
}
else if (Token::isCompareOp(op))
{
leftExpression.accept(*this);
rightExpression.accept(*this);
// the types to compare have to be the same, but the resulting type is always bool
assert(*leftExpression.getType() == *rightExpression.getType());
appendCompareOperatorCode(op, *leftExpression.getType());
}
else
{
leftExpression.accept(*this);
cleanHigherOrderBitsIfNeeded(*leftExpression.getType(), resultType);
rightExpression.accept(*this);
cleanHigherOrderBitsIfNeeded(*rightExpression.getType(), resultType);
appendOrdinaryBinaryOperatorCode(op, resultType);
}
// do not visit the child nodes, we already did that explicitly
return false;
}
bool ExpressionCompiler::visit(FunctionCall& _functionCall)
{
if (_functionCall.isTypeConversion())
{
//@todo we only have integers and bools for now which cannot be explicitly converted
assert(_functionCall.getArguments().size() == 1);
Expression& firstArgument = *_functionCall.getArguments().front();
firstArgument.accept(*this);
cleanHigherOrderBitsIfNeeded(*firstArgument.getType(), *_functionCall.getType());
}
else
{
// Calling convention: Caller pushes return address and arguments
// Callee removes them and pushes return values
m_currentLValue = nullptr;
_functionCall.getExpression().accept(*this);
FunctionDefinition const* function = dynamic_cast<FunctionDefinition*>(m_currentLValue);
assert(function);
eth::AssemblyItem returnLabel = m_context.pushNewTag();
std::vector<ASTPointer<Expression>> const& arguments = _functionCall.getArguments();
assert(arguments.size() == function->getParameters().size());
for (unsigned i = 0; i < arguments.size(); ++i)
{
arguments[i]->accept(*this);
cleanHigherOrderBitsIfNeeded(*arguments[i]->getType(),
*function->getParameters()[i]->getType());
}
m_context.appendJumpTo(m_context.getFunctionEntryLabel(*function));
m_context << returnLabel;
// callee adds return parameters, but removes arguments and return label
m_context.adjustStackOffset(function->getReturnParameters().size() - arguments.size() - 1);
// @todo for now, the return value of a function is its first return value, so remove
// all others
for (unsigned i = 1; i < function->getReturnParameters().size(); ++i)
m_context << eth::Instruction::POP;
}
return false;
}
void ExpressionCompiler::endVisit(MemberAccess&)
{
}
void ExpressionCompiler::endVisit(IndexAccess&)
{
}
void ExpressionCompiler::endVisit(Identifier& _identifier)
{
m_currentLValue = _identifier.getReferencedDeclaration();
switch (_identifier.getType()->getCategory())
{
case Type::Category::BOOL:
case Type::Category::INTEGER:
case Type::Category::REAL:
{
//@todo we also have to check where to retrieve them from once we add storage variables
unsigned stackPos = stackPositionOfLValue();
if (stackPos >= 15) //@todo correct this by fetching earlier or moving to memory
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_identifier.getLocation())
<< errinfo_comment("Stack too deep."));
m_context << eth::dupInstruction(stackPos + 1);
break;
}
default:
break;
}
}
void ExpressionCompiler::endVisit(Literal& _literal)
{
switch (_literal.getType()->getCategory())
{
case Type::Category::INTEGER:
case Type::Category::BOOL:
m_context << _literal.getType()->literalValue(_literal);
break;
default:
assert(false); // @todo
}
}
void ExpressionCompiler::cleanHigherOrderBitsIfNeeded(Type const& _typeOnStack, Type const& _targetType)
{
// If the type of one of the operands is extended, we need to remove all
// higher-order bits that we might have ignored in previous operations.
// @todo: store in the AST whether the operand might have "dirty" higher
// order bits
if (_typeOnStack == _targetType)
return;
if (_typeOnStack.getCategory() == Type::Category::INTEGER &&
_targetType.getCategory() == Type::Category::INTEGER)
{
//@todo
}
else
{
// If we get here, there is either an implementation missing to clean higher oder bits
// for non-integer types that are explicitly convertible or we got here in error.
assert(!_typeOnStack.isExplicitlyConvertibleTo(_targetType));
assert(false); // these types should not be convertible.
}
}
void ExpressionCompiler::appendAndOrOperatorCode(BinaryOperation& _binaryOperation)
{
Token::Value const op = _binaryOperation.getOperator();
assert(op == Token::OR || op == Token::AND);
_binaryOperation.getLeftExpression().accept(*this);
m_context << eth::Instruction::DUP1;
if (op == Token::AND)
m_context << eth::Instruction::ISZERO;
eth::AssemblyItem endLabel = m_context.appendConditionalJump();
_binaryOperation.getRightExpression().accept(*this);
m_context << endLabel;
}
void ExpressionCompiler::appendCompareOperatorCode(Token::Value _operator, Type const& _type)
{
if (_operator == Token::EQ || _operator == Token::NE)
{
m_context << eth::Instruction::EQ;
if (_operator == Token::NE)
m_context << eth::Instruction::ISZERO;
}
else
{
IntegerType const* type = dynamic_cast<IntegerType const*>(&_type);
assert(type);
bool const isSigned = type->isSigned();
// note that EVM opcodes compare like "stack[0] < stack[1]",
// but our left value is at stack[1], so everyhing is reversed.
switch (_operator)
{
case Token::GTE:
m_context << (isSigned ? eth::Instruction::SGT : eth::Instruction::GT)
<< eth::Instruction::ISZERO;
break;
case Token::LTE:
m_context << (isSigned ? eth::Instruction::SLT : eth::Instruction::LT)
<< eth::Instruction::ISZERO;
break;
case Token::GT:
m_context << (isSigned ? eth::Instruction::SLT : eth::Instruction::LT);
break;
case Token::LT:
m_context << (isSigned ? eth::Instruction::SGT : eth::Instruction::GT);
break;
default:
assert(false);
}
}
}
void ExpressionCompiler::appendOrdinaryBinaryOperatorCode(Token::Value _operator, Type const& _type)
{
if (Token::isArithmeticOp(_operator))
appendArithmeticOperatorCode(_operator, _type);
else if (Token::isBitOp(_operator))
appendBitOperatorCode(_operator);
else if (Token::isShiftOp(_operator))
appendShiftOperatorCode(_operator);
else
assert(false); // unknown binary operator
}
void ExpressionCompiler::appendArithmeticOperatorCode(Token::Value _operator, Type const& _type)
{
IntegerType const* type = dynamic_cast<IntegerType const*>(&_type);
assert(type);
bool const isSigned = type->isSigned();
switch (_operator)
{
case Token::ADD:
m_context << eth::Instruction::ADD;
break;
case Token::SUB:
m_context << eth::Instruction::SWAP1 << eth::Instruction::SUB;
break;
case Token::MUL:
m_context << eth::Instruction::MUL;
break;
case Token::DIV:
m_context << eth::Instruction::SWAP1 << (isSigned ? eth::Instruction::SDIV : eth::Instruction::DIV);
break;
case Token::MOD:
m_context << eth::Instruction::SWAP1 << (isSigned ? eth::Instruction::SMOD : eth::Instruction::MOD);
break;
default:
assert(false);
}
}
void ExpressionCompiler::appendBitOperatorCode(Token::Value _operator)
{
switch (_operator)
{
case Token::BIT_OR:
m_context << eth::Instruction::OR;
break;
case Token::BIT_AND:
m_context << eth::Instruction::AND;
break;
case Token::BIT_XOR:
m_context << eth::Instruction::XOR;
break;
default:
assert(false);
}
}
void ExpressionCompiler::appendShiftOperatorCode(Token::Value _operator)
{
switch (_operator)
{
case Token::SHL:
assert(false); //@todo
break;
case Token::SAR:
assert(false); //@todo
break;
default:
assert(false);
}
}
void ExpressionCompiler::storeInLValue(Expression const& _expression)
{
moveToLValue(_expression);
unsigned stackPos = stackPositionOfLValue();
if (stackPos > 16)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Stack too deep."));
m_context << eth::dupInstruction(stackPos + 1);
}
void ExpressionCompiler::moveToLValue(Expression const& _expression)
{
unsigned stackPos = stackPositionOfLValue();
if (stackPos > 16)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_sourceLocation(_expression.getLocation())
<< errinfo_comment("Stack too deep."));
else if (stackPos > 0)
m_context << eth::swapInstruction(stackPos) << eth::Instruction::POP;
}
unsigned ExpressionCompiler::stackPositionOfLValue() const
{
assert(m_currentLValue);
return m_context.getStackPositionOfVariable(*m_currentLValue);
}
}
}
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow 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 "tensorflow/lite/delegates/gpu/common/testing/feature_parity/utils.h"
#include <memory>
#include <optional>
#include <ostream>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/strings/substitute.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/string_type.h"
std::ostream& operator<<(std::ostream& os, const TfLiteTensor& tensor) {
std::string shape;
absl::optional<std::string> result = tflite::ShapeToString(tensor.dims);
if (result.has_value()) {
shape = std::move(result.value());
} else {
shape = "[error: unsupported number of dimensions]";
}
return os << "tensor of shape " << shape;
}
namespace tflite {
absl::optional<std::string> ShapeToString(TfLiteIntArray* shape) {
std::string result;
int* data = shape->data;
switch (shape->size) {
case 1:
result = absl::Substitute("Linear=[$0]", data[0]);
break;
case 2:
result = absl::Substitute("HW=[$0, $1]", data[0], data[1]);
break;
case 3:
result = absl::Substitute("HWC=[$0, $1, $2]", data[0], data[1], data[2]);
break;
case 4:
result = absl::Substitute("BHWC=[$0, $1, $2, $3]", data[0], data[1],
data[2], data[3]);
break;
default:
// This printer doesn't expect shapes of more than 4 dimensions.
return absl::nullopt;
}
return result;
}
absl::optional<std::string> CoordinateToString(TfLiteIntArray* shape,
int linear) {
std::string result;
switch (shape->size) {
case 1: {
result = absl::Substitute("[$0]", linear);
break;
} break;
case 2: {
const int tensor_width = shape->data[1];
const int h_coord = linear / tensor_width;
const int w_coord = linear % tensor_width;
result = absl::Substitute("[$0, $1]", h_coord, w_coord);
break;
} break;
case 3: {
const int tensor_width = shape->data[1];
const int tensor_channels = shape->data[2];
const int h_coord = linear / (tensor_width * tensor_channels);
const int w_coord =
(linear % (tensor_width * tensor_channels)) / tensor_channels;
const int c_coord =
(linear % (tensor_width * tensor_channels)) % tensor_channels;
result = absl::Substitute("[$0, $1, $2]", h_coord, w_coord, c_coord);
break;
} break;
case 4: {
const int tensor_height = shape->data[1];
const int tensor_width = shape->data[2];
const int tensor_channels = shape->data[3];
const int b_coord =
linear / (tensor_height * tensor_width * tensor_channels);
const int h_coord =
(linear % (tensor_height * tensor_width * tensor_channels)) /
(tensor_width * tensor_channels);
const int w_coord =
((linear % (tensor_height * tensor_width * tensor_channels)) %
(tensor_width * tensor_channels)) /
tensor_channels;
const int c_coord =
((linear % (tensor_height * tensor_width * tensor_channels)) %
(tensor_width * tensor_channels)) %
tensor_channels;
result = absl::Substitute("[$0, $1, $2, $3]", b_coord, h_coord, w_coord,
c_coord);
break;
}
default:
// This printer doesn't expect shapes of more than 4 dimensions.
return absl::nullopt;
}
return result;
}
// Builds interpreter for a model, allocates tensors.
absl::Status BuildInterpreter(const Model* model,
std::unique_ptr<Interpreter>* interpreter) {
TfLiteStatus status =
InterpreterBuilder(model, ops::builtin::BuiltinOpResolver())(interpreter);
if (status != kTfLiteOk || !*interpreter) {
return absl::InternalError(
"Failed to initialize interpreter with model binary.");
}
return absl::OkStatus();
}
absl::Status AllocateTensors(std::unique_ptr<Interpreter>* interpreter) {
if ((*interpreter)->AllocateTensors() != kTfLiteOk) {
return absl::InternalError("Failed to allocate tensors.");
}
return absl::OkStatus();
}
absl::Status ModifyGraphWithDelegate(std::unique_ptr<Interpreter>* interpreter,
TfLiteDelegate* delegate) {
if ((*interpreter)->ModifyGraphWithDelegate(delegate) != kTfLiteOk) {
return absl::InternalError("Failed modify graph with delegate.");
}
return absl::OkStatus();
}
void InitializeInputs(int left, int right,
std::unique_ptr<Interpreter>* interpreter) {
for (int id : (*interpreter)->inputs()) {
float* input_data = (*interpreter)->typed_tensor<float>(id);
int input_size = (*interpreter)->input_tensor(id)->bytes;
for (int i = 0; i < input_size; i++) {
input_data[i] = left + i % right;
}
}
}
absl::Status Invoke(std::unique_ptr<Interpreter>* interpreter) {
if ((*interpreter)->Invoke() != kTfLiteOk) {
return absl::InternalError("Failed during inference.");
}
return absl::OkStatus();
}
std::ostream& operator<<(std::ostream& os, const TestParams& param) {
return os << param.name;
}
} // namespace tflite
<commit_msg>(lite) Fix grammar error in error message.<commit_after>/* Copyright 2020 The TensorFlow 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 "tensorflow/lite/delegates/gpu/common/testing/feature_parity/utils.h"
#include <memory>
#include <optional>
#include <ostream>
#include <string>
#include <utility>
#include "absl/status/status.h"
#include "absl/strings/substitute.h"
#include "tensorflow/lite/interpreter.h"
#include "tensorflow/lite/kernels/register.h"
#include "tensorflow/lite/model.h"
#include "tensorflow/lite/string_type.h"
std::ostream& operator<<(std::ostream& os, const TfLiteTensor& tensor) {
std::string shape;
absl::optional<std::string> result = tflite::ShapeToString(tensor.dims);
if (result.has_value()) {
shape = std::move(result.value());
} else {
shape = "[error: unsupported number of dimensions]";
}
return os << "tensor of shape " << shape;
}
namespace tflite {
absl::optional<std::string> ShapeToString(TfLiteIntArray* shape) {
std::string result;
int* data = shape->data;
switch (shape->size) {
case 1:
result = absl::Substitute("Linear=[$0]", data[0]);
break;
case 2:
result = absl::Substitute("HW=[$0, $1]", data[0], data[1]);
break;
case 3:
result = absl::Substitute("HWC=[$0, $1, $2]", data[0], data[1], data[2]);
break;
case 4:
result = absl::Substitute("BHWC=[$0, $1, $2, $3]", data[0], data[1],
data[2], data[3]);
break;
default:
// This printer doesn't expect shapes of more than 4 dimensions.
return absl::nullopt;
}
return result;
}
absl::optional<std::string> CoordinateToString(TfLiteIntArray* shape,
int linear) {
std::string result;
switch (shape->size) {
case 1: {
result = absl::Substitute("[$0]", linear);
break;
} break;
case 2: {
const int tensor_width = shape->data[1];
const int h_coord = linear / tensor_width;
const int w_coord = linear % tensor_width;
result = absl::Substitute("[$0, $1]", h_coord, w_coord);
break;
} break;
case 3: {
const int tensor_width = shape->data[1];
const int tensor_channels = shape->data[2];
const int h_coord = linear / (tensor_width * tensor_channels);
const int w_coord =
(linear % (tensor_width * tensor_channels)) / tensor_channels;
const int c_coord =
(linear % (tensor_width * tensor_channels)) % tensor_channels;
result = absl::Substitute("[$0, $1, $2]", h_coord, w_coord, c_coord);
break;
} break;
case 4: {
const int tensor_height = shape->data[1];
const int tensor_width = shape->data[2];
const int tensor_channels = shape->data[3];
const int b_coord =
linear / (tensor_height * tensor_width * tensor_channels);
const int h_coord =
(linear % (tensor_height * tensor_width * tensor_channels)) /
(tensor_width * tensor_channels);
const int w_coord =
((linear % (tensor_height * tensor_width * tensor_channels)) %
(tensor_width * tensor_channels)) /
tensor_channels;
const int c_coord =
((linear % (tensor_height * tensor_width * tensor_channels)) %
(tensor_width * tensor_channels)) %
tensor_channels;
result = absl::Substitute("[$0, $1, $2, $3]", b_coord, h_coord, w_coord,
c_coord);
break;
}
default:
// This printer doesn't expect shapes of more than 4 dimensions.
return absl::nullopt;
}
return result;
}
// Builds interpreter for a model, allocates tensors.
absl::Status BuildInterpreter(const Model* model,
std::unique_ptr<Interpreter>* interpreter) {
TfLiteStatus status =
InterpreterBuilder(model, ops::builtin::BuiltinOpResolver())(interpreter);
if (status != kTfLiteOk || !*interpreter) {
return absl::InternalError(
"Failed to initialize interpreter with model binary.");
}
return absl::OkStatus();
}
absl::Status AllocateTensors(std::unique_ptr<Interpreter>* interpreter) {
if ((*interpreter)->AllocateTensors() != kTfLiteOk) {
return absl::InternalError("Failed to allocate tensors.");
}
return absl::OkStatus();
}
absl::Status ModifyGraphWithDelegate(std::unique_ptr<Interpreter>* interpreter,
TfLiteDelegate* delegate) {
if ((*interpreter)->ModifyGraphWithDelegate(delegate) != kTfLiteOk) {
return absl::InternalError("Failed to modify graph with delegate.");
}
return absl::OkStatus();
}
void InitializeInputs(int left, int right,
std::unique_ptr<Interpreter>* interpreter) {
for (int id : (*interpreter)->inputs()) {
float* input_data = (*interpreter)->typed_tensor<float>(id);
int input_size = (*interpreter)->input_tensor(id)->bytes;
for (int i = 0; i < input_size; i++) {
input_data[i] = left + i % right;
}
}
}
absl::Status Invoke(std::unique_ptr<Interpreter>* interpreter) {
if ((*interpreter)->Invoke() != kTfLiteOk) {
return absl::InternalError("Failed during inference.");
}
return absl::OkStatus();
}
std::ostream& operator<<(std::ostream& os, const TestParams& param) {
return os << param.name;
}
} // namespace tflite
<|endoftext|> |
<commit_before>#include "litesql.hpp"
#include "generator.hpp"
#include "litesql-gen-cpp.hpp"
#include "litesql-gen-graphviz.hpp"
#include "litesql-gen-ruby-activerecord.hpp"
#include "logger.hpp"
#include "objectmodel.hpp"
using namespace std;
using namespace litesql;
const char* help =
"Usage: litesql-gen [options] <my-database.xml>\n\n"
"Options:\n"
" -t, --target=TARGET generate code for TARGET (default: c++)\n"
" -v, --verbose verbosely report code generation\n"
" --help print help\n"
" -t, --target=TARGET generate code for TARGET (default: c++)\n"
" --output-dir=/path/to/src output all files to directory \n"
" --output-sources=/path/to/src output sources to directory \n"
" --output-include=/path/to/include output includes to directory\n"
" --refresh refresh code of target\n"
" --overwrite overwrite code on generation\n"
"\n"
"Supported targets:\n"
" 'c++' C++ target (.cpp,.hpp)\n"
" 'ruby-activerecord' ruby target (.rb)\n"
//" 'objc' Objective C (.m,.h)\n"
//" 'c' C target (.c,.h)\n"
//" 'haskell' Haskell target (.hs)\n"
//" 'sql' SQL schema of database (.sql)\n"
//" 'php' PHP target (.php)\n"
//" 'python' Python target (.py)\n"
" 'graphviz' Graphviz file (.dot)\n"
"\n\n"
;
struct options_t {
string output_dir;
string output_sources;
string output_includes;
bool refresh;
bool printHelp;
vector<string> targets;
};
options_t options = {"","","",true,false};
int parseArgs(int argc, char **argv)
{
if(argc==1)
return -1;
for (int i = 1; i < argc; i++) {
string arg = argv[i];
if (arg == "-v" || arg == "--verbose") {
Logger::verbose(true);
continue;
} else if (arg == "-t" || arg == "--target") {
if (i+1 >= argc) {
Logger::error("Error: missing target");
return -1;
}
options.targets.push_back(argv[i+1]);
i++;
continue;
} else if (litesql::startsWith(arg, "--target=")) {
litesql::Split lang(arg, "=");
options.targets.push_back(lang[1]);
continue;
} else if (litesql::startsWith(arg, "--output-dir")) {
litesql::Split lang(arg, "=");
options.output_dir=lang[1];
continue;
} else if (litesql::startsWith(arg, "--output-sources")) {
litesql::Split lang(arg, "=");
options.output_sources=lang[1];
continue;
} else if (litesql::startsWith(arg, "--output-include")) {
litesql::Split lang(arg, "=");
options.output_includes=lang[1];
continue;
}
else if (arg == "--help") {
options.printHelp = true;
continue;
} else if (i < argc - 1) {
Logger::error("Error: invalid argument "+ arg);
return -1;
}
}
return 0;
}
int generateCode(ObjectModel& model)
{
CompositeGenerator generator;
generator.setOutputDirectory(options.output_dir);
for (vector<string>::const_iterator target= options.targets.begin(); target!=options.targets.end();target++)
{
if (*target == "c++")
{
CppGenerator* pCppGen = new CppGenerator();
pCppGen->setOutputSourcesDirectory(options.output_sources);
pCppGen->setOutputIncludesDirectory(options.output_includes);
generator.add(pCppGen);
}
else if (*target == "graphviz")
{
generator.add(new GraphvizGenerator());
}
else if (*target == "ruby-activerecord")
{
generator.add(new RubyActiveRecordGenerator());
}
else
{
throw litesql::Except("unsupported target: " + *target);
}
}
return generator.generateCode(&model)? 0 : 1 ;
}
int main(int argc, char **argv) {
int rc = parseArgs(argc,argv);
if (rc!=0)
{
Logger::error(help);
return -1;
}
if (options.printHelp) {
cout << help << endl;
}
ObjectModel model;
try {
if (!model.loadFromFile(argv[argc-1]))
{
string msg = "could not load file '" + string(argv[argc-1]) + "'";
Logger::error(msg);
return -1;
}
else
{
return generateCode(model);
}
}
catch (Except e) {
Logger::error(e);
return -1;
}
}
<commit_msg>generic loop over registered codegenerators allows them all to be --target parameter<commit_after>#include "litesql.hpp"
#include "generator.hpp"
#include "litesql-gen-cpp.hpp"
#include "logger.hpp"
#include "objectmodel.hpp"
using namespace std;
using namespace litesql;
const char* help =
"Usage: litesql-gen [options] <my-database.xml>\n\n"
"Options:\n"
" -t, --target=TARGET generate code for TARGET (default: c++)\n"
" -v, --verbose verbosely report code generation\n"
" --help print help\n"
" -t, --target=TARGET generate code for TARGET (default: c++)\n"
" --output-dir=/path/to/src output all files to directory \n"
" --output-sources=/path/to/src output sources to directory \n"
" --output-include=/path/to/include output includes to directory\n"
" --refresh refresh code of target\n"
" --overwrite overwrite code on generation\n"
"\n"
"Supported targets:\n"
" 'c++' C++ target (.cpp,.hpp)\n"
" 'ruby-activerecord' ruby target (.rb)\n"
//" 'objc' Objective C (.m,.h)\n"
//" 'c' C target (.c,.h)\n"
//" 'haskell' Haskell target (.hs)\n"
//" 'sql' SQL schema of database (.sql)\n"
//" 'php' PHP target (.php)\n"
//" 'python' Python target (.py)\n"
" 'graphviz' Graphviz file (.dot)\n"
"\n\n"
;
struct options_t {
string output_dir;
string output_sources;
string output_includes;
bool refresh;
bool printHelp;
vector<string> targets;
};
options_t options = {"","","",true,false};
int parseArgs(int argc, char **argv)
{
if(argc==1)
return -1;
for (int i = 1; i < argc; i++) {
string arg = argv[i];
if (arg == "-v" || arg == "--verbose") {
Logger::verbose(true);
continue;
} else if (arg == "-t" || arg == "--target") {
if (i+1 >= argc) {
Logger::error("Error: missing target");
return -1;
}
options.targets.push_back(argv[i+1]);
i++;
continue;
} else if (litesql::startsWith(arg, "--target=")) {
litesql::Split lang(arg, "=");
options.targets.push_back(lang[1]);
continue;
} else if (litesql::startsWith(arg, "--output-dir")) {
litesql::Split lang(arg, "=");
options.output_dir=lang[1];
continue;
} else if (litesql::startsWith(arg, "--output-sources")) {
litesql::Split lang(arg, "=");
options.output_sources=lang[1];
continue;
} else if (litesql::startsWith(arg, "--output-include")) {
litesql::Split lang(arg, "=");
options.output_includes=lang[1];
continue;
}
else if (arg == "--help") {
options.printHelp = true;
continue;
} else if (i < argc - 1) {
Logger::error("Error: invalid argument "+ arg);
return -1;
}
}
return 0;
}
int generateCode(ObjectModel& model)
{
CompositeGenerator generator;
generator.setOutputDirectory(options.output_dir);
for (vector<string>::const_iterator target= options.targets.begin(); target!=options.targets.end();target++)
{
CodeGenerator* pGen = CodeGenerator::create(target->c_str());
if (!pGen)
{
throw litesql::Except("unsupported target: " + *target);
}
else
{
generator.add(pGen);
// special case for c++
CppGenerator* pCppGen= dynamic_cast<CppGenerator*>(pGen);
if (pCppGen)
{
pCppGen->setOutputSourcesDirectory(options.output_sources);
pCppGen->setOutputIncludesDirectory(options.output_includes);
}
}
}
return generator.generateCode(&model)? 0 : 1 ;
}
int main(int argc, char **argv) {
int rc = parseArgs(argc,argv);
if (rc!=0)
{
Logger::error(help);
return -1;
}
if (options.printHelp) {
cout << help << endl;
}
ObjectModel model;
try {
if (!model.loadFromFile(argv[argc-1]))
{
string msg = "could not load file '" + string(argv[argc-1]) + "'";
Logger::error(msg);
return -1;
}
else
{
return generateCode(model);
}
}
catch (Except e) {
Logger::error(e);
return -1;
}
}
<|endoftext|> |
<commit_before>#include <limits>
#include <type_traits>
#include "support.cuh"
namespace curng
{
namespace detail
{
__device__ inline
void sincos_(float aX, float* aSin, float* aCos)
{
sincosf(aX, aSin, aCos);
}
__device__ inline
void sincos_(double aX, double* aSin, double* aCos)
{
sincos(aX, aSin, aCos);
}
}
template< typename tReal > __device__ inline
NormalBoxMuller::Distribution<tReal>::Distribution( unsigned, NormalBoxMuller::GlobalData<tReal> const& )
: mCache( std::numeric_limits<tReal>::quiet_NaN() )
{}
template< typename tReal > template< class tRand, class tRandData > __device__ inline
auto NormalBoxMuller::Distribution<tReal>::operator() (tRand& aRng, unsigned aTid, GlobalData<tReal>&, tRandData& aEngData ) -> result_type
{
constexpr tReal pi2 = tReal(2)*tReal(3.14159265357989);
constexpr tReal eps = std::numeric_limits<tReal>::min();
constexpr std::size_t digits_ = std::numeric_limits<tReal>::digits;
if( !/*std::*/isnan( mCache ) )
{
auto ret = mCache;
mCache = std::numeric_limits<tReal>::quiet_NaN();
return ret;
}
tReal u1;
do
{
u1 = generate_canonical<tReal,digits_>( aRng, aTid, aEngData );
} while (u1 <= eps);
tReal const lu2 = std::sqrt(tReal(-2) * std::log(u1));
tReal u2 = generate_canonical<tReal,digits_>( aRng, aTid, aEngData );
tReal s, c;
detail::sincos_(pi2 * u2, &s, &c);
mCache = lu2 * s;
return lu2 * c;
}
template< typename tReal > __host__ inline
auto NormalBoxMuller::initialize( Identity<tReal>, std::size_t ) -> GlobalData<tReal>
{
return {};
}
template< typename tReal > __host__ inline
void NormalBoxMuller::cleanup( GlobalData<tReal>& )
{}
}
<commit_msg>µopt: use intrinsics when generating float normal dist<commit_after>#include <limits>
#include <type_traits>
#include "support.cuh"
namespace curng
{
namespace detail
{
__device__ inline
void sincos_(float aX, float* aSin, float* aCos)
{
//sincosf(aX, aSin, aCos);
__sincosf( aX, aSin, aCos );
}
__device__ inline
void sincos_(double aX, double* aSin, double* aCos)
{
sincos(aX, aSin, aCos);
}
__device__ inline
float log_( float aX )
{
//return logf( aX );
return __logf( aX );
}
__device__ inline
double log_( double aX )
{
return log( aX );
}
}
template< typename tReal > __device__ inline
NormalBoxMuller::Distribution<tReal>::Distribution( unsigned, NormalBoxMuller::GlobalData<tReal> const& )
: mCache( std::numeric_limits<tReal>::quiet_NaN() )
{}
template< typename tReal > template< class tRand, class tRandData > __device__ inline
auto NormalBoxMuller::Distribution<tReal>::operator() (tRand& aRng, unsigned aTid, GlobalData<tReal>&, tRandData& aEngData ) -> result_type
{
constexpr tReal pi2 = tReal(2)*tReal(3.14159265357989);
constexpr tReal eps = std::numeric_limits<tReal>::min();
constexpr std::size_t digits_ = std::numeric_limits<tReal>::digits;
if( !/*std::*/isnan( mCache ) )
{
auto ret = mCache;
mCache = std::numeric_limits<tReal>::quiet_NaN();
return ret;
}
tReal u1;
do
{
u1 = generate_canonical<tReal,digits_>( aRng, aTid, aEngData );
} while (u1 <= eps);
tReal const lu2 = std::sqrt(tReal(-2) * detail::log_(u1));
tReal const u2 = generate_canonical<tReal,digits_>( aRng, aTid, aEngData );
tReal s, c;
detail::sincos_(pi2 * u2, &s, &c);
mCache = lu2 * s;
return lu2 * c;
}
template< typename tReal > __host__ inline
auto NormalBoxMuller::initialize( Identity<tReal>, std::size_t ) -> GlobalData<tReal>
{
return {};
}
template< typename tReal > __host__ inline
void NormalBoxMuller::cleanup( GlobalData<tReal>& )
{}
}
<|endoftext|> |
<commit_before>#include <base/gl/Window.h>
#include <framework/TestRunner.h>
#include <tests/test1/BallsSceneTests.h>
#include <tests/test2/TerrainSceneTests.h>
#include <tests/test3/ShadowMappingSceneTests.h>
#include <iostream>
#include <stdexcept>
namespace framework {
TestRunner::TestRunner(base::ArgumentParser argumentParser)
: arguments(std::move(argumentParser))
{
}
int TestRunner::run()
{
const int TESTS = 3;
auto errorCallback = [&](const std::string& msg) -> int {
std::cerr << "Invalid usage! " << msg << std::endl;
std::cerr << "Usage: `" << arguments.getPath() << " -t T -api API [-m]`" << std::endl;
std::cerr << " -t T - test number (in range [1, " << TESTS << "])" << std::endl;
std::cerr << " -api API - API (`gl` or `vk`)" << std::endl;
std::cerr << " -m - run multithreaded version (if exists)" << std::endl;
return -1;
};
if (!arguments.hasArgument("t"))
return errorCallback("Missing `-t` argument!");
if (!arguments.hasArgument("api"))
return errorCallback("Missing `-api` argument!");
bool multithreaded = arguments.hasArgument("m");
int testNum = -1;
try {
testNum = arguments.getIntArgument("t");
} catch (...) {
// ignore, will fail with proper message later
}
if (testNum < 1 || testNum > TESTS)
return errorCallback("Invalid test number!");
std::string api = arguments.getArgument("api");
if (api != "gl" && api != "vk")
return errorCallback("Invalid `-api` value!");
if (api == "gl") {
return run_gl(testNum, multithreaded);
} else {
return run_vk(testNum, multithreaded);
}
}
int TestRunner::run_gl(int testNumber, bool multithreaded)
{
std::unique_ptr<TestInterface> test;
switch (testNumber) {
case 1:
if (multithreaded) {
test = std::unique_ptr<TestInterface>(new tests::test_gl::MultithreadedBallsSceneTest());
} else {
test = std::unique_ptr<TestInterface>(new tests::test_gl::SimpleBallsSceneTest());
}
break;
case 2:
if (multithreaded) {
// N/A
} else {
test = std::unique_ptr<TestInterface>(new tests::test_gl::TerrainSceneTest());
}
case 3:
if (multithreaded) {
// TODO:
} else {
test = std::unique_ptr<TestInterface>(new tests::test_gl::ShadowMappingSceneTest());
}
}
if (test) {
return run_any(std::move(test));
} else {
std::cerr << "Unknown OpenGL test: " << testNumber << std::endl;
return -1;
}
}
int TestRunner::run_vk(int testNumber, bool multithreaded)
{
std::unique_ptr<TestInterface> test;
switch (testNumber) {
case 1:
if (multithreaded) {
test = std::unique_ptr<TestInterface>(new tests::test_vk::MultithreadedBallsSceneTest());
} else {
test = std::unique_ptr<TestInterface>(new tests::test_vk::SimpleBallsSceneTest());
}
break;
case 2:
if (multithreaded) {
test = std::unique_ptr<TestInterface>(new tests::test_vk::MultithreadedTerrainSceneTest());
} else {
test = std::unique_ptr<TestInterface>(new tests::test_vk::TerrainSceneTest());
}
case 3:
if (multithreaded) {
// TODO:
} else {
test = std::unique_ptr<TestInterface>(new tests::test_vk::ShadowMappingSceneTest);
}
}
if (test) {
return run_any(std::move(test));
} else {
std::cerr << "Unknown Vulkan test: " << testNumber << std::endl;
return -1;
}
}
int TestRunner::run_any(std::unique_ptr<TestInterface> test)
{
try {
test->setup();
test->run();
test->teardown();
} catch (const std::runtime_error& exception) {
std::cerr << "Caught runtime exception during test execution!" << std::endl;
std::cerr << exception.what() << std::endl;
return -1;
} catch (const std::exception& exception) {
std::cerr << "Caught exception during test execution!" << std::endl;
std::cerr << exception.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Caught unknown exception during test execution!" << std::endl;
return -1;
}
return 0;
}
}
<commit_msg>Fixed bug in testrunner preventing to run second test.<commit_after>#include <base/gl/Window.h>
#include <framework/TestRunner.h>
#include <tests/test1/BallsSceneTests.h>
#include <tests/test2/TerrainSceneTests.h>
#include <tests/test3/ShadowMappingSceneTests.h>
#include <iostream>
#include <stdexcept>
namespace framework {
TestRunner::TestRunner(base::ArgumentParser argumentParser)
: arguments(std::move(argumentParser))
{
}
int TestRunner::run()
{
const int TESTS = 3;
auto errorCallback = [&](const std::string& msg) -> int {
std::cerr << "Invalid usage! " << msg << std::endl;
std::cerr << "Usage: `" << arguments.getPath() << " -t T -api API [-m]`" << std::endl;
std::cerr << " -t T - test number (in range [1, " << TESTS << "])" << std::endl;
std::cerr << " -api API - API (`gl` or `vk`)" << std::endl;
std::cerr << " -m - run multithreaded version (if exists)" << std::endl;
return -1;
};
if (!arguments.hasArgument("t"))
return errorCallback("Missing `-t` argument!");
if (!arguments.hasArgument("api"))
return errorCallback("Missing `-api` argument!");
bool multithreaded = arguments.hasArgument("m");
int testNum = -1;
try {
testNum = arguments.getIntArgument("t");
} catch (...) {
// ignore, will fail with proper message later
}
if (testNum < 1 || testNum > TESTS)
return errorCallback("Invalid test number!");
std::string api = arguments.getArgument("api");
if (api != "gl" && api != "vk")
return errorCallback("Invalid `-api` value!");
if (api == "gl") {
return run_gl(testNum, multithreaded);
} else {
return run_vk(testNum, multithreaded);
}
}
int TestRunner::run_gl(int testNumber, bool multithreaded)
{
std::unique_ptr<TestInterface> test;
switch (testNumber) {
case 1:
if (multithreaded) {
test = std::unique_ptr<TestInterface>(new tests::test_gl::MultithreadedBallsSceneTest());
} else {
test = std::unique_ptr<TestInterface>(new tests::test_gl::SimpleBallsSceneTest());
}
break;
case 2:
if (multithreaded) {
// N/A
} else {
test = std::unique_ptr<TestInterface>(new tests::test_gl::TerrainSceneTest());
}
break;
case 3:
if (multithreaded) {
// TODO:
} else {
test = std::unique_ptr<TestInterface>(new tests::test_gl::ShadowMappingSceneTest());
}
break;
}
if (test) {
return run_any(std::move(test));
} else {
std::cerr << "Unknown OpenGL test: " << testNumber << std::endl;
return -1;
}
}
int TestRunner::run_vk(int testNumber, bool multithreaded)
{
std::unique_ptr<TestInterface> test;
switch (testNumber) {
case 1:
if (multithreaded) {
test = std::unique_ptr<TestInterface>(new tests::test_vk::MultithreadedBallsSceneTest());
} else {
test = std::unique_ptr<TestInterface>(new tests::test_vk::SimpleBallsSceneTest());
}
break;
case 2:
if (multithreaded) {
test = std::unique_ptr<TestInterface>(new tests::test_vk::MultithreadedTerrainSceneTest());
} else {
test = std::unique_ptr<TestInterface>(new tests::test_vk::TerrainSceneTest());
}
break;
case 3:
if (multithreaded) {
// TODO:
} else {
test = std::unique_ptr<TestInterface>(new tests::test_vk::ShadowMappingSceneTest);
}
break;
}
if (test) {
return run_any(std::move(test));
} else {
std::cerr << "Unknown Vulkan test: " << testNumber << std::endl;
return -1;
}
}
int TestRunner::run_any(std::unique_ptr<TestInterface> test)
{
try {
test->setup();
test->run();
test->teardown();
} catch (const std::runtime_error& exception) {
std::cerr << "Caught runtime exception during test execution!" << std::endl;
std::cerr << exception.what() << std::endl;
return -1;
} catch (const std::exception& exception) {
std::cerr << "Caught exception during test execution!" << std::endl;
std::cerr << exception.what() << std::endl;
return -1;
} catch (...) {
std::cerr << "Caught unknown exception during test execution!" << std::endl;
return -1;
}
return 0;
}
}
<|endoftext|> |
<commit_before>#include <vector>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/PolygonStamped.h>
#include <geometry_msgs/Point32.h>
#include <visualization_msgs/MarkerArray.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/features/moment_of_inertia_estimation.h>
using namespace std;
ros::Publisher pub;
struct Plane {
pcl::PointXYZ min;
pcl::PointXYZ max;
};
void printROSPoint(geometry_msgs::Point *p) {
ROS_INFO("Point: %f %f %f", p->x, p->y, p->z);
}
void printPlane(struct Plane *plane) {
ROS_INFO("AABB: %f %f %f -> %f %f %f", plane->min.x, plane->min.y, plane->min.z, plane->max.x, plane->max.z,
plane->max.z);
}
void printPoint(pcl::PointXYZ *p) {
ROS_INFO("Point: %f %f %f", p->x, p->y, p->z);
}
void getAABB(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, struct Plane *plane) {
pcl::MomentOfInertiaEstimation<pcl::PointXYZ> feature_extractor;
feature_extractor.setInputCloud(cloud);
feature_extractor.compute();
feature_extractor.getAABB(plane->min, plane->max);
}
void buildRosMarker(visualization_msgs::Marker *marker, struct Plane *plane, unsigned int id) {
marker->header.frame_id = "base_link";
marker->header.stamp = ros::Time::now();
marker->ns = "hmmwv";
marker->id = id;
marker->type = visualization_msgs::Marker::LINE_STRIP;
marker->action = visualization_msgs::Marker::ADD;
marker->scale.x = 0.1f;
marker->color.r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
marker->color.g = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
marker->color.b = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
marker->color.a = 1.0;
marker->lifetime = ros::Duration();
geometry_msgs::Point p1;
p1.x = plane->min.z;
p1.y = plane->min.x * (-1);
p1.z = plane->min.y * (-1);
geometry_msgs::Point p2;
p2.x = plane->min.z;
p2.y = plane->max.x * (-1);
p2.z = plane->min.y * (-1);
geometry_msgs::Point p3;
p3.x = plane->min.z;
p3.y = plane->max.x * (-1);
p3.z = plane->max.y * (-1);
geometry_msgs::Point p4;
p4.x = plane->min.z;
p4.y = plane->min.x * (-1);
p4.z = plane->max.y * (-1);
marker->points.push_back(p1);
marker->points.push_back(p2);
marker->points.push_back(p3);
marker->points.push_back(p4);
marker->points.push_back(p1);
}
void callback(const sensor_msgs::PointCloud2ConstPtr& input) {
ROS_INFO("Callback!");
// convert from ros::pointcloud2 to pcl::pointcloud2
pcl::PCLPointCloud2* unfilteredCloud = new pcl::PCLPointCloud2;
pcl::PCLPointCloud2ConstPtr unfilteredCloudPtr(unfilteredCloud);
pcl_conversions::toPCL(*input, *unfilteredCloud);
// create a voxelgrid to downsample the input data to speed things up.
pcl::PCLPointCloud2::Ptr filteredCloud (new pcl::PCLPointCloud2);
pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
sor.setInputCloud(unfilteredCloudPtr);
sor.setLeafSize(0.01f, 0.01f, 0.01f);
sor.filter(*filteredCloud);
// convert to pointcloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2(*filteredCloud, *cloud);
// Does the parametric segmentation
pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
pcl::SACSegmentation<pcl::PointXYZ> seg;
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setMaxIterations(1000);
seg.setDistanceThreshold(0.01);
pcl::ExtractIndices<pcl::PointXYZ> extract;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>),
cloud2(new pcl::PointCloud<pcl::PointXYZ>);
unsigned int pointsAtStart = cloud->points.size(), id = 0;
std::vector<struct Plane> planes;
visualization_msgs::MarkerArray markerArray;
// while 30% of the original cloud is still present
while (cloud->points.size() > 0.3 * pointsAtStart) {
seg.setInputCloud(cloud);
seg.segment(*inliers, *coefficients);
if (inliers->indices.size() == 0) {
ROS_WARN("Could not estimate a planar model for the given dataset.");
break;
}
// extract the inliers
extract.setInputCloud(cloud);
extract.setIndices(inliers);
extract.setNegative(false);
extract.filter(*cloud1);
extract.setNegative(true);
extract.filter(*cloud2);
cloud.swap(cloud2);
// calculate AABB and add to planes list
struct Plane plane;
getAABB(cloud1, &plane);
printPlane(&plane);
visualization_msgs::Marker marker;
buildRosMarker(&marker, &plane, id);
markerArray.markers.push_back(marker);
id++;
}
pub.publish(markerArray);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "stairwaydetector");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe<sensor_msgs::PointCloud2>("/camera/depth/points", 1, callback);
pub = nh.advertise<visualization_msgs::MarkerArray>("/hmmwv/steps", 0);
ros::spin();
return 0;
}
<commit_msg>stairsdetection with PCL probably works.<commit_after>#include <vector>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <geometry_msgs/PolygonStamped.h>
#include <geometry_msgs/Point32.h>
#include <visualization_msgs/MarkerArray.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl_conversions/pcl_conversions.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/features/moment_of_inertia_estimation.h>
using namespace std;
ros::Publisher pub;
struct Plane {
pcl::PointXYZ min;
pcl::PointXYZ max;
};
void printROSPoint(geometry_msgs::Point *p) {
ROS_INFO("Point: %f %f %f", p->x, p->y, p->z);
}
void printPlane(struct Plane *plane) {
ROS_INFO("AABB: %f %f %f -> %f %f %f", plane->min.x, plane->min.y, plane->min.z, plane->max.x, plane->max.z,
plane->max.z);
}
void printPoint(pcl::PointXYZ *p) {
ROS_INFO("Point: %f %f %f", p->x, p->y, p->z);
}
void getAABB(pcl::PointCloud<pcl::PointXYZ>::Ptr cloud, struct Plane *plane) {
pcl::MomentOfInertiaEstimation<pcl::PointXYZ> feature_extractor;
feature_extractor.setInputCloud(cloud);
feature_extractor.compute();
feature_extractor.getAABB(plane->min, plane->max);
}
/**
* Transforms a point from PCL coordinate system to ROS coordinate system
*
* Documentation:
* ROS: http://wiki.ros.org/geometry/CoordinateFrameConventions
*/
void transformPCLPointToROSPoint(pcl::PointXYZ *input, geometry_msgs::Point *output) {
output->x = input->z;
output->y = input->x * (-1.f);
output->z = input->y * (-1.f);
}
void buildRosMarker(visualization_msgs::Marker *marker, struct Plane *plane, unsigned int id) {
marker->header.frame_id = "camera_link";
marker->header.stamp = ros::Time::now();
marker->ns = "hmmwv";
marker->id = id;
marker->lifetime = ros::Duration();
marker->type = visualization_msgs::Marker::LINE_STRIP;
marker->action = visualization_msgs::Marker::ADD;
marker->scale.x = 0.05f;
marker->color.r = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
marker->color.g = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
marker->color.b = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
marker->color.a = 1.0;
/*
* Get vertices of the rectangle and transform them to ROS coordinates
*
* p2-----------------p3
* | |
* | |
* p1-----------------p4
*
*/
geometry_msgs::Point p1;
transformPCLPointToROSPoint(&plane->min, &p1);
geometry_msgs::Point p2;
pcl::PointXYZ leftTop(plane->min.x, plane->max.y, plane->min.z);
transformPCLPointToROSPoint(&leftTop, &p2);
geometry_msgs::Point p3;
transformPCLPointToROSPoint(&plane->max, &p3);
geometry_msgs::Point p4;
pcl::PointXYZ rightBottom(plane->max.x, plane->min.y, plane->max.z);
transformPCLPointToROSPoint(&rightBottom, &p4);
marker->points.push_back(p1);
marker->points.push_back(p2);
marker->points.push_back(p3);
marker->points.push_back(p4);
marker->points.push_back(p1);
}
void callback(const sensor_msgs::PointCloud2ConstPtr& input) {
ROS_INFO("Callback!");
// convert from ros::pointcloud2 to pcl::pointcloud2
pcl::PCLPointCloud2* unfilteredCloud = new pcl::PCLPointCloud2;
pcl::PCLPointCloud2ConstPtr unfilteredCloudPtr(unfilteredCloud);
pcl_conversions::toPCL(*input, *unfilteredCloud);
// create a voxelgrid to downsample the input data to speed things up.
pcl::PCLPointCloud2::Ptr filteredCloud (new pcl::PCLPointCloud2);
pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
sor.setInputCloud(unfilteredCloudPtr);
sor.setLeafSize(0.01f, 0.01f, 0.01f);
sor.filter(*filteredCloud);
// convert to pointcloud
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);
pcl::fromPCLPointCloud2(*filteredCloud, *cloud);
// Does the parametric segmentation
pcl::ModelCoefficients::Ptr coefficients(new pcl::ModelCoefficients);
pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
pcl::SACSegmentation<pcl::PointXYZ> seg;
seg.setOptimizeCoefficients(true);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setModelType(pcl::SACMODEL_PLANE);
seg.setMaxIterations(1000);
seg.setDistanceThreshold(0.01);
pcl::ExtractIndices<pcl::PointXYZ> extract;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud1(new pcl::PointCloud<pcl::PointXYZ>),
cloud2(new pcl::PointCloud<pcl::PointXYZ>);
unsigned int pointsAtStart = cloud->points.size(), id = 0;
std::vector<struct Plane> planes;
visualization_msgs::MarkerArray markerArray;
// while 10% of the original cloud is still present
while (cloud->points.size() > 0.1 * pointsAtStart) {
seg.setInputCloud(cloud);
seg.segment(*inliers, *coefficients);
if (inliers->indices.size() == 0) {
ROS_WARN("Could not estimate a planar model for the given dataset.");
break;
}
// extract the inliers
extract.setInputCloud(cloud);
extract.setIndices(inliers);
extract.setNegative(false);
extract.filter(*cloud1);
extract.setNegative(true);
extract.filter(*cloud2);
cloud.swap(cloud2);
// calculate AABB and add to planes list
struct Plane plane;
getAABB(cloud1, &plane);
// calculate the height of the plane and remove planes with less than 5 cm or more than 40 cm
float height = plane.max.y - plane.min.y;
ROS_INFO("Height: %f", height);
if (height <= 0.4f && height >= 0.0f) {
visualization_msgs::Marker marker;
buildRosMarker(&marker, &plane, id);
markerArray.markers.push_back(marker);
}
id++;
}
pub.publish(markerArray);
}
int main(int argc, char **argv) {
ros::init(argc, argv, "stairwaydetector");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe<sensor_msgs::PointCloud2>("/camera/depth/points", 1, callback);
pub = nh.advertise<visualization_msgs::MarkerArray>("/hmmwv/steps", 0);
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>extern "C" {
#include <sys/uio.h>
#include <unistd.h>
}
#include "start_thread.h"
#include "tmd.h"
#include "incline_def_async_qtable.h"
#include "incline_driver_async_qtable.h"
#include "incline_mgr.h"
#include "incline_util.h"
using namespace std;
incline_def*
incline_driver_async_qtable::create_def() const
{
return new incline_def_async_qtable();
}
vector<string>
incline_driver_async_qtable::create_table_all(bool if_not_exists,
tmd::conn_t& dbh) const
{
vector<string> r;
for (std::vector<incline_def*>::const_iterator di = mgr_->defs().begin();
di != mgr_->defs().end();
++di) {
r.push_back(create_table_of(*di, if_not_exists, dbh));
}
return r;
}
vector<string>
incline_driver_async_qtable::drop_table_all(bool if_exists) const
{
vector<string> r;
for (std::vector<incline_def*>::const_iterator di = mgr_->defs().begin();
di != mgr_->defs().end();
++di) {
r.push_back(drop_table_of(*di, if_exists));
}
return r;
}
string
incline_driver_async_qtable::create_table_of(const incline_def* _def,
bool if_not_exists,
tmd::conn_t& dbh) const
{
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(_def);
assert(def != NULL);
return _create_table_of(def, def->queue_table(), if_not_exists, dbh);
}
string
incline_driver_async_qtable::drop_table_of(const incline_def* _def,
bool if_exists) const
{
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(_def);
assert(def != NULL);
return string("DROP TABLE ") + (if_exists ? "IF EXISTS " : "")
+ def->queue_table();
}
string
incline_driver_async_qtable::_create_table_of(const incline_def_async_qtable*
def,
const std::string& table_name,
bool if_not_exists,
tmd::conn_t& dbh) const
{
vector<string> col_defs;
for (map<string, string>::const_iterator ci = def->columns().begin();
ci != def->columns().end();
++ci) {
tmd::query_t res(dbh,
"SELECT UPPER(COLUMN_TYPE),CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s'",
tmd::escape(dbh, mgr_->db_name()).c_str(),
tmd::escape(dbh, def->destination()).c_str(),
tmd::escape(dbh, ci->second).c_str());
if (res.fetch().eof()) {
// TODO throw an exception instead
cerr << "failed to obtain column definition of: " << ci->first << endl;
exit(4);
}
col_defs.push_back(ci->second + ' ' + res.field(0));
if (res.field(1) != NULL) {
col_defs.back() += string(" CHARSET ") + res.field(1);
}
col_defs.back() += " NOT NULL";
}
return string("CREATE TABLE ") + (if_not_exists ? "IF NOT EXISTS " : "")
+ table_name
+ (" (_iq_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
" _iq_action CHAR(1) CHARACTER SET latin1 NOT NULL,")
+ incline_util::join(',', col_defs)
+ ",PRIMARY KEY (_iq_id)) ENGINE InnoDB";
}
vector<string>
incline_driver_async_qtable::do_build_enqueue_insert_sql(const incline_def*
_def,
const string&
src_table,
const string& command,
const vector<string>*
cond)
const
{
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(_def);
map<string, string> extra_columns;
extra_columns["_iq_action"] = "'R'";
string sql
= incline_driver_standalone::_build_insert_from_def(def, def->queue_table(),
src_table, command,
cond, &extra_columns);
return incline_util::vectorize(sql);
}
vector<string>
incline_driver_async_qtable::do_build_enqueue_delete_sql(const incline_def*
_def,
const string&
src_table,
const vector<string>*
_cond)
const
{
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(_def);
map<string, string> pk_columns;
for (map<string, string>::const_iterator pi = def->pk_columns().begin();
pi != def->pk_columns().end();
++pi) {
string src = pi->first;
if (incline_def::table_of_column(pi->first) == src_table) {
src = "OLD" + src.substr(src_table.size());
}
pk_columns[src] = pi->second;
}
vector<string> tables;
for (vector<string>::const_iterator si = def->source().begin();
si != def->source().end();
++si) {
if (*si != src_table && def->is_master_of(*si)) {
tables.push_back(*si);
}
}
vector<string> cond = def->build_merge_cond(src_table, "OLD", true);
if (_cond != NULL) {
incline_util::push_back(cond, *_cond);
}
string sql = "INSERT INTO " + def->queue_table() + " ("
+ incline_util::join(',', incline_util::filter("%2", pk_columns))
+ ",_iq_action) SELECT "
+ incline_util::join(',', incline_util::filter("%1", pk_columns))
+ ",'D'";
if (! tables.empty()) {
sql += " FROM " + incline_util::join(" INNER JOIN ", tables);
}
if (! cond.empty()){
sql += " WHERE " + incline_util::join(" AND ", cond);
}
return incline_util::vectorize(sql);
}
incline_driver_async_qtable::forwarder::forwarder(forwarder_mgr* mgr,
const
incline_def_async_qtable* def,
tmd::conn_t* dbh,
int poll_interval)
: mgr_(mgr), def_(def), dbh_(dbh), poll_interval_(poll_interval),
dest_pk_columns_(incline_util::filter("%2", def->pk_columns()))
{
fetch_query_base_ = "SELECT _iq_id,_iq_action,"
+ incline_util::join(',',
incline_util::filter("%2", def_->pk_columns()));
if (! def_->npk_columns().empty()) {
fetch_query_base_ += ','
+ incline_util::join(',',
incline_util::filter("%2",
def_->npk_columns()));
}
fetch_query_base_ += " FROM " + def_->queue_table() + ' ';
clear_queue_query_base_ = "DELETE FROM " + def_->queue_table()
+ " WHERE _iq_id IN ";
// build write queries
{
vector<string> dest_cols(incline_util::filter("%2", def->pk_columns()));
incline_util::push_back(dest_cols,
incline_util::filter("%2", def->npk_columns()));
replace_row_query_base_ =
"REPLACE INTO " + def->destination() + " ("
+ incline_util::join(',', dest_cols) + ") VALUES ";
}
delete_row_query_base_ = "DELETE FROM " + def->destination() + " WHERE ";
}
incline_driver_async_qtable::forwarder::~forwarder()
{
delete dbh_;
}
void* incline_driver_async_qtable::forwarder::run()
{
while (1) {
try {
vector<string> iq_ids;
vector<pair<char, vector<string> > > rows;
{ // fetch data
string query = fetch_query_base_;
string extra_cond = do_get_extra_cond();
if (! extra_cond.empty()) {
// TODO create and use index shard_key,_iq_id
query += " WHERE " + extra_cond;
}
query += " ORDER BY _iq_id LIMIT 50";
// load rows
for (tmd::query_t res(*dbh_, query);
! res.fetch().eof();
) {
iq_ids.push_back(res.field(0));
char action = res.field(1)[0];
rows.push_back(make_pair(action, vector<string>()));
for (size_t i = 0;
i < (action == 'R'
? def_->columns().size() : def_->pk_columns().size());
++i) {
rows.back().second.push_back(res.field(i + 2));
}
}
}
// sleep and retry if no data
if (rows.empty()) {
sleep(poll_interval_);
continue;
}
vector<const vector<string>*> replace_rows, delete_pks;
// fill replace_rows and delete_rows
for (vector<pair<char, vector<string> > >::const_reverse_iterator ri
= rows.rbegin();
ri != rows.rend();
++ri) {
for (vector<pair<char, vector<string> > >::const_reverse_iterator ci
= rows.rbegin();
ci != ri;
++ci) {
for (size_t i = 0; i < def_->pk_columns().size(); ++i) {
if (ri->second[i] != ci->second[i]) {
goto ROW_NOT_EQUAL;
}
}
goto EQ_ROW_FOUND;
ROW_NOT_EQUAL:
;
}
// row with same pk not exists, register it
switch (ri->first) {
case 'R': // replace
replace_rows.push_back(&ri->second);
break;
case 'D': // delete
delete_pks.push_back(&ri->second);
break;
default:
assert(0);
}
EQ_ROW_FOUND:
;
}
// update and remove from queue if successful
if (do_update_rows(replace_rows, delete_pks)) {
tmd::execute(*dbh_,
clear_queue_query_base_ + '('
+ incline_util::join(',', iq_ids) + ')');
}
} catch (tmd::error_t& e) {
switch (e.mysql_errno()) {
case ER_LOCK_DEADLOCK:
case ER_LOCK_WAIT_TIMEOUT:
// just retry
break;
default:
throw;
}
}
}
return NULL;
}
bool
incline_driver_async_qtable::forwarder::do_update_rows(const vector<const vector<string>*>& replace_rows, const vector<const vector<string>*>& delete_rows)
{
if (! replace_rows.empty()) {
this->replace_rows(*dbh_, replace_rows);
}
if (! delete_rows.empty()) {
this->delete_rows(*dbh_, delete_rows);
}
return true;
}
string
incline_driver_async_qtable::forwarder::do_get_extra_cond()
{
return string();
}
void
incline_driver_async_qtable::forwarder::replace_rows(tmd::conn_t& dbh,
const vector<const vector<string>*>& rows) const
{
string sql = replace_row_query_base_ + '(';
for (vector<const vector<string>*>::const_iterator ri = rows.begin();
ri != rows.end();
++ri) {
for (vector<string>::const_iterator ci = (*ri)->begin();
ci != (*ri)->end();
++ci) {
sql.push_back('\'');
sql += tmd::escape(dbh, *ci);
sql += "',";
}
sql.erase(sql.size() - 1);
sql += "),(";
}
sql.erase(sql.size() - 2);
mgr_->log_sql(sql);
tmd::execute(dbh, sql);
}
void
incline_driver_async_qtable::forwarder::delete_rows(tmd::conn_t& dbh,
const vector<const vector<string>*>& pk_rows) const
{
vector<string> conds;
for (vector<const vector<string>*>::const_iterator pi = pk_rows.begin();
pi != pk_rows.end();
++pi) {
conds.push_back("(" + _build_pk_cond(dbh, dest_pk_columns_, **pi) + ')');
}
string sql = delete_row_query_base_ + incline_util::join(" OR ", conds);
mgr_->log_sql(sql);
tmd::execute(dbh, sql);
}
string
incline_driver_async_qtable::forwarder::_build_pk_cond(tmd::conn_t& dbh,
const vector<string>&
colnames,
const vector<string>&
rows)
{
assert(colnames.size() == rows.size());
vector<string> cond;
for (size_t i = 0; i < rows.size(); ++i) {
cond.push_back(colnames[i] + "='" + tmd::escape(dbh, rows[i]) + '\'');
}
return incline_util::join(" AND ", cond);
}
void*
incline_driver_async_qtable::forwarder_mgr::run()
{
vector<pthread_t> threads;
{ // create and start forwarders
const vector<incline_def*>& defs = driver()->mgr()->defs();
for (vector<incline_def*>::const_iterator di = defs.begin();
di != defs.end();
++di) {
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(*di);
assert(def != NULL);
threads.push_back(start_thread(do_create_forwarder(def)));
}
}
// loop
while (! threads.empty()) {
pthread_join(threads.back(), NULL);
threads.pop_back();
}
return NULL;
}
void
incline_driver_async_qtable::forwarder_mgr::log_sql(const string& sql)
{
if (log_fd_ != -1) {
struct iovec vec[2];
vec[0].iov_base = const_cast<char*>(sql.c_str());
vec[0].iov_len = sql.size();
vec[1].iov_base = const_cast<char*>(";\n");
vec[1].iov_len = 2;
writev(log_fd_, vec, 2);
}
}
incline_driver_async_qtable::forwarder*
incline_driver_async_qtable::forwarder_mgr::do_create_forwarder(const incline_def_async_qtable* def)
{
tmd::conn_t* dbh = (*connect_)(src_host_.c_str(), src_port_);
assert(dbh != NULL);
return new forwarder(this, def, dbh, poll_interval_);
}
<commit_msg>proper handling of disconn. of shards (untested)<commit_after>extern "C" {
#include <sys/uio.h>
#include <unistd.h>
}
#include "start_thread.h"
#include "tmd.h"
#include "incline_def_async_qtable.h"
#include "incline_driver_async_qtable.h"
#include "incline_mgr.h"
#include "incline_util.h"
using namespace std;
incline_def*
incline_driver_async_qtable::create_def() const
{
return new incline_def_async_qtable();
}
vector<string>
incline_driver_async_qtable::create_table_all(bool if_not_exists,
tmd::conn_t& dbh) const
{
vector<string> r;
for (std::vector<incline_def*>::const_iterator di = mgr_->defs().begin();
di != mgr_->defs().end();
++di) {
r.push_back(create_table_of(*di, if_not_exists, dbh));
}
return r;
}
vector<string>
incline_driver_async_qtable::drop_table_all(bool if_exists) const
{
vector<string> r;
for (std::vector<incline_def*>::const_iterator di = mgr_->defs().begin();
di != mgr_->defs().end();
++di) {
r.push_back(drop_table_of(*di, if_exists));
}
return r;
}
string
incline_driver_async_qtable::create_table_of(const incline_def* _def,
bool if_not_exists,
tmd::conn_t& dbh) const
{
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(_def);
assert(def != NULL);
return _create_table_of(def, def->queue_table(), if_not_exists, dbh);
}
string
incline_driver_async_qtable::drop_table_of(const incline_def* _def,
bool if_exists) const
{
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(_def);
assert(def != NULL);
return string("DROP TABLE ") + (if_exists ? "IF EXISTS " : "")
+ def->queue_table();
}
string
incline_driver_async_qtable::_create_table_of(const incline_def_async_qtable*
def,
const std::string& table_name,
bool if_not_exists,
tmd::conn_t& dbh) const
{
vector<string> col_defs;
for (map<string, string>::const_iterator ci = def->columns().begin();
ci != def->columns().end();
++ci) {
tmd::query_t res(dbh,
"SELECT UPPER(COLUMN_TYPE),CHARACTER_SET_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s'",
tmd::escape(dbh, mgr_->db_name()).c_str(),
tmd::escape(dbh, def->destination()).c_str(),
tmd::escape(dbh, ci->second).c_str());
if (res.fetch().eof()) {
// TODO throw an exception instead
cerr << "failed to obtain column definition of: " << ci->first << endl;
exit(4);
}
col_defs.push_back(ci->second + ' ' + res.field(0));
if (res.field(1) != NULL) {
col_defs.back() += string(" CHARSET ") + res.field(1);
}
col_defs.back() += " NOT NULL";
}
return string("CREATE TABLE ") + (if_not_exists ? "IF NOT EXISTS " : "")
+ table_name
+ (" (_iq_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,"
" _iq_action CHAR(1) CHARACTER SET latin1 NOT NULL,")
+ incline_util::join(',', col_defs)
+ ",PRIMARY KEY (_iq_id)) ENGINE InnoDB";
}
vector<string>
incline_driver_async_qtable::do_build_enqueue_insert_sql(const incline_def*
_def,
const string&
src_table,
const string& command,
const vector<string>*
cond)
const
{
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(_def);
map<string, string> extra_columns;
extra_columns["_iq_action"] = "'R'";
string sql
= incline_driver_standalone::_build_insert_from_def(def, def->queue_table(),
src_table, command,
cond, &extra_columns);
return incline_util::vectorize(sql);
}
vector<string>
incline_driver_async_qtable::do_build_enqueue_delete_sql(const incline_def*
_def,
const string&
src_table,
const vector<string>*
_cond)
const
{
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(_def);
map<string, string> pk_columns;
for (map<string, string>::const_iterator pi = def->pk_columns().begin();
pi != def->pk_columns().end();
++pi) {
string src = pi->first;
if (incline_def::table_of_column(pi->first) == src_table) {
src = "OLD" + src.substr(src_table.size());
}
pk_columns[src] = pi->second;
}
vector<string> tables;
for (vector<string>::const_iterator si = def->source().begin();
si != def->source().end();
++si) {
if (*si != src_table && def->is_master_of(*si)) {
tables.push_back(*si);
}
}
vector<string> cond = def->build_merge_cond(src_table, "OLD", true);
if (_cond != NULL) {
incline_util::push_back(cond, *_cond);
}
string sql = "INSERT INTO " + def->queue_table() + " ("
+ incline_util::join(',', incline_util::filter("%2", pk_columns))
+ ",_iq_action) SELECT "
+ incline_util::join(',', incline_util::filter("%1", pk_columns))
+ ",'D'";
if (! tables.empty()) {
sql += " FROM " + incline_util::join(" INNER JOIN ", tables);
}
if (! cond.empty()){
sql += " WHERE " + incline_util::join(" AND ", cond);
}
return incline_util::vectorize(sql);
}
incline_driver_async_qtable::forwarder::forwarder(forwarder_mgr* mgr,
const
incline_def_async_qtable* def,
tmd::conn_t* dbh,
int poll_interval)
: mgr_(mgr), def_(def), dbh_(dbh), poll_interval_(poll_interval),
dest_pk_columns_(incline_util::filter("%2", def->pk_columns()))
{
fetch_query_base_ = "SELECT _iq_id,_iq_action,"
+ incline_util::join(',',
incline_util::filter("%2", def_->pk_columns()));
if (! def_->npk_columns().empty()) {
fetch_query_base_ += ','
+ incline_util::join(',',
incline_util::filter("%2",
def_->npk_columns()));
}
fetch_query_base_ += " FROM " + def_->queue_table() + ' ';
clear_queue_query_base_ = "DELETE FROM " + def_->queue_table()
+ " WHERE _iq_id IN ";
// build write queries
{
vector<string> dest_cols(incline_util::filter("%2", def->pk_columns()));
incline_util::push_back(dest_cols,
incline_util::filter("%2", def->npk_columns()));
replace_row_query_base_ =
"REPLACE INTO " + def->destination() + " ("
+ incline_util::join(',', dest_cols) + ") VALUES ";
}
delete_row_query_base_ = "DELETE FROM " + def->destination() + " WHERE ";
}
incline_driver_async_qtable::forwarder::~forwarder()
{
delete dbh_;
}
void* incline_driver_async_qtable::forwarder::run()
{
string extra_cond, last_id;
while (1) {
try {
vector<string> iq_ids;
vector<pair<char, vector<string> > > rows;
{ // update fetch state
string new_extra_cond = do_get_extra_cond();
if (extra_cond != new_extra_cond) {
extra_cond = new_extra_cond;
last_id.clear();
}
}
{ // fetch data
string query = fetch_query_base_;
if (! extra_cond.empty()) {
// TODO create and use index shard_key,_iq_id
query += " WHERE " + extra_cond;
if (! last_id.empty()) {
query += " AND _iq_id>" + last_id;
}
}
query += " ORDER BY _iq_id LIMIT 50";
// load rows
for (tmd::query_t res(*dbh_, query);
! res.fetch().eof();
) {
iq_ids.push_back(res.field(0));
char action = res.field(1)[0];
rows.push_back(make_pair(action, vector<string>()));
for (size_t i = 0;
i < (action == 'R'
? def_->columns().size() : def_->pk_columns().size());
++i) {
rows.back().second.push_back(res.field(i + 2));
}
}
}
// sleep and retry if no data
if (rows.empty()) {
sleep(poll_interval_);
continue;
}
if (! extra_cond.empty()) {
last_id = iq_ids.back();
}
vector<const vector<string>*> replace_rows, delete_pks;
// fill replace_rows and delete_rows
for (vector<pair<char, vector<string> > >::const_reverse_iterator ri
= rows.rbegin();
ri != rows.rend();
++ri) {
for (vector<pair<char, vector<string> > >::const_reverse_iterator ci
= rows.rbegin();
ci != ri;
++ci) {
for (size_t i = 0; i < def_->pk_columns().size(); ++i) {
if (ri->second[i] != ci->second[i]) {
goto ROW_NOT_EQUAL;
}
}
goto EQ_ROW_FOUND;
ROW_NOT_EQUAL:
;
}
// row with same pk not exists, register it
switch (ri->first) {
case 'R': // replace
replace_rows.push_back(&ri->second);
break;
case 'D': // delete
delete_pks.push_back(&ri->second);
break;
default:
assert(0);
}
EQ_ROW_FOUND:
;
}
// update and remove from queue if successful
if (do_update_rows(replace_rows, delete_pks)) {
tmd::execute(*dbh_,
clear_queue_query_base_ + '('
+ incline_util::join(',', iq_ids) + ')');
}
} catch (tmd::error_t& e) {
switch (e.mysql_errno()) {
case ER_LOCK_DEADLOCK:
case ER_LOCK_WAIT_TIMEOUT:
// just retry
break;
default:
throw;
}
}
}
return NULL;
}
bool
incline_driver_async_qtable::forwarder::do_update_rows(const vector<const vector<string>*>& replace_rows, const vector<const vector<string>*>& delete_rows)
{
if (! replace_rows.empty()) {
this->replace_rows(*dbh_, replace_rows);
}
if (! delete_rows.empty()) {
this->delete_rows(*dbh_, delete_rows);
}
return true;
}
string
incline_driver_async_qtable::forwarder::do_get_extra_cond()
{
return string();
}
void
incline_driver_async_qtable::forwarder::replace_rows(tmd::conn_t& dbh,
const vector<const vector<string>*>& rows) const
{
string sql = replace_row_query_base_ + '(';
for (vector<const vector<string>*>::const_iterator ri = rows.begin();
ri != rows.end();
++ri) {
for (vector<string>::const_iterator ci = (*ri)->begin();
ci != (*ri)->end();
++ci) {
sql.push_back('\'');
sql += tmd::escape(dbh, *ci);
sql += "',";
}
sql.erase(sql.size() - 1);
sql += "),(";
}
sql.erase(sql.size() - 2);
mgr_->log_sql(sql);
tmd::execute(dbh, sql);
}
void
incline_driver_async_qtable::forwarder::delete_rows(tmd::conn_t& dbh,
const vector<const vector<string>*>& pk_rows) const
{
vector<string> conds;
for (vector<const vector<string>*>::const_iterator pi = pk_rows.begin();
pi != pk_rows.end();
++pi) {
conds.push_back("(" + _build_pk_cond(dbh, dest_pk_columns_, **pi) + ')');
}
string sql = delete_row_query_base_ + incline_util::join(" OR ", conds);
mgr_->log_sql(sql);
tmd::execute(dbh, sql);
}
string
incline_driver_async_qtable::forwarder::_build_pk_cond(tmd::conn_t& dbh,
const vector<string>&
colnames,
const vector<string>&
rows)
{
assert(colnames.size() == rows.size());
vector<string> cond;
for (size_t i = 0; i < rows.size(); ++i) {
cond.push_back(colnames[i] + "='" + tmd::escape(dbh, rows[i]) + '\'');
}
return incline_util::join(" AND ", cond);
}
void*
incline_driver_async_qtable::forwarder_mgr::run()
{
vector<pthread_t> threads;
{ // create and start forwarders
const vector<incline_def*>& defs = driver()->mgr()->defs();
for (vector<incline_def*>::const_iterator di = defs.begin();
di != defs.end();
++di) {
const incline_def_async_qtable* def
= dynamic_cast<const incline_def_async_qtable*>(*di);
assert(def != NULL);
threads.push_back(start_thread(do_create_forwarder(def)));
}
}
// loop
while (! threads.empty()) {
pthread_join(threads.back(), NULL);
threads.pop_back();
}
return NULL;
}
void
incline_driver_async_qtable::forwarder_mgr::log_sql(const string& sql)
{
if (log_fd_ != -1) {
struct iovec vec[2];
vec[0].iov_base = const_cast<char*>(sql.c_str());
vec[0].iov_len = sql.size();
vec[1].iov_base = const_cast<char*>(";\n");
vec[1].iov_len = 2;
writev(log_fd_, vec, 2);
}
}
incline_driver_async_qtable::forwarder*
incline_driver_async_qtable::forwarder_mgr::do_create_forwarder(const incline_def_async_qtable* def)
{
tmd::conn_t* dbh = (*connect_)(src_host_.c_str(), src_port_);
assert(dbh != NULL);
return new forwarder(this, def, dbh, poll_interval_);
}
<|endoftext|> |
<commit_before>// This utility will act as an aid in order to identify the position of the cameras and generates two files: and automatically generate
// 1- A ROS launch file which can be used to start all the ROS video streams
// 2-
#include <string>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <tinyxml.h>
#include <openni2/OpenNI.h>
#include "openni2_camera/openni2_driver.h"
#include "openni2_camera/openni2_device_manager.h"
#include "openni2_camera/openni2_exception.h"
#include <openni2_camera/openni2_device.h>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// OpenCV stuff
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
// OpenCV to ROS stuff
#include <cv_bridge/cv_bridge.h>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
using namespace std;
using openni2_wrapper::OpenNI2DeviceManager;
using openni2_wrapper::OpenNI2DeviceInfo;
using openni2_wrapper::OpenNI2Exception;
openni2_wrapper::OpenNI2DeviceManager manager;
void newColorFrameCallback(sensor_msgs::ImagePtr image); // Get the images from the OpenNI2 stream
// Global flag stuff... the demon is inside hahahaha
int img_num = 0;
bool wait = false;
int max_wait = 10; // Maximum wait time in seconds
string device_id; // ID of the current camera
int data_skip = 0; // Data skip values
struct device_info {
string camera_name;
string serial;
string vendor_id;
string product_id;
string location;
string toString() const {
ostringstream os;
os << "Camera name: " << camera_name << "\n";
os << "Vendor ID: " << vendor_id << "\n";
os << "Product ID: " << product_id<< "\n";
os << "Serial: " << serial << "\n";
os << "Location: " << location << "\n";
return os.str();
}
};
vector <device_info> getCamerasInfo();
bool saveLaunchFile(const string& s, const vector <device_info> &cameras, const string &input_file);
void getDefaultParametersFromLaunchFile(const std::string &launch_file, TiXmlElement *launch_element);
bool saveUdevRules(const string &s, const vector <device_info> &cameras);
// Translates the URI of the device into a path: /dev/bus/usb/...
string getUsbLocation(const string &device_uri);
string getSerialNumber(const string &device_location);
void addArgumentTags(TiXmlElement& elem_add, const TiXmlElement& elem_source);
int main (int argc, char **argv) {
if (argc < 3) {
cerr << "Usage: " << argv[0] << " <launch_filename> <input_filename> [<data_skip>]\n";
return -1;
}
if (argc >=3) {
data_skip = atoi(argv[3]);
}
const std::string window_name = "image_show";
cv::namedWindow(window_name, cv::WINDOW_AUTOSIZE ); // Create a window for display.
vector<device_info> camera_names = getCamerasInfo(); // Save the camera names
if (camera_names.size() > 0) {
cout << "Detected " << camera_names.size() << " cameras. Info:\n";
for (uint i = 0; i < camera_names.size(); i++) {
cout << camera_names.at(i).toString();
}
cout << "Saving launch file.\n";
if (saveLaunchFile(string(argv[1]), camera_names, string(argv[2]))) {
cout << "Launch file saved successfully.\n";
}
}
cv::destroyWindow("image_show");
return 0;
}
// Uses tinyxml to generate a launch file with
bool saveLaunchFile(const string &s, const vector<device_info> &camera_info_vec, const string &input_file) {
bool ret_val = true;
// Create document
TiXmlDocument doc;
TiXmlDeclaration decl( "1.0", "", "" );
doc.InsertEndChild( decl );
// Create root launch node
TiXmlElement launch_element("launch");
getDefaultParametersFromLaunchFile(input_file, &launch_element);
TiXmlElement *arg_skip_tag = new TiXmlElement("arg");
arg_skip_tag->SetAttribute("name", "data_skip");
arg_skip_tag->SetAttribute("default", data_skip);
launch_element.LinkEndChild(arg_skip_tag);
for (int i = 0; i < camera_info_vec.size(); i++) {
const device_info &curr_cam = camera_info_vec.at(i);
TiXmlElement *include_elem = new TiXmlElement("include");
// File attribute: the default launch file of openni2
include_elem->SetAttribute("file", "$(find openni2_launch)/launch/openni2.launch");
// Tag argument 1: device_id
TiXmlElement *arg_tag = new TiXmlElement("arg");
arg_tag->SetAttribute("name", "device_id");
arg_tag->SetAttribute("value", curr_cam.serial);
include_elem->LinkEndChild(arg_tag);
// Second tag --> argument name of the camera
arg_tag = new TiXmlElement("arg");
arg_tag->SetAttribute("name", "camera");
arg_tag->SetAttribute("value", curr_cam.camera_name);
include_elem->LinkEndChild(arg_tag);
TiXmlElement *param_tag = new TiXmlElement("param");
string s("/");
s.append(curr_cam.camera_name);
s.append("/driver/data_skip");
param_tag->SetAttribute("name", s);
param_tag->SetAttribute("value", "$(arg data_skip)");
include_elem->LinkEndChild(param_tag);
addArgumentTags(*include_elem, launch_element);
launch_element.LinkEndChild(include_elem);
}
doc.InsertEndChild(launch_element);
doc.SaveFile(s);
return ret_val;
}
vector<device_info> getCamerasInfo()
{
vector<device_info> ret_val;
// Get the connected OpenNI2 devices
boost::shared_ptr<std::vector<openni2_wrapper::OpenNI2DeviceInfo> > device_infos = manager.getConnectedDeviceInfos();
std::cout << "Found " << device_infos->size() << " devices:" << std::endl;
// Iterate over the devices, asking the user for labels and generating the proper include tag
for (size_t i = 0; i < device_infos->size(); ++i)
{
openni2_wrapper::OpenNI2DeviceInfo &info = device_infos->at(i);
device_info camera_info;
ostringstream os, os2;
os << "camera_" << i;
std::string camera_label(os.str());
os2 << "#" << i + 1;
device_id = os2.str();
cout << "Showing the RGB image associated with camera " << device_id << endl;
try {
img_num = 0;
wait = true;
boost::shared_ptr<openni2_wrapper::OpenNI2Device> device = manager.getDevice(info.uri_);
if (device->hasColorSensor()) {
device->setColorFrameCallback(newColorFrameCallback);
device->startColorStream();
}
int cont = 0;
// Wait for the image to be shown and a key pressed
while (wait && cont < max_wait) {
cont++;
sleep(1);
}
if (wait) {
// No image has been found
cerr << "Warning: Could not retrieve image from camera " << device_id << ". Setting the label to camera_" << i + 1 << endl;
wait = false;
} else {
cout << "Please enter the label for camera " << device_id << endl;
getline(cin, camera_label);
}
// Save the camera info
camera_info.camera_name = camera_label;
std::ostringstream product_id, vendor_id;
product_id << std::hex << setfill('0') << setw(4) << info.product_id_;
camera_info.product_id = product_id.str();
vendor_id << std::hex << setfill('0') << setw(4) << std::hex << info.vendor_id_;
camera_info.vendor_id = vendor_id.str();
camera_info.location = getUsbLocation(info.uri_);
camera_info.serial = manager.getSerial(info.uri_);
ret_val.push_back(camera_info);
} catch (exception &e) {
cerr << "Exception thrown while managing camera " << device_id << ". Content: " << e.what() << endl;
}
}
return ret_val;
}
// Get the accepted arguments and their default values from another launch file (typically openni2_launch/launch/openni2.launch)
void getDefaultParametersFromLaunchFile(const std::string &launch_file, TiXmlElement *launch_element) {
// Load the file where the default parameters will be stored
TiXmlDocument doc(launch_file);
doc.LoadFile();
TiXmlElement *root = doc.RootElement();
if (!root) {
cerr << "Could not get the launch file.\n";
return;
}
// Iterate over the children and copy the argument data
TiXmlNode *it = root->FirstChild();
while (it) {
if (it->ValueStr() == "arg" && it->ToElement()) {
string name(it->ToElement()->Attribute("name"));
// Discard undesired tags
if (name != "camera" && name != "rgb_frame_id" && name != "device_id" && name != "rgb_frame_id" && name != "depth_frame_id" && name != "depth_camera_info_url" &&
name != "rgb_camera_info_url")
{
TiXmlElement *node = new TiXmlElement("arg");
node->SetAttribute("name", it->ToElement()->Attribute("name"));
node->SetAttribute("default", it->ToElement()->Attribute("default"));
if (it->ToElement()->Attribute("if")) {
node->SetAttribute("if", it->ToElement()->Attribute("if"));
} else if (it->ToElement()->Attribute("unless")) {
node->SetAttribute("unless", it->ToElement()->Attribute("unless"));
}
launch_element->LinkEndChild(node);
}
}
// Next getXmlCameraElement
it = root->IterateChildren(it);
}
}
void newColorFrameCallback(sensor_msgs::ImagePtr image)
{
if (img_num == 0 && wait) {
img_num++;
cv_bridge::CvImagePtr img_cv = cv_bridge::toCvCopy(image, "bgr8");
ostringstream os;
os << "Camera " << device_id;
cv::imshow("image_show", img_cv.get()->image ); // Show our image inside it.
cv::updateWindow ("image_show");
cv::startWindowThread();
cv::waitKey(0); // Wait for a key to be pressed in the window
wait = false;
}
}
string getUsbLocation(const string& device_uri)
{
string ret = "/dev/bus/usb/";
int i;
string bus_device = device_uri.substr(device_uri.find('@') + 1, device_uri.size());
istringstream bus_is (bus_device.substr(0, bus_device.find('/')));
bus_is >> i;
ostringstream bus_id;
bus_id << setfill('0') << setw(3) << i;
istringstream is (bus_device.substr(bus_device.find('/') + 1, bus_device.size()));
is >> i;
ostringstream device_id;
device_id << setfill('0') << setw(3) << i;
ret.append(bus_id.str());
ret.append("/");
ret.append(device_id.str());
return ret;
}
void addArgumentTags(TiXmlElement& elem_add, const TiXmlElement& elem_source)
{
// Iterate over the children and copy the argument data
const TiXmlNode *it = elem_source.FirstChild();
while (it) {
if (it->ValueStr() == "arg" && it->ToElement() && static_cast<string>(it->ToElement()->Attribute("name")) != "device_id") {
TiXmlElement *node = new TiXmlElement("arg");
node->SetAttribute("name", it->ToElement()->Attribute("name"));
ostringstream os;
os << "$(arg " << it->ToElement()->Attribute("name") << ")";
node->SetAttribute("value", os.str());
elem_add.LinkEndChild(node);
}
// Next getXmlCameraElement
it = elem_source.IterateChildren(it);
}
}
<commit_msg>Added a subtle documentation on data skip<commit_after>// This utility will act as an aid in order to identify the position of the cameras and generates two files: and automatically generate
// 1- A ROS launch file which can be used to start all the ROS video streams
// 2-
#include <string>
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <tinyxml.h>
#include <openni2/OpenNI.h>
#include "openni2_camera/openni2_driver.h"
#include "openni2_camera/openni2_device_manager.h"
#include "openni2_camera/openni2_exception.h"
#include <openni2_camera/openni2_device.h>
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
// OpenCV stuff
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
// OpenCV to ROS stuff
#include <cv_bridge/cv_bridge.h>
#include <boost/shared_ptr.hpp>
#include <boost/concept_check.hpp>
using namespace std;
using openni2_wrapper::OpenNI2DeviceManager;
using openni2_wrapper::OpenNI2DeviceInfo;
using openni2_wrapper::OpenNI2Exception;
openni2_wrapper::OpenNI2DeviceManager manager;
void newColorFrameCallback(sensor_msgs::ImagePtr image); // Get the images from the OpenNI2 stream
// Global flag stuff... the demon is inside hahahaha
int img_num = 0;
bool wait = false;
int max_wait = 10; // Maximum wait time in seconds
string device_id; // ID of the current camera
int data_skip = 0; // Data skip values
struct device_info {
string camera_name;
string serial;
string vendor_id;
string product_id;
string location;
string toString() const {
ostringstream os;
os << "Camera name: " << camera_name << "\n";
os << "Vendor ID: " << vendor_id << "\n";
os << "Product ID: " << product_id<< "\n";
os << "Serial: " << serial << "\n";
os << "Location: " << location << "\n";
return os.str();
}
};
vector <device_info> getCamerasInfo();
bool saveLaunchFile(const string& s, const vector <device_info> &cameras, const string &input_file);
void getDefaultParametersFromLaunchFile(const std::string &launch_file, TiXmlElement *launch_element);
bool saveUdevRules(const string &s, const vector <device_info> &cameras);
// Translates the URI of the device into a path: /dev/bus/usb/...
string getUsbLocation(const string &device_uri);
string getSerialNumber(const string &device_location);
void addArgumentTags(TiXmlElement& elem_add, const TiXmlElement& elem_source);
int main (int argc, char **argv) {
if (argc < 3) {
cerr << "Usage: " << argv[0] << " <launch_filename> <input_filename> [<data_skip>]\n";
cerr << "Data skip means the number of frames necessary in order to publish one. I.e. data skip = 3 will publish 1 image of each 3 received\n";
return -1;
}
if (argc >=3) {
data_skip = atoi(argv[3]);
}
const std::string window_name = "image_show";
cv::namedWindow(window_name, cv::WINDOW_AUTOSIZE ); // Create a window for display.
vector<device_info> camera_names = getCamerasInfo(); // Save the camera names
if (camera_names.size() > 0) {
cout << "Detected " << camera_names.size() << " cameras. Info:\n";
for (uint i = 0; i < camera_names.size(); i++) {
cout << camera_names.at(i).toString();
}
cout << "Saving launch file.\n";
if (saveLaunchFile(string(argv[1]), camera_names, string(argv[2]))) {
cout << "Launch file saved successfully.\n";
}
}
cv::destroyWindow("image_show");
return 0;
}
// Uses tinyxml to generate a launch file with
bool saveLaunchFile(const string &s, const vector<device_info> &camera_info_vec, const string &input_file) {
bool ret_val = true;
// Create document
TiXmlDocument doc;
TiXmlDeclaration decl( "1.0", "", "" );
doc.InsertEndChild( decl );
// Create root launch node
TiXmlElement launch_element("launch");
getDefaultParametersFromLaunchFile(input_file, &launch_element);
TiXmlElement *arg_skip_tag = new TiXmlElement("arg");
arg_skip_tag->SetAttribute("name", "data_skip");
arg_skip_tag->SetAttribute("default", data_skip);
launch_element.LinkEndChild(arg_skip_tag);
for (int i = 0; i < camera_info_vec.size(); i++) {
const device_info &curr_cam = camera_info_vec.at(i);
TiXmlElement *include_elem = new TiXmlElement("include");
// File attribute: the default launch file of openni2
include_elem->SetAttribute("file", "$(find openni2_launch)/launch/openni2.launch");
// Tag argument 1: device_id
TiXmlElement *arg_tag = new TiXmlElement("arg");
arg_tag->SetAttribute("name", "device_id");
arg_tag->SetAttribute("value", curr_cam.serial);
include_elem->LinkEndChild(arg_tag);
// Second tag --> argument name of the camera
arg_tag = new TiXmlElement("arg");
arg_tag->SetAttribute("name", "camera");
arg_tag->SetAttribute("value", curr_cam.camera_name);
include_elem->LinkEndChild(arg_tag);
TiXmlElement *param_tag = new TiXmlElement("param");
string s("/");
s.append(curr_cam.camera_name);
s.append("/driver/data_skip");
param_tag->SetAttribute("name", s);
param_tag->SetAttribute("value", "$(arg data_skip)");
include_elem->LinkEndChild(param_tag);
addArgumentTags(*include_elem, launch_element);
launch_element.LinkEndChild(include_elem);
}
doc.InsertEndChild(launch_element);
doc.SaveFile(s);
return ret_val;
}
vector<device_info> getCamerasInfo()
{
vector<device_info> ret_val;
// Get the connected OpenNI2 devices
boost::shared_ptr<std::vector<openni2_wrapper::OpenNI2DeviceInfo> > device_infos = manager.getConnectedDeviceInfos();
std::cout << "Found " << device_infos->size() << " devices:" << std::endl;
// Iterate over the devices, asking the user for labels and generating the proper include tag
for (size_t i = 0; i < device_infos->size(); ++i)
{
openni2_wrapper::OpenNI2DeviceInfo &info = device_infos->at(i);
device_info camera_info;
ostringstream os, os2;
os << "camera_" << i;
std::string camera_label(os.str());
os2 << "#" << i + 1;
device_id = os2.str();
cout << "Showing the RGB image associated with camera " << device_id << endl;
try {
img_num = 0;
wait = true;
boost::shared_ptr<openni2_wrapper::OpenNI2Device> device = manager.getDevice(info.uri_);
if (device->hasColorSensor()) {
device->setColorFrameCallback(newColorFrameCallback);
device->startColorStream();
}
int cont = 0;
// Wait for the image to be shown and a key pressed
while (wait && cont < max_wait) {
cont++;
sleep(1);
}
if (wait) {
// No image has been found
cerr << "Warning: Could not retrieve image from camera " << device_id << ". Setting the label to camera_" << i + 1 << endl;
wait = false;
} else {
cout << "Please enter the label for camera " << device_id << endl;
getline(cin, camera_label);
}
// Save the camera info
camera_info.camera_name = camera_label;
std::ostringstream product_id, vendor_id;
product_id << std::hex << setfill('0') << setw(4) << info.product_id_;
camera_info.product_id = product_id.str();
vendor_id << std::hex << setfill('0') << setw(4) << std::hex << info.vendor_id_;
camera_info.vendor_id = vendor_id.str();
camera_info.location = getUsbLocation(info.uri_);
camera_info.serial = manager.getSerial(info.uri_);
ret_val.push_back(camera_info);
} catch (exception &e) {
cerr << "Exception thrown while managing camera " << device_id << ". Content: " << e.what() << endl;
}
}
return ret_val;
}
// Get the accepted arguments and their default values from another launch file (typically openni2_launch/launch/openni2.launch)
void getDefaultParametersFromLaunchFile(const std::string &launch_file, TiXmlElement *launch_element) {
// Load the file where the default parameters will be stored
TiXmlDocument doc(launch_file);
doc.LoadFile();
TiXmlElement *root = doc.RootElement();
if (!root) {
cerr << "Could not get the launch file.\n";
return;
}
// Iterate over the children and copy the argument data
TiXmlNode *it = root->FirstChild();
while (it) {
if (it->ValueStr() == "arg" && it->ToElement()) {
string name(it->ToElement()->Attribute("name"));
// Discard undesired tags
if (name != "camera" && name != "rgb_frame_id" && name != "device_id" && name != "rgb_frame_id" && name != "depth_frame_id" && name != "depth_camera_info_url" &&
name != "rgb_camera_info_url")
{
TiXmlElement *node = new TiXmlElement("arg");
node->SetAttribute("name", it->ToElement()->Attribute("name"));
node->SetAttribute("default", it->ToElement()->Attribute("default"));
if (it->ToElement()->Attribute("if")) {
node->SetAttribute("if", it->ToElement()->Attribute("if"));
} else if (it->ToElement()->Attribute("unless")) {
node->SetAttribute("unless", it->ToElement()->Attribute("unless"));
}
launch_element->LinkEndChild(node);
}
}
// Next getXmlCameraElement
it = root->IterateChildren(it);
}
}
void newColorFrameCallback(sensor_msgs::ImagePtr image)
{
if (img_num == 0 && wait) {
img_num++;
cv_bridge::CvImagePtr img_cv = cv_bridge::toCvCopy(image, "bgr8");
ostringstream os;
os << "Camera " << device_id;
cv::imshow("image_show", img_cv.get()->image ); // Show our image inside it.
cv::updateWindow ("image_show");
cv::startWindowThread();
cv::waitKey(0); // Wait for a key to be pressed in the window
wait = false;
}
}
string getUsbLocation(const string& device_uri)
{
string ret = "/dev/bus/usb/";
int i;
string bus_device = device_uri.substr(device_uri.find('@') + 1, device_uri.size());
istringstream bus_is (bus_device.substr(0, bus_device.find('/')));
bus_is >> i;
ostringstream bus_id;
bus_id << setfill('0') << setw(3) << i;
istringstream is (bus_device.substr(bus_device.find('/') + 1, bus_device.size()));
is >> i;
ostringstream device_id;
device_id << setfill('0') << setw(3) << i;
ret.append(bus_id.str());
ret.append("/");
ret.append(device_id.str());
return ret;
}
void addArgumentTags(TiXmlElement& elem_add, const TiXmlElement& elem_source)
{
// Iterate over the children and copy the argument data
const TiXmlNode *it = elem_source.FirstChild();
while (it) {
if (it->ValueStr() == "arg" && it->ToElement() && static_cast<string>(it->ToElement()->Attribute("name")) != "device_id") {
TiXmlElement *node = new TiXmlElement("arg");
node->SetAttribute("name", it->ToElement()->Attribute("name"));
ostringstream os;
os << "$(arg " << it->ToElement()->Attribute("name") << ")";
node->SetAttribute("value", os.str());
elem_add.LinkEndChild(node);
}
// Next getXmlCameraElement
it = elem_source.IterateChildren(it);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
void
ast_array_specifier::print(void) const
{
foreach_list_typed (ast_node, array_dimension, link, &this->array_dimensions) {
printf("[ ");
if (((ast_expression*)array_dimension)->oper != ast_unsized_array_dim)
array_dimension->print();
printf("] ");
}
}
/**
* If \c ir is a reference to an array for which we are tracking the max array
* element accessed, track that the given element has been accessed.
* Otherwise do nothing.
*
* This function also checks whether the array is a built-in array whose
* maximum size is too small to accommodate the given index, and if so uses
* loc and state to report the error.
*/
static void
update_max_array_access(ir_rvalue *ir, int idx, YYLTYPE *loc,
struct _mesa_glsl_parse_state *state)
{
if (ir_dereference_variable *deref_var = ir->as_dereference_variable()) {
ir_variable *var = deref_var->var;
if (idx > (int)var->data.max_array_access) {
var->data.max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly cause
* the size of a built-in array to be too large.
*/
check_builtin_array_max_size(var->name, idx+1, *loc, state);
}
} else if (ir_dereference_record *deref_record =
ir->as_dereference_record()) {
/* There are two possibilities we need to consider:
*
* - Accessing an element of an array that is a member of a named
* interface block (e.g. ifc.foo[i])
*
* - Accessing an element of an array that is a member of a named
* interface block array (e.g. ifc[j].foo[i]).
*/
ir_dereference_variable *deref_var =
deref_record->record->as_dereference_variable();
if (deref_var == NULL) {
if (ir_dereference_array *deref_array =
deref_record->record->as_dereference_array()) {
deref_var = deref_array->array->as_dereference_variable();
}
}
if (deref_var != NULL) {
if (deref_var->var->is_interface_instance()) {
unsigned field_index =
deref_record->record->type->field_index(deref_record->field);
assert(field_index < deref_var->var->get_interface_type()->length);
unsigned *const max_ifc_array_access =
deref_var->var->get_max_ifc_array_access();
assert(max_ifc_array_access != NULL);
if (idx > (int)max_ifc_array_access[field_index]) {
max_ifc_array_access[field_index] = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(deref_record->field, idx+1, *loc,
state);
}
}
}
}
}
static int
get_implicit_array_size(struct _mesa_glsl_parse_state *state,
ir_rvalue *array)
{
ir_variable *var = array->variable_referenced();
/* Inputs in control shader are implicitly sized
* to the maximum patch size.
*/
if (state->stage == MESA_SHADER_TESS_CTRL &&
var->data.mode == ir_var_shader_in) {
return state->Const.MaxPatchVertices;
}
/* Non-patch inputs in evaluation shader are implicitly sized
* to the maximum patch size.
*/
if (state->stage == MESA_SHADER_TESS_EVAL &&
var->data.mode == ir_var_shader_in &&
!var->data.patch) {
return state->Const.MaxPatchVertices;
}
return 0;
}
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc)
{
if (!array->type->is_error()
&& !array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
}
if (!idx->type->is_error()) {
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns -1 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array())
update_max_array_access(array, idx, &loc, state);
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->is_unsized_array()) {
int implicit_size = get_implicit_array_size(state, array);
if (implicit_size) {
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = implicit_size - 1;
}
else if (state->stage == MESA_SHADER_TESS_CTRL &&
array->variable_referenced()->data.mode == ir_var_shader_out &&
!array->variable_referenced()->data.patch) {
/* Tessellation control shader output non-patch arrays are
* initially unsized. Despite that, they are allowed to be
* indexed with a non-constant expression (typically
* "gl_InvocationID"). The array size will be determined
* by the linker.
*/
}
else if (array->variable_referenced()->data.mode !=
ir_var_shader_storage) {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
}
} else if (array->type->fields.array->is_interface()
&& (array->variable_referenced()->data.mode == ir_var_uniform ||
array->variable_referenced()->data.mode == ir_var_shader_storage)
&& !state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
/* Page 50 in section 4.3.9 of the OpenGL ES 3.10 spec says:
*
* "All indices used to index a uniform or shader storage block
* array must be constant integral expressions."
*/
_mesa_glsl_error(&loc, state, "%s block array index must be constant",
array->variable_referenced()->data.mode
== ir_var_uniform ? "uniform" : "shader storage");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*
* In GLSL 4.00 / ARB_gpu_shader5, this requirement is relaxed again to allow
* indexing with dynamically uniform expressions. Note that these are not
* required to be uniforms or expressions based on them, but merely that the
* values must not diverge between shader invocations run together. If the
* values *do* diverge, then the behavior of the operation requiring a
* dynamically uniform expression is undefined.
*/
if (array->type->without_array()->is_sampler()) {
if (!state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
if (state->is_version(130, 300))
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions are forbidden in GLSL %s "
"and later",
state->es_shader ? "ES 3.00" : "1.30");
else if (state->es_shader)
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL "
"3.00 and later");
else
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL "
"1.30 and later");
}
}
/* From page 27 of the GLSL ES 3.1 specification:
*
* "When aggregated into arrays within a shader, images can only be
* indexed with a constant integral expression."
*
* On the other hand the desktop GL specification extension allows
* non-constant indexing of image arrays, but behavior is left undefined
* in cases where the indexing expression is not dynamically uniform.
*/
if (state->es_shader && array->type->without_array()->is_image()) {
_mesa_glsl_error(&loc, state,
"image arrays indexed with non-constant "
"expressions are forbidden in GLSL ES.");
}
}
/* After performing all of the error checking, generate the IR for the
* expression.
*/
if (array->type->is_array()
|| array->type->is_matrix()) {
return new(mem_ctx) ir_dereference_array(array, idx);
} else if (array->type->is_vector()) {
return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
} else if (array->type->is_error()) {
return array;
} else {
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
result->type = glsl_type::error_type;
return result;
}
}
<commit_msg>glsl: add AoA support for an inteface with unsized array members<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
void
ast_array_specifier::print(void) const
{
foreach_list_typed (ast_node, array_dimension, link, &this->array_dimensions) {
printf("[ ");
if (((ast_expression*)array_dimension)->oper != ast_unsized_array_dim)
array_dimension->print();
printf("] ");
}
}
/**
* If \c ir is a reference to an array for which we are tracking the max array
* element accessed, track that the given element has been accessed.
* Otherwise do nothing.
*
* This function also checks whether the array is a built-in array whose
* maximum size is too small to accommodate the given index, and if so uses
* loc and state to report the error.
*/
static void
update_max_array_access(ir_rvalue *ir, int idx, YYLTYPE *loc,
struct _mesa_glsl_parse_state *state)
{
if (ir_dereference_variable *deref_var = ir->as_dereference_variable()) {
ir_variable *var = deref_var->var;
if (idx > (int)var->data.max_array_access) {
var->data.max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly cause
* the size of a built-in array to be too large.
*/
check_builtin_array_max_size(var->name, idx+1, *loc, state);
}
} else if (ir_dereference_record *deref_record =
ir->as_dereference_record()) {
/* There are three possibilities we need to consider:
*
* - Accessing an element of an array that is a member of a named
* interface block (e.g. ifc.foo[i])
*
* - Accessing an element of an array that is a member of a named
* interface block array (e.g. ifc[j].foo[i]).
*
* - Accessing an element of an array that is a member of a named
* interface block array of arrays (e.g. ifc[j][k].foo[i]).
*/
ir_dereference_variable *deref_var =
deref_record->record->as_dereference_variable();
if (deref_var == NULL) {
ir_dereference_array *deref_array =
deref_record->record->as_dereference_array();
ir_dereference_array *deref_array_prev = NULL;
while (deref_array != NULL) {
deref_array_prev = deref_array;
deref_array = deref_array->array->as_dereference_array();
}
if (deref_array_prev != NULL)
deref_var = deref_array_prev->array->as_dereference_variable();
}
if (deref_var != NULL) {
if (deref_var->var->is_interface_instance()) {
unsigned field_index =
deref_record->record->type->field_index(deref_record->field);
assert(field_index < deref_var->var->get_interface_type()->length);
unsigned *const max_ifc_array_access =
deref_var->var->get_max_ifc_array_access();
assert(max_ifc_array_access != NULL);
if (idx > (int)max_ifc_array_access[field_index]) {
max_ifc_array_access[field_index] = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(deref_record->field, idx+1, *loc,
state);
}
}
}
}
}
static int
get_implicit_array_size(struct _mesa_glsl_parse_state *state,
ir_rvalue *array)
{
ir_variable *var = array->variable_referenced();
/* Inputs in control shader are implicitly sized
* to the maximum patch size.
*/
if (state->stage == MESA_SHADER_TESS_CTRL &&
var->data.mode == ir_var_shader_in) {
return state->Const.MaxPatchVertices;
}
/* Non-patch inputs in evaluation shader are implicitly sized
* to the maximum patch size.
*/
if (state->stage == MESA_SHADER_TESS_EVAL &&
var->data.mode == ir_var_shader_in &&
!var->data.patch) {
return state->Const.MaxPatchVertices;
}
return 0;
}
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc)
{
if (!array->type->is_error()
&& !array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
}
if (!idx->type->is_error()) {
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns -1 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array())
update_max_array_access(array, idx, &loc, state);
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->is_unsized_array()) {
int implicit_size = get_implicit_array_size(state, array);
if (implicit_size) {
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = implicit_size - 1;
}
else if (state->stage == MESA_SHADER_TESS_CTRL &&
array->variable_referenced()->data.mode == ir_var_shader_out &&
!array->variable_referenced()->data.patch) {
/* Tessellation control shader output non-patch arrays are
* initially unsized. Despite that, they are allowed to be
* indexed with a non-constant expression (typically
* "gl_InvocationID"). The array size will be determined
* by the linker.
*/
}
else if (array->variable_referenced()->data.mode !=
ir_var_shader_storage) {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
}
} else if (array->type->fields.array->is_interface()
&& (array->variable_referenced()->data.mode == ir_var_uniform ||
array->variable_referenced()->data.mode == ir_var_shader_storage)
&& !state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
/* Page 50 in section 4.3.9 of the OpenGL ES 3.10 spec says:
*
* "All indices used to index a uniform or shader storage block
* array must be constant integral expressions."
*/
_mesa_glsl_error(&loc, state, "%s block array index must be constant",
array->variable_referenced()->data.mode
== ir_var_uniform ? "uniform" : "shader storage");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*
* In GLSL 4.00 / ARB_gpu_shader5, this requirement is relaxed again to allow
* indexing with dynamically uniform expressions. Note that these are not
* required to be uniforms or expressions based on them, but merely that the
* values must not diverge between shader invocations run together. If the
* values *do* diverge, then the behavior of the operation requiring a
* dynamically uniform expression is undefined.
*/
if (array->type->without_array()->is_sampler()) {
if (!state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
if (state->is_version(130, 300))
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions are forbidden in GLSL %s "
"and later",
state->es_shader ? "ES 3.00" : "1.30");
else if (state->es_shader)
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL "
"3.00 and later");
else
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL "
"1.30 and later");
}
}
/* From page 27 of the GLSL ES 3.1 specification:
*
* "When aggregated into arrays within a shader, images can only be
* indexed with a constant integral expression."
*
* On the other hand the desktop GL specification extension allows
* non-constant indexing of image arrays, but behavior is left undefined
* in cases where the indexing expression is not dynamically uniform.
*/
if (state->es_shader && array->type->without_array()->is_image()) {
_mesa_glsl_error(&loc, state,
"image arrays indexed with non-constant "
"expressions are forbidden in GLSL ES.");
}
}
/* After performing all of the error checking, generate the IR for the
* expression.
*/
if (array->type->is_array()
|| array->type->is_matrix()) {
return new(mem_ctx) ir_dereference_array(array, idx);
} else if (array->type->is_vector()) {
return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
} else if (array->type->is_error()) {
return array;
} else {
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
result->type = glsl_type::error_type;
return result;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
void
ast_array_specifier::print(void) const
{
if (this->is_unsized_array) {
printf("[ ] ");
}
foreach_list_typed (ast_node, array_dimension, link, &this->array_dimensions) {
printf("[ ");
array_dimension->print();
printf("] ");
}
}
/**
* If \c ir is a reference to an array for which we are tracking the max array
* element accessed, track that the given element has been accessed.
* Otherwise do nothing.
*
* This function also checks whether the array is a built-in array whose
* maximum size is too small to accommodate the given index, and if so uses
* loc and state to report the error.
*/
static void
update_max_array_access(ir_rvalue *ir, int idx, YYLTYPE *loc,
struct _mesa_glsl_parse_state *state)
{
if (ir_dereference_variable *deref_var = ir->as_dereference_variable()) {
ir_variable *var = deref_var->var;
if (idx > (int)var->data.max_array_access) {
var->data.max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly cause
* the size of a built-in array to be too large.
*/
check_builtin_array_max_size(var->name, idx+1, *loc, state);
}
} else if (ir_dereference_record *deref_record =
ir->as_dereference_record()) {
/* There are two possibilities we need to consider:
*
* - Accessing an element of an array that is a member of a named
* interface block (e.g. ifc.foo[i])
*
* - Accessing an element of an array that is a member of a named
* interface block array (e.g. ifc[j].foo[i]).
*/
ir_dereference_variable *deref_var =
deref_record->record->as_dereference_variable();
if (deref_var == NULL) {
if (ir_dereference_array *deref_array =
deref_record->record->as_dereference_array()) {
deref_var = deref_array->array->as_dereference_variable();
}
}
if (deref_var != NULL) {
if (deref_var->var->is_interface_instance()) {
unsigned field_index =
deref_record->record->type->field_index(deref_record->field);
assert(field_index < deref_var->var->get_interface_type()->length);
unsigned *const max_ifc_array_access =
deref_var->var->get_max_ifc_array_access();
assert(max_ifc_array_access != NULL);
if (idx > (int)max_ifc_array_access[field_index]) {
max_ifc_array_access[field_index] = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(deref_record->field, idx+1, *loc,
state);
}
}
}
}
}
static int
get_implicit_array_size(struct _mesa_glsl_parse_state *state,
ir_rvalue *array)
{
ir_variable *var = array->variable_referenced();
/* Inputs in control shader are implicitly sized
* to the maximum patch size.
*/
if (state->stage == MESA_SHADER_TESS_CTRL &&
var->data.mode == ir_var_shader_in) {
return state->Const.MaxPatchVertices;
}
/* Non-patch inputs in evaluation shader are implicitly sized
* to the maximum patch size.
*/
if (state->stage == MESA_SHADER_TESS_EVAL &&
var->data.mode == ir_var_shader_in &&
!var->data.patch) {
return state->Const.MaxPatchVertices;
}
return 0;
}
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc)
{
if (!array->type->is_error()
&& !array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
}
if (!idx->type->is_error()) {
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns -1 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array())
update_max_array_access(array, idx, &loc, state);
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->is_unsized_array()) {
int implicit_size = get_implicit_array_size(state, array);
if (implicit_size) {
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = implicit_size - 1;
}
else {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
}
} else if (array->type->fields.array->is_interface()
&& array->variable_referenced()->data.mode == ir_var_uniform
&& !state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
/* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
*
* "All indexes used to index a uniform block array must be
* constant integral expressions."
*/
_mesa_glsl_error(&loc, state,
"uniform block array index must be constant");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*
* In GLSL 4.00 / ARB_gpu_shader5, this requirement is relaxed again to allow
* indexing with dynamically uniform expressions. Note that these are not
* required to be uniforms or expressions based on them, but merely that the
* values must not diverge between shader invocations run together. If the
* values *do* diverge, then the behavior of the operation requiring a
* dynamically uniform expression is undefined.
*/
if (array->type->without_array()->is_sampler()) {
if (!state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
if (state->is_version(130, 300))
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions are forbidden in GLSL %s "
"and later",
state->es_shader ? "ES 3.00" : "1.30");
else if (state->es_shader)
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL "
"3.00 and later");
else
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL "
"1.30 and later");
}
}
}
/* After performing all of the error checking, generate the IR for the
* expression.
*/
if (array->type->is_array()
|| array->type->is_matrix()) {
return new(mem_ctx) ir_dereference_array(array, idx);
} else if (array->type->is_vector()) {
return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
} else if (array->type->is_error()) {
return array;
} else {
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
result->type = glsl_type::error_type;
return result;
}
}
<commit_msg>glsl: allow indexing of gl_out with a non-const if length isn't known<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include "ast.h"
#include "glsl_types.h"
#include "ir.h"
void
ast_array_specifier::print(void) const
{
if (this->is_unsized_array) {
printf("[ ] ");
}
foreach_list_typed (ast_node, array_dimension, link, &this->array_dimensions) {
printf("[ ");
array_dimension->print();
printf("] ");
}
}
/**
* If \c ir is a reference to an array for which we are tracking the max array
* element accessed, track that the given element has been accessed.
* Otherwise do nothing.
*
* This function also checks whether the array is a built-in array whose
* maximum size is too small to accommodate the given index, and if so uses
* loc and state to report the error.
*/
static void
update_max_array_access(ir_rvalue *ir, int idx, YYLTYPE *loc,
struct _mesa_glsl_parse_state *state)
{
if (ir_dereference_variable *deref_var = ir->as_dereference_variable()) {
ir_variable *var = deref_var->var;
if (idx > (int)var->data.max_array_access) {
var->data.max_array_access = idx;
/* Check whether this access will, as a side effect, implicitly cause
* the size of a built-in array to be too large.
*/
check_builtin_array_max_size(var->name, idx+1, *loc, state);
}
} else if (ir_dereference_record *deref_record =
ir->as_dereference_record()) {
/* There are two possibilities we need to consider:
*
* - Accessing an element of an array that is a member of a named
* interface block (e.g. ifc.foo[i])
*
* - Accessing an element of an array that is a member of a named
* interface block array (e.g. ifc[j].foo[i]).
*/
ir_dereference_variable *deref_var =
deref_record->record->as_dereference_variable();
if (deref_var == NULL) {
if (ir_dereference_array *deref_array =
deref_record->record->as_dereference_array()) {
deref_var = deref_array->array->as_dereference_variable();
}
}
if (deref_var != NULL) {
if (deref_var->var->is_interface_instance()) {
unsigned field_index =
deref_record->record->type->field_index(deref_record->field);
assert(field_index < deref_var->var->get_interface_type()->length);
unsigned *const max_ifc_array_access =
deref_var->var->get_max_ifc_array_access();
assert(max_ifc_array_access != NULL);
if (idx > (int)max_ifc_array_access[field_index]) {
max_ifc_array_access[field_index] = idx;
/* Check whether this access will, as a side effect, implicitly
* cause the size of a built-in array to be too large.
*/
check_builtin_array_max_size(deref_record->field, idx+1, *loc,
state);
}
}
}
}
}
static int
get_implicit_array_size(struct _mesa_glsl_parse_state *state,
ir_rvalue *array)
{
ir_variable *var = array->variable_referenced();
/* Inputs in control shader are implicitly sized
* to the maximum patch size.
*/
if (state->stage == MESA_SHADER_TESS_CTRL &&
var->data.mode == ir_var_shader_in) {
return state->Const.MaxPatchVertices;
}
/* Non-patch inputs in evaluation shader are implicitly sized
* to the maximum patch size.
*/
if (state->stage == MESA_SHADER_TESS_EVAL &&
var->data.mode == ir_var_shader_in &&
!var->data.patch) {
return state->Const.MaxPatchVertices;
}
return 0;
}
ir_rvalue *
_mesa_ast_array_index_to_hir(void *mem_ctx,
struct _mesa_glsl_parse_state *state,
ir_rvalue *array, ir_rvalue *idx,
YYLTYPE &loc, YYLTYPE &idx_loc)
{
if (!array->type->is_error()
&& !array->type->is_array()
&& !array->type->is_matrix()
&& !array->type->is_vector()) {
_mesa_glsl_error(& idx_loc, state,
"cannot dereference non-array / non-matrix / "
"non-vector");
}
if (!idx->type->is_error()) {
if (!idx->type->is_integer()) {
_mesa_glsl_error(& idx_loc, state, "array index must be integer type");
} else if (!idx->type->is_scalar()) {
_mesa_glsl_error(& idx_loc, state, "array index must be scalar");
}
}
/* If the array index is a constant expression and the array has a
* declared size, ensure that the access is in-bounds. If the array
* index is not a constant expression, ensure that the array has a
* declared size.
*/
ir_constant *const const_index = idx->constant_expression_value();
if (const_index != NULL && idx->type->is_integer()) {
const int idx = const_index->value.i[0];
const char *type_name = "error";
unsigned bound = 0;
/* From page 24 (page 30 of the PDF) of the GLSL 1.50 spec:
*
* "It is illegal to declare an array with a size, and then
* later (in the same shader) index the same array with an
* integral constant expression greater than or equal to the
* declared size. It is also illegal to index an array with a
* negative constant expression."
*/
if (array->type->is_matrix()) {
if (array->type->row_type()->vector_elements <= idx) {
type_name = "matrix";
bound = array->type->row_type()->vector_elements;
}
} else if (array->type->is_vector()) {
if (array->type->vector_elements <= idx) {
type_name = "vector";
bound = array->type->vector_elements;
}
} else {
/* glsl_type::array_size() returns -1 for non-array types. This means
* that we don't need to verify that the type is an array before
* doing the bounds checking.
*/
if ((array->type->array_size() > 0)
&& (array->type->array_size() <= idx)) {
type_name = "array";
bound = array->type->array_size();
}
}
if (bound > 0) {
_mesa_glsl_error(& loc, state, "%s index must be < %u",
type_name, bound);
} else if (idx < 0) {
_mesa_glsl_error(& loc, state, "%s index must be >= 0",
type_name);
}
if (array->type->is_array())
update_max_array_access(array, idx, &loc, state);
} else if (const_index == NULL && array->type->is_array()) {
if (array->type->is_unsized_array()) {
int implicit_size = get_implicit_array_size(state, array);
if (implicit_size) {
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = implicit_size - 1;
}
else if (state->stage == MESA_SHADER_TESS_CTRL &&
array->variable_referenced()->data.mode == ir_var_shader_out &&
!array->variable_referenced()->data.patch) {
/* Tessellation control shader output non-patch arrays are
* initially unsized. Despite that, they are allowed to be
* indexed with a non-constant expression (typically
* "gl_InvocationID"). The array size will be determined
* by the linker.
*/
}
else {
_mesa_glsl_error(&loc, state, "unsized array index must be constant");
}
} else if (array->type->fields.array->is_interface()
&& array->variable_referenced()->data.mode == ir_var_uniform
&& !state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
/* Page 46 in section 4.3.7 of the OpenGL ES 3.00 spec says:
*
* "All indexes used to index a uniform block array must be
* constant integral expressions."
*/
_mesa_glsl_error(&loc, state,
"uniform block array index must be constant");
} else {
/* whole_variable_referenced can return NULL if the array is a
* member of a structure. In this case it is safe to not update
* the max_array_access field because it is never used for fields
* of structures.
*/
ir_variable *v = array->whole_variable_referenced();
if (v != NULL)
v->data.max_array_access = array->type->array_size() - 1;
}
/* From page 23 (29 of the PDF) of the GLSL 1.30 spec:
*
* "Samplers aggregated into arrays within a shader (using square
* brackets [ ]) can only be indexed with integral constant
* expressions [...]."
*
* This restriction was added in GLSL 1.30. Shaders using earlier
* version of the language should not be rejected by the compiler
* front-end for using this construct. This allows useful things such
* as using a loop counter as the index to an array of samplers. If the
* loop in unrolled, the code should compile correctly. Instead, emit a
* warning.
*
* In GLSL 4.00 / ARB_gpu_shader5, this requirement is relaxed again to allow
* indexing with dynamically uniform expressions. Note that these are not
* required to be uniforms or expressions based on them, but merely that the
* values must not diverge between shader invocations run together. If the
* values *do* diverge, then the behavior of the operation requiring a
* dynamically uniform expression is undefined.
*/
if (array->type->without_array()->is_sampler()) {
if (!state->is_version(400, 0) && !state->ARB_gpu_shader5_enable) {
if (state->is_version(130, 300))
_mesa_glsl_error(&loc, state,
"sampler arrays indexed with non-constant "
"expressions are forbidden in GLSL %s "
"and later",
state->es_shader ? "ES 3.00" : "1.30");
else if (state->es_shader)
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL "
"3.00 and later");
else
_mesa_glsl_warning(&loc, state,
"sampler arrays indexed with non-constant "
"expressions will be forbidden in GLSL "
"1.30 and later");
}
}
}
/* After performing all of the error checking, generate the IR for the
* expression.
*/
if (array->type->is_array()
|| array->type->is_matrix()) {
return new(mem_ctx) ir_dereference_array(array, idx);
} else if (array->type->is_vector()) {
return new(mem_ctx) ir_expression(ir_binop_vector_extract, array, idx);
} else if (array->type->is_error()) {
return array;
} else {
ir_rvalue *result = new(mem_ctx) ir_dereference_array(array, idx);
result->type = glsl_type::error_type;
return result;
}
}
<|endoftext|> |
<commit_before><commit_msg>grt: skip guides on nets grt ignores, with warning<commit_after><|endoftext|> |
<commit_before>/** @file gsFitting.hpp
@brief Provides implementation of data fitting algorithms by least
squares approximation.
This file is part of the G+Smo library.
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/.
Author(s): M. Kapl, G. Kiss, A. Mantzaflaris
*/
#include <gsCore/gsBasis.h>
#include <gsCore/gsGeometry.h>
#include <gsCore/gsLinearAlgebra.h>
#include <gsTensor/gsTensorDomainIterator.h>
namespace gismo
{
template<class T>
gsFitting<T>::~gsFitting()
{
if ( m_result )
delete m_result;
}
template<class T>
gsFitting<T>:: gsFitting(gsMatrix<T> const & param_values,
gsMatrix<T> const & points,
gsBasis<T> & basis)
{
m_param_values = param_values;
m_points = points;
m_result = NULL;
m_basis = &basis;
m_points.transposeInPlace();
}
template<class T>
void gsFitting<T>::compute(T lambda)
{
// Wipe out previous result
if ( m_result )
delete m_result;
const int num_basis=m_basis->size();
const int dimension=m_points.cols();
//left side matrix
//gsMatrix<T> A_mat(num_basis,num_basis);
gsSparseMatrix<T> A_mat(num_basis, num_basis);
//gsMatrix<T>A_mat(num_basis,num_basis);
//To optimize sparse matrix an estimation of nonzero elements per
//column can be given here
int nonZerosPerCol = 1;
for (int i = 0; i < m_basis->dim(); ++i) // to do: improve
nonZerosPerCol *= m_basis->degree(i) + 1;
// nonZerosPerCol *= ( 2 * m_basis->degree(i) + 1 ) * 4;
A_mat.reservePerColumn( nonZerosPerCol );
//right side vector (more dimensional!)
gsMatrix<T> m_B(num_basis, dimension);
m_B.setZero(); // enusure that all entries are zero in the beginning
// building the matrix A and the vector b of the system of linear
// equations A*x==b
assembleSystem(A_mat, m_B);
// --- Smoothing matrix computation
//test degree >=3
if(lambda > 0)
applySmoothing(lambda, A_mat);
//Solving the system of linear equations A*x=b (works directly for a right side which has a dimension with higher than 1)
//gsDebugVar( A_mat.nonZerosPerCol().maxCoeff() );
//gsDebugVar( A_mat.nonZerosPerCol().minCoeff() );
A_mat.makeCompressed();
typename gsSparseSolver<T>::BiCGSTABILUT solver( A_mat );
if ( solver.preconditioner().info() != Eigen::Success )
{
gsWarn<< "The preconditioner failed. Aborting.\n";
m_result = NULL;
return;
}
// Solves for many right hand side columns
gsMatrix<T> x;
x = solver.solve(m_B); //toDense()
//gsMatrix<T> x (m_B.rows(), m_B.cols());
//x=A_mat.fullPivHouseholderQr().solve( m_B);
// Solves for many right hand side columns
// finally generate the B-spline curve
m_result = m_basis->makeGeometry( give(x) ).release();
}
template <class T>
void gsFitting<T>::assembleSystem(gsSparseMatrix<T>& A_mat,
gsMatrix<T>& m_B)
{
const int num_points = m_points.rows();
//for computing the value of the basis function
gsMatrix<T> value, curr_point;
gsMatrix<unsigned> actives;
for(index_t k = 0; k != num_points; ++k)
{
curr_point = m_param_values.col(k);
//computing the values of the basis functions at the current point
m_basis->eval_into(curr_point, value);
// which functions have been computed i.e. which are active
m_basis->active_into(curr_point, actives);
const index_t numActive = actives.rows();
for (index_t i = 0; i != numActive; ++i)
{
const int ii = actives.at(i);
m_B.row(ii) += value.at(i) * m_points.row(k);
for (index_t j = 0; j != numActive; ++j)
A_mat(ii, actives.at(j)) += value.at(i) * value.at(j);
}
}
}
template<class T>
void gsFitting<T>::applySmoothing(T lambda, gsSparseMatrix<T> & A_mat)
{
const int dim = m_basis->dim();
const int stride = dim*(dim+1)/2;
gsVector<int> numNodes(dim);
for ( int i = 0; i!= dim; ++i )
numNodes[i] = this->m_basis->degree(i);//+1;
gsGaussRule<T> QuRule( numNodes ); // Reference Quadrature rule
gsMatrix<T> quNodes, der2, localA;
gsVector<T> quWeights;
gsMatrix<unsigned> actives;
typename gsBasis<T>::domainIter domIt = m_basis->makeDomainIterator();
for (; domIt->good(); domIt->next() )
{
// Map the Quadrature rule to the element and compute basis derivatives
QuRule.mapTo( domIt->lowerCorner(), domIt->upperCorner(), quNodes, quWeights );
m_basis->deriv2_into(quNodes, der2);
m_basis->active_into(domIt->center, actives);
const index_t numActive = actives.rows();
localA.setZero(numActive, numActive );
// perform the quadrature
for (index_t k = 0; k < quWeights.rows(); ++k)
{
const T weight = quWeights[k] * lambda;
for (index_t i=0; i!=numActive; ++i)
for (index_t j=0; j!=numActive; ++j)
{
T localAij = 0; // temporary variable
for (int s = 0; s < stride; s++)
{
// The pure second derivatives
// d^2u N_i * d^2u N_j + ...
if (s < dim)
{
localAij += der2(i * stride + s, k) *
der2(j * stride + s, k);
}
// Mixed derivatives 2 * dudv N_i * dudv N_j + ...
else
{
localAij += 2 * der2(i * stride + s, k) *
der2(j * stride + s, k);
}
}
localA(i, j) += weight * localAij;
// old code, just for the case if I break something
// localA(i,j) += weight * (
// // der2.template block<3,1>(i*stride,k)
// der2(i*stride , k) * der2(j*stride , k) + // d^2u N_i * d^2u N_j
// der2(i*stride+1, k) * der2(j*stride+1, k) + // d^2v N_i * d^2v N_j
// 2 * der2(i*stride+2, k) * der2(j*stride+2, k)// dudv N_i * dudv N_j
// );
}
}
for (index_t i=0; i!=numActive; ++i)
{
const int ii = actives(i,0);
for (index_t j=0; j!=numActive; ++j)
A_mat( ii, actives(j,0) ) += localA(i,j);
}
}
}
template<class T>
void gsFitting<T>::computeErrors()
{
m_pointErrors.clear();
gsMatrix<T> val_i;
//m_result->eval_into(m_param_values.col(0), val_i);
m_result->eval_into(m_param_values, val_i);
m_pointErrors.push_back( (m_points.row(0) - val_i.col(0).transpose()).norm() );
m_max_error = m_min_error = m_pointErrors.back();
for (index_t i = 1; i < m_points.rows(); i++)
{
//m_result->eval_into(m_param_values.col(i), val_i);
const T err = (m_points.row(i) - val_i.col(i).transpose()).norm() ;
m_pointErrors.push_back(err);
if ( err > m_max_error ) m_max_error = err;
if ( err < m_min_error ) m_min_error = err;
}
}
template<class T>
void gsFitting<T>::computeMaxNormErrors()
{
m_pointErrors.clear();
gsMatrix<T> values;
m_result->eval_into(m_param_values, values);
for (index_t i = 0; i != m_points.rows(); i++)
{
const T err = (m_points.row(i) - values.col(i).transpose()).cwiseAbs().maxCoeff();
m_pointErrors.push_back(err);
if ( i == 0 || m_max_error < err ) m_max_error = err;
if ( i == 0 || err < m_min_error ) m_min_error = err;
}
}
template<class T>
void gsFitting<T>::computeApproxError(T& error, int type) const
{
gsMatrix<T> results;
m_result->eval_into(m_param_values, results);
error = 0;
//computing the approximation error = sum_i ||x(u_i)-p_i||^2
for (index_t i = 0; i != m_points.rows(); ++i)
{
const T err = (m_points.row(i) - results.col(i).transpose()).squaredNorm();
switch (type) {
case 0:
error += err;
break;
case 1:
error += sqrt(err);
break;
default:
gsWarn << "Unknown type in computeApproxError(error, type)...\n";
break;
}
}
}
template<class T>
void gsFitting<T>::get_Error(std::vector<T>& errors, int type) const
{
errors.clear();
gsMatrix<T> results;
m_result->eval_into(m_param_values,results);
results.transposeInPlace();
for (index_t row = 0; row != m_points.rows(); row++)
{
T err = 0;
for (index_t col = 0; col != m_points.cols(); col++)
{
err += math::pow(m_points(row, col) - results(row, col), 2);
}
switch (type)
{
case 0:
errors.push_back(err);
break;
case 1:
errors.push_back(sqrt(err));
break;
default:
gsWarn << "Unknown type in get_Error(errors, type)...\n";
break;
}
}
}
} // namespace gismo
<commit_msg>fitting is faster with higher number of non zero entries...<commit_after>/** @file gsFitting.hpp
@brief Provides implementation of data fitting algorithms by least
squares approximation.
This file is part of the G+Smo library.
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/.
Author(s): M. Kapl, G. Kiss, A. Mantzaflaris
*/
#include <gsCore/gsBasis.h>
#include <gsCore/gsGeometry.h>
#include <gsCore/gsLinearAlgebra.h>
#include <gsTensor/gsTensorDomainIterator.h>
namespace gismo
{
template<class T>
gsFitting<T>::~gsFitting()
{
if ( m_result )
delete m_result;
}
template<class T>
gsFitting<T>:: gsFitting(gsMatrix<T> const & param_values,
gsMatrix<T> const & points,
gsBasis<T> & basis)
{
m_param_values = param_values;
m_points = points;
m_result = NULL;
m_basis = &basis;
m_points.transposeInPlace();
}
template<class T>
void gsFitting<T>::compute(T lambda)
{
// Wipe out previous result
if ( m_result )
delete m_result;
const int num_basis=m_basis->size();
const int dimension=m_points.cols();
//left side matrix
//gsMatrix<T> A_mat(num_basis,num_basis);
gsSparseMatrix<T> A_mat(num_basis, num_basis);
//gsMatrix<T>A_mat(num_basis,num_basis);
//To optimize sparse matrix an estimation of nonzero elements per
//column can be given here
int nonZerosPerCol = 1;
for (int i = 0; i < m_basis->dim(); ++i) // to do: improve
// nonZerosPerCol *= m_basis->degree(i) + 1;
nonZerosPerCol *= ( 2 * m_basis->degree(i) + 1 ) * 4;
A_mat.reservePerColumn( nonZerosPerCol );
//right side vector (more dimensional!)
gsMatrix<T> m_B(num_basis, dimension);
m_B.setZero(); // enusure that all entries are zero in the beginning
// building the matrix A and the vector b of the system of linear
// equations A*x==b
assembleSystem(A_mat, m_B);
// --- Smoothing matrix computation
//test degree >=3
if(lambda > 0)
applySmoothing(lambda, A_mat);
//Solving the system of linear equations A*x=b (works directly for a right side which has a dimension with higher than 1)
//gsDebugVar( A_mat.nonZerosPerCol().maxCoeff() );
//gsDebugVar( A_mat.nonZerosPerCol().minCoeff() );
A_mat.makeCompressed();
typename gsSparseSolver<T>::BiCGSTABILUT solver( A_mat );
if ( solver.preconditioner().info() != Eigen::Success )
{
gsWarn<< "The preconditioner failed. Aborting.\n";
m_result = NULL;
return;
}
// Solves for many right hand side columns
gsMatrix<T> x;
x = solver.solve(m_B); //toDense()
//gsMatrix<T> x (m_B.rows(), m_B.cols());
//x=A_mat.fullPivHouseholderQr().solve( m_B);
// Solves for many right hand side columns
// finally generate the B-spline curve
m_result = m_basis->makeGeometry( give(x) ).release();
}
template <class T>
void gsFitting<T>::assembleSystem(gsSparseMatrix<T>& A_mat,
gsMatrix<T>& m_B)
{
const int num_points = m_points.rows();
//for computing the value of the basis function
gsMatrix<T> value, curr_point;
gsMatrix<unsigned> actives;
for(index_t k = 0; k != num_points; ++k)
{
curr_point = m_param_values.col(k);
//computing the values of the basis functions at the current point
m_basis->eval_into(curr_point, value);
// which functions have been computed i.e. which are active
m_basis->active_into(curr_point, actives);
const index_t numActive = actives.rows();
for (index_t i = 0; i != numActive; ++i)
{
const int ii = actives.at(i);
m_B.row(ii) += value.at(i) * m_points.row(k);
for (index_t j = 0; j != numActive; ++j)
A_mat(ii, actives.at(j)) += value.at(i) * value.at(j);
}
}
}
template<class T>
void gsFitting<T>::applySmoothing(T lambda, gsSparseMatrix<T> & A_mat)
{
const int dim = m_basis->dim();
const int stride = dim*(dim+1)/2;
gsVector<int> numNodes(dim);
for ( int i = 0; i!= dim; ++i )
numNodes[i] = this->m_basis->degree(i);//+1;
gsGaussRule<T> QuRule( numNodes ); // Reference Quadrature rule
gsMatrix<T> quNodes, der2, localA;
gsVector<T> quWeights;
gsMatrix<unsigned> actives;
typename gsBasis<T>::domainIter domIt = m_basis->makeDomainIterator();
for (; domIt->good(); domIt->next() )
{
// Map the Quadrature rule to the element and compute basis derivatives
QuRule.mapTo( domIt->lowerCorner(), domIt->upperCorner(), quNodes, quWeights );
m_basis->deriv2_into(quNodes, der2);
m_basis->active_into(domIt->center, actives);
const index_t numActive = actives.rows();
localA.setZero(numActive, numActive );
// perform the quadrature
for (index_t k = 0; k < quWeights.rows(); ++k)
{
const T weight = quWeights[k] * lambda;
for (index_t i=0; i!=numActive; ++i)
for (index_t j=0; j!=numActive; ++j)
{
T localAij = 0; // temporary variable
for (int s = 0; s < stride; s++)
{
// The pure second derivatives
// d^2u N_i * d^2u N_j + ...
if (s < dim)
{
localAij += der2(i * stride + s, k) *
der2(j * stride + s, k);
}
// Mixed derivatives 2 * dudv N_i * dudv N_j + ...
else
{
localAij += 2 * der2(i * stride + s, k) *
der2(j * stride + s, k);
}
}
localA(i, j) += weight * localAij;
// old code, just for the case if I break something
// localA(i,j) += weight * (
// // der2.template block<3,1>(i*stride,k)
// der2(i*stride , k) * der2(j*stride , k) + // d^2u N_i * d^2u N_j
// der2(i*stride+1, k) * der2(j*stride+1, k) + // d^2v N_i * d^2v N_j
// 2 * der2(i*stride+2, k) * der2(j*stride+2, k)// dudv N_i * dudv N_j
// );
}
}
for (index_t i=0; i!=numActive; ++i)
{
const int ii = actives(i,0);
for (index_t j=0; j!=numActive; ++j)
A_mat( ii, actives(j,0) ) += localA(i,j);
}
}
}
template<class T>
void gsFitting<T>::computeErrors()
{
m_pointErrors.clear();
gsMatrix<T> val_i;
//m_result->eval_into(m_param_values.col(0), val_i);
m_result->eval_into(m_param_values, val_i);
m_pointErrors.push_back( (m_points.row(0) - val_i.col(0).transpose()).norm() );
m_max_error = m_min_error = m_pointErrors.back();
for (index_t i = 1; i < m_points.rows(); i++)
{
//m_result->eval_into(m_param_values.col(i), val_i);
const T err = (m_points.row(i) - val_i.col(i).transpose()).norm() ;
m_pointErrors.push_back(err);
if ( err > m_max_error ) m_max_error = err;
if ( err < m_min_error ) m_min_error = err;
}
}
template<class T>
void gsFitting<T>::computeMaxNormErrors()
{
m_pointErrors.clear();
gsMatrix<T> values;
m_result->eval_into(m_param_values, values);
for (index_t i = 0; i != m_points.rows(); i++)
{
const T err = (m_points.row(i) - values.col(i).transpose()).cwiseAbs().maxCoeff();
m_pointErrors.push_back(err);
if ( i == 0 || m_max_error < err ) m_max_error = err;
if ( i == 0 || err < m_min_error ) m_min_error = err;
}
}
template<class T>
void gsFitting<T>::computeApproxError(T& error, int type) const
{
gsMatrix<T> results;
m_result->eval_into(m_param_values, results);
error = 0;
//computing the approximation error = sum_i ||x(u_i)-p_i||^2
for (index_t i = 0; i != m_points.rows(); ++i)
{
const T err = (m_points.row(i) - results.col(i).transpose()).squaredNorm();
switch (type) {
case 0:
error += err;
break;
case 1:
error += sqrt(err);
break;
default:
gsWarn << "Unknown type in computeApproxError(error, type)...\n";
break;
}
}
}
template<class T>
void gsFitting<T>::get_Error(std::vector<T>& errors, int type) const
{
errors.clear();
gsMatrix<T> results;
m_result->eval_into(m_param_values,results);
results.transposeInPlace();
for (index_t row = 0; row != m_points.rows(); row++)
{
T err = 0;
for (index_t col = 0; col != m_points.cols(); col++)
{
err += math::pow(m_points(row, col) - results(row, col), 2);
}
switch (type)
{
case 0:
errors.push_back(err);
break;
case 1:
errors.push_back(sqrt(err));
break;
default:
gsWarn << "Unknown type in get_Error(errors, type)...\n";
break;
}
}
}
} // namespace gismo
<|endoftext|> |
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2016 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : glm/test/gtx_utilities.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// includes, system
#include <array> // std::array<>
#include <glm/gtc/constants.hpp> // glm::pi
#include <glm/gtc/random.hpp> // glm::*Rand
#include <glm/gtc/vec1.hpp> // glm::vec1
#include <glm/gtx/io.hpp> // glm::operator<<
#include <glm/gtx/transform.hpp> // glm::rotate, glm::scale, glm::translate>
// includes, project
#include <glm/gtx/utilities.hpp>
#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/mpl/list.hpp>
BOOST_AUTO_TEST_CASE(test_hugh_glm_gtx_utilities_op_literal_deg)
{
#if defined(_MSC_VER) && (_MSC_VER <= 1900)
BOOST_CHECK(glm::pi<double>() == 180.0 _deg);
BOOST_TEST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0 _deg);
#else
BOOST_CHECK(glm::pi<double>() == 180.0_deg);
BOOST_TEST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0_deg);
#endif
}
BOOST_AUTO_TEST_CASE(test_hugh_glm_gtx_utilities_op_literal_rad)
{
#if defined(_MSC_VER) && (_MSC_VER <= 1900)
BOOST_CHECK(glm::pi<double>() == 180.0 _deg);
BOOST_TEST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0 _deg);
#else
BOOST_CHECK(180.0_deg == glm::pi<double>());
BOOST_TEST_MESSAGE(std::setprecision(12)
<< "180.0_deg:" << 180.0_deg
<< " =?= glm::pi<double>():" << glm::pi<double>());
#endif
}
using rev_types = boost::mpl::list<glm::vec1, glm::vec2, glm::vec3, glm::vec4,
glm::dvec1, glm::dvec2, glm::dvec3, glm::dvec4>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_utilities_rev, T, rev_types)
{
BOOST_CHECK(glm::rev(T(glm::two_pi<typename T::value_type>())) == T(0.0));
}
BOOST_AUTO_TEST_CASE(test_hugh_glm_gtx_utilities_sgn)
{
BOOST_CHECK(glm::sgn(-1) < 0);
BOOST_CHECK(glm::sgn(+1) > 0);
}
BOOST_AUTO_TEST_CASE(test_hugh_glm_gtx_utilities_convert_transform)
{
using matrix_pair = std::pair<glm::mat4 const, glm::mat4 const>;
#if defined(_MSC_VER) && (_MSC_VER <= 1900)
glm::vec3::value_type const angle(float(45 _deg));
#else
glm::vec3::value_type const angle(float(45_deg));
#endif
glm::mat4 const ir(glm::rotate (angle, glm::vec3(glm::gaussRand( 0.0, 20.0),
glm::gaussRand( 0.0, 20.0),
glm::gaussRand( 0.0, 20.0))));
glm::mat4 const is(glm::scale ( glm::vec3(glm::linearRand( 0.1, 10.0),
glm::linearRand( 0.1, 10.0),
glm::linearRand( 0.1, 10.0))));
glm::mat4 const it(glm::translate( glm::vec3(glm::linearRand(-1.0, 1.0),
glm::linearRand(-1.0, 1.0),
glm::linearRand(-1.0, 1.0))));
std::array<std::pair<glm::mat4, std::string>, 7> const input_xform_list = {
{
std::make_pair(glm::mat4(), "Identity"),
std::make_pair(ir * is * it, "RST"),
std::make_pair(ir * it * is, "RTS"),
std::make_pair(is * ir * it, "SRT"),
std::make_pair(is * it * ir, "STR"),
std::make_pair(it * ir * is, "TRS"),
std::make_pair(it * is * ir, "TSR"),
}
};
std::array<std::pair<glm::decompose::order, std::string>, 6> const decompose_order_list = {
{
std::make_pair(glm::decompose::rst, "RST"),
std::make_pair(glm::decompose::rts, "RTS"),
std::make_pair(glm::decompose::srt, "SRT"),
std::make_pair(glm::decompose::str, "STR"),
std::make_pair(glm::decompose::trs, "TRS"),
std::make_pair(glm::decompose::tsr, "TSR"),
}
};
for (auto i : input_xform_list) {
for (auto e : decompose_order_list) {
glm::mat4 r, s, t;
glm::mat4 const x(glm::convert::transform(i.first, e.first, r, s, t));
matrix_pair const p(std::make_pair(i.first, x));
BOOST_TEST_MESSAGE(glm::io::precision(7) << glm::io::width(1 + 1 + 1 + 7)
<< i.second << ':' << std::string(47 - i.second.length(), ' ')
<< e.second << ':' << p << '\n');
static float const epsilon(177 * std::numeric_limits<float>::epsilon());
for (unsigned i(0); i < 4; ++i) {
for (unsigned j(0); j < 4; ++j) {
BOOST_CHECK(std::abs(p.first[i][j] - p.second[i][j]) < epsilon);
}
}
}
}
}
<commit_msg>fixed: MSVC 19.0 warning<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2016 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : glm/test/gtx_utilities.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// includes, system
#include <array> // std::array<>
#include <glm/gtc/constants.hpp> // glm::pi
#include <glm/gtc/random.hpp> // glm::*Rand
#include <glm/gtc/vec1.hpp> // glm::vec1
#include <glm/gtx/io.hpp> // glm::operator<<
#include <glm/gtx/transform.hpp> // glm::rotate, glm::scale, glm::translate>
// includes, project
#include <glm/gtx/utilities.hpp>
#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/mpl/list.hpp>
BOOST_AUTO_TEST_CASE(test_hugh_glm_gtx_utilities_op_literal_deg)
{
#if defined(_MSC_VER) && (_MSC_VER <= 1900)
BOOST_CHECK(glm::pi<double>() == 180.0 _deg);
BOOST_TEST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0 _deg);
#else
BOOST_CHECK(glm::pi<double>() == 180.0_deg);
BOOST_TEST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0_deg);
#endif
}
BOOST_AUTO_TEST_CASE(test_hugh_glm_gtx_utilities_op_literal_rad)
{
#if defined(_MSC_VER) && (_MSC_VER <= 1900)
BOOST_CHECK(glm::pi<double>() == 180.0 _deg);
BOOST_TEST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0 _deg);
#else
BOOST_CHECK(180.0_deg == glm::pi<double>());
BOOST_TEST_MESSAGE(std::setprecision(12)
<< "180.0_deg:" << 180.0_deg
<< " =?= glm::pi<double>():" << glm::pi<double>());
#endif
}
using rev_types = boost::mpl::list<glm::vec1, glm::vec2, glm::vec3, glm::vec4,
glm::dvec1, glm::dvec2, glm::dvec3, glm::dvec4>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_hugh_glm_gtx_utilities_rev, T, rev_types)
{
BOOST_CHECK(glm::rev(T(glm::two_pi<typename T::value_type>())) == T(0.0));
}
BOOST_AUTO_TEST_CASE(test_hugh_glm_gtx_utilities_sgn)
{
BOOST_CHECK(glm::sgn(-1) < 0);
BOOST_CHECK(glm::sgn(+1) > 0);
}
BOOST_AUTO_TEST_CASE(test_hugh_glm_gtx_utilities_convert_transform)
{
using matrix_pair = std::pair<glm::mat4 const, glm::mat4 const>;
#if defined(_MSC_VER) && (_MSC_VER <= 1900)
glm::vec3::value_type const angle(float(45 _deg));
#else
glm::vec3::value_type const angle(float(45_deg));
#endif
glm::mat4 const ir(glm::rotate (angle, glm::vec3(glm::gaussRand( 0.0, 20.0),
glm::gaussRand( 0.0, 20.0),
glm::gaussRand( 0.0, 20.0))));
glm::mat4 const is(glm::scale ( glm::vec3(glm::linearRand( 0.1, 10.0),
glm::linearRand( 0.1, 10.0),
glm::linearRand( 0.1, 10.0))));
glm::mat4 const it(glm::translate( glm::vec3(glm::linearRand(-1.0, 1.0),
glm::linearRand(-1.0, 1.0),
glm::linearRand(-1.0, 1.0))));
std::array<std::pair<glm::mat4, std::string>, 7> const input_xform_list = {
{
std::make_pair(glm::mat4(), "Identity"),
std::make_pair(ir * is * it, "RST"),
std::make_pair(ir * it * is, "RTS"),
std::make_pair(is * ir * it, "SRT"),
std::make_pair(is * it * ir, "STR"),
std::make_pair(it * ir * is, "TRS"),
std::make_pair(it * is * ir, "TSR"),
}
};
std::array<std::pair<glm::decompose::order, std::string>, 6> const decompose_order_list = {
{
std::make_pair(glm::decompose::rst, "RST"),
std::make_pair(glm::decompose::rts, "RTS"),
std::make_pair(glm::decompose::srt, "SRT"),
std::make_pair(glm::decompose::str, "STR"),
std::make_pair(glm::decompose::trs, "TRS"),
std::make_pair(glm::decompose::tsr, "TSR"),
}
};
for (auto ix : input_xform_list) {
for (auto e : decompose_order_list) {
glm::mat4 r, s, t;
glm::mat4 const x(glm::convert::transform(ix.first, e.first, r, s, t));
matrix_pair const p(std::make_pair(ix.first, x));
BOOST_TEST_MESSAGE(glm::io::precision(7) << glm::io::width(1 + 1 + 1 + 7)
<< ix.second << ':' << std::string(47 - ix.second.length(), ' ')
<< e.second << ':' << p << '\n');
static float const epsilon(177 * std::numeric_limits<float>::epsilon());
for (unsigned i(0); i < 4; ++i) {
for (unsigned j(0); j < 4; ++j) {
BOOST_CHECK(std::abs(p.first[i][j] - p.second[i][j]) < epsilon);
}
}
}
}
}
<|endoftext|> |
<commit_before>#include "GUI.hpp"
#include <string>
#include <vector>
#include <QMessageBox>
#include <QAction>
#include <QCloseEvent>
#include <QFontDatabase>
#include "Game.hpp"
#include "NewGameDialog.hpp"
#include "VirtualView.hpp"
#include "AugmentedView.hpp"
namespace Go_GUI {
GUI::GUI(QWidget *parent) : QMainWindow(parent), go_game(nullptr)
{
ui_main.setupUi(this);
texture_path = "res/textures/";
QApplication::setWindowIcon(QIcon(QPixmap(texture_path + "augmented_logo_transparent_icon.png")));
augmented_logo = QImage(texture_path + "augmented_logo.png");
virtual_view = new VirtualView(this);
augmented_view = new AugmentedView(this);
switchbutton_icon = QIcon(texture_path + "Arrow_SwitchButton.png");
switchbuttonpressed_icon = QIcon(texture_path + "Arrow_SwitchButton_pressed.png");
whitebasket_pixmap = QPixmap(texture_path + "white_basket.png");
blackbasket_pixmap = QPixmap(texture_path + "black_basket.png");
closedbasket_pixmap = QPixmap(texture_path + "Closed_basket.png");
gotable_pixmap = QPixmap(texture_path + "go_table.png");
if (blackbasket_pixmap.isNull() || whitebasket_pixmap.isNull() || closedbasket_pixmap.isNull() || gotable_pixmap.isNull())
QMessageBox::critical(this, "GUI element not found", QString("White and/or black basket textures not found!\n searched relative to exe in: " + texture_path));
// loading font
QFontDatabase fontDatabase;
QString font_path = "res/fonts/SHOJUMARU-REGULAR.TTF";
if (fontDatabase.addApplicationFont(font_path) == -1)
QMessageBox::critical(this, "Font not found", QString("Shojumaru font was not found!\n searched relative to exe in: " + font_path));
// connections
connect(ui_main.open_action, &QAction::triggered, this, &GUI::slot_MenuOpen);
connect(ui_main.save_action, &QAction::triggered, this, &GUI::slot_MenuSave);
connect(ui_main.exit_action, &QAction::triggered, this, &QWidget::close);
connect(ui_main.info_action, &QAction::triggered, this, &GUI::slot_MenuInfo);
connect(ui_main.automatic_action, &QAction::triggered, this, &GUI::slot_BoardDetectionAutomatically);
connect(ui_main.manually_action, &QAction::triggered, this, &GUI::slot_BoardDetectionManually);
connect(ui_main.virtual_game_mode_action, &QAction::triggered, this, &GUI::slot_ToggleVirtualGameMode);
connect(this, &GUI::signal_setVirtualGameMode, this->virtual_view, &VirtualView::slot_setVirtualGameMode);
connect(ui_main.viewswitch_button, &QPushButton::pressed, this, &GUI::slot_ViewSwitch);
connect(ui_main.viewswitch_button, &QPushButton::released, this, &GUI::slot_ViewSwitch_released);
connect(ui_main.newgame_button, &QPushButton::clicked, this, &GUI::slot_ButtonNewGame);
connect(ui_main.pass_button, &QPushButton::clicked, this, &GUI::slot_ButtonPass);
connect(ui_main.resign_button, &QPushButton::clicked, this, &GUI::slot_ButtonResign);
connect(this->virtual_view, &VirtualView::signal_virtualViewplayMove, this, &GUI::slot_passOnVirtualViewPlayMove);
// setting initial values
this->init();
}
void GUI::init(){
this->setWindowTitle("Augmented Go");
this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// Attaching augmented view to big container
augmented_view->setParent(ui_main.big_container);
augmented_view->rescaleImage(ui_main.big_container->size());
ui_main.big_container->setToolTip("augmented view");
augmented_view->show();
// Attaching virtual view to small container
virtual_view->setParent(ui_main.small_container);
ui_main.small_container->setToolTip("virtual view");
virtual_view->show();
ui_main.white_basket->setPixmap(closedbasket_pixmap);
ui_main.black_basket->setPixmap(closedbasket_pixmap);
ui_main.go_table_label->setPixmap(gotable_pixmap);
ui_main.viewswitch_button->setIcon(switchbutton_icon);
ui_main.capturedwhite_label->setText(QString());
ui_main.capturedblack_label->setText(QString());
emit signal_setVirtualGameMode(ui_main.virtual_game_mode_action->isChecked());
}
void GUI::setPlayerLabels(QString blackplayer_name, QString whiteplayer_name){
ui_main.blackplayer_label->setText(blackplayer_name);
ui_main.whiteplayer_label->setText(whiteplayer_name);
}
//////////
//Private Slots
//////////
void GUI::slot_ButtonNewGame(){
NewGameDialog* newgame = new NewGameDialog(this);
newgame->exec();
}
void GUI::slot_ButtonResign(){
if (QMessageBox::question(this, "Resign", "Do you really want to admit defeat?") == QMessageBox::Yes)
emit signal_resign();
}
void GUI::slot_ButtonPass(){
if (QMessageBox::question(this, "Pass", "Do you really want to pass?") == QMessageBox::Yes)
emit signal_pass();
}
void GUI::slot_ViewSwitch(){
ui_main.viewswitch_button->setIcon(this->switchbuttonpressed_icon);
auto differences = go_game->getDifferences();
if (ui_main.big_container->toolTip() == "virtual view"){
// switching augmented view to big container
augmented_view->setParent(ui_main.big_container);
augmented_view->rescaleImage(ui_main.big_container->size());
ui_main.big_container->setToolTip("augmented view");
augmented_view->show(); // when changing parent, it gets invisible -> show again! -.- !!
// new style
virtual_view->setParent(ui_main.small_container);
virtual_view->createAndSetScene(ui_main.small_container->size(), differences, &(go_game->getBoard()));
ui_main.small_container->setToolTip("virtual view");
virtual_view->show();
}
else if (ui_main.big_container->toolTip() == "augmented view"){
// switching augmented view to small container
augmented_view->setParent(ui_main.small_container);
augmented_view->rescaleImage(ui_main.small_container->size());
ui_main.small_container->setToolTip("augmented view");
augmented_view->show(); // when changing parent, it gets invisible -> show again! -.- !!
virtual_view->setParent(ui_main.big_container);
virtual_view->createAndSetScene(ui_main.big_container->size(), differences, &(go_game->getBoard()));
ui_main.big_container->setToolTip("virtual view");
virtual_view->show();
}
}
void GUI::slot_ViewSwitch_released(){
ui_main.viewswitch_button->setIcon(this->switchbutton_icon);
}
void GUI::slot_MenuOpen(){
QString selfilter = tr("SGF (*.sgf)");
QString fileName = QFileDialog::getOpenFileName(
this,
"open sgf-file",
NULL,
tr("SGF (*.sgf)" ),
&selfilter
);
if (!fileName.isNull()){
// TODO ask if user wants to save the current game!
emit signal_openGame(fileName);
}
}
void GUI::slot_MenuSave(){
QString selfilter = tr("SGF (*.sgf)");
QString fileName = QFileDialog::getSaveFileName(
this,
"save sgf-file",
NULL,
tr("SGF (*.sgf)" ),
&selfilter
);
if (!fileName.isNull())
emit signal_saveGame(fileName, ui_main.blackplayer_label->text(), ui_main.whiteplayer_label->text(), this->game_name);
}
void GUI::slot_MenuInfo(){
// Appliction Info
std::string output = "Augmented Go - Interactive Game of Go as Augmented Reality Application\n\n\n";
// Build date and time
output += "This build of Augmented Go was compiled at " __DATE__ ", " __TIME__ ".\n";
// Copyright
std::string year = __DATE__;
year = year.substr(year.find_last_of(" ")); // deleting day and month
output += "Copyright " + year + "\n";
// Licence
output += "\nThis software is released under the \"MIT License\".\n"
"See the file LICENSE for full license and copying terms.\n";
// Final InfoBox
QMessageBox::about(this, "Info", output.c_str());
}
void GUI::slot_BoardDetectionManually() {
emit signal_boardDetectionManually();
}
void GUI::slot_BoardDetectionAutomatically() {
emit signal_boardDetectionAutomatically();
}
void GUI::slot_ToggleVirtualGameMode() {
// if in augmented mode -> switch to virtual
if (ui_main.virtual_game_mode_action->isChecked()){
this->setWindowTitle("Augmented Go - Virtual Mode");
// change virtual view to big container
if (ui_main.big_container->toolTip() != "virtual view")
this->slot_ViewSwitch();
emit signal_setVirtualGameMode(true);
slot_newImage(augmented_logo);
}
// if in virtual mode -> switch to augmented
else{
this->setWindowTitle("Augmented Go");
// change augmented view to big container
if (ui_main.big_container->toolTip() != "augmented view")
this->slot_ViewSwitch();
augmented_view->setStyleSheet("background-color: black");
emit signal_setVirtualGameMode(false);
}
}
void GUI::slot_passOnVirtualViewPlayMove(const int x, const int y){
emit this->signal_playMove(x, y);
}
//////////
//Public Slots
//////////
void GUI::slot_newImage(QImage image) {
printf(">>> New Image arrived! '%d x %d' -- Format: %d <<<\n", image.width(), image.height(), image.format());
augmented_view->setImage(image);
augmented_view->rescaleImage(augmented_view->parentWidget()->size());
}
void GUI::slot_newGameData(const GoBackend::Game* game) {
// update internal pointer if the board has been changed
if (go_game != game)
go_game = game;
auto& board = go_game->getBoard();
auto differences = go_game->getDifferences();
auto current_player = board.ToPlay();
// Updating basket pictures
switch (current_player) {
case SG_WHITE:
ui_main.white_basket->setPixmap(whitebasket_pixmap);
ui_main.black_basket->setPixmap(closedbasket_pixmap);
break;
case SG_BLACK:
ui_main.white_basket->setPixmap(closedbasket_pixmap);
ui_main.black_basket->setPixmap(blackbasket_pixmap);
break;
default:
assert(false);
break;
}
// Updating Game-Settings
ui_main.movenumber_label->setText(QString::number(board.MoveNumber()));
ui_main.kominumber_label->setText(QString::number(board.Rules().Komi().ToFloat()));
ui_main.handicapnumber_label->setText(QString::number(board.Rules().Handicap()));
ui_main.capturedwhite_label->setText(QString::number(board.NumPrisoners(SG_WHITE)));
ui_main.capturedblack_label->setText(QString::number(board.NumPrisoners(SG_BLACK)));
// refresh virtual view
if (ui_main.big_container->toolTip() == "virtual view")
virtual_view->createAndSetScene(ui_main.big_container->size(), differences, &board);
else if (ui_main.big_container->toolTip() == "augmented view")
virtual_view->createAndSetScene(ui_main.small_container->size(), differences, &board);
printf(">>> New Game data! <<<\n");
}
void GUI::slot_showFinishedGameResults(QString result){
QMessageBox::information(this, "Game results", result);
auto answer = QMessageBox::question(this, "New Game?", "Do you want to start a new game?");
if (answer == QMessageBox::Yes)
this->slot_ButtonNewGame();
}
void GUI::slot_setupNewGame(QString game_name, QString blackplayer_name, QString whiteplayer_name, float komi){
// emit to backend that gui wants to set up a new game!
auto rules = GoRules(0, GoKomi(komi), true, true);
emit signal_newGame(rules);
// Setting up new names for players
ui_main.gamename_label->setText(game_name);
ui_main.blackplayer_label->setText(blackplayer_name);
ui_main.whiteplayer_label->setText(whiteplayer_name);
ui_main.kominumber_label->setText(QString::number(komi));
ui_main.handicapnumber_label->setText(QString::number(0));
}
///////////
//Events
///////////
void GUI::closeEvent(QCloseEvent *event){
// If at least one move was was done
// TODO If game loaded -> move number greater than start number!
int answer = 0;
// if at least one move was made -> ask if user wants to save
bool saveable = ui_main.movenumber_label->text().toInt() > 0;
if (saveable)
answer = QMessageBox::question(this, "Save?", "Do you want to save before quitting?", "Save", "Don't Save", "Cancel");
else
answer = QMessageBox::question(this, "Quit?", "Do you really want to quit?", "Quit", "Cancel");
if(answer == 0 && saveable){
this->slot_MenuSave();
emit stop_backend_thread();
event->accept();
}
else if((answer == 1 && saveable)
|| (answer == 0 && !saveable)){
emit stop_backend_thread();
event->accept();
}
else
event->ignore();
}
} // namespace Go_GUI<commit_msg>refs #115 - Quick fix for the crash if go_game is null<commit_after>#include "GUI.hpp"
#include <string>
#include <vector>
#include <QMessageBox>
#include <QAction>
#include <QCloseEvent>
#include <QFontDatabase>
#include "Game.hpp"
#include "NewGameDialog.hpp"
#include "VirtualView.hpp"
#include "AugmentedView.hpp"
namespace Go_GUI {
GUI::GUI(QWidget *parent) : QMainWindow(parent), go_game(nullptr)
{
ui_main.setupUi(this);
texture_path = "res/textures/";
QApplication::setWindowIcon(QIcon(QPixmap(texture_path + "augmented_logo_transparent_icon.png")));
augmented_logo = QImage(texture_path + "augmented_logo.png");
virtual_view = new VirtualView(this);
augmented_view = new AugmentedView(this);
switchbutton_icon = QIcon(texture_path + "Arrow_SwitchButton.png");
switchbuttonpressed_icon = QIcon(texture_path + "Arrow_SwitchButton_pressed.png");
whitebasket_pixmap = QPixmap(texture_path + "white_basket.png");
blackbasket_pixmap = QPixmap(texture_path + "black_basket.png");
closedbasket_pixmap = QPixmap(texture_path + "Closed_basket.png");
gotable_pixmap = QPixmap(texture_path + "go_table.png");
if (blackbasket_pixmap.isNull() || whitebasket_pixmap.isNull() || closedbasket_pixmap.isNull() || gotable_pixmap.isNull())
QMessageBox::critical(this, "GUI element not found", QString("White and/or black basket textures not found!\n searched relative to exe in: " + texture_path));
// loading font
QFontDatabase fontDatabase;
QString font_path = "res/fonts/SHOJUMARU-REGULAR.TTF";
if (fontDatabase.addApplicationFont(font_path) == -1)
QMessageBox::critical(this, "Font not found", QString("Shojumaru font was not found!\n searched relative to exe in: " + font_path));
// connections
connect(ui_main.open_action, &QAction::triggered, this, &GUI::slot_MenuOpen);
connect(ui_main.save_action, &QAction::triggered, this, &GUI::slot_MenuSave);
connect(ui_main.exit_action, &QAction::triggered, this, &QWidget::close);
connect(ui_main.info_action, &QAction::triggered, this, &GUI::slot_MenuInfo);
connect(ui_main.automatic_action, &QAction::triggered, this, &GUI::slot_BoardDetectionAutomatically);
connect(ui_main.manually_action, &QAction::triggered, this, &GUI::slot_BoardDetectionManually);
connect(ui_main.virtual_game_mode_action, &QAction::triggered, this, &GUI::slot_ToggleVirtualGameMode);
connect(this, &GUI::signal_setVirtualGameMode, this->virtual_view, &VirtualView::slot_setVirtualGameMode);
connect(ui_main.viewswitch_button, &QPushButton::pressed, this, &GUI::slot_ViewSwitch);
connect(ui_main.viewswitch_button, &QPushButton::released, this, &GUI::slot_ViewSwitch_released);
connect(ui_main.newgame_button, &QPushButton::clicked, this, &GUI::slot_ButtonNewGame);
connect(ui_main.pass_button, &QPushButton::clicked, this, &GUI::slot_ButtonPass);
connect(ui_main.resign_button, &QPushButton::clicked, this, &GUI::slot_ButtonResign);
connect(this->virtual_view, &VirtualView::signal_virtualViewplayMove, this, &GUI::slot_passOnVirtualViewPlayMove);
// setting initial values
this->init();
}
void GUI::init(){
this->setWindowTitle("Augmented Go");
this->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
// Attaching augmented view to big container
augmented_view->setParent(ui_main.big_container);
augmented_view->rescaleImage(ui_main.big_container->size());
ui_main.big_container->setToolTip("augmented view");
augmented_view->show();
// Attaching virtual view to small container
virtual_view->setParent(ui_main.small_container);
ui_main.small_container->setToolTip("virtual view");
virtual_view->show();
ui_main.white_basket->setPixmap(closedbasket_pixmap);
ui_main.black_basket->setPixmap(closedbasket_pixmap);
ui_main.go_table_label->setPixmap(gotable_pixmap);
ui_main.viewswitch_button->setIcon(switchbutton_icon);
ui_main.capturedwhite_label->setText(QString());
ui_main.capturedblack_label->setText(QString());
emit signal_setVirtualGameMode(ui_main.virtual_game_mode_action->isChecked());
}
void GUI::setPlayerLabels(QString blackplayer_name, QString whiteplayer_name){
ui_main.blackplayer_label->setText(blackplayer_name);
ui_main.whiteplayer_label->setText(whiteplayer_name);
}
//////////
//Private Slots
//////////
void GUI::slot_ButtonNewGame(){
NewGameDialog* newgame = new NewGameDialog(this);
newgame->exec();
}
void GUI::slot_ButtonResign(){
if (QMessageBox::question(this, "Resign", "Do you really want to admit defeat?") == QMessageBox::Yes)
emit signal_resign();
}
void GUI::slot_ButtonPass(){
if (QMessageBox::question(this, "Pass", "Do you really want to pass?") == QMessageBox::Yes)
emit signal_pass();
}
void GUI::slot_ViewSwitch(){
if (go_game == nullptr)
return;
ui_main.viewswitch_button->setIcon(this->switchbuttonpressed_icon);
auto differences = go_game->getDifferences();
if (ui_main.big_container->toolTip() == "virtual view"){
// switching augmented view to big container
augmented_view->setParent(ui_main.big_container);
augmented_view->rescaleImage(ui_main.big_container->size());
ui_main.big_container->setToolTip("augmented view");
augmented_view->show(); // when changing parent, it gets invisible -> show again! -.- !!
// new style
virtual_view->setParent(ui_main.small_container);
virtual_view->createAndSetScene(ui_main.small_container->size(), differences, &(go_game->getBoard()));
ui_main.small_container->setToolTip("virtual view");
virtual_view->show();
}
else if (ui_main.big_container->toolTip() == "augmented view"){
// switching augmented view to small container
augmented_view->setParent(ui_main.small_container);
augmented_view->rescaleImage(ui_main.small_container->size());
ui_main.small_container->setToolTip("augmented view");
augmented_view->show(); // when changing parent, it gets invisible -> show again! -.- !!
virtual_view->setParent(ui_main.big_container);
virtual_view->createAndSetScene(ui_main.big_container->size(), differences, &(go_game->getBoard()));
ui_main.big_container->setToolTip("virtual view");
virtual_view->show();
}
}
void GUI::slot_ViewSwitch_released(){
ui_main.viewswitch_button->setIcon(this->switchbutton_icon);
}
void GUI::slot_MenuOpen(){
QString selfilter = tr("SGF (*.sgf)");
QString fileName = QFileDialog::getOpenFileName(
this,
"open sgf-file",
NULL,
tr("SGF (*.sgf)" ),
&selfilter
);
if (!fileName.isNull()){
// TODO ask if user wants to save the current game!
emit signal_openGame(fileName);
}
}
void GUI::slot_MenuSave(){
QString selfilter = tr("SGF (*.sgf)");
QString fileName = QFileDialog::getSaveFileName(
this,
"save sgf-file",
NULL,
tr("SGF (*.sgf)" ),
&selfilter
);
if (!fileName.isNull())
emit signal_saveGame(fileName, ui_main.blackplayer_label->text(), ui_main.whiteplayer_label->text(), this->game_name);
}
void GUI::slot_MenuInfo(){
// Appliction Info
std::string output = "Augmented Go - Interactive Game of Go as Augmented Reality Application\n\n\n";
// Build date and time
output += "This build of Augmented Go was compiled at " __DATE__ ", " __TIME__ ".\n";
// Copyright
std::string year = __DATE__;
year = year.substr(year.find_last_of(" ")); // deleting day and month
output += "Copyright " + year + "\n";
// Licence
output += "\nThis software is released under the \"MIT License\".\n"
"See the file LICENSE for full license and copying terms.\n";
// Final InfoBox
QMessageBox::about(this, "Info", output.c_str());
}
void GUI::slot_BoardDetectionManually() {
emit signal_boardDetectionManually();
}
void GUI::slot_BoardDetectionAutomatically() {
emit signal_boardDetectionAutomatically();
}
void GUI::slot_ToggleVirtualGameMode() {
// if in augmented mode -> switch to virtual
if (ui_main.virtual_game_mode_action->isChecked()){
this->setWindowTitle("Augmented Go - Virtual Mode");
// change virtual view to big container
if (ui_main.big_container->toolTip() != "virtual view")
this->slot_ViewSwitch();
emit signal_setVirtualGameMode(true);
slot_newImage(augmented_logo);
}
// if in virtual mode -> switch to augmented
else{
this->setWindowTitle("Augmented Go");
// change augmented view to big container
if (ui_main.big_container->toolTip() != "augmented view")
this->slot_ViewSwitch();
augmented_view->setStyleSheet("background-color: black");
emit signal_setVirtualGameMode(false);
}
}
void GUI::slot_passOnVirtualViewPlayMove(const int x, const int y){
emit this->signal_playMove(x, y);
}
//////////
//Public Slots
//////////
void GUI::slot_newImage(QImage image) {
printf(">>> New Image arrived! '%d x %d' -- Format: %d <<<\n", image.width(), image.height(), image.format());
augmented_view->setImage(image);
augmented_view->rescaleImage(augmented_view->parentWidget()->size());
}
void GUI::slot_newGameData(const GoBackend::Game* game) {
// update internal pointer if the board has been changed
if (go_game != game)
go_game = game;
if (go_game == nullptr)
return;
auto& board = go_game->getBoard();
auto differences = go_game->getDifferences();
auto current_player = board.ToPlay();
// Updating basket pictures
switch (current_player) {
case SG_WHITE:
ui_main.white_basket->setPixmap(whitebasket_pixmap);
ui_main.black_basket->setPixmap(closedbasket_pixmap);
break;
case SG_BLACK:
ui_main.white_basket->setPixmap(closedbasket_pixmap);
ui_main.black_basket->setPixmap(blackbasket_pixmap);
break;
default:
assert(false);
break;
}
// Updating Game-Settings
ui_main.movenumber_label->setText(QString::number(board.MoveNumber()));
ui_main.kominumber_label->setText(QString::number(board.Rules().Komi().ToFloat()));
ui_main.handicapnumber_label->setText(QString::number(board.Rules().Handicap()));
ui_main.capturedwhite_label->setText(QString::number(board.NumPrisoners(SG_WHITE)));
ui_main.capturedblack_label->setText(QString::number(board.NumPrisoners(SG_BLACK)));
// refresh virtual view
if (ui_main.big_container->toolTip() == "virtual view")
virtual_view->createAndSetScene(ui_main.big_container->size(), differences, &board);
else if (ui_main.big_container->toolTip() == "augmented view")
virtual_view->createAndSetScene(ui_main.small_container->size(), differences, &board);
printf(">>> New Game data! <<<\n");
}
void GUI::slot_showFinishedGameResults(QString result){
QMessageBox::information(this, "Game results", result);
auto answer = QMessageBox::question(this, "New Game?", "Do you want to start a new game?");
if (answer == QMessageBox::Yes)
this->slot_ButtonNewGame();
}
void GUI::slot_setupNewGame(QString game_name, QString blackplayer_name, QString whiteplayer_name, float komi){
// emit to backend that gui wants to set up a new game!
auto rules = GoRules(0, GoKomi(komi), true, true);
emit signal_newGame(rules);
// Setting up new names for players
ui_main.gamename_label->setText(game_name);
ui_main.blackplayer_label->setText(blackplayer_name);
ui_main.whiteplayer_label->setText(whiteplayer_name);
ui_main.kominumber_label->setText(QString::number(komi));
ui_main.handicapnumber_label->setText(QString::number(0));
}
///////////
//Events
///////////
void GUI::closeEvent(QCloseEvent *event){
// If at least one move was was done
// TODO If game loaded -> move number greater than start number!
int answer = 0;
// if at least one move was made -> ask if user wants to save
bool saveable = ui_main.movenumber_label->text().toInt() > 0;
if (saveable)
answer = QMessageBox::question(this, "Save?", "Do you want to save before quitting?", "Save", "Don't Save", "Cancel");
else
answer = QMessageBox::question(this, "Quit?", "Do you really want to quit?", "Quit", "Cancel");
if(answer == 0 && saveable){
this->slot_MenuSave();
emit stop_backend_thread();
event->accept();
}
else if((answer == 1 && saveable)
|| (answer == 0 && !saveable)){
emit stop_backend_thread();
event->accept();
}
else
event->ignore();
}
} // namespace Go_GUI<|endoftext|> |
<commit_before>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : glm/test/gtx_utilities.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// includes, system
#include <array> // std::array<>
#include <glm/gtc/constants.hpp> // glm::pi
#include <glm/gtc/random.hpp> // glm::*Rand
#include <glm/gtx/io.hpp> // glm::operator<<
#include <glm/gtx/transform.hpp> // glm::rotate, gm::scale, glm::translate>
// includes, project
#include <glm/gtx/utilities.hpp>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test_utilities_deg2rad)
{
BOOST_CHECK(glm::pi<double>() == glm::deg2rad(180.0));
BOOST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= deg2rad(180.0):" << glm::deg2rad(180.0));
}
BOOST_AUTO_TEST_CASE(test_utilities_rad2deg)
{
BOOST_CHECK(180.0 == glm::rad2deg(glm::pi<double>()));
BOOST_MESSAGE(std::setprecision(12)
<< 180.0 << " =?= rad2deg(glm::pi<double>():"
<< glm::rad2deg(glm::pi<double>()));
}
BOOST_AUTO_TEST_CASE(test_utilities_op_literal_deg)
{
#if defined(_MSC_VER) && (_MSC_VER <= 1700)
BOOST_CHECK(glm::pi<double>() == 180.0 _deg);
BOOST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0 _deg);
#else
BOOST_CHECK(glm::pi<double>() == 180.0_deg);
BOOST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0_deg);
#endif
}
BOOST_AUTO_TEST_CASE(test_utilities_op_literal_rad)
{
#if defined(_MSC_VER) && (_MSC_VER <= 1700)
BOOST_CHECK(glm::pi<double>() == 180.0 _deg);
BOOST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0 _deg);
#else
BOOST_CHECK(180.0_deg == glm::pi<double>());
BOOST_MESSAGE(std::setprecision(12)
<< "180.0_deg:" << 180.0_deg
<< " =?= glm::pi<double>():" << glm::pi<double>());
#endif
}
BOOST_AUTO_TEST_CASE(test_utilities_convert_transform)
{
typedef std::pair<glm::mat4 const, glm::mat4 const> matrix_pair;
#if defined(_MSC_VER) && (_MSC_VER <= 1700)
glm::vec3::value_type const angle(45 _deg);
#else
glm::vec3::value_type const angle(45_deg);
#endif
glm::mat4 const ir(glm::rotate (angle, glm::vec3(glm::gaussRand(0.0, 20.0),
glm::gaussRand(0.0, 20.0),
glm::gaussRand(0.0, 20.0))));
glm::mat4 const is(glm::scale ( glm::vec3(glm::linearRand(0.1, 10.0),
glm::linearRand(0.1, 10.0),
glm::linearRand(0.1, 10.0))));
glm::mat4 const it(glm::translate( glm::vec3(glm::linearRand(-1.0, 1.0),
glm::linearRand(-1.0, 1.0),
glm::linearRand(-1.0, 1.0))));
std::array<std::pair<glm::mat4, std::string>, 7> const input_xform_list = {
{
std::make_pair(glm::mat4(), "Identity"),
std::make_pair(ir * is * it, "RST"),
std::make_pair(ir * it * is, "RTS"),
std::make_pair(is * ir * it, "SRT"),
std::make_pair(is * it * ir, "STR"),
std::make_pair(it * ir * is, "TRS"),
std::make_pair(it * is * ir, "TSR"),
}
};
std::array<std::pair<glm::decompose::order, std::string>, 6> const decompose_order_list = {
{
std::make_pair(glm::decompose::rst, "RST"),
std::make_pair(glm::decompose::rts, "RTS"),
std::make_pair(glm::decompose::srt, "SRT"),
std::make_pair(glm::decompose::str, "STR"),
std::make_pair(glm::decompose::trs, "TRS"),
std::make_pair(glm::decompose::tsr, "TSR"),
}
};
for (auto i : input_xform_list) {
for (auto e : decompose_order_list) {
glm::mat4 r, s, t;
glm::mat4 const x(glm::convert::transform(i.first, e.first, r, s, t));
matrix_pair const p(std::make_pair(i.first, x));
BOOST_MESSAGE(i.second << ':' << std::string(43 - i.second.length(), ' ') << e.second << ':'
<< p << '\n');
for (unsigned i(0); i < 4; ++i) {
for (unsigned j(0); j < 4; ++j) {
BOOST_CHECK(std::abs(p.first[i][j] - p.second[i][j]) < 5E-6);
}
}
}
}
}
<commit_msg>fixed: epsilon comparison value for decomposition tests<commit_after>// -*- Mode:C++ -*-
/**************************************************************************************************/
/* */
/* Copyright (C) 2014 University of Hull */
/* */
/**************************************************************************************************/
/* */
/* module : glm/test/gtx_utilities.cpp */
/* project : */
/* description: */
/* */
/**************************************************************************************************/
// includes, system
#include <array> // std::array<>
#include <glm/gtc/constants.hpp> // glm::pi
#include <glm/gtc/random.hpp> // glm::*Rand
#include <glm/gtx/io.hpp> // glm::operator<<
#include <glm/gtx/transform.hpp> // glm::rotate, gm::scale, glm::translate>
// includes, project
#include <glm/gtx/utilities.hpp>
#define UKACHULLDCS_USE_TRACE
#undef UKACHULLDCS_USE_TRACE
#include <support/trace.hpp>
// internal unnamed namespace
namespace {
// types, internal (class, enum, struct, union, typedef)
// variables, internal
// functions, internal
} // namespace {
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_CASE(test_utilities_deg2rad)
{
BOOST_CHECK(glm::pi<double>() == glm::deg2rad(180.0));
BOOST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= deg2rad(180.0):" << glm::deg2rad(180.0));
}
BOOST_AUTO_TEST_CASE(test_utilities_rad2deg)
{
BOOST_CHECK(180.0 == glm::rad2deg(glm::pi<double>()));
BOOST_MESSAGE(std::setprecision(12)
<< 180.0 << " =?= rad2deg(glm::pi<double>():"
<< glm::rad2deg(glm::pi<double>()));
}
BOOST_AUTO_TEST_CASE(test_utilities_op_literal_deg)
{
#if defined(_MSC_VER) && (_MSC_VER <= 1700)
BOOST_CHECK(glm::pi<double>() == 180.0 _deg);
BOOST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0 _deg);
#else
BOOST_CHECK(glm::pi<double>() == 180.0_deg);
BOOST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0_deg);
#endif
}
BOOST_AUTO_TEST_CASE(test_utilities_op_literal_rad)
{
#if defined(_MSC_VER) && (_MSC_VER <= 1700)
BOOST_CHECK(glm::pi<double>() == 180.0 _deg);
BOOST_MESSAGE(std::setprecision(12)
<< "glm::pi<double>():" << glm::pi<double>()
<< " =?= 180.0_deg:" << 180.0 _deg);
#else
BOOST_CHECK(180.0_deg == glm::pi<double>());
BOOST_MESSAGE(std::setprecision(12)
<< "180.0_deg:" << 180.0_deg
<< " =?= glm::pi<double>():" << glm::pi<double>());
#endif
}
BOOST_AUTO_TEST_CASE(test_utilities_convert_transform)
{
typedef std::pair<glm::mat4 const, glm::mat4 const> matrix_pair;
#if defined(_MSC_VER) && (_MSC_VER <= 1700)
glm::vec3::value_type const angle(45 _deg);
#else
glm::vec3::value_type const angle(45_deg);
#endif
glm::mat4 const ir(glm::rotate (angle, glm::vec3(glm::gaussRand( 0.0, 20.0),
glm::gaussRand( 0.0, 20.0),
glm::gaussRand( 0.0, 20.0))));
glm::mat4 const is(glm::scale ( glm::vec3(glm::linearRand( 0.1, 10.0),
glm::linearRand( 0.1, 10.0),
glm::linearRand( 0.1, 10.0))));
glm::mat4 const it(glm::translate( glm::vec3(glm::linearRand(-1.0, 1.0),
glm::linearRand(-1.0, 1.0),
glm::linearRand(-1.0, 1.0))));
std::array<std::pair<glm::mat4, std::string>, 7> const input_xform_list = {
{
std::make_pair(glm::mat4(), "Identity"),
std::make_pair(ir * is * it, "RST"),
std::make_pair(ir * it * is, "RTS"),
std::make_pair(is * ir * it, "SRT"),
std::make_pair(is * it * ir, "STR"),
std::make_pair(it * ir * is, "TRS"),
std::make_pair(it * is * ir, "TSR"),
}
};
std::array<std::pair<glm::decompose::order, std::string>, 6> const decompose_order_list = {
{
std::make_pair(glm::decompose::rst, "RST"),
std::make_pair(glm::decompose::rts, "RTS"),
std::make_pair(glm::decompose::srt, "SRT"),
std::make_pair(glm::decompose::str, "STR"),
std::make_pair(glm::decompose::trs, "TRS"),
std::make_pair(glm::decompose::tsr, "TSR"),
}
};
for (auto i : input_xform_list) {
for (auto e : decompose_order_list) {
glm::mat4 r, s, t;
glm::mat4 const x(glm::convert::transform(i.first, e.first, r, s, t));
matrix_pair const p(std::make_pair(i.first, x));
BOOST_MESSAGE(glm::io::precision(7) << glm::io::width(1 + 1 + 1 + 7)
<< i.second << ':' << std::string(47 - i.second.length(), ' ')
<< e.second << ':' << p << '\n');
static float const epsilon(9 * std::numeric_limits<float>::epsilon());
for (unsigned i(0); i < 4; ++i) {
for (unsigned j(0); j < 4; ++j) {
BOOST_CHECK(std::abs(p.first[i][j] - p.second[i][j]) < epsilon);
}
}
}
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2014, Falko Schumann <[email protected]>
* 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 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 "recordnavigation.h"
#include "recordnavigation_p.h"
#include "ui_recordnavigation.h"
#include <QModelIndex>
#include <QStandardItemModel>
using namespace Core;
RecordNavigationPrivate::RecordNavigationPrivate(RecordNavigation *q) :
q_ptr(q),
currentIndex(0),
ui(new Ui::RecordNavigation),
model(new QStandardItemModel())
{
ui->setupUi(q);
ui->currentRow->setFocus();
}
RecordNavigationPrivate::~RecordNavigationPrivate()
{
delete ui;
}
void RecordNavigationPrivate::update()
{
ui->currentRow->setText(QString::number(currentIndex + 1));
ui->rowCountLabel->setText(QString("of %1").arg(model->rowCount()));
bool currentIsFirst = currentIndex == 0;
ui->toFirstButton->setEnabled(!currentIsFirst);
ui->toPreviousButton->setEnabled(!currentIsFirst);
}
void RecordNavigationPrivate::currentRowEdited()
{
bool ok;
int newIndex = ui->currentRow->text().toInt(&ok);
if (ok) q_ptr->setCurrentIndex(newIndex - 1);
}
/*!
* \brief Ein Widget zum Navigieren innerhalb eines Modells.
*
* Man kann einen Datensatz vor- oder zurückspringen oder zum ersten oder letzten Datensatz
* springen. Der aktuelle Datensatz und die Anzahl der Datensätze werden angezeigt. Man kann direkt
* zu einem bestimmten Datensatz springen, in dem man den Datensatzindex angibt. Und natürlich kann
* ein neuer Datensatz angelegt werden.
*
* \remarks Die Klasse übernimmt nicht den Besitz des Modells und löscht es auch nicht, wenn sie
* zerstört wird.
* \invariant 0 <= currentIndex() && currentIndex() <= model()->rowCount()
*/
RecordNavigation::RecordNavigation(QWidget *parent) :
QWidget(parent),
d_ptr(new RecordNavigationPrivate(this))
{
connect(d_ptr->ui->toFirstButton, SIGNAL(clicked()), this, SLOT(toFirst()));
connect(d_ptr->ui->toPreviousButton, SIGNAL(clicked()), this, SLOT(toPrevious()));
connect(d_ptr->ui->currentRow, SIGNAL(editingFinished()), d_ptr, SLOT(currentRowEdited()));
connect(d_ptr->ui->toNextButton, SIGNAL(clicked()), this, SLOT(toNext()));
connect(d_ptr->ui->toLastButton, SIGNAL(clicked()), this, SLOT(toLast()));
connect(d_ptr->ui->toNewButton, SIGNAL(clicked()), this, SLOT(toNew()));
}
RecordNavigation::~RecordNavigation()
{
delete d_ptr;
}
QAbstractItemModel *RecordNavigation::model() const
{
return d_ptr->model;
}
/*!
* \post model() == model;
*/
void RecordNavigation::setModel(QAbstractItemModel *model)
{
d_ptr->model = model;
setCurrentIndex(0);
}
int RecordNavigation::currentIndex() const
{
return d_ptr->currentIndex;
}
/*!
* \pre 0 <= index && index <= model()->rowCount()
* \post currentIndex() == index
*/
void RecordNavigation::setCurrentIndex(int index)
{
d_ptr->currentIndex = index;
d_ptr->update();
}
/*!
* \pre 0 <= index.row() && index.row() <= model()->rowCount()
* \post currentIndex() == index.row()
*/
void RecordNavigation::setCurrentModelIndex(const QModelIndex &index)
{
setCurrentIndex(index.row());
}
/*!
* \post currentIndex() == 0
*/
void RecordNavigation::toFirst()
{
setCurrentIndex(0);
}
/*!
* \post currentIndex() == model()->rowCount() - 1
*/
void RecordNavigation::toLast()
{
setCurrentIndex(model()->rowCount() - 1);
}
/*!
* \pre $index = currentIndex()
* \pre currentIndex() <= model()->rowCount()
* \post currentIndex() == $index + 1
*/
void RecordNavigation::toNext()
{
setCurrentIndex(currentIndex() + 1);
}
/*!
* \pre $index = currentIndex()
* \pre currentIndex() > 0
* \post currentIndex() == $index - 1
*/
void RecordNavigation::toPrevious()
{
setCurrentIndex(currentIndex() - 1);
}
/**
* \post currentIndex() == model()->rowCount()
*/
void RecordNavigation::toNew()
{
setCurrentIndex(model()->rowCount());
}
<commit_msg>Verwendung von Namespaces verbessert.<commit_after>/* Copyright (c) 2014, Falko Schumann <[email protected]>
* 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 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 "recordnavigation.h"
#include "recordnavigation_p.h"
#include "ui_recordnavigation.h"
#include <QModelIndex>
#include <QStandardItemModel>
namespace Core {
RecordNavigationPrivate::RecordNavigationPrivate(RecordNavigation *q) :
q_ptr(q),
currentIndex(0),
ui(new Ui::RecordNavigation),
model(new QStandardItemModel())
{
ui->setupUi(q);
ui->currentRow->setFocus();
}
RecordNavigationPrivate::~RecordNavigationPrivate()
{
delete ui;
}
void RecordNavigationPrivate::update()
{
ui->currentRow->setText(QString::number(currentIndex + 1));
ui->rowCountLabel->setText(QString("of %1").arg(model->rowCount()));
bool currentIsFirst = currentIndex == 0;
ui->toFirstButton->setEnabled(!currentIsFirst);
ui->toPreviousButton->setEnabled(!currentIsFirst);
}
void RecordNavigationPrivate::currentRowEdited()
{
bool ok;
int newIndex = ui->currentRow->text().toInt(&ok);
if (ok) q_ptr->setCurrentIndex(newIndex - 1);
}
/*!
* \brief Ein Widget zum Navigieren innerhalb eines Modells.
*
* Man kann einen Datensatz vor- oder zurückspringen oder zum ersten oder letzten Datensatz
* springen. Der aktuelle Datensatz und die Anzahl der Datensätze werden angezeigt. Man kann direkt
* zu einem bestimmten Datensatz springen, in dem man den Datensatzindex angibt. Und natürlich kann
* ein neuer Datensatz angelegt werden.
*
* \remarks Die Klasse übernimmt nicht den Besitz des Modells und löscht es auch nicht, wenn sie
* zerstört wird.
* \invariant 0 <= currentIndex() && currentIndex() <= model()->rowCount()
*/
RecordNavigation::RecordNavigation(QWidget *parent) :
QWidget(parent),
d_ptr(new RecordNavigationPrivate(this))
{
connect(d_ptr->ui->toFirstButton, SIGNAL(clicked()), this, SLOT(toFirst()));
connect(d_ptr->ui->toPreviousButton, SIGNAL(clicked()), this, SLOT(toPrevious()));
connect(d_ptr->ui->currentRow, SIGNAL(editingFinished()), d_ptr, SLOT(currentRowEdited()));
connect(d_ptr->ui->toNextButton, SIGNAL(clicked()), this, SLOT(toNext()));
connect(d_ptr->ui->toLastButton, SIGNAL(clicked()), this, SLOT(toLast()));
connect(d_ptr->ui->toNewButton, SIGNAL(clicked()), this, SLOT(toNew()));
}
RecordNavigation::~RecordNavigation()
{
delete d_ptr;
}
QAbstractItemModel *RecordNavigation::model() const
{
return d_ptr->model;
}
/*!
* \post model() == model;
*/
void RecordNavigation::setModel(QAbstractItemModel *model)
{
d_ptr->model = model;
setCurrentIndex(0);
}
int RecordNavigation::currentIndex() const
{
return d_ptr->currentIndex;
}
/*!
* \pre 0 <= index && index <= model()->rowCount()
* \post currentIndex() == index
*/
void RecordNavigation::setCurrentIndex(int index)
{
d_ptr->currentIndex = index;
d_ptr->update();
}
/*!
* \pre 0 <= index.row() && index.row() <= model()->rowCount()
* \post currentIndex() == index.row()
*/
void RecordNavigation::setCurrentModelIndex(const QModelIndex &index)
{
setCurrentIndex(index.row());
}
/*!
* \post currentIndex() == 0
*/
void RecordNavigation::toFirst()
{
setCurrentIndex(0);
}
/*!
* \post currentIndex() == model()->rowCount() - 1
*/
void RecordNavigation::toLast()
{
setCurrentIndex(model()->rowCount() - 1);
}
/*!
* \pre $index = currentIndex()
* \pre currentIndex() <= model()->rowCount()
* \post currentIndex() == $index + 1
*/
void RecordNavigation::toNext()
{
setCurrentIndex(currentIndex() + 1);
}
/*!
* \pre $index = currentIndex()
* \pre currentIndex() > 0
* \post currentIndex() == $index - 1
*/
void RecordNavigation::toPrevious()
{
setCurrentIndex(currentIndex() - 1);
}
/**
* \post currentIndex() == model()->rowCount()
*/
void RecordNavigation::toNew()
{
setCurrentIndex(model()->rowCount());
}
} // namespace Core
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/core/p9_hcd_core_stopclocks.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 p9_hcd_core_stopclocks.C
/// @brief Core Clock Stop
///
/// Procedure Summary:
// *HWP HWP Owner : David Du <[email protected]>
// *HWP Backup HWP Owner : Greg Still <[email protected]>
// *HWP FW Owner : Sangeetha T S <[email protected]>
// *HWP Team : PM
// *HWP Consumed by : HB:PREV
// *HWP Level : 2
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_misc_scom_addresses.H>
#include <p9_quad_scom_addresses.H>
#include <p9_hcd_common.H>
#include <p9_common_clk_ctrl_state.H>
#include "p9_hcd_core_stopclocks.H"
//------------------------------------------------------------------------------
// Constant Definitions
//------------------------------------------------------------------------------
enum P9_HCD_CORE_STOPCLOCKS_CONSTANTS
{
CORE_PCB_MUX_POLLING_HW_NS_DELAY = 10000,
CORE_PCB_MUX_POLLING_SIM_CYCLE_DELAY = 320000,
CORE_CLK_SYNC_POLLING_HW_NS_DELAY = 10000,
CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY = 320000,
CORE_CLK_STOP_POLLING_HW_NS_DELAY = 10000,
CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY = 320000
};
//------------------------------------------------------------------------------
// Procedure: Core Clock Stop
//------------------------------------------------------------------------------
fapi2::ReturnCode
p9_hcd_core_stopclocks(
const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target)
{
FAPI_INF(">>p9_hcd_core_stopclocks");
fapi2::ReturnCode l_rc;
fapi2::buffer<uint64_t> l_ccsr;
fapi2::buffer<uint64_t> l_data64;
fapi2::buffer<uint64_t> l_temp64;
uint32_t l_loops1ms;
uint8_t l_attr_chip_unit_pos;
uint8_t l_attr_vdm_enable;
uint8_t l_attr_sdisn_setup;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sys;
auto l_quad = i_target.getParent<fapi2::TARGET_TYPE_EQ>();
auto l_perv = i_target.getParent<fapi2::TARGET_TYPE_PERV>();
auto l_chip = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_SDISN_SETUP, l_chip,
l_attr_sdisn_setup));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDM_ENABLE, l_sys,
l_attr_vdm_enable));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv,
l_attr_chip_unit_pos));
l_attr_chip_unit_pos = (l_attr_chip_unit_pos -
p9hcd::PERV_TO_CORE_POS_OFFSET) % 4;
// ----------------------------
// Prepare to stop core clocks
// ----------------------------
FAPI_DBG("Check PM_RESET_STATE_INDICATOR via GPMMR[15]");
FAPI_TRY(getScom(i_target, C_PPM_GPMMR_SCOM, l_data64));
if (!l_data64.getBit<15>())
{
FAPI_DBG("Gracefully turn off power management, continue anyways if fail");
/// @todo suspend_pm()
}
FAPI_DBG("Check core clock controller status");
l_rc = p9_common_clk_ctrl_state<fapi2::TARGET_TYPE_CORE>(i_target);
if (l_rc)
{
FAPI_INF("Clock controller of this core chiplet is inaccessible, return");
goto fapi_try_exit;
}
FAPI_DBG("Check cache clock controller status");
l_rc = p9_common_clk_ctrl_state<fapi2::TARGET_TYPE_EQ>(l_quad);
if (l_rc)
{
FAPI_INF("WARNING: core is enabled while cache is not, continue anyways");
}
else
{
FAPI_DBG("Check PERV clock status for access to CME via CLOCK_STAT[4]");
FAPI_TRY(getScom(l_quad, EQ_CLOCK_STAT_SL, l_data64));
FAPI_DBG("Check PERV fence status for access to CME via CPLT_CTRL1[4]");
FAPI_TRY(getScom(l_quad, EQ_CPLT_CTRL1, l_temp64));
if (l_data64.getBit<4>() == 0 && l_temp64.getBit<4>() == 0)
{
//halt cme(poll for halted, if timeout, print warnning keep going).
FAPI_DBG("Assert Core-L2/CC Quiesces via CME_SCOM_SICR[6,8]/[7,9]");
FAPI_TRY(putScom(l_quad,
(l_attr_chip_unit_pos < 2) ?
EX_0_CME_SCOM_SICR_OR : EX_1_CME_SCOM_SICR_OR,
(BIT64(6 + (l_attr_chip_unit_pos % 2)) |
BIT64(8 + (l_attr_chip_unit_pos % 2)))));
}
}
FAPI_DBG("Assert pm_mux_disable to get PCB Mux from CME via SLAVE_CONFIG[7]");
FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64));
FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_SET(7)));
FAPI_DBG("Override possible PPM write protection to CME via CPPM_CPMMR[1]");
FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_OR, MASK_SET(1)));
FAPI_DBG("Assert chiplet fence via NET_CTRL0[18]");
FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(18)));
// -------------------------------
// Stop core clocks
// -------------------------------
FAPI_DBG("Clear all SCAN_REGION_TYPE bits");
FAPI_TRY(putScom(i_target, C_SCAN_REGION_TYPE, MASK_ZERO));
FAPI_DBG("Stop core clocks(all but pll) via CLK_REGION");
l_data64 = (p9hcd::CLK_STOP_CMD |
p9hcd::CLK_REGION_ALL_BUT_PLL |
p9hcd::CLK_THOLD_ALL);
FAPI_TRY(putScom(i_target, C_CLK_REGION, l_data64));
FAPI_DBG("Poll for core clocks stopped via CPLT_STAT0[8]");
l_loops1ms = 1E6 / CORE_CLK_STOP_POLLING_HW_NS_DELAY;
do
{
fapi2::delay(CORE_CLK_STOP_POLLING_HW_NS_DELAY,
CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY);
FAPI_TRY(getScom(i_target, C_CPLT_STAT0, l_data64));
}
while((l_data64.getBit<8>() != 1) && ((--l_loops1ms) != 0));
FAPI_ASSERT((l_loops1ms != 0),
fapi2::PMPROC_CORECLKSTOP_TIMEOUT().set_CORECPLTSTAT(l_data64),
"Core Clock Stop Timeout");
FAPI_DBG("Check core clocks stopped via CLOCK_STAT_SL[4-13]");
FAPI_TRY(getScom(i_target, C_CLOCK_STAT_SL, l_data64));
FAPI_ASSERT((((~l_data64) & p9hcd::CLK_REGION_ALL_BUT_PLL) == 0),
fapi2::PMPROC_CORECLKSTOP_FAILED().set_CORECLKSTAT(l_data64),
"Core Clock Stop Failed");
FAPI_DBG("Core clocks stopped now");
// -------------------------------
// Disable core clock sync
// -------------------------------
FAPI_DBG("Drop core clock sync enable via CPPM_CACCR[15]");
FAPI_TRY(putScom(i_target, C_CPPM_CACCR_CLEAR, MASK_SET(15)));
FAPI_DBG("Poll for core clock sync done to drop via CPPM_CACSR[13]");
l_loops1ms = 1E6 / CORE_CLK_SYNC_POLLING_HW_NS_DELAY;
do
{
fapi2::delay(CORE_CLK_SYNC_POLLING_HW_NS_DELAY,
CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY);
FAPI_TRY(getScom(i_target, C_CPPM_CACSR, l_data64));
}
while((l_data64.getBit<13>() == 1) && ((--l_loops1ms) != 0));
FAPI_ASSERT((l_loops1ms != 0),
fapi2::PMPROC_CORECLKSYNCDROP_TIMEOUT().set_COREPPMCACSR(l_data64),
"Core Clock Sync Drop Timeout");
FAPI_DBG("Core clock sync done dropped");
// -------------------------------
// Fence up
// -------------------------------
FAPI_DBG("Assert skew sense to skew adjust fence via NET_CTRL0[22]");
FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(22)));
FAPI_DBG("Assert vital fence via CPLT_CTRL1[3]");
FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, MASK_SET(3)));
FAPI_DBG("Assert regional fences via CPLT_CTRL1[4-14]");
FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, p9hcd::CLK_REGION_ALL));
if (l_attr_sdisn_setup)
{
FAPI_DBG("DD1 Only: Drop sdis_n(flushing LCBES condition) vai CPLT_CONF0[34]");
FAPI_TRY(putScom(i_target, C_CPLT_CONF0_CLEAR, MASK_SET(34)));
}
// -------------------------------
// Disable VDM
// -------------------------------
if (l_attr_vdm_enable == fapi2::ENUM_ATTR_VDM_ENABLE_ON)
{
FAPI_DBG("Drop vdm enable via CPPM_VDMCR[0]");
FAPI_TRY(putScom(i_target, C_PPM_VDMCR_CLEAR, MASK_SET(0)));
}
// -------------------------------
// Update stop history
// -------------------------------
FAPI_DBG("Set core as stopped in STOP history register");
FAPI_TRY(putScom(i_target, C_PPM_SSHSRC, BIT64(0)));
// -------------------------------
// Clean up
// -------------------------------
FAPI_DBG("Return possible PPM write protection to CME via CPPM_CPMMR[1]");
FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_CLEAR, MASK_SET(1)));
FAPI_DBG("Drop pm_mux_disable to release PCB Mux via SLAVE_CONFIG[7]");
FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64));
FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_UNSET(7)));
fapi_try_exit:
FAPI_INF("<<p9_hcd_core_stopclocks");
return fapi2::current_err;
}
<commit_msg>Istep4: clean up istep4 todo items and mark them with RTC<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/core/p9_hcd_core_stopclocks.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 p9_hcd_core_stopclocks.C
/// @brief Core Clock Stop
///
/// Procedure Summary:
// *HWP HWP Owner : David Du <[email protected]>
// *HWP Backup HWP Owner : Greg Still <[email protected]>
// *HWP FW Owner : Sangeetha T S <[email protected]>
// *HWP Team : PM
// *HWP Consumed by : HB:PREV
// *HWP Level : 2
//------------------------------------------------------------------------------
// Includes
//------------------------------------------------------------------------------
#include <p9_misc_scom_addresses.H>
#include <p9_quad_scom_addresses.H>
#include <p9_hcd_common.H>
#include <p9_common_clk_ctrl_state.H>
#include "p9_hcd_core_stopclocks.H"
//------------------------------------------------------------------------------
// Constant Definitions
//------------------------------------------------------------------------------
enum P9_HCD_CORE_STOPCLOCKS_CONSTANTS
{
CORE_PCB_MUX_POLLING_HW_NS_DELAY = 10000,
CORE_PCB_MUX_POLLING_SIM_CYCLE_DELAY = 320000,
CORE_CLK_SYNC_POLLING_HW_NS_DELAY = 10000,
CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY = 320000,
CORE_CLK_STOP_POLLING_HW_NS_DELAY = 10000,
CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY = 320000
};
//------------------------------------------------------------------------------
// Procedure: Core Clock Stop
//------------------------------------------------------------------------------
fapi2::ReturnCode
p9_hcd_core_stopclocks(
const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target)
{
FAPI_INF(">>p9_hcd_core_stopclocks");
fapi2::ReturnCode l_rc;
fapi2::buffer<uint64_t> l_ccsr;
fapi2::buffer<uint64_t> l_data64;
fapi2::buffer<uint64_t> l_temp64;
uint32_t l_loops1ms;
uint8_t l_attr_chip_unit_pos;
uint8_t l_attr_vdm_enable;
uint8_t l_attr_sdisn_setup;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> l_sys;
auto l_quad = i_target.getParent<fapi2::TARGET_TYPE_EQ>();
auto l_perv = i_target.getParent<fapi2::TARGET_TYPE_PERV>();
auto l_chip = i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_SDISN_SETUP, l_chip,
l_attr_sdisn_setup));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_VDM_ENABLE, l_sys,
l_attr_vdm_enable));
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_perv,
l_attr_chip_unit_pos));
l_attr_chip_unit_pos = (l_attr_chip_unit_pos -
p9hcd::PERV_TO_CORE_POS_OFFSET) % 4;
// ----------------------------
// Prepare to stop core clocks
// ----------------------------
FAPI_DBG("Check PM_RESET_STATE_INDICATOR via GPMMR[15]");
FAPI_TRY(getScom(i_target, C_PPM_GPMMR_SCOM, l_data64));
if (!l_data64.getBit<15>())
{
FAPI_DBG("Gracefully turn off power management, continue anyways if fail");
/// @todo RTC158181 suspend_pm()
}
FAPI_DBG("Check core clock controller status");
l_rc = p9_common_clk_ctrl_state<fapi2::TARGET_TYPE_CORE>(i_target);
if (l_rc)
{
FAPI_INF("Clock controller of this core chiplet is inaccessible, return");
goto fapi_try_exit;
}
FAPI_DBG("Check cache clock controller status");
l_rc = p9_common_clk_ctrl_state<fapi2::TARGET_TYPE_EQ>(l_quad);
if (l_rc)
{
FAPI_INF("WARNING: core is enabled while cache is not, continue anyways");
}
else
{
FAPI_DBG("Check PERV clock status for access to CME via CLOCK_STAT[4]");
FAPI_TRY(getScom(l_quad, EQ_CLOCK_STAT_SL, l_data64));
FAPI_DBG("Check PERV fence status for access to CME via CPLT_CTRL1[4]");
FAPI_TRY(getScom(l_quad, EQ_CPLT_CTRL1, l_temp64));
if (l_data64.getBit<4>() == 0 && l_temp64.getBit<4>() == 0)
{
//halt cme(poll for halted, if timeout, print warnning keep going).
FAPI_DBG("Assert Core-L2/CC Quiesces via CME_SCOM_SICR[6,8]/[7,9]");
FAPI_TRY(putScom(l_quad,
(l_attr_chip_unit_pos < 2) ?
EX_0_CME_SCOM_SICR_OR : EX_1_CME_SCOM_SICR_OR,
(BIT64(6 + (l_attr_chip_unit_pos % 2)) |
BIT64(8 + (l_attr_chip_unit_pos % 2)))));
}
}
FAPI_DBG("Assert pm_mux_disable to get PCB Mux from CME via SLAVE_CONFIG[7]");
FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64));
FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_SET(7)));
FAPI_DBG("Override possible PPM write protection to CME via CPPM_CPMMR[1]");
FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_OR, MASK_SET(1)));
FAPI_DBG("Assert chiplet fence via NET_CTRL0[18]");
FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(18)));
// -------------------------------
// Stop core clocks
// -------------------------------
FAPI_DBG("Clear all SCAN_REGION_TYPE bits");
FAPI_TRY(putScom(i_target, C_SCAN_REGION_TYPE, MASK_ZERO));
FAPI_DBG("Stop core clocks(all but pll) via CLK_REGION");
l_data64 = (p9hcd::CLK_STOP_CMD |
p9hcd::CLK_REGION_ALL_BUT_PLL |
p9hcd::CLK_THOLD_ALL);
FAPI_TRY(putScom(i_target, C_CLK_REGION, l_data64));
FAPI_DBG("Poll for core clocks stopped via CPLT_STAT0[8]");
l_loops1ms = 1E6 / CORE_CLK_STOP_POLLING_HW_NS_DELAY;
do
{
fapi2::delay(CORE_CLK_STOP_POLLING_HW_NS_DELAY,
CORE_CLK_STOP_POLLING_SIM_CYCLE_DELAY);
FAPI_TRY(getScom(i_target, C_CPLT_STAT0, l_data64));
}
while((l_data64.getBit<8>() != 1) && ((--l_loops1ms) != 0));
FAPI_ASSERT((l_loops1ms != 0),
fapi2::PMPROC_CORECLKSTOP_TIMEOUT().set_CORECPLTSTAT(l_data64),
"Core Clock Stop Timeout");
FAPI_DBG("Check core clocks stopped via CLOCK_STAT_SL[4-13]");
FAPI_TRY(getScom(i_target, C_CLOCK_STAT_SL, l_data64));
FAPI_ASSERT((((~l_data64) & p9hcd::CLK_REGION_ALL_BUT_PLL) == 0),
fapi2::PMPROC_CORECLKSTOP_FAILED().set_CORECLKSTAT(l_data64),
"Core Clock Stop Failed");
FAPI_DBG("Core clocks stopped now");
// -------------------------------
// Disable core clock sync
// -------------------------------
FAPI_DBG("Drop core clock sync enable via CPPM_CACCR[15]");
FAPI_TRY(putScom(i_target, C_CPPM_CACCR_CLEAR, MASK_SET(15)));
FAPI_DBG("Poll for core clock sync done to drop via CPPM_CACSR[13]");
l_loops1ms = 1E6 / CORE_CLK_SYNC_POLLING_HW_NS_DELAY;
do
{
fapi2::delay(CORE_CLK_SYNC_POLLING_HW_NS_DELAY,
CORE_CLK_SYNC_POLLING_SIM_CYCLE_DELAY);
FAPI_TRY(getScom(i_target, C_CPPM_CACSR, l_data64));
}
while((l_data64.getBit<13>() == 1) && ((--l_loops1ms) != 0));
FAPI_ASSERT((l_loops1ms != 0),
fapi2::PMPROC_CORECLKSYNCDROP_TIMEOUT().set_COREPPMCACSR(l_data64),
"Core Clock Sync Drop Timeout");
FAPI_DBG("Core clock sync done dropped");
// -------------------------------
// Fence up
// -------------------------------
FAPI_DBG("Assert skew sense to skew adjust fence via NET_CTRL0[22]");
FAPI_TRY(putScom(i_target, C_NET_CTRL0_WOR, MASK_SET(22)));
FAPI_DBG("Assert vital fence via CPLT_CTRL1[3]");
FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, MASK_SET(3)));
FAPI_DBG("Assert regional fences via CPLT_CTRL1[4-14]");
FAPI_TRY(putScom(i_target, C_CPLT_CTRL1_OR, p9hcd::CLK_REGION_ALL));
if (l_attr_sdisn_setup)
{
FAPI_DBG("DD1 Only: Drop sdis_n(flushing LCBES condition) vai CPLT_CONF0[34]");
FAPI_TRY(putScom(i_target, C_CPLT_CONF0_CLEAR, MASK_SET(34)));
}
// -------------------------------
// Disable VDM
// -------------------------------
if (l_attr_vdm_enable == fapi2::ENUM_ATTR_VDM_ENABLE_ON)
{
FAPI_DBG("Drop vdm enable via CPPM_VDMCR[0]");
FAPI_TRY(putScom(i_target, C_PPM_VDMCR_CLEAR, MASK_SET(0)));
}
// -------------------------------
// Update stop history
// -------------------------------
FAPI_DBG("Set core as stopped in STOP history register");
FAPI_TRY(putScom(i_target, C_PPM_SSHSRC, BIT64(0)));
// -------------------------------
// Clean up
// -------------------------------
FAPI_DBG("Return possible PPM write protection to CME via CPPM_CPMMR[1]");
FAPI_TRY(putScom(i_target, C_CPPM_CPMMR_CLEAR, MASK_SET(1)));
FAPI_DBG("Drop pm_mux_disable to release PCB Mux via SLAVE_CONFIG[7]");
FAPI_TRY(getScom(i_target, C_SLAVE_CONFIG_REG, l_data64));
FAPI_TRY(putScom(i_target, C_SLAVE_CONFIG_REG, DATA_UNSET(7)));
fapi_try_exit:
FAPI_INF("<<p9_hcd_core_stopclocks");
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 p9_mss_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *HWP HWP Owner: Brian Silver <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <stdint.h>
#include <string.h>
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/dll_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>
using fapi2::TARGET_TYPE_MCBIST;
extern "C"
{
///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
{
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
"force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
FAPI_TRY( mss::dp16::reset_sysclk(i_target) );
// (Note: The chip should already be in this state.)
FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");
// 2. Assert reset to PHY for 32 memory clocks
FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));
// 3. Deassert reset_n
FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );
//
// Flush output drivers
//
// 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
// 9. Wait at least 32 dphy_gckn clock cycles.
// 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );
//
// ZCTL Enable
//
// 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
// 12. Wait at least 1024 dphy_gckn cycles
// 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );
//
// DLL calibration
//
// 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
// and DDRPHY_ADR_DLL_CNTL registers
// 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
// complete. One of the 3 bits will be asserted for ADR and DP16.
{
FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
bool l_run_workaround = false;
FAPI_TRY( mss::dll_calibration(i_target, l_run_workaround), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
// Only run DLL workaround if we fail DLL cal
// Note: there is no EC workaround for this workaround
// The designer team informed me that there is no hardware fix in plan for this type of fail as of DD2 - SPG
if( l_run_workaround )
{
FAPI_INF( "%s Applying DLL workaround", mss::c_str(i_target) );
FAPI_TRY( mss::workarounds::dll::fix_bad_voltage_settings(i_target), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
}
}
//
// Start bang-bang-lock
//
// 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
// 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
// perform initial alignment.
FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );
// 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
FAPI_TRY( mss::check_bang_bang_lock(i_target), "%s Error in p9_mss_ddr_phy_reset.C", mss::c_str(i_target) );
// 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target),
"%s Error in p9_mss_ddr_phy_reset.C", mss::c_str(i_target) );
// Reset the windage registers
// According to the PHY team, resetting the read delay offset must be done after SYSCLK_RESET
for( const auto& p : mss::find_targets<fapi2::TARGET_TYPE_MCA>(i_target) )
{
FAPI_TRY( mss::dp16::reset_read_delay_offset_registers(p),
"Failed reset_read_delay_offset_registers() for %s", mss::c_str(p) );
}
// 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
// DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
// SysClk alignment circuit out of the Continuous Update mode.
FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
"set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );
// 21. Wait at least 32 dphy_nclk clock cycles.
FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)),
"%s Error in p9_mss_ddr_phy_reset.C", mss::c_str(i_target) );
//
// Done bang-bang-lock
//
// Per J. Bialas, force_mclk_low can be dasserted.
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
"force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// Workarounds
FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
// New for Nimbus - perform duty cycle clock distortion calibration (DCD cal)
// Per PHY team's characterization, the DCD cal needs to be run after DLL calibration
FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
// mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
// (as part of the good-path) and once if we jump to the fapi_try label.
if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
{
goto leave_for_real;
}
// Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
// The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
// which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
// we're done with a success.
FAPI_TRY( mss::unmask::after_phy_reset(i_target), "%s Error in p9_mss_ddr_phy_reset.C", mss::c_str(i_target) );
// Leave as we're all good and checked the FIR already ...
return fapi2::current_err;
// ... here on a bad-path, check FIR and leave ...
fapi_try_exit:
// mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
// return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
return mss::check::during_phy_reset(i_target);
// ... here if the good-path FIR check found an error. We jumped over the unmasking and are
// returning an error to the caller.
leave_for_real:
return fapi2::current_err;
}
}
<commit_msg>Updated MSS HWP's level and owner change<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 p9_mss_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *HWP HWP Owner: Stephen Glancy <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <stdint.h>
#include <string.h>
#include <fapi2.H>
#include <mss.H>
#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/workarounds/dll_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>
using fapi2::TARGET_TYPE_MCBIST;
extern "C"
{
///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
{
// If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
// attributes for the PHY, etc.
if (mss::count_dimm(i_target) == 0)
{
FAPI_INF("... skipping ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
return fapi2::FAPI2_RC_SUCCESS;
}
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
"force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
FAPI_TRY( mss::dp16::reset_sysclk(i_target) );
// (Note: The chip should already be in this state.)
FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");
// 2. Assert reset to PHY for 32 memory clocks
FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));
// 3. Deassert reset_n
FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );
//
// Flush output drivers
//
// 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
// 9. Wait at least 32 dphy_gckn clock cycles.
// 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );
//
// ZCTL Enable
//
// 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
// 12. Wait at least 1024 dphy_gckn cycles
// 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );
//
// DLL calibration
//
// 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
// and DDRPHY_ADR_DLL_CNTL registers
// 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
// complete. One of the 3 bits will be asserted for ADR and DP16.
{
FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
bool l_run_workaround = false;
FAPI_TRY( mss::dll_calibration(i_target, l_run_workaround), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
// Only run DLL workaround if we fail DLL cal
// Note: there is no EC workaround for this workaround
// The designer team informed me that there is no hardware fix in plan for this type of fail as of DD2 - SPG
if( l_run_workaround )
{
FAPI_INF( "%s Applying DLL workaround", mss::c_str(i_target) );
FAPI_TRY( mss::workarounds::dll::fix_bad_voltage_settings(i_target), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
}
}
//
// Start bang-bang-lock
//
// 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
// 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
// perform initial alignment.
FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );
// 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
FAPI_TRY( mss::check_bang_bang_lock(i_target), "%s Error in p9_mss_ddr_phy_reset.C", mss::c_str(i_target) );
// 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target),
"%s Error in p9_mss_ddr_phy_reset.C", mss::c_str(i_target) );
// Reset the windage registers
// According to the PHY team, resetting the read delay offset must be done after SYSCLK_RESET
for( const auto& p : mss::find_targets<fapi2::TARGET_TYPE_MCA>(i_target) )
{
FAPI_TRY( mss::dp16::reset_read_delay_offset_registers(p),
"Failed reset_read_delay_offset_registers() for %s", mss::c_str(p) );
}
// 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
// DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
// SysClk alignment circuit out of the Continuous Update mode.
FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
"set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );
// 21. Wait at least 32 dphy_nclk clock cycles.
FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)),
"%s Error in p9_mss_ddr_phy_reset.C", mss::c_str(i_target) );
//
// Done bang-bang-lock
//
// Per J. Bialas, force_mclk_low can be dasserted.
FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
"force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );
// Workarounds
FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
// New for Nimbus - perform duty cycle clock distortion calibration (DCD cal)
// Per PHY team's characterization, the DCD cal needs to be run after DLL calibration
FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target), "%s Error in p9_mss_ddr_phy_reset.C",
mss::c_str(i_target) );
// mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
// (as part of the good-path) and once if we jump to the fapi_try label.
if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
{
goto leave_for_real;
}
// Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
// The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
// which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
// we're done with a success.
FAPI_TRY( mss::unmask::after_phy_reset(i_target), "%s Error in p9_mss_ddr_phy_reset.C", mss::c_str(i_target) );
// Leave as we're all good and checked the FIR already ...
return fapi2::current_err;
// ... here on a bad-path, check FIR and leave ...
fapi_try_exit:
// mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
// return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
return mss::check::during_phy_reset(i_target);
// ... here if the good-path FIR check found an error. We jumped over the unmasking and are
// returning an error to the caller.
leave_for_real:
return fapi2::current_err;
}
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_chiplet_enable_ridi.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 p9_chiplet_enable_ridi.H
///
/// @brief Enable RI/DI chip wide
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
#ifndef _P9_CHIPLET_ENABLE_RIDI_H_
#define _P9_CHIPLET_ENABLE_RIDI_H_
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_chiplet_enable_ridi_FP_t)(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Drop RI/DI for all chiplets being used (A, X, O, Pcie, DMI)
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_chiplet_enable_ridi(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<commit_msg>security -- split p9_chiplet_scominit and p9_chiplet_enable_ridi isteps<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_chiplet_enable_ridi.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,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 p9_chiplet_enable_ridi.H
///
/// @brief Enable RI/DI for all IO chiplets (excluding XBUS)
//------------------------------------------------------------------------------
// *HWP HW Owner : Abhishek Agarwal <[email protected]>
// *HWP HW Backup Owner : Srinivas V Naga <[email protected]>
// *HWP FW Owner : Sunil kumar <[email protected]>
// *HWP Team : Perv
// *HWP Level : 2
// *HWP Consumed by : HB
//------------------------------------------------------------------------------
#ifndef _P9_CHIPLET_ENABLE_RIDI_H_
#define _P9_CHIPLET_ENABLE_RIDI_H_
#include <fapi2.H>
typedef fapi2::ReturnCode (*p9_chiplet_enable_ridi_FP_t)(
const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);
/// @brief Drop RI/DI for O, PCIE, MC
///
/// @param[in] i_target_chip Reference to TARGET_TYPE_PROC_CHIP target
/// @return FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
fapi2::ReturnCode p9_chiplet_enable_ridi(const
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}
#endif
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Quick Layouts module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquicklinearlayout_p.h"
#include <QtCore/qnumeric.h>
#include "qdebug.h"
/*!
\qmltype RowLayout
\instantiates QQuickRowLayout
\inqmlmodule QtDesktop 1.0
\brief RowLayout is doing bla...bla...
*/
/*!
\qmltype ColumnLayout
\instantiates QQuickColumnLayout
\inqmlmodule QtDesktop 1.0
\brief ColumnLayout is doing bla...bla...
*/
QT_BEGIN_NAMESPACE
static const qreal q_declarativeLayoutDefaultSpacing = 4.0;
QQuickGridLayoutBase::QQuickGridLayoutBase(QQuickGridLayoutBasePrivate &dd,
Qt::Orientation orientation,
QQuickItem *parent /*= 0*/)
: QQuickLayout(dd, parent)
{
Q_D(QQuickGridLayoutBase);
d->orientation = orientation;
}
Qt::Orientation QQuickGridLayoutBase::orientation() const
{
Q_D(const QQuickGridLayoutBase);
return d->orientation;
}
void QQuickGridLayoutBase::setOrientation(Qt::Orientation orientation)
{
Q_D(QQuickGridLayoutBase);
if (d->orientation == orientation)
return;
d->orientation = orientation;
invalidate();
}
void QQuickGridLayoutBase::componentComplete()
{
Q_D(QQuickGridLayoutBase);
quickLayoutDebug() << objectName() << "QQuickGridLayoutBase::componentComplete()" << parent();
d->m_disableRearrange = true;
QQuickLayout::componentComplete(); // will call our geometryChange(), (where isComponentComplete() == true)
d->m_disableRearrange = false;
updateLayoutItems();
QQuickItem *par = parentItem();
if (qobject_cast<QQuickLayout*>(par))
return;
rearrange(QSizeF(width(), height()));
}
/*
Invalidation happens like this as a reaction to that a size hint changes on an item "a":
Suppose we have the following Qml document:
RowLayout {
id: l1
RowLayout {
id: l2
Item {
id: a
}
Item {
id: b
}
}
}
1. l2->invalidateChildItem(a) is called on l2, where item refers to "a".
(this will dirty the cached size hints of item "a")
2. l2->invalidate() is called
this will :
i) invalidate the layout engine
ii) dirty the cached size hints of item "l2" (by calling parentLayout()->invalidateChildItem
*/
/*!
\internal
Invalidates \a childItem and this layout.
After a call to invalidate, the next call to retrieve e.g. sizeHint will be up-to date.
This function will also call QQuickLayout::invalidate(0), to ensure that the parent layout
is invalidated.
*/
void QQuickGridLayoutBase::invalidate(QQuickItem *childItem)
{
Q_D(QQuickGridLayoutBase);
if (!isComponentComplete())
return;
quickLayoutDebug() << "QQuickGridLayoutBase::invalidate()";
if (childItem) {
if (QQuickGridLayoutItem *layoutItem = d->engine.findLayoutItem(childItem))
layoutItem->invalidate();
}
// invalidate engine
d->engine.invalidate();
QQuickLayout::invalidate(this);
}
void QQuickGridLayoutBase::updateLayoutItems()
{
Q_D(QQuickGridLayoutBase);
if (!isComponentComplete())
return;
quickLayoutDebug() << "QQuickGridLayoutBase::updateLayoutItems";
d->engine.deleteItems();
foreach (QQuickItem *child, childItems()) {
if (child->isVisible())
insertLayoutItem(child);
}
invalidate();
quickLayoutDebug() << "QQuickGridLayoutBase::updateLayoutItems LEAVING";
propagateLayoutSizeHints();
}
void QQuickGridLayoutBase::propagateLayoutSizeHints()
{
Q_D(QQuickGridLayoutBase);
quickLayoutDebug() << "propagateLayoutSizeHints()";
QObject *attached = qmlAttachedPropertiesObject<QQuickLayout>(this);
QQuickLayoutAttached *info = static_cast<QQuickLayoutAttached *>(attached);
const QSizeF min = d->engine.sizeHint(Qt::MinimumSize, QSizeF());
const QSizeF pref = d->engine.sizeHint(Qt::PreferredSize, QSizeF());
const QSizeF max = d->engine.sizeHint(Qt::MaximumSize, QSizeF());
info->setMinimumWidth(min.width());
info->setMinimumHeight(min.height());
setImplicitWidth(pref.width());
setImplicitHeight(pref.height());
info->setMaximumWidth(max.width());
info->setMaximumHeight(max.height());
}
void QQuickGridLayoutBase::itemChange(ItemChange change, const ItemChangeData &value)
{
if (change == ItemChildAddedChange) {
quickLayoutDebug() << "ItemChildAddedChange";
QQuickItem *item = value.item;
QObject::connect(item, SIGNAL(destroyed()), this, SLOT(onItemDestroyed()));
QObject::connect(item, SIGNAL(visibleChanged()), this, SLOT(onItemVisibleChanged()));
QObject::connect(item, SIGNAL(implicitWidthChanged()), this, SLOT(onItemImplicitSizeChanged()));
if (isComponentComplete() && isVisible())
updateLayoutItems();
} else if (change == ItemChildRemovedChange) {
quickLayoutDebug() << "ItemChildRemovedChange";
QQuickItem *item = value.item;
QObject::disconnect(item, SIGNAL(destroyed()), this, SLOT(onItemDestroyed()));
QObject::disconnect(item, SIGNAL(visibleChanged()), this, SLOT(onItemVisibleChanged()));
QObject::disconnect(item, SIGNAL(implicitWidthChanged()), this, SLOT(onItemImplicitSizeChanged()));
if (isComponentComplete() && isVisible())
updateLayoutItems();
}
QQuickLayout::itemChange(change, value);
}
void QQuickGridLayoutBase::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
Q_D(QQuickGridLayoutBase);
QQuickLayout::geometryChanged(newGeometry, oldGeometry);
if (d->m_disableRearrange || !isComponentComplete() || !newGeometry.isValid())
return;
quickLayoutDebug() << "QQuickGridLayoutBase::geometryChanged" << newGeometry << oldGeometry;
rearrange(newGeometry.size());
}
void QQuickGridLayoutBase::insertLayoutItem(QQuickItem *item)
{
Q_D(QQuickGridLayoutBase);
if (!item) {
qWarning("QGraphicsGridLayout::addItem: cannot add null item");
return;
}
QQuickLayoutAttached *info = attachedLayoutObject(item, false);
int row = 0;
int column = 0;
int rowSpan = 1;
int columnSpan = 1;
Qt::Alignment alignment = 0;
if (info) {
row = info->row();
column = info->column();
rowSpan = info->rowSpan();
columnSpan = info->columnSpan();
}
if (row < 0 || column < 0) {
qWarning("QQuickGridLayoutBase::insertLayoutItemAt: invalid row/column: %d",
row < 0 ? row : column);
return;
}
if (columnSpan < 1 || rowSpan < 1) {
qWarning("QQuickGridLayoutBase::addItem: invalid row span/column span: %d",
rowSpan < 1 ? rowSpan : columnSpan);
return;
}
QQuickGridLayoutItem *layoutItem = new QQuickGridLayoutItem(item, row, column, rowSpan, columnSpan, alignment);
d->engine.insertItem(layoutItem, -1);
setupItemLayout(item);
}
void QQuickGridLayoutBase::removeGridItem(QGridLayoutItem *gridItem)
{
Q_D(QQuickGridLayoutBase);
const int index = gridItem->firstRow(d->orientation);
d->engine.removeItem(gridItem);
d->engine.removeRows(index, 1, d->orientation);
}
void QQuickGridLayoutBase::removeLayoutItem(QQuickItem *item)
{
Q_D(QQuickGridLayoutBase);
quickLayoutDebug() << "QQuickGridLayoutBase::removeLayoutItem";
if (QQuickGridLayoutItem *gridItem = d->engine.findLayoutItem(item)) {
removeGridItem(gridItem);
delete gridItem;
invalidate();
}
}
void QQuickGridLayoutBase::onItemVisibleChanged()
{
if (!isComponentComplete())
return;
quickLayoutDebug() << "QQuickGridLayoutBase::onItemVisibleChanged";
updateLayoutItems();
}
void QQuickGridLayoutBase::onItemDestroyed()
{
Q_D(QQuickGridLayoutBase);
quickLayoutDebug() << "QQuickGridLayoutBase::onItemDestroyed";
QQuickItem *inDestruction = static_cast<QQuickItem *>(sender());
if (QQuickGridLayoutItem *gridItem = d->engine.findLayoutItem(inDestruction)) {
removeGridItem(gridItem);
delete gridItem;
invalidate();
}
}
void QQuickGridLayoutBase::onItemImplicitSizeChanged()
{
//QQuickItem *item = static_cast<QQuickItem *>(sender());
//Q_ASSERT(item);
//invalidate(item);
}
void QQuickGridLayoutBase::rearrange(const QSizeF &size)
{
Q_D(QQuickGridLayoutBase);
if (!isComponentComplete())
return;
quickLayoutDebug() << objectName() << "QQuickGridLayoutBase::rearrange()" << size;
Qt::LayoutDirection visualDir = Qt::LeftToRight; // ### Fix if RTL support is needed
d->engine.setVisualDirection(visualDir);
/*
qreal left, top, right, bottom;
left = top = right = bottom = 0; // ### support for margins?
if (visualDir == Qt::RightToLeft)
qSwap(left, right);
*/
d->engine.setGeometries(QRectF(QPointF(0,0), size));
QQuickLayout::rearrange(size);
// propagate hints to upper levels
propagateLayoutSizeHints();
}
/**********************************
**
** QQuickGridLayout
**
**/
QQuickGridLayout::QQuickGridLayout(QQuickItem *parent /* = 0*/)
: QQuickGridLayoutBase(*new QQuickGridLayoutPrivate, Qt::Horizontal, parent)
{
Q_D(QQuickGridLayout);
d->horizontalSpacing = q_declarativeLayoutDefaultSpacing;
d->verticalSpacing = q_declarativeLayoutDefaultSpacing;
d->engine.setSpacing(d->horizontalSpacing, Qt::Horizontal);
d->engine.setSpacing(d->verticalSpacing, Qt::Vertical);
}
qreal QQuickGridLayout::horizontalSpacing() const
{
Q_D(const QQuickGridLayout);
return d->horizontalSpacing;
}
void QQuickGridLayout::setHorizontalSpacing(qreal spacing)
{
Q_D(QQuickGridLayout);
if (qIsNaN(spacing) || d->horizontalSpacing == spacing)
return;
d->horizontalSpacing = spacing;
d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
invalidate();
}
qreal QQuickGridLayout::verticalSpacing() const
{
Q_D(const QQuickGridLayout);
return d->verticalSpacing;
}
void QQuickGridLayout::setVerticalSpacing(qreal spacing)
{
Q_D(QQuickGridLayout);
if (qIsNaN(spacing) || d->verticalSpacing == spacing)
return;
d->verticalSpacing = spacing;
d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
invalidate();
}
/**********************************
**
** QQuickLinearLayout
**
**/
QQuickLinearLayout::QQuickLinearLayout(Qt::Orientation orientation,
QQuickItem *parent /*= 0*/)
: QQuickGridLayoutBase(*new QQuickLinearLayoutPrivate, orientation, parent)
{
Q_D(QQuickLinearLayout);
d->spacing = q_declarativeLayoutDefaultSpacing;
d->engine.setSpacing(d->spacing, Qt::Horizontal | Qt::Vertical);
}
qreal QQuickLinearLayout::spacing() const
{
Q_D(const QQuickLinearLayout);
return d->spacing;
}
void QQuickLinearLayout::setSpacing(qreal spacing)
{
Q_D(QQuickLinearLayout);
if (qIsNaN(spacing) || d->spacing == spacing)
return;
d->spacing = spacing;
d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
invalidate();
}
void QQuickLinearLayout::insertLayoutItem(QQuickItem *item)
{
Q_D(QQuickLinearLayout);
const int index = d->engine.rowCount(d->orientation);
d->engine.insertRow(index, d->orientation);
int gridRow = 0;
int gridColumn = index;
if (d->orientation == Qt::Vertical)
qSwap(gridRow, gridColumn);
QQuickGridLayoutItem *layoutItem = new QQuickGridLayoutItem(item, gridRow, gridColumn, 1, 1, 0);
d->engine.insertItem(layoutItem, index);
setupItemLayout(item);
}
QT_END_NAMESPACE
<commit_msg>React to implicit size changes<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Quick Layouts module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquicklinearlayout_p.h"
#include <QtCore/qnumeric.h>
#include "qdebug.h"
/*!
\qmltype RowLayout
\instantiates QQuickRowLayout
\inqmlmodule QtDesktop 1.0
\brief RowLayout is doing bla...bla...
*/
/*!
\qmltype ColumnLayout
\instantiates QQuickColumnLayout
\inqmlmodule QtDesktop 1.0
\brief ColumnLayout is doing bla...bla...
*/
QT_BEGIN_NAMESPACE
static const qreal q_declarativeLayoutDefaultSpacing = 4.0;
QQuickGridLayoutBase::QQuickGridLayoutBase(QQuickGridLayoutBasePrivate &dd,
Qt::Orientation orientation,
QQuickItem *parent /*= 0*/)
: QQuickLayout(dd, parent)
{
Q_D(QQuickGridLayoutBase);
d->orientation = orientation;
}
Qt::Orientation QQuickGridLayoutBase::orientation() const
{
Q_D(const QQuickGridLayoutBase);
return d->orientation;
}
void QQuickGridLayoutBase::setOrientation(Qt::Orientation orientation)
{
Q_D(QQuickGridLayoutBase);
if (d->orientation == orientation)
return;
d->orientation = orientation;
invalidate();
}
void QQuickGridLayoutBase::componentComplete()
{
Q_D(QQuickGridLayoutBase);
quickLayoutDebug() << objectName() << "QQuickGridLayoutBase::componentComplete()" << parent();
d->m_disableRearrange = true;
QQuickLayout::componentComplete(); // will call our geometryChange(), (where isComponentComplete() == true)
d->m_disableRearrange = false;
updateLayoutItems();
QQuickItem *par = parentItem();
if (qobject_cast<QQuickLayout*>(par))
return;
rearrange(QSizeF(width(), height()));
}
/*
Invalidation happens like this as a reaction to that a size hint changes on an item "a":
Suppose we have the following Qml document:
RowLayout {
id: l1
RowLayout {
id: l2
Item {
id: a
}
Item {
id: b
}
}
}
1. l2->invalidateChildItem(a) is called on l2, where item refers to "a".
(this will dirty the cached size hints of item "a")
2. l2->invalidate() is called
this will :
i) invalidate the layout engine
ii) dirty the cached size hints of item "l2" (by calling parentLayout()->invalidateChildItem
*/
/*!
\internal
Invalidates \a childItem and this layout.
After a call to invalidate, the next call to retrieve e.g. sizeHint will be up-to date.
This function will also call QQuickLayout::invalidate(0), to ensure that the parent layout
is invalidated.
*/
void QQuickGridLayoutBase::invalidate(QQuickItem *childItem)
{
Q_D(QQuickGridLayoutBase);
if (!isComponentComplete())
return;
quickLayoutDebug() << "QQuickGridLayoutBase::invalidate()";
if (childItem) {
if (QQuickGridLayoutItem *layoutItem = d->engine.findLayoutItem(childItem))
layoutItem->invalidate();
}
// invalidate engine
d->engine.invalidate();
QQuickLayout::invalidate(this);
}
void QQuickGridLayoutBase::updateLayoutItems()
{
Q_D(QQuickGridLayoutBase);
if (!isComponentComplete())
return;
quickLayoutDebug() << "QQuickGridLayoutBase::updateLayoutItems";
d->engine.deleteItems();
foreach (QQuickItem *child, childItems()) {
if (child->isVisible())
insertLayoutItem(child);
}
invalidate();
quickLayoutDebug() << "QQuickGridLayoutBase::updateLayoutItems LEAVING";
propagateLayoutSizeHints();
}
void QQuickGridLayoutBase::propagateLayoutSizeHints()
{
Q_D(QQuickGridLayoutBase);
quickLayoutDebug() << "propagateLayoutSizeHints()";
QObject *attached = qmlAttachedPropertiesObject<QQuickLayout>(this);
QQuickLayoutAttached *info = static_cast<QQuickLayoutAttached *>(attached);
const QSizeF min = d->engine.sizeHint(Qt::MinimumSize, QSizeF());
const QSizeF pref = d->engine.sizeHint(Qt::PreferredSize, QSizeF());
const QSizeF max = d->engine.sizeHint(Qt::MaximumSize, QSizeF());
info->setMinimumWidth(min.width());
info->setMinimumHeight(min.height());
setImplicitWidth(pref.width());
setImplicitHeight(pref.height());
info->setMaximumWidth(max.width());
info->setMaximumHeight(max.height());
}
void QQuickGridLayoutBase::itemChange(ItemChange change, const ItemChangeData &value)
{
if (change == ItemChildAddedChange) {
quickLayoutDebug() << "ItemChildAddedChange";
QQuickItem *item = value.item;
QObject::connect(item, SIGNAL(destroyed()), this, SLOT(onItemDestroyed()));
QObject::connect(item, SIGNAL(visibleChanged()), this, SLOT(onItemVisibleChanged()));
QObject::connect(item, SIGNAL(implicitWidthChanged()), this, SLOT(onItemImplicitSizeChanged()));
QObject::connect(item, SIGNAL(implicitHeightChanged()), this, SLOT(onItemImplicitSizeChanged()));
if (isComponentComplete() && isVisible())
updateLayoutItems();
} else if (change == ItemChildRemovedChange) {
quickLayoutDebug() << "ItemChildRemovedChange";
QQuickItem *item = value.item;
QObject::disconnect(item, SIGNAL(destroyed()), this, SLOT(onItemDestroyed()));
QObject::disconnect(item, SIGNAL(visibleChanged()), this, SLOT(onItemVisibleChanged()));
QObject::disconnect(item, SIGNAL(implicitWidthChanged()), this, SLOT(onItemImplicitSizeChanged()));
QObject::disconnect(item, SIGNAL(implicitHeightChanged()), this, SLOT(onItemImplicitSizeChanged()));
if (isComponentComplete() && isVisible())
updateLayoutItems();
}
QQuickLayout::itemChange(change, value);
}
void QQuickGridLayoutBase::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
Q_D(QQuickGridLayoutBase);
QQuickLayout::geometryChanged(newGeometry, oldGeometry);
if (d->m_disableRearrange || !isComponentComplete() || !newGeometry.isValid())
return;
quickLayoutDebug() << "QQuickGridLayoutBase::geometryChanged" << newGeometry << oldGeometry;
rearrange(newGeometry.size());
}
void QQuickGridLayoutBase::insertLayoutItem(QQuickItem *item)
{
Q_D(QQuickGridLayoutBase);
if (!item) {
qWarning("QGraphicsGridLayout::addItem: cannot add null item");
return;
}
QQuickLayoutAttached *info = attachedLayoutObject(item, false);
int row = 0;
int column = 0;
int rowSpan = 1;
int columnSpan = 1;
Qt::Alignment alignment = 0;
if (info) {
row = info->row();
column = info->column();
rowSpan = info->rowSpan();
columnSpan = info->columnSpan();
}
if (row < 0 || column < 0) {
qWarning("QQuickGridLayoutBase::insertLayoutItemAt: invalid row/column: %d",
row < 0 ? row : column);
return;
}
if (columnSpan < 1 || rowSpan < 1) {
qWarning("QQuickGridLayoutBase::addItem: invalid row span/column span: %d",
rowSpan < 1 ? rowSpan : columnSpan);
return;
}
QQuickGridLayoutItem *layoutItem = new QQuickGridLayoutItem(item, row, column, rowSpan, columnSpan, alignment);
d->engine.insertItem(layoutItem, -1);
setupItemLayout(item);
}
void QQuickGridLayoutBase::removeGridItem(QGridLayoutItem *gridItem)
{
Q_D(QQuickGridLayoutBase);
const int index = gridItem->firstRow(d->orientation);
d->engine.removeItem(gridItem);
d->engine.removeRows(index, 1, d->orientation);
}
void QQuickGridLayoutBase::removeLayoutItem(QQuickItem *item)
{
Q_D(QQuickGridLayoutBase);
quickLayoutDebug() << "QQuickGridLayoutBase::removeLayoutItem";
if (QQuickGridLayoutItem *gridItem = d->engine.findLayoutItem(item)) {
removeGridItem(gridItem);
delete gridItem;
invalidate();
}
}
void QQuickGridLayoutBase::onItemVisibleChanged()
{
if (!isComponentComplete())
return;
quickLayoutDebug() << "QQuickGridLayoutBase::onItemVisibleChanged";
updateLayoutItems();
}
void QQuickGridLayoutBase::onItemDestroyed()
{
Q_D(QQuickGridLayoutBase);
quickLayoutDebug() << "QQuickGridLayoutBase::onItemDestroyed";
QQuickItem *inDestruction = static_cast<QQuickItem *>(sender());
if (QQuickGridLayoutItem *gridItem = d->engine.findLayoutItem(inDestruction)) {
removeGridItem(gridItem);
delete gridItem;
invalidate();
}
}
void QQuickGridLayoutBase::onItemImplicitSizeChanged()
{
QQuickItem *item = static_cast<QQuickItem *>(sender());
Q_ASSERT(item);
invalidate(item);
propagateLayoutSizeHints();
}
void QQuickGridLayoutBase::rearrange(const QSizeF &size)
{
Q_D(QQuickGridLayoutBase);
if (!isComponentComplete())
return;
quickLayoutDebug() << objectName() << "QQuickGridLayoutBase::rearrange()" << size;
Qt::LayoutDirection visualDir = Qt::LeftToRight; // ### Fix if RTL support is needed
d->engine.setVisualDirection(visualDir);
/*
qreal left, top, right, bottom;
left = top = right = bottom = 0; // ### support for margins?
if (visualDir == Qt::RightToLeft)
qSwap(left, right);
*/
d->engine.setGeometries(QRectF(QPointF(0,0), size));
QQuickLayout::rearrange(size);
// propagate hints to upper levels
propagateLayoutSizeHints();
}
/**********************************
**
** QQuickGridLayout
**
**/
QQuickGridLayout::QQuickGridLayout(QQuickItem *parent /* = 0*/)
: QQuickGridLayoutBase(*new QQuickGridLayoutPrivate, Qt::Horizontal, parent)
{
Q_D(QQuickGridLayout);
d->horizontalSpacing = q_declarativeLayoutDefaultSpacing;
d->verticalSpacing = q_declarativeLayoutDefaultSpacing;
d->engine.setSpacing(d->horizontalSpacing, Qt::Horizontal);
d->engine.setSpacing(d->verticalSpacing, Qt::Vertical);
}
qreal QQuickGridLayout::horizontalSpacing() const
{
Q_D(const QQuickGridLayout);
return d->horizontalSpacing;
}
void QQuickGridLayout::setHorizontalSpacing(qreal spacing)
{
Q_D(QQuickGridLayout);
if (qIsNaN(spacing) || d->horizontalSpacing == spacing)
return;
d->horizontalSpacing = spacing;
d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
invalidate();
}
qreal QQuickGridLayout::verticalSpacing() const
{
Q_D(const QQuickGridLayout);
return d->verticalSpacing;
}
void QQuickGridLayout::setVerticalSpacing(qreal spacing)
{
Q_D(QQuickGridLayout);
if (qIsNaN(spacing) || d->verticalSpacing == spacing)
return;
d->verticalSpacing = spacing;
d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
invalidate();
}
/**********************************
**
** QQuickLinearLayout
**
**/
QQuickLinearLayout::QQuickLinearLayout(Qt::Orientation orientation,
QQuickItem *parent /*= 0*/)
: QQuickGridLayoutBase(*new QQuickLinearLayoutPrivate, orientation, parent)
{
Q_D(QQuickLinearLayout);
d->spacing = q_declarativeLayoutDefaultSpacing;
d->engine.setSpacing(d->spacing, Qt::Horizontal | Qt::Vertical);
}
qreal QQuickLinearLayout::spacing() const
{
Q_D(const QQuickLinearLayout);
return d->spacing;
}
void QQuickLinearLayout::setSpacing(qreal spacing)
{
Q_D(QQuickLinearLayout);
if (qIsNaN(spacing) || d->spacing == spacing)
return;
d->spacing = spacing;
d->engine.setSpacing(spacing, Qt::Horizontal | Qt::Vertical);
invalidate();
}
void QQuickLinearLayout::insertLayoutItem(QQuickItem *item)
{
Q_D(QQuickLinearLayout);
const int index = d->engine.rowCount(d->orientation);
d->engine.insertRow(index, d->orientation);
int gridRow = 0;
int gridColumn = index;
if (d->orientation == Qt::Vertical)
qSwap(gridRow, gridColumn);
QQuickGridLayoutItem *layoutItem = new QQuickGridLayoutItem(item, gridRow, gridColumn, 1, 1, 0);
d->engine.insertItem(layoutItem, index);
setupItemLayout(item);
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>/*
RawSpeed - RAW file decoder.
Copyright (C) 2019 LibRaw LLC ([email protected])
Copyright (C) 2020 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/PanasonicDecompressorV6.h" // for PanasonicDecompre...
#include "common/Array2DRef.h" // for Array2DRef
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImag...
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include <algorithm> // for copy_n
#include <array>
#include <cstdint> // for uint16_t, uint32_t
#include <cstdlib> // for free, malloc
namespace rawspeed {
constexpr int PanasonicDecompressorV6::PixelsPerBlock;
constexpr int PanasonicDecompressorV6::BytesPerBlock;
namespace {
struct pana_cs6_page_decoder {
std::array<uint16_t, 14> pixelbuffer;
unsigned char current = 0;
explicit pana_cs6_page_decoder(const ByteStream& bs) {
pixelbuffer[0] = (bs.peekByte(15) << 6) | (bs.peekByte(14) >> 2); // 14 bit
pixelbuffer[1] = (((bs.peekByte(14) & 0x3) << 12) | (bs.peekByte(13) << 4) |
(bs.peekByte(12) >> 4)) &
0x3fff;
pixelbuffer[2] = (bs.peekByte(12) >> 2) & 0x3;
pixelbuffer[3] = ((bs.peekByte(12) & 0x3) << 8) | bs.peekByte(11);
pixelbuffer[4] = (bs.peekByte(10) << 2) | (bs.peekByte(9) >> 6);
pixelbuffer[5] = ((bs.peekByte(9) & 0x3f) << 4) | (bs.peekByte(8) >> 4);
pixelbuffer[6] = (bs.peekByte(8) >> 2) & 0x3;
pixelbuffer[7] = ((bs.peekByte(8) & 0x3) << 8) | bs.peekByte(7);
pixelbuffer[8] = ((bs.peekByte(6) << 2) & 0x3fc) | (bs.peekByte(5) >> 6);
pixelbuffer[9] = ((bs.peekByte(5) << 4) | (bs.peekByte(4) >> 4)) & 0x3ff;
pixelbuffer[10] = (bs.peekByte(4) >> 2) & 0x3;
pixelbuffer[11] = ((bs.peekByte(4) & 0x3) << 8) | bs.peekByte(3);
pixelbuffer[12] =
(((bs.peekByte(2) << 2) & 0x3fc) | bs.peekByte(1) >> 6) & 0x3ff;
pixelbuffer[13] = ((bs.peekByte(1) << 4) | (bs.peekByte(0) >> 4)) & 0x3ff;
}
uint16_t nextpixel() { return pixelbuffer[current++]; }
};
} // namespace
PanasonicDecompressorV6::PanasonicDecompressorV6(const RawImage& img,
ByteStream input_)
: mRaw(img), input(std::move(input_)) {
if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 ||
mRaw->getBpp() != sizeof(uint16_t))
ThrowRDE("Unexpected component count / data type");
if (!mRaw->dim.hasPositiveArea()) {
ThrowRDE("Unexpected image dimensions found: (%i; %i)", mRaw->dim.x,
mRaw->dim.y);
}
const int blocksperrow =
mRaw->dim.x / PanasonicDecompressorV6::PixelsPerBlock;
const int bytesPerRow = PanasonicDecompressorV6::BytesPerBlock * blocksperrow;
const int bytesTotal = bytesPerRow * mRaw->dim.y;
input = input_.peekStream(bytesTotal);
}
void PanasonicDecompressorV6::decompressBlock(ByteStream* rowInput, int row,
int col) const {
const Array2DRef<uint16_t> out(mRaw->getU16DataAsUncroppedArray2DRef());
pana_cs6_page_decoder page(
rowInput->getStream(PanasonicDecompressorV6::BytesPerBlock));
std::array<unsigned, 2> oddeven = {0, 0};
std::array<unsigned, 2> nonzero = {0, 0};
unsigned pmul = 0;
unsigned pixel_base = 0;
for (int pix = 0; pix < PanasonicDecompressorV6::PixelsPerBlock;
pix++, col++) {
if (pix % 3 == 2) {
uint16_t base = page.nextpixel();
if (base > 3)
ThrowRDE("Invariant failure");
if (base == 3)
base = 4;
pixel_base = 0x200 << base;
pmul = 1 << base;
}
uint16_t epixel = page.nextpixel();
if (oddeven[pix % 2]) {
epixel *= pmul;
if (pixel_base < 0x2000 && nonzero[pix % 2] > pixel_base)
epixel += nonzero[pix % 2] - pixel_base;
nonzero[pix % 2] = epixel;
} else {
oddeven[pix % 2] = epixel;
if (epixel)
nonzero[pix % 2] = epixel;
else
epixel = nonzero[pix % 2];
}
auto spix = static_cast<unsigned>(static_cast<int>(epixel) - 0xf);
if (spix <= 0xffff)
out(row, col) = spix & 0xffff;
else {
epixel = static_cast<int>(epixel + 0x7ffffff1) >> 0x1f;
out(row, col) = epixel & 0x3fff;
}
}
}
void PanasonicDecompressorV6::decompressRow(int row) const {
const int blocksperrow =
mRaw->dim.x / PanasonicDecompressorV6::PixelsPerBlock;
const int bytesPerRow = PanasonicDecompressorV6::BytesPerBlock * blocksperrow;
ByteStream rowInput = input.getSubStream(bytesPerRow * row, bytesPerRow);
for (int rblock = 0, col = 0; rblock < blocksperrow;
rblock++, col += PanasonicDecompressorV6::PixelsPerBlock)
decompressBlock(&rowInput, row, col);
}
void PanasonicDecompressorV6::decompress() const {
#ifdef HAVE_OPENMP
#pragma omp parallel for num_threads(rawspeed_get_number_of_processor_cores()) \
schedule(static) default(none)
#endif
for (int row = 0; row < mRaw->dim.y; ++row) {
try {
decompressRow(row);
} catch (RawspeedException& err) {
// Propagate the exception out of OpenMP magic.
mRaw->setError(err.what());
}
}
std::string firstErr;
if (mRaw->isTooManyErrors(1, &firstErr)) {
ThrowRDE("Too many errors encountered. Giving up. First Error:\n%s",
firstErr.c_str());
}
}
} // namespace rawspeed
<commit_msg>PanasonicDecompressorV6: do check that width is a multiple of 11<commit_after>/*
RawSpeed - RAW file decoder.
Copyright (C) 2019 LibRaw LLC ([email protected])
Copyright (C) 2020 Roman Lebedev
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "decompressors/PanasonicDecompressorV6.h" // for PanasonicDecompre...
#include "common/Array2DRef.h" // for Array2DRef
#include "common/Point.h" // for iPoint2D
#include "common/RawImage.h" // for RawImage, RawImag...
#include "decoders/RawDecoderException.h" // for ThrowRDE
#include <algorithm> // for copy_n
#include <array>
#include <cstdint> // for uint16_t, uint32_t
#include <cstdlib> // for free, malloc
namespace rawspeed {
constexpr int PanasonicDecompressorV6::PixelsPerBlock;
constexpr int PanasonicDecompressorV6::BytesPerBlock;
namespace {
struct pana_cs6_page_decoder {
std::array<uint16_t, 14> pixelbuffer;
unsigned char current = 0;
explicit pana_cs6_page_decoder(const ByteStream& bs) {
pixelbuffer[0] = (bs.peekByte(15) << 6) | (bs.peekByte(14) >> 2); // 14 bit
pixelbuffer[1] = (((bs.peekByte(14) & 0x3) << 12) | (bs.peekByte(13) << 4) |
(bs.peekByte(12) >> 4)) &
0x3fff;
pixelbuffer[2] = (bs.peekByte(12) >> 2) & 0x3;
pixelbuffer[3] = ((bs.peekByte(12) & 0x3) << 8) | bs.peekByte(11);
pixelbuffer[4] = (bs.peekByte(10) << 2) | (bs.peekByte(9) >> 6);
pixelbuffer[5] = ((bs.peekByte(9) & 0x3f) << 4) | (bs.peekByte(8) >> 4);
pixelbuffer[6] = (bs.peekByte(8) >> 2) & 0x3;
pixelbuffer[7] = ((bs.peekByte(8) & 0x3) << 8) | bs.peekByte(7);
pixelbuffer[8] = ((bs.peekByte(6) << 2) & 0x3fc) | (bs.peekByte(5) >> 6);
pixelbuffer[9] = ((bs.peekByte(5) << 4) | (bs.peekByte(4) >> 4)) & 0x3ff;
pixelbuffer[10] = (bs.peekByte(4) >> 2) & 0x3;
pixelbuffer[11] = ((bs.peekByte(4) & 0x3) << 8) | bs.peekByte(3);
pixelbuffer[12] =
(((bs.peekByte(2) << 2) & 0x3fc) | bs.peekByte(1) >> 6) & 0x3ff;
pixelbuffer[13] = ((bs.peekByte(1) << 4) | (bs.peekByte(0) >> 4)) & 0x3ff;
}
uint16_t nextpixel() { return pixelbuffer[current++]; }
};
} // namespace
PanasonicDecompressorV6::PanasonicDecompressorV6(const RawImage& img,
ByteStream input_)
: mRaw(img), input(std::move(input_)) {
if (mRaw->getCpp() != 1 || mRaw->getDataType() != TYPE_USHORT16 ||
mRaw->getBpp() != sizeof(uint16_t))
ThrowRDE("Unexpected component count / data type");
if (!mRaw->dim.hasPositiveArea() ||
mRaw->dim.x % PanasonicDecompressorV6::PixelsPerBlock != 0) {
ThrowRDE("Unexpected image dimensions found: (%i; %i)", mRaw->dim.x,
mRaw->dim.y);
}
const int blocksperrow =
mRaw->dim.x / PanasonicDecompressorV6::PixelsPerBlock;
const int bytesPerRow = PanasonicDecompressorV6::BytesPerBlock * blocksperrow;
const int bytesTotal = bytesPerRow * mRaw->dim.y;
input = input_.peekStream(bytesTotal);
}
void PanasonicDecompressorV6::decompressBlock(ByteStream* rowInput, int row,
int col) const {
const Array2DRef<uint16_t> out(mRaw->getU16DataAsUncroppedArray2DRef());
pana_cs6_page_decoder page(
rowInput->getStream(PanasonicDecompressorV6::BytesPerBlock));
std::array<unsigned, 2> oddeven = {0, 0};
std::array<unsigned, 2> nonzero = {0, 0};
unsigned pmul = 0;
unsigned pixel_base = 0;
for (int pix = 0; pix < PanasonicDecompressorV6::PixelsPerBlock;
pix++, col++) {
if (pix % 3 == 2) {
uint16_t base = page.nextpixel();
if (base > 3)
ThrowRDE("Invariant failure");
if (base == 3)
base = 4;
pixel_base = 0x200 << base;
pmul = 1 << base;
}
uint16_t epixel = page.nextpixel();
if (oddeven[pix % 2]) {
epixel *= pmul;
if (pixel_base < 0x2000 && nonzero[pix % 2] > pixel_base)
epixel += nonzero[pix % 2] - pixel_base;
nonzero[pix % 2] = epixel;
} else {
oddeven[pix % 2] = epixel;
if (epixel)
nonzero[pix % 2] = epixel;
else
epixel = nonzero[pix % 2];
}
auto spix = static_cast<unsigned>(static_cast<int>(epixel) - 0xf);
if (spix <= 0xffff)
out(row, col) = spix & 0xffff;
else {
epixel = static_cast<int>(epixel + 0x7ffffff1) >> 0x1f;
out(row, col) = epixel & 0x3fff;
}
}
}
void PanasonicDecompressorV6::decompressRow(int row) const {
assert(mRaw->dim.x % PanasonicDecompressorV6::PixelsPerBlock == 0);
const int blocksperrow =
mRaw->dim.x / PanasonicDecompressorV6::PixelsPerBlock;
const int bytesPerRow = PanasonicDecompressorV6::BytesPerBlock * blocksperrow;
ByteStream rowInput = input.getSubStream(bytesPerRow * row, bytesPerRow);
for (int rblock = 0, col = 0; rblock < blocksperrow;
rblock++, col += PanasonicDecompressorV6::PixelsPerBlock)
decompressBlock(&rowInput, row, col);
}
void PanasonicDecompressorV6::decompress() const {
#ifdef HAVE_OPENMP
#pragma omp parallel for num_threads(rawspeed_get_number_of_processor_cores()) \
schedule(static) default(none)
#endif
for (int row = 0; row < mRaw->dim.y; ++row) {
try {
decompressRow(row);
} catch (RawspeedException& err) {
// Propagate the exception out of OpenMP magic.
mRaw->setError(err.what());
}
}
std::string firstErr;
if (mRaw->isTooManyErrors(1, &firstErr)) {
ThrowRDE("Too many errors encountered. Giving up. First Error:\n%s",
firstErr.c_str());
}
}
} // namespace rawspeed
<|endoftext|> |
<commit_before>#ifdef _MSC_VER
# pragma warning(push)
//because LLVM IR Builder code is broken: e.g. Instructions.h:521-527
# pragma warning(disable:4244)
# pragma warning(disable:4800)
# pragma warning(disable:4267)
#endif
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/Analysis/CaptureTracking.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/Host.h>
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#include <stdio.h>
#include "codegen.h"
using namespace llvm;
char* LLVMGetHostCPUName()
{
return strdup(sys::getHostCPUName().str().c_str());
}
void LLVMSetUnsafeAlgebra(LLVMValueRef inst)
{
unwrap<Instruction>(inst)->setHasUnsafeAlgebra(true);
}
void LLVMSetReturnNoAlias(LLVMValueRef fun)
{
unwrap<Function>(fun)->setDoesNotAlias(0);
}
static void print_transform(compile_t* c, Instruction* inst, const char* s)
{
if(!c->opt->print_stats)
return;
Instruction* i = inst;
while(i->getDebugLoc().getLine() == 0)
{
BasicBlock::iterator iter = i;
if(++iter == i->getParent()->end())
{
return;
// i = inst;
// break;
}
i = iter;
}
DebugLoc loc = i->getDebugLoc();
DIScope scope = DIScope(loc.getScope());
MDLocation* at = cast_or_null<MDLocation>(loc.getInlinedAt());
if(at != NULL)
{
DIScope scope_at = DIScope((MDNode*)at->getScope());
errorf(NULL, "[%s] %s:%u:%u@%s:%u:%u: %s",
i->getParent()->getParent()->getName().str().c_str(),
scope.getFilename().str().c_str(), loc.getLine(), loc.getCol(),
scope_at.getFilename().str().c_str(), at->getLine(), at->getColumn(), s);
} else {
errorf(NULL, "[%s] %s:%u:%u: %s",
i->getParent()->getParent()->getName().str().c_str(),
scope.getFilename().str().c_str(), loc.getLine(), loc.getCol(), s);
}
}
static LLVMValueRef stack_alloc_inst(compile_t* c, LLVMValueRef inst)
{
CallInst* call = dyn_cast_or_null<CallInst>(unwrap(inst));
if(call == NULL)
return inst;
Function* fun = call->getCalledFunction();
if(fun == NULL)
return inst;
if(fun->getName().compare("pony_alloc") != 0)
return inst;
c->opt->check.stats.heap_alloc++;
if(PointerMayBeCaptured(call, true, false))
{
print_transform(c, call, "captured allocation");
return inst;
}
// TODO: what if it's not constant? could we still alloca?
// https://github.com/ldc-developers/ldc/blob/master/gen/passes/
// GarbageCollect2Stack.cpp
Value* size = call->getArgOperand(0);
ConstantInt* int_size = dyn_cast_or_null<ConstantInt>(size);
if(int_size == NULL)
{
print_transform(c, call, "variable size allocation");
return inst;
}
size_t alloc_size = int_size->getZExtValue();
// Limit stack allocations to 1 kb each.
if(alloc_size > 1024)
{
print_transform(c, call, "large allocation");
return inst;
}
// All alloca should happen in the entry block of a function.
LLVMBasicBlockRef block = LLVMGetInstructionParent(inst);
LLVMValueRef func = LLVMGetBasicBlockParent(block);
block = LLVMGetFirstBasicBlock(func);
LLVMValueRef first_inst = LLVMGetFirstInstruction(block);
LLVMPositionBuilderBefore(c->builder, first_inst);
LLVMValueRef len = LLVMConstInt(c->i64, alloc_size, false);
LLVMValueRef alloca = LLVMBuildArrayAlloca(c->builder, c->i8, len, "");
Instruction* alloca_value = unwrap<Instruction>(alloca);
alloca_value->setDebugLoc(call->getDebugLoc());
BasicBlock::iterator iter(call);
ReplaceInstWithValue(call->getParent()->getInstList(), iter, alloca_value);
c->opt->check.stats.heap_alloc--;
c->opt->check.stats.stack_alloc++;
print_transform(c, alloca_value, "stack allocation");
return wrap(alloca_value);
}
static void stack_alloc_block(compile_t* c, LLVMBasicBlockRef block)
{
LLVMValueRef inst = LLVMGetFirstInstruction(block);
while(inst != NULL)
{
inst = stack_alloc_inst(c, inst);
inst = LLVMGetNextInstruction(inst);
}
}
static void stack_alloc_fun(compile_t* c, LLVMValueRef fun)
{
LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(fun);
while(block != NULL)
{
stack_alloc_block(c, block);
block = LLVMGetNextBasicBlock(block);
}
}
void stack_alloc(compile_t* c)
{
LLVMValueRef fun = LLVMGetFirstFunction(c->module);
while(fun != NULL)
{
stack_alloc_fun(c, fun);
fun = LLVMGetNextFunction(fun);
}
}
<commit_msg>DIScope on LLVM 3.7 takes an MDScope<commit_after>#ifdef _MSC_VER
# pragma warning(push)
//because LLVM IR Builder code is broken: e.g. Instructions.h:521-527
# pragma warning(disable:4244)
# pragma warning(disable:4800)
# pragma warning(disable:4267)
#endif
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/DebugInfo.h>
#include <llvm/Analysis/CaptureTracking.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Support/Host.h>
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#include <stdio.h>
#include "codegen.h"
using namespace llvm;
char* LLVMGetHostCPUName()
{
return strdup(sys::getHostCPUName().str().c_str());
}
void LLVMSetUnsafeAlgebra(LLVMValueRef inst)
{
unwrap<Instruction>(inst)->setHasUnsafeAlgebra(true);
}
void LLVMSetReturnNoAlias(LLVMValueRef fun)
{
unwrap<Function>(fun)->setDoesNotAlias(0);
}
static void print_transform(compile_t* c, Instruction* inst, const char* s)
{
if(!c->opt->print_stats)
return;
Instruction* i = inst;
while(i->getDebugLoc().getLine() == 0)
{
BasicBlock::iterator iter = i;
if(++iter == i->getParent()->end())
return;
i = iter;
}
DebugLoc loc = i->getDebugLoc();
#if LLVM_VERSION_MAJOR > 3 || \
(LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR > 6)
DIScope scope = DIScope(cast_or_null<MDScope>(loc.getScope()));
#else
DIScope scope = DIScope(loc.getScope());
#endif
MDLocation* at = cast_or_null<MDLocation>(loc.getInlinedAt());
if(at != NULL)
{
#if LLVM_VERSION_MAJOR > 3 || \
(LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR > 6)
DIScope scope_at = DIScope(cast_or_null<MDScope>(at->getScope()));
#else
DIScope scope_at = DIScope(cast_or_null<MDNode>(at->getScope()));
#endif
errorf(NULL, "[%s] %s:%u:%u@%s:%u:%u: %s",
i->getParent()->getParent()->getName().str().c_str(),
scope.getFilename().str().c_str(), loc.getLine(), loc.getCol(),
scope_at.getFilename().str().c_str(), at->getLine(), at->getColumn(), s);
} else {
errorf(NULL, "[%s] %s:%u:%u: %s",
i->getParent()->getParent()->getName().str().c_str(),
scope.getFilename().str().c_str(), loc.getLine(), loc.getCol(), s);
}
}
static LLVMValueRef stack_alloc_inst(compile_t* c, LLVMValueRef inst)
{
CallInst* call = dyn_cast_or_null<CallInst>(unwrap(inst));
if(call == NULL)
return inst;
Function* fun = call->getCalledFunction();
if(fun == NULL)
return inst;
if(fun->getName().compare("pony_alloc") != 0)
return inst;
c->opt->check.stats.heap_alloc++;
if(PointerMayBeCaptured(call, true, false))
{
print_transform(c, call, "captured allocation");
return inst;
}
// TODO: what if it's not constant? could we still alloca?
// https://github.com/ldc-developers/ldc/blob/master/gen/passes/
// GarbageCollect2Stack.cpp
Value* size = call->getArgOperand(0);
ConstantInt* int_size = dyn_cast_or_null<ConstantInt>(size);
if(int_size == NULL)
{
print_transform(c, call, "variable size allocation");
return inst;
}
size_t alloc_size = int_size->getZExtValue();
// Limit stack allocations to 1 kb each.
if(alloc_size > 1024)
{
print_transform(c, call, "large allocation");
return inst;
}
// All alloca should happen in the entry block of a function.
LLVMBasicBlockRef block = LLVMGetInstructionParent(inst);
LLVMValueRef func = LLVMGetBasicBlockParent(block);
block = LLVMGetFirstBasicBlock(func);
LLVMValueRef first_inst = LLVMGetFirstInstruction(block);
LLVMPositionBuilderBefore(c->builder, first_inst);
LLVMValueRef len = LLVMConstInt(c->i64, alloc_size, false);
LLVMValueRef alloca = LLVMBuildArrayAlloca(c->builder, c->i8, len, "");
Instruction* alloca_value = unwrap<Instruction>(alloca);
alloca_value->setDebugLoc(call->getDebugLoc());
BasicBlock::iterator iter(call);
ReplaceInstWithValue(call->getParent()->getInstList(), iter, alloca_value);
c->opt->check.stats.heap_alloc--;
c->opt->check.stats.stack_alloc++;
print_transform(c, alloca_value, "stack allocation");
return wrap(alloca_value);
}
static void stack_alloc_block(compile_t* c, LLVMBasicBlockRef block)
{
LLVMValueRef inst = LLVMGetFirstInstruction(block);
while(inst != NULL)
{
inst = stack_alloc_inst(c, inst);
inst = LLVMGetNextInstruction(inst);
}
}
static void stack_alloc_fun(compile_t* c, LLVMValueRef fun)
{
LLVMBasicBlockRef block = LLVMGetFirstBasicBlock(fun);
while(block != NULL)
{
stack_alloc_block(c, block);
block = LLVMGetNextBasicBlock(block);
}
}
void stack_alloc(compile_t* c)
{
LLVMValueRef fun = LLVMGetFirstFunction(c->module);
while(fun != NULL)
{
stack_alloc_fun(c, fun);
fun = LLVMGetNextFunction(fun);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: scripttypedetector.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2004-03-08 17:17:18 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <com/sun/star/i18n/CTLScriptType.hpp>
#include <com/sun/star/i18n/ScriptDirection.hpp>
#include <com/sun/star/i18n/UnicodeScript.hpp>
#include <scripttypedetector.hxx>
#include <i18nutil/unicode.hxx>
// ----------------------------------------------------
// class ScriptTypeDetector
// ----------------------------------------------------;
using namespace com::sun::star::i18n;
ScriptTypeDetector::ScriptTypeDetector()
{
}
ScriptTypeDetector::~ScriptTypeDetector()
{
}
static sal_Int16 scriptDirection[] = {
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT = 0,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT = 1,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER = 2,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER_SEPARATOR = 3,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER_TERMINATOR = 4,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_ARABIC_NUMBER = 5,
ScriptDirection::NEUTRAL, // DirectionProperty_COMMON_NUMBER_SEPARATOR = 6,
ScriptDirection::NEUTRAL, // DirectionProperty_BLOCK_SEPARATOR = 7,
ScriptDirection::NEUTRAL, // DirectionProperty_SEGMENT_SEPARATOR = 8,
ScriptDirection::NEUTRAL, // DirectionProperty_WHITE_SPACE_NEUTRAL = 9,
ScriptDirection::NEUTRAL, // DirectionProperty_OTHER_NEUTRAL = 10,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT_EMBEDDING = 11,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT_OVERRIDE = 12,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_ARABIC = 13,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_EMBEDDING = 14,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_OVERRIDE = 15,
ScriptDirection::NEUTRAL, // DirectionProperty_POP_DIRECTIONAL_FORMAT = 16,
ScriptDirection::NEUTRAL, // DirectionProperty_DIR_NON_SPACING_MARK = 17,
ScriptDirection::NEUTRAL, // DirectionProperty_BOUNDARY_NEUTRAL = 18,
};
sal_Int16 SAL_CALL
ScriptTypeDetector::getScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 defaultScriptDirection ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int16 dir = scriptDirection[unicode::getUnicodeDirection(Text[nPos])];
return (dir == ScriptDirection::NEUTRAL) ? defaultScriptDirection : dir;
}
// return value '-1' means either the direction on nPos is not same as scriptDirection or nPos is out of range.
sal_Int32 SAL_CALL
ScriptTypeDetector::beginOfScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 scriptDirection ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int32 cPos = nPos;
if (cPos < Text.getLength()) {
for (; cPos >= 0; cPos--) {
if (scriptDirection != getScriptDirection(Text, cPos, scriptDirection))
break;
}
return cPos == nPos ? -1 : cPos + 1;
}
}
sal_Int32 SAL_CALL
ScriptTypeDetector::endOfScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 scriptDirection ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int32 cPos = nPos;
sal_Int32 len = Text.getLength();
if (cPos >=0) {
for (; cPos < len; cPos++) {
if (scriptDirection != getScriptDirection(Text, cPos, scriptDirection))
break;
}
}
return cPos == nPos ? -1 : cPos;
}
sal_Int16 SAL_CALL
ScriptTypeDetector::getCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
static ScriptTypeList typeList[] = {
{ UnicodeScript_kHebrew, UnicodeScript_kHebrew, CTLScriptType::CTL_HEBREW }, // 10
{ UnicodeScript_kArabic, UnicodeScript_kArabic, CTLScriptType::CTL_ARABIC }, // 11
{ UnicodeScript_kDevanagari, UnicodeScript_kDevanagari, CTLScriptType::CTL_INDIC }, // 14
{ UnicodeScript_kThai, UnicodeScript_kThai, CTLScriptType::CTL_THAI }, // 24
{ UnicodeScript_kScriptCount, UnicodeScript_kScriptCount, CTLScriptType::CTL_UNKNOWN } // 88
};
return unicode::getUnicodeScriptType(Text[nPos], typeList, CTLScriptType::CTL_UNKNOWN);
}
// Begin of Script Type is inclusive.
sal_Int32 SAL_CALL
ScriptTypeDetector::beginOfCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
if (nPos < 0)
return 0;
else if (nPos >= Text.getLength())
return Text.getLength();
else {
sal_Int16 cType = getCTLScriptType(Text, nPos);
for (nPos--; nPos >= 0; nPos--) {
if (cType != getCTLScriptType(Text, nPos))
break;
}
return nPos + 1;
}
}
// End of the Script Type is exclusive, the return value pointing to the begin of next script type
sal_Int32 SAL_CALL
ScriptTypeDetector::endOfCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
if (nPos < 0)
return 0;
else if (nPos >= Text.getLength())
return Text.getLength();
else {
sal_Int16 cType = getCTLScriptType(Text, nPos);
sal_Int32 len = Text.getLength();
for (nPos++; nPos < len; nPos++) {
if (cType != getCTLScriptType(Text, nPos))
break;
}
return nPos;
}
}
const sal_Char sDetector[] = "draft.com.sun.star.i18n.ScriptTypeDetector";
rtl::OUString SAL_CALL
ScriptTypeDetector::getImplementationName() throw( ::com::sun::star::uno::RuntimeException )
{
return ::rtl::OUString::createFromAscii(sDetector);
}
sal_Bool SAL_CALL
ScriptTypeDetector::supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException )
{
return !ServiceName.compareToAscii(sDetector);
}
::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
ScriptTypeDetector::getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException )
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aRet(1);
aRet[0] = ::rtl::OUString::createFromAscii(sDetector);
return aRet;
}
<commit_msg>INTEGRATION: CWS localedata5 (1.5.62); FILE MERGED 2005/05/19 17:20:12 er 1.5.62.1: #i47962# eliminate warning: control reached end of non-void function (could had been reached)<commit_after>/*************************************************************************
*
* $RCSfile: scripttypedetector.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2005-07-21 14:27:06 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#include <com/sun/star/i18n/CTLScriptType.hpp>
#include <com/sun/star/i18n/ScriptDirection.hpp>
#include <com/sun/star/i18n/UnicodeScript.hpp>
#include <scripttypedetector.hxx>
#include <i18nutil/unicode.hxx>
// ----------------------------------------------------
// class ScriptTypeDetector
// ----------------------------------------------------;
using namespace com::sun::star::i18n;
ScriptTypeDetector::ScriptTypeDetector()
{
}
ScriptTypeDetector::~ScriptTypeDetector()
{
}
static sal_Int16 scriptDirection[] = {
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT = 0,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT = 1,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER = 2,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER_SEPARATOR = 3,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_EUROPEAN_NUMBER_TERMINATOR = 4,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_ARABIC_NUMBER = 5,
ScriptDirection::NEUTRAL, // DirectionProperty_COMMON_NUMBER_SEPARATOR = 6,
ScriptDirection::NEUTRAL, // DirectionProperty_BLOCK_SEPARATOR = 7,
ScriptDirection::NEUTRAL, // DirectionProperty_SEGMENT_SEPARATOR = 8,
ScriptDirection::NEUTRAL, // DirectionProperty_WHITE_SPACE_NEUTRAL = 9,
ScriptDirection::NEUTRAL, // DirectionProperty_OTHER_NEUTRAL = 10,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT_EMBEDDING = 11,
ScriptDirection::LEFT_TO_RIGHT, // DirectionProperty_LEFT_TO_RIGHT_OVERRIDE = 12,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_ARABIC = 13,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_EMBEDDING = 14,
ScriptDirection::RIGHT_TO_LEFT, // DirectionProperty_RIGHT_TO_LEFT_OVERRIDE = 15,
ScriptDirection::NEUTRAL, // DirectionProperty_POP_DIRECTIONAL_FORMAT = 16,
ScriptDirection::NEUTRAL, // DirectionProperty_DIR_NON_SPACING_MARK = 17,
ScriptDirection::NEUTRAL, // DirectionProperty_BOUNDARY_NEUTRAL = 18,
};
sal_Int16 SAL_CALL
ScriptTypeDetector::getScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 defaultScriptDirection ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int16 dir = scriptDirection[unicode::getUnicodeDirection(Text[nPos])];
return (dir == ScriptDirection::NEUTRAL) ? defaultScriptDirection : dir;
}
// return value '-1' means either the direction on nPos is not same as scriptDirection or nPos is out of range.
sal_Int32 SAL_CALL
ScriptTypeDetector::beginOfScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 scriptDirection ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int32 cPos = nPos;
if (cPos < Text.getLength()) {
for (; cPos >= 0; cPos--) {
if (scriptDirection != getScriptDirection(Text, cPos, scriptDirection))
break;
}
}
return cPos == nPos ? -1 : cPos + 1;
}
sal_Int32 SAL_CALL
ScriptTypeDetector::endOfScriptDirection( const ::rtl::OUString& Text, sal_Int32 nPos, sal_Int16 scriptDirection ) throw (::com::sun::star::uno::RuntimeException)
{
sal_Int32 cPos = nPos;
sal_Int32 len = Text.getLength();
if (cPos >=0) {
for (; cPos < len; cPos++) {
if (scriptDirection != getScriptDirection(Text, cPos, scriptDirection))
break;
}
}
return cPos == nPos ? -1 : cPos;
}
sal_Int16 SAL_CALL
ScriptTypeDetector::getCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
static ScriptTypeList typeList[] = {
{ UnicodeScript_kHebrew, UnicodeScript_kHebrew, CTLScriptType::CTL_HEBREW }, // 10
{ UnicodeScript_kArabic, UnicodeScript_kArabic, CTLScriptType::CTL_ARABIC }, // 11
{ UnicodeScript_kDevanagari, UnicodeScript_kDevanagari, CTLScriptType::CTL_INDIC }, // 14
{ UnicodeScript_kThai, UnicodeScript_kThai, CTLScriptType::CTL_THAI }, // 24
{ UnicodeScript_kScriptCount, UnicodeScript_kScriptCount, CTLScriptType::CTL_UNKNOWN } // 88
};
return unicode::getUnicodeScriptType(Text[nPos], typeList, CTLScriptType::CTL_UNKNOWN);
}
// Begin of Script Type is inclusive.
sal_Int32 SAL_CALL
ScriptTypeDetector::beginOfCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
if (nPos < 0)
return 0;
else if (nPos >= Text.getLength())
return Text.getLength();
else {
sal_Int16 cType = getCTLScriptType(Text, nPos);
for (nPos--; nPos >= 0; nPos--) {
if (cType != getCTLScriptType(Text, nPos))
break;
}
return nPos + 1;
}
}
// End of the Script Type is exclusive, the return value pointing to the begin of next script type
sal_Int32 SAL_CALL
ScriptTypeDetector::endOfCTLScriptType( const ::rtl::OUString& Text, sal_Int32 nPos ) throw (::com::sun::star::uno::RuntimeException)
{
if (nPos < 0)
return 0;
else if (nPos >= Text.getLength())
return Text.getLength();
else {
sal_Int16 cType = getCTLScriptType(Text, nPos);
sal_Int32 len = Text.getLength();
for (nPos++; nPos < len; nPos++) {
if (cType != getCTLScriptType(Text, nPos))
break;
}
return nPos;
}
}
const sal_Char sDetector[] = "draft.com.sun.star.i18n.ScriptTypeDetector";
rtl::OUString SAL_CALL
ScriptTypeDetector::getImplementationName() throw( ::com::sun::star::uno::RuntimeException )
{
return ::rtl::OUString::createFromAscii(sDetector);
}
sal_Bool SAL_CALL
ScriptTypeDetector::supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException )
{
return !ServiceName.compareToAscii(sDetector);
}
::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL
ScriptTypeDetector::getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException )
{
::com::sun::star::uno::Sequence< ::rtl::OUString > aRet(1);
aRet[0] = ::rtl::OUString::createFromAscii(sDetector);
return aRet;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. 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.
//
// SPDX-License-Identifier: Apache-2.0
#if !defined(__APPLE__)
#include "iceoryx_posh/iceoryx_posh_config.hpp"
#include "iceoryx_posh/internal/roudi/memory/mempool_collection_memory_block.hpp"
#include "iceoryx_posh/mepoo/mepoo_config.hpp"
#include "iceoryx_posh/roudi/memory/posix_shm_memory_provider.hpp"
#include "iceoryx_utils/posix_wrapper/posix_access_rights.hpp"
#include "test.hpp"
#include <thread>
namespace
{
using namespace ::testing;
TEST(ShmCreatorDeathTest, AllocatingTooMuchMemoryLeadsToExitWithSIGBUS)
{
const iox::ShmName_t TEST_SHM_NAME{"/test_name"};
// try a config with high memory requirements, expect failure
iox::mepoo::MePooConfig badconfig;
badconfig.addMemPool({1 << 30, 100});
iox::roudi::MemPoolCollectionMemoryBlock badmempools(badconfig);
iox::roudi::PosixShmMemoryProvider badShmProvider(
TEST_SHM_NAME, iox::posix::AccessMode::readWrite, iox::posix::OwnerShip::mine);
badShmProvider.addMemoryBlock(&badmempools);
EXPECT_DEATH(badShmProvider.create(),
"\033\\[0;1;97;41mFatal error:\033\\[m the available memory is insufficient. Cannot allocate mempools "
"in shared memory. Please make sure that enough memory is available. For this, consider also the "
"memory which is required for the \\[/iceoryx_mgmt\\] segment. Please refer to "
"share\\/doc\\/iceoryx\\/FAQ.md in your release delivery.");
// try again with a config with low memory requirements; success clears shared memory allocated by the OS in e.g.
// /dev/shm
iox::mepoo::MePooConfig goodconfig;
goodconfig.addMemPool({1024, 1});
iox::roudi::MemPoolCollectionMemoryBlock goodmempools(goodconfig);
iox::roudi::PosixShmMemoryProvider goodShmProvider(
TEST_SHM_NAME, iox::posix::AccessMode::readWrite, iox::posix::OwnerShip::mine);
goodShmProvider.addMemoryBlock(&goodmempools);
goodShmProvider.create();
}
} // namespace
#endif
<commit_msg>iox-#542 removed posix wrapper error message from death test in posh integration test<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. 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.
//
// SPDX-License-Identifier: Apache-2.0
#if !defined(__APPLE__)
#include "iceoryx_posh/iceoryx_posh_config.hpp"
#include "iceoryx_posh/internal/roudi/memory/mempool_collection_memory_block.hpp"
#include "iceoryx_posh/mepoo/mepoo_config.hpp"
#include "iceoryx_posh/roudi/memory/posix_shm_memory_provider.hpp"
#include "iceoryx_utils/posix_wrapper/posix_access_rights.hpp"
#include "test.hpp"
#include <thread>
namespace
{
using namespace ::testing;
TEST(ShmCreatorDeathTest, AllocatingTooMuchMemoryLeadsToExitWithSIGBUS)
{
const iox::ShmName_t TEST_SHM_NAME{"/test_name"};
// try a config with high memory requirements, expect failure
iox::mepoo::MePooConfig badconfig;
badconfig.addMemPool({1 << 30, 100});
iox::roudi::MemPoolCollectionMemoryBlock badmempools(badconfig);
iox::roudi::PosixShmMemoryProvider badShmProvider(
TEST_SHM_NAME, iox::posix::AccessMode::readWrite, iox::posix::OwnerShip::mine);
badShmProvider.addMemoryBlock(&badmempools);
EXPECT_DEATH(badShmProvider.create(), ".*");
// try again with a config with low memory requirements; success clears shared memory allocated by the OS in e.g.
// /dev/shm
iox::mepoo::MePooConfig goodconfig;
goodconfig.addMemPool({1024, 1});
iox::roudi::MemPoolCollectionMemoryBlock goodmempools(goodconfig);
iox::roudi::PosixShmMemoryProvider goodShmProvider(
TEST_SHM_NAME, iox::posix::AccessMode::readWrite, iox::posix::OwnerShip::mine);
goodShmProvider.addMemoryBlock(&goodmempools);
goodShmProvider.create();
}
} // namespace
#endif
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* 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 <votca/tools/histogramnew.h>
namespace votca { namespace tools {
HistogramNew::HistogramNew()
{
_min=_max=_step=0;
_weight = 1.;
_periodic=false;
}
HistogramNew::HistogramNew(const HistogramNew &hist)
: _min(hist._min), _max(hist._max), _step(hist._step),
_weight(hist._weight), _periodic(hist._periodic)
{}
void HistogramNew::Initialize(double min, double max, int nbins)
{
_min = min; _max = max;
_step = (_max - _min)/nbins;
_weight = 1.;
_data.resize(nbins);
_nbins = nbins;
for(double v=_min, i=0; i<nbins; v+=_step,++i)
_data.x(i)=v;
_data.y()=ub::zero_vector<double>(_nbins);
_data.yerr()=ub::zero_vector<double>(_nbins);
_data.flags()=ub::scalar_vector<char>(_nbins, 'i');
}
void HistogramNew::Process(const double &v, double scale)
{
int i = (int) ((v - _min) / _step + 0.5);
if (i < 0 || i >= _nbins) {
if(!_periodic) return;
if(i<0) i = _nbins - ((-i) % _nbins);
else i = i % _nbins;
}
_data.y(i) += _weight * scale;
}
void HistogramNew::Normalize()
{
double area = 0;
area=ub::norm_1(_data.x()) * _step;
_weight /= area;
double scale = 1./area;
_data.y() *= scale;
}
void HistogramNew::Clear()
{
_weight = 1.;
_data.y() = ub::zero_vector<double>(_nbins);
_data.yerr() = ub::zero_vector<double>(_nbins);
}
}}
<commit_msg>fixed HistogramNew::Normalize - was used anywhere so far<commit_after>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* 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 <votca/tools/histogramnew.h>
namespace votca { namespace tools {
HistogramNew::HistogramNew()
{
_min=_max=_step=0;
_weight = 1.;
_periodic=false;
}
HistogramNew::HistogramNew(const HistogramNew &hist)
: _min(hist._min), _max(hist._max), _step(hist._step),
_weight(hist._weight), _periodic(hist._periodic)
{}
void HistogramNew::Initialize(double min, double max, int nbins)
{
_min = min; _max = max;
_step = (_max - _min)/nbins;
_weight = 1.;
_data.resize(nbins);
_nbins = nbins;
for(double v=_min, i=0; i<nbins; v+=_step,++i)
_data.x(i)=v;
_data.y()=ub::zero_vector<double>(_nbins);
_data.yerr()=ub::zero_vector<double>(_nbins);
_data.flags()=ub::scalar_vector<char>(_nbins, 'i');
}
void HistogramNew::Process(const double &v, double scale)
{
int i = (int) ((v - _min) / _step + 0.5);
if (i < 0 || i >= _nbins) {
if(!_periodic) return;
if(i<0) i = _nbins - ((-i) % _nbins);
else i = i % _nbins;
}
_data.y(i) += _weight * scale;
}
void HistogramNew::Normalize()
{
double area = 0;
area=ub::norm_1(_data.y()) * _step;
double scale = 1./area;
_data.y() *= scale;
}
void HistogramNew::Clear()
{
_weight = 1.;
_data.y() = ub::zero_vector<double>(_nbins);
_data.yerr() = ub::zero_vector<double>(_nbins);
}
}}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2019 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 <cassert>
#include <votca/tools/edge.h>
#include <votca/tools/reducedgraph.h>
using namespace std;
namespace votca {
namespace tools {
class GraphNode;
bool compareChainWithChains_(const vector<int>& chain,
const vector<vector<int>>& chains) {
bool match = false;
for (const vector<int>& chain2 : chains) {
if (chain2.size() == chain.size()) {
match = true;
for (size_t index = 0; index < chain.size(); ++index) {
if (chain2.at(index) != chain.at(index)) {
match = false;
break;
}
} // Cycle vertices in each chain
if (match) return true;
} // Chains same size
}
return false;
}
set<int> getVertexJunctions_(const vector<ReducedEdge>& reduced_edges) {
unordered_map<int, int> vertex_count;
for (ReducedEdge reduced_edge : reduced_edges) {
// if loop, increment value is double and the first index is skipped to
// prevent over counting of the first number
int increment = 1;
size_t index = 0;
if (reduced_edge.loop()) {
++index;
increment = 2;
}
vector<int> chain = reduced_edge.getChain();
for (; index < chain.size(); ++index) {
if (vertex_count.count(chain.at(index))) {
vertex_count[chain.at(index)] += increment;
} else {
vertex_count[chain.at(index)] = increment;
}
}
}
set<int> junctions;
for (pair<int, int> vertex_and_count : vertex_count) {
if (vertex_and_count.second > 2) {
junctions.insert(vertex_and_count.first);
}
}
return junctions;
}
void addEdgeIfNotLoop_(
vector<Edge>& edges, const ReducedEdge reduced_edge,
unordered_map<Edge, vector<vector<int>>>& expanded_edges) {
Edge edge(reduced_edge.getEndPoint1(), reduced_edge.getEndPoint2());
if (expanded_edges.count(edge)) {
bool match =
compareChainWithChains_(reduced_edge.getChain(), expanded_edges[edge]);
if (!match) {
expanded_edges[edge].push_back(reduced_edge.getChain());
}
} else {
expanded_edges[edge].push_back(reduced_edge.getChain());
}
edges.push_back(edge);
}
void orderChainAfterInitialVertex_(vector<int>& chain) {
size_t ignore_first_and_last_vertex = 2;
size_t total_number_to_parse =
(chain.size() - ignore_first_and_last_vertex) / 2;
bool reverse_vector = false;
for (size_t count = 0; count < (total_number_to_parse); ++count) {
if (chain.at(chain.size() - count - 1) < chain.at(count + 1)) {
reverse_vector = true;
break;
}
}
if (reverse_vector) {
reverse(chain.begin(), chain.end());
}
}
bool reordereAndStoreChainIfDoesNotExist_(
vector<Edge>& edges,
unordered_map<Edge, vector<vector<int>>>& expanded_edges, vector<int> chain,
int vertex, size_t& chain_index) {
Edge edge(vertex, vertex);
edges.push_back(edge);
vector<int> new_chain;
for (size_t index = 0; index < chain.size(); ++index) {
if (((chain_index + index) % chain.size()) == 0) {
++chain_index;
}
int new_chain_index = (chain_index + index) % chain.size();
new_chain.push_back(chain.at(new_chain_index));
}
// Ensure that the new_chain is sorted so after the first vertex they are
// ordered from smallest to largest
orderChainAfterInitialVertex_(new_chain);
bool match = compareChainWithChains_(new_chain, expanded_edges[edge]);
if (!match) {
expanded_edges[edge].push_back(new_chain);
return true;
}
return false;
}
void ReducedGraph::init_(vector<ReducedEdge> reduced_edges,
unordered_map<int, GraphNode> nodes) {
vector<Edge> edges;
nodes_ = nodes;
junctions_ = getVertexJunctions_(reduced_edges);
for (const ReducedEdge& reduced_edge : reduced_edges) {
if (reduced_edge.loop() &&
junctions_.count(reduced_edge.getEndPoint1()) == 0) {
vector<int> chain = reduced_edge.getChain();
size_t chain_index = 0;
bool edge_added = false;
for (int vertex : chain) {
if (junctions_.count(vertex)) {
edge_added = reordereAndStoreChainIfDoesNotExist_(
edges, expanded_edges_, chain, vertex, chain_index);
break;
}
++chain_index;
}
if (!edge_added) {
addEdgeIfNotLoop_(edges, reduced_edge, expanded_edges_);
}
} else {
addEdgeIfNotLoop_(edges, reduced_edge, expanded_edges_);
}
}
edge_container_ = EdgeContainer(edges);
calcId_();
}
set<int> getAllVertices_(const std::vector<ReducedEdge>& reduced_edges) {
set<int> vertices;
for (const ReducedEdge& reduced_edge : reduced_edges) {
vector<int> chain = reduced_edge.getChain();
for (const int vertex : chain) {
vertices.insert(vertex);
}
}
return vertices;
}
ReducedGraph::ReducedGraph(std::vector<ReducedEdge> reduced_edges) {
set<int> vertices = getAllVertices_(reduced_edges);
unordered_map<int, GraphNode> nodes;
for (const int vertex : vertices) {
GraphNode gn;
nodes[vertex] = gn;
}
init_(reduced_edges, nodes);
}
ReducedGraph::ReducedGraph(std::vector<ReducedEdge> reduced_edges,
unordered_map<int, GraphNode> nodes) {
set<int> vertices = getAllVertices_(reduced_edges);
if (nodes.size() < vertices.size()) {
throw invalid_argument(
"The number of nodes passed into a reduced graph "
"must be greater or equivalent to the number of vertices");
}
for (const int vertex : vertices) {
if (nodes.count(vertex) == 0) {
throw invalid_argument("A vertex is missing its corresponding node.");
}
}
init_(reduced_edges, nodes);
// Add all the nodes that are isolated
for (pair<const int, GraphNode>& id_and_node : nodes) {
if (vertices.count(id_and_node.first) == 0) {
edge_container_.addVertex(id_and_node.first);
}
}
}
Graph ReducedGraph::expandGraph() {
vector<Edge> all_expanded_edges;
for (const pair<Edge, vector<vector<int>>> edge_and_vertices :
expanded_edges_) {
vector<vector<Edge>> edges_local = expandEdge(edge_and_vertices.first);
for (vector<Edge>& edges : edges_local) {
all_expanded_edges.insert(all_expanded_edges.end(), edges.begin(),
edges.end());
}
}
return Graph(all_expanded_edges, nodes_);
}
vector<vector<Edge>> ReducedGraph::expandEdge(const Edge& edge) const {
vector<vector<Edge>> all_edges;
vector<vector<int>> chains = expanded_edges_.at(edge);
for (vector<int> vertices : chains) {
vector<Edge> edges;
for (size_t index = 0; index < (vertices.size() - 1); ++index) {
Edge edge_temp(vertices.at(index), vertices.at(index + 1));
edges.push_back(edge_temp);
}
all_edges.push_back(edges);
}
return all_edges;
}
set<int> getAllConnectedVertices_(
const unordered_map<Edge, vector<vector<int>>>& expanded_edges) {
set<int> all_vertices;
for (const auto& edge_and_chains : expanded_edges) {
for (vector<int> chain : edge_and_chains.second) {
all_vertices.insert(chain.begin(), chain.end());
}
}
return all_vertices;
}
vector<pair<int, GraphNode>> ReducedGraph::getNodes() const {
vector<int> vertices = edge_container_.getVertices();
vector<pair<int, GraphNode>> nodes;
for (const int vertex : vertices) {
pair<int, GraphNode> id_and_node(vertex, nodes_.at(vertex));
nodes.push_back(id_and_node);
}
set<int> all_connected_vertices = getAllConnectedVertices_(expanded_edges_);
// Grab the nodes that are not attached to any edges
for (pair<int, GraphNode> id_and_node : nodes_) {
if (!all_connected_vertices.count(id_and_node.first)) {
nodes.push_back(id_and_node);
}
}
return nodes;
}
/*
bool ReducedGraph::edgeExist(const Edge& edge) const {
return edge_container_.edgeExist(edge);
}*/
vector<Edge> ReducedGraph::getEdges() {
/* vector<Edge> edges_unfiltered = edge_container_.getEdges();
vector<Edge> edges;
for(const Edge edge : edges_unfiltered){
if(edge.loop()){
// Find which vertex if any is a junction if it is return the edge so that
// it points to the junction
vector<vector<int>> chains = expanded_edges_.at(edge);
// If it is a loop there should only be a single junction at most
assert(chains.size()==1);
for(int vertex : chains.at(0)){
if(junctions_.count(vertex)){
Edge edge(vertex,vertex);
edges.push_back(edge);
break;
}
}
}else{
edges.push_back(edge);
}
}
return edges;*/
return edge_container_.getEdges();
}
vector<int> ReducedGraph::getVertices() const {
// Get all the vertices that are in the reduced graph
vector<int> vertices = edge_container_.getVertices();
return vertices;
}
vector<int> ReducedGraph::getVerticesDegree(int degree) const {
if (degree == 0) {
set<int> all_connected_vertices = getAllConnectedVertices_(expanded_edges_);
vector<int> vertices;
for (const pair<int, GraphNode> id_and_node : nodes_) {
if (all_connected_vertices.count(id_and_node.first) == false) {
vertices.push_back(id_and_node.first);
}
return vertices;
}
}
return edge_container_.getVerticesDegree(degree);
}
ostream& operator<<(ostream& os, const ReducedGraph graph) {
os << "Graph" << endl;
for (const pair<int, GraphNode>& id_and_node : graph.nodes_) {
os << "Node " << id_and_node.first << endl;
os << id_and_node.second << endl;
}
os << endl;
os << graph.edge_container_ << endl;
os << endl;
os << "Expanded Edge Chains" << endl;
for (const pair<const Edge, vector<vector<int>>>& edge_and_chains :
graph.expanded_edges_) {
for (const vector<int>& chain : edge_and_chains.second) {
for (const int vertex : chain) {
os << vertex << " ";
}
os << endl;
}
os << endl;
}
return os;
}
} // namespace tools
} // namespace votca
<commit_msg>Added some function descriptions for internal functions of reduced graph also deleted some unneeded commented out functionality<commit_after>/*
* Copyright 2009-2019 The VOTCA Development Team
* (http://www.votca.org)
*
* 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 <cassert>
#include <votca/tools/edge.h>
#include <votca/tools/reducedgraph.h>
using namespace std;
namespace votca {
namespace tools {
class GraphNode;
/**
* \brief Function will compare a chain with a vector of chains
*
* If the one of the chains in the vector of chains is equivalent will return
* true. A chain is simply a vector of integers where each integer represents
* a vertex along an edge. The vertices appear in the chain in the same order
* as they exist in a graph.
**/
bool compareChainWithChains_(const vector<int>& chain,
const vector<vector<int>>& chains) {
bool match = false;
for (const vector<int>& chain2 : chains) {
if (chain2.size() == chain.size()) {
match = true;
for (size_t index = 0; index < chain.size(); ++index) {
if (chain2.at(index) != chain.at(index)) {
match = false;
break;
}
} // Cycle vertices in each chain
if (match) return true;
} // Chains same size
}
return false;
}
/**
* \brief Given a vector of Reduced Edges will find and return junctions if any
* exist
*
* A junction is a vertex in a graph that has 3 or more edges eminating from it.
*
* Consider three reduced edges given by
*
* Edge Reduced Edge when Expanded (chain of vertices)
* 1, 5 : 1 - 3 - 4 - 6 - 5
* 5, 10 : 5 - 2 - 10
* 5, 9 : 5 - 8 - 9
*
* Graph:
*
* 1 - 3 - 4 - 6 - 5 - 2 - 10
* |
* 8 - 9
*
* Reduced Graph:
*
* 1 - 5 - 10
* |
* 9
*
* Here vertex 5 would be found to be a junction
*
* @param[in,out] - vector of reduced edges
* @return - set of integers containing junctions
**/
set<int> getVertexJunctions_(const vector<ReducedEdge>& reduced_edges) {
unordered_map<int, int> vertex_count;
for (ReducedEdge reduced_edge : reduced_edges) {
// if loop, increment value is double and the first index is skipped to
// prevent over counting of the first number
int increment = 1;
size_t index = 0;
if (reduced_edge.loop()) {
++index;
increment = 2;
}
vector<int> chain = reduced_edge.getChain();
for (; index < chain.size(); ++index) {
if (vertex_count.count(chain.at(index))) {
vertex_count[chain.at(index)] += increment;
} else {
vertex_count[chain.at(index)] = increment;
}
}
}
set<int> junctions;
for (pair<int, int> vertex_and_count : vertex_count) {
if (vertex_and_count.second > 2) {
junctions.insert(vertex_and_count.first);
}
}
return junctions;
}
/**
* \breif function adds an edge to an unordered_map and a vector if it is found
* to not be a loop
*
* A loop is an edge that essentially makes a circle. In an edge that is a loop
* will have both end points equal to the samve vertex. E.g. a reduced edge
* like this:
*
* Edge Expanded edge (chain of vertices)
* 2, 2 : 2 - 4 - 3 - 5 - 2
*
* Graph
*
* 2 - 4
* | |
* 5 - 3
*
* Reduced Graph
*
* - 2
* |_|
*
* @param[in,out] - vector of edges, an edge is added to the vector if it is not
* a loop
* @param[in] - a reduced edge, the edge to be added
* @param[in,out] - an unordered_map that stores the edge and its chain if it
* is found to not be a loop
**/
void addEdgeIfNotLoop_(
vector<Edge>& edges, const ReducedEdge reduced_edge,
unordered_map<Edge, vector<vector<int>>>& expanded_edges) {
Edge edge(reduced_edge.getEndPoint1(), reduced_edge.getEndPoint2());
if (expanded_edges.count(edge)) {
bool match =
compareChainWithChains_(reduced_edge.getChain(), expanded_edges[edge]);
if (!match) {
expanded_edges[edge].push_back(reduced_edge.getChain());
}
} else {
expanded_edges[edge].push_back(reduced_edge.getChain());
}
edges.push_back(edge);
}
/**
* \brief This is a helper function used to help store the vertex chain in a
* reproducable order
*
* Ordering chains in a reproducable manner enable quicker comparison between
* chains.
*
* E.g. Given a chain
*
* End Point 1
* v
* 1 - 4 - 3 - 5 - 6 - 2 - 1
* ^
* End Point 2
*
* This function will ensure that it is reordered such that the next consecutive
* number in the chain after end point 2 is the lower number, in this case the
* two numbers that are compared are 4 and 2. The 2 is smaller so the chain is
* reordered.
*
* 1 - 2 - 6 - 5 - 3 - 4 - 1
*
* @param[in,out] - vector of integers containing the chain
**/
void orderChainAfterInitialVertex_(vector<int>& chain) {
size_t ignore_first_and_last_vertex = 2;
size_t total_number_to_parse =
(chain.size() - ignore_first_and_last_vertex) / 2;
bool reverse_vector = false;
for (size_t count = 0; count < (total_number_to_parse); ++count) {
if (chain.at(chain.size() - count - 1) < chain.at(count + 1)) {
reverse_vector = true;
break;
}
}
if (reverse_vector) {
reverse(chain.begin(), chain.end());
}
}
bool reorderAndStoreChainIfDoesNotExist_(
vector<Edge>& edges,
unordered_map<Edge, vector<vector<int>>>& expanded_edges, vector<int> chain,
int vertex, size_t& chain_index) {
Edge edge(vertex, vertex);
edges.push_back(edge);
vector<int> new_chain;
for (size_t index = 0; index < chain.size(); ++index) {
if (((chain_index + index) % chain.size()) == 0) {
++chain_index;
}
int new_chain_index = (chain_index + index) % chain.size();
new_chain.push_back(chain.at(new_chain_index));
}
// Ensure that the new_chain is sorted so after the first vertex they are
// ordered from smallest to largest
orderChainAfterInitialVertex_(new_chain);
bool match = compareChainWithChains_(new_chain, expanded_edges[edge]);
if (!match) {
expanded_edges[edge].push_back(new_chain);
return true;
}
return false;
}
void ReducedGraph::init_(vector<ReducedEdge> reduced_edges,
unordered_map<int, GraphNode> nodes) {
vector<Edge> edges;
nodes_ = nodes;
junctions_ = getVertexJunctions_(reduced_edges);
for (const ReducedEdge& reduced_edge : reduced_edges) {
if (reduced_edge.loop() &&
junctions_.count(reduced_edge.getEndPoint1()) == 0) {
vector<int> chain = reduced_edge.getChain();
size_t chain_index = 0;
bool edge_added = false;
for (int vertex : chain) {
if (junctions_.count(vertex)) {
edge_added = reorderAndStoreChainIfDoesNotExist_(
edges, expanded_edges_, chain, vertex, chain_index);
break;
}
++chain_index;
}
if (!edge_added) {
addEdgeIfNotLoop_(edges, reduced_edge, expanded_edges_);
}
} else {
addEdgeIfNotLoop_(edges, reduced_edge, expanded_edges_);
}
}
edge_container_ = EdgeContainer(edges);
calcId_();
}
set<int> getAllVertices_(const std::vector<ReducedEdge>& reduced_edges) {
set<int> vertices;
for (const ReducedEdge& reduced_edge : reduced_edges) {
vector<int> chain = reduced_edge.getChain();
for (const int vertex : chain) {
vertices.insert(vertex);
}
}
return vertices;
}
ReducedGraph::ReducedGraph(std::vector<ReducedEdge> reduced_edges) {
set<int> vertices = getAllVertices_(reduced_edges);
unordered_map<int, GraphNode> nodes;
for (const int vertex : vertices) {
GraphNode gn;
nodes[vertex] = gn;
}
init_(reduced_edges, nodes);
}
ReducedGraph::ReducedGraph(std::vector<ReducedEdge> reduced_edges,
unordered_map<int, GraphNode> nodes) {
set<int> vertices = getAllVertices_(reduced_edges);
if (nodes.size() < vertices.size()) {
throw invalid_argument(
"The number of nodes passed into a reduced graph "
"must be greater or equivalent to the number of vertices");
}
for (const int vertex : vertices) {
if (nodes.count(vertex) == 0) {
throw invalid_argument("A vertex is missing its corresponding node.");
}
}
init_(reduced_edges, nodes);
// Add all the nodes that are isolated
for (pair<const int, GraphNode>& id_and_node : nodes) {
if (vertices.count(id_and_node.first) == 0) {
edge_container_.addVertex(id_and_node.first);
}
}
}
Graph ReducedGraph::expandGraph() {
vector<Edge> all_expanded_edges;
for (const pair<Edge, vector<vector<int>>> edge_and_vertices :
expanded_edges_) {
vector<vector<Edge>> edges_local = expandEdge(edge_and_vertices.first);
for (vector<Edge>& edges : edges_local) {
all_expanded_edges.insert(all_expanded_edges.end(), edges.begin(),
edges.end());
}
}
return Graph(all_expanded_edges, nodes_);
}
vector<vector<Edge>> ReducedGraph::expandEdge(const Edge& edge) const {
vector<vector<Edge>> all_edges;
vector<vector<int>> chains = expanded_edges_.at(edge);
for (vector<int> vertices : chains) {
vector<Edge> edges;
for (size_t index = 0; index < (vertices.size() - 1); ++index) {
Edge edge_temp(vertices.at(index), vertices.at(index + 1));
edges.push_back(edge_temp);
}
all_edges.push_back(edges);
}
return all_edges;
}
set<int> getAllConnectedVertices_(
const unordered_map<Edge, vector<vector<int>>>& expanded_edges) {
set<int> all_vertices;
for (const auto& edge_and_chains : expanded_edges) {
for (vector<int> chain : edge_and_chains.second) {
all_vertices.insert(chain.begin(), chain.end());
}
}
return all_vertices;
}
vector<pair<int, GraphNode>> ReducedGraph::getNodes() const {
vector<int> vertices = edge_container_.getVertices();
vector<pair<int, GraphNode>> nodes;
for (const int vertex : vertices) {
pair<int, GraphNode> id_and_node(vertex, nodes_.at(vertex));
nodes.push_back(id_and_node);
}
set<int> all_connected_vertices = getAllConnectedVertices_(expanded_edges_);
// Grab the nodes that are not attached to any edges
for (pair<int, GraphNode> id_and_node : nodes_) {
if (!all_connected_vertices.count(id_and_node.first)) {
nodes.push_back(id_and_node);
}
}
return nodes;
}
vector<int> ReducedGraph::getVertices() const {
// Get all the vertices that are in the reduced graph
vector<int> vertices = edge_container_.getVertices();
return vertices;
}
vector<int> ReducedGraph::getVerticesDegree(int degree) const {
if (degree == 0) {
set<int> all_connected_vertices = getAllConnectedVertices_(expanded_edges_);
vector<int> vertices;
for (const pair<int, GraphNode> id_and_node : nodes_) {
if (all_connected_vertices.count(id_and_node.first) == false) {
vertices.push_back(id_and_node.first);
}
return vertices;
}
}
return edge_container_.getVerticesDegree(degree);
}
ostream& operator<<(ostream& os, const ReducedGraph graph) {
os << "Graph" << endl;
for (const pair<int, GraphNode>& id_and_node : graph.nodes_) {
os << "Node " << id_and_node.first << endl;
os << id_and_node.second << endl;
}
os << endl;
os << graph.edge_container_ << endl;
os << endl;
os << "Expanded Edge Chains" << endl;
for (const pair<const Edge, vector<vector<int>>>& edge_and_chains :
graph.expanded_edges_) {
for (const vector<int>& chain : edge_and_chains.second) {
for (const int vertex : chain) {
os << vertex << " ";
}
os << endl;
}
os << endl;
}
return os;
}
} // namespace tools
} // namespace votca
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.