text
stringlengths
54
60.6k
<commit_before> #include "executeBaton.h" #include "connection.h" #include "outParam.h" #include <iostream> using namespace std; ExecuteBaton::ExecuteBaton(Connection* connection, const char* sql, v8::Local<v8::Array>* values, v8::Handle<v8::Function>* callback) { this->connection = connection; this->sql = sql; if(callback!=NULL) { uni::Reset(this->callback, *callback); } this->outputs = new std::vector<output_t*>(); this->error = NULL; if (values) CopyValuesToBaton(this, values); this->rows = NULL; } ExecuteBaton::~ExecuteBaton() { callback.Dispose(); for (std::vector<column_t*>::iterator iterator = columns.begin(), end = columns.end(); iterator != end; ++iterator) { column_t* col = *iterator; delete col; } ResetValues(); ResetRows(); ResetOutputs(); ResetError(); } void ExecuteBaton::ResetValues() { for (std::vector<value_t*>::iterator iterator = values.begin(), end = values.end(); iterator != end; ++iterator) { value_t* val = *iterator; switch (val->type) { case VALUE_TYPE_STRING: delete (std::string*)val->value; break; case VALUE_TYPE_NUMBER: delete (oracle::occi::Number*)val->value; break; case VALUE_TYPE_TIMESTAMP: delete (oracle::occi::Timestamp*)val->value; break; case VALUE_TYPE_ARRAY: arrayParam_t* arrParam = (arrayParam_t*)val->value; if (arrParam->value != NULL && arrParam->elementsType == oracle::occi::OCCI_SQLT_STR) delete (char*)arrParam->value; else if (arrParam->value != NULL && arrParam->elementsType == oracle::occi::OCCI_SQLT_NUM) delete (char*)arrParam->value; if (arrParam->elementLength != NULL) delete arrParam->elementLength; delete (arrayParam_t*)val->value; break; } delete val; } values.clear(); } void ExecuteBaton::ResetRows() { if (rows) { for (std::vector<row_t*>::iterator iterator = rows->begin(), end = rows->end(); iterator != end; ++iterator) { row_t* currentRow = *iterator; delete currentRow; } delete rows; rows = NULL; } } void ExecuteBaton::ResetOutputs() { if (outputs) { for (std::vector<output_t*>::iterator iterator = outputs->begin(), end = outputs->end(); iterator != end; ++iterator) { output_t* o = *iterator; delete o; } delete outputs; outputs = NULL; } } void ExecuteBaton::ResetError() { if (error) { delete error; error = NULL; } } double CallDateMethod(v8::Local<v8::Date> date, const char* methodName) { Handle<Value> args[1]; // should be zero but on windows the compiler will not allow a zero length array Local<Value> result = Local<Function>::Cast(date->Get(String::New(methodName)))->Call(date, 0, args); return Local<Number>::Cast(result)->Value(); } oracle::occi::Timestamp* V8DateToOcciDate(oracle::occi::Environment* env, v8::Local<v8::Date> val) { int year = CallDateMethod(val, "getUTCFullYear"); int month = CallDateMethod(val, "getUTCMonth") + 1; int day = CallDateMethod(val, "getUTCDate"); int hours = CallDateMethod(val, "getUTCHours"); int minutes = CallDateMethod(val, "getUTCMinutes"); int seconds = CallDateMethod(val, "getUTCSeconds"); int fs = CallDateMethod(val, "getUTCMilliseconds") * 1000000; // occi::Timestamp() wants nanoseconds oracle::occi::Timestamp* d = new oracle::occi::Timestamp(env, year, month, day, hours, minutes, seconds, fs); return d; } void ExecuteBaton::CopyValuesToBaton(ExecuteBaton* baton, v8::Local<v8::Array>* values) { //XXX cache Length() for(uint32_t i=0; i<(*values)->Length(); i++) { v8::Local<v8::Value> val = (*values)->Get(i); value_t *value = new value_t(); // null if(val->IsNull()) { value->type = VALUE_TYPE_NULL; value->value = NULL; baton->values.push_back(value); } // string else if(val->IsString()) { v8::String::Utf8Value utf8Value(val); value->type = VALUE_TYPE_STRING; value->value = new std::string(*utf8Value); baton->values.push_back(value); } // date else if(val->IsDate()) { value->type = VALUE_TYPE_TIMESTAMP; value->value = V8DateToOcciDate(baton->connection->getEnvironment(), uni::DateCast(val)); baton->values.push_back(value); } // number else if(val->IsNumber()) { value->type = VALUE_TYPE_NUMBER; double d = v8::Number::Cast(*val)->Value(); value->value = new oracle::occi::Number(d); // XXX not deleted in dtor baton->values.push_back(value); } // array else if (val->IsArray()) { value->type = VALUE_TYPE_ARRAY; Local<Array> arr = Local<Array>::Cast(val); value->value = new arrayParam_t(); GetVectorParam(baton, (arrayParam_t*)value->value, arr); baton->values.push_back(value); } // output else if(val->IsObject() && val->ToObject()->FindInstanceInPrototypeChain(uni::Deref(OutParam::constructorTemplate)) != v8::Null()) { OutParam* op = node::ObjectWrap::Unwrap<OutParam>(val->ToObject()); // [rfeng] The OutParam object will be destructed. We need to create a new copy. // [bjouhier] new fails with weird error message - fix this later if we really need to copy (do we?) OutParam* p = op; //new OutParam(*op); value->type = VALUE_TYPE_OUTPUT; value->value = p; baton->values.push_back(value); output_t* output = new output_t(); output->rows = NULL; output->type = p->type(); output->index = i + 1; baton->outputs->push_back(output); } // unhandled type else { //XXX leaks new value on error std::ostringstream message; message << "CopyValuesToBaton: Unhandled value type: " << (val->IsUndefined() ? "undefined" : "unknown"); baton->error = new std::string(message.str()); return; } } } void ExecuteBaton::GetVectorParam(ExecuteBaton* baton, arrayParam_t* arrParam, Local<Array> arr) { // In case the array is empty just initialize the fields as we would need something in Connection::SetValuesOnStatement if (arr->Length() < 1) { arrParam->value = new int[0]; arrParam->collectionLength = 0; arrParam->elementsSize = 0; arrParam->elementLength = new ub2[0]; arrParam->elementsType = oracle::occi::OCCIINT; return; } // Next we create the array buffer that will be used later as the value for the param (in Connection::SetValuesOnStatement) // The array type will be derived from the type of the first element. Local<Value> val = arr->Get(0); // String array if (val->IsString()) { arrParam->elementsType = oracle::occi::OCCI_SQLT_STR; // Find the longest string, this is necessary in order to create a buffer later. int longestString = 0; for(unsigned int i = 0; i < arr->Length(); i++) { Local<Value> currVal = arr->Get(i); if (currVal->ToString()->Utf8Length() > longestString) longestString = currVal->ToString()->Utf8Length(); } // Add 1 for '\0' ++longestString; // Create a long char* that will hold the entire array, it is important to create a FIXED SIZE array, // meaning all strings have the same allocated length. char* strArr = new char[arr->Length() * longestString]; arrParam->elementLength = new ub2[arr->Length()]; // loop thru the arr and copy the strings into the strArr int bytesWritten = 0; for(unsigned int i = 0; i < arr->Length(); i++) { Local<Value> currVal = arr->Get(i); if(!currVal->IsString()) { std::ostringstream message; message << "Input array has object with invalid type at index " << i << ", all object must be of type 'string' which is the type of the first element"; baton->error = new std::string(message.str()); return; } String::Utf8Value utfStr(currVal); // Copy this string onto the strArr (we put \0 in the beginning as this is what strcat expects). strArr[bytesWritten] = '\0'; strncat(strArr + bytesWritten, *utfStr, longestString); bytesWritten += longestString; // Set the length of this element, add +1 for the '\0' arrParam->elementLength[i] = utfStr.length() + 1; } arrParam->value = strArr; arrParam->collectionLength = arr->Length(); arrParam->elementsSize = longestString; } // Integer array. else if (val->IsNumber()) { arrParam->elementsType = oracle::occi::OCCI_SQLT_NUM; // Allocate memory for the numbers array, Number in Oracle is 21 bytes unsigned char* numArr = new unsigned char[arr->Length() * 21]; arrParam->elementLength = new ub2[arr->Length()]; for(unsigned int i = 0; i < arr->Length(); i++) { Local<Value> currVal = arr->Get(i); if(!currVal->IsNumber()) { std::ostringstream message; message << "Input array has object with invalid type at index " << i << ", all object must be of type 'number' which is the type of the first element"; baton->error = new std::string(message.str()); return; } // JS numbers can exceed oracle numbers, make sure this is not the case. double d = currVal->ToNumber()->Value(); if (d > 9.99999999999999999999999999999999999999*std::pow(10, 125) || d < -9.99999999999999999999999999999999999999*std::pow(10, 125)) { std::ostringstream message; message << "Input array has number that is out of the range of Oracle numbers, check the number at index " << i; baton->error = new std::string(message.str()); return; } // Convert the JS number into Oracle Number and get its bytes representation oracle::occi::Number n = d; oracle::occi::Bytes b = n.toBytes(); arrParam->elementLength[i] = b.length (); b.getBytes(&numArr[i*21], b.length()); } arrParam->value = numArr; arrParam->collectionLength = arr->Length(); arrParam->elementsSize = 21; } // Unsupported type else { baton->error = new std::string("The type of the first element in the input array is not supported"); } }<commit_msg>[*] Fix compilation issues on Linux<commit_after> #include "executeBaton.h" #include "connection.h" #include "outParam.h" #include <iostream> #include <string.h> #include <cmath> using namespace std; ExecuteBaton::ExecuteBaton(Connection* connection, const char* sql, v8::Local<v8::Array>* values, v8::Handle<v8::Function>* callback) { this->connection = connection; this->sql = sql; if(callback!=NULL) { uni::Reset(this->callback, *callback); } this->outputs = new std::vector<output_t*>(); this->error = NULL; if (values) CopyValuesToBaton(this, values); this->rows = NULL; } ExecuteBaton::~ExecuteBaton() { callback.Dispose(); for (std::vector<column_t*>::iterator iterator = columns.begin(), end = columns.end(); iterator != end; ++iterator) { column_t* col = *iterator; delete col; } ResetValues(); ResetRows(); ResetOutputs(); ResetError(); } void ExecuteBaton::ResetValues() { for (std::vector<value_t*>::iterator iterator = values.begin(), end = values.end(); iterator != end; ++iterator) { value_t* val = *iterator; switch (val->type) { case VALUE_TYPE_STRING: delete (std::string*)val->value; break; case VALUE_TYPE_NUMBER: delete (oracle::occi::Number*)val->value; break; case VALUE_TYPE_TIMESTAMP: delete (oracle::occi::Timestamp*)val->value; break; case VALUE_TYPE_ARRAY: arrayParam_t* arrParam = (arrayParam_t*)val->value; if (arrParam->value != NULL && arrParam->elementsType == oracle::occi::OCCI_SQLT_STR) delete (char*)arrParam->value; else if (arrParam->value != NULL && arrParam->elementsType == oracle::occi::OCCI_SQLT_NUM) delete (char*)arrParam->value; if (arrParam->elementLength != NULL) delete arrParam->elementLength; delete (arrayParam_t*)val->value; break; } delete val; } values.clear(); } void ExecuteBaton::ResetRows() { if (rows) { for (std::vector<row_t*>::iterator iterator = rows->begin(), end = rows->end(); iterator != end; ++iterator) { row_t* currentRow = *iterator; delete currentRow; } delete rows; rows = NULL; } } void ExecuteBaton::ResetOutputs() { if (outputs) { for (std::vector<output_t*>::iterator iterator = outputs->begin(), end = outputs->end(); iterator != end; ++iterator) { output_t* o = *iterator; delete o; } delete outputs; outputs = NULL; } } void ExecuteBaton::ResetError() { if (error) { delete error; error = NULL; } } double CallDateMethod(v8::Local<v8::Date> date, const char* methodName) { Handle<Value> args[1]; // should be zero but on windows the compiler will not allow a zero length array Local<Value> result = Local<Function>::Cast(date->Get(String::New(methodName)))->Call(date, 0, args); return Local<Number>::Cast(result)->Value(); } oracle::occi::Timestamp* V8DateToOcciDate(oracle::occi::Environment* env, v8::Local<v8::Date> val) { int year = CallDateMethod(val, "getUTCFullYear"); int month = CallDateMethod(val, "getUTCMonth") + 1; int day = CallDateMethod(val, "getUTCDate"); int hours = CallDateMethod(val, "getUTCHours"); int minutes = CallDateMethod(val, "getUTCMinutes"); int seconds = CallDateMethod(val, "getUTCSeconds"); int fs = CallDateMethod(val, "getUTCMilliseconds") * 1000000; // occi::Timestamp() wants nanoseconds oracle::occi::Timestamp* d = new oracle::occi::Timestamp(env, year, month, day, hours, minutes, seconds, fs); return d; } void ExecuteBaton::CopyValuesToBaton(ExecuteBaton* baton, v8::Local<v8::Array>* values) { //XXX cache Length() for(uint32_t i=0; i<(*values)->Length(); i++) { v8::Local<v8::Value> val = (*values)->Get(i); value_t *value = new value_t(); // null if(val->IsNull()) { value->type = VALUE_TYPE_NULL; value->value = NULL; baton->values.push_back(value); } // string else if(val->IsString()) { v8::String::Utf8Value utf8Value(val); value->type = VALUE_TYPE_STRING; value->value = new std::string(*utf8Value); baton->values.push_back(value); } // date else if(val->IsDate()) { value->type = VALUE_TYPE_TIMESTAMP; value->value = V8DateToOcciDate(baton->connection->getEnvironment(), uni::DateCast(val)); baton->values.push_back(value); } // number else if(val->IsNumber()) { value->type = VALUE_TYPE_NUMBER; double d = v8::Number::Cast(*val)->Value(); value->value = new oracle::occi::Number(d); // XXX not deleted in dtor baton->values.push_back(value); } // array else if (val->IsArray()) { value->type = VALUE_TYPE_ARRAY; Local<Array> arr = Local<Array>::Cast(val); value->value = new arrayParam_t(); GetVectorParam(baton, (arrayParam_t*)value->value, arr); baton->values.push_back(value); } // output else if(val->IsObject() && val->ToObject()->FindInstanceInPrototypeChain(uni::Deref(OutParam::constructorTemplate)) != v8::Null()) { OutParam* op = node::ObjectWrap::Unwrap<OutParam>(val->ToObject()); // [rfeng] The OutParam object will be destructed. We need to create a new copy. // [bjouhier] new fails with weird error message - fix this later if we really need to copy (do we?) OutParam* p = op; //new OutParam(*op); value->type = VALUE_TYPE_OUTPUT; value->value = p; baton->values.push_back(value); output_t* output = new output_t(); output->rows = NULL; output->type = p->type(); output->index = i + 1; baton->outputs->push_back(output); } // unhandled type else { //XXX leaks new value on error std::ostringstream message; message << "CopyValuesToBaton: Unhandled value type: " << (val->IsUndefined() ? "undefined" : "unknown"); baton->error = new std::string(message.str()); return; } } } void ExecuteBaton::GetVectorParam(ExecuteBaton* baton, arrayParam_t* arrParam, Local<Array> arr) { // In case the array is empty just initialize the fields as we would need something in Connection::SetValuesOnStatement if (arr->Length() < 1) { arrParam->value = new int[0]; arrParam->collectionLength = 0; arrParam->elementsSize = 0; arrParam->elementLength = new ub2[0]; arrParam->elementsType = oracle::occi::OCCIINT; return; } // Next we create the array buffer that will be used later as the value for the param (in Connection::SetValuesOnStatement) // The array type will be derived from the type of the first element. Local<Value> val = arr->Get(0); // String array if (val->IsString()) { arrParam->elementsType = oracle::occi::OCCI_SQLT_STR; // Find the longest string, this is necessary in order to create a buffer later. int longestString = 0; for(unsigned int i = 0; i < arr->Length(); i++) { Local<Value> currVal = arr->Get(i); if (currVal->ToString()->Utf8Length() > longestString) longestString = currVal->ToString()->Utf8Length(); } // Add 1 for '\0' ++longestString; // Create a long char* that will hold the entire array, it is important to create a FIXED SIZE array, // meaning all strings have the same allocated length. char* strArr = new char[arr->Length() * longestString]; arrParam->elementLength = new ub2[arr->Length()]; // loop thru the arr and copy the strings into the strArr int bytesWritten = 0; for(unsigned int i = 0; i < arr->Length(); i++) { Local<Value> currVal = arr->Get(i); if(!currVal->IsString()) { std::ostringstream message; message << "Input array has object with invalid type at index " << i << ", all object must be of type 'string' which is the type of the first element"; baton->error = new std::string(message.str()); return; } String::Utf8Value utfStr(currVal); // Copy this string onto the strArr (we put \0 in the beginning as this is what strcat expects). strArr[bytesWritten] = '\0'; strncat(strArr + bytesWritten, *utfStr, longestString); bytesWritten += longestString; // Set the length of this element, add +1 for the '\0' arrParam->elementLength[i] = utfStr.length() + 1; } arrParam->value = strArr; arrParam->collectionLength = arr->Length(); arrParam->elementsSize = longestString; } // Integer array. else if (val->IsNumber()) { arrParam->elementsType = oracle::occi::OCCI_SQLT_NUM; // Allocate memory for the numbers array, Number in Oracle is 21 bytes unsigned char* numArr = new unsigned char[arr->Length() * 21]; arrParam->elementLength = new ub2[arr->Length()]; for(unsigned int i = 0; i < arr->Length(); i++) { Local<Value> currVal = arr->Get(i); if(!currVal->IsNumber()) { std::ostringstream message; message << "Input array has object with invalid type at index " << i << ", all object must be of type 'number' which is the type of the first element"; baton->error = new std::string(message.str()); return; } // JS numbers can exceed oracle numbers, make sure this is not the case. double d = currVal->ToNumber()->Value(); if (d > 9.99999999999999999999999999999999999999*std::pow(10, 125) || d < -9.99999999999999999999999999999999999999*std::pow(10, 125)) { std::ostringstream message; message << "Input array has number that is out of the range of Oracle numbers, check the number at index " << i; baton->error = new std::string(message.str()); return; } // Convert the JS number into Oracle Number and get its bytes representation oracle::occi::Number n = d; oracle::occi::Bytes b = n.toBytes(); arrParam->elementLength[i] = b.length (); b.getBytes(&numArr[i*21], b.length()); } arrParam->value = numArr; arrParam->collectionLength = arr->Length(); arrParam->elementsSize = 21; } // Unsupported type else { baton->error = new std::string("The type of the first element in the input array is not supported"); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: OglrLgt.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include <math.h> #include "OglrRen.hh" #include "OglrLgt.hh" // Description: // Implement base class method. void vtkOglrLight::Render(vtkLight *lgt, vtkRenderer *ren,int light_index) { this->Render(lgt, (vtkOglrRenderer *)ren,light_index); } // Description: // Actual light render method. void vtkOglrLight::Render(vtkLight *lgt, vtkOglrRenderer *ren,int light_index) { float dx, dy, dz; float color[4]; float *Color, *Position, *FocalPoint; float Intensity; float Info[4]; // get required info from light Intensity = lgt->GetIntensity(); Color = lgt->GetColor(); color[0] = Intensity * Color[0]; color[1] = Intensity * Color[1]; color[2] = Intensity * Color[2]; color[3] = 1.0; FocalPoint = lgt->GetFocalPoint(); Position = lgt->GetPosition(); dx = FocalPoint[0] - Position[0]; dy = FocalPoint[1] - Position[1]; dz = FocalPoint[2] - Position[2]; glLightfv( light_index, GL_DIFFUSE, color); glLightfv( light_index, GL_SPECULAR, color); if( ren->GetBackLight()) { glLightfv( light_index+1, GL_DIFFUSE, color); glLightfv( light_index+1, GL_SPECULAR, color); } // define the light source if (!lgt->GetPositional()) { Info[0] = -dx; Info[1] = -dy; Info[2] = -dz; Info[3] = 0.0; glLightfv( light_index, GL_POSITION, Info ); // define another mirror light if backlit is on if (ren->GetBackLight()) { Info[0] = dx; Info[1] = dy; Info[2] = dz; Info[3] = 0.0; glLightfv( light_index + 1, GL_POSITION, Info ); } } else { Info[0] = Position[0]; Info[1] = Position[1]; Info[2] = Position[2]; Info[3] = 1.0; glLightfv( light_index, GL_POSITION, Info ); Info[0] = dx; Info[1] = dy; Info[2] = dz; glLightfv( light_index, GL_SPOT_DIRECTION, Info ); glLightf( light_index, GL_SPOT_EXPONENT, lgt->GetExponent()); glLightf( light_index, GL_SPOT_CUTOFF, lgt->GetConeAngle()); float *AttenuationValues = lgt->GetAttenuationValues(); glLightf( light_index, GL_CONSTANT_ATTENUATION, AttenuationValues[0]); glLightf( light_index, GL_LINEAR_ATTENUATION, AttenuationValues[1]); glLightf( light_index, GL_QUADRATIC_ATTENUATION, AttenuationValues[2]); } } <commit_msg>fixed some warnings<commit_after>/*========================================================================= Program: Visualization Toolkit Module: OglrLgt.cc Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-1995 Ken Martin, Will Schroeder, Bill Lorensen. This software is copyrighted by Ken Martin, Will Schroeder and Bill Lorensen. The following terms apply to all files associated with the software unless explicitly disclaimed in individual files. This copyright specifically does not apply to the related textbook "The Visualization Toolkit" ISBN 013199837-4 published by Prentice Hall which is covered by its own copyright. The authors hereby grant permission to use, copy, and distribute this software and its documentation for any purpose, provided that existing copyright notices are retained in all copies and that this notice is included verbatim in any distributions. Additionally, the authors grant permission to modify this software and its documentation for any purpose, provided that such modifications are not distributed without the explicit consent of the authors and that existing copyright notices are retained in all copies. Some of the algorithms implemented by this software are patented, observe all applicable patent law. IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. =========================================================================*/ #include <math.h> #include "OglrRen.hh" #include "OglrLgt.hh" // Description: // Implement base class method. void vtkOglrLight::Render(vtkLight *lgt, vtkRenderer *ren,int light_index) { this->Render(lgt, (vtkOglrRenderer *)ren,light_index); } // Description: // Actual light render method. void vtkOglrLight::Render(vtkLight *lgt, vtkOglrRenderer *ren,int light_index) { float dx, dy, dz; float color[4]; float *Color, *Position, *FocalPoint; float Intensity; float Info[4]; // get required info from light Intensity = lgt->GetIntensity(); Color = lgt->GetColor(); color[0] = Intensity * Color[0]; color[1] = Intensity * Color[1]; color[2] = Intensity * Color[2]; color[3] = 1.0; FocalPoint = lgt->GetFocalPoint(); Position = lgt->GetPosition(); dx = FocalPoint[0] - Position[0]; dy = FocalPoint[1] - Position[1]; dz = FocalPoint[2] - Position[2]; glLightfv((enum GLenum)light_index, GL_DIFFUSE, color); glLightfv((enum GLenum)light_index, GL_SPECULAR, color); if( ren->GetBackLight()) { glLightfv((enum GLenum)(light_index+1), GL_DIFFUSE, color); glLightfv((enum GLenum)(light_index+1), GL_SPECULAR, color); } // define the light source if (!lgt->GetPositional()) { Info[0] = -dx; Info[1] = -dy; Info[2] = -dz; Info[3] = 0.0; glLightfv((enum GLenum)light_index, GL_POSITION, Info ); // define another mirror light if backlit is on if (ren->GetBackLight()) { Info[0] = dx; Info[1] = dy; Info[2] = dz; Info[3] = 0.0; glLightfv((enum GLenum)(light_index + 1), GL_POSITION, Info ); } } else { Info[0] = Position[0]; Info[1] = Position[1]; Info[2] = Position[2]; Info[3] = 1.0; glLightfv((enum GLenum)light_index, GL_POSITION, Info ); Info[0] = dx; Info[1] = dy; Info[2] = dz; glLightfv((enum GLenum)light_index, GL_SPOT_DIRECTION, Info ); glLightf((enum GLenum)light_index, GL_SPOT_EXPONENT, lgt->GetExponent()); glLightf((enum GLenum)light_index, GL_SPOT_CUTOFF, lgt->GetConeAngle()); float *AttenuationValues = lgt->GetAttenuationValues(); glLightf((enum GLenum)light_index, GL_CONSTANT_ATTENUATION, AttenuationValues[0]); glLightf((enum GLenum)light_index, GL_LINEAR_ATTENUATION, AttenuationValues[1]); glLightf((enum GLenum)light_index, GL_QUADRATIC_ATTENUATION, AttenuationValues[2]); } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include <cctype> #include <list> #include "Types.hpp" #include "Utils.hpp" #include "Parser.hpp" #include "Operators.hpp" #include "Lexer.hpp" #include "Branches.hpp" using std::string; using std::ios_base; using std::list; using namespace eddic; //TODO Review this method ParseNode* Parser::parseInstruction() { if (lexer.isIf()) { return parseIf(); } if (!lexer.isWord()) { throw CompilerException("An instruction can only start with a call or an assignation"); } string word = lexer.getCurrentToken(); if (!lexer.next()) { throw CompilerException("Incomplete instruction"); } if (lexer.isLeftParenth()) { //is a call return parseCall(word); } else if (lexer.isWord()) { //is a declaration return parseDeclaration(word); } else if (lexer.isAssign()) { //is an assign return parseAssignment(word); } else if (lexer.isSwap()) { return parseSwap(word); } else { throw CompilerException("Not an instruction"); } } Program* Parser::parse() { Program* program = new Program(); while (lexer.next()) { program->addLast(parseInstruction()); } return program; } inline static void assertNextIsRightParenth(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isRightParenth()) { throw CompilerException(message); } } inline static void assertNextIsLeftParenth(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isLeftParenth()) { throw CompilerException(message); } } inline static void assertNextIsRightBrace(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isRightBrace()) { throw CompilerException(message); } } inline static void assertNextIsLeftBrace(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isLeftBrace()) { throw CompilerException(message); } } inline static void assertNextIsStop(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isStop()) { throw CompilerException(message); } } ParseNode* Parser::parseCall(const string& call) { if (call != "Print" && call != "Println") { throw CompilerException("The call \"" + call + "\" does not exist"); } Value* value = parseValue(); assertNextIsRightParenth(lexer, "The call must be closed with a right parenth"); assertNextIsStop(lexer, "Every instruction must be closed by a semicolon"); if (call == "Print") { return new Print(value); } else { return new Println(value); } } ParseNode* Parser::parseDeclaration(const string& typeName) { if (typeName != "int" && typeName != "string") { throw CompilerException("Invalid type"); } Type type; if (typeName == "int") { type = INT; } else { type = STRING; } string variable = lexer.getCurrentToken(); if (!lexer.next() || !lexer.isAssign()) { throw CompilerException("A variable declaration must followed by '='"); } Value* value = parseValue(); assertNextIsStop(lexer, "Every instruction must be closed by a semicolon"); return new Declaration(type, variable, value); } ParseNode* Parser::parseAssignment(const string& variable) { Value* value = parseValue(); assertNextIsStop(lexer, "Every instruction must be closed by a semicolon"); return new Assignment(variable, value); } ParseNode* Parser::parseSwap(const string& lhs) { if (!lexer.next() || !lexer.isWord()) { throw CompilerException("Can only swap two variables"); } string rhs = lexer.getCurrentToken(); assertNextIsStop(lexer, "Every instruction must be closed by a semicolon"); return new Swap(lhs, rhs); } ParseNode* Parser::parseIf() { assertNextIsLeftParenth(lexer, "An if instruction must be followed by a condition surrounded by parenth"); Condition* condition = parseCondition(); assertNextIsRightParenth(lexer, "The condition of the if must be closed by a right parenth"); assertNextIsLeftBrace(lexer, "Waiting for a left brace"); If* block = new If(condition); lexer.next(); while (!lexer.isRightBrace()) { block->addLast(parseInstruction()); lexer.next(); } if (!lexer.isRightBrace()) { throw CompilerException("If body must be closed with right brace"); } while (true) { if (lexer.next()) { if (lexer.isElse()) { lexer.next(); if (lexer.isIf()) { block->addElseIf(parseElseIf()); } else { lexer.pushBack(); block->setElse(parseElse()); break; } } else { lexer.pushBack(); break; } } else { break; } } return block; } ElseIf* Parser::parseElseIf() { assertNextIsLeftParenth(lexer, "An else if instruction must be followed by a condition surrounded by parenth"); Condition* condition = parseCondition(); assertNextIsRightParenth(lexer, "The condition of the else if must be closed by a right parenth"); assertNextIsLeftBrace(lexer, "Waiting for a left brace"); ElseIf* block = new ElseIf(condition); lexer.next(); while (!lexer.isRightBrace()) { block->addLast(parseInstruction()); lexer.next(); } if (!lexer.isRightBrace()) { throw CompilerException("Else ff body must be closed with right brace"); } return block; } Else* Parser::parseElse() { Else* block = new Else(); assertNextIsLeftBrace(lexer, "else statement must be followed by left brace"); while (lexer.next() && !lexer.isRightBrace()) { block->addLast(parseInstruction()); } if (!lexer.isRightBrace()) { throw CompilerException("else body must be closed with right brace"); } return block; } enum Operator { ADD, MUL, SUB, DIV, MOD, ERROR }; class Part { public: virtual bool isResolved() = 0; virtual Operator getOperator() { return ERROR; } virtual Value* getValue() { return NULL; } }; class Resolved : public Part { public: Resolved(Value* v) : value(v) {} bool isResolved() { return true; } Value* getValue() { return value; } private: Value* value; }; class Unresolved : public Part { public: Unresolved(Operator o) : op(o) {} bool isResolved() { return false; } Operator getOperator() { return op; } private: Operator op; }; int priority(Operator op) { switch (op) { case MUL: case DIV: case MOD: return 10; case ADD: case SUB: return 0; default: return -1; //TODO should never happen } } Value* Parser::parseValue() { list<Part*> parts; while (true) { if (!lexer.next()) { throw CompilerException("Waiting for a value"); } Value* node = NULL; if (lexer.isLitteral()) { string litteral = lexer.getCurrentToken(); node = new Litteral(litteral); } else if (lexer.isWord()) { string variableRight = lexer.getCurrentToken(); node = new VariableValue(variableRight); } else if (lexer.isInteger()) { string integer = lexer.getCurrentToken(); int value = toNumber<int>(integer); node = new Integer(value); } else { throw CompilerException("Invalid value"); } parts.push_back(new Resolved(node)); if (!lexer.next()) { break; } if (lexer.isAddition()) { parts.push_back(new Unresolved(ADD)); } else if (lexer.isSubtraction()) { parts.push_back(new Unresolved(SUB)); } else if (lexer.isMultiplication()) { parts.push_back(new Unresolved(MUL)); } else if (lexer.isDivision()) { parts.push_back(new Unresolved(DIV)); } else if (lexer.isModulo()) { parts.push_back(new Unresolved(MOD)); } else { lexer.pushBack(); break; } } while (parts.size() > 1) { int maxPriority = -1; list<Part*>::iterator it, end, max; for (it = parts.begin(), end = parts.end(); it != end; ++it) { Part* part = *it; if (!part->isResolved()) { if (priority(part->getOperator()) > maxPriority) { maxPriority = priority(part->getOperator()); max = it; } } } list<Part*>::iterator first = max; --first; Part* left = *first; Part* center = *max; ++max; Part* right = *max; Value* lhs = left->getValue(); Operator op = center->getOperator(); Value* rhs = right->getValue(); Value* value = NULL; if (op == ADD) { value = new Addition(lhs, rhs); } else if (op == SUB) { value = new Subtraction(lhs, rhs); } else if (op == MUL) { value = new Multiplication(lhs, rhs); } else if (op == DIV) { value = new Division(lhs, rhs); } else if (op == MOD) { value = new Modulo(lhs, rhs); } parts.erase(first, ++max); parts.insert(max, new Resolved(value)); } Value* value = (*parts.begin())->getValue(); parts.clear(); return value; } Condition* Parser::parseCondition() { lexer.next(); if (lexer.isTrue()) { return new Condition(TRUE_VALUE); } else if (lexer.isFalse()) { return new Condition(FALSE_VALUE); } else { lexer.pushBack(); } Value* lhs = parseValue(); if (!lexer.next()) { throw CompilerException("waiting for a boolean operator"); } BooleanCondition operation; if (lexer.isGreater()) { operation = GREATER_OPERATOR; } else if (lexer.isLess()) { operation = LESS_OPERATOR; } else if (lexer.isEquals()) { operation = EQUALS_OPERATOR; } else if (lexer.isNotEquals()) { operation = NOT_EQUALS_OPERATOR; } else if (lexer.isGreaterOrEquals()) { operation = GREATER_EQUALS_OPERATOR; } else if (lexer.isLessOrEquals()) { operation = LESS_EQUALS_OPERATOR; } else { throw CompilerException("waiting for a boolean operator"); } Value* rhs = parseValue(); return new Condition(operation, lhs, rhs); } <commit_msg>Make constructors with one argument explicit<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <iostream> #include <cctype> #include <list> #include "Types.hpp" #include "Utils.hpp" #include "Parser.hpp" #include "Operators.hpp" #include "Lexer.hpp" #include "Branches.hpp" using std::string; using std::ios_base; using std::list; using namespace eddic; //TODO Review this method ParseNode* Parser::parseInstruction() { if (lexer.isIf()) { return parseIf(); } if (!lexer.isWord()) { throw CompilerException("An instruction can only start with a call or an assignation"); } string word = lexer.getCurrentToken(); if (!lexer.next()) { throw CompilerException("Incomplete instruction"); } if (lexer.isLeftParenth()) { //is a call return parseCall(word); } else if (lexer.isWord()) { //is a declaration return parseDeclaration(word); } else if (lexer.isAssign()) { //is an assign return parseAssignment(word); } else if (lexer.isSwap()) { return parseSwap(word); } else { throw CompilerException("Not an instruction"); } } Program* Parser::parse() { Program* program = new Program(); while (lexer.next()) { program->addLast(parseInstruction()); } return program; } inline static void assertNextIsRightParenth(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isRightParenth()) { throw CompilerException(message); } } inline static void assertNextIsLeftParenth(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isLeftParenth()) { throw CompilerException(message); } } inline static void assertNextIsRightBrace(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isRightBrace()) { throw CompilerException(message); } } inline static void assertNextIsLeftBrace(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isLeftBrace()) { throw CompilerException(message); } } inline static void assertNextIsStop(Lexer& lexer, const string& message) { if (!lexer.next() || !lexer.isStop()) { throw CompilerException(message); } } ParseNode* Parser::parseCall(const string& call) { if (call != "Print" && call != "Println") { throw CompilerException("The call \"" + call + "\" does not exist"); } Value* value = parseValue(); assertNextIsRightParenth(lexer, "The call must be closed with a right parenth"); assertNextIsStop(lexer, "Every instruction must be closed by a semicolon"); if (call == "Print") { return new Print(value); } else { return new Println(value); } } ParseNode* Parser::parseDeclaration(const string& typeName) { if (typeName != "int" && typeName != "string") { throw CompilerException("Invalid type"); } Type type; if (typeName == "int") { type = INT; } else { type = STRING; } string variable = lexer.getCurrentToken(); if (!lexer.next() || !lexer.isAssign()) { throw CompilerException("A variable declaration must followed by '='"); } Value* value = parseValue(); assertNextIsStop(lexer, "Every instruction must be closed by a semicolon"); return new Declaration(type, variable, value); } ParseNode* Parser::parseAssignment(const string& variable) { Value* value = parseValue(); assertNextIsStop(lexer, "Every instruction must be closed by a semicolon"); return new Assignment(variable, value); } ParseNode* Parser::parseSwap(const string& lhs) { if (!lexer.next() || !lexer.isWord()) { throw CompilerException("Can only swap two variables"); } string rhs = lexer.getCurrentToken(); assertNextIsStop(lexer, "Every instruction must be closed by a semicolon"); return new Swap(lhs, rhs); } ParseNode* Parser::parseIf() { assertNextIsLeftParenth(lexer, "An if instruction must be followed by a condition surrounded by parenth"); Condition* condition = parseCondition(); assertNextIsRightParenth(lexer, "The condition of the if must be closed by a right parenth"); assertNextIsLeftBrace(lexer, "Waiting for a left brace"); If* block = new If(condition); lexer.next(); while (!lexer.isRightBrace()) { block->addLast(parseInstruction()); lexer.next(); } if (!lexer.isRightBrace()) { throw CompilerException("If body must be closed with right brace"); } while (true) { if (lexer.next()) { if (lexer.isElse()) { lexer.next(); if (lexer.isIf()) { block->addElseIf(parseElseIf()); } else { lexer.pushBack(); block->setElse(parseElse()); break; } } else { lexer.pushBack(); break; } } else { break; } } return block; } ElseIf* Parser::parseElseIf() { assertNextIsLeftParenth(lexer, "An else if instruction must be followed by a condition surrounded by parenth"); Condition* condition = parseCondition(); assertNextIsRightParenth(lexer, "The condition of the else if must be closed by a right parenth"); assertNextIsLeftBrace(lexer, "Waiting for a left brace"); ElseIf* block = new ElseIf(condition); lexer.next(); while (!lexer.isRightBrace()) { block->addLast(parseInstruction()); lexer.next(); } if (!lexer.isRightBrace()) { throw CompilerException("Else ff body must be closed with right brace"); } return block; } Else* Parser::parseElse() { Else* block = new Else(); assertNextIsLeftBrace(lexer, "else statement must be followed by left brace"); while (lexer.next() && !lexer.isRightBrace()) { block->addLast(parseInstruction()); } if (!lexer.isRightBrace()) { throw CompilerException("else body must be closed with right brace"); } return block; } enum Operator { ADD, MUL, SUB, DIV, MOD, ERROR }; class Part { public: virtual bool isResolved() = 0; virtual Operator getOperator() { return ERROR; } virtual Value* getValue() { return NULL; } }; class Resolved : public Part { public: explicit Resolved(Value* v) : value(v) {} bool isResolved() { return true; } Value* getValue() { return value; } private: Value* value; }; class Unresolved : public Part { public: explicit Unresolved(Operator o) : op(o) {} bool isResolved() { return false; } Operator getOperator() { return op; } private: Operator op; }; int priority(Operator op) { switch (op) { case MUL: case DIV: case MOD: return 10; case ADD: case SUB: return 0; default: return -1; //TODO should never happen } } Value* Parser::parseValue() { list<Part*> parts; while (true) { if (!lexer.next()) { throw CompilerException("Waiting for a value"); } Value* node = NULL; if (lexer.isLitteral()) { string litteral = lexer.getCurrentToken(); node = new Litteral(litteral); } else if (lexer.isWord()) { string variableRight = lexer.getCurrentToken(); node = new VariableValue(variableRight); } else if (lexer.isInteger()) { string integer = lexer.getCurrentToken(); int value = toNumber<int>(integer); node = new Integer(value); } else { throw CompilerException("Invalid value"); } parts.push_back(new Resolved(node)); if (!lexer.next()) { break; } if (lexer.isAddition()) { parts.push_back(new Unresolved(ADD)); } else if (lexer.isSubtraction()) { parts.push_back(new Unresolved(SUB)); } else if (lexer.isMultiplication()) { parts.push_back(new Unresolved(MUL)); } else if (lexer.isDivision()) { parts.push_back(new Unresolved(DIV)); } else if (lexer.isModulo()) { parts.push_back(new Unresolved(MOD)); } else { lexer.pushBack(); break; } } while (parts.size() > 1) { int maxPriority = -1; list<Part*>::iterator it, end, max; for (it = parts.begin(), end = parts.end(); it != end; ++it) { Part* part = *it; if (!part->isResolved()) { if (priority(part->getOperator()) > maxPriority) { maxPriority = priority(part->getOperator()); max = it; } } } list<Part*>::iterator first = max; --first; Part* left = *first; Part* center = *max; ++max; Part* right = *max; Value* lhs = left->getValue(); Operator op = center->getOperator(); Value* rhs = right->getValue(); Value* value = NULL; if (op == ADD) { value = new Addition(lhs, rhs); } else if (op == SUB) { value = new Subtraction(lhs, rhs); } else if (op == MUL) { value = new Multiplication(lhs, rhs); } else if (op == DIV) { value = new Division(lhs, rhs); } else if (op == MOD) { value = new Modulo(lhs, rhs); } parts.erase(first, ++max); parts.insert(max, new Resolved(value)); } Value* value = (*parts.begin())->getValue(); parts.clear(); return value; } Condition* Parser::parseCondition() { lexer.next(); if (lexer.isTrue()) { return new Condition(TRUE_VALUE); } else if (lexer.isFalse()) { return new Condition(FALSE_VALUE); } else { lexer.pushBack(); } Value* lhs = parseValue(); if (!lexer.next()) { throw CompilerException("waiting for a boolean operator"); } BooleanCondition operation; if (lexer.isGreater()) { operation = GREATER_OPERATOR; } else if (lexer.isLess()) { operation = LESS_OPERATOR; } else if (lexer.isEquals()) { operation = EQUALS_OPERATOR; } else if (lexer.isNotEquals()) { operation = NOT_EQUALS_OPERATOR; } else if (lexer.isGreaterOrEquals()) { operation = GREATER_EQUALS_OPERATOR; } else if (lexer.isLessOrEquals()) { operation = LESS_EQUALS_OPERATOR; } else { throw CompilerException("waiting for a boolean operator"); } Value* rhs = parseValue(); return new Condition(operation, lhs, rhs); } <|endoftext|>
<commit_before>/* * Copyright (c) 2008-2018 the MRtrix3 contributors. * * 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/ * * MRtrix3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * For more details, see http://www.mrtrix.org/ */ #include "fixel/matrix.h" #include "thread_queue.h" #include "file/ofstream.h" #include "file/path.h" #include "file/utils.h" #include "fixel/helpers.h" #include "dwi/tractography/mapping/loader.h" #include "dwi/tractography/mapping/mapper.h" #include "dwi/tractography/mapping/voxel.h" #include "dwi/tractography/streamline.h" namespace MR { namespace Fixel { namespace Matrix { void InitFixel::add (const vector<index_type>& indices) { if ((*this).empty()) { (*this).reserve (indices.size()); for (auto i : indices) (*this).emplace_back (InitElement (i)); track_count = 1; return; } ssize_t self_index = 0, in_index = 0; // For anything in indices that doesn't yet appear in *this, // add to this list; once completed, extend *this by the appropriate // amount, and insert these into the appropriate locations // Need to continue making use of the existing allocated memory // Break into two passes: // - On first pass, increment those elements that already exist, and count the number of // fixels that are not yet part of the set (but don't store them) // - Extend the length of the vector by as much as is required to fit the new elements // - On second pass, from back to front, move elements from previous back of vector to new back, // inserting new elements at appropriate locations to retain sortedness of list const ssize_t old_size = (*this).size(); const ssize_t in_count = indices.size(); size_t intersection = 0; while (self_index < old_size && in_index < in_count) { if ((*this)[self_index].index() == indices[in_index]) { ++(*this)[self_index]; ++self_index; ++in_index; ++intersection; } else if ((*this)[self_index].index() > indices[in_index]) { ++in_index; } else { ++self_index; } } self_index = old_size - 1; in_index = indices.size() - 1; // It's possible that a resize() call may always result in requesting // a re-assignment of memory that exactly matches the size, which may in turn // lead to memory bloat due to inability to return the old memory // If this occurs, iteratively calling push_back() may instead engage the // memory-reservation-doubling behaviour while ((*this).size() < old_size + indices.size() - intersection) (*this).push_back (InitElement()); ssize_t out_index = (*this).size() - 1; // For each output vector location, need to determine whether it should come from copying an existing entry, // or creating a new one while (out_index > self_index && self_index >= 0 && in_index >= 0) { if ((*this)[self_index].index() == indices[in_index]) { (*this)[out_index] = (*this)[self_index]; --self_index; --in_index; } else if ((*this)[self_index].index() > indices[in_index]) { (*this)[out_index] = (*this)[self_index]; --self_index; } else { (*this)[out_index] = InitElement (indices[in_index]); --in_index; } --out_index; } if (self_index < 0) { while (in_index >= 0 && out_index >= 0) (*this)[out_index--] = InitElement (indices[in_index--]); } // Track total number of streamlines intersecting this fixel, // independently of the extent of fixel-fixel connectivity ++track_count; } init_matrix_type generate ( const std::string& track_filename, Image<index_type>& index_image, Image<bool>& fixel_mask, const float angular_threshold) { class TrackProcessor { MEMALIGN(TrackProcessor) public: TrackProcessor (const DWI::Tractography::Mapping::TrackMapperBase& mapper, Image<index_type>& fixel_indexer, Image<default_type>& fixel_directions, Image<bool>& fixel_mask, const default_type angular_threshold) : mapper (mapper), fixel_indexer (fixel_indexer) , fixel_directions (fixel_directions), fixel_mask (fixel_mask), angular_threshold_dp (std::cos (angular_threshold * (Math::pi/180.0))) { } bool operator() (const DWI::Tractography::Streamline<>& tck, vector<index_type>& out) const { using direction_type = Eigen::Vector3; using SetVoxelDir = DWI::Tractography::Mapping::SetVoxelDir; SetVoxelDir in; mapper (tck, in); // For each voxel tract tangent, assign to a fixel out.clear(); out.reserve (in.size()); for (const auto& i : in) { assign_pos_of (i).to (fixel_indexer); fixel_indexer.index(3) = 0; const index_type num_fixels = fixel_indexer.value(); if (num_fixels > 0) { fixel_indexer.index(3) = 1; const index_type first_index = fixel_indexer.value(); const index_type last_index = first_index + num_fixels; // Note: Streamlines can still be assigned to a fixel that is outside the mask; // however this will not be permitted to contribute to the matrix index_type closest_fixel_index = num_fixels; default_type largest_dp = 0.0; const direction_type dir (i.get_dir().normalized()); for (index_type j = first_index; j < last_index; ++j) { fixel_directions.index (0) = j; const default_type dp = abs (dir.dot (direction_type (fixel_directions.row (1)))); if (dp > largest_dp) { largest_dp = dp; fixel_mask.index(0) = j; if (fixel_mask.value()) closest_fixel_index = j; } } if (closest_fixel_index != num_fixels && largest_dp > angular_threshold_dp) out.push_back (closest_fixel_index); } } // Fixel indices must be sorted prior to providing to InitMatrixFixel::add() std::sort (out.begin(), out.end()); return true; } private: const DWI::Tractography::Mapping::TrackMapperBase& mapper; mutable Image<index_type> fixel_indexer; mutable Image<default_type> fixel_directions; mutable Image<bool> fixel_mask; const default_type angular_threshold_dp; }; auto directions_image = Fixel::find_directions_header (Path::dirname (index_image.name())).template get_image<default_type>().with_direct_io ({+2,+1}); DWI::Tractography::Properties properties; DWI::Tractography::Reader<float> track_file (track_filename, properties); const uint32_t num_tracks = properties["count"].empty() ? 0 : to<uint32_t>(properties["count"]); DWI::Tractography::Mapping::TrackLoader loader (track_file, num_tracks, "computing fixel-fixel connectivity matrix"); DWI::Tractography::Mapping::TrackMapperBase mapper (index_image); mapper.set_upsample_ratio (DWI::Tractography::Mapping::determine_upsample_ratio (index_image, properties, 0.333f)); mapper.set_use_precise_mapping (true); TrackProcessor track_processor (mapper, index_image, directions_image, fixel_mask, angular_threshold); init_matrix_type connectivity_matrix (Fixel::get_number_of_fixels (index_image)); Thread::run_queue (loader, Thread::batch (DWI::Tractography::Streamline<float>()), track_processor, Thread::batch (vector<index_type>()), // Inline lambda function for receiving streamline fixel visitations and // updating the connectivity matrix [&] (const vector<index_type>& fixels) { try { for (auto f : fixels) connectivity_matrix[f].add (fixels); return true; } catch (...) { throw Exception ("Error assigning memory for CFE connectivity matrix"); return false; } }); return connectivity_matrix; } // TODO Could receive a map<string, string> void normalise_and_write (init_matrix_type& matrix, const connectivity_value_type threshold, const std::string& path) { if (Path::exists (path)) { if (!Path::is_dir (path)) { if (App::overwrite_files) { File::unlink (path); } else { throw Exception ("Cannot create fixel-fixel connectivity matrix \"" + path + "\": Already exists as file"); } } } else { File::mkdir (path); } Header index_header; index_header.ndim() = 4; index_header.size(0) = matrix.size(); index_header.size(1) = 1; index_header.size(2) = 1; index_header.size(3) = 2; index_header.stride(0) = 2; index_header.stride(1) = 3; index_header.stride(2) = 4; index_header.stride(3) = 1; index_header.keyval()["nfixels"] = matrix.size(); index_header.datatype() = DataType::from<uint64_t>(); Image<uint64_t> index_image = Image<uint64_t>::create (Path::join (path, "index.mif"), index_header); // Can't use function write_mrtrix_header() as the file offset of the // first entry of the "dim" field needs to be known // (and enough space needs to be left to fill in a large number upon completion) File::OFStream fixel_stream (Path::join (path, "fixels.mif")); File::OFStream value_stream (Path::join (path, "fixels.mif")); const std::string leadin = "mrtrix image\ndim: "; // Need enough space for the largest possible 64-bit unsigned integer, // plus ",1,1" for the two dummy axes const size_t dim_padding = std::log10 (std::numeric_limits<size_t>::max()) + 4; Eigen::IOFormat fmt(Eigen::FullPrecision, Eigen::DontAlignCols, ", ", "\ntransform: ", "", "", "\ntransform: ", ""); for (size_t stream_index = 0; stream_index != 2; ++stream_index) { File::OFStream& stream (stream_index ? value_stream : fixel_stream); stream << leadin; for (size_t i = 0; i != dim_padding; ++i) stream << " "; stream << "\nvox: 1,1,1\nlayout: +1,+2,+3\ndatatype: "; if (stream_index) stream << DataType::from<index_type>().specifier(); else stream << DataType::from<connectivity_value_type>().specifier(); stream << "\ntransform: "; stream << transform_type::Identity().matrix().topLeftCorner(3,4).format(fmt); stream << "\nscaling:0,1\nnfixels: " + str(matrix.size()) + "\nfile: "; int64_t offset = stream.tellp() + int64_t(18); offset += ((4 - (offset % 4)) % 4); stream << ". " << offset << "\nEND\n"; while (stream.tellp() < offset) stream << "\0"; } size_t data_count = 0; for (size_t fixel_index = 0; fixel_index != matrix.size(); ++fixel_index) { index_image.index (0) = fixel_index; // Here, the connectivity matrix needs to be modified to reflect the // fact that fixel indices in the template fixel image may not // correspond to columns in the statistical analysis index_type num_fixels = 0; const connectivity_value_type normalisation_factor = 1.0 / connectivity_value_type (matrix[fixel_index].count()); for (auto& it : matrix[fixel_index]) { const connectivity_value_type connectivity = normalisation_factor * it.value(); if (connectivity >= threshold) { const index_type i = it.index(); fixel_stream.write (reinterpret_cast<const char*>(&i), sizeof (index_type)); value_stream.write (reinterpret_cast<const char*>(&connectivity), sizeof (connectivity_value_type)); ++num_fixels; } } index_image.index (3) = 0; index_image.value() = num_fixels; index_image.index (3) = 1; index_image.value() = data_count; data_count += num_fixels; // Force deallocation of memory used for this fixel in the generated matrix InitFixel().swap (matrix[fixel_index]); } // Update headers to reflect the number of fixel-fixel connections std::string dim_string = str(data_count) + ",1,1"; while (dim_string.size() < dim_padding - 1) dim_string += " "; dim_string += "\n"; for (size_t stream_index = 0; stream_index != 2; ++stream_index) { File::OFStream& stream (stream_index ? value_stream : fixel_stream); stream.seekp (leadin.size()); stream << dim_string; } } } } } <commit_msg>fixelconnectivity: First fixes to new matrix format output<commit_after>/* * Copyright (c) 2008-2018 the MRtrix3 contributors. * * 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/ * * MRtrix3 is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * For more details, see http://www.mrtrix.org/ */ #include "fixel/matrix.h" #include "thread_queue.h" #include "file/ofstream.h" #include "file/path.h" #include "file/utils.h" #include "fixel/helpers.h" #include "dwi/tractography/mapping/loader.h" #include "dwi/tractography/mapping/mapper.h" #include "dwi/tractography/mapping/voxel.h" #include "dwi/tractography/streamline.h" namespace MR { namespace Fixel { namespace Matrix { void InitFixel::add (const vector<index_type>& indices) { if ((*this).empty()) { (*this).reserve (indices.size()); for (auto i : indices) (*this).emplace_back (InitElement (i)); track_count = 1; return; } ssize_t self_index = 0, in_index = 0; // For anything in indices that doesn't yet appear in *this, // add to this list; once completed, extend *this by the appropriate // amount, and insert these into the appropriate locations // Need to continue making use of the existing allocated memory // Break into two passes: // - On first pass, increment those elements that already exist, and count the number of // fixels that are not yet part of the set (but don't store them) // - Extend the length of the vector by as much as is required to fit the new elements // - On second pass, from back to front, move elements from previous back of vector to new back, // inserting new elements at appropriate locations to retain sortedness of list const ssize_t old_size = (*this).size(); const ssize_t in_count = indices.size(); size_t intersection = 0; while (self_index < old_size && in_index < in_count) { if ((*this)[self_index].index() == indices[in_index]) { ++(*this)[self_index]; ++self_index; ++in_index; ++intersection; } else if ((*this)[self_index].index() > indices[in_index]) { ++in_index; } else { ++self_index; } } self_index = old_size - 1; in_index = indices.size() - 1; // It's possible that a resize() call may always result in requesting // a re-assignment of memory that exactly matches the size, which may in turn // lead to memory bloat due to inability to return the old memory // If this occurs, iteratively calling push_back() may instead engage the // memory-reservation-doubling behaviour while ((*this).size() < old_size + indices.size() - intersection) (*this).push_back (InitElement()); ssize_t out_index = (*this).size() - 1; // For each output vector location, need to determine whether it should come from copying an existing entry, // or creating a new one while (out_index > self_index && self_index >= 0 && in_index >= 0) { if ((*this)[self_index].index() == indices[in_index]) { (*this)[out_index] = (*this)[self_index]; --self_index; --in_index; } else if ((*this)[self_index].index() > indices[in_index]) { (*this)[out_index] = (*this)[self_index]; --self_index; } else { (*this)[out_index] = InitElement (indices[in_index]); --in_index; } --out_index; } if (self_index < 0) { while (in_index >= 0 && out_index >= 0) (*this)[out_index--] = InitElement (indices[in_index--]); } // Track total number of streamlines intersecting this fixel, // independently of the extent of fixel-fixel connectivity ++track_count; } init_matrix_type generate ( const std::string& track_filename, Image<index_type>& index_image, Image<bool>& fixel_mask, const float angular_threshold) { class TrackProcessor { MEMALIGN(TrackProcessor) public: TrackProcessor (const DWI::Tractography::Mapping::TrackMapperBase& mapper, Image<index_type>& fixel_indexer, Image<default_type>& fixel_directions, Image<bool>& fixel_mask, const default_type angular_threshold) : mapper (mapper), fixel_indexer (fixel_indexer) , fixel_directions (fixel_directions), fixel_mask (fixel_mask), angular_threshold_dp (std::cos (angular_threshold * (Math::pi/180.0))) { } bool operator() (const DWI::Tractography::Streamline<>& tck, vector<index_type>& out) const { using direction_type = Eigen::Vector3; using SetVoxelDir = DWI::Tractography::Mapping::SetVoxelDir; SetVoxelDir in; mapper (tck, in); // For each voxel tract tangent, assign to a fixel out.clear(); out.reserve (in.size()); for (const auto& i : in) { assign_pos_of (i).to (fixel_indexer); fixel_indexer.index(3) = 0; const index_type num_fixels = fixel_indexer.value(); if (num_fixels > 0) { fixel_indexer.index(3) = 1; const index_type first_index = fixel_indexer.value(); const index_type last_index = first_index + num_fixels; // Note: Streamlines can still be assigned to a fixel that is outside the mask; // however this will not be permitted to contribute to the matrix index_type closest_fixel_index = num_fixels; default_type largest_dp = 0.0; const direction_type dir (i.get_dir().normalized()); for (index_type j = first_index; j < last_index; ++j) { fixel_directions.index (0) = j; const default_type dp = abs (dir.dot (direction_type (fixel_directions.row (1)))); if (dp > largest_dp) { largest_dp = dp; fixel_mask.index(0) = j; if (fixel_mask.value()) closest_fixel_index = j; } } if (closest_fixel_index != num_fixels && largest_dp > angular_threshold_dp) out.push_back (closest_fixel_index); } } // Fixel indices must be sorted prior to providing to InitMatrixFixel::add() std::sort (out.begin(), out.end()); return true; } private: const DWI::Tractography::Mapping::TrackMapperBase& mapper; mutable Image<index_type> fixel_indexer; mutable Image<default_type> fixel_directions; mutable Image<bool> fixel_mask; const default_type angular_threshold_dp; }; auto directions_image = Fixel::find_directions_header (Path::dirname (index_image.name())).template get_image<default_type>().with_direct_io ({+2,+1}); DWI::Tractography::Properties properties; DWI::Tractography::Reader<float> track_file (track_filename, properties); const uint32_t num_tracks = properties["count"].empty() ? 0 : to<uint32_t>(properties["count"]); DWI::Tractography::Mapping::TrackLoader loader (track_file, num_tracks, "computing fixel-fixel connectivity matrix"); DWI::Tractography::Mapping::TrackMapperBase mapper (index_image); mapper.set_upsample_ratio (DWI::Tractography::Mapping::determine_upsample_ratio (index_image, properties, 0.333f)); mapper.set_use_precise_mapping (true); TrackProcessor track_processor (mapper, index_image, directions_image, fixel_mask, angular_threshold); init_matrix_type connectivity_matrix (Fixel::get_number_of_fixels (index_image)); Thread::run_queue (loader, Thread::batch (DWI::Tractography::Streamline<float>()), track_processor, Thread::batch (vector<index_type>()), // Inline lambda function for receiving streamline fixel visitations and // updating the connectivity matrix [&] (const vector<index_type>& fixels) { try { for (auto f : fixels) connectivity_matrix[f].add (fixels); return true; } catch (...) { throw Exception ("Error assigning memory for CFE connectivity matrix"); return false; } }); return connectivity_matrix; } // TODO Could receive a map<string, string> void normalise_and_write (init_matrix_type& matrix, const connectivity_value_type threshold, const std::string& path) { if (Path::exists (path)) { if (!Path::is_dir (path)) { if (App::overwrite_files) { File::unlink (path); } else { throw Exception ("Cannot create fixel-fixel connectivity matrix \"" + path + "\": Already exists as file"); } } } else { File::mkdir (path); } Header index_header; index_header.ndim() = 4; index_header.size(0) = matrix.size(); index_header.size(1) = 1; index_header.size(2) = 1; index_header.size(3) = 2; index_header.stride(0) = 2; index_header.stride(1) = 3; index_header.stride(2) = 4; index_header.stride(3) = 1; index_header.spacing(0) = index_header.spacing(1) = index_header.spacing(2) = 1.0; index_header.transform() = transform_type::Identity(); index_header.keyval()["nfixels"] = str(matrix.size()); index_header.datatype() = DataType::from<uint64_t>(); Image<uint64_t> index_image = Image<uint64_t>::create (Path::join (path, "index.mif"), index_header); // Can't use function write_mrtrix_header() as the file offset of the // first entry of the "dim" field needs to be known // (and enough space needs to be left to fill in a large number upon completion) File::OFStream fixel_stream (Path::join (path, "fixels.mif"), std::ios_base::out | std::ios_base::in); File::OFStream value_stream (Path::join (path, "values.mif"), std::ios_base::out | std::ios_base::in); const std::string leadin = "mrtrix image\ndim: "; // Need enough space for the largest possible 64-bit unsigned integer, // plus ",1,1" for the two dummy axes const size_t dim_padding = std::log10 (std::numeric_limits<size_t>::max()) + 4; Eigen::IOFormat fmt(Eigen::FullPrecision, Eigen::DontAlignCols, ", ", "\ntransform: ", "", "", "\ntransform: ", ""); for (size_t stream_index = 0; stream_index != 2; ++stream_index) { File::OFStream& stream (stream_index ? value_stream : fixel_stream); stream << leadin; for (size_t i = 0; i != dim_padding; ++i) stream << " "; stream << "\nvox: 1,1,1\nlayout: 0,1,2\ndatatype: "; if (stream_index) stream << DataType::from<connectivity_value_type>().specifier(); else stream << DataType::from<index_type>().specifier(); stream << transform_type::Identity().matrix().topLeftCorner(3,4).format(fmt); // TODO Insert command_history string stream << "\nscaling: 0,1\nnfixels: " + str(matrix.size()) + "\nfile: "; int64_t offset = stream.tellp() + int64_t(18); offset += ((4 - (offset % 4)) % 4); stream << ". " << offset << "\nEND\n"; while (stream.tellp() < offset) stream << "\0"; } size_t data_count = 0; for (size_t fixel_index = 0; fixel_index != matrix.size(); ++fixel_index) { index_image.index (0) = fixel_index; // Here, the connectivity matrix needs to be modified to reflect the // fact that fixel indices in the template fixel image may not // correspond to columns in the statistical analysis index_type num_fixels = 0; const connectivity_value_type normalisation_factor = 1.0 / connectivity_value_type (matrix[fixel_index].count()); for (auto& it : matrix[fixel_index]) { const connectivity_value_type connectivity = normalisation_factor * it.value(); if (connectivity >= threshold) { const index_type i = it.index(); fixel_stream.write (reinterpret_cast<const char*>(&i), sizeof (index_type)); value_stream.write (reinterpret_cast<const char*>(&connectivity), sizeof (connectivity_value_type)); ++num_fixels; } } index_image.index (3) = 0; index_image.value() = uint64_t(num_fixels); index_image.index (3) = 1; index_image.value() = num_fixels ? data_count : uint64_t(0); data_count += num_fixels; // Force deallocation of memory used for this fixel in the generated matrix InitFixel().swap (matrix[fixel_index]); } // Update headers to reflect the number of fixel-fixel connections std::string dim_string = str(data_count) + ",1,1"; while (dim_string.size() < dim_padding) dim_string += " "; for (size_t stream_index = 0; stream_index != 2; ++stream_index) { File::OFStream& stream (stream_index ? value_stream : fixel_stream); stream.seekp (leadin.size()); stream << dim_string; } } } } } <|endoftext|>
<commit_before>/// @file /// @author uentity /// @date 22.11.2017 /// @brief BS tree-related functions impl /// @copyright /// 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 https://mozilla.org/MPL/2.0/ #include <bs/tree.h> #include "tree_impl.h" #include <boost/uuid/string_generator.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/algorithm/string.hpp> NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN(tree) /*----------------------------------------------------------------------------- * impl details *-----------------------------------------------------------------------------*/ // hidden namespace { static boost::uuids::string_generator uuid_from_str; } // hidden ns // public NAMESPACE_BEGIN(detail) sp_link walk_down_tree(const std::string& cur_lid, const sp_node& level) { if(cur_lid != "..") { const auto next = level->find(uuid_from_str(cur_lid)); if(next != level->end()) { return *next; } } return nullptr; } NAMESPACE_END(detail) /*----------------------------------------------------------------------------- * public API *-----------------------------------------------------------------------------*/ std::string abspath(sp_clink l, bool human_readable) { std::deque<std::string> res; while(l) { res.push_front(human_readable ? l->name() : boost::uuids::to_string(l->id())); if(const auto parent = l->owner()) { l = parent->self_link(); } } return std::string("/") + boost::join(res, "/"); } std::string convert_path(std::string src_path, const sp_clink& start, bool from_human_readable) { std::string res_path; // convert from ID-based path to human-readable const auto id2name = [&res_path](std::string part, const sp_node& level) { sp_link res; if(part != "..") { const auto next = level->find(part); if(next != level->end()) { res = *next; part = boost::uuids::to_string(res->id()); } } // append link ID to link's path if(res_path.size()) res_path += '/'; res_path += std::move(part); return res; }; // convert from name-based to ID-based path const auto name2id = [&res_path](std::string part, const sp_node& level) { sp_link res; if(part != "..") { auto next = level->find(uuid_from_str(part)); if(next != level->end()) { res = *next; part = res->name(); } } // append link ID to link's path if(res_path.size()) res_path += '/'; res_path += std::move(part); return res; }; // do conversion boost::trim(src_path); from_human_readable ? detail::deref_path(src_path, *start, name2id) : detail::deref_path(src_path, *start, id2name); // if abs path given, return abs path if(src_path[0] == '/') res_path.insert(res_path.begin(), '/'); return res_path; } sp_link search_by_path(const std::string& path, const sp_clink& start) { if(!start) return nullptr; return detail::deref_path<>(path, *start); } NAMESPACE_END(tree) NAMESPACE_END(blue_sky) <commit_msg>tree: don't insert leading slash to dangling link abspath<commit_after>/// @file /// @author uentity /// @date 22.11.2017 /// @brief BS tree-related functions impl /// @copyright /// 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 https://mozilla.org/MPL/2.0/ #include <bs/tree.h> #include "tree_impl.h" #include <boost/uuid/string_generator.hpp> #include <boost/uuid/uuid_io.hpp> #include <boost/algorithm/string.hpp> NAMESPACE_BEGIN(blue_sky) NAMESPACE_BEGIN(tree) /*----------------------------------------------------------------------------- * impl details *-----------------------------------------------------------------------------*/ // hidden namespace { static boost::uuids::string_generator uuid_from_str; } // hidden ns // public NAMESPACE_BEGIN(detail) sp_link walk_down_tree(const std::string& cur_lid, const sp_node& level) { if(cur_lid != "..") { const auto next = level->find(uuid_from_str(cur_lid)); if(next != level->end()) { return *next; } } return nullptr; } NAMESPACE_END(detail) /*----------------------------------------------------------------------------- * public API *-----------------------------------------------------------------------------*/ std::string abspath(sp_clink l, bool human_readable) { std::deque<std::string> res; while(l) { res.push_front(human_readable ? l->name() : boost::uuids::to_string(l->id())); if(const auto parent = l->owner()) { l = parent->self_link(); } else return boost::join(res, "/"); } // leadind slash is appended only if we have 'real' root node without self link return std::string("/") + boost::join(res, "/"); // another possible implementation without multiple returns // just leave it here -) //sp_node parent; //do { // if(l) // res.push_front(human_readable ? l->name() : boost::uuids::to_string(l->id())); // else { // // for root node // res.emplace_front(""); // break; // } // if((parent = l->owner())) { // l = parent->self_link(); // } //} while(parent); //return boost::join(res, "/"); } std::string convert_path(std::string src_path, const sp_clink& start, bool from_human_readable) { std::string res_path; // convert from ID-based path to human-readable const auto id2name = [&res_path](std::string part, const sp_node& level) { sp_link res; if(part != "..") { const auto next = level->find(part); if(next != level->end()) { res = *next; part = boost::uuids::to_string(res->id()); } } // append link ID to link's path if(res_path.size()) res_path += '/'; res_path += std::move(part); return res; }; // convert from name-based to ID-based path const auto name2id = [&res_path](std::string part, const sp_node& level) { sp_link res; if(part != "..") { auto next = level->find(uuid_from_str(part)); if(next != level->end()) { res = *next; part = res->name(); } } // append link ID to link's path if(res_path.size()) res_path += '/'; res_path += std::move(part); return res; }; // do conversion boost::trim(src_path); from_human_readable ? detail::deref_path(src_path, *start, name2id) : detail::deref_path(src_path, *start, id2name); // if abs path given, return abs path if(src_path[0] == '/') res_path.insert(res_path.begin(), '/'); return res_path; } sp_link search_by_path(const std::string& path, const sp_clink& start) { if(!start) return nullptr; return detail::deref_path<>(path, *start); } NAMESPACE_END(tree) NAMESPACE_END(blue_sky) <|endoftext|>
<commit_before>#include "RTimer.h" #include "RTimerEvent.h" #include "RCoreApplication.h" RTimer::RTimer() : mIsSingleShot(false) { // NOTE: Set timer run as idle task by default, but we can't set interval to // zero, otherwise the created timer will return to NULL, so we give value 1 . mHandle = xTimerCreate( "", 1, pdFALSE, // one-shot timer reinterpret_cast<void *>(0), onTimeout ); vTimerSetTimerID(mHandle, this); } RTimer::~RTimer() { xTimerDelete(mHandle, 0); } int RTimer::interval() const { return xTimerGetPeriod(mHandle) * portTICK_PERIOD_MS; } bool RTimer::isActive() const { return xTimerIsTimerActive(mHandle); } bool RTimer::isSingleShot() const { return mIsSingleShot; } void RTimer::setInterval(int msec) { xTimerChangePeriod(mHandle, msec / portTICK_PERIOD_MS, 0); // xTimerChangePeriod will cause timer start, so we need to stop it // immediately stop(); } void RTimer::setSingleShot(bool singleShot) { mIsSingleShot = singleShot; } int RTimer::timerId() const { // WARNING: We shorten handle to id value, but it may lead duplicate id values. return rShortenPtr(pvTimerGetTimerID(mHandle)); } void RTimer::start(int msec) { setInterval(msec); start(); } void RTimer::start() { stop(); xTimerStart(mHandle, 0); } void RTimer::stop() { xTimerStop(mHandle, 0); } bool RTimer::event(REvent *e) { if(e->type() == RTimerEvent::staticType()) { // FIXME: Here may be generate a potential crash auto timerEvent = static_cast<RTimerEvent *>(e); timeout.emit(); if(!mIsSingleShot) { start(); // Restart timer for next round } timerEvent->accept(); return true; } return RObject::event(e); } void RTimer::onTimeout(TimerHandle_t handle) { auto self = static_cast<RTimer *>(pvTimerGetTimerID(handle)); // NOTE: Event will be deleted in REventLoop after they handled that event. RTimerEvent *event = new RTimerEvent(self->timerId()); RCoreApplication::postEvent(self, event); } <commit_msg>Use scope pointer to keep event will be free finally even postEvent() failed<commit_after>#include "RTimer.h" #include "RTimerEvent.h" #include "RCoreApplication.h" #include "RScopedPointer.h" RTimer::RTimer() : mIsSingleShot(false) { // NOTE: Set timer run as idle task by default, but we can't set interval to // zero, otherwise the created timer will return to NULL, so we give value 1 . mHandle = xTimerCreate( "", 1, pdFALSE, // one-shot timer reinterpret_cast<void *>(0), onTimeout ); vTimerSetTimerID(mHandle, this); } RTimer::~RTimer() { xTimerDelete(mHandle, 0); } int RTimer::interval() const { return xTimerGetPeriod(mHandle) * portTICK_PERIOD_MS; } bool RTimer::isActive() const { return xTimerIsTimerActive(mHandle); } bool RTimer::isSingleShot() const { return mIsSingleShot; } void RTimer::setInterval(int msec) { xTimerChangePeriod(mHandle, msec / portTICK_PERIOD_MS, 0); // xTimerChangePeriod will cause timer start, so we need to stop it // immediately stop(); } void RTimer::setSingleShot(bool singleShot) { mIsSingleShot = singleShot; } int RTimer::timerId() const { // WARNING: We shorten handle to id value, but it may lead duplicate id values. return rShortenPtr(pvTimerGetTimerID(mHandle)); } void RTimer::start(int msec) { setInterval(msec); start(); } void RTimer::start() { stop(); xTimerStart(mHandle, 0); } void RTimer::stop() { xTimerStop(mHandle, 0); } bool RTimer::event(REvent *e) { if(e->type() == RTimerEvent::staticType()) { // FIXME: Here may be generate a potential crash auto timerEvent = static_cast<RTimerEvent *>(e); timeout.emit(); if(!mIsSingleShot) { start(); // Restart timer for next round } timerEvent->accept(); return true; } return RObject::event(e); } void RTimer::onTimeout(TimerHandle_t handle) { auto self = static_cast<RTimer *>(pvTimerGetTimerID(handle)); // NOTE: Event will be deleted in REventLoop after they handled that event. RScopedPointer<RTimerEvent> event(new RTimerEvent(self->timerId())); RCoreApplication::postEvent(self, event.take()); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/visualization/software-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 <ostream> #include "Sample.h" namespace madai { Sample ::Sample( const std::vector< double > & parameterValues, const std::vector< double > & outputValues, double LogLikelihood, const std::vector< double > logLikelihoodValueGradient, const std::vector< double > logLikelihoodErrorGradient) : m_ParameterValues( parameterValues ), m_OutputValues( outputValues ), m_LogLikelihoodValueGradient( logLikelihoodValueGradient ), m_LogLikelihoodErrorGradient( logLikelihoodErrorGradient ), m_LogLikelihood( LogLikelihood ) { } Sample ::Sample( const std::vector< double > & parameter_values, const std::vector< double > & output_values, double LogLikelihood ) : m_ParameterValues( parameter_values ), m_OutputValues( output_values ), m_LogLikelihood( LogLikelihood ) { } Sample ::Sample( const std::vector< double > & parameter_values, const std::vector< double > & output_values ) : m_ParameterValues( parameter_values ), m_OutputValues( output_values ), m_LogLikelihood( 0.0 ) { } Sample ::Sample( const std::vector< double > & parameter_values ) : m_ParameterValues( parameter_values ), m_LogLikelihood( 0.0 ) { } Sample ::Sample() : m_LogLikelihood(0.0) { } void Sample ::Reset() { m_ParameterValues.clear(); m_OutputValues.clear(); m_Comments.clear(); m_LogLikelihood= 0.0; } bool Sample ::IsValid() const { return ( m_ParameterValues.size() > 0 || m_OutputValues.size() > 0 || m_Comments.size() > 0 ); } /** Provide this operator so that we can do: void SortSamples(std::vector< Sample > & s) { std::sort(s.begin(),s.end()); } */ bool Sample ::operator<(const Sample & rhs) const { return (m_LogLikelihood < rhs.m_LogLikelihood); } bool Sample ::operator==(const Sample & rhs) const { if ( m_LogLikelihood != rhs.m_LogLikelihood ) { return false; } if ( m_ParameterValues != rhs.m_ParameterValues ) { return false; } if ( m_OutputValues != rhs.m_OutputValues ) { return false; } if ( m_Comments != rhs.m_Comments ) { return false; } return true; } std::ostream & operator<<(std::ostream & os, const Sample & sample) { os << "Sample:\n"; os << " ParameterValues: ["; for ( size_t i = 0; i < sample.m_ParameterValues.size(); ++i ) { os << sample.m_ParameterValues[i]; if ( i < sample.m_ParameterValues.size()-1) os << ", "; } os << "]\n"; os << " OutputValues: ["; for ( size_t i = 0; i < sample.m_OutputValues.size(); ++i ) { os << sample.m_OutputValues[i]; if ( i < sample.m_OutputValues.size()-1) os << ", "; } os << "]\n"; os << " dLL/dobservable: ["; for ( size_t i = 0; i < sample.m_LogLikelihoodValueGradient.size(); ++i ) { os << sample.m_LogLikelihoodValueGradient[i]; if ( i < sample.m_LogLikelihoodValueGradient.size()-1) os << ", "; } os << "]\n"; os << " sigma_observable*dLL/dsigma_observable: ["; for ( size_t i = 0; i < sample.m_LogLikelihoodErrorGradient.size(); ++i ) { os << sample.m_LogLikelihoodErrorGradient[i]; if ( i < sample.m_LogLikelihoodErrorGradient.size()-1) os << ", "; } os << "]\n"; os << " LogLikelihood: [" << sample.m_LogLikelihood << "]\n"; if ( sample.m_Comments.size() > 0 ) { for ( size_t i = 0; i < sample.m_Comments.size(); ++i ) { os << sample.m_Comments[i]; if ( i < sample.m_Comments.size()-1) os << ", "; } } return os; } } // end namespace madai <commit_msg>Equality operator in Sample now checks the gradient vectors.<commit_after>/*========================================================================= * * Copyright 2011-2013 The University of North Carolina at Chapel Hill * All rights reserved. * * Licensed under the MADAI Software License. You may obtain a copy of * this license at * * https://madai-public.cs.unc.edu/visualization/software-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 <ostream> #include "Sample.h" namespace madai { Sample ::Sample( const std::vector< double > & parameterValues, const std::vector< double > & outputValues, double LogLikelihood, const std::vector< double > logLikelihoodValueGradient, const std::vector< double > logLikelihoodErrorGradient) : m_ParameterValues( parameterValues ), m_OutputValues( outputValues ), m_LogLikelihoodValueGradient( logLikelihoodValueGradient ), m_LogLikelihoodErrorGradient( logLikelihoodErrorGradient ), m_LogLikelihood( LogLikelihood ) { } Sample ::Sample( const std::vector< double > & parameter_values, const std::vector< double > & output_values, double LogLikelihood ) : m_ParameterValues( parameter_values ), m_OutputValues( output_values ), m_LogLikelihood( LogLikelihood ) { } Sample ::Sample( const std::vector< double > & parameter_values, const std::vector< double > & output_values ) : m_ParameterValues( parameter_values ), m_OutputValues( output_values ), m_LogLikelihood( 0.0 ) { } Sample ::Sample( const std::vector< double > & parameter_values ) : m_ParameterValues( parameter_values ), m_LogLikelihood( 0.0 ) { } Sample ::Sample() : m_LogLikelihood(0.0) { } void Sample ::Reset() { m_ParameterValues.clear(); m_OutputValues.clear(); m_Comments.clear(); m_LogLikelihood= 0.0; } bool Sample ::IsValid() const { return ( m_ParameterValues.size() > 0 || m_OutputValues.size() > 0 || m_Comments.size() > 0 ); } /** Provide this operator so that we can do: void SortSamples(std::vector< Sample > & s) { std::sort(s.begin(),s.end()); } */ bool Sample ::operator<(const Sample & rhs) const { return (m_LogLikelihood < rhs.m_LogLikelihood); } bool Sample ::operator==(const Sample & rhs) const { if ( m_LogLikelihood != rhs.m_LogLikelihood ) { return false; } if ( m_ParameterValues != rhs.m_ParameterValues ) { return false; } if ( m_OutputValues != rhs.m_OutputValues ) { return false; } if ( m_LogLikelihoodValueGradient != rhs.m_LogLikelihoodValueGradient ) { return false; } if ( m_LogLikelihoodErrorGradient != rhs.m_LogLikelihoodErrorGradient ) { return false; } if ( m_Comments != rhs.m_Comments ) { return false; } return true; } std::ostream & operator<<(std::ostream & os, const Sample & sample) { os << "Sample:\n"; os << " ParameterValues: ["; for ( size_t i = 0; i < sample.m_ParameterValues.size(); ++i ) { os << sample.m_ParameterValues[i]; if ( i < sample.m_ParameterValues.size()-1) os << ", "; } os << "]\n"; os << " OutputValues: ["; for ( size_t i = 0; i < sample.m_OutputValues.size(); ++i ) { os << sample.m_OutputValues[i]; if ( i < sample.m_OutputValues.size()-1) os << ", "; } os << "]\n"; os << " dLL/dobservable: ["; for ( size_t i = 0; i < sample.m_LogLikelihoodValueGradient.size(); ++i ) { os << sample.m_LogLikelihoodValueGradient[i]; if ( i < sample.m_LogLikelihoodValueGradient.size()-1) os << ", "; } os << "]\n"; os << " sigma_observable*dLL/dsigma_observable: ["; for ( size_t i = 0; i < sample.m_LogLikelihoodErrorGradient.size(); ++i ) { os << sample.m_LogLikelihoodErrorGradient[i]; if ( i < sample.m_LogLikelihoodErrorGradient.size()-1) os << ", "; } os << "]\n"; os << " LogLikelihood: [" << sample.m_LogLikelihood << "]\n"; if ( sample.m_Comments.size() > 0 ) { for ( size_t i = 0; i < sample.m_Comments.size(); ++i ) { os << sample.m_Comments[i]; if ( i < sample.m_Comments.size()-1) os << ", "; } } return os; } } // end namespace madai <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2010 - 2014, Göteborg Bit Factory. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <signal.h> #include <errno.h> #include <unistd.h> #include <syslog.h> #include <string.h> #include <assert.h> #include <Server.h> #include <TLSServer.h> #include <Timer.h> #include <text.h> // Indicates that certain signals were caught. bool _sighup = false; bool _sigusr1 = false; bool _sigusr2 = false; //////////////////////////////////////////////////////////////////////////////// static void signal_handler (int s) { switch (s) { case SIGHUP: _sighup = true; break; case SIGUSR1: _sigusr1 = true; break; case SIGUSR2: _sigusr2 = true; break; } } //////////////////////////////////////////////////////////////////////////////// Server::Server () : _log (NULL) , _log_clients (false) , _client_address ("") , _client_port (0) , _host ("::") , _port ("12345") , _pool_size (4) , _queue_size (10) , _daemon (false) , _pid_file ("") , _request_count (0) , _limit (0) // Unlimited , _ca_file ("") , _cert_file ("") , _key_file ("") , _crl_file ("") { } //////////////////////////////////////////////////////////////////////////////// Server::~Server () { } //////////////////////////////////////////////////////////////////////////////// void Server::setPort (const std::string& port) { if (_log) _log->format ("Using port %s", port.c_str ()); _port = port; } //////////////////////////////////////////////////////////////////////////////// void Server::setHost (const std::string& host) { if (_log) _log->format ("Using address %s", host.c_str ()); _host = host; } //////////////////////////////////////////////////////////////////////////////// void Server::setQueueSize (int size) { if (_log) _log->format ("Queue size %d requests", size); _queue_size = size; } //////////////////////////////////////////////////////////////////////////////// void Server::setPoolSize (int size) { if (_log) _log->format ("Thread Pool size %d", size); _pool_size = size; } //////////////////////////////////////////////////////////////////////////////// void Server::setDaemon () { if (_log) _log->write ("Will run as daemon"); _daemon = true; } //////////////////////////////////////////////////////////////////////////////// void Server::setPidFile (const std::string& file) { if (_log) _log->write ("PID file " + file); assert (file.length () > 0); _pid_file = file; } //////////////////////////////////////////////////////////////////////////////// void Server::setLimit (int max) { if (_log) _log->format ("Request size limit %d bytes", max); assert (max >= 0); _limit = max; } //////////////////////////////////////////////////////////////////////////////// void Server::setCAFile (const std::string& file) { if (_log) _log->format ("CA %s", file.c_str ()); _ca_file = file; File cert (file); if (! cert.readable ()) throw format ("CA Certificate not readable: '{1}'", file); } //////////////////////////////////////////////////////////////////////////////// void Server::setCertFile (const std::string& file) { if (_log) _log->format ("Certificate %s", file.c_str ()); _cert_file = file; File cert (file); if (! cert.readable ()) throw format ("Server Certificate not readable: '{1}'", file); } //////////////////////////////////////////////////////////////////////////////// void Server::setKeyFile (const std::string& file) { if (_log) _log->format ("Private Key %s", file.c_str ()); _key_file = file; File key (file); if (! key.readable ()) throw format ("Server key not readable: '{1}'", file); } //////////////////////////////////////////////////////////////////////////////// void Server::setCRLFile (const std::string& file) { if (_log) _log->format ("CRL %s", file.c_str ()); _crl_file = file; File crl (file); if (! crl.readable ()) throw format ("CRL Certificate not readable: '{1}'", file); } //////////////////////////////////////////////////////////////////////////////// void Server::setLogClients (bool value) { if (_log) _log->format ("IP logging %s", (value ? "on" : "off")); _log_clients = value; } //////////////////////////////////////////////////////////////////////////////// void Server::setLog (Log* l) { _log = l; } //////////////////////////////////////////////////////////////////////////////// void Server::setConfig (Config* c) { _config = c; } //////////////////////////////////////////////////////////////////////////////// void Server::beginServer () { if (_log) _log->write ("Server starting"); if (_daemon) { daemonize (); // Only the child returns. writePidFile (); } signal (SIGHUP, signal_handler); signal (SIGUSR1, signal_handler); signal (SIGUSR2, signal_handler); TLSServer server; if (_config) { server.debug (_config->getInteger ("debug.tls")); std::string ciphers = _config->get ("ciphers"); if (ciphers != "") { server.ciphers (ciphers); if (_log) _log->format ("Using ciphers: %s", ciphers.c_str ()); } } server.init (_ca_file, // CA _crl_file, // CRL _cert_file, // Cert _key_file); // Key server.queue (_queue_size); server.bind (_host, _port); server.listen (); if (_log) _log->write ("Server ready"); _request_count = 0; while (1) { try { TLSTransaction tx; server.accept (tx); // Get client address and port, for logging. if (_log_clients) tx.getClient (_client_address, _client_port); // Metrics. HighResTimer timer; timer.start (); std::string input; tx.recv (input); // Handle the request. ++_request_count; // Call the derived class handler. std::string output; handler (input, output); if (output.length ()) tx.send (output); if (_log) { timer.stop (); _log->format ("[%d] Serviced in %.6fs", _request_count, timer.total ()); } } catch (std::string& e) { if (_log) _log->write (std::string ("Error: ") + e); } catch (char* e) { if (_log) _log->write (std::string ("Error: ") + e); } catch (...) { if (_log) _log->write ("Error: Unknown exception"); } } } //////////////////////////////////////////////////////////////////////////////// // TODO To provide these data, a request count, a start time, and a cumulative // utilization time must be tracked. void Server::stats (int& requests, time_t& uptime, double& utilization) { requests = _request_count; uptime = 0; utilization = 0.0; } //////////////////////////////////////////////////////////////////////////////// void Server::daemonize () { if (_log) _log->write ("Daemonizing"); /* TODO Load RUN_AS_USER from config. // If run as root, switch to preferred user. if (getuid () == 0 || geteuid () == 0 ) { struct passwd *pw = getpwnam (RUN_AS_USER); if (pw) { if (_log) _log->write ("setting user to " RUN_AS_USER); setuid (pw->pw_uid); } } */ // Fork off the parent process pid_t pid = fork (); if (pid < 0) { exit (EXIT_FAILURE); } // If we got a good PID, then we can exit the parent process. if (pid > 0) { exit (EXIT_SUCCESS); } // Change the file mode mask umask (0); // Create a new SID for the child process pid_t sid = setsid (); if (sid < 0) { if (_log) _log->write ("setsid failed"); exit (EXIT_FAILURE); } // Change the current working directory // Why is this important? To ensure that program is independent of $CWD? if ((chdir ("/")) < 0) { if (_log) _log->write ("chdir failed"); exit (EXIT_FAILURE); } // Redirect standard files to /dev/null. freopen ("/dev/null", "r", stdin); freopen ("/dev/null", "w", stdout); freopen ("/dev/null", "w", stderr); if (_log) _log->write ("Daemonized"); } //////////////////////////////////////////////////////////////////////////////// void Server::writePidFile () { pid_t pid = getpid (); FILE* output = fopen (_pid_file.c_str (), "w"); if (output) { fprintf (output, "%d", pid); fclose (output); } else if (_log) _log->write ("Error: could not write PID to '" + _pid_file + "'."); } //////////////////////////////////////////////////////////////////////////////// void Server::removePidFile () { assert (_pid_file.length () > 0); unlink (_pid_file.c_str ()); } //////////////////////////////////////////////////////////////////////////////// <commit_msg>Diagnostics<commit_after>//////////////////////////////////////////////////////////////////////////////// // // Copyright 2010 - 2014, Göteborg Bit Factory. // // 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. // // http://www.opensource.org/licenses/mit-license.php // //////////////////////////////////////////////////////////////////////////////// #include <cmake.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <signal.h> #include <errno.h> #include <unistd.h> #include <syslog.h> #include <string.h> #include <assert.h> #include <Server.h> #include <TLSServer.h> #include <Timer.h> #include <text.h> // Indicates that certain signals were caught. bool _sighup = false; bool _sigusr1 = false; bool _sigusr2 = false; //////////////////////////////////////////////////////////////////////////////// static void signal_handler (int s) { switch (s) { case SIGHUP: _sighup = true; break; case SIGUSR1: _sigusr1 = true; break; case SIGUSR2: _sigusr2 = true; break; } } //////////////////////////////////////////////////////////////////////////////// Server::Server () : _log (NULL) , _log_clients (false) , _client_address ("") , _client_port (0) , _host ("::") , _port ("12345") , _pool_size (4) , _queue_size (10) , _daemon (false) , _pid_file ("") , _request_count (0) , _limit (0) // Unlimited , _ca_file ("") , _cert_file ("") , _key_file ("") , _crl_file ("") { } //////////////////////////////////////////////////////////////////////////////// Server::~Server () { } //////////////////////////////////////////////////////////////////////////////// void Server::setPort (const std::string& port) { if (_log) _log->format ("Using port %s", port.c_str ()); _port = port; } //////////////////////////////////////////////////////////////////////////////// void Server::setHost (const std::string& host) { if (_log) _log->format ("Using address %s", host.c_str ()); _host = host; } //////////////////////////////////////////////////////////////////////////////// void Server::setQueueSize (int size) { if (_log) _log->format ("Queue size %d requests", size); _queue_size = size; } //////////////////////////////////////////////////////////////////////////////// void Server::setPoolSize (int size) { if (_log) _log->format ("Thread Pool size %d", size); _pool_size = size; } //////////////////////////////////////////////////////////////////////////////// void Server::setDaemon () { if (_log) _log->write ("Will run as daemon"); _daemon = true; } //////////////////////////////////////////////////////////////////////////////// void Server::setPidFile (const std::string& file) { if (_log) _log->write ("PID file " + file); assert (file.length () > 0); _pid_file = file; } //////////////////////////////////////////////////////////////////////////////// void Server::setLimit (int max) { if (_log) _log->format ("Request size limit %d bytes", max); assert (max >= 0); _limit = max; } //////////////////////////////////////////////////////////////////////////////// void Server::setCAFile (const std::string& file) { if (_log) _log->format ("CA %s", file.c_str ()); _ca_file = file; File cert (file); if (! cert.readable ()) throw format ("CA Certificate not readable: '{1}'", file); } //////////////////////////////////////////////////////////////////////////////// void Server::setCertFile (const std::string& file) { if (_log) _log->format ("Certificate %s", file.c_str ()); _cert_file = file; File cert (file); if (! cert.readable ()) throw format ("Server Certificate not readable: '{1}'", file); } //////////////////////////////////////////////////////////////////////////////// void Server::setKeyFile (const std::string& file) { if (_log) _log->format ("Private Key %s", file.c_str ()); _key_file = file; File key (file); if (! key.readable ()) throw format ("Server key not readable: '{1}'", file); } //////////////////////////////////////////////////////////////////////////////// void Server::setCRLFile (const std::string& file) { if (_log) _log->format ("CRL %s", file.c_str ()); _crl_file = file; File crl (file); if (! crl.readable ()) throw format ("CRL Certificate not readable: '{1}'", file); } //////////////////////////////////////////////////////////////////////////////// void Server::setLogClients (bool value) { if (_log) _log->format ("IP logging %s", (value ? "on" : "off")); _log_clients = value; } //////////////////////////////////////////////////////////////////////////////// void Server::setLog (Log* l) { _log = l; } //////////////////////////////////////////////////////////////////////////////// void Server::setConfig (Config* c) { _config = c; } //////////////////////////////////////////////////////////////////////////////// void Server::beginServer () { if (_log) _log->write ("Server starting"); if (_daemon) { daemonize (); // Only the child returns. writePidFile (); } signal (SIGHUP, signal_handler); signal (SIGUSR1, signal_handler); signal (SIGUSR2, signal_handler); TLSServer server; if (_config) { server.debug (_config->getInteger ("debug.tls")); std::string ciphers = _config->get ("ciphers"); if (ciphers != "") { server.ciphers (ciphers); if (_log) _log->format ("Using ciphers: %s", ciphers.c_str ()); } } server.init (_ca_file, // CA _crl_file, // CRL _cert_file, // Cert _key_file); // Key server.queue (_queue_size); server.bind (_host, _port); server.listen (); if (_log) _log->write ("Server ready"); _request_count = 0; while (1) { try { TLSTransaction tx; server.accept (tx); // Get client address and port, for logging. if (_log_clients) tx.getClient (_client_address, _client_port); // Metrics. HighResTimer timer; timer.start (); std::string input; tx.recv (input); // Handle the request. ++_request_count; // Call the derived class handler. std::string output; handler (input, output); if (output.length ()) tx.send (output); if (_log) { timer.stop (); _log->format ("[%d] Serviced in %.6fs", _request_count, timer.total ()); } } catch (std::string& e) { if (_log) _log->write (std::string ("Error: ") + e); } catch (char* e) { if (_log) _log->write (std::string ("Error: ") + e); } catch (...) { if (_log) _log->write ("Error: Unknown exception"); } } } //////////////////////////////////////////////////////////////////////////////// // TODO To provide these data, a request count, a start time, and a cumulative // utilization time must be tracked. void Server::stats (int& requests, time_t& uptime, double& utilization) { requests = _request_count; uptime = 0; utilization = 0.0; } //////////////////////////////////////////////////////////////////////////////// void Server::daemonize () { if (_log) _log->write ("Daemonizing"); /* TODO Load RUN_AS_USER from config. // If run as root, switch to preferred user. if (getuid () == 0 || geteuid () == 0 ) { struct passwd *pw = getpwnam (RUN_AS_USER); if (pw) { if (_log) _log->write ("setting user to " RUN_AS_USER); setuid (pw->pw_uid); } } */ // Fork off the parent process pid_t pid = fork (); if (pid < 0) { exit (EXIT_FAILURE); } // If we got a good PID, then we can exit the parent process. if (pid > 0) { exit (EXIT_SUCCESS); } // Change the file mode mask umask (0); // Create a new SID for the child process pid_t sid = setsid (); if (sid < 0) { if (_log) _log->write ("setsid failed"); exit (EXIT_FAILURE); } // Change the current working directory // Why is this important? To ensure that program is independent of $CWD? if ((chdir ("/")) < 0) { if (_log) _log->write ("chdir failed"); exit (EXIT_FAILURE); } // Redirect standard files to /dev/null. freopen ("/dev/null", "r", stdin); freopen ("/dev/null", "w", stdout); freopen ("/dev/null", "w", stderr); if (_log) _log->write ("Daemonized"); } //////////////////////////////////////////////////////////////////////////////// void Server::writePidFile () { pid_t pid = getpid (); FILE* output = fopen (_pid_file.c_str (), "w"); if (output) { fprintf (output, "%d", pid); fclose (output); } else if (_log) _log->write ("Error: could not write PID to '" + _pid_file + "'."); } //////////////////////////////////////////////////////////////////////////////// void Server::removePidFile () { assert (_pid_file.length () > 0); unlink (_pid_file.c_str ()); } //////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/* * FastRPC -- Fast RPC library compatible with XML-RPC * Copyright (C) 2005-7 Seznam.cz, a.s. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Seznam.cz, a.s. * Radlicka 2, Praha 5, 15000, Czech Republic * http://www.seznam.cz, mailto:fastrpc@firma.seznam.cz * * FILE $Id: frpcconnector.cc,v 1.7 2011-02-11 08:56:17 burlog Exp $ * * DESCRIPTION * * AUTHOR * Vaclav Blazek <vaclav.blazek@firma.seznam.cz> * * HISTORY * */ #include "nonglibc.h" #include <sys/types.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <fcntl.h> #include <errno.h> #include "frpcplatform.h" #include "frpcconnector.h" #include "frpchttperror.h" #include "frpcsocket.h" using namespace FRPC; Connector_t::Connector_t(const URL_t &url, int connectTimeout, bool keepAlive) : url(url), connectTimeout(connectTimeout), keepAlive(keepAlive) {} Connector_t::~Connector_t() {} namespace { struct SocketCloser_t { SocketCloser_t(int &fd) : fd(fd), doClose(true) {} ~SocketCloser_t() { if (doClose && (fd > -1)) { TEMP_FAILURE_RETRY(::close(fd)); fd = -1; } } void release() { doClose = false; } int &fd; bool doClose; }; const char *host_strerror(int num) { switch (num) { case HOST_NOT_FOUND: return "The specified host is unknown"; case NO_ADDRESS: return "The requested name is valid but does " "not have an IP address."; case NO_RECOVERY: return "A non-recoverable name server error occurred."; case TRY_AGAIN: return "A temporary error occurred on an authoritative " "name server. Try again later."; default: return "Unknown DNS related error."; } } void checkSocket(int &fd) { // check for connect status socklen_t len = sizeof(int); int status; #ifdef WIN32 if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&status, &len)) #else //WIN32 if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &status, &len)) #endif //WIN32 { STRERROR_PRE(); throw HTTPError_t( HTTP_SYSCALL, "Cannot get socket info: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } // check for error if (status) { STRERROR_PRE(); throw HTTPError_t( HTTP_SYSCALL, "Cannot connect socket: <%d, %s>.", status, STRERROR(status)); } } } // namespace SimpleConnector_t::SimpleConnector_t(const URL_t &url, int connectTimeout, bool keepAlive) : Connector_t(url, connectTimeout, keepAlive) { struct hostent h, *he; char tmpbuf[1024]; int errcode; #if (defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)) he = gethostbyname_r(url.host.c_str(), &h, tmpbuf, 1024, &errcode); #else gethostbyname_r(url.host.c_str(), &h, tmpbuf, 1024, &he, &errcode); #endif if (!he) { // oops throw HTTPError_t(HTTP_DNS, "Cannot resolve host '%s': <%d, %s>.", url.host.c_str(), errcode, host_strerror(errcode)); } // remember IP address ipaddr = *reinterpret_cast<in_addr*>(he->h_addr_list[0]); } SimpleConnector_t::~SimpleConnector_t() {} void SimpleConnector_t::connectSocket(int &fd) { // check socket if (!keepAlive && (fd > -1)) { TEMP_FAILURE_RETRY(::close(fd)); fd = -1; } // initialize closer (initially closes socket when valid) SocketCloser_t closer(fd); // check open socket whether the peer had not closed it if (fd > -1) { closer.release(); // check for activity on socket pollfd pfd; pfd.fd = fd; pfd.events = POLLIN; // okam¾itý timeout switch (TEMP_FAILURE_RETRY(::poll(&pfd, 1, 0))) { case 0: // OK break; case -1: // some error on socket => close it TEMP_FAILURE_RETRY(::close(fd)); fd = -1; break; default: // check whether any data can be read from the socket char buff; switch (TEMP_FAILURE_RETRY(recv(fd, &buff, 1, MSG_PEEK))) { case -1: case 0: // zavøeme socket TEMP_FAILURE_RETRY(::close(fd)); fd = -1; break; default: // OK break; } } } // if open socket is not availabe open new one if (fd < 0) { // otevøeme socket if ((fd = ::socket(PF_INET, SOCK_STREAM, 0)) < 0) { // oops! error STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot select on socketr: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } #ifdef WIN32 unsigned int flag = 1; if (::ioctlsocket((SOCKET)fd, FIONBIO, &flag) < 0) #else //WIN32 if (::fcntl(fd, F_SETFL, O_NONBLOCK) < 0) #endif //WIN32 { STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot set socket non-blocking: " "<%d, %s>.", ERRNO, STRERROR(ERRNO)); } // set not-delayed IO (we are not telnet) int just_say_no = 1; if (::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*) &just_say_no, sizeof(int)) < 0) { STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot set socket non-delaying: " "<%d, %s>.", ERRNO, STRERROR(ERRNO)); } // peer address struct sockaddr_in addr; // initialize it addr.sin_family = AF_INET; addr.sin_port = htons(url.port); addr.sin_addr = ipaddr; memset(addr.sin_zero, 0x0, 8); // connect the socket if (TEMP_FAILURE_RETRY(::connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr))) < 0) { switch (ERRNO) { case EINPROGRESS: // connection already in progress case EALREADY: // connection already in progress case EWOULDBLOCK: // connection launched on the background break; default: STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot connect socket: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } // create poll struct pollfd pfd; pfd.fd = fd; pfd.events = POLLOUT; // wait for connect completion or timeout int ready = TEMP_FAILURE_RETRY( ::poll(&pfd, 1, (connectTimeout < 0) ? -1 : connectTimeout)); if (ready <= 0) { switch (ready) { case 0: throw HTTPError_t(HTTP_SYSCALL, "Timeout while connecting to %s.", url.getUrl().c_str()); default: STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot select on socket: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } } checkSocket(fd); } // connect OK => do not close the socket! closer.release(); } } SimpleConnectorIPv6_t::SimpleConnectorIPv6_t(const URL_t &url, int connectTimeout, bool keepAlive) : Connector_t(url, connectTimeout, keepAlive), addrInfo(0) { int errcode; struct addrinfo hints; char port[8] = {0}; memset(&hints, 0, sizeof(hints)); hints.ai_flags = 0; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; std::string host = url.host; if ( *host.begin() == '[' && *host.rbegin() == ']' ) { host = host.substr(1, host.size() - 2); hints.ai_family = AF_INET6; } snprintf(port, sizeof(port), "%u", url.port); errcode = getaddrinfo(host.c_str(), port, &hints, &addrInfo); if ( errcode != 0 ) { // oops throw HTTPError_t(HTTP_DNS, "Cannot resolve host '%s'('%s'): <%d, %s>.", url.host.c_str(), host.c_str(), errcode, gai_strerror(errcode)); } } SimpleConnectorIPv6_t::~SimpleConnectorIPv6_t() { if ( addrInfo ) freeaddrinfo(addrInfo); } void SimpleConnectorIPv6_t::connectSocket(int &fd) { // check socket if (!keepAlive && (fd > -1)) { TEMP_FAILURE_RETRY(::close(fd)); fd = -1; } // initialize closer (initially closes socket when valid) SocketCloser_t closer(fd); // check open socket whether the peer had not closed it if (fd > -1) { closer.release(); // check for activity on socket pollfd pfd; pfd.fd = fd; pfd.events = POLLIN; // okam¾itý timeout switch (TEMP_FAILURE_RETRY(::poll(&pfd, 1, 0))) { case 0: // OK break; case -1: // some error on socket => close it TEMP_FAILURE_RETRY(::close(fd)); fd = -1; break; default: // check whether any data can be read from the socket char buff; switch (TEMP_FAILURE_RETRY(recv(fd, &buff, 1, MSG_PEEK))) { case -1: case 0: // zavøeme socket TEMP_FAILURE_RETRY(::close(fd)); fd = -1; break; default: // OK break; } } } // if open socket is not availabe open new one if (fd < 0) { // otevøeme socket if ((fd = ::socket(addrInfo->ai_family, SOCK_STREAM, 0)) < 0) { // oops! error STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot select on socketr: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } #ifdef WIN32 unsigned int flag = 1; if (::ioctlsocket((SOCKET)fd, FIONBIO, &flag) < 0) #else //WIN32 if (::fcntl(fd, F_SETFL, O_NONBLOCK) < 0) #endif //WIN32 { STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot set socket non-blocking: " "<%d, %s>.", ERRNO, STRERROR(ERRNO)); } // set not-delayed IO (we are not telnet) int just_say_no = 1; if (::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*) &just_say_no, sizeof(int)) < 0) { STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot set socket non-delaying: " "<%d, %s>.", ERRNO, STRERROR(ERRNO)); } // connect the socket if (TEMP_FAILURE_RETRY(::connect(fd, addrInfo->ai_addr, addrInfo->ai_addrlen)) < 0) { switch (ERRNO) { case EINPROGRESS: // connection already in progress case EALREADY: // connection already in progress case EWOULDBLOCK: // connection launched on the background break; default: STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot connect socket: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } // create poll struct pollfd pfd; pfd.fd = fd; pfd.events = POLLOUT; // wait for connect completion or timeout int ready = TEMP_FAILURE_RETRY( ::poll(&pfd, 1, (connectTimeout < 0) ? -1 : connectTimeout)); if (ready <= 0) { switch (ready) { case 0: throw HTTPError_t(HTTP_SYSCALL, "Timeout while connecting to %s.", url.getUrl().c_str()); default: STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot select on socket: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } } checkSocket(fd); } // connect OK => do not close the socket! closer.release(); } } <commit_msg>Factored out setNonBlockingSocket() from connectSocket()<commit_after>/* * FastRPC -- Fast RPC library compatible with XML-RPC * Copyright (C) 2005-7 Seznam.cz, a.s. * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Seznam.cz, a.s. * Radlicka 2, Praha 5, 15000, Czech Republic * http://www.seznam.cz, mailto:fastrpc@firma.seznam.cz * * FILE $Id: frpcconnector.cc,v 1.7 2011-02-11 08:56:17 burlog Exp $ * * DESCRIPTION * * AUTHOR * Vaclav Blazek <vaclav.blazek@firma.seznam.cz> * * HISTORY * */ #include "nonglibc.h" #include <sys/types.h> #include <string.h> #include <errno.h> #include <ctype.h> #include <fcntl.h> #include <errno.h> #include "frpcplatform.h" #include "frpcconnector.h" #include "frpchttperror.h" #include "frpcsocket.h" using namespace FRPC; Connector_t::Connector_t(const URL_t &url, int connectTimeout, bool keepAlive) : url(url), connectTimeout(connectTimeout), keepAlive(keepAlive) {} Connector_t::~Connector_t() {} namespace { struct SocketCloser_t { SocketCloser_t(int &fd) : fd(fd), doClose(true) {} ~SocketCloser_t() { if (doClose && (fd > -1)) { TEMP_FAILURE_RETRY(::close(fd)); fd = -1; } } void release() { doClose = false; } int &fd; bool doClose; }; const char *host_strerror(int num) { switch (num) { case HOST_NOT_FOUND: return "The specified host is unknown"; case NO_ADDRESS: return "The requested name is valid but does " "not have an IP address."; case NO_RECOVERY: return "A non-recoverable name server error occurred."; case TRY_AGAIN: return "A temporary error occurred on an authoritative " "name server. Try again later."; default: return "Unknown DNS related error."; } } void checkSocket(int &fd) { // check for connect status socklen_t len = sizeof(int); int status; #ifdef WIN32 if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&status, &len)) #else //WIN32 if (::getsockopt(fd, SOL_SOCKET, SO_ERROR, &status, &len)) #endif //WIN32 { STRERROR_PRE(); throw HTTPError_t( HTTP_SYSCALL, "Cannot get socket info: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } // check for error if (status) { STRERROR_PRE(); throw HTTPError_t( HTTP_SYSCALL, "Cannot connect socket: <%d, %s>.", status, STRERROR(status)); } } void setNonBlockingSocket(int& fd) { #ifdef WIN32 unsigned int flag = 1; if (::ioctlsocket((SOCKET)fd, FIONBIO, &flag) < 0) #else //WIN32 if (::fcntl(fd, F_SETFL, O_NONBLOCK) < 0) #endif //WIN32 { STRERROR_PRE(); throw HTTPError_t( HTTP_SYSCALL, "Cannot set socket non-blocking: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } } } // namespace SimpleConnector_t::SimpleConnector_t(const URL_t &url, int connectTimeout, bool keepAlive) : Connector_t(url, connectTimeout, keepAlive) { struct hostent h, *he; char tmpbuf[1024]; int errcode; #if (defined(sun) || defined(__sun)) && (defined(__SVR4) || defined(__svr4__)) he = gethostbyname_r(url.host.c_str(), &h, tmpbuf, 1024, &errcode); #else gethostbyname_r(url.host.c_str(), &h, tmpbuf, 1024, &he, &errcode); #endif if (!he) { // oops throw HTTPError_t(HTTP_DNS, "Cannot resolve host '%s': <%d, %s>.", url.host.c_str(), errcode, host_strerror(errcode)); } // remember IP address ipaddr = *reinterpret_cast<in_addr*>(he->h_addr_list[0]); } SimpleConnector_t::~SimpleConnector_t() {} void SimpleConnector_t::connectSocket(int &fd) { // check socket if (!keepAlive && (fd > -1)) { TEMP_FAILURE_RETRY(::close(fd)); fd = -1; } // initialize closer (initially closes socket when valid) SocketCloser_t closer(fd); // check open socket whether the peer had not closed it if (fd > -1) { closer.release(); // check for activity on socket pollfd pfd; pfd.fd = fd; pfd.events = POLLIN; // okam¾itý timeout switch (TEMP_FAILURE_RETRY(::poll(&pfd, 1, 0))) { case 0: // OK break; case -1: // some error on socket => close it TEMP_FAILURE_RETRY(::close(fd)); fd = -1; break; default: // check whether any data can be read from the socket char buff; switch (TEMP_FAILURE_RETRY(recv(fd, &buff, 1, MSG_PEEK))) { case -1: case 0: // zavøeme socket TEMP_FAILURE_RETRY(::close(fd)); fd = -1; break; default: // OK break; } } } // if open socket is not availabe open new one if (fd < 0) { // otevøeme socket if ((fd = ::socket(PF_INET, SOCK_STREAM, 0)) < 0) { // oops! error STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot select on socketr: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } setNonBlockingSocket(fd); // set not-delayed IO (we are not telnet) int just_say_no = 1; if (::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*) &just_say_no, sizeof(int)) < 0) { STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot set socket non-delaying: " "<%d, %s>.", ERRNO, STRERROR(ERRNO)); } // peer address struct sockaddr_in addr; // initialize it addr.sin_family = AF_INET; addr.sin_port = htons(url.port); addr.sin_addr = ipaddr; memset(addr.sin_zero, 0x0, 8); // connect the socket if (TEMP_FAILURE_RETRY(::connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr))) < 0) { switch (ERRNO) { case EINPROGRESS: // connection already in progress case EALREADY: // connection already in progress case EWOULDBLOCK: // connection launched on the background break; default: STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot connect socket: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } // create poll struct pollfd pfd; pfd.fd = fd; pfd.events = POLLOUT; // wait for connect completion or timeout int ready = TEMP_FAILURE_RETRY( ::poll(&pfd, 1, (connectTimeout < 0) ? -1 : connectTimeout)); if (ready <= 0) { switch (ready) { case 0: throw HTTPError_t(HTTP_SYSCALL, "Timeout while connecting to %s.", url.getUrl().c_str()); default: STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot select on socket: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } } checkSocket(fd); } // connect OK => do not close the socket! closer.release(); } } SimpleConnectorIPv6_t::SimpleConnectorIPv6_t(const URL_t &url, int connectTimeout, bool keepAlive) : Connector_t(url, connectTimeout, keepAlive), addrInfo(0) { int errcode; struct addrinfo hints; char port[8] = {0}; memset(&hints, 0, sizeof(hints)); hints.ai_flags = 0; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; std::string host = url.host; if ( *host.begin() == '[' && *host.rbegin() == ']' ) { host = host.substr(1, host.size() - 2); hints.ai_family = AF_INET6; } snprintf(port, sizeof(port), "%u", url.port); errcode = getaddrinfo(host.c_str(), port, &hints, &addrInfo); if ( errcode != 0 ) { // oops throw HTTPError_t(HTTP_DNS, "Cannot resolve host '%s'('%s'): <%d, %s>.", url.host.c_str(), host.c_str(), errcode, gai_strerror(errcode)); } } SimpleConnectorIPv6_t::~SimpleConnectorIPv6_t() { if ( addrInfo ) freeaddrinfo(addrInfo); } void SimpleConnectorIPv6_t::connectSocket(int &fd) { // check socket if (!keepAlive && (fd > -1)) { TEMP_FAILURE_RETRY(::close(fd)); fd = -1; } // initialize closer (initially closes socket when valid) SocketCloser_t closer(fd); // check open socket whether the peer had not closed it if (fd > -1) { closer.release(); // check for activity on socket pollfd pfd; pfd.fd = fd; pfd.events = POLLIN; // okam¾itý timeout switch (TEMP_FAILURE_RETRY(::poll(&pfd, 1, 0))) { case 0: // OK break; case -1: // some error on socket => close it TEMP_FAILURE_RETRY(::close(fd)); fd = -1; break; default: // check whether any data can be read from the socket char buff; switch (TEMP_FAILURE_RETRY(recv(fd, &buff, 1, MSG_PEEK))) { case -1: case 0: // zavøeme socket TEMP_FAILURE_RETRY(::close(fd)); fd = -1; break; default: // OK break; } } } // if open socket is not availabe open new one if (fd < 0) { // otevøeme socket if ((fd = ::socket(addrInfo->ai_family, SOCK_STREAM, 0)) < 0) { // oops! error STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot select on socketr: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } setNonBlockingSocket(fd); // set not-delayed IO (we are not telnet) int just_say_no = 1; if (::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char*) &just_say_no, sizeof(int)) < 0) { STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot set socket non-delaying: " "<%d, %s>.", ERRNO, STRERROR(ERRNO)); } // connect the socket if (TEMP_FAILURE_RETRY(::connect(fd, addrInfo->ai_addr, addrInfo->ai_addrlen)) < 0) { switch (ERRNO) { case EINPROGRESS: // connection already in progress case EALREADY: // connection already in progress case EWOULDBLOCK: // connection launched on the background break; default: STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot connect socket: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } // create poll struct pollfd pfd; pfd.fd = fd; pfd.events = POLLOUT; // wait for connect completion or timeout int ready = TEMP_FAILURE_RETRY( ::poll(&pfd, 1, (connectTimeout < 0) ? -1 : connectTimeout)); if (ready <= 0) { switch (ready) { case 0: throw HTTPError_t(HTTP_SYSCALL, "Timeout while connecting to %s.", url.getUrl().c_str()); default: STRERROR_PRE(); throw HTTPError_t(HTTP_SYSCALL, "Cannot select on socket: <%d, %s>.", ERRNO, STRERROR(ERRNO)); } } checkSocket(fd); } // connect OK => do not close the socket! closer.release(); } } <|endoftext|>
<commit_before>// Vaca - Visual Application Components Abstraction // Copyright (c) 2005, 2006, 2007, 2008, David Capello // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the author nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "Vaca/Thread.h" #include "Vaca/Debug.h" #include "Vaca/Frame.h" #include "Vaca/Signal.h" #include "Vaca/Timer.h" #include "Vaca/Mutex.h" #include "Vaca/ScopedLock.h" #include "Vaca/Slot.h" #include "Vaca/TimePoint.h" #include <vector> #include <algorithm> #include <memory> using namespace Vaca; ////////////////////////////////////////////////////////////////////// // TODO // - replace with some C++0x's Thread-Local Storage // - use __thread in GCC, and __declspec( thread ) in MSVC // - use TlsAlloc struct ThreadData { /** * The ID of this thread. */ ThreadId threadId; /** * Visible frames in this thread. A frame is an instance of Frame * class. */ std::vector<Frame*> frames; TimePoint updateIndicatorsMark; bool updateIndicators : 1; /** * True if the message-loop must be stopped. */ bool breakLoop : 1; /** * Widget used to call createHandle. */ Widget* outsideWidget; ThreadData(ThreadId id) { threadId = id; breakLoop = false; updateIndicators = true; outsideWidget = NULL; } }; static Mutex data_mutex; static std::vector<ThreadData*> dataOfEachThread; static ThreadData* getThreadData() { ScopedLock hold(data_mutex); std::vector<ThreadData*>::iterator it, end = dataOfEachThread.end(); ThreadId id = ::GetCurrentThreadId(); // first of all search the thread-data in the list "dataOfEachThread"... for (it=dataOfEachThread.begin(); it!=end; ++it) { if ((*it)->threadId == id) // it's already created... return *it; // return it } // create the data for the this thread ThreadData* data = new ThreadData(id); VACA_TRACE("new data-thread %d\n", id); // add it to the list dataOfEachThread.push_back(data); // return the allocated data return data; } void Vaca::__vaca_remove_all_thread_data() { ScopedLock hold(data_mutex); std::vector<ThreadData*>::iterator it, end = dataOfEachThread.end(); for (it=dataOfEachThread.begin(); it!=end; ++it) { VACA_TRACE("delete data-thread %d\n", (*it)->threadId); delete *it; } dataOfEachThread.clear(); } Widget* Vaca::__vaca_get_outside_widget() { return getThreadData()->outsideWidget; } void Vaca::__vaca_set_outside_widget(Widget* widget) { getThreadData()->outsideWidget = widget; } ////////////////////////////////////////////////////////////////////// static DWORD WINAPI ThreadProxy(LPVOID slot) { std::auto_ptr<Slot0<void> > slot_ptr(reinterpret_cast<Slot0<void>*>(slot)); (*slot_ptr)(); return 0; } Thread::Thread() { m_handle = GetCurrentThread(); m_id = GetCurrentThreadId(); VACA_TRACE("current Thread (%p, %d)\n", this, m_id); } /** * @throw CreateThreadException * If the thread couldn't be created by Win32's @c CreateThread. * * @internal */ void Thread::_Thread(const Slot0<void>& slot) { Slot0<void>* slotclone = slot.clone(); DWORD id; m_handle = CreateThread(NULL, 0, ThreadProxy, // clone the slot reinterpret_cast<LPVOID>(slotclone), CREATE_SUSPENDED, &id); if (!m_handle) { delete slotclone; throw CreateThreadException(); } m_id = id; VACA_TRACE("new Thread (%p, %d)\n", this, m_id); ResumeThread(m_handle); } Thread::~Thread() { if (isJoinable() && m_handle != NULL) { CloseHandle(reinterpret_cast<HANDLE>(m_handle)); m_handle = NULL; } VACA_TRACE("delete Thread (%p, %d)\n", this, m_id); } /** * Returns the thread ID. * * @win32 * This is equal to @msdn{GetCurrentThreadId} for the current * thread or the ID returned by @msdn{CreateThread}. * @endwin32 */ ThreadId Thread::getId() const { return m_id; } /** * Waits the thread to finish, and them closes it. */ void Thread::join() { assert(m_handle != NULL); assert(isJoinable()); WaitForSingleObject(reinterpret_cast<HANDLE>(m_handle), INFINITE); CloseHandle(reinterpret_cast<HANDLE>(m_handle)); m_handle = NULL; VACA_TRACE("join Thread (%p, %d)\n", this, m_id); } /** * Returns true if this thread can be waited by the current thread. */ bool Thread::isJoinable() const { return m_id != ::GetCurrentThreadId(); } /** * Sets the priority of the thread. * * Thread priority is relative to the other threads of the same * process. If you want to change the priority of the entire process * (respecting to all other processes) you have to use the * Application#setProcessPriority method. In other words, you should * use this method only if you have more than one thread in your * application and you want to make run faster one thread than other. * * @param priority * Can be one of the following values: * One of the following values: * @li ThreadPriority::Idle * @li ThreadPriority::Lowest * @li ThreadPriority::Low * @li ThreadPriority::Normal * @li ThreadPriority::High * @li ThreadPriority::Highest * @li ThreadPriority::TimeCritical * * @see Application#setProcessPriority */ void Thread::setThreadPriority(ThreadPriority priority) { assert(m_handle != NULL); int nPriority; switch (priority) { case ThreadPriority::Idle: nPriority = THREAD_PRIORITY_IDLE; break; case ThreadPriority::Lowest: nPriority = THREAD_PRIORITY_LOWEST; break; case ThreadPriority::Low: nPriority = THREAD_PRIORITY_BELOW_NORMAL; break; case ThreadPriority::Normal: nPriority = THREAD_PRIORITY_NORMAL; break; case ThreadPriority::High: nPriority = THREAD_PRIORITY_ABOVE_NORMAL; break; case ThreadPriority::Highest: nPriority = THREAD_PRIORITY_HIGHEST; break; case ThreadPriority::TimeCritical: nPriority = THREAD_PRIORITY_TIME_CRITICAL; break; default: assert(false); // TODO throw invalid argument exception return; } ::SetThreadPriority(m_handle, nPriority); } void Thread::enqueueMessage(const Message& message) { MSG const* msg = (MSG const*)message; ::PostThreadMessage(m_id, msg->message, msg->wParam, msg->lParam); } /** * Does the message loop while there are * visible @link Vaca::Frame frames@endlink. * * @see Frame::setVisible */ void Thread::doMessageLoop() { // message loop Message msg; while (getMessage(msg)) processMessage(msg); } /** * Does the message loop until the @a widget is hidden. */ void Thread::doMessageLoopFor(Widget* widget) { // get widget HWND HWND hwnd = widget->getHandle(); assert(::IsWindow(hwnd)); // get parent HWND HWND hparent = widget->getParentHandle(); // disable the parent HWND if (hparent != NULL) ::EnableWindow(hparent, FALSE); // message loop Message message; while (widget->isVisible() && getMessage(message)) processMessage(message); // enable the parent HWND if (hparent) ::EnableWindow(hparent, TRUE); } void Thread::pumpMessageQueue() { Message msg; while (peekMessage(msg)) processMessage(msg); } void Thread::breakMessageLoop() { getThreadData()->breakLoop = true; ::PostThreadMessage(::GetCurrentThreadId(), WM_NULL, 0, 0); } void Thread::yield() { ::Sleep(0); } void Thread::sleep(int msecs) { ::Sleep(msecs); } /** * Gets a message waiting for it: locks the execution of the program * until a message is received from the operating system. * * @return * True if the @a message parameter was filled (because a message was received) * or false if there aren't more visible @link Frame frames@endlink * to dispatch messages. */ bool Thread::getMessage(Message& message) { ThreadData* data = getThreadData(); // break this loop? (explicit break or no-more visible frames) if (data->breakLoop || data->frames.empty()) return false; // we have to update indicators? if (data->updateIndicators && data->updateIndicatorsMark.elapsed() > 0.1) { data->updateIndicators = false; // for each registered frame we should call updateIndicators to // update the state of all visible indicators (like top-level // items in the menu-bar and buttons in the tool-bar) for (std::vector<Frame*>::iterator it = data->frames.begin(), end = data->frames.end(); it != end; ++it) { (*it)->updateIndicators(); } } // get the message from the queue LPMSG msg = (LPMSG)message; msg->hwnd = NULL; BOOL bRet = ::GetMessage(msg, NULL, 0, 0); // WM_QUIT received? if (bRet == 0) return false; // WM_NULL message... maybe Timers or CallInNextRound if (msg->message == WM_NULL) Timer::pollTimers(); return true; } /** * Gets a message without waiting for it, if the queue is empty, this * method returns false. * * The message is removed from the queue. * * @return * Returns true if the @a msg parameter was filled with the next message * in the queue or false if the queue was empty. */ bool Thread::peekMessage(Message& message) { LPMSG msg = (LPMSG)message; msg->hwnd = NULL; return ::PeekMessage(msg, NULL, 0, 0, PM_REMOVE) != FALSE; } void Thread::processMessage(Message& message) { LPMSG msg = (LPMSG)message; if (!preTranslateMessage(message)) { // Send preTranslateMessage to the active window (useful for // modeless dialogs). WARNING: Don't use GetForegroundWindow // because it returns windows from other applications HWND hactive = GetActiveWindow(); if (hactive != NULL && hactive != msg->hwnd) { Widget* activeWidget = Widget::fromHandle(hactive); if (activeWidget->preTranslateMessage(message)) return; } //if (!TranslateAccelerator(msg->hwnd, hAccelTable, msg)) //{ ::TranslateMessage(msg); ::DispatchMessage(msg); //} } } /** * Pretranslates the message. The main function is to retrieve the * Widget pointer (using Widget::fromHandle()) and then (if it isn't * NULL), call its Widget#preTranslateMessage. */ bool Thread::preTranslateMessage(Message& message) { LPMSG msg = (LPMSG)message; // TODO process messages that produce a update-indicators event if ((msg->message == WM_ACTIVATE) || (msg->message == WM_CLOSE) || (msg->message == WM_SETFOCUS) || (msg->message == WM_KILLFOCUS) || (msg->message >= WM_LBUTTONDOWN && msg->message <= WM_MBUTTONDBLCLK) || (msg->message >= WM_KEYDOWN && msg->message <= WM_DEADCHAR)) { ThreadData* data = getThreadData(); data->updateIndicators = true; data->updateIndicatorsMark = TimePoint(); } if (msg->hwnd != NULL) { Widget* widget = Widget::fromHandle(msg->hwnd); if (widget && widget->preTranslateMessage(message)) return true; } return false; } void Thread::addFrame(Frame* frame) { getThreadData()->frames.push_back(frame); } void Thread::removeFrame(Frame* frame) { remove_from_container(getThreadData()->frames, frame); // when this thread doesn't have more Frames to continue we must to // break the current message loop if (getThreadData()->frames.empty()) Thread::breakMessageLoop(); } <commit_msg>Fixed a bug in Thread::processMessage where "activeWidget" can be NULL.<commit_after>// Vaca - Visual Application Components Abstraction // Copyright (c) 2005, 2006, 2007, 2008, David Capello // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of the author nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. #include "Vaca/Thread.h" #include "Vaca/Debug.h" #include "Vaca/Frame.h" #include "Vaca/Signal.h" #include "Vaca/Timer.h" #include "Vaca/Mutex.h" #include "Vaca/ScopedLock.h" #include "Vaca/Slot.h" #include "Vaca/TimePoint.h" #include <vector> #include <algorithm> #include <memory> using namespace Vaca; ////////////////////////////////////////////////////////////////////// // TODO // - replace with some C++0x's Thread-Local Storage // - use __thread in GCC, and __declspec( thread ) in MSVC // - use TlsAlloc struct ThreadData { /** * The ID of this thread. */ ThreadId threadId; /** * Visible frames in this thread. A frame is an instance of Frame * class. */ std::vector<Frame*> frames; TimePoint updateIndicatorsMark; bool updateIndicators : 1; /** * True if the message-loop must be stopped. */ bool breakLoop : 1; /** * Widget used to call createHandle. */ Widget* outsideWidget; ThreadData(ThreadId id) { threadId = id; breakLoop = false; updateIndicators = true; outsideWidget = NULL; } }; static Mutex data_mutex; static std::vector<ThreadData*> dataOfEachThread; static ThreadData* getThreadData() { ScopedLock hold(data_mutex); std::vector<ThreadData*>::iterator it, end = dataOfEachThread.end(); ThreadId id = ::GetCurrentThreadId(); // first of all search the thread-data in the list "dataOfEachThread"... for (it=dataOfEachThread.begin(); it!=end; ++it) { if ((*it)->threadId == id) // it's already created... return *it; // return it } // create the data for the this thread ThreadData* data = new ThreadData(id); VACA_TRACE("new data-thread %d\n", id); // add it to the list dataOfEachThread.push_back(data); // return the allocated data return data; } void Vaca::__vaca_remove_all_thread_data() { ScopedLock hold(data_mutex); std::vector<ThreadData*>::iterator it, end = dataOfEachThread.end(); for (it=dataOfEachThread.begin(); it!=end; ++it) { VACA_TRACE("delete data-thread %d\n", (*it)->threadId); delete *it; } dataOfEachThread.clear(); } Widget* Vaca::__vaca_get_outside_widget() { return getThreadData()->outsideWidget; } void Vaca::__vaca_set_outside_widget(Widget* widget) { getThreadData()->outsideWidget = widget; } ////////////////////////////////////////////////////////////////////// static DWORD WINAPI ThreadProxy(LPVOID slot) { std::auto_ptr<Slot0<void> > slot_ptr(reinterpret_cast<Slot0<void>*>(slot)); (*slot_ptr)(); return 0; } Thread::Thread() { m_handle = GetCurrentThread(); m_id = GetCurrentThreadId(); VACA_TRACE("current Thread (%p, %d)\n", this, m_id); } /** * @throw CreateThreadException * If the thread couldn't be created by Win32's @c CreateThread. * * @internal */ void Thread::_Thread(const Slot0<void>& slot) { Slot0<void>* slotclone = slot.clone(); DWORD id; m_handle = CreateThread(NULL, 0, ThreadProxy, // clone the slot reinterpret_cast<LPVOID>(slotclone), CREATE_SUSPENDED, &id); if (!m_handle) { delete slotclone; throw CreateThreadException(); } m_id = id; VACA_TRACE("new Thread (%p, %d)\n", this, m_id); ResumeThread(m_handle); } Thread::~Thread() { if (isJoinable() && m_handle != NULL) { CloseHandle(reinterpret_cast<HANDLE>(m_handle)); m_handle = NULL; } VACA_TRACE("delete Thread (%p, %d)\n", this, m_id); } /** * Returns the thread ID. * * @win32 * This is equal to @msdn{GetCurrentThreadId} for the current * thread or the ID returned by @msdn{CreateThread}. * @endwin32 */ ThreadId Thread::getId() const { return m_id; } /** * Waits the thread to finish, and them closes it. */ void Thread::join() { assert(m_handle != NULL); assert(isJoinable()); WaitForSingleObject(reinterpret_cast<HANDLE>(m_handle), INFINITE); CloseHandle(reinterpret_cast<HANDLE>(m_handle)); m_handle = NULL; VACA_TRACE("join Thread (%p, %d)\n", this, m_id); } /** * Returns true if this thread can be waited by the current thread. */ bool Thread::isJoinable() const { return m_id != ::GetCurrentThreadId(); } /** * Sets the priority of the thread. * * Thread priority is relative to the other threads of the same * process. If you want to change the priority of the entire process * (respecting to all other processes) you have to use the * Application#setProcessPriority method. In other words, you should * use this method only if you have more than one thread in your * application and you want to make run faster one thread than other. * * @param priority * Can be one of the following values: * One of the following values: * @li ThreadPriority::Idle * @li ThreadPriority::Lowest * @li ThreadPriority::Low * @li ThreadPriority::Normal * @li ThreadPriority::High * @li ThreadPriority::Highest * @li ThreadPriority::TimeCritical * * @see Application#setProcessPriority */ void Thread::setThreadPriority(ThreadPriority priority) { assert(m_handle != NULL); int nPriority; switch (priority) { case ThreadPriority::Idle: nPriority = THREAD_PRIORITY_IDLE; break; case ThreadPriority::Lowest: nPriority = THREAD_PRIORITY_LOWEST; break; case ThreadPriority::Low: nPriority = THREAD_PRIORITY_BELOW_NORMAL; break; case ThreadPriority::Normal: nPriority = THREAD_PRIORITY_NORMAL; break; case ThreadPriority::High: nPriority = THREAD_PRIORITY_ABOVE_NORMAL; break; case ThreadPriority::Highest: nPriority = THREAD_PRIORITY_HIGHEST; break; case ThreadPriority::TimeCritical: nPriority = THREAD_PRIORITY_TIME_CRITICAL; break; default: assert(false); // TODO throw invalid argument exception return; } ::SetThreadPriority(m_handle, nPriority); } void Thread::enqueueMessage(const Message& message) { MSG const* msg = (MSG const*)message; ::PostThreadMessage(m_id, msg->message, msg->wParam, msg->lParam); } /** * Does the message loop while there are * visible @link Vaca::Frame frames@endlink. * * @see Frame::setVisible */ void Thread::doMessageLoop() { // message loop Message msg; while (getMessage(msg)) processMessage(msg); } /** * Does the message loop until the @a widget is hidden. */ void Thread::doMessageLoopFor(Widget* widget) { // get widget HWND HWND hwnd = widget->getHandle(); assert(::IsWindow(hwnd)); // get parent HWND HWND hparent = widget->getParentHandle(); // disable the parent HWND if (hparent != NULL) ::EnableWindow(hparent, FALSE); // message loop Message message; while (widget->isVisible() && getMessage(message)) processMessage(message); // enable the parent HWND if (hparent) ::EnableWindow(hparent, TRUE); } void Thread::pumpMessageQueue() { Message msg; while (peekMessage(msg)) processMessage(msg); } void Thread::breakMessageLoop() { getThreadData()->breakLoop = true; ::PostThreadMessage(::GetCurrentThreadId(), WM_NULL, 0, 0); } void Thread::yield() { ::Sleep(0); } void Thread::sleep(int msecs) { ::Sleep(msecs); } /** * Gets a message waiting for it: locks the execution of the program * until a message is received from the operating system. * * @return * True if the @a message parameter was filled (because a message was received) * or false if there aren't more visible @link Frame frames@endlink * to dispatch messages. */ bool Thread::getMessage(Message& message) { ThreadData* data = getThreadData(); // break this loop? (explicit break or no-more visible frames) if (data->breakLoop || data->frames.empty()) return false; // we have to update indicators? if (data->updateIndicators && data->updateIndicatorsMark.elapsed() > 0.1) { data->updateIndicators = false; // for each registered frame we should call updateIndicators to // update the state of all visible indicators (like top-level // items in the menu-bar and buttons in the tool-bar) for (std::vector<Frame*>::iterator it = data->frames.begin(), end = data->frames.end(); it != end; ++it) { (*it)->updateIndicators(); } } // get the message from the queue LPMSG msg = (LPMSG)message; msg->hwnd = NULL; BOOL bRet = ::GetMessage(msg, NULL, 0, 0); // WM_QUIT received? if (bRet == 0) return false; // WM_NULL message... maybe Timers or CallInNextRound if (msg->message == WM_NULL) Timer::pollTimers(); return true; } /** * Gets a message without waiting for it, if the queue is empty, this * method returns false. * * The message is removed from the queue. * * @return * Returns true if the @a msg parameter was filled with the next message * in the queue or false if the queue was empty. */ bool Thread::peekMessage(Message& message) { LPMSG msg = (LPMSG)message; msg->hwnd = NULL; return ::PeekMessage(msg, NULL, 0, 0, PM_REMOVE) != FALSE; } void Thread::processMessage(Message& message) { LPMSG msg = (LPMSG)message; if (!preTranslateMessage(message)) { // Send preTranslateMessage to the active window (useful for // modeless dialogs). WARNING: Don't use GetForegroundWindow // because it returns windows from other applications HWND hactive = GetActiveWindow(); if (hactive != NULL && hactive != msg->hwnd) { Widget* activeWidget = Widget::fromHandle(hactive); if (activeWidget != NULL && activeWidget->preTranslateMessage(message)) return; } //if (!TranslateAccelerator(msg->hwnd, hAccelTable, msg)) //{ ::TranslateMessage(msg); ::DispatchMessage(msg); //} } } /** * Pretranslates the message. The main function is to retrieve the * Widget pointer (using Widget::fromHandle()) and then (if it isn't * NULL), call its Widget#preTranslateMessage. */ bool Thread::preTranslateMessage(Message& message) { LPMSG msg = (LPMSG)message; // TODO process messages that produce a update-indicators event if ((msg->message == WM_ACTIVATE) || (msg->message == WM_CLOSE) || (msg->message == WM_SETFOCUS) || (msg->message == WM_KILLFOCUS) || (msg->message >= WM_LBUTTONDOWN && msg->message <= WM_MBUTTONDBLCLK) || (msg->message >= WM_KEYDOWN && msg->message <= WM_DEADCHAR)) { ThreadData* data = getThreadData(); data->updateIndicators = true; data->updateIndicatorsMark = TimePoint(); } if (msg->hwnd != NULL) { Widget* widget = Widget::fromHandle(msg->hwnd); if (widget && widget->preTranslateMessage(message)) return true; } return false; } void Thread::addFrame(Frame* frame) { getThreadData()->frames.push_back(frame); } void Thread::removeFrame(Frame* frame) { remove_from_container(getThreadData()->frames, frame); // when this thread doesn't have more Frames to continue we must to // break the current message loop if (getThreadData()->frames.empty()) Thread::breakMessageLoop(); } <|endoftext|>
<commit_before>/******************************************************************************* * Copyright 2016 Francesco Calimeri, Davide Fusca', Simona Perri and Jessica Zangari * * 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. *******************************************************************************/ /* * DecompositionOptimizer.cpp * * Created on: May 19, 2017 * Author: jessica */ #include "DecompositionOptimizer.h" #include "DecompositionMapper.h" namespace DLV2 { namespace grounder { void DecompositionOptimizer::decompose() { libraryInstance->treeDecompositionAlgorithmFactory().setConstructionTemplate(new BucketEliminationTreeDecompositionAlgorithm(libraryInstance.get())); IOrderingAlgorithm *orderAlg; switch(Options::globalOptions()->getDecompositionAlgorithm()) { case 0: orderAlg = new MinDegreeOrderingAlgorithm(libraryInstance.get()); break; case 1: orderAlg = new MaximumCardinalitySearchOrderingAlgorithm(libraryInstance.get()); break; case 2: orderAlg = new MinFillOrderingAlgorithm(libraryInstance.get()); break; case 3: orderAlg = new NaturalOrderingAlgorithm(libraryInstance.get()); break; default: orderAlg = new MinDegreeOrderingAlgorithm(libraryInstance.get()); break; } libraryInstance->orderingAlgorithmFactory().setConstructionTemplate(orderAlg); IHypergraph* ruleHypergraph=convertRuleToHypergraph(); FitnessFunction fitnessFunction(this); TreeDecompositionOptimizationOperation* operation=new TreeDecompositionOptimizationOperation(libraryInstance.get(), fitnessFunction); operation->setManagementInstance(libraryInstance.get()); RootingOperation* rootingOperation=new RootingOperation(this); ITreeDecompositionAlgorithm* treeDecompositionAlgorithm=libraryInstance->treeDecompositionAlgorithmFactory().createInstance(); treeDecompositionAlgorithm->addManipulationOperation(rootingOperation); treeDecompositionAlgorithm->addManipulationOperation(operation); IterativeImprovementTreeDecompositionAlgorithm algorithm(libraryInstance.get(),treeDecompositionAlgorithm,fitnessFunction); algorithm.setIterationCount(Options::globalOptions()->getDecompositionIterations()); algorithm.setNonImprovementLimit(Options::globalOptions()->getDecompositionNotImprovementLimit()); size_t optimalBagSize = 0; //unique_ptr<ITreeDecomposition> decomposition(treeDecompositionAlgorithm->computeDecomposition(*ruleHypergraph)); ITreeDecomposition * decomposition = algorithm.computeDecomposition(*ruleHypergraph, [&](const IMultiHypergraph & graph, const ITreeDecomposition & decomposition, const FitnessEvaluation & fitness) { size_t bagSize = fitness.at(1); if (bagSize > optimalBagSize) optimalBagSize = bagSize; } ); // if (decomposition->maximumBagSize() > width) width = decomposition->maximumBagSize(); vector<Rule*> decompositionResultingRules; Rule* decomposedRule; if(convertDecompositionToRules(*decomposition,decomposedRule,decompositionResultingRules)) DecompositionMapper::getInstance()->add(decomposedRule,decompositionResultingRules); delete ruleHypergraph; } bool comp(Term* t1,Term* t2){ return t1->getName()<t2->getName(); } Hypergraph* DecompositionOptimizer::convertRuleToHypergraph() { Hypergraph* hg = new Hypergraph(libraryInstance.get()); sort(variablesInRuleToDecompose.begin(),variablesInRuleToDecompose.end(),comp); firstVertex = hg->addVertices(variablesInRuleToDecompose.size()); for (auto it = variablesInRuleToDecompose.begin(); it != variablesInRuleToDecompose.end(); ++it) mapVertexVariable.insert({*it, (firstVertex + it - variablesInRuleToDecompose.begin())}); vector<vertex_t> head; for (vector<Atom*>::const_iterator it1 = ruleToDecompose->getBeginHead(); it1 != ruleToDecompose->getEndHead(); ++it1) { set_term vars=(*it1)->getVariable(); for (auto it2 = vars.begin(); it2 != vars.end(); ++it2) head.push_back(getVariableId(*it2)); } if(!head.empty()) hg->addEdge(head); for (vector<Atom*>::const_iterator it1 = ruleToDecompose->getBeginBody(); it1 != ruleToDecompose->getEndBody(); ++it1) { vector<vertex_t> edge; set_term vars; if((*it1)->isAggregateAtom()){ vars=(*it1)->getSharedVariable(ruleToDecompose->getBeginBody(),ruleToDecompose->getEndBody()); set_term guards=(*it1)->getGuardVariable(); vars.insert(guards.begin(),guards.end()); } else vars=(*it1)->getVariable(); for (auto it2 = vars.begin(); it2 != vars.end(); ++it2) edge.push_back(getVariableId(*it2)); if(!edge.empty()) hg->addEdge(edge); } return hg; } bool DecompositionOptimizer::convertDecompositionToRules(const ITreeDecomposition& decomposition,Rule*& ruleDecomposed,vector<Rule*>& rules){ vector<pair<vertex_t,unsigned>> verticesRules; verticesRules.push_back({decomposition.root(),0}); visitNode(decomposition.root(), 0, decomposition, verticesRules); unsigned count=0; unordered_map<vertex_t,vector<Atom*>> temporaryChildAtoms; //Build each decomposed rule and ensure its safety for(auto it=verticesRules.rbegin();it!=verticesRules.rend();++it,++count){ vertex_t vertex=it->first; unsigned level=it->second; vertex_t parent=decomposition.parent(vertex); set_term varsInBag; for (auto it1 = decomposition.bagContent(vertex).begin(); it1 != decomposition.bagContent(vertex).end(); ++it1) varsInBag.insert(getIdVariable(*it1)); Rule* newRule=new Rule; vector<Atom*> estratedAtoms; vector<unsigned> estratedAtomsPos; ruleToDecompose->extractAndCloneAtomsInBodyContainingVariables(varsInBag,estratedAtoms,estratedAtomsPos); newRule->setBody(estratedAtoms); for(auto a:temporaryChildAtoms[vertex]) newRule->addInBody(a->clone()); if(level!=0){ string headPredName=DECOMPOSITION_PREDICATES_PREFIX+"_"+to_string(ruleToDecompose->getIndex())+"_"+to_string(count); auto intersectionVertices = decomposition.rememberedVertices(parent, vertex); vector<Term*> headTerms; for (auto it2 = intersectionVertices.begin(); it2 != intersectionVertices.end(); ++it2) headTerms.push_back(getIdVariable(*it2)); Predicate* predicate=new Predicate(headPredName,headTerms.size()); predicate->setHiddenForPrinting(true); predicate->setIdb(); PredicateTable::getInstance()->insertPredicate(predicate); PredicateExtTable::getInstance()->addPredicateExt(predicate); Atom* auxiliaryAtom=new ClassicalLiteral(predicate,headTerms,false,false); newRule->setHead({auxiliaryAtom}); temporaryChildAtoms[parent].push_back(auxiliaryAtom); } else{ for(auto atom:ruleToDecompose->getHead()) newRule->addInHead(atom->clone()); } //Safety check OrderRule order(newRule); bool safe=order.order(); if(!safe){ unordered_set<unsigned> atomsAdded; list<unsigned> toVisit; for(unsigned i=0;i<estratedAtomsPos.size();++i){ for(auto dep:orderRuleToDecompose.getAtomsFromWhichDepends(estratedAtomsPos[i])){ atomsAdded.insert(dep.first); toVisit.push_back(dep.first); } } while(!toVisit.empty()){ unsigned next=toVisit.front(); toVisit.pop_front(); for(auto dep:orderRuleToDecompose.getAtomsFromWhichDepends(next)){ toVisit.push_back(dep.first); atomsAdded.insert(dep.first); } } if(!atomsAdded.empty()){ Rule* newSafeRule=new Rule; string headPredName=DECOMPOSITION_PREDICATES_PREFIX+"_"+DOMAIN_PRED_SUFFIX+"_"+to_string(ruleToDecompose->getIndex())+"_"+to_string(count); vector<Term*> headTerms; for(auto atomPos:atomsAdded) newSafeRule->addInBody(ruleToDecompose->getAtomInBody(atomPos)->clone()); set_term allVars; newRule->getGlobalVariables(allVars); set_term newVars; newSafeRule->getGlobalVariables(newVars); set_term headVars; Utils::intersectionSet(allVars,newVars,headVars); for (auto v:headVars) headTerms.push_back(v); Predicate* predicate=new Predicate(headPredName,headTerms.size()); predicate->setHiddenForPrinting(true); predicate->setIdb(); PredicateTable::getInstance()->insertPredicate(predicate); PredicateExtTable::getInstance()->addPredicateExt(predicate); Atom* auxiliaryAtom=new ClassicalLiteral(predicate,headTerms,false,false); newSafeRule->setHead({auxiliaryAtom}); OrderRule order(newSafeRule); order.order(); newRule->addInBody(auxiliaryAtom->clone()); OrderRule order2(newRule); safe=order2.order(); if(!safe) return false; rules.push_back(newSafeRule); } } if(level!=0) rules.push_back(newRule); else{ newRule->setIndex(ruleToDecompose->getIndex()); ruleDecomposed=newRule; } } return true; } void DecompositionOptimizer::visitNode(vertex_t node,unsigned level,const ITreeDecomposition& decomposition,vector<pair<vertex_t,unsigned>>& verticesRules) const { ConstCollection<vertex_t> children = decomposition.children(node); if (!children.empty()) { unsigned newLevel=++level; for (auto it = children.begin(); it != children.end(); ++it) verticesRules.push_back({*it,newLevel}); for (auto it = children.begin(); it != children.end(); ++it) visitNode(*it, newLevel, decomposition, verticesRules); } } FitnessEvaluation* FitnessFunction::fitness(const IMultiHypergraph & graph, const ITreeDecomposition & decomposition) const { HTD_UNUSED(graph) vector<Rule*> decompositionResultingRules; Rule* decomposedRule=0; decompositionOptimizer->convertDecompositionToRules(decomposition,decomposedRule,decompositionResultingRules); double eval=0; if(decomposedRule!=0){ IntelligentDecomposer::getInstance()->evaluateDecomposition(decomposedRule,decompositionResultingRules.begin(),decompositionResultingRules.end()); for(auto r:decompositionResultingRules) IntelligentDecomposer::getInstance()->cleanTempPredicatesStatistics(r->getAtomInHead(0)->getPredicate()); decomposedRule->free(); delete decomposedRule; } for(auto r:decompositionResultingRules){ r->free(); delete r; } // shared_ptr<FitnessEvaluation> ff(new FitnessEvaluation(1,eval)); return new FitnessEvaluation(1,eval); } } /* namespace grounder */ } /* namespace DLV2 */ <commit_msg>Improved the fitness function<commit_after>/******************************************************************************* * Copyright 2016 Francesco Calimeri, Davide Fusca', Simona Perri and Jessica Zangari * * 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. *******************************************************************************/ /* * DecompositionOptimizer.cpp * * Created on: May 19, 2017 * Author: jessica */ #include "DecompositionOptimizer.h" #include "DecompositionMapper.h" namespace DLV2 { namespace grounder { void DecompositionOptimizer::decompose() { libraryInstance->treeDecompositionAlgorithmFactory().setConstructionTemplate(new BucketEliminationTreeDecompositionAlgorithm(libraryInstance.get())); IOrderingAlgorithm *orderAlg; switch(Options::globalOptions()->getDecompositionAlgorithm()) { case 0: orderAlg = new MinDegreeOrderingAlgorithm(libraryInstance.get()); break; case 1: orderAlg = new MaximumCardinalitySearchOrderingAlgorithm(libraryInstance.get()); break; case 2: orderAlg = new MinFillOrderingAlgorithm(libraryInstance.get()); break; case 3: orderAlg = new NaturalOrderingAlgorithm(libraryInstance.get()); break; default: orderAlg = new MinDegreeOrderingAlgorithm(libraryInstance.get()); break; } libraryInstance->orderingAlgorithmFactory().setConstructionTemplate(orderAlg); IHypergraph* ruleHypergraph=convertRuleToHypergraph(); FitnessFunction fitnessFunction(this); TreeDecompositionOptimizationOperation* operation=new TreeDecompositionOptimizationOperation(libraryInstance.get(), fitnessFunction); operation->setManagementInstance(libraryInstance.get()); RootingOperation* rootingOperation=new RootingOperation(this); ITreeDecompositionAlgorithm* treeDecompositionAlgorithm=libraryInstance->treeDecompositionAlgorithmFactory().createInstance(); treeDecompositionAlgorithm->addManipulationOperation(rootingOperation); treeDecompositionAlgorithm->addManipulationOperation(operation); IterativeImprovementTreeDecompositionAlgorithm algorithm(libraryInstance.get(),treeDecompositionAlgorithm,fitnessFunction); algorithm.setIterationCount(Options::globalOptions()->getDecompositionIterations()); algorithm.setNonImprovementLimit(Options::globalOptions()->getDecompositionNotImprovementLimit()); size_t optimalBagSize = 0; //unique_ptr<ITreeDecomposition> decomposition(treeDecompositionAlgorithm->computeDecomposition(*ruleHypergraph)); ITreeDecomposition * decomposition = algorithm.computeDecomposition(*ruleHypergraph, [&](const IMultiHypergraph & graph, const ITreeDecomposition & decomposition, const FitnessEvaluation & fitness) { size_t bagSize = fitness.at(1); if (bagSize > optimalBagSize) optimalBagSize = bagSize; } ); // if (decomposition->maximumBagSize() > width) width = decomposition->maximumBagSize(); vector<Rule*> decompositionResultingRules; Rule* decomposedRule; if(convertDecompositionToRules(*decomposition,decomposedRule,decompositionResultingRules)) DecompositionMapper::getInstance()->add(decomposedRule,decompositionResultingRules); delete ruleHypergraph; } bool comp(Term* t1,Term* t2){ return t1->getName()<t2->getName(); } Hypergraph* DecompositionOptimizer::convertRuleToHypergraph() { Hypergraph* hg = new Hypergraph(libraryInstance.get()); sort(variablesInRuleToDecompose.begin(),variablesInRuleToDecompose.end(),comp); firstVertex = hg->addVertices(variablesInRuleToDecompose.size()); for (auto it = variablesInRuleToDecompose.begin(); it != variablesInRuleToDecompose.end(); ++it) mapVertexVariable.insert({*it, (firstVertex + it - variablesInRuleToDecompose.begin())}); vector<vertex_t> head; for (vector<Atom*>::const_iterator it1 = ruleToDecompose->getBeginHead(); it1 != ruleToDecompose->getEndHead(); ++it1) { set_term vars=(*it1)->getVariable(); for (auto it2 = vars.begin(); it2 != vars.end(); ++it2) head.push_back(getVariableId(*it2)); } if(!head.empty()) hg->addEdge(head); for (vector<Atom*>::const_iterator it1 = ruleToDecompose->getBeginBody(); it1 != ruleToDecompose->getEndBody(); ++it1) { vector<vertex_t> edge; set_term vars; if((*it1)->isAggregateAtom()){ vars=(*it1)->getSharedVariable(ruleToDecompose->getBeginBody(),ruleToDecompose->getEndBody()); set_term guards=(*it1)->getGuardVariable(); vars.insert(guards.begin(),guards.end()); } else vars=(*it1)->getVariable(); for (auto it2 = vars.begin(); it2 != vars.end(); ++it2) edge.push_back(getVariableId(*it2)); if(!edge.empty()) hg->addEdge(edge); } return hg; } bool DecompositionOptimizer::convertDecompositionToRules(const ITreeDecomposition& decomposition,Rule*& ruleDecomposed,vector<Rule*>& rules){ vector<pair<vertex_t,unsigned>> verticesRules; verticesRules.push_back({decomposition.root(),0}); visitNode(decomposition.root(), 0, decomposition, verticesRules); unsigned count=0; unordered_map<vertex_t,vector<Atom*>> temporaryChildAtoms; //Build each decomposed rule and ensure its safety for(auto it=verticesRules.rbegin();it!=verticesRules.rend();++it,++count){ vertex_t vertex=it->first; unsigned level=it->second; vertex_t parent=decomposition.parent(vertex); set_term varsInBag; for (auto it1 = decomposition.bagContent(vertex).begin(); it1 != decomposition.bagContent(vertex).end(); ++it1) varsInBag.insert(getIdVariable(*it1)); Rule* newRule=new Rule; vector<Atom*> estratedAtoms; vector<unsigned> estratedAtomsPos; ruleToDecompose->extractAndCloneAtomsInBodyContainingVariables(varsInBag,estratedAtoms,estratedAtomsPos); newRule->setBody(estratedAtoms); for(auto a:temporaryChildAtoms[vertex]) newRule->addInBody(a->clone()); if(level!=0){ string headPredName=DECOMPOSITION_PREDICATES_PREFIX+"_"+to_string(ruleToDecompose->getIndex())+"_"+to_string(count); auto intersectionVertices = decomposition.rememberedVertices(parent, vertex); vector<Term*> headTerms; for (auto it2 = intersectionVertices.begin(); it2 != intersectionVertices.end(); ++it2) headTerms.push_back(getIdVariable(*it2)); Predicate* predicate=new Predicate(headPredName,headTerms.size()); predicate->setHiddenForPrinting(true); predicate->setIdb(); PredicateTable::getInstance()->insertPredicate(predicate); PredicateExtTable::getInstance()->addPredicateExt(predicate); Atom* auxiliaryAtom=new ClassicalLiteral(predicate,headTerms,false,false); newRule->setHead({auxiliaryAtom}); temporaryChildAtoms[parent].push_back(auxiliaryAtom); } else{ for(auto atom:ruleToDecompose->getHead()) newRule->addInHead(atom->clone()); } //Safety check OrderRule order(newRule); bool safe=order.order(); if(!safe){ unordered_set<unsigned> atomsAdded; list<unsigned> toVisit; for(unsigned i=0;i<estratedAtomsPos.size();++i){ for(auto dep:orderRuleToDecompose.getAtomsFromWhichDepends(estratedAtomsPos[i])){ atomsAdded.insert(dep.first); toVisit.push_back(dep.first); } } while(!toVisit.empty()){ unsigned next=toVisit.front(); toVisit.pop_front(); for(auto dep:orderRuleToDecompose.getAtomsFromWhichDepends(next)){ toVisit.push_back(dep.first); atomsAdded.insert(dep.first); } } if(!atomsAdded.empty()){ Rule* newSafeRule=new Rule; string headPredName=DECOMPOSITION_PREDICATES_PREFIX+"_"+DOMAIN_PRED_SUFFIX+"_"+to_string(ruleToDecompose->getIndex())+"_"+to_string(count); vector<Term*> headTerms; for(auto atomPos:atomsAdded) newSafeRule->addInBody(ruleToDecompose->getAtomInBody(atomPos)->clone()); set_term allVars; newRule->getGlobalVariables(allVars); set_term newVars; newSafeRule->getGlobalVariables(newVars); set_term headVars; Utils::intersectionSet(allVars,newVars,headVars); for (auto v:headVars) headTerms.push_back(v); Predicate* predicate=new Predicate(headPredName,headTerms.size()); predicate->setHiddenForPrinting(true); predicate->setIdb(); PredicateTable::getInstance()->insertPredicate(predicate); PredicateExtTable::getInstance()->addPredicateExt(predicate); Atom* auxiliaryAtom=new ClassicalLiteral(predicate,headTerms,false,false); newSafeRule->setHead({auxiliaryAtom}); OrderRule order(newSafeRule); order.order(); newRule->addInBody(auxiliaryAtom->clone()); OrderRule order2(newRule); safe=order2.order(); if(!safe) return false; rules.push_back(newSafeRule); } } if(level!=0) rules.push_back(newRule); else{ newRule->setIndex(ruleToDecompose->getIndex()); ruleDecomposed=newRule; } } return true; } void DecompositionOptimizer::visitNode(vertex_t node,unsigned level,const ITreeDecomposition& decomposition,vector<pair<vertex_t,unsigned>>& verticesRules) const { ConstCollection<vertex_t> children = decomposition.children(node); if (!children.empty()) { unsigned newLevel=++level; for (auto it = children.begin(); it != children.end(); ++it) verticesRules.push_back({*it,newLevel}); for (auto it = children.begin(); it != children.end(); ++it) visitNode(*it, newLevel, decomposition, verticesRules); } } FitnessEvaluation* FitnessFunction::fitness(const IMultiHypergraph & graph, const ITreeDecomposition & decomposition) const { HTD_UNUSED(graph) vector<Rule*> decompositionResultingRules; Rule* decomposedRule=0; decompositionOptimizer->convertDecompositionToRules(decomposition,decomposedRule,decompositionResultingRules); double eval=0; if(decomposedRule!=0){ eval=IntelligentDecomposer::getInstance()->evaluateDecomposition(decomposedRule,decompositionResultingRules.begin(),decompositionResultingRules.end()); for(auto r:decompositionResultingRules) IntelligentDecomposer::getInstance()->cleanTempPredicatesStatistics(r->getAtomInHead(0)->getPredicate()); decomposedRule->free(); delete decomposedRule; } for(auto r:decompositionResultingRules){ r->free(); delete r; } // shared_ptr<FitnessEvaluation> ff(new FitnessEvaluation(1,eval)); return new FitnessEvaluation(1,eval); } } /* namespace grounder */ } /* namespace DLV2 */ <|endoftext|>
<commit_before>// Copyright 2017 Neon Edge Game. #include "Turret.h" #include "AIMovingOnGroudGraphicsComponent.h" #include "StageState.h" #include "Gallahad.h" #include "Projectile.h" Turret::Turret(int x, int y): Character(x, y), radius(), looking(1500), idle(1500) { name = "Turret"; graphicsComponent = new AIMovingOnGroudGraphicsComponent("Turret"); box.SetWH(graphicsComponent->GetSize()); attackCD.SetLimit(300); idle.Start(); hitpoints = 2; } Turret::~Turret() { } void Turret::Attack() { // Starts attack timer. attackCD.Start(); // Generates attack object. StageState::AddObject(new Projectile(this, Vec2(0.4, 0), 400, 1, false)); } void Turret::NotifyTileCollision(int tile, GameObject::Face face) { /* if (tile >= SOLID_TILE && (face == LEFT || face == RIGHT)) { if (physicsComponent.velocity.y >= 0.6) { physicsComponent.velocity.y = -0.5; } } */ } void Turret::UpdateTimers(float dt) { Character::UpdateTimers(dt); if (!stunned.IsRunning()) { if (looking.IsRunning()) { looking.Update(dt); if (!looking.IsRunning()) { idle.Start(); } } else if (idle.IsRunning()) { idle.Update(dt); if (!idle.IsRunning()) { looking.Start(); } } } } void Turret::UpdateAI(float dt) { radius = Rect(box.x - 200, box.y - 200, box.w + 400, box.h + 400); if (StageState::GetPlayer()) { if (!stunned.IsRunning()) { Rect player = StageState::GetPlayer()->box; bool visible = true; if (StageState::GetPlayer()->Is("Gallahad")) { Gallahad* g = (Gallahad*) StageState::GetPlayer(); if (g->Hiding()) { visible = false; } } if (player.OverlapsWith(radius) && visible) { if (player.x < box.x ) { physicsComponent.velocity.x -= 0.003 * dt; if (box.x - physicsComponent.velocity.x * dt < player.x) { box.x = player.x; physicsComponent.velocity.x = 0; } facing = LEFT; } else { physicsComponent.velocity.x += 0.003 * dt; if (box.x + physicsComponent.velocity.x * dt > player.x) { box.x = player.x; physicsComponent.velocity.x = 0; } facing = RIGHT; } clamp(physicsComponent.velocity.x, -0.3f, 0.3f); if (!Cooling()) { Attack(); } } else if (looking.IsRunning() && looking.GetElapsed() == 0) { if (facing == LEFT) { physicsComponent.velocity.x = -0.2; } else { physicsComponent.velocity.x = 0.2; } } else { if (idle.IsRunning() && idle.GetElapsed() == 0) { physicsComponent.velocity.x = 0; if (facing == LEFT) { facing = RIGHT; } else { facing = LEFT; } } } } else { physicsComponent.velocity.x = 0; } } } void Turret::Update(TileMap* world, float dt) { UpdateTimers(dt); UpdateAI(dt); physicsComponent.Update(this, world, dt); if (OutOfBounds(world)) { SetPosition(Vec2(startingX, startingY)); } graphicsComponent->Update(this, dt); } bool Turret::Is(std::string type) { return (type == "Enemy"); } <commit_msg>Aplicação 2 das técnicas de comentários em Turret.cpp<commit_after>/** Copyright 2017 Neon Edge Game File Name: Turret.cpp Header File Name: Turret.h Class Name: Turret Objective: Defines the behavior and actions of a Turret. */ #include "Turret.h" #include "AIMovingOnGroudGraphicsComponent.h" #include "StageState.h" #include "Gallahad.h" #include "Projectile.h" /** Objective: Constructor of the class Turret. @param int x - Size in x of the Turret. @param int y - Size in y of the Turret. @return instance of Turret. */ Turret::Turret(int x, int y): Character(x, y), radius(), looking(1500), idle(1500) { name = "Turret"; graphicsComponent = new AIMovingOnGroudGraphicsComponent("Turret"); box.SetWH(graphicsComponent->GetSize()); attackCD.SetLimit(300); idle.Start(); hitpoints = 2; } /** Objective: Destructor of the class Turret. @param none. @return none. */ Turret::~Turret() { } /** Objective: Starts the Turret attack, generating attack object (projectile). @param none. @return none. */ void Turret::Attack() { attackCD.Start(); StageState::AddObject(new Projectile(this, Vec2(0.4, 0), 400, 1, false)); } /** Objective: none. @param int tile. @param Face face - Short int indicating the facing of the GameObject. @return none. */ void Turret::NotifyTileCollision(int tile, GameObject::Face face) { } /** Objective: Updates the timers of 'looking' state and 'idle' state. @param float dt - Amount of time the tower remains in the 'looking' and 'idle' state. @return none. */ void Turret::UpdateTimers(float dt) { Character::UpdateTimers(dt); if (!stunned.IsRunning()) { if (looking.IsRunning()) { looking.Update(dt); if (!looking.IsRunning()) { idle.Start(); } } else if (idle.IsRunning()) { idle.Update(dt); if (!idle.IsRunning()) { looking.Start(); } } } } /** Objective: Updates the AI of the Turret, from a radius. @param float dt - The amount of time the Turret updates its graphics. @return none. */ void Turret::UpdateAI(float dt) { // Defines the radius of vision of the Turret as a rectangle. radius = Rect(box.x - 200, box.y - 200, box.w + 400, box.h + 400); if (StageState::GetPlayer()) { if (!stunned.IsRunning()) { Rect player = StageState::GetPlayer()->box; bool visible = true; // If the player is the galahad and if it is invisible, the visibility is false and the Turret does not attack. if (StageState::GetPlayer()->Is("Gallahad")) { Gallahad* g = (Gallahad*) StageState::GetPlayer(); if (g->Hiding()) { visible = false; } } // Does not allow the Turret to track the player instantly. if (player.OverlapsWith(radius) && visible) { if (player.x < box.x ) { physicsComponent.velocity.x -= 0.003 * dt; // Sets the speed at x of the Turret less than the velocity at x of the player if (box.x - physicsComponent.velocity.x * dt < player.x) { box.x = player.x; physicsComponent.velocity.x = 0; } facing = LEFT; // } else { physicsComponent.velocity.x += 0.003 * dt; if (box.x + physicsComponent.velocity.x * dt > player.x) { box.x = player.x; physicsComponent.velocity.x = 0; } facing = RIGHT; } clamp(physicsComponent.velocity.x, -0.3f, 0.3f); if (!Cooling()) { Attack(); } } else if (looking.IsRunning() && looking.GetElapsed() == 0) { if (facing == LEFT) { physicsComponent.velocity.x = -0.2; // Sets the speed at x of the Turret when in 'looking' state and facing left. } else { physicsComponent.velocity.x = 0.2; // Sets the speed at x of the Turret when in 'looking' state and facing right. } } else { if (idle.IsRunning() && idle.GetElapsed() == 0) { physicsComponent.velocity.x = 0; if (facing == LEFT) { facing = RIGHT; } else { facing = LEFT; } } } } else { physicsComponent.velocity.x = 0; } } } /** Objective: Function responsible to update Turret GameObject, but overloaded with the world object. @param TileMap* world. @param float dt - Time the tower updates its timers, in nanoseconds. @return none. */ void Turret::Update(TileMap* world, float dt) { UpdateTimers(dt); UpdateAI(dt); physicsComponent.Update(this, world, dt); // If the tower is outside the boundaries of the map, its position is resetted. if (OutOfBounds(world)) { SetPosition(Vec2(startingX, startingY)); } graphicsComponent->Update(this, dt); } /** Objective: Returns the Turret type. A turret is a Enemy. @param string type - Type of the turret (enemy or player). @return string type. */ bool Turret::Is(std::string type) { return (type == "Enemy"); } <|endoftext|>
<commit_before>/* * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji * * 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 <memory> #include <vector> #include <bcc/BPF.h> extern "C" { #include <unistd.h> #include <stdarg.h> #include <sys/time.h> #include "h2o/memory.h" #include "h2o/version.h" } #include "h2olog.h" #define POLL_TIMEOUT (1000) #define PERF_BUFFER_PAGE_COUNT 256 static void usage(void) { printf(R"(h2olog (h2o v%s) Usage: h2olog -p PID h2olog quic -p PID h2olog quic -s response_header_name -p PID Other options: -h Print this help and exit -d Print debugging information (-dd shows more) -w Path to write the output (default: stdout) )", H2O_VERSION); return; } static void make_timestamp(char *buf, size_t buf_len) { time_t t = time(NULL); struct tm tms; localtime_r(&t, &tms); const char *iso8601format = "%FT%TZ"; strftime(buf, buf_len, iso8601format, &tms); } static void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static void infof(const char *fmt, ...) { char buf[1024]; va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); char timestamp[128]; make_timestamp(timestamp, sizeof(timestamp)); fprintf(stderr, "%s %s\n", timestamp, buf); } uint64_t h2o_tracer::time_milliseconds() { struct timeval tv; gettimeofday(&tv, NULL); return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000; } void h2o_tracer::show_event_per_sec(time_t *t0) { time_t t1 = time(NULL); int64_t d = t1 - *t0; if (d > 10) { uint64_t c = stats_.num_events / d; if (c > 0) { if (stats_.num_lost > 0) { infof("%20" PRIu64 " events/s (possibly lost %" PRIu64 " events)", c, stats_.num_lost); stats_.num_lost = 0; } else { infof("%20" PRIu64 " events/s", c); } stats_.num_events = 0; } *t0 = t1; } } static void show_process(pid_t pid) { char cmdline[256]; char proc_file[256]; snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid); FILE *f = fopen(proc_file, "r"); if (f == nullptr) { fprintf(stderr, "Error: failed to open %s: %s\n", proc_file, strerror(errno)); exit(EXIT_FAILURE); } size_t nread = fread(cmdline, 1, sizeof(cmdline), f); fclose(f); if (nread == 0) { fprintf(stderr, "Error: failed to read from %s: %s\n", proc_file, strerror(errno)); exit(EXIT_FAILURE); } nread--; // skip trailing nul for (size_t i = 0; i < nread; i++) { if (cmdline[i] == '\0') { cmdline[i] = ' '; } } infof("Attaching pid=%d (%s)", pid, cmdline); } static std::string join_str(const std::string &sep, const std::vector<std::string> &strs) { std::string s; for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) { if (iter != strs.cbegin()) { s += sep; } s += *iter; } return s; } static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens) { std::vector<std::string> conditions; for (auto &token : tokens) { char buf[256]; snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size()); std::vector<std::string> exprs = {buf}; for (size_t i = 0; i < token.size(); ++i) { snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]); exprs.push_back(buf); } conditions.push_back("(" + join_str(" && ", exprs) + ")"); } std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=("); cflag += join_str(" || ", conditions); cflag += ")"; return cflag; } static std::string make_pid_cflag(const char *macro_name, pid_t pid) { char buf[256]; snprintf(buf, sizeof(buf), "-D%s=%d", macro_name, pid); return std::string(buf); } static void event_cb(void *context, void *data, int len) { h2o_tracer *tracer = (h2o_tracer *)context; tracer->handle_event(data, len); } static void lost_cb(void *context, uint64_t lost) { h2o_tracer *tracer = (h2o_tracer *)context; tracer->handle_lost(lost); } int main(int argc, char **argv) { std::unique_ptr<h2o_tracer> tracer; if (argc > 1 && strcmp(argv[1], "quic") == 0) { tracer.reset(create_quic_tracer()); --argc; ++argv; } else { tracer.reset(create_http_tracer()); } int debug = 0; FILE *outfp = stdout; std::vector<std::string> event_type_filters; std::vector<std::string> response_header_filters; int c; pid_t h2o_pid = -1; while ((c = getopt(argc, argv, "hdp:t:s:w:")) != -1) { switch (c) { case 'p': h2o_pid = atoi(optarg); break; case 't': event_type_filters.push_back(optarg); break; case 's': response_header_filters.push_back(optarg); break; case 'w': if ((outfp = fopen(optarg, "w")) == nullptr) { fprintf(stderr, "Error: failed to open %s: %s", optarg, strerror(errno)); exit(EXIT_FAILURE); } break; case 'd': debug++; break; case 'h': usage(); exit(EXIT_SUCCESS); default: usage(); exit(EXIT_FAILURE); } } if (argc > optind) { fprintf(stderr, "Error: too many aruments\n"); usage(); exit(EXIT_FAILURE); } if (h2o_pid == -1) { fprintf(stderr, "Error: -p option is missing\n"); usage(); exit(EXIT_FAILURE); } if (geteuid() != 0) { fprintf(stderr, "Error: root privilege is required\n"); exit(EXIT_FAILURE); } tracer->init(outfp); std::vector<std::string> cflags({ make_pid_cflag("H2OLOG_H2O_PID", h2o_pid), }); if (!response_header_filters.empty()) { cflags.push_back(generate_header_filter_cflag(response_header_filters)); } if (debug >= 2) { fprintf(stderr, "cflags="); for (size_t i = 0; i < cflags.size(); i++) { if (i > 0) { fprintf(stderr, " "); } fprintf(stderr, "%s", cflags[i].c_str()); } fprintf(stderr, "\n"); fprintf(stderr, "<BPF>\n%s\n</BPF>\n", tracer->bpf_text().c_str()); } ebpf::BPF *bpf = new ebpf::BPF(); const std::vector<h2o_tracer::usdt> probe_defs = tracer->usdt_probes(); std::vector<ebpf::USDT> probes; for (const auto &probe_defs : probe_defs) { probes.push_back(ebpf::USDT(h2o_pid, probe_defs.provider, probe_defs.name, probe_defs.probe_func)); } ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes); if (ret.code() != 0) { fprintf(stderr, "Error: init: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } bpf->attach_tracepoint("sched:sched_process_exit", "trace_sched_process_exit"); for (auto &probe : probes) { ret = bpf->attach_usdt(probe); if (ret.code() != 0) { fprintf(stderr, "Error: attach_usdt: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } } ret = bpf->open_perf_buffer("events", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT); if (ret.code() != 0) { fprintf(stderr, "Error: open_perf_buffer: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } if (debug) { show_process(h2o_pid); } ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events"); if (perf_buffer) { time_t t0 = time(NULL); while (true) { perf_buffer->poll(POLL_TIMEOUT); tracer->flush(); if (debug) { tracer->show_event_per_sec(&t0); } } } fprintf(stderr, "Error: failed to get_perf_buffer()\n"); return EXIT_FAILURE; } <commit_msg>h2olog: implement -t option to filter events<commit_after>/* * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji * * 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 <memory> #include <vector> #include <algorithm> #include <bcc/BPF.h> extern "C" { #include <unistd.h> #include <stdarg.h> #include <sys/time.h> #include "h2o/memory.h" #include "h2o/version.h" } #include "h2olog.h" #define POLL_TIMEOUT (1000) #define PERF_BUFFER_PAGE_COUNT 256 static void usage(void) { printf(R"(h2olog (h2o v%s) Usage: h2olog -p PID h2olog quic -p PID Optional arguments: -t EVENT_TYPES Fully-qualified probe names to show, joined by a comma, e.g. "quicly:accept,quicly:free" -s RESPONSE_HEADER_NAMES Response header names to show, joined by a comma, e.g. "content-type" (case-insensitive) -h Print this help and exit -d Print debugging information (-dd shows more) -w Path to write the output (default: stdout) Examples: h2olog quic -p $(pgrep -o h2o) h2olog quic -p $(pgrep -o h2o) -t quicly:accept,quicly:free h2olog quic -p $(pgrep -o h2o) -t h2o:send_response_header,h2o:h3s_accept,h2o:h3s_destroy -s alt-svc )", H2O_VERSION); return; } static void make_timestamp(char *buf, size_t buf_len) { time_t t = time(NULL); struct tm tms; localtime_r(&t, &tms); const char *iso8601format = "%FT%TZ"; strftime(buf, buf_len, iso8601format, &tms); } static void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2))); static void infof(const char *fmt, ...) { char buf[1024]; va_list args; va_start(args, fmt); vsnprintf(buf, sizeof(buf), fmt, args); va_end(args); char timestamp[128]; make_timestamp(timestamp, sizeof(timestamp)); fprintf(stderr, "%s %s\n", timestamp, buf); } uint64_t h2o_tracer::time_milliseconds() { struct timeval tv; gettimeofday(&tv, NULL); return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000; } void h2o_tracer::show_event_per_sec(time_t *t0) { time_t t1 = time(NULL); int64_t d = t1 - *t0; if (d > 10) { uint64_t c = stats_.num_events / d; if (c > 0) { if (stats_.num_lost > 0) { infof("%20" PRIu64 " events/s (possibly lost %" PRIu64 " events)", c, stats_.num_lost); stats_.num_lost = 0; } else { infof("%20" PRIu64 " events/s", c); } stats_.num_events = 0; } *t0 = t1; } } static void show_process(pid_t pid) { char cmdline[256]; char proc_file[256]; snprintf(proc_file, sizeof(proc_file), "/proc/%d/cmdline", pid); FILE *f = fopen(proc_file, "r"); if (f == nullptr) { fprintf(stderr, "Error: failed to open %s: %s\n", proc_file, strerror(errno)); exit(EXIT_FAILURE); } size_t nread = fread(cmdline, 1, sizeof(cmdline), f); fclose(f); if (nread == 0) { fprintf(stderr, "Error: failed to read from %s: %s\n", proc_file, strerror(errno)); exit(EXIT_FAILURE); } nread--; // skip trailing nul for (size_t i = 0; i < nread; i++) { if (cmdline[i] == '\0') { cmdline[i] = ' '; } } infof("Attaching pid=%d (%s)", pid, cmdline); } static const std::string join_str(const std::string &sep, const std::vector<std::string> &strs) { std::string s; for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) { if (iter != strs.cbegin()) { s += sep; } s += *iter; } return s; } static const std::vector<std::string> split_str(char delim, const std::string &s) { std::vector<std::string> tokens; std::size_t from = 0; for (std::size_t i = 0; i < s.size(); ++i) { if (s[i] == delim) { tokens.push_back(s.substr(from, i - from)); from = i + 1; } } if (from <= s.size()) { tokens.push_back(s.substr(from, s.size())); } return tokens; } static std::string generate_header_filter_cflag(const std::vector<std::string> &tokens) { std::vector<std::string> conditions; for (auto &token : tokens) { char buf[256]; snprintf(buf, sizeof(buf), "/* %s */ (slen) == %zu", token.c_str(), token.size()); std::vector<std::string> exprs = {buf}; for (size_t i = 0; i < token.size(); ++i) { snprintf(buf, sizeof(buf), "(s)[%zu] == '%c'", i, token[i]); exprs.push_back(buf); } conditions.push_back("(" + join_str(" && ", exprs) + ")"); } std::string cflag("-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=("); cflag += join_str(" || ", conditions); cflag += ")"; return cflag; } static std::string make_pid_cflag(const char *macro_name, pid_t pid) { char buf[256]; snprintf(buf, sizeof(buf), "-D%s=%d", macro_name, pid); return std::string(buf); } static void event_cb(void *context, void *data, int len) { h2o_tracer *tracer = (h2o_tracer *)context; tracer->handle_event(data, len); } static void lost_cb(void *context, uint64_t lost) { h2o_tracer *tracer = (h2o_tracer *)context; tracer->handle_lost(lost); } int main(int argc, char **argv) { std::unique_ptr<h2o_tracer> tracer; if (argc > 1 && strcmp(argv[1], "quic") == 0) { tracer.reset(create_quic_tracer()); --argc; ++argv; } else { tracer.reset(create_http_tracer()); } int debug = 0; FILE *outfp = stdout; std::vector<std::string> event_type_filters; std::vector<std::string> response_header_filters; int c; pid_t h2o_pid = -1; while ((c = getopt(argc, argv, "hdp:t:s:w:")) != -1) { switch (c) { case 'p': h2o_pid = atoi(optarg); break; case 't': for (const auto &item : split_str(',', optarg)) { event_type_filters.push_back(item); } break; case 's': for (const auto &item : split_str(',', optarg)) { response_header_filters.push_back(item); } break; case 'w': if ((outfp = fopen(optarg, "w")) == nullptr) { fprintf(stderr, "Error: failed to open %s: %s", optarg, strerror(errno)); exit(EXIT_FAILURE); } break; case 'd': debug++; break; case 'h': usage(); exit(EXIT_SUCCESS); default: usage(); exit(EXIT_FAILURE); } } if (argc > optind) { fprintf(stderr, "Error: too many aruments\n"); usage(); exit(EXIT_FAILURE); } if (h2o_pid == -1) { fprintf(stderr, "Error: -p option is missing\n"); usage(); exit(EXIT_FAILURE); } if (geteuid() != 0) { fprintf(stderr, "Error: root privilege is required\n"); exit(EXIT_FAILURE); } tracer->init(outfp); std::vector<std::string> cflags({ make_pid_cflag("H2OLOG_H2O_PID", h2o_pid), }); if (!response_header_filters.empty()) { cflags.push_back(generate_header_filter_cflag(response_header_filters)); } if (debug >= 2) { fprintf(stderr, "event_type_filters="); for (size_t i = 0; i < event_type_filters.size(); i++) { if (i > 0) { fprintf(stderr, ","); } fprintf(stderr, "%s", event_type_filters[i].c_str()); } fprintf(stderr, "\n"); fprintf(stderr, "cflags="); for (size_t i = 0; i < cflags.size(); i++) { if (i > 0) { fprintf(stderr, " "); } fprintf(stderr, "%s", cflags[i].c_str()); } fprintf(stderr, "\n"); fprintf(stderr, "<BPF>\n%s\n</BPF>\n", tracer->bpf_text().c_str()); } ebpf::BPF *bpf = new ebpf::BPF(); std::vector<ebpf::USDT> probes; for (const auto &probe_def : tracer->usdt_probes()) { if (event_type_filters.empty() || std::find(event_type_filters.cbegin(), event_type_filters.cend(), probe_def.provider + ":" + probe_def.name) != event_type_filters.cend()) { probes.push_back(ebpf::USDT(h2o_pid, probe_def.provider, probe_def.name, probe_def.probe_func)); } } ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes); if (ret.code() != 0) { fprintf(stderr, "Error: init: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } bpf->attach_tracepoint("sched:sched_process_exit", "trace_sched_process_exit"); for (auto &probe : probes) { ret = bpf->attach_usdt(probe); if (ret.code() != 0) { fprintf(stderr, "Error: attach_usdt: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } } ret = bpf->open_perf_buffer("events", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT); if (ret.code() != 0) { fprintf(stderr, "Error: open_perf_buffer: %s\n", ret.msg().c_str()); return EXIT_FAILURE; } if (debug) { show_process(h2o_pid); } ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer("events"); if (perf_buffer) { time_t t0 = time(NULL); while (true) { perf_buffer->poll(POLL_TIMEOUT); tracer->flush(); if (debug) { tracer->show_event_per_sec(&t0); } } } fprintf(stderr, "Error: failed to get_perf_buffer()\n"); return EXIT_FAILURE; } <|endoftext|>
<commit_before>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.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. */ /* -------------------------------------------------------------------------- */ /* ************************************************************************** */ /* Host Pool */ /* ************************************************************************** */ #include "HostPool.h" #include "Nebula.h" int HostPool::allocate ( int * oid, string hostname, string im_mad_name, string vmm_mad_name, string tm_mad_name) { Host * host; // Build a new Host object host = new Host(-1, hostname, im_mad_name, vmm_mad_name, tm_mad_name); // Insert the Object in the pool *oid = PoolSQL::allocate(host); return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ extern "C" { static int discover_cb ( void * _discovered_hosts, int num, char ** values, char ** names) { map<int, string> * discovered_hosts; string im_mad(values[1]); int hid; discovered_hosts = static_cast<map<int, string> *>(_discovered_hosts); if ( (discovered_hosts == 0) || (num<=0) || (values[0] == 0) ) { return -1; } hid = atoi(values[0]); im_mad = values[1]; discovered_hosts->insert(make_pair(hid,im_mad)); return 0; }; } /* -------------------------------------------------------------------------- */ int HostPool::discover(map<int, string> * discovered_hosts) { ostringstream sql; int rc; lock(); sql << "SELECT oid, im_mad FROM " << Host::table << " ORDER BY last_mon_time LIMIT 10"; rc = db->exec(sql,discover_cb,(void *) discovered_hosts); unlock(); return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <commit_msg>Bug #208: HostPool::discover filter outs disabled hosts (cherry picked from commit 0ecd07d8efa3cf39d739d65481046f344b7f4c2c)<commit_after>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2010, OpenNebula Project Leads (OpenNebula.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. */ /* -------------------------------------------------------------------------- */ /* ************************************************************************** */ /* Host Pool */ /* ************************************************************************** */ #include "HostPool.h" #include "Nebula.h" int HostPool::allocate ( int * oid, string hostname, string im_mad_name, string vmm_mad_name, string tm_mad_name) { Host * host; // Build a new Host object host = new Host(-1, hostname, im_mad_name, vmm_mad_name, tm_mad_name); // Insert the Object in the pool *oid = PoolSQL::allocate(host); return 0; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ extern "C" { static int discover_cb ( void * _discovered_hosts, int num, char ** values, char ** names) { map<int, string> * discovered_hosts; string im_mad(values[1]); int hid; discovered_hosts = static_cast<map<int, string> *>(_discovered_hosts); if ( (discovered_hosts == 0) || (num<=0) || (values[0] == 0) ) { return -1; } hid = atoi(values[0]); im_mad = values[1]; discovered_hosts->insert(make_pair(hid,im_mad)); return 0; }; } /* -------------------------------------------------------------------------- */ int HostPool::discover(map<int, string> * discovered_hosts) { ostringstream sql; int rc; lock(); sql << "SELECT oid, im_mad FROM " << Host::table << " WHERE state != " << Host::DISABLED << " ORDER BY last_mon_time LIMIT 10"; rc = db->exec(sql,discover_cb,(void *) discovered_hosts); unlock(); return rc; } /* -------------------------------------------------------------------------- */ /* -------------------------------------------------------------------------- */ <|endoftext|>
<commit_before>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "schema_fwd.hh" #include "query-request.hh" #include "mutation_fragment.hh" #include "partition_version.hh" #include "tracing/tracing.hh" #include "row_cache.hh" namespace cache { /* * Represent a flat reader to the underlying source. * This reader automatically makes sure that it's up to date with all cache updates */ class autoupdating_underlying_reader final { row_cache& _cache; read_context& _read_context; flat_mutation_reader_opt _reader; utils::phased_barrier::phase_type _reader_creation_phase = 0; dht::partition_range _range = { }; std::optional<dht::decorated_key> _last_key; std::optional<dht::decorated_key> _new_last_key; public: autoupdating_underlying_reader(row_cache& cache, read_context& context) : _cache(cache) , _read_context(context) { } future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) { _last_key = std::move(_new_last_key); auto start = population_range_start(); auto phase = _cache.phase_of(start); if (!_reader || _reader_creation_phase != phase) { if (_last_key) { auto cmp = dht::ring_position_comparator(*_cache._schema); auto&& new_range = _range.split_after(*_last_key, cmp); if (!new_range) { _reader = {}; return make_ready_future<mutation_fragment_opt>(); } _range = std::move(*new_range); _last_key = {}; } if (_reader) { ++_cache._tracker._stats.underlying_recreations; } auto& snap = _cache.snapshot_for_phase(phase); _reader = {}; // See issue #2644 _reader = _cache.create_underlying_reader(_read_context, snap, _range); _reader_creation_phase = phase; } return _reader->next_partition().then([this, timeout] { if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) { return make_ready_future<mutation_fragment_opt>(); } return (*_reader)(timeout).then([this] (auto&& mfopt) { if (mfopt) { assert(mfopt->is_partition_start()); _new_last_key = mfopt->as_partition_start().key(); } return std::move(mfopt); }); }); } future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) { auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range)); return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout); } future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) { _range = std::move(range); _last_key = { }; _new_last_key = { }; if (_reader) { if (_reader_creation_phase == phase) { ++_cache._tracker._stats.underlying_partition_skips; return _reader->fast_forward_to(_range, timeout); } else { ++_cache._tracker._stats.underlying_recreations; _reader = {}; // See issue #2644 } } _reader = _cache.create_underlying_reader(_read_context, snapshot, _range); _reader_creation_phase = phase; return make_ready_future<>(); } utils::phased_barrier::phase_type creation_phase() const { return _reader_creation_phase; } const dht::partition_range& range() const { return _range; } flat_mutation_reader& underlying() { return *_reader; } dht::ring_position_view population_range_start() const { return _last_key ? dht::ring_position_view::for_after_key(*_last_key) : dht::ring_position_view::for_range_start(_range); } }; class read_context final : public enable_lw_shared_from_this<read_context> { row_cache& _cache; schema_ptr _schema; reader_permit _permit; const dht::partition_range& _range; const query::partition_slice& _slice; const io_priority_class& _pc; tracing::trace_state_ptr _trace_state; mutation_reader::forwarding _fwd_mr; bool _range_query; // When reader enters a partition, it must be set up for reading that // partition from the underlying mutation source (_underlying) in one of two ways: // // 1) either _underlying is already in that partition // // 2) _underlying is before the partition, then _underlying_snapshot and _key // are set so that _underlying_flat can be fast forwarded to the right partition. // autoupdating_underlying_reader _underlying; uint64_t _underlying_created = 0; mutation_source_opt _underlying_snapshot; dht::partition_range _sm_range; std::optional<dht::decorated_key> _key; bool _partition_exists; row_cache::phase_type _phase; public: read_context(row_cache& cache, schema_ptr schema, reader_permit permit, const dht::partition_range& range, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, mutation_reader::forwarding fwd_mr) : _cache(cache) , _schema(std::move(schema)) , _permit(std::move(permit)) , _range(range) , _slice(slice) , _pc(pc) , _trace_state(std::move(trace_state)) , _fwd_mr(fwd_mr) , _range_query(!query::is_single_partition(range)) , _underlying(_cache, *this) { ++_cache._tracker._stats.reads; if (!_range_query) { _key = range.start()->value().as_decorated_key(); } } ~read_context() { ++_cache._tracker._stats.reads_done; if (_underlying_created) { _cache._stats.reads_with_misses.mark(); ++_cache._tracker._stats.reads_with_misses; } else { _cache._stats.reads_with_no_misses.mark(); } } read_context(const read_context&) = delete; row_cache& cache() { return _cache; } const schema_ptr& schema() const { return _schema; } reader_permit permit() const { return _permit; } const dht::partition_range& range() const { return _range; } const query::partition_slice& slice() const { return _slice; } const io_priority_class& pc() const { return _pc; } tracing::trace_state_ptr trace_state() const { return _trace_state; } mutation_reader::forwarding fwd_mr() const { return _fwd_mr; } bool is_range_query() const { return _range_query; } autoupdating_underlying_reader& underlying() { return _underlying; } row_cache::phase_type phase() const { return _phase; } const dht::decorated_key& key() const { return *_key; } bool partition_exists() const { return _partition_exists; } void on_underlying_created() { ++_underlying_created; } bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); } public: future<> ensure_underlying(db::timeout_clock::time_point timeout) { if (_underlying_snapshot) { return create_underlying(timeout).then([this, timeout] { return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) { _partition_exists = bool(mfopt); }); }); } // We know that partition exists because all the callers of // enter_partition(const dht::decorated_key&, row_cache::phase_type) // check that and there's no other way of setting _underlying_snapshot // to empty. Except for calling create_underlying. _partition_exists = true; return make_ready_future<>(); } public: future<> create_underlying(db::timeout_clock::time_point timeout); void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) { _phase = phase; _underlying_snapshot = snapshot; _key = dk; } // Precondition: each caller needs to make sure that partition with |dk| key // exists in underlying before calling this function. void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) { _phase = phase; _underlying_snapshot = {}; _key = dk; } }; } <commit_msg>row_cache: autoupdating_underlying_reader: close reader before updating it<commit_after>/* * Copyright (C) 2017 ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "schema_fwd.hh" #include "query-request.hh" #include "mutation_fragment.hh" #include "partition_version.hh" #include "tracing/tracing.hh" #include "row_cache.hh" namespace cache { /* * Represent a flat reader to the underlying source. * This reader automatically makes sure that it's up to date with all cache updates */ class autoupdating_underlying_reader final { row_cache& _cache; read_context& _read_context; flat_mutation_reader_opt _reader; utils::phased_barrier::phase_type _reader_creation_phase = 0; dht::partition_range _range = { }; std::optional<dht::decorated_key> _last_key; std::optional<dht::decorated_key> _new_last_key; future<> close_reader() noexcept { return _reader ? _reader->close() : make_ready_future<>(); } public: autoupdating_underlying_reader(row_cache& cache, read_context& context) : _cache(cache) , _read_context(context) { } future<mutation_fragment_opt> move_to_next_partition(db::timeout_clock::time_point timeout) { _last_key = std::move(_new_last_key); auto start = population_range_start(); auto phase = _cache.phase_of(start); auto refresh_reader = make_ready_future<>(); if (!_reader || _reader_creation_phase != phase) { if (_last_key) { auto cmp = dht::ring_position_comparator(*_cache._schema); auto&& new_range = _range.split_after(*_last_key, cmp); if (!new_range) { return close_reader().then([] { return make_ready_future<mutation_fragment_opt>(); }); } _range = std::move(*new_range); _last_key = {}; } if (_reader) { ++_cache._tracker._stats.underlying_recreations; } refresh_reader = close_reader().then([this, phase] { _reader = _cache.create_underlying_reader(_read_context, _cache.snapshot_for_phase(phase), _range); _reader_creation_phase = phase; }); } return refresh_reader.then([this, timeout] { return _reader->next_partition().then([this, timeout] { if (_reader->is_end_of_stream() && _reader->is_buffer_empty()) { return make_ready_future<mutation_fragment_opt>(); } return (*_reader)(timeout).then([this] (auto&& mfopt) { if (mfopt) { assert(mfopt->is_partition_start()); _new_last_key = mfopt->as_partition_start().key(); } return std::move(mfopt); }); }); }); } future<> fast_forward_to(dht::partition_range&& range, db::timeout_clock::time_point timeout) { auto snapshot_and_phase = _cache.snapshot_of(dht::ring_position_view::for_range_start(_range)); return fast_forward_to(std::move(range), snapshot_and_phase.snapshot, snapshot_and_phase.phase, timeout); } future<> fast_forward_to(dht::partition_range&& range, mutation_source& snapshot, row_cache::phase_type phase, db::timeout_clock::time_point timeout) { _range = std::move(range); _last_key = { }; _new_last_key = { }; if (_reader) { if (_reader_creation_phase == phase) { ++_cache._tracker._stats.underlying_partition_skips; return _reader->fast_forward_to(_range, timeout); } else { ++_cache._tracker._stats.underlying_recreations; } } return close_reader().then([this, &snapshot, phase] { _reader = _cache.create_underlying_reader(_read_context, snapshot, _range); _reader_creation_phase = phase; }); } utils::phased_barrier::phase_type creation_phase() const { return _reader_creation_phase; } const dht::partition_range& range() const { return _range; } flat_mutation_reader& underlying() { return *_reader; } dht::ring_position_view population_range_start() const { return _last_key ? dht::ring_position_view::for_after_key(*_last_key) : dht::ring_position_view::for_range_start(_range); } }; class read_context final : public enable_lw_shared_from_this<read_context> { row_cache& _cache; schema_ptr _schema; reader_permit _permit; const dht::partition_range& _range; const query::partition_slice& _slice; const io_priority_class& _pc; tracing::trace_state_ptr _trace_state; mutation_reader::forwarding _fwd_mr; bool _range_query; // When reader enters a partition, it must be set up for reading that // partition from the underlying mutation source (_underlying) in one of two ways: // // 1) either _underlying is already in that partition // // 2) _underlying is before the partition, then _underlying_snapshot and _key // are set so that _underlying_flat can be fast forwarded to the right partition. // autoupdating_underlying_reader _underlying; uint64_t _underlying_created = 0; mutation_source_opt _underlying_snapshot; dht::partition_range _sm_range; std::optional<dht::decorated_key> _key; bool _partition_exists; row_cache::phase_type _phase; public: read_context(row_cache& cache, schema_ptr schema, reader_permit permit, const dht::partition_range& range, const query::partition_slice& slice, const io_priority_class& pc, tracing::trace_state_ptr trace_state, mutation_reader::forwarding fwd_mr) : _cache(cache) , _schema(std::move(schema)) , _permit(std::move(permit)) , _range(range) , _slice(slice) , _pc(pc) , _trace_state(std::move(trace_state)) , _fwd_mr(fwd_mr) , _range_query(!query::is_single_partition(range)) , _underlying(_cache, *this) { ++_cache._tracker._stats.reads; if (!_range_query) { _key = range.start()->value().as_decorated_key(); } } ~read_context() { ++_cache._tracker._stats.reads_done; if (_underlying_created) { _cache._stats.reads_with_misses.mark(); ++_cache._tracker._stats.reads_with_misses; } else { _cache._stats.reads_with_no_misses.mark(); } } read_context(const read_context&) = delete; row_cache& cache() { return _cache; } const schema_ptr& schema() const { return _schema; } reader_permit permit() const { return _permit; } const dht::partition_range& range() const { return _range; } const query::partition_slice& slice() const { return _slice; } const io_priority_class& pc() const { return _pc; } tracing::trace_state_ptr trace_state() const { return _trace_state; } mutation_reader::forwarding fwd_mr() const { return _fwd_mr; } bool is_range_query() const { return _range_query; } autoupdating_underlying_reader& underlying() { return _underlying; } row_cache::phase_type phase() const { return _phase; } const dht::decorated_key& key() const { return *_key; } bool partition_exists() const { return _partition_exists; } void on_underlying_created() { ++_underlying_created; } bool digest_requested() const { return _slice.options.contains<query::partition_slice::option::with_digest>(); } public: future<> ensure_underlying(db::timeout_clock::time_point timeout) { if (_underlying_snapshot) { return create_underlying(timeout).then([this, timeout] { return _underlying.underlying()(timeout).then([this] (mutation_fragment_opt&& mfopt) { _partition_exists = bool(mfopt); }); }); } // We know that partition exists because all the callers of // enter_partition(const dht::decorated_key&, row_cache::phase_type) // check that and there's no other way of setting _underlying_snapshot // to empty. Except for calling create_underlying. _partition_exists = true; return make_ready_future<>(); } public: future<> create_underlying(db::timeout_clock::time_point timeout); void enter_partition(const dht::decorated_key& dk, mutation_source& snapshot, row_cache::phase_type phase) { _phase = phase; _underlying_snapshot = snapshot; _key = dk; } // Precondition: each caller needs to make sure that partition with |dk| key // exists in underlying before calling this function. void enter_partition(const dht::decorated_key& dk, row_cache::phase_type phase) { _phase = phase; _underlying_snapshot = {}; _key = dk; } }; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2011 Vince Durham // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2016 Daniel Kraft // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "auxpow.h" #include "compat/endian.h" #include "consensus/consensus.h" #include "consensus/merkle.h" #include "consensus/validation.h" #include "hash.h" #include "script/script.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include "validation.h" #include <algorithm> /* Moved from wallet.cpp. CMerkleTx is necessary for auxpow, independent of an enabled (or disabled) wallet. Always include the code. */ const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001")); void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock) { // Update the tx's hashBlock hashBlock = pindex->GetBlockHash(); // set the position of the transaction in the block nIndex = posInBlock; } void CMerkleTx::InitMerkleBranch(const CBlock& block, int posInBlock) { hashBlock = block.GetHash(); nIndex = posInBlock; vMerkleBranch = BlockMerkleBranch (block, nIndex); } int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const { if (hashUnset()) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; pindexRet = pindex; return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1); } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; if (nHeight < Params().GetConsensus().nCoinbaseMaturityV2Start) return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain()); return std::max(0, (COINBASE_MATURITY_V2+1) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state) { return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee); } /* ************************************************************************** */ bool CAuxPow::check (const uint256& hashAuxBlock, int nChainId, const Consensus::Params& params) const { if (nIndex != 0) return error("AuxPow is not a generate"); if (params.fStrictChainId && parentBlock.GetChainId () == nChainId) return error("Aux POW parent has our chain ID"); if (vChainMerkleBranch.size() > 30) return error("Aux POW chain merkle branch too long"); // Check that the chain merkle root is in the coinbase const uint256 nRootHash = CheckMerkleBranch (hashAuxBlock, vChainMerkleBranch, nChainIndex); valtype vchRootHash(nRootHash.begin (), nRootHash.end ()); std::reverse (vchRootHash.begin (), vchRootHash.end ()); // correct endian // Check that we are in the parent block merkle tree if (CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != parentBlock.hashMerkleRoot) return error("Aux POW merkle root incorrect"); const CScript script = tx->vin[0].scriptSig; // Check that the same work is not submitted twice to our chain. // CScript::const_iterator pcHead = std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)); CScript::const_iterator pc = std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end()); if (pc == script.end()) return error("Aux POW missing chain merkle root in parent coinbase"); if (pcHead != script.end()) { // Enforce only one chain merkle root by checking that a single instance of the merged // mining header exists just before. if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader))) return error("Multiple merged mining headers in coinbase"); if (pcHead + sizeof(pchMergedMiningHeader) != pc) return error("Merged mining header is not just before chain merkle root"); } else { // For backward compatibility. // Enforce only one chain merkle root by checking that it starts early in the coinbase. // 8-12 bytes are enough to encode extraNonce and nBits. if (pc - script.begin() > 20) return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase"); } // Ensure we are at a deterministic point in the merkle leaves by hashing // a nonce and our chain ID and comparing to the index. pc += vchRootHash.size(); if (script.end() - pc < 8) return error("Aux POW missing chain merkle tree size and nonce in parent coinbase"); uint32_t nSize; memcpy(&nSize, &pc[0], 4); nSize = le32toh (nSize); const unsigned merkleHeight = vChainMerkleBranch.size (); if (nSize != (1u << merkleHeight)) return error("Aux POW merkle branch size does not match parent coinbase"); uint32_t nNonce; memcpy(&nNonce, &pc[4], 4); nNonce = le32toh (nNonce); if (nChainIndex != getExpectedIndex (nNonce, nChainId, merkleHeight)) return error("Aux POW wrong index"); return true; } int CAuxPow::getExpectedIndex (uint32_t nNonce, int nChainId, unsigned h) { // Choose a pseudo-random slot in the chain merkle tree // but have it be fixed for a size/nonce/chain combination. // // This prevents the same work from being used twice for the // same chain while reducing the chance that two chains clash // for the same slot. /* This computation can overflow the uint32 used. This is not an issue, though, since we take the mod against a power-of-two in the end anyway. This also ensures that the computation is, actually, consistent even if done in 64 bits as it was in the past on some systems. Note that h is always <= 30 (enforced by the maximum allowed chain merkle branch length), so that 32 bits are enough for the computation. */ uint32_t rand = nNonce; rand = rand * 1103515245 + 12345; rand += nChainId; rand = rand * 1103515245 + 12345; return rand % (1 << h); } uint256 CAuxPow::CheckMerkleBranch (uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return uint256 (); for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin ()); it != vMerkleBranch.end (); ++it) { if (nIndex & 1) hash = Hash (BEGIN (*it), END (*it), BEGIN (hash), END (hash)); else hash = Hash (BEGIN (hash), END (hash), BEGIN (*it), END (*it)); nIndex >>= 1; } return hash; } void CAuxPow::initAuxPow (CBlockHeader& header) { /* Set auxpow flag right now, since we take the block hash below. */ header.SetAuxpowVersion(true); /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); valtype inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutableTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CTransactionRef coinbaseRef = MakeTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = BlockMerkleRoot (parent); /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->vMerkleBranch.empty ()); header.auxpow->nIndex = 0; header.auxpow->parentBlock = parent; } <commit_msg>return GetBlocksToMaturity to normal values<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2011 Vince Durham // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2016 Daniel Kraft // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #include "auxpow.h" #include "compat/endian.h" #include "consensus/consensus.h" #include "consensus/merkle.h" #include "consensus/validation.h" #include "hash.h" #include "script/script.h" #include "txmempool.h" #include "util.h" #include "utilstrencodings.h" #include "validation.h" #include <algorithm> /* Moved from wallet.cpp. CMerkleTx is necessary for auxpow, independent of an enabled (or disabled) wallet. Always include the code. */ const uint256 CMerkleTx::ABANDON_HASH(uint256S("0000000000000000000000000000000000000000000000000000000000000001")); void CMerkleTx::SetMerkleBranch(const CBlockIndex* pindex, int posInBlock) { // Update the tx's hashBlock hashBlock = pindex->GetBlockHash(); // set the position of the transaction in the block nIndex = posInBlock; } void CMerkleTx::InitMerkleBranch(const CBlock& block, int posInBlock) { hashBlock = block.GetHash(); nIndex = posInBlock; vMerkleBranch = BlockMerkleBranch (block, nIndex); } int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const { if (hashUnset()) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; pindexRet = pindex; return ((nIndex == -1) ? (-1) : 1) * (chainActive.Height() - pindex->nHeight + 1); } int CMerkleTx::GetBlocksToMaturity() const { if (!IsCoinBase()) return 0; return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(const CAmount& nAbsurdFee, CValidationState& state) { return ::AcceptToMemoryPool(mempool, state, tx, true, NULL, NULL, false, nAbsurdFee); } /* ************************************************************************** */ bool CAuxPow::check (const uint256& hashAuxBlock, int nChainId, const Consensus::Params& params) const { if (nIndex != 0) return error("AuxPow is not a generate"); if (params.fStrictChainId && parentBlock.GetChainId () == nChainId) return error("Aux POW parent has our chain ID"); if (vChainMerkleBranch.size() > 30) return error("Aux POW chain merkle branch too long"); // Check that the chain merkle root is in the coinbase const uint256 nRootHash = CheckMerkleBranch (hashAuxBlock, vChainMerkleBranch, nChainIndex); valtype vchRootHash(nRootHash.begin (), nRootHash.end ()); std::reverse (vchRootHash.begin (), vchRootHash.end ()); // correct endian // Check that we are in the parent block merkle tree if (CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != parentBlock.hashMerkleRoot) return error("Aux POW merkle root incorrect"); const CScript script = tx->vin[0].scriptSig; // Check that the same work is not submitted twice to our chain. // CScript::const_iterator pcHead = std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)); CScript::const_iterator pc = std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end()); if (pc == script.end()) return error("Aux POW missing chain merkle root in parent coinbase"); if (pcHead != script.end()) { // Enforce only one chain merkle root by checking that a single instance of the merged // mining header exists just before. if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader))) return error("Multiple merged mining headers in coinbase"); if (pcHead + sizeof(pchMergedMiningHeader) != pc) return error("Merged mining header is not just before chain merkle root"); } else { // For backward compatibility. // Enforce only one chain merkle root by checking that it starts early in the coinbase. // 8-12 bytes are enough to encode extraNonce and nBits. if (pc - script.begin() > 20) return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase"); } // Ensure we are at a deterministic point in the merkle leaves by hashing // a nonce and our chain ID and comparing to the index. pc += vchRootHash.size(); if (script.end() - pc < 8) return error("Aux POW missing chain merkle tree size and nonce in parent coinbase"); uint32_t nSize; memcpy(&nSize, &pc[0], 4); nSize = le32toh (nSize); const unsigned merkleHeight = vChainMerkleBranch.size (); if (nSize != (1u << merkleHeight)) return error("Aux POW merkle branch size does not match parent coinbase"); uint32_t nNonce; memcpy(&nNonce, &pc[4], 4); nNonce = le32toh (nNonce); if (nChainIndex != getExpectedIndex (nNonce, nChainId, merkleHeight)) return error("Aux POW wrong index"); return true; } int CAuxPow::getExpectedIndex (uint32_t nNonce, int nChainId, unsigned h) { // Choose a pseudo-random slot in the chain merkle tree // but have it be fixed for a size/nonce/chain combination. // // This prevents the same work from being used twice for the // same chain while reducing the chance that two chains clash // for the same slot. /* This computation can overflow the uint32 used. This is not an issue, though, since we take the mod against a power-of-two in the end anyway. This also ensures that the computation is, actually, consistent even if done in 64 bits as it was in the past on some systems. Note that h is always <= 30 (enforced by the maximum allowed chain merkle branch length), so that 32 bits are enough for the computation. */ uint32_t rand = nNonce; rand = rand * 1103515245 + 12345; rand += nChainId; rand = rand * 1103515245 + 12345; return rand % (1 << h); } uint256 CAuxPow::CheckMerkleBranch (uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return uint256 (); for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin ()); it != vMerkleBranch.end (); ++it) { if (nIndex & 1) hash = Hash (BEGIN (*it), END (*it), BEGIN (hash), END (hash)); else hash = Hash (BEGIN (hash), END (hash), BEGIN (*it), END (*it)); nIndex >>= 1; } return hash; } void CAuxPow::initAuxPow (CBlockHeader& header) { /* Set auxpow flag right now, since we take the block hash below. */ header.SetAuxpowVersion(true); /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); valtype inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutableTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CTransactionRef coinbaseRef = MakeTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = BlockMerkleRoot (parent); /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->vMerkleBranch.empty ()); header.auxpow->nIndex = 0; header.auxpow->parentBlock = parent; } <|endoftext|>
<commit_before>// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "hash.h" #include "uint256.h" #include <assert.h> #include <stdint.h> #include <string.h> #include <vector> #include <string> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> /** All alphanumeric characters except for "0", "I", "O", and "l" */ static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch) { // Skip leading spaces. while (*psz && isspace(*psz)) psz++; // Skip and count leading '1's. int zeroes = 0; while (*psz == '1') { zeroes++; psz++; } // Allocate enough space in big-endian base256 representation. std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up. // Process the characters. while (*psz && !isspace(*psz)) { // Decode base58 character const char* ch = strchr(pszBase58, *psz); if (ch == NULL) return false; // Apply "b256 = b256 * 58 + ch". int carry = ch - pszBase58; for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) { carry += 58 * (*it); *it = carry % 256; carry /= 256; } assert(carry == 0); psz++; } // Skip trailing spaces. while (isspace(*psz)) psz++; if (*psz != 0) return false; // Skip leading zeroes in b256. std::vector<unsigned char>::iterator it = b256.begin(); while (it != b256.end() && *it == 0) it++; // Copy result into output vector. vch.reserve(zeroes + (b256.end() - it)); vch.assign(zeroes, 0x00); while (it != b256.end()) vch.push_back(*(it++)); return true; } std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { // Skip & count leading zeroes. int zeroes = 0; int length = 0; while (pbegin != pend && *pbegin == 0) { pbegin++; zeroes++; } // Allocate enough space in big-endian base58 representation. int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up. std::vector<unsigned char> b58(size); // Process the bytes. while (pbegin != pend) { int carry = *pbegin; int i = 0; // Apply "b58 = b58 * 256 + ch". for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) { carry += 256 * (*it); *it = carry % 58; carry /= 58; } assert(carry == 0); length = i; pbegin++; } // Skip leading zeroes in base58 result. std::vector<unsigned char>::iterator it = b58.begin() + (size - length); while (it != b58.end() && *it == 0) it++; // Translate the result into a string. std::string str; str.reserve(zeroes + (b58.end() - it)); str.assign(zeroes, '1'); while (it != b58.end()) str += pszBase58[*(it++)]; return str; } std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet) || (vchRet.size() < 4)) { vchRet.clear(); return false; } // re-calculate the checksum, insure it matches the included 4-byte checksum uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size() - 4); return true; } bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } CBase58Data::CBase58Data() { vchVersion.clear(); vchData.clear(); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize) { vchVersion = vchVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize, const void* pdata2, size_t nSize2) { vchVersion = vchVersionIn; vchData.resize(nSize+nSize2); if (!vchData.empty()) { memcpy(&vchData[0], pdata, nSize); memcpy(&vchData[nSize], pdata2, nSize2); } } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend) { SetData(vchVersionIn, (void*)pbegin, pend - pbegin); } bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes) { std::vector<unsigned char> vchTemp; bool rc58 = DecodeBase58Check(psz, vchTemp); if ((!rc58) || (vchTemp.size() < nVersionBytes)) { vchData.clear(); vchVersion.clear(); return false; } vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes); vchData.resize(vchTemp.size() - nVersionBytes); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size()); memory_cleanse(&vchTemp[0], vchTemp.size()); return true; } bool CBase58Data::SetString(const std::string& str) { return SetString(str.c_str()); } std::string CBase58Data::ToString() const { std::vector<unsigned char> vch = vchVersion; vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CBase58Data::CompareTo(const CBase58Data& b58) const { if (vchVersion < b58.vchVersion) return -1; if (vchVersion > b58.vchVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } namespace { class CNavCoinAddressVisitor : public boost::static_visitor<bool> { private: CNavCoinAddress* addr; public: CNavCoinAddressVisitor(CNavCoinAddress* addrIn) : addr(addrIn) {} bool operator()(const CKeyID& id) const { return addr->Set(id); } bool operator()(const pair<CKeyID, CKeyID>& id) const { return addr->Set(id.first, id.second); } bool operator()(const CScriptID& id) const { return addr->Set(id); } bool operator()(const CNoDestination& no) const { return false; } }; } // anon namespace bool CNavCoinAddress::Set(const CKeyID& id) { SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20); return true; } bool CNavCoinAddress::Set(const CKeyID& id, const CKeyID& id2) { SetData(Params().Base58Prefix(CChainParams::COLDSTAKING_ADDRESS), &id, 20, &id2, 20); return true; } bool CNavCoinAddress::Set(const CScriptID& id) { SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20); return true; } bool CNavCoinAddress::Set(const CTxDestination& dest) { return boost::apply_visitor(CNavCoinAddressVisitor(this), dest); } bool CNavCoinAddress::IsValid() const { return IsValid(Params()); } bool CNavCoinAddress::GetSpendingAddress(CNavCoinAddress &address) const { if(!IsColdStakingAddress(Params())) return false; uint160 id; memcpy(&id, &vchData[0], 20); address.Set(CKeyID(id)); return true; } bool CNavCoinAddress::GetStakingAddress(CNavCoinAddress &address) const { if(!IsColdStakingAddress(Params())) return false; uint160 id; memcpy(&id, &vchData[20], 20); address.Set(CKeyID(id)); return true; } bool CNavCoinAddress::IsValid(const CChainParams& params) const { if (vchVersion == params.Base58Prefix(CChainParams::COLDSTAKING_ADDRESS)) return vchData.size() == 40; bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) || vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS); return fCorrectSize && fKnownVersion; } bool CNavCoinAddress::IsColdStakingAddress(const CChainParams& params) const { return vchVersion == params.Base58Prefix(CChainParams::COLDSTAKING_ADDRESS) && vchData.size() == 40; } CTxDestination CNavCoinAddress::Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == Params().Base58Prefix(CChainParams::COLDSTAKING_ADDRESS)) { uint160 id2; memcpy(&id2, &vchData[20], 20); return make_pair(CKeyID(id), CKeyID(id2)); } if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return CKeyID(id); else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) return CScriptID(id); else return CNoDestination(); } bool CNavCoinAddress::GetIndexKey(uint160& hashBytes, int& type) const { if (!IsValid()) { return false; } else if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) { memcpy(&hashBytes, &vchData[0], 20); type = 1; return true; } else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) { memcpy(&hashBytes, &vchData[0], 20); type = 2; return true; } return false; } bool CNavCoinAddress::GetKeyID(CKeyID& keyID) const { if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool CNavCoinAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } void CNavCoinSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey CNavCoinSecret::GetKey() { CKey ret; assert(vchData.size() >= 32); ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1); return ret; } bool CNavCoinSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; } bool CNavCoinSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool CNavCoinSecret::SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } <commit_msg>fix order of the public keys on raw decoded address<commit_after>// Copyright (c) 2014-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "hash.h" #include "uint256.h" #include <assert.h> #include <stdint.h> #include <string.h> #include <vector> #include <string> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> /** All alphanumeric characters except for "0", "I", "O", and "l" */ static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool DecodeBase58(const char* psz, std::vector<unsigned char>& vch) { // Skip leading spaces. while (*psz && isspace(*psz)) psz++; // Skip and count leading '1's. int zeroes = 0; while (*psz == '1') { zeroes++; psz++; } // Allocate enough space in big-endian base256 representation. std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up. // Process the characters. while (*psz && !isspace(*psz)) { // Decode base58 character const char* ch = strchr(pszBase58, *psz); if (ch == NULL) return false; // Apply "b256 = b256 * 58 + ch". int carry = ch - pszBase58; for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) { carry += 58 * (*it); *it = carry % 256; carry /= 256; } assert(carry == 0); psz++; } // Skip trailing spaces. while (isspace(*psz)) psz++; if (*psz != 0) return false; // Skip leading zeroes in b256. std::vector<unsigned char>::iterator it = b256.begin(); while (it != b256.end() && *it == 0) it++; // Copy result into output vector. vch.reserve(zeroes + (b256.end() - it)); vch.assign(zeroes, 0x00); while (it != b256.end()) vch.push_back(*(it++)); return true; } std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { // Skip & count leading zeroes. int zeroes = 0; int length = 0; while (pbegin != pend && *pbegin == 0) { pbegin++; zeroes++; } // Allocate enough space in big-endian base58 representation. int size = (pend - pbegin) * 138 / 100 + 1; // log(256) / log(58), rounded up. std::vector<unsigned char> b58(size); // Process the bytes. while (pbegin != pend) { int carry = *pbegin; int i = 0; // Apply "b58 = b58 * 256 + ch". for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); (carry != 0 || i < length) && (it != b58.rend()); it++, i++) { carry += 256 * (*it); *it = carry % 58; carry /= 58; } assert(carry == 0); length = i; pbegin++; } // Skip leading zeroes in base58 result. std::vector<unsigned char>::iterator it = b58.begin() + (size - length); while (it != b58.end() && *it == 0) it++; // Translate the result into a string. std::string str; str.reserve(zeroes + (b58.end() - it)); str.assign(zeroes, '1'); while (it != b58.end()) str += pszBase58[*(it++)]; return str; } std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet) || (vchRet.size() < 4)) { vchRet.clear(); return false; } // re-calculate the checksum, insure it matches the included 4-byte checksum uint256 hash = Hash(vchRet.begin(), vchRet.end() - 4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size() - 4); return true; } bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } CBase58Data::CBase58Data() { vchVersion.clear(); vchData.clear(); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize) { vchVersion = vchVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const void* pdata, size_t nSize, const void* pdata2, size_t nSize2) { vchVersion = vchVersionIn; vchData.resize(nSize+nSize2); if (!vchData.empty()) { memcpy(&vchData[0], pdata, nSize); memcpy(&vchData[nSize], pdata2, nSize2); } } void CBase58Data::SetData(const std::vector<unsigned char>& vchVersionIn, const unsigned char* pbegin, const unsigned char* pend) { SetData(vchVersionIn, (void*)pbegin, pend - pbegin); } bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes) { std::vector<unsigned char> vchTemp; bool rc58 = DecodeBase58Check(psz, vchTemp); if ((!rc58) || (vchTemp.size() < nVersionBytes)) { vchData.clear(); vchVersion.clear(); return false; } vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes); vchData.resize(vchTemp.size() - nVersionBytes); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size()); memory_cleanse(&vchTemp[0], vchTemp.size()); return true; } bool CBase58Data::SetString(const std::string& str) { return SetString(str.c_str()); } std::string CBase58Data::ToString() const { std::vector<unsigned char> vch = vchVersion; vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CBase58Data::CompareTo(const CBase58Data& b58) const { if (vchVersion < b58.vchVersion) return -1; if (vchVersion > b58.vchVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } namespace { class CNavCoinAddressVisitor : public boost::static_visitor<bool> { private: CNavCoinAddress* addr; public: CNavCoinAddressVisitor(CNavCoinAddress* addrIn) : addr(addrIn) {} bool operator()(const CKeyID& id) const { return addr->Set(id); } bool operator()(const pair<CKeyID, CKeyID>& id) const { return addr->Set(id.first, id.second); } bool operator()(const CScriptID& id) const { return addr->Set(id); } bool operator()(const CNoDestination& no) const { return false; } }; } // anon namespace bool CNavCoinAddress::Set(const CKeyID& id) { SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20); return true; } bool CNavCoinAddress::Set(const CKeyID& id, const CKeyID& id2) { SetData(Params().Base58Prefix(CChainParams::COLDSTAKING_ADDRESS), &id, 20, &id2, 20); return true; } bool CNavCoinAddress::Set(const CScriptID& id) { SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20); return true; } bool CNavCoinAddress::Set(const CTxDestination& dest) { return boost::apply_visitor(CNavCoinAddressVisitor(this), dest); } bool CNavCoinAddress::IsValid() const { return IsValid(Params()); } bool CNavCoinAddress::GetSpendingAddress(CNavCoinAddress &address) const { if(!IsColdStakingAddress(Params())) return false; uint160 id; memcpy(&id, &vchData[20], 20); address.Set(CKeyID(id)); return true; } bool CNavCoinAddress::GetStakingAddress(CNavCoinAddress &address) const { if(!IsColdStakingAddress(Params())) return false; uint160 id; memcpy(&id, &vchData[0], 20); address.Set(CKeyID(id)); return true; } bool CNavCoinAddress::IsValid(const CChainParams& params) const { if (vchVersion == params.Base58Prefix(CChainParams::COLDSTAKING_ADDRESS)) return vchData.size() == 40; bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == params.Base58Prefix(CChainParams::PUBKEY_ADDRESS) || vchVersion == params.Base58Prefix(CChainParams::SCRIPT_ADDRESS); return fCorrectSize && fKnownVersion; } bool CNavCoinAddress::IsColdStakingAddress(const CChainParams& params) const { return vchVersion == params.Base58Prefix(CChainParams::COLDSTAKING_ADDRESS) && vchData.size() == 40; } CTxDestination CNavCoinAddress::Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == Params().Base58Prefix(CChainParams::COLDSTAKING_ADDRESS)) { uint160 id2; memcpy(&id2, &vchData[20], 20); return make_pair(CKeyID(id), CKeyID(id2)); } if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return CKeyID(id); else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) return CScriptID(id); else return CNoDestination(); } bool CNavCoinAddress::GetIndexKey(uint160& hashBytes, int& type) const { if (!IsValid()) { return false; } else if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) { memcpy(&hashBytes, &vchData[0], 20); type = 1; return true; } else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) { memcpy(&hashBytes, &vchData[0], 20); type = 2; return true; } return false; } bool CNavCoinAddress::GetKeyID(CKeyID& keyID) const { if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool CNavCoinAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } void CNavCoinSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey CNavCoinSecret::GetKey() { CKey ret; assert(vchData.size() >= 32); ret.Set(vchData.begin(), vchData.begin() + 32, vchData.size() > 32 && vchData[32] == 1); return ret; } bool CNavCoinSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; } bool CNavCoinSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool CNavCoinSecret::SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } <|endoftext|>
<commit_before>// Copyright (c) 2017, 2021 Pieter Wuille // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bech32.h> #include <util/vector.h> #include <assert.h> namespace bech32 { namespace { typedef std::vector<uint8_t> data; /** The Bech32 and Bech32m character set for encoding. */ const char* CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; /** The Bech32 and Bech32m character set for decoding. */ const int8_t CHARSET_REV[128] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1 }; /* Determine the final constant to use for the specified encoding. */ uint32_t EncodingConstant(Encoding encoding) { assert(encoding == Encoding::BECH32 || encoding == Encoding::BECH32M); return encoding == Encoding::BECH32 ? 1 : 0x2bc830a3; } /** This function will compute what 6 5-bit values to XOR into the last 6 input values, in order to * make the checksum 0. These 6 values are packed together in a single 30-bit integer. The higher * bits correspond to earlier values. */ uint32_t PolyMod(const data& v) { // The input is interpreted as a list of coefficients of a polynomial over F = GF(32), with an // implicit 1 in front. If the input is [v0,v1,v2,v3,v4], that polynomial is v(x) = // 1*x^5 + v0*x^4 + v1*x^3 + v2*x^2 + v3*x + v4. The implicit 1 guarantees that // [v0,v1,v2,...] has a distinct checksum from [0,v0,v1,v2,...]. // The output is a 30-bit integer whose 5-bit groups are the coefficients of the remainder of // v(x) mod g(x), where g(x) is the Bech32 generator, // x^6 + {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18}. g(x) is chosen in such a way // that the resulting code is a BCH code, guaranteeing detection of up to 3 errors within a // window of 1023 characters. Among the various possible BCH codes, one was selected to in // fact guarantee detection of up to 4 errors within a window of 89 characters. // Note that the coefficients are elements of GF(32), here represented as decimal numbers // between {}. In this finite field, addition is just XOR of the corresponding numbers. For // example, {27} + {13} = {27 ^ 13} = {22}. Multiplication is more complicated, and requires // treating the bits of values themselves as coefficients of a polynomial over a smaller field, // GF(2), and multiplying those polynomials mod a^5 + a^3 + 1. For example, {5} * {26} = // (a^2 + 1) * (a^4 + a^3 + a) = (a^4 + a^3 + a) * a^2 + (a^4 + a^3 + a) = a^6 + a^5 + a^4 + a // = a^3 + 1 (mod a^5 + a^3 + 1) = {9}. // During the course of the loop below, `c` contains the bitpacked coefficients of the // polynomial constructed from just the values of v that were processed so far, mod g(x). In // the above example, `c` initially corresponds to 1 mod g(x), and after processing 2 inputs of // v, it corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the starting value // for `c`. uint32_t c = 1; for (const auto v_i : v) { // We want to update `c` to correspond to a polynomial with one extra term. If the initial // value of `c` consists of the coefficients of c(x) = f(x) mod g(x), we modify it to // correspond to c'(x) = (f(x) * x + v_i) mod g(x), where v_i is the next input to // process. Simplifying: // c'(x) = (f(x) * x + v_i) mod g(x) // ((f(x) mod g(x)) * x + v_i) mod g(x) // (c(x) * x + v_i) mod g(x) // If c(x) = c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5, we want to compute // c'(x) = (c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5) * x + v_i mod g(x) // = c0*x^6 + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i mod g(x) // = c0*(x^6 mod g(x)) + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i // If we call (x^6 mod g(x)) = k(x), this can be written as // c'(x) = (c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i) + c0*k(x) // First, determine the value of c0: uint8_t c0 = c >> 25; // Then compute c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i: c = ((c & 0x1ffffff) << 5) ^ v_i; // Finally, for each set bit n in c0, conditionally add {2^n}k(x): if (c0 & 1) c ^= 0x3b6a57b2; // k(x) = {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18} if (c0 & 2) c ^= 0x26508e6d; // {2}k(x) = {19}x^5 + {5}x^4 + x^3 + {3}x^2 + {19}x + {13} if (c0 & 4) c ^= 0x1ea119fa; // {4}k(x) = {15}x^5 + {10}x^4 + {2}x^3 + {6}x^2 + {15}x + {26} if (c0 & 8) c ^= 0x3d4233dd; // {8}k(x) = {30}x^5 + {20}x^4 + {4}x^3 + {12}x^2 + {30}x + {29} if (c0 & 16) c ^= 0x2a1462b3; // {16}k(x) = {21}x^5 + x^4 + {8}x^3 + {24}x^2 + {21}x + {19} } return c; } /** Convert to lower case. */ inline unsigned char LowerCase(unsigned char c) { return (c >= 'A' && c <= 'Z') ? (c - 'A') + 'a' : c; } /** Expand a HRP for use in checksum computation. */ data ExpandHRP(const std::string& hrp) { data ret; ret.reserve(hrp.size() + 90); ret.resize(hrp.size() * 2 + 1); for (size_t i = 0; i < hrp.size(); ++i) { unsigned char c = hrp[i]; ret[i] = c >> 5; ret[i + hrp.size() + 1] = c & 0x1f; } ret[hrp.size()] = 0; return ret; } /** Verify a checksum. */ Encoding VerifyChecksum(const std::string& hrp, const data& values) { // PolyMod computes what value to xor into the final values to make the checksum 0. However, // if we required that the checksum was 0, it would be the case that appending a 0 to a valid // list of values would result in a new valid list. For that reason, Bech32 requires the // resulting checksum to be 1 instead. In Bech32m, this constant was amended. const uint32_t check = PolyMod(Cat(ExpandHRP(hrp), values)); if (check == EncodingConstant(Encoding::BECH32)) return Encoding::BECH32; if (check == EncodingConstant(Encoding::BECH32M)) return Encoding::BECH32M; return Encoding::INVALID; } /** Create a checksum. */ data CreateChecksum(Encoding encoding, const std::string& hrp, const data& values) { data enc = Cat(ExpandHRP(hrp), values); enc.resize(enc.size() + 6); // Append 6 zeroes uint32_t mod = PolyMod(enc) ^ EncodingConstant(encoding); // Determine what to XOR into those 6 zeroes. data ret(6); for (size_t i = 0; i < 6; ++i) { // Convert the 5-bit groups in mod to checksum values. ret[i] = (mod >> (5 * (5 - i))) & 31; } return ret; } } // namespace /** Encode a Bech32 or Bech32m string. */ std::string Encode(Encoding encoding, const std::string& hrp, const data& values) { // First ensure that the HRP is all lowercase. BIP-173 and BIP350 require an encoder // to return a lowercase Bech32/Bech32m string, but if given an uppercase HRP, the // result will always be invalid. for (const char& c : hrp) assert(c < 'A' || c > 'Z'); data checksum = CreateChecksum(encoding, hrp, values); data combined = Cat(values, checksum); std::string ret = hrp + '1'; ret.reserve(ret.size() + combined.size()); for (const auto c : combined) { ret += CHARSET[c]; } return ret; } /** Decode a Bech32 or Bech32m string. */ DecodeResult Decode(const std::string& str) { bool lower = false, upper = false; for (size_t i = 0; i < str.size(); ++i) { unsigned char c = str[i]; if (c >= 'a' && c <= 'z') lower = true; else if (c >= 'A' && c <= 'Z') upper = true; else if (c < 33 || c > 126) return {}; } if (lower && upper) return {}; size_t pos = str.rfind('1'); if (str.size() > 90 || pos == str.npos || pos == 0 || pos + 7 > str.size()) { return {}; } data values(str.size() - 1 - pos); for (size_t i = 0; i < str.size() - 1 - pos; ++i) { unsigned char c = str[i + pos + 1]; int8_t rev = CHARSET_REV[c]; if (rev == -1) { return {}; } values[i] = rev; } std::string hrp; for (size_t i = 0; i < pos; ++i) { hrp += LowerCase(str[i]); } Encoding result = VerifyChecksum(hrp, values); if (result == Encoding::INVALID) return {}; return {result, std::move(hrp), data(values.begin(), values.end() - 6)}; } } // namespace bech32 <commit_msg>Add references for the generator/constant used in Bech32(m)<commit_after>// Copyright (c) 2017, 2021 Pieter Wuille // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <bech32.h> #include <util/vector.h> #include <assert.h> namespace bech32 { namespace { typedef std::vector<uint8_t> data; /** The Bech32 and Bech32m character set for encoding. */ const char* CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"; /** The Bech32 and Bech32m character set for decoding. */ const int8_t CHARSET_REV[128] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, 10, 17, 21, 20, 26, 30, 7, 5, -1, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1, -1, 29, -1, 24, 13, 25, 9, 8, 23, -1, 18, 22, 31, 27, 19, -1, 1, 0, 3, 16, 11, 28, 12, 14, 6, 4, 2, -1, -1, -1, -1, -1 }; /* Determine the final constant to use for the specified encoding. */ uint32_t EncodingConstant(Encoding encoding) { assert(encoding == Encoding::BECH32 || encoding == Encoding::BECH32M); return encoding == Encoding::BECH32 ? 1 : 0x2bc830a3; } /** This function will compute what 6 5-bit values to XOR into the last 6 input values, in order to * make the checksum 0. These 6 values are packed together in a single 30-bit integer. The higher * bits correspond to earlier values. */ uint32_t PolyMod(const data& v) { // The input is interpreted as a list of coefficients of a polynomial over F = GF(32), with an // implicit 1 in front. If the input is [v0,v1,v2,v3,v4], that polynomial is v(x) = // 1*x^5 + v0*x^4 + v1*x^3 + v2*x^2 + v3*x + v4. The implicit 1 guarantees that // [v0,v1,v2,...] has a distinct checksum from [0,v0,v1,v2,...]. // The output is a 30-bit integer whose 5-bit groups are the coefficients of the remainder of // v(x) mod g(x), where g(x) is the Bech32 generator, // x^6 + {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18}. g(x) is chosen in such a way // that the resulting code is a BCH code, guaranteeing detection of up to 3 errors within a // window of 1023 characters. Among the various possible BCH codes, one was selected to in // fact guarantee detection of up to 4 errors within a window of 89 characters. // Note that the coefficients are elements of GF(32), here represented as decimal numbers // between {}. In this finite field, addition is just XOR of the corresponding numbers. For // example, {27} + {13} = {27 ^ 13} = {22}. Multiplication is more complicated, and requires // treating the bits of values themselves as coefficients of a polynomial over a smaller field, // GF(2), and multiplying those polynomials mod a^5 + a^3 + 1. For example, {5} * {26} = // (a^2 + 1) * (a^4 + a^3 + a) = (a^4 + a^3 + a) * a^2 + (a^4 + a^3 + a) = a^6 + a^5 + a^4 + a // = a^3 + 1 (mod a^5 + a^3 + 1) = {9}. // During the course of the loop below, `c` contains the bitpacked coefficients of the // polynomial constructed from just the values of v that were processed so far, mod g(x). In // the above example, `c` initially corresponds to 1 mod g(x), and after processing 2 inputs of // v, it corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the starting value // for `c`. // The following Sage code constructs the generator used: // // B = GF(2) # Binary field // BP.<b> = B[] # Polynomials over the binary field // F_mod = b**5 + b**3 + 1 // F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition // FP.<x> = F[] # Polynomials over GF(32) // E_mod = x**2 + F.fetch_int(9)*x + F.fetch_int(23) // E.<e> = F.extension(E_mod) # GF(1024) extension field definition // for p in divisors(E.order() - 1): # Verify e has order 1023. // assert((e**p == 1) == (p % 1023 == 0)) // G = lcm([(e**i).minpoly() for i in range(997,1000)]) // print(G) # Print out the generator // // It demonstrates that g(x) is the least common multiple of the minimal polynomials // of 3 consecutive powers (997,998,999) of a primitive element (e) of GF(1024). // That guarantees it is, in fact, the generator of a primitive BCH code with cycle // length 1023 and distance 4. See https://en.wikipedia.org/wiki/BCH_code for more details. uint32_t c = 1; for (const auto v_i : v) { // We want to update `c` to correspond to a polynomial with one extra term. If the initial // value of `c` consists of the coefficients of c(x) = f(x) mod g(x), we modify it to // correspond to c'(x) = (f(x) * x + v_i) mod g(x), where v_i is the next input to // process. Simplifying: // c'(x) = (f(x) * x + v_i) mod g(x) // ((f(x) mod g(x)) * x + v_i) mod g(x) // (c(x) * x + v_i) mod g(x) // If c(x) = c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5, we want to compute // c'(x) = (c0*x^5 + c1*x^4 + c2*x^3 + c3*x^2 + c4*x + c5) * x + v_i mod g(x) // = c0*x^6 + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i mod g(x) // = c0*(x^6 mod g(x)) + c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i // If we call (x^6 mod g(x)) = k(x), this can be written as // c'(x) = (c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i) + c0*k(x) // First, determine the value of c0: uint8_t c0 = c >> 25; // Then compute c1*x^5 + c2*x^4 + c3*x^3 + c4*x^2 + c5*x + v_i: c = ((c & 0x1ffffff) << 5) ^ v_i; // Finally, for each set bit n in c0, conditionally add {2^n}k(x). These constants can be // computed using the following Sage code (continuing the code above): // // for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(g(x) mod x^6), packed in hex integers. // v = 0 // for coef in reversed((F.fetch_int(i)*(G % x**6)).coefficients(sparse=True)): // v = v*32 + coef.integer_representation() // print("0x%x" % v) // if (c0 & 1) c ^= 0x3b6a57b2; // k(x) = {29}x^5 + {22}x^4 + {20}x^3 + {21}x^2 + {29}x + {18} if (c0 & 2) c ^= 0x26508e6d; // {2}k(x) = {19}x^5 + {5}x^4 + x^3 + {3}x^2 + {19}x + {13} if (c0 & 4) c ^= 0x1ea119fa; // {4}k(x) = {15}x^5 + {10}x^4 + {2}x^3 + {6}x^2 + {15}x + {26} if (c0 & 8) c ^= 0x3d4233dd; // {8}k(x) = {30}x^5 + {20}x^4 + {4}x^3 + {12}x^2 + {30}x + {29} if (c0 & 16) c ^= 0x2a1462b3; // {16}k(x) = {21}x^5 + x^4 + {8}x^3 + {24}x^2 + {21}x + {19} } return c; } /** Convert to lower case. */ inline unsigned char LowerCase(unsigned char c) { return (c >= 'A' && c <= 'Z') ? (c - 'A') + 'a' : c; } /** Expand a HRP for use in checksum computation. */ data ExpandHRP(const std::string& hrp) { data ret; ret.reserve(hrp.size() + 90); ret.resize(hrp.size() * 2 + 1); for (size_t i = 0; i < hrp.size(); ++i) { unsigned char c = hrp[i]; ret[i] = c >> 5; ret[i + hrp.size() + 1] = c & 0x1f; } ret[hrp.size()] = 0; return ret; } /** Verify a checksum. */ Encoding VerifyChecksum(const std::string& hrp, const data& values) { // PolyMod computes what value to xor into the final values to make the checksum 0. However, // if we required that the checksum was 0, it would be the case that appending a 0 to a valid // list of values would result in a new valid list. For that reason, Bech32 requires the // resulting checksum to be 1 instead. In Bech32m, this constant was amended. See // https://gist.github.com/sipa/14c248c288c3880a3b191f978a34508e for details. const uint32_t check = PolyMod(Cat(ExpandHRP(hrp), values)); if (check == EncodingConstant(Encoding::BECH32)) return Encoding::BECH32; if (check == EncodingConstant(Encoding::BECH32M)) return Encoding::BECH32M; return Encoding::INVALID; } /** Create a checksum. */ data CreateChecksum(Encoding encoding, const std::string& hrp, const data& values) { data enc = Cat(ExpandHRP(hrp), values); enc.resize(enc.size() + 6); // Append 6 zeroes uint32_t mod = PolyMod(enc) ^ EncodingConstant(encoding); // Determine what to XOR into those 6 zeroes. data ret(6); for (size_t i = 0; i < 6; ++i) { // Convert the 5-bit groups in mod to checksum values. ret[i] = (mod >> (5 * (5 - i))) & 31; } return ret; } } // namespace /** Encode a Bech32 or Bech32m string. */ std::string Encode(Encoding encoding, const std::string& hrp, const data& values) { // First ensure that the HRP is all lowercase. BIP-173 and BIP350 require an encoder // to return a lowercase Bech32/Bech32m string, but if given an uppercase HRP, the // result will always be invalid. for (const char& c : hrp) assert(c < 'A' || c > 'Z'); data checksum = CreateChecksum(encoding, hrp, values); data combined = Cat(values, checksum); std::string ret = hrp + '1'; ret.reserve(ret.size() + combined.size()); for (const auto c : combined) { ret += CHARSET[c]; } return ret; } /** Decode a Bech32 or Bech32m string. */ DecodeResult Decode(const std::string& str) { bool lower = false, upper = false; for (size_t i = 0; i < str.size(); ++i) { unsigned char c = str[i]; if (c >= 'a' && c <= 'z') lower = true; else if (c >= 'A' && c <= 'Z') upper = true; else if (c < 33 || c > 126) return {}; } if (lower && upper) return {}; size_t pos = str.rfind('1'); if (str.size() > 90 || pos == str.npos || pos == 0 || pos + 7 > str.size()) { return {}; } data values(str.size() - 1 - pos); for (size_t i = 0; i < str.size() - 1 - pos; ++i) { unsigned char c = str[i + pos + 1]; int8_t rev = CHARSET_REV[c]; if (rev == -1) { return {}; } values[i] = rev; } std::string hrp; for (size_t i = 0; i < pos; ++i) { hrp += LowerCase(str[i]); } Encoding result = VerifyChecksum(hrp, values); if (result == Encoding::INVALID) return {}; return {result, std::move(hrp), data(values.begin(), values.end() - 6)}; } } // namespace bech32 <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shapefile.hpp 33 2005-04-04 13:01:03Z pavlenko $ #ifndef SHAPEFILE_HPP #define SHAPEFILE_HPP #include <mapnik/envelope.hpp> // boost #include <boost/utility.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/device/mapped_file.hpp> #include <cstring> using mapnik::Envelope; struct shape_record { const char* data; size_t size; mutable size_t pos; explicit shape_record(size_t size) : size(size), pos(0) {} void set_data(const char * data_) { data = data_; } void skip(unsigned n) { pos+=n; } int read_ndr_integer() { int val=(data[pos] & 0xff) | (data[pos+1] & 0xff) << 8 | (data[pos+2] & 0xff) << 16 | (data[pos+3] & 0xff) << 24; pos+=4; return val; } int read_xdr_integer() { int val=(data[pos] & 0xff) << 24 | (data[pos+1] & 0xff) << 16 | (data[pos+2] & 0xff) << 8 | (data[pos+3] & 0xff); pos+=4; return val; } double read_double() { double val; #ifndef WORDS_BIGENDIAN std::memcpy(&val,&data[pos],8); #else long long bits = ((long long)data[pos] & 0xff) | ((long long)data[pos+1] & 0xff) << 8 | ((long long)data[pos+2] & 0xff) << 16 | ((long long)data[pos+3] & 0xff) << 24 | ((long long)data[pos+4] & 0xff) << 32 | ((long long)data[pos+5] & 0xff) << 40 | ((long long)data[pos+6] & 0xff) << 48 | ((long long)data[pos+7] & 0xff) << 56 ; std::memcpy(&val,&bits,8); #endif pos+=8; return val; } long remains() { return (size-pos); } ~shape_record() {} }; using namespace boost::iostreams; class shape_file : boost::noncopyable { stream<mapped_file_source> file_; public: shape_file(); shape_file(const std::string& file_name); ~shape_file(); bool is_open(); void close(); inline void read_record(shape_record& rec) { rec.set_data(file_->data() + file_.tellg()); file_.seekg(rec.size,std::ios::cur); } inline int read_xdr_integer() { char b[4]; file_.read(b, 4); return b[3] & 0xffu | (b[2] & 0xffu) << 8 | (b[1] & 0xffu) << 16 | (b[0] & 0xffu) << 24; } inline int read_ndr_integer() { char b[4]; file_.read(b,4); return b[0]&0xffu | (b[1]&0xffu) << 8 | (b[2]&0xffu) << 16 | (b[3]&0xffu) << 24; } inline double read_double() { double val; #ifndef WORDS_BIGENDIAN file_.read(reinterpret_cast<char*>(&val),8); #else char b[8]; file_.read(b,8); long long bits = ((long long)b[0] & 0xff) | ((long long)b[1] & 0xff) << 8 | ((long long)b[2] & 0xff) << 16 | ((long long)b[3] & 0xff) << 24 | ((long long)b[4] & 0xff) << 32 | ((long long)b[5] & 0xff) << 40 | ((long long)b[6] & 0xff) << 48 | ((long long)b[7] & 0xff) << 56 ; memcpy(&val,&bits,8); #endif return val; } inline void read_envelope(Envelope<double>& envelope) { #ifndef WORDS_BIGENDIAN file_.read(reinterpret_cast<char*>(&envelope),sizeof(envelope)); #else double minx=read_double(); double miny=read_double(); double maxx=read_double(); double maxy=read_double(); envelope.init(minx,miny,maxx,maxy); #endif } inline void skip(std::streampos bytes) { file_.seekg(bytes,std::ios::cur); } inline void rewind() { seek(100); } inline void seek(std::streampos pos) { file_.seekg(pos,std::ios::beg); } inline std::streampos pos() { return file_.tellg(); } inline bool is_eof() { return file_.eof(); } }; #endif //SHAPEFILE_HPP <commit_msg>Add parentheses to avoid compiler warnings.<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id: shapefile.hpp 33 2005-04-04 13:01:03Z pavlenko $ #ifndef SHAPEFILE_HPP #define SHAPEFILE_HPP #include <mapnik/envelope.hpp> // boost #include <boost/utility.hpp> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/device/file.hpp> #include <boost/iostreams/device/mapped_file.hpp> #include <cstring> using mapnik::Envelope; struct shape_record { const char* data; size_t size; mutable size_t pos; explicit shape_record(size_t size) : size(size), pos(0) {} void set_data(const char * data_) { data = data_; } void skip(unsigned n) { pos+=n; } int read_ndr_integer() { int val=(data[pos] & 0xff) | (data[pos+1] & 0xff) << 8 | (data[pos+2] & 0xff) << 16 | (data[pos+3] & 0xff) << 24; pos+=4; return val; } int read_xdr_integer() { int val=(data[pos] & 0xff) << 24 | (data[pos+1] & 0xff) << 16 | (data[pos+2] & 0xff) << 8 | (data[pos+3] & 0xff); pos+=4; return val; } double read_double() { double val; #ifndef WORDS_BIGENDIAN std::memcpy(&val,&data[pos],8); #else long long bits = ((long long)data[pos] & 0xff) | ((long long)data[pos+1] & 0xff) << 8 | ((long long)data[pos+2] & 0xff) << 16 | ((long long)data[pos+3] & 0xff) << 24 | ((long long)data[pos+4] & 0xff) << 32 | ((long long)data[pos+5] & 0xff) << 40 | ((long long)data[pos+6] & 0xff) << 48 | ((long long)data[pos+7] & 0xff) << 56 ; std::memcpy(&val,&bits,8); #endif pos+=8; return val; } long remains() { return (size-pos); } ~shape_record() {} }; using namespace boost::iostreams; class shape_file : boost::noncopyable { stream<mapped_file_source> file_; public: shape_file(); shape_file(const std::string& file_name); ~shape_file(); bool is_open(); void close(); inline void read_record(shape_record& rec) { rec.set_data(file_->data() + file_.tellg()); file_.seekg(rec.size,std::ios::cur); } inline int read_xdr_integer() { char b[4]; file_.read(b, 4); return (b[3] & 0xffu) | ((b[2] & 0xffu) << 8) | ((b[1] & 0xffu) << 16) | ((b[0] & 0xffu) << 24); } inline int read_ndr_integer() { char b[4]; file_.read(b,4); return (b[0]&0xffu) | ((b[1]&0xffu) << 8) | ((b[2]&0xffu) << 16) | ((b[3]&0xffu) << 24); } inline double read_double() { double val; #ifndef WORDS_BIGENDIAN file_.read(reinterpret_cast<char*>(&val),8); #else char b[8]; file_.read(b,8); long long bits = ((long long)b[0] & 0xff) | ((long long)b[1] & 0xff) << 8 | ((long long)b[2] & 0xff) << 16 | ((long long)b[3] & 0xff) << 24 | ((long long)b[4] & 0xff) << 32 | ((long long)b[5] & 0xff) << 40 | ((long long)b[6] & 0xff) << 48 | ((long long)b[7] & 0xff) << 56 ; memcpy(&val,&bits,8); #endif return val; } inline void read_envelope(Envelope<double>& envelope) { #ifndef WORDS_BIGENDIAN file_.read(reinterpret_cast<char*>(&envelope),sizeof(envelope)); #else double minx=read_double(); double miny=read_double(); double maxx=read_double(); double maxy=read_double(); envelope.init(minx,miny,maxx,maxy); #endif } inline void skip(std::streampos bytes) { file_.seekg(bytes,std::ios::cur); } inline void rewind() { seek(100); } inline void seek(std::streampos pos) { file_.seekg(pos,std::ios::beg); } inline std::streampos pos() { return file_.tellg(); } inline bool is_eof() { return file_.eof(); } }; #endif //SHAPEFILE_HPP <|endoftext|>
<commit_before>//===--- IRGen.cpp - Swift LLVM IR Generation -----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the entrypoints into IR generation. // //===----------------------------------------------------------------------===// #include "swift/Subsystems.h" #include "swift/IRGen/Options.h" #include "swift/AST/AST.h" #include "swift/AST/Diagnostics.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/TargetRegistry.h" #include "IRGenModule.h" using namespace swift; using namespace irgen; using namespace llvm; static bool isBinaryOutput(OutputKind kind) { switch (kind) { case OutputKind::Module: case OutputKind::LLVMAssembly: case OutputKind::NativeAssembly: return false; case OutputKind::LLVMBitcode: case OutputKind::ObjectFile: return true; } llvm_unreachable("bad output kind!"); } void swift::performIRGeneration(Options &Opts, llvm::Module *Module, TranslationUnit *TU, unsigned StartElem) { assert(!TU->Ctx.hadError()); std::unique_ptr<LLVMContext> Context; std::unique_ptr<llvm::Module> ModuleOwner; if (!Module) { Context.reset(new LLVMContext); ModuleOwner.reset(new llvm::Module(Opts.OutputFilename, *Context)); Module = ModuleOwner.get(); } Module->setTargetTriple(Opts.Triple); std::string Error; const Target *Target = TargetRegistry::lookupTarget(Opts.Triple, Error); if (!Target) { TU->Ctx.Diags.diagnose(SourceLoc(), diag::no_llvm_target, Opts.Triple, Error); return; } // The integer values 0-3 map exactly to the values of this enum. CodeGenOpt::Level OptLevel = static_cast<CodeGenOpt::Level>(Opts.OptLevel); // Set up TargetOptions. // Things that maybe we should collect from the command line: // - CPU // - features // - relocation model // - code model TargetOptions Options; // Create a target machine. TargetMachine *TargetMachine = Target->createTargetMachine(Opts.Triple, /*cpu*/ "", /*features*/ "", Options, Reloc::Default, CodeModel::Default, OptLevel); if (!TargetMachine) { TU->Ctx.Diags.diagnose(SourceLoc(), diag::no_llvm_target, Opts.Triple, "no LLVM target machine"); return; } // Set the module's string representation. const TargetData *TargetData = TargetMachine->getTargetData(); assert(TargetData && "target machine didn't set TargetData?"); Module->setDataLayout(TargetData->getStringRepresentation()); // Emit the translation unit. IRGenModule IRM(TU->Ctx, Opts, *Module, *TargetData); IRM.emitTranslationUnit(TU, StartElem); // Bail out if there are any errors. if (TU->Ctx.hadError()) return; llvm::OwningPtr<raw_fd_ostream> RawOS; formatted_raw_ostream FormattedOS; if (!Opts.OutputFilename.empty()) { // Try to open the output file. Clobbering an existing file is fine. // Open in binary mode if we're doing binary output. unsigned OSFlags = 0; if (isBinaryOutput(Opts.OutputKind)) OSFlags |= raw_fd_ostream::F_Binary; RawOS.reset(new raw_fd_ostream(Opts.OutputFilename.c_str(), Error, OSFlags)); if (RawOS->has_error()) { TU->Ctx.Diags.diagnose(SourceLoc(), diag::error_opening_output, Opts.OutputFilename, Error); return; } // Most output kinds want a formatted output stream. It's not clear // why writing an object file does. if (Opts.OutputKind != OutputKind::LLVMBitcode) FormattedOS.setStream(*RawOS, formatted_raw_ostream::PRESERVE_STREAM); } // Set up a pipeline. PassManagerBuilder PMBuilder; PMBuilder.OptLevel = Opts.OptLevel; // Configure the function passes. FunctionPassManager FunctionPasses(Module); FunctionPasses.add(new llvm::TargetData(*TargetData)); if (Opts.Verify) FunctionPasses.add(createVerifierPass()); PMBuilder.populateFunctionPassManager(FunctionPasses); // Run the function passes. FunctionPasses.doInitialization(); for (auto I = Module->begin(), E = Module->end(); I != E; ++I) if (!I->isDeclaration()) FunctionPasses.run(*I); FunctionPasses.doFinalization(); // Configure the module passes. PassManager ModulePasses; ModulePasses.add(new llvm::TargetData(*TargetData)); PMBuilder.populateModulePassManager(ModulePasses); // Set up the final emission passes. switch (Opts.OutputKind) { case OutputKind::Module: break; case OutputKind::LLVMAssembly: ModulePasses.add(createPrintModulePass(&FormattedOS)); break; case OutputKind::LLVMBitcode: ModulePasses.add(createBitcodeWriterPass(*RawOS)); break; case OutputKind::NativeAssembly: case OutputKind::ObjectFile: { TargetMachine::CodeGenFileType FileType; FileType = (Opts.OutputKind == OutputKind::NativeAssembly ? TargetMachine::CGFT_AssemblyFile : TargetMachine::CGFT_ObjectFile); if (TargetMachine->addPassesToEmitFile(ModulePasses, FormattedOS, FileType, !Opts.Verify)) { TU->Ctx.Diags.diagnose(SourceLoc(), diag::error_codegen_init_fail); return; } break; } } // Do it. ModulePasses.run(*Module); } <commit_msg>A couple minor tweaks to IRGen: turn on inlining when we're optimizing, and turn off non-leaf frame pointer elimination when we're generating an object file.<commit_after>//===--- IRGen.cpp - Swift LLVM IR Generation -----------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file implements the entrypoints into IR generation. // //===----------------------------------------------------------------------===// #include "swift/Subsystems.h" #include "swift/IRGen/Options.h" #include "swift/AST/AST.h" #include "swift/AST/Diagnostics.h" #include "llvm/LLVMContext.h" #include "llvm/Module.h" #include "llvm/PassManager.h" #include "llvm/Analysis/Verifier.h" #include "llvm/Assembly/PrintModulePass.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/Target/TargetData.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/IPO.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormattedStream.h" #include "llvm/Support/TargetRegistry.h" #include "IRGenModule.h" using namespace swift; using namespace irgen; using namespace llvm; static bool isBinaryOutput(OutputKind kind) { switch (kind) { case OutputKind::Module: case OutputKind::LLVMAssembly: case OutputKind::NativeAssembly: return false; case OutputKind::LLVMBitcode: case OutputKind::ObjectFile: return true; } llvm_unreachable("bad output kind!"); } void swift::performIRGeneration(Options &Opts, llvm::Module *Module, TranslationUnit *TU, unsigned StartElem) { assert(!TU->Ctx.hadError()); std::unique_ptr<LLVMContext> Context; std::unique_ptr<llvm::Module> ModuleOwner; if (!Module) { Context.reset(new LLVMContext); ModuleOwner.reset(new llvm::Module(Opts.OutputFilename, *Context)); Module = ModuleOwner.get(); } Module->setTargetTriple(Opts.Triple); std::string Error; const Target *Target = TargetRegistry::lookupTarget(Opts.Triple, Error); if (!Target) { TU->Ctx.Diags.diagnose(SourceLoc(), diag::no_llvm_target, Opts.Triple, Error); return; } // The integer values 0-3 map exactly to the values of this enum. CodeGenOpt::Level OptLevel = static_cast<CodeGenOpt::Level>(Opts.OptLevel); // Set up TargetOptions. // Things that maybe we should collect from the command line: // - CPU // - features // - relocation model // - code model TargetOptions Options; Options.NoFramePointerElimNonLeaf = true; // Create a target machine. TargetMachine *TargetMachine = Target->createTargetMachine(Opts.Triple, /*cpu*/ "", /*features*/ "", Options, Reloc::Default, CodeModel::Default, OptLevel); if (!TargetMachine) { TU->Ctx.Diags.diagnose(SourceLoc(), diag::no_llvm_target, Opts.Triple, "no LLVM target machine"); return; } // Set the module's string representation. const TargetData *TargetData = TargetMachine->getTargetData(); assert(TargetData && "target machine didn't set TargetData?"); Module->setDataLayout(TargetData->getStringRepresentation()); // Emit the translation unit. IRGenModule IRM(TU->Ctx, Opts, *Module, *TargetData); IRM.emitTranslationUnit(TU, StartElem); // Bail out if there are any errors. if (TU->Ctx.hadError()) return; llvm::OwningPtr<raw_fd_ostream> RawOS; formatted_raw_ostream FormattedOS; if (!Opts.OutputFilename.empty()) { // Try to open the output file. Clobbering an existing file is fine. // Open in binary mode if we're doing binary output. unsigned OSFlags = 0; if (isBinaryOutput(Opts.OutputKind)) OSFlags |= raw_fd_ostream::F_Binary; RawOS.reset(new raw_fd_ostream(Opts.OutputFilename.c_str(), Error, OSFlags)); if (RawOS->has_error()) { TU->Ctx.Diags.diagnose(SourceLoc(), diag::error_opening_output, Opts.OutputFilename, Error); return; } // Most output kinds want a formatted output stream. It's not clear // why writing an object file does. if (Opts.OutputKind != OutputKind::LLVMBitcode) FormattedOS.setStream(*RawOS, formatted_raw_ostream::PRESERVE_STREAM); } // Set up a pipeline. PassManagerBuilder PMBuilder; PMBuilder.OptLevel = Opts.OptLevel; if (Opts.OptLevel != 0) PMBuilder.Inliner = llvm::createFunctionInliningPass(200); // Configure the function passes. FunctionPassManager FunctionPasses(Module); FunctionPasses.add(new llvm::TargetData(*TargetData)); if (Opts.Verify) FunctionPasses.add(createVerifierPass()); PMBuilder.populateFunctionPassManager(FunctionPasses); // Run the function passes. FunctionPasses.doInitialization(); for (auto I = Module->begin(), E = Module->end(); I != E; ++I) if (!I->isDeclaration()) FunctionPasses.run(*I); FunctionPasses.doFinalization(); // Configure the module passes. PassManager ModulePasses; ModulePasses.add(new llvm::TargetData(*TargetData)); PMBuilder.populateModulePassManager(ModulePasses); // Set up the final emission passes. switch (Opts.OutputKind) { case OutputKind::Module: break; case OutputKind::LLVMAssembly: ModulePasses.add(createPrintModulePass(&FormattedOS)); break; case OutputKind::LLVMBitcode: ModulePasses.add(createBitcodeWriterPass(*RawOS)); break; case OutputKind::NativeAssembly: case OutputKind::ObjectFile: { TargetMachine::CodeGenFileType FileType; FileType = (Opts.OutputKind == OutputKind::NativeAssembly ? TargetMachine::CGFT_AssemblyFile : TargetMachine::CGFT_ObjectFile); if (TargetMachine->addPassesToEmitFile(ModulePasses, FormattedOS, FileType, !Opts.Verify)) { TU->Ctx.Diags.diagnose(SourceLoc(), diag::error_codegen_init_fail); return; } break; } } // Do it. ModulePasses.run(*Module); } <|endoftext|>
<commit_before>#include "internal.hpp" #include "clause.hpp" #include "macros.hpp" #include "message.hpp" #include "proof.hpp" #include <algorithm> namespace CaDiCaL { void Internal::watch_clause (Clause * c) { const int size = c->size; const int l0 = c->literals[0]; const int l1 = c->literals[1]; watch_literal (l0, l1, c, size); watch_literal (l1, l0, c, size); } /*------------------------------------------------------------------------*/ void Internal::mark_removed (Clause * c, int except) { LOG (c, "marking removed"); assert (!c->redundant); const const_literal_iterator end = c->end (); const_literal_iterator i; for (i = c->begin (); i != end; i++) if (*i != except) mark_removed (*i); } void Internal::mark_added (Clause * c) { LOG (c, "marking added"); assert (likely_to_be_kept_clause (c)); const const_literal_iterator end = c->end (); const_literal_iterator i; for (i = c->begin (); i != end; i++) mark_added (*i); } /*------------------------------------------------------------------------*/ // Redundant clauses of large glue and large size are extended to hold a // 'analyzed' time stamp. This makes memory allocation and deallocation a // little bit tricky but saves space and time. Since the embedding of the // literals is really important and on the same level of complexity we keep // both optimizations. Clause * Internal::new_clause (bool red, int glue) { assert (clause.size () <= (size_t) INT_MAX); const int size = (int) clause.size (); assert (size >= 2); bool have_pos = (size > 2), have_glue, have_analyzed; if (size == 2) have_pos = have_glue = have_analyzed = false; else if (red) { have_pos = have_glue = true; have_analyzed = (size > opts.keepsize && glue > opts.keepglue); } else have_pos = (size > 3), have_glue = have_analyzed = false; #ifndef NDEBUG if (have_glue) assert (have_pos); if (have_analyzed) assert (have_glue); #endif Clause * c; size_t offset = 0; if (!have_pos) offset += sizeof c->_pos; if (!have_glue) offset += sizeof c->_glue; if (!have_analyzed) offset += sizeof c->_analyzed; size_t bytes = sizeof (Clause) + (size - 2) * sizeof (int) - offset; char * ptr = new char[bytes]; ptr -= offset; c = (Clause*) ptr; c->have.analyzed = have_analyzed; c->have.glue = have_glue; c->have.pos = have_pos; c->redundant = red; c->garbage = false; c->reason = false; c->moved = false; c->size = size; for (int i = 0; i < size; i++) c->literals[i] = clause[i]; if (have_analyzed) c->_analyzed = ++stats.analyzed; if (have_glue) c->_glue = glue; if (have_pos) c->_pos = 2; assert (c->offset () == offset); if (red) stats.redundant++; else stats.irredundant++, stats.irrbytes += bytes; clauses.push_back (c); LOG (c, "new"); if (likely_to_be_kept_clause (c)) mark_added (c); return c; } // This is the 'raw' deallocation of a clause. If the clause is in the // arena nothing happens. If the clause is not in the arena and its memory // is reclaimed immediately and the allocation statistics is updated. void Internal::deallocate_clause (Clause * c) { char * p = c->start (); if (arena.contains (p)) return; LOG (c, "deallocate"); delete [] p; } void Internal::delete_clause (Clause * c) { LOG (c, "delete"); size_t bytes = c->bytes (); stats.collected += bytes; if (c->garbage) assert (stats.garbage >= bytes), stats.garbage -= bytes; if (proof) proof->trace_delete_clause (c); deallocate_clause (c); } // We want to eagerly update statistics as soon clauses are marked garbage. // Otherwise 'report' for instance gives wrong numbers after 'subsume' // before the next 'reduce'. Thus we factored out marking and accounting // for garbage clauses. Note that we do not update allocated bytes // statistics at this point, but wait until the next 'collect'. In order // not to miss any update to those statistics we call 'check_clause_stats' // after garbage collection in debugging mode. // void Internal::mark_garbage (Clause * c) { assert (!c->garbage); size_t bytes = c->bytes (); if (c->redundant) assert (stats.redundant), stats.redundant--; else { assert (stats.irredundant), stats.irredundant--; assert (stats.irrbytes >= bytes), stats.irrbytes -= bytes; } stats.garbage += bytes; c->garbage = true; if (!c->redundant) mark_removed (c); } bool Internal::tautological_clause () { sort (clause.begin (), clause.end (), lit_less_than ()); const_int_iterator i = clause.begin (); int_iterator j = clause.begin (); int prev = 0; while (i != clause.end ()) { int lit = *i++; if (lit == -prev) return true; if (lit != prev) *j++ = prev = lit; } if (j != clause.end ()) { LOG ("removing %d duplicates", (long)(clause.end () - j)); clause.resize (j - clause.begin ()); } return false; } void Internal::add_new_original_clause () { stats.original++; int size = (int) clause.size (); if (!size) { if (!unsat) { MSG ("original empty clause"); unsat = true; } else LOG ("original empty clause produces another inconsistency"); } else if (size == 1) { int unit = clause[0], tmp = val (unit); if (!tmp) assign_unit (unit); else if (tmp < 0) { if (!unsat) { MSG ("parsed clashing unit"); clashing = true; } else LOG ("original clashing unit produces another inconsistency"); } else LOG ("original redundant unit"); } else watch_clause (new_clause (false)); } Clause * Internal::new_learned_redundant_clause (int glue) { Clause * res = new_clause (true, glue); if (proof) proof->trace_add_clause (res); watch_clause (res); return res; } Clause * Internal::new_resolved_irredundant_clause () { Clause * res = new_clause (false); if (proof) proof->trace_add_clause (res); assert (!watches ()); return res; } }; <commit_msg>another alignment<commit_after>#include "internal.hpp" #include "clause.hpp" #include "macros.hpp" #include "message.hpp" #include "proof.hpp" #include <algorithm> namespace CaDiCaL { void Internal::watch_clause (Clause * c) { const int size = c->size; const int l0 = c->literals[0]; const int l1 = c->literals[1]; watch_literal (l0, l1, c, size); watch_literal (l1, l0, c, size); } /*------------------------------------------------------------------------*/ void Internal::mark_removed (Clause * c, int except) { LOG (c, "marking removed"); assert (!c->redundant); const const_literal_iterator end = c->end (); const_literal_iterator i; for (i = c->begin (); i != end; i++) if (*i != except) mark_removed (*i); } void Internal::mark_added (Clause * c) { LOG (c, "marking added"); assert (likely_to_be_kept_clause (c)); const const_literal_iterator end = c->end (); const_literal_iterator i; for (i = c->begin (); i != end; i++) mark_added (*i); } /*------------------------------------------------------------------------*/ // Redundant clauses of large glue and large size are extended to hold a // 'analyzed' time stamp. This makes memory allocation and deallocation a // little bit tricky but saves space and time. Since the embedding of the // literals is really important and on the same level of complexity we keep // both optimizations. Clause * Internal::new_clause (bool red, int glue) { assert (clause.size () <= (size_t) INT_MAX); const int size = (int) clause.size (); assert (size >= 2); bool have_pos = (size > 2), have_glue, have_analyzed; if (size == 2) have_pos = have_glue = have_analyzed = false; else if (red) { have_pos = have_glue = true; have_analyzed = (size > opts.keepsize && glue > opts.keepglue); } else have_pos = (size > 3), have_glue = have_analyzed = false; #ifndef NDEBUG if (have_glue) assert (have_pos); if (have_analyzed) assert (have_glue); #endif Clause * c; size_t offset = 0; if (!have_pos) offset += sizeof c->_pos; if (!have_glue) offset += sizeof c->_glue; if (!have_analyzed) offset += sizeof c->_analyzed; size_t bytes = sizeof (Clause) + (size - 2) * sizeof (int) - offset; char * ptr = new char[bytes]; ptr -= offset; c = (Clause*) ptr; c->have.analyzed = have_analyzed; c->have.glue = have_glue; c->have.pos = have_pos; c->redundant = red; c->garbage = false; c->reason = false; c->moved = false; c->size = size; for (int i = 0; i < size; i++) c->literals[i] = clause[i]; if (have_analyzed) c->_analyzed = ++stats.analyzed; if (have_glue) c->_glue = glue; if (have_pos) c->_pos = 2; assert (c->offset () == offset); if (red) stats.redundant++; else stats.irredundant++, stats.irrbytes += bytes; clauses.push_back (c); LOG (c, "new"); if (likely_to_be_kept_clause (c)) mark_added (c); return c; } // This is the 'raw' deallocation of a clause. If the clause is in the // arena nothing happens. If the clause is not in the arena and its memory // is reclaimed immediately and the allocation statistics is updated. void Internal::deallocate_clause (Clause * c) { char * p = c->start (); if (arena.contains (p)) return; LOG (c, "deallocate"); delete [] p; } void Internal::delete_clause (Clause * c) { LOG (c, "delete"); size_t bytes = c->bytes (); stats.collected += bytes; if (c->garbage) assert (stats.garbage >= (long) bytes), stats.garbage -= bytes; if (proof) proof->trace_delete_clause (c); deallocate_clause (c); } // We want to eagerly update statistics as soon clauses are marked garbage. // Otherwise 'report' for instance gives wrong numbers after 'subsume' // before the next 'reduce'. Thus we factored out marking and accounting // for garbage clauses. Note that we do not update allocated bytes // statistics at this point, but wait until the next 'collect'. In order // not to miss any update to those statistics we call 'check_clause_stats' // after garbage collection in debugging mode. // void Internal::mark_garbage (Clause * c) { assert (!c->garbage); size_t bytes = c->bytes (); if (c->redundant) assert (stats.redundant), stats.redundant--; else { assert (stats.irredundant), stats.irredundant--; assert (stats.irrbytes >= (long) bytes), stats.irrbytes -= bytes; } stats.garbage += bytes; c->garbage = true; if (!c->redundant) mark_removed (c); } bool Internal::tautological_clause () { sort (clause.begin (), clause.end (), lit_less_than ()); const_int_iterator i = clause.begin (); int_iterator j = clause.begin (); int prev = 0; while (i != clause.end ()) { int lit = *i++; if (lit == -prev) return true; if (lit != prev) *j++ = prev = lit; } if (j != clause.end ()) { LOG ("removing %d duplicates", (long)(clause.end () - j)); clause.resize (j - clause.begin ()); } return false; } void Internal::add_new_original_clause () { stats.original++; int size = (int) clause.size (); if (!size) { if (!unsat) { MSG ("original empty clause"); unsat = true; } else LOG ("original empty clause produces another inconsistency"); } else if (size == 1) { int unit = clause[0], tmp = val (unit); if (!tmp) assign_unit (unit); else if (tmp < 0) { if (!unsat) { MSG ("parsed clashing unit"); clashing = true; } else LOG ("original clashing unit produces another inconsistency"); } else LOG ("original redundant unit"); } else watch_clause (new_clause (false)); } Clause * Internal::new_learned_redundant_clause (int glue) { Clause * res = new_clause (true, glue); if (proof) proof->trace_add_clause (res); watch_clause (res); return res; } Clause * Internal::new_resolved_irredundant_clause () { Clause * res = new_clause (false); if (proof) proof->trace_add_clause (res); assert (!watches ()); return res; } }; <|endoftext|>
<commit_before>/* ESP Wlan configurator */ #include <ESP8266WebServer.h> #include <ESP8266WiFi.h> #include <EEPROM.h> #include <string> #include <time.h> #define EE_SIZE 512 // Size of eeprom #define EE_SSID_SIZE 32 // Max SSID size #define EE_PWD_SIZE 32 // Max password size #define EE_HOST_SIZE 32 // Max hostname size #define EE_SIG 0x7812 // Signature of a valid EEPROM content // WLAN configuration states #define ST_UNDEFINED 0 // Nothing #define ST_NOTCONFIGURED 1 // No valid WLAN configuration, starting AP #define ST_WAITFORCONFIG 2 // AP is started, waiting for User to enter data #define ST_INITCONFIGURED 3 // User entered connection information, closing AP #define ST_CONFIGURED 4 // Trying to connect to external AP #define ST_CONNECTED 5 // Connected to AP #define ST_STARTUPOK 6 // Cleanup #define ST_NORMALOPERATION 7 // Normal operation, connected to external AP String appName="MeisterWerk"; unsigned int uuid = 0; // Micro UUID typedef struct t_eeprom { unsigned short int sig; // Only, if sig is equal to EE_SIG, content of eeprom is considered valid unsigned short int uuid; // current micro-UUID char SSID[EE_SSID_SIZE]; // Network SSID char password[EE_PWD_SIZE]; char localhostname[EE_HOST_SIZE]; char _fill[EE_SIZE - EE_SSID_SIZE - EE_HOST_SIZE - EE_PWD_SIZE - 2 * sizeof(short int)]; } T_EEPROM; T_EEPROM eepr; ESP8266WebServer webserver(80); String localhostname; // WLAN configuration states ST_* unsigned int state = ST_UNDEFINED; void initEEPROM(T_EEPROM *pep) { memset((void *)pep, 0, EE_SIZE); pep->sig = EE_SIG; pep->uuid = uuid; } void readEEPROM(T_EEPROM *pep) { unsigned char *buf=(unsigned char *)pep; for (int i = 0; i < EE_SIZE; i++) { buf[i] = EEPROM.read(i); } } void writeEEPROM(T_EEPROM *pep) { unsigned char *buf=(unsigned char *)pep; for (int i = 0; i < EE_SIZE; i++) { EEPROM.write(i, buf[i]); } EEPROM.commit(); } String body; String header; String ipStr; int statusCode; unsigned int genUUID() { unsigned int uuid = random(65536); return uuid; } String UUIDtoString(unsigned int uuid) { char uuidstr[16]; itoa(uuid, uuidstr, 16); return String(uuidstr); } String defaultHostname() { return appName+"x"+UUIDtoString(uuid); } String stylesheet = R"MWx(<style> input[type=text], select { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } input[type=password], select { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } input[type=submit] { width: 100%; background-color: #7C7CE0; color: white; padding: 14px 20px; margin: 8px 0; border: none; border-radius: 4px; cursor: pointer; } input[type=submit]:hover { background-color: #4549a0; } div { border-radius: 5px; background-color: #f2f2f2; padding: 20px; font-family: Verdana, Arial, Sans-serif; }</style>)MWx"; void runWebServer() { webserver.on("/", []() { body = "<!DOCTYPE HTML>\r\n<html>"; body += stylesheet; body += "<div><h3>"+header+"</h3>"; body += appName+"-node at "+ipStr + ", "+localhostname+", UUID="+UUIDtoString(uuid)+"</div><p></p>"; body += "<div><form method='get' action='save'>" "<label>SSID: </label><input name='ssid' type='text' value='"+String(eepr.SSID)+"' length=31><br>" "<label>Password: </label><input name='pass' type='password' value='"+String(eepr.password)+"' length=31><br>" "<label>Hostname: </label><input name='host' type='text' value='"+String(eepr.localhostname)+"' length=31><br>" "<input type='submit' value='Save'></form></div><p></p>"; body += "<div><form method='get' action='factory'>" "<label>Factory reset:</label><br><input type='submit' value='Reset'></form></div>"; body += "</html>"; webserver.send(200, "text/html", body); }); webserver.on("/save", []() { initEEPROM(&eepr); String ssid = webserver.arg("ssid"); String pwd = webserver.arg("pass"); String host = webserver.arg("host"); strncpy(eepr.SSID, ssid.c_str(), EE_SSID_SIZE - 1); strncpy(eepr.password, pwd.c_str(), EE_PWD_SIZE - 1); strncpy(eepr.localhostname, host.c_str(), EE_HOST_SIZE - 1); localhostname=String(eepr.localhostname); writeEEPROM(&eepr); body = "{\"Success\":\"saved " + ssid + " to eeprom.\"}"; statusCode = 200; webserver.send(statusCode, "application/json", body); state = ST_INITCONFIGURED; }); webserver.on("/factory", []() { memset((unsigned char *)&eepr,0,sizeof(T_EEPROM)); writeEEPROM(&eepr); body = "{\"Success\":\"erased eeprom.\"}"; statusCode = 200; webserver.send(statusCode, "application/json", body); state = ST_NOTCONFIGURED; }); webserver.begin(); } // Web server that runs during initial configuration, AP is ESP-module. void initialConfigServer() { IPAddress ip = WiFi.softAPIP(); ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]); header="Access point mode"; runWebServer(); } // Web server that runs if connected to external access point (normal operation) void startConfigServer() { IPAddress ip = WiFi.localIP(); ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]); header="Client mode"; runWebServer(); } // create local AP for initial config bool createAP(String name, String password="") { IPAddress apIP(10, 1, 1, 1); // Private network address: local & gateway IPAddress apNet(255, 255, 255, 0); WiFi.mode(WIFI_AP_STA); WiFi.softAPConfig(apIP, apIP, apNet); if (password=="") WiFi.softAP(name.c_str()); else WiFi.softAP(name.c_str(), password.c_str()); WiFi.hostname(localhostname.c_str()); state = ST_WAITFORCONFIG; initialConfigServer(); } unsigned int connectTimeout=30; // Number seconds, a connect to configured access point is tried, // before a local access point is spawned. // connect to external AP, create a local AP if cnnection fails for connectTimeout secs. bool connectToAp() { WiFi.mode(WIFI_STA); Serial.println("Connecting to "+String(eepr.SSID)+", "+String(eepr.password)); WiFi.begin(eepr.SSID, eepr.password); WiFi.hostname(localhostname.c_str()); digitalWrite(LED_BUILTIN, LOW); // LED on during connect-attempt for (int t=0; t<connectTimeout*10; t++) { // connectTimeout sec. timeout. if (WiFi.status() == WL_CONNECTED) { state=ST_CONNECTED; Serial.println("Connection successful!"); return true; } delay(100); } WiFi.disconnect(); Serial.println("Connection failed!"); state=ST_NOTCONFIGURED; // This needs to be removed (or adapted) for Leo-Use-Case XXX-LEO // Setting state to NOTCONFIGURED causes spawning of local access point. // In order to retry connection with existing configuration, simply set to ST_CONFIGURED. return false; } void setup() { Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); Serial.println("Starting up."); EEPROM.begin(512); state = ST_CONFIGURED; readEEPROM(&eepr); if (eepr.sig != EE_SIG) { uuid = genUUID(); Serial.println("New UUID generated."); initEEPROM(&eepr); localhostname=defaultHostname(); strncpy(eepr.localhostname,localhostname.c_str(),EE_HOST_SIZE-1); writeEEPROM(&eepr); } else { uuid=eepr.uuid; localhostname=String(eepr.localhostname); } Serial.println("Unique name: "+localhostname); if (eepr.SSID[0] == 0) { Serial.println("State: ST_NOTCONFIGURED"); state = ST_NOTCONFIGURED; } else { Serial.println("State: ST_CONFIGURED"); state = ST_CONFIGURED; } } unsigned int ctr = 0; unsigned int blfreq=10000; void loop() { // non-blocking event loop ++ctr; switch (state) { case ST_NOTCONFIGURED: Serial.println("Unconfigured server, creating AP"); blfreq=10000; // fast blink: initial config localhostname=defaultHostname(); createAP(localhostname); // use localhostname as network-name on initial setup. break; case ST_WAITFORCONFIG: break; case ST_INITCONFIGURED: Serial.println("Received connection information"); webserver.stop(); WiFi.disconnect(); state=ST_CONFIGURED; break; case ST_CONFIGURED: Serial.println("Configured, trying connect to AP"); connectToAp(); break; case ST_CONNECTED: Serial.println("Connected to AP"); blfreq=20000; // slow blink: normal operation startConfigServer(); state=ST_STARTUPOK; break; case ST_STARTUPOK: Serial.println("Ready for things to be done."); state=ST_NORMALOPERATION; break; case ST_NORMALOPERATION: break; } if (ctr % blfreq == 0) digitalWrite(LED_BUILTIN, LOW); // Turn the LED on if (ctr % (blfreq*2) == 0) digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off if (ctr > (blfreq*3)) ctr = 0; webserver.handleClient(); // handle web requests } <commit_msg>Tune style-sheet for mobile clients<commit_after>/* ESP Wlan configurator */ #include <ESP8266WebServer.h> #include <ESP8266WiFi.h> #include <EEPROM.h> #include <string> #include <time.h> #define EE_SIZE 512 // Size of eeprom #define EE_SSID_SIZE 32 // Max SSID size #define EE_PWD_SIZE 32 // Max password size #define EE_HOST_SIZE 32 // Max hostname size #define EE_SIG 0x7812 // Signature of a valid EEPROM content // WLAN configuration states #define ST_UNDEFINED 0 // Nothing #define ST_NOTCONFIGURED 1 // No valid WLAN configuration, starting AP #define ST_WAITFORCONFIG 2 // AP is started, waiting for User to enter data #define ST_INITCONFIGURED 3 // User entered connection information, closing AP #define ST_CONFIGURED 4 // Trying to connect to external AP #define ST_CONNECTED 5 // Connected to AP #define ST_STARTUPOK 6 // Cleanup #define ST_NORMALOPERATION 7 // Normal operation, connected to external AP String appName="MeisterWerk"; unsigned int uuid = 0; // Micro UUID typedef struct t_eeprom { unsigned short int sig; // Only, if sig is equal to EE_SIG, content of eeprom is considered valid unsigned short int uuid; // current micro-UUID char SSID[EE_SSID_SIZE]; // Network SSID char password[EE_PWD_SIZE]; char localhostname[EE_HOST_SIZE]; char _fill[EE_SIZE - EE_SSID_SIZE - EE_HOST_SIZE - EE_PWD_SIZE - 2 * sizeof(short int)]; } T_EEPROM; T_EEPROM eepr; ESP8266WebServer webserver(80); String localhostname; // WLAN configuration states ST_* unsigned int state = ST_UNDEFINED; void initEEPROM(T_EEPROM *pep) { memset((void *)pep, 0, EE_SIZE); pep->sig = EE_SIG; pep->uuid = uuid; } void readEEPROM(T_EEPROM *pep) { unsigned char *buf=(unsigned char *)pep; for (int i = 0; i < EE_SIZE; i++) { buf[i] = EEPROM.read(i); } } void writeEEPROM(T_EEPROM *pep) { unsigned char *buf=(unsigned char *)pep; for (int i = 0; i < EE_SIZE; i++) { EEPROM.write(i, buf[i]); } EEPROM.commit(); } String body; String header; String ipStr; int statusCode; unsigned int genUUID() { unsigned int uuid = random(65536); return uuid; } String UUIDtoString(unsigned int uuid) { char uuidstr[16]; itoa(uuid, uuidstr, 16); return String(uuidstr); } String defaultHostname() { return appName+"x"+UUIDtoString(uuid); } String stylesheet = R"MWx(<style> input[type=text], select { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; font-size: 18px; } input[type=password], select { width: 100%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; font-size: 18px; } input[type=submit] { width: 100%; background-color: #7C7CE0; color: white; padding: 14px 20px; margin: 8px 0; border: none; border-radius: 4px; cursor: pointer; font-size: 18px; } input[type=submit]:hover { background-color: #4549a0; } div { width: 640px; border-radius: 5px; background-color: #f2f2f2; padding: 20px; font-family: Verdana, Arial, Sans-serif; }</style>)MWx"; void runWebServer() { webserver.on("/", []() { body = "<!DOCTYPE HTML>\r\n<html>"; body += stylesheet; body += "<div><h3>"+header+"</h3>"; body += appName+"-node at "+ipStr + ", "+localhostname+", UUID="+UUIDtoString(uuid)+"</div><p></p>"; body += "<div><form method='get' action='save'>" "<label>SSID: </label><input name='ssid' type='text' value='"+String(eepr.SSID)+"' length=31><br>" "<label>Password: </label><input name='pass' type='password' value='"+String(eepr.password)+"' length=31><br>" "<label>Hostname: </label><input name='host' type='text' value='"+String(eepr.localhostname)+"' length=31><br>" "<input type='submit' value='Save'></form></div><p></p>"; body += "<div><form method='get' action='factory'>" "<label>Factory reset:</label><br><input type='submit' value='Reset'></form></div>"; body += "</html>"; webserver.send(200, "text/html", body); }); webserver.on("/save", []() { initEEPROM(&eepr); String ssid = webserver.arg("ssid"); String pwd = webserver.arg("pass"); String host = webserver.arg("host"); strncpy(eepr.SSID, ssid.c_str(), EE_SSID_SIZE - 1); strncpy(eepr.password, pwd.c_str(), EE_PWD_SIZE - 1); strncpy(eepr.localhostname, host.c_str(), EE_HOST_SIZE - 1); localhostname=String(eepr.localhostname); writeEEPROM(&eepr); body = "{\"Success\":\"saved " + ssid + " to eeprom.\"}"; statusCode = 200; webserver.send(statusCode, "application/json", body); state = ST_INITCONFIGURED; }); webserver.on("/factory", []() { memset((unsigned char *)&eepr,0,sizeof(T_EEPROM)); writeEEPROM(&eepr); body = "{\"Success\":\"erased eeprom.\"}"; statusCode = 200; webserver.send(statusCode, "application/json", body); state = ST_NOTCONFIGURED; }); webserver.begin(); } // Web server that runs during initial configuration, AP is ESP-module. void initialConfigServer() { IPAddress ip = WiFi.softAPIP(); ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]); header="Access point mode"; runWebServer(); } // Web server that runs if connected to external access point (normal operation) void startConfigServer() { IPAddress ip = WiFi.localIP(); ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]); header="Client mode"; runWebServer(); } // create local AP for initial config bool createAP(String name, String password="") { IPAddress apIP(10, 1, 1, 1); // Private network address: local & gateway IPAddress apNet(255, 255, 255, 0); WiFi.mode(WIFI_AP_STA); WiFi.softAPConfig(apIP, apIP, apNet); if (password=="") WiFi.softAP(name.c_str()); else WiFi.softAP(name.c_str(), password.c_str()); WiFi.hostname(localhostname.c_str()); state = ST_WAITFORCONFIG; initialConfigServer(); } unsigned int connectTimeout=30; // Number seconds, a connect to configured access point is tried, // before a local access point is spawned. // connect to external AP, create a local AP if cnnection fails for connectTimeout secs. bool connectToAp() { WiFi.mode(WIFI_STA); Serial.println("Connecting to "+String(eepr.SSID)+", "+String(eepr.password)); WiFi.begin(eepr.SSID, eepr.password); WiFi.hostname(localhostname.c_str()); digitalWrite(LED_BUILTIN, LOW); // LED on during connect-attempt for (int t=0; t<connectTimeout*10; t++) { // connectTimeout sec. timeout. if (WiFi.status() == WL_CONNECTED) { state=ST_CONNECTED; Serial.println("Connection successful!"); return true; } delay(100); } WiFi.disconnect(); Serial.println("Connection failed!"); state=ST_NOTCONFIGURED; // This needs to be removed (or adapted) for Leo-Use-Case XXX-LEO // Setting state to NOTCONFIGURED causes spawning of local access point. // In order to retry connection with existing configuration, simply set to ST_CONFIGURED. return false; } void setup() { Serial.begin(9600); pinMode(LED_BUILTIN, OUTPUT); Serial.println("Starting up."); EEPROM.begin(512); state = ST_CONFIGURED; readEEPROM(&eepr); if (eepr.sig != EE_SIG) { uuid = genUUID(); Serial.println("New UUID generated."); initEEPROM(&eepr); localhostname=defaultHostname(); strncpy(eepr.localhostname,localhostname.c_str(),EE_HOST_SIZE-1); writeEEPROM(&eepr); } else { uuid=eepr.uuid; localhostname=String(eepr.localhostname); } Serial.println("Unique name: "+localhostname); if (eepr.SSID[0] == 0) { Serial.println("State: ST_NOTCONFIGURED"); state = ST_NOTCONFIGURED; } else { Serial.println("State: ST_CONFIGURED"); state = ST_CONFIGURED; } } unsigned int ctr = 0; unsigned int blfreq=10000; void loop() { // non-blocking event loop ++ctr; switch (state) { case ST_NOTCONFIGURED: Serial.println("Unconfigured server, creating AP"); blfreq=10000; // fast blink: initial config localhostname=defaultHostname(); createAP(localhostname); // use localhostname as network-name on initial setup. break; case ST_WAITFORCONFIG: break; case ST_INITCONFIGURED: Serial.println("Received connection information"); webserver.stop(); WiFi.disconnect(); state=ST_CONFIGURED; break; case ST_CONFIGURED: Serial.println("Configured, trying connect to AP"); connectToAp(); break; case ST_CONNECTED: Serial.println("Connected to AP"); blfreq=20000; // slow blink: normal operation startConfigServer(); state=ST_STARTUPOK; break; case ST_STARTUPOK: Serial.println("Ready for things to be done."); state=ST_NORMALOPERATION; break; case ST_NORMALOPERATION: break; } if (ctr % blfreq == 0) digitalWrite(LED_BUILTIN, LOW); // Turn the LED on if (ctr % (blfreq*2) == 0) digitalWrite(LED_BUILTIN, HIGH); // Turn the LED off if (ctr > (blfreq*3)) ctr = 0; webserver.handleClient(); // handle web requests } <|endoftext|>
<commit_before>#include "hphp/runtime/ext/extension.h" #include "hphp/runtime/base/array-iterator.h" #include <bson.h> #include "encode.h" #include "classes.h" namespace HPHP { void fillBSONWithArray(const Array& value, bson_t* bson) { for (ArrayIter iter(value); iter; ++iter) { Variant key(iter.first()); const Variant& data(iter.secondRef()); variantToBSON(data, key.toString().c_str(), bson); } } void variantToBSON(const Variant& value, const char* key, bson_t* bson) { switch(value.getType()) { case KindOfUninit: case KindOfNull: nullToBSON(key, bson); break; case KindOfBoolean: boolToBSON(value.toBoolean(), key, bson); break; case KindOfInt64: int64ToBSON(value.toInt64(), key, bson); break; case KindOfDouble: doubleToBSON(value.toDouble(), key, bson); break; case KindOfStaticString: case KindOfString: stringToBSON(value.toString(), key, bson); break; case KindOfArray: arrayToBSON(value.toArray(), key, bson); break; case KindOfObject: objectToBSON(value.toObject(), key, bson); break; default: break; } } void arrayToBSON(const Array& value, const char* key, bson_t* bson) { bson_t child; bool isDocument = arrayIsDocument(value); if (isDocument) { bson_append_document_begin(bson, key, -1, &child); } else { bson_append_array_begin(bson, key, -1, &child); } fillBSONWithArray(value, &child); if (isDocument) { bson_append_document_end(bson, &child); } else { bson_append_array_end(bson, &child); } } void doubleToBSON(const double value,const char* key, bson_t* bson) { bson_append_double(bson, key, -1, value); } void nullToBSON(const char* key, bson_t* bson) { bson_append_null(bson, key, -1); } void boolToBSON(const bool value, const char* key, bson_t* bson) { bson_append_bool(bson, key, -1, value); } void int64ToBSON(const int64_t value, const char* key, bson_t* bson) { bson_append_int64(bson, key, -1, value); } void stringToBSON(const String& value, const char* key, bson_t* bson) { bson_append_utf8(bson, key, strlen(key), value.c_str(), -1); } void objectToBSON(const Object& value, const char* key, bson_t* bson) { #if HHVM_API_VERSION >= 20150112L const String& className = value->getClassName(); #else const String& className = value->o_getClassName(); #endif if (className == s_MongoId) { mongoIdToBSON(value, key, bson); } else if (className == s_MongoDate) { mongoDateToBSON(value, key, bson); } else if (className == s_MongoRegex) { mongoRegexToBSON(value, key, bson); } else if (className == s_MongoTimestamp) { mongoTimestampToBSON(value, key, bson); } else if (className == s_MongoCode) { mongoCodeToBSON(value, key, bson); } else if (className == s_MongoBinData) { mongoBinDataToBSON(value, key, bson); } else if (className == s_MongoInt32) { mongoInt32ToBSON(value, key, bson); } else if (className == s_MongoInt64) { mongoInt64ToBSON(value, key, bson); } else if (className == s_MongoMaxKey) { mongoMaxKeyToBSON(key, bson); } else if (className == s_MongoMinKey) { mongoMinKeyToBSON(key, bson); } else { arrayToBSON(value.toArray(), key, bson); } } ////////////////////////////////////////////////////////////////////////////// void mongoTimestampToBSON(const Object& value, const char* key, bson_t* bson) { bson_append_timestamp(bson, key, -1, value->o_get("sec").toInt64(), value->o_get("inc").toInt64() ); } void mongoRegexToBSON(const Object& value, const char* key, bson_t* bson) { bson_append_regex(bson, key, -1, value->o_get("regex").toString().c_str(), value->o_get("flags").toString().c_str() ); } void mongoIdToBSON(const Object& value, const char* key, bson_t* bson) { bson_oid_t oid; bson_oid_init_from_string(&oid, value->o_get("$id").toString().c_str()); bson_append_oid(bson, key, -1, &oid); } void mongoDateToBSON(const Object& value, const char* key, bson_t* bson) { int64_t mili = (value->o_get("sec").toInt64() * 1000) + (value->o_get("usec").toInt64() / 1000); bson_append_date_time(bson, key, -1, mili); } void mongoCodeToBSON(const Object& value, const char* key, bson_t* bson) { bson_t child; bson_init(&child); fillBSONWithArray( value->o_get("scope", true, String(s_MongoCode.get())).toArray(), &child ); bson_append_code_with_scope(bson, key, -1, value->o_get("code", true, String(s_MongoCode.get())).toString().c_str(), &child ); } void mongoBinDataToBSON(const Object& value, const char* key, bson_t* bson) { const String& binary = value->o_get("bin").toString(); bson_append_binary(bson, key, -1, (bson_subtype_t) value->o_get("type").toInt32(), (const uint8_t*) binary.c_str(), binary.size() ); } void mongoInt32ToBSON(const Object& value, const char* key, bson_t* bson) { bson_append_int32(bson, key, -1, value->o_get("value").toInt32()); } void mongoInt64ToBSON(const Object& value, const char* key, bson_t* bson) { bson_append_int64(bson, key, -1, value->o_get("value").toInt64()); } void mongoMinKeyToBSON(const char* key, bson_t* bson) { bson_append_minkey(bson, key, -1); } void mongoMaxKeyToBSON(const char* key, bson_t* bson) { bson_append_maxkey(bson, key, -1); } ////////////////////////////////////////////////////////////////////////////// //* Objects *// bool arrayIsDocument(const Array& arr) { int64_t max_index = 0; for (ArrayIter it(arr); it; ++it) { Variant key = it.first(); if (!key.isNumeric()) { return true; } int64_t index = key.toInt64(); if (index < 0) { return true; } if (index > max_index) { max_index = index; } } if (max_index >= arr.size() * 2) { // Might as well store it as a map return true; } return false; } } <commit_msg>hhvm 3.12.1 renamed KindOfStaticString<commit_after>#include "hphp/runtime/ext/extension.h" #include "hphp/runtime/base/array-iterator.h" #include <bson.h> #include "encode.h" #include "classes.h" #if HHVM_VERSION_ID > ((3 << 16) | (12 << 8)) #define KindOfStaticString KindOfPersistentString #else #define KindOfStaticString KindOfStaticString #endif namespace HPHP { void fillBSONWithArray(const Array& value, bson_t* bson) { for (ArrayIter iter(value); iter; ++iter) { Variant key(iter.first()); const Variant& data(iter.secondRef()); variantToBSON(data, key.toString().c_str(), bson); } } void variantToBSON(const Variant& value, const char* key, bson_t* bson) { switch(value.getType()) { case KindOfUninit: case KindOfNull: nullToBSON(key, bson); break; case KindOfBoolean: boolToBSON(value.toBoolean(), key, bson); break; case KindOfInt64: int64ToBSON(value.toInt64(), key, bson); break; case KindOfDouble: doubleToBSON(value.toDouble(), key, bson); break; case KindOfStaticString: case KindOfString: stringToBSON(value.toString(), key, bson); break; case KindOfArray: arrayToBSON(value.toArray(), key, bson); break; case KindOfObject: objectToBSON(value.toObject(), key, bson); break; default: break; } } void arrayToBSON(const Array& value, const char* key, bson_t* bson) { bson_t child; bool isDocument = arrayIsDocument(value); if (isDocument) { bson_append_document_begin(bson, key, -1, &child); } else { bson_append_array_begin(bson, key, -1, &child); } fillBSONWithArray(value, &child); if (isDocument) { bson_append_document_end(bson, &child); } else { bson_append_array_end(bson, &child); } } void doubleToBSON(const double value,const char* key, bson_t* bson) { bson_append_double(bson, key, -1, value); } void nullToBSON(const char* key, bson_t* bson) { bson_append_null(bson, key, -1); } void boolToBSON(const bool value, const char* key, bson_t* bson) { bson_append_bool(bson, key, -1, value); } void int64ToBSON(const int64_t value, const char* key, bson_t* bson) { bson_append_int64(bson, key, -1, value); } void stringToBSON(const String& value, const char* key, bson_t* bson) { bson_append_utf8(bson, key, strlen(key), value.c_str(), -1); } void objectToBSON(const Object& value, const char* key, bson_t* bson) { #if HHVM_API_VERSION >= 20150112L const String& className = value->getClassName(); #else const String& className = value->o_getClassName(); #endif if (className == s_MongoId) { mongoIdToBSON(value, key, bson); } else if (className == s_MongoDate) { mongoDateToBSON(value, key, bson); } else if (className == s_MongoRegex) { mongoRegexToBSON(value, key, bson); } else if (className == s_MongoTimestamp) { mongoTimestampToBSON(value, key, bson); } else if (className == s_MongoCode) { mongoCodeToBSON(value, key, bson); } else if (className == s_MongoBinData) { mongoBinDataToBSON(value, key, bson); } else if (className == s_MongoInt32) { mongoInt32ToBSON(value, key, bson); } else if (className == s_MongoInt64) { mongoInt64ToBSON(value, key, bson); } else if (className == s_MongoMaxKey) { mongoMaxKeyToBSON(key, bson); } else if (className == s_MongoMinKey) { mongoMinKeyToBSON(key, bson); } else { arrayToBSON(value.toArray(), key, bson); } } ////////////////////////////////////////////////////////////////////////////// void mongoTimestampToBSON(const Object& value, const char* key, bson_t* bson) { bson_append_timestamp(bson, key, -1, value->o_get("sec").toInt64(), value->o_get("inc").toInt64() ); } void mongoRegexToBSON(const Object& value, const char* key, bson_t* bson) { bson_append_regex(bson, key, -1, value->o_get("regex").toString().c_str(), value->o_get("flags").toString().c_str() ); } void mongoIdToBSON(const Object& value, const char* key, bson_t* bson) { bson_oid_t oid; bson_oid_init_from_string(&oid, value->o_get("$id").toString().c_str()); bson_append_oid(bson, key, -1, &oid); } void mongoDateToBSON(const Object& value, const char* key, bson_t* bson) { int64_t mili = (value->o_get("sec").toInt64() * 1000) + (value->o_get("usec").toInt64() / 1000); bson_append_date_time(bson, key, -1, mili); } void mongoCodeToBSON(const Object& value, const char* key, bson_t* bson) { bson_t child; bson_init(&child); fillBSONWithArray( value->o_get("scope", true, String(s_MongoCode.get())).toArray(), &child ); bson_append_code_with_scope(bson, key, -1, value->o_get("code", true, String(s_MongoCode.get())).toString().c_str(), &child ); } void mongoBinDataToBSON(const Object& value, const char* key, bson_t* bson) { const String& binary = value->o_get("bin").toString(); bson_append_binary(bson, key, -1, (bson_subtype_t) value->o_get("type").toInt32(), (const uint8_t*) binary.c_str(), binary.size() ); } void mongoInt32ToBSON(const Object& value, const char* key, bson_t* bson) { bson_append_int32(bson, key, -1, value->o_get("value").toInt32()); } void mongoInt64ToBSON(const Object& value, const char* key, bson_t* bson) { bson_append_int64(bson, key, -1, value->o_get("value").toInt64()); } void mongoMinKeyToBSON(const char* key, bson_t* bson) { bson_append_minkey(bson, key, -1); } void mongoMaxKeyToBSON(const char* key, bson_t* bson) { bson_append_maxkey(bson, key, -1); } ////////////////////////////////////////////////////////////////////////////// //* Objects *// bool arrayIsDocument(const Array& arr) { int64_t max_index = 0; for (ArrayIter it(arr); it; ++it) { Variant key = it.first(); if (!key.isNumeric()) { return true; } int64_t index = key.toInt64(); if (index < 0) { return true; } if (index > max_index) { max_index = index; } } if (max_index >= arr.size() * 2) { // Might as well store it as a map return true; } return false; } } <|endoftext|>
<commit_before>#include "core.h" #include "mpicontroller.h" #include "move.h" #include "montecarlo.h" #include "analysis.h" #include "docopt.h" #include "progress_tracker.h" #include <cstdlib> #include "spdlog/spdlog.h" #include <spdlog/sinks/null_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <iomanip> #include <unistd.h> #ifdef ENABLE_SID #include "cppsid.h" #include <thread> using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono_literals; // ns, us, ms, s, h, etc. using std::chrono::system_clock; #endif using namespace Faunus; using namespace std; #define Q(x) #x #define QUOTE(x) Q(x) #ifndef FAUNUS_TIPSFILE #define FAUNUS_TIPSFILE "" #endif static const char USAGE[] = R"(Faunus - the Monte Carlo code you're looking for! http://github.com/mlund/faunus Usage: faunus [-q] [--verbosity <N>] [--nobar] [--nopfx] [--notips] [--nofun] [--state=<file>] [--input=<file>] [--output=<file>] faunus (-h | --help) faunus --version Options: -i <file> --input <file> Input file [default: /dev/stdin]. -o <file> --output <file> Output file [default: out.json]. -s <file> --state <file> State file to start from (.json/.ubj). -v <N> --verbosity <N> Log verbosity level (0 = off, 1 = critical, ..., 6 = trace) [default: 3] -q --quiet Less verbose output. -h --help Show this screen. --nobar No progress bar. --nopfx Do not prefix input file with MPI rank. --notips Do not give input assistance --nofun No fun --version Show version. Multiple processes using MPI: 1. input and output files are prefixed with "mpi{rank}." 2. standard output is redirected to "mpi{rank}.stdout" 3. Input prefixing can be suppressed with --nopfx )"; using ProgressIndicator::ProgressTracker; std::shared_ptr<ProgressTracker> createProgressTracker(bool, unsigned int); int main(int argc, char **argv) { using namespace Faunus::MPI; bool nofun; try { std::string version = "Faunus"; #ifdef GIT_LATEST_TAG version += " "s + QUOTE(GIT_LATEST_TAG); #endif #ifdef GIT_COMMIT_HASH version += " git " + std::string(GIT_COMMIT_HASH); #endif #ifdef ENABLE_SID version += " [sid]"; #endif #ifdef ENABLE_MPI version += " [mpi]"; #endif #ifdef _OPENMP version += " [openmp]"; #endif auto args = docopt::docopt(USAGE, {argv + 1, argv + argc}, true, version); mpi.init(); // initialize MPI, if available // prepare loggers // TODO refactor to a standalone function and use cmd line options for different sinks, etc. faunus_logger = spdlog::stderr_color_mt("faunus"); faunus_logger->set_pattern("[%n %P] %^%L: %v%$"); mcloop_logger = spdlog::stderr_color_mt("mcloop"); mcloop_logger->set_pattern("[%n %P] [%E.%f] %L: %v"); // --verbosity (log level) long log_level = spdlog::level::off - args["--verbosity"].asLong(); // reverse sequence 0 → 6 to 6 → 0 spdlog::set_level(static_cast<spdlog::level::level_enum>(log_level)); // --notips if (not args["--notips"].asBool()) usageTip.load({FAUNUS_TIPSFILE}); // --nobar bool show_progress = !args["--nobar"].asBool(); // --quiet bool quiet = args["--quiet"].asBool(); if (quiet) { cout.setstate(std::ios_base::failbit); // hold kæft show_progress = false; } // --nofun nofun = args["--nofun"].asBool(); if (nofun or quiet) usageTip.asciiart = false; #ifdef ENABLE_SID usageTip.asciiart = false; // if SID is enabled, disable ascii #endif // --nopfx bool prefix = !args["--nopfx"].asBool(); // --input json j; auto input = args["--input"].asString(); if (input == "/dev/stdin") std::cin >> j; else { if (prefix) input = Faunus::MPI::prefix + input; j = openjson(input); } { pc::temperature = j.at("temperature").get<double>() * 1.0_K; MCSimulation sim(j, mpi); // --state if (args["--state"]) { std::ifstream f; std::string state = Faunus::MPI::prefix + args["--state"].asString(); std::string suffix = state.substr(state.find_last_of(".") + 1); bool binary = (suffix == "ubj"); auto mode = std::ios::in; if (binary) mode = std::ifstream::ate | std::ios::binary; // ate = open at end f.open(state, mode); if (f) { json j; if (not quiet) faunus_logger->info("loading state file {}", state); if (binary) { size_t size = f.tellg(); // get file size std::vector<std::uint8_t> v(size / sizeof(std::uint8_t)); f.seekg(0, f.beg); // go back to start f.read((char *)v.data(), size); j = json::from_ubjson(v); } else f >> j; sim.restore(j); } else throw std::runtime_error("state file error: " + state); } Analysis::CombinedAnalysis analysis(j.at("analysis"), sim.space(), sim.pot()); auto &loop = j.at("mcloop"); int macro = loop.at("macro"); int micro = loop.at("micro"); auto progress_tracker = createProgressTracker(show_progress, macro * micro); for (int i = 0; i < macro; i++) { for (int j = 0; j < micro; j++) { if (progress_tracker && mpi.isMaster()) { if(++(*progress_tracker) % 10 == 0) { progress_tracker->display(); } } sim.move(); analysis.sample(); } } if (progress_tracker && mpi.isMaster()) { progress_tracker->done(); if (not quiet) { faunus_logger->log((sim.drift() < 1E-9) ? spdlog::level::info : spdlog::level::warn, "relative drift = {}", sim.drift()); } // --output std::ofstream f(Faunus::MPI::prefix + args["--output"].asString()); if (f) { json j; Faunus::to_json(j, sim); j["relative drift"] = sim.drift(); j["analysis"] = analysis; if (mpi.nproc() > 1) j["mpi"] = mpi; #ifdef GIT_COMMIT_HASH j["git revision"] = GIT_COMMIT_HASH; #endif #ifdef __VERSION__ j["compiler"] = __VERSION__; #endif f << std::setw(4) << j << endl; } } mpi.finalize(); } catch (std::exception &e) { faunus_logger->error(e.what()); if (not usageTip.buffer.empty()) faunus_logger->error(usageTip.buffer); #ifdef ENABLE_SID // easter egg... if (not nofun and mpi.isMaster()) { // -> fun try { // look for json file with hvsc sid tune names std::string pfx; json j; for (std::string dir : {FAUNUS_BINARY_DIR, FAUNUS_INSTALL_PREFIX "/share/faunus/"}) { // installed and uninstalled cmake builds j = Faunus::openjson(dir + "/sids/music.json", false); if (not j.empty()) { pfx = dir + "/"; break; } } if (not j.empty()) { j = j.at("songs"); // load playlist std::vector<size_t> weight; // weight for each tune (= number of subsongs) for (auto &i : j) weight.push_back(i.at("subsongs").size()); std::discrete_distribution<size_t> dist(weight.begin(), weight.end()); Faunus::random.seed(); // give global random a hardware seed auto it = j.begin() + dist(Faunus::random.engine); // pick random tune weighted by subsongs auto subsongs = (*it).at("subsongs").get<std::vector<int>>(); // all subsongs int subsong = *(Faunus::random.sample(subsongs.begin(), subsongs.end())) - 1; // random subsong CPPSID::Player player; // let's emulate a Commodore 64... if (player.load(pfx + it->at("file").get<std::string>(), subsong)) { faunus_logger->info("error message music '{}' by {}, {} (6502/SID emulation)", player.title(), player.author(), player.info()); faunus_logger->info("\033[1mpress ctrl-c to quit\033[0m"); player.start(); // start music sleep_for(10ns); // short delay sleep_until(system_clock::now() + 240s); // play for 4 minutes, then exit player.stop(); std::cout << std::endl; } } } catch (const std::exception &) { // silently ignore if something fails; it's just for fun } } // end of fun #endif return EXIT_FAILURE; } return EXIT_SUCCESS; } std::shared_ptr<ProgressTracker> createProgressTracker(bool show_progress, unsigned int steps) { using namespace ProgressIndicator; using namespace std::chrono; std::shared_ptr<ProgressTracker> tracker = nullptr; if(show_progress) { if (isatty(fileno(stdout))) { // show a progress bar on the console tracker = std::make_shared<ProgressBar>(steps); } else { // not in a console tracker = std::make_shared<TaciturnDecorator>( // hence print a new line std::make_shared<ProgressLog>(steps), // at most every 10 minutes or after 0.5% of progress, whatever comes first duration_cast<milliseconds>(minutes(10)), 0.005); } } return tracker; } <commit_msg>Fix shadowing of json variable j<commit_after>#include "core.h" #include "mpicontroller.h" #include "move.h" #include "montecarlo.h" #include "analysis.h" #include "docopt.h" #include "progress_tracker.h" #include <cstdlib> #include "spdlog/spdlog.h" #include <spdlog/sinks/null_sink.h> #include <spdlog/sinks/stdout_color_sinks.h> #include <iomanip> #include <unistd.h> #ifdef ENABLE_SID #include "cppsid.h" #include <thread> using namespace std::this_thread; // sleep_for, sleep_until using namespace std::chrono_literals; // ns, us, ms, s, h, etc. using std::chrono::system_clock; #endif using namespace Faunus; using namespace std; #define Q(x) #x #define QUOTE(x) Q(x) #ifndef FAUNUS_TIPSFILE #define FAUNUS_TIPSFILE "" #endif static const char USAGE[] = R"(Faunus - the Monte Carlo code you're looking for! http://github.com/mlund/faunus Usage: faunus [-q] [--verbosity <N>] [--nobar] [--nopfx] [--notips] [--nofun] [--state=<file>] [--input=<file>] [--output=<file>] faunus (-h | --help) faunus --version Options: -i <file> --input <file> Input file [default: /dev/stdin]. -o <file> --output <file> Output file [default: out.json]. -s <file> --state <file> State file to start from (.json/.ubj). -v <N> --verbosity <N> Log verbosity level (0 = off, 1 = critical, ..., 6 = trace) [default: 3] -q --quiet Less verbose output. -h --help Show this screen. --nobar No progress bar. --nopfx Do not prefix input file with MPI rank. --notips Do not give input assistance --nofun No fun --version Show version. Multiple processes using MPI: 1. input and output files are prefixed with "mpi{rank}." 2. standard output is redirected to "mpi{rank}.stdout" 3. Input prefixing can be suppressed with --nopfx )"; using ProgressIndicator::ProgressTracker; std::shared_ptr<ProgressTracker> createProgressTracker(bool, unsigned int); int main(int argc, char **argv) { using namespace Faunus::MPI; bool nofun; try { std::string version = "Faunus"; #ifdef GIT_LATEST_TAG version += " "s + QUOTE(GIT_LATEST_TAG); #endif #ifdef GIT_COMMIT_HASH version += " git " + std::string(GIT_COMMIT_HASH); #endif #ifdef ENABLE_SID version += " [sid]"; #endif #ifdef ENABLE_MPI version += " [mpi]"; #endif #ifdef _OPENMP version += " [openmp]"; #endif auto args = docopt::docopt(USAGE, {argv + 1, argv + argc}, true, version); mpi.init(); // initialize MPI, if available // prepare loggers // TODO refactor to a standalone function and use cmd line options for different sinks, etc. faunus_logger = spdlog::stderr_color_mt("faunus"); faunus_logger->set_pattern("[%n %P] %^%L: %v%$"); mcloop_logger = spdlog::stderr_color_mt("mcloop"); mcloop_logger->set_pattern("[%n %P] [%E.%f] %L: %v"); // --verbosity (log level) long log_level = spdlog::level::off - args["--verbosity"].asLong(); // reverse sequence 0 → 6 to 6 → 0 spdlog::set_level(static_cast<spdlog::level::level_enum>(log_level)); // --notips if (not args["--notips"].asBool()) usageTip.load({FAUNUS_TIPSFILE}); // --nobar bool show_progress = !args["--nobar"].asBool(); // --quiet bool quiet = args["--quiet"].asBool(); if (quiet) { cout.setstate(std::ios_base::failbit); // hold kæft show_progress = false; } // --nofun nofun = args["--nofun"].asBool(); if (nofun or quiet) usageTip.asciiart = false; #ifdef ENABLE_SID usageTip.asciiart = false; // if SID is enabled, disable ascii #endif // --nopfx bool prefix = !args["--nopfx"].asBool(); // --input json json_in; auto input = args["--input"].asString(); if (input == "/dev/stdin") std::cin >> json_in; else { if (prefix) input = Faunus::MPI::prefix + input; json_in = openjson(input); } { pc::temperature = json_in.at("temperature").get<double>() * 1.0_K; MCSimulation sim(json_in, mpi); // --state if (args["--state"]) { std::ifstream f; std::string state = Faunus::MPI::prefix + args["--state"].asString(); std::string suffix = state.substr(state.find_last_of(".") + 1); bool binary = (suffix == "ubj"); auto mode = std::ios::in; if (binary) mode = std::ifstream::ate | std::ios::binary; // ate = open at end f.open(state, mode); if (f) { json json_state; if (not quiet) faunus_logger->info("loading state file {}", state); if (binary) { size_t size = f.tellg(); // get file size std::vector<std::uint8_t> v(size / sizeof(std::uint8_t)); f.seekg(0, f.beg); // go back to start f.read((char *)v.data(), size); json_state = json::from_ubjson(v); } else f >> json_state; sim.restore(json_state); } else throw std::runtime_error("state file error: " + state); } Analysis::CombinedAnalysis analysis(json_in.at("analysis"), sim.space(), sim.pot()); auto &loop = json_in.at("mcloop"); int macro = loop.at("macro"); int micro = loop.at("micro"); auto progress_tracker = createProgressTracker(show_progress, macro * micro); for (int i = 0; i < macro; i++) { for (int j = 0; j < micro; j++) { if (progress_tracker && mpi.isMaster()) { if(++(*progress_tracker) % 10 == 0) { progress_tracker->display(); } } sim.move(); analysis.sample(); } } if (progress_tracker && mpi.isMaster()) { progress_tracker->done(); if (not quiet) { faunus_logger->log((sim.drift() < 1E-9) ? spdlog::level::info : spdlog::level::warn, "relative drift = {}", sim.drift()); } // --output std::ofstream f(Faunus::MPI::prefix + args["--output"].asString()); if (f) { json json_out; Faunus::to_json(json_out, sim); json_out["relative drift"] = sim.drift(); json_out["analysis"] = analysis; if (mpi.nproc() > 1) { json_out["mpi"] = mpi; } #ifdef GIT_COMMIT_HASH json_out["git revision"] = GIT_COMMIT_HASH; #endif #ifdef __VERSION__ json_out["compiler"] = __VERSION__; #endif f << std::setw(4) << json_out << endl; } } mpi.finalize(); } catch (std::exception &e) { faunus_logger->error(e.what()); if (not usageTip.buffer.empty()) faunus_logger->error(usageTip.buffer); #ifdef ENABLE_SID // easter egg... if (not nofun and mpi.isMaster()) { // -> fun try { // look for json file with hvsc sid tune names std::string pfx; json json_music; for (std::string dir : {FAUNUS_BINARY_DIR, FAUNUS_INSTALL_PREFIX "/share/faunus/"}) { // installed and uninstalled cmake builds json_music = Faunus::openjson(dir + "/sids/music.json", false); if (!json_music.empty()) { pfx = dir + "/"; break; } } if (!json_music.empty()) { json_music = json_music.at("songs"); // load playlist std::vector<size_t> weight; // weight for each tune (= number of subsongs) for (auto &i : json_music) weight.push_back(i.at("subsongs").size()); std::discrete_distribution<size_t> dist(weight.begin(), weight.end()); Faunus::random.seed(); // give global random a hardware seed auto it = json_music.begin() + dist(Faunus::random.engine); // pick random tune weighted by subsongs auto subsongs = (*it).at("subsongs").get<std::vector<int>>(); // all subsongs int subsong = *(Faunus::random.sample(subsongs.begin(), subsongs.end())) - 1; // random subsong CPPSID::Player player; // let's emulate a Commodore 64... if (player.load(pfx + it->at("file").get<std::string>(), subsong)) { faunus_logger->info("error message music '{}' by {}, {} (6502/SID emulation)", player.title(), player.author(), player.info()); faunus_logger->info("\033[1mpress ctrl-c to quit\033[0m"); player.start(); // start music sleep_for(10ns); // short delay sleep_until(system_clock::now() + 240s); // play for 4 minutes, then exit player.stop(); std::cout << std::endl; } } } catch (const std::exception &) { // silently ignore if something fails; it's just for fun } } // end of fun #endif return EXIT_FAILURE; } return EXIT_SUCCESS; } std::shared_ptr<ProgressTracker> createProgressTracker(bool show_progress, unsigned int steps) { using namespace ProgressIndicator; using namespace std::chrono; std::shared_ptr<ProgressTracker> tracker = nullptr; if(show_progress) { if (isatty(fileno(stdout))) { // show a progress bar on the console tracker = std::make_shared<ProgressBar>(steps); } else { // not in a console tracker = std::make_shared<TaciturnDecorator>( // hence print a new line std::make_shared<ProgressLog>(steps), // at most every 10 minutes or after 0.5% of progress, whatever comes first duration_cast<milliseconds>(minutes(10)), 0.005); } } return tracker; } <|endoftext|>
<commit_before>// Load and save in binary or readable format. #include "fileio.h" // Get path to resource file. // Application responsible for freeing malloc'd memory. char *getResourcePath(char *file) { return(getPath((char *)"resource", file)); } // Get path to data file. // Application responsible for freeing malloc'd memory. char *getDataPath(char *file) { return(getPath((char *)"data", file)); } // Get path to file within directory. // Application responsible for freeing malloc'd memory. char *getPath(char *dir, char *file) { char *home, *path, *path2; // Sanity check. if ((file == NULL) || (*file == '\0')) { return(NULL); } // Fixed path? if ((file[0] == '/') || (file[0] == '.')) { if ((path = (char *)malloc(strlen(file) + 1)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } strcpy(path, file); return(path); } // Check MONA_HOME directory path environment variable. if ((home = getenv("MONA_HOME")) != NULL) { #ifdef WIN32 // Replace Cygwin path with Windows path. if ((strncmp(home, "/cygdrive/", 10) == 0) && (strlen(home) >= 11)) { if ((path = (char *)malloc(strlen(home) + strlen(dir) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "c:%s/%s", &home[11], dir); } else { if ((path = (char *)malloc(strlen(home) + strlen(dir) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "%s/%s", home, dir); } if (GetFileAttributes(path) != 0xffffffff) #else if ((path = (char *)malloc(strlen(home) + strlen(dir) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "%s/%s", home, dir); if (access(path, F_OK) != -1) #endif { // Add the file. if ((path2 = (char *)malloc(strlen(path) + strlen(file) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path2, "%s/%s", path, file); free(path); return(path2); } else { free(path); } } // Try relative paths. if ((path = (char *)malloc(strlen(dir) + 1)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "%s", dir); #ifdef WIN32 if (GetFileAttributes(path) != 0xffffffff) #else if (access(path, F_OK) != -1) #endif { free(path); if ((path = (char *)malloc(strlen(dir) + strlen(file) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "%s/%s", dir, file); return(path); } else { free(path); } if ((path = (char *)malloc(strlen(dir) + 4)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "../%s", dir); #ifdef WIN32 if (GetFileAttributes(path) != 0xffffffff) #else if (access(path, F_OK) != -1) #endif { free(path); if ((path = (char *)malloc(strlen(dir) + strlen(file) + 5)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "../%s/%s", dir, file); return(path); } else { free(path); } if ((path = (char *)malloc(strlen(dir) + 7)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "../../%s", dir); #ifdef WIN32 if (GetFileAttributes(path) != 0xffffffff) #else if (access(path, F_OK) != -1) #endif { free(path); if ((path = (char *)malloc(strlen(dir) + strlen(file) + 8)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "../../%s/%s", dir, file); return(path); } else { free(path); } // Default to input file. if ((path = (char *)malloc(strlen(file) + 1)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } strcpy(path, file); return(path); } FilePointer *myfopenRead(char *filename, bool binary) { FILE *fp = fopen(filename, "rb"); if (fp == NULL) { return(NULL); } FilePointer *filePointer = new FilePointer(fp, binary); assert(filePointer != NULL); return(filePointer); } FilePointer *myfopenWrite(char *filename, bool binary) { FILE *fp = fopen(filename, "wb"); if (fp == NULL) { return(NULL); } FilePointer *filePointer = new FilePointer(fp, binary); assert(filePointer != NULL); return(filePointer); } int myfclose(FilePointer *fp) { int result = fclose(fp->fp); delete fp; return(result); } int myfreadInt(int *i, FilePointer *fp) { if (fp->binary) { return((int)fread(i, sizeof(int), 1, fp->fp)); } else { return(fscanf(fp->fp, "%d", i)); } } int myfwriteInt(int *i, FilePointer *fp) { if (fp->binary) { return((int)fwrite(i, sizeof(int), 1, fp->fp)); } else { return(fprintf(fp->fp, "%d\n", *i)); } } int myfreadShort(short *s, FilePointer *fp) { if (fp->binary) { return((int)fread(s, sizeof(short), 1, fp->fp)); } else { short v; int ret = fscanf(fp->fp, "%hd", &v); *s = v; return(ret); } } int myfwriteShort(short *s, FilePointer *fp) { if (fp->binary) { return((int)fwrite(s, sizeof(short), 1, fp->fp)); } else { short v; v = *s; return(fprintf(fp->fp, "%hd\n", v)); } } int myfreadLong(unsigned long *l, FilePointer *fp) { if (fp->binary) { return((int)fread(l, sizeof(unsigned long), 1, fp->fp)); } else { return(fscanf(fp->fp, "%lu", l)); } } int myfwriteLong(unsigned long *l, FilePointer *fp) { if (fp->binary) { return((int)fwrite(l, sizeof(unsigned long), 1, fp->fp)); } else { return(fprintf(fp->fp, "%lu\n", *l)); } } int myfreadLongLong(unsigned long long *l, FilePointer *fp) { if (fp->binary) { return((int)fread(l, sizeof(unsigned long long), 1, fp->fp)); } else { return(fscanf(fp->fp, "%llu", l)); } } int myfwriteLongLong(unsigned long long *l, FilePointer *fp) { if (fp->binary) { return((int)fwrite(l, sizeof(unsigned long long), 1, fp->fp)); } else { return(fprintf(fp->fp, "%llu\n", *l)); } } int myfreadFloat(float *f, FilePointer *fp) { if (fp->binary) { return((int)fread(f, sizeof(float), 1, fp->fp)); } else { char buf[100]; int ret = fscanf(fp->fp, "%s", buf); *f = (float)atof(buf); return(ret); } } int myfwriteFloat(float *f, FilePointer *fp) { if (fp->binary) { return((int)fwrite(f, sizeof(float), 1, fp->fp)); } else { return(fprintf(fp->fp, "%f\n", *f)); } } int myfreadDouble(double *d, FilePointer *fp) { if (fp->binary) { return((int)fread(d, sizeof(double), 1, fp->fp)); } else { char buf[100]; int ret = fscanf(fp->fp, "%s", buf); *d = strtod(buf, NULL); return(ret); } } int myfwriteDouble(double *d, FilePointer *fp) { if (fp->binary) { return((int)fwrite(d, sizeof(double), 1, fp->fp)); } else { return(fprintf(fp->fp, "%f\n", *d)); } } int myfreadBool(bool *b, FilePointer *fp) { if (fp->binary) { return((int)fread(b, sizeof(bool), 1, fp->fp)); } else { int v; int ret = fscanf(fp->fp, "%d", &v); if (v == 1) { *b = true; } else { *b = false; } return(ret); } } int myfwriteBool(bool *b, FilePointer *fp) { if (fp->binary) { return((int)fwrite(b, sizeof(bool), 1, fp->fp)); } else { if (*b) { return(fprintf(fp->fp, "1\n")); } else { return(fprintf(fp->fp, "0\n")); } } } int myfreadChar(unsigned char *c, FilePointer *fp) { if (fp->binary) { return((int)fread(c, sizeof(unsigned char), 1, fp->fp)); } else { char buf[10]; int ret = fscanf(fp->fp, "%s", buf); *c = buf[0]; return(ret); } } int myfwriteChar(unsigned char *c, FilePointer *fp) { if (fp->binary) { return((int)fwrite(c, sizeof(unsigned char), 1, fp->fp)); } else { return(fprintf(fp->fp, "%c\n", *c)); } } int myfreadBytes(unsigned char *bytes, int size, FilePointer *fp) { if (fp->binary) { return((int)fread(bytes, size, 1, fp->fp)); } else { int len = (2 * size) + 1; unsigned char *buf = new unsigned char[len]; assert(buf != NULL); int ret = fscanf(fp->fp, "%s", buf); int i, j, d1, d2; for (i = 0; i < size; i++) { j = 2 * i; if ((buf[j] >= '0') && (buf[j] <= '9')) { d1 = buf[j] - '0'; } else { d1 = buf[j] - 'a' + 10; } j++; if ((buf[j] >= '0') && (buf[j] <= '9')) { d2 = buf[j] - '0'; } else { d2 = buf[j] - 'a' + 10; } bytes[i] = (d1 * 16) + d2; } delete[] buf; return(ret); } } int myfwriteBytes(unsigned char *bytes, int size, FilePointer *fp) { if (fp->binary) { return((int)fwrite(bytes, size, 1, fp->fp)); } else { int len = (2 * size) + 1; char *buf = new char[len]; assert(buf != NULL); for (int i = 0; i < size; i++) { sprintf(&buf[2 * i], "%02x", bytes[i]); } buf[len - 1] = '\0'; int ret = fprintf(fp->fp, "%s\n", buf); delete[] buf; return(ret); } } int myfreadString(char *str, int size, FilePointer *fp) { if (fp->binary) { return((int)fread(str, size, 1, fp->fp)); } else { // String is delimited by double quotes. char c; while (true) { c = fgetc(fp->fp); if (c == EOF) { return(0); } if (c == '"') { break; } } int i = 0; for ( ; i < size; i++) { c = fgetc(fp->fp); if (c == EOF) { return(i); } if (c == '"') { str[i] = '\0'; return(i); } else { str[i] = c; } } fgetc(fp->fp); return(i); } } int myfwriteString(char *str, int size, FilePointer *fp) { if (fp->binary) { return((int)fwrite(str, size, 1, fp->fp)); } else { // Delimit string with double quotes. fputc('"', fp->fp); int ret = 0; for (int i = 0; i < size && str[i] != '\0'; i++) { if (str[i] != '"') { fputc(str[i], fp->fp); ret++; } } fputc('"', fp->fp); fputc('\n', fp->fp); return(ret); } } <commit_msg>Fix path variable<commit_after>// Load and save in binary or readable format. #include "fileio.h" // Get path to resource file. // Application responsible for freeing malloc'd memory. char *getResourcePath(char *file) { return(getPath((char *)"resource", file)); } // Get path to data file. // Application responsible for freeing malloc'd memory. char *getDataPath(char *file) { return(getPath((char *)"data", file)); } // Get path to file within directory. // Application responsible for freeing malloc'd memory. char *getPath(char *dir, char *file) { char *home, *path, *path2; // Sanity check. if ((file == NULL) || (*file == '\0')) { return(NULL); } // Fixed path? if ((file[0] == '/') || (file[0] == '.')) { if ((path = (char *)malloc(strlen(file) + 1)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } strcpy(path, file); return(path); } // Check BIONET_HOME directory path environment variable. if ((home = getenv("BIONET_HOME")) != NULL) { #ifdef WIN32 // Replace Cygwin path with Windows path. if ((strncmp(home, "/cygdrive/", 10) == 0) && (strlen(home) >= 11)) { if ((path = (char *)malloc(strlen(home) + strlen(dir) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "c:%s/%s", &home[11], dir); } else { if ((path = (char *)malloc(strlen(home) + strlen(dir) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "%s/%s", home, dir); } if (GetFileAttributes(path) != 0xffffffff) #else if ((path = (char *)malloc(strlen(home) + strlen(dir) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "%s/%s", home, dir); if (access(path, F_OK) != -1) #endif { // Add the file. if ((path2 = (char *)malloc(strlen(path) + strlen(file) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path2, "%s/%s", path, file); free(path); return(path2); } else { free(path); } } // Try relative paths. if ((path = (char *)malloc(strlen(dir) + 1)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "%s", dir); #ifdef WIN32 if (GetFileAttributes(path) != 0xffffffff) #else if (access(path, F_OK) != -1) #endif { free(path); if ((path = (char *)malloc(strlen(dir) + strlen(file) + 2)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "%s/%s", dir, file); return(path); } else { free(path); } if ((path = (char *)malloc(strlen(dir) + 4)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "../%s", dir); #ifdef WIN32 if (GetFileAttributes(path) != 0xffffffff) #else if (access(path, F_OK) != -1) #endif { free(path); if ((path = (char *)malloc(strlen(dir) + strlen(file) + 5)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "../%s/%s", dir, file); return(path); } else { free(path); } if ((path = (char *)malloc(strlen(dir) + 7)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "../../%s", dir); #ifdef WIN32 if (GetFileAttributes(path) != 0xffffffff) #else if (access(path, F_OK) != -1) #endif { free(path); if ((path = (char *)malloc(strlen(dir) + strlen(file) + 8)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } sprintf(path, "../../%s/%s", dir, file); return(path); } else { free(path); } // Default to input file. if ((path = (char *)malloc(strlen(file) + 1)) == NULL) { fprintf(stderr, "getPath: cannot malloc path memory\n"); exit(1); } strcpy(path, file); return(path); } FilePointer *myfopenRead(char *filename, bool binary) { FILE *fp = fopen(filename, "rb"); if (fp == NULL) { return(NULL); } FilePointer *filePointer = new FilePointer(fp, binary); assert(filePointer != NULL); return(filePointer); } FilePointer *myfopenWrite(char *filename, bool binary) { FILE *fp = fopen(filename, "wb"); if (fp == NULL) { return(NULL); } FilePointer *filePointer = new FilePointer(fp, binary); assert(filePointer != NULL); return(filePointer); } int myfclose(FilePointer *fp) { int result = fclose(fp->fp); delete fp; return(result); } int myfreadInt(int *i, FilePointer *fp) { if (fp->binary) { return((int)fread(i, sizeof(int), 1, fp->fp)); } else { return(fscanf(fp->fp, "%d", i)); } } int myfwriteInt(int *i, FilePointer *fp) { if (fp->binary) { return((int)fwrite(i, sizeof(int), 1, fp->fp)); } else { return(fprintf(fp->fp, "%d\n", *i)); } } int myfreadShort(short *s, FilePointer *fp) { if (fp->binary) { return((int)fread(s, sizeof(short), 1, fp->fp)); } else { short v; int ret = fscanf(fp->fp, "%hd", &v); *s = v; return(ret); } } int myfwriteShort(short *s, FilePointer *fp) { if (fp->binary) { return((int)fwrite(s, sizeof(short), 1, fp->fp)); } else { short v; v = *s; return(fprintf(fp->fp, "%hd\n", v)); } } int myfreadLong(unsigned long *l, FilePointer *fp) { if (fp->binary) { return((int)fread(l, sizeof(unsigned long), 1, fp->fp)); } else { return(fscanf(fp->fp, "%lu", l)); } } int myfwriteLong(unsigned long *l, FilePointer *fp) { if (fp->binary) { return((int)fwrite(l, sizeof(unsigned long), 1, fp->fp)); } else { return(fprintf(fp->fp, "%lu\n", *l)); } } int myfreadLongLong(unsigned long long *l, FilePointer *fp) { if (fp->binary) { return((int)fread(l, sizeof(unsigned long long), 1, fp->fp)); } else { return(fscanf(fp->fp, "%llu", l)); } } int myfwriteLongLong(unsigned long long *l, FilePointer *fp) { if (fp->binary) { return((int)fwrite(l, sizeof(unsigned long long), 1, fp->fp)); } else { return(fprintf(fp->fp, "%llu\n", *l)); } } int myfreadFloat(float *f, FilePointer *fp) { if (fp->binary) { return((int)fread(f, sizeof(float), 1, fp->fp)); } else { char buf[100]; int ret = fscanf(fp->fp, "%s", buf); *f = (float)atof(buf); return(ret); } } int myfwriteFloat(float *f, FilePointer *fp) { if (fp->binary) { return((int)fwrite(f, sizeof(float), 1, fp->fp)); } else { return(fprintf(fp->fp, "%f\n", *f)); } } int myfreadDouble(double *d, FilePointer *fp) { if (fp->binary) { return((int)fread(d, sizeof(double), 1, fp->fp)); } else { char buf[100]; int ret = fscanf(fp->fp, "%s", buf); *d = strtod(buf, NULL); return(ret); } } int myfwriteDouble(double *d, FilePointer *fp) { if (fp->binary) { return((int)fwrite(d, sizeof(double), 1, fp->fp)); } else { return(fprintf(fp->fp, "%f\n", *d)); } } int myfreadBool(bool *b, FilePointer *fp) { if (fp->binary) { return((int)fread(b, sizeof(bool), 1, fp->fp)); } else { int v; int ret = fscanf(fp->fp, "%d", &v); if (v == 1) { *b = true; } else { *b = false; } return(ret); } } int myfwriteBool(bool *b, FilePointer *fp) { if (fp->binary) { return((int)fwrite(b, sizeof(bool), 1, fp->fp)); } else { if (*b) { return(fprintf(fp->fp, "1\n")); } else { return(fprintf(fp->fp, "0\n")); } } } int myfreadChar(unsigned char *c, FilePointer *fp) { if (fp->binary) { return((int)fread(c, sizeof(unsigned char), 1, fp->fp)); } else { char buf[10]; int ret = fscanf(fp->fp, "%s", buf); *c = buf[0]; return(ret); } } int myfwriteChar(unsigned char *c, FilePointer *fp) { if (fp->binary) { return((int)fwrite(c, sizeof(unsigned char), 1, fp->fp)); } else { return(fprintf(fp->fp, "%c\n", *c)); } } int myfreadBytes(unsigned char *bytes, int size, FilePointer *fp) { if (fp->binary) { return((int)fread(bytes, size, 1, fp->fp)); } else { int len = (2 * size) + 1; unsigned char *buf = new unsigned char[len]; assert(buf != NULL); int ret = fscanf(fp->fp, "%s", buf); int i, j, d1, d2; for (i = 0; i < size; i++) { j = 2 * i; if ((buf[j] >= '0') && (buf[j] <= '9')) { d1 = buf[j] - '0'; } else { d1 = buf[j] - 'a' + 10; } j++; if ((buf[j] >= '0') && (buf[j] <= '9')) { d2 = buf[j] - '0'; } else { d2 = buf[j] - 'a' + 10; } bytes[i] = (d1 * 16) + d2; } delete[] buf; return(ret); } } int myfwriteBytes(unsigned char *bytes, int size, FilePointer *fp) { if (fp->binary) { return((int)fwrite(bytes, size, 1, fp->fp)); } else { int len = (2 * size) + 1; char *buf = new char[len]; assert(buf != NULL); for (int i = 0; i < size; i++) { sprintf(&buf[2 * i], "%02x", bytes[i]); } buf[len - 1] = '\0'; int ret = fprintf(fp->fp, "%s\n", buf); delete[] buf; return(ret); } } int myfreadString(char *str, int size, FilePointer *fp) { if (fp->binary) { return((int)fread(str, size, 1, fp->fp)); } else { // String is delimited by double quotes. char c; while (true) { c = fgetc(fp->fp); if (c == EOF) { return(0); } if (c == '"') { break; } } int i = 0; for ( ; i < size; i++) { c = fgetc(fp->fp); if (c == EOF) { return(i); } if (c == '"') { str[i] = '\0'; return(i); } else { str[i] = c; } } fgetc(fp->fp); return(i); } } int myfwriteString(char *str, int size, FilePointer *fp) { if (fp->binary) { return((int)fwrite(str, size, 1, fp->fp)); } else { // Delimit string with double quotes. fputc('"', fp->fp); int ret = 0; for (int i = 0; i < size && str[i] != '\0'; i++) { if (str[i] != '"') { fputc(str[i], fp->fp); ret++; } } fputc('"', fp->fp); fputc('\n', fp->fp); return(ret); } } <|endoftext|>
<commit_before>/** * ifaces.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #include "ifaces.h" #define CheckPointerAndWarn(pPointer, className) \ if (pPointer == nullptr) { \ Warning("[StatusSpec] %s is not initialized!\n", #className); \ return false; \ } IBaseClientDLL *Interfaces::pClientDLL = nullptr; IClientEntityList *Interfaces::pClientEntityList = nullptr; CDllDemandLoader *Interfaces::pClientModule = nullptr; IVEngineClient *Interfaces::pEngineClient = nullptr; IFileSystem *Interfaces::pFileSystem = nullptr; IGameEventManager2 *Interfaces::pGameEventManager = nullptr; IVRenderView *Interfaces::pRenderView = nullptr; CSteamAPIContext *Interfaces::pSteamAPIContext = nullptr; CBaseEntityList *g_pEntityList; inline bool DataCompare(const BYTE* pData, const BYTE* bSig, const char* szMask) { for (; *szMask; ++szMask, ++pData, ++bSig) { if (*szMask == 'x' && *pData != *bSig) return false; } return (*szMask) == NULL; } inline DWORD FindPattern(DWORD dwAddress, DWORD dwSize, BYTE* pbSig, const char* szMask) { for (DWORD i = NULL; i < dwSize; i++) { if (DataCompare((BYTE*) (dwAddress + i), pbSig, szMask)) return (DWORD) (dwAddress + i); } return 0; } IClientMode* Interfaces::GetClientMode() { #if defined _WIN32 static DWORD pointer = NULL; if (!pointer) pointer = FindPattern((DWORD)GetHandleOfModule(_T("client")), CLIENT_MODULE_SIZE, (PBYTE)CLIENTMODE_SIG, CLIENTMODE_MASK) + CLIENTMODE_OFFSET; return **(IClientMode***)(pointer); #else return nullptr; #endif } IGameResources* Interfaces::GetGameResources() { #if defined _WIN32 static DWORD pointer = NULL; if (!pointer) pointer = FindPattern((DWORD) GetHandleOfModule(_T("client")), CLIENT_MODULE_SIZE, (PBYTE) GAMERESOURCES_SIG, GAMERESOURCES_MASK); typedef IGameResources* (*GGR_t) (void); GGR_t GGR = (GGR_t) pointer; return GGR(); #else return nullptr; #endif } bool Interfaces::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory) { ConnectTier1Libraries(&interfaceFactory, 1); ConnectTier2Libraries(&interfaceFactory, 1); ConnectTier3Libraries(&interfaceFactory, 1); if (!vgui::VGui_InitInterfacesList("statusspec", &interfaceFactory, 1)) { Warning("[StatusSpec] Could not initialize VGUI interfaces!\n"); return false; } pEngineClient = (IVEngineClient *)interfaceFactory(VENGINE_CLIENT_INTERFACE_VERSION, nullptr); pGameEventManager = (IGameEventManager2 *)interfaceFactory(INTERFACEVERSION_GAMEEVENTSMANAGER2, nullptr); pRenderView = (IVRenderView *)interfaceFactory(VENGINE_RENDERVIEW_INTERFACE_VERSION, nullptr); pClientModule = new CDllDemandLoader(CLIENT_MODULE_FILE); CreateInterfaceFn gameClientFactory = pClientModule->GetFactory(); pClientDLL = (IBaseClientDLL*)gameClientFactory(CLIENT_DLL_INTERFACE_VERSION, nullptr); pClientEntityList = (IClientEntityList*)gameClientFactory(VCLIENTENTITYLIST_INTERFACE_VERSION, nullptr); pSteamAPIContext = new CSteamAPIContext(); if (!SteamAPI_InitSafe() || !pSteamAPIContext->Init()) { Warning("[StatusSpec] Could not initialize Steam API!\n"); return false; } CheckPointerAndWarn(pClientDLL, IBaseClientDLL); CheckPointerAndWarn(pClientEntityList, IClientEntityList); CheckPointerAndWarn(pEngineClient, IVEngineClient); CheckPointerAndWarn(pGameEventManager, IGameEventManager2); CheckPointerAndWarn(pRenderView, IVRenderView); CheckPointerAndWarn(g_pMaterialSystem, IMaterialSystem); CheckPointerAndWarn(g_pMaterialSystemHardwareConfig, IMaterialSystemHardwareConfig); CheckPointerAndWarn(g_pStudioRender, IStudioRender); CheckPointerAndWarn(g_pVGuiSurface, vgui::ISurface); CheckPointerAndWarn(g_pVGui, vgui::IVGui); CheckPointerAndWarn(g_pVGuiPanel, vgui::IPanel); CheckPointerAndWarn(g_pVGuiSchemeManager, vgui::ISchemeManager); CheckPointerAndWarn(g_pFullFileSystem, IFileSystem); g_pEntityList = dynamic_cast<CBaseEntityList *>(Interfaces::pClientEntityList); char dll[MAX_PATH]; bool steam; if (FileSystem_GetFileSystemDLLName(dll, sizeof(dll), steam) == FS_OK) { CFSLoadModuleInfo fsLoadModuleInfo; fsLoadModuleInfo.m_bSteam = steam; fsLoadModuleInfo.m_pFileSystemDLLName = dll; fsLoadModuleInfo.m_ConnectFactory = interfaceFactory; if (FileSystem_LoadFileSystemModule(fsLoadModuleInfo) == FS_OK) { CFSMountContentInfo fsMountContentInfo; fsMountContentInfo.m_bToolsMode = fsLoadModuleInfo.m_bToolsMode; fsMountContentInfo.m_pDirectoryName = fsLoadModuleInfo.m_GameInfoPath; fsMountContentInfo.m_pFileSystem = fsLoadModuleInfo.m_pFileSystem; if (FileSystem_MountContent(fsMountContentInfo) == FS_OK) { CFSSearchPathsInit fsSearchPathsInit; fsSearchPathsInit.m_pDirectoryName = fsLoadModuleInfo.m_GameInfoPath; fsSearchPathsInit.m_pFileSystem = fsLoadModuleInfo.m_pFileSystem; if (FileSystem_LoadSearchPaths(fsSearchPathsInit) == FS_OK) { Interfaces::pFileSystem = fsLoadModuleInfo.m_pFileSystem; CheckPointerAndWarn(Interfaces::pFileSystem, IFileSystem); return true; } } } } return false; } void Interfaces::Unload() { DisconnectTier3Libraries(); DisconnectTier2Libraries(); DisconnectTier1Libraries(); pSteamAPIContext->Clear(); pClientModule->Unload(); pClientModule = nullptr; pClientDLL = nullptr; pClientEntityList = nullptr; pEngineClient = nullptr; pFileSystem = nullptr; pGameEventManager = nullptr; pRenderView = nullptr; }<commit_msg>Alphabetize interface checks.<commit_after>/** * ifaces.cpp * StatusSpec project * * Copyright (c) 2014 thesupremecommander * BSD 2-Clause License * http://opensource.org/licenses/BSD-2-Clause * */ #include "ifaces.h" #define CheckPointerAndWarn(pPointer, className) \ if (pPointer == nullptr) { \ Warning("[StatusSpec] %s is not initialized!\n", #className); \ return false; \ } IBaseClientDLL *Interfaces::pClientDLL = nullptr; IClientEntityList *Interfaces::pClientEntityList = nullptr; CDllDemandLoader *Interfaces::pClientModule = nullptr; IVEngineClient *Interfaces::pEngineClient = nullptr; IFileSystem *Interfaces::pFileSystem = nullptr; IGameEventManager2 *Interfaces::pGameEventManager = nullptr; IVRenderView *Interfaces::pRenderView = nullptr; CSteamAPIContext *Interfaces::pSteamAPIContext = nullptr; CBaseEntityList *g_pEntityList; inline bool DataCompare(const BYTE* pData, const BYTE* bSig, const char* szMask) { for (; *szMask; ++szMask, ++pData, ++bSig) { if (*szMask == 'x' && *pData != *bSig) return false; } return (*szMask) == NULL; } inline DWORD FindPattern(DWORD dwAddress, DWORD dwSize, BYTE* pbSig, const char* szMask) { for (DWORD i = NULL; i < dwSize; i++) { if (DataCompare((BYTE*) (dwAddress + i), pbSig, szMask)) return (DWORD) (dwAddress + i); } return 0; } IClientMode* Interfaces::GetClientMode() { #if defined _WIN32 static DWORD pointer = NULL; if (!pointer) pointer = FindPattern((DWORD)GetHandleOfModule(_T("client")), CLIENT_MODULE_SIZE, (PBYTE)CLIENTMODE_SIG, CLIENTMODE_MASK) + CLIENTMODE_OFFSET; return **(IClientMode***)(pointer); #else return nullptr; #endif } IGameResources* Interfaces::GetGameResources() { #if defined _WIN32 static DWORD pointer = NULL; if (!pointer) pointer = FindPattern((DWORD) GetHandleOfModule(_T("client")), CLIENT_MODULE_SIZE, (PBYTE) GAMERESOURCES_SIG, GAMERESOURCES_MASK); typedef IGameResources* (*GGR_t) (void); GGR_t GGR = (GGR_t) pointer; return GGR(); #else return nullptr; #endif } bool Interfaces::Load(CreateInterfaceFn interfaceFactory, CreateInterfaceFn gameServerFactory) { ConnectTier1Libraries(&interfaceFactory, 1); ConnectTier2Libraries(&interfaceFactory, 1); ConnectTier3Libraries(&interfaceFactory, 1); if (!vgui::VGui_InitInterfacesList("statusspec", &interfaceFactory, 1)) { Warning("[StatusSpec] Could not initialize VGUI interfaces!\n"); return false; } pEngineClient = (IVEngineClient *)interfaceFactory(VENGINE_CLIENT_INTERFACE_VERSION, nullptr); pGameEventManager = (IGameEventManager2 *)interfaceFactory(INTERFACEVERSION_GAMEEVENTSMANAGER2, nullptr); pRenderView = (IVRenderView *)interfaceFactory(VENGINE_RENDERVIEW_INTERFACE_VERSION, nullptr); pClientModule = new CDllDemandLoader(CLIENT_MODULE_FILE); CreateInterfaceFn gameClientFactory = pClientModule->GetFactory(); pClientDLL = (IBaseClientDLL*)gameClientFactory(CLIENT_DLL_INTERFACE_VERSION, nullptr); pClientEntityList = (IClientEntityList*)gameClientFactory(VCLIENTENTITYLIST_INTERFACE_VERSION, nullptr); pSteamAPIContext = new CSteamAPIContext(); if (!SteamAPI_InitSafe() || !pSteamAPIContext->Init()) { Warning("[StatusSpec] Could not initialize Steam API!\n"); return false; } CheckPointerAndWarn(pClientDLL, IBaseClientDLL); CheckPointerAndWarn(pClientEntityList, IClientEntityList); CheckPointerAndWarn(pEngineClient, IVEngineClient); CheckPointerAndWarn(pGameEventManager, IGameEventManager2); CheckPointerAndWarn(pRenderView, IVRenderView); CheckPointerAndWarn(g_pFullFileSystem, IFileSystem); CheckPointerAndWarn(g_pMaterialSystem, IMaterialSystem); CheckPointerAndWarn(g_pMaterialSystemHardwareConfig, IMaterialSystemHardwareConfig); CheckPointerAndWarn(g_pStudioRender, IStudioRender); CheckPointerAndWarn(g_pVGuiSurface, vgui::ISurface); CheckPointerAndWarn(g_pVGui, vgui::IVGui); CheckPointerAndWarn(g_pVGuiPanel, vgui::IPanel); CheckPointerAndWarn(g_pVGuiSchemeManager, vgui::ISchemeManager); g_pEntityList = dynamic_cast<CBaseEntityList *>(Interfaces::pClientEntityList); char dll[MAX_PATH]; bool steam; if (FileSystem_GetFileSystemDLLName(dll, sizeof(dll), steam) == FS_OK) { CFSLoadModuleInfo fsLoadModuleInfo; fsLoadModuleInfo.m_bSteam = steam; fsLoadModuleInfo.m_pFileSystemDLLName = dll; fsLoadModuleInfo.m_ConnectFactory = interfaceFactory; if (FileSystem_LoadFileSystemModule(fsLoadModuleInfo) == FS_OK) { CFSMountContentInfo fsMountContentInfo; fsMountContentInfo.m_bToolsMode = fsLoadModuleInfo.m_bToolsMode; fsMountContentInfo.m_pDirectoryName = fsLoadModuleInfo.m_GameInfoPath; fsMountContentInfo.m_pFileSystem = fsLoadModuleInfo.m_pFileSystem; if (FileSystem_MountContent(fsMountContentInfo) == FS_OK) { CFSSearchPathsInit fsSearchPathsInit; fsSearchPathsInit.m_pDirectoryName = fsLoadModuleInfo.m_GameInfoPath; fsSearchPathsInit.m_pFileSystem = fsLoadModuleInfo.m_pFileSystem; if (FileSystem_LoadSearchPaths(fsSearchPathsInit) == FS_OK) { Interfaces::pFileSystem = fsLoadModuleInfo.m_pFileSystem; CheckPointerAndWarn(Interfaces::pFileSystem, IFileSystem); return true; } } } } return false; } void Interfaces::Unload() { DisconnectTier3Libraries(); DisconnectTier2Libraries(); DisconnectTier1Libraries(); pSteamAPIContext->Clear(); pClientModule->Unload(); pClientModule = nullptr; pClientDLL = nullptr; pClientEntityList = nullptr; pEngineClient = nullptr; pFileSystem = nullptr; pGameEventManager = nullptr; pRenderView = nullptr; }<|endoftext|>
<commit_before>/// /// C++ interview quiz. /// /// What shall be printed as 'x' value? /// #include <iostream> #include <stdexcept> int x = 0; #define TRACE_CALL std::cout << __PRETTY_FUNCTION__ << std::endl class Base { public: Base() { TRACE_CALL; ++x; } Base(const Base &) { TRACE_CALL; --x; } Base(Base &&) { TRACE_CALL; x += 2; } virtual ~Base() { TRACE_CALL; x -= 3; } Base & operator=(const Base &) { TRACE_CALL; x += 5; return *this; } Base & operator=(Base &&) { TRACE_CALL; x -= 2; return *this; } }; class Derived: public Base { public: Derived() { TRACE_CALL; x += 2; } Derived(const Derived &other): Base(other) { TRACE_CALL; x += 3; } Derived(Derived &&other): Base(other) { TRACE_CALL; x -= 2; } ~Derived() { TRACE_CALL; --x; } Derived & operator=(const Derived &) { TRACE_CALL; x += 2; return *this; } Derived & operator=(Derived &&) { TRACE_CALL; x -= 3; return *this; } }; int main() try { Base b = Derived(); Derived d(std::move(Derived())); d = Derived(); b = d; throw std::logic_error("You shall not pass!"); return 0; } catch (...) { std::cout << x << std::endl; return 1; } <commit_msg>amend<commit_after>/// /// C++ interview quiz. /// /// What will be printed as 'x' value? /// #include <iostream> #include <stdexcept> int x = 0; #define TRACE_CALL std::cout << __PRETTY_FUNCTION__ << std::endl class Base { public: Base() { TRACE_CALL; ++x; } Base(const Base &) { TRACE_CALL; --x; } Base(Base &&) { TRACE_CALL; x += 2; } virtual ~Base() { TRACE_CALL; x -= 3; } Base & operator=(const Base &) { TRACE_CALL; x += 5; return *this; } Base & operator=(Base &&) { TRACE_CALL; x -= 2; return *this; } }; class Derived: public Base { public: Derived() { TRACE_CALL; x += 2; } Derived(const Derived &other): Base(other) { TRACE_CALL; x += 3; } Derived(Derived &&other): Base(other) { TRACE_CALL; x -= 2; } virtual ~Derived() { TRACE_CALL; --x; } Derived & operator=(const Derived &) { TRACE_CALL; x += 2; return *this; } Derived & operator=(Derived &&) { TRACE_CALL; x -= 3; return *this; } }; int main() try { Base b = Derived(); Derived d(std::move(Derived())); d = Derived(); b = d; throw std::logic_error("You shall not pass!"); return 0; } catch (...) { std::cout << x << std::endl; return 1; } <|endoftext|>
<commit_before>#include "incphp.h" #include <array> #include <iostream> #include <cmath> #include "tclap/CmdLine.h" #include "carj/carj.h" #include "carj/ScopedTimer.h" #include "ipasir/ipasir_cpp.h" #include "carj/logging.h" int neccessaryArgument = true; int defaultIsFalse = false; using json = nlohmann::json; TCLAP::CmdLine cmd( "This tool solves the pidgeon hole principle incrementally.", ' ', "0.1"); carj::TCarjArg<TCLAP::ValueArg, unsigned> numberOfPigeons("p", "numPigeons", "Number of pigeons", !neccessaryArgument, 1, "natural number", cmd); carj::TCarjArg<TCLAP::ValueArg, unsigned> startingMakeSpan("s", "startingMakeSpan", "Makespan to start with.", !neccessaryArgument, 0, "natural number", cmd); carj::CarjArg<TCLAP::SwitchArg, bool> dimspec("d", "dimspec", "Output dimspec.", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> extendedResolution("e", "extendedResolution", "Encode PHP with extended resolution.", cmd, defaultIsFalse); class DimSpecFixedPigeons { private: unsigned numPigeons; unsigned numLiteralsPerTime; /** * Variable representing that pigeon p is in hole h. * Note that hole is the same as time. */ int varPigeonInHole(unsigned p, unsigned h) { return numLiteralsPerTime * h + p + 1; } /** * Helper variable, which is true iff the pigeon sits in a future hole. * i.e. step created hole h, then pigeon sits in a hole added in step later */ int helperFutureHole(int p, int h) { return numLiteralsPerTime * h + numPigeons + p + 1; } void printClause(std::vector<int> clause) { for (int literal: clause) { std::cout << literal << " "; } std::cout << "0" << std::endl; } public: DimSpecFixedPigeons(unsigned _numPigeons): numPigeons(_numPigeons), numLiteralsPerTime(2 * _numPigeons) { } void print() { //i, u, g, t int numberOfClauses = 0; numberOfClauses = numPigeons; std::cout << "i cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { printClause({ varPigeonInHole(i, 0), helperFutureHole(i, 0) }); } numberOfClauses = (numPigeons - 1) * numPigeons / 2; std::cout << "u cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; // at most one pigeon in hole of step for (unsigned i = 0; i < numPigeons; i++) { for (unsigned j = 0; j < i; j++) { printClause({-varPigeonInHole(i, 0) , -varPigeonInHole(j, 0)}); } } numberOfClauses = numPigeons; std::cout << "g cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { printClause({-helperFutureHole(i, 0)}); } numberOfClauses = 3 * numPigeons; std::cout << "t cnf " << 2 * numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { // -> printClause({ -helperFutureHole(i, 0), varPigeonInHole(i, 1), helperFutureHole(i, 1), }); // <- printClause({ helperFutureHole(i, 0), -varPigeonInHole(i, 1) }); printClause({ helperFutureHole(i, 0), -helperFutureHole(i, 1) }); } } }; class IncrementalFixedPigeons { public: IncrementalFixedPigeons(unsigned _numPigeons): numPigeons(_numPigeons), numLiteralsPerTime(_numPigeons + 1) { } void solve(){ auto& solves = carj::getCarj() .data["/incphp/result/solves"_json_pointer]; solves.clear(); bool solved = false; for (unsigned makespan = 0; !solved; makespan++) { // at most one pigeon in hole of step for (unsigned i = 0; i < numPigeons; i++) { for (unsigned j = 0; j < i; j++) { addClause({ -varPigeonInHole(i, makespan), -varPigeonInHole(j, makespan)}); } } if (makespan >= startingMakeSpan.getValue()) { // each pigeon has at least one hole for (unsigned p = 0; p < numPigeons; p++) { std::vector<int> clause; for (unsigned h = 0; h <= makespan; h++) { clause.push_back(varPigeonInHole(p, h)); } clause.push_back(-activationLiteral(makespan)); addClause(clause); } solves.push_back({ {"makespan", makespan}, {"time", -1} }); { carj::ScopedTimer timer((*solves.rbegin())["time"]); solver.assume(activationLiteral(makespan)); solved = (solver.solve() == ipasir::SolveResult::SAT); } } } } private: /** * Variable representing that pigeon p is in hole h. * Note that hole is the same as makespan. */ int varPigeonInHole(unsigned p, unsigned h) { return numLiteralsPerTime * h + p + 2; } int activationLiteral(unsigned t) { return numLiteralsPerTime * t + 1; } void addClause(std::vector<int> clause) { for (int literal: clause) { solver.add(literal); } solver.add(0); } unsigned numPigeons; unsigned numLiteralsPerTime; ipasir::Solver solver; }; class ExtendedResolution { public: ExtendedResolution(unsigned _numPigeons): numPigeons(_numPigeons) { } void solve(){ unsigned sn = numPigeons; // at most one pigeon in hole h for (unsigned h = 0; h < numPigeons - 1; h++) { for (unsigned i = 0; i < numPigeons; i++) { for (unsigned j = 0; j < i; j++) { addClause({ -P(sn, i, h), -P(sn, j, h)}); } } } // each pigeon has at least one hole for (unsigned p = 0; p < numPigeons; p++) { std::vector<int> clause; for (unsigned h = 0; h < numPigeons - 1; h++) { clause.push_back(P(sn, p, h)); } addClause(clause); } for (unsigned n = sn; n > 2; n--) { for (unsigned i = 0; i < n - 1; i++) { for (unsigned j = 0; j < n - 2; j++) { addClause({ P(n - 1, i, j), -P(n, i, j) }); addClause({ P(n - 1, i, j), -P(n, i, n - 2), -P(n, n - 1, j) }); addClause({ -P(n - 1, i, j), P(n, i, j), P(n, i, n - 2) }); addClause({ -P(n - 1, i, j), P(n, i, j), P(n, n - 1, j) }); } } } auto& solves = carj::getCarj() .data["/incphp/result/solves"_json_pointer]; solves.clear(); for (unsigned makespan = 0; makespan < numPigeons; makespan++) { solves.push_back({ {"makespan", makespan}, {"time", -1} }); carj::ScopedTimer timer((*solves.rbegin())["time"]); for (unsigned p = 0; p < numPigeons; p++) { for (unsigned h = makespan; h < numPigeons - 1; h++) { solver.assume(-P(sn, p, h)); } } bool solved = (solver.solve() == ipasir::SolveResult::SAT); assert(!solved); } } private: ipasir::Solver solver; unsigned numPigeons; /** * Variable representing that pigeon p is in hole h. */ int P(unsigned n, unsigned p, unsigned h) { return ((n * numPigeons + p) * numPigeons + h) + 1; } void addClause(std::vector<int> clause) { for (int literal: clause) { solver.add(literal); } solver.add(0); } }; int incphp_main(int argc, const char **argv) { carj::init(argc, argv, cmd, "/incphp/parameters"); if (dimspec.getValue()) { DimSpecFixedPigeons dsfp(numberOfPigeons.getValue()); dsfp.print(); } else if (extendedResolution.getValue()) { ExtendedResolution er(numberOfPigeons.getValue()); er.solve(); } else { IncrementalFixedPigeons ifp(numberOfPigeons.getValue()); ifp.solve(); } return 0; } <commit_msg>Added assume for directed resolution to solve extended resolution php.<commit_after>#include "incphp.h" #include <array> #include <iostream> #include <cmath> #include "tclap/CmdLine.h" #include "carj/carj.h" #include "carj/ScopedTimer.h" #include "ipasir/ipasir_cpp.h" #include "carj/logging.h" int neccessaryArgument = true; int defaultIsFalse = false; using json = nlohmann::json; TCLAP::CmdLine cmd( "This tool solves the pidgeon hole principle incrementally.", ' ', "0.1"); carj::TCarjArg<TCLAP::ValueArg, unsigned> numberOfPigeons("p", "numPigeons", "Number of pigeons", !neccessaryArgument, 1, "natural number", cmd); carj::TCarjArg<TCLAP::ValueArg, unsigned> startingMakeSpan("s", "startingMakeSpan", "Makespan to start with.", !neccessaryArgument, 0, "natural number", cmd); carj::CarjArg<TCLAP::SwitchArg, bool> dimspec("d", "dimspec", "Output dimspec.", cmd, defaultIsFalse); carj::CarjArg<TCLAP::SwitchArg, bool> extendedResolution("e", "extendedResolution", "Encode PHP with extended resolution.", cmd, defaultIsFalse); class DimSpecFixedPigeons { private: unsigned numPigeons; unsigned numLiteralsPerTime; /** * Variable representing that pigeon p is in hole h. * Note that hole is the same as time. */ int varPigeonInHole(unsigned p, unsigned h) { return numLiteralsPerTime * h + p + 1; } /** * Helper variable, which is true iff the pigeon sits in a future hole. * i.e. step created hole h, then pigeon sits in a hole added in step later */ int helperFutureHole(int p, int h) { return numLiteralsPerTime * h + numPigeons + p + 1; } void printClause(std::vector<int> clause) { for (int literal: clause) { std::cout << literal << " "; } std::cout << "0" << std::endl; } public: DimSpecFixedPigeons(unsigned _numPigeons): numPigeons(_numPigeons), numLiteralsPerTime(2 * _numPigeons) { } void print() { //i, u, g, t int numberOfClauses = 0; numberOfClauses = numPigeons; std::cout << "i cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { printClause({ varPigeonInHole(i, 0), helperFutureHole(i, 0) }); } numberOfClauses = (numPigeons - 1) * numPigeons / 2; std::cout << "u cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; // at most one pigeon in hole of step for (unsigned i = 0; i < numPigeons; i++) { for (unsigned j = 0; j < i; j++) { printClause({-varPigeonInHole(i, 0) , -varPigeonInHole(j, 0)}); } } numberOfClauses = numPigeons; std::cout << "g cnf " << numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { printClause({-helperFutureHole(i, 0)}); } numberOfClauses = 3 * numPigeons; std::cout << "t cnf " << 2 * numLiteralsPerTime << " " << numberOfClauses << std::endl; for (unsigned i = 0; i < numPigeons; i++) { // -> printClause({ -helperFutureHole(i, 0), varPigeonInHole(i, 1), helperFutureHole(i, 1), }); // <- printClause({ helperFutureHole(i, 0), -varPigeonInHole(i, 1) }); printClause({ helperFutureHole(i, 0), -helperFutureHole(i, 1) }); } } }; class IncrementalFixedPigeons { public: IncrementalFixedPigeons(unsigned _numPigeons): numPigeons(_numPigeons), numLiteralsPerTime(_numPigeons + 1) { } void solve(){ auto& solves = carj::getCarj() .data["/incphp/result/solves"_json_pointer]; solves.clear(); bool solved = false; for (unsigned makespan = 0; !solved; makespan++) { // at most one pigeon in hole of step for (unsigned i = 0; i < numPigeons; i++) { for (unsigned j = 0; j < i; j++) { addClause({ -varPigeonInHole(i, makespan), -varPigeonInHole(j, makespan)}); } } if (makespan >= startingMakeSpan.getValue()) { // each pigeon has at least one hole for (unsigned p = 0; p < numPigeons; p++) { std::vector<int> clause; for (unsigned h = 0; h <= makespan; h++) { clause.push_back(varPigeonInHole(p, h)); } clause.push_back(-activationLiteral(makespan)); addClause(clause); } solves.push_back({ {"makespan", makespan}, {"time", -1} }); { carj::ScopedTimer timer((*solves.rbegin())["time"]); solver.assume(activationLiteral(makespan)); solved = (solver.solve() == ipasir::SolveResult::SAT); } } } } private: /** * Variable representing that pigeon p is in hole h. * Note that hole is the same as makespan. */ int varPigeonInHole(unsigned p, unsigned h) { return numLiteralsPerTime * h + p + 2; } int activationLiteral(unsigned t) { return numLiteralsPerTime * t + 1; } void addClause(std::vector<int> clause) { for (int literal: clause) { solver.add(literal); } solver.add(0); } unsigned numPigeons; unsigned numLiteralsPerTime; ipasir::Solver solver; }; class ExtendedResolution { public: ExtendedResolution(unsigned _numPigeons): numPigeons(_numPigeons) { } void solve(){ unsigned sn = numPigeons; // at most one pigeon in hole h for (unsigned h = 0; h < numPigeons - 1; h++) { for (unsigned i = 0; i < numPigeons; i++) { for (unsigned j = 0; j < i; j++) { addClause({ -P(sn, i, h), -P(sn, j, h)}); } } } // each pigeon has at least one hole for (unsigned p = 0; p < numPigeons; p++) { std::vector<int> clause; for (unsigned h = 0; h < numPigeons - 1; h++) { clause.push_back(P(sn, p, h)); } addClause(clause); } for (unsigned n = sn; n > 2; n--) { for (unsigned i = 0; i < n - 1; i++) { for (unsigned j = 0; j < n - 2; j++) { addClause({ P(n - 1, i, j), -P(n, i, j) }); addClause({ P(n - 1, i, j), -P(n, i, n - 2), -P(n, n - 1, j) }); addClause({ -P(n - 1, i, j), P(n, i, j), P(n, i, n - 2) }); addClause({ -P(n - 1, i, j), P(n, i, j), P(n, n - 1, j) }); } } } auto& solves = carj::getCarj() .data["/incphp/result/solves"_json_pointer]; solves.clear(); LOG(INFO) << "At most one"; for (unsigned makespan = 0; makespan < numPigeons; makespan++) { solves.push_back({ {"makespan", makespan}, {"time", -1} }); LOG(INFO) << "Makespan: " << makespan; carj::ScopedTimer timer((*solves.rbegin())["time"]); for (unsigned h = 0; h < numPigeons - 1 - makespan; h++) { for (unsigned p = 1; p < numPigeons - makespan; p++) { for (unsigned j = 0; j < p; j++) { //carj::ScopedTimer timer((*solves.rbegin())["time"]); //LOG(INFO) << "P(" << sn - makespan << ", " << p << ", " << h << ")"; //LOG(INFO) << "P(" << sn - makespan << ", " << j << ", " << h << ")"; solver.assume(P(sn - makespan, p, h)); solver.assume(P(sn - makespan, j, h)); bool solved = (solver.solve() == ipasir::SolveResult::SAT); assert(!solved); } } } for (unsigned p = 1; p < numPigeons - makespan; p++) { for (unsigned h = 0; h < numPigeons - 1 - makespan; h++) { //carj::ScopedTimer timer((*solves.rbegin())["time"]); //LOG(INFO) << "P(" << sn - makespan << ", " << p << ", " << h << ")"; //LOG(INFO) << "P(" << sn - makespan << ", " << j << ", " << h << ")"; solver.assume(-P(sn - makespan, p, h)); } bool solved = (solver.solve() == ipasir::SolveResult::SAT); assert(!solved); } } // LOG(INFO) << "At Least one"; // for (unsigned makespan = 0; makespan < numPigeons; makespan++) { // solves.push_back({ // {"makespan", makespan}, // {"time", -1} // }); // LOG(INFO) << "Makespan: " << makespan; // carj::ScopedTimer timer((*solves.rbegin())["time"]); // for (unsigned p = 1; p < numPigeons - makespan; p++) { // for (unsigned h = 0; h < numPigeons - 1 - makespan; h++) { // //carj::ScopedTimer timer((*solves.rbegin())["time"]); // //LOG(INFO) << "P(" << sn - makespan << ", " << p << ", " << h << ")"; // //LOG(INFO) << "P(" << sn - makespan << ", " << j << ", " << h << ")"; // solver.assume(-P(sn - makespan, p, h)); // } // bool solved = (solver.solve() == ipasir::SolveResult::SAT); // assert(!solved); // } // } LOG(INFO) << "Final solve"; bool solved = (solver.solve() == ipasir::SolveResult::SAT); assert(!solved); solved = (solver.solve() == ipasir::SolveResult::SAT); assert(!solved); } private: ipasir::Solver solver; unsigned numPigeons; /** * Variable representing that pigeon p is in hole h. */ int P(unsigned n, unsigned p, unsigned h) { return ((n * numPigeons + p) * numPigeons + h) + 1; } void addClause(std::vector<int> clause) { for (int literal: clause) { solver.add(literal); } solver.add(0); } }; int incphp_main(int argc, const char **argv) { carj::init(argc, argv, cmd, "/incphp/parameters"); if (dimspec.getValue()) { DimSpecFixedPigeons dsfp(numberOfPigeons.getValue()); dsfp.print(); } else if (extendedResolution.getValue()) { ExtendedResolution er(numberOfPigeons.getValue()); er.solve(); } else { IncrementalFixedPigeons ifp(numberOfPigeons.getValue()); ifp.solve(); } return 0; } <|endoftext|>
<commit_before>#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "kernel.h" #include <QDebug> Kernel::Kernel(int argc, char** argv) { /* default config */ height = DEF_HEIGHT; width = DEF_WIDTH; fullscreen = false; mode = SINGLEPLAY; map_name = "default_map"; load_config(); /* parse command line arguments */ static const char *optString = "m:h:w:f:c:s"; int opt = 0; opt = getopt(argc, argv, optString); while(opt != -1) { switch(opt) { case 'm': map_name = (char*)malloc(sizeof(optarg)); strcpy(map_name, optarg); break; case 'h': height = atof(optarg); break; case 'w': width = atof(optarg); break; case 'f': fullscreen = atoi(optarg); break; case 'c': if (mode == SERVER) { printf("Warning: options -c and -s should not be used at one time\n"); } mode = CLIENT; server_address = (char*)malloc(sizeof(optarg)); strcpy(server_address, optarg); break; case 's': if (mode == CLIENT) { printf("Warning: options -c and -s should not be used at one time\n"); } mode = SERVER; break; } opt = getopt(argc, argv, optString); } save_config(); printf("Resolution set to %fx%f\n", width, height); if (fullscreen) { printf("Mode fullscreen\n"); } else { printf("Mode windowed\n"); } switch (mode) { case SINGLEPLAY: printf("Mode singleplay\n"); break; case CLIENT: printf("Mode client, server address is %s\n", server_address); break; case SERVER: printf("Mode server\n"); break; } fpc_info.fpc = 0; fpc_info.fpc_max = 0; fpc_info.fpc_min = 0; fpc_info.fpc_min -=1; } void Kernel::load_config() { /* open and read config file */ char option[255]; char value[255]; FILE *config_file; config_file = fopen(CONFIG_PATH, "r"); if (config_file != NULL) { while(fscanf(config_file, "%s %s", option, value) != EOF) { if (!strcmp(option, "height")) { height = atof(value); } if (!strcmp(option, "width")) { width = atof(value); } if (!strcmp(option, "fullscreen")) { fullscreen = atoi(value); } } fclose(config_file); } else { printf("Warning: no config file found\n"); } } void Kernel::save_config() { /* write config to config file */ FILE *config_file; config_file = fopen(CONFIG_PATH, "w"); if (config_file != NULL) { fprintf(config_file, "%s %f\n", "width", width); fprintf(config_file, "%s %f\n", "height", height); fprintf(config_file, "%s %i\n", "fullscreen", fullscreen); fclose(config_file); printf("Config saved\n"); } else { printf("Warning: can not save config\n"); } } /* was not tested yet */ void Kernel::do_command(char* input) { printf("kernel \x1b[31mDEBUG\x1b[0m input comand '%s'\n", input); char command[255]; sscanf(input, "%s", command); if (!strcmp(command, "connect")) { mode = CLIENT; sscanf(input, "%*s %s", server_address); /* ... */ } if (!strcmp(command, "server")) { mode = SERVER; /* ... */ } if (!strcmp(command, "fullscreen")) { fullscreen = false; save_config(); } if (!strcmp(command, "windowed")) { fullscreen = true; save_config(); } if (!strcmp(command, "fpc")) { print_fpc(); } } void Kernel::load_map() { FILE *map_file; char map_path[255]; map_path[0] = '\0'; strcat(map_path, "res/maps/"); strcat(map_path, map_name); strcat(map_path, ".map"); printf("Loading map %s\n", map_path); map_file = fopen(map_path, "r"); int id; Position* pos; SModel* model; if (map_file != NULL) { while(fscanf(map_file, "%i", &id) != EOF) { printf("Loading object %d\n", id); pos = new Position(); model = (SModel*)malloc(sizeof(SModel)); model->mesh_number = id; model->position = pos; if (fscanf(map_file, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, ", model->position->_res_pos.position.v[0], model->position->_res_pos.position.v[1], model->position->_res_pos.position.v[2], model->position->_res_pos.velocity.v[0], model->position->_res_pos.velocity.v[1], model->position->_res_pos.velocity.v[2], model->position->_res_pos.acceleration.v[0], model->position->_res_pos.acceleration.v[1], model->position->_res_pos.acceleration.v[2], model->position->_res_pos.angular_position.v[0], model->position->_res_pos.angular_position.v[1], model->position->_res_pos.angular_position.v[2], model->position->_res_pos.angular_velocity.v[0], model->position->_res_pos.angular_velocity.v[1], model->position->_res_pos.angular_velocity.v[2], model->position->_res_pos.angular_acceleration.v[0], model->position->_res_pos.angular_acceleration.v[1], model->position->_res_pos.angular_acceleration.v[2]) == EOF) { printf("Unexpected end of map file %s\n", map_path); } else { models->push_back(model); } } } else { printf("Can not open map %s\n", map_path); } } void Kernel::print_fpc() { qDebug() << "fpc now: " << fpc_info.fpc; qDebug() << "fpc max: " << fpc_info.fpc_max; qDebug() << "fpc min: " << fpc_info.fpc_min; } <commit_msg>some fixes in load_map<commit_after>#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include "kernel.h" #include <QDebug> Kernel::Kernel(int argc, char** argv) { /* default config */ height = DEF_HEIGHT; width = DEF_WIDTH; fullscreen = false; mode = SINGLEPLAY; map_name = "default_map"; load_config(); /* parse command line arguments */ static const char *optString = "m:h:w:f:c:s"; int opt = 0; opt = getopt(argc, argv, optString); while(opt != -1) { switch(opt) { case 'm': map_name = (char*)malloc(sizeof(optarg)); strcpy(map_name, optarg); break; case 'h': height = atof(optarg); break; case 'w': width = atof(optarg); break; case 'f': fullscreen = atoi(optarg); break; case 'c': if (mode == SERVER) { printf("Warning: options -c and -s should not be used at one time\n"); } mode = CLIENT; server_address = (char*)malloc(sizeof(optarg)); strcpy(server_address, optarg); break; case 's': if (mode == CLIENT) { printf("Warning: options -c and -s should not be used at one time\n"); } mode = SERVER; break; } opt = getopt(argc, argv, optString); } save_config(); printf("Resolution set to %fx%f\n", width, height); if (fullscreen) { printf("Mode fullscreen\n"); } else { printf("Mode windowed\n"); } switch (mode) { case SINGLEPLAY: printf("Mode singleplay\n"); break; case CLIENT: printf("Mode client, server address is %s\n", server_address); break; case SERVER: printf("Mode server\n"); break; } fpc_info.fpc = 0; fpc_info.fpc_max = 0; fpc_info.fpc_min = 0; fpc_info.fpc_min -=1; } void Kernel::load_config() { /* open and read config file */ char option[255]; char value[255]; FILE *config_file; config_file = fopen(CONFIG_PATH, "r"); if (config_file != NULL) { while(fscanf(config_file, "%s %s", option, value) != EOF) { if (!strcmp(option, "height")) { height = atof(value); } if (!strcmp(option, "width")) { width = atof(value); } if (!strcmp(option, "fullscreen")) { fullscreen = atoi(value); } } fclose(config_file); } else { printf("Warning: no config file found\n"); } } void Kernel::save_config() { /* write config to config file */ FILE *config_file; config_file = fopen(CONFIG_PATH, "w"); if (config_file != NULL) { fprintf(config_file, "%s %f\n", "width", width); fprintf(config_file, "%s %f\n", "height", height); fprintf(config_file, "%s %i\n", "fullscreen", fullscreen); fclose(config_file); printf("Config saved\n"); } else { printf("Warning: can not save config\n"); } } /* was not tested yet */ void Kernel::do_command(char* input) { printf("kernel \x1b[31mDEBUG\x1b[0m input comand '%s'\n", input); char command[255]; sscanf(input, "%s", command); if (!strcmp(command, "connect")) { mode = CLIENT; sscanf(input, "%*s %s", server_address); /* ... */ } if (!strcmp(command, "server")) { mode = SERVER; /* ... */ } if (!strcmp(command, "fullscreen")) { fullscreen = false; save_config(); } if (!strcmp(command, "windowed")) { fullscreen = true; save_config(); } if (!strcmp(command, "fpc")) { print_fpc(); } } void Kernel::load_map() { // if (models == NULL) // { models = new std::vector<SModel*>(); // } // else // { /* erase models from vector */ // } FILE *map_file; char map_path[255]; map_path[0] = '\0'; strcat(map_path, "res/maps/"); strcat(map_path, map_name); strcat(map_path, ".map"); printf("Loading map %s\n", map_path); map_file = fopen(map_path, "r"); int id; Position* pos; SModel* model; if (map_file != NULL) { while(fscanf(map_file, "%i", &id) != EOF) { printf("Loading object %d\n", id); pos = new Position(); model = (SModel*)malloc(sizeof(SModel)); model->mesh_number = id; model->position = pos; model->position->_res_pos.angular_acceleration.v[2] = 0.01; float p0, p1, p2, v0, v1, v2, a0, a1, a2, ap0, ap1, ap2, av0, av1, av2, aa0, aa1, aa2; if (fscanf(map_file, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f", &p0, &p1, &p2, &v0, &v1, &v2, &a0, &a1, &a2, &ap0, &ap1, &ap2, &av0, &av1, &av2, &aa0, &aa1, &aa2) == EOF) { printf("Unexpected end of map file %s\n", map_path); } else { model->position->_res_pos.position.v[0] = p0; model->position->_res_pos.position.v[1] = p1; model->position->_res_pos.position.v[2] = p2; model->position->_res_pos.velocity.v[0] = v0; model->position->_res_pos.velocity.v[1] = v1; model->position->_res_pos.velocity.v[2] = v2; model->position->_res_pos.acceleration.v[0] = a0; model->position->_res_pos.acceleration.v[1] = a1; model->position->_res_pos.acceleration.v[2] = a2; model->position->_res_pos.angular_position.v[0] = ap0; model->position->_res_pos.angular_position.v[1] = ap1; model->position->_res_pos.angular_position.v[2] = ap2; model->position->_res_pos.angular_velocity.v[0] = av0; model->position->_res_pos.angular_velocity.v[1] = av1; model->position->_res_pos.angular_velocity.v[2] = av2; model->position->_res_pos.angular_acceleration.v[0] = aa0; model->position->_res_pos.angular_acceleration.v[1] = aa1; model->position->_res_pos.angular_acceleration.v[2] = aa2; models->push_back(model); printf("Added object %d\n", id); } } } else { printf("Can not open map %s\n", map_path); } } void Kernel::print_fpc() { qDebug() << "fpc now: " << fpc_info.fpc; qDebug() << "fpc max: " << fpc_info.fpc_max; qDebug() << "fpc min: " << fpc_info.fpc_min; } <|endoftext|>
<commit_before>/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *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 Redis 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 "logger.hpp" #include "util/helpers.hpp" #include "util/thread/thread_mutex.hpp" #include "util/thread/lock_guard.hpp" #include <stdarg.h> #include <stdio.h> #include <sstream> namespace ardb { static ArdbLogHandler* kLogHandler = 0; static IsLogEnable* kLogChecker = 0; static GetLogStream* kLogStream = 0; static const char* kLogLevelNames[] = { "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE" }; static const unsigned int k_default_log_line_buf_size = 256; static LogLevel kDeafultLevel = DEBUG_LOG_LEVEL; static FILE* kLogFile = stdout; static std::string kLogFilePath; static const uint32 k_max_file_size = 100 * 1024 * 1024; static const uint32 k_max_rolling_index = 2; static ThreadMutex kLogMutex; static void reopen_default_logfile() { if (!kLogFilePath.empty()) { make_file(kLogFilePath); kLogFile = fopen(kLogFilePath.c_str(), "a+"); if (NULL == kLogFile) { kLogFile = stdout; WARN_LOG("Failed to open log file:%s, use stdout instead."); return; } } } static void rollover_default_logfile() { if (NULL != kLogFile) { fclose(kLogFile); kLogFile = stdout; } std::stringstream oldest_file(std::stringstream::in | std::stringstream::out); oldest_file << kLogFilePath << "." << k_max_rolling_index; remove(oldest_file.str().c_str()); for (int i = k_max_rolling_index - 1; i >= 1; --i) { std::stringstream source_oss(std::stringstream::in | std::stringstream::out); std::stringstream target_oss(std::stringstream::in | std::stringstream::out); source_oss << kLogFilePath << "." << i; target_oss << kLogFilePath << "." << (i + 1); if (is_file_exist(source_oss.str())) { remove(target_oss.str().c_str()); rename(source_oss.str().c_str(), target_oss.str().c_str()); } //loglog_renaming_result(*loglog, source, target, ret); } std::stringstream ss(std::stringstream::in | std::stringstream::out); ss << kLogFilePath << ".1"; string path = ss.str(); rename(kLogFilePath.c_str(), path.c_str()); } static void default_loghandler(LogLevel level, const char* filename, const char* function, int line, const char* format, ...) { const char* levelstr = 0; uint64_t timestamp = get_current_epoch_millis(); if (level > 0 && level < ALL_LOG_LEVEL) { levelstr = kLogLevelNames[level - 1]; } else { levelstr = "???"; } size_t log_line_size = k_default_log_line_buf_size; va_list args; std::string record; va_start(args, format); for (;;) { //char content[log_line_size + 1]; char* content = new char[log_line_size + 1]; #ifndef va_copy #define va_copy(dst, src) memcpy(&(dst), &(src), sizeof(va_list)) #endif va_list aq; va_copy(aq, args); int sz = vsnprintf(content, log_line_size, format, aq); va_end(aq); if (sz < 0) { DELETE_A(content); return; } if ((size_t) sz < log_line_size) { record = content; DELETE_A(content); break; } log_line_size <<= 1; } uint32 mills = timestamp % 1000; char timetag[256]; struct tm& tm = get_current_tm(); sprintf(timetag, "%02u-%02u %02u:%02u:%02u", tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); LockGuard<ThreadMutex> guard(kLogMutex); fprintf(kLogFile, "[%u] %s,%03u %s %s\n", getpid(), timetag, mills, levelstr, record.c_str()); fflush(kLogFile); if (!kLogFilePath.empty() && kLogFile != stdout) { long file_size = ftell(kLogFile); if (file_size < 0) { reopen_default_logfile(); } else if ((uint32) file_size >= k_max_file_size) { rollover_default_logfile(); reopen_default_logfile(); } } } static bool default_logchcker(LogLevel level) { return level <= kDeafultLevel; } ArdbLogHandler* ArdbLogger::GetLogHandler() { if (!kLogHandler) { kLogHandler = default_loghandler; } return kLogHandler; } IsLogEnable* ArdbLogger::GetLogChecker() { if (!kLogChecker) { kLogChecker = default_logchcker; } return kLogChecker; } void ArdbLogger::InstallLogHandler(LoggerSetting& setting) { kLogHandler = setting.handler; kLogChecker = setting.enable; kLogStream = setting.logstream; } void ArdbLogger::SetLogLevel(const std::string& level) { std::string level_str = string_toupper(level); for (uint32 i = 0; (i + 1) < ALL_LOG_LEVEL; i++) { if (level_str == kLogLevelNames[i]) { kDeafultLevel = (LogLevel) (i + 1); } } } void ArdbLogger::InitDefaultLogger(const std::string& level, const std::string& logfile) { if (!logfile.empty() && (logfile != "stdout" && logfile != "stderr")) { kLogFilePath = logfile; reopen_default_logfile(); } SetLogLevel(level); } void ArdbLogger::DestroyDefaultLogger() { if (kLogFile != stdout) { fclose(kLogFile); } } FILE* ArdbLogger::GetLogStream() { if (!kLogFile) { return stderr; } return kLogFile; } } <commit_msg>fix potential memory leak for logger<commit_after>/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *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 Redis 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 "logger.hpp" #include "util/helpers.hpp" #include "util/thread/thread_mutex.hpp" #include "util/thread/lock_guard.hpp" #include <stdarg.h> #include <stdio.h> #include <sstream> namespace ardb { static ArdbLogHandler* kLogHandler = 0; static IsLogEnable* kLogChecker = 0; static GetLogStream* kLogStream = 0; static const char* kLogLevelNames[] = { "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE" }; static const unsigned int k_default_log_line_buf_size = 256; static LogLevel kDeafultLevel = DEBUG_LOG_LEVEL; static FILE* kLogFile = stdout; static std::string kLogFilePath; static const uint32 k_max_file_size = 100 * 1024 * 1024; static const uint32 k_max_rolling_index = 2; static ThreadMutex kLogMutex; static void reopen_default_logfile() { if (!kLogFilePath.empty()) { make_file(kLogFilePath); kLogFile = fopen(kLogFilePath.c_str(), "a+"); if (NULL == kLogFile) { kLogFile = stdout; WARN_LOG("Failed to open log file:%s, use stdout instead."); return; } } } static void rollover_default_logfile() { if (NULL != kLogFile) { fclose(kLogFile); kLogFile = stdout; } std::stringstream oldest_file(std::stringstream::in | std::stringstream::out); oldest_file << kLogFilePath << "." << k_max_rolling_index; remove(oldest_file.str().c_str()); for (int i = k_max_rolling_index - 1; i >= 1; --i) { std::stringstream source_oss(std::stringstream::in | std::stringstream::out); std::stringstream target_oss(std::stringstream::in | std::stringstream::out); source_oss << kLogFilePath << "." << i; target_oss << kLogFilePath << "." << (i + 1); if (is_file_exist(source_oss.str())) { remove(target_oss.str().c_str()); rename(source_oss.str().c_str(), target_oss.str().c_str()); } //loglog_renaming_result(*loglog, source, target, ret); } std::stringstream ss(std::stringstream::in | std::stringstream::out); ss << kLogFilePath << ".1"; string path = ss.str(); rename(kLogFilePath.c_str(), path.c_str()); } static void default_loghandler(LogLevel level, const char* filename, const char* function, int line, const char* format, ...) { const char* levelstr = 0; uint64_t timestamp = get_current_epoch_millis(); if (level > 0 && level < ALL_LOG_LEVEL) { levelstr = kLogLevelNames[level - 1]; } else { levelstr = "???"; } size_t log_line_size = k_default_log_line_buf_size; va_list args; std::string record; va_start(args, format); for (;;) { //char content[log_line_size + 1]; char* content = new char[log_line_size + 1]; #ifndef va_copy #define va_copy(dst, src) memcpy(&(dst), &(src), sizeof(va_list)) #endif va_list aq; va_copy(aq, args); int sz = vsnprintf(content, log_line_size, format, aq); va_end(aq); if (sz < 0) { DELETE_A(content); return; } if ((size_t) sz < log_line_size) { record = content; DELETE_A(content); break; } log_line_size <<= 1; DELETE_A(content); } uint32 mills = timestamp % 1000; char timetag[256]; struct tm& tm = get_current_tm(); sprintf(timetag, "%02u-%02u %02u:%02u:%02u", tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); LockGuard<ThreadMutex> guard(kLogMutex); fprintf(kLogFile, "[%u] %s,%03u %s %s\n", getpid(), timetag, mills, levelstr, record.c_str()); fflush(kLogFile); if (!kLogFilePath.empty() && kLogFile != stdout) { long file_size = ftell(kLogFile); if (file_size < 0) { reopen_default_logfile(); } else if ((uint32) file_size >= k_max_file_size) { rollover_default_logfile(); reopen_default_logfile(); } } } static bool default_logchcker(LogLevel level) { return level <= kDeafultLevel; } ArdbLogHandler* ArdbLogger::GetLogHandler() { if (!kLogHandler) { kLogHandler = default_loghandler; } return kLogHandler; } IsLogEnable* ArdbLogger::GetLogChecker() { if (!kLogChecker) { kLogChecker = default_logchcker; } return kLogChecker; } void ArdbLogger::InstallLogHandler(LoggerSetting& setting) { kLogHandler = setting.handler; kLogChecker = setting.enable; kLogStream = setting.logstream; } void ArdbLogger::SetLogLevel(const std::string& level) { std::string level_str = string_toupper(level); for (uint32 i = 0; (i + 1) < ALL_LOG_LEVEL; i++) { if (level_str == kLogLevelNames[i]) { kDeafultLevel = (LogLevel) (i + 1); } } } void ArdbLogger::InitDefaultLogger(const std::string& level, const std::string& logfile) { if (!logfile.empty() && (logfile != "stdout" && logfile != "stderr")) { kLogFilePath = logfile; reopen_default_logfile(); } SetLogLevel(level); } void ArdbLogger::DestroyDefaultLogger() { if (kLogFile != stdout) { fclose(kLogFile); } } FILE* ArdbLogger::GetLogStream() { if (!kLogFile) { return stderr; } return kLogFile; } } <|endoftext|>
<commit_before>#ifndef __LOGGER_HPP__ #define __LOGGER_HPP__ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> // The file to write log messages to. It defaults to stderr, but main() may set it to something // different. extern FILE *log_file; /* These functions log things. */ enum log_level_t { DBG = 0, INF = 1, WRN, ERR }; // Log a message in one chunk. You still have to provide '\n'. // logf is a standard library function in <math.h>. So we use _logf. void _logf(const char *src_file, int src_line, log_level_t level, const char *format, ...) __attribute__ ((format (printf, 4, 5))); #ifndef NDEBUG #define logDBG(fmt, args...) _logf(__FILE__, __LINE__, DBG, (fmt), ##args) #else #define logDBG(fmt, args...) ((void)0) #endif #define logINF(fmt, args...) _logf(__FILE__, __LINE__, INF, (fmt), ##args) #define logWRN(fmt, args...) _logf(__FILE__, __LINE__, WRN, (fmt), ##args) #define logERR(fmt, args...) _logf(__FILE__, __LINE__, ERR, (fmt), ##args) #ifndef NDEBUG #define log_call(fn, args...) do { \ debugf("%s:%u: %s: entered\n", __FILE__, __LINE__, stringify(fn)); \ fn(args); \ debugf("%s:%u: %s: returned\n", __FILE__, __LINE__, stringify(fn)); \ } while (0) #define TRACEPOINT debugf("%s:%u reached\n", __FILE__, __LINE__) #else #define log_call(fn, args...) fn(args) // TRACEPOINT is not defined in release, so that TRACEPOINTS do not linger in the code unnecessarily #endif // Log a message in pieces. void _mlog_start(const char *src_file, int src_line, log_level_t level); #define mlog_start(lvl) (_mlog_start(__FILE__, __LINE__, (lvl))) void mlogf(const char *format, ...) __attribute__ ((format (printf, 1, 2))); void mlog_end(); /* The logger has two modes. During the main phase of the server running, it will send all log messages to one thread and write them to the file from there; this makes it so that we don't block on the log file's lock. During the startup and shutdown phases, we just write messages directly from the file and don't care about the performance hit from the lock. To enter the high-performance mode, construct a log_controller_t from within a coroutine in a thread pool. */ class log_controller_t { public: // The constructor and destructor are potentially blocking. log_controller_t(); ~log_controller_t(); int home_thread; }; #endif // __LOGGER_HPP__ <commit_msg>A small TODO in logger.hpp.<commit_after>#ifndef __LOGGER_HPP__ #define __LOGGER_HPP__ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> // The file to write log messages to. It defaults to stderr, but main() may set it to something // different. extern FILE *log_file; /* These functions log things. */ enum log_level_t { DBG = 0, INF = 1, WRN, ERR }; // Log a message in one chunk. You still have to provide '\n'. // logf is a standard library function in <math.h>. So we use _logf. void _logf(const char *src_file, int src_line, log_level_t level, const char *format, ...) __attribute__ ((format (printf, 4, 5))); #ifndef NDEBUG #define logDBG(fmt, args...) _logf(__FILE__, __LINE__, DBG, (fmt), ##args) #else #define logDBG(fmt, args...) ((void)0) #endif #define logINF(fmt, args...) _logf(__FILE__, __LINE__, INF, (fmt), ##args) #define logWRN(fmt, args...) _logf(__FILE__, __LINE__, WRN, (fmt), ##args) #define logERR(fmt, args...) _logf(__FILE__, __LINE__, ERR, (fmt), ##args) // TODO: This should not be named log_call. It uses debugf. #ifndef NDEBUG #define log_call(fn, args...) do { \ debugf("%s:%u: %s: entered\n", __FILE__, __LINE__, stringify(fn)); \ fn(args); \ debugf("%s:%u: %s: returned\n", __FILE__, __LINE__, stringify(fn)); \ } while (0) #define TRACEPOINT debugf("%s:%u reached\n", __FILE__, __LINE__) #else #define log_call(fn, args...) fn(args) // TRACEPOINT is not defined in release, so that TRACEPOINTS do not linger in the code unnecessarily #endif // Log a message in pieces. void _mlog_start(const char *src_file, int src_line, log_level_t level); #define mlog_start(lvl) (_mlog_start(__FILE__, __LINE__, (lvl))) void mlogf(const char *format, ...) __attribute__ ((format (printf, 1, 2))); void mlog_end(); /* The logger has two modes. During the main phase of the server running, it will send all log messages to one thread and write them to the file from there; this makes it so that we don't block on the log file's lock. During the startup and shutdown phases, we just write messages directly from the file and don't care about the performance hit from the lock. To enter the high-performance mode, construct a log_controller_t from within a coroutine in a thread pool. */ class log_controller_t { public: // The constructor and destructor are potentially blocking. log_controller_t(); ~log_controller_t(); int home_thread; }; #endif // __LOGGER_HPP__ <|endoftext|>
<commit_before>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: yanshiguang02@baidu.com #include "logging.h" #include <assert.h> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/weak_ptr.hpp> #include <queue> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <syscall.h> #include <sys/time.h> #include <unistd.h> #include "mutex.h" #include "thread.h" #include "timer.h" namespace baidu { namespace common { int g_log_level = INFO; int64_t g_log_size = 0; FILE* g_log_file = stdout; std::string g_log_file_name; FILE* g_warning_file = NULL; bool GetNewLog(bool append) { char buf[30]; struct timeval tv; gettimeofday(&tv, NULL); const time_t seconds = tv.tv_sec; struct tm t; localtime_r(&seconds, &t); snprintf(buf, 30, "%02d-%02d.%02d:%02d:%02d.%06d", t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, static_cast<int>(tv.tv_usec)); std::string full_path(g_log_file_name + "."); full_path.append(buf); size_t idx = full_path.rfind('/'); if (idx == std::string::npos) { idx = 0; } else { idx += 1; } const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(full_path.c_str(), mode); if (fp == NULL) { return false; } if (g_log_file != stdout) { fclose(g_log_file); } g_log_file = fp; remove(g_log_file_name.c_str()); symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str()); return true; } void SetLogLevel(int level) { g_log_level = level; } class AsyncLogger { public: AsyncLogger() : jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) { thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this)); } ~AsyncLogger() { stopped_ = true; { MutexLock lock(&mu_); jobs_.Signal(); } thread_.Join(); // close fd } void WriteLog(int log_level, const char* buffer, int32_t len) { std::string* log_str = new std::string(buffer, len); MutexLock lock(&mu_); buffer_queue_.push(make_pair(log_level, log_str)); jobs_.Signal(); } void AsyncWriter() { MutexLock lock(&mu_); while (1) { int loglen = 0; int wflen = 0; while (!buffer_queue_.empty()) { int log_level = buffer_queue_.front().first; std::string* str = buffer_queue_.front().second; buffer_queue_.pop(); if (g_log_file != stdout && g_log_size && static_cast<int64_t>(size_ + str->length()) > g_log_size) { GetNewLog(false); size_ = 0; } mu_.Unlock(); if (str && !str->empty()) { fwrite(str->data(), 1, str->size(), g_log_file); loglen += str->size(); if (g_warning_file && log_level >= 8) { fwrite(str->data(), 1, str->size(), g_warning_file); wflen += str->size(); } if (g_log_size) size_ += str->length(); } delete str; mu_.Lock(); } if (loglen) fflush(g_log_file); if (wflen) fflush(g_warning_file); if (stopped_) { break; } done_.Broadcast(); jobs_.Wait(); } } void Flush() { MutexLock lock(&mu_); buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL))); jobs_.Signal(); done_.Wait(); } private: Mutex mu_; CondVar jobs_; CondVar done_; bool stopped_; int64_t size_; Thread thread_; std::queue<std::pair<int, std::string*> > buffer_queue_; }; boost::shared_ptr<AsyncLogger> g_logger(new AsyncLogger); bool SetWarningFile(const char* path, bool append) { const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(path, mode); if (fp == NULL) { return false; } if (g_warning_file) { fclose(g_warning_file); } g_warning_file = fp; return true; } bool SetLogFile(const char* path, bool append) { g_log_file_name.assign(path); return GetNewLog(append); } bool SetLogSize(int size) { if (size < 0) { return false; } g_log_size = static_cast<int64_t>(size) << 20; return true; } void Logv(int log_level, const char* format, va_list ap) { static __thread uint64_t thread_id = 0; if (thread_id == 0) { thread_id = syscall(__NR_gettid); } static __thread boost::weak_ptr<AsyncLogger> wk_logger = g_logger; boost::shared_ptr<AsyncLogger> logger = wk_logger.lock(); if (!logger) { return; } // We try twice: the first time with a fixed-size stack allocated buffer, // and the second time with a much larger dynamically allocated buffer. char buffer[500]; for (int iter = 0; iter < 2; iter++) { char* base; int bufsize; if (iter == 0) { bufsize = sizeof(buffer); base = buffer; } else { bufsize = 30000; base = new char[bufsize]; } char* p = base; char* limit = base + bufsize; int32_t rlen = timer::now_time_str(p, limit - p); p += rlen; p += snprintf(p, limit - p, " %lld ", static_cast<long long unsigned int>(thread_id)); // Print the message if (p < limit) { va_list backup_ap; va_copy(backup_ap, ap); p += vsnprintf(p, limit - p, format, backup_ap); va_end(backup_ap); } // Truncate to available space if necessary if (p >= limit) { if (iter == 0) { continue; // Try again with larger buffer } else { p = limit - 1; } } // Add newline if necessary if (p == base || p[-1] != '\n') { *p++ = '\n'; } assert(p <= limit); //fwrite(base, 1, p - base, g_log_file); //fflush(g_log_file); //if (g_warning_file && log_level >= 8) { // fwrite(base, 1, p - base, g_warning_file); // fflush(g_warning_file); //} logger->WriteLog(log_level, base, p - base); if (log_level == FATAL) { logger->Flush(); } if (base != buffer) { delete[] base; } break; } } void Log(int level, const char* fmt, ...) { va_list ap; va_start(ap, fmt); if (level >= g_log_level) { Logv(level, fmt, ap); } va_end(ap); if (level == FATAL) { abort(); } } LogStream::LogStream(int level) : level_(level) {} LogStream::~LogStream() { Log(level_, "%s", oss_.str().c_str()); } } // namespace common } // namespace baidu /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */ <commit_msg>Revert "Use shared_ptr/weak_ptr to manage g_logger's lifetime"<commit_after>// Copyright (c) 2014, Baidu.com, Inc. All Rights Reserved // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // Author: yanshiguang02@baidu.com #include "logging.h" #include <assert.h> #include <boost/bind.hpp> #include <queue> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string> #include <syscall.h> #include <sys/time.h> #include <unistd.h> #include "mutex.h" #include "thread.h" #include "timer.h" namespace baidu { namespace common { int g_log_level = INFO; int64_t g_log_size = 0; FILE* g_log_file = stdout; std::string g_log_file_name; FILE* g_warning_file = NULL; bool GetNewLog(bool append) { char buf[30]; struct timeval tv; gettimeofday(&tv, NULL); const time_t seconds = tv.tv_sec; struct tm t; localtime_r(&seconds, &t); snprintf(buf, 30, "%02d-%02d.%02d:%02d:%02d.%06d", t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, static_cast<int>(tv.tv_usec)); std::string full_path(g_log_file_name + "."); full_path.append(buf); size_t idx = full_path.rfind('/'); if (idx == std::string::npos) { idx = 0; } else { idx += 1; } const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(full_path.c_str(), mode); if (fp == NULL) { return false; } if (g_log_file != stdout) { fclose(g_log_file); } g_log_file = fp; remove(g_log_file_name.c_str()); symlink(full_path.substr(idx).c_str(), g_log_file_name.c_str()); return true; } void SetLogLevel(int level) { g_log_level = level; } class AsyncLogger { public: AsyncLogger() : jobs_(&mu_), done_(&mu_), stopped_(false), size_(0) { thread_.Start(boost::bind(&AsyncLogger::AsyncWriter, this)); } ~AsyncLogger() { stopped_ = true; { MutexLock lock(&mu_); jobs_.Signal(); } thread_.Join(); // close fd } void WriteLog(int log_level, const char* buffer, int32_t len) { std::string* log_str = new std::string(buffer, len); MutexLock lock(&mu_); buffer_queue_.push(make_pair(log_level, log_str)); jobs_.Signal(); } void AsyncWriter() { MutexLock lock(&mu_); while (1) { int loglen = 0; int wflen = 0; while (!buffer_queue_.empty()) { int log_level = buffer_queue_.front().first; std::string* str = buffer_queue_.front().second; buffer_queue_.pop(); if (g_log_file != stdout && g_log_size && static_cast<int64_t>(size_ + str->length()) > g_log_size) { GetNewLog(false); size_ = 0; } mu_.Unlock(); if (str && !str->empty()) { fwrite(str->data(), 1, str->size(), g_log_file); loglen += str->size(); if (g_warning_file && log_level >= 8) { fwrite(str->data(), 1, str->size(), g_warning_file); wflen += str->size(); } if (g_log_size) size_ += str->length(); } delete str; mu_.Lock(); } if (loglen) fflush(g_log_file); if (wflen) fflush(g_warning_file); if (stopped_) { break; } done_.Broadcast(); jobs_.Wait(); } } void Flush() { MutexLock lock(&mu_); buffer_queue_.push(std::make_pair(0, reinterpret_cast<std::string*>(NULL))); jobs_.Signal(); done_.Wait(); } private: Mutex mu_; CondVar jobs_; CondVar done_; bool stopped_; int64_t size_; Thread thread_; std::queue<std::pair<int, std::string*> > buffer_queue_; }; AsyncLogger g_logger; bool SetWarningFile(const char* path, bool append) { const char* mode = append ? "ab" : "wb"; FILE* fp = fopen(path, mode); if (fp == NULL) { return false; } if (g_warning_file) { fclose(g_warning_file); } g_warning_file = fp; return true; } bool SetLogFile(const char* path, bool append) { g_log_file_name.assign(path); return GetNewLog(append); } bool SetLogSize(int size) { if (size < 0) { return false; } g_log_size = static_cast<int64_t>(size) << 20; return true; } void Logv(int log_level, const char* format, va_list ap) { static __thread uint64_t thread_id = 0; if (thread_id == 0) { thread_id = syscall(__NR_gettid); } // We try twice: the first time with a fixed-size stack allocated buffer, // and the second time with a much larger dynamically allocated buffer. char buffer[500]; for (int iter = 0; iter < 2; iter++) { char* base; int bufsize; if (iter == 0) { bufsize = sizeof(buffer); base = buffer; } else { bufsize = 30000; base = new char[bufsize]; } char* p = base; char* limit = base + bufsize; int32_t rlen = timer::now_time_str(p, limit - p); p += rlen; p += snprintf(p, limit - p, " %lld ", static_cast<long long unsigned int>(thread_id)); // Print the message if (p < limit) { va_list backup_ap; va_copy(backup_ap, ap); p += vsnprintf(p, limit - p, format, backup_ap); va_end(backup_ap); } // Truncate to available space if necessary if (p >= limit) { if (iter == 0) { continue; // Try again with larger buffer } else { p = limit - 1; } } // Add newline if necessary if (p == base || p[-1] != '\n') { *p++ = '\n'; } assert(p <= limit); //fwrite(base, 1, p - base, g_log_file); //fflush(g_log_file); //if (g_warning_file && log_level >= 8) { // fwrite(base, 1, p - base, g_warning_file); // fflush(g_warning_file); //} g_logger.WriteLog(log_level, base, p - base); if (log_level == FATAL) { g_logger.Flush(); } if (base != buffer) { delete[] base; } break; } } void Log(int level, const char* fmt, ...) { va_list ap; va_start(ap, fmt); if (level >= g_log_level) { Logv(level, fmt, ap); } va_end(ap); if (level == FATAL) { abort(); } } LogStream::LogStream(int level) : level_(level) {} LogStream::~LogStream() { Log(level_, "%s", oss_.str().c_str()); } } // namespace common } // namespace baidu /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */ <|endoftext|>
<commit_before><commit_msg>improve SB<commit_after><|endoftext|>
<commit_before>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: lookup_benchmark.cc // ----------------------------------------------------------------------------- // // Benchmarks for various `IndexStructure`s. Add new benchmark configs in the // `main(..)` function. // // To run the benchmark run: // bazel run -c opt --cxxopt='-std=c++17' --dynamic_mode=off :lookup_benchmark // -- --input_file_path='...' --columns_to_test='A,B,C' // // Example run: // Run on (80 X 3900 MHz CPU s) // CPU Caches: // L1 Data 32 KiB (x40) // L1 Instruction 32 KiB (x40) // L2 Unified 1024 KiB (x40) // L3 Unified 28160 KiB (x2) // Load Average: 0.88, 0.68, 0.71 // ----------------------------------------------------------------------------- // Benchmark Time // ----------------------------------------------------------------------------- // PositiveDistinctLookup/Color/16384/PerStripeBloom/10 28543 ns // NegativeLookup/Color/16384/PerStripeBloom/10 34615 ns // PositiveDistinctLookup/Color/16384/CuckooIndex:1:0.49:0.02 2562 ns // NegativeLookup/Color/16384/CuckooIndex:1:0.49:0.02 891 ns // PositiveDistinctLookup/Color/16384/CuckooIndex:1:0.84:0.02 5240 ns // NegativeLookup/Color/16384/CuckooIndex:1:0.84:0.02 5113 ns // PositiveDistinctLookup/Color/16384/CuckooIndex:1:0.95:0.02 3845 ns // NegativeLookup/Color/16384/CuckooIndex:1:0.95:0.02 4157 ns // PositiveDistinctLookup/Color/16384/CuckooIndex:1:0.98:0.02 3396 ns // NegativeLookup/Color/16384/CuckooIndex:1:0.98:0.02 3992 ns // PositiveDistinctLookup/Color/16384/PerStripeXor 4768 ns // NegativeLookup/Color/16384/PerStripeXor 3664 ns // PositiveDistinctLookup/Color/65536/PerStripeBloom/10 7745 ns // NegativeLookup/Color/65536/PerStripeBloom/10 8782 ns // PositiveDistinctLookup/Color/65536/CuckooIndex:1:0.49:0.02 1396 ns // NegativeLookup/Color/65536/CuckooIndex:1:0.49:0.02 581 ns // PositiveDistinctLookup/Color/65536/CuckooIndex:1:0.84:0.02 4111 ns // NegativeLookup/Color/65536/CuckooIndex:1:0.84:0.02 5056 ns // PositiveDistinctLookup/Color/65536/CuckooIndex:1:0.95:0.02 2821 ns // NegativeLookup/Color/65536/CuckooIndex:1:0.95:0.02 4281 ns // PositiveDistinctLookup/Color/65536/CuckooIndex:1:0.98:0.02 2486 ns // NegativeLookup/Color/65536/CuckooIndex:1:0.98:0.02 4377 ns // PositiveDistinctLookup/Color/65536/PerStripeXor 1383 ns // NegativeLookup/Color/65536/PerStripeXor 895 ns #include <cstdlib> #include <random> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "benchmark/benchmark.h" #include "cuckoo_index.h" #include "cuckoo_utils.h" #include "index_structure.h" #include "per_stripe_bloom.h" #include "per_stripe_xor.h" ABSL_FLAG(std::string, input_file_path, "", "Path to the Capacitor file."); ABSL_FLAG(std::vector<std::string>, columns_to_test, {}, "Comma-separated list of columns to tests, e.g. " "'company_name,country_code'."); ABSL_FLAG(std::vector<std::string>, num_rows_per_stripe_to_test, {"10000"}, "Number of rows per stripe. Defaults to 10,000."); ABSL_FLAG(std::string, sorting, "NONE", "Sorting to apply to the data. Supported values: 'NONE', " "'BY_CARDINALITY' (sorts lexicographically, starting with columns " "with the lowest cardinality), 'RANDOM'"); // To avoid drawing a random value for each single lookup, we look values up in // batches. To avoid caching effects, we use 1M values as the batch size. constexpr size_t kLookupBatchSize = 1'000'000; constexpr absl::string_view kNoSorting = "NONE"; constexpr absl::string_view kByCardinalitySorting = "BY_CARDINALITY"; constexpr absl::string_view kRandomSorting = "RANDOM"; bool IsValidSorting(absl::string_view sorting) { static const auto* values = new absl::flat_hash_set<absl::string_view>( {kNoSorting, kByCardinalitySorting, kRandomSorting}); return values->contains(sorting); } void BM_PositiveDistinctLookup(const ci::Column& column, std::shared_ptr<ci::IndexStructure> index, const int num_stripes, benchmark::State& state) { std::mt19937 gen(42); std::vector<int> distinct_values = column.distinct_values(); // Remove NULLs from the lookup. distinct_values.erase( std::remove(distinct_values.begin(), distinct_values.end(), ci::Column::kIntNullSentinel), distinct_values.end()); std::uniform_int_distribution<std::size_t> distinct_values_offset_d( 0, distinct_values.size() - 1); std::vector<int> values; values.reserve(kLookupBatchSize); for (size_t i = 0; i < kLookupBatchSize; ++i) { values.push_back(distinct_values[distinct_values_offset_d(gen)]); } while (state.KeepRunningBatch(values.size())) { for (size_t i = 0; i < values.size(); ++i) { ::benchmark::DoNotOptimize(index->GetQualifyingStripes(values[i], num_stripes)); } } } void BM_NegativeLookup(const ci::Column& column, std::shared_ptr<ci::IndexStructure> index, const int num_stripes, benchmark::State& state) { std::mt19937 gen(42); std::uniform_int_distribution<int> value_d(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); std::vector<int> values; values.reserve(kLookupBatchSize); for (size_t i = 0; i < kLookupBatchSize; ++i) { // Draw random value that is not present in the column. int value = value_d(gen); while (column.Contains(value)) { value = value_d(gen); } values.push_back(value); } while (state.KeepRunningBatch(values.size())) { for (size_t i = 0; i < values.size(); ++i) { ::benchmark::DoNotOptimize(index->GetQualifyingStripes(values[i], num_stripes)); } } } int main(int argc, char* argv[]) { absl::ParseCommandLine(argc, argv); if (absl::GetFlag(FLAGS_input_file_path).empty()) { std::cerr << "You must specify --input_file_path" << std::endl; std::exit(EXIT_FAILURE); } // Define data. const std::vector<std::string> column_names = absl::GetFlag(FLAGS_columns_to_test); std::unique_ptr<ci::Table> table = ci::Table::FromCsv(absl::GetFlag(FLAGS_input_file_path), column_names); // Potentially sort the data. const std::string sorting = absl::GetFlag(FLAGS_sorting); if (!IsValidSorting(sorting)) { std::cerr << "Invalid sorting method: " << sorting << std::endl; std::exit(EXIT_FAILURE); } if (sorting == kByCardinalitySorting) { std::cerr << "Sorting the table according to column cardinality..." << std::endl; table->SortWithCardinalityKey(); } else if (sorting == kRandomSorting) { std::cerr << "Randomly shuffling the table..." << std::endl; table->Shuffle(); } std::vector<std::unique_ptr<ci::IndexStructureFactory>> index_factories; index_factories.push_back( absl::make_unique<ci::PerStripeBloomFactory>(/*num_bits_per_key=*/10)); index_factories.push_back(absl::make_unique<ci::CuckooIndexFactory>( ci::CuckooAlgorithm::SKEWED_KICKING, /*max_load_factor=*/ci::kMaxLoadFactor1SlotsPerBucket, /*scan_rate=*/0.02, /*slots_per_bucket=*/1, /*prefix_bits_optimization=*/false)); index_factories.push_back(absl::make_unique<ci::CuckooIndexFactory>( ci::CuckooAlgorithm::SKEWED_KICKING, /*max_load_factor=*/ci::kMaxLoadFactor2SlotsPerBucket, /*scan_rate=*/0.02, /*slots_per_bucket=*/2, /*prefix_bits_optimization=*/false)); index_factories.push_back(absl::make_unique<ci::CuckooIndexFactory>( ci::CuckooAlgorithm::SKEWED_KICKING, /*max_load_factor=*/ci::kMaxLoadFactor4SlotsPerBucket, /*scan_rate=*/0.02, /*slots_per_bucket=*/4, /*prefix_bits_optimization=*/false)); index_factories.push_back(absl::make_unique<ci::CuckooIndexFactory>( ci::CuckooAlgorithm::SKEWED_KICKING, /*max_load_factor=*/ci::kMaxLoadFactor8SlotsPerBucket, /*scan_rate=*/0.02, /*slots_per_bucket=*/8, /*prefix_bits_optimization=*/false)); index_factories.push_back(absl::make_unique<ci::PerStripeXorFactory>()); // Set up the benchmarks. for (const std::unique_ptr<ci::Column>& column : table->GetColumns()) { for (size_t num_rows_per_stripe : {1ULL << 14, 1ULL << 16}) { for (const std::unique_ptr<ci::IndexStructureFactory>& factory : index_factories) { std::shared_ptr<ci::IndexStructure> index = absl::WrapUnique( factory->Create(*column, num_rows_per_stripe).release()); const int num_stripes = column->num_rows() / num_rows_per_stripe; const std::string positive_distinct_lookup_benchmark_name = absl::StrFormat(/*format=*/"PositiveDistinctLookup/%s/%d/%s", column->name(), num_rows_per_stripe, index->name()); ::benchmark::RegisterBenchmark( positive_distinct_lookup_benchmark_name.c_str(), [&column, index, num_stripes](::benchmark::State& st) -> void { BM_PositiveDistinctLookup(*column, index, num_stripes, st); }); const std::string negative_lookup_benchmark_name = absl::StrFormat(/*format=*/"NegativeLookup/%s/%d/%s", column->name(), num_rows_per_stripe, index->name()); ::benchmark::RegisterBenchmark( negative_lookup_benchmark_name.c_str(), [&column, index, num_stripes](::benchmark::State& st) -> void { BM_NegativeLookup(*column, index, num_stripes, st); }); } } } ::benchmark::Initialize(&argc, argv); ::benchmark::RunSpecifiedBenchmarks(); return EXIT_SUCCESS; } <commit_msg>Use generated values in lookup benchmark.<commit_after>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ----------------------------------------------------------------------------- // File: lookup_benchmark.cc // ----------------------------------------------------------------------------- // // Benchmarks for various `IndexStructure`s. Add new benchmark configs in the // `main(..)` function. // // To run the benchmark run: // bazel run -c opt --cxxopt='-std=c++17' --dynamic_mode=off :lookup_benchmark // -- --input_file_path='...' --columns_to_test='A,B,C' // // Example run: // Run on (80 X 3900 MHz CPU s) // CPU Caches: // L1 Data 32 KiB (x40) // L1 Instruction 32 KiB (x40) // L2 Unified 1024 KiB (x40) // L3 Unified 28160 KiB (x2) // Load Average: 0.88, 0.68, 0.71 // ----------------------------------------------------------------------------- // Benchmark Time // ----------------------------------------------------------------------------- // PositiveDistinctLookup/Color/16384/PerStripeBloom/10 28543 ns // NegativeLookup/Color/16384/PerStripeBloom/10 34615 ns // PositiveDistinctLookup/Color/16384/CuckooIndex:1:0.49:0.02 2562 ns // NegativeLookup/Color/16384/CuckooIndex:1:0.49:0.02 891 ns // PositiveDistinctLookup/Color/16384/CuckooIndex:1:0.84:0.02 5240 ns // NegativeLookup/Color/16384/CuckooIndex:1:0.84:0.02 5113 ns // PositiveDistinctLookup/Color/16384/CuckooIndex:1:0.95:0.02 3845 ns // NegativeLookup/Color/16384/CuckooIndex:1:0.95:0.02 4157 ns // PositiveDistinctLookup/Color/16384/CuckooIndex:1:0.98:0.02 3396 ns // NegativeLookup/Color/16384/CuckooIndex:1:0.98:0.02 3992 ns // PositiveDistinctLookup/Color/16384/PerStripeXor 4768 ns // NegativeLookup/Color/16384/PerStripeXor 3664 ns // PositiveDistinctLookup/Color/65536/PerStripeBloom/10 7745 ns // NegativeLookup/Color/65536/PerStripeBloom/10 8782 ns // PositiveDistinctLookup/Color/65536/CuckooIndex:1:0.49:0.02 1396 ns // NegativeLookup/Color/65536/CuckooIndex:1:0.49:0.02 581 ns // PositiveDistinctLookup/Color/65536/CuckooIndex:1:0.84:0.02 4111 ns // NegativeLookup/Color/65536/CuckooIndex:1:0.84:0.02 5056 ns // PositiveDistinctLookup/Color/65536/CuckooIndex:1:0.95:0.02 2821 ns // NegativeLookup/Color/65536/CuckooIndex:1:0.95:0.02 4281 ns // PositiveDistinctLookup/Color/65536/CuckooIndex:1:0.98:0.02 2486 ns // NegativeLookup/Color/65536/CuckooIndex:1:0.98:0.02 4377 ns // PositiveDistinctLookup/Color/65536/PerStripeXor 1383 ns // NegativeLookup/Color/65536/PerStripeXor 895 ns #include <cstdlib> #include <random> #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "benchmark/benchmark.h" #include "cuckoo_index.h" #include "cuckoo_utils.h" #include "index_structure.h" #include "per_stripe_bloom.h" #include "per_stripe_xor.h" ABSL_FLAG(int, generate_num_values, 100000, "Number of values to generate (number of rows)."); ABSL_FLAG(int, num_unique_values, 1000, "Number of unique values to generate (cardinality)."); ABSL_FLAG(std::string, input_csv_path, "", "Path to the input CSV file."); ABSL_FLAG(std::vector<std::string>, columns_to_test, {}, "Comma-separated list of columns to tests, e.g. " "'company_name,country_code'."); ABSL_FLAG(std::vector<std::string>, num_rows_per_stripe_to_test, {"10000"}, "Number of rows per stripe. Defaults to 10,000."); ABSL_FLAG(std::string, sorting, "NONE", "Sorting to apply to the data. Supported values: 'NONE', " "'BY_CARDINALITY' (sorts lexicographically, starting with columns " "with the lowest cardinality), 'RANDOM'"); // To avoid drawing a random value for each single lookup, we look values up in // batches. To avoid caching effects, we use 1M values as the batch size. constexpr size_t kLookupBatchSize = 1'000'000; constexpr absl::string_view kNoSorting = "NONE"; constexpr absl::string_view kByCardinalitySorting = "BY_CARDINALITY"; constexpr absl::string_view kRandomSorting = "RANDOM"; bool IsValidSorting(absl::string_view sorting) { static const auto* values = new absl::flat_hash_set<absl::string_view>( {kNoSorting, kByCardinalitySorting, kRandomSorting}); return values->contains(sorting); } void BM_PositiveDistinctLookup(const ci::Column& column, std::shared_ptr<ci::IndexStructure> index, const int num_stripes, benchmark::State& state) { std::mt19937 gen(42); std::vector<int> distinct_values = column.distinct_values(); // Remove NULLs from the lookup. distinct_values.erase( std::remove(distinct_values.begin(), distinct_values.end(), ci::Column::kIntNullSentinel), distinct_values.end()); std::uniform_int_distribution<std::size_t> distinct_values_offset_d( 0, distinct_values.size() - 1); std::vector<int> values; values.reserve(kLookupBatchSize); for (size_t i = 0; i < kLookupBatchSize; ++i) { values.push_back(distinct_values[distinct_values_offset_d(gen)]); } while (state.KeepRunningBatch(values.size())) { for (size_t i = 0; i < values.size(); ++i) { ::benchmark::DoNotOptimize(index->GetQualifyingStripes(values[i], num_stripes)); } } } void BM_NegativeLookup(const ci::Column& column, std::shared_ptr<ci::IndexStructure> index, const int num_stripes, benchmark::State& state) { std::mt19937 gen(42); std::uniform_int_distribution<int> value_d(std::numeric_limits<int>::min(), std::numeric_limits<int>::max()); std::vector<int> values; values.reserve(kLookupBatchSize); for (size_t i = 0; i < kLookupBatchSize; ++i) { // Draw random value that is not present in the column. int value = value_d(gen); while (column.Contains(value)) { value = value_d(gen); } values.push_back(value); } while (state.KeepRunningBatch(values.size())) { for (size_t i = 0; i < values.size(); ++i) { ::benchmark::DoNotOptimize(index->GetQualifyingStripes(values[i], num_stripes)); } } } int main(int argc, char* argv[]) { absl::ParseCommandLine(argc, argv); const size_t generate_num_values = absl::GetFlag(FLAGS_generate_num_values); const size_t num_unique_values = absl::GetFlag(FLAGS_num_unique_values); const std::string input_csv_path = absl::GetFlag(FLAGS_input_csv_path); const std::vector<std::string> columns_to_test = absl::GetFlag(FLAGS_columns_to_test); // Define data. std::unique_ptr<ci::Table> table; if (input_csv_path.empty() || columns_to_test.empty()) { std::cerr << "[WARNING] --input_csv_path or --columns_to_test not specified, " "generating synthetic data." << std::endl; std::cout << "Generating " << generate_num_values << " values (" << static_cast<double>(num_unique_values) / generate_num_values * 100 << "% unique)..." << std::endl; table = ci::GenerateUniformData(generate_num_values, num_unique_values); } else { std::cout << "Loading data from file " << input_csv_path << "..." << std::endl; table = ci::Table::FromCsv(input_csv_path, columns_to_test); } // Potentially sort the data. const std::string sorting = absl::GetFlag(FLAGS_sorting); if (!IsValidSorting(sorting)) { std::cerr << "Invalid sorting method: " << sorting << std::endl; std::exit(EXIT_FAILURE); } if (sorting == kByCardinalitySorting) { std::cerr << "Sorting the table according to column cardinality..." << std::endl; table->SortWithCardinalityKey(); } else if (sorting == kRandomSorting) { std::cerr << "Randomly shuffling the table..." << std::endl; table->Shuffle(); } std::vector<std::unique_ptr<ci::IndexStructureFactory>> index_factories; index_factories.push_back(absl::make_unique<ci::CuckooIndexFactory>( ci::CuckooAlgorithm::SKEWED_KICKING, ci::kMaxLoadFactor1SlotsPerBucket, /*scan_rate=*/0.01, /*slots_per_bucket=*/1, /*prefix_bits_optimization=*/false)); index_factories.push_back( absl::make_unique<ci::PerStripeBloomFactory>(/*num_bits_per_key=*/10)); index_factories.push_back(absl::make_unique<ci::PerStripeXorFactory>()); // Set up the benchmarks. for (const std::unique_ptr<ci::Column>& column : table->GetColumns()) { for (size_t num_rows_per_stripe : {1ULL << 13, 1ULL << 16}) { for (const std::unique_ptr<ci::IndexStructureFactory>& factory : index_factories) { std::shared_ptr<ci::IndexStructure> index = absl::WrapUnique( factory->Create(*column, num_rows_per_stripe).release()); const int num_stripes = column->num_rows() / num_rows_per_stripe; const std::string positive_distinct_lookup_benchmark_name = absl::StrFormat(/*format=*/"PositiveDistinctLookup/%s/%d/%s", column->name(), num_rows_per_stripe, index->name()); ::benchmark::RegisterBenchmark( positive_distinct_lookup_benchmark_name.c_str(), [&column, index, num_stripes](::benchmark::State& st) -> void { BM_PositiveDistinctLookup(*column, index, num_stripes, st); }); const std::string negative_lookup_benchmark_name = absl::StrFormat(/*format=*/"NegativeLookup/%s/%d/%s", column->name(), num_rows_per_stripe, index->name()); ::benchmark::RegisterBenchmark( negative_lookup_benchmark_name.c_str(), [&column, index, num_stripes](::benchmark::State& st) -> void { BM_NegativeLookup(*column, index, num_stripes, st); }); } } } ::benchmark::Initialize(&argc, argv); ::benchmark::RunSpecifiedBenchmarks(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (C) 2015, 2016 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "msgpack.h" #include <sstream> #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" MsgPack::MsgPack() : handler(std::make_shared<object_handle>()), parent_body(nullptr), body(std::make_shared<MsgPackBody>(0, &handler->obj, MapPack(), 0)) { } MsgPack::MsgPack(const std::shared_ptr<object_handle>& handler_, const std::shared_ptr<MsgPackBody>& body_, const std::shared_ptr<MsgPackBody>& p_body_) : handler(handler_), parent_body(p_body_), body(body_) { init(); } MsgPack::MsgPack(const std::shared_ptr<MsgPackBody>& body_, std::unique_ptr<msgpack::zone>&& z) : handler(std::make_shared<object_handle>(*body_->obj, std::move(z))), parent_body(nullptr), body(std::make_shared<MsgPackBody>(0, &handler->obj, body_->map, body_->m_alloc)) { init(); } MsgPack::MsgPack(MsgPack&& other) noexcept : handler(std::move(other.handler)), parent_body(std::move(other.parent_body)), body(std::move(other.body)) { } MsgPack::MsgPack(const MsgPack& other) : handler(other.handler), parent_body(other.parent_body), body(other.body) { } void MsgPack::init() { if (body->m_alloc == -1 && body->obj->type == msgpack::type::MAP) { body->map.reserve(body->obj->via.map.size); body->m_alloc = body->obj->via.map.size; uint32_t pos = 0; const msgpack::object_kv* pend(body->obj->via.map.ptr + body->obj->via.map.size); for (auto p = body->obj->via.map.ptr; p != pend; ++p, ++pos) { if (p->key.type == msgpack::type::STR) { body->map.insert(std::make_pair(std::string(p->key.via.str.ptr, p->key.via.str.size), std::make_shared<MsgPackBody>(pos, &p->val))); } } } else { body->m_alloc = body->obj->type == msgpack::type::ARRAY ? body->obj->via.array.size : 0; } } MsgPack MsgPack::operator[](const std::string& key) { auto it = body->map.find(key); if (it != body->map.end()) { return MsgPack(handler, it->second, body); } if (body->obj->type == msgpack::type::NIL) { body->obj->type = msgpack::type::MAP; body->obj->via.map.ptr = nullptr; body->obj->via.map.size = 0; } if (body->obj->type == msgpack::type::MAP) { auto _size = body->obj->via.map.size; expand_map(_size); msgpack::object key_obj; msgpack::object val_obj; msgpack::detail::unpack_str(handler->user, key.data(), static_cast<uint32_t>(key.size()), key_obj); msgpack::detail::unpack_nil(val_obj); msgpack::detail::unpack_map_item(*body->obj, key_obj, val_obj); auto ins_it = body->map.insert(std::make_pair(key, std::make_shared<MsgPackBody>(_size, &body->obj->via.map.ptr[_size].val))); return MsgPack(handler, ins_it.first->second, body); } throw msgpack::type_error(); } MsgPack MsgPack::operator[](uint32_t off) { if (body->obj->type == msgpack::type::NIL) { body->obj->type = msgpack::type::ARRAY; body->obj->via.array.ptr = nullptr; body->obj->via.array.size = 0; } if (body->obj->type == msgpack::type::ARRAY) { auto r_size = off + 1; if (body->obj->via.array.size < r_size) { expand_array(r_size); // Initialize new elements. msgpack::object nil_obj; msgpack::detail::unpack_nil(nil_obj); const msgpack::object* p(body->obj->via.array.ptr + body->obj->via.array.size); const msgpack::object* pend(body->obj->via.array.ptr + r_size); for ( ; p != pend; ++p) { msgpack::detail::unpack_array_item(*body->obj, nil_obj); } } return MsgPack(handler, std::make_shared<MsgPackBody>(off, &body->obj->via.array.ptr[off]), body); } throw msgpack::type_error(); } MsgPack MsgPack::at(const std::string& key) const { if (body->obj->type == msgpack::type::MAP) { return MsgPack(handler, body->map.at(key), body); } else if (body->obj->type == msgpack::type::NIL) { throw std::out_of_range(key); } throw msgpack::type_error(); } MsgPack MsgPack::at(uint32_t off) const { if (body->obj->type == msgpack::type::ARRAY) { if (off < body->obj->via.array.size) { return MsgPack(handler, std::make_shared<MsgPackBody>(off, &body->obj->via.array.ptr[off]), body); } throw std::out_of_range(std::to_string(off)); } else if (body->obj->type == msgpack::type::NIL) { throw std::out_of_range(std::to_string(off)); } throw msgpack::type_error(); } bool MsgPack::erase(const std::string& key) { if (body->obj->type == msgpack::type::MAP) { auto it = body->map.find(key); if (it != body->map.end()) { auto p = body->obj->via.map.ptr + it->second->pos; memmove(p, p + 1, (body->obj->via.map.size - it->second->pos - 1) * sizeof(msgpack::object_kv)); --body->obj->via.map.size; body->erase(it); return true; } else { return false; } } throw msgpack::type_error(); } bool MsgPack::erase(uint32_t off) { if (body->obj->type == msgpack::type::ARRAY) { auto r_size = off + 1; if (body->obj->via.array.size >= r_size) { auto p = body->obj->via.array.ptr + off; memmove(p, p + 1, (body->obj->via.array.size - off - 1) * sizeof(msgpack::object)); --body->obj->via.array.size; return true; } else { return false; } } throw msgpack::type_error(); } std::string MsgPack::to_json_string(bool prettify) const { if (prettify) { rapidjson::Document doc = to_json(); rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); return std::string(buffer.GetString(), buffer.GetSize()); } else { std::ostringstream oss; oss << *body->obj; return oss.str(); } } rapidjson::Document MsgPack::to_json() const { rapidjson::Document doc; body->obj->convert(&doc); return doc; } std::string MsgPack::to_string() const { msgpack::sbuffer sbuf; msgpack::pack(&sbuf, *body->obj); return std::string(sbuf.data(), sbuf.size()); } void MsgPack::expand_map(size_t r_size) { if (body->m_alloc == static_cast<ssize_t>(r_size)) { size_t nsize = body->m_alloc > 0 ? body->m_alloc * 2 : MSGPACK_MAP_INIT_SIZE; while (nsize < r_size) { nsize *= 2; } const msgpack::object_kv* p(body->obj->via.map.ptr); const msgpack::object_kv* pend(body->obj->via.map.ptr + body->obj->via.map.size); // Create a new map msgpack::detail::unpack_map()(handler->user, static_cast<uint32_t>(nsize), *body->obj); body->map.reserve(nsize); // Copy all previous items to the new map for (int pos = 0; p != pend; ++p, ++pos) { msgpack::detail::unpack_map_item(*body->obj, p->key, p->val); body->map.at(std::string(p->key.via.str.ptr, p->key.via.str.size))->obj = &body->obj->via.map.ptr[pos].val; } body->m_alloc = nsize; } } void MsgPack::expand_array(size_t r_size) { if (body->m_alloc < static_cast<ssize_t>(r_size)) { size_t nsize = body->m_alloc > 0 ? body->m_alloc * 2 : MSGPACK_ARRAY_INIT_SIZE; while (nsize < r_size) { nsize *= 2; } const msgpack::object* p(body->obj->via.array.ptr); const msgpack::object* pend(body->obj->via.array.ptr + body->obj->via.array.size); // Create a new array msgpack::detail::unpack_array()(handler->user, static_cast<uint32_t>(nsize), *body->obj); // Copy all previous items to the new array for ( ; p != pend; ++p) { msgpack::detail::unpack_array_item(*body->obj, *p); } body->m_alloc = nsize; } } void MsgPack::reset(MsgPack&& other) noexcept { handler = std::move(other.handler); parent_body = std::move(other.parent_body); body = std::move(other.body); } void MsgPack::reset(const MsgPack& other) { handler = other.handler; parent_body = other.parent_body; body = other.body; } MsgPack MsgPack::path(const std::vector<std::string>& path) const { MsgPack current(*this); for (const auto& s : path) { switch (current.body->obj->type) { case msgpack::type::MAP: try { current.reset(current.at(s)); } catch (const std::out_of_range&) { throw std::out_of_range("The map must contain an object at key:" + s); } break; case msgpack::type::ARRAY: { std::string::size_type sz; int pos = std::stoi(s, &sz); if (pos < 0 || sz != s.size()) { throw std::invalid_argument("The index for the array must be a positive integer, it is: " + s); } try { current.reset(current.at(pos)); } catch (const std::out_of_range&) { throw std::out_of_range(("The array must contain an object at index: " + s).c_str()); } break; } default: throw std::invalid_argument(("The container must be a map or an array to access: " + s).c_str()); } } return current; } namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { namespace adaptor { const msgpack::object& convert<MsgPack>::operator()(const msgpack::object& o, MsgPack& v) const { v = MsgPack(v.body, std::make_unique<msgpack::zone>()); return o; } template <typename Stream> msgpack::packer<Stream>& pack<MsgPack>::operator()(msgpack::packer<Stream>& o, const MsgPack& v) const { o << v; return o; } void object<MsgPack>::operator()(msgpack::object& o, const MsgPack& v) const { msgpack::object obj(*v.body->obj); o.type = obj.type; o.via = obj.via; } void object_with_zone<MsgPack>::operator()(msgpack::object::with_zone& o, const MsgPack& v) const { msgpack::object obj(*v.body->obj, o.zone); o.type = obj.type; o.via = obj.via; } } // namespace adaptor } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // namespace msgpack <commit_msg>Fixing Bug in MsgPack::expand_map<commit_after>/* * Copyright (C) 2015, 2016 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "msgpack.h" #include <sstream> #include "rapidjson/stringbuffer.h" #include "rapidjson/prettywriter.h" MsgPack::MsgPack() : handler(std::make_shared<object_handle>()), parent_body(nullptr), body(std::make_shared<MsgPackBody>(0, &handler->obj, MapPack(), 0)) { } MsgPack::MsgPack(const std::shared_ptr<object_handle>& handler_, const std::shared_ptr<MsgPackBody>& body_, const std::shared_ptr<MsgPackBody>& p_body_) : handler(handler_), parent_body(p_body_), body(body_) { init(); } MsgPack::MsgPack(const std::shared_ptr<MsgPackBody>& body_, std::unique_ptr<msgpack::zone>&& z) : handler(std::make_shared<object_handle>(*body_->obj, std::move(z))), parent_body(nullptr), body(std::make_shared<MsgPackBody>(0, &handler->obj, body_->map, body_->m_alloc)) { init(); } MsgPack::MsgPack(MsgPack&& other) noexcept : handler(std::move(other.handler)), parent_body(std::move(other.parent_body)), body(std::move(other.body)) { } MsgPack::MsgPack(const MsgPack& other) : handler(other.handler), parent_body(other.parent_body), body(other.body) { } void MsgPack::init() { if (body->m_alloc == -1 && body->obj->type == msgpack::type::MAP) { body->map.reserve(body->obj->via.map.size); body->m_alloc = body->obj->via.map.size; uint32_t pos = 0; const msgpack::object_kv* pend(body->obj->via.map.ptr + body->obj->via.map.size); for (auto p = body->obj->via.map.ptr; p != pend; ++p, ++pos) { if (p->key.type == msgpack::type::STR) { body->map.insert(std::make_pair(std::string(p->key.via.str.ptr, p->key.via.str.size), std::make_shared<MsgPackBody>(pos, &p->val))); } } } else { body->m_alloc = body->obj->type == msgpack::type::ARRAY ? body->obj->via.array.size : 0; } } MsgPack MsgPack::operator[](const std::string& key) { auto it = body->map.find(key); if (it != body->map.end()) { return MsgPack(handler, it->second, body); } if (body->obj->type == msgpack::type::NIL) { body->obj->type = msgpack::type::MAP; body->obj->via.map.ptr = nullptr; body->obj->via.map.size = 0; } if (body->obj->type == msgpack::type::MAP) { auto _size = body->obj->via.map.size; expand_map(_size); msgpack::object key_obj; msgpack::object val_obj; msgpack::detail::unpack_str(handler->user, key.data(), static_cast<uint32_t>(key.size()), key_obj); msgpack::detail::unpack_nil(val_obj); msgpack::detail::unpack_map_item(*body->obj, key_obj, val_obj); auto ins_it = body->map.insert(std::make_pair(key, std::make_shared<MsgPackBody>(_size, &body->obj->via.map.ptr[_size].val))); return MsgPack(handler, ins_it.first->second, body); } throw msgpack::type_error(); } MsgPack MsgPack::operator[](uint32_t off) { if (body->obj->type == msgpack::type::NIL) { body->obj->type = msgpack::type::ARRAY; body->obj->via.array.ptr = nullptr; body->obj->via.array.size = 0; } if (body->obj->type == msgpack::type::ARRAY) { auto r_size = off + 1; if (body->obj->via.array.size < r_size) { expand_array(r_size); // Initialize new elements. msgpack::object nil_obj; msgpack::detail::unpack_nil(nil_obj); const msgpack::object* p(body->obj->via.array.ptr + body->obj->via.array.size); const msgpack::object* pend(body->obj->via.array.ptr + r_size); for ( ; p != pend; ++p) { msgpack::detail::unpack_array_item(*body->obj, nil_obj); } } return MsgPack(handler, std::make_shared<MsgPackBody>(off, &body->obj->via.array.ptr[off]), body); } throw msgpack::type_error(); } MsgPack MsgPack::at(const std::string& key) const { if (body->obj->type == msgpack::type::MAP) { return MsgPack(handler, body->map.at(key), body); } else if (body->obj->type == msgpack::type::NIL) { throw std::out_of_range(key); } throw msgpack::type_error(); } MsgPack MsgPack::at(uint32_t off) const { if (body->obj->type == msgpack::type::ARRAY) { if (off < body->obj->via.array.size) { return MsgPack(handler, std::make_shared<MsgPackBody>(off, &body->obj->via.array.ptr[off]), body); } throw std::out_of_range(std::to_string(off)); } else if (body->obj->type == msgpack::type::NIL) { throw std::out_of_range(std::to_string(off)); } throw msgpack::type_error(); } bool MsgPack::erase(const std::string& key) { if (body->obj->type == msgpack::type::MAP) { auto it = body->map.find(key); if (it != body->map.end()) { auto p = body->obj->via.map.ptr + it->second->pos; memmove(p, p + 1, (body->obj->via.map.size - it->second->pos - 1) * sizeof(msgpack::object_kv)); --body->obj->via.map.size; body->erase(it); return true; } else { return false; } } throw msgpack::type_error(); } bool MsgPack::erase(uint32_t off) { if (body->obj->type == msgpack::type::ARRAY) { auto r_size = off + 1; if (body->obj->via.array.size >= r_size) { auto p = body->obj->via.array.ptr + off; memmove(p, p + 1, (body->obj->via.array.size - off - 1) * sizeof(msgpack::object)); --body->obj->via.array.size; return true; } else { return false; } } throw msgpack::type_error(); } std::string MsgPack::to_json_string(bool prettify) const { if (prettify) { rapidjson::Document doc = to_json(); rapidjson::StringBuffer buffer; rapidjson::PrettyWriter<rapidjson::StringBuffer> writer(buffer); doc.Accept(writer); return std::string(buffer.GetString(), buffer.GetSize()); } else { std::ostringstream oss; oss << *body->obj; return oss.str(); } } rapidjson::Document MsgPack::to_json() const { rapidjson::Document doc; body->obj->convert(&doc); return doc; } std::string MsgPack::to_string() const { msgpack::sbuffer sbuf; msgpack::pack(&sbuf, *body->obj); return std::string(sbuf.data(), sbuf.size()); } void MsgPack::expand_map(size_t r_size) { if (body->m_alloc <= static_cast<ssize_t>(r_size)) { size_t nsize = body->m_alloc > 0 ? body->m_alloc * 2 : MSGPACK_MAP_INIT_SIZE; while (nsize < r_size) { nsize *= 2; } const msgpack::object_kv* p(body->obj->via.map.ptr); const msgpack::object_kv* pend(body->obj->via.map.ptr + body->obj->via.map.size); // Create a new map msgpack::detail::unpack_map()(handler->user, static_cast<uint32_t>(nsize), *body->obj); body->map.reserve(nsize); // Copy all previous items to the new map for (int pos = 0; p != pend; ++p, ++pos) { msgpack::detail::unpack_map_item(*body->obj, p->key, p->val); body->map.at(std::string(p->key.via.str.ptr, p->key.via.str.size))->obj = &body->obj->via.map.ptr[pos].val; } body->m_alloc = nsize; } } void MsgPack::expand_array(size_t r_size) { if (body->m_alloc < static_cast<ssize_t>(r_size)) { size_t nsize = body->m_alloc > 0 ? body->m_alloc * 2 : MSGPACK_ARRAY_INIT_SIZE; while (nsize < r_size) { nsize *= 2; } const msgpack::object* p(body->obj->via.array.ptr); const msgpack::object* pend(body->obj->via.array.ptr + body->obj->via.array.size); // Create a new array msgpack::detail::unpack_array()(handler->user, static_cast<uint32_t>(nsize), *body->obj); // Copy all previous items to the new array for ( ; p != pend; ++p) { msgpack::detail::unpack_array_item(*body->obj, *p); } body->m_alloc = nsize; } } void MsgPack::reset(MsgPack&& other) noexcept { handler = std::move(other.handler); parent_body = std::move(other.parent_body); body = std::move(other.body); } void MsgPack::reset(const MsgPack& other) { handler = other.handler; parent_body = other.parent_body; body = other.body; } MsgPack MsgPack::path(const std::vector<std::string>& path) const { MsgPack current(*this); for (const auto& s : path) { switch (current.body->obj->type) { case msgpack::type::MAP: try { current.reset(current.at(s)); } catch (const std::out_of_range&) { throw std::out_of_range("The map must contain an object at key:" + s); } break; case msgpack::type::ARRAY: { std::string::size_type sz; int pos = std::stoi(s, &sz); if (pos < 0 || sz != s.size()) { throw std::invalid_argument("The index for the array must be a positive integer, it is: " + s); } try { current.reset(current.at(pos)); } catch (const std::out_of_range&) { throw std::out_of_range(("The array must contain an object at index: " + s).c_str()); } break; } default: throw std::invalid_argument(("The container must be a map or an array to access: " + s).c_str()); } } return current; } namespace msgpack { MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) { namespace adaptor { const msgpack::object& convert<MsgPack>::operator()(const msgpack::object& o, MsgPack& v) const { v = MsgPack(v.body, std::make_unique<msgpack::zone>()); return o; } template <typename Stream> msgpack::packer<Stream>& pack<MsgPack>::operator()(msgpack::packer<Stream>& o, const MsgPack& v) const { o << v; return o; } void object<MsgPack>::operator()(msgpack::object& o, const MsgPack& v) const { msgpack::object obj(*v.body->obj); o.type = obj.type; o.via = obj.via; } void object_with_zone<MsgPack>::operator()(msgpack::object::with_zone& o, const MsgPack& v) const { msgpack::object obj(*v.body->obj, o.zone); o.type = obj.type; o.via = obj.via; } } // namespace adaptor } // MSGPACK_API_VERSION_NAMESPACE(MSGPACK_DEFAULT_API_NS) } // namespace msgpack <|endoftext|>
<commit_before>#include "offset.h" bool siren_offset_install(mrb_state* mrb, struct RClass* rclass) { rclass = mrb_define_module(mrb, "Offset"); mrb_define_class_method(mrb, rclass, "sweep_vec", siren_offset_sweep_vec, ARGS_REQ(2)); mrb_define_class_method(mrb, rclass, "sweep_path", siren_offset_sweep_path, ARGS_REQ(2) | ARGS_OPT(4)); mrb_define_class_method(mrb, rclass, "loft", siren_offset_loft, ARGS_REQ(1) | ARGS_OPT(3)); mrb_define_class_method(mrb, rclass, "offset", siren_offset_offset, ARGS_REQ(2) | ARGS_OPT(1)); return true; } mrb_value siren_offset_sweep_vec(mrb_state* mrb, mrb_value self) { mrb_value target, vec; int argc = mrb_get_args(mrb, "oo", &target, &vec); TopoDS_Shape* profile = siren_shape_get(mrb, target); gp_Pnt _pt = gp_Pnt(0., 0., 0.).Transformed(profile->Location()); TopoDS_Edge pe = BRepBuilderAPI_MakeEdge(_pt, siren_pnt_get(mrb, vec)); TopoDS_Wire path = BRepBuilderAPI_MakeWire(pe); BRepOffsetAPI_MakePipe mp(path, *profile); mp.Build(); return siren_shape_new(mrb, mp.Shape()); } mrb_value siren_offset_sweep_path(mrb_state* mrb, mrb_value self) { mrb_value target, pathwire; mrb_bool cont, corr; mrb_float scale_first, scale_last; int argc = mrb_get_args(mrb, "oo|bbff", &target, &pathwire, &cont, &corr, &scale_first, &scale_last); TopoDS_Shape* shape_profile = siren_shape_get(mrb, target); TopoDS_Shape* shape_path = siren_shape_get(mrb, pathwire); TopoDS_Wire path; if (shape_path->ShapeType() == TopAbs_EDGE) { path = BRepBuilderAPI_MakeWire(TopoDS::Edge(*shape_path)); } else if (shape_path->ShapeType() == TopAbs_WIRE) { path = TopoDS::Wire(*shape_path); } else { static const char m[] = "Path object is not Edge or Wire."; return mrb_exc_new(mrb, E_ARGUMENT_ERROR, m, sizeof(m) - 1); } mrb_value result = mrb_nil_value(); if (argc >= 3 && argc <= 6) { Standard_Boolean withContact = (Standard_Boolean)cont; Standard_Boolean withCorrection = (Standard_Boolean)corr; BRepOffsetAPI_MakePipeShell ps(path); // get params Standard_Real fparam, lparam; { BRepAdaptor_CompCurve cc(path); fparam = cc.FirstParameter(); lparam = cc.LastParameter(); } if (argc < 6) { scale_last = 1.0; if (argc < 5) { scale_first = 1.0; } } //Handle(Law_Linear) law = new Law_Linear(); //law->Set(fparam, scale_first, lparam, scale_last); Handle(Law_S) law = new Law_S(); law->Set(fparam, scale_first, lparam, scale_last); //Handle(Law_Composite) law = new Law_Composite(fparam, lparam, 1.0e-6); // get start point TopoDS_Vertex pfirst; { TopoDS_Vertex plast; TopExp::Vertices(path, pfirst, plast); } ps.SetLaw( *shape_profile, // セクションプロファイル law, // 掃引規則 pfirst, // 開始点 withContact, // translate profile to start point withCorrection // Change normal of profile by curveture ); ps.Build(); result = siren_shape_new(mrb, ps.Shape()); } else { BRepOffsetAPI_MakePipe mp(path, *shape_profile); mp.Build(); result = siren_shape_new(mrb, mp.Shape()); } return result; } mrb_value siren_offset_loft(mrb_state* mrb, mrb_value self) { mrb_value objs; mrb_bool smooth, is_solid, is_ruled; int argc = mrb_get_args(mrb, "A|bbb", &objs, &smooth, &is_solid, &is_ruled); int lsize = mrb_ary_len(mrb, objs); if (lsize < 2) { static const char m[] = "Number of objects must be over 2 lines."; return mrb_exc_new(mrb, E_ARGUMENT_ERROR, m, sizeof(m) - 1); } Standard_Boolean is_sm, is_s, is_r; is_sm = argc < 2 ? Standard_True : (Standard_Boolean)smooth; is_s = argc < 3 ? Standard_False : (Standard_Boolean)is_solid; is_r = argc < 4 ? Standard_True : (Standard_Boolean)is_ruled; BRepOffsetAPI_ThruSections ts(is_s, is_r); for (int i=0; i<lsize; i++) { mrb_value line = mrb_ary_ref(mrb, objs, i); TopoDS_Shape* shape = siren_shape_get(mrb, line); TopoDS_Wire w = TopoDS::Wire(*shape); ts.AddWire(w); } ts.SetSmoothing(is_sm); ts.Build(); return siren_shape_new(mrb, ts.Shape()); } mrb_value siren_offset_offset(mrb_state* mrb, mrb_value self) { mrb_value target; mrb_float offset, tol; int argc = mrb_get_args(mrb, "of|f", &target, &offset, &tol); Standard_Real t = 1.0; if (argc == 3) t = (Standard_Real)tol; TopoDS_Shape* shape = siren_shape_get(mrb, target); TopoDS_Compound comp; BRep_Builder B; B.MakeCompound(comp); TopExp_Explorer exp(*shape, TopAbs_FACE); for (; exp.More(); exp.Next()) { TopoDS_Face face = TopoDS::Face(exp.Current()); Handle(Geom_Surface) gs = BRep_Tool::Surface(face); Handle(Geom_OffsetSurface) gos = new Geom_OffsetSurface(gs, (Standard_Real)offset); TopoDS_Face newface = BRepBuilderAPI_MakeFace(gos, t); B.Add(comp, newface); } return siren_shape_new(mrb, comp); } <commit_msg>Fix bug at sweepv method in Offset module.<commit_after>#include "offset.h" bool siren_offset_install(mrb_state* mrb, struct RClass* rclass) { rclass = mrb_define_module(mrb, "Offset"); mrb_define_class_method(mrb, rclass, "sweep_vec", siren_offset_sweep_vec, ARGS_REQ(2)); mrb_define_class_method(mrb, rclass, "sweep_path", siren_offset_sweep_path, ARGS_REQ(2) | ARGS_OPT(4)); mrb_define_class_method(mrb, rclass, "loft", siren_offset_loft, ARGS_REQ(1) | ARGS_OPT(3)); mrb_define_class_method(mrb, rclass, "offset", siren_offset_offset, ARGS_REQ(2) | ARGS_OPT(1)); return true; } mrb_value siren_offset_sweep_vec(mrb_state* mrb, mrb_value self) { mrb_value target, vec; int argc = mrb_get_args(mrb, "oo", &target, &vec); TopoDS_Shape* profile = siren_shape_get(mrb, target); gp_Pnt sp = gp_Pnt(0., 0., 0.).Transformed(profile->Location()); gp_Pnt tp = siren_pnt_get(mrb, vec).Transformed(profile->Location()); TopoDS_Edge pe = BRepBuilderAPI_MakeEdge(sp, tp); TopoDS_Wire path = BRepBuilderAPI_MakeWire(pe); BRepOffsetAPI_MakePipe mp(path, *profile); mp.Build(); return siren_shape_new(mrb, mp.Shape()); } mrb_value siren_offset_sweep_path(mrb_state* mrb, mrb_value self) { mrb_value target, pathwire; mrb_bool cont, corr; mrb_float scale_first, scale_last; int argc = mrb_get_args(mrb, "oo|bbff", &target, &pathwire, &cont, &corr, &scale_first, &scale_last); TopoDS_Shape* shape_profile = siren_shape_get(mrb, target); TopoDS_Shape* shape_path = siren_shape_get(mrb, pathwire); TopoDS_Wire path; if (shape_path->ShapeType() == TopAbs_EDGE) { path = BRepBuilderAPI_MakeWire(TopoDS::Edge(*shape_path)); } else if (shape_path->ShapeType() == TopAbs_WIRE) { path = TopoDS::Wire(*shape_path); } else { static const char m[] = "Path object is not Edge or Wire."; return mrb_exc_new(mrb, E_ARGUMENT_ERROR, m, sizeof(m) - 1); } mrb_value result = mrb_nil_value(); if (argc >= 3 && argc <= 6) { Standard_Boolean withContact = (Standard_Boolean)cont; Standard_Boolean withCorrection = (Standard_Boolean)corr; BRepOffsetAPI_MakePipeShell ps(path); // get params Standard_Real fparam, lparam; { BRepAdaptor_CompCurve cc(path); fparam = cc.FirstParameter(); lparam = cc.LastParameter(); } if (argc < 6) { scale_last = 1.0; if (argc < 5) { scale_first = 1.0; } } //Handle(Law_Linear) law = new Law_Linear(); //law->Set(fparam, scale_first, lparam, scale_last); Handle(Law_S) law = new Law_S(); law->Set(fparam, scale_first, lparam, scale_last); //Handle(Law_Composite) law = new Law_Composite(fparam, lparam, 1.0e-6); // get start point TopoDS_Vertex pfirst; { TopoDS_Vertex plast; TopExp::Vertices(path, pfirst, plast); } ps.SetLaw( *shape_profile, // セクションプロファイル law, // 掃引規則 pfirst, // 開始点 withContact, // translate profile to start point withCorrection // Change normal of profile by curveture ); ps.Build(); result = siren_shape_new(mrb, ps.Shape()); } else { BRepOffsetAPI_MakePipe mp(path, *shape_profile); mp.Build(); result = siren_shape_new(mrb, mp.Shape()); } return result; } mrb_value siren_offset_loft(mrb_state* mrb, mrb_value self) { mrb_value objs; mrb_bool smooth, is_solid, is_ruled; int argc = mrb_get_args(mrb, "A|bbb", &objs, &smooth, &is_solid, &is_ruled); int lsize = mrb_ary_len(mrb, objs); if (lsize < 2) { static const char m[] = "Number of objects must be over 2 lines."; return mrb_exc_new(mrb, E_ARGUMENT_ERROR, m, sizeof(m) - 1); } Standard_Boolean is_sm, is_s, is_r; is_sm = argc < 2 ? Standard_True : (Standard_Boolean)smooth; is_s = argc < 3 ? Standard_False : (Standard_Boolean)is_solid; is_r = argc < 4 ? Standard_True : (Standard_Boolean)is_ruled; BRepOffsetAPI_ThruSections ts(is_s, is_r); for (int i=0; i<lsize; i++) { mrb_value line = mrb_ary_ref(mrb, objs, i); TopoDS_Shape* shape = siren_shape_get(mrb, line); TopoDS_Wire w = TopoDS::Wire(*shape); ts.AddWire(w); } ts.SetSmoothing(is_sm); ts.Build(); return siren_shape_new(mrb, ts.Shape()); } mrb_value siren_offset_offset(mrb_state* mrb, mrb_value self) { mrb_value target; mrb_float offset, tol; int argc = mrb_get_args(mrb, "of|f", &target, &offset, &tol); Standard_Real t = 1.0; if (argc == 3) t = (Standard_Real)tol; TopoDS_Shape* shape = siren_shape_get(mrb, target); TopoDS_Compound comp; BRep_Builder B; B.MakeCompound(comp); TopExp_Explorer exp(*shape, TopAbs_FACE); for (; exp.More(); exp.Next()) { TopoDS_Face face = TopoDS::Face(exp.Current()); Handle(Geom_Surface) gs = BRep_Tool::Surface(face); Handle(Geom_OffsetSurface) gos = new Geom_OffsetSurface(gs, (Standard_Real)offset); TopoDS_Face newface = BRepBuilderAPI_MakeFace(gos, t); B.Add(comp, newface); } return siren_shape_new(mrb, comp); } <|endoftext|>
<commit_before>#include "z2h/token.hpp" #include "z2h/parser.hpp" #include "ast.h" #include "parser.h" #include "bindpower.h" #include "exceptions.h" #include <map> #include <vector> #include <boost/regex.hpp> #include <iostream> namespace sota { // scanners long SotaParser::SkippingScanner(SotaSymbol *symbol, const std::string &source, size_t index) { return RegexScanner(symbol, source, index) * -1; //returns a neg number if matched } long SotaParser::RegexScanner(SotaSymbol *symbol, const std::string &source, size_t index) { auto pattern = symbol->pattern; boost::smatch matches; boost::regex re("^" + pattern); if (boost::regex_search(source, matches, re)) { auto match = matches[0]; return match.length(); } return 0; } long SotaParser::LiteralScanner(SotaSymbol *symbol, const std::string &source, size_t index) { auto pattern = symbol->pattern; auto patternSize = pattern.size(); if (source.size() >= patternSize && source.compare(0, patternSize, pattern) == 0) { return patternSize; } return 0; } long SotaParser::EosScanner(SotaSymbol *symbol, const std::string &source, size_t index) { if (!nesting.size()) { return RegexScanner(symbol, source, index); } return 0; } long SotaParser::EoeScanner(SotaSymbol *symbol, const std::string &source, size_t index) { if (nesting.size()) { } return 0; } long SotaParser::DentingScanner(SotaSymbol *symbol, const std::string &source, size_t index) { return 0; } // std parsing functions Ast * SotaParser::NotImplementedStd() { throw SotaNotImplemented(__FILE__, __LINE__, "std: NotImplemented; this shouldn't be called!"); } // nud parsing functions Ast * SotaParser::NotImplementedNud(SotaToken *token) { std::cout << "ni nud; token=" << *token << std::endl; throw SotaNotImplemented(__FILE__, __LINE__, "nud: NotImplemented; this shouldn't be called!"); } Ast * SotaParser::EndOfFileNud(SotaToken *token) { return nullptr; } Ast * SotaParser::NewlineNud(SotaToken *token) { std::cout << "newline" << std::endl; return new NewlineAst(token->Value()); } Ast * SotaParser::NumberNud(SotaToken *token) { return new NumberAst(token->Value()); } Ast * SotaParser::IdentifierNud(SotaToken *token) { return new IdentifierAst(token->Value()); } Ast * SotaParser::PrefixNud(SotaToken *token) { Ast *right = Expression(BindPower::Unary); return new PrefixAst(token, right); } Ast * SotaParser::IfThenElifElseNud(SotaToken *token) { return nullptr; } // led parsing functions Ast * SotaParser::NotImplementedLed(Ast *left, SotaToken *token) { std::cout << "ni led; token=" << *token << " left=" << left->Print() << std::endl; throw SotaNotImplemented(__FILE__, __LINE__, "led: NotImplemented; this shouldn't be called!"); } Ast * SotaParser::EndOfFileLed(Ast *left, SotaToken *token) { return left; } Ast * SotaParser::ComparisonLed(Ast *left, SotaToken *token) { return nullptr; } Ast * SotaParser::InfixLed(Ast *left, SotaToken *token) { Ast *right = Expression(token->symbol->lbp); return new InfixAst(token, left, right); } Ast * SotaParser::PostfixLed(Ast *left, SotaToken *token) { return nullptr; } Ast * SotaParser::AssignLed(Ast *left, SotaToken *token) { return nullptr; } Ast * SotaParser::RegexLed(Ast *left, SotaToken *token) { return nullptr; } Ast * SotaParser::TernaryLed(Ast *left, SotaToken *token) { auto action = Expression(); auto pair = ConditionalAst::Pair(left, action); auto expected = symbolmap[SotaParser::SymbolType::Colon]; Consume(expected, "colon : expected"); auto defaultAction = Expression(); return new ConditionalAst({pair}, defaultAction); } Ast * SotaParser::IfThenElseLed(Ast *left, SotaToken *token) { auto predicate = Expression(); auto pair = ConditionalAst::Pair(predicate, left); auto expected = symbolmap[SotaParser::SymbolType::Else]; Consume(expected, "else expected"); auto defaultAction = Expression(); return new ConditionalAst({pair}, defaultAction); } SotaParser::SotaParser() { //example calls, proving it works auto std1 = BindStd(&SotaParser::Nullptr); auto std2 = BindStd(&SotaParser::NotImplementedStd); auto nud1 = BindNud(&SotaParser::Nullptr); auto nud2 = BindNud(&SotaParser::NumberNud); auto led1 = BindLed(&SotaParser::Nullptr); auto led2 = BindLed(&SotaParser::PostfixLed); auto scan1 = BindScan(&SotaParser::Nullptr); auto scan2 = BindScan(&SotaParser::LiteralScanner); #define T(k,p,b,s,t,n,l) { SymbolType::k, new SotaSymbol(SymbolType::k, b, p, SCAN(s), STD(t), NUD(n), LED(l) ) }, \ symbolmap = { SYMBOLS }; #undef T } std::vector<SotaSymbol *> SotaParser::Symbols() { std::vector<SotaSymbol *> symbols; for (auto kvp : symbolmap) { symbols.push_back(kvp.second); } return symbols; } } <commit_msg>cleaned up example code... -sai<commit_after>#include "z2h/token.hpp" #include "z2h/parser.hpp" #include "ast.h" #include "parser.h" #include "bindpower.h" #include "exceptions.h" #include <map> #include <vector> #include <boost/regex.hpp> #include <iostream> namespace sota { // scanners long SotaParser::SkippingScanner(SotaSymbol *symbol, const std::string &source, size_t index) { return RegexScanner(symbol, source, index) * -1; //returns a neg number if matched } long SotaParser::RegexScanner(SotaSymbol *symbol, const std::string &source, size_t index) { auto pattern = symbol->pattern; boost::smatch matches; boost::regex re("^" + pattern); if (boost::regex_search(source, matches, re)) { auto match = matches[0]; return match.length(); } return 0; } long SotaParser::LiteralScanner(SotaSymbol *symbol, const std::string &source, size_t index) { auto pattern = symbol->pattern; auto patternSize = pattern.size(); if (source.size() >= patternSize && source.compare(0, patternSize, pattern) == 0) { return patternSize; } return 0; } long SotaParser::EosScanner(SotaSymbol *symbol, const std::string &source, size_t index) { if (!nesting.size()) { return RegexScanner(symbol, source, index); } return 0; } long SotaParser::EoeScanner(SotaSymbol *symbol, const std::string &source, size_t index) { if (nesting.size()) { } return 0; } long SotaParser::DentingScanner(SotaSymbol *symbol, const std::string &source, size_t index) { return 0; } // std parsing functions Ast * SotaParser::NotImplementedStd() { throw SotaNotImplemented(__FILE__, __LINE__, "std: NotImplemented; this shouldn't be called!"); } // nud parsing functions Ast * SotaParser::NotImplementedNud(SotaToken *token) { std::cout << "ni nud; token=" << *token << std::endl; throw SotaNotImplemented(__FILE__, __LINE__, "nud: NotImplemented; this shouldn't be called!"); } Ast * SotaParser::EndOfFileNud(SotaToken *token) { return nullptr; } Ast * SotaParser::NewlineNud(SotaToken *token) { std::cout << "newline" << std::endl; return new NewlineAst(token->Value()); } Ast * SotaParser::NumberNud(SotaToken *token) { return new NumberAst(token->Value()); } Ast * SotaParser::IdentifierNud(SotaToken *token) { return new IdentifierAst(token->Value()); } Ast * SotaParser::PrefixNud(SotaToken *token) { Ast *right = Expression(BindPower::Unary); return new PrefixAst(token, right); } Ast * SotaParser::IfThenElifElseNud(SotaToken *token) { return nullptr; } // led parsing functions Ast * SotaParser::NotImplementedLed(Ast *left, SotaToken *token) { std::cout << "ni led; token=" << *token << " left=" << left->Print() << std::endl; throw SotaNotImplemented(__FILE__, __LINE__, "led: NotImplemented; this shouldn't be called!"); } Ast * SotaParser::EndOfFileLed(Ast *left, SotaToken *token) { return left; } Ast * SotaParser::ComparisonLed(Ast *left, SotaToken *token) { return nullptr; } Ast * SotaParser::InfixLed(Ast *left, SotaToken *token) { Ast *right = Expression(token->symbol->lbp); return new InfixAst(token, left, right); } Ast * SotaParser::PostfixLed(Ast *left, SotaToken *token) { return nullptr; } Ast * SotaParser::AssignLed(Ast *left, SotaToken *token) { return nullptr; } Ast * SotaParser::RegexLed(Ast *left, SotaToken *token) { return nullptr; } Ast * SotaParser::TernaryLed(Ast *left, SotaToken *token) { auto action = Expression(); auto pair = ConditionalAst::Pair(left, action); auto expected = symbolmap[SotaParser::SymbolType::Colon]; Consume(expected, "colon : expected"); auto defaultAction = Expression(); return new ConditionalAst({pair}, defaultAction); } Ast * SotaParser::IfThenElseLed(Ast *left, SotaToken *token) { auto predicate = Expression(); auto pair = ConditionalAst::Pair(predicate, left); auto expected = symbolmap[SotaParser::SymbolType::Else]; Consume(expected, "else expected"); auto defaultAction = Expression(); return new ConditionalAst({pair}, defaultAction); } SotaParser::SotaParser() { #define T(k,p,b,s,t,n,l) { SymbolType::k, new SotaSymbol(SymbolType::k, b, p, SCAN(s), STD(t), NUD(n), LED(l) ) }, symbolmap = { SYMBOLS }; #undef T } std::vector<SotaSymbol *> SotaParser::Symbols() { std::vector<SotaSymbol *> symbols; for (auto kvp : symbolmap) { symbols.push_back(kvp.second); } return symbols; } } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "phml.hh" #include <cassert> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <memory> #include "db/statement-driver.hh" #include "phml.pb.h" using std::cerr; using std::endl; namespace flint { namespace phml { namespace { class Driver { public: Driver(const Driver &) = delete; Driver &operator=(const Driver &) = delete; Driver(sqlite3 *db, ::phml::NumericalConfiguration *nc) : nc_(nc) , nc_stmt_(NULL) , td_stmt_(NULL) { int e; e = sqlite3_prepare_v2(db, "SELECT * FROM ncs", -1, &nc_stmt_, NULL); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << e << endl; exit(EXIT_FAILURE); } e = sqlite3_prepare_v2(db, "SELECT unit_id, step FROM tds WHERE module_id IS NULL", -1, &td_stmt_, NULL); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << e << endl; exit(EXIT_FAILURE); } } ~Driver() { sqlite3_finalize(nc_stmt_); sqlite3_finalize(td_stmt_); } bool Drive() { return SetPartOfNumericalConfiguration() && SetTimeDiscretization(); } private: bool SetPartOfNumericalConfiguration() { int e = sqlite3_step(nc_stmt_); if (e == SQLITE_DONE) { // no row return true; } if (e != SQLITE_ROW) { // error cerr << "failed to step prepared statement" << endl; return false; } const unsigned char *rg_name = sqlite3_column_text(nc_stmt_, 0); const unsigned char *rg_seed = sqlite3_column_text(nc_stmt_, 1); const unsigned char *integration = sqlite3_column_text(nc_stmt_, 2); int sts_unit_id = sqlite3_column_int(nc_stmt_, 3); const unsigned char *sts_value = sqlite3_column_text(nc_stmt_, 4); if (rg_name) { ::phml::RandomGenerator *rg = nc_->mutable_rg(); rg->set_name((const char *)rg_name); if (rg_seed) rg->set_seed((const char *)rg_seed); } if (integration) { nc_->set_integration((const char *)integration); } if (sts_unit_id > 0 && sts_value) { ::phml::SimulationTimeSpan *sts = nc_->mutable_sts(); sts->set_unit_id(sts_unit_id); sts->set_value((const char *)sts_value); } return true; } bool SetTimeDiscretization() { int e = sqlite3_step(td_stmt_); if (e == SQLITE_DONE) { // no row return true; } if (e != SQLITE_ROW) { // error cerr << "failed to step prepared statement" << endl; return false; } int unit_id = sqlite3_column_int(td_stmt_, 0); const unsigned char *step = sqlite3_column_text(td_stmt_, 1); if (unit_id > 0 && step) { ::phml::TimeDiscretization *td = nc_->mutable_td(); td->set_unit_id(unit_id); td->set_step((const char *)step); } return true; } private: ::phml::NumericalConfiguration *nc_; sqlite3_stmt *nc_stmt_; sqlite3_stmt *td_stmt_; }; class MethodWriter : db::StatementDriver { public: explicit MethodWriter(sqlite3 *db) : db::StatementDriver(db, "UPDATE config SET method = ?") {} bool Write(const char *method) { int e; e = sqlite3_bind_text(stmt(), 1, method, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind method: " << e << endl; return false; } e = sqlite3_step(stmt()); if (e != SQLITE_DONE) { cerr << "failed to step statement: " << e << endl; return false; } sqlite3_reset(stmt()); return true; } }; } bool Nc(sqlite3 *db, const char *output, int *seed) { std::unique_ptr<::phml::NumericalConfiguration> nc(new ::phml::NumericalConfiguration); { std::unique_ptr<Driver> driver(new Driver(db, nc.get())); if (!driver->Drive()) return false; } { std::ofstream ofs(output, std::ios::binary); if (!ofs) { cerr << "failed to open " << output << endl; return false; } if (!nc->SerializeToOstream(&ofs)) { cerr << "failed to serialize NumericalConfiguration" << endl; return false; } ofs.close(); } if (seed && nc->has_rg() && nc->rg().has_seed()) *seed = std::atoi(nc->rg().seed().c_str()); MethodWriter writer(db); if (nc->has_integration()) { if (!writer.Write(nc->integration().c_str())) return false; } else { // unspecified, so let's assume rk4 if (!writer.Write("rk4")) return false; } return true; } } } <commit_msg>Do not exit from ctor<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- vim:set ts=4 sw=4 sts=4 noet: */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "phml.hh" #include <cassert> #include <cstdlib> #include <cstring> #include <fstream> #include <iostream> #include <memory> #include "db/statement-driver.hh" #include "phml.pb.h" using std::cerr; using std::endl; namespace flint { namespace phml { namespace { class Driver { public: Driver(const Driver &) = delete; Driver &operator=(const Driver &) = delete; explicit Driver(::phml::NumericalConfiguration *nc) : nc_(nc) , nc_stmt_(nullptr) , td_stmt_(nullptr) { } ~Driver() { sqlite3_finalize(nc_stmt_); sqlite3_finalize(td_stmt_); } bool Drive(sqlite3 *db) { int e; e = sqlite3_prepare_v2(db, "SELECT * FROM ncs", -1, &nc_stmt_, NULL); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << e << endl; return false; } e = sqlite3_prepare_v2(db, "SELECT unit_id, step FROM tds WHERE module_id IS NULL", -1, &td_stmt_, NULL); if (e != SQLITE_OK) { cerr << "failed to prepare statement: " << e << endl; return false; } return SetPartOfNumericalConfiguration() && SetTimeDiscretization(); } private: bool SetPartOfNumericalConfiguration() { int e = sqlite3_step(nc_stmt_); if (e == SQLITE_DONE) { // no row return true; } if (e != SQLITE_ROW) { // error cerr << "failed to step prepared statement" << endl; return false; } const unsigned char *rg_name = sqlite3_column_text(nc_stmt_, 0); const unsigned char *rg_seed = sqlite3_column_text(nc_stmt_, 1); const unsigned char *integration = sqlite3_column_text(nc_stmt_, 2); int sts_unit_id = sqlite3_column_int(nc_stmt_, 3); const unsigned char *sts_value = sqlite3_column_text(nc_stmt_, 4); if (rg_name) { ::phml::RandomGenerator *rg = nc_->mutable_rg(); rg->set_name((const char *)rg_name); if (rg_seed) rg->set_seed((const char *)rg_seed); } if (integration) { nc_->set_integration((const char *)integration); } if (sts_unit_id > 0 && sts_value) { ::phml::SimulationTimeSpan *sts = nc_->mutable_sts(); sts->set_unit_id(sts_unit_id); sts->set_value((const char *)sts_value); } return true; } bool SetTimeDiscretization() { int e = sqlite3_step(td_stmt_); if (e == SQLITE_DONE) { // no row return true; } if (e != SQLITE_ROW) { // error cerr << "failed to step prepared statement" << endl; return false; } int unit_id = sqlite3_column_int(td_stmt_, 0); const unsigned char *step = sqlite3_column_text(td_stmt_, 1); if (unit_id > 0 && step) { ::phml::TimeDiscretization *td = nc_->mutable_td(); td->set_unit_id(unit_id); td->set_step((const char *)step); } return true; } private: ::phml::NumericalConfiguration *nc_; sqlite3_stmt *nc_stmt_; sqlite3_stmt *td_stmt_; }; class MethodWriter : db::StatementDriver { public: explicit MethodWriter(sqlite3 *db) : db::StatementDriver(db, "UPDATE config SET method = ?") {} bool Write(const char *method) { int e; e = sqlite3_bind_text(stmt(), 1, method, -1, SQLITE_STATIC); if (e != SQLITE_OK) { cerr << "failed to bind method: " << e << endl; return false; } e = sqlite3_step(stmt()); if (e != SQLITE_DONE) { cerr << "failed to step statement: " << e << endl; return false; } sqlite3_reset(stmt()); return true; } }; } bool Nc(sqlite3 *db, const char *output, int *seed) { std::unique_ptr<::phml::NumericalConfiguration> nc(new ::phml::NumericalConfiguration); { std::unique_ptr<Driver> driver(new Driver(nc.get())); if (!driver->Drive(db)) return false; } { std::ofstream ofs(output, std::ios::binary); if (!ofs) { cerr << "failed to open " << output << endl; return false; } if (!nc->SerializeToOstream(&ofs)) { cerr << "failed to serialize NumericalConfiguration" << endl; return false; } ofs.close(); } if (seed && nc->has_rg() && nc->rg().has_seed()) *seed = std::atoi(nc->rg().seed().c_str()); MethodWriter writer(db); if (nc->has_integration()) { if (!writer.Write(nc->integration().c_str())) return false; } else { // unspecified, so let's assume rk4 if (!writer.Write("rk4")) return false; } return true; } } } <|endoftext|>
<commit_before>/// \file player.cpp /// Holds all code for the MistPlayer application used for VoD streams. #if DEBUG >= 4 #include <iostream>//for std::cerr #endif #include <stdio.h> //for fileno #include <sys/time.h> #include <mist/dtsc.h> #include <mist/json.h> #include <mist/config.h> #include <mist/socket.h> /// Copy of stats from buffer_user.cpp class Stats{ public: unsigned int up; unsigned int down; std::string host; std::string connector; unsigned int conntime; Stats(){ up = 0; down = 0; conntime = 0; }; /// Reads a stats string and parses it to the internal representation. Stats(std::string s){ Buffer::Stats::Stats(std::string s){ size_t f = s.find(' '); if (f != std::string::npos){ host = s.substr(0, f); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ connector = s.substr(0, f); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ conntime = atoi(s.substr(0, f).c_str()); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ up = atoi(s.substr(0, f).c_str()); s.erase(0, f+1); down = atoi(s.c_str()); } }; }; /// Gets the current system time in milliseconds. long long int getNowMS(){ timeval t; gettimeofday(&t, 0); return t.tv_sec * 1000 + t.tv_usec/1000; }//getNowMS int main(int argc, char** argv){ Util::Config conf(argv[0], PACKAGE_VERSION); conf.addOption("filename", JSON::fromString("{\"arg_num\":1, \"help\":\"Name of the file to write to stdout.\"}")); conf.parseArgs(argc, argv); conf.activate(); int playing = 0; DTSC::File source = DTSC::File(conf.getString("filename")); Socket::Connection in_out = Socket::Connection(fileno(stdout), fileno(stdin)); std::string meta_str = source.getHeader(); JSON::Value pausemark; pausemark["datatype"] = "pause_marker"; pausemark["time"] = (long long int)0; Socket::Connection StatsSocket = Socket::Connection("/tmp/mist/statistics", true); //send the header { in_out.Send("DTSC"); unsigned int size = htonl(meta_str.size()); in_out.Send((char*)&size, 4); in_out.Send(meta_str); } JSON::Value meta = JSON::fromDTMI(meta_str); JSON::Value last_pack; long long now, timeDiff = 0, lastTime = 0; Stats sts; while (in_out.connected()){ if (in_out.spool()){ while (in_out.Received().find('\n') != std::string::npos){ std::string cmd = in_out.Received().substr(0, in_out.Received().find('\n')); in_out.Received().erase(0, in_out.Received().find('\n')+1); if (cmd != ""){ switch (cmd[0]){ case 'P':{ //Push #if DEBUG >= 4 std::cerr << "Received push - ignoring (" << cmd << ")" << std::endl; #endif in_out.close();//pushing to VoD makes no sense } break; case 'S':{ //Stats if (!StatsSocket.connected()){ StatsSocket = Socket::Connection("/tmp/mist/statistics", true); } if (StatsSocket.connected()){ sts = Stats(cmd.substr(2)); JSON::Value json_sts; json_sts["vod"]["down"] = (long long int)sts.down; json_sts["vod"]["up"] = (long long int)sts.up; json_sts["vod"]["time"] = (long long int)sts.conntime; json_sts["vod"]["host"] = sts.host; json_sts["vod"]["connector"] = sts.connector; json_sts["vod"]["filename"] = conf.getString("filename"); json_sts["vod"]["now"] = (long long int)time(0); json_sts["vod"]["meta"] = meta; StatsSocket.Send(json_sys.toString()); StatsSocket.Send("\n\n"); StatsSocket.flush(); } } break; case 's':{ //second-seek #if DEBUG >= 4 std::cerr << "Received ms-seek (" << cmd << ")" << std::endl; #endif int ms = JSON::Value(cmd.substr(2)).asInt(); bool ret = source.seek_time(ms); #if DEBUG >= 4 std::cerr << "Second-seek completed (time " << ms << "ms) " << ret << std::endl; #endif } break; case 'f':{ //frame-seek #if DEBUG >= 4 std::cerr << "Received frame-seek (" << cmd << ")" << std::endl; #endif bool ret = source.seek_frame(JSON::Value(cmd.substr(2)).asInt()); #if DEBUG >= 4 std::cerr << "Frame-seek completed " << ret << std::endl; #endif } break; case 'p':{ //play #if DEBUG >= 4 std::cerr << "Received play" << std::endl; #endif playing = -1; in_out.setBlocking(false); } break; case 'o':{ //once-play #if DEBUG >= 4 std::cerr << "Received once-play" << std::endl; #endif if (playing <= 0){playing = 1;} ++playing; in_out.setBlocking(false); } break; case 'q':{ //quit-playing #if DEBUG >= 4 std::cerr << "Received quit-playing" << std::endl; #endif playing = 0; in_out.setBlocking(true); } break; } } } } if (playing != 0){ now = getNowMS(); if (playing > 0 || now - timeDiff >= lastTime || lastTime - (now - timeDiff) > 15000) { source.seekNext(); lastTime = source.getJSON()["time"].asInt(); if ((now - timeDiff - lastTime) > 5000 || (now - timeDiff - lastTime < -5000)){ timeDiff = now - lastTime; } if (source.getJSON().isMember("keyframe")){ if (playing > 0){--playing;} if (playing == 0){ #if DEBUG >= 4 std::cerr << "Sending pause_marker" << std::endl; #endif pausemark["time"] = (long long int)now; pausemark.toPacked(); in_out.Send(pausemark.toNetPacked()); in_out.flush(); in_out.setBlocking(true); } } if (playing != 0){ //insert proper header for this type of data in_out.Send("DTPD"); //insert the packet length unsigned int size = htonl(source.getPacket().size()); in_out.Send((char*)&size, 4); in_out.Send(source.getPacket()); } } else { usleep(std::min(10000LL, lastTime - (now - timeDiff)) * 1000); } } usleep(10000);//sleep 10ms } StatsSocket.close(); return 0; } <commit_msg>Fixed MistPlayer compiling.<commit_after>/// \file player.cpp /// Holds all code for the MistPlayer application used for VoD streams. #if DEBUG >= 4 #include <iostream>//for std::cerr #endif #include <stdio.h> //for fileno #include <stdlib.h> //for atoi #include <sys/time.h> #include <mist/dtsc.h> #include <mist/json.h> #include <mist/config.h> #include <mist/socket.h> /// Copy of stats from buffer_user.cpp class Stats{ public: unsigned int up; unsigned int down; std::string host; std::string connector; unsigned int conntime; Stats(){ up = 0; down = 0; conntime = 0; }; /// Reads a stats string and parses it to the internal representation. Stats(std::string s){ size_t f = s.find(' '); if (f != std::string::npos){ host = s.substr(0, f); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ connector = s.substr(0, f); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ conntime = atoi(s.substr(0, f).c_str()); s.erase(0, f+1); } f = s.find(' '); if (f != std::string::npos){ up = atoi(s.substr(0, f).c_str()); s.erase(0, f+1); down = atoi(s.c_str()); } }; }; /// Gets the current system time in milliseconds. long long int getNowMS(){ timeval t; gettimeofday(&t, 0); return t.tv_sec * 1000 + t.tv_usec/1000; }//getNowMS int main(int argc, char** argv){ Util::Config conf(argv[0], PACKAGE_VERSION); conf.addOption("filename", JSON::fromString("{\"arg_num\":1, \"help\":\"Name of the file to write to stdout.\"}")); conf.parseArgs(argc, argv); conf.activate(); int playing = 0; DTSC::File source = DTSC::File(conf.getString("filename")); Socket::Connection in_out = Socket::Connection(fileno(stdout), fileno(stdin)); std::string meta_str = source.getHeader(); JSON::Value pausemark; pausemark["datatype"] = "pause_marker"; pausemark["time"] = (long long int)0; Socket::Connection StatsSocket = Socket::Connection("/tmp/mist/statistics", true); //send the header { in_out.Send("DTSC"); unsigned int size = htonl(meta_str.size()); in_out.Send((char*)&size, 4); in_out.Send(meta_str); } JSON::Value meta = JSON::fromDTMI(meta_str); JSON::Value last_pack; long long now, timeDiff = 0, lastTime = 0; Stats sts; while (in_out.connected()){ if (in_out.spool()){ while (in_out.Received().find('\n') != std::string::npos){ std::string cmd = in_out.Received().substr(0, in_out.Received().find('\n')); in_out.Received().erase(0, in_out.Received().find('\n')+1); if (cmd != ""){ switch (cmd[0]){ case 'P':{ //Push #if DEBUG >= 4 std::cerr << "Received push - ignoring (" << cmd << ")" << std::endl; #endif in_out.close();//pushing to VoD makes no sense } break; case 'S':{ //Stats if (!StatsSocket.connected()){ StatsSocket = Socket::Connection("/tmp/mist/statistics", true); } if (StatsSocket.connected()){ sts = Stats(cmd.substr(2)); JSON::Value json_sts; json_sts["vod"]["down"] = (long long int)sts.down; json_sts["vod"]["up"] = (long long int)sts.up; json_sts["vod"]["time"] = (long long int)sts.conntime; json_sts["vod"]["host"] = sts.host; json_sts["vod"]["connector"] = sts.connector; json_sts["vod"]["filename"] = conf.getString("filename"); json_sts["vod"]["now"] = (long long int)time(0); json_sts["vod"]["meta"] = meta; StatsSocket.Send(json_sts.toString().c_str()); StatsSocket.Send("\n\n"); StatsSocket.flush(); } } break; case 's':{ //second-seek #if DEBUG >= 4 std::cerr << "Received ms-seek (" << cmd << ")" << std::endl; #endif int ms = JSON::Value(cmd.substr(2)).asInt(); bool ret = source.seek_time(ms); #if DEBUG >= 4 std::cerr << "Second-seek completed (time " << ms << "ms) " << ret << std::endl; #endif } break; case 'f':{ //frame-seek #if DEBUG >= 4 std::cerr << "Received frame-seek (" << cmd << ")" << std::endl; #endif bool ret = source.seek_frame(JSON::Value(cmd.substr(2)).asInt()); #if DEBUG >= 4 std::cerr << "Frame-seek completed " << ret << std::endl; #endif } break; case 'p':{ //play #if DEBUG >= 4 std::cerr << "Received play" << std::endl; #endif playing = -1; in_out.setBlocking(false); } break; case 'o':{ //once-play #if DEBUG >= 4 std::cerr << "Received once-play" << std::endl; #endif if (playing <= 0){playing = 1;} ++playing; in_out.setBlocking(false); } break; case 'q':{ //quit-playing #if DEBUG >= 4 std::cerr << "Received quit-playing" << std::endl; #endif playing = 0; in_out.setBlocking(true); } break; } } } } if (playing != 0){ now = getNowMS(); if (playing > 0 || now - timeDiff >= lastTime || lastTime - (now - timeDiff) > 15000) { source.seekNext(); lastTime = source.getJSON()["time"].asInt(); if ((now - timeDiff - lastTime) > 5000 || (now - timeDiff - lastTime < -5000)){ timeDiff = now - lastTime; } if (source.getJSON().isMember("keyframe")){ if (playing > 0){--playing;} if (playing == 0){ #if DEBUG >= 4 std::cerr << "Sending pause_marker" << std::endl; #endif pausemark["time"] = (long long int)now; pausemark.toPacked(); in_out.Send(pausemark.toNetPacked()); in_out.flush(); in_out.setBlocking(true); } } if (playing != 0){ //insert proper header for this type of data in_out.Send("DTPD"); //insert the packet length unsigned int size = htonl(source.getPacket().size()); in_out.Send((char*)&size, 4); in_out.Send(source.getPacket()); } } else { usleep(std::min(10000LL, lastTime - (now - timeDiff)) * 1000); } } usleep(10000);//sleep 10ms } StatsSocket.close(); return 0; } <|endoftext|>
<commit_before>#include "player.h" #include <cmath> const double PI = 3.14159265358979323846264338329750288419716939937510582; Player::Player() : Speed(0), Yrot(0), Zrot(0), X(0), Y(0), Z(0), Moving(false), Name("Untitled"), StandingOn(NULL), GravitySpeed(0.f), SurfaceZ(0.f) {} Player::Player(float initspeed, float initYrot, float initZrot, float initX, float initY, float initZ, std::string Name) : Speed(initspeed), Yrot(initYrot), Zrot(initZrot), X(initX), Y(initY), Z(initZ), Moving(false), Name(Name), StandingOn(NULL), GravitySpeed(0.f), SurfaceZ(0.f) {} void Player::Forward(float amount) { Moving = true; float xStep = Speed * sin((PI * Zrot) / 180) * amount; float yStep = Speed * cos((PI * Zrot) / 180) * amount; //float zStep = -Speed * sin((PI * Yrot) / 180) * amount; X += (xStep);// * cos((PI * Yrot) / 180)); Y += (yStep);// * cos((PI * Yrot) / 180)); //Z += zStep; } void Player::Strafe(float amount) { float xStep = Speed * sin((PI * Zrot) / 180) * amount; float yStep = Speed * cos((PI * Zrot) / 180) * amount; if(Moving == true) { xStep *= 0.707106; yStep *= 0.707106; } X -= yStep; Y += xStep; } void Player::ChangeRotation(float deltaYrot, float deltaZrot) { Zrot += deltaZrot; Yrot += deltaYrot; if(Zrot >= 360) Zrot -= 360; else if (Zrot < 0) Zrot += 360; if(Yrot < -90) Yrot = -90; else if(Yrot >= 90) Yrot = 90; } void Player::Jump() { if (StandingOn) { GravitySpeed = 9.8f; } } void Player::DoStep(float amount) { Moving = false; if (!StandingOn) { GravitySpeed -= 9.8f * amount; Z += GravitySpeed * amount; } else { GravitySpeed = 0.f; Z = SurfaceZ + 2.f; } } <commit_msg>Bouncy Bottom! :D<commit_after>#include "player.h" #include <cmath> const double PI = 3.14159265358979323846264338329750288419716939937510582; Player::Player() : Speed(0), Yrot(0), Zrot(0), X(0), Y(0), Z(0), Moving(false), Name("Untitled"), StandingOn(NULL), GravitySpeed(0.f), SurfaceZ(0.f) {} Player::Player(float initspeed, float initYrot, float initZrot, float initX, float initY, float initZ, std::string Name) : Speed(initspeed), Yrot(initYrot), Zrot(initZrot), X(initX), Y(initY), Z(initZ), Moving(false), Name(Name), StandingOn(NULL), GravitySpeed(0.f), SurfaceZ(0.f) {} void Player::Forward(float amount) { Moving = true; float xStep = Speed * sin((PI * Zrot) / 180) * amount; float yStep = Speed * cos((PI * Zrot) / 180) * amount; //float zStep = -Speed * sin((PI * Yrot) / 180) * amount; X += (xStep);// * cos((PI * Yrot) / 180)); Y += (yStep);// * cos((PI * Yrot) / 180)); //Z += zStep; } void Player::Strafe(float amount) { float xStep = Speed * sin((PI * Zrot) / 180) * amount; float yStep = Speed * cos((PI * Zrot) / 180) * amount; if(Moving == true) { xStep *= 0.707106; yStep *= 0.707106; } X -= yStep; Y += xStep; } void Player::ChangeRotation(float deltaYrot, float deltaZrot) { Zrot += deltaZrot; Yrot += deltaYrot; if(Zrot >= 360) Zrot -= 360; else if (Zrot < 0) Zrot += 360; if(Yrot < -90) Yrot = -90; else if(Yrot >= 90) Yrot = 90; } void Player::Jump() { if (StandingOn) { GravitySpeed = 9.8f; } } void Player::DoStep(float amount) { Moving = false; if (!StandingOn) { GravitySpeed -= 9.8f * amount; if (Z < 0) GravitySpeed = -GravitySpeed; Z += GravitySpeed * amount; } else { GravitySpeed = 0.f; Z = SurfaceZ + 2.f; } } <|endoftext|>
<commit_before>// SA:MP Profiler plugin // // Copyright (c) 2011 Zeex // // 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 <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iterator> #include <list> #include <map> #include <sstream> #include <string> #include <vector> #ifdef _WIN32 #include <Windows.h> #endif #include "amx_name.h" #include "config_reader.h" #include "debug_info.h" #include "html_printer.h" #include "jump_x86.h" #include "plugin.h" #include "profiler.h" #include "text_printer.h" #include "version.h" #include "xml_printer.h" #include "amx/amx.h" typedef void (*logprintf_t)(const char *format, ...); // AMX API functons array extern void *pAMXFunctions; // For logging static logprintf_t logprintf; // Symbolic info, used for getting function names static std::map<AMX*, samp_profiler::DebugInfo> debug_infos; // Contains currently loaded AMX scripts static std::list<AMX*> loaded_scripts; // Hooks static samp_profiler::JumpX86 ExecHook; static samp_profiler::JumpX86 CallbackHook; static int AMXAPI Exec(AMX *amx, cell *retval, int index) { ExecHook.Remove(); CallbackHook.Install(); // P-code may call natives // Return code int error = AMX_ERR_NONE; // Check if this script has a profiler attached to it samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx); if (prof != 0) { error = prof->Exec(retval, index); } else { error = amx_Exec(amx, retval, index); } CallbackHook.Remove(); ExecHook.Install(); return error; } static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) { CallbackHook.Remove(); ExecHook.Install(); // Natives may call amx_Exec() // The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes // with SYSREQ.D for better performance. amx->sysreq_d = 0; // Return code int error = AMX_ERR_NONE; // Check if this script has a profiler attached to it samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx); if (prof != 0) { error = prof->Callback(index, result, params); } else { error = amx_Callback(amx, index, result, params); } ExecHook.Remove(); CallbackHook.Install(); return error; } // Replaces back slashes with forward slashes static std::string ToNormalPath(const std::string &path) { std::string fsPath = path; std::replace(fsPath.begin(), fsPath.end(), '\\', '/'); return fsPath; } static bool IsGameMode(const std::string &amxName) { return ToNormalPath(amxName).find("gamemodes/") != std::string::npos; } static bool IsFilterScript(const std::string &amxName) { return ToNormalPath(amxName).find("filterscripts/") != std::string::npos; } static bool GetPublicVariable(AMX *amx, const char *name, cell &value) { cell amx_addr; if (amx_FindPubVar(amx, name, &amx_addr) == AMX_ERR_NONE) { cell *phys_addr; amx_GetAddr(amx, amx_addr, &phys_addr); value = *phys_addr; return true; } return false; } // Returns true if the .amx should be profiled static bool WantsProfiler(const std::string &amxName) { std::string goodAmxName = ToNormalPath(amxName); samp_profiler::ConfigReader server_cfg("server.cfg"); if (IsGameMode(amxName)) { // This is a gamemode if (server_cfg.GetOption("profile_gamemode", false)) { return true; } } else if (IsFilterScript(amxName)) { std::string fsList = server_cfg.GetOption("profile_filterscripts", std::string("")); std::stringstream fsStream(fsList); do { std::string fsName; fsStream >> fsName; if (goodAmxName == "filterscripts/" + fsName + ".amx" || goodAmxName == "filterscripts/" + fsName) { return true; } } while (!fsStream.eof()); } return false; } #ifdef _WIN32 PLUGIN_EXPORT void PLUGIN_CALL Unload(); PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx); // Manually call Unload and AmxUnload on Ctrl+Break // and server window close event. static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_CLOSE_EVENT: case CTRL_BREAK_EVENT: for (std::list<AMX*>::const_iterator iterator = ::loaded_scripts.begin(); iterator != ::loaded_scripts.end(); ++iterator) { AmxUnload(*iterator); } Unload(); } return FALSE; } #endif PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } // x86 is Little Endian... static void *AMXAPI my_amx_Align(void *v) { return v; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; // The server does not export amx_Align* for some reason. // They are used in amxdbg.c and amxaux.c, so they must be callable. ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)my_amx_Align; // amx_Align16 ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)my_amx_Align; // amx_Align32 ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)my_amx_Align; // amx_Align64 ExecHook.Install( ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec], (void*)::Exec); CallbackHook.Install( ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback], (void*)::Callback); #ifdef _WIN32 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); #endif logprintf(" Profiler plugin "VERSION_STRING" is OK."); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { logprintf("Profiler got unloaded."); return; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { std::string filename = samp_profiler::GetAmxName(amx); if (filename.empty()) { logprintf("Profiler: Failed to detect .amx name, prifiling will not be done"); return AMX_ERR_NONE; } if (!samp_profiler::Profiler::IsScriptProfilable(amx)) { logprintf("Profiler: Can't profile script %s (are you using -d0?)", filename.c_str()); return AMX_ERR_NONE; } cell profiler_enabled = false; if (GetPublicVariable(amx, "profiler_enabled", profiler_enabled) && !profiler_enabled) { return AMX_ERR_NONE; } if (profiler_enabled || WantsProfiler(filename)) { if (samp_profiler::DebugInfo::HasDebugInfo(amx)) { samp_profiler::DebugInfo debugInfo; debugInfo.Load(filename); if (debugInfo.IsLoaded()) { logprintf("Profiler: Loaded debug info from %s", filename.c_str()); ::debug_infos[amx] = debugInfo; samp_profiler::Profiler::Attach(amx, debugInfo); logprintf("Profiler: Attached profiler instance to %s", filename.c_str()); return AMX_ERR_NONE; } else { logprintf("Profiler: Error loading debug info from %s", filename.c_str()); } } samp_profiler::Profiler::Attach(amx); logprintf("Profiler: Attached profiler instance to %s (no debug symbols)", filename.c_str()); } ::loaded_scripts.push_back(amx); return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { // Get an instance of Profiler attached to the unloading AMX samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx); // Detach profiler if (prof != 0) { std::string amx_path = samp_profiler::GetAmxName(amx); // must be in cache std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of(".")); // Output stats depending on currently set output_format samp_profiler::ConfigReader server_cfg("server.cfg"); std::string format = server_cfg.GetOption("profile_format", std::string("html")); std::string filename = amx_name + "-profile"; samp_profiler::AbstractPrinter *printer = 0; if (format == "html") { filename += ".html"; printer = new samp_profiler::HtmlPrinter; } else if (format == "text") { filename += ".txt"; printer = new samp_profiler::TextPrinter; } else if (format == "xml") { filename += ".xml"; printer = new samp_profiler::XmlPrinter; } else { logprintf("Profiler: Unknown output format '%s'", format.c_str()); } if (printer != 0) { std::ofstream ostream(filename.c_str()); prof->PrintStats(ostream, printer); delete printer; } samp_profiler::Profiler::Detach(amx); } // Free debug info std::map<AMX*, samp_profiler::DebugInfo>::iterator it = ::debug_infos.find(amx); if (it != ::debug_infos.end()) { it->second.Free(); ::debug_infos.erase(it); } ::loaded_scripts.remove(amx); return AMX_ERR_NONE; } <commit_msg>Fix AmxUnload not called on Ctrl+C/close<commit_after>// SA:MP Profiler plugin // // Copyright (c) 2011 Zeex // // 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 <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <fstream> #include <iterator> #include <list> #include <map> #include <sstream> #include <string> #include <vector> #ifdef _WIN32 #include <Windows.h> #endif #include "amx_name.h" #include "config_reader.h" #include "debug_info.h" #include "html_printer.h" #include "jump_x86.h" #include "plugin.h" #include "profiler.h" #include "text_printer.h" #include "version.h" #include "xml_printer.h" #include "amx/amx.h" typedef void (*logprintf_t)(const char *format, ...); // AMX API functons array extern void *pAMXFunctions; // For logging static logprintf_t logprintf; // Symbolic info, used for getting function names static std::map<AMX*, samp_profiler::DebugInfo> debug_infos; // Contains currently loaded AMX scripts static std::list<AMX*> loaded_scripts; // Hooks static samp_profiler::JumpX86 ExecHook; static samp_profiler::JumpX86 CallbackHook; static int AMXAPI Exec(AMX *amx, cell *retval, int index) { ExecHook.Remove(); CallbackHook.Install(); // P-code may call natives // Return code int error = AMX_ERR_NONE; // Check if this script has a profiler attached to it samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx); if (prof != 0) { error = prof->Exec(retval, index); } else { error = amx_Exec(amx, retval, index); } CallbackHook.Remove(); ExecHook.Install(); return error; } static int AMXAPI Callback(AMX *amx, cell index, cell *result, cell *params) { CallbackHook.Remove(); ExecHook.Install(); // Natives may call amx_Exec() // The default AMX callback (amx_Callback) can replace SYSREQ.C opcodes // with SYSREQ.D for better performance. amx->sysreq_d = 0; // Return code int error = AMX_ERR_NONE; // Check if this script has a profiler attached to it samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx); if (prof != 0) { error = prof->Callback(index, result, params); } else { error = amx_Callback(amx, index, result, params); } ExecHook.Remove(); CallbackHook.Install(); return error; } // Replaces back slashes with forward slashes static std::string ToNormalPath(const std::string &path) { std::string fsPath = path; std::replace(fsPath.begin(), fsPath.end(), '\\', '/'); return fsPath; } static bool IsGameMode(const std::string &amxName) { return ToNormalPath(amxName).find("gamemodes/") != std::string::npos; } static bool IsFilterScript(const std::string &amxName) { return ToNormalPath(amxName).find("filterscripts/") != std::string::npos; } static bool GetPublicVariable(AMX *amx, const char *name, cell &value) { cell amx_addr; if (amx_FindPubVar(amx, name, &amx_addr) == AMX_ERR_NONE) { cell *phys_addr; amx_GetAddr(amx, amx_addr, &phys_addr); value = *phys_addr; return true; } return false; } // Returns true if the .amx should be profiled static bool WantsProfiler(const std::string &amxName) { std::string goodAmxName = ToNormalPath(amxName); samp_profiler::ConfigReader server_cfg("server.cfg"); if (IsGameMode(amxName)) { // This is a gamemode if (server_cfg.GetOption("profile_gamemode", false)) { return true; } } else if (IsFilterScript(amxName)) { std::string fsList = server_cfg.GetOption("profile_filterscripts", std::string("")); std::stringstream fsStream(fsList); do { std::string fsName; fsStream >> fsName; if (goodAmxName == "filterscripts/" + fsName + ".amx" || goodAmxName == "filterscripts/" + fsName) { return true; } } while (!fsStream.eof()); } return false; } #ifdef _WIN32 PLUGIN_EXPORT void PLUGIN_CALL Unload(); PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx); // Manually call Unload and AmxUnload on Ctrl+Break // and server window close event. static BOOL WINAPI ConsoleCtrlHandler(DWORD dwCtrlType) { switch (dwCtrlType) { case CTRL_CLOSE_EVENT: case CTRL_BREAK_EVENT: for (std::list<AMX*>::const_iterator iterator = ::loaded_scripts.begin(); iterator != ::loaded_scripts.end(); ++iterator) { AmxUnload(*iterator); } Unload(); } return FALSE; } #endif PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES; } // x86 is Little Endian... static void *AMXAPI my_amx_Align(void *v) { return v; } PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS]; logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF]; // The server does not export amx_Align* for some reason. // They are used in amxdbg.c and amxaux.c, so they must be callable. ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align16] = (void*)my_amx_Align; // amx_Align16 ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align32] = (void*)my_amx_Align; // amx_Align32 ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Align64] = (void*)my_amx_Align; // amx_Align64 ExecHook.Install( ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Exec], (void*)::Exec); CallbackHook.Install( ((void**)pAMXFunctions)[PLUGIN_AMX_EXPORT_Callback], (void*)::Callback); #ifdef _WIN32 SetConsoleCtrlHandler(ConsoleCtrlHandler, TRUE); #endif logprintf(" Profiler plugin "VERSION_STRING" is OK."); return true; } PLUGIN_EXPORT void PLUGIN_CALL Unload() { logprintf("Profiler got unloaded."); return; } PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX *amx) { ::loaded_scripts.push_back(amx); std::string filename = samp_profiler::GetAmxName(amx); if (filename.empty()) { logprintf("Profiler: Failed to detect .amx name, prifiling will not be done"); return AMX_ERR_NONE; } if (!samp_profiler::Profiler::IsScriptProfilable(amx)) { logprintf("Profiler: Can't profile script %s (are you using -d0?)", filename.c_str()); return AMX_ERR_NONE; } cell profiler_enabled = false; if (GetPublicVariable(amx, "profiler_enabled", profiler_enabled) && !profiler_enabled) { return AMX_ERR_NONE; } if (profiler_enabled || WantsProfiler(filename)) { if (samp_profiler::DebugInfo::HasDebugInfo(amx)) { samp_profiler::DebugInfo debugInfo; debugInfo.Load(filename); if (debugInfo.IsLoaded()) { logprintf("Profiler: Loaded debug info from %s", filename.c_str()); ::debug_infos[amx] = debugInfo; samp_profiler::Profiler::Attach(amx, debugInfo); logprintf("Profiler: Attached profiler instance to %s", filename.c_str()); return AMX_ERR_NONE; } else { logprintf("Profiler: Error loading debug info from %s", filename.c_str()); } } samp_profiler::Profiler::Attach(amx); logprintf("Profiler: Attached profiler instance to %s (no debug symbols)", filename.c_str()); } return AMX_ERR_NONE; } PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX *amx) { // Get an instance of Profiler attached to the unloading AMX samp_profiler::Profiler *prof = samp_profiler::Profiler::Get(amx); // Detach profiler if (prof != 0) { std::string amx_path = samp_profiler::GetAmxName(amx); // must be in cache std::string amx_name = std::string(amx_path, 0, amx_path.find_last_of(".")); // Output stats depending on currently set output_format samp_profiler::ConfigReader server_cfg("server.cfg"); std::string format = server_cfg.GetOption("profile_format", std::string("html")); std::string filename = amx_name + "-profile"; samp_profiler::AbstractPrinter *printer = 0; if (format == "html") { filename += ".html"; printer = new samp_profiler::HtmlPrinter; } else if (format == "text") { filename += ".txt"; printer = new samp_profiler::TextPrinter; } else if (format == "xml") { filename += ".xml"; printer = new samp_profiler::XmlPrinter; } else { logprintf("Profiler: Unknown output format '%s'", format.c_str()); } if (printer != 0) { std::ofstream ostream(filename.c_str()); prof->PrintStats(ostream, printer); delete printer; } samp_profiler::Profiler::Detach(amx); } // Free debug info std::map<AMX*, samp_profiler::DebugInfo>::iterator it = ::debug_infos.find(amx); if (it != ::debug_infos.end()) { it->second.Free(); ::debug_infos.erase(it); } return AMX_ERR_NONE; } <|endoftext|>
<commit_before>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 "plugin.h" #include "blocks/basic.h" #include "blocks/falling.h" #include "blocks/torch.h" #include "blocks/plant.h" #include "blocks/snow.h" #include "blocks/liquid.h" #include "blocks/fire.h" #include "blocks/stair.h" #include "blocks/door.h" #include "blocks/sign.h" Plugin &Plugin::get() { static Plugin instance; return instance; } void Plugin::init() { // Set default behaviours Callback call; /* FIXME: must remember to delete any memory we create here upon server stop */ BlockBasic* basicblock = new BlockBasic(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); setBlockCallback(BLOCK_STONE, call); setBlockCallback(BLOCK_GRASS, call); setBlockCallback(BLOCK_DIRT, call); setBlockCallback(BLOCK_COBBLESTONE, call); setBlockCallback(BLOCK_WOOD, call); setBlockCallback(BLOCK_LOG, call); setBlockCallback(BLOCK_SOIL, call); /* cloth */ setBlockCallback(BLOCK_RED_CLOTH, call); setBlockCallback(BLOCK_ORANGE_CLOTH, call); setBlockCallback(BLOCK_YELLOW_CLOTH, call); setBlockCallback(BLOCK_LIME_CLOTH, call); setBlockCallback(BLOCK_GREEN_CLOTH, call); setBlockCallback(BLOCK_AQUA_GREEN_CLOTH, call); setBlockCallback(BLOCK_CYAN_CLOTH, call); setBlockCallback(BLOCK_BLUE_CLOTH, call); setBlockCallback(BLOCK_PURPLE_CLOTH, call); setBlockCallback(BLOCK_INDIGO_CLOTH, call); setBlockCallback(BLOCK_VIOLET_CLOTH, call); setBlockCallback(BLOCK_MAGENTA_CLOTH, call); setBlockCallback(BLOCK_PINK_CLOTH, call); setBlockCallback(BLOCK_BLACK_CLOTH, call); setBlockCallback(BLOCK_GRAY_CLOTH, call); setBlockCallback(BLOCK_WHITE_CLOTH, call); /* metals */ setBlockCallback(BLOCK_GOLD_BLOCK, call); setBlockCallback(BLOCK_IRON_BLOCK, call); setBlockCallback(BLOCK_DOUBLE_STEP, call); setBlockCallback(BLOCK_STEP, call); setBlockCallback(BLOCK_BRICK, call); setBlockCallback(BLOCK_BOOKSHELF, call); setBlockCallback(BLOCK_MOSSY_COBBLESTONE, call); setBlockCallback(BLOCK_OBSIDIAN, call); setBlockCallback(BLOCK_MOB_SPAWNER, call); setBlockCallback(BLOCK_DIAMOND_BLOCK, call); setBlockCallback(BLOCK_PUMPKIN, call); setBlockCallback(BLOCK_CLAY, call); setBlockCallback(BLOCK_NETHERSTONE, call); setBlockCallback(BLOCK_LIGHTSTONE, call); setBlockCallback(BLOCK_JACK_O_LANTERN, call); setBlockCallback(BLOCK_JUKEBOX, call); setBlockCallback(BLOCK_MINECART_TRACKS, call); setBlockCallback(BLOCK_FENCE, call); setBlockCallback(BLOCK_GOLD_ORE, call); setBlockCallback(BLOCK_IRON_ORE, call); setBlockCallback(BLOCK_COAL_ORE, call); setBlockCallback(BLOCK_DIAMOND_ORE, call); setBlockCallback(BLOCK_GLOWING_REDSTONE_ORE, call); setBlockCallback(BLOCK_REDSTONE_ORE, call); /* Falling blocks (sand, etc) */ call.reset(); BlockFalling* fallingblock = new BlockFalling(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockFalling, &BlockFalling::onPlace>(fallingblock)); call.add("onNeighbourBroken", Function::from_method<BlockFalling, &BlockFalling::onNeighbourBroken>(fallingblock)); setBlockCallback(BLOCK_SAND, call); setBlockCallback(BLOCK_SLOW_SAND, call); setBlockCallback(BLOCK_GRAVEL, call); /* Torches */ call.reset(); BlockTorch* torchblock = new BlockTorch(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockTorch, &BlockTorch::onPlace>(torchblock)); call.add("onNeighbourBroken", Function::from_method<BlockTorch, &BlockTorch::onNeighbourBroken>(torchblock)); call.add("onReplace", Function::from_method<BlockBasic, &BlockBasic::onReplace>(basicblock)); setBlockCallback(BLOCK_TORCH, call); setBlockCallback(BLOCK_REDSTONE_TORCH_OFF, call); setBlockCallback(BLOCK_REDSTONE_TORCH_ON, call); /* ladders */ call.reset(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); call.add("onNeighbourBroken", Function::from_method<BlockTorch, &BlockTorch::onNeighbourBroken>(torchblock)); setBlockCallback(BLOCK_LADDER, call); /* Plants */ call.reset(); BlockPlant* plantblock = new BlockPlant(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); call.add("onNeighbourBroken", Function::from_method<BlockPlant, &BlockPlant::onNeighbourBroken>(plantblock)); call.add("onReplace", Function::from_method<BlockBasic, &BlockBasic::onReplace>(basicblock)); setBlockCallback(BLOCK_YELLOW_FLOWER, call); setBlockCallback(BLOCK_RED_ROSE, call); setBlockCallback(BLOCK_BROWN_MUSHROOM, call); setBlockCallback(BLOCK_RED_MUSHROOM, call); setBlockCallback(BLOCK_CROPS, call); setBlockCallback(BLOCK_CACTUS, call); setBlockCallback(BLOCK_REED, call); setBlockCallback(BLOCK_SAPLING, call); /* Snow */ call.reset(); BlockSnow* snowblock = new BlockSnow(); call.add("onNeighbourBroken", Function::from_method<BlockSnow, &BlockSnow::onNeighbourBroken>(snowblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); setBlockCallback(BLOCK_SNOW, call); /* Fire and Water */ call.reset(); BlockLiquid* liquidblock = new BlockLiquid(); call.add("onPlace", Function::from_method<BlockLiquid, &BlockLiquid::onPlace>(liquidblock)); call.add("onNeighbourBroken", Function::from_method<BlockLiquid, &BlockLiquid::onNeighbourBroken>(liquidblock)); call.add("onReplace", Function::from_method<BlockLiquid, &BlockLiquid::onReplace>(liquidblock)); setBlockCallback(BLOCK_WATER, call); setBlockCallback(BLOCK_STATIONARY_WATER, call); setBlockCallback(BLOCK_LAVA, call); setBlockCallback(BLOCK_STATIONARY_LAVA, call); /* Fire */ call.reset(); BlockFire* fireblock = new BlockFire(); call.add("onPlace", Function::from_method<BlockFire, &BlockFire::onPlace>(fireblock)); setBlockCallback(BLOCK_FIRE, call); /* Stairs */ call.reset(); BlockStair* stairblock = new BlockStair(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockStair, &BlockStair::onPlace>(stairblock)); call.add("onNeighbourBroken", Function::from_method<BlockStair, &BlockStair::onNeighbourBroken>(stairblock)); setBlockCallback(BLOCK_WOODEN_STAIRS, call); setBlockCallback(BLOCK_COBBLESTONE_STAIRS, call); /* TNT */ call.reset(); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); setBlockCallback(BLOCK_TNT, call); /* Containers */ call.reset(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); setBlockCallback(BLOCK_CHEST, call); setBlockCallback(BLOCK_WORKBENCH, call); setBlockCallback(BLOCK_FURNACE, call); /* TODO: Needs this? BLOCK_BURNING_FURNACE */ /* Doors */ call.reset(); BlockDoor* doorblock = new BlockDoor(); call.add("onStartedDigging", Function::from_method<BlockDoor, &BlockDoor::onStartedDigging>(doorblock)); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockDoor, &BlockDoor::onPlace>(doorblock)); setBlockCallback(BLOCK_WOODEN_DOOR, call); setBlockCallback(BLOCK_IRON_DOOR, call); /* leaves */ call.reset(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); setBlockCallback(BLOCK_LEAVES, call); /* signs */ call.reset(); BlockSign* signblock = new BlockSign(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onNeighbourBroken", Function::from_method<BlockTorch, &BlockTorch::onNeighbourBroken>(torchblock)); call.add("onPlace", Function::from_method<BlockSign, &BlockSign::onPlace>(signblock)); setBlockCallback(BLOCK_WALL_SIGN, call); setBlockCallback(BLOCK_SIGN_POST, call); setBlockCallback(ITEM_SIGN, call); /* TODO: Unimplemented */ /* BLOCK_SPONGE */ /* BLOCK_REDSTONE_WIRE */ /* BLOCK_PORTAL */ /* BLOCK_LEVER, BLOCK_STONE_BUTTON */ /* BLOCK_WOODEN_PRESSURE_PLATE, BLOCK_STONE_PRESSURE_PLATE */ /* BLOCK_ICE */ /* BLOCK_SNOW_BLOCK */ } void Plugin::setBlockCallback(const int type, Callback call) { removeBlockCallback(type); blockevents.insert(std::pair<int, Callback>(type, call)); } Callback* Plugin::getBlockCallback(const int type) { Callbacks::iterator iter = blockevents.find(type); if (iter == blockevents.end()) return NULL; return &(*iter).second; } bool Plugin::runBlockCallback(const int type, const std::string name, const Function::invoker_type function) { Callbacks::iterator iter = blockevents.find(type); if (iter == blockevents.end()) return false; return (*iter).second.run(name, function); } bool Plugin::removeBlockCallback(const int type) { Callbacks::iterator iter = blockevents.find(type); if (iter == blockevents.end()) return false; delete &iter->first; blockevents.erase(iter); return true; } <commit_msg>Fixed issue when blocks are set twice<commit_after>/* Copyright (c) 2010, The Mineserver Project 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 The Mineserver Project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER 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 "plugin.h" #include "blocks/basic.h" #include "blocks/falling.h" #include "blocks/torch.h" #include "blocks/plant.h" #include "blocks/snow.h" #include "blocks/liquid.h" #include "blocks/fire.h" #include "blocks/stair.h" #include "blocks/door.h" #include "blocks/sign.h" Plugin &Plugin::get() { static Plugin instance; return instance; } void Plugin::init() { // Set default behaviours Callback call; /* FIXME: must remember to delete any memory we create here upon server stop */ BlockBasic* basicblock = new BlockBasic(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); setBlockCallback(BLOCK_STONE, call); setBlockCallback(BLOCK_GRASS, call); setBlockCallback(BLOCK_DIRT, call); setBlockCallback(BLOCK_COBBLESTONE, call); setBlockCallback(BLOCK_WOOD, call); setBlockCallback(BLOCK_LOG, call); setBlockCallback(BLOCK_SOIL, call); /* cloth */ setBlockCallback(BLOCK_RED_CLOTH, call); setBlockCallback(BLOCK_ORANGE_CLOTH, call); setBlockCallback(BLOCK_YELLOW_CLOTH, call); setBlockCallback(BLOCK_LIME_CLOTH, call); setBlockCallback(BLOCK_GREEN_CLOTH, call); setBlockCallback(BLOCK_AQUA_GREEN_CLOTH, call); setBlockCallback(BLOCK_CYAN_CLOTH, call); setBlockCallback(BLOCK_BLUE_CLOTH, call); setBlockCallback(BLOCK_PURPLE_CLOTH, call); setBlockCallback(BLOCK_INDIGO_CLOTH, call); setBlockCallback(BLOCK_VIOLET_CLOTH, call); setBlockCallback(BLOCK_MAGENTA_CLOTH, call); setBlockCallback(BLOCK_PINK_CLOTH, call); setBlockCallback(BLOCK_BLACK_CLOTH, call); setBlockCallback(BLOCK_GRAY_CLOTH, call); setBlockCallback(BLOCK_WHITE_CLOTH, call); /* metals */ setBlockCallback(BLOCK_GOLD_BLOCK, call); setBlockCallback(BLOCK_IRON_BLOCK, call); setBlockCallback(BLOCK_DOUBLE_STEP, call); setBlockCallback(BLOCK_STEP, call); setBlockCallback(BLOCK_BRICK, call); setBlockCallback(BLOCK_BOOKSHELF, call); setBlockCallback(BLOCK_MOSSY_COBBLESTONE, call); setBlockCallback(BLOCK_OBSIDIAN, call); setBlockCallback(BLOCK_MOB_SPAWNER, call); setBlockCallback(BLOCK_DIAMOND_BLOCK, call); setBlockCallback(BLOCK_PUMPKIN, call); setBlockCallback(BLOCK_CLAY, call); setBlockCallback(BLOCK_NETHERSTONE, call); setBlockCallback(BLOCK_LIGHTSTONE, call); setBlockCallback(BLOCK_JACK_O_LANTERN, call); setBlockCallback(BLOCK_JUKEBOX, call); setBlockCallback(BLOCK_MINECART_TRACKS, call); setBlockCallback(BLOCK_FENCE, call); setBlockCallback(BLOCK_GOLD_ORE, call); setBlockCallback(BLOCK_IRON_ORE, call); setBlockCallback(BLOCK_COAL_ORE, call); setBlockCallback(BLOCK_DIAMOND_ORE, call); setBlockCallback(BLOCK_GLOWING_REDSTONE_ORE, call); setBlockCallback(BLOCK_REDSTONE_ORE, call); /* Falling blocks (sand, etc) */ call.reset(); BlockFalling* fallingblock = new BlockFalling(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockFalling, &BlockFalling::onPlace>(fallingblock)); call.add("onNeighbourBroken", Function::from_method<BlockFalling, &BlockFalling::onNeighbourBroken>(fallingblock)); setBlockCallback(BLOCK_SAND, call); setBlockCallback(BLOCK_SLOW_SAND, call); setBlockCallback(BLOCK_GRAVEL, call); /* Torches */ call.reset(); BlockTorch* torchblock = new BlockTorch(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockTorch, &BlockTorch::onPlace>(torchblock)); call.add("onNeighbourBroken", Function::from_method<BlockTorch, &BlockTorch::onNeighbourBroken>(torchblock)); call.add("onReplace", Function::from_method<BlockBasic, &BlockBasic::onReplace>(basicblock)); setBlockCallback(BLOCK_TORCH, call); setBlockCallback(BLOCK_REDSTONE_TORCH_OFF, call); setBlockCallback(BLOCK_REDSTONE_TORCH_ON, call); /* ladders */ call.reset(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); call.add("onNeighbourBroken", Function::from_method<BlockTorch, &BlockTorch::onNeighbourBroken>(torchblock)); setBlockCallback(BLOCK_LADDER, call); /* Plants */ call.reset(); BlockPlant* plantblock = new BlockPlant(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); call.add("onNeighbourBroken", Function::from_method<BlockPlant, &BlockPlant::onNeighbourBroken>(plantblock)); call.add("onReplace", Function::from_method<BlockBasic, &BlockBasic::onReplace>(basicblock)); setBlockCallback(BLOCK_YELLOW_FLOWER, call); setBlockCallback(BLOCK_RED_ROSE, call); setBlockCallback(BLOCK_BROWN_MUSHROOM, call); setBlockCallback(BLOCK_RED_MUSHROOM, call); setBlockCallback(BLOCK_CROPS, call); setBlockCallback(BLOCK_CACTUS, call); setBlockCallback(BLOCK_REED, call); setBlockCallback(BLOCK_SAPLING, call); /* Snow */ call.reset(); BlockSnow* snowblock = new BlockSnow(); call.add("onNeighbourBroken", Function::from_method<BlockSnow, &BlockSnow::onNeighbourBroken>(snowblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); setBlockCallback(BLOCK_SNOW, call); /* Fire and Water */ call.reset(); BlockLiquid* liquidblock = new BlockLiquid(); call.add("onPlace", Function::from_method<BlockLiquid, &BlockLiquid::onPlace>(liquidblock)); call.add("onNeighbourBroken", Function::from_method<BlockLiquid, &BlockLiquid::onNeighbourBroken>(liquidblock)); call.add("onReplace", Function::from_method<BlockLiquid, &BlockLiquid::onReplace>(liquidblock)); setBlockCallback(BLOCK_WATER, call); setBlockCallback(BLOCK_STATIONARY_WATER, call); setBlockCallback(BLOCK_LAVA, call); setBlockCallback(BLOCK_STATIONARY_LAVA, call); /* Fire */ call.reset(); BlockFire* fireblock = new BlockFire(); call.add("onPlace", Function::from_method<BlockFire, &BlockFire::onPlace>(fireblock)); setBlockCallback(BLOCK_FIRE, call); /* Stairs */ call.reset(); BlockStair* stairblock = new BlockStair(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockStair, &BlockStair::onPlace>(stairblock)); call.add("onNeighbourBroken", Function::from_method<BlockStair, &BlockStair::onNeighbourBroken>(stairblock)); setBlockCallback(BLOCK_WOODEN_STAIRS, call); setBlockCallback(BLOCK_COBBLESTONE_STAIRS, call); /* TNT */ call.reset(); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); setBlockCallback(BLOCK_TNT, call); /* Containers */ call.reset(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockBasic, &BlockBasic::onPlace>(basicblock)); setBlockCallback(BLOCK_CHEST, call); setBlockCallback(BLOCK_WORKBENCH, call); setBlockCallback(BLOCK_FURNACE, call); /* TODO: Needs this? BLOCK_BURNING_FURNACE */ /* Doors */ call.reset(); BlockDoor* doorblock = new BlockDoor(); call.add("onStartedDigging", Function::from_method<BlockDoor, &BlockDoor::onStartedDigging>(doorblock)); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onPlace", Function::from_method<BlockDoor, &BlockDoor::onPlace>(doorblock)); setBlockCallback(BLOCK_WOODEN_DOOR, call); setBlockCallback(BLOCK_IRON_DOOR, call); /* leaves */ call.reset(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); setBlockCallback(BLOCK_LEAVES, call); /* signs */ call.reset(); BlockSign* signblock = new BlockSign(); call.add("onBroken", Function::from_method<BlockBasic, &BlockBasic::onBroken>(basicblock)); call.add("onNeighbourBroken", Function::from_method<BlockTorch, &BlockTorch::onNeighbourBroken>(torchblock)); call.add("onPlace", Function::from_method<BlockSign, &BlockSign::onPlace>(signblock)); setBlockCallback(BLOCK_WALL_SIGN, call); setBlockCallback(BLOCK_SIGN_POST, call); setBlockCallback(ITEM_SIGN, call); /* TODO: Unimplemented */ /* BLOCK_SPONGE */ /* BLOCK_REDSTONE_WIRE */ /* BLOCK_PORTAL */ /* BLOCK_LEVER, BLOCK_STONE_BUTTON */ /* BLOCK_WOODEN_PRESSURE_PLATE, BLOCK_STONE_PRESSURE_PLATE */ /* BLOCK_ICE */ /* BLOCK_SNOW_BLOCK */ } void Plugin::setBlockCallback(const int type, Callback call) { removeBlockCallback(type); blockevents.insert(std::pair<int, Callback>(type, call)); } Callback* Plugin::getBlockCallback(const int type) { Callbacks::iterator iter = blockevents.find(type); if (iter == blockevents.end()) return NULL; return &(*iter).second; } bool Plugin::runBlockCallback(const int type, const std::string name, const Function::invoker_type function) { Callbacks::iterator iter = blockevents.find(type); if (iter == blockevents.end()) return false; return (*iter).second.run(name, function); } bool Plugin::removeBlockCallback(const int type) { Callbacks::iterator iter = blockevents.find(type); if (iter == blockevents.end()) return false; blockevents.erase(iter); return true; } <|endoftext|>
<commit_before>#include <boost/python.hpp> #include <boost/python/exception_translator.hpp> #include <boost/python/numpy.hpp> #include "cimage.h" #include "cproc.h" #include "gil.h" #include "except.h" #include "bitmap.h" using namespace boost::python; class BitmapWrapper : public Bitmap , public wrapper<Bitmap> { public: BitmapWrapper(std::string filepath) : Bitmap(filepath) { // nop } numpy::ndarray data_as_ndarray() const { tuple shape, strides; numpy::dtype data_type = numpy::dtype::get_builtin<uint8_t>(); shape = make_tuple(_height, _width, 3); strides = make_tuple(_width * 3 * sizeof(uint8_t), 3 * sizeof(uint8_t), sizeof(uint8_t)); return numpy::from_data(_data, data_type, shape, strides, object()); } }; class CimageWrapper : public Cimage , public wrapper<Cimage> { public: CimageWrapper(size_t width, size_t height) : Cimage(width, height) { } public: void info() { ScopedPythonGILLock gil_lock; override f = this->get_override("info"); if (f) f(); else Cimage::info(); } }; void translate_FileError(FileError const & e) { PyErr_SetString(PyExc_OSError, "FileError"); } BOOST_PYTHON_MODULE(pymycpp) { PyEval_InitThreads(); register_exception_translator<FileError>(&translate_FileError); class_<CimageWrapper, boost::noncopyable>( "Cimage", init<size_t, size_t>()) .def("width", &CimageWrapper::width) .def("height", &CimageWrapper::height) .def("how_many_bytes", &CimageWrapper::how_many_bytes) .staticmethod("how_many_bytes") .def("info", &CimageWrapper::info) ; class_<Cproc, boost::noncopyable>( "Cproc", init<>()) .def("run", &Cproc::run) .def("stop", &Cproc::stop) ; class_<BitmapWrapper, boost::noncopyable>( "Bitmap", init<std::string>()) .def("get_width", &BitmapWrapper::get_width) .def("get_height", &BitmapWrapper::get_height) .def("save", &BitmapWrapper::save) .def("data", &BitmapWrapper::data_as_ndarray) ; } <commit_msg>Issue #15 and #17: added missing numpy::initialize to module<commit_after>#include <boost/python.hpp> #include <boost/python/exception_translator.hpp> #include <boost/python/numpy.hpp> #include "cimage.h" #include "cproc.h" #include "gil.h" #include "except.h" #include "bitmap.h" using namespace boost::python; class BitmapWrapper : public Bitmap , public wrapper<Bitmap> { public: BitmapWrapper(std::string filepath) : Bitmap(filepath) { // nop } numpy::ndarray data_as_ndarray() const { tuple shape, strides; numpy::dtype data_type = numpy::dtype::get_builtin<uint8_t>(); shape = make_tuple(_height, _width, 3); strides = make_tuple(_width * 3 * sizeof(uint8_t), 3 * sizeof(uint8_t), sizeof(uint8_t)); return numpy::from_data(_data, data_type, shape, strides, object()); } }; class CimageWrapper : public Cimage , public wrapper<Cimage> { public: CimageWrapper(size_t width, size_t height) : Cimage(width, height) { } public: void info() { ScopedPythonGILLock gil_lock; override f = this->get_override("info"); if (f) f(); else Cimage::info(); } }; void translate_FileError(FileError const & e) { PyErr_SetString(PyExc_OSError, "FileError"); } BOOST_PYTHON_MODULE(pymycpp) { PyEval_InitThreads(); numpy::initialize(); register_exception_translator<FileError>(&translate_FileError); class_<CimageWrapper, boost::noncopyable>( "Cimage", init<size_t, size_t>()) .def("width", &CimageWrapper::width) .def("height", &CimageWrapper::height) .def("how_many_bytes", &CimageWrapper::how_many_bytes) .staticmethod("how_many_bytes") .def("info", &CimageWrapper::info) ; class_<Cproc, boost::noncopyable>( "Cproc", init<>()) .def("run", &Cproc::run) .def("stop", &Cproc::stop) ; class_<BitmapWrapper, boost::noncopyable>( "Bitmap", init<std::string>()) .def("get_width", &BitmapWrapper::get_width) .def("get_height", &BitmapWrapper::get_height) .def("save", &BitmapWrapper::save) .def("data", &BitmapWrapper::data_as_ndarray) ; } <|endoftext|>
<commit_before>/* * Pi 2 is connected to the ImP/IMU via UART, Camera via CSI, Burn Wire Relay * via GPIO and Pi 1 via Ethernet and GPIO for LO, SOE and SODS signals. * * This program controls most of the main logic and for the PIOneERs mission * on board REXUS. */ #include <stdio.h> #include <cstdint> #include <unistd.h> //For sleep #include <stdlib.h> #include <iostream> #include <signal.h> #include "pins2.h" #include "camera/camera.h" #include "UART/UART.h" #include "Ethernet/Ethernet.h" #include "comms/pipes.h" #include "comms/protocol.h" #include "comms/packet.h" #include "timing/timer.h" #include "logger/logger.h" #include "tests/tests.h" #include <wiringPi.h> Logger Log("/Docs/Logs/raspi2"); bool flight_mode = false; // Global variable for the Camera and IMU PiCamera Cam; // Setup for the UART communications int baud = 230400; ImP IMP(baud); comms::Pipe ImP_stream; // Ethernet communication setup and variables (we are acting as client) int port_no = 31415; // Random unused port for communication Raspi2 raspi2(port_no); /** * Checks whether input is activated * @param pin: GPIO to be checked * @return true or false */ bool poll_input(int pin) { int count = 0; for (int i = 0; i < 5; i++) { count += digitalRead(pin); delayMicroseconds(200); } return (count < 3) ? true : false; } /** * Checks the status of three input pins (in1, in2 and in3). If in1 and in2 are high * but in3 is low return value will look like: 0b0000 0011 * @return Integer where the three LSB represent the status of in1, in2 and in3. */ int poll_signals(int in1, int in2, int in3) { int rtn = 0; if (poll_input(in1)) rtn += 0b001; if (poll_input(in2)) rtn += 0b010; if (poll_input(in3)) rtn += 0b100; return rtn; } void signal_handler(int s) { Log("FATAL") << "Exiting program after signal " << s; if (Cam.is_running()) { Cam.stopVideo(); Log("INFO") << "Stopping camera process"; } else { Log("ERROR") << "Camera process died prematurely or did not start"; } if (raspi2.is_alive()) { raspi2.end(); Log("INFO") << "Closed Ethernet communication"; } else { Log("ERROR") << "Ethernet process died prematurely or did not start"; } if (&ImP_stream != NULL) { ImP_stream.close_pipes(); Log("INFO") << "Closed ImP communication"; } else { Log("ERROR") << "ImP process died prematurely or did not start"; } digitalWrite(BURNWIRE, 0); // TODO copy data to a further backup directory Log("INFO") << "Ending program, Pi rebooting"; system("sudo reboot"); exit(1); // This was an unexpected end so we will exit with an error! } int SODS_SIGNAL() { /* * When the 'Start of Data Storage' signal is received all data recording * is stopped (IMU and Camera) and power to the camera is cut off to stop * shorting due to melting on re-entry. All data is copied into a backup * directory. */ Log("INFO") << "SODS signal received"; /* if (Cam.is_running()) { Cam.stopVideo(); Log("INFO") << "Stopping camera process"; } else { Log("ERROR") << "Camera process died prematurely or did not start"; } */ if (raspi2.is_alive()) { raspi2.end(); Log("INFO") << "Closed Ethernet communication"; } else { Log("ERROR") << "Ethernet process died prematurely or did not start"; } if (&ImP_stream != NULL) { ImP_stream.close_pipes(); Log("INFO") << "Closed ImP communication"; } else { Log("ERROR") << "ImP process died prematurely or did not start"; } digitalWrite(BURNWIRE, 0); digitalWrite(BURNWIRE, 0); Log("INFO") << "Waiting for power off"; while (1) { Timer::sleep_ms(10000); } // TODO copy data to a further backup directory //Log("INFO") << "Ending program, Pi rebooting"; //system("sudo reboot"); return 0; } int SOE_SIGNAL() { /* * When the 'Start of Experiment' signal is received the boom needs to be * deployed and the ImP and IMU to start taking measurements. For boom * deployment is there is no increase in the encoder count or ?? seconds * have passed since start of deployment then it is assumed that either the * boom has reached it's full length or something has gone wrong and the * count of the encoder is sent to ground. */ Log("INFO") << "SOE signal received"; // Setup the ImP and start requesting data ImP_stream = IMP.startDataCollection("Docs/Data/Pi2/test"); Log("INFO") << "Started data collection from ImP"; comms::Packet p; // Buffer for reading data from the IMU stream // Trigger the burn wire for 10 seconds! Log("INFO") << "Triggering burnwire"; digitalWrite(BURNWIRE, 1); Timer tmr; raspi2.sendMsg("Burnwire triggered..."); Log("INFO") << "Burn wire triggered" << std::endl; while (tmr.elapsed() < 10000) { // Get ImP data int n = ImP_stream.binread(&p, sizeof (p)); if (n > 0) { Log("DATA (ImP)") << p; raspi2.sendPacket(p); } n = raspi2.recvPacket(p); if (n > 0) Log("DATA (PI1)") << p; Timer::sleep_ms(10); } digitalWrite(BURNWIRE, 0); Log("INFO") << "Burn wire off after " << tmr.elapsed() << " ms"; raspi2.sendMsg("Burnwire off"); Log("INFO") << "Waiting for SODS"; // Wait for the next signal to continue the program bool signal_received = false; while (!signal_received) { signal_received = (poll_signals(LO, SOE, SODS) & 0b100); // Read data from IMU_data_stream and echo it to Ethernet int n = ImP_stream.binread(&p, sizeof (p)); if (n > 0) { Log("DATA (ImP)") << p; raspi2.sendPacket(p); } n = raspi2.recvPacket(p); if (n > 0) Log("DATA (PI1)") << p; Timer::sleep_ms(10); } return SODS_SIGNAL(); } int LO_SIGNAL() { /* * When the 'Lift Off' signal is received from the REXUS Module the cameras * are set to start recording video and we then wait to receive the 'Start * of Experiment' signal (when the nose-cone is ejected) */ Log("INFO") << "LO signal received"; raspi2.sendMsg("Recevied LO"); Cam.startVideo("Docs/Video/rexus_video"); Log("INFO") << "Camera started recording video"; // Poll the SOE pin until signal is received Log("INFO") << "Waiting for SOE"; bool signal_received = false; int counter = 0; while (!signal_received) { Timer::sleep_ms(10); signal_received = (poll_signals(LO, SOE, SODS) & 0b110); // Send a message evert second if (counter++ >= 100) { counter = 0; raspi2.sendMsg("I'm alive too..."); } } return SOE_SIGNAL(); } int main() { /* * This part of the program is run before the Lift-Off. In effect it * continually listens for commands from the ground station and runs any * required tests, regularly reporting status until the LO Signal is * received. */ signal(SIGINT, signal_handler); // Create necessary directories for saving files system("mkdir -p Docs/Data/Pi1 Docs/Data/Pi2 Docs/Data/test Docs/Video Docs/Logs"); Log.start_log(); Log("INFO") << "Pi2 is alive"; wiringPiSetup(); // Setup main signal pins pinMode(LO, INPUT); pullUpDnControl(LO, PUD_UP); pinMode(SOE, INPUT); pullUpDnControl(SOE, PUD_UP); pinMode(SODS, INPUT); pullUpDnControl(SODS, PUD_UP); pinMode(ALIVE, OUTPUT); Log("INFO") << "Main signal pins setup"; // Setup pins and check whether we are in flight mode pinMode(LAUNCH_MODE, INPUT); pullUpDnControl(LAUNCH_MODE, PUD_UP); //flight_mode = digitalRead(LAUNCH_MODE); flight_mode = false; Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled"); // Setup Burn Wire pinMode(BURNWIRE, OUTPUT); // Setup server and wait for client digitalWrite(ALIVE, 1); Log("INFO") << "Waiting for connection from client on port " << port_no; try { raspi2.run("Docs/Data/Pi1/backup"); Log("INFO") << "Connection to Pi1 successfil"; raspi2.sendMsg("Connected to Pi1"); } catch (EthernetException e) { Log("FATAL") << "Unable to connect to pi 1\n\t" << e.what(); Log("INFO") << "Continuing without Ethernet connection"; } Log("INFO") << "Waiting for LO signal"; // Check for LO signal. std::string msg; bool signal_received = false; comms::Packet p; comms::byte1_t id; comms::byte2_t index; char data[16]; int n; while (!signal_received) { Timer::sleep_ms(10); signal_received = (poll_signals(LO, SOE, SODS) & 0b111); // TODO Implement communications with Pi 1 n = raspi2.recvPacket(p); if (n > 0) { Log("PI1") << p; comms::Protocol::unpack(p, id, index, data); if (id == 0b11000000) { Log("RXSM") << "Received Command: " << data[0]; switch (data[0]) { case 1: // restart { Log("INFO") << "Rebooting..."; system("sudo reboot now"); exit(0); } case 2: // shutdown { Log("INFO") << "Shutting down..."; system("sudo shutdown now"); exit(0); } case 3: // Toggle flight mode { Log("INFO") << "Toggling flight mode"; //flight_mode = (flight_mode) ? false : true; Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled"); if (flight_mode) raspi2.sendMsg("WARNING Flight mode enabled"); else raspi2.sendMsg("Test mode enabled"); break; } case 4: // Run all tests { Log("INFO") << "Running tests..."; std::string result = tests::pi2_tests(); raspi2.sendMsg(result); Log("INFO") << "Test results\n\t" << result; } } } Log("DATA (PI1)") << "Unpacked\n\t\"" << std::string(data) << "\""; //TODO handle incoming commands! } } LO_SIGNAL(); system("sudo reboot"); return 0; } <commit_msg>Update to Comments<commit_after>/* * Pi 2 is connected to the ImP/IMU via UART, Camera via CSI, Burn Wire Relay * via GPIO and Pi 1 via Ethernet and GPIO for LO, SOE and SODS signals. * * This program controls most of the main logic and for the PIOneERs mission * on board REXUS. */ #include <stdio.h> #include <cstdint> #include <unistd.h> //For sleep #include <stdlib.h> #include <iostream> #include <signal.h> #include "pins2.h" #include "camera/camera.h" #include "UART/UART.h" #include "Ethernet/Ethernet.h" #include "comms/pipes.h" #include "comms/protocol.h" #include "comms/packet.h" #include "timing/timer.h" #include "logger/logger.h" #include "tests/tests.h" #include <wiringPi.h> Logger Log("/Docs/Logs/raspi2"); bool flight_mode = false; // Global variable for the Camera and IMU PiCamera Cam; // Setup for the UART communications int baud = 230400; ImP IMP(baud); comms::Pipe ImP_stream; // Ethernet communication setup and variables (we are acting as client) int port_no = 31415; // Random unused port for communication Raspi2 raspi2(port_no); /** * Checks whether input is activated * @param pin: GPIO to be checked * @return true or false */ bool poll_input(int pin) { int count = 0; for (int i = 0; i < 5; i++) { count += digitalRead(pin); delayMicroseconds(200); } return (count < 3) ? true : false; } /** * Checks the status of three input pins (in1, in2 and in3). If in1 and in2 are high * but in3 is low return value will look like: 0b0000 0011 * @return Integer where the three LSB represent the status of in1, in2 and in3. */ int poll_signals(int in1, int in2, int in3) { int rtn = 0; if (poll_input(in1)) rtn += 0b001; if (poll_input(in2)) rtn += 0b010; if (poll_input(in3)) rtn += 0b100; return rtn; } void signal_handler(int s) { Log("FATAL") << "Exiting program after signal " << s; if (Cam.is_running()) { Cam.stopVideo(); Log("INFO") << "Stopping camera process"; } else { Log("ERROR") << "Camera process died prematurely or did not start"; } if (raspi2.is_alive()) { raspi2.end(); Log("INFO") << "Closed Ethernet communication"; } else { Log("ERROR") << "Ethernet process died prematurely or did not start"; } if (&ImP_stream != NULL) { ImP_stream.close_pipes(); Log("INFO") << "Closed ImP communication"; } else { Log("ERROR") << "ImP process died prematurely or did not start"; } digitalWrite(BURNWIRE, 0); // TODO copy data to a further backup directory Log("INFO") << "Ending program, Pi rebooting"; system("sudo reboot"); exit(1); // This was an unexpected end so we will exit with an error! } int SODS_SIGNAL() { /* * When the 'Start of Data Storage' signal is received recording of IMU data * stops while the camera continues running till power off or storage space is full */ Log("INFO") << "SODS signal received"; /* if (Cam.is_running()) { Cam.stopVideo(); Log("INFO") << "Stopping camera process"; } else { Log("ERROR") << "Camera process died prematurely or did not start"; } */ if (raspi2.is_alive()) { raspi2.end(); Log("INFO") << "Closed Ethernet communication"; } else { Log("ERROR") << "Ethernet process died prematurely or did not start"; } if (&ImP_stream != NULL) { ImP_stream.close_pipes(); Log("INFO") << "Closed ImP communication"; } else { Log("ERROR") << "ImP process died prematurely or did not start"; } digitalWrite(BURNWIRE, 0); digitalWrite(BURNWIRE, 0); Log("INFO") << "Waiting for power off"; while (1) { Timer::sleep_ms(10000); } // TODO copy data to a further backup directory //Log("INFO") << "Ending program, Pi rebooting"; //system("sudo reboot"); return 0; } int SOE_SIGNAL() { /* * When the 'Start of Experiment' signal is received the boom needs to be * deployed and the ImP and IMU to start taking measurements. For boom * deployment is there is no increase in the encoder count or ?? seconds * have passed since start of deployment then it is assumed that either the * boom has reached it's full length or something has gone wrong and the * count of the encoder is sent to ground. */ Log("INFO") << "SOE signal received"; raspi2.sendMsg("Received SOE"); // Setup the ImP and start requesting data ImP_stream = IMP.startDataCollection("Docs/Data/Pi2/test"); Log("INFO") << "Started data collection from ImP"; comms::Packet p; // Buffer for reading data from the IMU stream // Trigger the burn wire for 10 seconds! Log("INFO") << "Triggering burnwire"; digitalWrite(BURNWIRE, 1); Timer tmr; raspi2.sendMsg("Burnwire triggered..."); Log("INFO") << "Burn wire triggered" << std::endl; while (tmr.elapsed() < 10000) { // Get ImP data int n = ImP_stream.binread(&p, sizeof (p)); if (n > 0) { Log("DATA (ImP)") << p; raspi2.sendPacket(p); } n = raspi2.recvPacket(p); if (n > 0) Log("DATA (PI1)") << p; Timer::sleep_ms(10); } digitalWrite(BURNWIRE, 0); Log("INFO") << "Burn wire off after " << tmr.elapsed() << " ms"; raspi2.sendMsg("Burnwire off"); Log("INFO") << "Waiting for SODS"; // Wait for the next signal to continue the program bool signal_received = false; while (!signal_received) { signal_received = (poll_signals(LO, SOE, SODS) & 0b100); // Read data from IMU_data_stream and echo it to Ethernet int n = ImP_stream.binread(&p, sizeof (p)); if (n > 0) { Log("DATA (ImP)") << p; raspi2.sendPacket(p); } n = raspi2.recvPacket(p); if (n > 0) Log("DATA (PI1)") << p; Timer::sleep_ms(10); } return SODS_SIGNAL(); } int LO_SIGNAL() { /* * When the 'Lift Off' signal is received from the REXUS Module the cameras * are set to start recording video and we then wait to receive the 'Start * of Experiment' signal (when the nose-cone is ejected) */ Log("INFO") << "LO signal received"; raspi2.sendMsg("Recevied LO"); Cam.startVideo("Docs/Video/rexus_video"); Log("INFO") << "Camera started recording video"; // Poll the SOE pin until signal is received Log("INFO") << "Waiting for SOE"; bool signal_received = false; int counter = 0; while (!signal_received) { Timer::sleep_ms(10); signal_received = (poll_signals(LO, SOE, SODS) & 0b110); // Send a message evert second if (counter++ >= 100) { counter = 0; raspi2.sendMsg("I'm alive too..."); } } return SOE_SIGNAL(); } int main() { /* * This part of the program is run before the Lift-Off. In effect it * continually listens for commands from the ground station and runs any * required tests, regularly reporting status until the LO Signal is * received. */ signal(SIGINT, signal_handler); // Create necessary directories for saving files system("mkdir -p Docs/Data/Pi1 Docs/Data/Pi2 Docs/Data/test Docs/Video Docs/Logs"); Log.start_log(); Log("INFO") << "Pi2 is alive"; wiringPiSetup(); // Setup main signal pins pinMode(LO, INPUT); pullUpDnControl(LO, PUD_UP); pinMode(SOE, INPUT); pullUpDnControl(SOE, PUD_UP); pinMode(SODS, INPUT); pullUpDnControl(SODS, PUD_UP); pinMode(ALIVE, OUTPUT); Log("INFO") << "Main signal pins setup"; // Setup pins and check whether we are in flight mode pinMode(LAUNCH_MODE, INPUT); pullUpDnControl(LAUNCH_MODE, PUD_UP); //flight_mode = digitalRead(LAUNCH_MODE); flight_mode = false; Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled"); // Setup Burn Wire pinMode(BURNWIRE, OUTPUT); // Setup server and wait for client digitalWrite(ALIVE, 1); Log("INFO") << "Waiting for connection from client on port " << port_no; try { raspi2.run("Docs/Data/Pi1/backup"); Log("INFO") << "Connection to Pi1 successfil"; raspi2.sendMsg("Connected to Pi1"); } catch (EthernetException e) { Log("FATAL") << "Unable to connect to pi 1\n\t" << e.what(); Log("INFO") << "Continuing without Ethernet connection"; } Log("INFO") << "Waiting for LO signal"; // Check for LO signal. std::string msg; bool signal_received = false; comms::Packet p; comms::byte1_t id; comms::byte2_t index; char data[16]; int n; while (!signal_received) { Timer::sleep_ms(10); signal_received = (poll_signals(LO, SOE, SODS) & 0b111); // TODO Implement communications with Pi 1 n = raspi2.recvPacket(p); if (n > 0) { Log("PI1") << p; comms::Protocol::unpack(p, id, index, data); if (id == 0b11000000) { Log("RXSM") << "Received Command: " << data[0]; switch (data[0]) { case 1: // restart { Log("INFO") << "Rebooting..."; system("sudo reboot now"); exit(0); } case 2: // shutdown { Log("INFO") << "Shutting down..."; system("sudo shutdown now"); exit(0); } case 3: // Toggle flight mode { Log("INFO") << "Toggling flight mode"; //flight_mode = (flight_mode) ? false : true; Log("INFO") << (flight_mode ? "flight mode enabled" : "test mode enabled"); if (flight_mode) raspi2.sendMsg("WARNING Flight mode enabled"); else raspi2.sendMsg("Test mode enabled"); break; } case 4: // Run all tests { Log("INFO") << "Running tests..."; std::string result = tests::pi2_tests(); raspi2.sendMsg(result); Log("INFO") << "Test results\n\t" << result; } } } Log("DATA (PI1)") << "Unpacked\n\t\"" << std::string(data) << "\""; //TODO handle incoming commands! } } LO_SIGNAL(); system("sudo reboot"); return 0; } <|endoftext|>
<commit_before>#include <employ_server_config.h> #include <employ_server_info.h> #include <employ_database.h> #include <QSqlQuery> #include <QSqlRecord> REGISTRY_EMPLOY(EmployServerInfo) // --------------------------------------------------------------------- EmployServerInfo::EmployServerInfo() : EmployBase(EmployServerInfo::name(), {EmployDatabase::name()}) { m_nCountQuests = 0; m_nCountQuestsAttempt = 0; m_nCountQuestsCompleted = 0; } // --------------------------------------------------------------------- bool EmployServerInfo::init(){ EmployDatabase *pDatabase = findEmploy<EmployDatabase>(); QSqlDatabase db = *(pDatabase->database()); QSqlQuery query(db); // count quests { QSqlQuery query(db); query.prepare("SELECT COUNT(*) cnt FROM quest"); if (!query.exec()){ Log::err(TAG, query.lastError().text()); return false; } if (query.next()) { QSqlRecord record = query.record(); m_nCountQuests = record.value("cnt").toInt(); }else{ // TODO error m_nCountQuests = 0; } } // quest attempts { QSqlQuery query(db); query.prepare("SELECT COUNT(*) cnt FROM users_quests_answers"); if (!query.exec()){ Log::err(TAG, query.lastError().text()); return false; } if (query.next()) { QSqlRecord record = query.record(); m_nCountQuestsAttempt = record.value("cnt").toInt(); }else{ // TODO error m_nCountQuestsAttempt = 0; } } // completed { QSqlQuery query(db); query.prepare("SELECT COUNT(*) cnt FROM users_quests"); if (!query.exec()){ Log::err(TAG, query.lastError().text()); return false; } if (query.next()) { QSqlRecord record = query.record(); m_nCountQuestsCompleted = record.value("cnt").toInt(); }else{ // TODO error m_nCountQuestsCompleted = 0; } } return true; } // --------------------------------------------------------------------- void EmployServerInfo::incrementRequests(const std::string& cmd){ QMutexLocker locker (&m_mtxIncrementRequests); if(m_requestsCounter.contains(cmd)){ m_requestsCounter[cmd] = m_requestsCounter[cmd]+1; }else{ m_requestsCounter[cmd] = 1; } } // --------------------------------------------------------------------- nlohmann::json EmployServerInfo::toJson(){ nlohmann::json jsonRes; foreach( std::string key, m_requestsCounter.keys()){ int count = m_requestsCounter.value(key); jsonRes[key] = count; } return jsonRes; } // --------------------------------------------------------------------- void EmployServerInfo::serverStarted(){ m_dtServerStarted = QDateTime::currentDateTimeUtc(); } // --------------------------------------------------------------------- QDateTime EmployServerInfo::getServerStart(){ return m_dtServerStarted; } // --------------------------------------------------------------------- int EmployServerInfo::countQuests(){ return m_nCountQuests; } // --------------------------------------------------------------------- int EmployServerInfo::countQuestsAttempt(){ return m_nCountQuestsAttempt; } // --------------------------------------------------------------------- int EmployServerInfo::countQuestsCompleted(){ return m_nCountQuestsCompleted; } // --------------------------------------------------------------------- void EmployServerInfo::incrementQuests(){ m_nCountQuests++; } // --------------------------------------------------------------------- void EmployServerInfo::decrementQuests(){ m_nCountQuests--; } // --------------------------------------------------------------------- void EmployServerInfo::incrementQuestsAttempt(){ m_nCountQuestsAttempt++; } // --------------------------------------------------------------------- void EmployServerInfo::incrementQuestsCompleted(){ m_nCountQuestsCompleted++; } // --------------------------------------------------------------------- nlohmann::json EmployServerInfo::developers(){ auto jsonDevelopers = nlohmann::json::array(); nlohmann::json jsonDev1; jsonDev1["name"] = "Evgenii Sopov"; jsonDev1["email"] = "mrseakg@gmail.com"; jsonDevelopers.push_back(jsonDev1); nlohmann::json jsonDev2; jsonDev2["name"] = "Igor Polyakov"; jsonDev2["email"] = "?"; jsonDevelopers.push_back(jsonDev2); nlohmann::json jsonDev3; jsonDev3["name"] = "Sergey Ushev"; jsonDev3["email"] = "?"; jsonDevelopers.push_back(jsonDev3); nlohmann::json jsonDev4; jsonDev4["name"] = "Danil Dudkin"; jsonDev4["email"] = "?"; jsonDevelopers.push_back(jsonDev4); return jsonDevelopers; } // --------------------------------------------------------------------- <commit_msg>Added mail to developer list #117 #118<commit_after>#include <employ_server_config.h> #include <employ_server_info.h> #include <employ_database.h> #include <QSqlQuery> #include <QSqlRecord> REGISTRY_EMPLOY(EmployServerInfo) // --------------------------------------------------------------------- EmployServerInfo::EmployServerInfo() : EmployBase(EmployServerInfo::name(), {EmployDatabase::name()}) { m_nCountQuests = 0; m_nCountQuestsAttempt = 0; m_nCountQuestsCompleted = 0; } // --------------------------------------------------------------------- bool EmployServerInfo::init(){ EmployDatabase *pDatabase = findEmploy<EmployDatabase>(); QSqlDatabase db = *(pDatabase->database()); QSqlQuery query(db); // count quests { QSqlQuery query(db); query.prepare("SELECT COUNT(*) cnt FROM quest"); if (!query.exec()){ Log::err(TAG, query.lastError().text()); return false; } if (query.next()) { QSqlRecord record = query.record(); m_nCountQuests = record.value("cnt").toInt(); }else{ // TODO error m_nCountQuests = 0; } } // quest attempts { QSqlQuery query(db); query.prepare("SELECT COUNT(*) cnt FROM users_quests_answers"); if (!query.exec()){ Log::err(TAG, query.lastError().text()); return false; } if (query.next()) { QSqlRecord record = query.record(); m_nCountQuestsAttempt = record.value("cnt").toInt(); }else{ // TODO error m_nCountQuestsAttempt = 0; } } // completed { QSqlQuery query(db); query.prepare("SELECT COUNT(*) cnt FROM users_quests"); if (!query.exec()){ Log::err(TAG, query.lastError().text()); return false; } if (query.next()) { QSqlRecord record = query.record(); m_nCountQuestsCompleted = record.value("cnt").toInt(); }else{ // TODO error m_nCountQuestsCompleted = 0; } } return true; } // --------------------------------------------------------------------- void EmployServerInfo::incrementRequests(const std::string& cmd){ QMutexLocker locker (&m_mtxIncrementRequests); if(m_requestsCounter.contains(cmd)){ m_requestsCounter[cmd] = m_requestsCounter[cmd]+1; }else{ m_requestsCounter[cmd] = 1; } } // --------------------------------------------------------------------- nlohmann::json EmployServerInfo::toJson(){ nlohmann::json jsonRes; foreach( std::string key, m_requestsCounter.keys()){ int count = m_requestsCounter.value(key); jsonRes[key] = count; } return jsonRes; } // --------------------------------------------------------------------- void EmployServerInfo::serverStarted(){ m_dtServerStarted = QDateTime::currentDateTimeUtc(); } // --------------------------------------------------------------------- QDateTime EmployServerInfo::getServerStart(){ return m_dtServerStarted; } // --------------------------------------------------------------------- int EmployServerInfo::countQuests(){ return m_nCountQuests; } // --------------------------------------------------------------------- int EmployServerInfo::countQuestsAttempt(){ return m_nCountQuestsAttempt; } // --------------------------------------------------------------------- int EmployServerInfo::countQuestsCompleted(){ return m_nCountQuestsCompleted; } // --------------------------------------------------------------------- void EmployServerInfo::incrementQuests(){ m_nCountQuests++; } // --------------------------------------------------------------------- void EmployServerInfo::decrementQuests(){ m_nCountQuests--; } // --------------------------------------------------------------------- void EmployServerInfo::incrementQuestsAttempt(){ m_nCountQuestsAttempt++; } // --------------------------------------------------------------------- void EmployServerInfo::incrementQuestsCompleted(){ m_nCountQuestsCompleted++; } // --------------------------------------------------------------------- nlohmann::json EmployServerInfo::developers(){ auto jsonDevelopers = nlohmann::json::array(); nlohmann::json jsonDev1; jsonDev1["name"] = "Evgenii Sopov"; jsonDev1["email"] = "mrseakg@gmail.com"; jsonDevelopers.push_back(jsonDev1); nlohmann::json jsonDev2; jsonDev2["name"] = "Igor Polyakov"; jsonDev2["email"] = "?"; jsonDevelopers.push_back(jsonDev2); nlohmann::json jsonDev3; jsonDev3["name"] = "Sergey Ushev"; jsonDev3["email"] = "sergo.moreno@gmail.com"; jsonDevelopers.push_back(jsonDev3); nlohmann::json jsonDev4; jsonDev4["name"] = "Danil Dudkin"; jsonDev4["email"] = "shikamaru740@gmail.com"; jsonDevelopers.push_back(jsonDev4); return jsonDevelopers; } // --------------------------------------------------------------------- <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //----------------------------------------------------------------- // Implementation of the ESD class // This is the class to deal with during the phisical analysis of data // This class is generated directly by the reconstruction methods // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch //----------------------------------------------------------------- #include "AliESD.h" #include "AliESDfriend.h" ClassImp(AliESD) //______________________________________________________________________________ AliESD::AliESD(): fEventNumber(0), fRunNumber(0), fTriggerMask(0), fTriggerCluster(0), fRecoVersion(0), fMagneticField(0), fZDCN1Energy(0), fZDCP1Energy(0), fZDCN2Energy(0), fZDCP2Energy(0), fZDCEMEnergy(0), fZDCParticipants(0), fT0zVertex(0), fT0timeStart(0), fPrimaryVertex(), fTracks("AliESDtrack",15000), fHLTConfMapTracks("AliESDHLTtrack",25000), fHLTHoughTracks("AliESDHLTtrack",15000), fMuonTracks("AliESDMuonTrack",30), fPmdTracks("AliESDPmdTrack",3000), fTrdTracks("AliESDTrdTrack",300), fV0s("AliESDv0",200), fCascades("AliESDcascade",20), fKinks("AliESDkink",4000), fV0MIs("AliESDV0MI",4000), fCaloClusters("AliESDCaloCluster",10000), fEMCALClusters(0), fFirstEMCALCluster(-1), fPHOSClusters(0), fFirstPHOSCluster(-1), fESDFMD(0x0) { for (Int_t i=0; i<24; i++) { fT0time[i] = 0; fT0amplitude[i] = 0; } } //______________________________________________________________________________ AliESD::~AliESD() { // // Standard destructor // fTracks.Delete(); fHLTConfMapTracks.Delete(); fHLTHoughTracks.Delete(); fMuonTracks.Delete(); fPmdTracks.Delete(); fTrdTracks.Delete(); fV0s.Delete(); fCascades.Delete(); fKinks.Delete(); fV0MIs.Delete(); fCaloClusters.Delete(); delete fESDFMD; } void AliESD::UpdateV0PIDs() { // // // Int_t nV0 = GetNumberOfV0MIs(); for (Int_t i=0;i<nV0;i++){ AliESDV0MI * v0 = GetV0MI(i); AliESDtrack* tp = GetTrack(v0->GetIndex(0)); AliESDtrack* tm = GetTrack(v0->GetIndex(1)); if (!tm || !tp){ printf("BBBUUUUUUUGGGG\n"); } Double_t pp[5],pm[5]; tp->GetESDpid(pp); tm->GetESDpid(pm); v0->UpdatePID(pp,pm); } } //______________________________________________________________________________ void AliESD::Reset() { fEventNumber=0; fRunNumber=0; fTriggerMask=0; fTriggerCluster=0; fRecoVersion=0; fMagneticField=0; fZDCN1Energy=0; fZDCP1Energy=0; fZDCN2Energy=0; fZDCP2Energy=0; fZDCEMEnergy=0; fZDCParticipants=0; fT0zVertex=0; fT0timeStart = 0; fPrimaryVertex.Reset(); fTracks.Clear(); fHLTConfMapTracks.Clear(); fHLTHoughTracks.Clear(); fMuonTracks.Clear(); fPmdTracks.Clear(); fTrdTracks.Clear(); fV0s.Clear(); fCascades.Clear(); fCaloClusters.Clear(); fEMCALClusters=0; fFirstEMCALCluster=-1; fPHOSClusters=0; fFirstPHOSCluster=-1; if (fESDFMD) fESDFMD->Clear(); } //______________________________________________________________________________ void AliESD::Print(Option_t *) const { // // Print header information of the event // printf("ESD run information\n"); printf("Event # %d Run # %d Trigger %lld Magnetic field %f \n", GetEventNumber(), GetRunNumber(), GetTriggerMask(), GetMagneticField() ); printf("Vertex: (%.4f +- %.4f, %.4f +- %.4f, %.4f +- %.4f) cm\n", fPrimaryVertex.GetXv(), fPrimaryVertex.GetXRes(), fPrimaryVertex.GetYv(), fPrimaryVertex.GetYRes(), fPrimaryVertex.GetZv(), fPrimaryVertex.GetZRes()); printf("Event from reconstruction version %d \n",fRecoVersion); printf("Number of tracks: \n"); printf(" charged %d\n", GetNumberOfTracks()); printf(" hlt CF %d\n", GetNumberOfHLTConfMapTracks()); printf(" hlt HT %d\n", GetNumberOfHLTHoughTracks()); printf(" phos %d\n", GetNumberOfPHOSClusters()); printf(" emcal %d\n", GetNumberOfEMCALClusters()); printf(" muon %d\n", GetNumberOfMuonTracks()); printf(" pmd %d\n", GetNumberOfPmdTracks()); printf(" trd %d\n", GetNumberOfTrdTracks()); printf(" v0 %d\n", GetNumberOfV0s()); printf(" cascades %d\n)", GetNumberOfCascades()); printf(" kinks %d\n)", GetNumberOfKinks()); printf(" V0MIs %d\n)", GetNumberOfV0MIs()); printf(" CaloClusters %d\n)", GetNumberOfCaloClusters()); printf(" FMD %s\n)", (fESDFMD ? "yes" : "no")); } void AliESD::SetESDfriend(const AliESDfriend *ev) { // // Attaches the complementary info to the ESD // if (!ev) return; Int_t ntrk=ev->GetNumberOfTracks(); for (Int_t i=0; i<ntrk; i++) { const AliESDfriendTrack *f=ev->GetTrack(i); GetTrack(i)->SetFriendTrack(f); } } void AliESD::GetESDfriend(AliESDfriend *ev) const { // // Extracts the complementary info from the ESD // if (!ev) return; Int_t ntrk=GetNumberOfTracks(); for (Int_t i=0; i<ntrk; i++) { const AliESDtrack *t=GetTrack(i); const AliESDfriendTrack *f=t->GetFriendTrack(); ev->AddTrack(f); } } <commit_msg>Fixing the printout<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //----------------------------------------------------------------- // Implementation of the ESD class // This is the class to deal with during the phisical analysis of data // This class is generated directly by the reconstruction methods // Origin: Iouri Belikov, CERN, Jouri.Belikov@cern.ch //----------------------------------------------------------------- #include "AliESD.h" #include "AliESDfriend.h" ClassImp(AliESD) //______________________________________________________________________________ AliESD::AliESD(): fEventNumber(0), fRunNumber(0), fTriggerMask(0), fTriggerCluster(0), fRecoVersion(0), fMagneticField(0), fZDCN1Energy(0), fZDCP1Energy(0), fZDCN2Energy(0), fZDCP2Energy(0), fZDCEMEnergy(0), fZDCParticipants(0), fT0zVertex(0), fT0timeStart(0), fPrimaryVertex(), fTracks("AliESDtrack",15000), fHLTConfMapTracks("AliESDHLTtrack",25000), fHLTHoughTracks("AliESDHLTtrack",15000), fMuonTracks("AliESDMuonTrack",30), fPmdTracks("AliESDPmdTrack",3000), fTrdTracks("AliESDTrdTrack",300), fV0s("AliESDv0",200), fCascades("AliESDcascade",20), fKinks("AliESDkink",4000), fV0MIs("AliESDV0MI",4000), fCaloClusters("AliESDCaloCluster",10000), fEMCALClusters(0), fFirstEMCALCluster(-1), fPHOSClusters(0), fFirstPHOSCluster(-1), fESDFMD(0x0) { for (Int_t i=0; i<24; i++) { fT0time[i] = 0; fT0amplitude[i] = 0; } } //______________________________________________________________________________ AliESD::~AliESD() { // // Standard destructor // fTracks.Delete(); fHLTConfMapTracks.Delete(); fHLTHoughTracks.Delete(); fMuonTracks.Delete(); fPmdTracks.Delete(); fTrdTracks.Delete(); fV0s.Delete(); fCascades.Delete(); fKinks.Delete(); fV0MIs.Delete(); fCaloClusters.Delete(); delete fESDFMD; } void AliESD::UpdateV0PIDs() { // // // Int_t nV0 = GetNumberOfV0MIs(); for (Int_t i=0;i<nV0;i++){ AliESDV0MI * v0 = GetV0MI(i); AliESDtrack* tp = GetTrack(v0->GetIndex(0)); AliESDtrack* tm = GetTrack(v0->GetIndex(1)); if (!tm || !tp){ printf("BBBUUUUUUUGGGG\n"); } Double_t pp[5],pm[5]; tp->GetESDpid(pp); tm->GetESDpid(pm); v0->UpdatePID(pp,pm); } } //______________________________________________________________________________ void AliESD::Reset() { fEventNumber=0; fRunNumber=0; fTriggerMask=0; fTriggerCluster=0; fRecoVersion=0; fMagneticField=0; fZDCN1Energy=0; fZDCP1Energy=0; fZDCN2Energy=0; fZDCP2Energy=0; fZDCEMEnergy=0; fZDCParticipants=0; fT0zVertex=0; fT0timeStart = 0; fPrimaryVertex.Reset(); fTracks.Clear(); fHLTConfMapTracks.Clear(); fHLTHoughTracks.Clear(); fMuonTracks.Clear(); fPmdTracks.Clear(); fTrdTracks.Clear(); fV0s.Clear(); fCascades.Clear(); fCaloClusters.Clear(); fEMCALClusters=0; fFirstEMCALCluster=-1; fPHOSClusters=0; fFirstPHOSCluster=-1; if (fESDFMD) fESDFMD->Clear(); } //______________________________________________________________________________ void AliESD::Print(Option_t *) const { // // Print header information of the event // printf("ESD run information\n"); printf("Event # %d Run # %d Trigger %lld Magnetic field %f \n", GetEventNumber(), GetRunNumber(), GetTriggerMask(), GetMagneticField() ); printf("Vertex: (%.4f +- %.4f, %.4f +- %.4f, %.4f +- %.4f) cm\n", fPrimaryVertex.GetXv(), fPrimaryVertex.GetXRes(), fPrimaryVertex.GetYv(), fPrimaryVertex.GetYRes(), fPrimaryVertex.GetZv(), fPrimaryVertex.GetZRes()); printf("Event from reconstruction version %d \n",fRecoVersion); printf("Number of tracks: \n"); printf(" charged %d\n", GetNumberOfTracks()); printf(" hlt CF %d\n", GetNumberOfHLTConfMapTracks()); printf(" hlt HT %d\n", GetNumberOfHLTHoughTracks()); printf(" muon %d\n", GetNumberOfMuonTracks()); printf(" pmd %d\n", GetNumberOfPmdTracks()); printf(" trd %d\n", GetNumberOfTrdTracks()); printf(" v0 %d\n", GetNumberOfV0s()); printf(" cascades %d\n", GetNumberOfCascades()); printf(" kinks %d\n", GetNumberOfKinks()); printf(" V0MIs %d\n", GetNumberOfV0MIs()); printf(" CaloClusters %d\n", GetNumberOfCaloClusters()); printf(" phos %d\n", GetNumberOfPHOSClusters()); printf(" emcal %d\n", GetNumberOfEMCALClusters()); printf(" FMD %s\n", (fESDFMD ? "yes" : "no")); } void AliESD::SetESDfriend(const AliESDfriend *ev) { // // Attaches the complementary info to the ESD // if (!ev) return; Int_t ntrk=ev->GetNumberOfTracks(); for (Int_t i=0; i<ntrk; i++) { const AliESDfriendTrack *f=ev->GetTrack(i); GetTrack(i)->SetFriendTrack(f); } } void AliESD::GetESDfriend(AliESDfriend *ev) const { // // Extracts the complementary info from the ESD // if (!ev) return; Int_t ntrk=GetNumberOfTracks(); for (Int_t i=0; i<ntrk; i++) { const AliESDtrack *t=GetTrack(i); const AliESDfriendTrack *f=t->GetFriendTrack(); ev->AddTrack(f); } } <|endoftext|>
<commit_before>#include "PositionModule.hpp" #include <assert.h> #include <ros/console.h> #include "sensor_msgs/Image.h" #include "api_application/Ping.h" #include "api_application/Announce.h" PositionModule::PositionModule(IPositionReceiver* receiver) { assert(receiver != 0); this->receiver = receiver; _isInitialized = true; isCalibrating = false; isRunning = false; ros::NodeHandle n; this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4); this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4); this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this); this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this); this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this); this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this); // Advertise myself to API ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("Announce"); api_application::Announce announce; announce.request.type = 3; // 3 means position module announce.request.initializeServiceName = std::string("InitializePositionModule"); if (announceClient.call(announce)) { rosId = announce.response.ID; if (rosId == ~0 /* -1 */) { ROS_ERROR("Error! Got id -1"); _isInitialized = false; } else { ROS_INFO("Position module successfully announced. Got id %d", rosId); } } else { ROS_ERROR("Error! Could not announce myself to API!"); _isInitialized = false; } msg = new KitrokopterMessages(rosId); if (_isInitialized) { ROS_DEBUG("PositionModule initialized."); } } PositionModule::~PositionModule() { msg->~KitrokopterMessages(); // TODO: Free picture cache. ROS_DEBUG("PositionModule destroyed."); } // Service bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res) { res.ok = !isCalibrating; if (!isCalibrating) { setPictureSendingActivated(true); } isCalibrating = true; return true; } // Service bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res) { for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++) { if (*it != 0) { // TODO: check if image is "good" sensor_msgs::Image img; img.width = 640; img.height = 480; img.step = 3 * 640; for (int i = 0; i < 640 * 480 * 3; i++) { img.data[i] = (*it)->data[i]; } res.images.push_back(img); delete *it; *it = 0; } } return true; } // Service bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res) { // TODO: Do stuff with danis code... return true; } // Topic void PositionModule::pictureCallback(const camera_application::Picture &msg) { if (isCalibrating) { // Don't know if it works that way and I really can randomly insert now... pictureCache.reserve(msg.ID + 1); pictureTimes.reserve(msg.ID + 1); if (pictureCache[msg.ID] != 0) { delete pictureCache[msg.ID]; pictureCache[msg.ID] = 0; } cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3); for (int i = 0; i < 640 * 480 * 3; i++) { image->data[i] = msg.image[i]; } pictureCache[msg.ID] = image; pictureTimes[msg.ID] = msg.timestamp; } } // Topic void PositionModule::systemCallback(const api_application::System &msg) { isRunning = msg.command == 1; } void PositionModule::setPictureSendingActivated(bool activated) { camera_application::PictureSendingActivation msg; msg.ID = rosId; msg.active = activated; pictureSendingActivationPublisher.publish(msg); } void PositionModule::sendPing() { api_application::Ping msg; msg.ID = rosId; pingPublisher.publish(msg); } bool PositionModule::isInitialized() { return _isInitialized; }<commit_msg>Made position module activate all cameras for calibration.<commit_after>#include "PositionModule.hpp" #include <assert.h> #include <ros/console.h> #include "sensor_msgs/Image.h" #include "api_application/Ping.h" #include "api_application/Announce.h" PositionModule::PositionModule(IPositionReceiver* receiver) { assert(receiver != 0); this->receiver = receiver; _isInitialized = true; isCalibrating = false; isRunning = false; ros::NodeHandle n; this->pictureSendingActivationPublisher = n.advertise<camera_application::PictureSendingActivation>("PictureSendingActivation", 4); this->pingPublisher = n.advertise<api_application::Ping>("Ping", 4); this->pictureSubscriber = n.subscribe("Picture", 128, &PositionModule::pictureCallback, this); this->startCalibrationService = n.advertiseService("StartCalibration", &PositionModule::startCalibrationCallback, this); this->takeCalibrationPictureService = n.advertiseService("TakeCalibrationPicture", &PositionModule::takeCalibrationPictureCallback, this); this->calculateCalibrationService = n.advertiseService("CalculateCalibration", &PositionModule::calculateCalibrationCallback, this); // Advertise myself to API ros::ServiceClient announceClient = n.serviceClient<api_application::Announce>("Announce"); api_application::Announce announce; announce.request.type = 3; // 3 means position module announce.request.initializeServiceName = std::string("InitializePositionModule"); if (announceClient.call(announce)) { rosId = announce.response.ID; if (rosId == ~0 /* -1 */) { ROS_ERROR("Error! Got id -1"); _isInitialized = false; } else { ROS_INFO("Position module successfully announced. Got id %d", rosId); } } else { ROS_ERROR("Error! Could not announce myself to API!"); _isInitialized = false; } msg = new KitrokopterMessages(rosId); if (_isInitialized) { ROS_DEBUG("PositionModule initialized."); } } PositionModule::~PositionModule() { msg->~KitrokopterMessages(); // TODO: Free picture cache. ROS_DEBUG("PositionModule destroyed."); } // Service bool PositionModule::startCalibrationCallback(control_application::StartCalibration::Request &req, control_application::StartCalibration::Response &res) { res.ok = !isCalibrating; if (!isCalibrating) { setPictureSendingActivated(true); } isCalibrating = true; return true; } // Service bool PositionModule::takeCalibrationPictureCallback(control_application::TakeCalibrationPicture::Request &req, control_application::TakeCalibrationPicture::Response &res) { for (std::vector<cv::Mat*>::iterator it = pictureCache.begin(); it != pictureCache.end(); it++) { if (*it != 0) { // TODO: check if image is "good" sensor_msgs::Image img; img.width = 640; img.height = 480; img.step = 3 * 640; for (int i = 0; i < 640 * 480 * 3; i++) { img.data[i] = (*it)->data[i]; } res.images.push_back(img); delete *it; *it = 0; } } return true; } // Service bool PositionModule::calculateCalibrationCallback(control_application::CalculateCalibration::Request &req, control_application::CalculateCalibration::Response &res) { // TODO: Do stuff with danis code... return true; } // Topic void PositionModule::pictureCallback(const camera_application::Picture &msg) { if (isCalibrating) { // Don't know if it works that way and I really can randomly insert now... pictureCache.reserve(msg.ID + 1); pictureTimes.reserve(msg.ID + 1); if (pictureCache[msg.ID] != 0) { delete pictureCache[msg.ID]; pictureCache[msg.ID] = 0; } cv::Mat* image = new cv::Mat(cv::Size(640, 480), CV_8UC3); for (int i = 0; i < 640 * 480 * 3; i++) { image->data[i] = msg.image[i]; } pictureCache[msg.ID] = image; pictureTimes[msg.ID] = msg.timestamp; } } // Topic void PositionModule::systemCallback(const api_application::System &msg) { isRunning = msg.command == 1; } void PositionModule::setPictureSendingActivated(bool activated) { camera_application::PictureSendingActivation msg; msg.ID = 0; msg.active = activated; pictureSendingActivationPublisher.publish(msg); } void PositionModule::sendPing() { api_application::Ping msg; msg.ID = rosId; pingPublisher.publish(msg); } bool PositionModule::isInitialized() { return _isInitialized; }<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include "opencv2/core.hpp" #include <opencv2/core/utility.hpp> #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include "opencv2/video.hpp" #include "opencv2/cudaoptflow.hpp" #include "opencv2/cudaimgproc.hpp" using namespace std; using namespace cv; using namespace cv::cuda; static void download(const GpuMat& d_mat, vector<Point2f>& vec) { vec.resize(d_mat.cols); Mat mat(1, d_mat.cols, CV_32FC2, (void*)&vec[0]); d_mat.download(mat); } static void download(const GpuMat& d_mat, vector<uchar>& vec) { vec.resize(d_mat.cols); Mat mat(1, d_mat.cols, CV_8UC1, (void*)&vec[0]); d_mat.download(mat); } static void drawArrows(Mat& frame, const vector<Point2f>& prevPts, const vector<Point2f>& nextPts, const vector<uchar>& status, Scalar line_color = Scalar(0, 0, 255)) { for (size_t i = 0; i < prevPts.size(); ++i) { if (status[i]) { int line_thickness = 1; Point p = prevPts[i]; Point q = nextPts[i]; double angle = atan2((double) p.y - q.y, (double) p.x - q.x); double hypotenuse = sqrt( (double)(p.y - q.y)*(p.y - q.y) + (double)(p.x - q.x)*(p.x - q.x) ); if (hypotenuse < 1.0) continue; // Here we lengthen the arrow by a factor of three. q.x = (int) (p.x - 3 * hypotenuse * cos(angle)); q.y = (int) (p.y - 3 * hypotenuse * sin(angle)); // Now we draw the main line of the arrow. line(frame, p, q, line_color, line_thickness); // Now draw the tips of the arrow. I do some scaling so that the // tips look proportional to the main line of the arrow. p.x = (int) (q.x + 9 * cos(angle + CV_PI / 4)); p.y = (int) (q.y + 9 * sin(angle + CV_PI / 4)); line(frame, p, q, line_color, line_thickness); p.x = (int) (q.x + 9 * cos(angle - CV_PI / 4)); p.y = (int) (q.y + 9 * sin(angle - CV_PI / 4)); line(frame, p, q, line_color, line_thickness); } } } template <typename T> inline T clamp (T x, T a, T b) { return ((x) > (a) ? ((x) < (b) ? (x) : (b)) : (a)); } template <typename T> inline T mapValue(T x, T a, T b, T c, T d) { x = clamp(x, a, b); return c + (d - c) * (x - a) / (b - a); } static void getFlowField(const Mat& u, const Mat& v, Mat& flowField) { float maxDisplacement = 1.0f; for (int i = 0; i < u.rows; ++i) { const float* ptr_u = u.ptr<float>(i); const float* ptr_v = v.ptr<float>(i); for (int j = 0; j < u.cols; ++j) { float d = max(fabsf(ptr_u[j]), fabsf(ptr_v[j])); if (d > maxDisplacement) maxDisplacement = d; } } flowField.create(u.size(), CV_8UC4); for (int i = 0; i < flowField.rows; ++i) { const float* ptr_u = u.ptr<float>(i); const float* ptr_v = v.ptr<float>(i); Vec4b* row = flowField.ptr<Vec4b>(i); for (int j = 0; j < flowField.cols; ++j) { row[j][0] = 0; row[j][1] = static_cast<unsigned char> (mapValue (-ptr_v[j], -maxDisplacement, maxDisplacement, 0.0f, 255.0f)); row[j][2] = static_cast<unsigned char> (mapValue ( ptr_u[j], -maxDisplacement, maxDisplacement, 0.0f, 255.0f)); row[j][3] = 255; } } } int main(int argc, const char* argv[]) { const char* keys = "{ h help | | print help message }" "{ l left | ../data/pic1.png | specify left image }" "{ r right | ../data/pic2.png | specify right image }" "{ gray | | use grayscale sources [PyrLK Sparse] }" "{ win_size | 21 | specify windows size [PyrLK] }" "{ max_level | 3 | specify max level [PyrLK] }" "{ iters | 30 | specify iterations count [PyrLK] }" "{ points | 4000 | specify points count [GoodFeatureToTrack] }" "{ min_dist | 0 | specify minimal distance between points [GoodFeatureToTrack] }"; CommandLineParser cmd(argc, argv, keys); if (cmd.has("help") || !cmd.check()) { cmd.printMessage(); cmd.printErrors(); return 0; } string fname0 = cmd.get<string>("left"); string fname1 = cmd.get<string>("right"); if (fname0.empty() || fname1.empty()) { cerr << "Missing input file names" << endl; return -1; } bool useGray = cmd.has("gray"); int winSize = cmd.get<int>("win_size"); int maxLevel = cmd.get<int>("max_level"); int iters = cmd.get<int>("iters"); int points = cmd.get<int>("points"); double minDist = cmd.get<double>("min_dist"); Mat frame0 = imread(fname0); Mat frame1 = imread(fname1); if (frame0.empty() || frame1.empty()) { cout << "Can't load input images" << endl; return -1; } namedWindow("PyrLK [Sparse]", WINDOW_NORMAL); namedWindow("PyrLK [Dense] Flow Field", WINDOW_NORMAL); cout << "Image size : " << frame0.cols << " x " << frame0.rows << endl; cout << "Points count : " << points << endl; cout << endl; Mat frame0Gray; cv::cvtColor(frame0, frame0Gray, COLOR_BGR2GRAY); Mat frame1Gray; cv::cvtColor(frame1, frame1Gray, COLOR_BGR2GRAY); // goodFeaturesToTrack GpuMat d_frame0Gray(frame0Gray); GpuMat d_prevPts; Ptr<cuda::CornersDetector> detector = cuda::createGoodFeaturesToTrackDetector(d_frame0Gray.type(), points, 0.01, minDist); detector->detect(d_frame0Gray, d_prevPts); // Sparse Ptr<cuda::SparsePyrLKOpticalFlow> d_pyrLK = cuda::SparsePyrLKOpticalFlow::create( Size(winSize, winSize), maxLevel, iters); GpuMat d_frame0(frame0); GpuMat d_frame1(frame1); GpuMat d_frame1Gray(frame1Gray); GpuMat d_nextPts; GpuMat d_status; d_pyrLK->calc(useGray ? d_frame0Gray : d_frame0, useGray ? d_frame1Gray : d_frame1, d_prevPts, d_nextPts, d_status); // Draw arrows vector<Point2f> prevPts(d_prevPts.cols); download(d_prevPts, prevPts); vector<Point2f> nextPts(d_nextPts.cols); download(d_nextPts, nextPts); vector<uchar> status(d_status.cols); download(d_status, status); drawArrows(frame0, prevPts, nextPts, status, Scalar(255, 0, 0)); imshow("PyrLK [Sparse]", frame0); waitKey(); return 0; } <commit_msg>remove unused function from pyrlk_optical_flow sample<commit_after>#include <iostream> #include <vector> #include "opencv2/core.hpp" #include <opencv2/core/utility.hpp> #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include "opencv2/video.hpp" #include "opencv2/cudaoptflow.hpp" #include "opencv2/cudaimgproc.hpp" using namespace std; using namespace cv; using namespace cv::cuda; static void download(const GpuMat& d_mat, vector<Point2f>& vec) { vec.resize(d_mat.cols); Mat mat(1, d_mat.cols, CV_32FC2, (void*)&vec[0]); d_mat.download(mat); } static void download(const GpuMat& d_mat, vector<uchar>& vec) { vec.resize(d_mat.cols); Mat mat(1, d_mat.cols, CV_8UC1, (void*)&vec[0]); d_mat.download(mat); } static void drawArrows(Mat& frame, const vector<Point2f>& prevPts, const vector<Point2f>& nextPts, const vector<uchar>& status, Scalar line_color = Scalar(0, 0, 255)) { for (size_t i = 0; i < prevPts.size(); ++i) { if (status[i]) { int line_thickness = 1; Point p = prevPts[i]; Point q = nextPts[i]; double angle = atan2((double) p.y - q.y, (double) p.x - q.x); double hypotenuse = sqrt( (double)(p.y - q.y)*(p.y - q.y) + (double)(p.x - q.x)*(p.x - q.x) ); if (hypotenuse < 1.0) continue; // Here we lengthen the arrow by a factor of three. q.x = (int) (p.x - 3 * hypotenuse * cos(angle)); q.y = (int) (p.y - 3 * hypotenuse * sin(angle)); // Now we draw the main line of the arrow. line(frame, p, q, line_color, line_thickness); // Now draw the tips of the arrow. I do some scaling so that the // tips look proportional to the main line of the arrow. p.x = (int) (q.x + 9 * cos(angle + CV_PI / 4)); p.y = (int) (q.y + 9 * sin(angle + CV_PI / 4)); line(frame, p, q, line_color, line_thickness); p.x = (int) (q.x + 9 * cos(angle - CV_PI / 4)); p.y = (int) (q.y + 9 * sin(angle - CV_PI / 4)); line(frame, p, q, line_color, line_thickness); } } } template <typename T> inline T clamp (T x, T a, T b) { return ((x) > (a) ? ((x) < (b) ? (x) : (b)) : (a)); } template <typename T> inline T mapValue(T x, T a, T b, T c, T d) { x = clamp(x, a, b); return c + (d - c) * (x - a) / (b - a); } int main(int argc, const char* argv[]) { const char* keys = "{ h help | | print help message }" "{ l left | ../data/pic1.png | specify left image }" "{ r right | ../data/pic2.png | specify right image }" "{ gray | | use grayscale sources [PyrLK Sparse] }" "{ win_size | 21 | specify windows size [PyrLK] }" "{ max_level | 3 | specify max level [PyrLK] }" "{ iters | 30 | specify iterations count [PyrLK] }" "{ points | 4000 | specify points count [GoodFeatureToTrack] }" "{ min_dist | 0 | specify minimal distance between points [GoodFeatureToTrack] }"; CommandLineParser cmd(argc, argv, keys); if (cmd.has("help") || !cmd.check()) { cmd.printMessage(); cmd.printErrors(); return 0; } string fname0 = cmd.get<string>("left"); string fname1 = cmd.get<string>("right"); if (fname0.empty() || fname1.empty()) { cerr << "Missing input file names" << endl; return -1; } bool useGray = cmd.has("gray"); int winSize = cmd.get<int>("win_size"); int maxLevel = cmd.get<int>("max_level"); int iters = cmd.get<int>("iters"); int points = cmd.get<int>("points"); double minDist = cmd.get<double>("min_dist"); Mat frame0 = imread(fname0); Mat frame1 = imread(fname1); if (frame0.empty() || frame1.empty()) { cout << "Can't load input images" << endl; return -1; } namedWindow("PyrLK [Sparse]", WINDOW_NORMAL); namedWindow("PyrLK [Dense] Flow Field", WINDOW_NORMAL); cout << "Image size : " << frame0.cols << " x " << frame0.rows << endl; cout << "Points count : " << points << endl; cout << endl; Mat frame0Gray; cv::cvtColor(frame0, frame0Gray, COLOR_BGR2GRAY); Mat frame1Gray; cv::cvtColor(frame1, frame1Gray, COLOR_BGR2GRAY); // goodFeaturesToTrack GpuMat d_frame0Gray(frame0Gray); GpuMat d_prevPts; Ptr<cuda::CornersDetector> detector = cuda::createGoodFeaturesToTrackDetector(d_frame0Gray.type(), points, 0.01, minDist); detector->detect(d_frame0Gray, d_prevPts); // Sparse Ptr<cuda::SparsePyrLKOpticalFlow> d_pyrLK = cuda::SparsePyrLKOpticalFlow::create( Size(winSize, winSize), maxLevel, iters); GpuMat d_frame0(frame0); GpuMat d_frame1(frame1); GpuMat d_frame1Gray(frame1Gray); GpuMat d_nextPts; GpuMat d_status; d_pyrLK->calc(useGray ? d_frame0Gray : d_frame0, useGray ? d_frame1Gray : d_frame1, d_prevPts, d_nextPts, d_status); // Draw arrows vector<Point2f> prevPts(d_prevPts.cols); download(d_prevPts, prevPts); vector<Point2f> nextPts(d_nextPts.cols); download(d_nextPts, nextPts); vector<uchar> status(d_status.cols); download(d_status, status); drawArrows(frame0, prevPts, nextPts, status, Scalar(255, 0, 0)); imshow("PyrLK [Sparse]", frame0); waitKey(); return 0; } <|endoftext|>
<commit_before>#ifndef SCREENBUFFER_CPP #define SCREENBUFFER_CPP #include "ScreenBuffer.h" using namespace std; ScreenBuffer::ScreenBuffer(const int screenWidth, const int screenHeight): m_BufferHeight(screenHeight), m_BufferWidth(screenWidth), // Allocate the memory for the 2d array m_screenBuffer(new char *[m_BufferHeight]), // In the Terminal the height of a row is more then a field is wide, // so we have to increase the height m_window(sf::VideoMode(/*800, 600*/screenWidth * 10, (screenHeight * 10) * 2) , "Quadris SFML") { for (int i = 0; i != m_BufferHeight; i++) { m_screenBuffer[i] = new char[m_BufferWidth]; } } ScreenBuffer::~ScreenBuffer() { // Free the memory of the screenBuffer for (int i = 0; i != m_BufferHeight; i++) { delete[] m_screenBuffer[i]; } delete[] m_screenBuffer; } int ScreenBuffer::getHeight() const { return m_BufferHeight; } int ScreenBuffer::getWidth() const { return m_BufferWidth; } void ScreenBuffer::add(const int X, const int Y, const char C) { if (isInBufferArea(X, Y)) { m_screenBuffer[Y][X] = C; } } void ScreenBuffer::add(const int StartX, const int StartY, const string Text) { for (size_t x = StartX; x != StartX + Text.length(); x++) { if (isInBufferArea(x, StartY)) { m_screenBuffer[StartY][x] = Text[x - StartX]; } } } void ScreenBuffer::clear() { m_window.clear(); for (int y = 0; y != m_BufferHeight; y++) { for (int x = 0; x != m_BufferWidth; x++) { m_screenBuffer[y][x] = ' '; } } } void ScreenBuffer::drawToScreen() { m_window.display(); for (int y = 0; y != m_BufferHeight; y++) { for (int x = 0; x != m_BufferWidth; x++) { cout << m_screenBuffer[y][x]; } cout << endl; } } sf::RenderWindow * ScreenBuffer::getWindow() { return &m_window; } bool ScreenBuffer::isInBufferArea(const int X, const int Y) const { return (X >= 0 && X < m_BufferWidth && Y >= 0 && Y < m_BufferHeight); } #endif // !SCREENBUFFER_CPP <commit_msg>Add color to window clear<commit_after>#ifndef SCREENBUFFER_CPP #define SCREENBUFFER_CPP #include "ScreenBuffer.h" using namespace std; ScreenBuffer::ScreenBuffer(const int screenWidth, const int screenHeight): m_BufferHeight(screenHeight), m_BufferWidth(screenWidth), // Allocate the memory for the 2d array m_screenBuffer(new char *[m_BufferHeight]), // In the Terminal the height of a row is more then a field is wide, // so we have to increase the height m_window(sf::VideoMode(/*800, 600*/screenWidth * 10, (screenHeight * 10) * 2) , "Quadris SFML") { for (int i = 0; i != m_BufferHeight; i++) { m_screenBuffer[i] = new char[m_BufferWidth]; } } ScreenBuffer::~ScreenBuffer() { // Free the memory of the screenBuffer for (int i = 0; i != m_BufferHeight; i++) { delete[] m_screenBuffer[i]; } delete[] m_screenBuffer; } int ScreenBuffer::getHeight() const { return m_BufferHeight; } int ScreenBuffer::getWidth() const { return m_BufferWidth; } void ScreenBuffer::add(const int X, const int Y, const char C) { if (isInBufferArea(X, Y)) { m_screenBuffer[Y][X] = C; } } void ScreenBuffer::add(const int StartX, const int StartY, const string Text) { for (size_t x = StartX; x != StartX + Text.length(); x++) { if (isInBufferArea(x, StartY)) { m_screenBuffer[StartY][x] = Text[x - StartX]; } } } void ScreenBuffer::clear() { m_window.clear(sf::Color::Black); for (int y = 0; y != m_BufferHeight; y++) { for (int x = 0; x != m_BufferWidth; x++) { m_screenBuffer[y][x] = ' '; } } } void ScreenBuffer::drawToScreen() { m_window.display(); for (int y = 0; y != m_BufferHeight; y++) { for (int x = 0; x != m_BufferWidth; x++) { cout << m_screenBuffer[y][x]; } cout << endl; } } sf::RenderWindow * ScreenBuffer::getWindow() { return &m_window; } bool ScreenBuffer::isInBufferArea(const int X, const int Y) const { return (X >= 0 && X < m_BufferWidth && Y >= 0 && Y < m_BufferHeight); } #endif // !SCREENBUFFER_CPP <|endoftext|>
<commit_before>/** \file Subfields.cc * \brief Implementation of the Subfields class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2014 Universitätsbiblothek Tübingen. All rights reserved. * * 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 "Subfields.h" #include <stdexcept> #include "util.h" Subfields::Subfields(const std::string &field_data) { if (field_data.size() < 3) { indicator1_ = indicator2_ = '\0'; return; } std::string::const_iterator ch(field_data.begin()); indicator1_ = *ch++; indicator2_ = *ch++; while (ch != field_data.end()) { if (*ch != '\x1F') std::runtime_error("Expected subfield code delimiter not found! Found " + std::string(1, *ch) + " in " + field_data + " indicators: " + std::string(1, indicator1_) + ", " + std::string(1, indicator2_)); ++ch; if (ch == field_data.end()) std::runtime_error("Unexpected subfield data end while expecting a subfield code!"); const char subfield_code = *ch++; std::string subfield_data; while (ch != field_data.end() and *ch != '\x1F') subfield_data += *ch++; if (subfield_data.empty()) throw std::runtime_error("Empty subfield for code '" + std::to_string(subfield_code) + "'!"); subfield_code_to_data_map_.insert(std::make_pair(subfield_code, subfield_data)); } } bool Subfields::hasSubfieldWithValue(const char subfield_code, const std::string &value) const { for (auto code_and_value(subfield_code_to_data_map_.find(subfield_code)); code_and_value != subfield_code_to_data_map_.end() and code_and_value->first == subfield_code; ++code_and_value) { if (code_and_value->second == value) return true; } return false; } std::string Subfields::getFirstSubfieldValue(const char subfield_code) const { const auto begin_end(getIterators(subfield_code)); if (begin_end.first == begin_end.second) return ""; return begin_end.first->second; } void Subfields::replace(const char subfield_code, const std::string &old_value, const std::string &new_value) { bool found(false); const std::pair<Iterator, Iterator> begin_end(getIterators(subfield_code)); for (Iterator code_and_value(begin_end.first); code_and_value != begin_end.second; ++code_and_value) { if (code_and_value->second == old_value) { found = true; code_and_value->second = new_value; } } if (not found) throw std::runtime_error("Unexpected: tried to replace \"" + old_value + "\" with \"" + new_value + "\" in subfield '" + subfield_code + "' but did not find the original value!"); } void Subfields::erase(const char subfield_code, const std::string &value) { Iterator code_and_value(subfield_code_to_data_map_.find(subfield_code)); while (code_and_value != subfield_code_to_data_map_.end() and code_and_value->first == subfield_code) { if (code_and_value->second == value) code_and_value = subfield_code_to_data_map_.erase(code_and_value); else ++code_and_value; } } std::string Subfields::toString() const { std::string as_string; as_string += indicator1_; as_string += indicator2_; for (ConstIterator code_and_value(subfield_code_to_data_map_.begin()); code_and_value != subfield_code_to_data_map_.end(); ++code_and_value) { as_string += '\x1F'; as_string += code_and_value->first; as_string += code_and_value->second; } return as_string; } <commit_msg>We now throw an exception for error conditions instead if immediately bailing out.<commit_after>/** \file Subfields.cc * \brief Implementation of the Subfields class. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2014 Universitätsbiblothek Tübingen. All rights reserved. * * 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 "Subfields.h" #include <stdexcept> #include "util.h" Subfields::Subfields(const std::string &field_data) { if (field_data.size() < 3) { indicator1_ = indicator2_ = '\0'; return; } std::string::const_iterator ch(field_data.begin()); indicator1_ = *ch++; indicator2_ = *ch++; while (ch != field_data.end()) { if (*ch != '\x1F') std::runtime_error("in Subfields::Subfields(const std::string &): expected subfield code delimiter not found! " "Found " + std::string(1, *ch) + " in " + field_data + " indicators: " + std::string(1, indicator1_) + ", " + std::string(1, indicator2_)); ++ch; if (ch == field_data.end()) std::runtime_error("in Subfields::Subfields(const std::string &): unexpected subfield data end while expecting " "a subfield code!"); const char subfield_code = *ch++; std::string subfield_data; while (ch != field_data.end() and *ch != '\x1F') subfield_data += *ch++; if (subfield_data.empty()) throw std::runtime_error("in Subfields::Subfields(const std::string &): empty subfield for code '" + std::to_string(subfield_code) + "'!"); subfield_code_to_data_map_.insert(std::make_pair(subfield_code, subfield_data)); } } bool Subfields::hasSubfieldWithValue(const char subfield_code, const std::string &value) const { for (auto code_and_value(subfield_code_to_data_map_.find(subfield_code)); code_and_value != subfield_code_to_data_map_.end() and code_and_value->first == subfield_code; ++code_and_value) { if (code_and_value->second == value) return true; } return false; } std::string Subfields::getFirstSubfieldValue(const char subfield_code) const { const auto begin_end(getIterators(subfield_code)); if (begin_end.first == begin_end.second) return ""; return begin_end.first->second; } void Subfields::replace(const char subfield_code, const std::string &old_value, const std::string &new_value) { bool found(false); const std::pair<Iterator, Iterator> begin_end(getIterators(subfield_code)); for (Iterator code_and_value(begin_end.first); code_and_value != begin_end.second; ++code_and_value) { if (code_and_value->second == old_value) { found = true; code_and_value->second = new_value; } } if (not found) throw std::runtime_error("Unexpected: tried to replace \"" + old_value + "\" with \"" + new_value + "\" in subfield '" + subfield_code + "' but did not find the original value!"); } void Subfields::erase(const char subfield_code, const std::string &value) { Iterator code_and_value(subfield_code_to_data_map_.find(subfield_code)); while (code_and_value != subfield_code_to_data_map_.end() and code_and_value->first == subfield_code) { if (code_and_value->second == value) code_and_value = subfield_code_to_data_map_.erase(code_and_value); else ++code_and_value; } } std::string Subfields::toString() const { std::string as_string; as_string += indicator1_; as_string += indicator2_; for (ConstIterator code_and_value(subfield_code_to_data_map_.begin()); code_and_value != subfield_code_to_data_map_.end(); ++code_and_value) { as_string += '\x1F'; as_string += code_and_value->first; as_string += code_and_value->second; } return as_string; } <|endoftext|>
<commit_before>// Copyright 2013 The Flutter 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 "flutter/testing/assertions_skia.h" namespace flutter { namespace testing { std::ostream& operator<<(std::ostream& os, const SkClipOp& o) { switch (o) { case SkClipOp::kDifference: os << "ClipOpDifference"; break; case SkClipOp::kIntersect: os << "ClipOpIntersect"; break; #ifdef SK_SUPPORT_DEPRECATED_CLIPOPS case SkClipOp::kUnion_deprecated: os << "ClipOpUnion_deprecated"; break; case SkClipOp::kXOR_deprecated: os << "ClipOpXOR_deprecated"; break; case SkClipOp::kReverseDifference_deprecated: os << "ClipOpReverseDifference_deprecated"; break; case SkClipOp::kReplace_deprecated: os << "ClipOpReplace_deprectaed"; break; #else case SkClipOp::kExtraEnumNeedInternallyPleaseIgnoreWillGoAway2: os << "ClipOpReserved2"; break; case SkClipOp::kExtraEnumNeedInternallyPleaseIgnoreWillGoAway3: os << "ClipOpReserved3"; break; case SkClipOp::kExtraEnumNeedInternallyPleaseIgnoreWillGoAway4: os << "ClipOpReserved4"; break; case SkClipOp::kExtraEnumNeedInternallyPleaseIgnoreWillGoAway5: os << "ClipOpReserved5"; break; #endif } return os; } std::ostream& operator<<(std::ostream& os, const SkMatrix& m) { os << std::endl; os << "Scale X: " << m[SkMatrix::kMScaleX] << ", "; os << "Skew X: " << m[SkMatrix::kMSkewX] << ", "; os << "Trans X: " << m[SkMatrix::kMTransX] << std::endl; os << "Skew Y: " << m[SkMatrix::kMSkewY] << ", "; os << "Scale Y: " << m[SkMatrix::kMScaleY] << ", "; os << "Trans Y: " << m[SkMatrix::kMTransY] << std::endl; os << "Persp X: " << m[SkMatrix::kMPersp0] << ", "; os << "Persp Y: " << m[SkMatrix::kMPersp1] << ", "; os << "Persp Z: " << m[SkMatrix::kMPersp2]; os << std::endl; return os; } std::ostream& operator<<(std::ostream& os, const SkM44& m) { os << m.rc(0, 0) << ", " << m.rc(0, 1) << ", " << m.rc(0, 2) << ", " << m.rc(0, 3) << std::endl; os << m.rc(1, 0) << ", " << m.rc(1, 1) << ", " << m.rc(1, 2) << ", " << m.rc(1, 3) << std::endl; os << m.rc(2, 0) << ", " << m.rc(2, 1) << ", " << m.rc(2, 2) << ", " << m.rc(2, 3) << std::endl; os << m.rc(3, 0) << ", " << m.rc(3, 1) << ", " << m.rc(3, 2) << ", " << m.rc(3, 3); return os; } std::ostream& operator<<(std::ostream& os, const SkVector3& v) { return os << v.x() << ", " << v.y() << ", " << v.z(); } std::ostream& operator<<(std::ostream& os, const SkRect& r) { return os << "LTRB: " << r.fLeft << ", " << r.fTop << ", " << r.fRight << ", " << r.fBottom; } std::ostream& operator<<(std::ostream& os, const SkRRect& r) { return os << "LTRB: " << r.rect().fLeft << ", " << r.rect().fTop << ", " << r.rect().fRight << ", " << r.rect().fBottom; } std::ostream& operator<<(std::ostream& os, const SkPath& r) { return os << "Valid: " << r.isValid() << ", FillType: " << static_cast<int>(r.getFillType()) << ", Bounds: " << r.getBounds(); } std::ostream& operator<<(std::ostream& os, const SkPoint& r) { return os << "XY: " << r.fX << ", " << r.fY; } std::ostream& operator<<(std::ostream& os, const SkISize& size) { return os << size.width() << ", " << size.height(); } std::ostream& operator<<(std::ostream& os, const SkColor4f& r) { return os << r.fR << ", " << r.fG << ", " << r.fB << ", " << r.fA; } std::ostream& operator<<(std::ostream& os, const SkPaint& r) { return os << "Color: " << r.getColor4f() << ", Style: " << r.getStyle() << ", AA: " << r.isAntiAlias() << ", Shader: " << r.getShader(); } std::ostream& operator<<(std::ostream& os, const SkSamplingOptions& s) { if (s.useCubic) { return os << "CubicResampler: " << s.cubic.B << ", " << s.cubic.C; } else { return os << "Filter: " << static_cast<int>(s.filter) << ", Mipmap: " << static_cast<int>(s.mipmap); } } } // namespace testing } // namespace flutter <commit_msg>Remove references to deprecated SkClipOps (#27900)<commit_after>// Copyright 2013 The Flutter 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 "flutter/testing/assertions_skia.h" namespace flutter { namespace testing { std::ostream& operator<<(std::ostream& os, const SkClipOp& o) { switch (o) { case SkClipOp::kDifference: os << "ClipOpDifference"; break; case SkClipOp::kIntersect: os << "ClipOpIntersect"; break; default: os << "ClipOpUnknown" << static_cast<int>(o); break; } return os; } std::ostream& operator<<(std::ostream& os, const SkMatrix& m) { os << std::endl; os << "Scale X: " << m[SkMatrix::kMScaleX] << ", "; os << "Skew X: " << m[SkMatrix::kMSkewX] << ", "; os << "Trans X: " << m[SkMatrix::kMTransX] << std::endl; os << "Skew Y: " << m[SkMatrix::kMSkewY] << ", "; os << "Scale Y: " << m[SkMatrix::kMScaleY] << ", "; os << "Trans Y: " << m[SkMatrix::kMTransY] << std::endl; os << "Persp X: " << m[SkMatrix::kMPersp0] << ", "; os << "Persp Y: " << m[SkMatrix::kMPersp1] << ", "; os << "Persp Z: " << m[SkMatrix::kMPersp2]; os << std::endl; return os; } std::ostream& operator<<(std::ostream& os, const SkM44& m) { os << m.rc(0, 0) << ", " << m.rc(0, 1) << ", " << m.rc(0, 2) << ", " << m.rc(0, 3) << std::endl; os << m.rc(1, 0) << ", " << m.rc(1, 1) << ", " << m.rc(1, 2) << ", " << m.rc(1, 3) << std::endl; os << m.rc(2, 0) << ", " << m.rc(2, 1) << ", " << m.rc(2, 2) << ", " << m.rc(2, 3) << std::endl; os << m.rc(3, 0) << ", " << m.rc(3, 1) << ", " << m.rc(3, 2) << ", " << m.rc(3, 3); return os; } std::ostream& operator<<(std::ostream& os, const SkVector3& v) { return os << v.x() << ", " << v.y() << ", " << v.z(); } std::ostream& operator<<(std::ostream& os, const SkRect& r) { return os << "LTRB: " << r.fLeft << ", " << r.fTop << ", " << r.fRight << ", " << r.fBottom; } std::ostream& operator<<(std::ostream& os, const SkRRect& r) { return os << "LTRB: " << r.rect().fLeft << ", " << r.rect().fTop << ", " << r.rect().fRight << ", " << r.rect().fBottom; } std::ostream& operator<<(std::ostream& os, const SkPath& r) { return os << "Valid: " << r.isValid() << ", FillType: " << static_cast<int>(r.getFillType()) << ", Bounds: " << r.getBounds(); } std::ostream& operator<<(std::ostream& os, const SkPoint& r) { return os << "XY: " << r.fX << ", " << r.fY; } std::ostream& operator<<(std::ostream& os, const SkISize& size) { return os << size.width() << ", " << size.height(); } std::ostream& operator<<(std::ostream& os, const SkColor4f& r) { return os << r.fR << ", " << r.fG << ", " << r.fB << ", " << r.fA; } std::ostream& operator<<(std::ostream& os, const SkPaint& r) { return os << "Color: " << r.getColor4f() << ", Style: " << r.getStyle() << ", AA: " << r.isAntiAlias() << ", Shader: " << r.getShader(); } std::ostream& operator<<(std::ostream& os, const SkSamplingOptions& s) { if (s.useCubic) { return os << "CubicResampler: " << s.cubic.B << ", " << s.cubic.C; } else { return os << "Filter: " << static_cast<int>(s.filter) << ", Mipmap: " << static_cast<int>(s.mipmap); } } } // namespace testing } // namespace flutter <|endoftext|>
<commit_before>/** * This file is part of libstreamswtich, which belongs to StreamSwitch * project. * * Copyright (C) 2014 OpenSight (www.opensight.cn) * * StreamSwitch is an extensible and scalable media stream server for * multi-protocol environment. * * 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/>. **/ /** * stsw_ffmpeg_muxer.cc * FFmpegMuxer class implementation file, define its methods * FFmpegMuxer is a media file muxer based on ffmpeg libavformat * * author: OpenSight Team * date: 2015-11-25 **/ #include "stsw_ffmpeg_muxer.h" #include "stsw_log.h" #include "stsw_ffmpeg_sender_global.h" #include "parsers/stsw_stream_mux_parser.h" #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <sstream> extern "C"{ //#include <libavutil/avutil.h> #include <libavformat/avformat.h> } FFmpegMuxer::FFmpegMuxer() :fmt_ctx_(NULL), io_timeout_(0), frame_num_(0) { stream_mux_parsers_.reserve(8); //reserve for 8 streams stream_mux_parsers_.clear(); io_start_ts_.tv_nsec = 0; io_start_ts_.tv_sec = 0; base_timestamp_.tv_sec = 0; base_timestamp_.tv_usec = 0; } FFmpegMuxer::~FFmpegMuxer() { } int FFmpegMuxer::Open(const std::string &dest_url, const std::string &format, const std::string &ffmpeg_options_str, const stream_switch::StreamMetadata &metadata, unsigned long io_timeout) { using namespace stream_switch; int ret = 0; AVDictionary *format_opts = NULL; const char * format_name = NULL; SubStreamMetadataVector::const_iterator meta_it; //printf("ffmpeg_options_str:%s\n", ffmpeg_options_str.c_str()); //parse ffmpeg_options_str ret = av_dict_parse_string(&format_opts, ffmpeg_options_str.c_str(), "=", ",", 0); if(ret){ //log STDERR_LOG(LOG_LEVEL_ERR, "Failed to parse the ffmpeg_options_str:%s to av_dict(ret:%d)\n", ffmpeg_options_str.c_str(), ret); ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out1; } //av_dict_set(&format_opts, "rtsp_transport", "tcp", 0); //printf("option dict count:%d\n", av_dict_count(format_opts)); //allocate the format context if(format.size() != 0){ format_name = format.c_str(); } ret = avformat_alloc_output_context2(&fmt_ctx_, NULL, format_name, dest_url.c_str()); if(fmt_ctx_ == NULL){ //log STDERR_LOG(LOG_LEVEL_ERR, "Failed to allocate AVFormatContext structure:%s\n", av_err2str(ret)); ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out1; } //install the io interrupt callback function fmt_ctx_->interrupt_callback.callback = FFmpegMuxer::StaticIOInterruptCB; fmt_ctx_->interrupt_callback.opaque = this; io_timeout_ = io_timeout; //setup the parsers for(meta_it=metadata.sub_streams.begin(); meta_it!=metadata.sub_streams.end(); meta_it++){ StreamMuxParser *parser = NewStreamMuxParser(meta_it->codec_name); ret = parser->Init(this, (*meta_it), fmt_ctx_); if(ret){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Parser for codec (name:%s) init failed\n", meta_it->codec_name.c_str()); delete parser; ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out3; } stream_mux_parsers_.push_back(parser); } #define DUMP_AVFORMAT #ifdef DUMP_AVFORMAT STDERR_LOG(stream_switch::LOG_LEVEL_INFO, "FFmpegMuxer::Open(): avformat context is dumped below\n"); av_dump_format(fmt_ctx_, 0, dest_url.c_str(), 1); #endif // open output file if (!(fmt_ctx_->flags & AVFMT_NOFILE)) { StartIO(); ret = avio_open2(&(fmt_ctx_->pb), dest_url.c_str(), AVIO_FLAG_WRITE, &(fmt_ctx_->interrupt_callback), &format_opts); StopIO(); if (ret < 0) { STDERR_LOG(LOG_LEVEL_ERR, "Could not open output file '%s':%s\n", dest_url.c_str(), av_err2str(ret)); ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out3; } } ret = avformat_write_header(fmt_ctx_, &format_opts); if (ret < 0) { STDERR_LOG(LOG_LEVEL_ERR, "Error occurred when write header to the output file: %s\n", av_err2str(ret)); ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out4; } if(format_opts != NULL){ int no_parsed_option_num = av_dict_count(format_opts); if(no_parsed_option_num){ STDERR_LOG(stream_switch::LOG_LEVEL_WARNING, "%d options cannot be parsed by ffmpeg avformat context\n", no_parsed_option_num); } //printf("after open, option dict count:%d\n", av_dict_count(format_opts)); av_dict_free(&format_opts); format_opts = NULL; } base_timestamp_.tv_sec = 0; base_timestamp_.tv_usec = 0; frame_num_ = 0; return 0; err_out4: if (fmt_ctx_->oformat && !(fmt_ctx_->oformat->flags & AVFMT_NOFILE)) avio_closep(&fmt_ctx_->pb); err_out3: { StreamMuxParserVector::iterator it; for(it = stream_mux_parsers_.begin(); it != stream_mux_parsers_.end(); it++){ (*it)->Uninit(); delete (*it); (*it) = NULL; } stream_mux_parsers_.clear(); } //err_out2: avformat_free_context(fmt_ctx_); fmt_ctx_ = NULL; err_out1: if(format_opts != NULL){ av_dict_free(&format_opts); format_opts = NULL; } return ret; } void FFmpegMuxer::Close() { if(fmt_ctx_ == NULL){ return; } StartIO(); //flush all parser { StreamMuxParserVector::iterator it; for(it = stream_mux_parsers_.begin(); it != stream_mux_parsers_.end(); it++){ (*it)->Flush(); } } av_write_trailer(fmt_ctx_); StopIO(); //close ffmpeg format context if (fmt_ctx_->oformat && !(fmt_ctx_->oformat->flags & AVFMT_NOFILE)) avio_closep(&fmt_ctx_->pb); //uninit all parser { StreamMuxParserVector::iterator it; for(it = stream_mux_parsers_.begin(); it != stream_mux_parsers_.end(); it++){ (*it)->Uninit(); delete (*it); (*it) = NULL; } stream_mux_parsers_.clear(); } avformat_free_context(fmt_ctx_); fmt_ctx_ = NULL; } int FFmpegMuxer::WritePacket(const stream_switch::MediaFrameInfo &frame_info, const char * frame_data, size_t frame_size) { int ret = 0; const stream_switch::MediaFrameInfo * frame_info_p = &frame_info; StreamMuxParser * parser = NULL; if(fmt_ctx_ == NULL){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "FFmpegMuxer not open\n"); return -1; } if(frame_info.sub_stream_index >= stream_mux_parsers_.size()){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "sub_stream_index is over the number of parser\n"); return -1; } //get stream muxer parser parser = stream_mux_parsers_[frame_info.sub_stream_index]; for (;;) { AVPacket opkt = { 0 }; av_init_packet(&opkt); int ret = parser->Parse(frame_info_p, frame_data, frame_size, &base_timestamp_, &opkt); if (frame_info_p != NULL) { frame_info_p = NULL; } if(ret == 0){ //no pkt need to write, exit break; }if (ret < 0){ //some error ocurs in parse STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Failed to parse the media data from stream %d\n", frame_info.sub_stream_index); break; } //#define DUMP_PACKET #ifdef DUMP_PACKET { STDERR_LOG(stream_switch::LOG_LEVEL_DEBUG, "The following packet will be written to the output file\n"); av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &opkt, 0, fmt_ctx_->streams[opkt.stream_index]); } #endif StartIO(); ret = av_interleaved_write_frame(fmt_ctx_, &opkt); StopIO(); if(ret){ //some error ocurs in parse STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Failed to write pkt to the output file:%s\n", av_err2str(ret)); ret = FFMPEG_SENDER_ERR_IO; break; } frame_num_++; } return ret; } uint32_t FFmpegMuxer::frame_num() { return frame_num_; } void FFmpegMuxer::StartIO() { clock_gettime(CLOCK_MONOTONIC, &io_start_ts_); } void FFmpegMuxer::StopIO() { io_start_ts_.tv_sec = 0; io_start_ts_.tv_nsec = 0; } int FFmpegMuxer::StaticIOInterruptCB(void* user_data) { FFmpegMuxer *muxer = (FFmpegMuxer *)user_data; return muxer->IOInterruptCB(); } int FFmpegMuxer::IOInterruptCB() { if(io_start_ts_.tv_sec != 0){ struct timespec cur_ts; clock_gettime(CLOCK_MONOTONIC, &cur_ts); uint64_t io_dur = (cur_ts.tv_sec - io_start_ts_.tv_sec) * 1000 + (cur_ts.tv_nsec - io_start_ts_.tv_nsec) / 1000000; if(io_dur >= (uint64_t)io_timeout_){ return 1; } } return 0; } static std::string uint2str(unsigned int uint_value) { std::stringstream stream; stream<<uint_value; return stream.str(); } void FFmpegMuxer::GetClientInfo(const std::string &dest_url, const std::string &format, stream_switch::StreamClientInfo *client_info) { const char * protocol_name = NULL; if(client_info == NULL){ return; } //get protocol protocol_name = avio_find_protocol_name(dest_url.c_str()); if(protocol_name == NULL){ if(format.size() > 0){ protocol_name = format.c_str(); }else{ AVOutputFormat *oformat; oformat = av_guess_format(NULL, dest_url.c_str(), NULL); if (oformat!= NULL) { protocol_name = oformat->name; } }//if(format.size() > 0){ } if(protocol_name == NULL){ protocol_name = "ffmpeg"; } client_info->client_text = protocol_name; //get ip and port { char hostname[1024],proto[1024],path[1024]; int port; av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port, path, sizeof(path), dest_url.c_str()); if(port >0 && port < 65536){ client_info->client_port = port; } if (hostname[0] != 0){ client_info->client_ip = hostname; } //the url as the client text client_info->client_text = dest_url; } //the pid as the client token { pid_t pid; pid = getpid() ; client_info->client_token = uint2str((unsigned)pid); } } <commit_msg>test change name<commit_after>/** * This file is part of libstreamswtich, which belongs to StreamSwitch * project. * * Copyright (C) 2014 OpenSight (www.opensight.cn) * * StreamSwitch is an extensible and scalable media stream server for * multi-protocol environment. * * 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/>. **/ /** * stsw_ffmpeg_muxer.cc * FFmpegMuxer class implementation file, define its methods * FFmpegMuxer is a media file muxer based on ffmpeg libavformat * * author: OpenSight Team * date: 2015-11-25 **/ #include "stsw_ffmpeg_muxer.h" #include "stsw_log.h" #include "stsw_ffmpeg_sender_global.h" #include "parsers/stsw_stream_mux_parser.h" #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <sstream> extern "C"{ //#include <libavutil/avutil.h> #include <libavformat/avformat.h> } FFmpegMuxer::FFmpegMuxer() :fmt_ctx_(NULL), io_timeout_(0), frame_num_(0) { stream_mux_parsers_.reserve(8); //reserve for 8 streams stream_mux_parsers_.clear(); io_start_ts_.tv_nsec = 0; io_start_ts_.tv_sec = 0; base_timestamp_.tv_sec = 0; base_timestamp_.tv_usec = 0; } FFmpegMuxer::~FFmpegMuxer() { } int FFmpegMuxer::Open(const std::string &dest_url, const std::string &format, const std::string &ffmpeg_options_str, const stream_switch::StreamMetadata &metadata, unsigned long io_timeout) { using namespace stream_switch; int ret = 0; AVDictionary *format_opts = NULL; const char * format_name = NULL; SubStreamMetadataVector::const_iterator meta_it; //printf("ffmpeg_options_str:%s\n", ffmpeg_options_str.c_str()); //parse ffmpeg_options_str ret = av_dict_parse_string(&format_opts, ffmpeg_options_str.c_str(), "=", ",", 0); if(ret){ //log STDERR_LOG(LOG_LEVEL_ERR, "Failed to parse the ffmpeg_options_str:%s to av_dict(ret:%d)\n", ffmpeg_options_str.c_str(), ret); ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out1; } //av_dict_set(&format_opts, "rtsp_transport", "tcp", 0); //printf("option dict count:%d\n", av_dict_count(format_opts)); //allocate the format context if(format.size() != 0){ format_name = format.c_str(); } ret = avformat_alloc_output_context2(&fmt_ctx_, NULL, format_name, dest_url.c_str()); if(fmt_ctx_ == NULL){ //log STDERR_LOG(LOG_LEVEL_ERR, "Failed to allocate AVFormatContext structure:%s\n", av_err2str(ret)); ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out1; } //install the io interrupt callback function fmt_ctx_->interrupt_callback.callback = FFmpegMuxer::StaticIOInterruptCB; fmt_ctx_->interrupt_callback.opaque = this; io_timeout_ = io_timeout; //setup the parsers for(meta_it=metadata.sub_streams.begin(); meta_it!=metadata.sub_streams.end(); meta_it++){ StreamMuxParser *parser = NewStreamMuxParser(meta_it->codec_name); ret = parser->Init(this, (*meta_it), fmt_ctx_); if(ret){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Parser for codec (name:%s) init failed\n", meta_it->codec_name.c_str()); delete parser; ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out3; } stream_mux_parsers_.push_back(parser); } #define DUMP_AVFORMAT #ifdef DUMP_AVFORMAT STDERR_LOG(stream_switch::LOG_LEVEL_INFO, "FFmpegMuxer::Open(): avformat context is dumped below\n"); av_dump_format(fmt_ctx_, 0, dest_url.c_str(), 1); #endif // open output file if (!(fmt_ctx_->flags & AVFMT_NOFILE)) { StartIO(); ret = avio_open2(&(fmt_ctx_->pb), dest_url.c_str(), AVIO_FLAG_WRITE, &(fmt_ctx_->interrupt_callback), &format_opts); StopIO(); if (ret < 0) { STDERR_LOG(LOG_LEVEL_ERR, "Could not open output file '%s':%s\n", dest_url.c_str(), av_err2str(ret)); ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out3; } } ret = avformat_write_header(fmt_ctx_, &format_opts); if (ret < 0) { STDERR_LOG(LOG_LEVEL_ERR, "Error occurred when write header to the output file: %s\n", av_err2str(ret)); ret = FFMPEG_SENDER_ERR_GENERAL; goto err_out4; } if(format_opts != NULL){ int no_parsed_option_num = av_dict_count(format_opts); if(no_parsed_option_num){ STDERR_LOG(stream_switch::LOG_LEVEL_WARNING, "%d options cannot be parsed by ffmpeg avformat context\n", no_parsed_option_num); } //printf("after open, option dict count:%d\n", av_dict_count(format_opts)); av_dict_free(&format_opts); format_opts = NULL; } base_timestamp_.tv_sec = 0; base_timestamp_.tv_usec = 0; frame_num_ = 0; return 0; err_out4: if (fmt_ctx_->oformat && !(fmt_ctx_->oformat->flags & AVFMT_NOFILE)) avio_closep(&fmt_ctx_->pb); err_out3: { StreamMuxParserVector::iterator it; for(it = stream_mux_parsers_.begin(); it != stream_mux_parsers_.end(); it++){ (*it)->Uninit(); delete (*it); (*it) = NULL; } stream_mux_parsers_.clear(); } //err_out2: avformat_free_context(fmt_ctx_); fmt_ctx_ = NULL; err_out1: if(format_opts != NULL){ av_dict_free(&format_opts); format_opts = NULL; } return ret; } void FFmpegMuxer::Close() { if(fmt_ctx_ == NULL){ return; } StartIO(); //flush all parser { StreamMuxParserVector::iterator it; for(it = stream_mux_parsers_.begin(); it != stream_mux_parsers_.end(); it++){ (*it)->Flush(); } } av_write_trailer(fmt_ctx_); StopIO(); //close ffmpeg format context if (fmt_ctx_->oformat && !(fmt_ctx_->oformat->flags & AVFMT_NOFILE)) avio_closep(&fmt_ctx_->pb); //uninit all parser { StreamMuxParserVector::iterator it; for(it = stream_mux_parsers_.begin(); it != stream_mux_parsers_.end(); it++){ (*it)->Uninit(); delete (*it); (*it) = NULL; } stream_mux_parsers_.clear(); } avformat_free_context(fmt_ctx_); fmt_ctx_ = NULL; } int FFmpegMuxer::WritePacket(const stream_switch::MediaFrameInfo &frame_info, const char * frame_data, size_t frame_size) { int ret = 0; const stream_switch::MediaFrameInfo * frame_info_p = &frame_info; StreamMuxParser * parser = NULL; if(fmt_ctx_ == NULL){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "FFmpegMuxer not open\n"); return -1; } if(frame_info.sub_stream_index >= stream_mux_parsers_.size()){ STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "sub_stream_index is over the number of parser\n"); return -1; } //get stream muxer parser parser = stream_mux_parsers_[frame_info.sub_stream_index]; for (;;) { AVPacket opkt = { 0 }; av_init_packet(&opkt); int ret = parser->Parse(frame_info_p, frame_data, frame_size, &base_timestamp_, &opkt); if (frame_info_p != NULL) { frame_info_p = NULL; } if(ret == 0){ //no pkt need to write, exit break; }if (ret < 0){ //some error ocurs in parse STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Failed to parse the media data from stream %d\n", frame_info.sub_stream_index); break; } //#define DUMP_PACKET #ifdef DUMP_PACKET { STDERR_LOG(stream_switch::LOG_LEVEL_DEBUG, "The following packet will be written to the output file\n"); av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &opkt, 0, fmt_ctx_->streams[opkt.stream_index]); } #endif StartIO(); ret = av_interleaved_write_frame(fmt_ctx_, &opkt); StopIO(); if(ret){ //some error ocurs in parse STDERR_LOG(stream_switch::LOG_LEVEL_ERR, "Failed to write pkt to the output file:%s\n", av_err2str(ret)); ret = FFMPEG_SENDER_ERR_IO; break; } frame_num_++; } return ret; } uint32_t FFmpegMuxer::frame_num() { return frame_num_; } void FFmpegMuxer::StartIO() { clock_gettime(CLOCK_MONOTONIC, &io_start_ts_); } void FFmpegMuxer::StopIO() { io_start_ts_.tv_sec = 0; io_start_ts_.tv_nsec = 0; } int FFmpegMuxer::StaticIOInterruptCB(void* user_data) { FFmpegMuxer *muxer = (FFmpegMuxer *)user_data; return muxer->IOInterruptCB(); } int FFmpegMuxer::IOInterruptCB() { if(io_start_ts_.tv_sec != 0){ struct timespec cur_ts; clock_gettime(CLOCK_MONOTONIC, &cur_ts); uint64_t io_dur = (cur_ts.tv_sec - io_start_ts_.tv_sec) * 1000 + (cur_ts.tv_nsec - io_start_ts_.tv_nsec) / 1000000; if(io_dur >= (uint64_t)io_timeout_){ return 1; } } return 0; } static std::string uint2str(unsigned int uint_value) { std::stringstream stream; stream<<uint_value; return stream.str(); } void FFmpegMuxer::GetClientInfo(const std::string &dest_url, const std::string &format, stream_switch::StreamClientInfo *client_info) { const char * protocol_name = NULL; if(client_info == NULL){ return; } //get protocol protocol_name = avio_find_protocol_name(dest_url.c_str()); if(protocol_name == NULL){ if(format.size() > 0){ protocol_name = format.c_str(); }else{ AVOutputFormat *oformat; oformat = av_guess_format(NULL, dest_url.c_str(), NULL); if (oformat!= NULL) { protocol_name = oformat->name; } }//if(format.size() > 0){ } if(protocol_name == NULL){ protocol_name = "ffmpeg"; } client_info->client_text = protocol_name; //get ip and port { char hostname[1024],proto[1024],path[1024]; int port; av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port, path, sizeof(path), dest_url.c_str()); if(port >0 && port < 65536){ client_info->client_port = port; } if (hostname[0] != 0){ client_info->client_ip = hostname; } //the url as the client text client_info->client_text = dest_url; } //the pid as the client token { pid_t pid; pid = getpid() ; client_info->client_token = uint2str((unsigned)pid); } } <|endoftext|>
<commit_before>/** \file mysql_schema_diff.cc * \brief A tool for comparing a sql file with create table statements against an existing database, using mysqldiff. * \author Mario Trojan (mario.trojan@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * 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 <iostream> #include "DbConnection.h" #include "ExecUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " username password db_name sql_file\n"; std::exit(EXIT_FAILURE); } void CleanupTemporaryDatabase(DbConnection &db_connection, const std::string &database_name_temporary) { if (db_connection.mySQLDatabaseExists(database_name_temporary)) db_connection.mySQLDropDatabase(database_name_temporary); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 5) Usage(); const std::string MYSQLDIFF_EXECUTABLE(ExecUtil::Which("mysqldiff")); if (MYSQLDIFF_EXECUTABLE.empty()) LOG_ERROR("Dependency \"mysqldiff\" is missing, please install \"mysql-utilities\"-package first!"); const std::string user(argv[1]); const std::string passwd(argv[2]); const std::string database_name(argv[3]); const std::string sql_file(argv[4]); const std::string host("localhost"); const std::string port("3306"); const std::string database_name_temporary(database_name + "_tempdiff"); DbConnection db_connection(database_name, user, passwd); CleanupTemporaryDatabase(db_connection, database_name_temporary); db_connection.mySQLCreateDatabase(database_name_temporary); DbConnection::MySQLImportFile(sql_file, database_name_temporary, user, passwd); return ExecUtil::Exec(MYSQLDIFF_EXECUTABLE, { "--force", "--server1=" + user + ":" + passwd + "@" + host + ":" + port, database_name + ":" + database_name_temporary }); } <commit_msg>mysql_schema_diff: Cleanup after diff<commit_after>/** \file mysql_schema_diff.cc * \brief A tool for comparing a sql file with create table statements against an existing database, using mysqldiff. * \author Mario Trojan (mario.trojan@uni-tuebingen.de) * * \copyright 2019 Universitätsbibliothek Tübingen. All rights reserved. * * 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 <iostream> #include "DbConnection.h" #include "ExecUtil.h" #include "util.h" namespace { [[noreturn]] void Usage() { std::cerr << "Usage: " << ::progname << " username password db_name sql_file\n"; std::exit(EXIT_FAILURE); } void CleanupTemporaryDatabase(DbConnection &db_connection, const std::string &database_name_temporary) { if (db_connection.mySQLDatabaseExists(database_name_temporary)) db_connection.mySQLDropDatabase(database_name_temporary); } } // unnamed namespace int Main(int argc, char *argv[]) { if (argc != 5) Usage(); const std::string MYSQLDIFF_EXECUTABLE(ExecUtil::Which("mysqldiff")); if (MYSQLDIFF_EXECUTABLE.empty()) LOG_ERROR("Dependency \"mysqldiff\" is missing, please install \"mysql-utilities\"-package first!"); const std::string user(argv[1]); const std::string passwd(argv[2]); const std::string database_name(argv[3]); const std::string sql_file(argv[4]); const std::string host("localhost"); const std::string port("3306"); const std::string database_name_temporary(database_name + "_tempdiff"); DbConnection db_connection(database_name, user, passwd); CleanupTemporaryDatabase(db_connection, database_name_temporary); db_connection.mySQLCreateDatabase(database_name_temporary); DbConnection::MySQLImportFile(sql_file, database_name_temporary, user, passwd); int exec_result(ExecUtil::Exec(MYSQLDIFF_EXECUTABLE, { "--force", "--server1=" + user + ":" + passwd + "@" + host + ":" + port, database_name + ":" + database_name_temporary })); CleanupTemporaryDatabase(db_connection, database_name_temporary); return exec_result; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: frmbase.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: dr $ $Date: 2001-02-06 16:16:27 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop #include "formel.hxx" _ScRangeList::~_ScRangeList() { ScRange* p = ( ScRange* ) First(); while( p ) { delete p; p = ( ScRange* ) Next(); } } _ScRangeListTabs::_ScRangeListTabs( void ) { ppTabLists = new _ScRangeList*[ MAXTAB + 1 ]; for( UINT16 n = 0 ; n <= MAXTAB ; n++ ) ppTabLists[ n ] = NULL; bHasRanges = FALSE; pAct = NULL; nAct = 0; } _ScRangeListTabs::~_ScRangeListTabs() { if( bHasRanges ) { for( UINT16 n = 0 ; n <= MAXTAB ; n++ ) { if( ppTabLists[ n ] ) delete ppTabLists[ n ]; } } delete[] ppTabLists; } void _ScRangeListTabs::Append( SingleRefData a, const BOOL b ) { if( b ) { if( a.nTab > MAXTAB ) a.nTab = MAXTAB; if( a.nCol > MAXCOL ) a.nCol = MAXCOL; if( a.nRow > MAXROW ) a.nRow = MAXROW; } else { DBG_ASSERT( a.nTab <= MAXTAB, "-_ScRangeListTabs::Append(): Luegen haben kurze Abstuerze!" ); } bHasRanges = TRUE; _ScRangeList* p = ppTabLists[ a.nTab ]; if( !p ) p = ppTabLists[ a.nTab ] = new _ScRangeList; p->Append( a ); } void _ScRangeListTabs::Append( ComplRefData a, const BOOL b ) { if( b ) { INT16& rTab = a.Ref1.nTab; if( rTab > MAXTAB ) rTab = MAXTAB; else if( rTab < 0 ) rTab = 0; INT16& rCol1 = a.Ref1.nCol; if( rCol1 > MAXCOL ) rCol1 = MAXCOL; else if( rCol1 < 0 ) rCol1 = 0; INT16& rRow1 = a.Ref1.nRow; if( rRow1 > MAXROW ) rRow1 = MAXROW; else if( rRow1 < 0 ) rRow1 = 0; INT16& rCol2 = a.Ref2.nCol; if( rCol2 > MAXCOL ) rCol2 = MAXCOL; else if( rCol2 < 0 ) rCol2 = 0; INT16& rRow2 = a.Ref2.nRow; if( rRow2 > MAXROW ) rRow2 = MAXROW; else if( rRow2 < 0 ) rRow2 = 0; } else { DBG_ASSERT( a.Ref1.nTab <= MAXTAB, "-_ScRangeListTabs::Append(): Luegen haben kurze Abstuerze!" ); DBG_ASSERT( a.Ref1.nTab == a.Ref2.nTab, "+_ScRangeListTabs::Append(): 3D-Ranges werden in SC nicht unterstuetzt!" ); } bHasRanges = TRUE; _ScRangeList* p = ppTabLists[ a.Ref1.nTab ]; if( !p ) p = ppTabLists[ a.Ref1.nTab ] = new _ScRangeList; p->Append( a ); } const ScRange* _ScRangeListTabs::First( const UINT16 n ) { DBG_ASSERT( n <= MAXTAB, "-_ScRangeListTabs::First(): Und tschuessssssss!" ); if( ppTabLists[ n ] ) { pAct = ppTabLists[ n ]; nAct = n; return pAct->First(); } else { pAct = NULL; nAct = 0; return NULL; } } const ScRange* _ScRangeListTabs::Next( void ) { if( pAct ) return pAct->Next(); else return NULL; } ConverterBase::ConverterBase( UINT16 nNewBuffer ) : aPool(), aStack(), aEingPos( 0, 0, 0 ), nBufferSize( nNewBuffer ), eStatus( ConvOK ) { DBG_ASSERT( nNewBuffer > 0, "ConverterBase::ConverterBase - nNewBuffer == 0!" ); pBuffer = new sal_Char[ nNewBuffer ]; } ConverterBase::~ConverterBase() { delete[] pBuffer; } void ConverterBase::Reset() { eStatus = ConvOK; aPool.Reset(); aStack.Reset(); } ExcelConverterBase::ExcelConverterBase( XclImpStream &rStr, UINT16 nNewBuffer ) : ConverterBase( nNewBuffer ), aIn( rStr ) { } ExcelConverterBase::~ExcelConverterBase() { } void ExcelConverterBase::Reset( ScAddress aNewEingPos ) { ConverterBase::Reset(); aEingPos = aNewEingPos; } void ExcelConverterBase::Reset() { ConverterBase::Reset(); aEingPos.Set( 0, 0, 0 ); } LotusConverterBase::LotusConverterBase( SvStream &rStr, UINT16 nNewBuffer ) : ConverterBase( nNewBuffer ), aIn( rStr ), nBytesLeft( 0 ) { } LotusConverterBase::~LotusConverterBase() { } void LotusConverterBase::Reset( INT32 nLen, ScAddress aNewEingPos ) { ConverterBase::Reset(); nBytesLeft = nLen; aEingPos = aNewEingPos; } void LotusConverterBase::Reset( INT32 nLen ) { ConverterBase::Reset(); nBytesLeft = nLen; aEingPos.Set( 0, 0, 0 ); } void LotusConverterBase::Reset( ScAddress aNewEingPos ) { ConverterBase::Reset(); nBytesLeft = 0; aEingPos = aNewEingPos; } <commit_msg>#96263# loop on sheet range 0x0-0xFFFF<commit_after>/************************************************************************* * * $RCSfile: frmbase.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: dr $ $Date: 2002-01-08 07:23:24 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop #include "formel.hxx" _ScRangeList::~_ScRangeList() { ScRange* p = ( ScRange* ) First(); while( p ) { delete p; p = ( ScRange* ) Next(); } } _ScRangeListTabs::_ScRangeListTabs( void ) { ppTabLists = new _ScRangeList*[ MAXTAB + 1 ]; for( UINT16 n = 0 ; n <= MAXTAB ; n++ ) ppTabLists[ n ] = NULL; bHasRanges = FALSE; pAct = NULL; nAct = 0; } _ScRangeListTabs::~_ScRangeListTabs() { if( bHasRanges ) { for( UINT16 n = 0 ; n <= MAXTAB ; n++ ) { if( ppTabLists[ n ] ) delete ppTabLists[ n ]; } } delete[] ppTabLists; } void _ScRangeListTabs::Append( SingleRefData a, const BOOL b ) { if( b ) { if( a.nTab > MAXTAB ) a.nTab = MAXTAB; if( a.nCol > MAXCOL ) a.nCol = MAXCOL; if( a.nRow > MAXROW ) a.nRow = MAXROW; } else { DBG_ASSERT( a.nTab <= MAXTAB, "-_ScRangeListTabs::Append(): Luegen haben kurze Abstuerze!" ); } bHasRanges = TRUE; _ScRangeList* p = ppTabLists[ a.nTab ]; if( !p ) p = ppTabLists[ a.nTab ] = new _ScRangeList; p->Append( a ); } void _ScRangeListTabs::Append( ComplRefData a, const BOOL b ) { if( b ) { // #96263# ignore 3D ranges if( a.Ref1.nTab != a.Ref2.nTab ) return; INT16& rTab = a.Ref1.nTab; if( rTab > MAXTAB ) rTab = MAXTAB; else if( rTab < 0 ) rTab = 0; INT16& rCol1 = a.Ref1.nCol; if( rCol1 > MAXCOL ) rCol1 = MAXCOL; else if( rCol1 < 0 ) rCol1 = 0; INT16& rRow1 = a.Ref1.nRow; if( rRow1 > MAXROW ) rRow1 = MAXROW; else if( rRow1 < 0 ) rRow1 = 0; INT16& rCol2 = a.Ref2.nCol; if( rCol2 > MAXCOL ) rCol2 = MAXCOL; else if( rCol2 < 0 ) rCol2 = 0; INT16& rRow2 = a.Ref2.nRow; if( rRow2 > MAXROW ) rRow2 = MAXROW; else if( rRow2 < 0 ) rRow2 = 0; } else { DBG_ASSERT( a.Ref1.nTab <= MAXTAB, "-_ScRangeListTabs::Append(): Luegen haben kurze Abstuerze!" ); DBG_ASSERT( a.Ref1.nTab == a.Ref2.nTab, "+_ScRangeListTabs::Append(): 3D-Ranges werden in SC nicht unterstuetzt!" ); } bHasRanges = TRUE; _ScRangeList* p = ppTabLists[ a.Ref1.nTab ]; if( !p ) p = ppTabLists[ a.Ref1.nTab ] = new _ScRangeList; p->Append( a ); } const ScRange* _ScRangeListTabs::First( const UINT16 n ) { DBG_ASSERT( n <= MAXTAB, "-_ScRangeListTabs::First(): Und tschuessssssss!" ); if( ppTabLists[ n ] ) { pAct = ppTabLists[ n ]; nAct = n; return pAct->First(); } else { pAct = NULL; nAct = 0; return NULL; } } const ScRange* _ScRangeListTabs::Next( void ) { if( pAct ) return pAct->Next(); else return NULL; } ConverterBase::ConverterBase( UINT16 nNewBuffer ) : aPool(), aStack(), aEingPos( 0, 0, 0 ), nBufferSize( nNewBuffer ), eStatus( ConvOK ) { DBG_ASSERT( nNewBuffer > 0, "ConverterBase::ConverterBase - nNewBuffer == 0!" ); pBuffer = new sal_Char[ nNewBuffer ]; } ConverterBase::~ConverterBase() { delete[] pBuffer; } void ConverterBase::Reset() { eStatus = ConvOK; aPool.Reset(); aStack.Reset(); } ExcelConverterBase::ExcelConverterBase( XclImpStream &rStr, UINT16 nNewBuffer ) : ConverterBase( nNewBuffer ), aIn( rStr ) { } ExcelConverterBase::~ExcelConverterBase() { } void ExcelConverterBase::Reset( ScAddress aNewEingPos ) { ConverterBase::Reset(); aEingPos = aNewEingPos; } void ExcelConverterBase::Reset() { ConverterBase::Reset(); aEingPos.Set( 0, 0, 0 ); } LotusConverterBase::LotusConverterBase( SvStream &rStr, UINT16 nNewBuffer ) : ConverterBase( nNewBuffer ), aIn( rStr ), nBytesLeft( 0 ) { } LotusConverterBase::~LotusConverterBase() { } void LotusConverterBase::Reset( INT32 nLen, ScAddress aNewEingPos ) { ConverterBase::Reset(); nBytesLeft = nLen; aEingPos = aNewEingPos; } void LotusConverterBase::Reset( INT32 nLen ) { ConverterBase::Reset(); nBytesLeft = nLen; aEingPos.Set( 0, 0, 0 ); } void LotusConverterBase::Reset( ScAddress aNewEingPos ) { ConverterBase::Reset(); nBytesLeft = 0; aEingPos = aNewEingPos; } <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <type_traits> #include "maths/maths.hpp" constexpr const int BASE_MOD = 1000000007; /// caide keep template<typename T> inline T& add_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a += b) >= mod) { a -= mod; } return a; } template<typename T> inline T& sub_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a -= b) < 0) { a += mod; } return a; } template<typename T> inline T& mul_mod(T& a, const T b, const T mod = BASE_MOD) { a = static_cast<long long>(a) * b % mod; return a; } template<typename T, T MOD = BASE_MOD> class ModInt { public: /// caide keep constexpr ModInt() : ModInt(0) {} constexpr ModInt(const T value) : value_(value) { static_assert(MOD > 0, "Modulo must be strictly positive."); // static_assert((std::equal<T, int32_t> && mod <= 0x3f3f3f3f) || (std::equal<T, int64_t> && mod <= 0x3f3f3f3f3f3f3f3fLL), "Modulo must be less than half of the max value for typename."); } template<typename U> constexpr static ModInt from_integer(const U value) { return{ ModInt::normalize(value) }; } constexpr T value() const { return value_; } constexpr bool operator ==(const ModInt rhs) const { return value_ == rhs.value_; } constexpr bool operator !=(const ModInt rhs) const { return !operator==(rhs); } constexpr bool operator <(const ModInt& rhs) const { return value_ < rhs.value_; } constexpr bool operator >(const ModInt& rhs) const { return value_ > rhs.value_; } ModInt operator +(const ModInt rhs) const { T x = value_; return{ add_mod(x, rhs.value_, MOD) }; } ModInt operator -(const ModInt rhs) const { T x = value_; return{ sub_mod(x, rhs.value_, MOD) }; } ModInt operator *(const ModInt rhs) const { T x = value_; return{ mul_mod(x, rhs.value_, MOD) }; } ModInt& operator +=(const ModInt rhs) { add_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator -=(const ModInt rhs) { sub_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator *=(const ModInt rhs) { mul_mod(value_, rhs.value_, MOD); return *this; } ModInt operator ++(int) { const ModInt ret(value_); add_mod(value_, static_cast<T>(1), MOD); return ret; } ModInt operator --(int) { const ModInt ret(value_); sub_mod(value_, static_cast<T>(1), MOD); return ret; } ModInt& operator ++() { add_mod(value_, static_cast<T>(1), MOD); return *this; } ModInt& operator --() { sub_mod(value_, static_cast<T>(1), MOD); return *this; } constexpr ModInt operator +() const { return{ value_ }; } constexpr ModInt operator -() const { return negate(); } constexpr ModInt negate() const { return{ normalize(-value_) }; } constexpr ModInt inverse() const { return{ inverse_element(value_, MOD) }; } friend std::istream& operator >>(std::istream& in, ModInt& rhs) { T x; in >> x; rhs.value_ = rhs.normalize(x); return in; } friend std::ostream& operator <<(std::ostream& out, const ModInt& rhs) { out << rhs.value_; return out; } private: T value_; template<typename U> static T normalize(const U value) { if (value >= 0 && value < MOD) { return value; } const T ret = value % MOD; if (ret < 0) { return ret + MOD; } return ret; } }; namespace std { template<typename T, T MOD> struct is_integral<ModInt<T, MOD>> : std::true_type {}; template<typename T, T MOD> struct is_arithmetic<ModInt<T, MOD>> : std::true_type {}; } <commit_msg>Added to_string() method for ModInt<>.<commit_after>#pragma once #include <iostream> #include <string> #include <type_traits> #include "maths/maths.hpp" constexpr const int BASE_MOD = 1000000007; /// caide keep template<typename T> inline T& add_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a += b) >= mod) { a -= mod; } return a; } template<typename T> inline T& sub_mod(T& a, const T b, const T mod = BASE_MOD) { if ((a -= b) < 0) { a += mod; } return a; } template<typename T> inline T& mul_mod(T& a, const T b, const T mod = BASE_MOD) { a = static_cast<long long>(a) * b % mod; return a; } template<typename T, T MOD = BASE_MOD> class ModInt { public: /// caide keep constexpr ModInt() : ModInt(0) {} constexpr ModInt(const T value) : value_(value) { static_assert(MOD > 0, "Modulo must be strictly positive."); // static_assert((std::equal<T, int32_t> && mod <= 0x3f3f3f3f) || (std::equal<T, int64_t> && mod <= 0x3f3f3f3f3f3f3f3fLL), "Modulo must be less than half of the max value for typename."); } template<typename U> constexpr static ModInt from_integer(const U value) { return{ ModInt::normalize(value) }; } constexpr T value() const { return value_; } constexpr bool operator ==(const ModInt rhs) const { return value_ == rhs.value_; } constexpr bool operator !=(const ModInt rhs) const { return !operator==(rhs); } constexpr bool operator <(const ModInt& rhs) const { return value_ < rhs.value_; } constexpr bool operator >(const ModInt& rhs) const { return value_ > rhs.value_; } ModInt operator +(const ModInt rhs) const { T x = value_; return{ add_mod(x, rhs.value_, MOD) }; } ModInt operator -(const ModInt rhs) const { T x = value_; return{ sub_mod(x, rhs.value_, MOD) }; } ModInt operator *(const ModInt rhs) const { T x = value_; return{ mul_mod(x, rhs.value_, MOD) }; } ModInt& operator +=(const ModInt rhs) { add_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator -=(const ModInt rhs) { sub_mod(value_, rhs.value_, MOD); return *this; } ModInt& operator *=(const ModInt rhs) { mul_mod(value_, rhs.value_, MOD); return *this; } ModInt operator ++(int) { const ModInt ret(value_); add_mod(value_, static_cast<T>(1), MOD); return ret; } ModInt operator --(int) { const ModInt ret(value_); sub_mod(value_, static_cast<T>(1), MOD); return ret; } ModInt& operator ++() { add_mod(value_, static_cast<T>(1), MOD); return *this; } ModInt& operator --() { sub_mod(value_, static_cast<T>(1), MOD); return *this; } constexpr ModInt operator +() const { return{ value_ }; } constexpr ModInt operator -() const { return negate(); } constexpr ModInt negate() const { return{ normalize(-value_) }; } constexpr ModInt inverse() const { return{ inverse_element(value_, MOD) }; } std::string str() const { return std::to_string(value_); } friend std::istream& operator >>(std::istream& in, ModInt& rhs) { T x; in >> x; rhs.value_ = rhs.normalize(x); return in; } friend std::ostream& operator <<(std::ostream& out, const ModInt& rhs) { out << rhs.value_; return out; } private: T value_; template<typename U> static T normalize(const U value) { if (value >= 0 && value < MOD) { return value; } const T ret = value % MOD; if (ret < 0) { return ret + MOD; } return ret; } }; namespace std { template<typename T, T MOD> struct is_integral<ModInt<T, MOD>> : std::true_type {}; template<typename T, T MOD> struct is_arithmetic<ModInt<T, MOD>> : std::true_type {}; } template<typename T, T MOD> std::string to_string(const ModInt<T, MOD>& val) { return val.str(); } <|endoftext|>
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit) * Copyright (C) 2005 Artem Pavlenko * * Mapnik is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ //$Id: render.cpp 44 2005-04-22 18:53:54Z pavlenko $ #include "render.hpp" #include "image_util.hpp" #include "utils.hpp" #include "symbolizer.hpp" #include "query.hpp" #include "feature_layer_desc.hpp" #include "attribute_collector.hpp" #include "property_index.hpp" #include <algorithm> #include <cmath> #include <set> namespace mapnik { template <typename Image> void Renderer<Image>::render_vector_layer(datasource_p const& ds,Map const& map, std::vector<std::string> const& namedStyles, unsigned width,unsigned height, const Envelope<double>& bbox,Image& image) { CoordTransform t(width,height,bbox); std::vector<std::string>::const_iterator stylesIter=namedStyles.begin(); while (stylesIter!=namedStyles.end()) { std::set<std::string> names; attribute_collector<Feature> collector(names); property_index<Feature> indexer(names); query q(bbox,width,height); double scale = 1.0/t.scale(); std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; bool active_rules=false; feature_type_style const& style=map.find_style(*stylesIter++); const std::vector<rule_type>& rules=style.get_rules(); std::vector<rule_type>::const_iterator ruleIter=rules.begin(); while (ruleIter!=rules.end()) { if (ruleIter->active(scale)) { active_rules=true; filter_ptr& filter=const_cast<filter_ptr&>(ruleIter->get_filter()); filter->accept(collector); filter->accept(indexer); if (ruleIter->has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } else { if_rules.push_back(const_cast<rule_type*>(&(*ruleIter))); } } ++ruleIter; } std::set<std::string>::const_iterator namesIter=names.begin(); // push all property names while (namesIter!=names.end()) { q.add_property_name(*namesIter); ++namesIter; } //only query datasource if there are active rules if (active_rules) { featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; std::vector<rule_type*>::const_iterator itr=if_rules.begin(); while (itr!=if_rules.end()) { const filter_ptr& filter=(*itr)->get_filter(); if (filter->pass(*feature)) { do_else=false; const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { (*symIter)->render(*feature,t,image); ++symIter; } } ++itr; } if (do_else) { //else filter std::vector<rule_type*>::const_iterator itr=else_rules.begin(); while (itr != else_rules.end()) { const symbolizers& symbols = (*itr)->get_symbolizers(); symbolizers::const_iterator symIter=symbols.begin(); while (symIter!=symbols.end()) { (*symIter)->render(*feature,t,image); ++symIter; } ++itr; } } } } } } } template <typename Image> void Renderer<Image>::render_raster_layer(datasource_p const& ds, std::vector<std::string> const& , unsigned width,unsigned height, const Envelope<double>& bbox,Image& image) { query q(bbox,width,height); featureset_ptr fs=ds->features(q); if (fs) { feature_ptr feature; while ((feature = fs->next())) { raster_ptr const& raster=feature->get_raster(); if (raster) { image.set_rectangle(raster->x_,raster->y_,raster->data_); } } } } template <typename Image> void Renderer<Image>::render(Map const& map,Image& image) { timer clock; ////////////////////////////////////////////////////// Envelope<double> const& extent=map.getCurrentExtent(); std::clog<<"BBOX:"<<extent<<std::endl; double scale=map.scale(); std::clog<<" scale="<<scale<<std::endl; unsigned width=map.getWidth(); unsigned height=map.getHeight(); Color const& background=map.getBackground(); image.setBackground(background); for (size_t n=0;n<map.layerCount();++n) { Layer const& l=map.getLayer(n); if (l.isVisible(scale) && l.envelope().intersects(extent)) { datasource_p const& ds=l.datasource(); if (!ds) continue; if (ds->type() == datasource::Vector) { render_vector_layer(ds,map,l.styles(),width,height,extent,image); } else if (ds->type() == datasource::Raster) { render_raster_layer(ds,l.styles(),width,height,extent,image); } } } clock.stop(); } template class Renderer<Image32>; } <commit_msg>removed unused files<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: htmlexp2.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: er $ $Date: 2001-08-06 12:11:47 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------ #ifdef MAC #define _SYSDEP_HXX #endif #include <svx/svditer.hxx> #include <svx/svdograf.hxx> #include <svx/svdoole2.hxx> #include <svx/svdpage.hxx> #include <svx/xoutbmp.hxx> #include <so3/ipobj.hxx> #include <sot/exchange.hxx> #include <svtools/htmlkywd.hxx> #include <svtools/htmlout.hxx> #include <svtools/transfer.hxx> #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include <tools/urlobj.hxx> #if defined(WIN) || defined(WNT) #ifndef _SVWIN_H #include <tools/svwin.h> #endif #endif #include "htmlexp.hxx" #include "global.hxx" #include "flttools.hxx" #include "document.hxx" #include "drwlayer.hxx" //------------------------------------------------------------------------ void ScHTMLExport::PrepareGraphics( ScDrawLayer* pDrawLayer, USHORT nTab, USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow ) { if ( pDrawLayer->HasObjectsInRows( nTab, nStartRow, nEndRow ) ) { SdrPage* pDrawPage = pDrawLayer->GetPage( nTab ); if ( pDrawPage ) { bTabHasGraphics = TRUE; FillGraphList( pDrawPage, nTab, nStartCol, nStartRow, nEndCol, nEndRow ); for ( ScHTMLGraphEntry* pE = aGraphList.First(); pE; pE = aGraphList.Next() ) { if ( !pE->bInCell ) { // nicht alle in Zellen: einige neben Tabelle bTabAlignedLeft = TRUE; break; } } } } } void ScHTMLExport::FillGraphList( const SdrPage* pPage, USHORT nTab, USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow ) { ULONG nObjCount = pPage->GetObjCount(); if ( nObjCount ) { Rectangle aRect; if ( !bAll ) aRect = pDoc->GetMMRect( nStartCol, nStartRow, nEndCol, nEndRow, nTab ); SdrObjListIter aIter( *pPage, IM_FLAT ); SdrObject* pObject = aIter.Next(); while ( pObject ) { Rectangle aObjRect = pObject->GetBoundRect(); if ( bAll || aRect.IsInside( aObjRect ) ) { switch ( pObject->GetObjIdentifier() ) { case OBJ_GRAF: case OBJ_OLE2: { Size aSpace; ScRange aR = pDoc->GetRange( nTab, aObjRect ); // Rectangle in mm/100 Size aSize( MMToPixel( aObjRect.GetSize() ) ); // If the image is somewhere in a merged range we must // move the anchor to the upper left (THE span cell). pDoc->ExtendOverlapped( aR ); USHORT nCol1 = aR.aStart.Col(); USHORT nRow1 = aR.aStart.Row(); USHORT nCol2 = aR.aEnd.Col(); USHORT nRow2 = aR.aEnd.Row(); // alle Zellen unter der Grafik leer? BOOL bInCell = (pDoc->GetEmptyLinesInBlock( nCol1, nRow1, nTab, nCol2, nRow2, nTab, DIR_TOP ) == (nRow2 - nRow1)); // rows-1 ! if ( bInCell ) { // Spacing innerhalb der Span-Cell Rectangle aCellRect = pDoc->GetMMRect( nCol1, nRow1, nCol2, nRow2, nTab ); aSpace = MMToPixel( Size( aCellRect.GetWidth() - aObjRect.GetWidth(), aCellRect.GetHeight() - aObjRect.GetHeight() )); aSpace.Width() += (nCol2-nCol1) * (nCellSpacing+1); aSpace.Height() += (nRow2-nRow1) * (nCellSpacing+1); aSpace.Width() /= 2; aSpace.Height() /= 2; } ScHTMLGraphEntry* pE = new ScHTMLGraphEntry( pObject, aR, aSize, bInCell, aSpace ); aGraphList.Insert( pE, LIST_APPEND ); } break; default: DBG_ERRORFILE( "FillGraphList: no OBJ_GRAF, no OBJ_OLE2, can't write" ); // #90610# need enhancement from drawing layer group to // get a metafile for any object. // Then do the above also for all drawing objects and // in WriteGraphEntry get metafile of drawing object // and write image. } } pObject = aIter.Next(); } } } void ScHTMLExport::WriteGraphEntry( ScHTMLGraphEntry* pE ) { SdrObject* pObject = pE->pObject; ByteString aOpt; (((aOpt += ' ') += sHTML_O_width) += '=') += ByteString::CreateFromInt32( pE->aSize.Width() ); (((aOpt += ' ') += sHTML_O_height) += '=') += ByteString::CreateFromInt32( pE->aSize.Height() ); if ( pE->bInCell ) { (((aOpt += ' ') += sHTML_O_hspace) += '=') += ByteString::CreateFromInt32( pE->aSpace.Width() ); (((aOpt += ' ') += sHTML_O_vspace) += '=') += ByteString::CreateFromInt32( pE->aSpace.Height() ); } switch ( pObject->GetObjIdentifier() ) { case OBJ_GRAF: { const SdrGrafObj* pSGO = (SdrGrafObj*)pObject; const SdrGrafObjGeoData* pGeo = (SdrGrafObjGeoData*)pSGO->GetGeoData(); USHORT nMirrorCase = (pGeo->aGeo.nDrehWink == 18000 ? ( pGeo->bMirrored ? 3 : 4 ) : ( pGeo->bMirrored ? 2 : 1 )); BOOL bHMirr = ( ( nMirrorCase == 2 ) || ( nMirrorCase == 4 ) ); BOOL bVMirr = ( ( nMirrorCase == 3 ) || ( nMirrorCase == 4 ) ); ULONG nXOutFlags = 0; if ( bHMirr ) nXOutFlags |= XOUTBMP_MIRROR_HORZ; if ( bVMirr ) nXOutFlags |= XOUTBMP_MIRROR_VERT; String aLinkName; if ( pSGO->IsLinkedGraphic() ) aLinkName = pSGO->GetFileName(); WriteImage( aLinkName, pSGO->GetGraphic(), aOpt, nXOutFlags ); pE->bWritten = TRUE; } break; case OBJ_OLE2: { const SvInPlaceObjectRef& rRef = ((SdrOle2Obj*)pObject)->GetObjRef(); DBG_ASSERT( rRef.Is(), "WriteGraphEntry: no OLE ObjRef" ); if ( rRef.Is() ) { TransferableDataHelper aOleData( rRef->CreateTransferableSnapshot() ); GDIMetaFile aMtf; if( aOleData.GetGDIMetaFile( FORMAT_GDIMETAFILE, aMtf ) ) { Graphic aGraph( aMtf ); String aLinkName; WriteImage( aLinkName, aGraph, aOpt ); pE->bWritten = TRUE; } } } break; } } void ScHTMLExport::WriteImage( String& rLinkName, const Graphic& rGrf, const ByteString& rImgOptions, ULONG nXOutFlags ) { // embeddete Grafik -> via WriteGraphic schreiben if( !rLinkName.Len() ) { if( aStreamPath.Len() > 0 ) { // Grafik als (JPG-)File speichern String aGrfNm( aStreamPath ); nXOutFlags |= XOUTBMP_USE_NATIVE_IF_POSSIBLE; USHORT nErr = XOutBitmap::WriteGraphic( rGrf, aGrfNm, _STRINGCONST( "JPG" ), nXOutFlags ); if( !nErr ) // sonst fehlerhaft, da ist nichts auszugeben { rLinkName = URIHelper::SmartRelToAbs( aGrfNm ); if ( HasCId() ) MakeCIdURL( rLinkName ); } } } else { if( bCopyLocalFileToINet || HasCId() ) { CopyLocalFileToINet( rLinkName, aStreamPath ); if ( HasCId() ) MakeCIdURL( rLinkName ); } else rLinkName = URIHelper::SmartRelToAbs( rLinkName ); } if( rLinkName.Len() ) { // <IMG SRC="..."[ rImgOptions]> rStrm << '<' << sHTML_image << ' ' << sHTML_O_src << "=\""; HTMLOutFuncs::Out_String( rStrm, INetURLObject::AbsToRel( rLinkName ), eDestEnc ) << '\"'; if ( rImgOptions.Len() ) rStrm << rImgOptions.GetBuffer(); rStrm << '>' << sNewLine << GetIndentStr(); } } <commit_msg>#90610# export any drawing object, not just graphics and OLE<commit_after>/************************************************************************* * * $RCSfile: htmlexp2.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: er $ $Date: 2001-09-07 13:58:38 $ * * 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): _______________________________________ * * ************************************************************************/ #ifdef PCH #include "filt_pch.hxx" #endif #pragma hdrstop //------------------------------------------------------------------------ #ifdef MAC #define _SYSDEP_HXX #endif #include <svx/svditer.hxx> #include <svx/svdograf.hxx> #include <svx/svdoole2.hxx> #include <svx/svdpage.hxx> #include <svx/xoutbmp.hxx> #ifndef _SVDXCGV_HXX #include <svx/svdxcgv.hxx> #endif #include <so3/ipobj.hxx> #include <sot/exchange.hxx> #include <svtools/htmlkywd.hxx> #include <svtools/htmlout.hxx> #include <svtools/transfer.hxx> #ifndef SVTOOLS_URIHELPER_HXX #include <svtools/urihelper.hxx> #endif #include <tools/urlobj.hxx> #if defined(WIN) || defined(WNT) #ifndef _SVWIN_H #include <tools/svwin.h> #endif #endif #include "htmlexp.hxx" #include "global.hxx" #include "flttools.hxx" #include "document.hxx" #include "drwlayer.hxx" //------------------------------------------------------------------------ void ScHTMLExport::PrepareGraphics( ScDrawLayer* pDrawLayer, USHORT nTab, USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow ) { if ( pDrawLayer->HasObjectsInRows( nTab, nStartRow, nEndRow ) ) { SdrPage* pDrawPage = pDrawLayer->GetPage( nTab ); if ( pDrawPage ) { bTabHasGraphics = TRUE; FillGraphList( pDrawPage, nTab, nStartCol, nStartRow, nEndCol, nEndRow ); for ( ScHTMLGraphEntry* pE = aGraphList.First(); pE; pE = aGraphList.Next() ) { if ( !pE->bInCell ) { // nicht alle in Zellen: einige neben Tabelle bTabAlignedLeft = TRUE; break; } } } } } void ScHTMLExport::FillGraphList( const SdrPage* pPage, USHORT nTab, USHORT nStartCol, USHORT nStartRow, USHORT nEndCol, USHORT nEndRow ) { ULONG nObjCount = pPage->GetObjCount(); if ( nObjCount ) { Rectangle aRect; if ( !bAll ) aRect = pDoc->GetMMRect( nStartCol, nStartRow, nEndCol, nEndRow, nTab ); SdrObjListIter aIter( *pPage, IM_FLAT ); SdrObject* pObject = aIter.Next(); while ( pObject ) { Rectangle aObjRect = pObject->GetBoundRect(); if ( bAll || aRect.IsInside( aObjRect ) ) { Size aSpace; ScRange aR = pDoc->GetRange( nTab, aObjRect ); // Rectangle in mm/100 Size aSize( MMToPixel( aObjRect.GetSize() ) ); // If the image is somewhere in a merged range we must // move the anchor to the upper left (THE span cell). pDoc->ExtendOverlapped( aR ); USHORT nCol1 = aR.aStart.Col(); USHORT nRow1 = aR.aStart.Row(); USHORT nCol2 = aR.aEnd.Col(); USHORT nRow2 = aR.aEnd.Row(); // All cells empty under object? BOOL bInCell = (pDoc->GetEmptyLinesInBlock( nCol1, nRow1, nTab, nCol2, nRow2, nTab, DIR_TOP ) == (nRow2 - nRow1)); // rows-1 ! if ( bInCell ) { // Spacing in spanning cell Rectangle aCellRect = pDoc->GetMMRect( nCol1, nRow1, nCol2, nRow2, nTab ); aSpace = MMToPixel( Size( aCellRect.GetWidth() - aObjRect.GetWidth(), aCellRect.GetHeight() - aObjRect.GetHeight() )); aSpace.Width() += (nCol2-nCol1) * (nCellSpacing+1); aSpace.Height() += (nRow2-nRow1) * (nCellSpacing+1); aSpace.Width() /= 2; aSpace.Height() /= 2; } ScHTMLGraphEntry* pE = new ScHTMLGraphEntry( pObject, aR, aSize, bInCell, aSpace ); aGraphList.Insert( pE, LIST_APPEND ); } pObject = aIter.Next(); } } } void ScHTMLExport::WriteGraphEntry( ScHTMLGraphEntry* pE ) { SdrObject* pObject = pE->pObject; ByteString aOpt; (((aOpt += ' ') += sHTML_O_width) += '=') += ByteString::CreateFromInt32( pE->aSize.Width() ); (((aOpt += ' ') += sHTML_O_height) += '=') += ByteString::CreateFromInt32( pE->aSize.Height() ); if ( pE->bInCell ) { (((aOpt += ' ') += sHTML_O_hspace) += '=') += ByteString::CreateFromInt32( pE->aSpace.Width() ); (((aOpt += ' ') += sHTML_O_vspace) += '=') += ByteString::CreateFromInt32( pE->aSpace.Height() ); } switch ( pObject->GetObjIdentifier() ) { case OBJ_GRAF: { const SdrGrafObj* pSGO = (SdrGrafObj*)pObject; const SdrGrafObjGeoData* pGeo = (SdrGrafObjGeoData*)pSGO->GetGeoData(); USHORT nMirrorCase = (pGeo->aGeo.nDrehWink == 18000 ? ( pGeo->bMirrored ? 3 : 4 ) : ( pGeo->bMirrored ? 2 : 1 )); BOOL bHMirr = ( ( nMirrorCase == 2 ) || ( nMirrorCase == 4 ) ); BOOL bVMirr = ( ( nMirrorCase == 3 ) || ( nMirrorCase == 4 ) ); ULONG nXOutFlags = 0; if ( bHMirr ) nXOutFlags |= XOUTBMP_MIRROR_HORZ; if ( bVMirr ) nXOutFlags |= XOUTBMP_MIRROR_VERT; String aLinkName; if ( pSGO->IsLinkedGraphic() ) aLinkName = pSGO->GetFileName(); WriteImage( aLinkName, pSGO->GetGraphic(), aOpt, nXOutFlags ); pE->bWritten = TRUE; } break; case OBJ_OLE2: { const SvInPlaceObjectRef& rRef = ((SdrOle2Obj*)pObject)->GetObjRef(); DBG_ASSERT( rRef.Is(), "WriteGraphEntry: no OLE ObjRef" ); if ( rRef.Is() ) { TransferableDataHelper aOleData( rRef->CreateTransferableSnapshot() ); GDIMetaFile aMtf; if( aOleData.GetGDIMetaFile( FORMAT_GDIMETAFILE, aMtf ) ) { Graphic aGraph( aMtf ); String aLinkName; WriteImage( aLinkName, aGraph, aOpt ); pE->bWritten = TRUE; } } } break; default: { Graphic aGraph( SdrExchangeView::GetObjGraphic( pDoc->GetDrawLayer(), pObject ) ); String aLinkName; WriteImage( aLinkName, aGraph, aOpt ); pE->bWritten = TRUE; } } } void ScHTMLExport::WriteImage( String& rLinkName, const Graphic& rGrf, const ByteString& rImgOptions, ULONG nXOutFlags ) { // embeddete Grafik -> via WriteGraphic schreiben if( !rLinkName.Len() ) { if( aStreamPath.Len() > 0 ) { // Grafik als (JPG-)File speichern String aGrfNm( aStreamPath ); nXOutFlags |= XOUTBMP_USE_NATIVE_IF_POSSIBLE; USHORT nErr = XOutBitmap::WriteGraphic( rGrf, aGrfNm, _STRINGCONST( "JPG" ), nXOutFlags ); if( !nErr ) // sonst fehlerhaft, da ist nichts auszugeben { rLinkName = URIHelper::SmartRelToAbs( aGrfNm ); if ( HasCId() ) MakeCIdURL( rLinkName ); } } } else { if( bCopyLocalFileToINet || HasCId() ) { CopyLocalFileToINet( rLinkName, aStreamPath ); if ( HasCId() ) MakeCIdURL( rLinkName ); } else rLinkName = URIHelper::SmartRelToAbs( rLinkName ); } if( rLinkName.Len() ) { // <IMG SRC="..."[ rImgOptions]> rStrm << '<' << sHTML_image << ' ' << sHTML_O_src << "=\""; HTMLOutFuncs::Out_String( rStrm, INetURLObject::AbsToRel( rLinkName ), eDestEnc ) << '\"'; if ( rImgOptions.Len() ) rStrm << rImgOptions.GetBuffer(); rStrm << '>' << sNewLine << GetIndentStr(); } } <|endoftext|>
<commit_before>// render_mp4.cpp // // Author: Sam Atkinson // Date modified: 28-Oct-2016 // // Renders an animated mp4 of a julia fractal transformation #include <iostream> #include <fstream> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <iomanip> #include <cstdlib> #include "lodepng.h" #include "opencl_errors.hpp" #include "julia_set.hpp" // Function prototypes cl_uint4* colormap(std::string filename, unsigned int* size); cl::Platform get_platform(void); cl::Device get_device(cl::Platform* platform); cl::Context get_context(cl::Device* device); cl::Program build_program(std::string source_file, cl::Context* context, cl::Device* device); void check_device_info(cl::Device* device); std::string ts(time_t* start_time); int main(int argc, char** argv) { // Parse arguments if (argc != 3) { std::cerr << "Error: Incomplete arguments" << std::endl << "Usage: ./render.o <video size in px> <colormap png>" << std::endl; return EXIT_FAILURE; } size_t size = (size_t)atoi(argv[1]); std::string cmap_filename = argv[2]; // Define parameters for fractal animation unsigned int num_frames = 600; float center_re = 0.3; float center_im = 0.0; float zoom = 1.0; float c_re = 0.0; float c_im = 0.635; float c_re_step = 0.0; float c_im_step = 0.00002; // Declare OpenCL objects cl_int err = CL_SUCCESS; cl::Platform platform; cl::Device device; cl::Context context; cl::CommandQueue queue; // Initialize OpenCL platform layer // =============================================================== // Create OpenCL platform platform = get_platform(); // Create OpenCL device device = get_device(&platform); // Create OpenCL context context = get_context(&device); // Create OpenCL command queue queue = cl::CommandQueue(context, device); // Check device information for image support and dimensions check_device_info(&device); // Create buffers // =============================================================== // Create buffers for real and imaginary values cl::Buffer buffer_re(context, CL_MEM_READ_WRITE, sizeof(float) * size); cl::Buffer buffer_im(context, CL_MEM_READ_WRITE, sizeof(float) * size); // Create buffer for colormap and fill with generated colormap unsigned int cmap_size; cl_uint4* cmap = colormap(cmap_filename, &cmap_size); if (cmap == NULL) return EXIT_FAILURE; cl::Buffer cmap_buf(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint4) * cmap_size, cmap, &err); if (err != CL_SUCCESS) { std::cerr << "Could not create colormap buffer: " << get_err_str(err) << std::endl; return EXIT_FAILURE; } // Initialize Julia Set objects and fill images with white // =============================================================== // Declare image format as RGBA with 1 byte per color element cl::ImageFormat image_format(CL_RGBA, CL_UNSIGNED_INT8); std::vector<Julia_Set> frames; frames.resize(num_frames); for (unsigned int i = 0; i < num_frames; i++) { frames[i] = Julia_Set(size, &image_format, &context); frames[i].fill_white(&queue); } // Create kernels // =============================================================== // Build kernel program from source cl::Program program = build_program("src/kernel.cl", &context, &device); // Create kernels for julia set objects for (unsigned int i = 0; i < num_frames; i++) frames[i].create_kernel(&program, "render_image", &buffer_re, &buffer_im, &cmap_buf, cmap_size, c_re + i * c_re_step, c_im + i * c_im_step); // Create kernels for real & imaginary value buffers cl::Kernel spaced_re_kernel(program, "even_re"); spaced_re_kernel.setArg(0, center_re); spaced_re_kernel.setArg(1, zoom); spaced_re_kernel.setArg(2, (float)size); spaced_re_kernel.setArg(3, buffer_re); cl::Kernel spaced_im_kernel(program, "even_im"); spaced_im_kernel.setArg(0, center_im); spaced_im_kernel.setArg(1, zoom); spaced_im_kernel.setArg(2, (float)size); spaced_im_kernel.setArg(3, buffer_im); // Start OpenCL operations // =============================================================== // Start execution timer std::cout << "STARTING EXECUTION" << std::endl; time_t t_s = time(0); // Compute evenly spaced real and imaginary values // =============================================================== err = queue.enqueueTask(spaced_re_kernel, NULL, NULL); if (err != CL_SUCCESS) { std::cerr << "Could not compute spaced real values: " << get_err_str(err) << std::endl; return EXIT_FAILURE; } err = queue.enqueueTask(spaced_im_kernel, NULL, NULL); if (err != CL_SUCCESS) { std::cerr << "Could not compute spaced imaginary values: " << get_err_str(err) << std::endl; return EXIT_FAILURE; } err = queue.finish(); std::cout << ts(&t_s) << "Computed evenly spaced real and imaginary values" << std::endl; // Compute julia sets // =============================================================== for (unsigned int i = 0; i < num_frames; i++) frames[i].queue_kernel(&queue); err = queue.finish(); std::cout << ts(&t_s) << "Computed julia sets" << std::endl; if (err != CL_SUCCESS) { std::cerr << "Could not finish rendering: " << get_err_str(err) << std::endl; return EXIT_FAILURE; } // Read julia sets to host memory and export // =============================================================== for (unsigned int i = 0; i < num_frames; i++) frames[i].read_image_to_host(&queue); err = queue.finish(); std::cout << ts(&t_s) << "Finished reading julia sets to host memory" << std::endl; // Create directory to hold rendered frames struct stat st = {0}; if (stat("./frames/", &st) == -1) mkdir("./frames/", 0700); // Export julia set images to PPM files char ppm_buf[100]; for (unsigned int i = 0; i < num_frames; i++) { snprintf(ppm_buf, sizeof(ppm_buf), "./frames/F%04d.ppm", i); frames[i].export_to_ppm(ppm_buf); } err = queue.finish(); std::cout << ts(&t_s) << "Finished exporting julia sets to PPM files" << std::endl; // Cleanup resources // =============================================================== platform.unloadCompiler(); // Create MP4 video from PPM image frames // =============================================================== std::string mp4_system_call = "ffmpeg -f image2 -r 60 -i "; mp4_system_call += "frames/F%04d.ppm -vcodec mpeg4 -q:v 1 -y "; mp4_system_call += "out.mp4 >> ffmpeg_output.txt"; system(mp4_system_call.c_str()); return EXIT_SUCCESS; } cl::Platform get_platform(void) { // Get all available OpenCL platforms std::vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); if (all_platforms.size() == 0) { std::cerr << "No OpenCL platforms found... exiting" << std::endl; exit(EXIT_FAILURE); } // Print number of available platforms to stdout else if (all_platforms.size() > 1) std::cout << "Found " << all_platforms.size() << " available" << " OpenCL platforms" << std::endl; else std::cout << "Found 1 available OpenCL platform" << std::endl; cl::Platform platform = all_platforms[0]; std::cout << "\tUsing platform " << platform.getInfo<CL_PLATFORM_NAME>() << std::endl; return platform; } cl::Device get_device(cl::Platform* platform) { // Get list of all OpenCL devices on platform std::vector<cl::Device> all_devices; platform->getDevices(CL_DEVICE_TYPE_ALL, &all_devices); if (all_devices.size() == 0) { std::cerr << "No OpenCL devices found... exiting" << std::endl; exit(EXIT_FAILURE); } // Let user choose OpenCL device if more than 1 is avialable unsigned int device_num = 0; if (all_devices.size() > 1) { std::cout << "Available OpenCL devices:" << std::endl; for (unsigned int i = 0; i < all_devices.size(); i++) { std::cout << "\t[" << i << "] " << all_devices[i].getInfo<CL_DEVICE_NAME>() << std::endl; } std::cout << "Device preference: "; std::cin >> device_num; } else { std::cout << "Found 1 available OpenCL device" << std::endl; } return all_devices[device_num]; } cl::Context get_context(cl::Device* device) { return cl::Context({*device}); } cl::Program build_program(std::string source_file, cl::Context* context, cl::Device* device) { // Get text from kernel file cl::Program::Sources sources; std::ifstream kernel_file(source_file); std::stringstream buffer; buffer << kernel_file.rdbuf(); std::string kernel_source = buffer.str(); sources.push_back({kernel_source.c_str(), kernel_source.length()}); // Build program from kernel source code cl::Program program(*context, sources); if (program.build({*device}) != CL_SUCCESS) { // Output build errors to file std::string err_str; err_str = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(*device); std::ofstream build_log; build_log.open("kernel_build_log.txt", std::ios::out); build_log << err_str; build_log.close(); std::cerr << "Error building kernel. See file kernel_build_log.txt" << std::endl; } return program; } void check_device_info(cl::Device* device) { // Make sure device has image support if (!device->getInfo<CL_DEVICE_IMAGE_SUPPORT>()) { std::cerr << "OpenCL device does not have image support" << std::endl; } // Output device info to stdout std::cout << "DEVICE INFO:" << std::endl; cl_uint max_work_item_dims; max_work_item_dims = device->getInfo<CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS>(); std::cout << "\tMaximum work item dimensions: " << max_work_item_dims << std::endl; std::vector<long unsigned int> max_work_item_sizes; max_work_item_sizes = device->getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>(); for (cl_uint i = 0; i < max_work_item_dims; i++) std::cout << "\t\tMaximum work item size for dimension " << i << ": " << max_work_item_sizes[i] << std::endl; cl_uint max_work_group_size; max_work_group_size = device->getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>(); std::cout << "\tMaximum work group size: " << max_work_group_size << std::endl; } cl_uint4* colormap(std::string filename, unsigned int* size) { std::vector<unsigned char> image; unsigned int width, height; // Use lodepng library to decode png colormap unsigned err = lodepng::decode(image, width, height, filename.c_str()); if (err) { std::cerr << "Invalid colormap PNG file" << std::endl; return NULL; } // Add colors from image vector into array of uint vector types cl_uint4* cmap = new cl_uint4[width]; for (unsigned int i = 0; i < width; i++) { cmap[i] = {{image[i * 4 + 0], image[i * 4 + 1], image[i * 4 + 2], 255}}; } *size = width; return cmap; } std::string ts(time_t* start_time) { // Return string with time difference from start of execution std::stringstream stream; stream << difftime(time(0), *start_time); return "[" + stream.str() + "s] "; } <commit_msg>Switched to h264 codec<commit_after>// render_mp4.cpp // // Author: Sam Atkinson // Date modified: 28-Oct-2016 // // Renders an animated mp4 of a julia fractal transformation #include <iostream> #include <fstream> #include <sstream> #include <sys/types.h> #include <sys/stat.h> #include <time.h> #include <iomanip> #include <cstdlib> #include "lodepng.h" #include "opencl_errors.hpp" #include "julia_set.hpp" // Function prototypes cl_uint4* colormap(std::string filename, unsigned int* size); cl::Platform get_platform(void); cl::Device get_device(cl::Platform* platform); cl::Context get_context(cl::Device* device); cl::Program build_program(std::string source_file, cl::Context* context, cl::Device* device); void check_device_info(cl::Device* device); std::string ts(time_t* start_time); int main(int argc, char** argv) { // Parse arguments if (argc != 3) { std::cerr << "Error: Incomplete arguments" << std::endl << "Usage: ./render.o <video size in px> <colormap png>" << std::endl; return EXIT_FAILURE; } size_t size = (size_t)atoi(argv[1]); std::string cmap_filename = argv[2]; // Define parameters for fractal animation unsigned int num_frames = 600; float center_re = 0.0; float center_im = 0.0; float zoom = 1.0; float c_re = 0.0; float c_im = 0.635; float c_re_step = 0.0; float c_im_step = 0.00002; // Declare OpenCL objects cl_int err = CL_SUCCESS; cl::Platform platform; cl::Device device; cl::Context context; cl::CommandQueue queue; // Initialize OpenCL platform layer // =============================================================== // Create OpenCL platform platform = get_platform(); // Create OpenCL device device = get_device(&platform); // Create OpenCL context context = get_context(&device); // Create OpenCL command queue queue = cl::CommandQueue(context, device); // Check device information for image support and dimensions check_device_info(&device); // Create buffers // =============================================================== // Create buffers for real and imaginary values cl::Buffer buffer_re(context, CL_MEM_READ_WRITE, sizeof(float) * size); cl::Buffer buffer_im(context, CL_MEM_READ_WRITE, sizeof(float) * size); // Create buffer for colormap and fill with generated colormap unsigned int cmap_size; cl_uint4* cmap = colormap(cmap_filename, &cmap_size); if (cmap == NULL) return EXIT_FAILURE; cl::Buffer cmap_buf(context, CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, sizeof(cl_uint4) * cmap_size, cmap, &err); if (err != CL_SUCCESS) { std::cerr << "Could not create colormap buffer: " << get_err_str(err) << std::endl; return EXIT_FAILURE; } // Initialize Julia Set objects and fill images with white // =============================================================== // Declare image format as RGBA with 1 byte per color element cl::ImageFormat image_format(CL_RGBA, CL_UNSIGNED_INT8); std::vector<Julia_Set> frames; frames.resize(num_frames); for (unsigned int i = 0; i < num_frames; i++) { frames[i] = Julia_Set(size, &image_format, &context); frames[i].fill_white(&queue); } // Create kernels // =============================================================== // Build kernel program from source cl::Program program = build_program("src/kernel.cl", &context, &device); // Create kernels for julia set objects for (unsigned int i = 0; i < num_frames; i++) frames[i].create_kernel(&program, "render_image", &buffer_re, &buffer_im, &cmap_buf, cmap_size, c_re + i * c_re_step, c_im + i * c_im_step); // Create kernels for real & imaginary value buffers cl::Kernel spaced_re_kernel(program, "even_re"); spaced_re_kernel.setArg(0, center_re); spaced_re_kernel.setArg(1, zoom); spaced_re_kernel.setArg(2, (float)size); spaced_re_kernel.setArg(3, buffer_re); cl::Kernel spaced_im_kernel(program, "even_im"); spaced_im_kernel.setArg(0, center_im); spaced_im_kernel.setArg(1, zoom); spaced_im_kernel.setArg(2, (float)size); spaced_im_kernel.setArg(3, buffer_im); // Start OpenCL operations // =============================================================== // Start execution timer std::cout << "STARTING EXECUTION" << std::endl; time_t t_s = time(0); // Compute evenly spaced real and imaginary values // =============================================================== err = queue.enqueueTask(spaced_re_kernel, NULL, NULL); if (err != CL_SUCCESS) { std::cerr << "Could not compute spaced real values: " << get_err_str(err) << std::endl; return EXIT_FAILURE; } err = queue.enqueueTask(spaced_im_kernel, NULL, NULL); if (err != CL_SUCCESS) { std::cerr << "Could not compute spaced imaginary values: " << get_err_str(err) << std::endl; return EXIT_FAILURE; } err = queue.finish(); std::cout << ts(&t_s) << "Computed evenly spaced real and imaginary values" << std::endl; // Compute julia sets // =============================================================== for (unsigned int i = 0; i < num_frames; i++) frames[i].queue_kernel(&queue); err = queue.finish(); std::cout << ts(&t_s) << "Computed julia sets" << std::endl; if (err != CL_SUCCESS) { std::cerr << "Could not finish rendering: " << get_err_str(err) << std::endl; return EXIT_FAILURE; } // Read julia sets to host memory and export // =============================================================== for (unsigned int i = 0; i < num_frames; i++) frames[i].read_image_to_host(&queue); err = queue.finish(); std::cout << ts(&t_s) << "Finished reading julia sets to host memory" << std::endl; // Create directory to hold rendered frames struct stat st = {0}; if (stat("./frames/", &st) == -1) mkdir("./frames/", 0700); // Export julia set images to PPM files char ppm_buf[100]; for (unsigned int i = 0; i < num_frames; i++) { snprintf(ppm_buf, sizeof(ppm_buf), "./frames/F%04d.ppm", i); frames[i].export_to_ppm(ppm_buf); } err = queue.finish(); std::cout << ts(&t_s) << "Finished exporting julia sets to PPM files" << std::endl; // Cleanup resources // =============================================================== platform.unloadCompiler(); // Create MP4 video from PPM image frames // =============================================================== std::string mp4_system_call = "ffmpeg -f image2 -r 60 -i "; mp4_system_call += "frames/F%04d.ppm -vcodec mpeg4 -q:v 20 -c:v libx264 "; mp4_system_call += "-y out.mp4"; system(mp4_system_call.c_str()); return EXIT_SUCCESS; } cl::Platform get_platform(void) { // Get all available OpenCL platforms std::vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); if (all_platforms.size() == 0) { std::cerr << "No OpenCL platforms found... exiting" << std::endl; exit(EXIT_FAILURE); } // Print number of available platforms to stdout else if (all_platforms.size() > 1) std::cout << "Found " << all_platforms.size() << " available" << " OpenCL platforms" << std::endl; else std::cout << "Found 1 available OpenCL platform" << std::endl; cl::Platform platform = all_platforms[0]; std::cout << "\tUsing platform " << platform.getInfo<CL_PLATFORM_NAME>() << std::endl; return platform; } cl::Device get_device(cl::Platform* platform) { // Get list of all OpenCL devices on platform std::vector<cl::Device> all_devices; platform->getDevices(CL_DEVICE_TYPE_ALL, &all_devices); if (all_devices.size() == 0) { std::cerr << "No OpenCL devices found... exiting" << std::endl; exit(EXIT_FAILURE); } // Let user choose OpenCL device if more than 1 is avialable unsigned int device_num = 0; if (all_devices.size() > 1) { std::cout << "Available OpenCL devices:" << std::endl; for (unsigned int i = 0; i < all_devices.size(); i++) { std::cout << "\t[" << i << "] " << all_devices[i].getInfo<CL_DEVICE_NAME>() << std::endl; } std::cout << "Device preference: "; std::cin >> device_num; } else { std::cout << "Found 1 available OpenCL device" << std::endl; } return all_devices[device_num]; } cl::Context get_context(cl::Device* device) { return cl::Context({*device}); } cl::Program build_program(std::string source_file, cl::Context* context, cl::Device* device) { // Get text from kernel file cl::Program::Sources sources; std::ifstream kernel_file(source_file); std::stringstream buffer; buffer << kernel_file.rdbuf(); std::string kernel_source = buffer.str(); sources.push_back({kernel_source.c_str(), kernel_source.length()}); // Build program from kernel source code cl::Program program(*context, sources); if (program.build({*device}) != CL_SUCCESS) { // Output build errors to file std::string err_str; err_str = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(*device); std::ofstream build_log; build_log.open("kernel_build_log.txt", std::ios::out); build_log << err_str; build_log.close(); std::cerr << "Error building kernel. See file kernel_build_log.txt" << std::endl; } return program; } void check_device_info(cl::Device* device) { // Make sure device has image support if (!device->getInfo<CL_DEVICE_IMAGE_SUPPORT>()) { std::cerr << "OpenCL device does not have image support" << std::endl; } // Output device info to stdout std::cout << "DEVICE INFO:" << std::endl; cl_uint max_work_item_dims; max_work_item_dims = device->getInfo<CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS>(); std::cout << "\tMaximum work item dimensions: " << max_work_item_dims << std::endl; std::vector<long unsigned int> max_work_item_sizes; max_work_item_sizes = device->getInfo<CL_DEVICE_MAX_WORK_ITEM_SIZES>(); for (cl_uint i = 0; i < max_work_item_dims; i++) std::cout << "\t\tMaximum work item size for dimension " << i << ": " << max_work_item_sizes[i] << std::endl; cl_uint max_work_group_size; max_work_group_size = device->getInfo<CL_DEVICE_MAX_WORK_GROUP_SIZE>(); std::cout << "\tMaximum work group size: " << max_work_group_size << std::endl; } cl_uint4* colormap(std::string filename, unsigned int* size) { std::vector<unsigned char> image; unsigned int width, height; // Use lodepng library to decode png colormap unsigned err = lodepng::decode(image, width, height, filename.c_str()); if (err) { std::cerr << "Invalid colormap PNG file" << std::endl; return NULL; } // Add colors from image vector into array of uint vector types cl_uint4* cmap = new cl_uint4[width]; for (unsigned int i = 0; i < width; i++) { cmap[i] = {{image[i * 4 + 0], image[i * 4 + 1], image[i * 4 + 2], 255}}; } *size = width; return cmap; } std::string ts(time_t* start_time) { // Return string with time difference from start of execution std::stringstream stream; stream << difftime(time(0), *start_time); return "[" + stream.str() + "s] "; } <|endoftext|>
<commit_before>#include "MainWindow.h" QtMsgHandler pOldHandler = NULL; MainWindow *pw = NULL; void myMessageOutput(QtMsgType type, const char *msg) { QString strMsg = msg; int level = -1; switch (type) { case QtDebugMsg: level = 3; break; case QtWarningMsg: level = 2; break; case QtCriticalMsg: level = 1; break; case QtFatalMsg: level = 0; } if (NULL != pw) { pw->log (strMsg, level); } if (NULL == pOldHandler) { if (NULL == pw) { strMsg += "\n"; fwrite (strMsg.toLatin1 (), strMsg.size (), 1, stderr); } if (QtFatalMsg == type) { abort(); } } else { pOldHandler (type, strMsg.toLatin1 ()); } }//myMessageOutput int main (int argc, char **argv) { pOldHandler = qInstallMsgHandler(myMessageOutput); QApplication app(argc, argv); MainWindow w; pw = &w; int rv = app.exec (); pw = NULL; return rv; }//main <commit_msg>Really make qgvnotify a console app.<commit_after>#include "MainWindow.h" QtMsgHandler pOldHandler = NULL; MainWindow *pw = NULL; void myMessageOutput(QtMsgType type, const char *msg) { QString strMsg = msg; int level = -1; switch (type) { case QtDebugMsg: level = 3; break; case QtWarningMsg: level = 2; break; case QtCriticalMsg: level = 1; break; case QtFatalMsg: level = 0; } if (NULL != pw) { pw->log (strMsg, level); } if (NULL == pOldHandler) { if (NULL == pw) { strMsg += "\n"; fwrite (strMsg.toLatin1 (), strMsg.size (), 1, stderr); } if (QtFatalMsg == type) { abort(); } } else { pOldHandler (type, strMsg.toLatin1 ()); } }//myMessageOutput int main (int argc, char **argv) { pOldHandler = qInstallMsgHandler(myMessageOutput); QCoreApplication app(argc, argv); MainWindow w; pw = &w; int rv = app.exec (); pw = NULL; return rv; }//main <|endoftext|>
<commit_before>// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "WavLoader.h" #include "LoggingFunctions.h" #include "MemoryLeakCheck.h" #include <iostream> #include <sstream> using namespace std; static void ReadBytes(u8* dest, const u8* src, uint& index, unsigned int numBytes) { memcpy(dest, &src[index], numBytes); index += numBytes; } /// @todo Dead code, evalue if this function is needed static u8 ReadU8(const u8* src, uint& index) { u8 ret = src[index]; index += sizeof(u8); return ret; } static u16 ReadU16(const u8* src, uint& index) { u16 ret = *((u16*)(&src[index])); index += sizeof(u16); return ret; } static u32 ReadU32(const u8* src, uint& index) { u32 ret = *((u32*)(&src[index])); index += sizeof(u32); return ret; } namespace WavLoader { bool IdentifyWavFileInMemory(const u8 *fileData, size_t numBytes) { if (!fileData || numBytes < 4) return false; if (!memcmp(fileData, "RIFF", 4)) return true; else return false; } bool LoadWavFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency) { if (!fileData || numBytes == 0) { LogError("Null input data passed in"); return false; } if (!isStereo || !is16Bit || !frequency) { LogError("Outputs not set"); return false; } unsigned int index = 0; u8 riff_text[4]; ReadBytes(riff_text, fileData, index, 4); if (!!memcmp(riff_text, "RIFF", 4)) { LogError("No RIFF chunk in WAV data"); return false; } if (index >= numBytes) return false; ReadU32(fileData, index); u8 wave_text[4]; ReadBytes(wave_text, fileData, index, 4); if (!!memcmp(wave_text, "WAVE", 4)) { LogError("No WAVE chunk in WAV data"); return false; } // Search for the fmt chunk for(;;) { if (index >= numBytes) { LogError("No fmt chunk in WAV data"); return false; } u8 chunk_text[4]; ReadBytes(chunk_text, fileData, index, 4); unsigned int chunk_size = ReadU32(fileData, index); if (!memcmp(chunk_text, "fmt ", 4)) break; if (!chunk_size) return false; index += chunk_size; } if (index >= numBytes) return false; u16 format = ReadU16(fileData, index); u16 channels = ReadU16(fileData, index); unsigned int sampleFrequency = ReadU32(fileData, index); /*unsigned int avgbytes =*/ ReadU32(fileData, index); /*unsigned int blockalign =*/ ReadU16(fileData, index); u16 bits = ReadU16(fileData, index); if (format != 1) { LogError("Sound is not PCM data"); return false; } if (channels != 1 && channels != 2) { LogError("Sound is not either mono or stereo"); return false; } if (bits != 8 && bits != 16) { LogError("Sound is not either 8bit or 16bit"); return false; } // Search for the data chunk unsigned int data_length = 0; for(;;) { if (index >= numBytes) { LogError("No data chunk in WAV data"); return false; } u8 chunk_text[4]; ReadBytes(chunk_text, fileData, index, 4); data_length = ReadU32(fileData, index); if (!memcmp(chunk_text, "data", 4)) break; if (!data_length) return false; index += data_length; } if (!data_length) { LogError("Zero numBytes data chunk in WAV data"); return false; } std::ostringstream msg; msg << "Loaded WAV sound with " << channels << " channels " << bits << " bits, frequency " << sampleFrequency << " datasize " << data_length; LogDebug(msg.str()); dst.clear(); dst.insert(dst.end(), &fileData[index], &fileData[index + data_length]); *isStereo = (channels == 2); *is16Bit = (bits == 16); *frequency = sampleFrequency; return true; } } // ~WavLoader <commit_msg>Fix "unreferenced local function has been removed" warning.<commit_after>// For conditions of distribution and use, see copyright notice in LICENSE #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "WavLoader.h" #include "LoggingFunctions.h" #include "MemoryLeakCheck.h" #include <iostream> #include <sstream> using namespace std; static void ReadBytes(u8* dest, const u8* src, uint& index, unsigned int numBytes) { memcpy(dest, &src[index], numBytes); index += numBytes; } /// @note The following function was dead code. Bring back if needed. /*static u8 ReadU8(const u8* src, uint& index) { u8 ret = src[index]; index += sizeof(u8); return ret; }*/ static u16 ReadU16(const u8* src, uint& index) { u16 ret = *((u16*)(&src[index])); index += sizeof(u16); return ret; } static u32 ReadU32(const u8* src, uint& index) { u32 ret = *((u32*)(&src[index])); index += sizeof(u32); return ret; } namespace WavLoader { bool IdentifyWavFileInMemory(const u8 *fileData, size_t numBytes) { if (!fileData || numBytes < 4) return false; if (!memcmp(fileData, "RIFF", 4)) return true; else return false; } bool LoadWavFromFileInMemory(const u8 *fileData, size_t numBytes, std::vector<u8> &dst, bool *isStereo, bool *is16Bit, int *frequency) { if (!fileData || numBytes == 0) { LogError("Null input data passed in"); return false; } if (!isStereo || !is16Bit || !frequency) { LogError("Outputs not set"); return false; } unsigned int index = 0; u8 riff_text[4]; ReadBytes(riff_text, fileData, index, 4); if (!!memcmp(riff_text, "RIFF", 4)) { LogError("No RIFF chunk in WAV data"); return false; } if (index >= numBytes) return false; ReadU32(fileData, index); u8 wave_text[4]; ReadBytes(wave_text, fileData, index, 4); if (!!memcmp(wave_text, "WAVE", 4)) { LogError("No WAVE chunk in WAV data"); return false; } // Search for the fmt chunk for(;;) { if (index >= numBytes) { LogError("No fmt chunk in WAV data"); return false; } u8 chunk_text[4]; ReadBytes(chunk_text, fileData, index, 4); unsigned int chunk_size = ReadU32(fileData, index); if (!memcmp(chunk_text, "fmt ", 4)) break; if (!chunk_size) return false; index += chunk_size; } if (index >= numBytes) return false; u16 format = ReadU16(fileData, index); u16 channels = ReadU16(fileData, index); unsigned int sampleFrequency = ReadU32(fileData, index); /*unsigned int avgbytes =*/ ReadU32(fileData, index); /*unsigned int blockalign =*/ ReadU16(fileData, index); u16 bits = ReadU16(fileData, index); if (format != 1) { LogError("Sound is not PCM data"); return false; } if (channels != 1 && channels != 2) { LogError("Sound is not either mono or stereo"); return false; } if (bits != 8 && bits != 16) { LogError("Sound is not either 8bit or 16bit"); return false; } // Search for the data chunk unsigned int data_length = 0; for(;;) { if (index >= numBytes) { LogError("No data chunk in WAV data"); return false; } u8 chunk_text[4]; ReadBytes(chunk_text, fileData, index, 4); data_length = ReadU32(fileData, index); if (!memcmp(chunk_text, "data", 4)) break; if (!data_length) return false; index += data_length; } if (!data_length) { LogError("Zero numBytes data chunk in WAV data"); return false; } std::ostringstream msg; msg << "Loaded WAV sound with " << channels << " channels " << bits << " bits, frequency " << sampleFrequency << " datasize " << data_length; LogDebug(msg.str()); dst.clear(); dst.insert(dst.end(), &fileData[index], &fileData[index + data_length]); *isStereo = (channels == 2); *is16Bit = (bits == 16); *frequency = sampleFrequency; return true; } } // ~WavLoader <|endoftext|>
<commit_before>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, John Haddon. All rights reserved. // Copyright (c) 2011-2013, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 "boost/python.hpp" #include "boost/format.hpp" #include "IECore/MurmurHash.h" #include "IECorePython/Wrapper.h" #include "IECorePython/RunTimeTypedBinding.h" #include "Gaffer/ValuePlug.h" #include "Gaffer/Node.h" #include "GafferBindings/ValuePlugBinding.h" #include "GafferBindings/PlugBinding.h" #include "GafferBindings/Serialisation.h" using namespace boost::python; using namespace GafferBindings; using namespace Gaffer; static std::string maskedRepr( const Plug *plug, unsigned flagsMask ) { std::string result = Serialisation::classPath( plug ) + "( \"" + plug->getName().string() + "\", "; if( plug->direction()!=Plug::In ) { result += "direction = " + PlugSerialiser::directionRepr( plug->direction() ) + ", "; } object pythonPlug( PlugPtr( const_cast<Plug *>( plug ) ) ); if( PyObject_HasAttrString( pythonPlug.ptr(), "defaultValue" ) ) { object pythonDefaultValue = pythonPlug.attr( "defaultValue" )(); object r = pythonDefaultValue.attr( "__repr__" )(); extract<std::string> defaultValueExtractor( r ); std::string defaultValue = defaultValueExtractor(); if( defaultValue.size() && defaultValue[0] != '<' ) { result += "defaultValue = " + defaultValue + ", "; } else { throw IECore::Exception( boost::str( boost::format( "Default value for plug \"%s\" cannot be serialised" ) % plug->fullName() ) ); } } const unsigned flags = plug->getFlags() & flagsMask; if( flags != Plug::Default ) { result += "flags = " + PlugSerialiser::flagsRepr( flags ) + ", "; } result += ")"; return result; } static std::string repr( const Plug *plug ) { return maskedRepr( plug, Plug::All ); } void ValuePlugSerialiser::moduleDependencies( const Gaffer::GraphComponent *graphComponent, std::set<std::string> &modules ) const { PlugSerialiser::moduleDependencies( graphComponent, modules ); const ValuePlug *valuePlug = static_cast<const ValuePlug *> ( graphComponent ); object pythonPlug( ValuePlugPtr( const_cast<ValuePlug *>( valuePlug ) ) ); if( PyObject_HasAttrString( pythonPlug.ptr(), "defaultValue" ) ) { object pythonDefaultValue = pythonPlug.attr( "defaultValue" )(); std::string module = Serialisation::modulePath( pythonDefaultValue ); if( module.size() ) { modules.insert( module ); } } } std::string ValuePlugSerialiser::constructor( const Gaffer::GraphComponent *graphComponent ) const { return maskedRepr( static_cast<const Plug *>( graphComponent ), Plug::All & ~Plug::ReadOnly ); } std::string ValuePlugSerialiser::postConstructor( const Gaffer::GraphComponent *graphComponent, const std::string &identifier, const Serialisation &serialisation ) const { const Plug *plug = static_cast<const Plug *>( graphComponent ); // output a setValue() call if the plug is serialisable and has no input. // we don't do this for non-leaf plugs, since some children may have connections // which make setting the value inappropriate. if( plug->direction() == Plug::In && plug->getFlags( Plug::Serialisable ) && !plug->children().size() ) { if( !serialisation.identifier( plug->getInput<Plug>() ).size() ) { object pythonPlug( PlugPtr( const_cast<Plug *>( plug ) ) ); if( PyObject_HasAttrString( pythonPlug.ptr(), "getValue" ) ) { object pythonValue = pythonPlug.attr( "getValue" )(); std::string value = extract<std::string>( pythonValue.attr( "__repr__" )() ); return identifier + ".setValue( " + value + " )\n"; } } } return ""; } void GafferBindings::bindValuePlug() { IECorePython::RunTimeTypedClass<ValuePlug>() .GAFFERBINDINGS_DEFPLUGWRAPPERFNS( ValuePlug ) .def( "settable", &ValuePlug::settable ) .def( "setToDefault", &ValuePlug::setToDefault ) .def( "hash", (IECore::MurmurHash (ValuePlug::*)() const)&ValuePlug::hash ) .def( "hash", (void (ValuePlug::*)( IECore::MurmurHash & ) const)&ValuePlug::hash ) .def( "getCacheMemoryLimit", &ValuePlug::getCacheMemoryLimit ) .staticmethod( "getCacheMemoryLimit" ) .def( "setCacheMemoryLimit", &ValuePlug::setCacheMemoryLimit ) .staticmethod( "setCacheMemoryLimit" ) .def( "__repr__", &repr ) ; Serialisation::registerSerialiser( Gaffer::ValuePlug::staticTypeId(), new ValuePlugSerialiser ); } <commit_msg>python binding for ValuePlug.setValue()<commit_after>////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2011-2012, John Haddon. All rights reserved. // Copyright (c) 2011-2013, Image Engine Design 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 John Haddon nor the names of // any other contributors to this software 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 "boost/python.hpp" #include "boost/format.hpp" #include "IECore/MurmurHash.h" #include "IECorePython/Wrapper.h" #include "IECorePython/RunTimeTypedBinding.h" #include "Gaffer/ValuePlug.h" #include "Gaffer/Node.h" #include "GafferBindings/ValuePlugBinding.h" #include "GafferBindings/PlugBinding.h" #include "GafferBindings/Serialisation.h" using namespace boost::python; using namespace GafferBindings; using namespace Gaffer; static std::string maskedRepr( const Plug *plug, unsigned flagsMask ) { std::string result = Serialisation::classPath( plug ) + "( \"" + plug->getName().string() + "\", "; if( plug->direction()!=Plug::In ) { result += "direction = " + PlugSerialiser::directionRepr( plug->direction() ) + ", "; } object pythonPlug( PlugPtr( const_cast<Plug *>( plug ) ) ); if( PyObject_HasAttrString( pythonPlug.ptr(), "defaultValue" ) ) { object pythonDefaultValue = pythonPlug.attr( "defaultValue" )(); object r = pythonDefaultValue.attr( "__repr__" )(); extract<std::string> defaultValueExtractor( r ); std::string defaultValue = defaultValueExtractor(); if( defaultValue.size() && defaultValue[0] != '<' ) { result += "defaultValue = " + defaultValue + ", "; } else { throw IECore::Exception( boost::str( boost::format( "Default value for plug \"%s\" cannot be serialised" ) % plug->fullName() ) ); } } const unsigned flags = plug->getFlags() & flagsMask; if( flags != Plug::Default ) { result += "flags = " + PlugSerialiser::flagsRepr( flags ) + ", "; } result += ")"; return result; } static std::string repr( const Plug *plug ) { return maskedRepr( plug, Plug::All ); } void ValuePlugSerialiser::moduleDependencies( const Gaffer::GraphComponent *graphComponent, std::set<std::string> &modules ) const { PlugSerialiser::moduleDependencies( graphComponent, modules ); const ValuePlug *valuePlug = static_cast<const ValuePlug *> ( graphComponent ); object pythonPlug( ValuePlugPtr( const_cast<ValuePlug *>( valuePlug ) ) ); if( PyObject_HasAttrString( pythonPlug.ptr(), "defaultValue" ) ) { object pythonDefaultValue = pythonPlug.attr( "defaultValue" )(); std::string module = Serialisation::modulePath( pythonDefaultValue ); if( module.size() ) { modules.insert( module ); } } } std::string ValuePlugSerialiser::constructor( const Gaffer::GraphComponent *graphComponent ) const { return maskedRepr( static_cast<const Plug *>( graphComponent ), Plug::All & ~Plug::ReadOnly ); } std::string ValuePlugSerialiser::postConstructor( const Gaffer::GraphComponent *graphComponent, const std::string &identifier, const Serialisation &serialisation ) const { const Plug *plug = static_cast<const Plug *>( graphComponent ); // output a setValue() call if the plug is serialisable and has no input. // we don't do this for non-leaf plugs, since some children may have connections // which make setting the value inappropriate. if( plug->direction() == Plug::In && plug->getFlags( Plug::Serialisable ) && !plug->children().size() ) { if( !serialisation.identifier( plug->getInput<Plug>() ).size() ) { object pythonPlug( PlugPtr( const_cast<Plug *>( plug ) ) ); if( PyObject_HasAttrString( pythonPlug.ptr(), "getValue" ) ) { object pythonValue = pythonPlug.attr( "getValue" )(); std::string value = extract<std::string>( pythonValue.attr( "__repr__" )() ); return identifier + ".setValue( " + value + " )\n"; } } } return ""; } void GafferBindings::bindValuePlug() { IECorePython::RunTimeTypedClass<ValuePlug>() .GAFFERBINDINGS_DEFPLUGWRAPPERFNS( ValuePlug ) .def( "settable", &ValuePlug::settable ) .def( "setFrom", &ValuePlug::setFrom ) .def( "setToDefault", &ValuePlug::setToDefault ) .def( "hash", (IECore::MurmurHash (ValuePlug::*)() const)&ValuePlug::hash ) .def( "hash", (void (ValuePlug::*)( IECore::MurmurHash & ) const)&ValuePlug::hash ) .def( "getCacheMemoryLimit", &ValuePlug::getCacheMemoryLimit ) .staticmethod( "getCacheMemoryLimit" ) .def( "setCacheMemoryLimit", &ValuePlug::setCacheMemoryLimit ) .staticmethod( "setCacheMemoryLimit" ) .def( "__repr__", &repr ) ; Serialisation::registerSerialiser( Gaffer::ValuePlug::staticTypeId(), new ValuePlugSerialiser ); } <|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: solvrdlg.cxx,v $ * $Revision: 1.12 $ * * 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 "rangelst.hxx" #include "scitems.hxx" #include <sfx2/dispatch.hxx> #include <svtools/zforlist.hxx> #include <vcl/msgbox.hxx> #include "uiitems.hxx" #include "reffact.hxx" #include "document.hxx" #include "scresid.hxx" #include "solvrdlg.hrc" #define _SOLVRDLG_CXX #include "solvrdlg.hxx" #undef _SOLVERDLG_CXX #define ERRORBOX(s) ErrorBox( this, WinBits( WB_OK | WB_DEF_OK), s ).Execute() //============================================================================ // class ScSolverDlg //---------------------------------------------------------------------------- ScSolverDlg::ScSolverDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScDocument* pDocument, ScAddress aCursorPos ) : ScAnyRefDlg ( pB, pCW, pParent, RID_SCDLG_SOLVER ), // aFlVariables ( this, ScResId( FL_VARIABLES ) ), aFtFormulaCell ( this, ScResId( FT_FORMULACELL ) ), aEdFormulaCell ( this, ScResId( ED_FORMULACELL ) ), aRBFormulaCell ( this, ScResId( RB_FORMULACELL ), &aEdFormulaCell ), aFtTargetVal ( this, ScResId( FT_TARGETVAL ) ), aEdTargetVal ( this, ScResId( ED_TARGETVAL ) ), aFtVariableCell ( this, ScResId( FT_VARCELL ) ), aEdVariableCell ( this, ScResId( ED_VARCELL ) ), aRBVariableCell ( this, ScResId( RB_VARCELL ), &aEdVariableCell ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), // theFormulaCell ( aCursorPos ), theVariableCell ( aCursorPos ), pDoc ( pDocument ), nCurTab ( aCursorPos.Tab() ), pEdActive ( NULL ), bDlgLostFocus ( FALSE ), errMsgInvalidVar ( ScResId( STR_INVALIDVAR ) ), errMsgInvalidForm ( ScResId( STR_INVALIDFORM ) ), errMsgNoFormula ( ScResId( STR_NOFORMULA ) ), errMsgInvalidVal ( ScResId( STR_INVALIDVAL ) ) { Init(); FreeResource(); } //---------------------------------------------------------------------------- __EXPORT ScSolverDlg::~ScSolverDlg() { } //---------------------------------------------------------------------------- void __EXPORT ScSolverDlg::Init() { String aStr; aBtnOk. SetClickHdl ( LINK( this, ScSolverDlg, BtnHdl ) ); aBtnCancel. SetClickHdl ( LINK( this, ScSolverDlg, BtnHdl ) ); Link aLink = LINK( this, ScSolverDlg, GetFocusHdl ); aEdFormulaCell. SetGetFocusHdl ( aLink ); aRBFormulaCell. SetGetFocusHdl ( aLink ); aEdVariableCell.SetGetFocusHdl ( aLink ); aRBVariableCell.SetGetFocusHdl ( aLink ); aEdTargetVal. SetGetFocusHdl ( aLink ); aLink = LINK( this, ScSolverDlg, LoseFocusHdl ); aEdFormulaCell. SetLoseFocusHdl ( aLink ); aRBFormulaCell. SetLoseFocusHdl ( aLink ); aEdVariableCell.SetLoseFocusHdl ( aLink ); aRBVariableCell.SetLoseFocusHdl ( aLink ); theFormulaCell.Format( aStr, SCA_ABS ); aEdFormulaCell.SetText( aStr ); aEdFormulaCell.GrabFocus(); pEdActive = &aEdFormulaCell; } //---------------------------------------------------------------------------- BOOL __EXPORT ScSolverDlg::Close() { return DoClose( ScSolverDlgWrapper::GetChildWindowId() ); } //---------------------------------------------------------------------------- void ScSolverDlg::SetActive() { if ( bDlgLostFocus ) { bDlgLostFocus = FALSE; if( pEdActive ) pEdActive->GrabFocus(); } else { GrabFocus(); } RefInputDone(); } //---------------------------------------------------------------------------- void ScSolverDlg::SetReference( const ScRange& rRef, ScDocument* pDocP ) { if( pEdActive ) { if ( rRef.aStart != rRef.aEnd ) RefInputStart(pEdActive); String aStr; ScAddress aAdr = rRef.aStart; USHORT nFmt = ( aAdr.Tab() == nCurTab ) ? SCA_ABS : SCA_ABS_3D; aAdr.Format( aStr, nFmt, pDocP ); pEdActive->SetRefString( aStr ); if ( pEdActive == &aEdFormulaCell ) theFormulaCell = aAdr; else if ( pEdActive == &aEdVariableCell ) theVariableCell = aAdr; } } //---------------------------------------------------------------------------- void ScSolverDlg::RaiseError( ScSolverErr eError ) { switch ( eError ) { case SOLVERR_NOFORMULA: ERRORBOX( errMsgNoFormula ); aEdFormulaCell.GrabFocus(); break; case SOLVERR_INVALID_FORMULA: ERRORBOX( errMsgInvalidForm ); aEdFormulaCell.GrabFocus(); break; case SOLVERR_INVALID_VARIABLE: ERRORBOX( errMsgInvalidVar ); aEdVariableCell.GrabFocus(); break; case SOLVERR_INVALID_TARGETVALUE: ERRORBOX( errMsgInvalidVal ); aEdTargetVal.GrabFocus(); break; } } //---------------------------------------------------------------------------- BOOL ScSolverDlg::IsRefInputMode() const { return pEdActive != NULL; } //---------------------------------------------------------------------------- BOOL __EXPORT ScSolverDlg::CheckTargetValue( String& rStrVal ) { sal_uInt32 n1 = 0; double n2; return pDoc->GetFormatTable()->IsNumberFormat( rStrVal, n1, n2 ); } //---------------------------------------------------------------------------- // Handler: IMPL_LINK( ScSolverDlg, BtnHdl, PushButton*, pBtn ) { if ( pBtn == &aBtnOk ) { theTargetValStr = aEdTargetVal.GetText(); // Zu ueberpruefen: // 1. enthalten die Strings korrekte Tabellenkoordinaten/def.Namen? // 2. verweist die Formel-Koordinate wirklich auf eine Formelzelle? // 3. wurde ein korrekter Zielwert eingegeben USHORT nRes1 = theFormulaCell .Parse( aEdFormulaCell.GetText(), pDoc ); USHORT nRes2 = theVariableCell.Parse( aEdVariableCell.GetText(), pDoc ); if ( SCA_VALID == ( nRes1 & SCA_VALID ) ) { if ( SCA_VALID == ( nRes2 & SCA_VALID ) ) { if ( CheckTargetValue( theTargetValStr ) ) { CellType eType; pDoc->GetCellType( theFormulaCell.Col(), theFormulaCell.Row(), theFormulaCell.Tab(), eType ); if ( CELLTYPE_FORMULA == eType ) { ScSolveParam aOutParam( theFormulaCell, theVariableCell, theTargetValStr ); ScSolveItem aOutItem( SCITEM_SOLVEDATA, &aOutParam ); SetDispatcherLock( FALSE ); SwitchToDocument(); GetBindings().GetDispatcher()->Execute( SID_SOLVE, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD, &aOutItem, 0L, 0L ); Close(); } else RaiseError( SOLVERR_NOFORMULA ); } else RaiseError( SOLVERR_INVALID_TARGETVALUE ); } else RaiseError( SOLVERR_INVALID_VARIABLE ); } else RaiseError( SOLVERR_INVALID_FORMULA ); } else if ( pBtn == &aBtnCancel ) { Close(); } return 0; } //---------------------------------------------------------------------------- IMPL_LINK( ScSolverDlg, GetFocusHdl, Control*, pCtrl ) { Edit* pEdit = NULL; pEdActive = NULL; if( (pCtrl == (Control*)&aEdFormulaCell) || (pCtrl == (Control*)&aRBFormulaCell) ) pEdit = pEdActive = &aEdFormulaCell; else if( (pCtrl == (Control*)&aEdVariableCell) || (pCtrl == (Control*)&aRBVariableCell) ) pEdit = pEdActive = &aEdVariableCell; else if( pCtrl == (Control*)&aEdTargetVal ) pEdit = &aEdTargetVal; if( pEdit ) pEdit->SetSelection( Selection( 0, SELECTION_MAX ) ); return 0; } //---------------------------------------------------------------------------- IMPL_LINK( ScSolverDlg, LoseFocusHdl, Control*, EMPTYARG ) { bDlgLostFocus = !IsActive(); return 0; } <commit_msg>INTEGRATION: CWS koheiformula01 (1.11.314); FILE MERGED 2008/04/23 15:09:22 kohei 1.11.314.3: RESYNC: (1.11-1.12); FILE MERGED 2008/03/21 17:23:57 kohei 1.11.314.2: const a read-only variable. 2008/03/20 23:20:34 kohei 1.11.314.1: Use the current address convention everywhere instead of always using the OOo convention.<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: solvrdlg.cxx,v $ * $Revision: 1.13 $ * * 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 "rangelst.hxx" #include "scitems.hxx" #include <sfx2/dispatch.hxx> #include <svtools/zforlist.hxx> #include <vcl/msgbox.hxx> #include "uiitems.hxx" #include "reffact.hxx" #include "document.hxx" #include "scresid.hxx" #include "solvrdlg.hrc" #define _SOLVRDLG_CXX #include "solvrdlg.hxx" #undef _SOLVERDLG_CXX #define ERRORBOX(s) ErrorBox( this, WinBits( WB_OK | WB_DEF_OK), s ).Execute() //============================================================================ // class ScSolverDlg //---------------------------------------------------------------------------- ScSolverDlg::ScSolverDlg( SfxBindings* pB, SfxChildWindow* pCW, Window* pParent, ScDocument* pDocument, ScAddress aCursorPos ) : ScAnyRefDlg ( pB, pCW, pParent, RID_SCDLG_SOLVER ), // aFlVariables ( this, ScResId( FL_VARIABLES ) ), aFtFormulaCell ( this, ScResId( FT_FORMULACELL ) ), aEdFormulaCell ( this, ScResId( ED_FORMULACELL ) ), aRBFormulaCell ( this, ScResId( RB_FORMULACELL ), &aEdFormulaCell ), aFtTargetVal ( this, ScResId( FT_TARGETVAL ) ), aEdTargetVal ( this, ScResId( ED_TARGETVAL ) ), aFtVariableCell ( this, ScResId( FT_VARCELL ) ), aEdVariableCell ( this, ScResId( ED_VARCELL ) ), aRBVariableCell ( this, ScResId( RB_VARCELL ), &aEdVariableCell ), aBtnOk ( this, ScResId( BTN_OK ) ), aBtnCancel ( this, ScResId( BTN_CANCEL ) ), aBtnHelp ( this, ScResId( BTN_HELP ) ), // theFormulaCell ( aCursorPos ), theVariableCell ( aCursorPos ), pDoc ( pDocument ), nCurTab ( aCursorPos.Tab() ), pEdActive ( NULL ), bDlgLostFocus ( FALSE ), errMsgInvalidVar ( ScResId( STR_INVALIDVAR ) ), errMsgInvalidForm ( ScResId( STR_INVALIDFORM ) ), errMsgNoFormula ( ScResId( STR_NOFORMULA ) ), errMsgInvalidVal ( ScResId( STR_INVALIDVAL ) ) { Init(); FreeResource(); } //---------------------------------------------------------------------------- __EXPORT ScSolverDlg::~ScSolverDlg() { } //---------------------------------------------------------------------------- void __EXPORT ScSolverDlg::Init() { String aStr; aBtnOk. SetClickHdl ( LINK( this, ScSolverDlg, BtnHdl ) ); aBtnCancel. SetClickHdl ( LINK( this, ScSolverDlg, BtnHdl ) ); Link aLink = LINK( this, ScSolverDlg, GetFocusHdl ); aEdFormulaCell. SetGetFocusHdl ( aLink ); aRBFormulaCell. SetGetFocusHdl ( aLink ); aEdVariableCell.SetGetFocusHdl ( aLink ); aRBVariableCell.SetGetFocusHdl ( aLink ); aEdTargetVal. SetGetFocusHdl ( aLink ); aLink = LINK( this, ScSolverDlg, LoseFocusHdl ); aEdFormulaCell. SetLoseFocusHdl ( aLink ); aRBFormulaCell. SetLoseFocusHdl ( aLink ); aEdVariableCell.SetLoseFocusHdl ( aLink ); aRBVariableCell.SetLoseFocusHdl ( aLink ); theFormulaCell.Format( aStr, SCA_ABS, NULL, pDoc->GetAddressConvention() ); aEdFormulaCell.SetText( aStr ); aEdFormulaCell.GrabFocus(); pEdActive = &aEdFormulaCell; } //---------------------------------------------------------------------------- BOOL __EXPORT ScSolverDlg::Close() { return DoClose( ScSolverDlgWrapper::GetChildWindowId() ); } //---------------------------------------------------------------------------- void ScSolverDlg::SetActive() { if ( bDlgLostFocus ) { bDlgLostFocus = FALSE; if( pEdActive ) pEdActive->GrabFocus(); } else { GrabFocus(); } RefInputDone(); } //---------------------------------------------------------------------------- void ScSolverDlg::SetReference( const ScRange& rRef, ScDocument* pDocP ) { if( pEdActive ) { if ( rRef.aStart != rRef.aEnd ) RefInputStart(pEdActive); String aStr; ScAddress aAdr = rRef.aStart; USHORT nFmt = ( aAdr.Tab() == nCurTab ) ? SCA_ABS : SCA_ABS_3D; aAdr.Format( aStr, nFmt, pDocP, pDocP->GetAddressConvention() ); pEdActive->SetRefString( aStr ); if ( pEdActive == &aEdFormulaCell ) theFormulaCell = aAdr; else if ( pEdActive == &aEdVariableCell ) theVariableCell = aAdr; } } //---------------------------------------------------------------------------- void ScSolverDlg::RaiseError( ScSolverErr eError ) { switch ( eError ) { case SOLVERR_NOFORMULA: ERRORBOX( errMsgNoFormula ); aEdFormulaCell.GrabFocus(); break; case SOLVERR_INVALID_FORMULA: ERRORBOX( errMsgInvalidForm ); aEdFormulaCell.GrabFocus(); break; case SOLVERR_INVALID_VARIABLE: ERRORBOX( errMsgInvalidVar ); aEdVariableCell.GrabFocus(); break; case SOLVERR_INVALID_TARGETVALUE: ERRORBOX( errMsgInvalidVal ); aEdTargetVal.GrabFocus(); break; } } //---------------------------------------------------------------------------- BOOL ScSolverDlg::IsRefInputMode() const { return pEdActive != NULL; } //---------------------------------------------------------------------------- BOOL __EXPORT ScSolverDlg::CheckTargetValue( String& rStrVal ) { sal_uInt32 n1 = 0; double n2; return pDoc->GetFormatTable()->IsNumberFormat( rStrVal, n1, n2 ); } //---------------------------------------------------------------------------- // Handler: IMPL_LINK( ScSolverDlg, BtnHdl, PushButton*, pBtn ) { if ( pBtn == &aBtnOk ) { theTargetValStr = aEdTargetVal.GetText(); // Zu ueberpruefen: // 1. enthalten die Strings korrekte Tabellenkoordinaten/def.Namen? // 2. verweist die Formel-Koordinate wirklich auf eine Formelzelle? // 3. wurde ein korrekter Zielwert eingegeben const ScAddress::Convention eConv = pDoc->GetAddressConvention(); USHORT nRes1 = theFormulaCell .Parse( aEdFormulaCell.GetText(), pDoc, eConv ); USHORT nRes2 = theVariableCell.Parse( aEdVariableCell.GetText(), pDoc, eConv ); if ( SCA_VALID == ( nRes1 & SCA_VALID ) ) { if ( SCA_VALID == ( nRes2 & SCA_VALID ) ) { if ( CheckTargetValue( theTargetValStr ) ) { CellType eType; pDoc->GetCellType( theFormulaCell.Col(), theFormulaCell.Row(), theFormulaCell.Tab(), eType ); if ( CELLTYPE_FORMULA == eType ) { ScSolveParam aOutParam( theFormulaCell, theVariableCell, theTargetValStr ); ScSolveItem aOutItem( SCITEM_SOLVEDATA, &aOutParam ); SetDispatcherLock( FALSE ); SwitchToDocument(); GetBindings().GetDispatcher()->Execute( SID_SOLVE, SFX_CALLMODE_SLOT | SFX_CALLMODE_RECORD, &aOutItem, 0L, 0L ); Close(); } else RaiseError( SOLVERR_NOFORMULA ); } else RaiseError( SOLVERR_INVALID_TARGETVALUE ); } else RaiseError( SOLVERR_INVALID_VARIABLE ); } else RaiseError( SOLVERR_INVALID_FORMULA ); } else if ( pBtn == &aBtnCancel ) { Close(); } return 0; } //---------------------------------------------------------------------------- IMPL_LINK( ScSolverDlg, GetFocusHdl, Control*, pCtrl ) { Edit* pEdit = NULL; pEdActive = NULL; if( (pCtrl == (Control*)&aEdFormulaCell) || (pCtrl == (Control*)&aRBFormulaCell) ) pEdit = pEdActive = &aEdFormulaCell; else if( (pCtrl == (Control*)&aEdVariableCell) || (pCtrl == (Control*)&aRBVariableCell) ) pEdit = pEdActive = &aEdVariableCell; else if( pCtrl == (Control*)&aEdTargetVal ) pEdit = &aEdTargetVal; if( pEdit ) pEdit->SetSelection( Selection( 0, SELECTION_MAX ) ); return 0; } //---------------------------------------------------------------------------- IMPL_LINK( ScSolverDlg, LoseFocusHdl, Control*, EMPTYARG ) { bDlgLostFocus = !IsActive(); return 0; } <|endoftext|>
<commit_before>#include "WebClient.h" #include "Curl.h" #include "../RuntimeException.h" #include "../StringAlgorithm.h" namespace EasyCpp { namespace Net { AnyValue WebClient::getProperty(const std::string & name) { if (name == "headers") { return this->getHeaders(); } else if (name == "base_address") { return this->getBaseAddress().str(); } else if (name == "response_headers") { return this->getResponseHeaders(); } else if (name == "auth_user" || name == "auth_password") { return AnyValue(); } else if (name == "user_agent") { return this->getUserAgent(); } else return AnyValue(); } std::vector<std::string> WebClient::getProperties() { return{ "headers", "base_address", "response_headers", "auth_user", "auth_password", "user_agent" }; } void WebClient::setProperty(const std::string & name, AnyValue value) { if (name == "headers") { this->setHeaders(value.as<Bundle>()); } else if (name == "base_address") { this->setBaseAddress(URI(value.as<std::string>())); } else if (name == "response_headers") { // Read only } else if (name == "auth_user") { _password = value.as<std::string>(); } else if (name == "auth_password") { _username = value.as<std::string>(); } else if (name == "user_agent") { this->setUserAgent(value.as<std::string>()); } } AnyValue WebClient::callFunction(const std::string & name, const std::vector<AnyValue>& params) { if (name == "DownloadFile") { } else if (name == "Download") { } else if (name == "Upload") { } else if (name == "setBaseAddress") { if (params.size() != 1) { throw RuntimeException("Missing parameter"); } this->setBaseAddress(params[0].as<std::string>()); return AnyValue(); } else if (name == "getBaseAddress") { return this->getBaseAddress(); } else if (name == "setHeaders") { if (params.size() != 1) { throw RuntimeException("Missing parameter"); } this->setHeaders(params[0].as<Bundle>()); return AnyValue(); } else if (name == "getHeaders") { return this->getHeaders(); } else if (name == "setUserAgent") { if (params.size() != 1) { throw RuntimeException("Missing parameter"); } this->setUserAgent(params[0].as<std::string>()); return AnyValue(); } else if (name == "getUserAgent") { return this->getUserAgent(); } else if (name == "setCredentials") { if (params.size() != 2) { throw RuntimeException("Missing parameter"); } this->setCredentials(params[0].as<std::string>(), params[1].as<std::string>()); return AnyValue(); } else if (name == "getResponseHeaders") { return this->getResponseHeaders(); } return AnyValue(); } std::vector<std::string> WebClient::getFunctions() { return{ "DownloadFile", "Download", "Upload", "setBaseAddress", "getBaseAddress", "setHeaders", "getHeaders", "setUserAgent", "getUserAgent", "setCredentials", "getResponseHeaders" }; } void WebClient::DownloadFile(const std::string & url, VFS::OutputStreamPtr stream) { Curl curl; curl.setURL(URI(_base_uri.str() + url).str()); curl.setWriteFunction([stream](char* data, uint64_t len) { return stream->write(std::vector<uint8_t>(data, data + len)); }); if (_user_agent != "") { curl.setUserAgent(_user_agent); } else { curl.setUserAgent("libcurl-agent/1.0"); } if (_username != "" || _password != "") { curl.setUsername(_username); curl.setPassword(_password); } std::multimap<std::string, std::string> headers; for (auto& e : _headers) headers.insert({ e.first, e.second.as<std::string>() }); curl.setHeaders(headers); curl.setHeaderFunction([this](std::string header) { size_t pos = header.find(':'); if (pos != std::string::npos) { std::string key = header.substr(0, pos); std::string value = header.substr(pos + 1); _response_headers.set(trim(key), trim(value)); } }); curl.perform(); } std::string WebClient::Download(const std::string & url) { std::string result; Curl curl; curl.setURL(URI(_base_uri.str() + url).str()); curl.setOutputString(result); if (_user_agent != "") { curl.setUserAgent(_user_agent); } else { curl.setUserAgent("libcurl-agent/1.0"); } if (_username != "" || _password != "") { curl.setUsername(_username); curl.setPassword(_password); } std::multimap<std::string, std::string> headers; for (auto& e : _headers) headers.insert({ e.first, e.second }); curl.setHeaders(headers); curl.setHeaderFunction([this](std::string header) { size_t pos = header.find(':'); if (pos != std::string::npos) { _response_headers.set(trim(header.substr(0, pos)), trim(header.substr(pos + 1))); } }); curl.perform(); return result; } std::string WebClient::Upload(const std::string & url, VFS::InputStreamPtr stream) { std::string result; Curl curl; curl.setURL(URI(_base_uri.str() + url).str()); curl.setOutputString(result); curl.setReadFunction([stream](char* data, uint64_t len) { if (!stream->isGood()) return size_t(0); auto read = stream->read((size_t)std::min<uint64_t>(size_t(-1),len)); memcpy(data, read.data(), read.size()); return read.size(); }); if (_user_agent != "") { curl.setUserAgent(_user_agent); } else { curl.setUserAgent("libcurl-agent/1.0"); } if (_username != "" || _password != "") { curl.setUsername(_username); curl.setPassword(_password); } std::multimap<std::string, std::string> headers; for (auto& e : _headers) headers.insert({ e.first, e.second }); curl.setHeaders(headers); curl.setHeaderFunction([this](std::string header) { size_t pos = header.find(':'); if (pos != std::string::npos) { _response_headers.set(trim(header.substr(0, pos)), trim(header.substr(pos + 1))); } }); curl.perform(); return result; } std::string WebClient::Upload(const std::string & url, const std::string & data) { std::string result; Curl curl; curl.setURL(URI(_base_uri.str() + url).str()); curl.setOutputString(result); curl.setInputString(data); if (_user_agent != "") { curl.setUserAgent(_user_agent); } else { curl.setUserAgent("libcurl-agent/1.0"); } if (_username != "" || _password != "") { curl.setUsername(_username); curl.setPassword(_password); } std::multimap<std::string, std::string> headers; for (auto& e : _headers) headers.insert({ e.first, e.second }); curl.setHeaders(headers); curl.setHeaderFunction([this](std::string header) { size_t pos = header.find(':'); if (pos != std::string::npos) { _response_headers.set(trim(header.substr(0, pos)), trim(header.substr(pos + 1))); } }); curl.perform(); return result; } std::string WebClient::Upload(const std::string & url, const Bundle & b) { std::vector<std::string> elems; for (auto& e : b) { elems.push_back(URI::URLEncode(e.first) + "=" + URI::URLEncode(e.second.as<std::string>())); } return this->Upload(url, implode<std::string>("&", elems)); } void WebClient::setBaseAddress(const URI & base) { _base_uri = base; } URI WebClient::getBaseAddress() { return _base_uri; } void WebClient::setHeaders(const Bundle & headers) { _headers = headers; } Bundle WebClient::getHeaders() { return _headers; } void WebClient::setUserAgent(const std::string & ua) { _user_agent = ua; } std::string WebClient::getUserAgent() { return _user_agent; } void WebClient::setCredentials(const std::string & user, const std::string & pass) { _username = user; _password = pass; } Bundle WebClient::getResponseHeaders() { return _response_headers; } } }<commit_msg>Fixed copy paste error<commit_after>#include "WebClient.h" #include "Curl.h" #include "../RuntimeException.h" #include "../StringAlgorithm.h" #include <cstring> namespace EasyCpp { namespace Net { AnyValue WebClient::getProperty(const std::string & name) { if (name == "headers") { return this->getHeaders(); } else if (name == "base_address") { return this->getBaseAddress().str(); } else if (name == "response_headers") { return this->getResponseHeaders(); } else if (name == "auth_user" || name == "auth_password") { return AnyValue(); } else if (name == "user_agent") { return this->getUserAgent(); } else return AnyValue(); } std::vector<std::string> WebClient::getProperties() { return{ "headers", "base_address", "response_headers", "auth_user", "auth_password", "user_agent" }; } void WebClient::setProperty(const std::string & name, AnyValue value) { if (name == "headers") { this->setHeaders(value.as<Bundle>()); } else if (name == "base_address") { this->setBaseAddress(URI(value.as<std::string>())); } else if (name == "response_headers") { // Read only } else if (name == "auth_user") { _password = value.as<std::string>(); } else if (name == "auth_password") { _username = value.as<std::string>(); } else if (name == "user_agent") { this->setUserAgent(value.as<std::string>()); } } AnyValue WebClient::callFunction(const std::string & name, const std::vector<AnyValue>& params) { if (name == "DownloadFile") { } else if (name == "Download") { } else if (name == "Upload") { } else if (name == "setBaseAddress") { if (params.size() != 1) { throw RuntimeException("Missing parameter"); } this->setBaseAddress(params[0].as<std::string>()); return AnyValue(); } else if (name == "getBaseAddress") { return this->getBaseAddress(); } else if (name == "setHeaders") { if (params.size() != 1) { throw RuntimeException("Missing parameter"); } this->setHeaders(params[0].as<Bundle>()); return AnyValue(); } else if (name == "getHeaders") { return this->getHeaders(); } else if (name == "setUserAgent") { if (params.size() != 1) { throw RuntimeException("Missing parameter"); } this->setUserAgent(params[0].as<std::string>()); return AnyValue(); } else if (name == "getUserAgent") { return this->getUserAgent(); } else if (name == "setCredentials") { if (params.size() != 2) { throw RuntimeException("Missing parameter"); } this->setCredentials(params[0].as<std::string>(), params[1].as<std::string>()); return AnyValue(); } else if (name == "getResponseHeaders") { return this->getResponseHeaders(); } return AnyValue(); } std::vector<std::string> WebClient::getFunctions() { return{ "DownloadFile", "Download", "Upload", "setBaseAddress", "getBaseAddress", "setHeaders", "getHeaders", "setUserAgent", "getUserAgent", "setCredentials", "getResponseHeaders" }; } void WebClient::DownloadFile(const std::string & url, VFS::OutputStreamPtr stream) { Curl curl; curl.setURL(URI(_base_uri.str() + url).str()); curl.setWriteFunction([stream](char* data, uint64_t len) { return stream->write(std::vector<uint8_t>(data, data + len)); }); if (_user_agent != "") { curl.setUserAgent(_user_agent); } else { curl.setUserAgent("libcurl-agent/1.0"); } if (_username != "" || _password != "") { curl.setUsername(_username); curl.setPassword(_password); } std::multimap<std::string, std::string> headers; for (auto& e : _headers) headers.insert({ e.first, e.second.as<std::string>() }); curl.setHeaders(headers); curl.setHeaderFunction([this](std::string header) { size_t pos = header.find(':'); if (pos != std::string::npos) { std::string key = header.substr(0, pos); std::string value = header.substr(pos + 1); _response_headers.set(trim(key), trim(value)); } }); curl.perform(); } std::string WebClient::Download(const std::string & url) { std::string result; Curl curl; curl.setURL(URI(_base_uri.str() + url).str()); curl.setOutputString(result); if (_user_agent != "") { curl.setUserAgent(_user_agent); } else { curl.setUserAgent("libcurl-agent/1.0"); } if (_username != "" || _password != "") { curl.setUsername(_username); curl.setPassword(_password); } std::multimap<std::string, std::string> headers; for (auto& e : _headers) headers.insert({ e.first, e.second.as<std::string>() }); curl.setHeaders(headers); curl.setHeaderFunction([this](std::string header) { size_t pos = header.find(':'); if (pos != std::string::npos) { std::string key = header.substr(0, pos); std::string value = header.substr(pos + 1); _response_headers.set(trim(key), trim(value)); } }); curl.perform(); return result; } std::string WebClient::Upload(const std::string & url, VFS::InputStreamPtr stream) { std::string result; Curl curl; curl.setURL(URI(_base_uri.str() + url).str()); curl.setOutputString(result); curl.setReadFunction([stream](char* data, uint64_t len) { if (!stream->isGood()) return size_t(0); auto read = stream->read((size_t)std::min<uint64_t>(size_t(-1),len)); memcpy(data, read.data(), read.size()); return read.size(); }); if (_user_agent != "") { curl.setUserAgent(_user_agent); } else { curl.setUserAgent("libcurl-agent/1.0"); } if (_username != "" || _password != "") { curl.setUsername(_username); curl.setPassword(_password); } std::multimap<std::string, std::string> headers; for (auto& e : _headers) headers.insert({ e.first, e.second.as<std::string>() }); curl.setHeaders(headers); curl.setHeaderFunction([this](std::string header) { size_t pos = header.find(':'); if (pos != std::string::npos) { std::string key = header.substr(0, pos); std::string value = header.substr(pos + 1); _response_headers.set(trim(key), trim(value)); } }); curl.perform(); return result; } std::string WebClient::Upload(const std::string & url, const std::string & data) { std::string result; Curl curl; curl.setURL(URI(_base_uri.str() + url).str()); curl.setOutputString(result); curl.setInputString(data); if (_user_agent != "") { curl.setUserAgent(_user_agent); } else { curl.setUserAgent("libcurl-agent/1.0"); } if (_username != "" || _password != "") { curl.setUsername(_username); curl.setPassword(_password); } std::multimap<std::string, std::string> headers; for (auto& e : _headers) headers.insert({ e.first, e.second.as<std::string>() }); curl.setHeaders(headers); curl.setHeaderFunction([this](std::string header) { size_t pos = header.find(':'); if (pos != std::string::npos) { std::string key = header.substr(0, pos); std::string value = header.substr(pos + 1); _response_headers.set(trim(key), trim(value)); } }); curl.perform(); return result; } std::string WebClient::Upload(const std::string & url, const Bundle & b) { std::vector<std::string> elems; for (auto& e : b) { elems.push_back(URI::URLEncode(e.first) + "=" + URI::URLEncode(e.second.as<std::string>())); } return this->Upload(url, implode<std::string>("&", elems)); } void WebClient::setBaseAddress(const URI & base) { _base_uri = base; } URI WebClient::getBaseAddress() { return _base_uri; } void WebClient::setHeaders(const Bundle & headers) { _headers = headers; } Bundle WebClient::getHeaders() { return _headers; } void WebClient::setUserAgent(const std::string & ua) { _user_agent = ua; } std::string WebClient::getUserAgent() { return _user_agent; } void WebClient::setCredentials(const std::string & user, const std::string & pass) { _username = user; _password = pass; } Bundle WebClient::getResponseHeaders() { return _response_headers; } } }<|endoftext|>
<commit_before> #include <stdio.h> #include <stdlib.h> #include <time.h> int main ( int argc, char *argv[] ) { time_t rawtime; struct tm * timeinfo; char buffer [256]; if ( argc != 10 ) return 1; FILE * pFile; pFile = fopen( argv[1], "w" ); if (pFile!=NULL) { time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (buffer,256,"%c %Z",timeinfo); // // The version string should be something like this: // "CMISS(cmgui) version @CMGUI_MAJOR_VERSION@.@CMGUI_MINOR_VERSION@.@CMGUI_PATCH_VERSION@ [DATE]\nCopyright 1996-[YEAR], Auckland UniServices Ltd." // fprintf( pFile, "\n#if !defined GENERATED_VERSION_H\n#define GENERATED_VERSION_H\n\n" ); fprintf( pFile, "#define CMISS_NAME_STRING \"CMISS(cmgui)\"\n" ); fprintf( pFile, "#define CMISS_VERSION_STRING \"%d.%d.%d\"\n", atoi(argv[2]),atoi(argv[3]),atoi(argv[4]) ); fprintf( pFile, "#define CMISS_DATE_STRING \"%s\"\n", buffer ); fprintf( pFile, "#define CMISS_COPYRIGHT_STRING \"Copyright 1996-2009, Auckland UniServices Ltd.\"\n" ); fprintf( pFile, "#define CMISS_SVN_REVISION_STRING \"%d\"\n", atoi(argv[5]) ); fprintf( pFile, "#define CMISS_BUILD_STRING \"%s %s %s %s\"\n", argv[6], argv[7], argv[8], argv[9] ); fprintf( pFile, "\n#endif\n\n" ); fclose (pFile); } return 0; } <commit_msg>Updating version helper application to push out only a date string. This is used by the build time GenerateVersionHeader script.<commit_after> #include <stdio.h> #include <stdlib.h> #include <time.h> int main ( int argc, char *argv[] ) { time_t rawtime; struct tm * timeinfo; char buffer [256]; if ( argc == 1) { time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (buffer,256,"%d/%m/%y %X %Z",timeinfo); printf( "%s\n", buffer ); return 0; } if ( argc != 10 ) return 1; FILE * pFile; pFile = fopen( argv[1], "w" ); if (pFile!=NULL) { time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (buffer,256,"%d/%m/%y %X %Z",timeinfo); // // The version string should be something like this: // "CMISS(cmgui) version @CMGUI_MAJOR_VERSION@.@CMGUI_MINOR_VERSION@.@CMGUI_PATCH_VERSION@ [DATE]\nCopyright 1996-[YEAR], Auckland UniServices Ltd." // fprintf( pFile, "\n#if !defined GENERATED_VERSION_H\n#define GENERATED_VERSION_H\n\n" ); fprintf( pFile, "#define CMISS_NAME_STRING \"CMISS(cmgui)\"\n" ); fprintf( pFile, "#define CMISS_VERSION_STRING \"%d.%d.%d\"\n", atoi(argv[2]),atoi(argv[3]),atoi(argv[4]) ); fprintf( pFile, "#define CMISS_DATE_STRING \"%s\"\n", buffer ); fprintf( pFile, "#define CMISS_COPYRIGHT_STRING \"Copyright 1996-2009, Auckland UniServices Ltd.\"\n" ); fprintf( pFile, "#define CMISS_SVN_REVISION_STRING \"%d\"\n", atoi(argv[5]) ); fprintf( pFile, "#define CMISS_BUILD_STRING \"%s %s %s %s\"\n", argv[6], argv[7], argv[8], argv[9] ); fprintf( pFile, "\n#endif\n\n" ); fclose (pFile); } return 0; } <|endoftext|>
<commit_before>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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. // For std::equal() on Windows. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #include <iostream> // TODO: Remove this temporary include. #include <sstream> #include "gtest/gtest.h" #include "BitFunnel/RowIdSequence.h" #include "DocumentFrequencyTable.h" #include "TermTable.h" #include "TermTableBuilder.h" #include "TermTreatments.h" namespace BitFunnel { class MockTermTreatment : public ITermTreatment { public: // // ITermTreatment methods. // virtual RowConfiguration GetTreatment(Term term) const override { return m_configurations[term.GetRawHash()]; } void OpenConfiguration() { m_current = RowConfiguration(); } void AddEntry(Rank rank, RowIndex count, bool isPrivate) { m_current.push_front(RowConfiguration::Entry(rank, count, isPrivate)); } void CloseConfiguration() { m_configurations.push_back(m_current); } private: RowConfiguration m_current; // MockTermTreatment uses the Term::Hash as the index into the vector // of RowConfigurations. std::vector<RowConfiguration> m_configurations; }; class TestEnvironment { public: TestEnvironment() { // For this test, configurations will be indexed by the Term::Hash // values which we expect will be presented to the TermTableBuilder // in increasing order from 0 to ??. // Therefore we add RowConfigurations() in the order that we expect // they will be used by the TermTableBuilder. Each RowConfiguration // will be used once. // // Construct DocumentFrequencyTable // std::stringstream input; input << // Rank:RowIndex "0,1,1,.9\n" // 0:0 "1,1,1,.7\n" // 0:1 "2,1,1,.07\n" // 0:2 "3,1,1,.05\n" // 0:3 "4,1,1,.02\n" // 0:2 "5,1,1,.0099\n" // 0:2, 0:3 "6,1,1,.0098\n" // 0:3, 4:0 ""; m_documentFrequencyTable.reset(new DocumentFrequencyTable(input)); // // Construct TermTreatment data. // // // Construct expected TermTable. // std::vector<RowIndex> rows; for (Rank r = 0; r <= c_maxRankValue; ++r) { rows.push_back(0); } Term::Hash hash = 0ull; // First term configured as private rank 0 so it should go in its // own row. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, true); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, rows[0]++)); m_termTable.CloseTerm(hash++); // Second term is configurated as a single shared rank 0 row, but // will be placed in its own row because of its high density of 0.7. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, rows[0]++)); m_termTable.CloseTerm(hash++); // Third row is configured as a single shared rank 0 row. It's // density of 0.07 is low enough that it will share with the fifth // row. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.CloseConfiguration(); RowIndex third = rows[0]; m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, rows[0]++)); m_termTable.CloseTerm(hash++); // Fourth row is configured as a single shared rank 0 row. It's // density of 0.05 is low enough that it will share with the sixth // and seventh rows. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.CloseConfiguration(); RowIndex fourth = rows[0]; m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, rows[0]++)); m_termTable.CloseTerm(hash++); // Fifth row is configured as a single shared rank 0 row. It's // density of 0.02 is low enough that it will share with the // third row. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, third)); m_termTable.CloseTerm(hash++); // Sixth row is configured as a pair of shared rank 0 rows. It's // density of 0.01 is low enough that it will share with the third // and fourth rows. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 2, false); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, third)); m_termTable.AddRowId(RowId(0, 0, fourth)); m_termTable.CloseTerm(hash++); // Seventh row is configured two shared rows, one rank 0 and one // rank 4. Seventh row's frequency of 0.01 is great enough to // require a private row at rank 4. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.AddEntry(4, 1, false); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, fourth)); m_termTable.AddRowId(RowId(0, 4, rows[4]++)); m_termTable.CloseTerm(hash++); } DocumentFrequencyTable const & GetDocFrequencyTable() const { return *m_documentFrequencyTable; } TermTable const & GetTermTable() const { return m_termTable; } ITermTreatment const & GetTermTreatment() const { return m_termTreatment; } private: std::unique_ptr<DocumentFrequencyTable> m_documentFrequencyTable; MockTermTreatment m_termTreatment; TermTable m_termTable; }; namespace TermTableBuilderTest { TEST(TermTableBuilder, GeneralCases) { // Construct a test environment that provides the ITermTreatment // and DocumentFrequencyTable to be used by the TermTableBuilder. // The test environement also provides a hand-constructed expected // TermTable for verification purposes. TestEnvironment environment; // Run the TermTableBuilder to configure a TermTable. ITermTreatment const & treatment = environment.GetTermTreatment(); DocumentFrequencyTable const & terms = environment.GetDocFrequencyTable(); TermTable termTable; double density = 0.1; double adhocFrequency = 0.0001; TermTableBuilder builder(density, adhocFrequency, treatment, terms, termTable); // // Verify that configured TermTable is the same as the expected // TermTable provided by the enviornment. // // Ensure that all known terms have the same RowIdSequences. // NOTE: This test relies on the existence of a separate unit test // for TermTable that ensures that RowIds and Terms are added // correctly. Without such a test, a bogus TermTable that ignores // all RowId additions would allow TermTableBuilderTest to pass. for (auto term : terms) { RowIdSequence expected(term.GetTerm(), environment.GetTermTable()); RowIdSequence observed(term.GetTerm(), termTable); EXPECT_TRUE(std::equal(observed.begin(), observed.end(), expected.begin())); EXPECT_TRUE(std::equal(expected.begin(), expected.end(), observed.begin())); } // NOTE: This test relies on the existence of a separate unit test // for TermTable that ensures that row counts are recorded // correctly. Without such a test, a bogus TermTable that ignores // all SetRowCounts would allow TermTableBuilderTest to pass. for (Rank rank = 0; rank <= c_maxRankValue; ++rank) { EXPECT_EQ(termTable.GetTotalRowCount(rank), environment.GetTermTable().GetTotalRowCount(rank)); } // TODO: Verify adhoc // TODO: Verify facts // TODO: Verify row counts. } } } #ifdef _MSC_VER #pragma warning(pop) #endif <commit_msg>Fixed TermTableBuilder.GeneralCases failure.<commit_after>// The MIT License (MIT) // Copyright (c) 2016, Microsoft // 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. // For std::equal() on Windows. #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #include <iostream> // TODO: Remove this temporary include. #include <sstream> #include "gtest/gtest.h" #include "BitFunnel/RowIdSequence.h" #include "DocumentFrequencyTable.h" #include "TermTable.h" #include "TermTableBuilder.h" #include "TermTreatments.h" namespace BitFunnel { class MockTermTreatment : public ITermTreatment { public: // // ITermTreatment methods. // virtual RowConfiguration GetTreatment(Term term) const override { return m_configurations[term.GetRawHash()]; } void OpenConfiguration() { m_current = RowConfiguration(); } void AddEntry(Rank rank, RowIndex count, bool isPrivate) { m_current.push_front(RowConfiguration::Entry(rank, count, isPrivate)); } void CloseConfiguration() { m_configurations.push_back(m_current); } private: RowConfiguration m_current; // MockTermTreatment uses the Term::Hash as the index into the vector // of RowConfigurations. std::vector<RowConfiguration> m_configurations; }; class TestEnvironment { public: TestEnvironment() { // For this test, configurations will be indexed by the Term::Hash // values which we expect will be presented to the TermTableBuilder // in increasing order from 0 to ??. // Therefore we add RowConfigurations() in the order that we expect // they will be used by the TermTableBuilder. Each RowConfiguration // will be used once. // // Construct DocumentFrequencyTable // std::stringstream input; input << // Rank:RowIndex "0,1,1,.9\n" // 0:0 "1,1,1,.7\n" // 0:1 "2,1,1,.07\n" // 0:2 "3,1,1,.05\n" // 0:3 "4,1,1,.02\n" // 0:2 "5,1,1,.0099\n" // 0:2, 0:3 "6,1,1,.0098\n" // 0:3, 4:0 ""; m_documentFrequencyTable.reset(new DocumentFrequencyTable(input)); // // Construct TermTreatment data. // // // Construct expected TermTable. // std::vector<RowIndex> rows; for (Rank r = 0; r <= c_maxRankValue; ++r) { rows.push_back(0); } Term::Hash hash = 0ull; // First term configured as private rank 0 so it should go in its // own row. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, true); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, rows[0]++)); m_termTable.CloseTerm(hash++); // Second term is configurated as a single shared rank 0 row, but // will be placed in its own row because of its high density of 0.7. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, rows[0]++)); m_termTable.CloseTerm(hash++); // Third row is configured as a single shared rank 0 row. It's // density of 0.07 is low enough that it will share with the fifth // row. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.CloseConfiguration(); RowIndex third = rows[0]; m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, rows[0]++)); m_termTable.CloseTerm(hash++); // Fourth row is configured as a single shared rank 0 row. It's // density of 0.05 is low enough that it will share with the sixth // and seventh rows. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.CloseConfiguration(); RowIndex fourth = rows[0]; m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, rows[0]++)); m_termTable.CloseTerm(hash++); // Fifth row is configured as a single shared rank 0 row. It's // density of 0.02 is low enough that it will share with the // third row. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, third)); m_termTable.CloseTerm(hash++); // Sixth row is configured as a pair of shared rank 0 rows. It's // density of 0.01 is low enough that it will share with the third // and fourth rows. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 2, false); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, third)); m_termTable.AddRowId(RowId(0, 0, fourth)); m_termTable.CloseTerm(hash++); // Seventh row is configured two shared rows, one rank 0 and one // rank 4. Seventh row's frequency of 0.01 is great enough to // require a private row at rank 4. m_termTreatment.OpenConfiguration(); m_termTreatment.AddEntry(0, 1, false); m_termTreatment.AddEntry(4, 1, false); m_termTreatment.CloseConfiguration(); m_termTable.OpenTerm(); m_termTable.AddRowId(RowId(0, 0, fourth)); m_termTable.AddRowId(RowId(0, 4, rows[4]++)); m_termTable.CloseTerm(hash++); m_termTable.SetRowCounts(0, 4, 0); m_termTable.SetRowCounts(4, 1, 0); } DocumentFrequencyTable const & GetDocFrequencyTable() const { return *m_documentFrequencyTable; } TermTable const & GetTermTable() const { return m_termTable; } ITermTreatment const & GetTermTreatment() const { return m_termTreatment; } private: std::unique_ptr<DocumentFrequencyTable> m_documentFrequencyTable; MockTermTreatment m_termTreatment; TermTable m_termTable; }; namespace TermTableBuilderTest { TEST(TermTableBuilder, GeneralCases) { // Construct a test environment that provides the ITermTreatment // and DocumentFrequencyTable to be used by the TermTableBuilder. // The test environement also provides a hand-constructed expected // TermTable for verification purposes. TestEnvironment environment; // Run the TermTableBuilder to configure a TermTable. ITermTreatment const & treatment = environment.GetTermTreatment(); DocumentFrequencyTable const & terms = environment.GetDocFrequencyTable(); TermTable termTable; double density = 0.1; double adhocFrequency = 0.0001; TermTableBuilder builder(density, adhocFrequency, treatment, terms, termTable); // // Verify that configured TermTable is the same as the expected // TermTable provided by the enviornment. // // Ensure that all known terms have the same RowIdSequences. // NOTE: This test relies on the existence of a separate unit test // for TermTable that ensures that RowIds and Terms are added // correctly. Without such a test, a bogus TermTable that ignores // all RowId additions would allow TermTableBuilderTest to pass. for (auto term : terms) { RowIdSequence expected(term.GetTerm(), environment.GetTermTable()); RowIdSequence observed(term.GetTerm(), termTable); EXPECT_TRUE(std::equal(observed.begin(), observed.end(), expected.begin())); EXPECT_TRUE(std::equal(expected.begin(), expected.end(), observed.begin())); } // NOTE: This test relies on the existence of a separate unit test // for TermTable that ensures that row counts are recorded // correctly. Without such a test, a bogus TermTable that ignores // all SetRowCounts would allow TermTableBuilderTest to pass. for (Rank rank = 0; rank <= c_maxRankValue; ++rank) { EXPECT_EQ(termTable.GetTotalRowCount(rank), environment.GetTermTable().GetTotalRowCount(rank)); } // TODO: Verify adhoc // TODO: Verify facts // TODO: Verify row counts. } } } #ifdef _MSC_VER #pragma warning(pop) #endif <|endoftext|>
<commit_before>/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ #include "storage/TupleStreamWrapper.h" #include "common/TupleSchema.h" #include "common/types.h" #include "common/NValue.hpp" #include "common/ValuePeeker.hpp" #include "common/tabletuple.h" #include "common/ExportSerializeIo.h" #include "common/executorcontext.hpp" #include <cstdio> #include <iostream> #include <cassert> #include <ctime> #include <utility> #include <math.h> using namespace std; using namespace voltdb; const int METADATA_COL_CNT = 6; const int MAX_BUFFER_AGE = 4000; TupleStreamWrapper::TupleStreamWrapper(CatalogId partitionId, int64_t siteId) : m_partitionId(partitionId), m_siteId(siteId), m_lastFlush(0), m_defaultCapacity(EL_BUFFER_SIZE), m_uso(0), m_currBlock(NULL), m_openSpHandle(0), m_openTransactionUso(0), m_committedSpHandle(0), m_committedUso(0), m_signature(""), m_generation(0) { extendBufferChain(m_defaultCapacity); } void TupleStreamWrapper::setDefaultCapacity(size_t capacity) { assert (capacity > 0); if (m_uso != 0 || m_openSpHandle != 0 || m_openTransactionUso != 0 || m_committedSpHandle != 0) { throwFatalException("setDefaultCapacity only callable before " "TupleStreamWrapper is used"); } cleanupManagedBuffers(); m_defaultCapacity = capacity; extendBufferChain(m_defaultCapacity); } /* * Essentially, shutdown. */ void TupleStreamWrapper::cleanupManagedBuffers() { StreamBlock *sb = NULL; discardBlock(m_currBlock); m_currBlock = NULL; while (m_pendingBlocks.empty() != true) { sb = m_pendingBlocks.front(); m_pendingBlocks.pop_front(); discardBlock(sb); } } void TupleStreamWrapper::setSignatureAndGeneration(std::string signature, int64_t generation) { assert(generation > m_generation); assert(signature == m_signature || m_signature == string("")); //The first time through this is catalog load and m_generation will be 0 //Don't send the end of stream notice. if (generation != m_generation && m_generation > 0) { //Notify that no more data is coming from this generation. ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, NULL, false, true); /* * With the new generational code the USO is reset to 0 for each * generation. The sequence number stored on the table outside the wrapper * is not reset and remains constant. USO is really just for transport purposes. */ m_uso = 0; m_openSpHandle = 0; m_openTransactionUso = 0; m_committedSpHandle = 0; m_committedUso = 0; //Reconstruct the next block so it has a USO of 0. assert(m_currBlock->offset() == 0); extendBufferChain(m_defaultCapacity); } m_signature = signature; m_generation = generation; } /* * Handoff fully committed blocks to the top end. * * This is the only function that should modify m_openSpHandle, * m_openTransactionUso. */ void TupleStreamWrapper::commit(int64_t lastCommittedSpHandle, int64_t currentSpHandle, bool sync) { if (currentSpHandle < m_openSpHandle) { throwFatalException("Active transactions moving backwards"); } // more data for an ongoing transaction with no new committed data if ((currentSpHandle == m_openSpHandle) && (lastCommittedSpHandle == m_committedSpHandle)) { //std::cout << "Current spHandle(" << currentSpHandle << ") == m_openSpHandle(" << m_openSpHandle << //") && lastCommittedSpHandle(" << lastCommittedSpHandle << ") m_committedSpHandle(" << //m_committedSpHandle << ")" << std::endl; if (sync) { ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, NULL, true, false); } return; } // If the current TXN ID has advanced, then we know that: // - The old open transaction has been committed // - The current transaction is now our open transaction if (m_openSpHandle < currentSpHandle) { //std::cout << "m_openSpHandle(" << m_openSpHandle << ") < currentSpHandle(" //<< currentSpHandle << ")" << std::endl; m_committedUso = m_uso; // Advance the tip to the new transaction. m_committedSpHandle = m_openSpHandle; m_openSpHandle = currentSpHandle; } // now check to see if the lastCommittedSpHandle tells us that our open // transaction should really be committed. If so, update the // committed state. if (m_openSpHandle <= lastCommittedSpHandle) { //std::cout << "m_openSpHandle(" << m_openSpHandle << ") <= lastCommittedSpHandle(" << //lastCommittedSpHandle << ")" << std::endl; m_committedUso = m_uso; m_committedSpHandle = m_openSpHandle; } while (!m_pendingBlocks.empty()) { StreamBlock* block = m_pendingBlocks.front(); //std::cout << "m_committedUso(" << m_committedUso << "), block->uso() + block->offset() == " //<< (block->uso() + block->offset()) << std::endl; // check that the entire remainder is committed if (m_committedUso >= (block->uso() + block->offset())) { //The block is handed off to the topend which is responsible for releasing the //memory associated with the block data. The metadata is deleted here. ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, block, false, false); delete block; m_pendingBlocks.pop_front(); } else { break; } } if (sync) { ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, NULL, true, false); } } /* * Discard all data with a uso gte mark */ void TupleStreamWrapper::rollbackTo(size_t mark) { if (mark > m_uso) { throwFatalException("Truncating the future."); } // back up the universal stream counter m_uso = mark; // working from newest to oldest block, throw // away blocks that are fully after mark; truncate // the block that contains mark. if (!(m_currBlock->uso() >= mark)) { m_currBlock->truncateTo(mark); } else { StreamBlock *sb = NULL; discardBlock(m_currBlock); m_currBlock = NULL; while (m_pendingBlocks.empty() != true) { sb = m_pendingBlocks.back(); m_pendingBlocks.pop_back(); if (sb->uso() >= mark) { discardBlock(sb); } else { sb->truncateTo(mark); m_currBlock = sb; break; } } } } /* * Correctly release and delete a managed buffer that won't * be handed off */ void TupleStreamWrapper::discardBlock(StreamBlock *sb) { delete [] sb->rawPtr(); delete sb; } /* * Allocate another buffer, preserving the current buffer's content in * the pending queue. */ void TupleStreamWrapper::extendBufferChain(size_t minLength) { if (m_defaultCapacity < minLength) { // exportxxx: rollback instead? throwFatalException("Default capacity is less than required buffer size."); } if (m_currBlock) { if (m_currBlock->offset() > 0) { if (m_committedUso >= (m_currBlock->uso() + m_currBlock->offset())) { //The block is handed off to the topend which is responsible for releasing the //memory associated with the block data. The metadata is deleted here. ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, m_currBlock, false, false); delete m_currBlock; } else { m_pendingBlocks.push_back(m_currBlock); m_currBlock = NULL; } } // fully discard empty blocks. makes valgrind/testcase // conclusion easier. else { discardBlock(m_currBlock); m_currBlock = NULL; } } char *buffer = new char[m_defaultCapacity]; if (!buffer) { throwFatalException("Failed to claim managed buffer for Export."); } m_currBlock = new StreamBlock(buffer, m_defaultCapacity, m_uso); } /* * Create a new buffer and flush all pending committed data. * Creating a new buffer will push all queued data into the * pending list for commit to operate against. */ void TupleStreamWrapper::periodicFlush(int64_t timeInMillis, int64_t lastCommittedSpHandle, int64_t currentSpHandle) { // negative timeInMillis instructs a mandatory flush if (timeInMillis < 0 || (timeInMillis - m_lastFlush > MAX_BUFFER_AGE)) { if (timeInMillis > 0) { m_lastFlush = timeInMillis; } extendBufferChain(0); commit(lastCommittedSpHandle, currentSpHandle, timeInMillis < 0 ? true : false); } } /* * If SpHandle represents a new transaction, commit previous data. * Always serialize the supplied tuple in to the stream. * Return m_uso before this invocation - this marks the point * in the stream the caller can rollback to if this append * should be rolled back. */ size_t TupleStreamWrapper::appendTuple(int64_t lastCommittedSpHandle, int64_t spHandle, int64_t seqNo, int64_t uniqueId, int64_t timestamp, TableTuple &tuple, TupleStreamWrapper::Type type) { size_t rowHeaderSz = 0; size_t tupleMaxLength = 0; // Transaction IDs for transactions applied to this tuple stream // should always be moving forward in time. if (spHandle < m_openSpHandle) { throwFatalException( "Active transactions moving backwards: openSpHandle is %jd, while the append spHandle is %jd", (intmax_t)m_openSpHandle, (intmax_t)spHandle ); } commit(lastCommittedSpHandle, spHandle); // Compute the upper bound on bytes required to serialize tuple. // exportxxx: can memoize this calculation. tupleMaxLength = computeOffsets(tuple, &rowHeaderSz); if (!m_currBlock) { extendBufferChain(m_defaultCapacity); } if ((m_currBlock->rawLength() + tupleMaxLength) > m_defaultCapacity) { extendBufferChain(tupleMaxLength); } // initialize the full row header to 0. This also // has the effect of setting each column non-null. ::memset(m_currBlock->mutableDataPtr(), 0, rowHeaderSz); // the nullarray lives in rowheader after the 4 byte header length prefix uint8_t *nullArray = reinterpret_cast<uint8_t*>(m_currBlock->mutableDataPtr() + sizeof (int32_t)); // position the serializer after the full rowheader ExportSerializeOutput io(m_currBlock->mutableDataPtr() + rowHeaderSz, m_currBlock->remaining() - rowHeaderSz); // write metadata columns io.writeLong(spHandle); io.writeLong(timestamp); io.writeLong(seqNo); io.writeLong(m_partitionId); io.writeLong(m_siteId); // use 1 for INSERT EXPORT op, 0 for DELETE EXPORT op io.writeLong((type == INSERT) ? 1L : 0L); // write the tuple's data tuple.serializeToExport(io, METADATA_COL_CNT, nullArray); // write the row size in to the row header // rowlength does not include the 4 byte row header // but does include the null array. ExportSerializeOutput hdr(m_currBlock->mutableDataPtr(), 4); hdr.writeInt((int32_t)(io.position()) + (int32_t)rowHeaderSz - 4); // update m_offset m_currBlock->consumed(rowHeaderSz + io.position()); // update uso. const size_t startingUso = m_uso; m_uso += (rowHeaderSz + io.position()); return startingUso; } size_t TupleStreamWrapper::computeOffsets(TableTuple &tuple, size_t *rowHeaderSz) { // round-up columncount to next multiple of 8 and divide by 8 int columnCount = tuple.sizeInValues() + METADATA_COL_CNT; int nullMaskLength = ((columnCount + 7) & -8) >> 3; // row header is 32-bit length of row plus null mask *rowHeaderSz = sizeof (int32_t) + nullMaskLength; // metadata column width: 5 int64_ts plus CHAR(1). size_t metadataSz = (sizeof (int64_t) * 5) + 1; // returns 0 if corrupt tuple detected size_t dataSz = tuple.maxExportSerializationSize(); if (dataSz == 0) { throwFatalException("Invalid tuple passed to computeTupleMaxLength. Crashing System."); } return *rowHeaderSz + metadataSz + dataSz; } <commit_msg>ENG-6037 better message around tx moving backwards in TupleStreamWrapper<commit_after>/* This file is part of VoltDB. * Copyright (C) 2008-2014 VoltDB Inc. * * 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ #include "storage/TupleStreamWrapper.h" #include "common/TupleSchema.h" #include "common/types.h" #include "common/NValue.hpp" #include "common/ValuePeeker.hpp" #include "common/tabletuple.h" #include "common/ExportSerializeIo.h" #include "common/executorcontext.hpp" #include <cstdio> #include <iostream> #include <cassert> #include <ctime> #include <utility> #include <math.h> using namespace std; using namespace voltdb; const int METADATA_COL_CNT = 6; const int MAX_BUFFER_AGE = 4000; TupleStreamWrapper::TupleStreamWrapper(CatalogId partitionId, int64_t siteId) : m_partitionId(partitionId), m_siteId(siteId), m_lastFlush(0), m_defaultCapacity(EL_BUFFER_SIZE), m_uso(0), m_currBlock(NULL), // snapshot restores will call load table which in turn // calls appendTupple with LONG_MIN transaction ids // this allows initial ticks to succeed after rejoins m_openSpHandle(0), m_openTransactionUso(0), m_committedSpHandle(0), m_committedUso(0), m_signature(""), m_generation(0) { extendBufferChain(m_defaultCapacity); } void TupleStreamWrapper::setDefaultCapacity(size_t capacity) { assert (capacity > 0); if (m_uso != 0 || m_openSpHandle != 0 || m_openTransactionUso != 0 || m_committedSpHandle != 0) { throwFatalException("setDefaultCapacity only callable before " "TupleStreamWrapper is used"); } cleanupManagedBuffers(); m_defaultCapacity = capacity; extendBufferChain(m_defaultCapacity); } /* * Essentially, shutdown. */ void TupleStreamWrapper::cleanupManagedBuffers() { StreamBlock *sb = NULL; discardBlock(m_currBlock); m_currBlock = NULL; while (m_pendingBlocks.empty() != true) { sb = m_pendingBlocks.front(); m_pendingBlocks.pop_front(); discardBlock(sb); } } void TupleStreamWrapper::setSignatureAndGeneration(std::string signature, int64_t generation) { assert(generation > m_generation); assert(signature == m_signature || m_signature == string("")); //The first time through this is catalog load and m_generation will be 0 //Don't send the end of stream notice. if (generation != m_generation && m_generation > 0) { //Notify that no more data is coming from this generation. ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, NULL, false, true); /* * With the new generational code the USO is reset to 0 for each * generation. The sequence number stored on the table outside the wrapper * is not reset and remains constant. USO is really just for transport purposes. */ m_uso = 0; m_openSpHandle = 0; m_openTransactionUso = 0; m_committedSpHandle = 0; m_committedUso = 0; //Reconstruct the next block so it has a USO of 0. assert(m_currBlock->offset() == 0); extendBufferChain(m_defaultCapacity); } m_signature = signature; m_generation = generation; } /* * Handoff fully committed blocks to the top end. * * This is the only function that should modify m_openSpHandle, * m_openTransactionUso. */ void TupleStreamWrapper::commit(int64_t lastCommittedSpHandle, int64_t currentSpHandle, bool sync) { if (currentSpHandle < m_openSpHandle) { throwFatalException( "Active transactions moving backwards: openSpHandle is %jd, while the current spHandle is %jd", (intmax_t)m_openSpHandle, (intmax_t)currentSpHandle ); } // more data for an ongoing transaction with no new committed data if ((currentSpHandle == m_openSpHandle) && (lastCommittedSpHandle == m_committedSpHandle)) { //std::cout << "Current spHandle(" << currentSpHandle << ") == m_openSpHandle(" << m_openSpHandle << //") && lastCommittedSpHandle(" << lastCommittedSpHandle << ") m_committedSpHandle(" << //m_committedSpHandle << ")" << std::endl; if (sync) { ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, NULL, true, false); } return; } // If the current TXN ID has advanced, then we know that: // - The old open transaction has been committed // - The current transaction is now our open transaction if (m_openSpHandle < currentSpHandle) { //std::cout << "m_openSpHandle(" << m_openSpHandle << ") < currentSpHandle(" //<< currentSpHandle << ")" << std::endl; m_committedUso = m_uso; // Advance the tip to the new transaction. m_committedSpHandle = m_openSpHandle; m_openSpHandle = currentSpHandle; } // now check to see if the lastCommittedSpHandle tells us that our open // transaction should really be committed. If so, update the // committed state. if (m_openSpHandle <= lastCommittedSpHandle) { //std::cout << "m_openSpHandle(" << m_openSpHandle << ") <= lastCommittedSpHandle(" << //lastCommittedSpHandle << ")" << std::endl; m_committedUso = m_uso; m_committedSpHandle = m_openSpHandle; } while (!m_pendingBlocks.empty()) { StreamBlock* block = m_pendingBlocks.front(); //std::cout << "m_committedUso(" << m_committedUso << "), block->uso() + block->offset() == " //<< (block->uso() + block->offset()) << std::endl; // check that the entire remainder is committed if (m_committedUso >= (block->uso() + block->offset())) { //The block is handed off to the topend which is responsible for releasing the //memory associated with the block data. The metadata is deleted here. ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, block, false, false); delete block; m_pendingBlocks.pop_front(); } else { break; } } if (sync) { ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, NULL, true, false); } } /* * Discard all data with a uso gte mark */ void TupleStreamWrapper::rollbackTo(size_t mark) { if (mark > m_uso) { throwFatalException("Truncating the future."); } // back up the universal stream counter m_uso = mark; // working from newest to oldest block, throw // away blocks that are fully after mark; truncate // the block that contains mark. if (!(m_currBlock->uso() >= mark)) { m_currBlock->truncateTo(mark); } else { StreamBlock *sb = NULL; discardBlock(m_currBlock); m_currBlock = NULL; while (m_pendingBlocks.empty() != true) { sb = m_pendingBlocks.back(); m_pendingBlocks.pop_back(); if (sb->uso() >= mark) { discardBlock(sb); } else { sb->truncateTo(mark); m_currBlock = sb; break; } } } } /* * Correctly release and delete a managed buffer that won't * be handed off */ void TupleStreamWrapper::discardBlock(StreamBlock *sb) { delete [] sb->rawPtr(); delete sb; } /* * Allocate another buffer, preserving the current buffer's content in * the pending queue. */ void TupleStreamWrapper::extendBufferChain(size_t minLength) { if (m_defaultCapacity < minLength) { // exportxxx: rollback instead? throwFatalException("Default capacity is less than required buffer size."); } if (m_currBlock) { if (m_currBlock->offset() > 0) { if (m_committedUso >= (m_currBlock->uso() + m_currBlock->offset())) { //The block is handed off to the topend which is responsible for releasing the //memory associated with the block data. The metadata is deleted here. ExecutorContext::getExecutorContext()->getTopend()->pushExportBuffer( m_generation, m_partitionId, m_signature, m_currBlock, false, false); delete m_currBlock; } else { m_pendingBlocks.push_back(m_currBlock); m_currBlock = NULL; } } // fully discard empty blocks. makes valgrind/testcase // conclusion easier. else { discardBlock(m_currBlock); m_currBlock = NULL; } } char *buffer = new char[m_defaultCapacity]; if (!buffer) { throwFatalException("Failed to claim managed buffer for Export."); } m_currBlock = new StreamBlock(buffer, m_defaultCapacity, m_uso); } /* * Create a new buffer and flush all pending committed data. * Creating a new buffer will push all queued data into the * pending list for commit to operate against. */ void TupleStreamWrapper::periodicFlush(int64_t timeInMillis, int64_t lastCommittedSpHandle, int64_t currentSpHandle) { // negative timeInMillis instructs a mandatory flush if (timeInMillis < 0 || (timeInMillis - m_lastFlush > MAX_BUFFER_AGE)) { if (timeInMillis > 0) { m_lastFlush = timeInMillis; } extendBufferChain(0); commit(lastCommittedSpHandle, currentSpHandle, timeInMillis < 0 ? true : false); } } /* * If SpHandle represents a new transaction, commit previous data. * Always serialize the supplied tuple in to the stream. * Return m_uso before this invocation - this marks the point * in the stream the caller can rollback to if this append * should be rolled back. */ size_t TupleStreamWrapper::appendTuple(int64_t lastCommittedSpHandle, int64_t spHandle, int64_t seqNo, int64_t uniqueId, int64_t timestamp, TableTuple &tuple, TupleStreamWrapper::Type type) { size_t rowHeaderSz = 0; size_t tupleMaxLength = 0; // Transaction IDs for transactions applied to this tuple stream // should always be moving forward in time. if (spHandle < m_openSpHandle) { throwFatalException( "Active transactions moving backwards: openSpHandle is %jd, while the append spHandle is %jd", (intmax_t)m_openSpHandle, (intmax_t)spHandle ); } commit(lastCommittedSpHandle, spHandle); // Compute the upper bound on bytes required to serialize tuple. // exportxxx: can memoize this calculation. tupleMaxLength = computeOffsets(tuple, &rowHeaderSz); if (!m_currBlock) { extendBufferChain(m_defaultCapacity); } if ((m_currBlock->rawLength() + tupleMaxLength) > m_defaultCapacity) { extendBufferChain(tupleMaxLength); } // initialize the full row header to 0. This also // has the effect of setting each column non-null. ::memset(m_currBlock->mutableDataPtr(), 0, rowHeaderSz); // the nullarray lives in rowheader after the 4 byte header length prefix uint8_t *nullArray = reinterpret_cast<uint8_t*>(m_currBlock->mutableDataPtr() + sizeof (int32_t)); // position the serializer after the full rowheader ExportSerializeOutput io(m_currBlock->mutableDataPtr() + rowHeaderSz, m_currBlock->remaining() - rowHeaderSz); // write metadata columns io.writeLong(spHandle); io.writeLong(timestamp); io.writeLong(seqNo); io.writeLong(m_partitionId); io.writeLong(m_siteId); // use 1 for INSERT EXPORT op, 0 for DELETE EXPORT op io.writeLong((type == INSERT) ? 1L : 0L); // write the tuple's data tuple.serializeToExport(io, METADATA_COL_CNT, nullArray); // write the row size in to the row header // rowlength does not include the 4 byte row header // but does include the null array. ExportSerializeOutput hdr(m_currBlock->mutableDataPtr(), 4); hdr.writeInt((int32_t)(io.position()) + (int32_t)rowHeaderSz - 4); // update m_offset m_currBlock->consumed(rowHeaderSz + io.position()); // update uso. const size_t startingUso = m_uso; m_uso += (rowHeaderSz + io.position()); return startingUso; } size_t TupleStreamWrapper::computeOffsets(TableTuple &tuple, size_t *rowHeaderSz) { // round-up columncount to next multiple of 8 and divide by 8 int columnCount = tuple.sizeInValues() + METADATA_COL_CNT; int nullMaskLength = ((columnCount + 7) & -8) >> 3; // row header is 32-bit length of row plus null mask *rowHeaderSz = sizeof (int32_t) + nullMaskLength; // metadata column width: 5 int64_ts plus CHAR(1). size_t metadataSz = (sizeof (int64_t) * 5) + 1; // returns 0 if corrupt tuple detected size_t dataSz = tuple.maxExportSerializationSize(); if (dataSz == 0) { throwFatalException("Invalid tuple passed to computeTupleMaxLength. Crashing System."); } return *rowHeaderSz + metadataSz + dataSz; } <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * Version 0.9 * * Copyright (c) 2013-2015 Inviwo 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. * * 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 "textoverlaygl.h" #include <inviwo/core/common/inviwoapplication.h> #include <modules/opengl/glwrap/shader.h> #include <modules/opengl/textureutils.h> #include <modules/fontrendering/fontrenderingmodule.h> #include <inviwo/core/datastructures/geometry/mesh.h> #include <inviwo/core/datastructures/buffer/bufferramprecision.h> #include <modules/opengl/glwrap/bufferobjectarray.h> #include <modules/opengl/geometry/meshgl.h> #include <modules/opengl/buffer/buffergl.h> namespace inviwo { ProcessorClassIdentifier(TextOverlayGL, "org.inviwo.TextOverlayGL"); ProcessorDisplayName(TextOverlayGL, "Text Overlay"); ProcessorTags(TextOverlayGL, Tags::GL); ProcessorCategory(TextOverlayGL, "Drawing"); ProcessorCodeState(TextOverlayGL, CODE_STATE_STABLE); TextOverlayGL::TextOverlayGL() : Processor() , inport_("inport") , outport_("outport") , text_("Text", "Text", "Lorem ipsum etc.", INVALID_OUTPUT, PropertySemantics::TextEditor) , font_size_(20) , xpos_(0) , ypos_(0) , color_("color_", "Color", vec4(1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f), INVALID_OUTPUT, PropertySemantics::Color) , fontSize_("Font size", "Font size") , fontPos_("Position", "Position", vec2(0.0f), vec2(0.0f), vec2(1.0f), vec2(0.01f)) , refPos_("Reference", "Reference", vec2(-1.0f), vec2(-1.0f), vec2(1.0f), vec2(0.01f)) , textShader_(NULL) { addPort(inport_); addPort(outport_); addProperty(text_); addProperty(color_); addProperty(fontPos_); addProperty(refPos_); addProperty(fontSize_); fontSize_.addOption("10", "10", 10); fontSize_.addOption("12", "12", 12); fontSize_.addOption("18", "18", 18); fontSize_.addOption("24", "24", 24); fontSize_.addOption("36", "36", 36); fontSize_.addOption("48", "48", 48); fontSize_.addOption("60", "60", 60); fontSize_.addOption("72", "72", 72); fontSize_.setSelectedIndex(3); fontSize_.setCurrentStateAsDefault(); } TextOverlayGL::~TextOverlayGL() {} void TextOverlayGL::initialize() { Processor::initialize(); textShader_ = new Shader("fontrendering_freetype.vert", "fontrendering_freetype.frag", true); int error = 0; if (FT_Init_FreeType(&fontlib_)) LogWarn("FreeType: Major error."); std::string arialfont = InviwoApplication::getPtr() ->getModuleByType<FontRenderingModule>() ->getPath() + "/fonts/arial.ttf"; error = FT_New_Face(fontlib_, arialfont.c_str(), 0, &fontface_); if (error == FT_Err_Unknown_File_Format) { LogWarn("FreeType: File opened and read, format unsupported."); } else if (error) { LogWarn("FreeType: Could not read/open the font file."); } glGenTextures(1, &texCharacter_); initMesh(); } void TextOverlayGL::deinitialize() { delete textShader_; textShader_ = NULL; glDeleteTextures(1, &texCharacter_); delete mesh_; Processor::deinitialize(); } vec2 TextOverlayGL::measure_text(const char* text, float sx, float sy) { const char* p; FT_Set_Pixel_Sizes(fontface_, 0, fontSize_.get()); float x = 0.0f; float y = 0.0f; float maxx = 0.0f; float maxy = 0.0f; char lf = (char)0xA; // Line Feed Ascii for std::endl, \n char tab = (char)0x9; // Tab Ascii for (p = text; *p; p++) { if (FT_Load_Char(fontface_, *p, FT_LOAD_RENDER)) { LogWarn("FreeType: could not render char"); continue; } float w = fontface_->glyph->bitmap.width * sx; float h = fontface_->glyph->bitmap.rows * sy; if(y == 0.0f) y+=2*h; if (*p == lf) { y += (2 * h); x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; maxx = std::max(maxx, x); x = 0.0f; continue; } else if (*p == tab) { x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; x += (4 * w); // 4 times glyph character width maxx = std::max(maxx, x); continue; } x += (fontface_->glyph->advance.x >> 6) * sx; maxx = std::max(maxx, x); y += (fontface_->glyph->advance.y >> 6) * sy; maxy = std::max(maxy, y); } return vec2(maxx, maxy); } void TextOverlayGL::render_text(const char* text, float x, float y, float sx, float sy) { const char* p; FT_Set_Pixel_Sizes(fontface_, 0, fontSize_.get()); float offset = 0; float inputX = x; // TODO: To make things more reliable ask the system for proper ascii char lf = (char)0xA; // Line Feed Ascii for std::endl, \n char tab = (char)0x9; // Tab Ascii BufferObjectArray rectArray; for (p = text; *p; p++) { if (FT_Load_Char(fontface_, *p, FT_LOAD_RENDER)) { LogWarn("FreeType: could not render char"); continue; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, fontface_->glyph->bitmap.width, fontface_->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, fontface_->glyph->bitmap.buffer); float x2 = x + fontface_->glyph->bitmap_left * sx; float y2 = -y - fontface_->glyph->bitmap_top * sy; float w = fontface_->glyph->bitmap.width * sx; float h = fontface_->glyph->bitmap.rows * sy; if (*p == lf) { offset += (2 * h); x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; x = inputX; continue; } else if (*p == tab) { x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; x += (4 * w); // 4 times glyph character width continue; } y2 += offset; Position2dBufferRAM* positions = mesh_->getAttributes(0)->getEditableRepresentation<Position2dBufferRAM>(); positions->set(0,vec2(x2, -y2)); positions->set(1,vec2(x2 + w, -y2)); positions->set(2,vec2(x2, -y2 - h)); positions->set(3,vec2(x2 + w, -y2 - h)); const MeshGL* meshgl = mesh_->getRepresentation<MeshGL>(); rectArray.bind(); rectArray.attachBufferObject(meshgl->getBufferGL(0)->getBufferObject(), POSITION_ATTRIB); rectArray.attachBufferObject(meshgl->getBufferGL(1)->getBufferObject(), TEXCOORD_ATTRIB); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); rectArray.unbind(); x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; } } void TextOverlayGL::process() { inport_.passOnDataToOutport(&outport_); utilgl::activateTarget(outport_); glDepthFunc(GL_ALWAYS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); TextureUnit texUnit; texUnit.activate(); glBindTexture(GL_TEXTURE_2D, texCharacter_); 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_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); float sx = 2.f / outport_.getData()->getDimensions().x; float sy = 2.f / outport_.getData()->getDimensions().y; font_size_ = fontSize_.getSelectedValue(); xpos_ = fontPos_.get().x * outport_.getData()->getDimensions().x; ypos_ = fontPos_.get().y * outport_.getData()->getDimensions().y + float(font_size_); textShader_->activate(); textShader_->setUniform("tex", texUnit.getUnitNumber()); textShader_->setUniform("color", color_.get()); vec2 size = measure_text(text_.get().c_str(), sx, sy); vec2 shift = 0.5f * size * (refPos_.get() + vec2(1.0f,1.0f)); render_text(text_.get().c_str(), -1 + xpos_*sx - shift.x, 1 - ypos_*sy + shift.y, sx, sy); textShader_->deactivate(); glDisable(GL_BLEND); glDepthFunc(GL_LESS); utilgl::deactivateCurrentTarget(); } void TextOverlayGL::initMesh() { Position2dBuffer* verticesBuffer = new Position2dBuffer(); Position2dBufferRAM* verticesBufferRAM = verticesBuffer->getEditableRepresentation<Position2dBufferRAM>(); verticesBufferRAM->add(vec2(-1.0f, -1.0f)); verticesBufferRAM->add(vec2(1.0f, -1.0f)); verticesBufferRAM->add(vec2(-1.0f, 1.0f)); verticesBufferRAM->add(vec2(1.0f, 1.0f)); TexCoord2dBuffer* texCoordsBuffer = new TexCoord2dBuffer(); TexCoord2dBufferRAM* texCoordsBufferRAM = texCoordsBuffer->getEditableRepresentation<TexCoord2dBufferRAM>(); texCoordsBufferRAM->add(vec2(0.0f, 0.0f)); texCoordsBufferRAM->add(vec2(1.0f, 0.0f)); texCoordsBufferRAM->add(vec2(0.0f, 1.0f)); texCoordsBufferRAM->add(vec2(1.0f, 1.0f)); IndexBuffer* indices_ = new IndexBuffer(); Mesh::AttributesInfo(GeometryEnums::TRIANGLES, GeometryEnums::STRIP); IndexBufferRAM* indexBufferRAM = indices_->getEditableRepresentation<IndexBufferRAM>(); indexBufferRAM->add(0); indexBufferRAM->add(1); indexBufferRAM->add(2); indexBufferRAM->add(3); mesh_ = new Mesh(); mesh_->addAttribute(verticesBuffer); mesh_->addAttribute(texCoordsBuffer); mesh_->addIndicies(Mesh::AttributesInfo(GeometryEnums::TRIANGLES, GeometryEnums::STRIP), indices_); } } // namespace <commit_msg>FontRendering: Remove unused code<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * Version 0.9 * * Copyright (c) 2013-2015 Inviwo 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. * * 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 "textoverlaygl.h" #include <inviwo/core/common/inviwoapplication.h> #include <modules/opengl/glwrap/shader.h> #include <modules/opengl/textureutils.h> #include <modules/fontrendering/fontrenderingmodule.h> #include <inviwo/core/datastructures/geometry/mesh.h> #include <inviwo/core/datastructures/buffer/bufferramprecision.h> #include <modules/opengl/glwrap/bufferobjectarray.h> #include <modules/opengl/geometry/meshgl.h> #include <modules/opengl/buffer/buffergl.h> namespace inviwo { ProcessorClassIdentifier(TextOverlayGL, "org.inviwo.TextOverlayGL"); ProcessorDisplayName(TextOverlayGL, "Text Overlay"); ProcessorTags(TextOverlayGL, Tags::GL); ProcessorCategory(TextOverlayGL, "Drawing"); ProcessorCodeState(TextOverlayGL, CODE_STATE_STABLE); TextOverlayGL::TextOverlayGL() : Processor() , inport_("inport") , outport_("outport") , text_("Text", "Text", "Lorem ipsum etc.", INVALID_OUTPUT, PropertySemantics::TextEditor) , font_size_(20) , xpos_(0) , ypos_(0) , color_("color_", "Color", vec4(1.0f), vec4(0.0f), vec4(1.0f), vec4(0.01f), INVALID_OUTPUT, PropertySemantics::Color) , fontSize_("Font size", "Font size") , fontPos_("Position", "Position", vec2(0.0f), vec2(0.0f), vec2(1.0f), vec2(0.01f)) , refPos_("Reference", "Reference", vec2(-1.0f), vec2(-1.0f), vec2(1.0f), vec2(0.01f)) , textShader_(NULL) { addPort(inport_); addPort(outport_); addProperty(text_); addProperty(color_); addProperty(fontPos_); addProperty(refPos_); addProperty(fontSize_); fontSize_.addOption("10", "10", 10); fontSize_.addOption("12", "12", 12); fontSize_.addOption("18", "18", 18); fontSize_.addOption("24", "24", 24); fontSize_.addOption("36", "36", 36); fontSize_.addOption("48", "48", 48); fontSize_.addOption("60", "60", 60); fontSize_.addOption("72", "72", 72); fontSize_.setSelectedIndex(3); fontSize_.setCurrentStateAsDefault(); } TextOverlayGL::~TextOverlayGL() {} void TextOverlayGL::initialize() { Processor::initialize(); textShader_ = new Shader("fontrendering_freetype.vert", "fontrendering_freetype.frag", true); int error = 0; if (FT_Init_FreeType(&fontlib_)) LogWarn("FreeType: Major error."); std::string arialfont = InviwoApplication::getPtr() ->getModuleByType<FontRenderingModule>() ->getPath() + "/fonts/arial.ttf"; error = FT_New_Face(fontlib_, arialfont.c_str(), 0, &fontface_); if (error == FT_Err_Unknown_File_Format) { LogWarn("FreeType: File opened and read, format unsupported."); } else if (error) { LogWarn("FreeType: Could not read/open the font file."); } glGenTextures(1, &texCharacter_); initMesh(); } void TextOverlayGL::deinitialize() { delete textShader_; textShader_ = NULL; glDeleteTextures(1, &texCharacter_); delete mesh_; Processor::deinitialize(); } vec2 TextOverlayGL::measure_text(const char* text, float sx, float sy) { const char* p; FT_Set_Pixel_Sizes(fontface_, 0, fontSize_.get()); float x = 0.0f; float y = 0.0f; float maxx = 0.0f; float maxy = 0.0f; char lf = (char)0xA; // Line Feed Ascii for std::endl, \n char tab = (char)0x9; // Tab Ascii for (p = text; *p; p++) { if (FT_Load_Char(fontface_, *p, FT_LOAD_RENDER)) { LogWarn("FreeType: could not render char"); continue; } float w = fontface_->glyph->bitmap.width * sx; float h = fontface_->glyph->bitmap.rows * sy; if(y == 0.0f) y+=2*h; if (*p == lf) { y += (2 * h); x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; maxx = std::max(maxx, x); x = 0.0f; continue; } else if (*p == tab) { x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; x += (4 * w); // 4 times glyph character width maxx = std::max(maxx, x); continue; } x += (fontface_->glyph->advance.x >> 6) * sx; maxx = std::max(maxx, x); y += (fontface_->glyph->advance.y >> 6) * sy; maxy = std::max(maxy, y); } return vec2(maxx, maxy); } void TextOverlayGL::render_text(const char* text, float x, float y, float sx, float sy) { const char* p; FT_Set_Pixel_Sizes(fontface_, 0, fontSize_.get()); float offset = 0; float inputX = x; // TODO: To make things more reliable ask the system for proper ascii char lf = (char)0xA; // Line Feed Ascii for std::endl, \n char tab = (char)0x9; // Tab Ascii BufferObjectArray rectArray; for (p = text; *p; p++) { if (FT_Load_Char(fontface_, *p, FT_LOAD_RENDER)) { LogWarn("FreeType: could not render char"); continue; } glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, fontface_->glyph->bitmap.width, fontface_->glyph->bitmap.rows, 0, GL_RED, GL_UNSIGNED_BYTE, fontface_->glyph->bitmap.buffer); float x2 = x + fontface_->glyph->bitmap_left * sx; float y2 = -y - fontface_->glyph->bitmap_top * sy; float w = fontface_->glyph->bitmap.width * sx; float h = fontface_->glyph->bitmap.rows * sy; if (*p == lf) { offset += (2 * h); x += inputX; y += (fontface_->glyph->advance.y >> 6) * sy; continue; } else if (*p == tab) { x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; x += (4 * w); // 4 times glyph character width continue; } y2 += offset; Position2dBufferRAM* positions = mesh_->getAttributes(0)->getEditableRepresentation<Position2dBufferRAM>(); positions->set(0,vec2(x2, -y2)); positions->set(1,vec2(x2 + w, -y2)); positions->set(2,vec2(x2, -y2 - h)); positions->set(3,vec2(x2 + w, -y2 - h)); const MeshGL* meshgl = mesh_->getRepresentation<MeshGL>(); rectArray.bind(); rectArray.attachBufferObject(meshgl->getBufferGL(0)->getBufferObject(), POSITION_ATTRIB); rectArray.attachBufferObject(meshgl->getBufferGL(1)->getBufferObject(), TEXCOORD_ATTRIB); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); rectArray.unbind(); x += (fontface_->glyph->advance.x >> 6) * sx; y += (fontface_->glyph->advance.y >> 6) * sy; } } void TextOverlayGL::process() { inport_.passOnDataToOutport(&outport_); utilgl::activateTarget(outport_); glDepthFunc(GL_ALWAYS); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); TextureUnit texUnit; texUnit.activate(); glBindTexture(GL_TEXTURE_2D, texCharacter_); 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_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); float sx = 2.f / outport_.getData()->getDimensions().x; float sy = 2.f / outport_.getData()->getDimensions().y; font_size_ = fontSize_.getSelectedValue(); xpos_ = fontPos_.get().x * outport_.getData()->getDimensions().x; ypos_ = fontPos_.get().y * outport_.getData()->getDimensions().y + float(font_size_); textShader_->activate(); textShader_->setUniform("tex", texUnit.getUnitNumber()); textShader_->setUniform("color", color_.get()); vec2 size = measure_text(text_.get().c_str(), sx, sy); vec2 shift = 0.5f * size * (refPos_.get() + vec2(1.0f,1.0f)); render_text(text_.get().c_str(), -1 + xpos_*sx - shift.x, 1 - ypos_*sy + shift.y, sx, sy); textShader_->deactivate(); glDisable(GL_BLEND); glDepthFunc(GL_LESS); utilgl::deactivateCurrentTarget(); } void TextOverlayGL::initMesh() { Position2dBuffer* verticesBuffer = new Position2dBuffer(); Position2dBufferRAM* verticesBufferRAM = verticesBuffer->getEditableRepresentation<Position2dBufferRAM>(); verticesBufferRAM->add(vec2(-1.0f, -1.0f)); verticesBufferRAM->add(vec2(1.0f, -1.0f)); verticesBufferRAM->add(vec2(-1.0f, 1.0f)); verticesBufferRAM->add(vec2(1.0f, 1.0f)); TexCoord2dBuffer* texCoordsBuffer = new TexCoord2dBuffer(); TexCoord2dBufferRAM* texCoordsBufferRAM = texCoordsBuffer->getEditableRepresentation<TexCoord2dBufferRAM>(); texCoordsBufferRAM->add(vec2(0.0f, 0.0f)); texCoordsBufferRAM->add(vec2(1.0f, 0.0f)); texCoordsBufferRAM->add(vec2(0.0f, 1.0f)); texCoordsBufferRAM->add(vec2(1.0f, 1.0f)); IndexBuffer* indices_ = new IndexBuffer(); Mesh::AttributesInfo(GeometryEnums::TRIANGLES, GeometryEnums::STRIP); IndexBufferRAM* indexBufferRAM = indices_->getEditableRepresentation<IndexBufferRAM>(); indexBufferRAM->add(0); indexBufferRAM->add(1); indexBufferRAM->add(2); indexBufferRAM->add(3); mesh_ = new Mesh(); mesh_->addAttribute(verticesBuffer); mesh_->addAttribute(texCoordsBuffer); mesh_->addIndicies(Mesh::AttributesInfo(GeometryEnums::TRIANGLES, GeometryEnums::STRIP), indices_); } } // namespace <|endoftext|>
<commit_before><commit_msg>AIXOS05035967 enable scomdef parser to search additional addresses<commit_after><|endoftext|>
<commit_before> #include "Builder.h" #include <iostream> #include <QDebug> #include <QCoreApplication> #include <QCommandLineOption> #include <glraw/MirrorEditor.h> #include <glraw/ScaleEditor.h> #include <glraw/FileWriter.h> #include <glraw/Converter.h> #include <glraw/CompressionConverter.h> #include "CommandLineOption.h" #include "Conversions.h" namespace { void messageHandler(QtMsgType type, const QMessageLogContext & context, const QString & message) { if (type == QtDebugMsg) return; std::cerr << message.toStdString() << std::endl; } } Builder::Builder() : m_converter(nullptr) , m_writer(new glraw::FileWriter()) , m_manager(m_writer) { initialize(); } Builder::~Builder() { } QList<CommandLineOption> Builder::commandLineOptions() { QList<CommandLineOption> options; options.append({ QStringList() << "h" << "help", "Displays this help.", QString(), &Builder::help }); options.append({ QStringList() << "q" << "quiet", "Suppresses any output", QString(), &Builder::quiet }); options.append({ QStringList() << "n" << "no-suffixes", "Disables file suffixes.", QString(), &Builder::noSuffixes }); options.append({ QStringList() << "f" << "format", "Output format (default: GL_RGBA)", "format", &Builder::format }); options.append({ QStringList() << "t" << "type", "Output type (default: GL_UNSIGNED_BYTE)", "type", &Builder::type }); options.append({ QStringList() << "compressed-format", "Output format (default: GL_COMPRESSED_RGBA)", "format", &Builder::compressedFormat }); options.append({ QStringList() << "r" << "raw", "Writes files without header.", QString(), &Builder::raw }); options.append({ QStringList() << "mv" << "mirror-vertical", "Mirrors the image vertically.", QString(), &Builder::mirrorVertical }); options.append({ QStringList() << "mh" << "mirror-horizontal", "Mirrors the image horizontally.", QString(), &Builder::mirrorHorizontal }); options.append({ QStringList() << "s" << "scale", "Scales the image.", "decimal", &Builder::scale }); options.append({ QStringList() << "ws" << "width-scale", "Scales the width.", "decimal", &Builder::widthScale }); options.append({ QStringList() << "hs" << "height-scale", "Scales the height.", "decimal", &Builder::heightScale }); options.append({ QStringList() << "width", "Sets the width in px.", "integer", &Builder::width }); options.append({ QStringList() << "height", "Sets the height in px.", "integer", &Builder::height }); options.append({ QStringList() << "transform-mode", "Transformation mode used for resizing " "(default: nearest)", "mode", &Builder::transformMode }); options.append({ QStringList() << "aspect-ratio-mode", "Aspect ratio mode used for resizing " "(default: IgnoreAspectRatio)", "mode", &Builder::aspectRatioMode }); options.append({ QStringList() << "shader", "Applies a fragment shader before conversion " "(see for example data/grayscale.frag)", "source", &Builder::shader }); return options; } void Builder::initialize() { m_parser.setApplicationDescription("Converts Qt supported images to an OpenGL compatible raw format."); m_parser.addVersionOption(); m_parser.addPositionalArgument("source", "Source file with Qt-supported image format."); for (auto option : commandLineOptions()) { m_parser.addOption(QCommandLineOption( option.names, option.description, option.valueName )); for (auto name : option.names) { m_configureMethods.insert( name, option.configureMethod ); } } } void Builder::process(const QCoreApplication & app) { if (app.arguments().size() == 1) { showHelp(); return; } m_parser.process(app); m_manager.setConverter(nullptr); m_converter = nullptr; for (auto option : m_parser.optionNames()) { if (!(this->*m_configureMethods.value(option))(option)) return; } if (m_converter == nullptr) m_converter = new glraw::Converter(); m_manager.setConverter(m_converter); QStringList sources = m_parser.positionalArguments(); if (sources.size() < 1) { qDebug() << "No source files passed in."; return; } for (auto source : sources) m_manager.process(source); } bool Builder::help(const QString & name) { showHelp(); return false; } bool Builder::quiet(const QString & name) { qInstallMessageHandler(messageHandler); return true; } bool Builder::noSuffixes(const QString & name) { m_writer->setSuffixesEnabled(false); return true; } bool Builder::format(const QString & name) { QString formatString = m_parser.value(name); if (!Conversions::isFormat(formatString)) { qDebug() << qPrintable(formatString) << "is not a format."; return false; } if (m_converter == nullptr) m_converter = new glraw::Converter(); glraw::Converter * converter = dynamic_cast<glraw::Converter *>(m_converter); if (converter == nullptr) { qDebug() << "You can either specify a compressed format or an uncompressed format and type."; return false; } converter->setFormat(Conversions::stringToFormat(formatString)); return true; } bool Builder::type(const QString & name) { QString formatString = m_parser.value(name); if (!Conversions::isType(formatString)) { qDebug() << qPrintable(formatString) << "is not a type."; return false; } if (m_converter == nullptr) m_converter = new glraw::Converter(); glraw::Converter * converter = dynamic_cast<glraw::Converter *>(m_converter); if (converter == nullptr) { qDebug() << "You can either specify a compressed format or an uncompressed format and type."; return false; } converter->setType(Conversions::stringToType(formatString)); return true; } bool Builder::compressedFormat(const QString & name) { QString formatString = m_parser.value(name); if (!Conversions::isCompressedFormat(formatString)) { qDebug() << qPrintable(formatString) << "is not a compressed format."; return false; } if (m_converter == nullptr) m_converter = new glraw::CompressionConverter(); glraw::CompressionConverter * converter = dynamic_cast<glraw::CompressionConverter *>(m_converter); if (converter == nullptr) { qDebug() << "You can either specify a compressed format or an uncompressed format and type."; return false; } converter->setCompressedFormat(Conversions::stringToCompressedFormat(formatString)); return true; } bool Builder::raw(const QString & name) { m_writer->setHeaderEnabled(false); return true; } bool Builder::mirrorVertical(const QString & name) { const QString editorName = "MirrorEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::MirrorEditor()); auto e = editor<glraw::MirrorEditor>(editorName); e->setVertical(true); return true; } bool Builder::mirrorHorizontal(const QString & name) { const QString editorName = "MirrorEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::MirrorEditor()); auto e = editor<glraw::MirrorEditor>(editorName); e->setHorizontal(true); return true; } bool Builder::scale(const QString & name) { QString scaleString = m_parser.value(name); bool ok; float scale = scaleString.toFloat(&ok); if (!ok) { qDebug() << scaleString << "isn't a float."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setScale(scale); return true; } bool Builder::widthScale(const QString & name) { QString widthScaleString = m_parser.value(name); bool ok; float widthScale = widthScaleString.toFloat(&ok); if (!ok) { qDebug() << widthScaleString << "isn't a float."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setWidthScale(widthScale); return true; } bool Builder::heightScale(const QString & name) { QString heighScaleString = m_parser.value(name); bool ok; float heightScale = heighScaleString.toFloat(&ok); if (!ok) { qDebug() << heighScaleString << "isn't a float."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setHeightScale(heightScale); return true; } bool Builder::width(const QString & name) { QString widthString = m_parser.value(name); bool ok; int width = widthString.toInt(&ok); if (!ok) { qDebug() << widthString << "isn't a int."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setWidth(width); return true; } bool Builder::height(const QString & name) { QString heightString = m_parser.value(name); bool ok; int height = heightString.toInt(&ok); if (!ok) { qDebug() << heightString << "isn't a int."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setHeight(height); return true; } bool Builder::transformMode(const QString & name) { QString modeString = m_parser.value(name); if (!Conversions::isTransformationMode(modeString)) { qDebug() << qPrintable(modeString) << "is not a transformation mode."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setTransformationMode( Conversions::stringToTransformationMode(modeString) ); return true; } bool Builder::aspectRatioMode(const QString & name) { QString modeString = m_parser.value(name); if (!Conversions::isAspectRatioMode(modeString)) { qDebug() << qPrintable(modeString) << "is not a transformation mode."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setAspectRatioMode( Conversions::stringToAspectRatioMode(modeString) ); return true; } bool Builder::shader(const QString & name) { QString sourcePath = m_parser.value(name); if (!m_converter->setFragmentShader(sourcePath)) return false; return true; } bool Builder::editorExists(const QString & key) { return m_editors.contains(key); } void Builder::appendEditor(const QString & key, glraw::ImageEditorInterface * editor) { m_manager.appendImageEditor(editor); m_editors.insert(key, editor); } void Builder::showHelp() const { qDebug() << qPrintable(m_parser.helpText()) << R"( Formats: Types: Transformation Modes: GL_RED GL_UNSIGNED_BYTE nearest GL_BLUE GL_BYTE linear GL_GREEN GL_UNSIGNED_SHORT GL_RG GL_SHORT Aspect Ratio Modes: GL_RGB GL_UNSIGNED_INT IgnoreAspectRatio GL_BGR GL_INT KeepAspectRatio GL_RGBA GL_FLOAT KeepAspectRatioByExpanding GL_BGRA )"; } <commit_msg>add compressed formats to help text<commit_after> #include "Builder.h" #include <iostream> #include <QDebug> #include <QCoreApplication> #include <QCommandLineOption> #include <glraw/MirrorEditor.h> #include <glraw/ScaleEditor.h> #include <glraw/FileWriter.h> #include <glraw/Converter.h> #include <glraw/CompressionConverter.h> #include "CommandLineOption.h" #include "Conversions.h" namespace { void messageHandler(QtMsgType type, const QMessageLogContext & context, const QString & message) { if (type == QtDebugMsg) return; std::cerr << message.toStdString() << std::endl; } } Builder::Builder() : m_converter(nullptr) , m_writer(new glraw::FileWriter()) , m_manager(m_writer) { initialize(); } Builder::~Builder() { } QList<CommandLineOption> Builder::commandLineOptions() { QList<CommandLineOption> options; options.append({ QStringList() << "h" << "help", "Displays this help.", QString(), &Builder::help }); options.append({ QStringList() << "q" << "quiet", "Suppresses any output", QString(), &Builder::quiet }); options.append({ QStringList() << "n" << "no-suffixes", "Disables file suffixes.", QString(), &Builder::noSuffixes }); options.append({ QStringList() << "f" << "format", "Output format (default: GL_RGBA)", "format", &Builder::format }); options.append({ QStringList() << "t" << "type", "Output type (default: GL_UNSIGNED_BYTE)", "type", &Builder::type }); options.append({ QStringList() << "compressed-format", "Output format (default: GL_COMPRESSED_RGBA)", "format", &Builder::compressedFormat }); options.append({ QStringList() << "r" << "raw", "Writes files without header.", QString(), &Builder::raw }); options.append({ QStringList() << "mv" << "mirror-vertical", "Mirrors the image vertically.", QString(), &Builder::mirrorVertical }); options.append({ QStringList() << "mh" << "mirror-horizontal", "Mirrors the image horizontally.", QString(), &Builder::mirrorHorizontal }); options.append({ QStringList() << "s" << "scale", "Scales the image.", "decimal", &Builder::scale }); options.append({ QStringList() << "ws" << "width-scale", "Scales the width.", "decimal", &Builder::widthScale }); options.append({ QStringList() << "hs" << "height-scale", "Scales the height.", "decimal", &Builder::heightScale }); options.append({ QStringList() << "width", "Sets the width in px.", "integer", &Builder::width }); options.append({ QStringList() << "height", "Sets the height in px.", "integer", &Builder::height }); options.append({ QStringList() << "transform-mode", "Transformation mode used for resizing " "(default: nearest)", "mode", &Builder::transformMode }); options.append({ QStringList() << "aspect-ratio-mode", "Aspect ratio mode used for resizing " "(default: IgnoreAspectRatio)", "mode", &Builder::aspectRatioMode }); options.append({ QStringList() << "shader", "Applies a fragment shader before conversion " "(see for example data/grayscale.frag)", "source", &Builder::shader }); return options; } void Builder::initialize() { m_parser.setApplicationDescription("Converts Qt supported images to an OpenGL compatible raw format."); m_parser.addVersionOption(); m_parser.addPositionalArgument("source", "Source file with Qt-supported image format."); for (auto option : commandLineOptions()) { m_parser.addOption(QCommandLineOption( option.names, option.description, option.valueName )); for (auto name : option.names) { m_configureMethods.insert( name, option.configureMethod ); } } } void Builder::process(const QCoreApplication & app) { if (app.arguments().size() == 1) { showHelp(); return; } m_parser.process(app); m_manager.setConverter(nullptr); m_converter = nullptr; for (auto option : m_parser.optionNames()) { if (!(this->*m_configureMethods.value(option))(option)) return; } if (m_converter == nullptr) m_converter = new glraw::Converter(); m_manager.setConverter(m_converter); QStringList sources = m_parser.positionalArguments(); if (sources.size() < 1) { qDebug() << "No source files passed in."; return; } for (auto source : sources) m_manager.process(source); } bool Builder::help(const QString & name) { showHelp(); return false; } bool Builder::quiet(const QString & name) { qInstallMessageHandler(messageHandler); return true; } bool Builder::noSuffixes(const QString & name) { m_writer->setSuffixesEnabled(false); return true; } bool Builder::format(const QString & name) { QString formatString = m_parser.value(name); if (!Conversions::isFormat(formatString)) { qDebug() << qPrintable(formatString) << "is not a format."; return false; } if (m_converter == nullptr) m_converter = new glraw::Converter(); glraw::Converter * converter = dynamic_cast<glraw::Converter *>(m_converter); if (converter == nullptr) { qDebug() << "You can either specify a compressed format or an uncompressed format and type."; return false; } converter->setFormat(Conversions::stringToFormat(formatString)); return true; } bool Builder::type(const QString & name) { QString formatString = m_parser.value(name); if (!Conversions::isType(formatString)) { qDebug() << qPrintable(formatString) << "is not a type."; return false; } if (m_converter == nullptr) m_converter = new glraw::Converter(); glraw::Converter * converter = dynamic_cast<glraw::Converter *>(m_converter); if (converter == nullptr) { qDebug() << "You can either specify a compressed format or an uncompressed format and type."; return false; } converter->setType(Conversions::stringToType(formatString)); return true; } bool Builder::compressedFormat(const QString & name) { QString formatString = m_parser.value(name); if (!Conversions::isCompressedFormat(formatString)) { qDebug() << qPrintable(formatString) << "is not a compressed format."; return false; } if (m_converter == nullptr) m_converter = new glraw::CompressionConverter(); glraw::CompressionConverter * converter = dynamic_cast<glraw::CompressionConverter *>(m_converter); if (converter == nullptr) { qDebug() << "You can either specify a compressed format or an uncompressed format and type."; return false; } converter->setCompressedFormat(Conversions::stringToCompressedFormat(formatString)); return true; } bool Builder::raw(const QString & name) { m_writer->setHeaderEnabled(false); return true; } bool Builder::mirrorVertical(const QString & name) { const QString editorName = "MirrorEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::MirrorEditor()); auto e = editor<glraw::MirrorEditor>(editorName); e->setVertical(true); return true; } bool Builder::mirrorHorizontal(const QString & name) { const QString editorName = "MirrorEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::MirrorEditor()); auto e = editor<glraw::MirrorEditor>(editorName); e->setHorizontal(true); return true; } bool Builder::scale(const QString & name) { QString scaleString = m_parser.value(name); bool ok; float scale = scaleString.toFloat(&ok); if (!ok) { qDebug() << scaleString << "isn't a float."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setScale(scale); return true; } bool Builder::widthScale(const QString & name) { QString widthScaleString = m_parser.value(name); bool ok; float widthScale = widthScaleString.toFloat(&ok); if (!ok) { qDebug() << widthScaleString << "isn't a float."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setWidthScale(widthScale); return true; } bool Builder::heightScale(const QString & name) { QString heighScaleString = m_parser.value(name); bool ok; float heightScale = heighScaleString.toFloat(&ok); if (!ok) { qDebug() << heighScaleString << "isn't a float."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setHeightScale(heightScale); return true; } bool Builder::width(const QString & name) { QString widthString = m_parser.value(name); bool ok; int width = widthString.toInt(&ok); if (!ok) { qDebug() << widthString << "isn't a int."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setWidth(width); return true; } bool Builder::height(const QString & name) { QString heightString = m_parser.value(name); bool ok; int height = heightString.toInt(&ok); if (!ok) { qDebug() << heightString << "isn't a int."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setHeight(height); return true; } bool Builder::transformMode(const QString & name) { QString modeString = m_parser.value(name); if (!Conversions::isTransformationMode(modeString)) { qDebug() << qPrintable(modeString) << "is not a transformation mode."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setTransformationMode( Conversions::stringToTransformationMode(modeString) ); return true; } bool Builder::aspectRatioMode(const QString & name) { QString modeString = m_parser.value(name); if (!Conversions::isAspectRatioMode(modeString)) { qDebug() << qPrintable(modeString) << "is not a transformation mode."; return false; } const QString editorName = "ScaleEditor"; if (!editorExists(editorName)) appendEditor(editorName, new glraw::ScaleEditor()); auto e = editor<glraw::ScaleEditor>(editorName); e->setAspectRatioMode( Conversions::stringToAspectRatioMode(modeString) ); return true; } bool Builder::shader(const QString & name) { QString sourcePath = m_parser.value(name); if (!m_converter->setFragmentShader(sourcePath)) return false; return true; } bool Builder::editorExists(const QString & key) { return m_editors.contains(key); } void Builder::appendEditor(const QString & key, glraw::ImageEditorInterface * editor) { m_manager.appendImageEditor(editor); m_editors.insert(key, editor); } void Builder::showHelp() const { qDebug() << qPrintable(m_parser.helpText()) << R"( Formats: Types: Transformation Modes: GL_RED GL_UNSIGNED_BYTE nearest GL_BLUE GL_BYTE linear GL_GREEN GL_UNSIGNED_SHORT GL_RG GL_SHORT Aspect Ratio Modes: GL_RGB GL_UNSIGNED_INT IgnoreAspectRatio GL_BGR GL_INT KeepAspectRatio GL_RGBA GL_FLOAT KeepAspectRatioByExpanding GL_BGRA Compressed Formats: GL_COMPRESSED_RED GL_COMPRESSED_RG GL_COMPRESSED_RGB GL_COMPRESSED_RGBA GL_COMPRESSED_RED_RGTC1 GL_COMPRESSED_SIGNED_RED_RGTC1 GL_COMPRESSED_RG_RGTC2 GL_COMPRESSED_SIGNED_RG_RGTC2 GL_COMPRESSED_RGB_S3TC_DXT1_EXT GL_COMPRESSED_RGBA_S3TC_DXT1_EXT GL_COMPRESSED_RGBA_S3TC_DXT3_EXT GL_COMPRESSED_RGBA_S3TC_DXT5_EXT )"; } <|endoftext|>
<commit_before>/* * Copyright © 2015 Connor Abbott * * 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 "brw_fs.h" #include "brw_cfg.h" #include "brw_fs_builder.h" using namespace brw; bool fs_visitor::lower_d2x() { bool progress = false; foreach_block_and_inst_safe(block, fs_inst, inst, cfg) { if (inst->opcode != BRW_OPCODE_MOV) continue; if (inst->dst.type != BRW_REGISTER_TYPE_F && inst->dst.type != BRW_REGISTER_TYPE_D && inst->dst.type != BRW_REGISTER_TYPE_UD) continue; if (inst->src[0].type != BRW_REGISTER_TYPE_DF) continue; assert(inst->dst.file == VGRF); assert(inst->saturate == false); fs_reg dst = inst->dst; const fs_builder ibld(this, block, inst); /* From the Broadwell PRM, 3D Media GPGPU, "Double Precision Float to * Single Precision Float": * * The upper Dword of every Qword will be written with undefined * value when converting DF to F. * * So we need to allocate a temporary that's two registers, and then do * a strided MOV to get the lower DWord of every Qword that has the * result. */ fs_reg temp = ibld.vgrf(inst->src[0].type, 1); fs_reg strided_temp = subscript(temp, inst->dst.type, 0); ibld.MOV(strided_temp, inst->src[0]); ibld.MOV(dst, strided_temp); inst->remove(block); progress = true; } if (progress) invalidate_live_intervals(); return progress; } <commit_msg>i965/fs: legalize [u]int64 to 32-bit data conversions in lower_d2x<commit_after>/* * Copyright © 2015 Connor Abbott * * 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 "brw_fs.h" #include "brw_cfg.h" #include "brw_fs_builder.h" using namespace brw; bool fs_visitor::lower_d2x() { bool progress = false; foreach_block_and_inst_safe(block, fs_inst, inst, cfg) { if (inst->opcode != BRW_OPCODE_MOV) continue; if (inst->dst.type != BRW_REGISTER_TYPE_F && inst->dst.type != BRW_REGISTER_TYPE_D && inst->dst.type != BRW_REGISTER_TYPE_UD) continue; if (inst->src[0].type != BRW_REGISTER_TYPE_DF && inst->src[0].type != BRW_REGISTER_TYPE_UQ && inst->src[0].type != BRW_REGISTER_TYPE_Q) continue; assert(inst->dst.file == VGRF); assert(inst->saturate == false); fs_reg dst = inst->dst; const fs_builder ibld(this, block, inst); /* From the Broadwell PRM, 3D Media GPGPU, "Double Precision Float to * Single Precision Float": * * The upper Dword of every Qword will be written with undefined * value when converting DF to F. * * So we need to allocate a temporary that's two registers, and then do * a strided MOV to get the lower DWord of every Qword that has the * result. */ fs_reg temp = ibld.vgrf(inst->src[0].type, 1); fs_reg strided_temp = subscript(temp, inst->dst.type, 0); ibld.MOV(strided_temp, inst->src[0]); ibld.MOV(dst, strided_temp); inst->remove(block); progress = true; } if (progress) invalidate_live_intervals(); return progress; } <|endoftext|>
<commit_before>/** * @author Carsten Könemann */ // This is a ROS project #include <ros/ros.h> // Local headers #include <thesis/math3d.h> #include <thesis/semantic_map.h> // We are working with TF #include <tf/transform_listener.h> // We want to subscribe to messages of this types #include <thesis/ObjectInstance.h> #include <thesis/ObjectInstanceArray.h> // We want to call these services #include <thesis/DatabaseGetByID.h> // This node provides these services #include <thesis/MappingGetAll.h> #include <thesis/MappingGetByID.h> #include <thesis/MappingGetByPosition.h> #include <thesis/MappingGetVisible.h> using namespace geometry_msgs; // Config parameters std::string camera_frame, map_frame; double tf_timeout, age_threshold, fov_near, fov_far; int memory_size, min_confirmations, fov_width, fov_height; bool debug; // Transform listener tf::TransformListener* transform_listener; // Reusable service clients ros::ServiceClient db_get_by_type_client; // The actual semantic map, storing recognized objects with map coordinates SemanticMap semantic_map; // Time since last cleanup ros::Time last_cleanup; void map_2_camera(const PoseStamped& pose_map, PoseStamped& pose_camera) { // Make sure transformation exists at this point in time if(transform_listener->waitForTransform( map_frame, camera_frame, pose_map.header.stamp, ros::Duration(tf_timeout) )) { // Transform recognized camera pose to map frame transform_listener->transformPose(camera_frame, pose_map, pose_camera); pose_camera.header.stamp = ros::Time::now(); } } void camera_2_map(const PoseStamped& pose_camera, PoseStamped& pose_map) { // Make sure transformation exists at this point in time if(transform_listener->waitForTransform( camera_frame, map_frame, pose_camera.header.stamp, ros::Duration(tf_timeout) )) { // Transform recognized camera pose to map frame transform_listener->transformPose(map_frame, pose_camera, pose_map); pose_map.header.stamp = ros::Time(0); } } cv::Point3f get_current_camera_position() { // geometry_msgs::PoseStamped pose_camera; pose_camera.header.stamp = ros::Time::now(); pose_camera.header.frame_id = camera_frame; pose_camera.pose.position.x = 0; pose_camera.pose.position.y = 0; pose_camera.pose.position.z = 0; tf::quaternionTFToMsg(IDENTITY_QUATERNION, pose_camera.pose.orientation); // geometry_msgs::PoseStamped pose_map; camera_2_map(pose_camera, pose_map); // return ros2cv3f(pose_map.pose.position); } inline bool is_visible(geometry_msgs::Point p) { // Calculate angles between point and camera direction float angle_width = angle3f(cv::Point3f(p.x, 0.0f, p.z), cv::Point3f(0.0f, 0.0f, 1.0f)), angle_heigth = angle3f(cv::Point3f(0.0f, p.y, p.z), cv::Point3f(0.0f, 0.0f, 1.0f)); // Check if point is inside camera frustum return (angle_width <= fov_width && angle_heigth <= fov_height && p.z >= fov_near && p.z <= fov_far); } inline float get_shorter_side(std::string type) { thesis::DatabaseGetByID db_get_by_type_service; db_get_by_type_service.request.id = type; if(db_get_by_type_client.call(db_get_by_type_service)) { // Get dimensions float width = db_get_by_type_service.response.object_class.width, height = db_get_by_type_service.response.object_class.height; // Return shorter side return std::min(width, height); } else { // Error ROS_WARN("Mapping::get_shorter_side(%s): ", type.c_str()); ROS_WARN(" Failed to call service 'thesis_database/get_by_type'."); std::cout << std::endl; return NAN; } } inline void get_currently_visible(std::vector<thesis::ObjectInstance>& visible) { visible.clear(); // Get all objects std::vector<thesis::ObjectInstance> all_objects; semantic_map.setCurrentPosition(get_current_camera_position()); semantic_map.getAll(all_objects); // Check which are currently visible for(size_t i = 0; i < all_objects.size(); i++) { // Transform object pose to camera coordinates // (which makes checking for visibility a lot easier) geometry_msgs::PoseStamped pose_camera; map_2_camera(all_objects[i].pose_stamped, pose_camera); // Check if object is currently visible if(is_visible(pose_camera.pose.position)) { visible.push_back(all_objects[i]); } } } bool object_callback(const thesis::ObjectInstance& input, boost::uuids::uuid& id) { // thesis::ObjectInstance transformed; transformed.type_id = input.type_id; transformed.confidence = input.confidence; // If available, transform recognized object pose to map frame if(!isnan(input.pose_stamped.pose.position)) { // Compute min distance for object to be considered a new object float min_distance = get_shorter_side(input.type_id); // if(!isnan(min_distance) && min_distance > 0.0f) { // Debug output if(debug) { ROS_INFO("Mapping::object_callback(%s): ", input.type_id.c_str()); ROS_INFO(" min_distance: %f.", min_distance); std::cout << std::endl; } // Transform object to map space camera_2_map(input.pose_stamped, transformed.pose_stamped); // Add object to semantic map return semantic_map.add(transformed, id, min_distance); } else { // Error if(debug) { ROS_INFO("Mapping::object_callback(%s): ", input.type_id.c_str()); ROS_INFO(" Database does not know dimensions yet."); ROS_INFO(" Don't add object to semantic map."); std::cout << std::endl; } // 'true' might seem weird, // but it must remain consistent with SemanticMap::add() return true; } } else { // Error if(debug) { ROS_INFO("Mapping::object_callback(%s): ", input.type_id.c_str()); ROS_INFO(" Got bad object position values (at least one is NaN)."); std::cout << std::endl; } // 'true' might seem weird, // but it must remain consistent with SemanticMap::add() return true; } } void object_array_callback(const thesis::ObjectInstanceArray::ConstPtr& input) { // Attempt cleanup if delay is up if((ros::Time::now() - last_cleanup).toSec() > age_threshold) { semantic_map.cleanup(age_threshold, (int) min_confirmations); last_cleanup = ros::Time::now(); } // Get currently visible objects std::vector<thesis::ObjectInstance> visible; get_currently_visible(visible); size_t nof_visible = visible.size(); // Add objects to semantic map for(size_t i = 0; i < input->array.size(); i++) { boost::uuids::uuid id; // 'false' if an object was updated instead of adding a new one if(!object_callback(input->array[i], id)) { // Remove updated objects from currently visible objects std::vector<thesis::ObjectInstance>::iterator vec_iter = visible.begin(); while(vec_iter != visible.end()) { if(uuid_msgs::fromMsg(vec_iter->uuid) == id) { vec_iter = visible.erase(vec_iter); // We shouldn't find an object with the same UUID again break; } else { vec_iter++; } } } } // Flag not updated visible objects for removal for(size_t i = 0; i < visible.size(); i++) { semantic_map.flag( visible[i].type_id, uuid_msgs::fromMsg(visible[i].uuid), age_threshold ); } // Debug output if(debug) { ROS_INFO("Mapping::object_array_callback(): "); ROS_INFO(" %lo visible objects.", nof_visible); ROS_INFO(" %lo of them were updated,", nof_visible - visible.size()); ROS_INFO(" %lo were flagged for removal.", visible.size()); std::cout << std::endl; } } bool get_all(thesis::MappingGetAll::Request& request, thesis::MappingGetAll::Response& result) { semantic_map.setCurrentPosition(get_current_camera_position()); semantic_map.getAll(result.objects); return true; } bool get_by_type(thesis::MappingGetByID::Request& request, thesis::MappingGetByID::Response& result) { semantic_map.setCurrentPosition(get_current_camera_position()); semantic_map.getByID(request.id, result.objects); return true; } bool get_by_position(thesis::MappingGetByPosition::Request& request, thesis::MappingGetByPosition::Response& result) { semantic_map.setCurrentPosition(get_current_camera_position()); semantic_map.getByPosition(ros2cv3f(request.position), result.objects); return true; } bool get_visible(thesis::MappingGetVisible::Request& request, thesis::MappingGetVisible::Response& result) { // Just a fail-safe, get_currently_visible() should be doing this anyway semantic_map.setCurrentPosition(get_current_camera_position()); // Get currently visible objects get_currently_visible(result.objects); // Success return true; } int main(int argc, char** argv) { // Initialize ROS ros::init(argc, argv, "thesis_mapping"); ros::NodeHandle nh; ros::NodeHandle nh_private("~"); // Get global parameters nh.getParam("/thesis/camera_frame", camera_frame); nh.getParam("/thesis/map_frame", map_frame); nh.getParam("/thesis/tf_timeout", tf_timeout); nh.getParam("/thesis/memory_size", memory_size); ROS_INFO("Mapping (global parameters): "); ROS_INFO(" Camera frame: %s.", camera_frame.c_str()); ROS_INFO(" Map frame: %s.", map_frame.c_str()); ROS_INFO(" TF timeout: %f.", tf_timeout); ROS_INFO(" Memory size: %i.", memory_size); std::cout << std::endl; // Get local parameters nh_private.param("debug", debug, false); nh_private.param("age_threshold", age_threshold, 1.0); nh_private.param("min_confirmations", min_confirmations, 0); nh_private.param("fov_width", fov_width, 90); nh_private.param("fov_height", fov_height, 90); nh_private.param("fov_near", fov_near, 0.0); nh_private.param("fov_far", fov_far, 5.0); ROS_INFO("Mapping (local parameters): "); ROS_INFO(" Debug mode: %s.", debug ? "true" : "false"); ROS_INFO(" Age threshold: %f.", age_threshold); ROS_INFO(" Min confirmations: %i.", min_confirmations); ROS_INFO(" FOV width: %i.", fov_width); ROS_INFO(" FOV height: %i.", fov_height); ROS_INFO(" FOV near: %f.", fov_near); ROS_INFO(" FOV far: %f.", fov_far); std::cout << std::endl; // Create transform listener transform_listener = new tf::TransformListener(); // Initialize reusable service clients ros::service::waitForService("thesis_database/get_by_type", -1); db_get_by_type_client = nh.serviceClient<thesis::DatabaseGetByID>("thesis_database/get_by_type"); // Subscribe to relevant topics ros::Subscriber object_subscriber = nh.subscribe("thesis_recognition/object_pose", 1, object_array_callback); // Advertise services ros::ServiceServer srv_all = nh_private.advertiseService("all", get_all); ros::ServiceServer srv_by_type = nh_private.advertiseService("by_type", get_by_type); ros::ServiceServer srv_by_position = nh_private.advertiseService("by_position", get_by_position); ros::ServiceServer srv_visible = nh_private.advertiseService("visible", get_visible); // Initialize semantic map semantic_map = SemanticMap(memory_size, debug); last_cleanup = ros::Time::now(); // Spin ros::spin(); // Free memory delete transform_listener; // Exit return 0; } <commit_msg>Added try-catch block to mapping, so the node doesn't shut down whenever there is a tf lookup error.<commit_after>/** * @author Carsten Könemann */ // This is a ROS project #include <ros/ros.h> // Local headers #include <thesis/math3d.h> #include <thesis/semantic_map.h> // We are working with TF #include <tf/transform_listener.h> // We want to subscribe to messages of this types #include <thesis/ObjectInstance.h> #include <thesis/ObjectInstanceArray.h> // We want to call these services #include <thesis/DatabaseGetByID.h> // This node provides these services #include <thesis/MappingGetAll.h> #include <thesis/MappingGetByID.h> #include <thesis/MappingGetByPosition.h> #include <thesis/MappingGetVisible.h> using namespace geometry_msgs; // Config parameters std::string camera_frame, map_frame; double tf_timeout, age_threshold, fov_near, fov_far; int memory_size, min_confirmations, fov_width, fov_height; bool debug; // Transform listener tf::TransformListener* transform_listener; // Reusable service clients ros::ServiceClient db_get_by_type_client; // The actual semantic map, storing recognized objects with map coordinates SemanticMap semantic_map; // Time since last cleanup ros::Time last_cleanup; void map_2_camera(const PoseStamped& pose_map, PoseStamped& pose_camera) { try { // Make sure transformation exists at this point in time if(transform_listener->waitForTransform( map_frame, camera_frame, pose_map.header.stamp, ros::Duration(tf_timeout) )) { // Transform recognized camera pose to map frame transform_listener->transformPose(camera_frame, pose_map, pose_camera); pose_camera.header.stamp = ros::Time::now(); } } catch(tf::TransformException e) { ROS_ERROR("Mapping::map_2_camera(): "); ROS_ERROR(" tf::TransformException caught."); ROS_ERROR(" %s", e.what()); } } void camera_2_map(const PoseStamped& pose_camera, PoseStamped& pose_map) { try { // Make sure transformation exists at this point in time if(transform_listener->waitForTransform( camera_frame, map_frame, pose_camera.header.stamp, ros::Duration(tf_timeout) )) { // Transform recognized camera pose to map frame transform_listener->transformPose(map_frame, pose_camera, pose_map); pose_map.header.stamp = ros::Time(0); } } catch(tf::TransformException e) { ROS_ERROR("Mapping::camera_2_map(): "); ROS_ERROR(" tf::TransformException caught."); ROS_ERROR(" %s", e.what()); } } cv::Point3f get_current_camera_position() { // geometry_msgs::PoseStamped pose_camera; pose_camera.header.stamp = ros::Time::now(); pose_camera.header.frame_id = camera_frame; pose_camera.pose.position.x = 0; pose_camera.pose.position.y = 0; pose_camera.pose.position.z = 0; tf::quaternionTFToMsg(IDENTITY_QUATERNION, pose_camera.pose.orientation); // geometry_msgs::PoseStamped pose_map; camera_2_map(pose_camera, pose_map); // return ros2cv3f(pose_map.pose.position); } inline bool is_visible(geometry_msgs::Point p) { // Calculate angles between point and camera direction float angle_width = angle3f(cv::Point3f(p.x, 0.0f, p.z), cv::Point3f(0.0f, 0.0f, 1.0f)), angle_heigth = angle3f(cv::Point3f(0.0f, p.y, p.z), cv::Point3f(0.0f, 0.0f, 1.0f)); // Check if point is inside camera frustum return (angle_width <= fov_width && angle_heigth <= fov_height && p.z >= fov_near && p.z <= fov_far); } inline float get_shorter_side(std::string type) { thesis::DatabaseGetByID db_get_by_type_service; db_get_by_type_service.request.id = type; if(db_get_by_type_client.call(db_get_by_type_service)) { // Get dimensions float width = db_get_by_type_service.response.object_class.width, height = db_get_by_type_service.response.object_class.height; // Return shorter side return std::min(width, height); } else { // Error ROS_WARN("Mapping::get_shorter_side(%s): ", type.c_str()); ROS_WARN(" Failed to call service 'thesis_database/get_by_type'."); std::cout << std::endl; return NAN; } } inline void get_currently_visible(std::vector<thesis::ObjectInstance>& visible) { visible.clear(); // Get all objects std::vector<thesis::ObjectInstance> all_objects; semantic_map.setCurrentPosition(get_current_camera_position()); semantic_map.getAll(all_objects); // Check which are currently visible for(size_t i = 0; i < all_objects.size(); i++) { // Transform object pose to camera coordinates // (which makes checking for visibility a lot easier) geometry_msgs::PoseStamped pose_camera; map_2_camera(all_objects[i].pose_stamped, pose_camera); // Check if object is currently visible if(is_visible(pose_camera.pose.position)) { visible.push_back(all_objects[i]); } } } bool object_callback(const thesis::ObjectInstance& input, boost::uuids::uuid& id) { // thesis::ObjectInstance transformed; transformed.type_id = input.type_id; transformed.confidence = input.confidence; // If available, transform recognized object pose to map frame if(!isnan(input.pose_stamped.pose.position)) { // Compute min distance for object to be considered a new object float min_distance = get_shorter_side(input.type_id); // if(!isnan(min_distance) && min_distance > 0.0f) { // Debug output if(debug) { ROS_INFO("Mapping::object_callback(%s): ", input.type_id.c_str()); ROS_INFO(" min_distance: %f.", min_distance); std::cout << std::endl; } // Transform object to map space camera_2_map(input.pose_stamped, transformed.pose_stamped); // Add object to semantic map return semantic_map.add(transformed, id, min_distance); } else { // Error if(debug) { ROS_INFO("Mapping::object_callback(%s): ", input.type_id.c_str()); ROS_INFO(" Database does not know dimensions yet."); ROS_INFO(" Don't add object to semantic map."); std::cout << std::endl; } // 'true' might seem weird, // but it must remain consistent with SemanticMap::add() return true; } } else { // Error if(debug) { ROS_INFO("Mapping::object_callback(%s): ", input.type_id.c_str()); ROS_INFO(" Got bad object position values (at least one is NaN)."); std::cout << std::endl; } // 'true' might seem weird, // but it must remain consistent with SemanticMap::add() return true; } } void object_array_callback(const thesis::ObjectInstanceArray::ConstPtr& input) { // Attempt cleanup if delay is up if((ros::Time::now() - last_cleanup).toSec() > age_threshold) { semantic_map.cleanup(age_threshold, (int) min_confirmations); last_cleanup = ros::Time::now(); } // Get currently visible objects std::vector<thesis::ObjectInstance> visible; get_currently_visible(visible); size_t nof_visible = visible.size(); // Add objects to semantic map for(size_t i = 0; i < input->array.size(); i++) { boost::uuids::uuid id; // 'false' if an object was updated instead of adding a new one if(!object_callback(input->array[i], id)) { // Remove updated objects from currently visible objects std::vector<thesis::ObjectInstance>::iterator vec_iter = visible.begin(); while(vec_iter != visible.end()) { if(uuid_msgs::fromMsg(vec_iter->uuid) == id) { vec_iter = visible.erase(vec_iter); // We shouldn't find an object with the same UUID again break; } else { vec_iter++; } } } } // Flag not updated visible objects for removal for(size_t i = 0; i < visible.size(); i++) { semantic_map.flag( visible[i].type_id, uuid_msgs::fromMsg(visible[i].uuid), age_threshold ); } // Debug output if(debug) { ROS_INFO("Mapping::object_array_callback(): "); ROS_INFO(" %lo visible objects.", nof_visible); ROS_INFO(" %lo of them were updated,", nof_visible - visible.size()); ROS_INFO(" %lo were flagged for removal.", visible.size()); std::cout << std::endl; } } bool get_all(thesis::MappingGetAll::Request& request, thesis::MappingGetAll::Response& result) { semantic_map.setCurrentPosition(get_current_camera_position()); semantic_map.getAll(result.objects); return true; } bool get_by_type(thesis::MappingGetByID::Request& request, thesis::MappingGetByID::Response& result) { semantic_map.setCurrentPosition(get_current_camera_position()); semantic_map.getByID(request.id, result.objects); return true; } bool get_by_position(thesis::MappingGetByPosition::Request& request, thesis::MappingGetByPosition::Response& result) { semantic_map.setCurrentPosition(get_current_camera_position()); semantic_map.getByPosition(ros2cv3f(request.position), result.objects); return true; } bool get_visible(thesis::MappingGetVisible::Request& request, thesis::MappingGetVisible::Response& result) { // Just a fail-safe, get_currently_visible() should be doing this anyway semantic_map.setCurrentPosition(get_current_camera_position()); // Get currently visible objects get_currently_visible(result.objects); // Success return true; } int main(int argc, char** argv) { // Initialize ROS ros::init(argc, argv, "thesis_mapping"); ros::NodeHandle nh; ros::NodeHandle nh_private("~"); // Get global parameters nh.getParam("/thesis/camera_frame", camera_frame); nh.getParam("/thesis/map_frame", map_frame); nh.getParam("/thesis/tf_timeout", tf_timeout); nh.getParam("/thesis/memory_size", memory_size); ROS_INFO("Mapping (global parameters): "); ROS_INFO(" Camera frame: %s.", camera_frame.c_str()); ROS_INFO(" Map frame: %s.", map_frame.c_str()); ROS_INFO(" TF timeout: %f.", tf_timeout); ROS_INFO(" Memory size: %i.", memory_size); std::cout << std::endl; // Get local parameters nh_private.param("debug", debug, false); nh_private.param("age_threshold", age_threshold, 1.0); nh_private.param("min_confirmations", min_confirmations, 0); nh_private.param("fov_width", fov_width, 90); nh_private.param("fov_height", fov_height, 90); nh_private.param("fov_near", fov_near, 0.0); nh_private.param("fov_far", fov_far, 5.0); ROS_INFO("Mapping (local parameters): "); ROS_INFO(" Debug mode: %s.", debug ? "true" : "false"); ROS_INFO(" Age threshold: %f.", age_threshold); ROS_INFO(" Min confirmations: %i.", min_confirmations); ROS_INFO(" FOV width: %i.", fov_width); ROS_INFO(" FOV height: %i.", fov_height); ROS_INFO(" FOV near: %f.", fov_near); ROS_INFO(" FOV far: %f.", fov_far); std::cout << std::endl; // Create transform listener transform_listener = new tf::TransformListener(); // Initialize reusable service clients ros::service::waitForService("thesis_database/get_by_type", -1); db_get_by_type_client = nh.serviceClient<thesis::DatabaseGetByID>("thesis_database/get_by_type"); // Subscribe to relevant topics ros::Subscriber object_subscriber = nh.subscribe("thesis_recognition/object_pose", 1, object_array_callback); // Advertise services ros::ServiceServer srv_all = nh_private.advertiseService("all", get_all); ros::ServiceServer srv_by_type = nh_private.advertiseService("by_type", get_by_type); ros::ServiceServer srv_by_position = nh_private.advertiseService("by_position", get_by_position); ros::ServiceServer srv_visible = nh_private.advertiseService("visible", get_visible); // Initialize semantic map semantic_map = SemanticMap(memory_size, debug); last_cleanup = ros::Time::now(); // Spin ros::spin(); // Free memory delete transform_listener; // Exit return 0; } <|endoftext|>
<commit_before>/* * A library for controlling a Microchip rn2xx3 LoRa radio. * * @Author JP Meijers * @Author Nicolas Schteinschraber * @Date 18/12/2015 * */ #include "Arduino.h" #include "rn2xx3.h" extern "C" { #include <string.h> #include <stdlib.h> } /* @param serial Needs to be an already opened Stream ({Software/Hardware}Serial) to write to and read from. */ rn2xx3::rn2xx3(Stream& serial): _serial(serial) { _serial.setTimeout(2000); } void rn2xx3::autobaud() { String response = ""; while (response=="") { delay(1000); _serial.write((byte)0x00); _serial.write(0x55); _serial.println(); _serial.println("sys get ver"); response = _serial.readStringUntil('\n'); } } RN2xx3_t rn2xx3::configureModuleType() { String version = sysver(); String model = version.substring(2,6); switch (model.toInt()) { case 2903: _moduleType = RN2903; break; case 2483: _moduleType = RN2483; break; default: _moduleType = RN_NA; break; } return _moduleType; } String rn2xx3::hweui() { delay(100); while(_serial.available()) { _serial.read(); } _serial.println("sys get hweui"); String addr = _serial.readStringUntil('\n'); addr.trim(); return addr; } String rn2xx3::sysver() { delay(100); while(_serial.available()) _serial.read(); _serial.println("sys get ver"); String ver = _serial.readStringUntil('\n'); ver.trim(); return ver; } bool rn2xx3::init() { if(_appskey=="0") //appskey variable is set by both OTAA and ABP { return false; } else if(_otaa==true) { return initOTAA(_appeui, _appskey); } else { return initABP(_devAddr, _appskey, _nwkskey); } } bool rn2xx3::initOTAA(String AppEUI, String AppKey) { _otaa = true; _appeui = AppEUI; _nwkskey = "0"; _appskey = AppKey; //reuse the variable String receivedData; //clear serial buffer while(_serial.available()) _serial.read(); _serial.println("sys get hweui"); String addr = _serial.readStringUntil('\n'); addr.trim(); configureModuleType(); switch (_moduleType) { case RN2903: _serial.println("mac reset"); break; case RN2483: _serial.println("mac reset 868"); break; default: // we shouldn't go forward with the init return false; } receivedData = _serial.readStringUntil('\n'); _serial.println("mac set appeui "+_appeui); receivedData = _serial.readStringUntil('\n'); _serial.println("mac set appkey "+_appskey); receivedData = _serial.readStringUntil('\n'); if(addr!="" && addr.length() == 16) { _serial.println("mac set deveui "+addr); } else { _serial.println("mac set deveui "+_default_deveui); } receivedData = _serial.readStringUntil('\n'); if (_moduleType == RN2903) { _serial.println("mac set pwridx 5"); } else { _serial.println("mac set pwridx 1"); } receivedData = _serial.readStringUntil('\n'); _serial.println("mac set adr off"); receivedData = _serial.readStringUntil('\n'); // Switch off automatic replies, because this library can not // handle more than one mac_rx per tx. See RN2483 datasheet, // 2.4.8.14, page 27 and the scenario on page 19. _serial.println("mac set ar off"); _serial.readStringUntil('\n'); if (_moduleType == RN2483) { _serial.println("mac set rx2 3 869525000"); receivedData = _serial.readStringUntil('\n'); } _serial.setTimeout(30000); _serial.println("mac save"); receivedData = _serial.readStringUntil('\n'); bool joined = false; for(int i=0; i<2 && !joined; i++) { _serial.println("mac join otaa"); receivedData = _serial.readStringUntil('\n'); receivedData = _serial.readStringUntil('\n'); if(receivedData.startsWith("accepted")) { joined=true; delay(1000); } else { delay(1000); } } _serial.setTimeout(2000); return joined; } bool rn2xx3::initABP(String devAddr, String AppSKey, String NwkSKey) { _otaa = false; _devAddr = devAddr; _appskey = AppSKey; _nwkskey = NwkSKey; String receivedData; //clear serial buffer while(_serial.available()) _serial.read(); configureModuleType(); switch (_moduleType) { case RN2903: _serial.println("mac reset"); _serial.readStringUntil('\n'); break; case RN2483: _serial.println("mac reset 868"); _serial.readStringUntil('\n'); _serial.println("mac set rx2 3 869525000"); _serial.readStringUntil('\n'); break; default: // we shouldn't go forward with the init return false; } _serial.println("mac set nwkskey "+_nwkskey); _serial.readStringUntil('\n'); _serial.println("mac set appskey "+_appskey); _serial.readStringUntil('\n'); _serial.println("mac set devaddr "+_devAddr); _serial.readStringUntil('\n'); _serial.println("mac set adr off"); _serial.readStringUntil('\n'); // Switch off automatic replies, because this library can not // handle more than one mac_rx per tx. See RN2483 datasheet, // 2.4.8.14, page 27 and the scenario on page 19. _serial.println("mac set ar off"); _serial.readStringUntil('\n'); if (_moduleType == RN2903) { _serial.println("mac set pwridx 5"); } else { _serial.println("mac set pwridx 1"); } _serial.readStringUntil('\n'); _serial.println("mac set dr 5"); //0= min, 7=max _serial.readStringUntil('\n'); _serial.setTimeout(60000); _serial.println("mac save"); _serial.readStringUntil('\n'); _serial.println("mac join abp"); receivedData = _serial.readStringUntil('\n'); receivedData = _serial.readStringUntil('\n'); _serial.setTimeout(2000); delay(1000); if(receivedData.startsWith("accepted")) { return true; //with abp we can always join successfully as long as the keys are valid } else { return false; } } TX_RETURN_TYPE rn2xx3::tx(String data) { return txUncnf(data); //we are unsure which mode we're in. Better not to wait for acks. } TX_RETURN_TYPE rn2xx3::txBytes(const byte* data, uint8_t size) { char msgBuffer[size*2 + 1]; char buffer[3]; for (unsigned i=0; i<size; i++) { sprintf(buffer, "%02X", data[i]); memcpy(&msgBuffer[i*2], &buffer, sizeof(buffer)); } String dataToTx(msgBuffer); return txCommand("mac tx uncnf 1 ", dataToTx, false); } TX_RETURN_TYPE rn2xx3::txCnf(String data) { return txCommand("mac tx cnf 1 ", data, true); } TX_RETURN_TYPE rn2xx3::txUncnf(String data) { return txCommand("mac tx uncnf 1 ", data, true); } TX_RETURN_TYPE rn2xx3::txCommand(String command, String data, bool shouldEncode) { bool send_success = false; uint8_t busy_count = 0; uint8_t retry_count = 0; //clear serial buffer while(_serial.available()) _serial.read(); while(!send_success) { //retransmit a maximum of 10 times retry_count++; if(retry_count>10) { return TX_FAIL; } _serial.print(command); if(shouldEncode) { sendEncoded(data); } else { _serial.print(data); } _serial.println(); String receivedData = _serial.readStringUntil('\n'); if(receivedData.startsWith("ok")) { _serial.setTimeout(30000); receivedData = _serial.readStringUntil('\n'); _serial.setTimeout(2000); if(receivedData.startsWith("mac_tx_ok")) { //SUCCESS!! send_success = true; return TX_SUCCESS; } else if(receivedData.startsWith("mac_rx")) { //example: mac_rx 1 54657374696E6720313233 _rxMessenge = receivedData.substring(receivedData.indexOf(' ', 7)+1); send_success = true; return TX_WITH_RX; } else if(receivedData.startsWith("mac_err")) { init(); } else if(receivedData.startsWith("invalid_data_len")) { //this should never happen if the prototype worked send_success = true; return TX_FAIL; } else if(receivedData.startsWith("radio_tx_ok")) { //SUCCESS!! send_success = true; return TX_SUCCESS; } else if(receivedData.startsWith("radio_err")) { //This should never happen. If it does, something major is wrong. init(); } else { //unknown response //init(); } } else if(receivedData.startsWith("invalid_param")) { //should not happen if we typed the commands correctly send_success = true; return TX_FAIL; } else if(receivedData.startsWith("not_joined")) { init(); } else if(receivedData.startsWith("no_free_ch")) { //retry delay(1000); } else if(receivedData.startsWith("silent")) { init(); } else if(receivedData.startsWith("frame_counter_err_rejoin_needed")) { init(); } else if(receivedData.startsWith("busy")) { busy_count++; if(busy_count>=10) { init(); } else { delay(1000); } } else if(receivedData.startsWith("mac_paused")) { init(); } else if(receivedData.startsWith("invalid_data_len")) { //should not happen if the prototype worked send_success = true; return TX_FAIL; } else { //unknown response after mac tx command init(); } } return TX_FAIL; //should never reach this } void rn2xx3::sendEncoded(String input) { char working; char buffer[3]; for (unsigned i=0; i<input.length(); i++) { working = input.charAt(i); sprintf(buffer, "%02x", int(working)); _serial.print(buffer); } } String rn2xx3::base16encode(String input) { char charsOut[input.length()*2+1]; char charsIn[input.length()+1]; input.trim(); input.toCharArray(charsIn, input.length()+1); unsigned i = 0; for(i = 0; i<input.length()+1; i++) { if(charsIn[i] == '\0') break; int value = int(charsIn[i]); char buffer[3]; sprintf(buffer, "%02x", value); charsOut[2*i] = buffer[0]; charsOut[2*i+1] = buffer[1]; } charsOut[2*i] = '\0'; String toReturn = String(charsOut); return toReturn; } String rn2xx3::getRx() { return _rxMessenge; } String rn2xx3::base16decode(String input) { char charsIn[input.length()+1]; char charsOut[input.length()/2+1]; input.trim(); input.toCharArray(charsIn, input.length()+1); unsigned i = 0; for(i = 0; i<input.length()/2+1; i++) { if(charsIn[i*2] == '\0') break; if(charsIn[i*2+1] == '\0') break; char toDo[2]; toDo[0] = charsIn[i*2]; toDo[1] = charsIn[i*2+1]; int out = strtoul(toDo, 0, 16); if(out<128) { charsOut[i] = char(out); } } charsOut[i] = '\0'; return charsOut; } void rn2xx3::setDR(int dr) { if(dr>=0 && dr<=5) { delay(100); while(_serial.available()) _serial.read(); _serial.print("mac set dr "); _serial.println(dr); _serial.readStringUntil('\n'); } } void rn2xx3::setSF(int sf) { if(dr>=7 && dr<=12) { delay(100); while(_serial.available()) _serial.read(); _serial.print("mac set sf sf"); _serial.println(dr); _serial.readStringUntil('\n'); } } void rn2xx3::sleep(long msec) { _serial.print("sys sleep "); _serial.println(msec); } String rn2xx3::sendRawCommand(String command) { delay(100); while(_serial.available()) _serial.read(); _serial.println(command); String ret = _serial.readStringUntil('\n'); ret.trim(); return ret; } RN2xx3_t rn2xx3::moduleType() { return _moduleType; } void rn2xx3::setFrequencyPlan(FREQ_PLAN fp) { switch (fp) { case SINGLE_CHANNEL_EU: //mac set rx2 <dataRate> <frequency> //sendRawCommand(F("mac set rx2 5 868100000")); //use this for "strict" one channel gateways sendRawCommand(F("mac set rx2 3 869525000")); //use for "non-strict" one channel gateways sendRawCommand(F("mac set ch dcycle 0 50")); //1% duty cycle for this channel sendRawCommand(F("mac set ch dcycle 1 65535")); //almost never use this channel sendRawCommand(F("mac set ch dcycle 2 65535")); //almost never use this channel break; case TTN_EU: break; case DEFAULT_EU: default: //set 868.1, 868.3 and 868.5 break; } } <commit_msg>Fixed compile error<commit_after>/* * A library for controlling a Microchip rn2xx3 LoRa radio. * * @Author JP Meijers * @Author Nicolas Schteinschraber * @Date 18/12/2015 * */ #include "Arduino.h" #include "rn2xx3.h" extern "C" { #include <string.h> #include <stdlib.h> } /* @param serial Needs to be an already opened Stream ({Software/Hardware}Serial) to write to and read from. */ rn2xx3::rn2xx3(Stream& serial): _serial(serial) { _serial.setTimeout(2000); } void rn2xx3::autobaud() { String response = ""; while (response=="") { delay(1000); _serial.write((byte)0x00); _serial.write(0x55); _serial.println(); _serial.println("sys get ver"); response = _serial.readStringUntil('\n'); } } RN2xx3_t rn2xx3::configureModuleType() { String version = sysver(); String model = version.substring(2,6); switch (model.toInt()) { case 2903: _moduleType = RN2903; break; case 2483: _moduleType = RN2483; break; default: _moduleType = RN_NA; break; } return _moduleType; } String rn2xx3::hweui() { delay(100); while(_serial.available()) { _serial.read(); } _serial.println("sys get hweui"); String addr = _serial.readStringUntil('\n'); addr.trim(); return addr; } String rn2xx3::sysver() { delay(100); while(_serial.available()) _serial.read(); _serial.println("sys get ver"); String ver = _serial.readStringUntil('\n'); ver.trim(); return ver; } bool rn2xx3::init() { if(_appskey=="0") //appskey variable is set by both OTAA and ABP { return false; } else if(_otaa==true) { return initOTAA(_appeui, _appskey); } else { return initABP(_devAddr, _appskey, _nwkskey); } } bool rn2xx3::initOTAA(String AppEUI, String AppKey) { _otaa = true; _appeui = AppEUI; _nwkskey = "0"; _appskey = AppKey; //reuse the variable String receivedData; //clear serial buffer while(_serial.available()) _serial.read(); _serial.println("sys get hweui"); String addr = _serial.readStringUntil('\n'); addr.trim(); configureModuleType(); switch (_moduleType) { case RN2903: _serial.println("mac reset"); break; case RN2483: _serial.println("mac reset 868"); break; default: // we shouldn't go forward with the init return false; } receivedData = _serial.readStringUntil('\n'); _serial.println("mac set appeui "+_appeui); receivedData = _serial.readStringUntil('\n'); _serial.println("mac set appkey "+_appskey); receivedData = _serial.readStringUntil('\n'); if(addr!="" && addr.length() == 16) { _serial.println("mac set deveui "+addr); } else { _serial.println("mac set deveui "+_default_deveui); } receivedData = _serial.readStringUntil('\n'); if (_moduleType == RN2903) { _serial.println("mac set pwridx 5"); } else { _serial.println("mac set pwridx 1"); } receivedData = _serial.readStringUntil('\n'); _serial.println("mac set adr off"); receivedData = _serial.readStringUntil('\n'); // Switch off automatic replies, because this library can not // handle more than one mac_rx per tx. See RN2483 datasheet, // 2.4.8.14, page 27 and the scenario on page 19. _serial.println("mac set ar off"); _serial.readStringUntil('\n'); if (_moduleType == RN2483) { _serial.println("mac set rx2 3 869525000"); receivedData = _serial.readStringUntil('\n'); } _serial.setTimeout(30000); _serial.println("mac save"); receivedData = _serial.readStringUntil('\n'); bool joined = false; for(int i=0; i<2 && !joined; i++) { _serial.println("mac join otaa"); receivedData = _serial.readStringUntil('\n'); receivedData = _serial.readStringUntil('\n'); if(receivedData.startsWith("accepted")) { joined=true; delay(1000); } else { delay(1000); } } _serial.setTimeout(2000); return joined; } bool rn2xx3::initABP(String devAddr, String AppSKey, String NwkSKey) { _otaa = false; _devAddr = devAddr; _appskey = AppSKey; _nwkskey = NwkSKey; String receivedData; //clear serial buffer while(_serial.available()) _serial.read(); configureModuleType(); switch (_moduleType) { case RN2903: _serial.println("mac reset"); _serial.readStringUntil('\n'); break; case RN2483: _serial.println("mac reset 868"); _serial.readStringUntil('\n'); _serial.println("mac set rx2 3 869525000"); _serial.readStringUntil('\n'); break; default: // we shouldn't go forward with the init return false; } _serial.println("mac set nwkskey "+_nwkskey); _serial.readStringUntil('\n'); _serial.println("mac set appskey "+_appskey); _serial.readStringUntil('\n'); _serial.println("mac set devaddr "+_devAddr); _serial.readStringUntil('\n'); _serial.println("mac set adr off"); _serial.readStringUntil('\n'); // Switch off automatic replies, because this library can not // handle more than one mac_rx per tx. See RN2483 datasheet, // 2.4.8.14, page 27 and the scenario on page 19. _serial.println("mac set ar off"); _serial.readStringUntil('\n'); if (_moduleType == RN2903) { _serial.println("mac set pwridx 5"); } else { _serial.println("mac set pwridx 1"); } _serial.readStringUntil('\n'); _serial.println("mac set dr 5"); //0= min, 7=max _serial.readStringUntil('\n'); _serial.setTimeout(60000); _serial.println("mac save"); _serial.readStringUntil('\n'); _serial.println("mac join abp"); receivedData = _serial.readStringUntil('\n'); receivedData = _serial.readStringUntil('\n'); _serial.setTimeout(2000); delay(1000); if(receivedData.startsWith("accepted")) { return true; //with abp we can always join successfully as long as the keys are valid } else { return false; } } TX_RETURN_TYPE rn2xx3::tx(String data) { return txUncnf(data); //we are unsure which mode we're in. Better not to wait for acks. } TX_RETURN_TYPE rn2xx3::txBytes(const byte* data, uint8_t size) { char msgBuffer[size*2 + 1]; char buffer[3]; for (unsigned i=0; i<size; i++) { sprintf(buffer, "%02X", data[i]); memcpy(&msgBuffer[i*2], &buffer, sizeof(buffer)); } String dataToTx(msgBuffer); return txCommand("mac tx uncnf 1 ", dataToTx, false); } TX_RETURN_TYPE rn2xx3::txCnf(String data) { return txCommand("mac tx cnf 1 ", data, true); } TX_RETURN_TYPE rn2xx3::txUncnf(String data) { return txCommand("mac tx uncnf 1 ", data, true); } TX_RETURN_TYPE rn2xx3::txCommand(String command, String data, bool shouldEncode) { bool send_success = false; uint8_t busy_count = 0; uint8_t retry_count = 0; //clear serial buffer while(_serial.available()) _serial.read(); while(!send_success) { //retransmit a maximum of 10 times retry_count++; if(retry_count>10) { return TX_FAIL; } _serial.print(command); if(shouldEncode) { sendEncoded(data); } else { _serial.print(data); } _serial.println(); String receivedData = _serial.readStringUntil('\n'); if(receivedData.startsWith("ok")) { _serial.setTimeout(30000); receivedData = _serial.readStringUntil('\n'); _serial.setTimeout(2000); if(receivedData.startsWith("mac_tx_ok")) { //SUCCESS!! send_success = true; return TX_SUCCESS; } else if(receivedData.startsWith("mac_rx")) { //example: mac_rx 1 54657374696E6720313233 _rxMessenge = receivedData.substring(receivedData.indexOf(' ', 7)+1); send_success = true; return TX_WITH_RX; } else if(receivedData.startsWith("mac_err")) { init(); } else if(receivedData.startsWith("invalid_data_len")) { //this should never happen if the prototype worked send_success = true; return TX_FAIL; } else if(receivedData.startsWith("radio_tx_ok")) { //SUCCESS!! send_success = true; return TX_SUCCESS; } else if(receivedData.startsWith("radio_err")) { //This should never happen. If it does, something major is wrong. init(); } else { //unknown response //init(); } } else if(receivedData.startsWith("invalid_param")) { //should not happen if we typed the commands correctly send_success = true; return TX_FAIL; } else if(receivedData.startsWith("not_joined")) { init(); } else if(receivedData.startsWith("no_free_ch")) { //retry delay(1000); } else if(receivedData.startsWith("silent")) { init(); } else if(receivedData.startsWith("frame_counter_err_rejoin_needed")) { init(); } else if(receivedData.startsWith("busy")) { busy_count++; if(busy_count>=10) { init(); } else { delay(1000); } } else if(receivedData.startsWith("mac_paused")) { init(); } else if(receivedData.startsWith("invalid_data_len")) { //should not happen if the prototype worked send_success = true; return TX_FAIL; } else { //unknown response after mac tx command init(); } } return TX_FAIL; //should never reach this } void rn2xx3::sendEncoded(String input) { char working; char buffer[3]; for (unsigned i=0; i<input.length(); i++) { working = input.charAt(i); sprintf(buffer, "%02x", int(working)); _serial.print(buffer); } } String rn2xx3::base16encode(String input) { char charsOut[input.length()*2+1]; char charsIn[input.length()+1]; input.trim(); input.toCharArray(charsIn, input.length()+1); unsigned i = 0; for(i = 0; i<input.length()+1; i++) { if(charsIn[i] == '\0') break; int value = int(charsIn[i]); char buffer[3]; sprintf(buffer, "%02x", value); charsOut[2*i] = buffer[0]; charsOut[2*i+1] = buffer[1]; } charsOut[2*i] = '\0'; String toReturn = String(charsOut); return toReturn; } String rn2xx3::getRx() { return _rxMessenge; } String rn2xx3::base16decode(String input) { char charsIn[input.length()+1]; char charsOut[input.length()/2+1]; input.trim(); input.toCharArray(charsIn, input.length()+1); unsigned i = 0; for(i = 0; i<input.length()/2+1; i++) { if(charsIn[i*2] == '\0') break; if(charsIn[i*2+1] == '\0') break; char toDo[2]; toDo[0] = charsIn[i*2]; toDo[1] = charsIn[i*2+1]; int out = strtoul(toDo, 0, 16); if(out<128) { charsOut[i] = char(out); } } charsOut[i] = '\0'; return charsOut; } void rn2xx3::setDR(int dr) { if(dr>=0 && dr<=5) { delay(100); while(_serial.available()) _serial.read(); _serial.print("mac set dr "); _serial.println(dr); _serial.readStringUntil('\n'); } } void rn2xx3::setSF(int sf) { if(sf>=7 && sf<=12) { delay(100); while(_serial.available()) _serial.read(); _serial.print("mac set sf sf"); _serial.println(sf); _serial.readStringUntil('\n'); } } void rn2xx3::sleep(long msec) { _serial.print("sys sleep "); _serial.println(msec); } String rn2xx3::sendRawCommand(String command) { delay(100); while(_serial.available()) _serial.read(); _serial.println(command); String ret = _serial.readStringUntil('\n'); ret.trim(); return ret; } RN2xx3_t rn2xx3::moduleType() { return _moduleType; } void rn2xx3::setFrequencyPlan(FREQ_PLAN fp) { switch (fp) { case SINGLE_CHANNEL_EU: //mac set rx2 <dataRate> <frequency> //sendRawCommand(F("mac set rx2 5 868100000")); //use this for "strict" one channel gateways sendRawCommand(F("mac set rx2 3 869525000")); //use for "non-strict" one channel gateways sendRawCommand(F("mac set ch dcycle 0 50")); //1% duty cycle for this channel sendRawCommand(F("mac set ch dcycle 1 65535")); //almost never use this channel sendRawCommand(F("mac set ch dcycle 2 65535")); //almost never use this channel break; case TTN_EU: break; case DEFAULT_EU: default: //set 868.1, 868.3 and 868.5 break; } } <|endoftext|>
<commit_before>//============================================================================// // File: qcan_network.hpp // // Description: QCAN classes - CAN network // // // // Copyright (C) MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // 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, the following disclaimer and // // the referenced file 'LICENSE'. // // 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. Neither the name of MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Provided that this notice is retained in full, this software may be // // distributed under the terms of the GNU Lesser General Public License // // ("LGPL") version 3 as distributed in the 'LICENSE' file. // // // //============================================================================// #ifndef QCAN_NETWORK_HPP_ #define QCAN_NETWORK_HPP_ /*----------------------------------------------------------------------------*\ ** Include files ** ** ** \*----------------------------------------------------------------------------*/ #include <QTcpServer> #include <QTcpSocket> #include <QMutex> #include <QPointer> #include <QTimer> #include "qcan_frame.hpp" #include "qcan_frame_api.hpp" #include "qcan_frame_error.hpp" using namespace QCan; /*----------------------------------------------------------------------------*\ ** Referenced classes ** ** ** \*----------------------------------------------------------------------------*/ class QCanInterface; //----------------------------------------------------------------------------- /*! ** \class QCanNetwork ** \brief CAN network representation ** ** This class represents a CAN network with a unique bit-rate. ** It supports one physical CAN interface (QCanInterface), which can be ** assigned during run-time to the CAN network and a limited number of ** virtual CAN interfaces (sockets). Clients can connect to a QCanNetwork ** via the QCanSocket class. ** */ class QCanNetwork : public QObject { Q_OBJECT public: /*! ** \param[in] pclParentV Pointer to QObject parent class ** \param[in] uwPortV Port number ** ** Create new CAN network with unique channel number. */ QCanNetwork(QObject * pclParentV = Q_NULLPTR, uint16_t uwPortV = QCAN_TCP_DEFAULT_PORT); ~QCanNetwork(); /*! ** \param[in] pclCanIfV Pointer to CAN interface class ** \return \c true if CAN interface added successfully ** \see removeInterface() ** ** The function adds a physical CAN interface to the CAN network. ** Each CAN network supports only one physical CAN interface. ** The CAN interface is removed from the network by calling ** the removeInterface() method. The parameter \c pclCanIfV is a pointer ** to an instance of a QCanInterface class. ** <p> ** The function returns \c true if the CAN interface is added, otherwise ** it will return \c false. */ bool addInterface(QCanInterface * pclCanIfV); inline int32_t bitrate(void) { return (slNomBitRateP); }; /*! ** \return Bit-rate value for Nominal Bit Timing ** \see setBitrate() ** ** This function returns the nominal bit-rate of the CAN network. ** For <b>classical CAN</b>, the return value defines the bit-rate for the ** complete frame. ** For <b>CAN FD</b> the return value defines the bit-rate for ** the arbitration phase. ** <p> ** If no bit-rate is configured, the function will return ** CANpie::eCAN_BITRATE_NONE. */ inline int32_t nominalBitrate(void) { return (slNomBitRateP); }; /*! ** \return Bit-rate value for Nominal Bit Timing ** ** This function returns the nominal bit-rate of the CAN network as ** QString. ** <p> ** If no bit-rate is configured, the function will return ** "None". */ QString nominalBitrateString(void); /*! ** \return Bit-rate value for Data Bit Timing ** \see setBitrate() ** ** This function returns the data bit-rate of the CAN network. ** For <b>classical CAN</b>, the return value is always ** CANpie::eCAN_BITRATE_NONE ** For <b>CAN FD</b> the return value defines the bit-rate for ** the data phase. ** <p> ** If no bit-rate is configured, the function will return ** CANpie::eCAN_BITRATE_NONE. */ inline int32_t dataBitrate(void) { return (slDatBitRateP); }; /*! ** \return Bit-rate value for Data Bit Timing ** ** This function returns the data bit-rate of the CAN network as ** QString. ** <p> ** If no bit-rate is configured, the function will return ** "None". */ QString dataBitrateString(void); /*! ** \return Current dispatcher time ** \see setDispatcherTime() ** ** This function returns the current dispatcher time for the ** internal CAN frame handler in milliseconds. */ uint32_t dispatcherTime(void) {return (ulDispatchTimeP); }; bool hasErrorFramesSupport(void); bool hasFastDataSupport(void); bool hasListenOnlySupport(void); inline uint8_t id(void) {return (ubIdP); }; bool isErrorFramesEnabled(void) {return (btErrorFramesEnabledP); }; bool isFastDataEnabled(void) {return (btFastDataEnabledP); }; bool isListenOnlyEnabled(void) {return (btListenOnlyEnabledP); }; /*! ** \return \c true if CAN is enabled ** \see setNetworkEnabled() ** ** This function returns \c true if the network is enabled, ** otherwise it returns \c false. */ bool isNetworkEnabled(void) {return (btNetworkEnabledP); }; QString name() { return(clNetNameP); }; void reset(void); /*! ** \see addInterface() ** ** Remove a physical CAN interface from the CAN network. */ void removeInterface(void); QHostAddress serverAddress(void); /*! ** \param[in] slNomBitRateV Nominal Bit-rate value ** \param[in] slDatBitRateV Data Bit-rate value ** \see bitrate() ** ** This function sets the bit-rate for the CAN network. For <b>classic CAN</b>, ** the parameter \c slBitrateV defines the bit-rate for the complete frame, ** the parameter \c slBrsClockV is not evaluated in that case. ** For <b>CAN FD</b> the parameter \c slBitrateV defines the bit-rate for ** the arbitration phase, the parameter \c slBrsClockV defines the ** bit-rate for the data phase. ** <p> ** For selection of predefined bit-rates the value can be taken from ** the enumeration CANpie::CAN_Bitrate_e. */ void setBitrate(int32_t slNomBitRateV, int32_t slDatBitRateV = eCAN_BITRATE_NONE); /*! ** \param[in] ulTimeV Dispatcher time ** \see dispatcherTime() ** ** This function sets the dispatcher time for the internal CAN frame ** handler in milliseconds. */ void setDispatcherTime(uint32_t ulTimeV); /*! ** \param[in] btEnableV Enable / disable error frames ** \see isErrorFramesEnabled() ** ** This function enables the dispatching of CAN error frames if \a btEnable ** is \c true, it is disabled on \c false. */ void setErrorFramesEnabled(bool btEnableV = true); void setFastDataEnabled(bool btEnableV = true); void setListenOnlyEnabled(bool btEnableV = true); /*! ** \param[in] btEnableV Enable / disable network ** \see isNetworkEnabled() ** ** This function enables the dispatching of CAN frames if \a btEnable is ** \c true, it is disabled on \c false. */ void setNetworkEnabled(bool btEnableV = true); bool setServerAddress(QHostAddress clHostAddressV); signals: void addLogMessage(const CAN_Channel_e & ubChannelR, const QString & clMessageR, LogLevel_e teLogLevelV); /*! ** \param[in] ulFrameTotalV Total number of frames ** ** This signal is emitted every second. The parameter \a ulFrameTotalV ** denotes the total number of API frames. */ void showApiFrames(uint32_t ulFrameTotalV); /*! ** \param[in] ulFrameTotalV Total number of frames ** ** This signal is emitted every second. The parameter \a ulFrameTotalV ** denotes the total number of CAN frames. */ void showCanFrames(uint32_t ulFrameTotalV); /*! ** \param[in] ulFrameTotalV Total number of frames ** ** This signal is emitted every second. The parameter \a ulFrameTotalV ** denotes the total number of CAN error frames. */ void showErrFrames(uint32_t ulFrameTotalV); /*! ** \param[in] ubLoadV Bus load in percent ** \param[in] ulMsgPerSecV Messages per second ** ** ** This signal is emitted every second. The parameter \a ubLoadV ** denotes the bus load in percent (value range 0 .. 100). */ void showLoad(uint8_t ubLoadV, uint32_t ulMsgPerSecV); private slots: /*! ** This function is called upon socket connection. */ void onSocketConnect(void); /*! ** This function is called upon socket disconnection. */ void onSocketDisconnect(void); void onTimerEvent(void); protected: private: QCanData::Type_e frameType(const QByteArray & clSockDataR); bool handleApiFrame(int32_t & slSockSrcR, QByteArray & clSockDataR); bool handleCanFrame(int32_t & slSockSrcR, QByteArray & clSockDataR); bool handleErrFrame(int32_t & slSockSrcR, QByteArray & clSockDataR); //---------------------------------------------------------------- // unique network ID, ubNetIdP is used to manage a unique id // for all networks, ubIdP holds the id of the current instance // static uint8_t ubNetIdP; uint8_t ubIdP; //---------------------------------------------------------------- // unique network name // QString clNetNameP; QPointer<QCanInterface> pclInterfaceP; QPointer<QTcpServer> pclTcpSrvP; QVector<QTcpSocket *> * pclTcpSockListP; QHostAddress clTcpHostAddrP; uint16_t uwTcpPortP; QMutex clTcpSockMutexP; QCanFrameError clLastErrorP; //---------------------------------------------------------------- // Frame dispatcher time // QTimer clDispatchTmrP; uint32_t ulDispatchTimeP; //---------------------------------------------------------------- // bit-rate settings // int32_t slNomBitRateP; int32_t slDatBitRateP; //---------------------------------------------------------------- // statistic frame counter // uint32_t ulCntFrameApiP; uint32_t ulCntFrameCanP; uint32_t ulCntFrameErrP; //---------------------------------------------------------------- // statistic bit counter // uint32_t ulCntBitMaxP; uint32_t ulCntBitCurP; //---------------------------------------------------------------- // statistic timing // uint32_t ulStatisticTickP; uint32_t ulStatisticTimeP; uint32_t ulFramePerSecMaxP; uint32_t ulFrameCntSaveP; bool btErrorFramesEnabledP; bool btFastDataEnabledP; bool btListenOnlyEnabledP; bool btNetworkEnabledP; }; #endif // QCAN_NETWORK_HPP_ <commit_msg>Add new method frameSize() and add members for statistic timing and error state of the CAN interface.<commit_after>//============================================================================// // File: qcan_network.hpp // // Description: QCAN classes - CAN network // // // // Copyright (C) MicroControl GmbH & Co. KG // // 53844 Troisdorf - Germany // // www.microcontrol.net // // // //----------------------------------------------------------------------------// // 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, the following disclaimer and // // the referenced file 'LICENSE'. // // 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. Neither the name of MicroControl nor the names of its contributors // // may be used to endorse or promote products derived from this software // // without specific prior written permission. // // // // Provided that this notice is retained in full, this software may be // // distributed under the terms of the GNU Lesser General Public License // // ("LGPL") version 3 as distributed in the 'LICENSE' file. // // // //============================================================================// #ifndef QCAN_NETWORK_HPP_ #define QCAN_NETWORK_HPP_ /*----------------------------------------------------------------------------*\ ** Include files ** ** ** \*----------------------------------------------------------------------------*/ #include <QTcpServer> #include <QTcpSocket> #include <QMutex> #include <QPointer> #include <QTimer> #include <QDateTime> #include "qcan_frame.hpp" #include "qcan_frame_api.hpp" #include "qcan_frame_error.hpp" using namespace QCan; /*----------------------------------------------------------------------------*\ ** Referenced classes ** ** ** \*----------------------------------------------------------------------------*/ class QCanInterface; //----------------------------------------------------------------------------- /*! ** \class QCanNetwork ** \brief CAN network representation ** ** This class represents a CAN network with a unique bit-rate. ** It supports one physical CAN interface (QCanInterface), which can be ** assigned during run-time to the CAN network and a limited number of ** virtual CAN interfaces (sockets). Clients can connect to a QCanNetwork ** via the QCanSocket class. ** */ class QCanNetwork : public QObject { Q_OBJECT public: /*! ** \param[in] pclParentV Pointer to QObject parent class ** \param[in] uwPortV Port number ** ** Create new CAN network with unique channel number. */ QCanNetwork(QObject * pclParentV = Q_NULLPTR, uint16_t uwPortV = QCAN_TCP_DEFAULT_PORT); ~QCanNetwork(); /*! ** \param[in] pclCanIfV Pointer to CAN interface class ** \return \c true if CAN interface added successfully ** \see removeInterface() ** ** The function adds a physical CAN interface to the CAN network. ** Each CAN network supports only one physical CAN interface. ** The CAN interface is removed from the network by calling ** the removeInterface() method. The parameter \c pclCanIfV is a pointer ** to an instance of a QCanInterface class. ** <p> ** The function returns \c true if the CAN interface is added, otherwise ** it will return \c false. */ bool addInterface(QCanInterface * pclCanIfV); inline int32_t bitrate(void) { return (slNomBitRateP); }; /*! ** \return Bit-rate value for Nominal Bit Timing ** \see setBitrate() ** ** This function returns the nominal bit-rate of the CAN network. ** For <b>classical CAN</b>, the return value defines the bit-rate for the ** complete frame. ** For <b>CAN FD</b> the return value defines the bit-rate for ** the arbitration phase. ** <p> ** If no bit-rate is configured, the function will return ** CANpie::eCAN_BITRATE_NONE. */ inline int32_t nominalBitrate(void) { return (slNomBitRateP); }; /*! ** \return Bit-rate value for Nominal Bit Timing ** ** This function returns the nominal bit-rate of the CAN network as ** QString. ** <p> ** If no bit-rate is configured, the function will return ** "None". */ QString nominalBitrateString(void); /*! ** \return Bit-rate value for Data Bit Timing ** \see setBitrate() ** ** This function returns the data bit-rate of the CAN network. ** For <b>classical CAN</b>, the return value is always ** CANpie::eCAN_BITRATE_NONE ** For <b>CAN FD</b> the return value defines the bit-rate for ** the data phase. ** <p> ** If no bit-rate is configured, the function will return ** CANpie::eCAN_BITRATE_NONE. */ inline int32_t dataBitrate(void) { return (slDatBitRateP); }; /*! ** \return Bit-rate value for Data Bit Timing ** ** This function returns the data bit-rate of the CAN network as ** QString. ** <p> ** If no bit-rate is configured, the function will return ** "None". */ QString dataBitrateString(void); /*! ** \return Current dispatcher time ** \see setDispatcherTime() ** ** This function returns the current dispatcher time for the ** internal CAN frame handler in milliseconds. */ uint32_t dispatcherTime(void) {return (ulDispatchTimeP); }; bool hasErrorFramesSupport(void); bool hasFastDataSupport(void); bool hasListenOnlySupport(void); inline uint8_t id(void) {return (ubIdP); }; bool isErrorFramesEnabled(void) {return (btErrorFramesEnabledP); }; bool isFastDataEnabled(void) {return (btFastDataEnabledP); }; bool isListenOnlyEnabled(void) {return (btListenOnlyEnabledP); }; /*! ** \return \c true if CAN is enabled ** \see setNetworkEnabled() ** ** This function returns \c true if the network is enabled, ** otherwise it returns \c false. */ bool isNetworkEnabled(void) {return (btNetworkEnabledP); }; QString name() { return(clNetNameP); }; void reset(void); /*! ** \see addInterface() ** ** Remove a physical CAN interface from the CAN network. */ void removeInterface(void); QHostAddress serverAddress(void); /*! ** \param[in] slNomBitRateV Nominal Bit-rate value ** \param[in] slDatBitRateV Data Bit-rate value ** \see dataBitrate(), nominalBitrate() ** ** ** This function sets the bit-rate for the CAN network. For <b>Classical ** CAN</b>, the parameter \c slBitrateV defines the bit-rate for the ** complete frame, the parameter \c slBrsClockV is not evaluated in that ** case. For <b>CAN FD</b> the parameter \c slBitrateV defines the bit-rate ** for the arbitration phase, the parameter \c slBrsClockV defines the ** bit-rate for the data phase. ** <p> ** For selection of predefined bit-rates the value can be taken from ** the enumeration CANpie::CAN_Bitrate_e. */ void setBitrate(int32_t slNomBitRateV, int32_t slDatBitRateV = eCAN_BITRATE_NONE); /*! ** \param[in] ulTimeV Dispatcher time ** \see dispatcherTime() ** ** This function sets the dispatcher time for the internal CAN frame ** handler in milliseconds. */ void setDispatcherTime(uint32_t ulTimeV); /*! ** \param[in] btEnableV Enable / disable error frames ** \see isErrorFramesEnabled() ** ** This function enables the dispatching of CAN error frames if \a btEnable ** is \c true, it is disabled on \c false. */ void setErrorFramesEnabled(bool btEnableV = true); void setFastDataEnabled(bool btEnableV = true); void setListenOnlyEnabled(bool btEnableV = true); /*! ** \param[in] btEnableV Enable / disable network ** \see isNetworkEnabled() ** ** This function enables the dispatching of CAN frames if \a btEnable is ** \c true, it is disabled on \c false. */ void setNetworkEnabled(bool btEnableV = true); bool setServerAddress(QHostAddress clHostAddressV); signals: void addLogMessage(const CAN_Channel_e & ubChannelR, const QString & clMessageR, LogLevel_e teLogLevelV); /*! ** \param[in] ulFrameTotalV Total number of frames ** ** This signal is emitted every second. The parameter \a ulFrameTotalV ** denotes the total number of API frames. */ void showApiFrames(uint32_t ulFrameTotalV); /*! ** \param[in] ulFrameTotalV Total number of frames ** ** This signal is emitted every second. The parameter \a ulFrameTotalV ** denotes the total number of CAN frames. */ void showCanFrames(uint32_t ulFrameTotalV); /*! ** \param[in] ulFrameTotalV Total number of frames ** ** This signal is emitted every second. The parameter \a ulFrameTotalV ** denotes the total number of CAN error frames. */ void showErrFrames(uint32_t ulFrameTotalV); /*! ** \param[in] ubLoadV Bus load in percent ** \param[in] ulMsgPerSecV Messages per second ** ** ** This signal is emitted every second. The parameter \a ubLoadV ** denotes the bus load in percent (value range 0 .. 100). */ void showLoad(uint8_t ubLoadV, uint32_t ulMsgPerSecV); private slots: /*! ** This function is called upon socket connection. */ void onSocketConnect(void); /*! ** This function is called upon socket disconnection. */ void onSocketDisconnect(void); void onTimerEvent(void); protected: private: QCanData::Type_e frameType(const QByteArray & clSockDataR); //---------------------------------------------------------------- // returns number of bits inside a data frame for static // calculations // uint32_t frameSize(const QByteArray & clSockDataR); bool handleApiFrame(int32_t & slSockSrcR, QByteArray & clSockDataR); bool handleCanFrame(int32_t & slSockSrcR, QByteArray & clSockDataR); bool handleErrFrame(int32_t & slSockSrcR, QByteArray & clSockDataR); //---------------------------------------------------------------- // unique network ID, ubNetIdP is used to manage a unique id // for all networks, ubIdP holds the id of the current instance // static uint8_t ubNetIdP; uint8_t ubIdP; //---------------------------------------------------------------- // unique network name // QString clNetNameP; QPointer<QCanInterface> pclInterfaceP; QPointer<QTcpServer> pclTcpSrvP; QVector<QTcpSocket *> * pclTcpSockListP; QHostAddress clTcpHostAddrP; uint16_t uwTcpPortP; QMutex clTcpSockMutexP; QCanFrameError clLastErrorP; //---------------------------------------------------------------- // Frame dispatcher time // QTimer clDispatchTmrP; uint32_t ulDispatchTimeP; //---------------------------------------------------------------- // bit-rate settings: the variables hold the bit-rate in // bit/s, if no bit-rate is configured the value is // eCAN_BITRATE_NONE // int32_t slNomBitRateP; int32_t slDatBitRateP; CAN_State_e teCanStateP; //---------------------------------------------------------------- // statistic frame counter // uint32_t ulCntFrameApiP; uint32_t ulCntFrameCanP; uint32_t ulCntFrameErrP; //---------------------------------------------------------------- // statistic bit counter // uint32_t ulCntBitMaxP; uint32_t ulCntBitCurP; //---------------------------------------------------------------- // statistic timing // QDateTime clTimeStartP; QDateTime clTimeStopP; uint32_t ulStatisticTickP; uint32_t ulStatisticTimeP; uint32_t ulFramePerSecMaxP; uint32_t ulFrameCntSaveP; bool btErrorFramesEnabledP; bool btFastDataEnabledP; bool btListenOnlyEnabledP; bool btNetworkEnabledP; }; #endif // QCAN_NETWORK_HPP_ <|endoftext|>
<commit_before>/// \file flv_analyser.cpp /// Contains the code for the FLV Analysing tool. #include <fcntl.h> #include <iostream> #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <string.h> #include <fstream> #include <unistd.h> #include <signal.h> #include <mist/flv_tag.h> //FLV support #include <mist/config.h> /// Reads FLV from stdin and outputs human-readable information to stderr. int main(int argc, char ** argv){ Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION); conf.parseArgs(argc, argv); FLV::Tag FLV_in; // Temporary storage for incoming FLV data. std::ofstream vData("vData"); std::ofstream aData("aData"); while ( !feof(stdin)){ if (FLV_in.FileLoader(stdin)){ std::cout << "Tag: " << FLV_in.tagType() << "\n\tTime: " << FLV_in.tagTime() << std::endl; if (FLV_in.data[0] == 0x08){ //Audio aData.write(FLV_in.data + 13, FLV_in.len - 17); } if (FLV_in.data[0] == 0x09){ //Video vData.write(FLV_in.data + 16, FLV_in.len - 20); } } } vData.close(); aData.close(); return 0; } <commit_msg>Removed unneccesary temporary debugging code from FLV analyser.<commit_after>/// \file flv_analyser.cpp /// Contains the code for the FLV Analysing tool. #include <fcntl.h> #include <iostream> #include <string> #include <vector> #include <cstdlib> #include <cstdio> #include <string.h> #include <fstream> #include <unistd.h> #include <signal.h> #include <mist/flv_tag.h> //FLV support #include <mist/config.h> /// Reads FLV from stdin and outputs human-readable information to stderr. int main(int argc, char ** argv){ Util::Config conf = Util::Config(argv[0], PACKAGE_VERSION); conf.parseArgs(argc, argv); FLV::Tag FLV_in; // Temporary storage for incoming FLV data. while ( !feof(stdin)){ if (FLV_in.FileLoader(stdin)){ std::cout << "Tag: " << FLV_in.tagType() << "\n\tTime: " << FLV_in.tagTime() << std::endl; } } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include "Student.h" #include "StudentDB.h" int main(int argc, char* argv[]) { // Welcoming information std::cout << "*************************" << std::endl; std::cout << "*欢迎使用考试报名系统! *" << std::endl; std::cout << "*开发人员:侯剑锋1552719*" << std::endl; std::cout << "*************************" << std::endl << std::endl; // Set up the initial database std::cout << "首先请建立考生信息系统!" << std::endl; StudentDB* studentDB = new StudentDB(); int n = 0; std::cout << "请输入考生人数:" << std::endl; std::cin >> n; std::cout << "请依次输入考生的考号,姓名,性别,年龄及报考类别(请以一个空格隔开各项):" << std::endl; for (int i = 0; i < n; i++) { studentDB->addStudent(std::cin); } // Display the students that the user has just input std::cout << "您已经输入了如下数据:" << std::endl; studentDB->count(); // Receive the user's choice and operate according to the choice in loops std::cout << "请选择您要进行的操作(1为插入,2为删除,3为查找,4为修改,5为统计,0为取消操作):" << std::endl; char choice = '\0'; while (std::cin >> choice) { // Cancel if (choice == '0') { std::cout << "即将退出考试报名系统!" << std::endl; delete studentDB; break; } // Insert else if (choice == '1') { studentDB->insertStudent(); } // Delete else if (choice == '2') { studentDB->deleteStudent(); } // Search else if (choice == '3') { studentDB->searchStudent(); } // Modify else if (choice == '4') { studentDB->modifyStudent(); } // Count else if (choice == '5') { studentDB->count(); } // Exceptions else { std::cout << "Illegal input!!!" << std::endl; } std::cout << "请选择您要进行的操作(1为插入,2为删除,3为查找,4为修改,5为统计,0为取消操作):" << std::endl; } return 0; } <commit_msg>Update Exercise01.cpp<commit_after>#include <iostream> #include "Student.h" #include "StudentDB.h" void displayOptions(void); int main(int argc, char* argv[]) { // Display the welcoming information std::cout << "***********************************" << std::endl; std::cout << "* Exercise 01 *" << std::endl; std::cout << "* 考生报名管理系统 *" << std::endl; std::cout << "* 1552719 侯剑锋 *" << std::endl; std::cout << "***********************************" << std::endl; displayOptions(); // Set up the initial database std::cout << "首先请建立考生信息系统!" << std::endl; StudentDB* studentDB = new StudentDB(); int n = 0; std::cout << "请输入考生人数:" << std::endl; std::cin >> n; std::cout << "请依次输入考生的考号,姓名,性别,年龄及报考类别(请以一个空格隔开各项):" << std::endl; for (int i = 0; i < n; i++) { studentDB->addStudent(std::cin); } // Display the students that the user has just input std::cout << "您已经输入了如下数据:" << std::endl; studentDB->count(); // Receive the user's choice and operate according to the choice in loops displayOptions(); char choice = '\0'; while (std::cin >> choice) { // Cancel if (choice == '0') { std::cout << "即将退出考试报名系统!" << std::endl; delete studentDB; break; } // Insert else if (choice == '1') { studentDB->insertStudent(); } // Delete else if (choice == '2') { studentDB->deleteStudent(); } // Search else if (choice == '3') { studentDB->searchStudent(); } // Modify else if (choice == '4') { studentDB->modifyStudent(); } // Count else if (choice == '5') { studentDB->count(); } // Exceptions else { std::cout << "Illegal input!!!" << std::endl; } // Display the options for the next loop displayOptions(); } return 0; } void displayOptions(void) { /* Display the options for the user */ std::cout << "请选择您的操作(1-插入,2-删除,3-查找,4-修改,5-统计,0-取消操作):" << std::endl; } <|endoftext|>
<commit_before>/** * @file activation_functions_test.cpp * @author Marcus Edel * * Tests for the various activation functions. */ #include <mlpack/core.hpp> #include <mlpack/methods/ann/activation_functions/logistic_function.hpp> #include <mlpack/methods/ann/activation_functions/identity_function.hpp> #include <mlpack/methods/ann/activation_functions/softsign_function.hpp> #include <mlpack/methods/ann/activation_functions/tanh_function.hpp> #include <mlpack/methods/ann/activation_functions/rectifier_function.hpp> #include <mlpack/methods/ann/ffn.hpp> #include <mlpack/methods/ann/init_rules/random_init.hpp> #include <mlpack/methods/ann/optimizer/rmsprop.hpp> #include <mlpack/methods/ann/performance_functions/mse_function.hpp> #include <mlpack/methods/ann/layer/bias_layer.hpp> #include <mlpack/methods/ann/layer/linear_layer.hpp> #include <mlpack/methods/ann/layer/base_layer.hpp> #include <mlpack/methods/ann/layer/binary_classification_layer.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace mlpack; using namespace mlpack::ann; BOOST_AUTO_TEST_SUITE(ActivationFunctionsTest); // Be careful! When writing new tests, always get the boolean value and store // it in a temporary, because the Boost unit test macros do weird things and // will cause bizarre problems. // Generate dataset for activation function tests. const arma::colvec activationData("-2 3.2 4.5 -100.2 1 -1 2 0"); /* * Implementation of the activation function test. * * @param input Input data used for evaluating the activation function. * @param target Target data used to evaluate the activation. * * @tparam ActivationFunction Activation function used for the check. */ template<class ActivationFunction> void CheckActivationCorrect(const arma::colvec input, const arma::colvec target) { // Test the activation function using a single value as input. for (size_t i = 0; i < target.n_elem; i++) { BOOST_REQUIRE_CLOSE(ActivationFunction::fn(input.at(i)), target.at(i), 1e-3); } // Test the activation function using the entire vector as input. arma::colvec activations; ActivationFunction::fn(input, activations); for (size_t i = 0; i < activations.n_elem; i++) { BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3); } } /* * Implementation of the activation function derivative test. * * @param input Input data used for evaluating the activation function. * @param target Target data used to evaluate the activation. * * @tparam ActivationFunction Activation function used for the check. */ template<class ActivationFunction> void CheckDerivativeCorrect(const arma::colvec input, const arma::colvec target) { // Test the calculation of the derivatives using a single value as input. for (size_t i = 0; i < target.n_elem; i++) { BOOST_REQUIRE_CLOSE(ActivationFunction::deriv(input.at(i)), target.at(i), 1e-3); } // Test the calculation of the derivatives using the entire vector as input. arma::colvec derivatives; ActivationFunction::deriv(input, derivatives); for (size_t i = 0; i < derivatives.n_elem; i++) { BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3); } } /* * Implementation of the activation function inverse test. * * @param input Input data used for evaluating the activation function. * @param target Target data used to evaluate the activation. * * @tparam ActivationFunction Activation function used for the check. */ template<class ActivationFunction> void CheckInverseCorrect(const arma::colvec input) { // Test the calculation of the inverse using a single value as input. for (size_t i = 0; i < input.n_elem; i++) { BOOST_REQUIRE_CLOSE(ActivationFunction::inv(ActivationFunction::fn( input.at(i))), input.at(i), 1e-3); } // Test the calculation of the inverse using the entire vector as input. arma::colvec activations; ActivationFunction::fn(input, activations); ActivationFunction::inv(activations, activations); for (size_t i = 0; i < input.n_elem; i++) { BOOST_REQUIRE_CLOSE(activations.at(i), input.at(i), 1e-3); } } /** * Basic test of the tanh function. */ BOOST_AUTO_TEST_CASE(TanhFunctionTest) { const arma::colvec desiredActivations("-0.96402758 0.9966824 0.99975321 -1 \ 0.76159416 -0.76159416 0.96402758 0"); const arma::colvec desiredDerivatives("0.07065082 0.00662419 0.00049352 0 \ 0.41997434 0.41997434 0.07065082 1"); CheckActivationCorrect<TanhFunction>(activationData, desiredActivations); CheckDerivativeCorrect<TanhFunction>(desiredActivations, desiredDerivatives); CheckInverseCorrect<TanhFunction>(desiredActivations); } /** * Basic test of the logistic function. */ BOOST_AUTO_TEST_CASE(LogisticFunctionTest) { const arma::colvec desiredActivations("1.19202922e-01 9.60834277e-01 \ 9.89013057e-01 3.04574e-44 \ 7.31058579e-01 2.68941421e-01 \ 8.80797078e-01 0.5"); const arma::colvec desiredDerivatives("0.10499359 0.03763177 0.01086623 \ 3.04574e-44 0.19661193 0.19661193 \ 0.10499359 0.25"); CheckActivationCorrect<LogisticFunction>(activationData, desiredActivations); CheckDerivativeCorrect<LogisticFunction>(desiredActivations, desiredDerivatives); CheckInverseCorrect<LogisticFunction>(activationData); } /** * Basic test of the softsign function. */ BOOST_AUTO_TEST_CASE(SoftsignFunctionTest) { const arma::colvec desiredActivations("-0.66666667 0.76190476 0.81818182 \ -0.99011858 0.5 -0.5 0.66666667 0"); const arma::colvec desiredDerivatives("0.11111111 0.05668934 0.03305785 \ 9.7642e-05 0.25 0.25 0.11111111 1"); CheckActivationCorrect<SoftsignFunction>(activationData, desiredActivations); CheckDerivativeCorrect<SoftsignFunction>(desiredActivations, desiredDerivatives); CheckInverseCorrect<SoftsignFunction>(desiredActivations); } /** * Basic test of the identity function. */ BOOST_AUTO_TEST_CASE(IdentityFunctionTest) { const arma::colvec desiredDerivatives = arma::ones<arma::colvec>( activationData.n_elem); CheckActivationCorrect<IdentityFunction>(activationData, activationData); CheckDerivativeCorrect<IdentityFunction>(activationData, desiredDerivatives); } /** * Basic test of the rectifier function. */ BOOST_AUTO_TEST_CASE(RectifierFunctionTest) { const arma::colvec desiredActivations("0 3.2 4.5 0 1 0 2 0"); const arma::colvec desiredDerivatives("0 1 1 0 1 0 1 0"); CheckActivationCorrect<RectifierFunction>(activationData, desiredActivations); CheckDerivativeCorrect<RectifierFunction>(desiredActivations, desiredDerivatives); } /* * Implementation of the numerical gradient checking. * * @param input Input data used for evaluating the network. * @param target Target data used to calculate the network error. * @param perturbation Constant perturbation value. * @param threshold Threshold used as bounding check. * * @tparam ActivationFunction Activation function used for the gradient check. */ template<class ActivationFunction> void CheckGradientNumericallyCorrect(const arma::mat input, const arma::mat target, const double perturbation, const double threshold) { // Specify the structure of the feed forward neural network. RandomInitialization randInit(-0.5, 0.5); arma::mat error; // Number of hidden layer units. const size_t hiddenLayerSize = 4; LinearLayer<mlpack::ann::RMSPROP, RandomInitialization> linearLayer0( input.n_rows, hiddenLayerSize, randInit); BiasLayer<> biasLayer0(hiddenLayerSize); BaseLayer<ActivationFunction> baseLayer0; LinearLayer<mlpack::ann::RMSPROP, RandomInitialization> linearLayer1( hiddenLayerSize, hiddenLayerSize, randInit); BiasLayer<> biasLayer1(hiddenLayerSize); BaseLayer<ActivationFunction> baseLayer1; LinearLayer<mlpack::ann::RMSPROP, RandomInitialization> linearLayer2( hiddenLayerSize, target.n_rows, randInit); BiasLayer<> biasLayer2(target.n_rows); BaseLayer<ActivationFunction> baseLayer2; BinaryClassificationLayer classOutputLayer; auto modules = std::tie(linearLayer0, biasLayer0, baseLayer0, linearLayer1, biasLayer1, baseLayer1, linearLayer2, biasLayer2, baseLayer2); FFN<decltype(modules), decltype(classOutputLayer), MeanSquaredErrorFunction> net(modules, classOutputLayer); // Initialize the feed forward neural network. net.FeedForward(input, target, error); net.FeedBackward(input, error); std::vector<std::reference_wrapper<decltype(linearLayer0)> > layer { linearLayer0, linearLayer1, linearLayer2 }; std::vector<arma::mat> gradient {linearLayer0.Gradient(), linearLayer1.Gradient(), linearLayer2.Gradient()}; double weight, mLoss, pLoss, dW, e; for (size_t l = 0; l < layer.size(); ++l) { for (size_t i = 0; i < layer[l].get().Weights().n_rows; ++i) { for (size_t j = 0; j < layer[l].get().Weights().n_cols; ++j) { // Store original weight. weight = layer[l].get().Weights()(i, j); // Add negative perturbation and compute error. layer[l].get().Weights().at(i, j) -= perturbation; net.FeedForward(input, target, error); mLoss = arma::as_scalar(0.5 * arma::sum(arma::pow(error, 2))); // Add positive perturbation and compute error. layer[l].get().Weights().at(i, j) += (2 * perturbation); net.FeedForward(input, target, error); pLoss = arma::as_scalar(0.5 * arma::sum(arma::pow(error, 2))); // Compute symmetric difference. dW = (pLoss - mLoss) / (2 * perturbation); e = std::abs(dW - gradient[l].at(i, j)); bool b = e < threshold; BOOST_REQUIRE_EQUAL(b, 1); // Restore original weight. layer[l].get().Weights().at(i, j) = weight; } } } } /** * The following test implements numerical gradient checking. It computes the * numerical gradient, a numerical approximation of the partial derivative of J * with respect to the i-th input argument, evaluated at g. The numerical * gradient should be approximately the partial derivative of J with respect to * g(i). * * Given a function g(\theta) that is supposedly computing: * * @f[ * \frac{\partial}{\partial \theta} J(\theta) * @f] * * we can now numerically verify its correctness by checking: * * @f[ * g(\theta) \approx \frac{J(\theta + eps) - J(\theta - eps)}{2 * eps} * @f] */ BOOST_AUTO_TEST_CASE(GradientNumericallyCorrect) { // Initialize dataset. const arma::colvec input = arma::randu<arma::colvec>(10); const arma::colvec target("0 1;"); // Perturbation and threshold constant. const double perturbation = 1e-6; const double threshold = 1e-5; CheckGradientNumericallyCorrect<LogisticFunction>(input, target, perturbation, threshold); CheckGradientNumericallyCorrect<IdentityFunction>(input, target, perturbation, threshold); CheckGradientNumericallyCorrect<RectifierFunction>(input, target, perturbation, threshold); CheckGradientNumericallyCorrect<SoftsignFunction>(input, target, perturbation, threshold); CheckGradientNumericallyCorrect<TanhFunction>(input, target, perturbation, threshold); } BOOST_AUTO_TEST_SUITE_END(); <commit_msg>Adjust the activation function test; Use the simplified layer structure.<commit_after>/** * @file activation_functions_test.cpp * @author Marcus Edel * * Tests for the various activation functions. */ #include <mlpack/core.hpp> #include <mlpack/methods/ann/activation_functions/logistic_function.hpp> #include <mlpack/methods/ann/activation_functions/identity_function.hpp> #include <mlpack/methods/ann/activation_functions/softsign_function.hpp> #include <mlpack/methods/ann/activation_functions/tanh_function.hpp> #include <mlpack/methods/ann/activation_functions/rectifier_function.hpp> #include <mlpack/methods/ann/ffn.hpp> #include <mlpack/methods/ann/init_rules/random_init.hpp> #include <mlpack/methods/ann/optimizer/rmsprop.hpp> #include <mlpack/methods/ann/performance_functions/mse_function.hpp> #include <mlpack/methods/ann/layer/bias_layer.hpp> #include <mlpack/methods/ann/layer/linear_layer.hpp> #include <mlpack/methods/ann/layer/base_layer.hpp> #include <mlpack/methods/ann/layer/binary_classification_layer.hpp> #include <boost/test/unit_test.hpp> #include "old_boost_test_definitions.hpp" using namespace mlpack; using namespace mlpack::ann; BOOST_AUTO_TEST_SUITE(ActivationFunctionsTest); // Be careful! When writing new tests, always get the boolean value and store // it in a temporary, because the Boost unit test macros do weird things and // will cause bizarre problems. // Generate dataset for activation function tests. const arma::colvec activationData("-2 3.2 4.5 -100.2 1 -1 2 0"); /* * Implementation of the activation function test. * * @param input Input data used for evaluating the activation function. * @param target Target data used to evaluate the activation. * * @tparam ActivationFunction Activation function used for the check. */ template<class ActivationFunction> void CheckActivationCorrect(const arma::colvec input, const arma::colvec target) { // Test the activation function using a single value as input. for (size_t i = 0; i < target.n_elem; i++) { BOOST_REQUIRE_CLOSE(ActivationFunction::fn(input.at(i)), target.at(i), 1e-3); } // Test the activation function using the entire vector as input. arma::colvec activations; ActivationFunction::fn(input, activations); for (size_t i = 0; i < activations.n_elem; i++) { BOOST_REQUIRE_CLOSE(activations.at(i), target.at(i), 1e-3); } } /* * Implementation of the activation function derivative test. * * @param input Input data used for evaluating the activation function. * @param target Target data used to evaluate the activation. * * @tparam ActivationFunction Activation function used for the check. */ template<class ActivationFunction> void CheckDerivativeCorrect(const arma::colvec input, const arma::colvec target) { // Test the calculation of the derivatives using a single value as input. for (size_t i = 0; i < target.n_elem; i++) { BOOST_REQUIRE_CLOSE(ActivationFunction::deriv(input.at(i)), target.at(i), 1e-3); } // Test the calculation of the derivatives using the entire vector as input. arma::colvec derivatives; ActivationFunction::deriv(input, derivatives); for (size_t i = 0; i < derivatives.n_elem; i++) { BOOST_REQUIRE_CLOSE(derivatives.at(i), target.at(i), 1e-3); } } /* * Implementation of the activation function inverse test. * * @param input Input data used for evaluating the activation function. * @param target Target data used to evaluate the activation. * * @tparam ActivationFunction Activation function used for the check. */ template<class ActivationFunction> void CheckInverseCorrect(const arma::colvec input) { // Test the calculation of the inverse using a single value as input. for (size_t i = 0; i < input.n_elem; i++) { BOOST_REQUIRE_CLOSE(ActivationFunction::inv(ActivationFunction::fn( input.at(i))), input.at(i), 1e-3); } // Test the calculation of the inverse using the entire vector as input. arma::colvec activations; ActivationFunction::fn(input, activations); ActivationFunction::inv(activations, activations); for (size_t i = 0; i < input.n_elem; i++) { BOOST_REQUIRE_CLOSE(activations.at(i), input.at(i), 1e-3); } } /** * Basic test of the tanh function. */ BOOST_AUTO_TEST_CASE(TanhFunctionTest) { const arma::colvec desiredActivations("-0.96402758 0.9966824 0.99975321 -1 \ 0.76159416 -0.76159416 0.96402758 0"); const arma::colvec desiredDerivatives("0.07065082 0.00662419 0.00049352 0 \ 0.41997434 0.41997434 0.07065082 1"); CheckActivationCorrect<TanhFunction>(activationData, desiredActivations); CheckDerivativeCorrect<TanhFunction>(desiredActivations, desiredDerivatives); CheckInverseCorrect<TanhFunction>(desiredActivations); } /** * Basic test of the logistic function. */ BOOST_AUTO_TEST_CASE(LogisticFunctionTest) { const arma::colvec desiredActivations("1.19202922e-01 9.60834277e-01 \ 9.89013057e-01 3.04574e-44 \ 7.31058579e-01 2.68941421e-01 \ 8.80797078e-01 0.5"); const arma::colvec desiredDerivatives("0.10499359 0.03763177 0.01086623 \ 3.04574e-44 0.19661193 0.19661193 \ 0.10499359 0.25"); CheckActivationCorrect<LogisticFunction>(activationData, desiredActivations); CheckDerivativeCorrect<LogisticFunction>(desiredActivations, desiredDerivatives); CheckInverseCorrect<LogisticFunction>(activationData); } /** * Basic test of the softsign function. */ BOOST_AUTO_TEST_CASE(SoftsignFunctionTest) { const arma::colvec desiredActivations("-0.66666667 0.76190476 0.81818182 \ -0.99011858 0.5 -0.5 0.66666667 0"); const arma::colvec desiredDerivatives("0.11111111 0.05668934 0.03305785 \ 9.7642e-05 0.25 0.25 0.11111111 1"); CheckActivationCorrect<SoftsignFunction>(activationData, desiredActivations); CheckDerivativeCorrect<SoftsignFunction>(desiredActivations, desiredDerivatives); CheckInverseCorrect<SoftsignFunction>(desiredActivations); } /** * Basic test of the identity function. */ BOOST_AUTO_TEST_CASE(IdentityFunctionTest) { const arma::colvec desiredDerivatives = arma::ones<arma::colvec>( activationData.n_elem); CheckActivationCorrect<IdentityFunction>(activationData, activationData); CheckDerivativeCorrect<IdentityFunction>(activationData, desiredDerivatives); } /** * Basic test of the rectifier function. */ BOOST_AUTO_TEST_CASE(RectifierFunctionTest) { const arma::colvec desiredActivations("0 3.2 4.5 0 1 0 2 0"); const arma::colvec desiredDerivatives("0 1 1 0 1 0 1 0"); CheckActivationCorrect<RectifierFunction>(activationData, desiredActivations); CheckDerivativeCorrect<RectifierFunction>(desiredActivations, desiredDerivatives); } BOOST_AUTO_TEST_SUITE_END(); <|endoftext|>
<commit_before>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "api/dynamiccontextimpl.h" #include <zorba/default_error_handler.h> #include <zorba/zorba.h> #include "context/dynamic_context.h" #include "context/static_context.h" #include "context/internal_uri_resolvers.h" #include "system/globalenv.h" #include "types/typeops.h" #include "types/typemanager.h" #include "types/root_typemanager.h" #include "api/unmarshaller.h" #include "api/zorbaimpl.h" #include "api/resultiteratorimpl.h" #include "api/resultiteratorchainer.h" #include "runtime/api/plan_wrapper.h" #include "runtime/util/item_iterator.h" #include "runtime/validate/validate.h" #include "store/api/item.h" #include "store/api/store.h" #include "store/api/item_factory.h" namespace zorba { #define ZORBA_DCTX_TRY try #define ZORBA_DCTX_CATCH catch (error::ZorbaError& e) { \ ZorbaImpl::notifyError(theQuery->theErrorHandler, e); \ } catch (std::exception& e) { \ ZorbaImpl::notifyError(theQuery->theErrorHandler, e.what()); \ } catch (...) { \ ZorbaImpl::notifyError(theQuery->theErrorHandler); \ } \ DynamicContextImpl::DynamicContextImpl(const XQueryImpl* aQuery) : theQuery(aQuery) { theCtx = theQuery->theDynamicContext; theStaticContext = theQuery->theStaticContext; SYNC_CODE(theCloningMutexp = &theQuery->theCloningMutex;) } DynamicContextImpl::~DynamicContextImpl() { } bool DynamicContextImpl::setVariable( const String& aQName, const Item& aItem ) { ZORBA_DCTX_TRY { checkNoIterators(); // unmarshall the string and the item store::Item_t lItem(Unmarshaller::getInternalItem(aItem)); ZorbaImpl::checkItem(lItem); xqpString lString (Unmarshaller::getInternalString(aQName)); // create an item iterator to store in the dyn context ItemIterator_t lIterator = new ItemIterator(lItem); xqpString lExpandedName = theCtx->expand_varname(theStaticContext, lString); // add it to the internal context theCtx->add_variable(lExpandedName, &*lIterator); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setVariableAsDocument( const String& aQName, const String& xml_uri ) { ZORBA_DCTX_TRY { checkNoIterators(); xqpString uriString (Unmarshaller::getInternalString(xml_uri)); InternalDocumentURIResolver *uri_resolver; uri_resolver = theStaticContext->get_document_uri_resolver(); store::Item_t uriItem; zorba::store::ItemFactory* item_factory = GENV_ITEMFACTORY; xqpStringStore_t uriStore = uriString.getStore(); item_factory->createAnyURI(uriItem, uriStore); store::Item_t docItem; docItem = uri_resolver->resolve(uriItem, theStaticContext, true, false); if(docItem.isNull()) return false; return setVariable(aQName, Item(docItem)); } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setVariable( const String& aQName, const ResultIterator_t& aResultIterator ) { ZORBA_DCTX_TRY { checkNoIterators(); ResultIterator* lIter = &*aResultIterator; if (!lIter) ZORBA_ERROR_DESC(API0014_INVALID_ARGUMENT, "Invalid ResultIterator given"); store::Iterator_t lRes = new store::ResultIteratorChainer(lIter); xqpString lExpandedName = theCtx->expand_varname(theStaticContext, Unmarshaller::getInternalString(aQName)); theCtx->add_variable(lExpandedName, &*lRes); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setVariableAsDocument( const String& aQName, const String& aDocURI, std::auto_ptr<std::istream> aStream ) { ZORBA_DCTX_TRY { checkNoIterators(); xqpStringStore_t lInternalDocURI = Unmarshaller::getInternalString(aDocURI); store::Item_t lDocItem = GENV_STORE.loadDocument(lInternalDocURI, *(aStream.get())); #if 0 if (lDocItem->haveSchemaUri() && !lDocItem->isValidated()) { store::Item_t validatedNode; store::Item_t typeName; QueryLoc loc; bool success = ValidateIterator:: effectiveValidationValue(validatedNode, lDocItem, typeName, theStaticContext->get_typemanager(), ParseConstants::val_strict, theStaticContext, loc); ZORBA_ASSERT(success); if (lDocItem != validatedNode) { GENV_STORE.deleteDocument(lInternalDocURI); lDocItem = validatedNode; GENV_STORE.addNode(lInternalDocURI.getp(), lDocItem); } } #endif setVariable ( aQName, Item(lDocItem) ); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setContextItem ( const Item& aItem ) { ZORBA_DCTX_TRY { checkNoIterators(); store::Item_t lItem(Unmarshaller::getInternalItem(aItem)); ZorbaImpl::checkItem(lItem); SYNC_CODE(AutoMutex lock(theCloningMutexp);) theCtx->set_context_item(lItem, 0); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setContextItemAsDocument ( const String& aDocURI, std::auto_ptr<std::istream> aInStream ) { ZORBA_DCTX_TRY { checkNoIterators(); xqpStringStore* lInternalDocURI = Unmarshaller::getInternalString(aDocURI); store::Item_t lDocItem = GENV_STORE.loadDocument(lInternalDocURI, *(aInStream.get())); setContextItem ( Item(lDocItem) ); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setContextItemAsDocument ( const String& aDocURI) { ZORBA_DCTX_TRY { checkNoIterators(); xqpString uriString (Unmarshaller::getInternalString(aDocURI)); InternalDocumentURIResolver *uri_resolver; uri_resolver = theStaticContext->get_document_uri_resolver(); store::Item_t uriItem; zorba::store::ItemFactory *item_factory = GENV_ITEMFACTORY; xqpStringStore_t uriStore = uriString.getStore(); item_factory->createAnyURI(uriItem, uriStore); store::Item_t docItem; docItem = uri_resolver->resolve(uriItem, theStaticContext, true, false); if(docItem.isNull()) return false; return setContextItem ( Item(docItem) ); } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setCurrentDateTime( const Item& aDateTimeItem ) { ZORBA_DCTX_TRY { checkNoIterators(); store::Item_t lItem = Unmarshaller::getInternalItem(aDateTimeItem); ZorbaImpl::checkItem(lItem); xqtref_t lItemType = theStaticContext->get_typemanager()-> create_named_type(lItem->getType(), TypeConstants::QUANT_ONE); if (!TypeOps::is_subtype(*lItemType, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE)) { ZORBA_ERROR_DESC_OSS(API0014_INVALID_ARGUMENT, "Given item of type [" << lItemType->toString() << "] is not a subtype of [" << GENV_TYPESYSTEM.DATETIME_TYPE_ONE->toString() << "]"); } SYNC_CODE(AutoMutex lock(theCloningMutexp);) theCtx->set_current_date_time(lItem); return true; } ZORBA_DCTX_CATCH return false; } Item DynamicContextImpl::getCurrentDateTime( ) { ZORBA_DCTX_TRY { return &*theCtx->get_current_date_time(); } ZORBA_DCTX_CATCH return Item(); } bool DynamicContextImpl::setImplicitTimezone( int aTimezoneMinutes ) { ZORBA_DCTX_TRY { checkNoIterators(); SYNC_CODE(AutoMutex lock(theCloningMutexp);) theCtx->set_implicit_timezone(aTimezoneMinutes * 60); return true; } ZORBA_DCTX_CATCH return false; } int DynamicContextImpl::getImplicitTimezone() { ZORBA_DCTX_TRY { return theCtx->get_implicit_timezone() / 60; } ZORBA_DCTX_CATCH return 0; } bool DynamicContextImpl::setDefaultCollection( const Item& aCollectionUri ) { ZORBA_DCTX_TRY { checkNoIterators(); store::Item_t lItem = Unmarshaller::getInternalItem(aCollectionUri); ZorbaImpl::checkItem(lItem); SYNC_CODE(AutoMutex lock(theCloningMutexp);) theCtx->set_default_collection(lItem); return true; } ZORBA_DCTX_CATCH return false; } void DynamicContextImpl::checkNoIterators() { ulong numIters = theQuery->theResultIterators.size(); for (ulong i = 0; i < numIters; i++) { if (theQuery->theResultIterators[i]->isActive()) ZORBA_ERROR(API0027_CANNOT_UPDATE_DCTX_WITH_ITERATORS); } } Item DynamicContextImpl::getDefaultCollection() { ZORBA_DCTX_TRY { return &*theCtx->get_default_collection(); } ZORBA_DCTX_CATCH return Item(); } } /* namespace zorba */ <commit_msg>temporary: always validate doc bound to external var<commit_after>/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "api/dynamiccontextimpl.h" #include <zorba/default_error_handler.h> #include <zorba/zorba.h> #include "context/dynamic_context.h" #include "context/static_context.h" #include "context/internal_uri_resolvers.h" #include "system/globalenv.h" #include "types/typeops.h" #include "types/typemanager.h" #include "types/root_typemanager.h" #include "api/unmarshaller.h" #include "api/zorbaimpl.h" #include "api/resultiteratorimpl.h" #include "api/resultiteratorchainer.h" #include "runtime/api/plan_wrapper.h" #include "runtime/util/item_iterator.h" #include "runtime/validate/validate.h" #include "store/api/item.h" #include "store/api/store.h" #include "store/api/item_factory.h" namespace zorba { #define ZORBA_DCTX_TRY try #define ZORBA_DCTX_CATCH catch (error::ZorbaError& e) { \ ZorbaImpl::notifyError(theQuery->theErrorHandler, e); \ } catch (std::exception& e) { \ ZorbaImpl::notifyError(theQuery->theErrorHandler, e.what()); \ } catch (...) { \ ZorbaImpl::notifyError(theQuery->theErrorHandler); \ } \ DynamicContextImpl::DynamicContextImpl(const XQueryImpl* aQuery) : theQuery(aQuery) { theCtx = theQuery->theDynamicContext; theStaticContext = theQuery->theStaticContext; SYNC_CODE(theCloningMutexp = &theQuery->theCloningMutex;) } DynamicContextImpl::~DynamicContextImpl() { } bool DynamicContextImpl::setVariable( const String& aQName, const Item& aItem ) { ZORBA_DCTX_TRY { checkNoIterators(); // unmarshall the string and the item store::Item_t lItem(Unmarshaller::getInternalItem(aItem)); ZorbaImpl::checkItem(lItem); xqpString lString (Unmarshaller::getInternalString(aQName)); // create an item iterator to store in the dyn context ItemIterator_t lIterator = new ItemIterator(lItem); xqpString lExpandedName = theCtx->expand_varname(theStaticContext, lString); // add it to the internal context theCtx->add_variable(lExpandedName, &*lIterator); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setVariable( const String& aQName, const ResultIterator_t& aResultIterator ) { ZORBA_DCTX_TRY { checkNoIterators(); ResultIterator* lIter = &*aResultIterator; if (!lIter) ZORBA_ERROR_DESC(API0014_INVALID_ARGUMENT, "Invalid ResultIterator given"); store::Iterator_t lRes = new store::ResultIteratorChainer(lIter); xqpString lExpandedName = theCtx->expand_varname(theStaticContext, Unmarshaller::getInternalString(aQName)); theCtx->add_variable(lExpandedName, &*lRes); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setVariableAsDocument( const String& aQName, const String& xml_uri ) { ZORBA_DCTX_TRY { checkNoIterators(); xqpString uriString (Unmarshaller::getInternalString(xml_uri)); InternalDocumentURIResolver *uri_resolver; uri_resolver = theStaticContext->get_document_uri_resolver(); store::Item_t uriItem; zorba::store::ItemFactory* item_factory = GENV_ITEMFACTORY; xqpStringStore_t uriStore = uriString.getStore(); item_factory->createAnyURI(uriItem, uriStore); store::Item_t docItem; docItem = uri_resolver->resolve(uriItem, theStaticContext, true, false); if(docItem.isNull()) return false; return setVariable(aQName, Item(docItem)); } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setVariableAsDocument( const String& aQName, const String& aDocURI, std::auto_ptr<std::istream> aStream) { ZORBA_DCTX_TRY { checkNoIterators(); TypeManager* tm = theStaticContext->get_typemanager(); xqpStringStore_t lInternalDocURI = Unmarshaller::getInternalString(aDocURI); store::Item_t lDocItem = GENV_STORE.loadDocument(lInternalDocURI, *(aStream.get())); #if 1 if (!lDocItem->isValidated()) { store::Item_t validatedNode; store::Item_t typeName; QueryLoc loc; try { bool success = ValidateIterator:: effectiveValidationValue(validatedNode, lDocItem, typeName, tm, ParseConstants::val_strict, theStaticContext, loc); ZORBA_ASSERT(success); if (lDocItem != validatedNode) { GENV_STORE.deleteDocument(lInternalDocURI); lDocItem = validatedNode; lDocItem->markValidated(); GENV_STORE.addNode(lInternalDocURI.getp(), lDocItem); } } catch(error::ZorbaError& e) { std::cout << "Failed to validate document " << lInternalDocURI->c_str() << std::endl << "Error : " << e.toString() << std::endl << std::endl; } } else if (tm->getSchema() == NULL) { GENV_STORE.deleteDocument(lInternalDocURI); lDocItem = GENV_STORE.loadDocument(lInternalDocURI, *(aStream.get())); } #endif setVariable (aQName, Item(lDocItem)); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setContextItem ( const Item& aItem ) { ZORBA_DCTX_TRY { checkNoIterators(); store::Item_t lItem(Unmarshaller::getInternalItem(aItem)); ZorbaImpl::checkItem(lItem); SYNC_CODE(AutoMutex lock(theCloningMutexp);) theCtx->set_context_item(lItem, 0); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setContextItemAsDocument ( const String& aDocURI, std::auto_ptr<std::istream> aInStream ) { ZORBA_DCTX_TRY { checkNoIterators(); xqpStringStore* lInternalDocURI = Unmarshaller::getInternalString(aDocURI); store::Item_t lDocItem = GENV_STORE.loadDocument(lInternalDocURI, *(aInStream.get())); setContextItem ( Item(lDocItem) ); return true; } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setContextItemAsDocument ( const String& aDocURI) { ZORBA_DCTX_TRY { checkNoIterators(); xqpString uriString (Unmarshaller::getInternalString(aDocURI)); InternalDocumentURIResolver *uri_resolver; uri_resolver = theStaticContext->get_document_uri_resolver(); store::Item_t uriItem; zorba::store::ItemFactory *item_factory = GENV_ITEMFACTORY; xqpStringStore_t uriStore = uriString.getStore(); item_factory->createAnyURI(uriItem, uriStore); store::Item_t docItem; docItem = uri_resolver->resolve(uriItem, theStaticContext, true, false); if(docItem.isNull()) return false; return setContextItem ( Item(docItem) ); } ZORBA_DCTX_CATCH return false; } bool DynamicContextImpl::setCurrentDateTime( const Item& aDateTimeItem ) { ZORBA_DCTX_TRY { checkNoIterators(); store::Item_t lItem = Unmarshaller::getInternalItem(aDateTimeItem); ZorbaImpl::checkItem(lItem); xqtref_t lItemType = theStaticContext->get_typemanager()-> create_named_type(lItem->getType(), TypeConstants::QUANT_ONE); if (!TypeOps::is_subtype(*lItemType, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE)) { ZORBA_ERROR_DESC_OSS(API0014_INVALID_ARGUMENT, "Given item of type [" << lItemType->toString() << "] is not a subtype of [" << GENV_TYPESYSTEM.DATETIME_TYPE_ONE->toString() << "]"); } SYNC_CODE(AutoMutex lock(theCloningMutexp);) theCtx->set_current_date_time(lItem); return true; } ZORBA_DCTX_CATCH return false; } Item DynamicContextImpl::getCurrentDateTime( ) { ZORBA_DCTX_TRY { return &*theCtx->get_current_date_time(); } ZORBA_DCTX_CATCH return Item(); } bool DynamicContextImpl::setImplicitTimezone( int aTimezoneMinutes ) { ZORBA_DCTX_TRY { checkNoIterators(); SYNC_CODE(AutoMutex lock(theCloningMutexp);) theCtx->set_implicit_timezone(aTimezoneMinutes * 60); return true; } ZORBA_DCTX_CATCH return false; } int DynamicContextImpl::getImplicitTimezone() { ZORBA_DCTX_TRY { return theCtx->get_implicit_timezone() / 60; } ZORBA_DCTX_CATCH return 0; } bool DynamicContextImpl::setDefaultCollection( const Item& aCollectionUri ) { ZORBA_DCTX_TRY { checkNoIterators(); store::Item_t lItem = Unmarshaller::getInternalItem(aCollectionUri); ZorbaImpl::checkItem(lItem); SYNC_CODE(AutoMutex lock(theCloningMutexp);) theCtx->set_default_collection(lItem); return true; } ZORBA_DCTX_CATCH return false; } void DynamicContextImpl::checkNoIterators() { ulong numIters = theQuery->theResultIterators.size(); for (ulong i = 0; i < numIters; i++) { if (theQuery->theResultIterators[i]->isActive()) ZORBA_ERROR(API0027_CANNOT_UPDATE_DCTX_WITH_ITERATORS); } } Item DynamicContextImpl::getDefaultCollection() { ZORBA_DCTX_TRY { return &*theCtx->get_default_collection(); } ZORBA_DCTX_CATCH return Item(); } } /* namespace zorba */ <|endoftext|>
<commit_before>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. 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. Neither the name PX4 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. * ****************************************************************************/ /** * @file PositionControl.cpp * * This file implements a P-position-control cascaded with a * PID-velocity-controller. * * Inputs: vehicle states (pos, vel, q) * desired setpoints (pos, vel, thrust, yaw) * Outputs: thrust and yaw setpoint */ #include "PositionControl.hpp" #include <float.h> #include <mathlib/mathlib.h> #include "uORB/topics/parameter_update.h" #include "Utility/ControlMath.hpp" using namespace matrix; PositionControl::PositionControl() { _Pz_h = param_find("MPC_Z_P"); _Pvz_h = param_find("MPC_Z_VEL_P"); _Ivz_h = param_find("MPC_Z_VEL_I"); _Dvz_h = param_find("MPC_Z_VEL_D"); _Pxy_h = param_find("MPC_XY_P"); _Pvxy_h = param_find("MPC_XY_VEL_P"); _Ivxy_h = param_find("MPC_XY_VEL_I"); _Dvxy_h = param_find("MPC_XY_VEL_D"); _VelMaxXY_h = param_find("MPC_XY_VEL_MAX"); _VelMaxZdown_h = param_find("MPC_Z_VEL_MAX_DN"); _VelMaxZup_h = param_find("MPC_Z_VEL_MAX_UP"); _ThrHover_h = param_find("MPC_THR_HOVER"); _ThrMax_h = param_find("MPC_THR_MAX"); _ThrMinPosition_h = param_find("MPC_THR_MIN"); _ThrMinStab_h = param_find("MPC_MANTHR_MIN"); /* Set parameter the very first time. */ _setParams(); }; void PositionControl::updateState(const vehicle_local_position_s &state, const Vector3f &vel_dot) { _pos = Vector3f(&state.x); _vel = Vector3f(&state.vx); _yaw = state.yaw; _vel_dot = vel_dot; } void PositionControl::updateSetpoint(const vehicle_local_position_setpoint_s &setpoint) { _pos_sp = Vector3f(&setpoint.x); _vel_sp = Vector3f(&setpoint.vx); _acc_sp = Vector3f(&setpoint.acc_x); _thr_sp = Vector3f(setpoint.thrust); _yaw_sp = setpoint.yaw; _yawspeed_sp = setpoint.yawspeed; _interfaceMapping(); /* If full manual is required (thrust already generated), don't run position/velocity * controller and just return thrust. */ _skipController = false; _ThrLimit[1] = _ThrMinPosition; if (PX4_ISFINITE(setpoint.thrust[0]) && PX4_ISFINITE(setpoint.thrust[1]) && PX4_ISFINITE(setpoint.thrust[2])) { _skipController = true; _ThrLimit[1] = _ThrMinStab; _pos_sp.zero(); _vel_sp.zero(); _acc_sp.zero(); } } void PositionControl::generateThrustYawSetpoint(const float &dt) { _updateParams(); /* Only run position/velocity controller * if thrust needs to be generated */ if (!_skipController) { _positionController(); _velocityController(dt); } } void PositionControl::_interfaceMapping() { /* Respects FlightTask interface, where * NAN-setpoints are of no interest and * do not require control. */ /* Loop through x,y and z components of all setpoints. */ for (int i = 0; i <= 2; i++) { if (PX4_ISFINITE(_pos_sp(i))) { /* Position control is required */ if (!PX4_ISFINITE(_vel_sp(i))) { /* Velocity is not used as feedforward term. */ _vel_sp(i) = 0.0f; } /* thrust setpoint is not supported * in position control */ _thr_sp(i) = 0.0f; } else if (PX4_ISFINITE(_vel_sp(i))) { /* Velocity controller is active without * position control. */ _pos_sp(i) = _pos(i); _thr_sp(i) = 0.0f; } else if (PX4_ISFINITE(_thr_sp(i))) { /* Thrust setpoint was generated from * stick directly. */ _pos_sp(i) = _pos(i); _vel_sp(i) = _vel(i); _thr_int(i) = 0.0f; _vel_dot(i) = 0.0f; } else { PX4_WARN("TODO: add safety"); } } if (!PX4_ISFINITE(_yawspeed_sp)) { _yawspeed_sp = 0.0f; } if (!PX4_ISFINITE(_yaw_sp)) { _yaw_sp = _yaw; } } void PositionControl::_positionController() { /* Generate desired velocity setpoint */ /* P-controller */ Vector3f vel_sp_position = (_pos_sp - _pos).emult(Pp); _vel_sp = vel_sp_position + _vel_sp; Vector2f vel_sp_xy = ControlMath::constrainXY(Vector2f(&vel_sp_position(0)), Vector2f(&(_vel_sp - vel_sp_position)(0)), _VelMaxXY); _vel_sp(0) = vel_sp_xy(0); _vel_sp(1) = vel_sp_xy(1); _vel_sp(2) = math::constrain(_vel_sp(2), -_VelMaxZ[0], _VelMaxZ[1]); } void PositionControl::_velocityController(const float &dt) { /* Generate desired thrust setpoint */ /* PID * u_des = P(vel_err) + D(vel_err_dot) + I(vel_integral) * Umin <= u_des <= Umax * * Anti-Windup: * u_des = _thr_sp; r = _vel_sp; y = _vel * u_des >= Umax and r - y >= 0 => Saturation = true * u_des >= Umax and r - y <= 0 => Saturation = false * u_des <= Umin and r - y <= 0 => Saturation = true * u_des <= Umin and r - y >= 0 => Saturation = false * * Notes: * - PID implementation is in NED-frame * - control output in D-direction has priority over NE-direction * - the equilibrium point for the PID is at hover-thrust * - the maximum tilt cannot exceed 90 degrees. This means that it is * not possible to have a desired thrust direction pointing in the positive * D-direction (= downward) * - the desired thrust in D-direction is limited by the thrust limits * - the desired thrust in NE-direction is limited by the thrust excess after * consideration of the desired thrust in D-direction. In addition, the thrust in * NE-direction is also limited by the maximum tilt. */ /* Get maximum tilt */ float tilt_max = M_PI_2_F; if (PX4_ISFINITE(_constraints.tilt_max) && _constraints.tilt_max <= tilt_max) { tilt_max = _constraints.tilt_max; } Vector3f vel_err = _vel_sp - _vel; /* * TODO: add offboard acceleration mode * */ /* Consider thrust in D-direction */ float thrust_desired_D = Pv(2) * vel_err(2) + Dv(2) * _vel_dot(2) + _thr_int(2) - _ThrHover; /* The Thrust limits are negated and swapped due to NED-frame */ float uMax = -_ThrustLimit.min; float uMin = -_ThrustLimit.max; /* Apply Anti-Windup in D-direction */ bool stop_integral_D = (thrust_desired_D >= uMax && vel_err(2) >= 0.0f) || (thrust_desired_D <= uMin && vel_err(2) <= 0.0f); if (!stop_integral_D) { _thr_int(2) += vel_err(2) * Iv(2) * dt; } /* Saturate thrust setpoint in D-direction */ _thr_sp(2) = math::constrain(thrust_desired_D, uMin, uMax); if (fabsf(_thr_sp(0)) + fabsf(_thr_sp(1)) > FLT_EPSILON) { /* Thrust setpoints in NE-direction is already provided. Only * scaling is required. */ float thr_xy_max = fabsf(_thr_sp(2)) * tanf(tilt_max); _thr_sp(0) *= thr_xy_max; _thr_sp(1) *= thr_xy_max; } else { /* PID for NE-direction */ Vector2f thrust_desired_NE; thrust_desired_NE(0) = Pv(0) * vel_err(0) + Dv(0) * _vel_dot(0) + _thr_int(0); thrust_desired_NE(1) = Pv(1) * vel_err(1) + Dv(1) * _vel_dot(1) + _thr_int(1); /* Get maximum allowed thrust in NE based on tilt and excess thrust */ float thrust_max_NE_tilt = fabsf(_thr_sp(2)) * tanf(tilt_max); float thrust_max_NE = sqrtf(_ThrustLimit.max * _ThrustLimit.max - _thr_sp(2) * _thr_sp(2)); thrust_max_NE = math::min(thrust_max_NE_tilt, thrust_max_NE); /* Get the direction of (r-y) in NE-direction */ float direction_NE = Vector2f(&vel_err(0)) * Vector2f(&_vel_sp(0)); /* Apply Anti-Windup in NE-direction */ bool stop_integral_NE = (thrust_desired_NE * thrust_desired_NE >= thrust_max_NE * thrust_max_NE && direction_NE >= 0.0f); if (!stop_integral_NE) { _thr_int(0) += vel_err(0) * Iv(0) * dt; _thr_int(1) += vel_err(1) * Iv(1) * dt; } /* Saturate thrust in NE-direction */ _thr_sp(0) = thrust_desired_NE(0); _thr_sp(1) = thrust_desired_NE(1); if (thrust_desired_NE * thrust_desired_NE > thrust_max_NE * thrust_max_NE) { float mag = thrust_desired_NE.length(); _thr_sp(0) = thrust_desired_NE(0) / mag * thrust_max_NE; _thr_sp(1) = thrust_desired_NE(1) / mag * thrust_max_NE; } } } void PositionControl::updateConstraints(const Controller::Constraints &constraints) { _constraints = constraints; } void PositionControl::_updateParams() { bool updated; parameter_update_s param_update; orb_check(_parameter_sub, &updated); if (updated) { orb_copy(ORB_ID(parameter_update), _parameter_sub, &param_update); _setParams(); } } void PositionControl::_setParams() { param_get(_Pxy_h, &Pp(0)); param_get(_Pxy_h, &Pp(1)); param_get(_Pz_h, &Pp(2)); param_get(_Pvxy_h, &Pv(0)); param_get(_Pvxy_h, &Pv(1)); param_get(_Pvz_h, &Pv(2)); param_get(_Ivxy_h, &Iv(0)); param_get(_Ivxy_h, &Iv(1)); param_get(_Ivz_h, &Iv(2)); param_get(_Dvxy_h, &Dv(0)); param_get(_Dvxy_h, &Dv(1)); param_get(_Dvz_h, &Dv(2)); param_get(_VelMaxXY_h, &_VelMaxXY); param_get(_VelMaxZup_h, &_VelMaxZ.up); param_get(_VelMaxZdown_h, &_VelMaxZ.down); param_get(_ThrHover_h, &_ThrHover); param_get(_ThrMax_h, &_ThrLimit[0]); param_get(_ThrMinPosition_h, &_ThrMinPosition); param_get(_ThrMinStab_h, &_ThrMinStab); } <commit_msg>PositionControl: parameter subscription declaration<commit_after>/**************************************************************************** * * Copyright (c) 2017 PX4 Development Team. 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. Neither the name PX4 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. * ****************************************************************************/ /** * @file PositionControl.cpp * * This file implements a P-position-control cascaded with a * PID-velocity-controller. * * Inputs: vehicle states (pos, vel, q) * desired setpoints (pos, vel, thrust, yaw) * Outputs: thrust and yaw setpoint */ #include "PositionControl.hpp" #include <float.h> #include <mathlib/mathlib.h> #include "uORB/topics/parameter_update.h" #include "Utility/ControlMath.hpp" using namespace matrix; PositionControl::PositionControl() { _Pz_h = param_find("MPC_Z_P"); _Pvz_h = param_find("MPC_Z_VEL_P"); _Ivz_h = param_find("MPC_Z_VEL_I"); _Dvz_h = param_find("MPC_Z_VEL_D"); _Pxy_h = param_find("MPC_XY_P"); _Pvxy_h = param_find("MPC_XY_VEL_P"); _Ivxy_h = param_find("MPC_XY_VEL_I"); _Dvxy_h = param_find("MPC_XY_VEL_D"); _VelMaxXY_h = param_find("MPC_XY_VEL_MAX"); _VelMaxZdown_h = param_find("MPC_Z_VEL_MAX_DN"); _VelMaxZup_h = param_find("MPC_Z_VEL_MAX_UP"); _ThrHover_h = param_find("MPC_THR_HOVER"); _ThrMax_h = param_find("MPC_THR_MAX"); _ThrMinPosition_h = param_find("MPC_THR_MIN"); _ThrMinStab_h = param_find("MPC_MANTHR_MIN"); _parameter_sub = orb_subscribe(ORB_ID(parameter_update)); /* Set parameter the very first time. */ _setParams(); }; void PositionControl::updateState(const vehicle_local_position_s &state, const Vector3f &vel_dot) { _pos = Vector3f(&state.x); _vel = Vector3f(&state.vx); _yaw = state.yaw; _vel_dot = vel_dot; } void PositionControl::updateSetpoint(const vehicle_local_position_setpoint_s &setpoint) { _pos_sp = Vector3f(&setpoint.x); _vel_sp = Vector3f(&setpoint.vx); _acc_sp = Vector3f(&setpoint.acc_x); _thr_sp = Vector3f(setpoint.thrust); _yaw_sp = setpoint.yaw; _yawspeed_sp = setpoint.yawspeed; _interfaceMapping(); /* If full manual is required (thrust already generated), don't run position/velocity * controller and just return thrust. */ _skipController = false; _ThrLimit[1] = _ThrMinPosition; if (PX4_ISFINITE(setpoint.thrust[0]) && PX4_ISFINITE(setpoint.thrust[1]) && PX4_ISFINITE(setpoint.thrust[2])) { _skipController = true; _ThrLimit[1] = _ThrMinStab; _pos_sp.zero(); _vel_sp.zero(); _acc_sp.zero(); } } void PositionControl::generateThrustYawSetpoint(const float &dt) { _updateParams(); /* Only run position/velocity controller * if thrust needs to be generated */ if (!_skipController) { _positionController(); _velocityController(dt); } } void PositionControl::_interfaceMapping() { /* Respects FlightTask interface, where * NAN-setpoints are of no interest and * do not require control. */ /* Loop through x,y and z components of all setpoints. */ for (int i = 0; i <= 2; i++) { if (PX4_ISFINITE(_pos_sp(i))) { /* Position control is required */ if (!PX4_ISFINITE(_vel_sp(i))) { /* Velocity is not used as feedforward term. */ _vel_sp(i) = 0.0f; } /* thrust setpoint is not supported * in position control */ _thr_sp(i) = 0.0f; } else if (PX4_ISFINITE(_vel_sp(i))) { /* Velocity controller is active without * position control. */ _pos_sp(i) = _pos(i); _thr_sp(i) = 0.0f; } else if (PX4_ISFINITE(_thr_sp(i))) { /* Thrust setpoint was generated from * stick directly. */ _pos_sp(i) = _pos(i); _vel_sp(i) = _vel(i); _thr_int(i) = 0.0f; _vel_dot(i) = 0.0f; } else { PX4_WARN("TODO: add safety"); } } if (!PX4_ISFINITE(_yawspeed_sp)) { _yawspeed_sp = 0.0f; } if (!PX4_ISFINITE(_yaw_sp)) { _yaw_sp = _yaw; } } void PositionControl::_positionController() { /* Generate desired velocity setpoint */ /* P-controller */ Vector3f vel_sp_position = (_pos_sp - _pos).emult(Pp); _vel_sp = vel_sp_position + _vel_sp; Vector2f vel_sp_xy = ControlMath::constrainXY(Vector2f(&vel_sp_position(0)), Vector2f(&(_vel_sp - vel_sp_position)(0)), _VelMaxXY); _vel_sp(0) = vel_sp_xy(0); _vel_sp(1) = vel_sp_xy(1); _vel_sp(2) = math::constrain(_vel_sp(2), -_VelMaxZ[0], _VelMaxZ[1]); } void PositionControl::_velocityController(const float &dt) { /* Generate desired thrust setpoint */ /* PID * u_des = P(vel_err) + D(vel_err_dot) + I(vel_integral) * Umin <= u_des <= Umax * * Anti-Windup: * u_des = _thr_sp; r = _vel_sp; y = _vel * u_des >= Umax and r - y >= 0 => Saturation = true * u_des >= Umax and r - y <= 0 => Saturation = false * u_des <= Umin and r - y <= 0 => Saturation = true * u_des <= Umin and r - y >= 0 => Saturation = false * * Notes: * - PID implementation is in NED-frame * - control output in D-direction has priority over NE-direction * - the equilibrium point for the PID is at hover-thrust * - the maximum tilt cannot exceed 90 degrees. This means that it is * not possible to have a desired thrust direction pointing in the positive * D-direction (= downward) * - the desired thrust in D-direction is limited by the thrust limits * - the desired thrust in NE-direction is limited by the thrust excess after * consideration of the desired thrust in D-direction. In addition, the thrust in * NE-direction is also limited by the maximum tilt. */ /* Get maximum tilt */ float tilt_max = M_PI_2_F; if (PX4_ISFINITE(_constraints.tilt_max) && _constraints.tilt_max <= tilt_max) { tilt_max = _constraints.tilt_max; } Vector3f vel_err = _vel_sp - _vel; /* * TODO: add offboard acceleration mode * */ /* Consider thrust in D-direction */ float thrust_desired_D = Pv(2) * vel_err(2) + Dv(2) * _vel_dot(2) + _thr_int(2) - _ThrHover; /* The Thrust limits are negated and swapped due to NED-frame */ float uMax = -_ThrustLimit.min; float uMin = -_ThrustLimit.max; /* Apply Anti-Windup in D-direction */ bool stop_integral_D = (thrust_desired_D >= uMax && vel_err(2) >= 0.0f) || (thrust_desired_D <= uMin && vel_err(2) <= 0.0f); if (!stop_integral_D) { _thr_int(2) += vel_err(2) * Iv(2) * dt; } /* Saturate thrust setpoint in D-direction */ _thr_sp(2) = math::constrain(thrust_desired_D, uMin, uMax); if (fabsf(_thr_sp(0)) + fabsf(_thr_sp(1)) > FLT_EPSILON) { /* Thrust setpoints in NE-direction is already provided. Only * scaling is required. */ float thr_xy_max = fabsf(_thr_sp(2)) * tanf(tilt_max); _thr_sp(0) *= thr_xy_max; _thr_sp(1) *= thr_xy_max; } else { /* PID for NE-direction */ Vector2f thrust_desired_NE; thrust_desired_NE(0) = Pv(0) * vel_err(0) + Dv(0) * _vel_dot(0) + _thr_int(0); thrust_desired_NE(1) = Pv(1) * vel_err(1) + Dv(1) * _vel_dot(1) + _thr_int(1); /* Get maximum allowed thrust in NE based on tilt and excess thrust */ float thrust_max_NE_tilt = fabsf(_thr_sp(2)) * tanf(tilt_max); float thrust_max_NE = sqrtf(_ThrustLimit.max * _ThrustLimit.max - _thr_sp(2) * _thr_sp(2)); thrust_max_NE = math::min(thrust_max_NE_tilt, thrust_max_NE); /* Get the direction of (r-y) in NE-direction */ float direction_NE = Vector2f(&vel_err(0)) * Vector2f(&_vel_sp(0)); /* Apply Anti-Windup in NE-direction */ bool stop_integral_NE = (thrust_desired_NE * thrust_desired_NE >= thrust_max_NE * thrust_max_NE && direction_NE >= 0.0f); if (!stop_integral_NE) { _thr_int(0) += vel_err(0) * Iv(0) * dt; _thr_int(1) += vel_err(1) * Iv(1) * dt; } /* Saturate thrust in NE-direction */ _thr_sp(0) = thrust_desired_NE(0); _thr_sp(1) = thrust_desired_NE(1); if (thrust_desired_NE * thrust_desired_NE > thrust_max_NE * thrust_max_NE) { float mag = thrust_desired_NE.length(); _thr_sp(0) = thrust_desired_NE(0) / mag * thrust_max_NE; _thr_sp(1) = thrust_desired_NE(1) / mag * thrust_max_NE; } } } void PositionControl::updateConstraints(const Controller::Constraints &constraints) { _constraints = constraints; } void PositionControl::_updateParams() { bool updated; parameter_update_s param_update; orb_check(_parameter_sub, &updated); if (updated) { orb_copy(ORB_ID(parameter_update), _parameter_sub, &param_update); _setParams(); } } void PositionControl::_setParams() { param_get(_Pxy_h, &Pp(0)); param_get(_Pxy_h, &Pp(1)); param_get(_Pz_h, &Pp(2)); param_get(_Pvxy_h, &Pv(0)); param_get(_Pvxy_h, &Pv(1)); param_get(_Pvz_h, &Pv(2)); param_get(_Ivxy_h, &Iv(0)); param_get(_Ivxy_h, &Iv(1)); param_get(_Ivz_h, &Iv(2)); param_get(_Dvxy_h, &Dv(0)); param_get(_Dvxy_h, &Dv(1)); param_get(_Dvz_h, &Dv(2)); param_get(_VelMaxXY_h, &_VelMaxXY); param_get(_VelMaxZup_h, &_VelMaxZ.up); param_get(_VelMaxZdown_h, &_VelMaxZ.down); param_get(_ThrHover_h, &_ThrHover); param_get(_ThrMax_h, &_ThrLimit[0]); param_get(_ThrMinPosition_h, &_ThrMinPosition); param_get(_ThrMinStab_h, &_ThrMinStab); } <|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/browser/autocomplete/autocomplete.h" #include "chrome/browser/autocomplete/autocomplete_edit.h" #include "chrome/browser/autocomplete/autocomplete_edit_view.h" #include "chrome/browser/autocomplete/autocomplete_popup_model.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/location_bar.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" class AutocompleteBrowserTest : public InProcessBrowserTest { protected: LocationBar* GetLocationBar() const { return browser()->window()->GetLocationBar(); } AutocompleteController* GetAutocompleteController() const { return GetLocationBar()->location_entry()->model()->popup_model()-> autocomplete_controller(); } }; IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Basic) { LocationBar* location_bar = GetLocationBar(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); // TODO(phajdan.jr): check state of IsSelectAll when it's consistent across // platforms. location_bar->FocusLocation(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->SetUserText(L"chrome"); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(L"chrome", location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->RevertAll(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->SetUserText(L"chrome"); location_bar->Revert(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Autocomplete) { LocationBar* location_bar = GetLocationBar(); AutocompleteController* autocomplete_controller = GetAutocompleteController(); { autocomplete_controller->Start(L"chrome", std::wstring(), true, false, true); EXPECT_TRUE(autocomplete_controller->done()); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(std::wstring(), location_bar->location_entry()->GetText()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); ASSERT_EQ(1U, result.size()); AutocompleteMatch match = result.match_at(0); EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type); EXPECT_FALSE(match.deletable); } { location_bar->Revert(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); EXPECT_TRUE(result.empty()); } } <commit_msg>Gather more info when AutocompleteBrowserTest flakily fails.<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 "chrome/browser/autocomplete/autocomplete.h" #include "chrome/browser/autocomplete/autocomplete_edit.h" #include "chrome/browser/autocomplete/autocomplete_edit_view.h" #include "chrome/browser/autocomplete/autocomplete_popup_model.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/location_bar.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace { std::wstring AutocompleteResultAsString(const AutocompleteResult& result) { std::wstring output(StringPrintf(L"{%d} ", result.size())); for (size_t i = 0; i < result.size(); ++i) { AutocompleteMatch match = result.match_at(i); std::wstring provider_name(ASCIIToWide(match.provider->name())); output.append(StringPrintf(L"[\"%ls\" by \"%ls\"] ", match.contents.c_str(), provider_name.c_str())); } return output; } } // namespace class AutocompleteBrowserTest : public InProcessBrowserTest { protected: LocationBar* GetLocationBar() const { return browser()->window()->GetLocationBar(); } AutocompleteController* GetAutocompleteController() const { return GetLocationBar()->location_entry()->model()->popup_model()-> autocomplete_controller(); } }; IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Basic) { LocationBar* location_bar = GetLocationBar(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); // TODO(phajdan.jr): check state of IsSelectAll when it's consistent across // platforms. location_bar->FocusLocation(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->SetUserText(L"chrome"); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(L"chrome", location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->RevertAll(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); location_bar->location_entry()->SetUserText(L"chrome"); location_bar->Revert(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); } IN_PROC_BROWSER_TEST_F(AutocompleteBrowserTest, Autocomplete) { LocationBar* location_bar = GetLocationBar(); AutocompleteController* autocomplete_controller = GetAutocompleteController(); { autocomplete_controller->Start(L"chrome", std::wstring(), true, false, true); EXPECT_TRUE(autocomplete_controller->done()); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(std::wstring(), location_bar->location_entry()->GetText()); EXPECT_TRUE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); ASSERT_EQ(1U, result.size()) << AutocompleteResultAsString(result); AutocompleteMatch match = result.match_at(0); EXPECT_EQ(AutocompleteMatch::SEARCH_WHAT_YOU_TYPED, match.type); EXPECT_FALSE(match.deletable); } { location_bar->Revert(); EXPECT_EQ(std::wstring(), location_bar->GetInputString()); EXPECT_EQ(UTF8ToWide(chrome::kAboutBlankURL), location_bar->location_entry()->GetText()); EXPECT_FALSE(location_bar->location_entry()->IsSelectAll()); const AutocompleteResult& result = autocomplete_controller->result(); EXPECT_TRUE(result.empty()) << AutocompleteResultAsString(result); } } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Rene Brun 26/12/94 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TNamed \ingroup Base The TNamed class is the base class for all named ROOT classes. A TNamed contains the essential elements (name, title) to identify a derived object in containers, directories and files. Most member functions defined in this base class are in general overridden by the derived classes. */ #include "Riostream.h" #include "Strlen.h" #include "TNamed.h" #include "TROOT.h" #include "TVirtualPad.h" #include "TClass.h" ClassImp(TNamed) //////////////////////////////////////////////////////////////////////////////// /// TNamed copy ctor. TNamed::TNamed(const TNamed &named) : TObject(named),fName(named.fName),fTitle(named.fTitle) { } //////////////////////////////////////////////////////////////////////////////// /// TNamed assignment operator. TNamed& TNamed::operator=(const TNamed& rhs) { if (this != &rhs) { TObject::operator=(rhs); fName = rhs.fName; fTitle = rhs.fTitle; } return *this; } //////////////////////////////////////////////////////////////////////////////// /// Set name and title to empty strings (""). void TNamed::Clear(Option_t *) { fName = ""; fTitle = ""; } //////////////////////////////////////////////////////////////////////////////// /// Make a clone of an object using the Streamer facility. /// If newname is specified, this will be the name of the new object. TObject *TNamed::Clone(const char *newname) const { TNamed *named = (TNamed*)TObject::Clone(newname); if (newname && strlen(newname)) named->SetName(newname); return named; } //////////////////////////////////////////////////////////////////////////////// /// Compare two TNamed objects. Returns 0 when equal, -1 when this is /// smaller and +1 when bigger (like strcmp). Int_t TNamed::Compare(const TObject *obj) const { if (this == obj) return 0; return fName.CompareTo(obj->GetName()); } //////////////////////////////////////////////////////////////////////////////// /// Copy this to obj. void TNamed::Copy(TObject &obj) const { TObject::Copy(obj); ((TNamed&)obj).fName = fName; ((TNamed&)obj).fTitle = fTitle; } //////////////////////////////////////////////////////////////////////////////// /// Encode TNamed into output buffer. void TNamed::FillBuffer(char *&buffer) { fName.FillBuffer(buffer); fTitle.FillBuffer(buffer); } //////////////////////////////////////////////////////////////////////////////// /// List TNamed name and title. void TNamed::ls(Option_t *opt) const { TROOT::IndentLevel(); if (opt && strstr(opt,"noaddr")) { std::cout <<"OBJ: " << IsA()->GetName() << "\t" << GetName() << "\t" << GetTitle() << " : " << Int_t(TestBit(kCanDelete)) << std::endl; } else { std::cout <<"OBJ: " << IsA()->GetName() << "\t" << GetName() << "\t" << GetTitle() << " : " << Int_t(TestBit(kCanDelete)) << " at: "<<this<< std::endl; } } //////////////////////////////////////////////////////////////////////////////// /// Print TNamed name and title. void TNamed::Print(Option_t *) const { std::cout <<"OBJ: " << IsA()->GetName() << "\t" << GetName() << "\t" << GetTitle() << std::endl; } //////////////////////////////////////////////////////////////////////////////// /// Change (i.e. set) the name of the TNamed. /// WARNING: if the object is a member of a THashTable or THashList container /// the container must be Rehash()'ed after SetName(). For example the list /// of objects in the current directory is a THashList. void TNamed::SetName(const char *name) { fName = name; if (gPad && TestBit(kMustCleanup)) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Change (i.e. set) all the TNamed parameters (name and title). // /// WARNING: if the name is changed and the object is a member of a /// THashTable or THashList container the container must be Rehash()'ed /// after SetName(). For example the list of objects in the current /// directory is a THashList. void TNamed::SetNameTitle(const char *name, const char *title) { fName = name; fTitle = title; if (gPad && TestBit(kMustCleanup)) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Change (i.e. set) the title of the TNamed. void TNamed::SetTitle(const char *title) { fTitle = title; if (gPad && TestBit(kMustCleanup)) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Return size of the TNamed part of the TObject. Int_t TNamed::Sizeof() const { Int_t nbytes = fName.Sizeof() + fTitle.Sizeof(); return nbytes; } <commit_msg>Remove "e.i." in the brief description. The " ." after the "i" made doxygen produce a <CR><commit_after>// @(#)root/base:$Id$ // Author: Rene Brun 26/12/94 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /** \class TNamed \ingroup Base The TNamed class is the base class for all named ROOT classes. A TNamed contains the essential elements (name, title) to identify a derived object in containers, directories and files. Most member functions defined in this base class are in general overridden by the derived classes. */ #include "Riostream.h" #include "Strlen.h" #include "TNamed.h" #include "TROOT.h" #include "TVirtualPad.h" #include "TClass.h" ClassImp(TNamed) //////////////////////////////////////////////////////////////////////////////// /// TNamed copy ctor. TNamed::TNamed(const TNamed &named) : TObject(named),fName(named.fName),fTitle(named.fTitle) { } //////////////////////////////////////////////////////////////////////////////// /// TNamed assignment operator. TNamed& TNamed::operator=(const TNamed& rhs) { if (this != &rhs) { TObject::operator=(rhs); fName = rhs.fName; fTitle = rhs.fTitle; } return *this; } //////////////////////////////////////////////////////////////////////////////// /// Set name and title to empty strings (""). void TNamed::Clear(Option_t *) { fName = ""; fTitle = ""; } //////////////////////////////////////////////////////////////////////////////// /// Make a clone of an object using the Streamer facility. /// If newname is specified, this will be the name of the new object. TObject *TNamed::Clone(const char *newname) const { TNamed *named = (TNamed*)TObject::Clone(newname); if (newname && strlen(newname)) named->SetName(newname); return named; } //////////////////////////////////////////////////////////////////////////////// /// Compare two TNamed objects. Returns 0 when equal, -1 when this is /// smaller and +1 when bigger (like strcmp). Int_t TNamed::Compare(const TObject *obj) const { if (this == obj) return 0; return fName.CompareTo(obj->GetName()); } //////////////////////////////////////////////////////////////////////////////// /// Copy this to obj. void TNamed::Copy(TObject &obj) const { TObject::Copy(obj); ((TNamed&)obj).fName = fName; ((TNamed&)obj).fTitle = fTitle; } //////////////////////////////////////////////////////////////////////////////// /// Encode TNamed into output buffer. void TNamed::FillBuffer(char *&buffer) { fName.FillBuffer(buffer); fTitle.FillBuffer(buffer); } //////////////////////////////////////////////////////////////////////////////// /// List TNamed name and title. void TNamed::ls(Option_t *opt) const { TROOT::IndentLevel(); if (opt && strstr(opt,"noaddr")) { std::cout <<"OBJ: " << IsA()->GetName() << "\t" << GetName() << "\t" << GetTitle() << " : " << Int_t(TestBit(kCanDelete)) << std::endl; } else { std::cout <<"OBJ: " << IsA()->GetName() << "\t" << GetName() << "\t" << GetTitle() << " : " << Int_t(TestBit(kCanDelete)) << " at: "<<this<< std::endl; } } //////////////////////////////////////////////////////////////////////////////// /// Print TNamed name and title. void TNamed::Print(Option_t *) const { std::cout <<"OBJ: " << IsA()->GetName() << "\t" << GetName() << "\t" << GetTitle() << std::endl; } //////////////////////////////////////////////////////////////////////////////// /// Set the name of the TNamed. /// /// WARNING: if the object is a member of a THashTable or THashList container /// the container must be Rehash()'ed after SetName(). For example the list /// of objects in the current directory is a THashList. void TNamed::SetName(const char *name) { fName = name; if (gPad && TestBit(kMustCleanup)) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set all the TNamed parameters (name and title). // /// WARNING: if the name is changed and the object is a member of a /// THashTable or THashList container the container must be Rehash()'ed /// after SetName(). For example the list of objects in the current /// directory is a THashList. void TNamed::SetNameTitle(const char *name, const char *title) { fName = name; fTitle = title; if (gPad && TestBit(kMustCleanup)) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Set the title of the TNamed. void TNamed::SetTitle(const char *title) { fTitle = title; if (gPad && TestBit(kMustCleanup)) gPad->Modified(); } //////////////////////////////////////////////////////////////////////////////// /// Return size of the TNamed part of the TObject. Int_t TNamed::Sizeof() const { Int_t nbytes = fName.Sizeof() + fTitle.Sizeof(); return nbytes; } <|endoftext|>
<commit_before>#ifdef HAVE_CCTAG #pragma once #include <openMVG/features/image_describer.hpp> #include <openMVG/features/regions_factory.hpp> #include <openMVG/types.hpp> #include <cctag/view.hpp> #include <cctag/ICCTag.hpp> #include <cereal/cereal.hpp> #include <iostream> #include <numeric> namespace openMVG { namespace features { /** @brief CCTag filter pixel type */ class CCTAG_Image_describer : public Image_describer { public: CCTAG_Image_describer() :Image_describer(), _params(3) {} CCTAG_Image_describer(const std::size_t nRings, const bool doAppend = false) :Image_describer(), _params(nRings), _doAppend(doAppend){} ~CCTAG_Image_describer() {} bool Set_configuration_preset(EDESCRIBER_PRESET preset) { // todo@L: choose most relevant preset names switch(preset) { // Normal lighting conditions: normal contrast case LOW_PRESET: case MEDIUM_PRESET: case NORMAL_PRESET: _params._cannyThrLow = 0.01f; _params._cannyThrHigh = 0.04f; break; // Low lighting conditions: very low contrast case HIGH_PRESET: case ULTRA_PRESET: // todo@L: not set yet _params._cannyThrLow = 0.002f; _params._cannyThrHigh = 0.01f; break; default: return false; } return true; } /** @brief Detect regions on the image and compute their attributes (description) @param image Image. @param regions The detected regions and attributes (the caller must delete the allocated data) @param mask 8-bit gray image for keypoint filtering (optional). Non-zero values depict the region of interest. */ bool Describe(const image::Image<unsigned char>& image, std::unique_ptr<Regions> &regions, const image::Image<unsigned char> * mask = NULL); /// Allocate Regions type depending of the Image_describer void Allocate(std::unique_ptr<Regions> &regions) const { regions.reset( new CCTAG_Regions ); } template<class Archive> void serialize( Archive & ar ) { //ar( //cereal::make_nvp("params", _params), //cereal::make_nvp("bOrientation", _bOrientation)); } private: //CCTag parameters cctag::Parameters _params; bool _doAppend; }; /** * @brief Convert the descriptor representation into a CCTag ID. * @param[in] desc descriptor * @return cctag id or UndefinedIndexT if wrong cctag descriptor */ template <class DescriptorT> IndexT getCCTagId(const DescriptorT & desc) { std::size_t cctagId = UndefinedIndexT; for (int i = 0; i < desc.size(); ++i) { if (desc.getData()[i] == (unsigned char) 255) { if (cctagId != UndefinedIndexT) { return UndefinedIndexT; } cctagId = i; } else if(desc.getData()[i] != (unsigned char) 0) { return UndefinedIndexT; } } return cctagId; } } // namespace features } // namespace openMVG #include <cereal/types/polymorphic.hpp> #include <cereal/archives/json.hpp> CEREAL_REGISTER_TYPE_WITH_NAME(openMVG::features::CCTAG_Image_describer, "CCTAG_Image_describer"); #endif //HAVE_CCTAG <commit_msg>[cctag] initialize all variables<commit_after>#ifdef HAVE_CCTAG #pragma once #include <openMVG/features/image_describer.hpp> #include <openMVG/features/regions_factory.hpp> #include <openMVG/types.hpp> #include <cctag/view.hpp> #include <cctag/ICCTag.hpp> #include <cereal/cereal.hpp> #include <iostream> #include <numeric> namespace openMVG { namespace features { /** @brief CCTag filter pixel type */ class CCTAG_Image_describer : public Image_describer { public: CCTAG_Image_describer() :Image_describer(), _params(3), _doAppend(false) {} CCTAG_Image_describer(const std::size_t nRings, const bool doAppend = false) :Image_describer(), _params(nRings), _doAppend(doAppend){} ~CCTAG_Image_describer() {} bool Set_configuration_preset(EDESCRIBER_PRESET preset) { // todo@L: choose most relevant preset names switch(preset) { // Normal lighting conditions: normal contrast case LOW_PRESET: case MEDIUM_PRESET: case NORMAL_PRESET: _params._cannyThrLow = 0.01f; _params._cannyThrHigh = 0.04f; break; // Low lighting conditions: very low contrast case HIGH_PRESET: case ULTRA_PRESET: // todo@L: not set yet _params._cannyThrLow = 0.002f; _params._cannyThrHigh = 0.01f; break; default: return false; } return true; } /** @brief Detect regions on the image and compute their attributes (description) @param image Image. @param regions The detected regions and attributes (the caller must delete the allocated data) @param mask 8-bit gray image for keypoint filtering (optional). Non-zero values depict the region of interest. */ bool Describe(const image::Image<unsigned char>& image, std::unique_ptr<Regions> &regions, const image::Image<unsigned char> * mask = NULL); /// Allocate Regions type depending of the Image_describer void Allocate(std::unique_ptr<Regions> &regions) const { regions.reset( new CCTAG_Regions ); } template<class Archive> void serialize( Archive & ar ) { //ar( //cereal::make_nvp("params", _params), //cereal::make_nvp("bOrientation", _bOrientation)); } private: //CCTag parameters cctag::Parameters _params; bool _doAppend; }; /** * @brief Convert the descriptor representation into a CCTag ID. * @param[in] desc descriptor * @return cctag id or UndefinedIndexT if wrong cctag descriptor */ template <class DescriptorT> IndexT getCCTagId(const DescriptorT & desc) { std::size_t cctagId = UndefinedIndexT; for (int i = 0; i < desc.size(); ++i) { if (desc.getData()[i] == (unsigned char) 255) { if (cctagId != UndefinedIndexT) { return UndefinedIndexT; } cctagId = i; } else if(desc.getData()[i] != (unsigned char) 0) { return UndefinedIndexT; } } return cctagId; } } // namespace features } // namespace openMVG #include <cereal/types/polymorphic.hpp> #include <cereal/archives/json.hpp> CEREAL_REGISTER_TYPE_WITH_NAME(openMVG::features::CCTAG_Image_describer, "CCTAG_Image_describer"); #endif //HAVE_CCTAG <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, 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 the Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan, Sachin Chitta */ #include "ompl_interface_ros/ompl_interface_ros.h" #include "planning_scene_monitor/planning_scene_monitor.h" #include <tf/transform_listener.h> #include <visualization_msgs/MarkerArray.h> static const std::string PLANNER_NODE_NAME="ompl_planning"; // name of node static const std::string PLANNER_SERVICE_NAME="plan_kinematic_path"; // name of the advertised service (within the ~ namespace) static const std::string BENCHMARK_SERVICE_NAME="benchmark_planning_problem"; // name of the advertised service (within the ~ namespace) static const std::string ROBOT_DESCRIPTION="robot_description"; // name of the robot description (a param name, so it can be changed externally) class OMPLPlannerService { public: OMPLPlannerService(planning_scene_monitor::PlanningSceneMonitor &psm) : nh_("~"), psm_(psm), ompl_interface_(psm.getPlanningScene()->getKinematicModel()) { plan_service_ = nh_.advertiseService(PLANNER_SERVICE_NAME, &OMPLPlannerService::computePlan, this); benchmark_service_ = nh_.advertiseService(BENCHMARK_SERVICE_NAME, &OMPLPlannerService::computeBenchmark, this); pub_markers_ = nh_.advertise<visualization_msgs::MarkerArray>("visualization_marker_array", 5); } bool computePlan(moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::GetMotionPlan::Response &res) { ROS_INFO("Received new planning request..."); bool result = ompl_interface_.solve(psm_.getPlanningScene(), req, res); displayPlannerData("r_wrist_roll_link"); return result; } void displayPlannerData(const std::string &link_name) { const ompl_interface::PlanningConfigurationPtr &pc = ompl_interface_.getLastPlanningConfiguration(); if (pc) { const ompl::base::PlannerData &pd = pc->getOMPLSimpleSetup().getPlannerData(); planning_models::KinematicState kstate = psm_.getPlanningScene()->getCurrentState(); visualization_msgs::MarkerArray arr; std_msgs::ColorRGBA color; color.r = 1.0f; color.g = 0.0f; color.b = 0.0f; color.a = 1.0f; for (std::size_t i = 0 ; i < pd.states.size() ; ++i) { pc->getKMStateSpace().copyToKinematicState(kstate, pd.states[i]); kstate.getJointStateGroup(pc->getJointModelGroupName())->updateLinkTransforms(); const Eigen::Vector3d &pos = kstate.getLinkState(link_name)->getGlobalLinkTransform().translation(); visualization_msgs::Marker mk; mk.header.stamp = ros::Time::now(); mk.header.frame_id = psm_.getPlanningScene()->getPlanningFrame(); mk.ns = "planner_data"; mk.id = i; mk.type = visualization_msgs::Marker::SPHERE; mk.action = visualization_msgs::Marker::ADD; mk.pose.position.x = pos.x(); mk.pose.position.y = pos.y(); mk.pose.position.z = pos.z(); mk.pose.orientation.w = 1.0; mk.scale.x = mk.scale.y = mk.scale.z = 0.035; mk.color = color; mk.lifetime = ros::Duration(10.0); arr.markers.push_back(mk); } pub_markers_.publish(arr); } } bool computeBenchmark(moveit_msgs::ComputePlanningBenchmark::Request &req, moveit_msgs::ComputePlanningBenchmark::Response &res) { ROS_INFO("Received new benchmark request..."); return ompl_interface_.benchmark(psm_.getPlanningScene(), req, res); } void status(void) { ompl_interface_.printStatus(); ROS_INFO("Responding to planning and bechmark requests"); } private: ros::NodeHandle nh_; planning_scene_monitor::PlanningSceneMonitor &psm_; ompl_interface_ros::OMPLInterfaceROS ompl_interface_; ros::ServiceServer plan_service_; ros::ServiceServer benchmark_service_; ros::ServiceServer display_states_service_; ros::Publisher pub_markers_; }; int main(int argc, char **argv) { ros::init(argc, argv, PLANNER_NODE_NAME); ros::AsyncSpinner spinner(1); spinner.start(); tf::TransformListener tf; planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION, &tf); if (psm.getPlanningScene()->isConfigured()) { psm.startWorldGeometryMonitor(); psm.startSceneMonitor(); psm.startStateMonitor(); OMPLPlannerService pservice(psm); pservice.status(); ros::waitForShutdown(); } else ROS_ERROR("Planning scene not configured"); return 0; } <commit_msg>print status updates<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2011, 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 the Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan, Sachin Chitta */ #include "ompl_interface_ros/ompl_interface_ros.h" #include "planning_scene_monitor/planning_scene_monitor.h" #include <tf/transform_listener.h> #include <visualization_msgs/MarkerArray.h> static const std::string PLANNER_NODE_NAME="ompl_planning"; // name of node static const std::string PLANNER_SERVICE_NAME="plan_kinematic_path"; // name of the advertised service (within the ~ namespace) static const std::string BENCHMARK_SERVICE_NAME="benchmark_planning_problem"; // name of the advertised service (within the ~ namespace) static const std::string ROBOT_DESCRIPTION="robot_description"; // name of the robot description (a param name, so it can be changed externally) class OMPLPlannerService { public: OMPLPlannerService(planning_scene_monitor::PlanningSceneMonitor &psm) : nh_("~"), psm_(psm), ompl_interface_(psm.getPlanningScene()->getKinematicModel()) { plan_service_ = nh_.advertiseService(PLANNER_SERVICE_NAME, &OMPLPlannerService::computePlan, this); benchmark_service_ = nh_.advertiseService(BENCHMARK_SERVICE_NAME, &OMPLPlannerService::computeBenchmark, this); pub_markers_ = nh_.advertise<visualization_msgs::MarkerArray>("visualization_marker_array", 5); } bool computePlan(moveit_msgs::GetMotionPlan::Request &req, moveit_msgs::GetMotionPlan::Response &res) { ROS_INFO("Received new planning request..."); bool result = ompl_interface_.solve(psm_.getPlanningScene(), req, res); displayPlannerData("r_wrist_roll_link"); std::stringstream ss; ompl::Profiler::Status(ss); ROS_INFO("%s", ss.str().c_str()); return result; } void displayPlannerData(const std::string &link_name) { const ompl_interface::PlanningConfigurationPtr &pc = ompl_interface_.getLastPlanningConfiguration(); if (pc) { const ompl::base::PlannerData &pd = pc->getOMPLSimpleSetup().getPlannerData(); planning_models::KinematicState kstate = psm_.getPlanningScene()->getCurrentState(); visualization_msgs::MarkerArray arr; std_msgs::ColorRGBA color; color.r = 1.0f; color.g = 0.0f; color.b = 0.0f; color.a = 1.0f; for (std::size_t i = 0 ; i < pd.states.size() ; ++i) { pc->getKMStateSpace().copyToKinematicState(kstate, pd.states[i]); kstate.getJointStateGroup(pc->getJointModelGroupName())->updateLinkTransforms(); const Eigen::Vector3d &pos = kstate.getLinkState(link_name)->getGlobalLinkTransform().translation(); visualization_msgs::Marker mk; mk.header.stamp = ros::Time::now(); mk.header.frame_id = psm_.getPlanningScene()->getPlanningFrame(); mk.ns = "planner_data"; mk.id = i; mk.type = visualization_msgs::Marker::SPHERE; mk.action = visualization_msgs::Marker::ADD; mk.pose.position.x = pos.x(); mk.pose.position.y = pos.y(); mk.pose.position.z = pos.z(); mk.pose.orientation.w = 1.0; mk.scale.x = mk.scale.y = mk.scale.z = 0.035; mk.color = color; mk.lifetime = ros::Duration(10.0); arr.markers.push_back(mk); } pub_markers_.publish(arr); } } bool computeBenchmark(moveit_msgs::ComputePlanningBenchmark::Request &req, moveit_msgs::ComputePlanningBenchmark::Response &res) { ROS_INFO("Received new benchmark request..."); return ompl_interface_.benchmark(psm_.getPlanningScene(), req, res); } void status(void) { ompl_interface_.printStatus(); ROS_INFO("Responding to planning and bechmark requests"); } private: ros::NodeHandle nh_; planning_scene_monitor::PlanningSceneMonitor &psm_; ompl_interface_ros::OMPLInterfaceROS ompl_interface_; ros::ServiceServer plan_service_; ros::ServiceServer benchmark_service_; ros::ServiceServer display_states_service_; ros::Publisher pub_markers_; }; int main(int argc, char **argv) { ros::init(argc, argv, PLANNER_NODE_NAME); ros::AsyncSpinner spinner(1); spinner.start(); tf::TransformListener tf; planning_scene_monitor::PlanningSceneMonitor psm(ROBOT_DESCRIPTION, &tf); if (psm.getPlanningScene()->isConfigured()) { psm.startWorldGeometryMonitor(); psm.startSceneMonitor(); psm.startStateMonitor(); OMPLPlannerService pservice(psm); pservice.status(); ros::waitForShutdown(); } else ROS_ERROR("Planning scene not configured"); return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "rocksdb/db.h" #include "db/db_impl.h" #include "db/filename.h" #include "db/version_set.h" #include "db/write_batch_internal.h" #include "util/testharness.h" #include "util/testutil.h" #include "rocksdb/env.h" #include "rocksdb/transaction_log.h" #include <vector> #include <stdlib.h> #include <map> #include <string> namespace rocksdb { class DeleteFileTest { public: std::string dbname_; Options options_; DB* db_; Env* env_; int numlevels_; DeleteFileTest() { db_ = nullptr; env_ = Env::Default(); options_.max_background_flushes = 0; options_.write_buffer_size = 1024*1024*1000; options_.target_file_size_base = 1024*1024*1000; options_.max_bytes_for_level_base = 1024*1024*1000; options_.WAL_ttl_seconds = 300; // Used to test log files options_.WAL_size_limit_MB = 1024; // Used to test log files dbname_ = test::TmpDir() + "/deletefile_test"; options_.wal_dir = dbname_ + "/wal_files"; // clean up all the files that might have been there before std::vector<std::string> old_files; env_->GetChildren(dbname_, &old_files); for (auto file : old_files) { env_->DeleteFile(dbname_ + "/" + file); } env_->GetChildren(options_.wal_dir, &old_files); for (auto file : old_files) { env_->DeleteFile(options_.wal_dir + "/" + file); } DestroyDB(dbname_, options_); numlevels_ = 7; ASSERT_OK(ReopenDB(true)); } Status ReopenDB(bool create) { delete db_; if (create) { DestroyDB(dbname_, options_); } db_ = nullptr; options_.create_if_missing = create; return DB::Open(options_, dbname_, &db_); } void CloseDB() { delete db_; } void AddKeys(int numkeys, int startkey = 0) { WriteOptions options; options.sync = false; ReadOptions roptions; for (int i = startkey; i < (numkeys + startkey) ; i++) { std::string temp = std::to_string(i); Slice key(temp); Slice value(temp); ASSERT_OK(db_->Put(options, key, value)); } } int numKeysInLevels( std::vector<LiveFileMetaData> &metadata, std::vector<int> *keysperlevel = nullptr) { if (keysperlevel != nullptr) { keysperlevel->resize(numlevels_); } int numKeys = 0; for (size_t i = 0; i < metadata.size(); i++) { int startkey = atoi(metadata[i].smallestkey.c_str()); int endkey = atoi(metadata[i].largestkey.c_str()); int numkeysinfile = (endkey - startkey + 1); numKeys += numkeysinfile; if (keysperlevel != nullptr) { (*keysperlevel)[(int)metadata[i].level] += numkeysinfile; } fprintf(stderr, "level %d name %s smallest %s largest %s\n", metadata[i].level, metadata[i].name.c_str(), metadata[i].smallestkey.c_str(), metadata[i].largestkey.c_str()); } return numKeys; } void CreateTwoLevels() { AddKeys(50000, 10000); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); ASSERT_OK(dbi->TEST_FlushMemTable()); ASSERT_OK(dbi->TEST_WaitForFlushMemTable()); AddKeys(50000, 10000); ASSERT_OK(dbi->TEST_FlushMemTable()); ASSERT_OK(dbi->TEST_WaitForFlushMemTable()); } void CheckFileTypeCounts(std::string& dir, int required_log, int required_sst, int required_manifest) { std::vector<std::string> filenames; env_->GetChildren(dir, &filenames); int log_cnt = 0, sst_cnt = 0, manifest_cnt = 0; for (auto file : filenames) { uint64_t number; FileType type; if (ParseFileName(file, &number, &type)) { log_cnt += (type == kLogFile); sst_cnt += (type == kTableFile); manifest_cnt += (type == kDescriptorFile); } } ASSERT_EQ(required_log, log_cnt); ASSERT_EQ(required_sst, sst_cnt); ASSERT_EQ(required_manifest, manifest_cnt); } }; TEST(DeleteFileTest, AddKeysAndQueryLevels) { CreateTwoLevels(); std::vector<LiveFileMetaData> metadata; std::vector<int> keysinlevel; db_->GetLiveFilesMetaData(&metadata); std::string level1file = ""; int level1keycount = 0; std::string level2file = ""; int level2keycount = 0; int level1index = 0; int level2index = 1; ASSERT_EQ((int)metadata.size(), 2); if (metadata[0].level == 2) { level1index = 1; level2index = 0; } level1file = metadata[level1index].name; int startkey = atoi(metadata[level1index].smallestkey.c_str()); int endkey = atoi(metadata[level1index].largestkey.c_str()); level1keycount = (endkey - startkey + 1); level2file = metadata[level2index].name; startkey = atoi(metadata[level2index].smallestkey.c_str()); endkey = atoi(metadata[level2index].largestkey.c_str()); level2keycount = (endkey - startkey + 1); // COntrolled setup. Levels 1 and 2 should both have 50K files. // This is a little fragile as it depends on the current // compaction heuristics. ASSERT_EQ(level1keycount, 50000); ASSERT_EQ(level2keycount, 50000); Status status = db_->DeleteFile("0.sst"); ASSERT_TRUE(status.IsInvalidArgument()); // intermediate level files cannot be deleted. status = db_->DeleteFile(level1file); ASSERT_TRUE(status.IsInvalidArgument()); // Lowest level file deletion should succeed. ASSERT_OK(db_->DeleteFile(level2file)); CloseDB(); } TEST(DeleteFileTest, PurgeObsoleteFilesTest) { CreateTwoLevels(); // there should be only one (empty) log file because CreateTwoLevels() // flushes the memtables to disk CheckFileTypeCounts(options_.wal_dir, 1, 0, 0); // 2 ssts, 1 manifest CheckFileTypeCounts(dbname_, 0, 2, 1); std::string first("0"), last("999999"); Slice first_slice(first), last_slice(last); db_->CompactRange(&first_slice, &last_slice, true, 2); // 1 sst after compaction CheckFileTypeCounts(dbname_, 0, 1, 1); // this time, we keep an iterator alive ReopenDB(true); Iterator *itr = 0; CreateTwoLevels(); itr = db_->NewIterator(ReadOptions()); db_->CompactRange(&first_slice, &last_slice, true, 2); // 3 sst after compaction with live iterator CheckFileTypeCounts(dbname_, 0, 3, 1); delete itr; // 1 sst after iterator deletion CheckFileTypeCounts(dbname_, 0, 1, 1); CloseDB(); } TEST(DeleteFileTest, DeleteFileWithIterator) { CreateTwoLevels(); ReadOptions options; Iterator* it = db_->NewIterator(options); std::vector<LiveFileMetaData> metadata; db_->GetLiveFilesMetaData(&metadata); std::string level2file = ""; ASSERT_EQ((int)metadata.size(), 2); if (metadata[0].level == 1) { level2file = metadata[1].name; } else { level2file = metadata[0].name; } Status status = db_->DeleteFile(level2file); fprintf(stdout, "Deletion status %s: %s\n", level2file.c_str(), status.ToString().c_str()); ASSERT_TRUE(status.ok()); it->SeekToFirst(); int numKeysIterated = 0; while(it->Valid()) { numKeysIterated++; it->Next(); } ASSERT_EQ(numKeysIterated, 50000); delete it; CloseDB(); } TEST(DeleteFileTest, DeleteLogFiles) { AddKeys(10, 0); VectorLogPtr logfiles; db_->GetSortedWalFiles(logfiles); ASSERT_GT(logfiles.size(), 0UL); // Take the last log file which is expected to be alive and try to delete it // Should not succeed because live logs are not allowed to be deleted std::unique_ptr<LogFile> alive_log = std::move(logfiles.back()); ASSERT_EQ(alive_log->Type(), kAliveLogFile); ASSERT_TRUE(env_->FileExists(options_.wal_dir + "/" + alive_log->PathName())); fprintf(stdout, "Deleting alive log file %s\n", alive_log->PathName().c_str()); ASSERT_TRUE(!db_->DeleteFile(alive_log->PathName()).ok()); ASSERT_TRUE(env_->FileExists(options_.wal_dir + "/" + alive_log->PathName())); logfiles.clear(); // Call Flush to bring about a new working log file and add more keys // Call Flush again to flush out memtable and move alive log to archived log // and try to delete the archived log file FlushOptions fopts; db_->Flush(fopts); AddKeys(10, 0); db_->Flush(fopts); db_->GetSortedWalFiles(logfiles); ASSERT_GT(logfiles.size(), 0UL); std::unique_ptr<LogFile> archived_log = std::move(logfiles.front()); ASSERT_EQ(archived_log->Type(), kArchivedLogFile); ASSERT_TRUE(env_->FileExists(options_.wal_dir + "/" + archived_log->PathName())); fprintf(stdout, "Deleting archived log file %s\n", archived_log->PathName().c_str()); ASSERT_OK(db_->DeleteFile(archived_log->PathName())); ASSERT_TRUE(!env_->FileExists(options_.wal_dir + "/" + archived_log->PathName())); CloseDB(); } } //namespace rocksdb int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } <commit_msg>db/deletefile_test.cc: remove unused variable<commit_after>// Copyright (c) 2013, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "rocksdb/db.h" #include "db/db_impl.h" #include "db/filename.h" #include "db/version_set.h" #include "db/write_batch_internal.h" #include "util/testharness.h" #include "util/testutil.h" #include "rocksdb/env.h" #include "rocksdb/transaction_log.h" #include <vector> #include <stdlib.h> #include <map> #include <string> namespace rocksdb { class DeleteFileTest { public: std::string dbname_; Options options_; DB* db_; Env* env_; int numlevels_; DeleteFileTest() { db_ = nullptr; env_ = Env::Default(); options_.max_background_flushes = 0; options_.write_buffer_size = 1024*1024*1000; options_.target_file_size_base = 1024*1024*1000; options_.max_bytes_for_level_base = 1024*1024*1000; options_.WAL_ttl_seconds = 300; // Used to test log files options_.WAL_size_limit_MB = 1024; // Used to test log files dbname_ = test::TmpDir() + "/deletefile_test"; options_.wal_dir = dbname_ + "/wal_files"; // clean up all the files that might have been there before std::vector<std::string> old_files; env_->GetChildren(dbname_, &old_files); for (auto file : old_files) { env_->DeleteFile(dbname_ + "/" + file); } env_->GetChildren(options_.wal_dir, &old_files); for (auto file : old_files) { env_->DeleteFile(options_.wal_dir + "/" + file); } DestroyDB(dbname_, options_); numlevels_ = 7; ASSERT_OK(ReopenDB(true)); } Status ReopenDB(bool create) { delete db_; if (create) { DestroyDB(dbname_, options_); } db_ = nullptr; options_.create_if_missing = create; return DB::Open(options_, dbname_, &db_); } void CloseDB() { delete db_; } void AddKeys(int numkeys, int startkey = 0) { WriteOptions options; options.sync = false; ReadOptions roptions; for (int i = startkey; i < (numkeys + startkey) ; i++) { std::string temp = std::to_string(i); Slice key(temp); Slice value(temp); ASSERT_OK(db_->Put(options, key, value)); } } int numKeysInLevels( std::vector<LiveFileMetaData> &metadata, std::vector<int> *keysperlevel = nullptr) { if (keysperlevel != nullptr) { keysperlevel->resize(numlevels_); } int numKeys = 0; for (size_t i = 0; i < metadata.size(); i++) { int startkey = atoi(metadata[i].smallestkey.c_str()); int endkey = atoi(metadata[i].largestkey.c_str()); int numkeysinfile = (endkey - startkey + 1); numKeys += numkeysinfile; if (keysperlevel != nullptr) { (*keysperlevel)[(int)metadata[i].level] += numkeysinfile; } fprintf(stderr, "level %d name %s smallest %s largest %s\n", metadata[i].level, metadata[i].name.c_str(), metadata[i].smallestkey.c_str(), metadata[i].largestkey.c_str()); } return numKeys; } void CreateTwoLevels() { AddKeys(50000, 10000); DBImpl* dbi = reinterpret_cast<DBImpl*>(db_); ASSERT_OK(dbi->TEST_FlushMemTable()); ASSERT_OK(dbi->TEST_WaitForFlushMemTable()); AddKeys(50000, 10000); ASSERT_OK(dbi->TEST_FlushMemTable()); ASSERT_OK(dbi->TEST_WaitForFlushMemTable()); } void CheckFileTypeCounts(std::string& dir, int required_log, int required_sst, int required_manifest) { std::vector<std::string> filenames; env_->GetChildren(dir, &filenames); int log_cnt = 0, sst_cnt = 0, manifest_cnt = 0; for (auto file : filenames) { uint64_t number; FileType type; if (ParseFileName(file, &number, &type)) { log_cnt += (type == kLogFile); sst_cnt += (type == kTableFile); manifest_cnt += (type == kDescriptorFile); } } ASSERT_EQ(required_log, log_cnt); ASSERT_EQ(required_sst, sst_cnt); ASSERT_EQ(required_manifest, manifest_cnt); } }; TEST(DeleteFileTest, AddKeysAndQueryLevels) { CreateTwoLevels(); std::vector<LiveFileMetaData> metadata; db_->GetLiveFilesMetaData(&metadata); std::string level1file = ""; int level1keycount = 0; std::string level2file = ""; int level2keycount = 0; int level1index = 0; int level2index = 1; ASSERT_EQ((int)metadata.size(), 2); if (metadata[0].level == 2) { level1index = 1; level2index = 0; } level1file = metadata[level1index].name; int startkey = atoi(metadata[level1index].smallestkey.c_str()); int endkey = atoi(metadata[level1index].largestkey.c_str()); level1keycount = (endkey - startkey + 1); level2file = metadata[level2index].name; startkey = atoi(metadata[level2index].smallestkey.c_str()); endkey = atoi(metadata[level2index].largestkey.c_str()); level2keycount = (endkey - startkey + 1); // COntrolled setup. Levels 1 and 2 should both have 50K files. // This is a little fragile as it depends on the current // compaction heuristics. ASSERT_EQ(level1keycount, 50000); ASSERT_EQ(level2keycount, 50000); Status status = db_->DeleteFile("0.sst"); ASSERT_TRUE(status.IsInvalidArgument()); // intermediate level files cannot be deleted. status = db_->DeleteFile(level1file); ASSERT_TRUE(status.IsInvalidArgument()); // Lowest level file deletion should succeed. ASSERT_OK(db_->DeleteFile(level2file)); CloseDB(); } TEST(DeleteFileTest, PurgeObsoleteFilesTest) { CreateTwoLevels(); // there should be only one (empty) log file because CreateTwoLevels() // flushes the memtables to disk CheckFileTypeCounts(options_.wal_dir, 1, 0, 0); // 2 ssts, 1 manifest CheckFileTypeCounts(dbname_, 0, 2, 1); std::string first("0"), last("999999"); Slice first_slice(first), last_slice(last); db_->CompactRange(&first_slice, &last_slice, true, 2); // 1 sst after compaction CheckFileTypeCounts(dbname_, 0, 1, 1); // this time, we keep an iterator alive ReopenDB(true); Iterator *itr = 0; CreateTwoLevels(); itr = db_->NewIterator(ReadOptions()); db_->CompactRange(&first_slice, &last_slice, true, 2); // 3 sst after compaction with live iterator CheckFileTypeCounts(dbname_, 0, 3, 1); delete itr; // 1 sst after iterator deletion CheckFileTypeCounts(dbname_, 0, 1, 1); CloseDB(); } TEST(DeleteFileTest, DeleteFileWithIterator) { CreateTwoLevels(); ReadOptions options; Iterator* it = db_->NewIterator(options); std::vector<LiveFileMetaData> metadata; db_->GetLiveFilesMetaData(&metadata); std::string level2file = ""; ASSERT_EQ((int)metadata.size(), 2); if (metadata[0].level == 1) { level2file = metadata[1].name; } else { level2file = metadata[0].name; } Status status = db_->DeleteFile(level2file); fprintf(stdout, "Deletion status %s: %s\n", level2file.c_str(), status.ToString().c_str()); ASSERT_TRUE(status.ok()); it->SeekToFirst(); int numKeysIterated = 0; while(it->Valid()) { numKeysIterated++; it->Next(); } ASSERT_EQ(numKeysIterated, 50000); delete it; CloseDB(); } TEST(DeleteFileTest, DeleteLogFiles) { AddKeys(10, 0); VectorLogPtr logfiles; db_->GetSortedWalFiles(logfiles); ASSERT_GT(logfiles.size(), 0UL); // Take the last log file which is expected to be alive and try to delete it // Should not succeed because live logs are not allowed to be deleted std::unique_ptr<LogFile> alive_log = std::move(logfiles.back()); ASSERT_EQ(alive_log->Type(), kAliveLogFile); ASSERT_TRUE(env_->FileExists(options_.wal_dir + "/" + alive_log->PathName())); fprintf(stdout, "Deleting alive log file %s\n", alive_log->PathName().c_str()); ASSERT_TRUE(!db_->DeleteFile(alive_log->PathName()).ok()); ASSERT_TRUE(env_->FileExists(options_.wal_dir + "/" + alive_log->PathName())); logfiles.clear(); // Call Flush to bring about a new working log file and add more keys // Call Flush again to flush out memtable and move alive log to archived log // and try to delete the archived log file FlushOptions fopts; db_->Flush(fopts); AddKeys(10, 0); db_->Flush(fopts); db_->GetSortedWalFiles(logfiles); ASSERT_GT(logfiles.size(), 0UL); std::unique_ptr<LogFile> archived_log = std::move(logfiles.front()); ASSERT_EQ(archived_log->Type(), kArchivedLogFile); ASSERT_TRUE(env_->FileExists(options_.wal_dir + "/" + archived_log->PathName())); fprintf(stdout, "Deleting archived log file %s\n", archived_log->PathName().c_str()); ASSERT_OK(db_->DeleteFile(archived_log->PathName())); ASSERT_TRUE(!env_->FileExists(options_.wal_dir + "/" + archived_log->PathName())); CloseDB(); } } //namespace rocksdb int main(int argc, char** argv) { return rocksdb::test::RunAllTests(); } <|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 "chrome/browser/tab_contents/blocked_infobar_delegate.h" #include "base/metrics/histogram.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/render_messages.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { enum BlockedInfoBarEvent { BLOCKED_INFOBAR_EVENT_SHOWN = 0, // Infobar was added to the tab. BLOCKED_INFOBAR_EVENT_ALLOWED, // User clicked allowed anyay button. BLOCKED_INFOBAR_EVENT_CANCELLED, // Reserved (if future cancel button). BLOCKED_INFOBAR_EVENT_DISMISSED, // User clicked "x" to dismiss bar. BLOCKED_INFOBAR_EVENT_LAST // First unused value. }; const char kDisplayingLearnMoreURL[] = "https://www.google.com/support/chrome/bin/answer.py?answer=1342710"; const char kRunningLearnMoreURL[] = "https://www.google.com/support/chrome/bin/answer.py?answer=1342714"; } // namespace BlockedInfoBarDelegate::BlockedInfoBarDelegate(TabContentsWrapper* wrapper, int message_resource_id, int button_resource_id, const GURL& url) : ConfirmInfoBarDelegate(wrapper->tab_contents()), wrapper_(wrapper), message_resource_id_(message_resource_id), button_resource_id_(button_resource_id), url_(url) { } BlockedInfoBarDelegate* BlockedInfoBarDelegate::AsBlockedInfoBarDelegate() { return this; } string16 BlockedInfoBarDelegate::GetMessageText() const { return l10n_util::GetStringUTF16(message_resource_id_); } int BlockedInfoBarDelegate::GetButtons() const { return BUTTON_OK | BUTTON_CANCEL; } string16 BlockedInfoBarDelegate::GetButtonLabel(InfoBarButton button) const { if (button == BUTTON_CANCEL) return l10n_util::GetStringUTF16(IDS_OK); DCHECK_EQ(button, BUTTON_OK); return l10n_util::GetStringUTF16(button_resource_id_); }; string16 BlockedInfoBarDelegate::GetLinkText() { return l10n_util::GetStringUTF16(IDS_LEARN_MORE); } bool BlockedInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) { TabContents* contents = wrapper_->tab_contents(); contents->OpenURL(url_, GURL(), disposition, PageTransition::LINK); return false; } BlockedRunningInfoBarDelegate* BlockedInfoBarDelegate::AsBlockedRunningInfoBarDelegate() { return NULL; } BlockedDisplayingInfoBarDelegate::BlockedDisplayingInfoBarDelegate( TabContentsWrapper* wrapper) : BlockedInfoBarDelegate( wrapper, IDS_BLOCKED_DISPLAYING_INSECURE_CONTENT, IDS_ALLOW_INSECURE_CONTENT_BUTTON, GURL(kDisplayingLearnMoreURL)) { UMA_HISTOGRAM_ENUMERATION("MixedContent.DisplayingInfoBar", BLOCKED_INFOBAR_EVENT_SHOWN, BLOCKED_INFOBAR_EVENT_LAST); } void BlockedDisplayingInfoBarDelegate::InfoBarDismissed() { UMA_HISTOGRAM_ENUMERATION("MixedContent.DisplayingInfoBar", BLOCKED_INFOBAR_EVENT_DISMISSED, BLOCKED_INFOBAR_EVENT_LAST); InfoBarDelegate::InfoBarDismissed(); } bool BlockedDisplayingInfoBarDelegate::Accept() { UMA_HISTOGRAM_ENUMERATION("MixedContent.DisplayingInfoBar", BLOCKED_INFOBAR_EVENT_ALLOWED, BLOCKED_INFOBAR_EVENT_LAST); wrapper()->Send(new ViewMsg_SetAllowDisplayingInsecureContent( wrapper()->routing_id(), true)); return true; } bool BlockedDisplayingInfoBarDelegate::Cancel() { UMA_HISTOGRAM_ENUMERATION("MixedContent.DisplayingInfoBar", BLOCKED_INFOBAR_EVENT_CANCELLED, BLOCKED_INFOBAR_EVENT_LAST); return true; } BlockedRunningInfoBarDelegate::BlockedRunningInfoBarDelegate( TabContentsWrapper* wrapper) : BlockedInfoBarDelegate( wrapper, IDS_BLOCKED_RUNNING_INSECURE_CONTENT, IDS_ALLOW_INSECURE_CONTENT_BUTTON, GURL(kRunningLearnMoreURL)) { UMA_HISTOGRAM_ENUMERATION("MixedContent.RunningInfoBar", BLOCKED_INFOBAR_EVENT_SHOWN, BLOCKED_INFOBAR_EVENT_LAST); } BlockedRunningInfoBarDelegate* BlockedRunningInfoBarDelegate::AsBlockedRunningInfoBarDelegate() { return this; } void BlockedRunningInfoBarDelegate::InfoBarDismissed() { UMA_HISTOGRAM_ENUMERATION("MixedContent.RunningInfoBar", BLOCKED_INFOBAR_EVENT_DISMISSED, BLOCKED_INFOBAR_EVENT_LAST); InfoBarDelegate::InfoBarDismissed(); } bool BlockedRunningInfoBarDelegate::Accept() { UMA_HISTOGRAM_ENUMERATION("MixedContent.RunningInfoBar", BLOCKED_INFOBAR_EVENT_ALLOWED, BLOCKED_INFOBAR_EVENT_LAST); wrapper()->Send(new ViewMsg_SetAllowRunningInsecureContent( wrapper()->routing_id(), true)); return true; } bool BlockedRunningInfoBarDelegate::Cancel() { UMA_HISTOGRAM_ENUMERATION("MixedContent.RunningInfoBar", BLOCKED_INFOBAR_EVENT_CANCELLED, BLOCKED_INFOBAR_EVENT_LAST); return true; } <commit_msg>Reverse the OK / Allow Anyways buttons to make them occur in the order we want on windows and opposite the order we want on linux, rather than the other way arond, since windows and linux don't show them in the same order. Show learn more link in a new FG tab rather than the current one. Review URL: http://codereview.chromium.org/7219011<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 "chrome/browser/tab_contents/blocked_infobar_delegate.h" #include "base/metrics/histogram.h" #include "chrome/browser/prefs/pref_service.h" #include "chrome/browser/profiles/profile.h" #include "chrome/common/render_messages.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" namespace { enum BlockedInfoBarEvent { BLOCKED_INFOBAR_EVENT_SHOWN = 0, // Infobar was added to the tab. BLOCKED_INFOBAR_EVENT_ALLOWED, // User clicked allowed anyay button. BLOCKED_INFOBAR_EVENT_CANCELLED, // Reserved (if future cancel button). BLOCKED_INFOBAR_EVENT_DISMISSED, // User clicked "x" to dismiss bar. BLOCKED_INFOBAR_EVENT_LAST // First unused value. }; const char kDisplayingLearnMoreURL[] = "https://www.google.com/support/chrome/bin/answer.py?answer=1342710"; const char kRunningLearnMoreURL[] = "https://www.google.com/support/chrome/bin/answer.py?answer=1342714"; } // namespace BlockedInfoBarDelegate::BlockedInfoBarDelegate(TabContentsWrapper* wrapper, int message_resource_id, int button_resource_id, const GURL& url) : ConfirmInfoBarDelegate(wrapper->tab_contents()), wrapper_(wrapper), message_resource_id_(message_resource_id), button_resource_id_(button_resource_id), url_(url) { } BlockedInfoBarDelegate* BlockedInfoBarDelegate::AsBlockedInfoBarDelegate() { return this; } string16 BlockedInfoBarDelegate::GetMessageText() const { return l10n_util::GetStringUTF16(message_resource_id_); } int BlockedInfoBarDelegate::GetButtons() const { return BUTTON_OK | BUTTON_CANCEL; } string16 BlockedInfoBarDelegate::GetButtonLabel(InfoBarButton button) const { return l10n_util::GetStringUTF16( button == BUTTON_OK ? IDS_OK : button_resource_id_); }; string16 BlockedInfoBarDelegate::GetLinkText() { return l10n_util::GetStringUTF16(IDS_LEARN_MORE); } bool BlockedInfoBarDelegate::LinkClicked(WindowOpenDisposition disposition) { TabContents* contents = wrapper_->tab_contents(); if (disposition == CURRENT_TAB) disposition = NEW_FOREGROUND_TAB; contents->OpenURL(url_, GURL(), disposition, PageTransition::LINK); return false; } BlockedRunningInfoBarDelegate* BlockedInfoBarDelegate::AsBlockedRunningInfoBarDelegate() { return NULL; } BlockedDisplayingInfoBarDelegate::BlockedDisplayingInfoBarDelegate( TabContentsWrapper* wrapper) : BlockedInfoBarDelegate( wrapper, IDS_BLOCKED_DISPLAYING_INSECURE_CONTENT, IDS_ALLOW_INSECURE_CONTENT_BUTTON, GURL(kDisplayingLearnMoreURL)) { UMA_HISTOGRAM_ENUMERATION("MixedContent.DisplayingInfoBar", BLOCKED_INFOBAR_EVENT_SHOWN, BLOCKED_INFOBAR_EVENT_LAST); } void BlockedDisplayingInfoBarDelegate::InfoBarDismissed() { UMA_HISTOGRAM_ENUMERATION("MixedContent.DisplayingInfoBar", BLOCKED_INFOBAR_EVENT_DISMISSED, BLOCKED_INFOBAR_EVENT_LAST); InfoBarDelegate::InfoBarDismissed(); } bool BlockedDisplayingInfoBarDelegate::Accept() { UMA_HISTOGRAM_ENUMERATION("MixedContent.DisplayingInfoBar", BLOCKED_INFOBAR_EVENT_CANCELLED, BLOCKED_INFOBAR_EVENT_LAST); return true; } bool BlockedDisplayingInfoBarDelegate::Cancel() { UMA_HISTOGRAM_ENUMERATION("MixedContent.DisplayingInfoBar", BLOCKED_INFOBAR_EVENT_ALLOWED, BLOCKED_INFOBAR_EVENT_LAST); wrapper()->Send(new ViewMsg_SetAllowDisplayingInsecureContent( wrapper()->routing_id(), true)); return true; } BlockedRunningInfoBarDelegate::BlockedRunningInfoBarDelegate( TabContentsWrapper* wrapper) : BlockedInfoBarDelegate( wrapper, IDS_BLOCKED_RUNNING_INSECURE_CONTENT, IDS_ALLOW_INSECURE_CONTENT_BUTTON, GURL(kRunningLearnMoreURL)) { UMA_HISTOGRAM_ENUMERATION("MixedContent.RunningInfoBar", BLOCKED_INFOBAR_EVENT_SHOWN, BLOCKED_INFOBAR_EVENT_LAST); } BlockedRunningInfoBarDelegate* BlockedRunningInfoBarDelegate::AsBlockedRunningInfoBarDelegate() { return this; } void BlockedRunningInfoBarDelegate::InfoBarDismissed() { UMA_HISTOGRAM_ENUMERATION("MixedContent.RunningInfoBar", BLOCKED_INFOBAR_EVENT_DISMISSED, BLOCKED_INFOBAR_EVENT_LAST); InfoBarDelegate::InfoBarDismissed(); } bool BlockedRunningInfoBarDelegate::Accept() { UMA_HISTOGRAM_ENUMERATION("MixedContent.RunningInfoBar", BLOCKED_INFOBAR_EVENT_CANCELLED, BLOCKED_INFOBAR_EVENT_LAST); return true; } bool BlockedRunningInfoBarDelegate::Cancel() { UMA_HISTOGRAM_ENUMERATION("MixedContent.RunningInfoBar", BLOCKED_INFOBAR_EVENT_ALLOWED, BLOCKED_INFOBAR_EVENT_LAST); wrapper()->Send(new ViewMsg_SetAllowRunningInsecureContent( wrapper()->routing_id(), true)); return true; } <|endoftext|>
<commit_before>// 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/browser/task_manager/task_manager.h" #include "app/l10n_util.h" #include "base/file_path.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_navigator.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/crashed_extension_infobar.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/notification_test_util.h" #include "chrome/browser/notifications/notification_ui_manager.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/page_transition_types.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "grit/generated_resources.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html"); class ResourceChangeObserver : public TaskManagerModelObserver { public: ResourceChangeObserver(const TaskManagerModel* model, int target_resource_count) : model_(model), target_resource_count_(target_resource_count) { } virtual void OnModelChanged() { OnResourceChange(); } virtual void OnItemsChanged(int start, int length) { OnResourceChange(); } virtual void OnItemsAdded(int start, int length) { OnResourceChange(); } virtual void OnItemsRemoved(int start, int length) { OnResourceChange(); } private: void OnResourceChange() { if (model_->ResourceCount() == target_resource_count_) MessageLoopForUI::current()->Quit(); } const TaskManagerModel* model_; const int target_resource_count_; }; } // namespace class TaskManagerBrowserTest : public ExtensionBrowserTest { public: TaskManagerModel* model() const { return TaskManager::GetInstance()->model(); } void WaitForResourceChange(int target_count) { if (model()->ResourceCount() == target_count) return; ResourceChangeObserver observer(model(), target_count); model()->AddObserver(&observer); ui_test_utils::RunMessageLoop(); model()->RemoveObserver(&observer); } }; // Crashes on Vista (dbg): http://crbug.com/44991 #if defined(OS_WIN) #define ShutdownWhileOpen DISABLED_ShutdownWhileOpen #endif // Regression test for http://crbug.com/13361 IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) { browser()->window()->ShowTaskManager(); } // Times out on Vista; disabled to keep tests fast. http://crbug.com/44991 #if defined(OS_WIN) #define NoticeTabContentsChanges DISABLED_NoticeTabContentsChanges #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) { EXPECT_EQ(0, model()->ResourceCount()); // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); // Browser and the New Tab Page. EXPECT_EQ(2, model()->ResourceCount()); // Open a new tab and make sure we notice that. GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle1File))); AddTabAtIndex(0, url, PageTransition::TYPED); WaitForResourceChange(3); // Close the tab and verify that we notice. TabContents* first_tab = browser()->GetTabContentsAt(0); ASSERT_TRUE(first_tab); browser()->CloseTabContents(first_tab); WaitForResourceChange(2); } #if defined(OS_WIN) // http://crbug.com/31663 #define MAYBE_NoticeExtensionChanges DISABLED_NoticeExtensionChanges #else // Flaky test bug filed in http://crbug.com/51701 #define MAYBE_NoticeExtensionChanges FLAKY_NoticeExtensionChanges #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, MAYBE_NoticeExtensionChanges) { EXPECT_EQ(0, model()->ResourceCount()); // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); // Browser and the New Tab Page. EXPECT_EQ(2, model()->ResourceCount()); // Loading an extension with a background page should result in a new // resource being created for it. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("common").AppendASCII("background_page"))); WaitForResourceChange(3); } IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeNotificationChanges) { EXPECT_EQ(0, model()->ResourceCount()); // Show the task manager. browser()->window()->ShowTaskManager(); // Expect to see the browser and the New Tab Page renderer. EXPECT_EQ(2, model()->ResourceCount()); // Show a notification. NotificationUIManager* notifications = g_browser_process->notification_ui_manager(); string16 content = DesktopNotificationService::CreateDataUrl( GURL(), ASCIIToUTF16("Hello World!"), string16(), WebKit::WebTextDirectionDefault); scoped_refptr<NotificationDelegate> del1(new MockNotificationDelegate("n1")); Notification n1( GURL(), GURL(content), ASCIIToUTF16("Test 1"), string16(), del1.get()); scoped_refptr<NotificationDelegate> del2(new MockNotificationDelegate("n2")); Notification n2( GURL(), GURL(content), ASCIIToUTF16("Test 2"), string16(), del2.get()); notifications->Add(n1, browser()->profile()); WaitForResourceChange(3); notifications->Add(n2, browser()->profile()); WaitForResourceChange(4); notifications->Cancel(n1); WaitForResourceChange(3); notifications->Cancel(n2); WaitForResourceChange(2); } // Times out on Vista; disabled to keep tests fast. http://crbug.com/44991 #if defined(OS_WIN) #define KillExtension DISABLED_KillExtension #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) { // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("common").AppendASCII("background_page"))); // Wait until we see the loaded extension in the task manager (the three // resources are: the browser process, New Tab Page, and the extension). WaitForResourceChange(3); EXPECT_TRUE(model()->GetResourceExtension(0) == NULL); EXPECT_TRUE(model()->GetResourceExtension(1) == NULL); ASSERT_TRUE(model()->GetResourceExtension(2) != NULL); // Kill the extension process and make sure we notice it. TaskManager::GetInstance()->KillProcess(2); WaitForResourceChange(2); } // Times out on Vista; disabled to keep tests fast. http://crbug.com/44991 #if defined(OS_WIN) #define KillExtensionAndReload DISABLED_KillExtensionAndReload #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) { // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("common").AppendASCII("background_page"))); // Wait until we see the loaded extension in the task manager (the three // resources are: the browser process, New Tab Page, and the extension). WaitForResourceChange(3); EXPECT_TRUE(model()->GetResourceExtension(0) == NULL); EXPECT_TRUE(model()->GetResourceExtension(1) == NULL); ASSERT_TRUE(model()->GetResourceExtension(2) != NULL); // Kill the extension process and make sure we notice it. TaskManager::GetInstance()->KillProcess(2); WaitForResourceChange(2); // Reload the extension using the "crashed extension" infobar while the task // manager is still visible. Make sure we don't crash and the extension // gets reloaded and noticed in the task manager. TabContents* current_tab = browser()->GetSelectedTabContents(); ASSERT_EQ(1, current_tab->infobar_delegate_count()); InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0); CrashedExtensionInfoBarDelegate* crashed_delegate = delegate->AsCrashedExtensionInfoBarDelegate(); ASSERT_TRUE(crashed_delegate); crashed_delegate->Accept(); WaitForResourceChange(3); } // Regression test for http://crbug.com/18693. // Crashy, http://crbug.com/42315. IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, DISABLED_ReloadExtension) { // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("common").AppendASCII("background_page"))); // Wait until we see the loaded extension in the task manager (the three // resources are: the browser process, New Tab Page, and the extension). WaitForResourceChange(3); EXPECT_TRUE(model()->GetResourceExtension(0) == NULL); EXPECT_TRUE(model()->GetResourceExtension(1) == NULL); ASSERT_TRUE(model()->GetResourceExtension(2) != NULL); const Extension* extension = model()->GetResourceExtension(2); // Reload the extension a few times and make sure our resource count // doesn't increase. ReloadExtension(extension->id()); WaitForResourceChange(3); extension = model()->GetResourceExtension(2); ReloadExtension(extension->id()); WaitForResourceChange(3); extension = model()->GetResourceExtension(2); ReloadExtension(extension->id()); WaitForResourceChange(3); } // Crashy, http://crbug.com/42301. IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, DISABLED_PopulateWebCacheFields) { EXPECT_EQ(0, model()->ResourceCount()); // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); // Browser and the New Tab Page. EXPECT_EQ(2, model()->ResourceCount()); // Open a new tab and make sure we notice that. GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle1File))); AddTabAtIndex(0, url, PageTransition::TYPED); WaitForResourceChange(3); // Check that we get some value for the cache columns. DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2), l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT)); DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2), l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT)); DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2), l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT)); } <commit_msg>Mark TaskManagerBrowserTest.NoticeNotificationChanges flaky.<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/browser/task_manager/task_manager.h" #include "app/l10n_util.h" #include "base/file_path.h" #include "base/utf_string_conversions.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_navigator.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/extensions/crashed_extension_infobar.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/notifications/desktop_notification_service.h" #include "chrome/browser/notifications/notification_test_util.h" #include "chrome/browser/notifications/notification_ui_manager.h" #include "chrome/browser/tab_contents/infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/page_transition_types.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "grit/generated_resources.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL("title1.html"); class ResourceChangeObserver : public TaskManagerModelObserver { public: ResourceChangeObserver(const TaskManagerModel* model, int target_resource_count) : model_(model), target_resource_count_(target_resource_count) { } virtual void OnModelChanged() { OnResourceChange(); } virtual void OnItemsChanged(int start, int length) { OnResourceChange(); } virtual void OnItemsAdded(int start, int length) { OnResourceChange(); } virtual void OnItemsRemoved(int start, int length) { OnResourceChange(); } private: void OnResourceChange() { if (model_->ResourceCount() == target_resource_count_) MessageLoopForUI::current()->Quit(); } const TaskManagerModel* model_; const int target_resource_count_; }; } // namespace class TaskManagerBrowserTest : public ExtensionBrowserTest { public: TaskManagerModel* model() const { return TaskManager::GetInstance()->model(); } void WaitForResourceChange(int target_count) { if (model()->ResourceCount() == target_count) return; ResourceChangeObserver observer(model(), target_count); model()->AddObserver(&observer); ui_test_utils::RunMessageLoop(); model()->RemoveObserver(&observer); } }; // Crashes on Vista (dbg): http://crbug.com/44991 #if defined(OS_WIN) #define ShutdownWhileOpen DISABLED_ShutdownWhileOpen #endif // Regression test for http://crbug.com/13361 IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, ShutdownWhileOpen) { browser()->window()->ShowTaskManager(); } // Times out on Vista; disabled to keep tests fast. http://crbug.com/44991 #if defined(OS_WIN) #define NoticeTabContentsChanges DISABLED_NoticeTabContentsChanges #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeTabContentsChanges) { EXPECT_EQ(0, model()->ResourceCount()); // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); // Browser and the New Tab Page. EXPECT_EQ(2, model()->ResourceCount()); // Open a new tab and make sure we notice that. GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle1File))); AddTabAtIndex(0, url, PageTransition::TYPED); WaitForResourceChange(3); // Close the tab and verify that we notice. TabContents* first_tab = browser()->GetTabContentsAt(0); ASSERT_TRUE(first_tab); browser()->CloseTabContents(first_tab); WaitForResourceChange(2); } #if defined(OS_WIN) // http://crbug.com/31663 #define MAYBE_NoticeExtensionChanges DISABLED_NoticeExtensionChanges #else // Flaky test bug filed in http://crbug.com/51701 #define MAYBE_NoticeExtensionChanges FLAKY_NoticeExtensionChanges #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, MAYBE_NoticeExtensionChanges) { EXPECT_EQ(0, model()->ResourceCount()); // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); // Browser and the New Tab Page. EXPECT_EQ(2, model()->ResourceCount()); // Loading an extension with a background page should result in a new // resource being created for it. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("common").AppendASCII("background_page"))); WaitForResourceChange(3); } // Fails on win when storage for props get exhausted. http://crbug.com/44991 #if defined(OS_WIN) #define NoticeNotificationChanges FLAKY_NoticeNotificationChanges #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, NoticeNotificationChanges) { EXPECT_EQ(0, model()->ResourceCount()); // Show the task manager. browser()->window()->ShowTaskManager(); // Expect to see the browser and the New Tab Page renderer. EXPECT_EQ(2, model()->ResourceCount()); // Show a notification. NotificationUIManager* notifications = g_browser_process->notification_ui_manager(); string16 content = DesktopNotificationService::CreateDataUrl( GURL(), ASCIIToUTF16("Hello World!"), string16(), WebKit::WebTextDirectionDefault); scoped_refptr<NotificationDelegate> del1(new MockNotificationDelegate("n1")); Notification n1( GURL(), GURL(content), ASCIIToUTF16("Test 1"), string16(), del1.get()); scoped_refptr<NotificationDelegate> del2(new MockNotificationDelegate("n2")); Notification n2( GURL(), GURL(content), ASCIIToUTF16("Test 2"), string16(), del2.get()); notifications->Add(n1, browser()->profile()); WaitForResourceChange(3); notifications->Add(n2, browser()->profile()); WaitForResourceChange(4); notifications->Cancel(n1); WaitForResourceChange(3); notifications->Cancel(n2); WaitForResourceChange(2); } // Times out on Vista; disabled to keep tests fast. http://crbug.com/44991 #if defined(OS_WIN) #define KillExtension DISABLED_KillExtension #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtension) { // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("common").AppendASCII("background_page"))); // Wait until we see the loaded extension in the task manager (the three // resources are: the browser process, New Tab Page, and the extension). WaitForResourceChange(3); EXPECT_TRUE(model()->GetResourceExtension(0) == NULL); EXPECT_TRUE(model()->GetResourceExtension(1) == NULL); ASSERT_TRUE(model()->GetResourceExtension(2) != NULL); // Kill the extension process and make sure we notice it. TaskManager::GetInstance()->KillProcess(2); WaitForResourceChange(2); } // Times out on Vista; disabled to keep tests fast. http://crbug.com/44991 #if defined(OS_WIN) #define KillExtensionAndReload DISABLED_KillExtensionAndReload #endif IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, KillExtensionAndReload) { // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("common").AppendASCII("background_page"))); // Wait until we see the loaded extension in the task manager (the three // resources are: the browser process, New Tab Page, and the extension). WaitForResourceChange(3); EXPECT_TRUE(model()->GetResourceExtension(0) == NULL); EXPECT_TRUE(model()->GetResourceExtension(1) == NULL); ASSERT_TRUE(model()->GetResourceExtension(2) != NULL); // Kill the extension process and make sure we notice it. TaskManager::GetInstance()->KillProcess(2); WaitForResourceChange(2); // Reload the extension using the "crashed extension" infobar while the task // manager is still visible. Make sure we don't crash and the extension // gets reloaded and noticed in the task manager. TabContents* current_tab = browser()->GetSelectedTabContents(); ASSERT_EQ(1, current_tab->infobar_delegate_count()); InfoBarDelegate* delegate = current_tab->GetInfoBarDelegateAt(0); CrashedExtensionInfoBarDelegate* crashed_delegate = delegate->AsCrashedExtensionInfoBarDelegate(); ASSERT_TRUE(crashed_delegate); crashed_delegate->Accept(); WaitForResourceChange(3); } // Regression test for http://crbug.com/18693. // Crashy, http://crbug.com/42315. IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, DISABLED_ReloadExtension) { // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("common").AppendASCII("background_page"))); // Wait until we see the loaded extension in the task manager (the three // resources are: the browser process, New Tab Page, and the extension). WaitForResourceChange(3); EXPECT_TRUE(model()->GetResourceExtension(0) == NULL); EXPECT_TRUE(model()->GetResourceExtension(1) == NULL); ASSERT_TRUE(model()->GetResourceExtension(2) != NULL); const Extension* extension = model()->GetResourceExtension(2); // Reload the extension a few times and make sure our resource count // doesn't increase. ReloadExtension(extension->id()); WaitForResourceChange(3); extension = model()->GetResourceExtension(2); ReloadExtension(extension->id()); WaitForResourceChange(3); extension = model()->GetResourceExtension(2); ReloadExtension(extension->id()); WaitForResourceChange(3); } // Crashy, http://crbug.com/42301. IN_PROC_BROWSER_TEST_F(TaskManagerBrowserTest, DISABLED_PopulateWebCacheFields) { EXPECT_EQ(0, model()->ResourceCount()); // Show the task manager. This populates the model, and helps with debugging // (you see the task manager). browser()->window()->ShowTaskManager(); // Browser and the New Tab Page. EXPECT_EQ(2, model()->ResourceCount()); // Open a new tab and make sure we notice that. GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory), FilePath(kTitle1File))); AddTabAtIndex(0, url, PageTransition::TYPED); WaitForResourceChange(3); // Check that we get some value for the cache columns. DCHECK_NE(model()->GetResourceWebCoreImageCacheSize(2), l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT)); DCHECK_NE(model()->GetResourceWebCoreScriptsCacheSize(2), l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT)); DCHECK_NE(model()->GetResourceWebCoreCSSCacheSize(2), l10n_util::GetStringUTF16(IDS_TASK_MANAGER_NA_CELL_TEXT)); } <|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 "chrome/test/ui/ui_test.h" #include "base/file_path.h" #include "base/memory/singleton.h" #include "base/message_loop.h" #include "chrome/browser/ui/views/html_dialog_view.h" #include "chrome/browser/ui/webui/html_dialog_ui.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/renderer_host/render_widget_host_view.h" #include "content/browser/tab_contents/tab_contents.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "views/widget/widget.h" using testing::Eq; namespace { // Window non-client-area means that the minimum size for the window // won't be the actual minimum size - our layout and resizing code // makes sure the chrome is always visible. const int kMinimumWidthToTestFor = 20; const int kMinimumHeightToTestFor = 30; class TestHtmlDialogUIDelegate : public HtmlDialogUIDelegate { public: TestHtmlDialogUIDelegate() {} virtual ~TestHtmlDialogUIDelegate() {} // HTMLDialogUIDelegate implementation: virtual bool IsDialogModal() const { return true; } virtual std::wstring GetDialogTitle() const { return std::wstring(L"Test"); } virtual GURL GetDialogContentURL() const { return GURL(chrome::kAboutAboutURL); } virtual void GetWebUIMessageHandlers( std::vector<WebUIMessageHandler*>* handlers) const { } virtual void GetDialogSize(gfx::Size* size) const { size->set_width(40); size->set_height(40); } virtual std::string GetDialogArgs() const { return std::string(); } virtual void OnDialogClosed(const std::string& json_retval) { } virtual void OnCloseContents(TabContents* source, bool* out_close_dialog) { if (out_close_dialog) *out_close_dialog = true; } virtual bool ShouldShowDialogTitle() const { return true; } }; } // namespace class HtmlDialogBrowserTest : public InProcessBrowserTest { public: HtmlDialogBrowserTest() {} #if defined(OS_WIN) class WindowChangedObserver : public MessageLoopForUI::Observer { public: WindowChangedObserver() {} static WindowChangedObserver* GetInstance() { return Singleton<WindowChangedObserver>::get(); } // This method is called before processing a message. virtual void WillProcessMessage(const MSG& msg) {} // This method is called after processing a message. virtual void DidProcessMessage(const MSG& msg) { // Either WM_PAINT or WM_TIMER indicates the actual work of // pushing through the window resizing messages is done since // they are lower priority (we don't get to see the // WM_WINDOWPOSCHANGED message here). if (msg.message == WM_PAINT || msg.message == WM_TIMER) MessageLoop::current()->Quit(); } }; #elif !defined(OS_MACOSX) class WindowChangedObserver : public MessageLoopForUI::Observer { public: WindowChangedObserver() {} static WindowChangedObserver* GetInstance() { return Singleton<WindowChangedObserver>::get(); } // This method is called before processing a message. virtual void WillProcessEvent(GdkEvent* event) {} // This method is called after processing a message. virtual void DidProcessEvent(GdkEvent* event) { // Quit once the GDK_CONFIGURE event has been processed - seeing // this means the window sizing request that was made actually // happened. if (event->type == GDK_CONFIGURE) MessageLoop::current()->Quit(); } }; #endif }; #if defined(OS_LINUX) && !defined(OS_CHROMEOS) #define MAYBE_SizeWindow SizeWindow #else // http://code.google.com/p/chromium/issues/detail?id=52602 // Windows has some issues resizing windows- an off by one problem, // and a minimum size that seems too big. This file isn't included in // Mac builds yet. On Chrome OS, this test doesn't apply since ChromeOS // doesn't allow resizing of windows. #define MAYBE_SizeWindow DISABLED_SizeWindow #endif IN_PROC_BROWSER_TEST_F(HtmlDialogBrowserTest, MAYBE_SizeWindow) { HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate(); HtmlDialogView* html_view = new HtmlDialogView(browser()->profile(), delegate); TabContents* tab_contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(tab_contents != NULL); views::Widget::CreateWindowWithParent(html_view, tab_contents->GetDialogRootWindow()); html_view->InitDialog(); html_view->GetWidget()->Show(); MessageLoopForUI::current()->AddObserver( WindowChangedObserver::GetInstance()); gfx::Rect bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); gfx::Rect set_bounds = bounds; gfx::Rect actual_bounds, rwhv_bounds; // Bigger than the default in both dimensions. set_bounds.set_width(400); set_bounds.set_height(300); html_view->MoveContents(tab_contents, set_bounds); ui_test_utils::RunMessageLoop(); actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); EXPECT_EQ(set_bounds, actual_bounds); rwhv_bounds = html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds(); EXPECT_LT(0, rwhv_bounds.width()); EXPECT_LT(0, rwhv_bounds.height()); EXPECT_GE(set_bounds.width(), rwhv_bounds.width()); EXPECT_GE(set_bounds.height(), rwhv_bounds.height()); // Larger in one dimension and smaller in the other. set_bounds.set_width(550); set_bounds.set_height(250); html_view->MoveContents(tab_contents, set_bounds); ui_test_utils::RunMessageLoop(); actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); EXPECT_EQ(set_bounds, actual_bounds); rwhv_bounds = html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds(); EXPECT_LT(0, rwhv_bounds.width()); EXPECT_LT(0, rwhv_bounds.height()); EXPECT_GE(set_bounds.width(), rwhv_bounds.width()); EXPECT_GE(set_bounds.height(), rwhv_bounds.height()); // Get very small. set_bounds.set_width(kMinimumWidthToTestFor); set_bounds.set_height(kMinimumHeightToTestFor); html_view->MoveContents(tab_contents, set_bounds); ui_test_utils::RunMessageLoop(); actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); EXPECT_EQ(set_bounds, actual_bounds); rwhv_bounds = html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds(); EXPECT_LT(0, rwhv_bounds.width()); EXPECT_LT(0, rwhv_bounds.height()); EXPECT_GE(set_bounds.width(), rwhv_bounds.width()); EXPECT_GE(set_bounds.height(), rwhv_bounds.height()); // Check to make sure we can't get to 0x0 set_bounds.set_width(0); set_bounds.set_height(0); html_view->MoveContents(tab_contents, set_bounds); ui_test_utils::RunMessageLoop(); actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); EXPECT_LT(0, actual_bounds.width()); EXPECT_LT(0, actual_bounds.height()); MessageLoopForUI::current()->RemoveObserver( WindowChangedObserver::GetInstance()); } IN_PROC_BROWSER_TEST_F(HtmlDialogBrowserTest, FLAKY_TestStateTransition) { HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate(); HtmlDialogView* html_view = new HtmlDialogView(browser()->profile(), delegate); TabContents* tab_contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(tab_contents != NULL); views::Widget::CreateWindowWithParent(html_view, tab_contents->GetDialogRootWindow()); // Test if the state transitions from INITIALIZED to -> PAINTED EXPECT_EQ(HtmlDialogView::INITIALIZED, html_view->state_); html_view->InitDialog(); html_view->GetWidget()->Show(); MessageLoopForUI::current()->AddObserver( WindowChangedObserver::GetInstance()); // We use busy loop because the state is updated in notifications. while (html_view->state_ != HtmlDialogView::PAINTED) MessageLoop::current()->RunAllPending(); EXPECT_EQ(HtmlDialogView::PAINTED, html_view->state_); MessageLoopForUI::current()->RemoveObserver( WindowChangedObserver::GetInstance()); } <commit_msg>Disabling HtmlDialogBrowserTest.TestStateTranstion It's timing out about 5~10%. Disabling it while i'm looking into it.<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 "chrome/test/ui/ui_test.h" #include "base/file_path.h" #include "base/memory/singleton.h" #include "base/message_loop.h" #include "chrome/browser/ui/views/html_dialog_view.h" #include "chrome/browser/ui/webui/html_dialog_ui.h" #include "chrome/common/url_constants.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "content/browser/renderer_host/render_widget_host_view.h" #include "content/browser/tab_contents/tab_contents.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "views/widget/widget.h" using testing::Eq; namespace { // Window non-client-area means that the minimum size for the window // won't be the actual minimum size - our layout and resizing code // makes sure the chrome is always visible. const int kMinimumWidthToTestFor = 20; const int kMinimumHeightToTestFor = 30; class TestHtmlDialogUIDelegate : public HtmlDialogUIDelegate { public: TestHtmlDialogUIDelegate() {} virtual ~TestHtmlDialogUIDelegate() {} // HTMLDialogUIDelegate implementation: virtual bool IsDialogModal() const { return true; } virtual std::wstring GetDialogTitle() const { return std::wstring(L"Test"); } virtual GURL GetDialogContentURL() const { return GURL(chrome::kAboutAboutURL); } virtual void GetWebUIMessageHandlers( std::vector<WebUIMessageHandler*>* handlers) const { } virtual void GetDialogSize(gfx::Size* size) const { size->set_width(40); size->set_height(40); } virtual std::string GetDialogArgs() const { return std::string(); } virtual void OnDialogClosed(const std::string& json_retval) { } virtual void OnCloseContents(TabContents* source, bool* out_close_dialog) { if (out_close_dialog) *out_close_dialog = true; } virtual bool ShouldShowDialogTitle() const { return true; } }; } // namespace class HtmlDialogBrowserTest : public InProcessBrowserTest { public: HtmlDialogBrowserTest() {} #if defined(OS_WIN) class WindowChangedObserver : public MessageLoopForUI::Observer { public: WindowChangedObserver() {} static WindowChangedObserver* GetInstance() { return Singleton<WindowChangedObserver>::get(); } // This method is called before processing a message. virtual void WillProcessMessage(const MSG& msg) {} // This method is called after processing a message. virtual void DidProcessMessage(const MSG& msg) { // Either WM_PAINT or WM_TIMER indicates the actual work of // pushing through the window resizing messages is done since // they are lower priority (we don't get to see the // WM_WINDOWPOSCHANGED message here). if (msg.message == WM_PAINT || msg.message == WM_TIMER) MessageLoop::current()->Quit(); } }; #elif !defined(OS_MACOSX) class WindowChangedObserver : public MessageLoopForUI::Observer { public: WindowChangedObserver() {} static WindowChangedObserver* GetInstance() { return Singleton<WindowChangedObserver>::get(); } // This method is called before processing a message. virtual void WillProcessEvent(GdkEvent* event) {} // This method is called after processing a message. virtual void DidProcessEvent(GdkEvent* event) { // Quit once the GDK_CONFIGURE event has been processed - seeing // this means the window sizing request that was made actually // happened. if (event->type == GDK_CONFIGURE) MessageLoop::current()->Quit(); } }; #endif }; #if defined(OS_LINUX) && !defined(OS_CHROMEOS) #define MAYBE_SizeWindow SizeWindow #else // http://code.google.com/p/chromium/issues/detail?id=52602 // Windows has some issues resizing windows- an off by one problem, // and a minimum size that seems too big. This file isn't included in // Mac builds yet. On Chrome OS, this test doesn't apply since ChromeOS // doesn't allow resizing of windows. #define MAYBE_SizeWindow DISABLED_SizeWindow #endif IN_PROC_BROWSER_TEST_F(HtmlDialogBrowserTest, MAYBE_SizeWindow) { HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate(); HtmlDialogView* html_view = new HtmlDialogView(browser()->profile(), delegate); TabContents* tab_contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(tab_contents != NULL); views::Widget::CreateWindowWithParent(html_view, tab_contents->GetDialogRootWindow()); html_view->InitDialog(); html_view->GetWidget()->Show(); MessageLoopForUI::current()->AddObserver( WindowChangedObserver::GetInstance()); gfx::Rect bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); gfx::Rect set_bounds = bounds; gfx::Rect actual_bounds, rwhv_bounds; // Bigger than the default in both dimensions. set_bounds.set_width(400); set_bounds.set_height(300); html_view->MoveContents(tab_contents, set_bounds); ui_test_utils::RunMessageLoop(); actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); EXPECT_EQ(set_bounds, actual_bounds); rwhv_bounds = html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds(); EXPECT_LT(0, rwhv_bounds.width()); EXPECT_LT(0, rwhv_bounds.height()); EXPECT_GE(set_bounds.width(), rwhv_bounds.width()); EXPECT_GE(set_bounds.height(), rwhv_bounds.height()); // Larger in one dimension and smaller in the other. set_bounds.set_width(550); set_bounds.set_height(250); html_view->MoveContents(tab_contents, set_bounds); ui_test_utils::RunMessageLoop(); actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); EXPECT_EQ(set_bounds, actual_bounds); rwhv_bounds = html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds(); EXPECT_LT(0, rwhv_bounds.width()); EXPECT_LT(0, rwhv_bounds.height()); EXPECT_GE(set_bounds.width(), rwhv_bounds.width()); EXPECT_GE(set_bounds.height(), rwhv_bounds.height()); // Get very small. set_bounds.set_width(kMinimumWidthToTestFor); set_bounds.set_height(kMinimumHeightToTestFor); html_view->MoveContents(tab_contents, set_bounds); ui_test_utils::RunMessageLoop(); actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); EXPECT_EQ(set_bounds, actual_bounds); rwhv_bounds = html_view->tab_contents()->GetRenderWidgetHostView()->GetViewBounds(); EXPECT_LT(0, rwhv_bounds.width()); EXPECT_LT(0, rwhv_bounds.height()); EXPECT_GE(set_bounds.width(), rwhv_bounds.width()); EXPECT_GE(set_bounds.height(), rwhv_bounds.height()); // Check to make sure we can't get to 0x0 set_bounds.set_width(0); set_bounds.set_height(0); html_view->MoveContents(tab_contents, set_bounds); ui_test_utils::RunMessageLoop(); actual_bounds = html_view->GetWidget()->GetClientAreaScreenBounds(); EXPECT_LT(0, actual_bounds.width()); EXPECT_LT(0, actual_bounds.height()); MessageLoopForUI::current()->RemoveObserver( WindowChangedObserver::GetInstance()); } // This is timing out about 5~10% of runs. See crbug.com/86059. IN_PROC_BROWSER_TEST_F(HtmlDialogBrowserTest, DISABLED_TestStateTransition) { HtmlDialogUIDelegate* delegate = new TestHtmlDialogUIDelegate(); HtmlDialogView* html_view = new HtmlDialogView(browser()->profile(), delegate); TabContents* tab_contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(tab_contents != NULL); views::Widget::CreateWindowWithParent(html_view, tab_contents->GetDialogRootWindow()); // Test if the state transitions from INITIALIZED to -> PAINTED EXPECT_EQ(HtmlDialogView::INITIALIZED, html_view->state_); html_view->InitDialog(); html_view->GetWidget()->Show(); MessageLoopForUI::current()->AddObserver( WindowChangedObserver::GetInstance()); // We use busy loop because the state is updated in notifications. while (html_view->state_ != HtmlDialogView::PAINTED) MessageLoop::current()->RunAllPending(); EXPECT_EQ(HtmlDialogView::PAINTED, html_view->state_); MessageLoopForUI::current()->RemoveObserver( WindowChangedObserver::GetInstance()); } <|endoftext|>
<commit_before>// 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/browser/views/content_blocked_bubble_contents.h" #if defined(OS_LINUX) #include <gdk/gdk.h> #endif #include "app/l10n_util.h" #include "chrome/browser/blocked_popup_container.h" #include "chrome/browser/content_setting_bubble_model.h" #include "chrome/browser/host_content_settings_map.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/browser_dialogs.h" #include "chrome/browser/views/info_bubble.h" #include "chrome/common/notification_source.h" #include "chrome/common/notification_type.h" #include "grit/generated_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/button/radio_button.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/controls/separator.h" #include "views/grid_layout.h" #include "views/standard_layout.h" class ContentSettingBubbleContents::Favicon : public views::ImageView { public: Favicon(const SkBitmap& image, ContentSettingBubbleContents* parent, views::Link* link); virtual ~Favicon(); private: #if defined(OS_WIN) static HCURSOR g_hand_cursor; #endif // views::View overrides: virtual bool OnMousePressed(const views::MouseEvent& event); virtual void OnMouseReleased(const views::MouseEvent& event, bool canceled); virtual gfx::NativeCursor GetCursorForPoint( views::Event::EventType event_type, const gfx::Point& p); ContentSettingBubbleContents* parent_; views::Link* link_; }; #if defined(OS_WIN) HCURSOR ContentSettingBubbleContents::Favicon::g_hand_cursor = NULL; #endif ContentSettingBubbleContents::Favicon::Favicon( const SkBitmap& image, ContentSettingBubbleContents* parent, views::Link* link) : parent_(parent), link_(link) { SetImage(image); } ContentSettingBubbleContents::Favicon::~Favicon() { } bool ContentSettingBubbleContents::Favicon::OnMousePressed( const views::MouseEvent& event) { return event.IsLeftMouseButton() || event.IsMiddleMouseButton(); } void ContentSettingBubbleContents::Favicon::OnMouseReleased( const views::MouseEvent& event, bool canceled) { if (!canceled && (event.IsLeftMouseButton() || event.IsMiddleMouseButton()) && HitTest(event.location())) parent_->LinkActivated(link_, event.GetFlags()); } gfx::NativeCursor ContentSettingBubbleContents::Favicon::GetCursorForPoint( views::Event::EventType event_type, const gfx::Point& p) { #if defined(OS_WIN) if (!g_hand_cursor) g_hand_cursor = LoadCursor(NULL, IDC_HAND); return g_hand_cursor; #elif defined(OS_LINUX) return gdk_cursor_new(GDK_HAND2); #endif } ContentSettingBubbleContents::ContentSettingBubbleContents( ContentSettingBubbleModel* content_setting_bubble_model, Profile* profile, TabContents* tab_contents) : content_setting_bubble_model_(content_setting_bubble_model), profile_(profile), tab_contents_(tab_contents), info_bubble_(NULL), close_button_(NULL), manage_link_(NULL), clear_link_(NULL) { registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(tab_contents)); } ContentSettingBubbleContents::~ContentSettingBubbleContents() { } void ContentSettingBubbleContents::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && (child == this)) InitControlLayout(); } void ContentSettingBubbleContents::ButtonPressed(views::Button* sender, const views::Event& event) { if (sender == close_button_) { info_bubble_->Close(); // CAREFUL: This deletes us. return; } for (std::vector<RadioGroup>::const_iterator i = radio_groups_.begin(); i != radio_groups_.end(); ++i) { for (RadioGroup::const_iterator j = i->begin(); j != i->end(); ++j) { if (sender == *j) { content_setting_bubble_model_->OnRadioClicked( i - radio_groups_.begin(), j - i->begin()); return; } } } NOTREACHED() << "unknown radio"; } void ContentSettingBubbleContents::LinkActivated(views::Link* source, int event_flags) { if (source == manage_link_) { content_setting_bubble_model_->OnManageLinkClicked(); // CAREFUL: Showing the settings window activates it, which deactivates the // info bubble, which causes it to close, which deletes us. return; } if (source == clear_link_) { content_setting_bubble_model_->OnClearLinkClicked(); info_bubble_->Close(); // CAREFUL: This deletes us. return; } PopupLinks::const_iterator i(popup_links_.find(source)); DCHECK(i != popup_links_.end()); content_setting_bubble_model_->OnPopupClicked(i->second); } void ContentSettingBubbleContents::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED); DCHECK(source == Source<TabContents>(tab_contents_)); tab_contents_ = NULL; } void ContentSettingBubbleContents::InitControlLayout() { using views::GridLayout; GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int single_column_set_id = 0; views::ColumnSet* column_set = layout->AddColumnSet(single_column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); const ContentSettingBubbleModel::BubbleContent& bubble_content = content_setting_bubble_model_->bubble_content(); if (!bubble_content.title.empty()) { views::Label* title_label = new views::Label(UTF8ToWide( bubble_content.title)); layout->StartRow(0, single_column_set_id); layout->AddView(title_label); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (content_setting_bubble_model_->content_type() == CONTENT_SETTINGS_TYPE_POPUPS) { const int popup_column_set_id = 2; views::ColumnSet* popup_column_set = layout->AddColumnSet(popup_column_set_id); popup_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 0, GridLayout::USE_PREF, 0, 0); popup_column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); popup_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); for (std::vector<ContentSettingBubbleModel::PopupItem>::const_iterator i(bubble_content.popup_items.begin()); i != bubble_content.popup_items.end(); ++i) { if (i != bubble_content.popup_items.begin()) layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, popup_column_set_id); views::Link* link = new views::Link(UTF8ToWide(i->title)); link->SetController(this); popup_links_[link] = i - bubble_content.popup_items.begin(); layout->AddView(new Favicon((*i).bitmap, this, link)); layout->AddView(link); } layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); views::Separator* separator = new views::Separator; layout->StartRow(0, single_column_set_id); layout->AddView(separator); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } const ContentSettingBubbleModel::RadioGroups& radio_groups = bubble_content.radio_groups; for (ContentSettingBubbleModel::RadioGroups::const_iterator i = radio_groups.begin(); i != radio_groups.end(); ++i) { const ContentSettingBubbleModel::RadioItems& radio_items = i->radio_items; RadioGroup radio_group; for (ContentSettingBubbleModel::RadioItems::const_iterator j = radio_items.begin(); j != radio_items.end(); ++j) { views::RadioButton* radio = new views::RadioButton( UTF8ToWide(*j), i - radio_groups.begin()); radio->set_listener(this); radio_group.push_back(radio); layout->StartRow(0, single_column_set_id); layout->AddView(radio); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } radio_groups_.push_back(radio_group); views::Separator* separator = new views::Separator; layout->StartRow(0, single_column_set_id); layout->AddView(separator, 1, 1, GridLayout::FILL, GridLayout::FILL); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); // Now that the buttons have been added to the view hierarchy, it's safe // to call SetChecked() on them. radio_group[i->default_item]->SetChecked(true); } gfx::Font domain_font = views::Label().GetFont().DeriveFont(0, gfx::Font::BOLD); const int indented_single_column_set_id = 3; // Insert a column set to indent the domain list. views::ColumnSet* indented_single_column_set = layout->AddColumnSet(indented_single_column_set_id); indented_single_column_set->AddPaddingColumn(0, kPanelHorizIndentation); indented_single_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); for (std::vector<ContentSettingBubbleModel::DomainList>::const_iterator i = bubble_content.domain_lists.begin(); i != bubble_content.domain_lists.end(); ++i) { layout->StartRow(0, single_column_set_id); views::Label* section_title = new views::Label(UTF8ToWide(i->title)); section_title->SetMultiLine(true); // TODO(joth): Should need to have hard coded size here, but without it // we get empty space at very end of bubble (as it's initially sized really // tall & skinny but then widens once the link/buttons are added // at the end of this method). section_title->SizeToFit(256); section_title->SetHorizontalAlignment(views::Label::ALIGN_LEFT); layout->AddView(section_title, 1, 1, GridLayout::FILL, GridLayout::LEADING); layout->StartRow(0, indented_single_column_set_id); for (std::set<std::string>::const_iterator j = i->hosts.begin(); j != i->hosts.end(); ++j) { layout->AddView(new views::Label(UTF8ToWide(*j), domain_font)); } layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (!bubble_content.clear_link.empty()) { clear_link_ = new views::Link(UTF8ToWide(bubble_content.clear_link)); clear_link_->SetController(this); layout->StartRow(0, single_column_set_id); layout->AddView(clear_link_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_set_id); layout->AddView(new views::Separator, 1, 1, GridLayout::FILL, GridLayout::FILL); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } const int double_column_set_id = 1; views::ColumnSet* double_column_set = layout->AddColumnSet(double_column_set_id); double_column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); double_column_set->AddPaddingColumn(0, kUnrelatedControlHorizontalSpacing); double_column_set->AddColumn(GridLayout::TRAILING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, double_column_set_id); manage_link_ = new views::Link(UTF8ToWide(bubble_content.manage_link)); manage_link_->SetController(this); layout->AddView(manage_link_); close_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_DONE)); layout->AddView(close_button_); } <commit_msg>Fixes http://code.google.com/p/chromium/issues/detail?id=39687 On the geolocation bubble, need to StartRow() before AddView() per host.<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/browser/views/content_blocked_bubble_contents.h" #if defined(OS_LINUX) #include <gdk/gdk.h> #endif #include "app/l10n_util.h" #include "chrome/browser/blocked_popup_container.h" #include "chrome/browser/content_setting_bubble_model.h" #include "chrome/browser/host_content_settings_map.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/browser_dialogs.h" #include "chrome/browser/views/info_bubble.h" #include "chrome/common/notification_source.h" #include "chrome/common/notification_type.h" #include "grit/generated_resources.h" #include "views/controls/button/native_button.h" #include "views/controls/button/radio_button.h" #include "views/controls/image_view.h" #include "views/controls/label.h" #include "views/controls/separator.h" #include "views/grid_layout.h" #include "views/standard_layout.h" class ContentSettingBubbleContents::Favicon : public views::ImageView { public: Favicon(const SkBitmap& image, ContentSettingBubbleContents* parent, views::Link* link); virtual ~Favicon(); private: #if defined(OS_WIN) static HCURSOR g_hand_cursor; #endif // views::View overrides: virtual bool OnMousePressed(const views::MouseEvent& event); virtual void OnMouseReleased(const views::MouseEvent& event, bool canceled); virtual gfx::NativeCursor GetCursorForPoint( views::Event::EventType event_type, const gfx::Point& p); ContentSettingBubbleContents* parent_; views::Link* link_; }; #if defined(OS_WIN) HCURSOR ContentSettingBubbleContents::Favicon::g_hand_cursor = NULL; #endif ContentSettingBubbleContents::Favicon::Favicon( const SkBitmap& image, ContentSettingBubbleContents* parent, views::Link* link) : parent_(parent), link_(link) { SetImage(image); } ContentSettingBubbleContents::Favicon::~Favicon() { } bool ContentSettingBubbleContents::Favicon::OnMousePressed( const views::MouseEvent& event) { return event.IsLeftMouseButton() || event.IsMiddleMouseButton(); } void ContentSettingBubbleContents::Favicon::OnMouseReleased( const views::MouseEvent& event, bool canceled) { if (!canceled && (event.IsLeftMouseButton() || event.IsMiddleMouseButton()) && HitTest(event.location())) parent_->LinkActivated(link_, event.GetFlags()); } gfx::NativeCursor ContentSettingBubbleContents::Favicon::GetCursorForPoint( views::Event::EventType event_type, const gfx::Point& p) { #if defined(OS_WIN) if (!g_hand_cursor) g_hand_cursor = LoadCursor(NULL, IDC_HAND); return g_hand_cursor; #elif defined(OS_LINUX) return gdk_cursor_new(GDK_HAND2); #endif } ContentSettingBubbleContents::ContentSettingBubbleContents( ContentSettingBubbleModel* content_setting_bubble_model, Profile* profile, TabContents* tab_contents) : content_setting_bubble_model_(content_setting_bubble_model), profile_(profile), tab_contents_(tab_contents), info_bubble_(NULL), close_button_(NULL), manage_link_(NULL), clear_link_(NULL) { registrar_.Add(this, NotificationType::TAB_CONTENTS_DESTROYED, Source<TabContents>(tab_contents)); } ContentSettingBubbleContents::~ContentSettingBubbleContents() { } void ContentSettingBubbleContents::ViewHierarchyChanged(bool is_add, View* parent, View* child) { if (is_add && (child == this)) InitControlLayout(); } void ContentSettingBubbleContents::ButtonPressed(views::Button* sender, const views::Event& event) { if (sender == close_button_) { info_bubble_->Close(); // CAREFUL: This deletes us. return; } for (std::vector<RadioGroup>::const_iterator i = radio_groups_.begin(); i != radio_groups_.end(); ++i) { for (RadioGroup::const_iterator j = i->begin(); j != i->end(); ++j) { if (sender == *j) { content_setting_bubble_model_->OnRadioClicked( i - radio_groups_.begin(), j - i->begin()); return; } } } NOTREACHED() << "unknown radio"; } void ContentSettingBubbleContents::LinkActivated(views::Link* source, int event_flags) { if (source == manage_link_) { content_setting_bubble_model_->OnManageLinkClicked(); // CAREFUL: Showing the settings window activates it, which deactivates the // info bubble, which causes it to close, which deletes us. return; } if (source == clear_link_) { content_setting_bubble_model_->OnClearLinkClicked(); info_bubble_->Close(); // CAREFUL: This deletes us. return; } PopupLinks::const_iterator i(popup_links_.find(source)); DCHECK(i != popup_links_.end()); content_setting_bubble_model_->OnPopupClicked(i->second); } void ContentSettingBubbleContents::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK(type == NotificationType::TAB_CONTENTS_DESTROYED); DCHECK(source == Source<TabContents>(tab_contents_)); tab_contents_ = NULL; } void ContentSettingBubbleContents::InitControlLayout() { using views::GridLayout; GridLayout* layout = new views::GridLayout(this); SetLayoutManager(layout); const int single_column_set_id = 0; views::ColumnSet* column_set = layout->AddColumnSet(single_column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); const ContentSettingBubbleModel::BubbleContent& bubble_content = content_setting_bubble_model_->bubble_content(); if (!bubble_content.title.empty()) { views::Label* title_label = new views::Label(UTF8ToWide( bubble_content.title)); layout->StartRow(0, single_column_set_id); layout->AddView(title_label); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (content_setting_bubble_model_->content_type() == CONTENT_SETTINGS_TYPE_POPUPS) { const int popup_column_set_id = 2; views::ColumnSet* popup_column_set = layout->AddColumnSet(popup_column_set_id); popup_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 0, GridLayout::USE_PREF, 0, 0); popup_column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing); popup_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); for (std::vector<ContentSettingBubbleModel::PopupItem>::const_iterator i(bubble_content.popup_items.begin()); i != bubble_content.popup_items.end(); ++i) { if (i != bubble_content.popup_items.begin()) layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, popup_column_set_id); views::Link* link = new views::Link(UTF8ToWide(i->title)); link->SetController(this); popup_links_[link] = i - bubble_content.popup_items.begin(); layout->AddView(new Favicon((*i).bitmap, this, link)); layout->AddView(link); } layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); views::Separator* separator = new views::Separator; layout->StartRow(0, single_column_set_id); layout->AddView(separator); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } const ContentSettingBubbleModel::RadioGroups& radio_groups = bubble_content.radio_groups; for (ContentSettingBubbleModel::RadioGroups::const_iterator i = radio_groups.begin(); i != radio_groups.end(); ++i) { const ContentSettingBubbleModel::RadioItems& radio_items = i->radio_items; RadioGroup radio_group; for (ContentSettingBubbleModel::RadioItems::const_iterator j = radio_items.begin(); j != radio_items.end(); ++j) { views::RadioButton* radio = new views::RadioButton( UTF8ToWide(*j), i - radio_groups.begin()); radio->set_listener(this); radio_group.push_back(radio); layout->StartRow(0, single_column_set_id); layout->AddView(radio); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } radio_groups_.push_back(radio_group); views::Separator* separator = new views::Separator; layout->StartRow(0, single_column_set_id); layout->AddView(separator, 1, 1, GridLayout::FILL, GridLayout::FILL); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); // Now that the buttons have been added to the view hierarchy, it's safe // to call SetChecked() on them. radio_group[i->default_item]->SetChecked(true); } gfx::Font domain_font = views::Label().GetFont().DeriveFont(0, gfx::Font::BOLD); const int indented_single_column_set_id = 3; // Insert a column set to indent the domain list. views::ColumnSet* indented_single_column_set = layout->AddColumnSet(indented_single_column_set_id); indented_single_column_set->AddPaddingColumn(0, kPanelHorizIndentation); indented_single_column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); for (std::vector<ContentSettingBubbleModel::DomainList>::const_iterator i = bubble_content.domain_lists.begin(); i != bubble_content.domain_lists.end(); ++i) { layout->StartRow(0, single_column_set_id); views::Label* section_title = new views::Label(UTF8ToWide(i->title)); section_title->SetMultiLine(true); // TODO(joth): Should need to have hard coded size here, but without it // we get empty space at very end of bubble (as it's initially sized really // tall & skinny but then widens once the link/buttons are added // at the end of this method). section_title->SizeToFit(256); section_title->SetHorizontalAlignment(views::Label::ALIGN_LEFT); layout->AddView(section_title, 1, 1, GridLayout::FILL, GridLayout::LEADING); for (std::set<std::string>::const_iterator j = i->hosts.begin(); j != i->hosts.end(); ++j) { layout->StartRow(0, indented_single_column_set_id); layout->AddView(new views::Label(UTF8ToWide(*j), domain_font)); } layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } if (!bubble_content.clear_link.empty()) { clear_link_ = new views::Link(UTF8ToWide(bubble_content.clear_link)); clear_link_->SetController(this); layout->StartRow(0, single_column_set_id); layout->AddView(clear_link_); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); layout->StartRow(0, single_column_set_id); layout->AddView(new views::Separator, 1, 1, GridLayout::FILL, GridLayout::FILL); layout->AddPaddingRow(0, kRelatedControlVerticalSpacing); } const int double_column_set_id = 1; views::ColumnSet* double_column_set = layout->AddColumnSet(double_column_set_id); double_column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 1, GridLayout::USE_PREF, 0, 0); double_column_set->AddPaddingColumn(0, kUnrelatedControlHorizontalSpacing); double_column_set->AddColumn(GridLayout::TRAILING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, double_column_set_id); manage_link_ = new views::Link(UTF8ToWide(bubble_content.manage_link)); manage_link_->SetController(this); layout->AddView(manage_link_); close_button_ = new views::NativeButton(this, l10n_util::GetString(IDS_DONE)); layout->AddView(close_button_); } <|endoftext|>
<commit_before>// bsls_atomicoperations_x64_all_gcc.t.cpp -*-C++-*- #include <bsls_atomicoperations_x64_all_gcc.h> #include <cstdlib> #include <iostream> #if defined(BSLS_PLATFORM_CPU_X86_64) \ && (defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG)) // For thread support #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> typedef HANDLE thread_t; #else #include <pthread.h> #include <unistd.h> typedef pthread_t thread_t; #endif // For timer support #ifdef BSLS_PLATFORM_OS_WINDOWS #include <sys/timeb.h> // ftime(struct timeb *) #else #include <sys/time.h> #endif using namespace BloombergLP; using namespace std; typedef void *(*thread_func)(void *arg); typedef bsls::Atomic_TypeTraits<bsls::AtomicOperations_X64_ALL_GCC>::Int atomic_int; struct thread_args { atomic_int *d_obj_p; bsls::Types::Int64 d_iterations; bsls::Types::Int64 d_runtimeMs; }; bsls::Types::Int64 getTimerMs() { // It'd be nice to use TimeUtil here, but that would be a dependency // cycle. Duplicating all the portable support for high-resolution // timing is more complication than is needed here. We'll run enough // iterations that the basic portable lower-resolution timers will give // good results. #if defined(BSLS_PLATFORM_OS_UNIX) timeval native; gettimeofday(&native, 0); return ((bsls::Types::Int64) native.tv_sec * 1000 + native.tv_usec / 1000); #elif defined(BSLS_PLATFORM_OS_WINDOWS) timeb t; ::ftime(&t); return = static_cast<bsls::Types::Int64>(t.time) * 1000 + t.millitm; #else #error "Don't know how to get timer for this platform" #endif } thread_t createThread(thread_func func, void *arg) { #ifdef BSLS_PLATFORM_OS_WINDOWS return CreateThread(0, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, 0); #else thread_t thr; pthread_create(&thr, 0, func, arg); return thr; #endif } void joinThread(thread_t thr) { #ifdef BSLS_PLATFORM_OS_WINDOWS WaitForSingleObject(thr, INFINITE); CloseHandle(thr); #else pthread_join(thr, 0); #endif } struct atomic_get_mfence { int operator()(atomic_int * obj) { int ret; asm volatile ( " mfence \n\t" " movl %[obj], %[ret] \n\t" : [ret] "=r" (ret) : [obj] "m" (*obj) : "memory"); return ret; } }; struct atomic_get_free { int operator()(const atomic_int * obj) { int ret; asm volatile ( " movl %[obj], %[ret] \n\t" : [ret] "=r" (ret) : [obj] "m" (*obj) : "memory"); return ret; } }; struct atomic_set_mfence { void operator()(atomic_int * obj, int value) { asm volatile ( " movl %[val], %[obj] \n\t" " mfence \n\t" : [obj] "=m" (*obj) : [val] "r" (value) : "memory"); } }; struct atomic_set_lock { void operator()(atomic_int * obj, int value) { asm volatile ( " movl %[val], %[obj] \n\t" " lock addq $0, 0(%%rsp) \n\t" : [obj] "=m" (*obj) : [val] "r" (value) : "memory", "cc"); } }; struct atomic_set_xchg { void operator()(atomic_int * obj, int value) { asm volatile ( " xchgl %[obj], %[val] \n\t" : [obj] "=m" (*obj) : [val] "r" (value) : "memory"); } }; template <typename AtomicGet> void * test_atomics_get_thread(void * args) { thread_args * thr_args = reinterpret_cast<thread_args *>(args); atomic_int *obj = thr_args->d_obj_p; AtomicGet get_fun; bsls::Types::Int64 i; bsls::Types::Int64 start = getTimerMs(); for (i = 0; get_fun(obj) != -1; ++i) ; thr_args->d_runtimeMs = getTimerMs() - start; thr_args->d_iterations = i; return 0; } template <typename AtomicGet> void * test_atomics_set_thread(void * args) { thread_args * thr_args = reinterpret_cast<thread_args *>(args); atomic_int *obj = thr_args->d_obj_p; AtomicGet set_fun; bsls::Types::Int64 start = getTimerMs(); for (bsls::Types::Int64 i = thr_args->d_iterations; i > 0; --i) set_fun(obj, (int)i); // signal finish set_fun(obj, -1); thr_args->d_runtimeMs = getTimerMs() - start; return 0; } template <typename AtomicGet, typename AtomicSet> void test_atomics(bsls::Types::Int64 iterations) { enum { NUM_READERS = 3 }; thread_t readers[NUM_READERS]; thread_args readerArgs[NUM_READERS]; thread_args args; args.d_obj_p = new atomic_int; args.d_iterations = iterations; for (int i = 0 ; i < NUM_READERS; ++i) { readerArgs[i] = args; readers[i] = createThread(&test_atomics_get_thread<AtomicGet>, &readerArgs[i]); } thread_t writer; writer = createThread(&test_atomics_set_thread<AtomicSet>, &args); for (int i = 0; i < NUM_READERS; ++i) { joinThread(readers[i]); } joinThread(writer); bsls::Types::Int64 totalReadIter = 0, totalReadTime = 0; for (int i = 0; i < NUM_READERS; ++i) { totalReadIter += readerArgs[i].d_iterations; totalReadTime += readerArgs[i].d_runtimeMs; } static const double MS_PER_SEC = 1000; double readPerSec = (double)totalReadIter / totalReadTime * MS_PER_SEC; double writePerSec = (double)iterations / args.d_runtimeMs * MS_PER_SEC; cout << " " << readPerSec << " / " << writePerSec << endl; delete args.d_obj_p; } int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; switch (test) { case 0: return 0; case -1: { //////////////////////////////////////////// // Benchmark test // // Time get/set operations for several possible implementations // of get and set. To simulate the typical reader/writer // configuration, run 1 "setter" thread and 3 "getter" threads. // The "setter" thread will run a fixed number of iterations and // the "getter" threads will run until they see a value indicating // the setter has stopped. /////////////////////////////////////////// enum { NUM_ITER = 30 * 1000 * 1000 }; cout << "get mfence / set mfence: "; test_atomics<atomic_get_mfence, atomic_set_mfence>(NUM_ITER); cout << "get free / set mfence: "; test_atomics<atomic_get_free, atomic_set_mfence>(NUM_ITER); cout << "get free / set lock: "; test_atomics<atomic_get_free, atomic_set_lock>(NUM_ITER); cout << "get free / set xchg: "; test_atomics<atomic_get_free, atomic_set_xchg>(NUM_ITER); } break; default: return -1; } } #else // BSLS_PLATFORM_CPU_X86_64 && // (BSLS_PLATFORM_CMP_GNU || BSLS_PLATFORM_CMP_CLANG) int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; switch (test) { case 0: return 0; default: return -1; } } #endif // BSLS_PLATFORM_CPU_X86_64 && // (BSLS_PLATFORM_CMP_GNU || BSLS_PLATFORM_CMP_CLANG) // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>[APPROVAL] OSS pr-156-fix-gcc-on-windwos-drqs-59840853 to master<commit_after>// bsls_atomicoperations_x64_all_gcc.t.cpp -*-C++-*- #include <bsls_atomicoperations_x64_all_gcc.h> #include <cstdlib> #include <iostream> #if defined(BSLS_PLATFORM_CPU_X86_64) \ && (defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG)) // For thread support #ifdef BSLS_PLATFORM_OS_WINDOWS #include <windows.h> typedef HANDLE thread_t; #else #include <pthread.h> #include <unistd.h> typedef pthread_t thread_t; #endif // For timer support #ifdef BSLS_PLATFORM_OS_WINDOWS #include <sys/timeb.h> // ftime(struct timeb *) #else #include <sys/time.h> #endif using namespace BloombergLP; using namespace std; typedef void *(*thread_func)(void *arg); typedef bsls::Atomic_TypeTraits<bsls::AtomicOperations_X64_ALL_GCC>::Int atomic_int; struct thread_args { atomic_int *d_obj_p; bsls::Types::Int64 d_iterations; bsls::Types::Int64 d_runtimeMs; }; bsls::Types::Int64 getTimerMs() { // It'd be nice to use TimeUtil here, but that would be a dependency // cycle. Duplicating all the portable support for high-resolution // timing is more complication than is needed here. We'll run enough // iterations that the basic portable lower-resolution timers will give // good results. #if defined(BSLS_PLATFORM_OS_UNIX) timeval native; gettimeofday(&native, 0); return ((bsls::Types::Int64) native.tv_sec * 1000 + native.tv_usec / 1000); #elif defined(BSLS_PLATFORM_OS_WINDOWS) timeb t; ::ftime(&t); return static_cast<bsls::Types::Int64>(t.time) * 1000 + t.millitm; #else #error "Don't know how to get timer for this platform" #endif } thread_t createThread(thread_func func, void *arg) { #ifdef BSLS_PLATFORM_OS_WINDOWS return CreateThread(0, 0, (LPTHREAD_START_ROUTINE) func, arg, 0, 0); #else thread_t thr; pthread_create(&thr, 0, func, arg); return thr; #endif } void joinThread(thread_t thr) { #ifdef BSLS_PLATFORM_OS_WINDOWS WaitForSingleObject(thr, INFINITE); CloseHandle(thr); #else pthread_join(thr, 0); #endif } struct atomic_get_mfence { int operator()(atomic_int * obj) { int ret; asm volatile ( " mfence \n\t" " movl %[obj], %[ret] \n\t" : [ret] "=r" (ret) : [obj] "m" (*obj) : "memory"); return ret; } }; struct atomic_get_free { int operator()(const atomic_int * obj) { int ret; asm volatile ( " movl %[obj], %[ret] \n\t" : [ret] "=r" (ret) : [obj] "m" (*obj) : "memory"); return ret; } }; struct atomic_set_mfence { void operator()(atomic_int * obj, int value) { asm volatile ( " movl %[val], %[obj] \n\t" " mfence \n\t" : [obj] "=m" (*obj) : [val] "r" (value) : "memory"); } }; struct atomic_set_lock { void operator()(atomic_int * obj, int value) { asm volatile ( " movl %[val], %[obj] \n\t" " lock addq $0, 0(%%rsp) \n\t" : [obj] "=m" (*obj) : [val] "r" (value) : "memory", "cc"); } }; struct atomic_set_xchg { void operator()(atomic_int * obj, int value) { asm volatile ( " xchgl %[obj], %[val] \n\t" : [obj] "=m" (*obj) : [val] "r" (value) : "memory"); } }; template <typename AtomicGet> void * test_atomics_get_thread(void * args) { thread_args * thr_args = reinterpret_cast<thread_args *>(args); atomic_int *obj = thr_args->d_obj_p; AtomicGet get_fun; bsls::Types::Int64 i; bsls::Types::Int64 start = getTimerMs(); for (i = 0; get_fun(obj) != -1; ++i) ; thr_args->d_runtimeMs = getTimerMs() - start; thr_args->d_iterations = i; return 0; } template <typename AtomicGet> void * test_atomics_set_thread(void * args) { thread_args * thr_args = reinterpret_cast<thread_args *>(args); atomic_int *obj = thr_args->d_obj_p; AtomicGet set_fun; bsls::Types::Int64 start = getTimerMs(); for (bsls::Types::Int64 i = thr_args->d_iterations; i > 0; --i) set_fun(obj, (int)i); // signal finish set_fun(obj, -1); thr_args->d_runtimeMs = getTimerMs() - start; return 0; } template <typename AtomicGet, typename AtomicSet> void test_atomics(bsls::Types::Int64 iterations) { enum { NUM_READERS = 3 }; thread_t readers[NUM_READERS]; thread_args readerArgs[NUM_READERS]; thread_args args; args.d_obj_p = new atomic_int; args.d_iterations = iterations; for (int i = 0 ; i < NUM_READERS; ++i) { readerArgs[i] = args; readers[i] = createThread(&test_atomics_get_thread<AtomicGet>, &readerArgs[i]); } thread_t writer; writer = createThread(&test_atomics_set_thread<AtomicSet>, &args); for (int i = 0; i < NUM_READERS; ++i) { joinThread(readers[i]); } joinThread(writer); bsls::Types::Int64 totalReadIter = 0, totalReadTime = 0; for (int i = 0; i < NUM_READERS; ++i) { totalReadIter += readerArgs[i].d_iterations; totalReadTime += readerArgs[i].d_runtimeMs; } static const double MS_PER_SEC = 1000; double readPerSec = (double)totalReadIter / totalReadTime * MS_PER_SEC; double writePerSec = (double)iterations / args.d_runtimeMs * MS_PER_SEC; cout << " " << readPerSec << " / " << writePerSec << endl; delete args.d_obj_p; } int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; switch (test) { case 0: return 0; case -1: { //////////////////////////////////////////// // Benchmark test // // Time get/set operations for several possible implementations // of get and set. To simulate the typical reader/writer // configuration, run 1 "setter" thread and 3 "getter" threads. // The "setter" thread will run a fixed number of iterations and // the "getter" threads will run until they see a value indicating // the setter has stopped. /////////////////////////////////////////// enum { NUM_ITER = 30 * 1000 * 1000 }; cout << "get mfence / set mfence: "; test_atomics<atomic_get_mfence, atomic_set_mfence>(NUM_ITER); cout << "get free / set mfence: "; test_atomics<atomic_get_free, atomic_set_mfence>(NUM_ITER); cout << "get free / set lock: "; test_atomics<atomic_get_free, atomic_set_lock>(NUM_ITER); cout << "get free / set xchg: "; test_atomics<atomic_get_free, atomic_set_xchg>(NUM_ITER); } break; default: return -1; } } #else // BSLS_PLATFORM_CPU_X86_64 && // (BSLS_PLATFORM_CMP_GNU || BSLS_PLATFORM_CMP_CLANG) int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; switch (test) { case 0: return 0; default: return -1; } } #endif // BSLS_PLATFORM_CPU_X86_64 && // (BSLS_PLATFORM_CMP_GNU || BSLS_PLATFORM_CMP_CLANG) // ---------------------------------------------------------------------------- // Copyright 2013 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>/*************************************************************************/ /* math_funcs.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "math_funcs.h" #include "core/os/os.h" #include <math.h> #include "float.h" uint32_t Math::default_seed=1; #define PHI 0x9e3779b9 static uint32_t Q[4096], c = 362436; uint32_t Math::rand_from_seed(uint32_t *seed) { #if 1 uint32_t k; uint32_t s = (*seed); if (s == 0) s = 0x12345987; k = s / 127773; s = 16807 * (s - k * 127773) - 2836 * k; if (s < 0) s += 2147483647; (*seed) = s; return (s & Math::RANDOM_MAX); #else *seed = *seed * 1103515245 + 12345; return (*seed % ((unsigned int)RANDOM_MAX + 1)); #endif } void Math::seed(uint32_t x) { #if 0 int i; Q[0] = x; Q[1] = x + PHI; Q[2] = x + PHI + PHI; for (i = 3; i < 4096; i++) Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i; #else default_seed=x; #endif } void Math::randomize() { OS::Time time = OS::get_singleton()->get_time(); seed(OS::get_singleton()->get_ticks_usec()*time.hour*time.min*time.sec*rand()); /* *OS::get_singleton()->get_time().sec); // windows doesn't have get_time(), returns always 0 */ } uint32_t Math::rand() { return rand_from_seed(&default_seed)&0x7FFFFFFF; } double Math::randf() { return (double)rand() / (double)RANDOM_MAX; } double Math::sin(double p_x) { return ::sin(p_x); } double Math::cos(double p_x) { return ::cos(p_x); } double Math::tan(double p_x) { return ::tan(p_x); } double Math::sinh(double p_x) { return ::sinh(p_x); } double Math::cosh(double p_x) { return ::cosh(p_x); } double Math::tanh(double p_x) { return ::tanh(p_x); } double Math::deg2rad(double p_y) { return p_y*Math_PI/180.0; } double Math::rad2deg(double p_y) { return p_y*180.0/Math_PI; } double Math::round(double p_val) { if (p_val>0) { return ::floor(p_val+0.5); } else { p_val=-p_val; return -::floor(p_val+0.5); } } double Math::asin(double p_x) { return ::asin(p_x); } double Math::acos(double p_x) { return ::acos(p_x); } double Math::atan(double p_x) { return ::atan(p_x); } double Math::dectime(double p_value,double p_amount, double p_step) { float sgn = p_value < 0 ? -1.0 : 1.0; float val = absf(p_value); val-=p_amount*p_step; if (val<0.0) val=0.0; return val*sgn; } double Math::atan2(double p_y, double p_x) { return ::atan2(p_y,p_x); } double Math::sqrt(double p_x) { return ::sqrt(p_x); } double Math::fmod(double p_x,double p_y) { return ::fmod(p_x,p_y); } double Math::fposmod(double p_x,double p_y) { if (p_x>=0) { return Math::fmod(p_x,p_y); } else { return p_y-Math::fmod(-p_x,p_y); } } double Math::floor(double p_x) { return ::floor(p_x); } double Math::ceil(double p_x) { return ::ceil(p_x); } int Math::decimals(double p_step) { int max=4; int i=0; while( (p_step - Math::floor(p_step)) != 0.0 && max) { p_step*=10.0; max--; i++; } return i; } double Math::ease(double p_x, double p_c) { if (p_x<0) p_x=0; else if (p_x>1.0) p_x=1.0; if (p_c>0) { if (p_c<1.0) { return 1.0-Math::pow(1.0-p_x,1.0/p_c); } else { return Math::pow(p_x,p_c); } } else if (p_c<0) { //inout ease if (p_x<0.5) { return Math::pow(p_x*2.0,-p_c)*0.5; } else { return (1.0-Math::pow(1.0-(p_x-0.5)*2.0,-p_c))*0.5+0.5; } } else return 0; // no ease (raw) } double Math::stepify(double p_value,double p_step) { if (p_step!=0) { p_value=floor( p_value / p_step + 0.5 ) * p_step; } return p_value; } bool Math::is_nan(double p_val) { return (p_val!=p_val); } bool Math::is_inf(double p_val) { #ifdef _MSC_VER return !_finite(p_val); #else return isinf(p_val); #endif } uint32_t Math::larger_prime(uint32_t p_val) { static const int primes[] = { 5, 13, 23, 47, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, 0, }; int idx=0; while (true) { ERR_FAIL_COND_V(primes[idx]==0,0); if (primes[idx]>p_val) return primes[idx]; idx++; } return 0; } double Math::random(double from, double to) { unsigned int r = Math::rand(); double ret = (double)r/(double)RANDOM_MAX; return (ret)*(to-from) + from; } double Math::pow(double x, double y) { return ::pow(x,y); } double Math::log(double x) { return ::log(x); } double Math::exp(double x) { return ::exp(x); } <commit_msg>- Fix issue #802: randomize() now generate non-zero seed during the first hour of every days, the first minute of every hours and the first second of every minutes.<commit_after>/*************************************************************************/ /* math_funcs.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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 "math_funcs.h" #include "core/os/os.h" #include <math.h> #include "float.h" uint32_t Math::default_seed=1; #define PHI 0x9e3779b9 static uint32_t Q[4096], c = 362436; uint32_t Math::rand_from_seed(uint32_t *seed) { #if 1 uint32_t k; uint32_t s = (*seed); if (s == 0) s = 0x12345987; k = s / 127773; s = 16807 * (s - k * 127773) - 2836 * k; if (s < 0) s += 2147483647; (*seed) = s; return (s & Math::RANDOM_MAX); #else *seed = *seed * 1103515245 + 12345; return (*seed % ((unsigned int)RANDOM_MAX + 1)); #endif } void Math::seed(uint32_t x) { #if 0 int i; Q[0] = x; Q[1] = x + PHI; Q[2] = x + PHI + PHI; for (i = 3; i < 4096; i++) Q[i] = Q[i - 3] ^ Q[i - 2] ^ PHI ^ i; #else default_seed=x; #endif } void Math::randomize() { OS::Time time = OS::get_singleton()->get_time(); seed(OS::get_singleton()->get_ticks_usec()*(time.hour+1)*(time.min+1)*(time.sec+1)*rand()); /* *OS::get_singleton()->get_time().sec); // windows doesn't have get_time(), returns always 0 */ } uint32_t Math::rand() { return rand_from_seed(&default_seed)&0x7FFFFFFF; } double Math::randf() { return (double)rand() / (double)RANDOM_MAX; } double Math::sin(double p_x) { return ::sin(p_x); } double Math::cos(double p_x) { return ::cos(p_x); } double Math::tan(double p_x) { return ::tan(p_x); } double Math::sinh(double p_x) { return ::sinh(p_x); } double Math::cosh(double p_x) { return ::cosh(p_x); } double Math::tanh(double p_x) { return ::tanh(p_x); } double Math::deg2rad(double p_y) { return p_y*Math_PI/180.0; } double Math::rad2deg(double p_y) { return p_y*180.0/Math_PI; } double Math::round(double p_val) { if (p_val>0) { return ::floor(p_val+0.5); } else { p_val=-p_val; return -::floor(p_val+0.5); } } double Math::asin(double p_x) { return ::asin(p_x); } double Math::acos(double p_x) { return ::acos(p_x); } double Math::atan(double p_x) { return ::atan(p_x); } double Math::dectime(double p_value,double p_amount, double p_step) { float sgn = p_value < 0 ? -1.0 : 1.0; float val = absf(p_value); val-=p_amount*p_step; if (val<0.0) val=0.0; return val*sgn; } double Math::atan2(double p_y, double p_x) { return ::atan2(p_y,p_x); } double Math::sqrt(double p_x) { return ::sqrt(p_x); } double Math::fmod(double p_x,double p_y) { return ::fmod(p_x,p_y); } double Math::fposmod(double p_x,double p_y) { if (p_x>=0) { return Math::fmod(p_x,p_y); } else { return p_y-Math::fmod(-p_x,p_y); } } double Math::floor(double p_x) { return ::floor(p_x); } double Math::ceil(double p_x) { return ::ceil(p_x); } int Math::decimals(double p_step) { int max=4; int i=0; while( (p_step - Math::floor(p_step)) != 0.0 && max) { p_step*=10.0; max--; i++; } return i; } double Math::ease(double p_x, double p_c) { if (p_x<0) p_x=0; else if (p_x>1.0) p_x=1.0; if (p_c>0) { if (p_c<1.0) { return 1.0-Math::pow(1.0-p_x,1.0/p_c); } else { return Math::pow(p_x,p_c); } } else if (p_c<0) { //inout ease if (p_x<0.5) { return Math::pow(p_x*2.0,-p_c)*0.5; } else { return (1.0-Math::pow(1.0-(p_x-0.5)*2.0,-p_c))*0.5+0.5; } } else return 0; // no ease (raw) } double Math::stepify(double p_value,double p_step) { if (p_step!=0) { p_value=floor( p_value / p_step + 0.5 ) * p_step; } return p_value; } bool Math::is_nan(double p_val) { return (p_val!=p_val); } bool Math::is_inf(double p_val) { #ifdef _MSC_VER return !_finite(p_val); #else return isinf(p_val); #endif } uint32_t Math::larger_prime(uint32_t p_val) { static const int primes[] = { 5, 13, 23, 47, 97, 193, 389, 769, 1543, 3079, 6151, 12289, 24593, 49157, 98317, 196613, 393241, 786433, 1572869, 3145739, 6291469, 12582917, 25165843, 50331653, 100663319, 201326611, 402653189, 805306457, 1610612741, 0, }; int idx=0; while (true) { ERR_FAIL_COND_V(primes[idx]==0,0); if (primes[idx]>p_val) return primes[idx]; idx++; } return 0; } double Math::random(double from, double to) { unsigned int r = Math::rand(); double ret = (double)r/(double)RANDOM_MAX; return (ret)*(to-from) + from; } double Math::pow(double x, double y) { return ::pow(x,y); } double Math::log(double x) { return ::log(x); } double Math::exp(double x) { return ::exp(x); } <|endoftext|>
<commit_before> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2013-2017 Igor Mironchik 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. */ // UnitTest include. #include <UnitTest/unit_test.hpp> // Args include. #include <Args/all.hpp> using namespace Args; #ifdef ARGS_WSTRING_BUILD using CHAR = String::value_type; #else using CHAR = char; #endif TEST( GroupCase, TestOnlyOneAllIsOk ) { const int argc = 3; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); OnlyOneGroup g( SL( "only_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); cmd.parse(); CHECK_CONDITION( timeout.isDefined() == true ) CHECK_CONDITION( timeout.value() == SL( "100" ) ) CHECK_CONDITION( port.isDefined() == false ) CHECK_CONDITION( host.isDefined() == false ) } TEST( GroupCase, TestOnlyOneFailed ) { const int argc = 5; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); OnlyOneGroup g( SL( "only_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestOnlyOneWithRequiredFailed ) { const int argc = 3; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true, true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); OnlyOneGroup g( SL( "only_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestAllOfIsOk ) { const int argc = 7; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ), SL( "-h" ), SL( "localhost" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AllOfGroup g( SL( "all_of" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); cmd.parse(); CHECK_CONDITION( timeout.isDefined() == true ) CHECK_CONDITION( timeout.value() == SL( "100" ) ) CHECK_CONDITION( port.isDefined() == true ) CHECK_CONDITION( port.value() == SL( "4545" ) ) CHECK_CONDITION( host.isDefined() == true ) CHECK_CONDITION( host.value() == SL( "localhost" ) ) } TEST( GroupCase, TestAllOfFailed ) { const int argc = 5; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AllOfGroup g( SL( "all_of" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestAllOfWithRequiredFailed ) { const int argc = 3; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true, true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); OnlyOneGroup g( SL( "all_of" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestAtLeasOneIsOk ) { const int argc = 5; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AtLeastOneGroup g( SL( "at_least_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); cmd.parse(); CHECK_CONDITION( timeout.isDefined() == true ) CHECK_CONDITION( timeout.value() == SL( "100" ) ) CHECK_CONDITION( port.isDefined() == true ) CHECK_CONDITION( port.value() == SL( "4545" ) ) CHECK_CONDITION( host.isDefined() == false ) CHECK_CONDITION( g.isDefined() == true ) } TEST( GroupCase, TestAtLeasOneFailed ) { const int argc = 1; const CHAR * argv[ argc ] = { SL( "program.exe" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AtLeastOneGroup g( SL( "at_least_one" ) ); g.setRequired( true ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestAtLeasOneWithRequiredFailed ) { const int argc = 3; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true, true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AtLeastOneGroup g( SL( "at_least_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, GroupsIsOk ) { const int argc = 9; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ), SL( "-h" ), SL( "localhost" ), SL( "-s" ), SL( "db" ) }; CmdLine cmd( argc, argv ); Arg store( Char( SL( 's' ) ), SL( "store" ), true ); Arg file( Char( SL( 'f' ) ), SL( "file" ), true ); OnlyOneGroup onlyOne( SL( "only_one" ) ); onlyOne.addArg( store ); onlyOne.addArg( file ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AllOfGroup g( SL( "all_of" ) ); g.setRequired( true ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); g.addArg( onlyOne ); cmd.addArg( g ); cmd.parse(); CHECK_CONDITION( timeout.isDefined() == true ) CHECK_CONDITION( timeout.value() == SL( "100" ) ) CHECK_CONDITION( port.isDefined() == true ) CHECK_CONDITION( port.value() == SL( "4545" ) ) CHECK_CONDITION( host.isDefined() == true ) CHECK_CONDITION( host.value() == SL( "localhost" ) ) CHECK_CONDITION( store.isDefined() == true ) CHECK_CONDITION( store.value() == SL( "db" ) ) CHECK_CONDITION( file.isDefined() == false ) CHECK_CONDITION( g.isDefined() == true ) } TEST( GroupCase, GroupsFailed ) { const int argc = 11; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ), SL( "-h" ), SL( "localhost" ), SL( "-s" ), SL( "db" ), SL( "-f" ), SL( "out.txt" ) }; CmdLine cmd( argc, argv ); Arg store( Char( SL( 's' ) ), SL( "store" ), true ); Arg file( Char( SL( 'f' ) ), SL( "file" ), true ); OnlyOneGroup onlyOne( SL( "only_one" ) ); onlyOne.addArg( store ); onlyOne.addArg( file ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AllOfGroup g( SL( "all_of" ) ); g.setRequired( true ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); g.addArg( onlyOne ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, GroupsStuff ) { OnlyOneGroup one( SL( "only_one" ) ); CHECK_CONDITION( !one.isWithValue() ) CHECK_CONDITION( one.flag().empty() ) CHECK_CONDITION( one.argumentName().empty() ) CHECK_CONDITION( one.valueSpecifier().empty() ) CHECK_CONDITION( one.description().empty() ) CHECK_CONDITION( one.longDescription().empty() ) } int main() { RUN_ALL_TESTS() return 0; } <commit_msg>Testing.<commit_after> /*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2013-2017 Igor Mironchik 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. */ // UnitTest include. #include <UnitTest/unit_test.hpp> // Args include. #include <Args/all.hpp> using namespace Args; #ifdef ARGS_WSTRING_BUILD using CHAR = String::value_type; #else using CHAR = char; #endif TEST( GroupCase, TestOnlyOneAllIsOk ) { const int argc = 3; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); OnlyOneGroup g( SL( "only_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); cmd.parse(); CHECK_CONDITION( timeout.isDefined() == true ) CHECK_CONDITION( timeout.value() == SL( "100" ) ) CHECK_CONDITION( port.isDefined() == false ) CHECK_CONDITION( host.isDefined() == false ) } TEST( GroupCase, TestOnlyOneFailed ) { const int argc = 5; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); OnlyOneGroup g( SL( "only_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestOnlyOneWithRequiredFailed ) { const int argc = 3; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true, true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); OnlyOneGroup g( SL( "only_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestAllOfIsOk ) { const int argc = 7; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ), SL( "-h" ), SL( "localhost" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AllOfGroup g( SL( "all_of" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); cmd.parse(); CHECK_CONDITION( timeout.isDefined() == true ) CHECK_CONDITION( timeout.value() == SL( "100" ) ) CHECK_CONDITION( port.isDefined() == true ) CHECK_CONDITION( port.value() == SL( "4545" ) ) CHECK_CONDITION( host.isDefined() == true ) CHECK_CONDITION( host.value() == SL( "localhost" ) ) } TEST( GroupCase, TestAllOfFailed ) { const int argc = 5; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AllOfGroup g( SL( "all_of" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestAllOfWithRequiredFailed ) { const int argc = 3; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true, true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); OnlyOneGroup g( SL( "all_of" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestAtLeasOneIsOk ) { const int argc = 5; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AtLeastOneGroup g( SL( "at_least_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); cmd.parse(); CHECK_CONDITION( timeout.isDefined() == true ) CHECK_CONDITION( timeout.value() == SL( "100" ) ) CHECK_CONDITION( port.isDefined() == true ) CHECK_CONDITION( port.value() == SL( "4545" ) ) CHECK_CONDITION( host.isDefined() == false ) CHECK_CONDITION( g.isDefined() == true ) } TEST( GroupCase, TestAtLeasOneFailed ) { const int argc = 1; const CHAR * argv[ argc ] = { SL( "program.exe" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AtLeastOneGroup g( SL( "at_least_one" ) ); g.setRequired( true ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, TestAtLeasOneWithRequiredFailed ) { const int argc = 3; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ) }; CmdLine cmd( argc, argv ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true, true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AtLeastOneGroup g( SL( "at_least_one" ) ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, GroupsIsOk ) { const int argc = 9; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ), SL( "-h" ), SL( "localhost" ), SL( "-s" ), SL( "db" ) }; CmdLine cmd( argc, argv ); Arg store( Char( SL( 's' ) ), SL( "store" ), true ); Arg file( Char( SL( 'f' ) ), SL( "file" ), true ); OnlyOneGroup onlyOne( SL( "only_one" ) ); onlyOne.addArg( store ); onlyOne.addArg( file ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AllOfGroup g( SL( "all_of" ) ); g.setRequired( true ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); g.addArg( onlyOne ); cmd.addArg( g ); cmd.parse(); CHECK_CONDITION( timeout.isDefined() == true ) CHECK_CONDITION( timeout.value() == SL( "100" ) ) CHECK_CONDITION( port.isDefined() == true ) CHECK_CONDITION( port.value() == SL( "4545" ) ) CHECK_CONDITION( host.isDefined() == true ) CHECK_CONDITION( host.value() == SL( "localhost" ) ) CHECK_CONDITION( store.isDefined() == true ) CHECK_CONDITION( store.value() == SL( "db" ) ) CHECK_CONDITION( file.isDefined() == false ) CHECK_CONDITION( g.isDefined() == true ) } TEST( GroupCase, GroupsFailed ) { const int argc = 11; const CHAR * argv[ argc ] = { SL( "program.exe" ), SL( "-t" ), SL( "100" ), SL( "-p" ), SL( "4545" ), SL( "-h" ), SL( "localhost" ), SL( "-s" ), SL( "db" ), SL( "-f" ), SL( "out.txt" ) }; CmdLine cmd( argc, argv ); Arg store( Char( SL( 's' ) ), SL( "store" ), true ); Arg file( Char( SL( 'f' ) ), SL( "file" ), true ); OnlyOneGroup onlyOne( SL( "only_one" ) ); onlyOne.addArg( store ); onlyOne.addArg( file ); Arg timeout( SL( 't' ), String( SL( "timeout" ) ), true ); Arg port( SL( 'p' ), String( SL( "port" ) ), true ); Arg host( SL( 'h' ), String( SL( "host" ) ), true ); AllOfGroup g( SL( "all_of" ) ); g.setRequired( true ); g.addArg( timeout ); g.addArg( port ); g.addArg( host ); g.addArg( onlyOne ); cmd.addArg( g ); CHECK_THROW( cmd.parse(), BaseException ) } TEST( GroupCase, GroupsStuff ) { OnlyOneGroup one( SL( "only_one" ) ); const GroupIface & g = one; CHECK_CONDITION( !g.isWithValue() ) CHECK_CONDITION( g.flag().empty() ) CHECK_CONDITION( g.argumentName().empty() ) CHECK_CONDITION( g.valueSpecifier().empty() ) CHECK_CONDITION( g.description().empty() ) CHECK_CONDITION( g.longDescription().empty() ) } int main() { RUN_ALL_TESTS() return 0; } <|endoftext|>
<commit_before>/*! \file file_lock.cpp \brief File-lock synchronization primitive implementation \author Ivan Shynkarenka \date 01.09.2016 \copyright MIT License */ #include "threads/file_lock.h" #include "errors/fatal.h" #include "threads/thread.h" #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) #include <sys/file.h> #include <fcntl.h> #include <unistd.h> #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) #include <windows.h> #undef Yield #endif namespace CppCommon { //! @cond INTERNALS // In case we are on a system with glibc version earlier than 2.20 #ifndef F_OFD_GETLK #define F_OFD_GETLK 36 #define F_OFD_SETLK 37 #define F_OFD_SETLKW 38 #endif class FileLock::Impl { public: #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) Impl() : _file(0) {} #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) Impl() : _file(nullptr) {} #endif ~Impl() { try { Reset(); } catch (const SystemException& ex) { fatality(SystemException(ex.string())); } } const Path& path() const noexcept { return _path; } void Assign(const Path& path) { // Reset the previous file-lock Reset(); _path = path; #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) _file = open(_path.string().c_str(), O_CREAT | O_RDWR, 0644); if (_file < 0) throwex FileSystemException("Cannot create or open file-lock file!").Attach(path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) // Retries in CreateFile, see http://support.microsoft.com/kb/316609 const std::wstring wpath = _path.wstring(); const int attempts = 100; const int sleep = 100; for (int attempt = 0; attempt < attempts; ++attempt) { _file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE, nullptr); if (_file == INVALID_HANDLE_VALUE) { Sleep(sleep); continue; } return; } throwex FileSystemException("Cannot create or open file-lock file!").Attach(path); #endif } void Reset() { if (!_file) return; #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = close(_file); if (result != 0) fatality(FileSystemException("Cannot close the file-lock descriptor!").Attach(_path)); _file = 0; // Remove the file-lock file unlink(_path.string().c_str()); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) if (!CloseHandle(_file)) fatality(FileSystemException("Cannot close the file-lock handle!").Attach(_path)); _file = nullptr; #endif } bool TryLockRead() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLK, &lock); if (result == -1) { if (errno == EAGAIN) return false; else throwex FileSystemException("Failed to try lock for read!").Attach(_path); } else return true; #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_SH | LOCK_NB); if (result != 0) { if (errno == EWOULDBLOCK) return false; else throwex FileSystemException("Failed to try lock for read!").Attach(_path); } else return true; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); return LockFileEx(_file, LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) != 0; #endif } bool TryLockWrite() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLK, &lock); if (result == -1) { if (errno == EAGAIN) return false; else throwex FileSystemException("Failed to try lock for write!").Attach(_path); } else return true; #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_EX | LOCK_NB); if (result != 0) { if (errno == EWOULDBLOCK) return false; else throwex FileSystemException("Failed to try lock for write!").Attach(_path); } else return true; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); return LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) != 0; #endif } void LockRead() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLKW, &lock); if (result == -1) throwex FileSystemException("Failed to lock for read!").Attach(_path); #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_SH); if (result != 0) throwex FileSystemException("Failed to lock for read!").Attach(_path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!LockFileEx(_file, 0, 0, MAXDWORD, MAXDWORD, &overlapped)) throwex FileSystemException("Failed to lock for read!").Attach(_path); #endif } void LockWrite() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLKW, &lock); if (result == -1) throwex FileSystemException("Failed to lock for write!").Attach(_path); #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_EX); if (result != 0) throwex FileSystemException("Failed to lock for write!").Attach(_path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped)) throwex FileSystemException("Failed to lock for write!").Attach(_path); #endif } void UnlockRead() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLK, &lock); if (result != 0) throwex FileSystemException("Failed to unlock the read lock!").Attach(_path); #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_UN); if (result != 0) throwex FileSystemException("Failed to unlock the read lock!").Attach(_path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped)) throwex FileSystemException("Failed to unlock the read lock!").Attach(_path); #endif } void UnlockWrite() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLK, &lock); if (result != 0) throwex FileSystemException("Failed to unlock the write lock!").Attach(_path); #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_UN); if (result != 0) throwex FileSystemException("Failed to unlock the write lock!").Attach(_path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped)) throwex FileSystemException("Failed to unlock the write lock!").Attach(_path); #endif } private: Path _path; #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int _file; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) HANDLE _file; #endif }; //! @endcond FileLock::FileLock() : _pimpl(std::make_unique<Impl>()) { } FileLock::FileLock(const Path& path) : FileLock() { Assign(path); } FileLock::~FileLock() { } FileLock& FileLock::operator=(const Path& path) { Assign(path); return *this; } const Path& FileLock::path() const noexcept { return _pimpl->path(); } void FileLock::Assign(const Path& path) { _pimpl->Assign(path); } void FileLock::Reset() { _pimpl->Reset(); } bool FileLock::TryLockRead() { return _pimpl->TryLockRead(); } bool FileLock::TryLockWrite() { return _pimpl->TryLockWrite(); } bool FileLock::TryLockReadFor(const Timespan& timespan) { // Calculate a finish timestamp Timestamp finish = NanoTimestamp() + timespan; // Try to acquire read lock at least one time if (TryLockRead()) return true; else { // Try lock or yield for the given timespan while (NanoTimestamp() < finish) { if (TryLockRead()) return true; else Thread::Yield(); } // Failed to acquire read lock return false; } } bool FileLock::TryLockWriteFor(const Timespan& timespan) { // Calculate a finish timestamp Timestamp finish = NanoTimestamp() + timespan; // Try to acquire write lock at least one time if (TryLockWrite()) return true; else { // Try lock or yield for the given timespan while (NanoTimestamp() < finish) { if (TryLockWrite()) return true; else Thread::Yield(); } // Failed to acquire write lock return false; } } void FileLock::LockRead() { _pimpl->LockRead(); } void FileLock::LockWrite() { _pimpl->LockWrite(); } void FileLock::UnlockRead() { _pimpl->UnlockRead(); } void FileLock::UnlockWrite() { _pimpl->UnlockWrite(); } } // namespace CppCommon <commit_msg>More file lock<commit_after>/*! \file file_lock.cpp \brief File-lock synchronization primitive implementation \author Ivan Shynkarenka \date 01.09.2016 \copyright MIT License */ #include "threads/file_lock.h" #include "errors/fatal.h" #include "threads/thread.h" #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) #include <sys/file.h> #include <fcntl.h> #include <unistd.h> #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) #include <windows.h> #undef Yield #endif namespace CppCommon { //! @cond INTERNALS // In case we are on a system with glibc version earlier than 2.20 #ifndef F_OFD_GETLK #define F_OFD_GETLK 36 #define F_OFD_SETLK 37 #define F_OFD_SETLKW 38 #endif class FileLock::Impl { public: #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) Impl() : _file(0) {} #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) Impl() : _file(nullptr) {} #endif ~Impl() { try { Reset(); } catch (const SystemException& ex) { fatality(SystemException(ex.string())); } } const Path& path() const noexcept { return _path; } void Assign(const Path& path) { // Reset the previous file-lock Reset(); _path = path; #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) _file = open(_path.string().c_str(), O_CREAT | O_RDWR, 0644); if (_file < 0) throwex FileSystemException("Cannot create or open file-lock file!").Attach(path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) // Retries in CreateFile, see http://support.microsoft.com/kb/316609 const std::wstring wpath = _path.wstring(); const int attempts = 1000; const int sleep = 100; for (int attempt = 0; attempt < attempts; ++attempt) { _file = CreateFileW(wpath.c_str(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_ALWAYS, FILE_ATTRIBUTE_HIDDEN | FILE_FLAG_DELETE_ON_CLOSE, nullptr); if (_file == INVALID_HANDLE_VALUE) { Sleep(sleep); continue; } return; } throwex FileSystemException("Cannot create or open file-lock file!").Attach(path); #endif } void Reset() { if (!_file) return; #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = close(_file); if (result != 0) fatality(FileSystemException("Cannot close the file-lock descriptor!").Attach(_path)); _file = 0; // Remove the file-lock file unlink(_path.string().c_str()); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) if (!CloseHandle(_file)) fatality(FileSystemException("Cannot close the file-lock handle!").Attach(_path)); _file = nullptr; #endif } bool TryLockRead() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLK, &lock); if (result == -1) { if (errno == EAGAIN) return false; else throwex FileSystemException("Failed to try lock for read!").Attach(_path); } else return true; #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_SH | LOCK_NB); if (result != 0) { if (errno == EWOULDBLOCK) return false; else throwex FileSystemException("Failed to try lock for read!").Attach(_path); } else return true; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); return LockFileEx(_file, LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) != 0; #endif } bool TryLockWrite() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLK, &lock); if (result == -1) { if (errno == EAGAIN) return false; else throwex FileSystemException("Failed to try lock for write!").Attach(_path); } else return true; #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_EX | LOCK_NB); if (result != 0) { if (errno == EWOULDBLOCK) return false; else throwex FileSystemException("Failed to try lock for write!").Attach(_path); } else return true; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); return LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY, 0, MAXDWORD, MAXDWORD, &overlapped) != 0; #endif } void LockRead() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_RDLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLKW, &lock); if (result == -1) throwex FileSystemException("Failed to lock for read!").Attach(_path); #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_SH); if (result != 0) throwex FileSystemException("Failed to lock for read!").Attach(_path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!LockFileEx(_file, 0, 0, MAXDWORD, MAXDWORD, &overlapped)) throwex FileSystemException("Failed to lock for read!").Attach(_path); #endif } void LockWrite() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_WRLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLKW, &lock); if (result == -1) throwex FileSystemException("Failed to lock for write!").Attach(_path); #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_EX); if (result != 0) throwex FileSystemException("Failed to lock for write!").Attach(_path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!LockFileEx(_file, LOCKFILE_EXCLUSIVE_LOCK, 0, MAXDWORD, MAXDWORD, &overlapped)) throwex FileSystemException("Failed to lock for write!").Attach(_path); #endif } void UnlockRead() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLK, &lock); if (result != 0) throwex FileSystemException("Failed to unlock the read lock!").Attach(_path); #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_UN); if (result != 0) throwex FileSystemException("Failed to unlock the read lock!").Attach(_path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped)) throwex FileSystemException("Failed to unlock the read lock!").Attach(_path); #endif } void UnlockWrite() { #if defined(linux) || defined(__linux) || defined(__linux__) struct flock lock; lock.l_type = F_UNLCK; lock.l_whence = SEEK_SET; lock.l_start = 0; lock.l_len = 0; lock.l_pid = 0; int result = fcntl(_file, F_OFD_SETLK, &lock); if (result != 0) throwex FileSystemException("Failed to unlock the write lock!").Attach(_path); #elif (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int result = flock(_file, LOCK_UN); if (result != 0) throwex FileSystemException("Failed to unlock the write lock!").Attach(_path); #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) OVERLAPPED overlapped; ZeroMemory(&overlapped, sizeof(OVERLAPPED)); if (!UnlockFileEx(_file, 0, MAXDWORD, MAXDWORD, &overlapped)) throwex FileSystemException("Failed to unlock the write lock!").Attach(_path); #endif } private: Path _path; #if (defined(unix) || defined(__unix) || defined(__unix__) || defined(__APPLE__)) && !defined(__CYGWIN__) int _file; #elif defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) HANDLE _file; #endif }; //! @endcond FileLock::FileLock() : _pimpl(std::make_unique<Impl>()) { } FileLock::FileLock(const Path& path) : FileLock() { Assign(path); } FileLock::~FileLock() { } FileLock& FileLock::operator=(const Path& path) { Assign(path); return *this; } const Path& FileLock::path() const noexcept { return _pimpl->path(); } void FileLock::Assign(const Path& path) { _pimpl->Assign(path); } void FileLock::Reset() { _pimpl->Reset(); } bool FileLock::TryLockRead() { return _pimpl->TryLockRead(); } bool FileLock::TryLockWrite() { return _pimpl->TryLockWrite(); } bool FileLock::TryLockReadFor(const Timespan& timespan) { // Calculate a finish timestamp Timestamp finish = NanoTimestamp() + timespan; // Try to acquire read lock at least one time if (TryLockRead()) return true; else { // Try lock or yield for the given timespan while (NanoTimestamp() < finish) { if (TryLockRead()) return true; else Thread::Yield(); } // Failed to acquire read lock return false; } } bool FileLock::TryLockWriteFor(const Timespan& timespan) { // Calculate a finish timestamp Timestamp finish = NanoTimestamp() + timespan; // Try to acquire write lock at least one time if (TryLockWrite()) return true; else { // Try lock or yield for the given timespan while (NanoTimestamp() < finish) { if (TryLockWrite()) return true; else Thread::Yield(); } // Failed to acquire write lock return false; } } void FileLock::LockRead() { _pimpl->LockRead(); } void FileLock::LockWrite() { _pimpl->LockWrite(); } void FileLock::UnlockRead() { _pimpl->UnlockRead(); } void FileLock::UnlockWrite() { _pimpl->UnlockWrite(); } } // namespace CppCommon <|endoftext|>
<commit_before>//===- FileUpdate.cpp - Conditionally update a file -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FileUpdate is a utility for conditionally updating a file from its input // based on whether the input differs from the output. It is used to avoid // unnecessary modifications in a build system. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/Signals.h" using namespace llvm; static cl::opt<bool> Quiet("quiet", cl::desc("Don't print unnecessary status information"), cl::init(false)); static cl::opt<std::string> InputFilename("input-file", cl::desc("Input file (defaults to stdin)"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> OutputFilename(cl::Positional, cl::desc("<output-file>"), cl::Required); int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); if (OutputFilename == "-") { errs() << argv[0] << ": error: Can't update standard output\n"; return 1; } // Get the input data. std::string ErrorStr; MemoryBuffer *In = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr); if (In == 0) { errs() << argv[0] << ": error: Unable to get input '" << InputFilename << "': " << ErrorStr << '\n'; return 1; } // Get the output data. MemoryBuffer *Out = MemoryBuffer::getFile(OutputFilename.c_str(), &ErrorStr); // If the output exists and the contents match, we are done. if (Out && In->getBufferSize() == Out->getBufferSize() && memcmp(In->getBufferStart(), Out->getBufferStart(), Out->getBufferSize()) == 0) { if (!Quiet) errs() << argv[0] << ": Not updating '" << OutputFilename << "', contents match input.\n"; return 0; } delete Out; // Otherwise, overwrite the output. if (!Quiet) errs() << argv[0] << ": Updating '" << OutputFilename << "', contents changed.\n"; tool_output_file OutStream(OutputFilename.c_str(), ErrorStr, raw_fd_ostream::F_Binary); if (!ErrorStr.empty()) { errs() << argv[0] << ": Unable to write output '" << OutputFilename << "': " << ErrorStr << '\n'; return 1; } OutStream.os().write(In->getBufferStart(), In->getBufferSize()); // Declare success. OutStream.keep(); return 0; } <commit_msg>Missed FileUpdate because CMake doesn't build it yet :(.<commit_after>//===- FileUpdate.cpp - Conditionally update a file -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FileUpdate is a utility for conditionally updating a file from its input // based on whether the input differs from the output. It is used to avoid // unnecessary modifications in a build system. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/Signals.h" #include "llvm/Support/system_error.h" using namespace llvm; static cl::opt<bool> Quiet("quiet", cl::desc("Don't print unnecessary status information"), cl::init(false)); static cl::opt<std::string> InputFilename("input-file", cl::desc("Input file (defaults to stdin)"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> OutputFilename(cl::Positional, cl::desc("<output-file>"), cl::Required); int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); if (OutputFilename == "-") { errs() << argv[0] << ": error: Can't update standard output\n"; return 1; } // Get the input data. error_code ec; MemoryBuffer *In = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), ec); if (In == 0) { errs() << argv[0] << ": error: Unable to get input '" << InputFilename << "': " << ec.message() << '\n'; return 1; } // Get the output data. MemoryBuffer *Out = MemoryBuffer::getFile(OutputFilename.c_str(), ec); // If the output exists and the contents match, we are done. if (Out && In->getBufferSize() == Out->getBufferSize() && memcmp(In->getBufferStart(), Out->getBufferStart(), Out->getBufferSize()) == 0) { if (!Quiet) errs() << argv[0] << ": Not updating '" << OutputFilename << "', contents match input.\n"; return 0; } delete Out; // Otherwise, overwrite the output. if (!Quiet) errs() << argv[0] << ": Updating '" << OutputFilename << "', contents changed.\n"; std::string ErrorStr; tool_output_file OutStream(OutputFilename.c_str(), ErrorStr, raw_fd_ostream::F_Binary); if (!ErrorStr.empty()) { errs() << argv[0] << ": Unable to write output '" << OutputFilename << "': " << ErrorStr << '\n'; return 1; } OutStream.os().write(In->getBufferStart(), In->getBufferSize()); // Declare success. OutStream.keep(); return 0; } <|endoftext|>
<commit_before>/* 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/. */ /* Authors: Michael Berg <michael.berg@zalf.de> Maintainers: Currently maintained by the authors. This file is part of the MONICA model. Copyright (C) Leibniz Centre for Agricultural Landscape Research (ZALF) */ #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <tuple> #include "zhelpers.hpp" #include "json11/json11.hpp" #include "tools/zmq-helper.h" #include "tools/helper.h" #include "db/abstract-db-connections.h" #include "tools/debug.h" #include "../run/run-monica.h" #include "../run/run-monica-zmq.h" #include "../io/database-io.h" #include "../core/monica.h" #include "tools/json11-helper.h" #include "climate/climate-file-io.h" #include "soil/conversion.h" #include "env-json-from-json-config.h" #include "tools/algorithms.h" #include "../io/csv-format.h" #include "monica-zmq-defaults.h" using namespace std; using namespace Monica; using namespace Tools; using namespace json11; string appName = "monica-zmq-run"; string version = "2.0.0-beta"; int main(int argc, char** argv) { setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); //use a possibly non-default db-connections.ini //Db::dbConnectionParameters("db-connections.ini"); bool debug = false, debugSet = false; string startDate, endDate; string pathToOutput; string pathToOutputFile; bool writeOutputFile = false; string address = defaultInputAddress; int port = defaultInputPort; string pathToSimJson = "./sim.json", crop, site, climate; string dailyOutputs; bool useLeapYears = true, useLeapYearsSet = false; auto printHelp = [=]() { cout << appName << endl << " [-d | --debug] ... show debug outputs" << endl << " [[-a | --address] (PROXY-)ADDRESS (default: " << address << ")] ... connect client to give IP address" << endl << " [[-p | --port] (PROXY-)PORT (default: " << port << ")] ... run server/connect client on/to given port" << endl << " [[-sd | --start-date] ISO-DATE (default: start of given climate data)] ... date in iso-date-format yyyy-mm-dd" << endl << " [[-ed | --end-date] ISO-DATE (default: end of given climate data)] ... date in iso-date-format yyyy-mm-dd" << endl << " [[-nly | --no-leap-years]] ... skip 29th of february on leap years in climate data" << endl << " [-w | --write-output-files] ... write MONICA output files (rmout, smout)" << endl << " [[-op | --path-to-output] DIRECTORY (default: .)] ... path to output directory" << endl << " [[-o | --path-to-output-file] FILE (default: ./rmout.csv)] ... path to output file" << endl << " [[-do | --daily-outputs] [LIST] (default: value of key 'sim.json:output.daily')] ... list of daily output elements" << endl << " [[-c | --path-to-crop] FILE (default: ./crop.json)] ... path to crop.json file" << endl << " [[-s | --path-to-site] FILE (default: ./site.json)] ... path to site.json file" << endl << " [[-w | --path-to-climate] FILE (default: ./climate.csv)] ... path to climate.csv" << endl << " [-h | --help] ... this help output" << endl << " [-v | --version] ... outputs MONICA version" << endl << " path-to-sim-json ... path to sim.json file" << endl; }; zmq::context_t context(1); if(argc > 1) { for(auto i = 1; i < argc; i++) { string arg = argv[i]; if(arg == "-d" || arg == "--debug") debug = debugSet = true; else if((arg == "-a" || arg == "--address") && i + 1 < argc) address = argv[++i]; else if((arg == "-p" || arg == "--port") && i + 1 < argc) port = stoi(argv[++i]); else if((arg == "-sd" || arg == "--start-date") && i+1 < argc) startDate = argv[++i]; else if((arg == "-ed" || arg == "--end-date") && i+1 < argc) endDate = argv[++i]; else if(arg == "-nly" || arg == "--no-leap-years") useLeapYears = false, useLeapYearsSet = true; else if((arg == "-op" || arg == "--path-to-output") && i+1 < argc) pathToOutput = argv[++i]; else if((arg == "-o" || arg == "--path-to-output-file") && i + 1 < argc) pathToOutputFile = argv[++i]; else if((arg == "-do" || arg == "--daily-outputs") && i + 1 < argc) dailyOutputs = argv[++i]; else if((arg == "-c" || arg == "--path-to-crop") && i+1 < argc) crop = argv[++i]; else if((arg == "-s" || arg == "--path-to-site") && i+1 < argc) site = argv[++i]; else if((arg == "-w" || arg == "--path-to-climate") && i+1 < argc) climate = argv[++i]; else if(arg == "-h" || arg == "--help") printHelp(), exit(0); else if(arg == "-v" || arg == "--version") cout << appName << " version " << version << endl, exit(0); else pathToSimJson = argv[i]; } string pathOfSimJson, simFileName; tie(pathOfSimJson, simFileName) = splitPathToFile(pathToSimJson); auto simj = readAndParseJsonFile(pathToSimJson); if(simj.failure()) for(auto e : simj.errors) cerr << e << endl; auto simm = simj.result.object_items(); if(!startDate.empty()) simm["start-date"] = startDate; if(!endDate.empty()) simm["end-date"] = endDate; if(debugSet) simm["debug?"] = debug; if(!pathToOutput.empty()) simm["path-to-output"] = pathToOutput; //if(!pathToOutputFile.empty()) // simm["path-to-output-file"] = pathToOutputFile; simm["sim.json"] = pathToSimJson; if(!crop.empty()) simm["crop.json"] = crop; auto pathToCropJson = simm["crop.json"].string_value(); if(!isAbsolutePath(pathToCropJson)) simm["crop.json"] = pathOfSimJson + pathToCropJson; if(!site.empty()) simm["site.json"] = site; auto pathToSiteJson = simm["site.json"].string_value(); if(!isAbsolutePath(pathToSiteJson)) simm["site.json"] = pathOfSimJson + pathToSiteJson; if(!climate.empty()) simm["climate.csv"] = climate; auto pathToClimateCSV = simm["climate.csv"].string_value(); if(!isAbsolutePath(pathToClimateCSV)) simm["climate.csv"] = pathOfSimJson + pathToClimateCSV; if(useLeapYearsSet) simm["use-leap-years"] = useLeapYears; if(!dailyOutputs.empty()) { auto outm = simm["output"].object_items(); string err; J11Array daily; string trimmedDailyOutputs = trim(dailyOutputs); if(trimmedDailyOutputs.front() == '[') trimmedDailyOutputs.erase(0, 1); if(trimmedDailyOutputs.back() == ']') trimmedDailyOutputs.pop_back(); for(auto el : splitString(trimmedDailyOutputs, ",", make_pair("[", "]"))) { if(trim(el).at(0) == '[') { J11Array a; auto es = splitString(trim(el, "[]"), ","); if(es.size() >= 1) a.push_back(es.at(0)); if(es.size() >= 3) a.push_back(stoi(es.at(1))), a.push_back(stoi(es.at(2))); if(es.size() >= 4) a.push_back(es.at(3)); daily.push_back(a); } else daily.push_back(el); } outm["daily"] = daily; simm["output"] = outm; } map<string, string> ps; ps["sim-json-str"] = json11::Json(simm).dump(); ps["crop-json-str"] = printPossibleErrors(readFile(simm["crop.json"].string_value()), activateDebug); ps["site-json-str"] = printPossibleErrors(readFile(simm["site.json"].string_value()), activateDebug); //ps["path-to-climate-csv"] = simm["climate.csv"].string_value(); auto env = createEnvJsonFromJsonConfigFiles(ps); activateDebug = env["debugMode"].bool_value(); if(activateDebug) cout << "starting MONICA with JSON input files" << endl; Output output; Json res = sendZmqRequestMonicaFull(&context, string("tcp://") + address + ":" + to_string(port), env); addResultMessageToOutput(res.object_items(), output); if(pathToOutputFile.empty() && simm["output"]["write-file?"].bool_value()) pathToOutputFile = fixSystemSeparator(simm["path-to-output"].string_value() + "/" + simm["output"]["file-name"].string_value()); writeOutputFile = !pathToOutputFile.empty(); ofstream fout; if(writeOutputFile) { string path, filename; tie(path, filename) = splitPathToFile(pathToOutputFile); ensureDirExists(path); fout.open(pathToOutputFile); if(fout.fail()) { cerr << "Error while opening output file \"" << pathToOutputFile << "\"" << endl; writeOutputFile = false; } } ostream& out = writeOutputFile ? fout : cout; string csvSep = simm["output"]["csv-options"]["csv-separator"].string_value(); bool includeHeaderRow = simm["output"]["csv-options"]["include-header-row"].bool_value(); bool includeUnitsRow = simm["output"]["csv-options"]["include-units-row"].bool_value(); auto toOIdVector = [](const Json& a) { vector<OId> oids; for(auto j : a.array_items()) oids.push_back(OId(j)); return oids; }; if(!output.daily.empty()) { writeOutputHeaderRows(out, toOIdVector(env["dailyOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow, false); writeOutput(out, toOIdVector(env["dailyOutputIds"]), output.daily, csvSep, includeHeaderRow, includeUnitsRow); } if(!output.monthly.empty()) { out << endl; writeOutputHeaderRows(out, toOIdVector(env["monthlyOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow); for(auto& p : output.monthly) writeOutput(out, toOIdVector(env["monthlyOutputIds"]), p.second, csvSep, includeHeaderRow, includeUnitsRow); } if(!output.yearly.empty()) { out << endl; writeOutputHeaderRows(out, toOIdVector(env["yearlyOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow); writeOutput(out, toOIdVector(env["yearlyOutputIds"]), output.yearly, csvSep, includeHeaderRow, includeUnitsRow); } if(!output.at.empty()) { for(auto& p : env["atOutputIds"].object_items()) { out << endl; auto ci = output.at.find(p.first); if(ci != output.at.end()) { out << p.first << endl; writeOutputHeaderRows(out, toOIdVector(p.second), csvSep, includeHeaderRow, includeUnitsRow); writeOutput(out, toOIdVector(p.second), ci->second, csvSep, includeHeaderRow, includeUnitsRow); } } } auto makeWriteOutputCompatible = [](const J11Array& a) { vector<J11Array> vs; for(auto j : a) vs.push_back({j}); return vs; }; if(!output.crop.empty()) { out << endl; writeOutputHeaderRows(out, toOIdVector(env["cropOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow); for(auto& p : output.crop) writeOutput(out, toOIdVector(env["cropOutputIds"]), makeWriteOutputCompatible(p.second), csvSep, includeHeaderRow, includeUnitsRow); } if(!output.run.empty()) { out << endl; writeOutputHeaderRows(out, toOIdVector(env["runOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow); writeOutput(out, toOIdVector(env["runOutputIds"]), makeWriteOutputCompatible(output.run), csvSep, includeHeaderRow, includeUnitsRow); } if(writeOutputFile) fout.close(); if(activateDebug) cout << "finished MONICA" << endl; } else printHelp(); return 0; } <commit_msg>forgot to update code during refactoring<commit_after>/* 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/. */ /* Authors: Michael Berg <michael.berg@zalf.de> Maintainers: Currently maintained by the authors. This file is part of the MONICA model. Copyright (C) Leibniz Centre for Agricultural Landscape Research (ZALF) */ #include <stdio.h> #include <iostream> #include <fstream> #include <string> #include <tuple> #include "zhelpers.hpp" #include "json11/json11.hpp" #include "tools/zmq-helper.h" #include "tools/helper.h" #include "db/abstract-db-connections.h" #include "tools/debug.h" #include "../run/run-monica.h" #include "../run/run-monica-zmq.h" #include "../io/database-io.h" #include "../core/monica.h" #include "tools/json11-helper.h" #include "climate/climate-file-io.h" #include "soil/conversion.h" #include "env-json-from-json-config.h" #include "tools/algorithms.h" #include "../io/csv-format.h" #include "monica-zmq-defaults.h" using namespace std; using namespace Monica; using namespace Tools; using namespace json11; string appName = "monica-zmq-run"; string version = "2.0.0-beta"; int main(int argc, char** argv) { setlocale(LC_ALL, ""); setlocale(LC_NUMERIC, "C"); //use a possibly non-default db-connections.ini //Db::dbConnectionParameters("db-connections.ini"); bool debug = false, debugSet = false; string startDate, endDate; string pathToOutput; string pathToOutputFile; bool writeOutputFile = false; string address = defaultInputAddress; int port = defaultInputPort; string pathToSimJson = "./sim.json", crop, site, climate; string dailyOutputs; bool useLeapYears = true, useLeapYearsSet = false; auto printHelp = [=]() { cout << appName << endl << " [-d | --debug] ... show debug outputs" << endl << " [[-a | --address] (PROXY-)ADDRESS (default: " << address << ")] ... connect client to give IP address" << endl << " [[-p | --port] (PROXY-)PORT (default: " << port << ")] ... run server/connect client on/to given port" << endl << " [[-sd | --start-date] ISO-DATE (default: start of given climate data)] ... date in iso-date-format yyyy-mm-dd" << endl << " [[-ed | --end-date] ISO-DATE (default: end of given climate data)] ... date in iso-date-format yyyy-mm-dd" << endl << " [[-nly | --no-leap-years]] ... skip 29th of february on leap years in climate data" << endl << " [-w | --write-output-files] ... write MONICA output files (rmout, smout)" << endl << " [[-op | --path-to-output] DIRECTORY (default: .)] ... path to output directory" << endl << " [[-o | --path-to-output-file] FILE (default: ./rmout.csv)] ... path to output file" << endl << " [[-do | --daily-outputs] [LIST] (default: value of key 'sim.json:output.daily')] ... list of daily output elements" << endl << " [[-c | --path-to-crop] FILE (default: ./crop.json)] ... path to crop.json file" << endl << " [[-s | --path-to-site] FILE (default: ./site.json)] ... path to site.json file" << endl << " [[-w | --path-to-climate] FILE (default: ./climate.csv)] ... path to climate.csv" << endl << " [-h | --help] ... this help output" << endl << " [-v | --version] ... outputs MONICA version" << endl << " path-to-sim-json ... path to sim.json file" << endl; }; zmq::context_t context(1); if(argc > 1) { for(auto i = 1; i < argc; i++) { string arg = argv[i]; if(arg == "-d" || arg == "--debug") debug = debugSet = true; else if((arg == "-a" || arg == "--address") && i + 1 < argc) address = argv[++i]; else if((arg == "-p" || arg == "--port") && i + 1 < argc) port = stoi(argv[++i]); else if((arg == "-sd" || arg == "--start-date") && i+1 < argc) startDate = argv[++i]; else if((arg == "-ed" || arg == "--end-date") && i+1 < argc) endDate = argv[++i]; else if(arg == "-nly" || arg == "--no-leap-years") useLeapYears = false, useLeapYearsSet = true; else if((arg == "-op" || arg == "--path-to-output") && i+1 < argc) pathToOutput = argv[++i]; else if((arg == "-o" || arg == "--path-to-output-file") && i + 1 < argc) pathToOutputFile = argv[++i]; else if((arg == "-do" || arg == "--daily-outputs") && i + 1 < argc) dailyOutputs = argv[++i]; else if((arg == "-c" || arg == "--path-to-crop") && i+1 < argc) crop = argv[++i]; else if((arg == "-s" || arg == "--path-to-site") && i+1 < argc) site = argv[++i]; else if((arg == "-w" || arg == "--path-to-climate") && i+1 < argc) climate = argv[++i]; else if(arg == "-h" || arg == "--help") printHelp(), exit(0); else if(arg == "-v" || arg == "--version") cout << appName << " version " << version << endl, exit(0); else pathToSimJson = argv[i]; } string pathOfSimJson, simFileName; tie(pathOfSimJson, simFileName) = splitPathToFile(pathToSimJson); auto simj = readAndParseJsonFile(pathToSimJson); if(simj.failure()) for(auto e : simj.errors) cerr << e << endl; auto simm = simj.result.object_items(); if(!startDate.empty()) simm["start-date"] = startDate; if(!endDate.empty()) simm["end-date"] = endDate; if(debugSet) simm["debug?"] = debug; if(!pathToOutput.empty()) simm["path-to-output"] = pathToOutput; //if(!pathToOutputFile.empty()) // simm["path-to-output-file"] = pathToOutputFile; simm["sim.json"] = pathToSimJson; if(!crop.empty()) simm["crop.json"] = crop; auto pathToCropJson = simm["crop.json"].string_value(); if(!isAbsolutePath(pathToCropJson)) simm["crop.json"] = pathOfSimJson + pathToCropJson; if(!site.empty()) simm["site.json"] = site; auto pathToSiteJson = simm["site.json"].string_value(); if(!isAbsolutePath(pathToSiteJson)) simm["site.json"] = pathOfSimJson + pathToSiteJson; if(!climate.empty()) simm["climate.csv"] = climate; auto pathToClimateCSV = simm["climate.csv"].string_value(); if(!isAbsolutePath(pathToClimateCSV)) simm["climate.csv"] = pathOfSimJson + pathToClimateCSV; if(useLeapYearsSet) simm["use-leap-years"] = useLeapYears; if(!dailyOutputs.empty()) { auto outm = simm["output"].object_items(); string err; J11Array daily; string trimmedDailyOutputs = trim(dailyOutputs); if(trimmedDailyOutputs.front() == '[') trimmedDailyOutputs.erase(0, 1); if(trimmedDailyOutputs.back() == ']') trimmedDailyOutputs.pop_back(); for(auto el : splitString(trimmedDailyOutputs, ",", make_pair("[", "]"))) { if(trim(el).at(0) == '[') { J11Array a; auto es = splitString(trim(el, "[]"), ","); if(es.size() >= 1) a.push_back(es.at(0)); if(es.size() >= 3) a.push_back(stoi(es.at(1))), a.push_back(stoi(es.at(2))); if(es.size() >= 4) a.push_back(es.at(3)); daily.push_back(a); } else daily.push_back(el); } outm["daily"] = daily; simm["output"] = outm; } map<string, string> ps; ps["sim-json-str"] = json11::Json(simm).dump(); ps["crop-json-str"] = printPossibleErrors(readFile(simm["crop.json"].string_value()), activateDebug); ps["site-json-str"] = printPossibleErrors(readFile(simm["site.json"].string_value()), activateDebug); //ps["path-to-climate-csv"] = simm["climate.csv"].string_value(); auto env = createEnvJsonFromJsonConfigFiles(ps); activateDebug = env["debugMode"].bool_value(); if(activateDebug) cout << "starting MONICA with JSON input files" << endl; Output output; Json res = sendZmqRequestMonicaFull(&context, string("tcp://") + address + ":" + to_string(port), env); addResultMessageToOutput(res.object_items(), output); if(pathToOutputFile.empty() && simm["output"]["write-file?"].bool_value()) pathToOutputFile = fixSystemSeparator(simm["path-to-output"].string_value() + "/" + simm["output"]["file-name"].string_value()); writeOutputFile = !pathToOutputFile.empty(); ofstream fout; if(writeOutputFile) { string path, filename; tie(path, filename) = splitPathToFile(pathToOutputFile); ensureDirExists(path); fout.open(pathToOutputFile); if(fout.fail()) { cerr << "Error while opening output file \"" << pathToOutputFile << "\"" << endl; writeOutputFile = false; } } ostream& out = writeOutputFile ? fout : cout; string csvSep = simm["output"]["csv-options"]["csv-separator"].string_value(); bool includeHeaderRow = simm["output"]["csv-options"]["include-header-row"].bool_value(); bool includeUnitsRow = simm["output"]["csv-options"]["include-units-row"].bool_value(); auto toOIdVector = [](const Json& a) { vector<OId> oids; for(auto j : a.array_items()) oids.push_back(OId(j)); return oids; }; if(!output.daily.empty()) { writeOutputHeaderRows(out, toOIdVector(env["dailyOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow, false); writeOutput(out, toOIdVector(env["dailyOutputIds"]), output.daily, csvSep); } if(!output.monthly.empty()) { out << endl; writeOutputHeaderRows(out, toOIdVector(env["monthlyOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow); for(auto& p : output.monthly) writeOutput(out, toOIdVector(env["monthlyOutputIds"]), p.second, csvSep); } if(!output.yearly.empty()) { out << endl; writeOutputHeaderRows(out, toOIdVector(env["yearlyOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow); writeOutput(out, toOIdVector(env["yearlyOutputIds"]), output.yearly, csvSep); } if(!output.at.empty()) { for(auto& p : env["atOutputIds"].object_items()) { out << endl; auto ci = output.at.find(p.first); if(ci != output.at.end()) { out << p.first << endl; writeOutputHeaderRows(out, toOIdVector(p.second), csvSep, includeHeaderRow, includeUnitsRow); writeOutput(out, toOIdVector(p.second), ci->second, csvSep); } } } auto makeWriteOutputCompatible = [](const J11Array& a) { vector<J11Array> vs; for(auto j : a) vs.push_back({j}); return vs; }; if(!output.crop.empty()) { out << endl; writeOutputHeaderRows(out, toOIdVector(env["cropOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow); for(auto& p : output.crop) writeOutput(out, toOIdVector(env["cropOutputIds"]), makeWriteOutputCompatible(p.second), csvSep); } if(!output.run.empty()) { out << endl; writeOutputHeaderRows(out, toOIdVector(env["runOutputIds"]), csvSep, includeHeaderRow, includeUnitsRow); writeOutput(out, toOIdVector(env["runOutputIds"]), makeWriteOutputCompatible(output.run), csvSep); } if(writeOutputFile) fout.close(); if(activateDebug) cout << "finished MONICA" << endl; } else printHelp(); return 0; } <|endoftext|>
<commit_before>// This is a personal academic project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "maploader.hpp" MapLoader::MapLoader() { _width = _height = 0; _imageData = nullptr; } MapLoader::~MapLoader() {} std::vector<Uint8> MapLoader::getMap(const std::string& filename) { // Don't need _data member variable. Might have a list of maps instead. SDL_Surface* loadedSurface = IMG_Load(filename.c_str()); if (loadedSurface == NULL) printf("Couldn't load image %s! SDL_image error: %s\n", filename.c_str(), IMG_GetError()); int bpp = loadedSurface->format->BytesPerPixel; _width = loadedSurface->w; _height = loadedSurface->h; for (int y = 0; y < _height; y++) for (int x = 0; x < _width; x++) _data.push_back(((Uint8*)loadedSurface->pixels)[loadedSurface->pitch * y + x * bpp]); SDL_FreeSurface(loadedSurface); return _data; } <commit_msg>map y loading corrected<commit_after>// This is a personal academic project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com #include "maploader.hpp" MapLoader::MapLoader() { _width = _height = 0; _imageData = nullptr; } MapLoader::~MapLoader() {} std::vector<Uint8> MapLoader::getMap(const std::string& filename) { // Don't need _data member variable. Might have a list of maps instead. SDL_Surface* loadedSurface = IMG_Load(filename.c_str()); if (loadedSurface == NULL) printf("Couldn't load image %s! SDL_image error: %s\n", filename.c_str(), IMG_GetError()); int bpp = loadedSurface->format->BytesPerPixel; _width = loadedSurface->w; _height = loadedSurface->h; for (int y = _height - 1; y >= 0; y--) for (int x = 0; x < _width; x++) _data.push_back(((Uint8*)loadedSurface->pixels)[loadedSurface->pitch * y + x * bpp]); SDL_FreeSurface(loadedSurface); return _data; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <stdlib.h> //exit #include <stdio.h> //perror #include <errno.h> //perror #include <sys/types.h> //wait #include <sys/wait.h> //wait #include <unistd.h> //execvp, fork, gethost, getlogin #include <string.h> //strtok #include <vector> #include <fcntl.h> #include <sys/stat.h> using namespace std; //checks for comments and if stuff is after comments, it deletes it void checkcomm(string &str){ size_t comment = str.find("#"); //cout << "THis is pos of comment: " << comment << endl; str[comment] = '\0'; if(comment != string :: npos) str.erase(str.begin()+comment, str.end()); //cout << "This is str: " << str << endl; } void fixSpaces(string &input); void IOredir(char **argv); void forkPipes(char **argv, char **afterPipe); void simpleFork(char **argv); void getPipes(char** argv); int main(){ //get username and hostname char login[100]; if(getlogin_r(login, sizeof(login)-1)){ perror("Error with getlogin_r"); } char host[100]; if(-1 == gethostname(host,sizeof(host)-1)){ perror("Error with gethostname."); } for(int pos=0; pos<30; pos++){ if(host[pos] == '.'){ host[pos] = '\0'; } } //execute while(1){ string input; char buf[1000]; int sdi = dup(0), sdo = dup(1); if(sdi == -1) perror("There was an error with dup"); if(sdo == -1) perror("There was an error with dup"); cout << login << "@" << host << "$ "; //get the input from user getline(cin, input); //check if user pushes enter if(input == "") continue; //checks the spacing fixSpaces(input); //check for comments checkcomm(input); strcpy(buf, input.c_str()); //check if user inputs exit if( input.find("exit") != string::npos ) exit(1); //tokenize the commandline char delim[]= " \t\n"; int size=input.size()+1; char **argv=new char*[size]; int pos=0; argv[pos]=strtok(buf, delim); while(argv[pos] != NULL) { pos++; argv[pos] = strtok(NULL,delim); } //argv[pos]=NULL; //for(unsigned i=0; argv[i] != NULL ; i++) // cout << argv[i] << ' '; IOredir(argv); getPipes(argv); if(dup2(sdi, 0) == -1) perror("There was an error with dup2"); if(dup2(sdo,1) == -1) perror("There was an error with dup2"); delete[] argv; } return 0; } void simpleFork(char **argv, bool BG){ int status = 0; int i = fork(); if(i == -1){ //error check fork perror("There was an error with fork()"); exit(1); } else if(i == 0) { //error check execvp if (-1==execvp(argv[0], argv)) { perror("execvp didn't work correctly"); exit(1); } } //in parent if(! BG){ //error check parent if(wait(&status)==-1){ perror("Error in wait"); exit(1); } } } void getPipes(char** argv){ bool pipeFound = false; //save spots for the beginning arguments and ending arguments char **args = argv; char **nextA = argv; //go through argv and check if pipes are found //if they are found, it goes into function forkpipes for(int i=0; argv[i] != '\0'; i++){ if(strcmp(argv[i], "|") == 0){ pipeFound=true; argv[i] = '\0'; char** beforeA = args; nextA = args + i + 1; forkPipes(beforeA, nextA); break; } } //if pipe isn't found, it goes into the simple fork if(!pipeFound){ bool BG = false; for(int i=0; nextA[i] != '\0'; i++){ if(strcmp(nextA[i], "&") == 0) BG=true; } simpleFork(nextA, BG); } } //execution if the command line has pipes void forkPipes(char **argv, char **afterPipe){ int fd[2]; int pid; //pipe new file descriptors if(pipe(fd) == -1){ perror("Error with pipe."); exit(EXIT_FAILURE); } pid = fork(); if(pid == -1){ perror("There was an error with piping fork."); exit(1); } //in child else if(pid ==0){ //close stdin if(close(fd[0]) == -1){ perror("Error with close in piping."); exit(1); } //save stdout if(dup2(fd[1],1)==-1){ perror("Error with dup2 in piping."); } //execute if(execvp(argv[0], argv) == -1){ perror("There was an error with execvp piping"); exit(1); } else{ exit(0); } } //in parent //save stdin int save=dup(0); if((save== -1)) perror("There was an error with dup."); //close std out if(close(fd[1]) == -1){ perror("Error with close in piping."); exit(1); } //make stdin with dup2 if(dup2(fd[0],0) == -1){ perror("Error with dup2 in piping."); } //make sure the parent waits if(wait(0) == -1) perror("There was an error in wait."); //while(waitpid(-1, &status, 0) >= 0); //check for pipes after we execute getPipes(afterPipe); if(dup2(save,0)==-1){ perror("Error with dup2 in piping."); } } //deals with the IO redirection void IOredir(char *argv[]){ //check if there are any I/O redirection symbols for(int i=0; argv[i] != '\0'; i++){ //check for "<" output redir if(strcmp(argv[i], "<") == 0){ //open the file for read only int file = open(argv[i+1], O_RDONLY); if(file == -1) perror("There was an error with open"); if(dup2(file, 0)==-1) perror("There was an error in dup2"); argv[i] = NULL; break; } //check for ">" input redir else if(strcmp(argv[i], ">") == 0){ //open the file, create or truncate and make write only int file = open(argv[i + 1], O_CREAT|O_TRUNC|O_WRONLY, 0666); if(file ==-1) perror("There was an error with open"); if(dup2(file, 1)== -1) perror("There was an error with dup2"); argv[i] = NULL; break; } //check for appending ">>" input redir else if(!strcmp(argv[i], ">>")){ argv[i] = NULL; //open the file, create or append to old file and make write only int file = open(argv[i+1], O_CREAT|O_WRONLY|O_APPEND, 0666); if(file == -1) perror("There was an error with open"); if(dup2(file,1) == -1) perror("There was an error with dup2"); break; } } } void fixSpaces(string &input){ for(unsigned int i = 0; i < input.size(); i++){ //check if | is right next to word //if | is in the middle of a word if(input[i] == '|' && input[i+1] != ' ' && input[i-1] != ' ' && i !=0){ input.insert(i+1, " "); input.insert(i, " "); } //if | is right before a word else if(input[i] == '|' && input[i+1] != ' ') input.insert(i+1, " "); //if | is right after word else if(input[i] == '|' && input[i-1] != ' ' && i!=0) input.insert(i, " "); //check if < is right next to word //if < is in the middle of a word if(input[i] == '<' && input[i+1] != ' ' && input[i-1] != ' ' && i !=0){ input.insert(i+1, " "); input.insert(i, " "); } //if < is right before a word else if(input[i] == '<' && input[i+1] != ' ') input.insert(i+1, " "); //if < is right after word else if(input[i] == '<' && input[i-1] != ' ' && i!=0) input.insert(i, " "); //check if > is right next to word /*if( input[i-1] != '>' && input[i+1]!= '>'){ //if > is in the middle of a word if(input[i] == '>' && input[i+1] != ' ' && input[i-1] != ' ' && i !=0){ input.insert(i+1, " "); input.insert(i, " "); } //if > is right before a word else if(input[i] == '>' && input[i+1] != ' ') input.insert(i+1, " "); //if > is right after word else if(input[i] == '>' && input[i-1] != ' ' && i!=0) input.insert(i, " "); } //has to be >> if(input[i-1] != '>' && input[i+1] == '>'){ //if >> is in the middle of a word if(input[i] == '>' && input[i+1] == '>' && input[i-1] != '>' && i !=0){ input.insert(i-1, " "); input.insert(i, " "); } //if | is right before a word else if(input[i] == '|' && input[i+1] != ' ') input.insert(i+1, " "); //if | is right after word else if(input[i] == '|' && input[i-1] != ' ' && i!=0) input.insert(i, " "); }*/ } } <commit_msg>^C works<commit_after>#include <iostream> #include <string> #include <stdlib.h> //exit #include <stdio.h> //perror #include <errno.h> //perror #include <sys/types.h> //wait #include <sys/wait.h> //wait #include <unistd.h> //execvp, fork, gethost, getlogin #include <string.h> //strtok #include <vector> #include <fcntl.h> #include <sys/stat.h> #include <signal.h> using namespace std; //checks for comments and if stuff is after comments, it deletes it void checkcomm(string &str){ size_t comment = str.find("#"); //cout << "THis is pos of comment: " << comment << endl; str[comment] = '\0'; if(comment != string :: npos) str.erase(str.begin()+comment, str.end()); //cout << "This is str: " << str << endl; } void fixSpaces(string &input); void IOredir(char **argv); void forkPipes(char **argv, char **afterPipe); void simpleFork(char **argv); void getPipes(char** argv); static void handleC(int sigNum){ //cout << "Caught SIGINT, do nothing now." << endl; //exit(0); cout << endl; } int main(){ struct sigaction oldAction, newAction; newAction.sa_handler = SIG_IGN; sigemptyset (&newAction.sa_mask); newAction.sa_flags = 0; //get username and hostname char login[100]; if(getlogin_r(login, sizeof(login)-1)){ perror("Error with getlogin_r"); } char host[100]; if(-1 == gethostname(host,sizeof(host)-1)){ perror("Error with gethostname."); } for(int pos=0; pos<30; pos++){ if(host[pos] == '.'){ host[pos] = '\0'; } } //execute while(1){ cin.clear(); if (sigaction(SIGINT, &newAction, &oldAction) == 0 && oldAction.sa_handler != SIG_IGN){ newAction.sa_handler = handleC; sigaction(SIGINT, &newAction, 0); } string input; char buf[1024]; int sdi = dup(0), sdo = dup(1); if(sdi == -1) perror("There was an error with dup"); if(sdo == -1) perror("There was an error with dup"); cout << login << "@" << host << "$ "; //get the input from user getline(cin, input); //check if user pushes enter if(input == "") continue; //checks the spacing fixSpaces(input); //check for comments checkcomm(input); strcpy(buf, input.c_str()); //check if user inputs exit if( input.find("exit") != string::npos ) exit(1); //tokenize the commandline char delim[]= " \t\n"; int size=input.size()+1; char **argv=new char*[size]; int pos=0; argv[pos]=strtok(buf, delim); while(argv[pos] != NULL) { pos++; argv[pos] = strtok(NULL,delim); } //argv[pos]=NULL; //for(unsigned i=0; argv[i] != NULL ; i++) // cout << argv[i] << ' '; IOredir(argv); getPipes(argv); if(dup2(sdi, 0) == -1) perror("There was an error with dup2"); if(dup2(sdo,1) == -1) perror("There was an error with dup2"); delete[] argv; } return 0; } void simpleFork(char **argv, bool BG){ int status = 0; int i = fork(); if(i == -1){ //error check fork perror("There was an error with fork()"); exit(1); } else if(i == 0) { //error check execvp if (-1==execvp(argv[0], argv)) { perror("execvp didn't work correctly"); exit(1); } } int wpid; //in parent if(! BG){ do { wpid = wait(&status); } while (wpid == -1 && errno == EINTR); if (wpid == -1) { perror("wait error"); exit(1); } } } void getPipes(char** argv){ bool pipeFound = false; //save spots for the beginning arguments and ending arguments char **args = argv; char **nextA = argv; //go through argv and check if pipes are found //if they are found, it goes into function forkpipes for(int i=0; argv[i] != '\0'; i++){ if(strcmp(argv[i], "|") == 0){ pipeFound=true; argv[i] = '\0'; char** beforeA = args; nextA = args + i + 1; forkPipes(beforeA, nextA); break; } } //if pipe isn't found, it goes into the simple fork if(!pipeFound){ bool BG = false; for(int i=0; nextA[i] != '\0'; i++){ if(strcmp(nextA[i], "&") == 0) BG=true; } simpleFork(nextA, BG); } } //execution if the command line has pipes void forkPipes(char **argv, char **afterPipe){ int fd[2]; int pid; //pipe new file descriptors if(pipe(fd) == -1){ perror("Error with pipe."); exit(EXIT_FAILURE); } pid = fork(); if(pid == -1){ perror("There was an error with piping fork."); exit(1); } //in child else if(pid ==0){ //close stdin if(close(fd[0]) == -1){ perror("Error with close in piping."); exit(1); } //save stdout if(dup2(fd[1],1)==-1){ perror("Error with dup2 in piping."); } //execute if(execvp(argv[0], argv) == -1){ perror("There was an error with execvp piping"); exit(1); } else{ exit(0); } } //in parent //save stdin int save=dup(0); if((save== -1)) perror("There was an error with dup."); //close std out if(close(fd[1]) == -1){ perror("Error with close in piping."); exit(1); } //make stdin with dup2 if(dup2(fd[0],0) == -1){ perror("Error with dup2 in piping."); } //make sure the parent waits if(wait(0) == -1) perror("There was an error in wait."); //while(waitpid(-1, &status, 0) >= 0); //check for pipes after we execute getPipes(afterPipe); if(dup2(save,0)==-1){ perror("Error with dup2 in piping."); } } //deals with the IO redirection void IOredir(char *argv[]){ //check if there are any I/O redirection symbols for(int i=0; argv[i] != '\0'; i++){ //check for "<" output redir if(strcmp(argv[i], "<") == 0){ //open the file for read only int file = open(argv[i+1], O_RDONLY); if(file == -1) perror("There was an error with open"); if(dup2(file, 0)==-1) perror("There was an error in dup2"); argv[i] = NULL; break; } //check for ">" input redir else if(strcmp(argv[i], ">") == 0){ //open the file, create or truncate and make write only int file = open(argv[i + 1], O_CREAT|O_TRUNC|O_WRONLY, 0666); if(file ==-1) perror("There was an error with open"); if(dup2(file, 1)== -1) perror("There was an error with dup2"); argv[i] = NULL; break; } //check for appending ">>" input redir else if(!strcmp(argv[i], ">>")){ argv[i] = NULL; //open the file, create or append to old file and make write only int file = open(argv[i+1], O_CREAT|O_WRONLY|O_APPEND, 0666); if(file == -1) perror("There was an error with open"); if(dup2(file,1) == -1) perror("There was an error with dup2"); break; } } } void fixSpaces(string &input){ for(unsigned int i = 0; i < input.size(); i++){ //check if | is right next to word //if | is in the middle of a word if(input[i] == '|' && input[i+1] != ' ' && input[i-1] != ' ' && i !=0){ input.insert(i+1, " "); input.insert(i, " "); } //if | is right before a word else if(input[i] == '|' && input[i+1] != ' ') input.insert(i+1, " "); //if | is right after word else if(input[i] == '|' && input[i-1] != ' ' && i!=0) input.insert(i, " "); //check if < is right next to word //if < is in the middle of a word if(input[i] == '<' && input[i+1] != ' ' && input[i-1] != ' ' && i !=0){ input.insert(i+1, " "); input.insert(i, " "); } //if < is right before a word else if(input[i] == '<' && input[i+1] != ' ') input.insert(i+1, " "); //if < is right after word else if(input[i] == '<' && input[i-1] != ' ' && i!=0) input.insert(i, " "); //check if > is right next to word /*if( input[i-1] != '>' && input[i+1]!= '>'){ //if > is in the middle of a word if(input[i] == '>' && input[i+1] != ' ' && input[i-1] != ' ' && i !=0){ input.insert(i+1, " "); input.insert(i, " "); } //if > is right before a word else if(input[i] == '>' && input[i+1] != ' ') input.insert(i+1, " "); //if > is right after word else if(input[i] == '>' && input[i-1] != ' ' && i!=0) input.insert(i, " "); } //has to be >> if(input[i-1] != '>' && input[i+1] == '>'){ //if >> is in the middle of a word if(input[i] == '>' && input[i+1] == '>' && input[i-1] != '>' && i !=0){ input.insert(i-1, " "); input.insert(i, " "); } //if | is right before a word else if(input[i] == '|' && input[i+1] != ' ') input.insert(i+1, " "); //if | is right after word else if(input[i] == '|' && input[i-1] != ' ' && i!=0) input.insert(i, " "); }*/ } } <|endoftext|>
<commit_before>#include "HalideRuntime.h" extern "C" { typedef long dispatch_once_t; extern void dispatch_once_f(dispatch_once_t *, void *context, void (*initializer)(void *)); typedef struct dispatch_queue_s *dispatch_queue_t; typedef long dispatch_queue_priority_t; extern dispatch_queue_t dispatch_get_global_queue( dispatch_queue_priority_t priority, unsigned long flags); extern void dispatch_apply_f(size_t iterations, dispatch_queue_t queue, void *context, void (*work)(void *, size_t)); extern void dispatch_async_f(dispatch_queue_t queue, void *context, void (*work)(void *)); typedef struct dispatch_semaphore_s *dispatch_semaphore_t; typedef uint64_t dispatch_time_t; #define DISPATCH_TIME_FOREVER (~0ull) extern dispatch_semaphore_t dispatch_semaphore_create(long value); extern long dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout); extern long dispatch_semaphore_signal(dispatch_semaphore_t dsema); extern void dispatch_release(void *object); WEAK int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure); } WEAK halide_thread *halide_spawn_thread(void *user_context, void (*f)(void *), void *closure) { dispatch_async_f(dispatch_get_global_queue(0, 0), closure, f); return NULL; } // Join thread and condition variables intentionally unimplemented for // now on OS X. Use of them will result in linker errors. Currently // only the common thread pool uses them. namespace Halide { namespace Runtime { namespace Internal { struct gcd_mutex { dispatch_once_t once; dispatch_semaphore_t semaphore; }; WEAK void init_mutex(void *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; mutex->semaphore = dispatch_semaphore_create(1); } WEAK int default_do_task(void *user_context, int (*f)(void *, int, uint8_t *), int idx, uint8_t *closure) { return f(user_context, idx, closure); } struct halide_gcd_job { int (*f)(void *, int, uint8_t *); void *user_context; uint8_t *closure; int min; int exit_status; }; // Take a call from grand-central-dispatch's parallel for loop, and // make a call to Halide's do task WEAK void halide_do_gcd_task(void *job, size_t idx) { halide_gcd_job *j = (halide_gcd_job *)job; j->exit_status = halide_do_task(j->user_context, j->f, j->min + (int)idx, j->closure); } WEAK int default_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { halide_gcd_job job; job.f = f; job.user_context = user_context; job.closure = closure; job.min = min; job.exit_status = 0; dispatch_apply_f(size, dispatch_get_global_queue(0, 0), &job, &halide_do_gcd_task); return job.exit_status; } WEAK halide_do_task_t custom_do_task = default_do_task; WEAK halide_do_par_for_t custom_do_par_for = default_do_par_for; }}} // namespace Halide::Runtime::Internal extern "C" { WEAK void halide_mutex_cleanup(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; if (mutex->once != 0) { dispatch_release(mutex->semaphore); memset(mutex_arg, 0, sizeof(halide_mutex)); } } WEAK void halide_mutex_lock(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; dispatch_once_f(&mutex->once, mutex, init_mutex); dispatch_semaphore_wait(mutex->semaphore, DISPATCH_TIME_FOREVER); } WEAK void halide_mutex_unlock(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; dispatch_semaphore_signal(mutex->semaphore); } WEAK void halide_shutdown_thread_pool() { } WEAK int halide_set_num_threads(int) { return 1; } WEAK halide_do_task_t halide_set_custom_do_task(halide_do_task_t f) { halide_do_task_t result = custom_do_task; custom_do_task = f; return result; } WEAK halide_do_par_for_t halide_set_custom_do_par_for(halide_do_par_for_t f) { halide_do_par_for_t result = custom_do_par_for; custom_do_par_for = f; return result; } WEAK int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure) { return (*custom_do_task)(user_context, f, idx, closure); } WEAK int halide_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { return (*custom_do_par_for)(user_context, f, min, size, closure); } } <commit_msg>Fix mutex_destroy name on os x<commit_after>#include "HalideRuntime.h" extern "C" { typedef long dispatch_once_t; extern void dispatch_once_f(dispatch_once_t *, void *context, void (*initializer)(void *)); typedef struct dispatch_queue_s *dispatch_queue_t; typedef long dispatch_queue_priority_t; extern dispatch_queue_t dispatch_get_global_queue( dispatch_queue_priority_t priority, unsigned long flags); extern void dispatch_apply_f(size_t iterations, dispatch_queue_t queue, void *context, void (*work)(void *, size_t)); extern void dispatch_async_f(dispatch_queue_t queue, void *context, void (*work)(void *)); typedef struct dispatch_semaphore_s *dispatch_semaphore_t; typedef uint64_t dispatch_time_t; #define DISPATCH_TIME_FOREVER (~0ull) extern dispatch_semaphore_t dispatch_semaphore_create(long value); extern long dispatch_semaphore_wait(dispatch_semaphore_t dsema, dispatch_time_t timeout); extern long dispatch_semaphore_signal(dispatch_semaphore_t dsema); extern void dispatch_release(void *object); WEAK int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure); } WEAK halide_thread *halide_spawn_thread(void *user_context, void (*f)(void *), void *closure) { dispatch_async_f(dispatch_get_global_queue(0, 0), closure, f); return NULL; } // Join thread and condition variables intentionally unimplemented for // now on OS X. Use of them will result in linker errors. Currently // only the common thread pool uses them. namespace Halide { namespace Runtime { namespace Internal { struct gcd_mutex { dispatch_once_t once; dispatch_semaphore_t semaphore; }; WEAK void init_mutex(void *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; mutex->semaphore = dispatch_semaphore_create(1); } WEAK int default_do_task(void *user_context, int (*f)(void *, int, uint8_t *), int idx, uint8_t *closure) { return f(user_context, idx, closure); } struct halide_gcd_job { int (*f)(void *, int, uint8_t *); void *user_context; uint8_t *closure; int min; int exit_status; }; // Take a call from grand-central-dispatch's parallel for loop, and // make a call to Halide's do task WEAK void halide_do_gcd_task(void *job, size_t idx) { halide_gcd_job *j = (halide_gcd_job *)job; j->exit_status = halide_do_task(j->user_context, j->f, j->min + (int)idx, j->closure); } WEAK int default_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { halide_gcd_job job; job.f = f; job.user_context = user_context; job.closure = closure; job.min = min; job.exit_status = 0; dispatch_apply_f(size, dispatch_get_global_queue(0, 0), &job, &halide_do_gcd_task); return job.exit_status; } WEAK halide_do_task_t custom_do_task = default_do_task; WEAK halide_do_par_for_t custom_do_par_for = default_do_par_for; }}} // namespace Halide::Runtime::Internal extern "C" { WEAK void halide_mutex_destroy(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; if (mutex->once != 0) { dispatch_release(mutex->semaphore); memset(mutex_arg, 0, sizeof(halide_mutex)); } } WEAK void halide_mutex_lock(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; dispatch_once_f(&mutex->once, mutex, init_mutex); dispatch_semaphore_wait(mutex->semaphore, DISPATCH_TIME_FOREVER); } WEAK void halide_mutex_unlock(halide_mutex *mutex_arg) { gcd_mutex *mutex = (gcd_mutex *)mutex_arg; dispatch_semaphore_signal(mutex->semaphore); } WEAK void halide_shutdown_thread_pool() { } WEAK int halide_set_num_threads(int) { return 1; } WEAK halide_do_task_t halide_set_custom_do_task(halide_do_task_t f) { halide_do_task_t result = custom_do_task; custom_do_task = f; return result; } WEAK halide_do_par_for_t halide_set_custom_do_par_for(halide_do_par_for_t f) { halide_do_par_for_t result = custom_do_par_for; custom_do_par_for = f; return result; } WEAK int halide_do_task(void *user_context, halide_task_t f, int idx, uint8_t *closure) { return (*custom_do_task)(user_context, f, idx, closure); } WEAK int halide_do_par_for(void *user_context, halide_task_t f, int min, int size, uint8_t *closure) { return (*custom_do_par_for)(user_context, f, min, size, closure); } } <|endoftext|>
<commit_before>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014 Vladimír Vondruš <mosra@centrum.cz> 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 <sstream> #include <Corrade/compatibility.h> #include <Corrade/TestSuite/Tester.h> #include "Magnum/AbstractResourceLoader.h" #include "Magnum/ResourceManager.h" namespace Magnum { namespace Test { class ResourceManagerTest: public TestSuite::Tester { public: ResourceManagerTest(); void state(); void stateFallback(); void stateDisallowed(); void basic(); void residentPolicy(); void referenceCountedPolicy(); void manualPolicy(); void clear(); void clearWhileReferenced(); void loader(); }; class Data { public: static std::size_t count; Data() { ++count; } ~Data() { --count; } }; typedef Magnum::ResourceManager<Int, Data> ResourceManager; size_t Data::count = 0; ResourceManagerTest::ResourceManagerTest() { addTests({&ResourceManagerTest::state, &ResourceManagerTest::stateFallback, &ResourceManagerTest::stateDisallowed, &ResourceManagerTest::basic, &ResourceManagerTest::residentPolicy, &ResourceManagerTest::referenceCountedPolicy, &ResourceManagerTest::manualPolicy, &ResourceManagerTest::clear, &ResourceManagerTest::clearWhileReferenced, &ResourceManagerTest::loader}); } void ResourceManagerTest::state() { ResourceManager rm; Resource<Data> data = rm.get<Data>("data"); CORRADE_VERIFY(!data); CORRADE_COMPARE(data.state(), ResourceState::NotLoaded); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::NotLoaded); rm.set<Data>("data", nullptr, ResourceDataState::Loading, ResourcePolicy::Resident); CORRADE_VERIFY(!data); CORRADE_COMPARE(data.state(), ResourceState::Loading); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::Loading); rm.set<Data>("data", nullptr, ResourceDataState::NotFound, ResourcePolicy::Resident); CORRADE_VERIFY(!data); CORRADE_COMPARE(data.state(), ResourceState::NotFound); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::NotFound); /* Nothing happened at all */ CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::stateFallback() { { ResourceManager rm; rm.setFallback(new Data); Resource<Data> data = rm.get<Data>("data"); CORRADE_VERIFY(data); CORRADE_COMPARE(data.state(), ResourceState::NotLoadedFallback); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::NotLoadedFallback); rm.set<Data>("data", nullptr, ResourceDataState::Loading, ResourcePolicy::Resident); CORRADE_VERIFY(data); CORRADE_COMPARE(data.state(), ResourceState::LoadingFallback); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::LoadingFallback); rm.set<Data>("data", nullptr, ResourceDataState::NotFound, ResourcePolicy::Resident); CORRADE_VERIFY(data); CORRADE_COMPARE(data.state(), ResourceState::NotFoundFallback); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::NotFoundFallback); /* Only fallback is here */ CORRADE_COMPARE(Data::count, 1); } /* Fallback gets destroyed */ CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::stateDisallowed() { ResourceManager rm; std::ostringstream out; Error::setOutput(&out); rm.set("data", Data(), ResourceDataState::Loading, ResourcePolicy::Resident); CORRADE_COMPARE(out.str(), "ResourceManager::set(): data should be null if and only if state is NotFound or Loading\n"); out.str({}); rm.set<Data>("data", nullptr, ResourceDataState::Final, ResourcePolicy::Resident); CORRADE_COMPARE(out.str(), "ResourceManager::set(): data should be null if and only if state is NotFound or Loading\n"); } void ResourceManagerTest::basic() { ResourceManager rm; /* One mutable, one final */ ResourceKey questionKey("the-question"); ResourceKey answerKey("the-answer"); rm.set(questionKey, 10, ResourceDataState::Mutable, ResourcePolicy::Resident); rm.set(answerKey, 42, ResourceDataState::Final, ResourcePolicy::Resident); Resource<Int> theQuestion = rm.get<Int>(questionKey); Resource<Int> theAnswer = rm.get<Int>(answerKey); /* Check basic functionality */ CORRADE_COMPARE(theQuestion.state(), ResourceState::Mutable); CORRADE_COMPARE(theAnswer.state(), ResourceState::Final); CORRADE_COMPARE(*theQuestion, 10); CORRADE_COMPARE(*theAnswer, 42); CORRADE_COMPARE(rm.count<Int>(), 2); /* Cannot change already final resource */ std::ostringstream out; Error::setOutput(&out); rm.set(answerKey, 43, ResourceDataState::Mutable, ResourcePolicy::Resident); CORRADE_COMPARE(*theAnswer, 42); CORRADE_COMPARE(out.str(), "ResourceManager::set(): cannot change already final resource " + answerKey.hexString() + '\n'); /* But non-final can be changed */ rm.set(questionKey, 20, ResourceDataState::Final, ResourcePolicy::Resident); CORRADE_COMPARE(theQuestion.state(), ResourceState::Final); CORRADE_COMPARE(*theQuestion, 20); } void ResourceManagerTest::residentPolicy() { ResourceManager* rm = new ResourceManager; rm->set("blah", new Data, ResourceDataState::Mutable, ResourcePolicy::Resident); CORRADE_COMPARE(Data::count, 1); rm->free(); CORRADE_COMPARE(Data::count, 1); delete rm; CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::referenceCountedPolicy() { ResourceManager rm; ResourceKey dataRefCountKey("dataRefCount"); /* Reference counted resources must be requested first */ { rm.set(dataRefCountKey, new Data, ResourceDataState::Final, ResourcePolicy::ReferenceCounted); CORRADE_COMPARE(rm.count<Data>(), 0); Resource<Data> data = rm.get<Data>(dataRefCountKey); CORRADE_COMPARE(data.state(), ResourceState::NotLoaded); CORRADE_COMPARE(Data::count, 0); } { Resource<Data> data = rm.get<Data>(dataRefCountKey); CORRADE_COMPARE(rm.count<Data>(), 1); CORRADE_COMPARE(data.state(), ResourceState::NotLoaded); rm.set(dataRefCountKey, new Data, ResourceDataState::Final, ResourcePolicy::ReferenceCounted); CORRADE_COMPARE(data.state(), ResourceState::Final); CORRADE_COMPARE(Data::count, 1); } CORRADE_COMPARE(rm.count<Data>(), 0); CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::manualPolicy() { ResourceManager rm; ResourceKey dataKey("data"); /* Manual free */ { rm.set(dataKey, new Data, ResourceDataState::Mutable, ResourcePolicy::Manual); Resource<Data> data = rm.get<Data>(dataKey); rm.free(); } CORRADE_COMPARE(rm.count<Data>(), 1); CORRADE_COMPARE(Data::count, 1); rm.free(); CORRADE_COMPARE(rm.count<Data>(), 0); CORRADE_COMPARE(Data::count, 0); rm.set(dataKey, new Data, ResourceDataState::Mutable, ResourcePolicy::Manual); CORRADE_COMPARE(rm.count<Data>(), 1); CORRADE_COMPARE(Data::count, 1); } void ResourceManagerTest::clear() { ResourceManager rm; rm.set("blah", new Data); CORRADE_COMPARE(Data::count, 1); rm.free(); CORRADE_COMPARE(Data::count, 1); rm.clear(); CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::clearWhileReferenced() { /* Should cover also the destruction case */ std::ostringstream out; Error::setOutput(&out); ResourceManager rm; rm.set("blah", Int()); /** @todo this will leak, is there any better solution without hitting assertion in decrementReferenceCount()? */ new Resource<Int>(rm.get<Int>("blah")); rm.clear(); CORRADE_COMPARE(out.str(), "ResourceManager: cleared/destroyed while data are still referenced\n"); } void ResourceManagerTest::loader() { class IntResourceLoader: public AbstractResourceLoader<Int> { public: IntResourceLoader(): resource(ResourceManager::instance().get<Data>("data")) {} void load() { set("hello", 773, ResourceDataState::Final, ResourcePolicy::Resident); setNotFound("world"); } private: void doLoad(ResourceKey) override {} std::string doName(ResourceKey key) const override { if(key == ResourceKey("hello")) return "hello"; return ""; } /* To verify that the loader is destroyed before unloading _all types of_ resources */ Resource<Data> resource; }; auto rm = new ResourceManager; auto loader = new IntResourceLoader; rm->setLoader(loader); { Resource<Data> data = rm->get<Data>("data"); Resource<Int> hello = rm->get<Int>("hello"); Resource<Int> world = rm->get<Int>("world"); CORRADE_COMPARE(data.state(), ResourceState::NotLoaded); CORRADE_COMPARE(hello.state(), ResourceState::Loading); CORRADE_COMPARE(world.state(), ResourceState::Loading); CORRADE_COMPARE(loader->requestedCount(), 2); CORRADE_COMPARE(loader->loadedCount(), 0); CORRADE_COMPARE(loader->notFoundCount(), 0); CORRADE_COMPARE(loader->name(ResourceKey("hello")), "hello"); loader->load(); CORRADE_COMPARE(hello.state(), ResourceState::Final); CORRADE_COMPARE(*hello, 773); CORRADE_COMPARE(world.state(), ResourceState::NotFound); CORRADE_COMPARE(loader->requestedCount(), 2); CORRADE_COMPARE(loader->loadedCount(), 1); CORRADE_COMPARE(loader->notFoundCount(), 1); /* Verify that the loader is deleted at proper time */ rm->set("data", new Data); CORRADE_COMPARE(Data::count, 1); } delete rm; CORRADE_COMPARE(Data::count, 0); } }} CORRADE_TEST_MAIN(Magnum::Test::ResourceManagerTest) <commit_msg>Test also ResourceManager::set() with default values.<commit_after>/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014 Vladimír Vondruš <mosra@centrum.cz> 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 <sstream> #include <Corrade/compatibility.h> #include <Corrade/TestSuite/Tester.h> #include "Magnum/AbstractResourceLoader.h" #include "Magnum/ResourceManager.h" namespace Magnum { namespace Test { class ResourceManagerTest: public TestSuite::Tester { public: ResourceManagerTest(); void state(); void stateFallback(); void stateDisallowed(); void basic(); void residentPolicy(); void referenceCountedPolicy(); void manualPolicy(); void defaults(); void clear(); void clearWhileReferenced(); void loader(); }; class Data { public: static std::size_t count; Data() { ++count; } ~Data() { --count; } }; typedef Magnum::ResourceManager<Int, Data> ResourceManager; size_t Data::count = 0; ResourceManagerTest::ResourceManagerTest() { addTests({&ResourceManagerTest::state, &ResourceManagerTest::stateFallback, &ResourceManagerTest::stateDisallowed, &ResourceManagerTest::basic, &ResourceManagerTest::residentPolicy, &ResourceManagerTest::referenceCountedPolicy, &ResourceManagerTest::manualPolicy, &ResourceManagerTest::defaults, &ResourceManagerTest::clear, &ResourceManagerTest::clearWhileReferenced, &ResourceManagerTest::loader}); } void ResourceManagerTest::state() { ResourceManager rm; Resource<Data> data = rm.get<Data>("data"); CORRADE_VERIFY(!data); CORRADE_COMPARE(data.state(), ResourceState::NotLoaded); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::NotLoaded); rm.set<Data>("data", nullptr, ResourceDataState::Loading, ResourcePolicy::Resident); CORRADE_VERIFY(!data); CORRADE_COMPARE(data.state(), ResourceState::Loading); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::Loading); rm.set<Data>("data", nullptr, ResourceDataState::NotFound, ResourcePolicy::Resident); CORRADE_VERIFY(!data); CORRADE_COMPARE(data.state(), ResourceState::NotFound); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::NotFound); /* Nothing happened at all */ CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::stateFallback() { { ResourceManager rm; rm.setFallback(new Data); Resource<Data> data = rm.get<Data>("data"); CORRADE_VERIFY(data); CORRADE_COMPARE(data.state(), ResourceState::NotLoadedFallback); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::NotLoadedFallback); rm.set<Data>("data", nullptr, ResourceDataState::Loading, ResourcePolicy::Resident); CORRADE_VERIFY(data); CORRADE_COMPARE(data.state(), ResourceState::LoadingFallback); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::LoadingFallback); rm.set<Data>("data", nullptr, ResourceDataState::NotFound, ResourcePolicy::Resident); CORRADE_VERIFY(data); CORRADE_COMPARE(data.state(), ResourceState::NotFoundFallback); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::NotFoundFallback); /* Only fallback is here */ CORRADE_COMPARE(Data::count, 1); } /* Fallback gets destroyed */ CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::stateDisallowed() { ResourceManager rm; std::ostringstream out; Error::setOutput(&out); rm.set("data", Data(), ResourceDataState::Loading, ResourcePolicy::Resident); CORRADE_COMPARE(out.str(), "ResourceManager::set(): data should be null if and only if state is NotFound or Loading\n"); out.str({}); rm.set<Data>("data", nullptr, ResourceDataState::Final, ResourcePolicy::Resident); CORRADE_COMPARE(out.str(), "ResourceManager::set(): data should be null if and only if state is NotFound or Loading\n"); } void ResourceManagerTest::basic() { ResourceManager rm; /* One mutable, one final */ ResourceKey questionKey("the-question"); ResourceKey answerKey("the-answer"); rm.set(questionKey, 10, ResourceDataState::Mutable, ResourcePolicy::Resident); rm.set(answerKey, 42, ResourceDataState::Final, ResourcePolicy::Resident); Resource<Int> theQuestion = rm.get<Int>(questionKey); Resource<Int> theAnswer = rm.get<Int>(answerKey); /* Check basic functionality */ CORRADE_COMPARE(theQuestion.state(), ResourceState::Mutable); CORRADE_COMPARE(theAnswer.state(), ResourceState::Final); CORRADE_COMPARE(*theQuestion, 10); CORRADE_COMPARE(*theAnswer, 42); CORRADE_COMPARE(rm.count<Int>(), 2); /* Cannot change already final resource */ std::ostringstream out; Error::setOutput(&out); rm.set(answerKey, 43, ResourceDataState::Mutable, ResourcePolicy::Resident); CORRADE_COMPARE(*theAnswer, 42); CORRADE_COMPARE(out.str(), "ResourceManager::set(): cannot change already final resource " + answerKey.hexString() + '\n'); /* But non-final can be changed */ rm.set(questionKey, 20, ResourceDataState::Final, ResourcePolicy::Resident); CORRADE_COMPARE(theQuestion.state(), ResourceState::Final); CORRADE_COMPARE(*theQuestion, 20); } void ResourceManagerTest::residentPolicy() { ResourceManager* rm = new ResourceManager; rm->set("blah", new Data, ResourceDataState::Mutable, ResourcePolicy::Resident); CORRADE_COMPARE(Data::count, 1); rm->free(); CORRADE_COMPARE(Data::count, 1); delete rm; CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::referenceCountedPolicy() { ResourceManager rm; ResourceKey dataRefCountKey("dataRefCount"); /* Reference counted resources must be requested first */ { rm.set(dataRefCountKey, new Data, ResourceDataState::Final, ResourcePolicy::ReferenceCounted); CORRADE_COMPARE(rm.count<Data>(), 0); Resource<Data> data = rm.get<Data>(dataRefCountKey); CORRADE_COMPARE(data.state(), ResourceState::NotLoaded); CORRADE_COMPARE(Data::count, 0); } { Resource<Data> data = rm.get<Data>(dataRefCountKey); CORRADE_COMPARE(rm.count<Data>(), 1); CORRADE_COMPARE(data.state(), ResourceState::NotLoaded); rm.set(dataRefCountKey, new Data, ResourceDataState::Final, ResourcePolicy::ReferenceCounted); CORRADE_COMPARE(data.state(), ResourceState::Final); CORRADE_COMPARE(Data::count, 1); } CORRADE_COMPARE(rm.count<Data>(), 0); CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::manualPolicy() { ResourceManager rm; ResourceKey dataKey("data"); /* Manual free */ { rm.set(dataKey, new Data, ResourceDataState::Mutable, ResourcePolicy::Manual); Resource<Data> data = rm.get<Data>(dataKey); rm.free(); } CORRADE_COMPARE(rm.count<Data>(), 1); CORRADE_COMPARE(Data::count, 1); rm.free(); CORRADE_COMPARE(rm.count<Data>(), 0); CORRADE_COMPARE(Data::count, 0); rm.set(dataKey, new Data, ResourceDataState::Mutable, ResourcePolicy::Manual); CORRADE_COMPARE(rm.count<Data>(), 1); CORRADE_COMPARE(Data::count, 1); } void ResourceManagerTest::defaults() { ResourceManager rm; rm.set("data", new Data); CORRADE_COMPARE(rm.state<Data>("data"), ResourceState::Final); } void ResourceManagerTest::clear() { ResourceManager rm; rm.set("blah", new Data); CORRADE_COMPARE(Data::count, 1); rm.free(); CORRADE_COMPARE(Data::count, 1); rm.clear(); CORRADE_COMPARE(Data::count, 0); } void ResourceManagerTest::clearWhileReferenced() { /* Should cover also the destruction case */ std::ostringstream out; Error::setOutput(&out); ResourceManager rm; rm.set("blah", Int()); /** @todo this will leak, is there any better solution without hitting assertion in decrementReferenceCount()? */ new Resource<Int>(rm.get<Int>("blah")); rm.clear(); CORRADE_COMPARE(out.str(), "ResourceManager: cleared/destroyed while data are still referenced\n"); } void ResourceManagerTest::loader() { class IntResourceLoader: public AbstractResourceLoader<Int> { public: IntResourceLoader(): resource(ResourceManager::instance().get<Data>("data")) {} void load() { set("hello", 773, ResourceDataState::Final, ResourcePolicy::Resident); setNotFound("world"); } private: void doLoad(ResourceKey) override {} std::string doName(ResourceKey key) const override { if(key == ResourceKey("hello")) return "hello"; return ""; } /* To verify that the loader is destroyed before unloading _all types of_ resources */ Resource<Data> resource; }; auto rm = new ResourceManager; auto loader = new IntResourceLoader; rm->setLoader(loader); { Resource<Data> data = rm->get<Data>("data"); Resource<Int> hello = rm->get<Int>("hello"); Resource<Int> world = rm->get<Int>("world"); CORRADE_COMPARE(data.state(), ResourceState::NotLoaded); CORRADE_COMPARE(hello.state(), ResourceState::Loading); CORRADE_COMPARE(world.state(), ResourceState::Loading); CORRADE_COMPARE(loader->requestedCount(), 2); CORRADE_COMPARE(loader->loadedCount(), 0); CORRADE_COMPARE(loader->notFoundCount(), 0); CORRADE_COMPARE(loader->name(ResourceKey("hello")), "hello"); loader->load(); CORRADE_COMPARE(hello.state(), ResourceState::Final); CORRADE_COMPARE(*hello, 773); CORRADE_COMPARE(world.state(), ResourceState::NotFound); CORRADE_COMPARE(loader->requestedCount(), 2); CORRADE_COMPARE(loader->loadedCount(), 1); CORRADE_COMPARE(loader->notFoundCount(), 1); /* Verify that the loader is deleted at proper time */ rm->set("data", new Data); CORRADE_COMPARE(Data::count, 1); } delete rm; CORRADE_COMPARE(Data::count, 0); } }} CORRADE_TEST_MAIN(Magnum::Test::ResourceManagerTest) <|endoftext|>
<commit_before>#include <boost/tokenizer.hpp> #include <iostream> #include <unistd.h> #include <string.h> #include <cstdlib> #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <sstream> #include <vector> //using namespace boost; using namespace std; int main() { using namespace boost; string args; while(1 != 2) { cout << "$ "; getline(cin, args); char *argv[9]; int i = 0; vector<string> arg_s; tokenizer<> tok(args); for(tokenizer<>::iterator beg=tok.begin(); beg!=tok.end();++beg) { arg_s.push_back(*beg); argv[i] = new char[6]; strcpy(argv[i], const_cast<char*>(arg_s[i].c_str())); if(*beg == "exit") exit(1); ++i; } argv[i] = NULL; int pid = fork(); if(pid == -1) { perror("fork"); exit(1); } if(pid == 0) { int r = execvp(argv[0], argv); if(r == -1) { perror("execvp"); exit(1); } } else { if(-1 == waitpid(pid, &pid, 0)) { perror("waitpid"); } } // int pid = fork(); // if(pid == -1) { // perror("fork"); // exit(1); // } // if(pid == 0) // { //char *argv2[4]; //argv2[0] = new char[6]; //strcpy(argv[0], "ls"); //argv2[1] = new char[6]; //strcpy(argv[1], "-a"); //argv2[2] = new char [6]; //strcpy(argv[2], "-l"); // int pid2 = fork(); // if(pid2 == -1) { // perror("fork"); // exit(1); // } // if(pid2 == 0) { /// if(execvp(argv[0], argv) == -1) { // perror("execvp"); // exit(1); // } // } // else { // if(-1 == waitpid(pid2,&pid2,0 )) // perror("waitpid"); // } // // if(execvp(argv[1], argv) == -1) { // perror("execvp"); // exit(1); // } // // cout << "after" << endl; // } // else { // if(-1 == waitpid(pid, &pid, 0)) // perror("waitpid"); // } } return 0; } <commit_msg>rshell.cpp updated<commit_after>#include <boost/tokenizer.hpp> #include <iostream> #include <unistd.h> #include <string.h> #include <cstdlib> #include <errno.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <string> #include <sstream> #include <vector> //using namespace boost; using namespace std; int main() { using namespace boost; string args; while(1 != 2) { cout << "$ "; getline(cin, args); char *argv[9]; int i = 0; vector<string> arg_s; typedef tokenizer< char_separator<char> > tokenizer; char_separator<char> sep(" ", "-;||&&", drop_empty_tokens); tokenizer tokens(args, sep); for(tokenizer::iterator tok_iter=tokens.begin(); tok_iter != tokens.end();++tok_iter) { if(*tok_iter == "&&" || *tok_iter == "||" || *tok_iter == ";") { // argv[i] = NULL; // int pidb = fork(); // if(pidb == -1) { // perror("fork"); // } // if(pidb == 0) { // int t = execvp(argv[0], argv); // if(t == -1) { // perror("execvp"); // } // } // else { // if(-1 == waitpid(pidb, &pidb, 0)) { // perror("waitpid"); // } // } } else { cout << *tok_iter << endl; arg_s.push_back(*tok_iter); argv[i] = new char[12]; strcpy(argv[i], const_cast<char*>(arg_s[i].c_str())); if(*tok_iter == "exit") exit(1); ++i; } } argv[i] = NULL; int pid = fork(); if(pid == -1) { perror("fork"); exit(1); } if(pid == 0) { int r = execvp(argv[0], argv); if(r == -1) { perror("execvp"); exit(1); } } else { if(-1 == waitpid(pid, &pid, 0)) { perror("waitpid"); } } // int pid = fork(); // if(pid == -1) { // perror("fork"); // exit(1); // } // if(pid == 0) // { //char *argv2[4]; //argv2[0] = new char[6]; //strcpy(argv[0], "ls"); //argv2[1] = new char[6]; //strcpy(argv[1], "-a"); //argv2[2] = new char [6]; //strcpy(argv[2], "-l"); // int pid2 = fork(); // if(pid2 == -1) { // perror("fork"); // exit(1); // } // if(pid2 == 0) { /// if(execvp(argv[0], argv) == -1) { // perror("execvp"); // exit(1); // } // } // else { // if(-1 == waitpid(pid2,&pid2,0 )) // perror("waitpid"); // } // // if(execvp(argv[1], argv) == -1) { // perror("execvp"); // exit(1); // } // // cout << "after" << endl; // } // else { // if(-1 == waitpid(pid, &pid, 0)) // perror("waitpid"); // } } return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <string> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <errno.h> #include <vector> #include <stdlib.h> using namespace std; void parse(char* line, vector<string> & input) { char * pch; pch = strtok (line, " \n"); while (pch!= NULL) { if (*pch == '#') break; input.push_back(pch); pch = strtok (NULL, " \n"); } } void execute(vector<string> & input, int start, int end) { //Call execvp, based on which elements in the string vector to use char * argv[(end - start)+1]; int i = 0; for (i = 0; i <= (end - start); i++) { argv[i] = new char[5]; } for (i = 0; i < (end-start); i++) { strcpy(argv[i], input[i+start].c_str()); } argv[i] = NULL; int r = execvp(argv[0], argv); if (r == -1) perror("execvp"); exit(1); } int main() { char buffer[512]; vector<string> input; while (1) { if (input.size() != 0) input.clear(); cout << "Please enter cmd: "; fgets(buffer, 512, stdin); parse(buffer, input); if (strcmp(input[0].c_str(), "exit") == 0) exit(0); int pid=fork(); int pid2; if (pid == 0) { int start = 0; int end = input.size(); int i; // Check for semi colons for (i = 0; i < input.size(); i++) { if (input[i][(input[i].length() -1)] == ';') { end = i; pid2 = fork(); break; } } if (pid2==0) { start = i+1; end = input.size(); } execute(input, start, end); } else { while(wait(NULL) > 0); } } return 0; } <commit_msg>Updated rshell to deal with semi colons<commit_after>#include <iostream> #include <unistd.h> #include <string> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <errno.h> #include <vector> #include <stdlib.h> using namespace std; void parse(char* line, vector<string> & input) { char * pch; pch = strtok (line, " \n"); while (pch!= NULL) { if (*pch == '#') break; input.push_back(pch); pch = strtok (NULL, " \n"); } } void execute(vector<string> & input, int start, int end) { //Call execvp, based on which elements in the string vector to use char * argv[(end - start)+1]; int i = 0; for (i = 0; i <= (end - start); i++) { argv[i] = new char[5]; } for (i = 0; i < (end-start); i++) { strcpy(argv[i], input[i+start].c_str()); } argv[i] = NULL; int r = execvp(argv[0], argv); if (r == -1) perror("execvp"); exit(1); } int main() { char buffer[512]; vector<string> input; while (1) { if (input.size() != 0) input.clear(); cout << "Please enter cmd: "; fgets(buffer, 512, stdin); parse(buffer, input); if (strcmp(input[0].c_str(), "exit") == 0) exit(0); int pid=fork(); int pid2; if (pid == 0) { int start = 0; int end = input.size(); int i; loop: end = input.size(); for (i = start; i < input.size(); i++) { // Check for semi colons if (input[i][input[i].size() - 1] == ';' || input[i] == ";") { pid2 = fork(); if (pid2!=0) { start = i + 1; goto loop; } if (input[i] != ";") { input[i] = input[i].substr(0, input[i].size() -1); end = i+1; } else end = i; break; } } if (pid2 != 0) wait(NULL); execute(input, start, end); } else { while(wait(NULL) > 0); } } return 0; } <|endoftext|>
<commit_before>#pragma once #include "../utils.hpp" struct horizontal_diffusion_reference { horizontal_diffusion_reference(repository &repo) : m_repo(repo) {} void generate_reference() { m_repo.make_field("u_diff_ref"); m_repo.make_field("lap_ref"); m_repo.make_field("flx_ref"); m_repo.make_field("fly_ref"); Real *u_in = m_repo.field_h("u_in"); Real *u_diff_ref = m_repo.field_h("u_diff_ref"); Real *lap = m_repo.field_h("lap_ref"); Real *flx = m_repo.field_h("flx_ref"); Real *fly = m_repo.field_h("fly_ref"); Real *coeff = m_repo.field_h("coeff"); IJKSize domain = m_repo.domain(); IJKSize halo = m_repo.halo(); IJKSize strides; compute_strides(domain, strides); for (unsigned int k = 0; k < domain.m_k; ++k) { for (unsigned int i = halo.m_i - 1; i < domain.m_i - halo.m_i + 1; ++i) { for (unsigned int j = halo.m_j - 1; j < domain.m_j - halo.m_j + 1; ++j) { lap[index(i, j, k, strides)] = (Real)4 * u_in[index(i, j, k, strides)] - (u_in[index(i + 1, j, k, strides)] + u_in[index(i, j + 1, k, strides)] + u_in[index(i - 1, j, k, strides)] + u_in[index(i, j - 1, k, strides)]); } } for (unsigned int i = halo.m_i - 1; i < domain.m_i - halo.m_i; ++i) { for (unsigned int j = halo.m_j; j < domain.m_j - halo.m_j; ++j) { flx[index(i, j, k, strides)] = lap[index(i + 1, j, k, strides)] - lap[index(i, j, k, strides)]; if (flx[index(i, j, k, strides)] * (u_in[index(i + 1, j, k, strides)] - u_in[index(i, j, k, strides)]) > 0) flx[index(i, j, k, strides)] = 0.; } } for (unsigned int i = halo.m_i; i < domain.m_i - halo.m_i; ++i) { for (unsigned int j = halo.m_j - 1; j < domain.m_j - halo.m_j; ++j) { fly[index(i, j, k, strides)] = lap[index(i, j + 1, k, strides)] - lap[index(i, j, k, strides)]; if (fly[index(i, j, k, strides)] * (u_in[index(i, j + 1, k, strides)] - u_in[index(i, j, k, strides)]) > 0) fly[index(i, j, k, strides)] = 0.; } } for (unsigned int i = halo.m_i; i < domain.m_i - halo.m_i; ++i) { for (unsigned int j = halo.m_j; j < domain.m_j - halo.m_j; ++j) { u_diff_ref[index(i, j, k, strides)] = u_in[index(i, j, k, strides)] - coeff[index(i, j, k, strides)] * (flx[index(i, j, k, strides)] - flx[index(i - 1, j, k, strides)] + fly[index(i, j, k, strides)] - fly[index(i, j - 1, k, strides)]); } } } } private: repository m_repo; }; <commit_msg>make repo a ref<commit_after>#pragma once #include "../utils.hpp" struct horizontal_diffusion_reference { horizontal_diffusion_reference(repository &repo) : m_repo(repo) {} void generate_reference() { m_repo.make_field("u_diff_ref"); m_repo.make_field("lap_ref"); m_repo.make_field("flx_ref"); m_repo.make_field("fly_ref"); Real *u_in = m_repo.field_h("u_in"); Real *u_diff_ref = m_repo.field_h("u_diff_ref"); Real *lap = m_repo.field_h("lap_ref"); Real *flx = m_repo.field_h("flx_ref"); Real *fly = m_repo.field_h("fly_ref"); Real *coeff = m_repo.field_h("coeff"); IJKSize domain = m_repo.domain(); IJKSize halo = m_repo.halo(); IJKSize strides; compute_strides(domain, strides); for (unsigned int k = 0; k < domain.m_k; ++k) { for (unsigned int i = halo.m_i - 1; i < domain.m_i - halo.m_i + 1; ++i) { for (unsigned int j = halo.m_j - 1; j < domain.m_j - halo.m_j + 1; ++j) { lap[index(i, j, k, strides)] = (Real)4 * u_in[index(i, j, k, strides)] - (u_in[index(i + 1, j, k, strides)] + u_in[index(i, j + 1, k, strides)] + u_in[index(i - 1, j, k, strides)] + u_in[index(i, j - 1, k, strides)]); } } for (unsigned int i = halo.m_i - 1; i < domain.m_i - halo.m_i; ++i) { for (unsigned int j = halo.m_j; j < domain.m_j - halo.m_j; ++j) { flx[index(i, j, k, strides)] = lap[index(i + 1, j, k, strides)] - lap[index(i, j, k, strides)]; if (flx[index(i, j, k, strides)] * (u_in[index(i + 1, j, k, strides)] - u_in[index(i, j, k, strides)]) > 0) flx[index(i, j, k, strides)] = 0.; } } for (unsigned int i = halo.m_i; i < domain.m_i - halo.m_i; ++i) { for (unsigned int j = halo.m_j - 1; j < domain.m_j - halo.m_j; ++j) { fly[index(i, j, k, strides)] = lap[index(i, j + 1, k, strides)] - lap[index(i, j, k, strides)]; if (fly[index(i, j, k, strides)] * (u_in[index(i, j + 1, k, strides)] - u_in[index(i, j, k, strides)]) > 0) fly[index(i, j, k, strides)] = 0.; } } for (unsigned int i = halo.m_i; i < domain.m_i - halo.m_i; ++i) { for (unsigned int j = halo.m_j; j < domain.m_j - halo.m_j; ++j) { u_diff_ref[index(i, j, k, strides)] = u_in[index(i, j, k, strides)] - coeff[index(i, j, k, strides)] * (flx[index(i, j, k, strides)] - flx[index(i - 1, j, k, strides)] + fly[index(i, j, k, strides)] - fly[index(i, j - 1, k, strides)]); } } } } private: repository& m_repo; }; <|endoftext|>