text
stringlengths 54
60.6k
|
---|
<commit_before>/*
* mod_compare - compares apache requests
*
* Copyright (C) 2013 Orange
*
* 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 <httpd.h>
#include <http_config.h>
#include <http_request.h>
#include <http_protocol.h>
#include <http_connection.h>
#include <apr_pools.h>
#include <apr_hooks.h>
#include "apr_strings.h"
#include <unistd.h>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <exception>
#include <set>
#include <sstream>
#include <sys/syscall.h>
#include <algorithm>
#include <boost/tokenizer.hpp>
#include <fstream>
#include <unixd.h>
#include "mod_compare.hh"
#define MOD_REWRITE_NAME "mod_rewrite.c"
namespace alg = boost::algorithm;
namespace CompareModule {
const char* gName = "Compare";
const char* gNameOut = "CompareOut";
const char* gNameOut2 = "CompareOut2";
const char* c_COMPONENT_VERSION = "Compare/1.0";
const char* c_named_mutex = "mod_compare_log_mutex";
bool gRem = boost::interprocess::named_mutex::remove(c_named_mutex);
std::ofstream gFile;
const char * gFilePath = "/var/opt/hosting/log/apache2/compare_diff.log";
bool gWriteInFile = true;
std::string gLogFacility;
boost::interprocess::named_mutex &getGlobalMutex() {
static boost::interprocess::named_mutex *gMutex = NULL;
try {
if (!gMutex) {
gMutex = new boost::interprocess::named_mutex(boost::interprocess::open_or_create, c_named_mutex);
}
return *gMutex;
} catch (boost::interprocess::interprocess_exception& e) {
// Just in case the log has not been init yet
Log::init();
Log::error(42, "Cannot initialize global mutex named: %s. What: %s", c_named_mutex, e.what());
throw e;
}
}
CompareConf::CompareConf(): mCompareDisabled(false), mIsActive(false) {
}
apr_status_t CompareConf::cleaner(void *self) {
if(self){
CompareConf *c = reinterpret_cast<CompareConf *>(self);
c->~CompareConf();
}
return 0;
}
/**
* @brief allocate a pointer to a string which will hold the path for the dir config if mod_compare is active on it
* @param pPool the apache pool on which to allocate data
* @param pDirName the directory name for which to create data
* @return a void pointer to newly allocated object
*/
void *
createDirConfig(apr_pool_t *pPool, char *pDirName)
{
void *addr= apr_pcalloc(pPool, sizeof(class CompareConf));
new (addr) CompareConf();
apr_pool_cleanup_register(pPool, addr, CompareConf::cleaner, apr_pool_cleanup_null);
return addr;
}
/**
* @brief Initialize logging post-config
* @param pPool the apache pool
* @param pServer the corresponding server record
* @return Always OK
*/
int
postConfig(apr_pool_t * pPool, apr_pool_t * pLog, apr_pool_t * pTemp, server_rec * pServer) {
Log::init();
ap_add_version_component(pPool, c_COMPONENT_VERSION) ;
if( !gWriteInFile ){
return APR_SUCCESS;
}
apr_pool_cleanup_register(pPool, NULL, apr_pool_cleanup_null, closeLogFile);
return openLogFile(gFilePath, std::ofstream::out | std::ofstream::app);
}
apr_status_t
closeLogFile(void *) {
gFile.close();
return APR_SUCCESS;
}
apr_status_t openLogFile(const char * filepath,std::ios_base::openmode mode) {
gFile.open(filepath,mode);
if (!gFile.is_open()){
Log::error(43,"Couldn't open correctly the file");
return 400; // to modify
}
if ( chown(filepath, unixd_config.user_id, unixd_config.group_id) < 0 ) {
Log::error(528, "Failed to change ownership of shared mem file %s to child user %s, error %d (%s)", filepath, unixd_config.user_name, errno, strerror(errno) );
}
gFile.close();
return APR_SUCCESS;
}
void
childInit(apr_pool_t *pPool, server_rec *pServer)
{
if( gWriteInFile ){
gFile.open(gFilePath, std::ofstream::out | std::ofstream::app );
if (!gFile.is_open()){
Log::error(43,"Couldn't open correctly the file");
}
}
}
/**
* @brief Set the list of errors which stop the comparison
* @param pParams miscellaneous data
* @param pCfg user data for the directory/location
* @param pListType the type of list (STOP or IGNORE)
* @param pValue the reg_ex to insert in the list
* @return NULL if parameters are valid, otherwise a string describing the error
*/
const char*
setBodyList(cmd_parms* pParams, void* pCfg, const char* pListType, const char* pValue) {
if (!pValue || strlen(pValue) == 0) {
return "Missing reg_ex value for the body";
}
if (!pListType || strlen(pListType) == 0) {
return "Missing the type of list";
}
CompareConf *lConf = reinterpret_cast<CompareConf *>(pCfg);
std::string lListType(pListType);
std::string lValue(pValue);
if (strcmp("STOP", pListType) == 0)
{
lConf->mCompBody.addStopRegex(lValue);
}
else if(strcmp("IGNORE", pListType) == 0)
{
lConf->mCompBody.addIgnoreRegex(lValue);
}
else
{
return "Invalid value for the list type";
}
return NULL;
}
/**
* @brief Set the list of errors to ignore in the comparison
* @param pParams miscellaneous data
* @param pCfg user data for the directory/location
* @param pListType the type of list (STOP or IGNORE)
* @param pHeader the header for which to apply the regex
* @param pValue the reg_ex to insert in the list
* @return NULL if parameters are valid, otherwise a string describing the error
*/
const char* setHeaderList(cmd_parms* pParams, void* pCfg, const char* pListType, const char* pAffectedKey,const char* pValue) {
if (!pValue || strlen(pValue) == 0) {
return "Missing reg_ex value for the header";
}
if (!pAffectedKey || strlen(pAffectedKey) == 0) {
return "Missing header value";
}
if (!pListType || strlen(pListType) == 0) {
return "Missing the type list";
}
CompareConf *lConf = reinterpret_cast<CompareConf *>(pCfg);
std::string lHeader(pAffectedKey);
std::string lValue(pValue);
if (strcmp("STOP", pListType) == 0)
{
lConf->mCompHeader.addStopRegex(lHeader, lValue);
}
else if(strcmp("IGNORE", pListType) == 0)
{
lConf->mCompHeader.addIgnoreRegex(lHeader, lValue);
}
else
{
return "Invalid value for the list type";
}
return NULL;
}
/**
* @brief Enable/Disable the utilization of the libws-diff tools
* @param pParams miscellaneous data
* @param pCfg user data for the directory/location
* @param pValue the value
* @return NULL if parameters are valid, otherwise a string describing the error
*/
const char*
setDisableLibwsdiff(cmd_parms* pParams, void* pCfg, const char* pValue) {
Log::init();
CompareConf *lConf = reinterpret_cast<CompareConf *>(pCfg);
lConf->mCompareDisabled= strcmp(pValue, "1")==0 || strcmp(pValue, "true")==0;
if(lConf->mCompareDisabled){
Log::warn(42,"The use of the diffing library \nlibws-diff has been disabled!");
}
return NULL;
}
const char*
setCompareLog(cmd_parms* pParams, void* pCfg, const char* pType, const char* pValue) {
if (!pType || strlen(pValue) == 0) {
return "Missing log type";
}
if (!pValue || strlen(pValue) == 0) {
return "Missing file path or facility";
}
if (strcmp("FILE", pType) == 0)
{
gWriteInFile = true;
gFilePath = pValue;
}
else if(strcmp("SYSLOG", pType) == 0)
{
gLogFacility = std::string(pValue);
gWriteInFile = false;
//closes the log if it was initialized
Log::close();
//initializes the log
Log::init(gLogFacility);
}
else
{
return "Invalid value for the log type";
}
return NULL;
}
const char*
setCompare(cmd_parms* pParams, void* pCfg, const char* pValue) {
CompareConf *lConf = reinterpret_cast<CompareConf *>(pCfg);
lConf->mIsActive= true;
#ifndef UNIT_TESTING
if (!ap_find_linked_module(MOD_REWRITE_NAME)) {
return "'mod_rewrite' is not loaded, Enable mod_rewrite to use mod_compare";
}
#endif
return NULL;
}
/** @brief Declaration of configuration commands */
command_rec gCmds[] = {
// AP_INIT_(directive,
// function,
// void * extra data,
// overrides to allow in order to enable,
// help message),
AP_INIT_TAKE2("BodyList",
reinterpret_cast<const char *(*)()>(&setBodyList),
0,
ACCESS_CONF,
"List of reg_ex to apply to the body for the comparison."),
AP_INIT_TAKE3("HeaderList",
reinterpret_cast<const char *(*)()>(&setHeaderList),
0,
ACCESS_CONF,
"List of reg_ex to apply to the Header for the comparison."),
AP_INIT_NO_ARGS("Compare",
reinterpret_cast<const char *(*)()>(&setCompare),
0,
ACCESS_CONF,
"Activate mod_compare."),
AP_INIT_TAKE2("CompareLog",
reinterpret_cast<const char *(*)()>(&setCompareLog),
0,
OR_ALL,
"Log to a facility instead of a file."),
AP_INIT_TAKE1("DisableLibwsdiff",
reinterpret_cast<const char *(*)()>(&setDisableLibwsdiff),
0,
ACCESS_CONF,
"Disable the use of libws-diff tools. Print raw serialization of the data in the log file."),
{0}
};
#ifndef UNIT_TESTING
static void insertInputFilter(request_rec *pRequest) {
CompareConf *lConf = reinterpret_cast<CompareConf *>(ap_get_module_config(pRequest->per_dir_config, &compare_module));
assert(lConf);
if (lConf->mIsActive){
ap_add_input_filter(gName, NULL, pRequest, pRequest->connection);
}
}
static void insertOutputFilter(request_rec *pRequest) {
CompareConf *lConf = reinterpret_cast<CompareConf *>(ap_get_module_config(pRequest->per_dir_config, &compare_module));
assert(lConf);
if (lConf->mIsActive){
ap_add_output_filter(gNameOut, NULL, pRequest, pRequest->connection);
}
}
static void insertOutputFilter2(request_rec *pRequest) {
CompareConf *lConf = reinterpret_cast<CompareConf *>(ap_get_module_config(pRequest->per_dir_config, &compare_module));
assert(lConf);
if (lConf->mIsActive){
ap_add_output_filter(gNameOut2, NULL, pRequest, pRequest->connection);
}
}
#endif
/**
* @brief register hooks in apache
* @param pPool the apache pool
*/
void
registerHooks(apr_pool_t *pPool) {
#ifndef UNIT_TESTING
ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_child_init(&childInit, NULL, NULL, APR_HOOK_MIDDLE);
ap_register_input_filter(gName, inputFilterHandler, NULL, AP_FTYPE_RESOURCE);
// output filter of type AP_FTYPE_RESOURCE => only the body will be read ( the headers_out not set yet)
ap_register_output_filter(gNameOut, outputFilterHandler, NULL, AP_FTYPE_RESOURCE);
// output filter of type AP_FTYPE_CONNECTION => only the response header will be read
ap_register_output_filter(gNameOut2, outputFilterHandler2, NULL, AP_FTYPE_TRANSCODE);
ap_hook_insert_filter(&insertInputFilter, NULL, NULL, APR_HOOK_FIRST);
ap_hook_insert_filter(&insertOutputFilter, NULL, NULL, APR_HOOK_LAST);
ap_hook_insert_filter(&insertOutputFilter2, NULL, NULL, APR_HOOK_LAST);
ap_hook_translate_name(&translateHook, NULL, NULL, APR_HOOK_MIDDLE);
#endif
}
} // End namespace
/// Apache module declaration
module AP_MODULE_DECLARE_DATA compare_module = {
STANDARD20_MODULE_STUFF,
CompareModule::createDirConfig,
0, // merge_dir_config
0, // create_server_config
0, // merge_server_config
CompareModule::gCmds,
CompareModule::registerHooks
};
<commit_msg>removed ap_hook_insert_filter for the input filter, to be able to specify it via conf<commit_after>/*
* mod_compare - compares apache requests
*
* Copyright (C) 2013 Orange
*
* 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 <httpd.h>
#include <http_config.h>
#include <http_request.h>
#include <http_protocol.h>
#include <http_connection.h>
#include <apr_pools.h>
#include <apr_hooks.h>
#include "apr_strings.h"
#include <unistd.h>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <exception>
#include <set>
#include <sstream>
#include <sys/syscall.h>
#include <algorithm>
#include <boost/tokenizer.hpp>
#include <fstream>
#include <unixd.h>
#include "mod_compare.hh"
#define MOD_REWRITE_NAME "mod_rewrite.c"
namespace alg = boost::algorithm;
namespace CompareModule {
const char* gName = "Compare";
const char* gNameOut = "CompareOut";
const char* gNameOut2 = "CompareOut2";
const char* c_COMPONENT_VERSION = "Compare/1.0";
const char* c_named_mutex = "mod_compare_log_mutex";
bool gRem = boost::interprocess::named_mutex::remove(c_named_mutex);
std::ofstream gFile;
const char * gFilePath = "/var/opt/hosting/log/apache2/compare_diff.log";
bool gWriteInFile = true;
std::string gLogFacility;
boost::interprocess::named_mutex &getGlobalMutex() {
static boost::interprocess::named_mutex *gMutex = NULL;
try {
if (!gMutex) {
gMutex = new boost::interprocess::named_mutex(boost::interprocess::open_or_create, c_named_mutex);
}
return *gMutex;
} catch (boost::interprocess::interprocess_exception& e) {
// Just in case the log has not been init yet
Log::init();
Log::error(42, "Cannot initialize global mutex named: %s. What: %s", c_named_mutex, e.what());
throw e;
}
}
CompareConf::CompareConf(): mCompareDisabled(false), mIsActive(false) {
}
apr_status_t CompareConf::cleaner(void *self) {
if(self){
CompareConf *c = reinterpret_cast<CompareConf *>(self);
c->~CompareConf();
}
return 0;
}
/**
* @brief allocate a pointer to a string which will hold the path for the dir config if mod_compare is active on it
* @param pPool the apache pool on which to allocate data
* @param pDirName the directory name for which to create data
* @return a void pointer to newly allocated object
*/
void *
createDirConfig(apr_pool_t *pPool, char *pDirName)
{
void *addr= apr_pcalloc(pPool, sizeof(class CompareConf));
new (addr) CompareConf();
apr_pool_cleanup_register(pPool, addr, CompareConf::cleaner, apr_pool_cleanup_null);
return addr;
}
/**
* @brief Initialize logging post-config
* @param pPool the apache pool
* @param pServer the corresponding server record
* @return Always OK
*/
int
postConfig(apr_pool_t * pPool, apr_pool_t * pLog, apr_pool_t * pTemp, server_rec * pServer) {
Log::init();
ap_add_version_component(pPool, c_COMPONENT_VERSION) ;
if( !gWriteInFile ){
return APR_SUCCESS;
}
apr_pool_cleanup_register(pPool, NULL, apr_pool_cleanup_null, closeLogFile);
return openLogFile(gFilePath, std::ofstream::out | std::ofstream::app);
}
apr_status_t
closeLogFile(void *) {
gFile.close();
return APR_SUCCESS;
}
apr_status_t openLogFile(const char * filepath,std::ios_base::openmode mode) {
gFile.open(filepath,mode);
if (!gFile.is_open()){
Log::error(43,"Couldn't open correctly the file");
return 400; // to modify
}
if ( chown(filepath, unixd_config.user_id, unixd_config.group_id) < 0 ) {
Log::error(528, "Failed to change ownership of shared mem file %s to child user %s, error %d (%s)", filepath, unixd_config.user_name, errno, strerror(errno) );
}
gFile.close();
return APR_SUCCESS;
}
void
childInit(apr_pool_t *pPool, server_rec *pServer)
{
if( gWriteInFile ){
gFile.open(gFilePath, std::ofstream::out | std::ofstream::app );
if (!gFile.is_open()){
Log::error(43,"Couldn't open correctly the file");
}
}
}
/**
* @brief Set the list of errors which stop the comparison
* @param pParams miscellaneous data
* @param pCfg user data for the directory/location
* @param pListType the type of list (STOP or IGNORE)
* @param pValue the reg_ex to insert in the list
* @return NULL if parameters are valid, otherwise a string describing the error
*/
const char*
setBodyList(cmd_parms* pParams, void* pCfg, const char* pListType, const char* pValue) {
if (!pValue || strlen(pValue) == 0) {
return "Missing reg_ex value for the body";
}
if (!pListType || strlen(pListType) == 0) {
return "Missing the type of list";
}
CompareConf *lConf = reinterpret_cast<CompareConf *>(pCfg);
std::string lListType(pListType);
std::string lValue(pValue);
if (strcmp("STOP", pListType) == 0)
{
lConf->mCompBody.addStopRegex(lValue);
}
else if(strcmp("IGNORE", pListType) == 0)
{
lConf->mCompBody.addIgnoreRegex(lValue);
}
else
{
return "Invalid value for the list type";
}
return NULL;
}
/**
* @brief Set the list of errors to ignore in the comparison
* @param pParams miscellaneous data
* @param pCfg user data for the directory/location
* @param pListType the type of list (STOP or IGNORE)
* @param pHeader the header for which to apply the regex
* @param pValue the reg_ex to insert in the list
* @return NULL if parameters are valid, otherwise a string describing the error
*/
const char* setHeaderList(cmd_parms* pParams, void* pCfg, const char* pListType, const char* pAffectedKey,const char* pValue) {
if (!pValue || strlen(pValue) == 0) {
return "Missing reg_ex value for the header";
}
if (!pAffectedKey || strlen(pAffectedKey) == 0) {
return "Missing header value";
}
if (!pListType || strlen(pListType) == 0) {
return "Missing the type list";
}
CompareConf *lConf = reinterpret_cast<CompareConf *>(pCfg);
std::string lHeader(pAffectedKey);
std::string lValue(pValue);
if (strcmp("STOP", pListType) == 0)
{
lConf->mCompHeader.addStopRegex(lHeader, lValue);
}
else if(strcmp("IGNORE", pListType) == 0)
{
lConf->mCompHeader.addIgnoreRegex(lHeader, lValue);
}
else
{
return "Invalid value for the list type";
}
return NULL;
}
/**
* @brief Enable/Disable the utilization of the libws-diff tools
* @param pParams miscellaneous data
* @param pCfg user data for the directory/location
* @param pValue the value
* @return NULL if parameters are valid, otherwise a string describing the error
*/
const char*
setDisableLibwsdiff(cmd_parms* pParams, void* pCfg, const char* pValue) {
Log::init();
CompareConf *lConf = reinterpret_cast<CompareConf *>(pCfg);
lConf->mCompareDisabled= strcmp(pValue, "1")==0 || strcmp(pValue, "true")==0;
if(lConf->mCompareDisabled){
Log::warn(42,"The use of the diffing library \nlibws-diff has been disabled!");
}
return NULL;
}
const char*
setCompareLog(cmd_parms* pParams, void* pCfg, const char* pType, const char* pValue) {
if (!pType || strlen(pValue) == 0) {
return "Missing log type";
}
if (!pValue || strlen(pValue) == 0) {
return "Missing file path or facility";
}
if (strcmp("FILE", pType) == 0)
{
gWriteInFile = true;
gFilePath = pValue;
}
else if(strcmp("SYSLOG", pType) == 0)
{
gLogFacility = std::string(pValue);
gWriteInFile = false;
//closes the log if it was initialized
Log::close();
//initializes the log
Log::init(gLogFacility);
}
else
{
return "Invalid value for the log type";
}
return NULL;
}
const char*
setCompare(cmd_parms* pParams, void* pCfg, const char* pValue) {
CompareConf *lConf = reinterpret_cast<CompareConf *>(pCfg);
lConf->mIsActive= true;
#ifndef UNIT_TESTING
if (!ap_find_linked_module(MOD_REWRITE_NAME)) {
return "'mod_rewrite' is not loaded, Enable mod_rewrite to use mod_compare";
}
#endif
return NULL;
}
/** @brief Declaration of configuration commands */
command_rec gCmds[] = {
// AP_INIT_(directive,
// function,
// void * extra data,
// overrides to allow in order to enable,
// help message),
AP_INIT_TAKE2("BodyList",
reinterpret_cast<const char *(*)()>(&setBodyList),
0,
ACCESS_CONF,
"List of reg_ex to apply to the body for the comparison."),
AP_INIT_TAKE3("HeaderList",
reinterpret_cast<const char *(*)()>(&setHeaderList),
0,
ACCESS_CONF,
"List of reg_ex to apply to the Header for the comparison."),
AP_INIT_NO_ARGS("Compare",
reinterpret_cast<const char *(*)()>(&setCompare),
0,
ACCESS_CONF,
"Activate mod_compare."),
AP_INIT_TAKE2("CompareLog",
reinterpret_cast<const char *(*)()>(&setCompareLog),
0,
OR_ALL,
"Log to a facility instead of a file."),
AP_INIT_TAKE1("DisableLibwsdiff",
reinterpret_cast<const char *(*)()>(&setDisableLibwsdiff),
0,
ACCESS_CONF,
"Disable the use of libws-diff tools. Print raw serialization of the data in the log file."),
{0}
};
#ifndef UNIT_TESTING
static void insertInputFilter(request_rec *pRequest) {
CompareConf *lConf = reinterpret_cast<CompareConf *>(ap_get_module_config(pRequest->per_dir_config, &compare_module));
assert(lConf);
if (lConf->mIsActive){
ap_add_input_filter(gName, NULL, pRequest, pRequest->connection);
}
}
static void insertOutputFilter(request_rec *pRequest) {
CompareConf *lConf = reinterpret_cast<CompareConf *>(ap_get_module_config(pRequest->per_dir_config, &compare_module));
assert(lConf);
if (lConf->mIsActive){
ap_add_output_filter(gNameOut, NULL, pRequest, pRequest->connection);
}
}
static void insertOutputFilter2(request_rec *pRequest) {
CompareConf *lConf = reinterpret_cast<CompareConf *>(ap_get_module_config(pRequest->per_dir_config, &compare_module));
assert(lConf);
if (lConf->mIsActive){
ap_add_output_filter(gNameOut2, NULL, pRequest, pRequest->connection);
}
}
#endif
/**
* @brief register hooks in apache
* @param pPool the apache pool
*/
void
registerHooks(apr_pool_t *pPool) {
#ifndef UNIT_TESTING
ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE);
ap_hook_child_init(&childInit, NULL, NULL, APR_HOOK_MIDDLE);
ap_register_input_filter(gName, inputFilterHandler, NULL, AP_FTYPE_RESOURCE);
// output filter of type AP_FTYPE_RESOURCE => only the body will be read ( the headers_out not set yet)
ap_register_output_filter(gNameOut, outputFilterHandler, NULL, AP_FTYPE_RESOURCE);
// output filter of type AP_FTYPE_CONNECTION => only the response header will be read
ap_register_output_filter(gNameOut2, outputFilterHandler2, NULL, AP_FTYPE_TRANSCODE);
// ap_hook_insert_filter(&insertInputFilter, NULL, NULL, APR_HOOK_FIRST);
ap_hook_insert_filter(&insertOutputFilter, NULL, NULL, APR_HOOK_LAST);
ap_hook_insert_filter(&insertOutputFilter2, NULL, NULL, APR_HOOK_LAST);
ap_hook_translate_name(&translateHook, NULL, NULL, APR_HOOK_MIDDLE);
#endif
}
} // End namespace
/// Apache module declaration
module AP_MODULE_DECLARE_DATA compare_module = {
STANDARD20_MODULE_STUFF,
CompareModule::createDirConfig,
0, // merge_dir_config
0, // create_server_config
0, // merge_server_config
CompareModule::gCmds,
CompareModule::registerHooks
};
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2007 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "arch/x86/generated/decoder.hh"
#include "arch/x86/faults.hh"
#include "arch/x86/isa_traits.hh"
#include "base/trace.hh"
#include "cpu/thread_context.hh"
#include "debug/Faults.hh"
#include "sim/full_system.hh"
namespace X86ISA
{
void X86FaultBase::invoke(ThreadContext * tc, StaticInstPtr inst)
{
if (!FullSystem) {
FaultBase::invoke(tc, inst);
return;
}
PCState pcState = tc->pcState();
Addr pc = pcState.pc();
DPRINTF(Faults, "RIP %#x: vector %d: %s\n",
pc, vector, describe());
using namespace X86ISAInst::RomLabels;
HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);
MicroPC entry;
if (m5reg.mode == LongMode) {
if (isSoft()) {
entry = extern_label_longModeSoftInterrupt;
} else {
entry = extern_label_longModeInterrupt;
}
} else {
entry = extern_label_legacyModeInterrupt;
}
tc->setIntReg(INTREG_MICRO(1), vector);
tc->setIntReg(INTREG_MICRO(7), pc);
if (errorCode != (uint64_t)(-1)) {
if (m5reg.mode == LongMode) {
entry = extern_label_longModeInterruptWithError;
} else {
panic("Legacy mode interrupts with error codes "
"aren't implementde.\n");
}
// Software interrupts shouldn't have error codes. If one
// does, there would need to be microcode to set it up.
assert(!isSoft());
tc->setIntReg(INTREG_MICRO(15), errorCode);
}
pcState.upc(romMicroPC(entry));
pcState.nupc(romMicroPC(entry) + 1);
tc->pcState(pcState);
}
std::string
X86FaultBase::describe() const
{
std::stringstream ss;
ccprintf(ss, "%s", mnemonic());
if (errorCode != (uint64_t)(-1)) {
ccprintf(ss, "(%#x)", errorCode);
}
return ss.str();
}
void X86Trap::invoke(ThreadContext * tc, StaticInstPtr inst)
{
X86FaultBase::invoke(tc);
if (!FullSystem)
return;
// This is the same as a fault, but it happens -after- the
// instruction.
PCState pc = tc->pcState();
pc.uEnd();
}
void X86Abort::invoke(ThreadContext * tc, StaticInstPtr inst)
{
panic("Abort exception!");
}
void
InvalidOpcode::invoke(ThreadContext * tc, StaticInstPtr inst)
{
if (FullSystem) {
X86Fault::invoke(tc, inst);
} else {
panic("Unrecognized/invalid instruction executed:\n %s",
inst->machInst);
}
}
void PageFault::invoke(ThreadContext * tc, StaticInstPtr inst)
{
if (FullSystem) {
HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);
X86FaultBase::invoke(tc);
/*
* If something bad happens while trying to enter the page fault
* handler, I'm pretty sure that's a double fault and then all
* bets are off. That means it should be safe to update this
* state now.
*/
if (m5reg.mode == LongMode) {
tc->setMiscReg(MISCREG_CR2, addr);
} else {
tc->setMiscReg(MISCREG_CR2, (uint32_t)addr);
}
} else {
PageFaultErrorCode code = errorCode;
const char *modeStr = "";
if (code.fetch)
modeStr = "execute";
else if (code.write)
modeStr = "write";
else
modeStr = "read";
panic("Tried to %s unmapped address %#x.\n", modeStr, addr);
}
}
std::string
PageFault::describe() const
{
std::stringstream ss;
ccprintf(ss, "%s at %#x", X86FaultBase::describe(), addr);
return ss.str();
}
void
InitInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst)
{
DPRINTF(Faults, "Init interrupt.\n");
// The otherwise unmodified integer registers should be set to 0.
for (int index = 0; index < NUM_INTREGS; index++) {
tc->setIntReg(index, 0);
}
CR0 cr0 = tc->readMiscReg(MISCREG_CR0);
CR0 newCR0 = 1 << 4;
newCR0.cd = cr0.cd;
newCR0.nw = cr0.nw;
tc->setMiscReg(MISCREG_CR0, newCR0);
tc->setMiscReg(MISCREG_CR2, 0);
tc->setMiscReg(MISCREG_CR3, 0);
tc->setMiscReg(MISCREG_CR4, 0);
tc->setMiscReg(MISCREG_RFLAGS, 0x0000000000000002ULL);
tc->setMiscReg(MISCREG_EFER, 0);
SegAttr dataAttr = 0;
dataAttr.dpl = 0;
dataAttr.unusable = 0;
dataAttr.defaultSize = 0;
dataAttr.longMode = 0;
dataAttr.avl = 0;
dataAttr.granularity = 0;
dataAttr.present = 1;
dataAttr.type = 3;
dataAttr.writable = 1;
dataAttr.readable = 1;
dataAttr.expandDown = 0;
dataAttr.system = 1;
for (int seg = 0; seg != NUM_SEGMENTREGS; seg++) {
tc->setMiscReg(MISCREG_SEG_SEL(seg), 0);
tc->setMiscReg(MISCREG_SEG_BASE(seg), 0);
tc->setMiscReg(MISCREG_SEG_EFF_BASE(seg), 0);
tc->setMiscReg(MISCREG_SEG_LIMIT(seg), 0xffff);
tc->setMiscReg(MISCREG_SEG_ATTR(seg), dataAttr);
}
SegAttr codeAttr = 0;
codeAttr.dpl = 0;
codeAttr.unusable = 0;
codeAttr.defaultSize = 0;
codeAttr.longMode = 0;
codeAttr.avl = 0;
codeAttr.granularity = 0;
codeAttr.present = 1;
codeAttr.type = 10;
codeAttr.writable = 0;
codeAttr.readable = 1;
codeAttr.expandDown = 0;
codeAttr.system = 1;
tc->setMiscReg(MISCREG_CS, 0xf000);
tc->setMiscReg(MISCREG_CS_BASE,
0x00000000ffff0000ULL);
tc->setMiscReg(MISCREG_CS_EFF_BASE,
0x00000000ffff0000ULL);
// This has the base value pre-added.
tc->setMiscReg(MISCREG_CS_LIMIT, 0xffffffff);
tc->setMiscReg(MISCREG_CS_ATTR, codeAttr);
PCState pc(0x000000000000fff0ULL + tc->readMiscReg(MISCREG_CS_BASE));
tc->pcState(pc);
tc->setMiscReg(MISCREG_TSG_BASE, 0);
tc->setMiscReg(MISCREG_TSG_LIMIT, 0xffff);
tc->setMiscReg(MISCREG_IDTR_BASE, 0);
tc->setMiscReg(MISCREG_IDTR_LIMIT, 0xffff);
tc->setMiscReg(MISCREG_TSL, 0);
tc->setMiscReg(MISCREG_TSL_BASE, 0);
tc->setMiscReg(MISCREG_TSL_LIMIT, 0xffff);
tc->setMiscReg(MISCREG_TSL_ATTR, 0);
tc->setMiscReg(MISCREG_TR, 0);
tc->setMiscReg(MISCREG_TR_BASE, 0);
tc->setMiscReg(MISCREG_TR_LIMIT, 0xffff);
tc->setMiscReg(MISCREG_TR_ATTR, 0);
// This value should be the family/model/stepping of the processor.
// (page 418). It should be consistent with the value from CPUID, but
// the actual value probably doesn't matter much.
tc->setIntReg(INTREG_RDX, 0);
tc->setMiscReg(MISCREG_DR0, 0);
tc->setMiscReg(MISCREG_DR1, 0);
tc->setMiscReg(MISCREG_DR2, 0);
tc->setMiscReg(MISCREG_DR3, 0);
tc->setMiscReg(MISCREG_DR6, 0x00000000ffff0ff0ULL);
tc->setMiscReg(MISCREG_DR7, 0x0000000000000400ULL);
// Update the handy M5 Reg.
tc->setMiscReg(MISCREG_M5_REG, 0);
MicroPC entry = X86ISAInst::RomLabels::extern_label_initIntHalt;
pc.upc(romMicroPC(entry));
pc.nupc(romMicroPC(entry) + 1);
tc->pcState(pc);
}
void
StartupInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst)
{
DPRINTF(Faults, "Startup interrupt with vector %#x.\n", vector);
HandyM5Reg m5Reg = tc->readMiscReg(MISCREG_M5_REG);
if (m5Reg.mode != LegacyMode || m5Reg.submode != RealMode) {
panic("Startup IPI recived outside of real mode. "
"Don't know what to do. %d, %d", m5Reg.mode, m5Reg.submode);
}
tc->setMiscReg(MISCREG_CS, vector << 8);
tc->setMiscReg(MISCREG_CS_BASE, vector << 12);
tc->setMiscReg(MISCREG_CS_EFF_BASE, vector << 12);
// This has the base value pre-added.
tc->setMiscReg(MISCREG_CS_LIMIT, 0xffff);
tc->pcState(tc->readMiscReg(MISCREG_CS_BASE));
}
} // namespace X86ISA
<commit_msg>x86: Initialize the MXCSR register<commit_after>/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2007 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabe Black
*/
#include "arch/x86/generated/decoder.hh"
#include "arch/x86/faults.hh"
#include "arch/x86/isa_traits.hh"
#include "base/trace.hh"
#include "cpu/thread_context.hh"
#include "debug/Faults.hh"
#include "sim/full_system.hh"
namespace X86ISA
{
void X86FaultBase::invoke(ThreadContext * tc, StaticInstPtr inst)
{
if (!FullSystem) {
FaultBase::invoke(tc, inst);
return;
}
PCState pcState = tc->pcState();
Addr pc = pcState.pc();
DPRINTF(Faults, "RIP %#x: vector %d: %s\n",
pc, vector, describe());
using namespace X86ISAInst::RomLabels;
HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);
MicroPC entry;
if (m5reg.mode == LongMode) {
if (isSoft()) {
entry = extern_label_longModeSoftInterrupt;
} else {
entry = extern_label_longModeInterrupt;
}
} else {
entry = extern_label_legacyModeInterrupt;
}
tc->setIntReg(INTREG_MICRO(1), vector);
tc->setIntReg(INTREG_MICRO(7), pc);
if (errorCode != (uint64_t)(-1)) {
if (m5reg.mode == LongMode) {
entry = extern_label_longModeInterruptWithError;
} else {
panic("Legacy mode interrupts with error codes "
"aren't implementde.\n");
}
// Software interrupts shouldn't have error codes. If one
// does, there would need to be microcode to set it up.
assert(!isSoft());
tc->setIntReg(INTREG_MICRO(15), errorCode);
}
pcState.upc(romMicroPC(entry));
pcState.nupc(romMicroPC(entry) + 1);
tc->pcState(pcState);
}
std::string
X86FaultBase::describe() const
{
std::stringstream ss;
ccprintf(ss, "%s", mnemonic());
if (errorCode != (uint64_t)(-1)) {
ccprintf(ss, "(%#x)", errorCode);
}
return ss.str();
}
void X86Trap::invoke(ThreadContext * tc, StaticInstPtr inst)
{
X86FaultBase::invoke(tc);
if (!FullSystem)
return;
// This is the same as a fault, but it happens -after- the
// instruction.
PCState pc = tc->pcState();
pc.uEnd();
}
void X86Abort::invoke(ThreadContext * tc, StaticInstPtr inst)
{
panic("Abort exception!");
}
void
InvalidOpcode::invoke(ThreadContext * tc, StaticInstPtr inst)
{
if (FullSystem) {
X86Fault::invoke(tc, inst);
} else {
panic("Unrecognized/invalid instruction executed:\n %s",
inst->machInst);
}
}
void PageFault::invoke(ThreadContext * tc, StaticInstPtr inst)
{
if (FullSystem) {
HandyM5Reg m5reg = tc->readMiscRegNoEffect(MISCREG_M5_REG);
X86FaultBase::invoke(tc);
/*
* If something bad happens while trying to enter the page fault
* handler, I'm pretty sure that's a double fault and then all
* bets are off. That means it should be safe to update this
* state now.
*/
if (m5reg.mode == LongMode) {
tc->setMiscReg(MISCREG_CR2, addr);
} else {
tc->setMiscReg(MISCREG_CR2, (uint32_t)addr);
}
} else {
PageFaultErrorCode code = errorCode;
const char *modeStr = "";
if (code.fetch)
modeStr = "execute";
else if (code.write)
modeStr = "write";
else
modeStr = "read";
panic("Tried to %s unmapped address %#x.\n", modeStr, addr);
}
}
std::string
PageFault::describe() const
{
std::stringstream ss;
ccprintf(ss, "%s at %#x", X86FaultBase::describe(), addr);
return ss.str();
}
void
InitInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst)
{
DPRINTF(Faults, "Init interrupt.\n");
// The otherwise unmodified integer registers should be set to 0.
for (int index = 0; index < NUM_INTREGS; index++) {
tc->setIntReg(index, 0);
}
CR0 cr0 = tc->readMiscReg(MISCREG_CR0);
CR0 newCR0 = 1 << 4;
newCR0.cd = cr0.cd;
newCR0.nw = cr0.nw;
tc->setMiscReg(MISCREG_CR0, newCR0);
tc->setMiscReg(MISCREG_CR2, 0);
tc->setMiscReg(MISCREG_CR3, 0);
tc->setMiscReg(MISCREG_CR4, 0);
tc->setMiscReg(MISCREG_RFLAGS, 0x0000000000000002ULL);
tc->setMiscReg(MISCREG_EFER, 0);
SegAttr dataAttr = 0;
dataAttr.dpl = 0;
dataAttr.unusable = 0;
dataAttr.defaultSize = 0;
dataAttr.longMode = 0;
dataAttr.avl = 0;
dataAttr.granularity = 0;
dataAttr.present = 1;
dataAttr.type = 3;
dataAttr.writable = 1;
dataAttr.readable = 1;
dataAttr.expandDown = 0;
dataAttr.system = 1;
for (int seg = 0; seg != NUM_SEGMENTREGS; seg++) {
tc->setMiscReg(MISCREG_SEG_SEL(seg), 0);
tc->setMiscReg(MISCREG_SEG_BASE(seg), 0);
tc->setMiscReg(MISCREG_SEG_EFF_BASE(seg), 0);
tc->setMiscReg(MISCREG_SEG_LIMIT(seg), 0xffff);
tc->setMiscReg(MISCREG_SEG_ATTR(seg), dataAttr);
}
SegAttr codeAttr = 0;
codeAttr.dpl = 0;
codeAttr.unusable = 0;
codeAttr.defaultSize = 0;
codeAttr.longMode = 0;
codeAttr.avl = 0;
codeAttr.granularity = 0;
codeAttr.present = 1;
codeAttr.type = 10;
codeAttr.writable = 0;
codeAttr.readable = 1;
codeAttr.expandDown = 0;
codeAttr.system = 1;
tc->setMiscReg(MISCREG_CS, 0xf000);
tc->setMiscReg(MISCREG_CS_BASE,
0x00000000ffff0000ULL);
tc->setMiscReg(MISCREG_CS_EFF_BASE,
0x00000000ffff0000ULL);
// This has the base value pre-added.
tc->setMiscReg(MISCREG_CS_LIMIT, 0xffffffff);
tc->setMiscReg(MISCREG_CS_ATTR, codeAttr);
PCState pc(0x000000000000fff0ULL + tc->readMiscReg(MISCREG_CS_BASE));
tc->pcState(pc);
tc->setMiscReg(MISCREG_TSG_BASE, 0);
tc->setMiscReg(MISCREG_TSG_LIMIT, 0xffff);
tc->setMiscReg(MISCREG_IDTR_BASE, 0);
tc->setMiscReg(MISCREG_IDTR_LIMIT, 0xffff);
tc->setMiscReg(MISCREG_TSL, 0);
tc->setMiscReg(MISCREG_TSL_BASE, 0);
tc->setMiscReg(MISCREG_TSL_LIMIT, 0xffff);
tc->setMiscReg(MISCREG_TSL_ATTR, 0);
tc->setMiscReg(MISCREG_TR, 0);
tc->setMiscReg(MISCREG_TR_BASE, 0);
tc->setMiscReg(MISCREG_TR_LIMIT, 0xffff);
tc->setMiscReg(MISCREG_TR_ATTR, 0);
// This value should be the family/model/stepping of the processor.
// (page 418). It should be consistent with the value from CPUID, but
// the actual value probably doesn't matter much.
tc->setIntReg(INTREG_RDX, 0);
tc->setMiscReg(MISCREG_DR0, 0);
tc->setMiscReg(MISCREG_DR1, 0);
tc->setMiscReg(MISCREG_DR2, 0);
tc->setMiscReg(MISCREG_DR3, 0);
tc->setMiscReg(MISCREG_DR6, 0x00000000ffff0ff0ULL);
tc->setMiscReg(MISCREG_DR7, 0x0000000000000400ULL);
tc->setMiscReg(MISCREG_MXCSR, 0x1f80);
// Update the handy M5 Reg.
tc->setMiscReg(MISCREG_M5_REG, 0);
MicroPC entry = X86ISAInst::RomLabels::extern_label_initIntHalt;
pc.upc(romMicroPC(entry));
pc.nupc(romMicroPC(entry) + 1);
tc->pcState(pc);
}
void
StartupInterrupt::invoke(ThreadContext *tc, StaticInstPtr inst)
{
DPRINTF(Faults, "Startup interrupt with vector %#x.\n", vector);
HandyM5Reg m5Reg = tc->readMiscReg(MISCREG_M5_REG);
if (m5Reg.mode != LegacyMode || m5Reg.submode != RealMode) {
panic("Startup IPI recived outside of real mode. "
"Don't know what to do. %d, %d", m5Reg.mode, m5Reg.submode);
}
tc->setMiscReg(MISCREG_CS, vector << 8);
tc->setMiscReg(MISCREG_CS_BASE, vector << 12);
tc->setMiscReg(MISCREG_CS_EFF_BASE, vector << 12);
// This has the base value pre-added.
tc->setMiscReg(MISCREG_CS_LIMIT, 0xffff);
tc->pcState(tc->readMiscReg(MISCREG_CS_BASE));
}
} // namespace X86ISA
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SvXMLAutoCorrectExport.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-17 04:47:27 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _SV_XMLAUTOCORRECTEXPORT_HXX
#include <SvXMLAutoCorrectExport.hxx>
#endif
#define _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;
// #110680#
SvXMLAutoCorrectExport::SvXMLAutoCorrectExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const SvxAutocorrWordList * pNewAutocorr_List,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler)
: SvXMLExport( xServiceFactory, rFileName, rHandler ),
pAutocorr_List( pNewAutocorr_List )
{
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_BLOCK_LIST),
GetXMLToken ( XML_N_BLOCK_LIST ),
XML_NAMESPACE_BLOCKLIST );
}
sal_uInt32 SvXMLAutoCorrectExport::exportDoc(enum XMLTokenEnum eClass)
{
GetDocHandler()->startDocument();
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_BLOCKLIST ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_BLOCKLIST ) );
{
SvXMLElementExport aRoot (*this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK_LIST, sal_True, sal_True);
sal_uInt16 nBlocks= pAutocorr_List->Count();
for ( sal_uInt16 i = 0; i < nBlocks; i++)
{
SvxAutocorrWord* p = pAutocorr_List->GetObject(i);
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_ABBREVIATED_NAME,
OUString(p->GetShort()));
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_NAME,
OUString(p->IsTextOnly() ? p->GetLong() : p->GetShort()));
SvXMLElementExport aBlock( *this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK, sal_True, sal_True);
}
}
GetDocHandler()->endDocument();
return 0;
}
// #110680#
SvXMLExceptionListExport::SvXMLExceptionListExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const SvStringsISortDtor &rNewList,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler)
: SvXMLExport( xServiceFactory, rFileName, rHandler ),
rList( rNewList )
{
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_BLOCK_LIST ),
GetXMLToken ( XML_N_BLOCK_LIST ),
XML_NAMESPACE_BLOCKLIST );
}
sal_uInt32 SvXMLExceptionListExport::exportDoc(enum XMLTokenEnum eClass)
{
GetDocHandler()->startDocument();
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_BLOCKLIST ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_BLOCKLIST ) );
{
SvXMLElementExport aRoot (*this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK_LIST, sal_True, sal_True);
sal_uInt16 nBlocks= rList.Count();
for ( sal_uInt16 i = 0; i < nBlocks; i++)
{
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_ABBREVIATED_NAME,
OUString( *rList[i] ) );
SvXMLElementExport aBlock( *this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK, sal_True, sal_True);
}
}
GetDocHandler()->endDocument();
return 0;
}
<commit_msg>INTEGRATION: CWS sb59 (1.6.488); FILE MERGED 2006/08/03 13:51:39 cl 1.6.488.1: removed compiler warnings<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SvXMLAutoCorrectExport.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-10-12 12:33:34 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"
#ifndef _SV_XMLAUTOCORRECTEXPORT_HXX
#include <SvXMLAutoCorrectExport.hxx>
#endif
#define _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_STRINGSDTOR
#include <svtools/svstdarr.hxx>
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star;
using namespace ::xmloff::token;
using namespace ::rtl;
// #110680#
SvXMLAutoCorrectExport::SvXMLAutoCorrectExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const SvxAutocorrWordList * pNewAutocorr_List,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler)
: SvXMLExport( xServiceFactory, rFileName, rHandler ),
pAutocorr_List( pNewAutocorr_List )
{
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_BLOCK_LIST),
GetXMLToken ( XML_N_BLOCK_LIST ),
XML_NAMESPACE_BLOCKLIST );
}
sal_uInt32 SvXMLAutoCorrectExport::exportDoc(enum XMLTokenEnum /*eClass*/)
{
GetDocHandler()->startDocument();
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_BLOCKLIST ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_BLOCKLIST ) );
{
SvXMLElementExport aRoot (*this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK_LIST, sal_True, sal_True);
sal_uInt16 nBlocks= pAutocorr_List->Count();
for ( sal_uInt16 i = 0; i < nBlocks; i++)
{
SvxAutocorrWord* p = pAutocorr_List->GetObject(i);
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_ABBREVIATED_NAME,
OUString(p->GetShort()));
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_NAME,
OUString(p->IsTextOnly() ? p->GetLong() : p->GetShort()));
SvXMLElementExport aBlock( *this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK, sal_True, sal_True);
}
}
GetDocHandler()->endDocument();
return 0;
}
// #110680#
SvXMLExceptionListExport::SvXMLExceptionListExport(
const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory > xServiceFactory,
const SvStringsISortDtor &rNewList,
const rtl::OUString &rFileName,
com::sun::star::uno::Reference< com::sun::star::xml::sax::XDocumentHandler> &rHandler)
: SvXMLExport( xServiceFactory, rFileName, rHandler ),
rList( rNewList )
{
_GetNamespaceMap().Add( GetXMLToken ( XML_NP_BLOCK_LIST ),
GetXMLToken ( XML_N_BLOCK_LIST ),
XML_NAMESPACE_BLOCKLIST );
}
sal_uInt32 SvXMLExceptionListExport::exportDoc(enum XMLTokenEnum /*eClass*/)
{
GetDocHandler()->startDocument();
AddAttribute ( XML_NAMESPACE_NONE,
_GetNamespaceMap().GetAttrNameByKey ( XML_NAMESPACE_BLOCKLIST ),
_GetNamespaceMap().GetNameByKey ( XML_NAMESPACE_BLOCKLIST ) );
{
SvXMLElementExport aRoot (*this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK_LIST, sal_True, sal_True);
sal_uInt16 nBlocks= rList.Count();
for ( sal_uInt16 i = 0; i < nBlocks; i++)
{
AddAttribute( XML_NAMESPACE_BLOCKLIST,
XML_ABBREVIATED_NAME,
OUString( *rList[i] ) );
SvXMLElementExport aBlock( *this, XML_NAMESPACE_BLOCKLIST, XML_BLOCK, sal_True, sal_True);
}
}
GetDocHandler()->endDocument();
return 0;
}
<|endoftext|> |
<commit_before>//
// nthRoot.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "nthRoot.h"
using namespace std;
nthRoot::nthRoot(int root, int operand, int coefficient) {
this->type = "nthRoot";
this->operand = operand;
this->root = root;
this->coefficient = coefficient;
if ((root % 2) == 0 && operand < 0) {
throw runtime_error("unreal answer");
}
}
nthRoot::~nthRoot() {
}
int* nthRoot::primeFactorization(int n) {
int k = 0;
while (n%2 == 0) {
factors[k] = 2;
k++;
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i + 2) {
if (n%i == 0) {
while (n%i == 0) {
factors[k] = i;
k++;
n = n/i;
}
}
}
if (n > 1) {
factors[k] = n;
}
return factors;
// added bonus: factors should be sorted already
}
Expression* nthRoot::simplify(){
//if coefficient == 0 then return 0?
//if operand < 0 throw an error
if ((root % 2) == 0 && operand < 0) { //this needs to be made right
throw runtime_error("unreal answer");
}
factors = this->primeFactorization(operand);
int i = 0;
int factorsSize = sizeof(factors)/sizeof(factors[0]);
while (i <= factorsSize) { //all this takes unnecessary factors out of the operand
int j = i; //and puts them into the coefficient
int count = 0;
while (j <= factorsSize && factors[j + 1] == factors[j]) {
count++;
j++;
}
if (count >= root) {
coefficient *= (factors[i] ^ (count/root));
operand = operand / (factors[i] ^ (count - (count % root)));
}
i = j + 1;
}
if (operand == 1) {
Integer* newInt = new Integer(coefficient);
return newInt;
}
else {
Expression* newRoot = new nthRoot(root, operand, coefficient);
delete this; //is this necessary?
return newRoot;
}
}
Expression* nthRoot::add(Expression* a) {
nthRoot *b = (nthRoot *)a;
int asCoefficient = b->getCoefficient();
int asOperand = b->getOperand();
int asRoot = b->getRoot();
if (root == asRoot && operand == asOperand) {
int newCoefficient = asCoefficient + coefficient;
nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else {
return this;
}
}
Expression* nthRoot::subtract(Expression* a) {
nthRoot *b = (nthRoot *)a;
int asCoefficient = b->getCoefficient();
int asOperand = b->getOperand();
int asRoot = b->getRoot();
if (root == asRoot && operand == asOperand) {
int newCoefficient = coefficient - asCoefficient;
nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else {
return this;
}
}
Expression* nthRoot::multiply(Expression* a) {
nthRoot *b = (nthRoot *)a;
int asCoefficient = b->getCoefficient();
int asOperand = b->getOperand();
int asRoot = b->getRoot();
if (root == asRoot) {
int newCoefficient = asCoefficient * coefficient;
int newOperand = operand * asOperand; //asOperand doesnt exist?
nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else {
return this;
}
}
Expression* nthRoot::divide(Expression* a) {
nthRoot *b = (nthRoot *)a;
int asRoot = b->getRoot();
int asOperand = b->getOperand();
int asCoefficient = b->getCoefficient();
if (root == asRoot && ((double)coefficient / (double)asCoefficient) % 1 == 0 && ((double)operand / (double)asOperand) % 1 == 0) {
int newCoefficient = coefficient / asCoefficient;
int newOperand = operand / asOperand;
nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else if (((double)coefficient / (double)asCoefficient) % 1 == 0) {
int newCoefficient = coefficient / asCoefficient;
nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else {
return this;
}
}
int nthRoot::getRoot() {
return root;
}
int nthRoot::getOperand() {
return operand;
}
int nthRoot::getCoefficient() {
return coefficient;
}
void nthRoot::setCoefficient(int n) {
this->coefficient = n;
}
void nthRoot::setOperand(int n) {
this->operand = n;
}
void nthRoot::setRoot(int n) {
this->root = n;
}
ostream& nthRoot::print(std::ostream& output) const {
output << this->coefficient << "*" << this->root << "rt:" << this->operand;
return output;
}
string nthRoot::toString() {
stringstream s;
s << coefficient << "*" << root << "rt:" << operand;
return s.str();
}
<commit_msg>changed % to fmod() for doubles<commit_after>//
// nthRoot.cpp
// Calculator
//
// Created by Gavin Scheele on 3/27/14.
// Copyright (c) 2014 Gavin Scheele. All rights reserved.
//
#include "nthRoot.h"
using namespace std;
nthRoot::nthRoot(int root, int operand, int coefficient) {
this->type = "nthRoot";
this->operand = operand;
this->root = root;
this->coefficient = coefficient;
if ((root % 2) == 0 && operand < 0) {
throw runtime_error("unreal answer");
}
}
nthRoot::~nthRoot() {
}
int* nthRoot::primeFactorization(int n) {
int k = 0;
while (n%2 == 0) {
factors[k] = 2;
k++;
n = n/2;
}
for (int i = 3; i <= sqrt(n); i = i + 2) {
if (n%i == 0) {
while (n%i == 0) {
factors[k] = i;
k++;
n = n/i;
}
}
}
if (n > 1) {
factors[k] = n;
}
return factors;
// added bonus: factors should be sorted already
}
Expression* nthRoot::simplify(){
//if coefficient == 0 then return 0?
//if operand < 0 throw an error
if ((root % 2) == 0 && operand < 0) { //this needs to be made right
throw runtime_error("unreal answer");
}
factors = this->primeFactorization(operand);
int i = 0;
int factorsSize = sizeof(factors)/sizeof(factors[0]);
while (i <= factorsSize) { //all this takes unnecessary factors out of the operand
int j = i; //and puts them into the coefficient
int count = 0;
while (j <= factorsSize && factors[j + 1] == factors[j]) {
count++;
j++;
}
if (count >= root) {
coefficient *= (factors[i] ^ (count/root));
operand = operand / (factors[i] ^ (count - (count % root)));
}
i = j + 1;
}
if (operand == 1) {
Integer* newInt = new Integer(coefficient);
return newInt;
}
else {
Expression* newRoot = new nthRoot(root, operand, coefficient);
delete this; //is this necessary?
return newRoot;
}
}
Expression* nthRoot::add(Expression* a) {
nthRoot *b = (nthRoot *)a;
int asCoefficient = b->getCoefficient();
int asOperand = b->getOperand();
int asRoot = b->getRoot();
if (root == asRoot && operand == asOperand) {
int newCoefficient = asCoefficient + coefficient;
nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else {
return this;
}
}
Expression* nthRoot::subtract(Expression* a) {
nthRoot *b = (nthRoot *)a;
int asCoefficient = b->getCoefficient();
int asOperand = b->getOperand();
int asRoot = b->getRoot();
if (root == asRoot && operand == asOperand) {
int newCoefficient = coefficient - asCoefficient;
nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else {
return this;
}
}
Expression* nthRoot::multiply(Expression* a) {
nthRoot *b = (nthRoot *)a;
int asCoefficient = b->getCoefficient();
int asOperand = b->getOperand();
int asRoot = b->getRoot();
if (root == asRoot) {
int newCoefficient = asCoefficient * coefficient;
int newOperand = operand * asOperand; //asOperand doesnt exist?
nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else {
return this;
}
}
Expression* nthRoot::divide(Expression* a) {
nthRoot *b = (nthRoot *)a;
int asRoot = b->getRoot();
int asOperand = b->getOperand();
int asCoefficient = b->getCoefficient();
if (root == asRoot && fmod( ((double)coefficient / (double)asCoefficient), 1) == 0 && fmod(((double)operand / (double)asOperand), 1) == 0) {
int newCoefficient = coefficient / asCoefficient;
int newOperand = operand / asOperand;
nthRoot* newNthRoot = new nthRoot(root, newOperand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else if (fmod( ((double)coefficient / (double)asCoefficient),1) == 0) {
int newCoefficient = coefficient / asCoefficient;
nthRoot* newNthRoot = new nthRoot(root, operand, newCoefficient);
nthRoot* simplifiedVersion = (nthRoot *)newNthRoot->simplify();
return simplifiedVersion;
}
else {
return this;
}
}
int nthRoot::getRoot() {
return root;
}
int nthRoot::getOperand() {
return operand;
}
int nthRoot::getCoefficient() {
return coefficient;
}
void nthRoot::setCoefficient(int n) {
this->coefficient = n;
}
void nthRoot::setOperand(int n) {
this->operand = n;
}
void nthRoot::setRoot(int n) {
this->root = n;
}
ostream& nthRoot::print(std::ostream& output) const {
output << this->coefficient << "*" << this->root << "rt:" << this->operand;
return output;
}
string nthRoot::toString() {
stringstream s;
s << coefficient << "*" << root << "rt:" << operand;
return s.str();
}
<|endoftext|> |
<commit_before>#include "x11api.h"
#ifdef __LINUX__
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xos.h>
#include <X11/keysymdef.h>
#include <X11/Xutil.h>
//#include <GL/glx.h> //FIXME
#include <Tempest/Event>
#include <Tempest/TextCodec>
#include <Tempest/Window>
#include <atomic>
#include <stdexcept>
#include <cstring>
#include <thread>
#include <unordered_map>
struct HWND final {
::Window wnd;
HWND()=default;
HWND(::Window w):wnd(w) {
}
HWND(Tempest::SystemApi::Window* p) {
std::memcpy(&wnd,&p,sizeof(wnd));
}
HWND& operator = (::Window w) { wnd = w; return *this; }
operator ::Window() { return wnd; }
Tempest::SystemApi::Window* ptr() {
static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer");
Tempest::SystemApi::Window* ret=nullptr;
std::memcpy(&ret,&wnd,sizeof(wnd));
return ret;
}
};
using namespace Tempest;
static const char* wndClassName="Tempest.Window";
static Display* dpy = nullptr;
static ::Window root = {};
static std::atomic_bool isExit{0};
static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows;
static Atom& wmDeleteMessage(){
static Atom w = XInternAtom( dpy, "WM_DELETE_WINDOW", 0);
return w;
}
static Atom& _NET_WM_STATE(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE", 0);
return w;
}
static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
return w;
}
static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
return w;
}
static Atom& _NET_WM_STATE_FULLSCREEN(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0);
return w;
}
static Event::MouseButton toButton( XButtonEvent& msg ){
if( msg.button==Button1 )
return Event::ButtonLeft;
if( msg.button==Button3 )
return Event::ButtonRight;
if( msg.button==Button2 )
return Event::ButtonMid;
return Event::ButtonNone;
}
static void maximizeWindow(HWND& w) {
Atom a[2];
a[0] = _NET_WM_STATE_MAXIMIZED_HORZ();
a[1] = _NET_WM_STATE_MAXIMIZED_VERT();
XChangeProperty ( dpy, w, _NET_WM_STATE(),
XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2);
XSync(dpy,False);
}
static void alignGeometry(::Window w,Tempest::Window& owner) {
XWindowAttributes xwa={};
if(XGetWindowAttributes(dpy, HWND(w), &xwa)){
owner.resize(xwa.width, xwa.height);
}
}
X11Api::X11Api() {
dpy = XOpenDisplay(nullptr);
if(dpy == nullptr)
throw std::runtime_error("cannot connect to X server!");
root = DefaultRootWindow(dpy);
static const TranslateKeyPair k[] = {
{ XK_KP_Left, Event::K_Left },
{ XK_KP_Right, Event::K_Right },
{ XK_KP_Up, Event::K_Up },
{ XK_KP_Down, Event::K_Down },
{ XK_Shift_L, Event::K_LShift },
{ XK_Shift_R, Event::K_RShift },
{ XK_Control_L, Event::K_LControl },
{ XK_Control_R, Event::K_RControl },
{ XK_Escape, Event::K_ESCAPE },
{ XK_Tab, Event::K_Tab },
{ XK_BackSpace, Event::K_Back },
{ XK_Delete, Event::K_Delete },
{ XK_Insert, Event::K_Insert },
{ XK_Home, Event::K_Home },
{ XK_End, Event::K_End },
{ XK_Pause, Event::K_Pause },
{ XK_Return, Event::K_Return },
{ XK_F1, Event::K_F1 },
{ 48, Event::K_0 },
{ 97, Event::K_A },
{ 0, Event::K_NoKey }
};
setupKeyTranslate(k,24);
}
void *X11Api::display() {
return dpy;
}
SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) {
//GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
//XVisualInfo * vi = glXChooseVisual(dpy, 0, att);
long visualMask = VisualScreenMask;
int numberOfVisuals;
XVisualInfo vInfoTemplate = {};
vInfoTemplate.screen = DefaultScreen(dpy);
XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals);
Colormap cmap;
cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);
XSetWindowAttributes swa={};
swa.colormap = cmap;
swa.event_mask = PointerMotionMask | ExposureMask |
ButtonPressMask | ButtonReleaseMask |
KeyPressMask | KeyReleaseMask;
HWND win = XCreateWindow( dpy, root, 0, 0, w, h,
0, vi->depth, InputOutput, vi->visual,
CWColormap | CWEventMask, &swa );
XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1);
XStoreName(dpy, win, wndClassName);
XFreeColormap( dpy, cmap );
XFree(vi);
auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr());
windows[ret] = owner;
//maximizeWindow(win);
XMapWindow(dpy, win);
XSync(dpy,False);
alignGeometry(win,*owner);
return ret;
}
SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) {
return implCreateWindow(owner,800,600); //TODO
}
void X11Api::implDestroyWindow(SystemApi::Window *w) {
windows.erase(w);
XDestroyWindow(dpy, HWND(w));
}
bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) {
return false;
}
bool X11Api::implIsFullscreen(SystemApi::Window *w) {
return false;
}
void X11Api::implSetCursorPosition(int x, int y) {
// TODO
}
void X11Api::implShowCursor(bool show) {
// TODO
}
Rect X11Api::implWindowClientRect(SystemApi::Window *w) {
XWindowAttributes xwa;
XGetWindowAttributes(dpy, HWND(w), &xwa);
return Rect( xwa.x, xwa.y, xwa.width, xwa.height );
}
void X11Api::implExit() {
isExit.store(true);
}
int X11Api::implExec(SystemApi::AppCallBack &cb) {
// main message loop
while (!isExit.load()) {
if(XPending(dpy)>0) {
XEvent xev={};
XNextEvent(dpy, &xev);
HWND hWnd = xev.xclient.window;
Tempest::Window* cb = windows.find(hWnd.ptr())->second; //TODO: validation
switch( xev.type ) {
case ClientMessage: {
if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){
SystemApi::exit();
}
break;
}
case ButtonPress:
case ButtonRelease: {
if(cb) {
bool isWheel = false;
if( xev.type==ButtonPress && XPending(dpy) &&
(xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){
XEvent ev;
XNextEvent(dpy, &ev);
isWheel = (ev.type==ButtonRelease);
}
if( isWheel ){
int ticks = 0;
if( xev.xbutton.button == Button4 ) {
ticks = 100;
}
else if ( xev.xbutton.button == Button5 ) {
ticks = -100;
}
Tempest::MouseEvent e( xev.xbutton.x,
xev.xbutton.y,
Tempest::Event::ButtonNone,
ticks,
0,
Event::MouseWheel );
SystemApi::dispatchMouseWheel(*cb, e);
} else {
MouseEvent e( xev.xbutton.x,
xev.xbutton.y,
toButton( xev.xbutton ),
0,
0,
xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp );
if(xev.type==ButtonPress)
SystemApi::dispatchMouseDown(*cb, e); else
SystemApi::dispatchMouseUp(*cb, e);
}
}
break;
}
case MotionNotify: {
MouseEvent e( xev.xmotion.x,
xev.xmotion.y,
Event::ButtonNone,
0,
0,
Event::MouseMove );
SystemApi::dispatchMouseMove(*cb, e);
break;
}
case KeyPress:
case KeyRelease: {
if(cb) {
int keysyms_per_keycode_return = 0;
KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode),
1,
&keysyms_per_keycode_return );
char txt[10]={};
XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr );
auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation
auto key = SystemApi::translateKey(*ksym);
uint32_t scan = xev.xkey.keycode;
Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp);
if(xev.type==KeyPress)
SystemApi::dispatchKeyDown(*cb,e,scan); else
SystemApi::dispatchKeyUp (*cb,e,scan);
}
break;
}
}
std::this_thread::yield();
} else {
if(cb.onTimer()==0)
std::this_thread::yield();
for(auto& i:windows) {
::Window hWnd = HWND(i.first);
// artificial move/resize event
alignGeometry(hWnd,*i.second);
SystemApi::dispatchRender(*i.second);
}
}
}
return 0;
}
#endif
<commit_msg>x11 fixup<commit_after>#include "x11api.h"
#ifdef __LINUX__
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#include <X11/Xos.h>
#include <X11/keysymdef.h>
#include <X11/Xutil.h>
//#include <GL/glx.h> //FIXME
#include <Tempest/Event>
#include <Tempest/TextCodec>
#include <Tempest/Window>
#include <atomic>
#include <stdexcept>
#include <cstring>
#include <thread>
#include <unordered_map>
struct HWND final {
::Window wnd;
HWND()=default;
HWND(::Window w):wnd(w) {
}
HWND(Tempest::SystemApi::Window* p) {
std::memcpy(&wnd,&p,sizeof(wnd));
}
HWND& operator = (::Window w) { wnd = w; return *this; }
operator ::Window() { return wnd; }
Tempest::SystemApi::Window* ptr() {
static_assert (sizeof(::Window)<=sizeof(void*),"cannot map X11 window handle to pointer");
Tempest::SystemApi::Window* ret=nullptr;
std::memcpy(&ret,&wnd,sizeof(wnd));
return ret;
}
};
using namespace Tempest;
static const char* wndClassName="Tempest.Window";
static Display* dpy = nullptr;
static ::Window root = {};
static std::atomic_bool isExit{0};
static std::unordered_map<SystemApi::Window*,Tempest::Window*> windows;
static Atom& wmDeleteMessage(){
static Atom w = XInternAtom( dpy, "WM_DELETE_WINDOW", 0);
return w;
}
static Atom& _NET_WM_STATE(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE", 0);
return w;
}
static Atom& _NET_WM_STATE_MAXIMIZED_HORZ(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_HORZ", 0);
return w;
}
static Atom& _NET_WM_STATE_MAXIMIZED_VERT(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_MAXIMIZED_VERT", 0);
return w;
}
static Atom& _NET_WM_STATE_FULLSCREEN(){
static Atom w = XInternAtom( dpy, "_NET_WM_STATE_FULLSCREEN", 0);
return w;
}
static Event::MouseButton toButton( XButtonEvent& msg ){
if( msg.button==Button1 )
return Event::ButtonLeft;
if( msg.button==Button3 )
return Event::ButtonRight;
if( msg.button==Button2 )
return Event::ButtonMid;
return Event::ButtonNone;
}
static void maximizeWindow(HWND& w) {
Atom a[2];
a[0] = _NET_WM_STATE_MAXIMIZED_HORZ();
a[1] = _NET_WM_STATE_MAXIMIZED_VERT();
XChangeProperty ( dpy, w, _NET_WM_STATE(),
XA_ATOM, 32, PropModeReplace, (unsigned char*)a, 2);
XSync(dpy,False);
}
static void alignGeometry(::Window w,Tempest::Window& owner) {
XWindowAttributes xwa={};
if(XGetWindowAttributes(dpy, HWND(w), &xwa)){
owner.resize(xwa.width, xwa.height);
}
}
X11Api::X11Api() {
dpy = XOpenDisplay(nullptr);
if(dpy == nullptr)
throw std::runtime_error("cannot connect to X server!");
root = DefaultRootWindow(dpy);
static const TranslateKeyPair k[] = {
{ XK_KP_Left, Event::K_Left },
{ XK_KP_Right, Event::K_Right },
{ XK_KP_Up, Event::K_Up },
{ XK_KP_Down, Event::K_Down },
{ XK_Shift_L, Event::K_LShift },
{ XK_Shift_R, Event::K_RShift },
{ XK_Control_L, Event::K_LControl },
{ XK_Control_R, Event::K_RControl },
{ XK_Escape, Event::K_ESCAPE },
{ XK_Tab, Event::K_Tab },
{ XK_BackSpace, Event::K_Back },
{ XK_Delete, Event::K_Delete },
{ XK_Insert, Event::K_Insert },
{ XK_Home, Event::K_Home },
{ XK_End, Event::K_End },
{ XK_Pause, Event::K_Pause },
{ XK_Return, Event::K_Return },
{ XK_F1, Event::K_F1 },
{ 48, Event::K_0 },
{ 97, Event::K_A },
{ 0, Event::K_NoKey }
};
setupKeyTranslate(k,24);
}
void *X11Api::display() {
return dpy;
}
SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, uint32_t w, uint32_t h) {
//GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None };
//XVisualInfo * vi = glXChooseVisual(dpy, 0, att);
long visualMask = VisualScreenMask;
int numberOfVisuals;
XVisualInfo vInfoTemplate = {};
vInfoTemplate.screen = DefaultScreen(dpy);
XVisualInfo * vi = XGetVisualInfo(dpy, visualMask, &vInfoTemplate, &numberOfVisuals);
Colormap cmap;
cmap = XCreateColormap(dpy, root, vi->visual, AllocNone);
XSetWindowAttributes swa={};
swa.colormap = cmap;
swa.event_mask = PointerMotionMask | ExposureMask |
ButtonPressMask | ButtonReleaseMask |
KeyPressMask | KeyReleaseMask;
HWND win = XCreateWindow( dpy, root, 0, 0, w, h,
0, vi->depth, InputOutput, vi->visual,
CWColormap | CWEventMask, &swa );
XSetWMProtocols(dpy, win, &wmDeleteMessage(), 1);
XStoreName(dpy, win, wndClassName);
XFreeColormap( dpy, cmap );
XFree(vi);
auto ret = reinterpret_cast<SystemApi::Window*>(win.ptr());
windows[ret] = owner;
//maximizeWindow(win);
XMapWindow(dpy, win);
XSync(dpy,False);
alignGeometry(win,*owner);
return ret;
}
SystemApi::Window *X11Api::implCreateWindow(Tempest::Window *owner, SystemApi::ShowMode sm) {
return implCreateWindow(owner,800,600); //TODO
}
void X11Api::implDestroyWindow(SystemApi::Window *w) {
windows.erase(w);
XDestroyWindow(dpy, HWND(w));
}
bool X11Api::implSetAsFullscreen(SystemApi::Window *w, bool fullScreen) {
return false;
}
bool X11Api::implIsFullscreen(SystemApi::Window *w) {
return false;
}
void X11Api::implSetCursorPosition(int x, int y) {
// TODO
}
void X11Api::implShowCursor(bool show) {
// TODO
}
Rect X11Api::implWindowClientRect(SystemApi::Window *w) {
XWindowAttributes xwa;
XGetWindowAttributes(dpy, HWND(w), &xwa);
return Rect( xwa.x, xwa.y, xwa.width, xwa.height );
}
void X11Api::implExit() {
isExit.store(true);
}
int X11Api::implExec(SystemApi::AppCallBack &cb) {
// main message loop
while (!isExit.load()) {
if(XPending(dpy)>0) {
XEvent xev={};
XNextEvent(dpy, &xev);
HWND hWnd = xev.xclient.window;
Tempest::Window* cb = windows.find(hWnd.ptr())->second; //TODO: validation
switch( xev.type ) {
case ClientMessage: {
if( xev.xclient.data.l[0] == long(wmDeleteMessage()) ){
SystemApi::exit();
}
break;
}
case ButtonPress:
case ButtonRelease: {
if(cb) {
bool isWheel = false;
if( xev.type==ButtonPress && XPending(dpy) &&
(xev.xbutton.button == Button4 || xev.xbutton.button == Button5) ){
XEvent ev;
XNextEvent(dpy, &ev);
isWheel = (ev.type==ButtonRelease);
}
if( isWheel ){
int ticks = 0;
if( xev.xbutton.button == Button4 ) {
ticks = 100;
}
else if ( xev.xbutton.button == Button5 ) {
ticks = -100;
}
Tempest::MouseEvent e( xev.xbutton.x,
xev.xbutton.y,
Tempest::Event::ButtonNone,
ticks,
0,
Event::MouseWheel );
SystemApi::dispatchMouseWheel(*cb, e);
} else {
MouseEvent e( xev.xbutton.x,
xev.xbutton.y,
toButton( xev.xbutton ),
0,
0,
xev.type==ButtonPress ? Event::MouseDown : Event::MouseUp );
if(xev.type==ButtonPress)
SystemApi::dispatchMouseDown(*cb, e); else
SystemApi::dispatchMouseUp(*cb, e);
}
}
break;
}
case MotionNotify: {
MouseEvent e( xev.xmotion.x,
xev.xmotion.y,
Event::ButtonNone,
0,
0,
Event::MouseMove );
SystemApi::dispatchMouseMove(*cb, e);
break;
}
case KeyPress:
case KeyRelease: {
if(cb) {
int keysyms_per_keycode_return = 0;
KeySym *ksym = XGetKeyboardMapping( dpy, KeyCode(xev.xkey.keycode),
1,
&keysyms_per_keycode_return );
char txt[10]={};
XLookupString(&xev.xkey, txt, sizeof(txt)-1, ksym, nullptr );
auto u16 = TextCodec::toUtf16(txt); // TODO: remove dynamic allocation
auto key = SystemApi::translateKey(*ksym);
uint32_t scan = xev.xkey.keycode;
Tempest::KeyEvent e(Event::KeyType(key),uint32_t(u16.size()>0 ? u16[0] : 0),Event::M_NoModifier,(xev.type==KeyPress) ? Event::KeyDown : Event::KeyUp);
if(xev.type==KeyPress)
SystemApi::dispatchKeyDown(*cb,e,scan); else
SystemApi::dispatchKeyUp (*cb,e,scan);
}
break;
}
}
std::this_thread::yield();
} else {
if(cb.onTimer()==0)
std::this_thread::yield();
for(auto& i:windows) {
::Window hWnd = HWND(i.first);
// artificial move/resize event
alignGeometry(hWnd,*i.second);
SystemApi::dispatchRender(*i.second);
}
}
}
return 0;
}
#endif
<|endoftext|> |
<commit_before>#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SystemConfiguration.h>
namespace {
bool
verifyUser(void)
{
uid_t consoleUID;
CFStringRef result = SCDynamicStoreCopyConsoleUser(NULL, &consoleUID, NULL);
if (! result) return false;
CFRelease(result);
return (getuid() == consoleUID);
}
}
int
main(int argc, char **argv)
{
if (argc != 3) {
fprintf(stderr, "Usage: %s key value\n", argv[0]);
return 1;
}
if (! verifyUser()) {
fprintf(stderr, "Permission denied\n");
return 1;
}
char name[512];
snprintf(name, sizeof(name), "pckeyboardhack.%s", argv[1]);
int value = atoi(argv[2]);
size_t oldlen = 0;
size_t newlen = sizeof(value);
int error = sysctlbyname(name, NULL, &oldlen, &value, newlen);
if (error) {
perror("sysctl");
return 1;
}
fprintf(stderr, "%s -> %d\n", name, value);
return 0;
}
<commit_msg>update src/bin/sysctl_set<commit_after>#include <sys/types.h>
#include <sys/sysctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <CoreFoundation/CoreFoundation.h>
#include <SystemConfiguration/SystemConfiguration.h>
namespace {
bool
verifyUser(void)
{
uid_t consoleUID;
CFStringRef result = SCDynamicStoreCopyConsoleUser(NULL, &consoleUID, NULL);
if (! result) return false;
CFRelease(result);
return (getuid() == consoleUID);
}
}
int
main(int argc, char** argv)
{
if (argc != 3) {
fprintf(stderr, "Usage: %s key value\n", argv[0]);
return 1;
}
if (! verifyUser()) {
return 1;
}
char name[512];
snprintf(name, sizeof(name), "pckeyboardhack.%s", argv[1]);
int value = atoi(argv[2]);
size_t oldlen = 0;
size_t newlen = sizeof(value);
int error = sysctlbyname(name, NULL, &oldlen, &value, newlen);
if (error) {
perror("sysctl");
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>// CToolDlg.cpp
// Copyright (c) 2014, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "CToolDlg.h"
#include "interface/NiceTextCtrl.h"
enum
{
ID_TITLE_TYPE = 100,
ID_TOOL_TYPE,
ID_MATERIAL,
ID_DIRECTION,
};
BEGIN_EVENT_TABLE(CToolDlg, HeeksObjDlg)
EVT_COMBOBOX(ID_TITLE_TYPE,CToolDlg::OnComboTitleType)
EVT_COMBOBOX(ID_TOOL_TYPE, CToolDlg::OnComboToolType)
EVT_COMBOBOX(ID_MATERIAL, CToolDlg::OnComboMaterial)
EVT_TEXT(wxID_ANY,CToolDlg::OnTextCtrlEvent)
EVT_BUTTON(wxID_HELP, CToolDlg::OnHelp)
END_EVENT_TABLE()
CToolDlg::CToolDlg(wxWindow *parent, CTool* object, const wxString& title, bool top_level)
: HeeksObjDlg(parent, object, title, false)
{
// add some of the controls to the right side
rightControls.push_back(MakeLabelAndControl(_("Title"), m_txtTitle = new wxTextCtrl(this, wxID_ANY)));
wxString title_choices[] = {_("Leave manually assigned title"), _("Automatically Generate Title")};
rightControls.push_back(MakeLabelAndControl(_("Title Type"), m_cmbTitleType = new wxComboBox(this, ID_TITLE_TYPE, _T(""), wxDefaultPosition, wxDefaultSize, 2, title_choices)));
// add all the controls to the left side
leftControls.push_back(MakeLabelAndControl(_("Tool Number"), m_dlbToolNumber = new wxTextCtrl(this, wxID_ANY)));
wxString materials[] = {_("High Speed Steel"),_("Carbide") };
leftControls.push_back(MakeLabelAndControl(_("Tool Material"), m_cmbMaterial = new wxComboBox(this, ID_MATERIAL, _T(""), wxDefaultPosition, wxDefaultSize, 2, materials)));
wxString tool_types[] = {_("Drill Bit"), _("Centre Drill Bit"), _("End Mill"), _("Slot Cutter"), _("Ball End Mill"), _("Chamfer"), _("Engraving Bit")};
leftControls.push_back(MakeLabelAndControl(_("Tool Type"), m_cmbToolType = new wxComboBox(this, ID_TOOL_TYPE, _T(""), wxDefaultPosition, wxDefaultSize, sizeof(tool_types)/sizeof(CToolParams::eToolType), tool_types)));
leftControls.push_back(MakeLabelAndControl(_("Diameter"), m_dblDiameter = new CLengthCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Tool Length Offset"), m_dblToolLengthOffset = new CLengthCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Flat Radius"), m_dblFlatRadius = new CLengthCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Corner Radius"), m_dblCornerRadius = new CLengthCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Cutting Edge Angle"), m_dblCuttingEdgeAngle = new CDoubleCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Cutting Edge Height"), m_dblCuttingEdgeHeight = new CLengthCtrl(this)));
if(top_level)
{
HeeksObjDlg::AddControlsAndCreate();
m_dblDiameter->SetFocus();
}
}
void CToolDlg::GetDataRaw(HeeksObj* object)
{
long i = 0;
m_dlbToolNumber->GetValue().ToLong(&i);
((CTool*)object)->m_tool_number = i;
((CTool*)object)->m_params.m_material = m_cmbMaterial->GetSelection();
((CTool*)object)->m_params.m_type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
((CTool*)object)->m_params.m_diameter = m_dblDiameter->GetValue();
((CTool*)object)->m_params.m_tool_length_offset = m_dblToolLengthOffset->GetValue();
((CTool*)object)->m_params.m_flat_radius = m_dblFlatRadius->GetValue();
((CTool*)object)->m_params.m_corner_radius = m_dblCornerRadius->GetValue();
((CTool*)object)->m_params.m_cutting_edge_angle = m_dblCuttingEdgeAngle->GetValue();
((CTool*)object)->m_params.m_cutting_edge_height = m_dblCuttingEdgeHeight->GetValue();
((CTool*)object)->m_title = m_txtTitle->GetValue();
((CTool*)object)->m_params.m_automatically_generate_title = (m_cmbTitleType->GetSelection() != 0);
}
void CToolDlg::SetFromDataRaw(HeeksObj* object)
{
m_dlbToolNumber->SetValue(wxString::Format(_T("%d"), ((CTool*)object)->m_tool_number));
m_txtTitle->SetValue(((CTool*)object)->m_title);
m_cmbMaterial->SetSelection(((CTool*)object)->m_params.m_material);
m_cmbToolType->SetSelection(((CTool*)object)->m_params.m_type);
m_dblDiameter->SetValue(((CTool*)object)->m_params.m_diameter);
m_dblToolLengthOffset->SetValue(((CTool*)object)->m_params.m_tool_length_offset);
m_dblCuttingEdgeHeight->SetValue(((CTool*)object)->m_params.m_cutting_edge_height);
m_txtTitle->SetValue(((CTool*)object)->m_title);
m_cmbTitleType->SetSelection(((CTool*)object)->m_params.m_automatically_generate_title ? 1:0);
EnableAndSetCornerFlatAndAngle(((CTool*)object)->m_params.m_type);
}
void CToolDlg::SetPicture(const wxString& name)
{
HeeksObjDlg::SetPicture(name, _T("ctool"));
}
void CToolDlg::SetPictureByWindow(wxWindow* w)
{
CToolParams::eToolType type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
switch(type)
{
case CToolParams::eDrill:
if(w == m_dblDiameter)SetPicture(_T("drill_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("drill_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("drill_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("drill_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("drill_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("drill_height"));
else SetPicture(_T("drill"));
break;
case CToolParams::eCentreDrill:
if(w == m_dblDiameter)SetPicture(_T("centre_drill_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("centre_drill_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("centre_drill_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("centre_drill_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("centre_drill_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("centre_drill_height"));
else SetPicture(_T("centre_drill"));
break;
case CToolParams::eEndmill:
case CToolParams::eSlotCutter:
if(w == m_dblDiameter)SetPicture(_T("end_mill_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("end_mill_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("end_mill_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("end_mill_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("end_mill_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("end_mill_height"));
else SetPicture(_T("end_mill"));
break;
case CToolParams::eBallEndMill:
if(w == m_dblDiameter)SetPicture(_T("ball_mill_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("ball_mill_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("ball_mill_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("ball_mill_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("ball_mill_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("ball_mill_height"));
else SetPicture(_T("ball_mill"));
break;
case CToolParams::eChamfer:
if(w == m_dblDiameter)SetPicture(_T("chamfer_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("chamfer_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("chamfer_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("chamfer_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("chamfer_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("chamfer_height"));
else SetPicture(_T("chamfer"));
break;
case CToolParams::eEngravingTool:
if(w == m_dblDiameter)SetPicture(_T("engraver_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("engraver_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("engraver_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("engraver_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("engraver_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("engraver_height"));
else SetPicture(_T("engraver"));
break;
default:
SetPicture(_T("undefined"));
break;
}
}
void CToolDlg::OnComboTitleType( wxCommandEvent& event )
{
if(m_ignore_event_functions)return;
// SetPicture();
}
void CToolDlg::OnComboMaterial( wxCommandEvent& event )
{
if(m_ignore_event_functions)return;
// //SetPicture();
}
void CToolDlg::OnTextCtrlEvent(wxCommandEvent& event)
{
if(m_ignore_event_functions)return;
// something's changed, recalculate the title
CTool* object = (CTool*)(m_object->MakeACopy());
GetData(object);
m_ignore_event_functions = true;
object->ResetTitle();
m_txtTitle->SetValue(object->m_title);
delete object;
m_ignore_event_functions = false;
}
void CToolDlg::OnComboToolType(wxCommandEvent& event)
{
if(m_ignore_event_functions)return;
CToolParams::eToolType type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
EnableAndSetCornerFlatAndAngle(type);
HeeksObjDlg::SetPicture();
}
void CToolDlg::EnableAndSetCornerFlatAndAngle(CToolParams::eToolType type)
{
switch(type)
{
case CToolParams::eDrill:
case CToolParams::eCentreDrill:
m_dblCornerRadius->Enable(false);
m_dblCornerRadius->SetLabel(_T(""));
m_dblFlatRadius->Enable(false);
m_dblFlatRadius->SetLabel(_T(""));
m_dblCuttingEdgeAngle->Enable();
m_dblCuttingEdgeAngle->SetValue(((CTool*)m_object)->m_params.m_cutting_edge_angle);
break;
case CToolParams::eEndmill:
case CToolParams::eSlotCutter:
m_dblCornerRadius->Enable();
m_dblCornerRadius->SetValue(((CTool*)m_object)->m_params.m_corner_radius);
m_dblFlatRadius->Enable(false);
m_dblFlatRadius->SetLabel(_T(""));
m_dblCuttingEdgeAngle->Enable(false);
m_dblCuttingEdgeAngle->SetLabel(_T(""));
break;
case CToolParams::eBallEndMill:
m_dblCornerRadius->Enable(false);
m_dblCornerRadius->SetLabel(_T(""));
m_dblFlatRadius->Enable(false);
m_dblFlatRadius->SetLabel(_T(""));
m_dblCuttingEdgeAngle->Enable(false);
m_dblCuttingEdgeAngle->SetLabel(_T(""));
break;
case CToolParams::eChamfer:
case CToolParams::eEngravingTool:
m_dblCornerRadius->Enable(false);
m_dblCornerRadius->SetLabel(_T(""));
m_dblFlatRadius->Enable();
m_dblFlatRadius->SetValue(((CTool*)m_object)->m_params.m_flat_radius);
m_dblCuttingEdgeAngle->Enable();
m_dblCuttingEdgeAngle->SetValue(((CTool*)m_object)->m_params.m_cutting_edge_angle);
break;
default:
break;
}
}
void CToolDlg::OnHelp( wxCommandEvent& event )
{
::wxLaunchDefaultBrowser(_T("http://heeks.net/help/tool"));
}
<commit_msg>Fix crash while editing tools under 64 bits arch.<commit_after>// CToolDlg.cpp
// Copyright (c) 2014, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.
#include "stdafx.h"
#include "CToolDlg.h"
#include "interface/NiceTextCtrl.h"
enum
{
ID_TITLE_TYPE = 100,
ID_TOOL_TYPE,
ID_MATERIAL,
ID_DIRECTION,
};
BEGIN_EVENT_TABLE(CToolDlg, HeeksObjDlg)
EVT_COMBOBOX(ID_TITLE_TYPE,CToolDlg::OnComboTitleType)
EVT_COMBOBOX(ID_TOOL_TYPE, CToolDlg::OnComboToolType)
EVT_COMBOBOX(ID_MATERIAL, CToolDlg::OnComboMaterial)
EVT_TEXT(wxID_ANY,CToolDlg::OnTextCtrlEvent)
EVT_BUTTON(wxID_HELP, CToolDlg::OnHelp)
END_EVENT_TABLE()
CToolDlg::CToolDlg(wxWindow *parent, CTool* object, const wxString& title, bool top_level)
: HeeksObjDlg(parent, object, title, false)
{
// add some of the controls to the right side
rightControls.push_back(MakeLabelAndControl(_("Title"), m_txtTitle = new wxTextCtrl(this, wxID_ANY)));
wxString title_choices[] = {_("Leave manually assigned title"), _("Automatically Generate Title")};
rightControls.push_back(MakeLabelAndControl(_("Title Type"), m_cmbTitleType = new wxComboBox(this, ID_TITLE_TYPE, _T(""), wxDefaultPosition, wxDefaultSize, 2, title_choices)));
// add all the controls to the left side
leftControls.push_back(MakeLabelAndControl(_("Tool Number"), m_dlbToolNumber = new wxTextCtrl(this, wxID_ANY)));
wxString materials[] = {_("High Speed Steel"),_("Carbide") };
leftControls.push_back(MakeLabelAndControl(_("Tool Material"), m_cmbMaterial = new wxComboBox(this, ID_MATERIAL, _T(""), wxDefaultPosition, wxDefaultSize, 2, materials)));
wxString tool_types[] = {_("Drill Bit"), _("Centre Drill Bit"), _("End Mill"), _("Slot Cutter"), _("Ball End Mill"), _("Chamfer"), _("Engraving Bit")};
leftControls.push_back(MakeLabelAndControl(_("Tool Type"), m_cmbToolType = new wxComboBox(this, ID_TOOL_TYPE, _T(""), wxDefaultPosition, wxDefaultSize, sizeof(tool_types)/sizeof(wxString), tool_types)));
leftControls.push_back(MakeLabelAndControl(_("Diameter"), m_dblDiameter = new CLengthCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Tool Length Offset"), m_dblToolLengthOffset = new CLengthCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Flat Radius"), m_dblFlatRadius = new CLengthCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Corner Radius"), m_dblCornerRadius = new CLengthCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Cutting Edge Angle"), m_dblCuttingEdgeAngle = new CDoubleCtrl(this)));
leftControls.push_back(MakeLabelAndControl(_("Cutting Edge Height"), m_dblCuttingEdgeHeight = new CLengthCtrl(this)));
if(top_level)
{
HeeksObjDlg::AddControlsAndCreate();
m_dblDiameter->SetFocus();
}
}
void CToolDlg::GetDataRaw(HeeksObj* object)
{
long i = 0;
m_dlbToolNumber->GetValue().ToLong(&i);
((CTool*)object)->m_tool_number = i;
((CTool*)object)->m_params.m_material = m_cmbMaterial->GetSelection();
((CTool*)object)->m_params.m_type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
((CTool*)object)->m_params.m_diameter = m_dblDiameter->GetValue();
((CTool*)object)->m_params.m_tool_length_offset = m_dblToolLengthOffset->GetValue();
((CTool*)object)->m_params.m_flat_radius = m_dblFlatRadius->GetValue();
((CTool*)object)->m_params.m_corner_radius = m_dblCornerRadius->GetValue();
((CTool*)object)->m_params.m_cutting_edge_angle = m_dblCuttingEdgeAngle->GetValue();
((CTool*)object)->m_params.m_cutting_edge_height = m_dblCuttingEdgeHeight->GetValue();
((CTool*)object)->m_title = m_txtTitle->GetValue();
((CTool*)object)->m_params.m_automatically_generate_title = (m_cmbTitleType->GetSelection() != 0);
}
void CToolDlg::SetFromDataRaw(HeeksObj* object)
{
m_dlbToolNumber->SetValue(wxString::Format(_T("%d"), ((CTool*)object)->m_tool_number));
m_txtTitle->SetValue(((CTool*)object)->m_title);
m_cmbMaterial->SetSelection(((CTool*)object)->m_params.m_material);
m_cmbToolType->SetSelection(((CTool*)object)->m_params.m_type);
m_dblDiameter->SetValue(((CTool*)object)->m_params.m_diameter);
m_dblToolLengthOffset->SetValue(((CTool*)object)->m_params.m_tool_length_offset);
m_dblCuttingEdgeHeight->SetValue(((CTool*)object)->m_params.m_cutting_edge_height);
m_txtTitle->SetValue(((CTool*)object)->m_title);
m_cmbTitleType->SetSelection(((CTool*)object)->m_params.m_automatically_generate_title ? 1:0);
EnableAndSetCornerFlatAndAngle(((CTool*)object)->m_params.m_type);
}
void CToolDlg::SetPicture(const wxString& name)
{
HeeksObjDlg::SetPicture(name, _T("ctool"));
}
void CToolDlg::SetPictureByWindow(wxWindow* w)
{
CToolParams::eToolType type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
switch(type)
{
case CToolParams::eDrill:
if(w == m_dblDiameter)SetPicture(_T("drill_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("drill_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("drill_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("drill_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("drill_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("drill_height"));
else SetPicture(_T("drill"));
break;
case CToolParams::eCentreDrill:
if(w == m_dblDiameter)SetPicture(_T("centre_drill_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("centre_drill_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("centre_drill_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("centre_drill_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("centre_drill_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("centre_drill_height"));
else SetPicture(_T("centre_drill"));
break;
case CToolParams::eEndmill:
case CToolParams::eSlotCutter:
if(w == m_dblDiameter)SetPicture(_T("end_mill_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("end_mill_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("end_mill_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("end_mill_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("end_mill_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("end_mill_height"));
else SetPicture(_T("end_mill"));
break;
case CToolParams::eBallEndMill:
if(w == m_dblDiameter)SetPicture(_T("ball_mill_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("ball_mill_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("ball_mill_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("ball_mill_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("ball_mill_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("ball_mill_height"));
else SetPicture(_T("ball_mill"));
break;
case CToolParams::eChamfer:
if(w == m_dblDiameter)SetPicture(_T("chamfer_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("chamfer_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("chamfer_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("chamfer_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("chamfer_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("chamfer_height"));
else SetPicture(_T("chamfer"));
break;
case CToolParams::eEngravingTool:
if(w == m_dblDiameter)SetPicture(_T("engraver_diameter"));
else if(w == m_dblToolLengthOffset)SetPicture(_T("engraver_offset"));
else if(w == m_dblFlatRadius)SetPicture(_T("engraver_flat"));
else if(w == m_dblCornerRadius)SetPicture(_T("engraver_corner"));
else if(w == m_dblCuttingEdgeAngle)SetPicture(_T("engraver_angle"));
else if(w == m_dblCuttingEdgeHeight)SetPicture(_T("engraver_height"));
else SetPicture(_T("engraver"));
break;
default:
SetPicture(_T("undefined"));
break;
}
}
void CToolDlg::OnComboTitleType( wxCommandEvent& event )
{
if(m_ignore_event_functions)return;
// SetPicture();
}
void CToolDlg::OnComboMaterial( wxCommandEvent& event )
{
if(m_ignore_event_functions)return;
// //SetPicture();
}
void CToolDlg::OnTextCtrlEvent(wxCommandEvent& event)
{
if(m_ignore_event_functions)return;
// something's changed, recalculate the title
CTool* object = (CTool*)(m_object->MakeACopy());
GetData(object);
m_ignore_event_functions = true;
object->ResetTitle();
m_txtTitle->SetValue(object->m_title);
delete object;
m_ignore_event_functions = false;
}
void CToolDlg::OnComboToolType(wxCommandEvent& event)
{
if(m_ignore_event_functions)return;
CToolParams::eToolType type = (CToolParams::eToolType)(m_cmbToolType->GetSelection());
EnableAndSetCornerFlatAndAngle(type);
HeeksObjDlg::SetPicture();
}
void CToolDlg::EnableAndSetCornerFlatAndAngle(CToolParams::eToolType type)
{
switch(type)
{
case CToolParams::eDrill:
case CToolParams::eCentreDrill:
m_dblCornerRadius->Enable(false);
m_dblCornerRadius->SetLabel(_T(""));
m_dblFlatRadius->Enable(false);
m_dblFlatRadius->SetLabel(_T(""));
m_dblCuttingEdgeAngle->Enable();
m_dblCuttingEdgeAngle->SetValue(((CTool*)m_object)->m_params.m_cutting_edge_angle);
break;
case CToolParams::eEndmill:
case CToolParams::eSlotCutter:
m_dblCornerRadius->Enable();
m_dblCornerRadius->SetValue(((CTool*)m_object)->m_params.m_corner_radius);
m_dblFlatRadius->Enable(false);
m_dblFlatRadius->SetLabel(_T(""));
m_dblCuttingEdgeAngle->Enable(false);
m_dblCuttingEdgeAngle->SetLabel(_T(""));
break;
case CToolParams::eBallEndMill:
m_dblCornerRadius->Enable(false);
m_dblCornerRadius->SetLabel(_T(""));
m_dblFlatRadius->Enable(false);
m_dblFlatRadius->SetLabel(_T(""));
m_dblCuttingEdgeAngle->Enable(false);
m_dblCuttingEdgeAngle->SetLabel(_T(""));
break;
case CToolParams::eChamfer:
case CToolParams::eEngravingTool:
m_dblCornerRadius->Enable(false);
m_dblCornerRadius->SetLabel(_T(""));
m_dblFlatRadius->Enable();
m_dblFlatRadius->SetValue(((CTool*)m_object)->m_params.m_flat_radius);
m_dblCuttingEdgeAngle->Enable();
m_dblCuttingEdgeAngle->SetValue(((CTool*)m_object)->m_params.m_cutting_edge_angle);
break;
default:
break;
}
}
void CToolDlg::OnHelp( wxCommandEvent& event )
{
::wxLaunchDefaultBrowser(_T("http://heeks.net/help/tool"));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TitledControl.cxx,v $
*
* $Revision: 1.12 $
*
* last change: $Author: kz $ $Date: 2006-12-12 18:44:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "taskpane/TitledControl.hxx"
#include "AccessibleTreeNode.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
namespace sd { namespace toolpanel {
TitledControl::TitledControl (
TreeNode* pParent,
::std::auto_ptr<TreeNode> pControl,
const String& rTitle,
TitleBar::TitleBarType eType)
: ::Window (pParent->GetWindow(), WB_TABSTOP),
TreeNode(pParent),
msTitle(rTitle),
mbVisible(true),
mpUserData(NULL),
mpControlFactory(NULL),
mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
if (pControl.get() != NULL)
{
mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
pControl->SetParentNode (this);
}
mpControlContainer->AddControl (pControl);
FocusManager::Instance().RegisterDownLink(this, GetControl()->GetWindow());
FocusManager::Instance().RegisterUpLink(GetControl()->GetWindow(), this);
SetBackground (Wallpaper());
GetTitleBar()->GetWindow()->Show ();
GetTitleBar()->GetWindow()->AddEventListener (
LINK(this,TitledControl,WindowEventListener));
UpdateStates ();
}
TitledControl::TitledControl (
TreeNode* pParent,
::std::auto_ptr<ControlFactory> pControlFactory,
const String& rTitle,
TitleBar::TitleBarType eType)
: ::Window (pParent->GetWindow(), WB_TABSTOP),
TreeNode(pParent),
msTitle (rTitle),
mbVisible (true),
mpUserData (NULL),
mpControlFactory(pControlFactory),
mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
new TitleBar (this, rTitle, eType, true)));
// The second control is created on demand, i.e. when GetControl(true)
// is called the first time.
SetBackground (Wallpaper());
GetTitleBar()->GetWindow()->Show ();
GetTitleBar()->GetWindow()->AddEventListener (
LINK(this,TitledControl,WindowEventListener));
UpdateStates ();
}
TitledControl::~TitledControl (void)
{
GetTitleBar()->GetWindow()->RemoveEventListener (
LINK(this,TitledControl,WindowEventListener));
}
Size TitledControl::GetPreferredSize (void)
{
Size aPreferredSize;
if (GetControl(false) != NULL)
{
aPreferredSize = GetControl()->GetPreferredSize();
if ( ! IsExpanded())
aPreferredSize.Height() = 0;
}
else
aPreferredSize = Size (GetSizePixel().Width(), 0);
if (aPreferredSize.Width() == 0)
aPreferredSize.Width() = 300;
aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
aPreferredSize.Width());
return aPreferredSize;
}
sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
int nPreferredWidth = 0;
if (GetControl(false) != NULL)
nPreferredWidth = GetControl()->GetPreferredWidth(
nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
else
nPreferredWidth = GetSizePixel().Width();
if (nPreferredWidth == 0)
nPreferredWidth = 300;
return nPreferredWidth;
}
sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
int nPreferredHeight = 0;
if (IsExpanded() && GetControl(false)!=NULL)
nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);
return nPreferredHeight;
}
bool TitledControl::IsResizable (void)
{
return IsExpanded()
&& GetControl()->IsResizable();
}
::Window* TitledControl::GetWindow (void)
{
return this;
}
void TitledControl::Resize (void)
{
Size aWindowSize (GetOutputSizePixel());
int nTitleBarHeight
= GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
GetTitleBar()->GetWindow()->SetPosSizePixel (
Point (0,0),
Size (aWindowSize.Width(), nTitleBarHeight));
TreeNode* pControl = GetControl(false);
if (pControl != NULL
&& pControl->GetWindow() != NULL
&& pControl->GetWindow()->IsVisible())
{
pControl->GetWindow()->SetPosSizePixel (
Point (0,nTitleBarHeight),
Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
}
}
void TitledControl::GetFocus (void)
{
::Window::GetFocus();
if (GetTitleBar() != NULL)
GetTitleBar()->SetFocus (true);
}
void TitledControl::LoseFocus (void)
{
::Window::LoseFocus();
if (GetTitleBar() != NULL)
GetTitleBar()->SetFocus (false);
}
void TitledControl::KeyInput (const KeyEvent& rEvent)
{
KeyCode nCode = rEvent.GetKeyCode();
if (nCode == KEY_SPACE)
{
// Toggle the expansion state of the control (when toggling is
// supported.) The focus remains on this control.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
ControlContainer::ES_TOGGLE);
}
else if (nCode == KEY_RETURN)
{
// Return, also called enter, enters the control and puts the
// focus to the first child. If the control is not yet
// expanded then do that first.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
ControlContainer::ES_EXPAND);
if ( ! FocusManager::Instance().TransferFocus(this,nCode))
{
// When already expanded then put focus on first child.
TreeNode* pControl = GetControl(false);
if (pControl!=NULL && IsExpanded())
if (pControl->GetWindow() != NULL)
pControl->GetWindow()->GrabFocus();
}
}
else if (nCode == KEY_ESCAPE)
{
if ( ! FocusManager::Instance().TransferFocus(this,nCode))
// Put focus to parent.
GetParent()->GrabFocus();
}
else
Window::KeyInput (rEvent);
}
const String& TitledControl::GetTitle (void) const
{
return msTitle;
}
bool TitledControl::Expand (bool bExpanded)
{
bool bExpansionStateChanged (false);
if (IsExpandable())
{
if (GetTitleBar()->IsExpanded() != bExpanded)
bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
// Get the control. Use the bExpanded parameter as argument to
// indicate that a control is created via its factory only when it
// is to be expanded. When it is collapsed this is not necessary.
TreeNode* pControl = GetControl(bExpanded);
if (pControl != NULL
&& GetControl()->IsExpanded() != bExpanded)
{
bExpansionStateChanged |= pControl->Expand (bExpanded);
}
if (bExpansionStateChanged)
UpdateStates();
}
return bExpansionStateChanged;
}
bool TitledControl::IsExpandable (void) const
{
const TreeNode* pControl = GetConstControl(false);
if (pControl != NULL)
return pControl->IsExpandable();
else
// When a control factory is given but the control has not yet been
// created we assume that the control is expandable.
return true;
}
bool TitledControl::IsExpanded (void) const
{
const TreeNode* pControl = GetConstControl(false);
if (pControl != NULL)
return pControl->IsExpanded();
else
return false;
}
void TitledControl::SetUserData (void* pUserData)
{
mpUserData = pUserData;
}
void* TitledControl::GetUserData (void) const
{
return mpUserData;
}
bool TitledControl::IsShowing (void) const
{
return mbVisible;
}
void TitledControl::Show (bool bVisible)
{
if (mbVisible != bVisible)
{
mbVisible = bVisible;
UpdateStates ();
}
}
void TitledControl::UpdateStates (void)
{
if (mbVisible)
GetWindow()->Show();
else
GetWindow()->Hide();
TreeNode* pControl = GetControl(false);
if (pControl!=NULL && pControl->GetWindow() != NULL)
if (IsVisible() && IsExpanded())
pControl->GetWindow()->Show();
else
pControl->GetWindow()->Hide();
}
IMPL_LINK(TitledControl, WindowEventListener,
VclSimpleEvent*, pEvent)
{
if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
{
VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
switch (pWindowEvent->GetId())
{
case VCLEVENT_WINDOW_MOUSEBUTTONUP:
// Toggle expansion.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
mbExpansionModeIsToggle ? ControlContainer::ES_TOGGLE
: ControlContainer::ES_EXPAND);
break;
}
}
return 0;
}
TreeNode* TitledControl::GetControl (bool bCreate)
{
TreeNode* pNode = mpControlContainer->GetControl(1);
if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
{
// We have to create the control with the factory object.
::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
if (pControl.get() != NULL)
{
pControl->SetParentNode(this);
mpControlContainer->AddControl(pControl);
pNode = mpControlContainer->GetControl(1);
FocusManager::Instance().RegisterDownLink(this, pNode->GetWindow());
FocusManager::Instance().RegisterUpLink(pNode->GetWindow(), this);
}
}
return pNode;
}
const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
return const_cast<TitledControl*>(this)->GetControl(bCreate);
}
TitleBar* TitledControl::GetTitleBar (void)
{
return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> TitledControl::CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& )
{
return new ::accessibility::AccessibleTreeNode(
*this,
GetTitle(),
GetTitle(),
::com::sun::star::accessibility::AccessibleRole::LIST_ITEM);
}
} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS components1 (1.11.14); FILE MERGED 2007/01/25 15:24:19 af 1.11.14.2: RESYNC: (1.11-1.12); FILE MERGED 2007/01/24 17:51:21 af 1.11.14.1: #i68075# The click handler can now be supplied along with a control.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: TitledControl.cxx,v $
*
* $Revision: 1.13 $
*
* last change: $Author: rt $ $Date: 2007-04-03 16:21:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "taskpane/TitledControl.hxx"
#include "AccessibleTreeNode.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
namespace sd { namespace toolpanel {
TitledControl::TitledControl (
TreeNode* pParent,
::std::auto_ptr<TreeNode> pControl,
const String& rTitle,
const ClickHandler& rClickHandler,
TitleBar::TitleBarType eType)
: ::Window (pParent->GetWindow(), WB_TABSTOP),
TreeNode(pParent),
msTitle(rTitle),
mbVisible(true),
mpUserData(NULL),
mpControlFactory(NULL),
mpClickHandler(new ClickHandler(rClickHandler)),
mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
if (pControl.get() != NULL)
{
mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
new TitleBar (this, rTitle, eType, pControl->IsExpandable())));
pControl->SetParentNode (this);
}
mpControlContainer->AddControl (pControl);
FocusManager::Instance().RegisterDownLink(this, GetControl()->GetWindow());
FocusManager::Instance().RegisterUpLink(GetControl()->GetWindow(), this);
SetBackground (Wallpaper());
GetTitleBar()->GetWindow()->Show ();
GetTitleBar()->GetWindow()->AddEventListener (
LINK(this,TitledControl,WindowEventListener));
UpdateStates ();
}
TitledControl::TitledControl (
TreeNode* pParent,
::std::auto_ptr<ControlFactory> pControlFactory,
const String& rTitle,
const ClickHandler& rClickHandler,
TitleBar::TitleBarType eType)
: ::Window (pParent->GetWindow(), WB_TABSTOP),
TreeNode(pParent),
msTitle (rTitle),
mbVisible (true),
mpUserData (NULL),
mpControlFactory(pControlFactory),
mpClickHandler(new ClickHandler(rClickHandler)),
mbExpansionModeIsToggle(eType!=TitleBar::TBT_CONTROL_TITLE)
{
mpControlContainer->AddControl (::std::auto_ptr<TreeNode> (
new TitleBar (this, rTitle, eType, true)));
// The second control is created on demand, i.e. when GetControl(true)
// is called the first time.
SetBackground (Wallpaper());
GetTitleBar()->GetWindow()->Show ();
GetTitleBar()->GetWindow()->AddEventListener (
LINK(this,TitledControl,WindowEventListener));
UpdateStates ();
}
TitledControl::~TitledControl (void)
{
GetTitleBar()->GetWindow()->RemoveEventListener (
LINK(this,TitledControl,WindowEventListener));
}
Size TitledControl::GetPreferredSize (void)
{
Size aPreferredSize;
if (GetControl(false) != NULL)
{
aPreferredSize = GetControl()->GetPreferredSize();
if ( ! IsExpanded())
aPreferredSize.Height() = 0;
}
else
aPreferredSize = Size (GetSizePixel().Width(), 0);
if (aPreferredSize.Width() == 0)
aPreferredSize.Width() = 300;
aPreferredSize.Height() += GetTitleBar()->GetPreferredHeight(
aPreferredSize.Width());
return aPreferredSize;
}
sal_Int32 TitledControl::GetPreferredWidth (sal_Int32 nHeight)
{
int nPreferredWidth = 0;
if (GetControl(false) != NULL)
nPreferredWidth = GetControl()->GetPreferredWidth(
nHeight - GetTitleBar()->GetWindow()->GetSizePixel().Height());
else
nPreferredWidth = GetSizePixel().Width();
if (nPreferredWidth == 0)
nPreferredWidth = 300;
return nPreferredWidth;
}
sal_Int32 TitledControl::GetPreferredHeight (sal_Int32 nWidth)
{
int nPreferredHeight = 0;
if (IsExpanded() && GetControl(false)!=NULL)
nPreferredHeight = GetControl()->GetPreferredHeight(nWidth);
nPreferredHeight += GetTitleBar()->GetPreferredHeight(nWidth);
return nPreferredHeight;
}
bool TitledControl::IsResizable (void)
{
return IsExpanded()
&& GetControl()->IsResizable();
}
::Window* TitledControl::GetWindow (void)
{
return this;
}
void TitledControl::Resize (void)
{
Size aWindowSize (GetOutputSizePixel());
int nTitleBarHeight
= GetTitleBar()->GetPreferredHeight(aWindowSize.Width());
GetTitleBar()->GetWindow()->SetPosSizePixel (
Point (0,0),
Size (aWindowSize.Width(), nTitleBarHeight));
TreeNode* pControl = GetControl(false);
if (pControl != NULL
&& pControl->GetWindow() != NULL
&& pControl->GetWindow()->IsVisible())
{
pControl->GetWindow()->SetPosSizePixel (
Point (0,nTitleBarHeight),
Size (aWindowSize.Width(), aWindowSize.Height()-nTitleBarHeight));
}
}
void TitledControl::GetFocus (void)
{
::Window::GetFocus();
if (GetTitleBar() != NULL)
GetTitleBar()->SetFocus (true);
}
void TitledControl::LoseFocus (void)
{
::Window::LoseFocus();
if (GetTitleBar() != NULL)
GetTitleBar()->SetFocus (false);
}
void TitledControl::KeyInput (const KeyEvent& rEvent)
{
KeyCode nCode = rEvent.GetKeyCode();
if (nCode == KEY_SPACE)
{
// Toggle the expansion state of the control (when toggling is
// supported.) The focus remains on this control.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
ControlContainer::ES_TOGGLE);
}
else if (nCode == KEY_RETURN)
{
// Return, also called enter, enters the control and puts the
// focus to the first child. If the control is not yet
// expanded then do that first.
GetParentNode()->GetControlContainer().SetExpansionState (
this,
ControlContainer::ES_EXPAND);
if ( ! FocusManager::Instance().TransferFocus(this,nCode))
{
// When already expanded then put focus on first child.
TreeNode* pControl = GetControl(false);
if (pControl!=NULL && IsExpanded())
if (pControl->GetWindow() != NULL)
pControl->GetWindow()->GrabFocus();
}
}
else if (nCode == KEY_ESCAPE)
{
if ( ! FocusManager::Instance().TransferFocus(this,nCode))
// Put focus to parent.
GetParent()->GrabFocus();
}
else
Window::KeyInput (rEvent);
}
const String& TitledControl::GetTitle (void) const
{
return msTitle;
}
bool TitledControl::Expand (bool bExpanded)
{
bool bExpansionStateChanged (false);
if (IsExpandable())
{
if (GetTitleBar()->IsExpanded() != bExpanded)
bExpansionStateChanged |= GetTitleBar()->Expand (bExpanded);
// Get the control. Use the bExpanded parameter as argument to
// indicate that a control is created via its factory only when it
// is to be expanded. When it is collapsed this is not necessary.
TreeNode* pControl = GetControl(bExpanded);
if (pControl != NULL
&& GetControl()->IsExpanded() != bExpanded)
{
bExpansionStateChanged |= pControl->Expand (bExpanded);
}
if (bExpansionStateChanged)
UpdateStates();
}
return bExpansionStateChanged;
}
bool TitledControl::IsExpandable (void) const
{
const TreeNode* pControl = GetConstControl(false);
if (pControl != NULL)
return pControl->IsExpandable();
else
// When a control factory is given but the control has not yet been
// created we assume that the control is expandable.
return true;
}
bool TitledControl::IsExpanded (void) const
{
const TreeNode* pControl = GetConstControl(false);
if (pControl != NULL)
return pControl->IsExpanded();
else
return false;
}
void TitledControl::SetUserData (void* pUserData)
{
mpUserData = pUserData;
}
void* TitledControl::GetUserData (void) const
{
return mpUserData;
}
bool TitledControl::IsShowing (void) const
{
return mbVisible;
}
void TitledControl::Show (bool bVisible)
{
if (mbVisible != bVisible)
{
mbVisible = bVisible;
UpdateStates ();
}
}
void TitledControl::UpdateStates (void)
{
if (mbVisible)
GetWindow()->Show();
else
GetWindow()->Hide();
TreeNode* pControl = GetControl(false);
if (pControl!=NULL && pControl->GetWindow() != NULL)
if (IsVisible() && IsExpanded())
pControl->GetWindow()->Show();
else
pControl->GetWindow()->Hide();
}
IMPL_LINK(TitledControl, WindowEventListener,
VclSimpleEvent*, pEvent)
{
if (pEvent!=NULL && pEvent->ISA(VclWindowEvent))
{
VclWindowEvent* pWindowEvent = static_cast<VclWindowEvent*>(pEvent);
switch (pWindowEvent->GetId())
{
case VCLEVENT_WINDOW_MOUSEBUTTONUP:
(*mpClickHandler)(*this);
break;
}
}
return 0;
}
TreeNode* TitledControl::GetControl (bool bCreate)
{
TreeNode* pNode = mpControlContainer->GetControl(1);
if (pNode==NULL && mpControlFactory.get()!=NULL && bCreate)
{
// We have to create the control with the factory object.
::std::auto_ptr<TreeNode> pControl (mpControlFactory->CreateControl(this));//GetParentNode()));
if (pControl.get() != NULL)
{
pControl->SetParentNode(this);
mpControlContainer->AddControl(pControl);
pNode = mpControlContainer->GetControl(1);
FocusManager::Instance().RegisterDownLink(this, pNode->GetWindow());
FocusManager::Instance().RegisterUpLink(pNode->GetWindow(), this);
}
}
return pNode;
}
const TreeNode* TitledControl::GetConstControl (bool bCreate) const
{
return const_cast<TitledControl*>(this)->GetControl(bCreate);
}
TitleBar* TitledControl::GetTitleBar (void)
{
return static_cast<TitleBar*>(mpControlContainer->GetControl(0));
}
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> TitledControl::CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& )
{
return new ::accessibility::AccessibleTreeNode(
*this,
GetTitle(),
GetTitle(),
::com::sun::star::accessibility::AccessibleRole::LIST_ITEM);
}
//===== TitledControlStandardClickHandler =====================================
TitledControlStandardClickHandler::TitledControlStandardClickHandler (
ControlContainer& rControlContainer,
ControlContainer::ExpansionState eExpansionState)
: mrControlContainer(rControlContainer),
meExpansionState(eExpansionState)
{
}
void TitledControlStandardClickHandler::operator () (TitledControl& rTitledControl)
{
// Toggle expansion.
mrControlContainer.SetExpansionState (&rTitledControl, meExpansionState);
}
} } // end of namespace ::sd::toolpanel
<|endoftext|> |
<commit_before>//
// nif_cass_uuid.cpp
// erlcass
//
// Created by silviu on 6/2/15.
//
//
#include "nif_cass_uuid.h"
#include "erlcass.h"
#include "utils.h"
typedef struct
{
CassUuidGen* gen;
}
EnifCassUuidGen;
ERL_NIF_TERM nif_cass_uuid_gen_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
cassandra_data* data = (cassandra_data*) enif_priv_data(env);
EnifCassUuidGen *enif_gen = (EnifCassUuidGen*) enif_alloc_resource(data->resCassUuidGen, sizeof(EnifCassUuidGen));
if(enif_gen == NULL)
return make_error(env, "enif_alloc_resource failed");
enif_gen->gen = cass_uuid_gen_new();
ERL_NIF_TERM term = enif_make_resource(env, enif_gen);
enif_release_resource(enif_gen);
return enif_make_tuple2(env, ATOMS.atomOk, term);
}
void nif_cass_uuid_gen_free(ErlNifEnv* env, void* obj)
{
EnifCassUuidGen *enif_gen = (EnifCassUuidGen*) obj;
if(enif_gen->gen != NULL)
cass_uuid_gen_free(enif_gen->gen);
}
ERL_NIF_TERM cass_uuid_to_nif(ErlNifEnv* env, const CassUuid& obj)
{
char buffer[CASS_UUID_STRING_LENGTH];
cass_uuid_string(obj, buffer);
return enif_make_tuple2(env, ATOMS.atomOk, make_binary(env, buffer, CASS_UUID_STRING_LENGTH - 1));
}
ERL_NIF_TERM nif_cass_uuid_gen_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
cassandra_data* data = (cassandra_data*) enif_priv_data(env);
EnifCassUuidGen * enif_gen = NULL;
if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_gen_time(enif_gen->gen, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_gen_random(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
cassandra_data* data = (cassandra_data*) enif_priv_data(env);
EnifCassUuidGen * enif_gen = NULL;
if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_gen_random(enif_gen->gen, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_gen_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
cassandra_data* data = (cassandra_data*) enif_priv_data(env);
EnifCassUuidGen * enif_gen = NULL;
if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
return enif_make_badarg(env);
unsigned long timestamp;
if(!enif_get_uint64(env, argv[1], ×tamp))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_gen_from_time(enif_gen->gen, timestamp, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_min_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned long timestamp;
if(!enif_get_uint64(env, argv[1], ×tamp))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_min_from_time(timestamp, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_max_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned long timestamp;
if(!enif_get_uint64(env, argv[1], ×tamp))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_max_from_time(timestamp, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_timestamp(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
std::string str_value;
if(!get_string(env, argv[1], str_value))
return enif_make_badarg(env);
CassUuid uuid;
if(cass_uuid_from_string(str_value.c_str(), &uuid) != CASS_OK)
return enif_make_badarg(env);
return enif_make_tuple2(env, ATOMS.atomOk, enif_make_uint64(env, cass_uuid_timestamp(uuid)));
}
ERL_NIF_TERM nif_cass_uuid_version(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
std::string str_value;
if(!get_string(env, argv[1], str_value))
return enif_make_badarg(env);
CassUuid uuid;
if(cass_uuid_from_string(str_value.c_str(), &uuid) != CASS_OK)
return enif_make_badarg(env);
return enif_make_tuple2(env, ATOMS.atomOk, enif_make_int(env,cass_uuid_version(uuid)));
}
<commit_msg>Fix for uuid functions<commit_after>//
// nif_cass_uuid.cpp
// erlcass
//
// Created by silviu on 6/2/15.
//
//
#include "nif_cass_uuid.h"
#include "erlcass.h"
#include "utils.h"
typedef struct
{
CassUuidGen* gen;
}
EnifCassUuidGen;
ERL_NIF_TERM nif_cass_uuid_gen_new(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
cassandra_data* data = (cassandra_data*) enif_priv_data(env);
EnifCassUuidGen *enif_gen = (EnifCassUuidGen*) enif_alloc_resource(data->resCassUuidGen, sizeof(EnifCassUuidGen));
if(enif_gen == NULL)
return make_error(env, "enif_alloc_resource failed");
enif_gen->gen = cass_uuid_gen_new();
ERL_NIF_TERM term = enif_make_resource(env, enif_gen);
enif_release_resource(enif_gen);
return enif_make_tuple2(env, ATOMS.atomOk, term);
}
void nif_cass_uuid_gen_free(ErlNifEnv* env, void* obj)
{
EnifCassUuidGen *enif_gen = (EnifCassUuidGen*) obj;
if(enif_gen->gen != NULL)
cass_uuid_gen_free(enif_gen->gen);
}
ERL_NIF_TERM cass_uuid_to_nif(ErlNifEnv* env, const CassUuid& obj)
{
char buffer[CASS_UUID_STRING_LENGTH];
cass_uuid_string(obj, buffer);
return enif_make_tuple2(env, ATOMS.atomOk, make_binary(env, buffer, CASS_UUID_STRING_LENGTH - 1));
}
ERL_NIF_TERM nif_cass_uuid_gen_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
cassandra_data* data = (cassandra_data*) enif_priv_data(env);
EnifCassUuidGen * enif_gen = NULL;
if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_gen_time(enif_gen->gen, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_gen_random(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
cassandra_data* data = (cassandra_data*) enif_priv_data(env);
EnifCassUuidGen * enif_gen = NULL;
if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_gen_random(enif_gen->gen, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_gen_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
cassandra_data* data = (cassandra_data*) enif_priv_data(env);
EnifCassUuidGen * enif_gen = NULL;
if(!enif_get_resource(env, argv[0], data->resCassUuidGen, (void**) &enif_gen))
return enif_make_badarg(env);
unsigned long timestamp;
if(!enif_get_uint64(env, argv[1], ×tamp))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_gen_from_time(enif_gen->gen, timestamp, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_min_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned long timestamp;
if(!enif_get_uint64(env, argv[0], ×tamp))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_min_from_time(timestamp, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_max_from_time(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
unsigned long timestamp;
if(!enif_get_uint64(env, argv[0], ×tamp))
return enif_make_badarg(env);
CassUuid obj;
cass_uuid_max_from_time(timestamp, &obj);
return cass_uuid_to_nif(env, obj);
}
ERL_NIF_TERM nif_cass_uuid_timestamp(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
std::string str_value;
if(!get_string(env, argv[0], str_value))
return enif_make_badarg(env);
CassUuid uuid;
if(cass_uuid_from_string(str_value.c_str(), &uuid) != CASS_OK)
return enif_make_badarg(env);
return enif_make_tuple2(env, ATOMS.atomOk, enif_make_uint64(env, cass_uuid_timestamp(uuid)));
}
ERL_NIF_TERM nif_cass_uuid_version(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[])
{
std::string str_value;
if(!get_string(env, argv[0], str_value))
return enif_make_badarg(env);
CassUuid uuid;
if(cass_uuid_from_string(str_value.c_str(), &uuid) != CASS_OK)
return enif_make_badarg(env);
return enif_make_tuple2(env, ATOMS.atomOk, enif_make_int(env,cass_uuid_version(uuid)));
}
<|endoftext|> |
<commit_before>#ifdef USE_SDL
#include <SDL.h>
#endif
#include "bitmap.h"
#include "events.h"
#include "exceptions/shutdown_exception.h"
#include "funcs.h"
#include "thread.h"
namespace Util{
EventManager::EventManager(){
}
#ifdef USE_SDL
void EventManager::runSDL(){
SDL_Event event;
while (SDL_PollEvent(&event) == 1){
switch (event.type){
case SDL_QUIT : {
dispatch(CloseWindow);
break;
}
case SDL_VIDEORESIZE : {
dispatch(ResizeScreen, event.resize.w, event.resize.h);
break;
}
default : {
break;
}
}
}
}
#endif
void EventManager::run(){
#ifdef USE_SDL
runSDL();
#endif
}
/* kill the program if the user requests */
void EventManager::waitForThread(WaitThread & thread){
while (!thread.isRunning()){
try{
run();
} catch (const ShutdownException & death){
thread.kill();
throw death;
}
Util::rest(10);
}
}
EventManager::~EventManager(){
}
void EventManager::dispatch(Event type, int arg1, int arg2){
switch (type){
case ResizeScreen : {
Bitmap::setGraphicsMode(0, arg1, arg2);
break;
}
default : break;
}
}
void EventManager::dispatch(Event type){
switch (type){
case CloseWindow : {
throw ShutdownException();
}
default : break;
}
}
}
<commit_msg>enforce aspect ratios<commit_after>#ifdef USE_SDL
#include <SDL.h>
#endif
#include "bitmap.h"
#include "events.h"
#include "exceptions/shutdown_exception.h"
#include "funcs.h"
#include "thread.h"
namespace Util{
EventManager::EventManager(){
}
#ifdef USE_SDL
void EventManager::runSDL(){
SDL_Event event;
while (SDL_PollEvent(&event) == 1){
switch (event.type){
case SDL_QUIT : {
dispatch(CloseWindow);
break;
}
case SDL_VIDEORESIZE : {
int width = event.resize.w;
int height = event.resize.h;
/* to keep the perspective correct
* 640/480 = 1.33333
*/
if (width > height){
height = (int)((double) width / 1.3333333333);
} else {
width = (int)((double) height * 1.3333333333);
}
dispatch(ResizeScreen, width, height);
break;
}
default : {
break;
}
}
}
}
#endif
void EventManager::run(){
#ifdef USE_SDL
runSDL();
#endif
}
/* kill the program if the user requests */
void EventManager::waitForThread(WaitThread & thread){
while (!thread.isRunning()){
try{
run();
} catch (const ShutdownException & death){
thread.kill();
throw death;
}
Util::rest(10);
}
}
EventManager::~EventManager(){
}
void EventManager::dispatch(Event type, int arg1, int arg2){
switch (type){
case ResizeScreen : {
Bitmap::setGraphicsMode(0, arg1, arg2);
break;
}
default : break;
}
}
void EventManager::dispatch(Event type){
switch (type){
case CloseWindow : {
throw ShutdownException();
}
default : break;
}
}
}
<|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: statusbarcontroller.hxx,v $
* $Revision: 1.2 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef RPTUI_STATUSBARCONTROLLER_HXX
#define RPTUI_STATUSBARCONTROLLER_HXX
#include <svtools/statusbarcontroller.hxx>
#include <comphelper/uno3.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <cppuhelper/implbase1.hxx>
#include <comphelper/implementationreference.hxx>
class SfxStatusBarControl;
namespace rptui
{
typedef ::comphelper::ImplementationReference<SfxStatusBarControl,::com::sun::star::frame::XStatusbarController> TStatusbarHelper;
typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XServiceInfo> OStatusbarController_BASE;
class OStatusbarController : public ::svt::StatusbarController,
public OStatusbarController_BASE
{
TStatusbarHelper m_pController;
sal_uInt16 m_nSlotId;
sal_uInt16 m_nId;
public:
OStatusbarController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
create(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext);
private:
void SAL_CALL OStatusbarController::dispose() throw (::com::sun::star::uno::RuntimeException);
// XInterface
DECLARE_XINTERFACE( )
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// need by registration
virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XUpdatable
virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException);
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );
// XStatusbarController
virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos,
::sal_Int32 nCommand,
::sal_Bool bMouseEvent,
const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics,
const ::com::sun::star::awt::Rectangle& rOutputRectangle,
::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException);
};
}
#endif // DBAUI_STATUSBARCONTROLLER_HXX
<commit_msg>#i10000# removed extra qualification<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: statusbarcontroller.hxx,v $
* $Revision: 1.2 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef RPTUI_STATUSBARCONTROLLER_HXX
#define RPTUI_STATUSBARCONTROLLER_HXX
#include <svtools/statusbarcontroller.hxx>
#include <comphelper/uno3.hxx>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <cppuhelper/implbase1.hxx>
#include <comphelper/implementationreference.hxx>
class SfxStatusBarControl;
namespace rptui
{
typedef ::comphelper::ImplementationReference<SfxStatusBarControl,::com::sun::star::frame::XStatusbarController> TStatusbarHelper;
typedef ::cppu::ImplHelper1 < ::com::sun::star::lang::XServiceInfo> OStatusbarController_BASE;
class OStatusbarController : public ::svt::StatusbarController,
public OStatusbarController_BASE
{
TStatusbarHelper m_pController;
sal_uInt16 m_nSlotId;
sal_uInt16 m_nId;
public:
OStatusbarController(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxORB);
static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL
create(::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext > const & xContext);
private:
void SAL_CALL dispose() throw (::com::sun::star::uno::RuntimeException);
// XInterface
DECLARE_XINTERFACE( )
// XServiceInfo
virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);
// need by registration
virtual ::sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException);
// XInitialization
virtual void SAL_CALL initialize( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& aArguments ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException);
// XUpdatable
virtual void SAL_CALL update() throw (::com::sun::star::uno::RuntimeException);
// XStatusListener
virtual void SAL_CALL statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event ) throw ( ::com::sun::star::uno::RuntimeException );
// XStatusbarController
virtual ::sal_Bool SAL_CALL mouseButtonDown( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL mouseMove( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual ::sal_Bool SAL_CALL mouseButtonUp( const ::com::sun::star::awt::MouseEvent& aMouseEvent ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL command( const ::com::sun::star::awt::Point& aPos,
::sal_Int32 nCommand,
::sal_Bool bMouseEvent,
const ::com::sun::star::uno::Any& aData ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL paint( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XGraphics >& xGraphics,
const ::com::sun::star::awt::Rectangle& rOutputRectangle,
::sal_Int32 nItemId, ::sal_Int32 nStyle ) throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL click() throw (::com::sun::star::uno::RuntimeException);
virtual void SAL_CALL doubleClick() throw (::com::sun::star::uno::RuntimeException);
};
}
#endif // DBAUI_STATUSBARCONTROLLER_HXX
<|endoftext|> |
<commit_before>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University 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.
*/
/*booksim_config.cpp
*
*Contains all the configurable parameters in a network
*
*/
#include "booksim.hpp"
#include "booksim_config.hpp"
BookSimConfig::BookSimConfig( )
{
//========================================================
// Network options
//========================================================
// Channel length listing file
AddStrField( "channel_file", "" ) ;
// Use read/write request reply scheme
_int_map["use_read_write"] = 0;
_int_map["read_request_begin_vc"] = 0;
_int_map["read_request_end_vc"] = 5;
_int_map["write_request_begin_vc"] = 2;
_int_map["write_request_end_vc"] = 7;
_int_map["read_reply_begin_vc"] = 8;
_int_map["read_reply_end_vc"] = 13;
_int_map["write_reply_begin_vc"] = 10;
_int_map["write_reply_end_vc"] = 15;
// Physical sub-networks
_int_map["physical_subnetworks"] = 1;
// Control Injection of Packets into Replicated Networks
_int_map["read_request_subnet"] = 0;
_int_map["read_reply_subnet"] = 0;
_int_map["write_request_subnet"] = 0;
_int_map["write_reply_subnet"] = 0;
// TCC Simulation Traffic Trace
AddStrField( "trace_file", "trace-file.txt" ) ;
//==== Topology options =======================
//important
AddStrField( "topology", "torus" );
_int_map["k"] = 8; //network radix
_int_map["n"] = 2; //network dimension
_int_map["c"] = 1; //concentration
AddStrField( "routing_function", "none" );
_int_map["use_noc_latency"] = 1;
//not critical
_int_map["x"] = 8; //number of routers in X
_int_map["y"] = 8; //number of routers in Y
_int_map["xr"] = 1; //number of nodes per router in X only if c>1
_int_map["yr"] = 1; //number of nodes per router in Y only if c>1
_int_map["limit"] = 0; //how many of the nodes are actually used
_int_map["link_failures"] = 0; //legacy
_int_map["fail_seed"] = 0; //legacy
//==== Cmesh topology options =======================
_int_map["express_channels"] = 0; //for Cmesh only, 0=no express channels
//==== Single-node options ===============================
_int_map["in_ports"] = 5;
_int_map["out_ports"] = 5;
_int_map["voq"] = 0; //output queuing
//========================================================
// Router options
//========================================================
//==== General options ===================================
AddStrField( "router", "iq" );
_int_map["output_delay"] = 0;
_int_map["credit_delay"] = 0;
_float_map["internal_speedup"] = 1.0;
//==== Input-queued ======================================
// Control of virtual channel speculation
_int_map["speculative"] = 0 ;
// what to use to inhibit speculative allocator grants?
AddStrField("filter_spec_grants", "confl_nonspec_gnts");
_int_map["num_vcs"] = 16;
_int_map["vc_buf_size"] = 8;
_int_map["wait_for_tail_credit"] = 0; // reallocate a VC before a tail credit?
_int_map["vc_busy_when_full"] = 0; // mark VCs as in use when they have no credit available
_int_map["vc_priority_donation"] = 0; // allow high-priority flits to donate their priority to low-priority that they are queued up behind
_int_map["replies_inherit_priority"] = 0; // whenusing request-reply traffic (use_read_write=1) with age-based priority, make replies inherit their corresponding requests' age
_int_map["hold_switch_for_packet"] = 0; // hold a switch config for the entire packet
_int_map["input_speedup"] = 1; // expansion of input ports into crossbar
_int_map["output_speedup"] = 1; // expansion of output ports into crossbar
_int_map["routing_delay"] = 0;
_int_map["vc_alloc_delay"] = 0;
_int_map["sw_alloc_delay"] = 0;
_int_map["st_prepare_delay"] = 0;
_int_map["st_final_delay"] = 0;
//==== Event-driven =====================================
_int_map["vct"] = 0;
//==== Allocators ========================================
AddStrField( "vc_allocator", "islip" );
AddStrField( "sw_allocator", "islip" );
AddStrField( "vc_alloc_arb_type", "round_robin" );
AddStrField( "sw_alloc_arb_type", "round_robin" );
_int_map["alloc_iters"] = 1;
// dub: allow setting the number of iterations for each allocator separately
// (a value of 0 indicates it should inherit its value from alloc_iters)
_int_map["vc_alloc_iters"] = 0;
_int_map["sw_alloc_iters"] = 0;
//==== Traffic ========================================
AddStrField( "traffic", "uniform" );
_int_map["perm_seed"] = 0; // seed value for random permuation trafficpattern generator
_float_map["injection_rate"] = 0.1; //if 0.0 assumes it is batch mode
_int_map["injection_rate_uses_flits"] = 0;
_int_map["const_flits_per_packet"] = 1; //use read_request_size etc insted
AddStrField( "injection_process", "bernoulli" );
_float_map["burst_alpha"] = 0.5; // burst interval
_float_map["burst_beta"] = 0.5; // burst length
AddStrField( "priority", "none" ); // message priorities
_int_map["batch_size"] = 1000;
_int_map["batch_count"] = 1;
_int_map["max_outstanding_requests"] = 4;
_int_map["read_request_size"] = 1; //flit per packet
_int_map["write_request_size"] = 1; //flit per packet
_int_map["read_reply_size"] = 1; //flit per packet
_int_map["write_reply_size"] = 1; //flit per packet
//==== Simulation parameters ==========================
// types:
// latency - average + latency distribution for a particular injection rate
// throughput - sustained throughput for a particular injection rate
AddStrField( "sim_type", "latency" );
_int_map["warmup_periods"] = 3; // number of samples periods to "warm-up" the simulation
_int_map["sample_period"] = 1000; // how long between measurements
_int_map["max_samples"] = 10; // maximum number of sample periods in a simulation
_float_map["latency_thres"] = 500.0; // if avg. latency exceeds the threshold, assume unstable
_float_map["warmup_thres"] = 0.05; // consider warmed up once relative change in latency and throughput between successive iterations is smaller than this
// consider converged once relative change in latency / throughput between successive iterations is smaller than this
_float_map["stopping_thres"] = 0.05;
_float_map["acc_stopping_thres"] = 0.05;
_int_map["sim_count"] = 1; // number of simulations to perform
_int_map["include_queuing"] =1; // non-zero includes source queuing latency
// _int_map["reorder"] = 0; // know what you're doing
//_int_map["flit_timing"] = 0; // know what you're doing
//_int_map["split_packets"] = 0; // know what you're doing
_int_map["seed"] = 0; //random seed for simulation, e.g. traffic
_int_map["print_activity"] = 0;
_int_map["print_csv_results"] = 0;
_int_map["print_vc_stats"] = 0;
_int_map["drain_measured_only"] = 0;
_int_map["viewer_trace"] = 0;
AddStrField("watch_file", "");
AddStrField("watch_out", "");
AddStrField("stats_out", "");
AddStrField("flow_out", "");
//==================Power model params=====================
_int_map["sim_power"] = 0;
AddStrField("power_output_file","pwr_tmp");
AddStrField("tech_file", "../utils/temp");
_int_map["channel_width"] = 128;
_int_map["channel_sweep"] = 0;
//==================Network file===========================
AddStrField("network_file","");
}
//A list of important simulator for the booksim gui, anything else not listed here is still included
//but just not very organized
vector< pair<string, vector< string> > > *BookSimConfig::GetImportantMap(){
//Vector of 5 categories, each category is a vector of potions. Maps don't work because it autosorts
vector< pair<string, vector< string> > > *important = new vector< pair<string, vector< string> > >;
important->push_back( make_pair( "Topology", vector<string>() ));
(*important)[0].second.push_back("topology");
(*important)[0].second.push_back("k");
(*important)[0].second.push_back("n");
(*important)[0].second.push_back("c");
(*important)[0].second.push_back( "routing_function");
(*important)[0].second.push_back("use_noc_latency");
important->push_back(make_pair("Router", vector<string>()));
(*important)[1].second.push_back("router");
(*important)[1].second.push_back("num_vcs");
(*important)[1].second.push_back("vc_buf_size");
(*important)[1].second.push_back("routing_delay");
(*important)[1].second.push_back("vc_alloc_delay");
(*important)[1].second.push_back("sw_alloc_delay");
(*important)[1].second.push_back("st_prepare_delay");
(*important)[1].second.push_back("st_final_delay");
important->push_back(make_pair("Allocator", vector<string>()));
(*important)[2].second.push_back("vc_allocator");
(*important)[2].second.push_back("vc_alloc_arb_type");
(*important)[2].second.push_back("sw_allocator");
(*important)[2].second.push_back("sw_alloc_arb_type");
(*important)[2].second.push_back( "priority");
(*important)[2].second.push_back("speculative");
important->push_back(make_pair("Simulation", vector<string>()));
(*important)[3].second.push_back("traffic");
(*important)[3].second.push_back("injection_rate");
(*important)[3].second.push_back("injection_rate_uses_flits");
(*important)[3].second.push_back("sim_type");
(*important)[3].second.push_back("latency_thres");
(*important)[3].second.push_back("const_flits_per_packet");
(*important)[3].second.push_back("injection_process");
(*important)[3].second.push_back("sample_period");
important->push_back(make_pair("Statistics", vector<string>()));
(*important)[4].second.push_back("print_activity");
(*important)[4].second.push_back("print_csv_results");
(*important)[4].second.push_back("print_vc_stats");
(*important)[4].second.push_back("stats_out");
(*important)[4].second.push_back("sim_power");
(*important)[4].second.push_back("power_output_file");
return important;
}
PowerConfig::PowerConfig( )
{
_int_map["H_INVD2"] = 0;
_int_map["W_INVD2"] = 0;
_int_map["H_DFQD1"] = 0;
_int_map["W_DFQD1"] = 0;
_int_map["H_ND2D1"] = 0;
_int_map["W_ND2D1"] = 0;
_int_map["H_SRAM"] = 0;
_int_map["W_SRAM"] = 0;
_float_map["Vdd"] = 0;
_float_map["R"] = 0;
_float_map["IoffSRAM"] = 0;
_float_map["IoffP"] = 0;
_float_map["IoffN"] = 0;
_float_map["Cg_pwr"] = 0;
_float_map["Cd_pwr"] = 0;
_float_map["Cgdl"] = 0;
_float_map["Cg"] = 0;
_float_map["Cd"] = 0;
_float_map["LAMBDA"] = 0;
_float_map["MetalPitch"] = 0;
_float_map["Rw"] = 0;
_float_map["Cw_gnd"] = 0;
_float_map["Cw_cpl"] = 0;
_float_map["wire_length"] = 0;
}
<commit_msg>use sane default for router configuration<commit_after>// $Id$
/*
Copyright (c) 2007-2009, Trustees of The Leland Stanford Junior University
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
Neither the name of the Stanford University 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.
*/
/*booksim_config.cpp
*
*Contains all the configurable parameters in a network
*
*/
#include "booksim.hpp"
#include "booksim_config.hpp"
BookSimConfig::BookSimConfig( )
{
//========================================================
// Network options
//========================================================
// Channel length listing file
AddStrField( "channel_file", "" ) ;
// Use read/write request reply scheme
_int_map["use_read_write"] = 0;
_int_map["read_request_begin_vc"] = 0;
_int_map["read_request_end_vc"] = 5;
_int_map["write_request_begin_vc"] = 2;
_int_map["write_request_end_vc"] = 7;
_int_map["read_reply_begin_vc"] = 8;
_int_map["read_reply_end_vc"] = 13;
_int_map["write_reply_begin_vc"] = 10;
_int_map["write_reply_end_vc"] = 15;
// Physical sub-networks
_int_map["physical_subnetworks"] = 1;
// Control Injection of Packets into Replicated Networks
_int_map["read_request_subnet"] = 0;
_int_map["read_reply_subnet"] = 0;
_int_map["write_request_subnet"] = 0;
_int_map["write_reply_subnet"] = 0;
// TCC Simulation Traffic Trace
AddStrField( "trace_file", "trace-file.txt" ) ;
//==== Topology options =======================
//important
AddStrField( "topology", "torus" );
_int_map["k"] = 8; //network radix
_int_map["n"] = 2; //network dimension
_int_map["c"] = 1; //concentration
AddStrField( "routing_function", "none" );
_int_map["use_noc_latency"] = 1;
//not critical
_int_map["x"] = 8; //number of routers in X
_int_map["y"] = 8; //number of routers in Y
_int_map["xr"] = 1; //number of nodes per router in X only if c>1
_int_map["yr"] = 1; //number of nodes per router in Y only if c>1
_int_map["limit"] = 0; //how many of the nodes are actually used
_int_map["link_failures"] = 0; //legacy
_int_map["fail_seed"] = 0; //legacy
//==== Cmesh topology options =======================
_int_map["express_channels"] = 0; //for Cmesh only, 0=no express channels
//==== Single-node options ===============================
_int_map["in_ports"] = 5;
_int_map["out_ports"] = 5;
_int_map["voq"] = 0; //output queuing
//========================================================
// Router options
//========================================================
//==== General options ===================================
AddStrField( "router", "iq" );
_int_map["output_delay"] = 0;
_int_map["credit_delay"] = 0;
_float_map["internal_speedup"] = 1.0;
//==== Input-queued ======================================
// Control of virtual channel speculation
_int_map["speculative"] = 0 ;
// what to use to inhibit speculative allocator grants?
AddStrField("filter_spec_grants", "confl_nonspec_gnts");
_int_map["num_vcs"] = 16;
_int_map["vc_buf_size"] = 8;
_int_map["wait_for_tail_credit"] = 0; // reallocate a VC before a tail credit?
_int_map["vc_busy_when_full"] = 0; // mark VCs as in use when they have no credit available
_int_map["vc_priority_donation"] = 0; // allow high-priority flits to donate their priority to low-priority that they are queued up behind
_int_map["replies_inherit_priority"] = 0; // whenusing request-reply traffic (use_read_write=1) with age-based priority, make replies inherit their corresponding requests' age
_int_map["hold_switch_for_packet"] = 0; // hold a switch config for the entire packet
_int_map["input_speedup"] = 1; // expansion of input ports into crossbar
_int_map["output_speedup"] = 1; // expansion of output ports into crossbar
_int_map["routing_delay"] = 1;
_int_map["vc_alloc_delay"] = 1;
_int_map["sw_alloc_delay"] = 1;
_int_map["st_prepare_delay"] = 0;
_int_map["st_final_delay"] = 1;
//==== Event-driven =====================================
_int_map["vct"] = 0;
//==== Allocators ========================================
AddStrField( "vc_allocator", "islip" );
AddStrField( "sw_allocator", "islip" );
AddStrField( "vc_alloc_arb_type", "round_robin" );
AddStrField( "sw_alloc_arb_type", "round_robin" );
_int_map["alloc_iters"] = 1;
// dub: allow setting the number of iterations for each allocator separately
// (a value of 0 indicates it should inherit its value from alloc_iters)
_int_map["vc_alloc_iters"] = 0;
_int_map["sw_alloc_iters"] = 0;
//==== Traffic ========================================
AddStrField( "traffic", "uniform" );
_int_map["perm_seed"] = 0; // seed value for random permuation trafficpattern generator
_float_map["injection_rate"] = 0.1; //if 0.0 assumes it is batch mode
_int_map["injection_rate_uses_flits"] = 0;
_int_map["const_flits_per_packet"] = 1; //use read_request_size etc insted
AddStrField( "injection_process", "bernoulli" );
_float_map["burst_alpha"] = 0.5; // burst interval
_float_map["burst_beta"] = 0.5; // burst length
AddStrField( "priority", "none" ); // message priorities
_int_map["batch_size"] = 1000;
_int_map["batch_count"] = 1;
_int_map["max_outstanding_requests"] = 4;
_int_map["read_request_size"] = 1; //flit per packet
_int_map["write_request_size"] = 1; //flit per packet
_int_map["read_reply_size"] = 1; //flit per packet
_int_map["write_reply_size"] = 1; //flit per packet
//==== Simulation parameters ==========================
// types:
// latency - average + latency distribution for a particular injection rate
// throughput - sustained throughput for a particular injection rate
AddStrField( "sim_type", "latency" );
_int_map["warmup_periods"] = 3; // number of samples periods to "warm-up" the simulation
_int_map["sample_period"] = 1000; // how long between measurements
_int_map["max_samples"] = 10; // maximum number of sample periods in a simulation
_float_map["latency_thres"] = 500.0; // if avg. latency exceeds the threshold, assume unstable
_float_map["warmup_thres"] = 0.05; // consider warmed up once relative change in latency and throughput between successive iterations is smaller than this
// consider converged once relative change in latency / throughput between successive iterations is smaller than this
_float_map["stopping_thres"] = 0.05;
_float_map["acc_stopping_thres"] = 0.05;
_int_map["sim_count"] = 1; // number of simulations to perform
_int_map["include_queuing"] =1; // non-zero includes source queuing latency
// _int_map["reorder"] = 0; // know what you're doing
//_int_map["flit_timing"] = 0; // know what you're doing
//_int_map["split_packets"] = 0; // know what you're doing
_int_map["seed"] = 0; //random seed for simulation, e.g. traffic
_int_map["print_activity"] = 0;
_int_map["print_csv_results"] = 0;
_int_map["print_vc_stats"] = 0;
_int_map["drain_measured_only"] = 0;
_int_map["viewer_trace"] = 0;
AddStrField("watch_file", "");
AddStrField("watch_out", "");
AddStrField("stats_out", "");
AddStrField("flow_out", "");
//==================Power model params=====================
_int_map["sim_power"] = 0;
AddStrField("power_output_file","pwr_tmp");
AddStrField("tech_file", "../utils/temp");
_int_map["channel_width"] = 128;
_int_map["channel_sweep"] = 0;
//==================Network file===========================
AddStrField("network_file","");
}
//A list of important simulator for the booksim gui, anything else not listed here is still included
//but just not very organized
vector< pair<string, vector< string> > > *BookSimConfig::GetImportantMap(){
//Vector of 5 categories, each category is a vector of potions. Maps don't work because it autosorts
vector< pair<string, vector< string> > > *important = new vector< pair<string, vector< string> > >;
important->push_back( make_pair( "Topology", vector<string>() ));
(*important)[0].second.push_back("topology");
(*important)[0].second.push_back("k");
(*important)[0].second.push_back("n");
(*important)[0].second.push_back("c");
(*important)[0].second.push_back( "routing_function");
(*important)[0].second.push_back("use_noc_latency");
important->push_back(make_pair("Router", vector<string>()));
(*important)[1].second.push_back("router");
(*important)[1].second.push_back("num_vcs");
(*important)[1].second.push_back("vc_buf_size");
(*important)[1].second.push_back("routing_delay");
(*important)[1].second.push_back("vc_alloc_delay");
(*important)[1].second.push_back("sw_alloc_delay");
(*important)[1].second.push_back("st_prepare_delay");
(*important)[1].second.push_back("st_final_delay");
important->push_back(make_pair("Allocator", vector<string>()));
(*important)[2].second.push_back("vc_allocator");
(*important)[2].second.push_back("vc_alloc_arb_type");
(*important)[2].second.push_back("sw_allocator");
(*important)[2].second.push_back("sw_alloc_arb_type");
(*important)[2].second.push_back( "priority");
(*important)[2].second.push_back("speculative");
important->push_back(make_pair("Simulation", vector<string>()));
(*important)[3].second.push_back("traffic");
(*important)[3].second.push_back("injection_rate");
(*important)[3].second.push_back("injection_rate_uses_flits");
(*important)[3].second.push_back("sim_type");
(*important)[3].second.push_back("latency_thres");
(*important)[3].second.push_back("const_flits_per_packet");
(*important)[3].second.push_back("injection_process");
(*important)[3].second.push_back("sample_period");
important->push_back(make_pair("Statistics", vector<string>()));
(*important)[4].second.push_back("print_activity");
(*important)[4].second.push_back("print_csv_results");
(*important)[4].second.push_back("print_vc_stats");
(*important)[4].second.push_back("stats_out");
(*important)[4].second.push_back("sim_power");
(*important)[4].second.push_back("power_output_file");
return important;
}
PowerConfig::PowerConfig( )
{
_int_map["H_INVD2"] = 0;
_int_map["W_INVD2"] = 0;
_int_map["H_DFQD1"] = 0;
_int_map["W_DFQD1"] = 0;
_int_map["H_ND2D1"] = 0;
_int_map["W_ND2D1"] = 0;
_int_map["H_SRAM"] = 0;
_int_map["W_SRAM"] = 0;
_float_map["Vdd"] = 0;
_float_map["R"] = 0;
_float_map["IoffSRAM"] = 0;
_float_map["IoffP"] = 0;
_float_map["IoffN"] = 0;
_float_map["Cg_pwr"] = 0;
_float_map["Cd_pwr"] = 0;
_float_map["Cgdl"] = 0;
_float_map["Cg"] = 0;
_float_map["Cd"] = 0;
_float_map["LAMBDA"] = 0;
_float_map["MetalPitch"] = 0;
_float_map["Rw"] = 0;
_float_map["Cw_gnd"] = 0;
_float_map["Cw_cpl"] = 0;
_float_map["wire_length"] = 0;
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Fangfang Bai, [email protected]
// Jin Ma, [email protected]
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "../perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"
#ifdef HAVE_OPENCL
namespace opencv_test {
namespace ocl {
typedef tuple<Size, MatType, int> FilterParams;
typedef TestBaseWithParam<FilterParams> FilterFixture;
///////////// Blur ////////////////////////
typedef FilterFixture BlurFixture;
OCL_PERF_TEST_P(BlurFixture, Blur,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params), bordertype = BORDER_CONSTANT;
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::blur(src, dst, Size(ksize, ksize), Point(-1, -1), bordertype);
SANITY_CHECK(dst, eps);
}
///////////// SqrBoxFilter ////////////////////////
typedef tuple<Size, MatType, Size> SqrBoxFilterParams;
typedef TestBaseWithParam<SqrBoxFilterParams> SqrBoxFilterFixture;
OCL_PERF_TEST_P(SqrBoxFilterFixture, SqrBoxFilter,
::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4),
OCL_PERF_ENUM(Size(3, 3), Size(20, 3), Size(3, 20), Size(20, 20))))
{
const SqrBoxFilterParams params = GetParam();
const Size srcSize = get<0>(params), ksize = get<2>(params);
const int type = get<1>(params), depth = CV_MAT_DEPTH(type),
ddepth = depth == CV_8U ? CV_32S : CV_32F;
const double eps = ddepth == CV_32S ? 0 : 5e-5;
checkDeviceMaxMemoryAllocSize(srcSize, CV_MAKE_TYPE(ddepth, CV_MAT_CN(type)));
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::sqrBoxFilter(src, dst, ddepth, ksize, Point(-1, -1), false);
SANITY_CHECK(dst, eps);
}
///////////// Laplacian////////////////////////
typedef FilterFixture LaplacianFixture;
OCL_PERF_TEST_P(LaplacianFixture, Laplacian,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 2e-5;
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize, 1);
SANITY_CHECK(dst, eps);
}
///////////// Erode ////////////////////
typedef FilterFixture ErodeFixture;
OCL_PERF_TEST_P(ErodeFixture, Erode,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst).in(ker);
OCL_TEST_CYCLE() cv::erode(src, dst, ker);
SANITY_CHECK(dst);
}
///////////// Dilate ////////////////////
typedef FilterFixture DilateFixture;
OCL_PERF_TEST_P(DilateFixture, Dilate,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst).in(ker);
OCL_TEST_CYCLE() cv::dilate(src, dst, ker);
SANITY_CHECK(dst);
}
///////////// MorphologyEx ////////////////////////
CV_ENUM(MorphOp, MORPH_OPEN, MORPH_CLOSE, MORPH_GRADIENT, MORPH_TOPHAT, MORPH_BLACKHAT)
typedef tuple<Size, MatType, MorphOp, int> MorphologyExParams;
typedef TestBaseWithParam<MorphologyExParams> MorphologyExFixture;
OCL_PERF_TEST_P(MorphologyExFixture, MorphologyEx,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, MorphOp::all(), OCL_PERF_ENUM(3, 5)))
{
const MorphologyExParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), op = get<2>(params), ksize = get<3>(params);
const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst).in(ker);
OCL_TEST_CYCLE() cv::morphologyEx(src, dst, op, ker);
SANITY_CHECK(dst);
}
///////////// Sobel ////////////////////////
typedef Size_MatType SobelFixture;
OCL_PERF_TEST_P(SobelFixture, Sobel,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), dx = 1, dy = 1;
checkDeviceMaxMemoryAllocSize(srcSize, type, sizeof(float) * 2);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::Sobel(src, dst, -1, dx, dy);
SANITY_CHECK(dst, 1e-6);
}
///////////// Scharr ////////////////////////
typedef Size_MatType ScharrFixture;
OCL_PERF_TEST_P(ScharrFixture, Scharr,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), dx = 1, dy = 0;
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;
checkDeviceMaxMemoryAllocSize(srcSize, type, sizeof(float) * 2);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::Scharr(src, dst, -1, dx, dy);
SANITY_CHECK(dst, eps);
}
///////////// GaussianBlur ////////////////////////
typedef FilterFixture GaussianBlurFixture;
OCL_PERF_TEST_P(GaussianBlurFixture, GaussianBlur,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5, 7)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 2 + DBL_EPSILON : 3e-4;
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::GaussianBlur(src, dst, Size(ksize, ksize), 1, 1, cv::BORDER_CONSTANT);
SANITY_CHECK(dst, eps);
}
///////////// Filter2D ////////////////////////
typedef FilterFixture Filter2DFixture;
OCL_PERF_TEST_P(Filter2DFixture, Filter2D,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
Mat kernel(ksize, ksize, CV_32SC1);
declare.in(src, WARMUP_RNG).in(kernel).out(dst);
randu(kernel, -3.0, 3.0);
OCL_TEST_CYCLE() cv::filter2D(src, dst, -1, kernel);
SANITY_CHECK(dst, eps);
}
///////////// Bilateral ////////////////////////
typedef TestBaseWithParam<Size> BilateralFixture;
OCL_PERF_TEST_P(BilateralFixture, Bilateral, OCL_TEST_SIZES)
{
const Size srcSize = GetParam();
const int d = 7;
const double sigmacolor = 50.0, sigmaspace = 50.0;
checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);
UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::bilateralFilter(src, dst, d, sigmacolor, sigmaspace);
SANITY_CHECK(dst);
}
///////////// MedianBlur ////////////////////////
typedef tuple<Size, int> MedianBlurParams;
typedef TestBaseWithParam<MedianBlurParams> MedianBlurFixture;
OCL_PERF_TEST_P(MedianBlurFixture, Bilateral, ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(3, 5)))
{
MedianBlurParams params = GetParam();
const Size srcSize = get<0>(params);
const int ksize = get<1>(params);
checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);
UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::medianBlur(src, dst, ksize);
SANITY_CHECK(dst);
}
} } // namespace opencv_test::ocl
#endif // HAVE_OPENCL
<commit_msg>imgproc(perf): add GaussianBlur cases for SIFT<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Fangfang Bai, [email protected]
// Jin Ma, [email protected]
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "../perf_precomp.hpp"
#include "opencv2/ts/ocl_perf.hpp"
#ifdef HAVE_OPENCL
namespace opencv_test {
namespace ocl {
typedef tuple<Size, MatType, int> FilterParams;
typedef TestBaseWithParam<FilterParams> FilterFixture;
///////////// Blur ////////////////////////
typedef FilterFixture BlurFixture;
OCL_PERF_TEST_P(BlurFixture, Blur,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params), bordertype = BORDER_CONSTANT;
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::blur(src, dst, Size(ksize, ksize), Point(-1, -1), bordertype);
SANITY_CHECK(dst, eps);
}
///////////// SqrBoxFilter ////////////////////////
typedef tuple<Size, MatType, Size> SqrBoxFilterParams;
typedef TestBaseWithParam<SqrBoxFilterParams> SqrBoxFilterFixture;
OCL_PERF_TEST_P(SqrBoxFilterFixture, SqrBoxFilter,
::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(CV_8UC1, CV_8UC4, CV_32FC1, CV_32FC4),
OCL_PERF_ENUM(Size(3, 3), Size(20, 3), Size(3, 20), Size(20, 20))))
{
const SqrBoxFilterParams params = GetParam();
const Size srcSize = get<0>(params), ksize = get<2>(params);
const int type = get<1>(params), depth = CV_MAT_DEPTH(type),
ddepth = depth == CV_8U ? CV_32S : CV_32F;
const double eps = ddepth == CV_32S ? 0 : 5e-5;
checkDeviceMaxMemoryAllocSize(srcSize, CV_MAKE_TYPE(ddepth, CV_MAT_CN(type)));
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::sqrBoxFilter(src, dst, ddepth, ksize, Point(-1, -1), false);
SANITY_CHECK(dst, eps);
}
///////////// Laplacian////////////////////////
typedef FilterFixture LaplacianFixture;
OCL_PERF_TEST_P(LaplacianFixture, Laplacian,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 2e-5;
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::Laplacian(src, dst, -1, ksize, 1);
SANITY_CHECK(dst, eps);
}
///////////// Erode ////////////////////
typedef FilterFixture ErodeFixture;
OCL_PERF_TEST_P(ErodeFixture, Erode,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst).in(ker);
OCL_TEST_CYCLE() cv::erode(src, dst, ker);
SANITY_CHECK(dst);
}
///////////// Dilate ////////////////////
typedef FilterFixture DilateFixture;
OCL_PERF_TEST_P(DilateFixture, Dilate,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst).in(ker);
OCL_TEST_CYCLE() cv::dilate(src, dst, ker);
SANITY_CHECK(dst);
}
///////////// MorphologyEx ////////////////////////
CV_ENUM(MorphOp, MORPH_OPEN, MORPH_CLOSE, MORPH_GRADIENT, MORPH_TOPHAT, MORPH_BLACKHAT)
typedef tuple<Size, MatType, MorphOp, int> MorphologyExParams;
typedef TestBaseWithParam<MorphologyExParams> MorphologyExFixture;
OCL_PERF_TEST_P(MorphologyExFixture, MorphologyEx,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, MorphOp::all(), OCL_PERF_ENUM(3, 5)))
{
const MorphologyExParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), op = get<2>(params), ksize = get<3>(params);
const Mat ker = getStructuringElement(MORPH_RECT, Size(ksize, ksize));
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst).in(ker);
OCL_TEST_CYCLE() cv::morphologyEx(src, dst, op, ker);
SANITY_CHECK(dst);
}
///////////// Sobel ////////////////////////
typedef Size_MatType SobelFixture;
OCL_PERF_TEST_P(SobelFixture, Sobel,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), dx = 1, dy = 1;
checkDeviceMaxMemoryAllocSize(srcSize, type, sizeof(float) * 2);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::Sobel(src, dst, -1, dx, dy);
SANITY_CHECK(dst, 1e-6);
}
///////////// Scharr ////////////////////////
typedef Size_MatType ScharrFixture;
OCL_PERF_TEST_P(ScharrFixture, Scharr,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES))
{
const Size_MatType_t params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), dx = 1, dy = 0;
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;
checkDeviceMaxMemoryAllocSize(srcSize, type, sizeof(float) * 2);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::Scharr(src, dst, -1, dx, dy);
SANITY_CHECK(dst, eps);
}
///////////// GaussianBlur ////////////////////////
typedef FilterFixture OCL_GaussianBlurFixture;
PERF_TEST_P_(OCL_GaussianBlurFixture, GaussianBlur)
{
const FilterParams& params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::GaussianBlur(src, dst, Size(ksize, ksize), 1, 1, cv::BORDER_CONSTANT);
SANITY_CHECK_NOTHING();
}
INSTANTIATE_TEST_CASE_P(/*nothing*/, OCL_GaussianBlurFixture,
::testing::Combine(
OCL_TEST_SIZES,
OCL_TEST_TYPES,
OCL_PERF_ENUM(3, 5, 7)
)
);
INSTANTIATE_TEST_CASE_P(SIFT, OCL_GaussianBlurFixture,
::testing::Combine(
::testing::Values(sz1080p),
::testing::Values(CV_32FC1),
OCL_PERF_ENUM(11, 13, 17, 21, 27)
)
);
INSTANTIATE_TEST_CASE_P(DISABLED_FULL, OCL_GaussianBlurFixture,
::testing::Combine(
::testing::Values(sz1080p),
::testing::Values(
CV_8UC1, CV_8UC2, CV_8UC3, CV_8UC4,
CV_8SC1, CV_8SC2, CV_8SC3, CV_8SC4,
CV_16UC1, CV_16UC2, CV_16UC3, CV_16UC4,
CV_16SC1, CV_16SC2, CV_16SC3, CV_16SC4,
CV_32SC1, CV_32SC2, CV_32SC3, CV_32SC4,
CV_32FC1, CV_32FC2, CV_32FC3, CV_32FC4,
CV_64FC1, CV_64FC2, CV_64FC3, CV_64FC4
),
OCL_PERF_ENUM(3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29)
)
);
///////////// Filter2D ////////////////////////
typedef FilterFixture Filter2DFixture;
OCL_PERF_TEST_P(Filter2DFixture, Filter2D,
::testing::Combine(OCL_TEST_SIZES, OCL_TEST_TYPES, OCL_PERF_ENUM(3, 5)))
{
const FilterParams params = GetParam();
const Size srcSize = get<0>(params);
const int type = get<1>(params), ksize = get<2>(params);
const double eps = CV_MAT_DEPTH(type) <= CV_32S ? 1 : 1e-5;
checkDeviceMaxMemoryAllocSize(srcSize, type);
UMat src(srcSize, type), dst(srcSize, type);
Mat kernel(ksize, ksize, CV_32SC1);
declare.in(src, WARMUP_RNG).in(kernel).out(dst);
randu(kernel, -3.0, 3.0);
OCL_TEST_CYCLE() cv::filter2D(src, dst, -1, kernel);
SANITY_CHECK(dst, eps);
}
///////////// Bilateral ////////////////////////
typedef TestBaseWithParam<Size> BilateralFixture;
OCL_PERF_TEST_P(BilateralFixture, Bilateral, OCL_TEST_SIZES)
{
const Size srcSize = GetParam();
const int d = 7;
const double sigmacolor = 50.0, sigmaspace = 50.0;
checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);
UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::bilateralFilter(src, dst, d, sigmacolor, sigmaspace);
SANITY_CHECK(dst);
}
///////////// MedianBlur ////////////////////////
typedef tuple<Size, int> MedianBlurParams;
typedef TestBaseWithParam<MedianBlurParams> MedianBlurFixture;
OCL_PERF_TEST_P(MedianBlurFixture, Bilateral, ::testing::Combine(OCL_TEST_SIZES, OCL_PERF_ENUM(3, 5)))
{
MedianBlurParams params = GetParam();
const Size srcSize = get<0>(params);
const int ksize = get<1>(params);
checkDeviceMaxMemoryAllocSize(srcSize, CV_8UC1);
UMat src(srcSize, CV_8UC1), dst(srcSize, CV_8UC1);
declare.in(src, WARMUP_RNG).out(dst);
OCL_TEST_CYCLE() cv::medianBlur(src, dst, ksize);
SANITY_CHECK(dst);
}
} } // namespace opencv_test::ocl
#endif // HAVE_OPENCL
<|endoftext|> |
<commit_before>#include <stdexcept>
#include <memory>
#include <functional>
#include <algorithm>
namespace crashes {
typedef std::function<void (int)> on_feedback;
namespace detail {
//////////////////////////////////////////////
typedef std::shared_ptr<size_t> shared_number;
////////////////////
class simple_count {
size_t copy_nr;
public:
simple_count():copy_nr(0){}
size_t get_copy_nr() const {
return copy_nr;
}
void increment() {
++copy_nr;
}
bool should_have_crashed_on(size_t) {
return false;
}
};
////////////////////////////////////////////
template <typename TSharedInt=shared_number>
class shared_count {
TSharedInt copy_nr;
public:
shared_count():copy_nr(new size_t(0)){}
size_t get_copy_nr() const {
return *copy_nr;
}
void increment() {
++(*copy_nr);
}
bool should_have_crashed_on(size_t) {
return false;
}
};
////////////////////////////////////////
struct should_decrement_on_destruction {
static const bool should_decrement=true;
};
//////////////////////////////////////////
struct shouldnt_decrement_on_destruction {
static const bool should_decrement=false;
};
/////////////////////
template <typename T,typename TDecrement>
class total_count
{
static size_t count_nr;
public:
total_count()
{
increment();
}
size_t get_copy_nr() const {
return count_nr;
}
void increment() {
++count_nr;
}
bool should_have_crashed_on(size_t N) {
return count_nr>=N;
}
//protected:
~total_count()
{
if (TDecrement::should_decrement)
--count_nr;
}
};
template <typename T,typename TDecrement> size_t total_count<T,TDecrement>::count_nr(0);
////////////////////////////////////////////////////////////////////////////////////////////////////
template <size_t MaxN,typename TFeedback=on_feedback, typename TCounter=simple_count>
struct when {
class copies {
TCounter counter;
TFeedback feedback;
public:
copies() {
if (counter.should_have_crashed_on(MaxN))
throw std::runtime_error("illegal number of copies");
}
virtual ~copies() {} //todo: review
copies(const copies& other):
counter(other.counter),
feedback(other.feedback)
{
counter.increment();
size_t count=counter.get_copy_nr();
if (feedback)
feedback(count);
if (count>=MaxN)
throw std::runtime_error("illegal number of copies");
}
copies& operator=(copies const& other) {
copies tmp(other);
swap(other);
return *this;
}
void swap(copies const& other) {
std::swap(counter,other.counter);
std::swap(feedback,other.feedback);
}
public:
void set_feedback(TFeedback const& f) {
feedback=f;
}
};
typedef copies copy;
};
}
/// crashes on MaxN total number of copies
template <size_t MaxN>
struct on : public detail::when<MaxN,on_feedback,detail::shared_count<detail::shared_number>>
{};
/// crashes on MaxN'th copy
template <size_t MaxN>
struct after : public detail::when<MaxN,on_feedback,detail::simple_count>
{};
/// crashes on MaxN total instances of T
template <size_t MaxN,typename T>
struct on_total : public detail::when<MaxN,on_feedback,detail::total_count<T,detail::should_decrement_on_destruction>>
{
// instead typedef copies instance - for gcc/standard complience
typedef typename crashes::detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::should_decrement_on_destruction> >::copies instances;
typedef typename crashes::detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::should_decrement_on_destruction> >::copies instance;
};
/// crashes on MaxN total instances of T
template <size_t MaxN,typename T>
struct after_total : public detail::when<MaxN,on_feedback,detail::total_count<T,detail::shouldnt_decrement_on_destruction>>
{
typedef typename crashes::detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::shouldnt_decrement_on_destruction> >::copies instances;
typedef typename crashes::detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::shouldnt_decrement_on_destruction> >::copies instance;
};
}<commit_msg>slightly shorter<commit_after>#include <stdexcept>
#include <memory>
#include <functional>
#include <algorithm>
namespace crashes {
typedef std::function<void (int)> on_feedback;
namespace detail {
//////////////////////////////////////////////
typedef std::shared_ptr<size_t> shared_number;
////////////////////
class simple_count {
size_t copy_nr;
public:
simple_count():copy_nr(0){}
size_t get_copy_nr() const {
return copy_nr;
}
void increment() {
++copy_nr;
}
bool should_have_crashed_on(size_t) {
return false;
}
};
////////////////////////////////////////////
template <typename TSharedInt=shared_number>
class shared_count {
TSharedInt copy_nr;
public:
shared_count():copy_nr(new size_t(0)){}
size_t get_copy_nr() const {
return *copy_nr;
}
void increment() {
++(*copy_nr);
}
bool should_have_crashed_on(size_t) {
return false;
}
};
////////////////////////////////////////
struct should_decrement_on_destruction {
static const bool should_decrement=true;
};
//////////////////////////////////////////
struct shouldnt_decrement_on_destruction {
static const bool should_decrement=false;
};
/////////////////////
template <typename T,typename TDecrement>
class total_count
{
static size_t count_nr;
public:
total_count()
{
increment();
}
size_t get_copy_nr() const {
return count_nr;
}
void increment() {
++count_nr;
}
bool should_have_crashed_on(size_t N) {
return count_nr>=N;
}
//protected:
~total_count()
{
if (TDecrement::should_decrement)
--count_nr;
}
};
template <typename T,typename TDecrement> size_t total_count<T,TDecrement>::count_nr(0);
////////////////////////////////////////////////////////////////////////////////////////////////////
template <size_t MaxN,typename TFeedback=on_feedback, typename TCounter=simple_count>
struct when {
class copies {
TCounter counter;
TFeedback feedback;
public:
copies() {
if (counter.should_have_crashed_on(MaxN))
throw std::runtime_error("illegal number of copies");
}
virtual ~copies() {} //todo: review
copies(const copies& other):
counter(other.counter),
feedback(other.feedback)
{
counter.increment();
size_t count=counter.get_copy_nr();
if (feedback)
feedback(count);
if (count>=MaxN)
throw std::runtime_error("illegal number of copies");
}
copies& operator=(copies const& other) {
copies tmp(other);
swap(other);
return *this;
}
void swap(copies const& other) {
std::swap(counter,other.counter);
std::swap(feedback,other.feedback);
}
public:
void set_feedback(TFeedback const& f) {
feedback=f;
}
};
typedef copies copy;
};
}
/// crashes on MaxN total number of copies
template <size_t MaxN>
struct on : public detail::when<MaxN,on_feedback,detail::shared_count<detail::shared_number>>
{};
/// crashes on MaxN'th copy
template <size_t MaxN>
struct after : public detail::when<MaxN,on_feedback,detail::simple_count>
{};
/// crashes on MaxN total instances of T
template <size_t MaxN,typename T>
struct on_total : public detail::when<MaxN,on_feedback,detail::total_count<T,detail::should_decrement_on_destruction>>
{
// instead typedef copies instance - for gcc/standard complience
typedef typename detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::should_decrement_on_destruction> >::copies instances;
typedef typename detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::should_decrement_on_destruction> >::copies instance;
};
/// crashes on MaxN total instances of T
template <size_t MaxN,typename T>
struct after_total : public detail::when<MaxN,on_feedback,detail::total_count<T,detail::shouldnt_decrement_on_destruction>>
{
typedef typename detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::shouldnt_decrement_on_destruction> >::copies instances;
typedef typename detail::when<MaxN, std::function<void(int)>, crashes::detail::total_count<T, crashes::detail::shouldnt_decrement_on_destruction> >::copies instance;
};
}<|endoftext|> |
<commit_before>// Time: O(logn)
// Space: O(logn)
class Solution {
public:
int findKthNumber(int n, int k) {
int result = 0;
vector<int> cnts(10);
for (int i = 1; i < 10; i++) {
cnts[i] = cnts[i - 1] * 10 + 1;
}
vector<int> nums;
for (int i = n; i > 0; i /= 10) {
nums.push_back(i % 10);
}
int total = n;
int target = 0;
for (int i = nums.size() - 1; i >= 0 && k; --i) {
target = target * 10 + nums[i];
const auto start = i == nums.size() - 1 ? 1 : 0;
for (int j = start; j < 10; ++j) {
int candidate = result * 10 + j;
int num;
if (candidate < target) {
num = cnts[i + 1];
} else if (candidate > target) {
num = cnts[i];
} else {
num = total - cnts[i + 1] * (j - start) - cnts[i] * (9 - j);
}
if (k > num) {
k -= num;
} else {
result = candidate;
--k;
total = num - 1;
break;
}
}
}
return result;
}
};
// Time: O(logn * logn)
// Space: O(logn)
class Solution2 {
public:
int findKthNumber(int n, int k) {
int result = 0;
int index = 0;
findKthNumberHelper(n, k, 0, &index, &result);
return result;
}
private:
bool findKthNumberHelper(int n, int k, int cur, int *index, int *result) {
if (cur) {
++(*index);
if (*index == k) {
*result = cur;
return true;
}
}
for (int i = (cur == 0 ? 1 : 0); i <= 9; ++i, cur /= 10) {
cur = cur * 10 + i;
int cnt = count(n, cur);
if (k > cnt + *index) {
*index += cnt;
continue;
}
if (cur <= n && findKthNumberHelper(n, k, cur, index, result)) {
return true;
}
}
return false;
}
int count(int n, long long prefix) { // Time: O(logn)
int result = 0;
int number = 1;
while (prefix <= n) {
result += number;
prefix *= 10;
number *= 10;
}
result -= max(number / 10 - (n - prefix / 10 + 1), static_cast<long long>(0));
return result;
}
};
<commit_msg>Update k-th-smallest-in-lexicographical-order.cpp<commit_after>// Time: O(logn)
// Space: O(logn)
class Solution {
public:
int findKthNumber(int n, int k) {
int result = 0;
vector<int> cnts(10);
for (int i = 1; i <= 9; ++i) {
cnts[i] = cnts[i - 1] * 10 + 1;
}
vector<int> nums;
for (int i = n; i > 0; i /= 10) {
nums.push_back(i % 10);
}
int total = n;
int target = 0;
for (int i = nums.size() - 1; i >= 0 && k; --i) {
target = target * 10 + nums[i];
const auto start = i == nums.size() - 1 ? 1 : 0;
for (int j = start; j <= 9; ++j) {
int candidate = result * 10 + j;
int num;
if (candidate < target) {
num = cnts[i + 1];
} else if (candidate > target) {
num = cnts[i];
} else {
num = total - cnts[i + 1] * (j - start) - cnts[i] * (9 - j);
}
if (k > num) {
k -= num;
} else {
result = candidate;
--k;
total = num - 1;
break;
}
}
}
return result;
}
};
// Time: O(logn * logn)
// Space: O(logn)
class Solution2 {
public:
int findKthNumber(int n, int k) {
int result = 0;
int index = 0;
findKthNumberHelper(n, k, 0, &index, &result);
return result;
}
private:
bool findKthNumberHelper(int n, int k, int cur, int *index, int *result) {
if (cur) {
++(*index);
if (*index == k) {
*result = cur;
return true;
}
}
for (int i = (cur == 0 ? 1 : 0); i <= 9; ++i, cur /= 10) {
cur = cur * 10 + i;
int cnt = count(n, cur);
if (k > cnt + *index) {
*index += cnt;
continue;
}
if (cur <= n && findKthNumberHelper(n, k, cur, index, result)) {
return true;
}
}
return false;
}
int count(int n, long long prefix) { // Time: O(logn)
int result = 0;
int number = 1;
while (prefix <= n) {
result += number;
prefix *= 10;
number *= 10;
}
result -= max(number / 10 - (n - prefix / 10 + 1), static_cast<long long>(0));
return result;
}
};
<|endoftext|> |
<commit_before>// RUN: %clang %s -S -emit-llvm -o - | grep -e "define linkonce_odr.*_ZlsR11std_ostreamRK8StreamerI3FooE"
// PR8007: friend function not instantiated.
struct std_ostream
{
int dummy;
};
std_ostream cout;
template <typename STRUCT_TYPE>
struct Streamer
{
friend std_ostream& operator << (std_ostream& o, const Streamer& f)
{
Streamer s(f);
s(o);
return o;
}
Streamer(const STRUCT_TYPE& s) : s(s) {}
const STRUCT_TYPE& s;
void operator () (std_ostream&) const;
};
typedef struct Foo {} Foo;
std_ostream& operator << (std_ostream& o, const Streamer<Foo>& f);
/*std_ostream& operator << (std_ostream& o, const Streamer<Foo>& f)
{
// Sema should flag this as a redefinition
}*/
template <>
void Streamer<Foo>::operator () (std_ostream& o) const
{
}
int main(void)
{
Foo foo;
cout << foo;
}
<commit_msg>check whether sema issues a redefinition error<commit_after>// RUN: %clang %s -S -emit-llvm -o - | grep -e "define linkonce_odr.*_ZlsR11std_ostreamRK8StreamerI3FooE"
// RUN: %clang -cc1 %s -DREDEFINE -verify
// PR8007: friend function not instantiated.
struct std_ostream
{
int dummy;
};
std_ostream cout;
template <typename STRUCT_TYPE>
struct Streamer
{
friend std_ostream& operator << (std_ostream& o, const Streamer& f) // expected-error{{redefinition of 'operator<<'}}
{
Streamer s(f);
s(o);
return o;
}
Streamer(const STRUCT_TYPE& s) : s(s) {}
const STRUCT_TYPE& s;
void operator () (std_ostream&) const;
};
typedef struct Foo {} Foo;
std_ostream& operator << (std_ostream&, const Streamer<Foo>&);
#ifdef REDEFINE
std_ostream& operator << (std_ostream& o, const Streamer<Foo>&) // expected-note{{is here}}
{
// Sema should flag this as a redefinition
return o;
}
#endif
template <>
void Streamer<Foo>::operator () (std_ostream& o) const // expected-note{{requested here}}
{
}
int main(void)
{
Foo foo;
cout << foo;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013, Ford Motor Company
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 Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/mobile/slider_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "utils/helpers.h"
namespace application_manager {
namespace commands {
SliderRequest::SliderRequest(const MessageSharedPtr& message)
: CommandRequestImpl(message) {
subscribe_on_event(hmi_apis::FunctionID::UI_OnResetTimeout);
}
SliderRequest::~SliderRequest() {
}
bool SliderRequest::Init() {
/* Timeout in milliseconds.
If omitted a standard value of 10000 milliseconds is used.*/
if ((*message_)[strings::msg_params].keyExists(strings::timeout)) {
default_timeout_ =
(*message_)[strings::msg_params][strings::timeout].asUInt();
}
return true;
}
void SliderRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
application_manager::ApplicationManagerImpl::instance()->application(
(*message_)[strings::params][strings::connection_key].asUInt());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
if ((*message_)[strings::msg_params][strings::num_ticks].asInt()
< (*message_)[strings::msg_params][strings::position].asInt()) {
LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
if (1 < (*message_)[strings::msg_params][strings::slider_footer].length()) {
if ((*message_)[strings::msg_params][strings::num_ticks].asUInt()
!= (*message_)[strings::msg_params]
[strings::slider_footer].length()) {
LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
}
}
if (IsWhiteSpaceExist()) {
LOG4CXX_ERROR(logger_, "Incoming slider has contains \t\n \\t \\n");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
smart_objects::SmartObject msg_params = smart_objects::SmartObject(
smart_objects::SmartType_Map);
msg_params = (*message_)[strings::msg_params];
msg_params[strings::app_id] = application->app_id();
if (!(*message_)[strings::msg_params].keyExists(strings::timeout)) {
msg_params[strings::timeout] = default_timeout_;
}
SendHMIRequest(hmi_apis::FunctionID::UI_Slider, &msg_params, true);
}
void SliderRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
const event_engine::Event::EventID event_id = event.id();
if (event_id == hmi_apis::FunctionID::UI_OnResetTimeout) {
LOG4CXX_INFO(logger_, "Received UI_OnResetTimeout event");
ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
correlation_id(),
default_timeout());
return;
}
if (event_id != hmi_apis::FunctionID::UI_Slider) {
LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
LOG4CXX_INFO(logger_, "Received UI_Slider event");
const hmi_apis::Common_Result::eType response_code =
static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
smart_objects::SmartObject response_msg_params = message[strings::msg_params];
if (response_code == hmi_apis::Common_Result::ABORTED &&
response_msg_params[strings::data].keyExists(strings::slider_position)) {
//Copy slider_position info to msg_params section
response_msg_params[strings::slider_position] =
message[strings::params][strings::data][strings::slider_position];
}
const bool is_response_success =
Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
response_code,
hmi_apis::Common_Result::SUCCESS,
hmi_apis::Common_Result::WARNINGS);
SendResponse(is_response_success,
MessageHelper::HMIToMobileResult(response_code),
0,
&response_msg_params);
}
bool SliderRequest::IsWhiteSpaceExist() {
LOG4CXX_AUTO_TRACE(logger_);
const char* str = NULL;
str = (*message_)[strings::msg_params][strings::slider_header].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid slider_header value syntax check failed");
return true;
}
if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
const smart_objects::SmartArray* sf_array =
(*message_)[strings::msg_params][strings::slider_footer].asArray();
smart_objects::SmartArray::const_iterator it_sf = sf_array->begin();
smart_objects::SmartArray::const_iterator it_sf_end = sf_array->end();
for (; it_sf != it_sf_end; ++it_sf) {
str = (*it_sf).asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid slider_footer syntax check failed");
return true;
}
}
}
return false;
}
} // namespace commands
} // namespace application_manager
<commit_msg>Implements sending 'sliderPosition' to app on respose TIMED_OUT<commit_after>/*
Copyright (c) 2013, Ford Motor Company
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 Ford Motor Company nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/mobile/slider_request.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "utils/helpers.h"
namespace application_manager {
namespace commands {
SliderRequest::SliderRequest(const MessageSharedPtr& message)
: CommandRequestImpl(message) {
subscribe_on_event(hmi_apis::FunctionID::UI_OnResetTimeout);
}
SliderRequest::~SliderRequest() {
}
bool SliderRequest::Init() {
/* Timeout in milliseconds.
If omitted a standard value of 10000 milliseconds is used.*/
if ((*message_)[strings::msg_params].keyExists(strings::timeout)) {
default_timeout_ =
(*message_)[strings::msg_params][strings::timeout].asUInt();
}
return true;
}
void SliderRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
application_manager::ApplicationManagerImpl::instance()->application(
(*message_)[strings::params][strings::connection_key].asUInt());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
if ((*message_)[strings::msg_params][strings::num_ticks].asInt() <
(*message_)[strings::msg_params][strings::position].asInt()) {
LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
if (1 < (*message_)[strings::msg_params][strings::slider_footer].length()) {
if ((*message_)[strings::msg_params][strings::num_ticks].asUInt()
!= (*message_)[strings::msg_params]
[strings::slider_footer].length()) {
LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
}
}
if (IsWhiteSpaceExist()) {
LOG4CXX_ERROR(logger_, "Incoming slider has contains \t\n \\t \\n");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
smart_objects::SmartObject msg_params = smart_objects::SmartObject(
smart_objects::SmartType_Map);
msg_params = (*message_)[strings::msg_params];
msg_params[strings::app_id] = application->app_id();
if (!(*message_)[strings::msg_params].keyExists(strings::timeout)) {
msg_params[strings::timeout] = default_timeout_;
}
SendHMIRequest(hmi_apis::FunctionID::UI_Slider, &msg_params, true);
}
void SliderRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace helpers;
using namespace smart_objects;
using namespace hmi_apis;
const SmartObject& message = event.smart_object();
const event_engine::Event::EventID event_id = event.id();
if (event_id == FunctionID::UI_OnResetTimeout) {
LOG4CXX_INFO(logger_, "Received UI_OnResetTimeout event");
ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
correlation_id(),
default_timeout());
return;
}
if (event_id != FunctionID::UI_Slider) {
LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
LOG4CXX_DEBUG(logger_, "Received UI_Slider event");
const Common_Result::eType response_code = static_cast<Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
SmartObject response_msg_params = message[strings::msg_params];
const bool is_timeout_aborted =
Compare<Common_Result::eType, EQ, ONE>(
response_code,
Common_Result::TIMED_OUT,
Common_Result::ABORTED);
if (is_timeout_aborted) {
if (message[strings::params][strings::data]
.keyExists(strings::slider_position)) {
//Copy slider_position info to msg_params section
response_msg_params[strings::slider_position] =
message[strings::params][strings::data][strings::slider_position];
} else {
LOG4CXX_ERROR(logger_, strings::slider_position << " field is absent"
" in response.");
response_msg_params[strings::slider_position] = 0;
}
}
const bool is_response_success =
Compare<Common_Result::eType, EQ, ONE>(
response_code,
Common_Result::SUCCESS,
Common_Result::WARNINGS);
SendResponse(is_response_success,
MessageHelper::HMIToMobileResult(response_code),
0,
&response_msg_params);
}
bool SliderRequest::IsWhiteSpaceExist() {
LOG4CXX_AUTO_TRACE(logger_);
const char* str = NULL;
str = (*message_)[strings::msg_params][strings::slider_header].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid slider_header value syntax check failed");
return true;
}
if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
const smart_objects::SmartArray* sf_array =
(*message_)[strings::msg_params][strings::slider_footer].asArray();
smart_objects::SmartArray::const_iterator it_sf = sf_array->begin();
smart_objects::SmartArray::const_iterator it_sf_end = sf_array->end();
for (; it_sf != it_sf_end; ++it_sf) {
str = (*it_sf).asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid slider_footer syntax check failed");
return true;
}
}
}
return false;
}
} // namespace commands
} // namespace application_manager
<|endoftext|> |
<commit_before>// renderable_sprite.t.cpp
#include <engine/rendering/renderable_sprite.h>
#include <engine/rendering/renderer.h>
#include <gtest/gtest.h>
TEST( RenderableSpriteTest, Construction )
{
using namespace StevensDev::sgdr;
RenderableSprite blank;
RenderableSprite copy( blank );
Renderer renderer;
// can't continue if can't find the texture
ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/block.png" ) );
RenderableSprite texture( renderer.getTexture( "test" ) );
RenderableSprite sprite( sf::Sprite( renderer.getTexture( "test" ) ) );
texture = sprite;
}
TEST( RenderableSpriteTest, Position )
{
using namespace StevensDev::sgdr;
Renderer renderer;
// can't continue if can't find the texture
ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/block.png" ) );
RenderableSprite sprite( renderer.getTexture( "test" ) );
sprite.setPosition( 25.0f, 25.0f );
EXPECT_EQ( 25.0f, sprite.getPositionX() );
EXPECT_EQ( 25.0f, sprite.getPositionY() );
sprite.move( -25.0f, -25.0f );
EXPECT_EQ( 0.0f, sprite.getPositionX() );
EXPECT_EQ( 0.0f, sprite.getPositionY() );
}
TEST( RenderableSpriteTest, Print )
{
using namespace StevensDev::sgdr;
Renderer renderer;
// can't continue if can't find the texture
ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/block.png" ) );
RenderableSprite sprite( renderer.getTexture( "test" ) );
sprite.setPosition( 0.0f, 0.0f );
std::ostringstream oss;
oss << sprite;
EXPECT_STREQ( "{ \"x\": 0.0, \"y\": 0.0 }", oss.str().c_str() );
}<commit_msg>Correct resource paths.<commit_after>// renderable_sprite.t.cpp
#include <engine/rendering/renderable_sprite.h>
#include <engine/rendering/renderer.h>
#include <gtest/gtest.h>
TEST( RenderableSpriteTest, Construction )
{
using namespace StevensDev::sgdr;
RenderableSprite blank;
RenderableSprite copy( blank );
Renderer renderer;
// can't continue if can't find the texture
ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/actor/block/block.png" ) );
RenderableSprite texture( renderer.getTexture( "test" ) );
RenderableSprite sprite( sf::Sprite( renderer.getTexture( "test" ) ) );
texture = sprite;
}
TEST( RenderableSpriteTest, Position )
{
using namespace StevensDev::sgdr;
Renderer renderer;
// can't continue if can't find the texture
ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/actor/block/block.png" ) );
RenderableSprite sprite( renderer.getTexture( "test" ) );
sprite.setPosition( 25.0f, 25.0f );
EXPECT_EQ( 25.0f, sprite.getPositionX() );
EXPECT_EQ( 25.0f, sprite.getPositionY() );
sprite.move( -25.0f, -25.0f );
EXPECT_EQ( 0.0f, sprite.getPositionX() );
EXPECT_EQ( 0.0f, sprite.getPositionY() );
}
TEST( RenderableSpriteTest, Print )
{
using namespace StevensDev::sgdr;
Renderer renderer;
// can't continue if can't find the texture
ASSERT_TRUE( renderer.loadTexture( "test", "res/texture/actor/block/block.png" ) );
RenderableSprite sprite( renderer.getTexture( "test" ) );
sprite.setPosition( 0.0f, 0.0f );
std::ostringstream oss;
oss << sprite;
EXPECT_STREQ( "{ \"x\": 0.0, \"y\": 0.0 }", oss.str().c_str() );
}<|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 <cstdio>
#include "Compiler.hpp"
#include "Target.hpp"
#include "Utils.hpp"
#include "DebugStopWatch.hpp"
#include "Options.hpp"
#include "StringPool.hpp"
#include "FunctionTable.hpp"
#include "SemanticalException.hpp"
#include "AssemblyFileWriter.hpp"
#include "parser/SpiritParser.hpp"
#include "ast/SourceFile.hpp"
#include "ast/Position.hpp"
//Annotators
#include "ast/DefaultValues.hpp"
#include "ast/ContextAnnotator.hpp"
#include "ast/FunctionsAnnotator.hpp"
#include "ast/VariablesAnnotator.hpp"
//Checkers
#include "ast/StringChecker.hpp"
#include "ast/TypeChecker.hpp"
//Visitors
#include "ast/DependenciesResolver.hpp"
#include "ast/OptimizationEngine.hpp"
#include "ast/TransformerEngine.hpp"
#include "ast/WarningsEngine.hpp"
#include "ast/DebugVisitor.hpp"
//Three Address Code
#include "tac/Program.hpp"
#include "tac/Compiler.hpp"
#include "tac/BasicBlockExtractor.hpp"
#include "tac/TemporaryAllocator.hpp"
#include "tac/LivenessAnalyzer.hpp"
#include "tac/Optimizer.hpp"
#include "tac/Printer.hpp"
//Code generation
#include "asm/CodeGeneratorFactory.hpp"
//32 bits by default
eddic::Platform eddic::platform = Platform::INTEL_X86;
#ifdef DEBUG
static const bool debug = true;
#else
static const bool debug = false;
#endif
#define TIMER_START(name) StopWatch name_timer;
#define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;}
using namespace eddic;
void exec(const std::string& command);
int Compiler::compile(const std::string& file) {
std::cout << "Compile " << file << std::endl;
if(TargetDetermined && Target64){
platform = Platform::INTEL_X86_64;
}
if(options.count("32")){
platform = Platform::INTEL_X86;
}
if(options.count("64")){
platform = Platform::INTEL_X86_64;
}
StopWatch timer;
int code = compileOnly(file, platform);
std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl;
return code;
}
void assemble(Platform platform, const std::string& output);
void assembleWithDebug(Platform platform, const std::string& output);
int Compiler::compileOnly(const std::string& file, Platform platform) {
std::string output = options["output"].as<std::string>();
int code = 0;
try {
TIMER_START(parsing)
parser::SpiritParser parser;
//The program to build
ast::SourceFile program;
//Parse the file into the program
bool parsing = parser.parse(file, program);
TIMER_END(parsing)
if(parsing){
//Symbol tables
FunctionTable functionTable;
StringPool pool;
//Read dependencies
includeDependencies(program, parser);
//Apply some cleaning transformations
clean(program);
//Annotate the AST with more informations
defineDefaultValues(program);
//Fill the string pool
checkStrings(program, pool);
//Add some more informations to the AST
defineContexts(program);
defineVariables(program);
defineFunctions(program, functionTable);
//Transform the AST
transform(program);
//Static analysis
checkTypes(program);
//Check for warnings
checkForWarnings(program, functionTable);
//Check that there is a main in the program
checkForMain(functionTable);
//Optimize the AST
optimize(program, functionTable, pool);
tac::Program tacProgram;
//Generate Three-Address-Code language
tac::Compiler compiler;
compiler.compile(program, pool, tacProgram);
//Separate into basic blocks
tac::BasicBlockExtractor extractor;
extractor.extract(tacProgram);
//Allocate storage for the temporaries that need to be stored
tac::TemporaryAllocator allocator;
allocator.allocate(tacProgram);
tac::Optimizer optimizer;
optimizer.optimize(tacProgram, pool);
//Compute liveness of variables
tac::LivenessAnalyzer liveness;
liveness.compute(tacProgram);
//Generate assembly from TAC
AssemblyFileWriter writer("output.asm");
as::CodeGeneratorFactory factory;
auto generator = factory.get(platform, writer);
generator->generate(tacProgram, pool, functionTable);
writer.write();
//If it's necessary, assemble and link the assembly
if(!options.count("assembly")){
if(options.count("debug")){
assembleWithDebug(platform, output);
} else {
assemble(platform, output);
}
//Remove temporary files
if(!options.count("keep")){
remove("output.asm");
}
remove("output.o");
}
}
} catch (const SemanticalException& e) {
if(e.position()){
auto& position = *e.position();
std::cout << position.file << ":" << position.line << ":" << " error: " << e.what() << std::endl;
} else {
std::cout << e.what() << std::endl;
}
code = 1;
}
return code;
}
void assemble(Platform platform, const std::string& output){
switch(platform){
case Platform::INTEL_X86:
exec("nasm -f elf32 -o output.o output.asm");
exec("ld -S -m elf_i386 output.o -o " + output);
break;
case Platform::INTEL_X86_64:
exec("nasm -f elf64 -o output.o output.asm");
exec("ld -S -m elf_x86_64 output.o -o " + output);
break;
}
}
void assembleWithDebug(Platform platform, const std::string& output){
switch(platform){
case Platform::INTEL_X86:
exec("nasm -g -f elf32 -o output.o output.asm");
exec("ld -m elf_i386 output.o -o " + output);
break;
case Platform::INTEL_X86_64:
exec("nasm -g -f elf64 -o output.o output.asm");
exec("ld -m elf_x86_64 output.o -o " + output);
break;
}
}
void eddic::defineDefaultValues(ast::SourceFile& program){
DebugStopWatch<debug> timer("Annotate with default values");
ast::DefaultValues values;
values.fill(program);
}
void eddic::defineContexts(ast::SourceFile& program){
DebugStopWatch<debug> timer("Annotate contexts");
ast::ContextAnnotator annotator;
annotator.annotate(program);
}
void eddic::defineVariables(ast::SourceFile& program){
DebugStopWatch<debug> timer("Annotate variables");
ast::VariablesAnnotator annotator;
annotator.annotate(program);
}
void eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){
DebugStopWatch<debug> timer("Annotate functions");
ast::FunctionsAnnotator annotator;
annotator.annotate(program, functionTable);
}
void eddic::checkStrings(ast::SourceFile& program, StringPool& pool){
DebugStopWatch<debug> timer("Strings checking");
ast::StringChecker checker;
checker.check(program, pool);
}
void eddic::checkTypes(ast::SourceFile& program){
DebugStopWatch<debug> timer("Types checking");
ast::TypeChecker checker;
checker.check(program);
}
void eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){
DebugStopWatch<debug> timer("Check for warnings");
ast::WarningsEngine engine;
engine.check(program, table);
}
void eddic::checkForMain(FunctionTable& table){
if(!table.exists("main")){
throw SemanticalException("Your program must contain a main function");
}
auto function = table.getFunction("main");
if(function->parameters.size() > 1){
throw SemanticalException("The signature of your main function is not valid");
}
if(function->parameters.size() == 1){
auto type = function->parameters[0].paramType;
if(type.base() != BaseType::STRING || !type.isArray()){
throw SemanticalException("The signature of your main function is not valid");
}
}
}
void eddic::clean(ast::SourceFile& program){
DebugStopWatch<debug> timer("Cleaning");
ast::TransformerEngine engine;
engine.clean(program);
}
void eddic::transform(ast::SourceFile& program){
DebugStopWatch<debug> timer("Transformation");
ast::TransformerEngine engine;
engine.transform(program);
}
void eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){
DebugStopWatch<debug> timer("Optimization");
ast::OptimizationEngine engine;
engine.optimize(program, functionTable, pool);
}
void eddic::includeDependencies(ast::SourceFile& sourceFile, parser::SpiritParser& parser){
DebugStopWatch<debug> timer("Resolve dependencies");
ast::DependenciesResolver resolver(parser);
resolver.resolve(sourceFile);
}
void exec(const std::string& command) {
DebugStopWatch<debug> timer("Exec " + command);
if(debug){
std::cout << "eddic : exec command : " << command << std::endl;
}
std::string result = execCommand(command);
if(result.size() > 0){
std::cout << result << std::endl;
}
}
void eddic::warn(const std::string& warning){
std::cout << "warning: " << warning << std::endl;
}
void eddic::warn(const eddic::ast::Position& position, const std::string& warning){
std::cout << position.file << ":" << position.line << ": warning: " << warning << std::endl;
}
<commit_msg>Allow printing only tac or ast<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 <cstdio>
#include "Compiler.hpp"
#include "Target.hpp"
#include "Utils.hpp"
#include "DebugStopWatch.hpp"
#include "Options.hpp"
#include "StringPool.hpp"
#include "FunctionTable.hpp"
#include "SemanticalException.hpp"
#include "AssemblyFileWriter.hpp"
#include "parser/SpiritParser.hpp"
#include "ast/SourceFile.hpp"
#include "ast/Position.hpp"
//Annotators
#include "ast/DefaultValues.hpp"
#include "ast/ContextAnnotator.hpp"
#include "ast/FunctionsAnnotator.hpp"
#include "ast/VariablesAnnotator.hpp"
//Checkers
#include "ast/StringChecker.hpp"
#include "ast/TypeChecker.hpp"
//Visitors
#include "ast/DependenciesResolver.hpp"
#include "ast/OptimizationEngine.hpp"
#include "ast/TransformerEngine.hpp"
#include "ast/WarningsEngine.hpp"
#include "ast/DebugVisitor.hpp"
//Three Address Code
#include "tac/Program.hpp"
#include "tac/Compiler.hpp"
#include "tac/BasicBlockExtractor.hpp"
#include "tac/TemporaryAllocator.hpp"
#include "tac/LivenessAnalyzer.hpp"
#include "tac/Optimizer.hpp"
#include "tac/Printer.hpp"
//Code generation
#include "asm/CodeGeneratorFactory.hpp"
//32 bits by default
eddic::Platform eddic::platform = Platform::INTEL_X86;
#ifdef DEBUG
static const bool debug = true;
#else
static const bool debug = false;
#endif
#define TIMER_START(name) StopWatch name_timer;
#define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;}
using namespace eddic;
void exec(const std::string& command);
int Compiler::compile(const std::string& file) {
std::cout << "Compile " << file << std::endl;
if(TargetDetermined && Target64){
platform = Platform::INTEL_X86_64;
}
if(options.count("32")){
platform = Platform::INTEL_X86;
}
if(options.count("64")){
platform = Platform::INTEL_X86_64;
}
StopWatch timer;
int code = compileOnly(file, platform);
std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl;
return code;
}
void assemble(Platform platform, const std::string& output);
void assembleWithDebug(Platform platform, const std::string& output);
int Compiler::compileOnly(const std::string& file, Platform platform) {
std::string output = options["output"].as<std::string>();
int code = 0;
try {
TIMER_START(parsing)
parser::SpiritParser parser;
//The program to build
ast::SourceFile program;
//Parse the file into the program
bool parsing = parser.parse(file, program);
TIMER_END(parsing)
//If the parsing was sucessfully
if(parsing){
//Symbol tables
FunctionTable functionTable;
StringPool pool;
//Read dependencies
includeDependencies(program, parser);
//Apply some cleaning transformations
clean(program);
//Annotate the AST with more informations
defineDefaultValues(program);
//Fill the string pool
checkStrings(program, pool);
//Add some more informations to the AST
defineContexts(program);
defineVariables(program);
defineFunctions(program, functionTable);
//Transform the AST
transform(program);
//Static analysis
checkTypes(program);
//Check for warnings
checkForWarnings(program, functionTable);
//Check that there is a main in the program
checkForMain(functionTable);
//Optimize the AST
optimize(program, functionTable, pool);
//If the user asked for it, print the Abstract Syntax Tree
if(options.count("ast") || options.count("ast-only")){
ast::DebugVisitor()(program);
}
//If necessary, continue the compilation process
if(!options.count("ast-only")){
tac::Program tacProgram;
//Generate Three-Address-Code language
tac::Compiler compiler;
compiler.compile(program, pool, tacProgram);
//Separate into basic blocks
tac::BasicBlockExtractor extractor;
extractor.extract(tacProgram);
//Allocate storage for the temporaries that need to be stored
tac::TemporaryAllocator allocator;
allocator.allocate(tacProgram);
tac::Optimizer optimizer;
optimizer.optimize(tacProgram, pool);
//If asked by the user, print the Three Address code representation
if(options.count("tac") || options.count("tac-only")){
tac::Printer printer;
printer.print(tacProgram);
}
//If necessary, continue the compilation process
if(!options.count("tac-only")){
//Compute liveness of variables
tac::LivenessAnalyzer liveness;
liveness.compute(tacProgram);
//Generate assembly from TAC
AssemblyFileWriter writer("output.asm");
as::CodeGeneratorFactory factory;
auto generator = factory.get(platform, writer);
generator->generate(tacProgram, pool, functionTable);
writer.write();
//If it's necessary, assemble and link the assembly
if(!options.count("assembly")){
if(options.count("debug")){
assembleWithDebug(platform, output);
} else {
assemble(platform, output);
}
//Remove temporary files
if(!options.count("keep")){
remove("output.asm");
}
remove("output.o");
}
}
}
}
} catch (const SemanticalException& e) {
if(e.position()){
auto& position = *e.position();
std::cout << position.file << ":" << position.line << ":" << " error: " << e.what() << std::endl;
} else {
std::cout << e.what() << std::endl;
}
code = 1;
}
return code;
}
void assemble(Platform platform, const std::string& output){
switch(platform){
case Platform::INTEL_X86:
exec("nasm -f elf32 -o output.o output.asm");
exec("ld -S -m elf_i386 output.o -o " + output);
break;
case Platform::INTEL_X86_64:
exec("nasm -f elf64 -o output.o output.asm");
exec("ld -S -m elf_x86_64 output.o -o " + output);
break;
}
}
void assembleWithDebug(Platform platform, const std::string& output){
switch(platform){
case Platform::INTEL_X86:
exec("nasm -g -f elf32 -o output.o output.asm");
exec("ld -m elf_i386 output.o -o " + output);
break;
case Platform::INTEL_X86_64:
exec("nasm -g -f elf64 -o output.o output.asm");
exec("ld -m elf_x86_64 output.o -o " + output);
break;
}
}
void eddic::defineDefaultValues(ast::SourceFile& program){
DebugStopWatch<debug> timer("Annotate with default values");
ast::DefaultValues values;
values.fill(program);
}
void eddic::defineContexts(ast::SourceFile& program){
DebugStopWatch<debug> timer("Annotate contexts");
ast::ContextAnnotator annotator;
annotator.annotate(program);
}
void eddic::defineVariables(ast::SourceFile& program){
DebugStopWatch<debug> timer("Annotate variables");
ast::VariablesAnnotator annotator;
annotator.annotate(program);
}
void eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){
DebugStopWatch<debug> timer("Annotate functions");
ast::FunctionsAnnotator annotator;
annotator.annotate(program, functionTable);
}
void eddic::checkStrings(ast::SourceFile& program, StringPool& pool){
DebugStopWatch<debug> timer("Strings checking");
ast::StringChecker checker;
checker.check(program, pool);
}
void eddic::checkTypes(ast::SourceFile& program){
DebugStopWatch<debug> timer("Types checking");
ast::TypeChecker checker;
checker.check(program);
}
void eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){
DebugStopWatch<debug> timer("Check for warnings");
ast::WarningsEngine engine;
engine.check(program, table);
}
void eddic::checkForMain(FunctionTable& table){
if(!table.exists("main")){
throw SemanticalException("Your program must contain a main function");
}
auto function = table.getFunction("main");
if(function->parameters.size() > 1){
throw SemanticalException("The signature of your main function is not valid");
}
if(function->parameters.size() == 1){
auto type = function->parameters[0].paramType;
if(type.base() != BaseType::STRING || !type.isArray()){
throw SemanticalException("The signature of your main function is not valid");
}
}
}
void eddic::clean(ast::SourceFile& program){
DebugStopWatch<debug> timer("Cleaning");
ast::TransformerEngine engine;
engine.clean(program);
}
void eddic::transform(ast::SourceFile& program){
DebugStopWatch<debug> timer("Transformation");
ast::TransformerEngine engine;
engine.transform(program);
}
void eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){
DebugStopWatch<debug> timer("Optimization");
ast::OptimizationEngine engine;
engine.optimize(program, functionTable, pool);
}
void eddic::includeDependencies(ast::SourceFile& sourceFile, parser::SpiritParser& parser){
DebugStopWatch<debug> timer("Resolve dependencies");
ast::DependenciesResolver resolver(parser);
resolver.resolve(sourceFile);
}
void exec(const std::string& command) {
DebugStopWatch<debug> timer("Exec " + command);
if(debug){
std::cout << "eddic : exec command : " << command << std::endl;
}
std::string result = execCommand(command);
if(result.size() > 0){
std::cout << result << std::endl;
}
}
void eddic::warn(const std::string& warning){
std::cout << "warning: " << warning << std::endl;
}
void eddic::warn(const eddic::ast::Position& position, const std::string& warning){
std::cout << position.file << ":" << position.line << ": warning: " << warning << std::endl;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* thrill/api/groupby.hpp
*
* DIANode for a groupby operation. Performs the actual groupby operation
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 Huyen Chau Nguyen <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_API_GROUPBY_HEADER
#define THRILL_API_GROUPBY_HEADER
#include <thrill/api/dia.hpp>
#include <thrill/api/dop_node.hpp>
#include <thrill/api/groupby_iterator.hpp>
#include <thrill/common/functional.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/core/iterator_wrapper.hpp>
#include <thrill/core/multiway_merge.hpp>
#include <algorithm>
#include <functional>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
namespace thrill {
namespace api {
template <typename ValueType, typename ParentDIA,
typename KeyExtractor, typename GroupFunction, typename HashFunction>
class GroupByNode final : public DOpNode<ValueType>
{
static const bool debug = false;
using Super = DOpNode<ValueType>;
using Key = typename common::FunctionTraits<KeyExtractor>::result_type;
using ValueOut = ValueType;
using ValueIn = typename std::decay<typename common::FunctionTraits<KeyExtractor>
::template arg<0> >::type;
using File = data::File;
using Reader = typename File::Reader;
using Writer = typename File::Writer;
struct ValueComparator
{
explicit ValueComparator(const GroupByNode& info) : info_(info) { }
const GroupByNode& info_;
bool operator () (const ValueIn& i,
const ValueIn& j) {
// REVIEW(ch): why is this a comparison by hash key? hash can have
// collisions.
auto i_cmp = info_.hash_function_(info_.key_extractor_(i));
auto j_cmp = info_.hash_function_(info_.key_extractor_(j));
return (i_cmp < j_cmp);
}
};
using Super::context_;
public:
/*!
* Constructor for a GroupByNode. Sets the DataManager, parent, stack,
* key_extractor and reduce_function.
*
* \param parent Parent DIA.
* and this node
* \param key_extractor Key extractor function
* \param reduce_function Reduce function
*/
GroupByNode(const ParentDIA& parent,
const KeyExtractor& key_extractor,
const GroupFunction& groupby_function,
StatsNode* stats_node,
const HashFunction& hash_function = HashFunction())
: DOpNode<ValueType>(parent.ctx(), { parent.node() }, stats_node),
key_extractor_(key_extractor),
groupby_function_(groupby_function),
hash_function_(hash_function)
{
// Hook PreOp
auto pre_op_fn = [=](const ValueIn& input) {
PreOp(input);
};
// close the function stack with our pre op and register it at
// parent node for output
auto lop_chain = parent.stack().push(pre_op_fn).emit();
parent.node()->RegisterChild(lop_chain, this->type());
stream_->OnClose([this]() {
this->WriteStreamStats(this->stream_);
});
}
/*!
* Actually executes the reduce operation. Uses the member functions PreOp,
* MainOp and PostOp.
*/
void Execute() override {
MainOp();
}
void PushData(bool consume) final {
using Iterator = thrill::core::FileIteratorWrapper<ValueIn>;
const size_t num_runs = files_.size();
// if there's only one run, call user funcs
if (num_runs == 1) {
RunUserFunc(files_[0], consume);
} // otherwise sort all runs using multiway merge
else {
std::vector<std::pair<Iterator, Iterator> > seq;
seq.reserve(num_runs);
for (size_t t = 0; t < num_runs; ++t) {
std::shared_ptr<Reader> reader = std::make_shared<Reader>(
files_[t].GetReader(consume));
Iterator s = Iterator(&files_[t], reader, 0, true);
Iterator e = Iterator(&files_[t], reader, files_[t].num_items(), false);
seq.push_back(std::make_pair(std::move(s), std::move(e)));
}
auto puller = core::get_sequential_file_multiway_merge_tree<true, false>(
seq.begin(),
seq.end(),
totalsize_,
ValueComparator(*this));
if (puller.HasNext()) {
// create iterator to pass to user_function
auto user_iterator = GroupByMultiwayMergeIterator<
ValueIn, KeyExtractor, ValueComparator>(puller, key_extractor_);
while (user_iterator.HasNextForReal()) {
// call user function
const ValueOut res = groupby_function_(
user_iterator, user_iterator.GetNextKey());
// push result to callback functions
this->PushItem(res);
}
}
}
}
void Dispose() override { }
private:
const KeyExtractor& key_extractor_;
const GroupFunction& groupby_function_;
const HashFunction& hash_function_;
data::CatStreamPtr stream_ { context_.GetNewCatStream() };
std::vector<data::Stream::Writer> emitter_ { stream_->OpenWriters() };
std::vector<data::File> files_;
data::File sorted_elems_ { context_.GetFile() };
size_t totalsize_ = 0;
void RunUserFunc(File& f, bool consume) {
auto r = f.GetReader(consume);
if (r.HasNext()) {
// create iterator to pass to user_function
auto user_iterator = GroupByIterator<ValueIn, KeyExtractor, ValueComparator>(r, key_extractor_);
while (user_iterator.HasNextForReal()) {
// call user function
const ValueOut res = groupby_function_(user_iterator,
user_iterator.GetNextKey());
// push result to callback functions
this->PushItem(res);
}
}
}
/*
* Send all elements to their designated PEs
*/
void PreOp(const ValueIn& v) {
const Key k = key_extractor_(v);
const auto recipient = hash_function_(k) % emitter_.size();
emitter_[recipient](v);
}
/*
* Sort and store elements in a file
*/
void FlushVectorToFile(std::vector<ValueIn>& v) {
totalsize_ += v.size();
// sort run and sort to file
std::sort(v.begin(), v.end(), ValueComparator(*this));
File f = context_.GetFile();
{
Writer w = f.GetWriter();
for (const ValueIn& e : v) {
w(e);
}
w.Close();
}
files_.emplace_back(std::move(f));
}
//! Receive elements from other workers.
auto MainOp() {
LOG << "running group by main op";
const size_t FIXED_VECTOR_SIZE = 1000000000 / sizeof(ValueIn);
// const size_t FIXED_VECTOR_SIZE = 4;
std::vector<ValueIn> incoming;
incoming.reserve(FIXED_VECTOR_SIZE);
// close all emitters
for (auto& e : emitter_) {
e.Close();
}
// get incoming elements
auto reader = stream_->OpenCatReader(true /* consume */);
while (reader.HasNext()) {
// if vector is full save to disk
if (incoming.size() == FIXED_VECTOR_SIZE) {
FlushVectorToFile(incoming);
incoming.clear();
}
// store incoming element
incoming.emplace_back(reader.template Next<ValueIn>());
}
FlushVectorToFile(incoming);
std::vector<ValueIn>().swap(incoming);
stream_->Close();
}
};
/******************************************************************************/
template <typename ValueType, typename Stack>
template <typename ValueOut,
typename KeyExtractor,
typename GroupFunction,
typename HashFunction>
auto DIA<ValueType, Stack>::GroupBy(
const KeyExtractor &key_extractor,
const GroupFunction &groupby_function) const {
using DOpResult = ValueOut;
static_assert(
std::is_same<
typename std::decay<typename common::FunctionTraits<KeyExtractor>
::template arg<0> >::type,
ValueType>::value,
"KeyExtractor has the wrong input type");
StatsNode* stats_node = AddChildStatsNode("GroupBy", DIANodeType::DOP);
using GroupByNode
= api::GroupByNode<DOpResult, DIA, KeyExtractor,
GroupFunction, HashFunction>;
auto shared_node
= std::make_shared<GroupByNode>(
*this, key_extractor, groupby_function, stats_node);
return DIA<DOpResult>(shared_node, { stats_node });
}
} // namespace api
} // namespace thrill
#endif // !THRILL_API_GROUPBY_HEADER
/******************************************************************************/
<commit_msg>GroupBy: applying fix that @sebalamm only applied to GroupByIndex, one week ago, fixes #101.<commit_after>/*******************************************************************************
* thrill/api/groupby.hpp
*
* DIANode for a groupby operation. Performs the actual groupby operation
*
* Part of Project Thrill - http://project-thrill.org
*
* Copyright (C) 2015 Huyen Chau Nguyen <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#ifndef THRILL_API_GROUPBY_HEADER
#define THRILL_API_GROUPBY_HEADER
#include <thrill/api/dia.hpp>
#include <thrill/api/dop_node.hpp>
#include <thrill/api/groupby_iterator.hpp>
#include <thrill/common/functional.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/core/iterator_wrapper.hpp>
#include <thrill/core/multiway_merge.hpp>
#include <algorithm>
#include <functional>
#include <string>
#include <type_traits>
#include <typeinfo>
#include <utility>
#include <vector>
namespace thrill {
namespace api {
template <typename ValueType, typename ParentDIA,
typename KeyExtractor, typename GroupFunction, typename HashFunction>
class GroupByNode final : public DOpNode<ValueType>
{
static const bool debug = false;
using Super = DOpNode<ValueType>;
using Key = typename common::FunctionTraits<KeyExtractor>::result_type;
using ValueOut = ValueType;
using ValueIn = typename std::decay<typename common::FunctionTraits<KeyExtractor>
::template arg<0> >::type;
using File = data::File;
using Reader = typename File::Reader;
using Writer = typename File::Writer;
struct ValueComparator
{
explicit ValueComparator(const GroupByNode& info) : info_(info) { }
const GroupByNode& info_;
bool operator () (const ValueIn& i,
const ValueIn& j) {
// REVIEW(ch): why is this a comparison by hash key? hash can have
// collisions.
auto i_cmp = info_.hash_function_(info_.key_extractor_(i));
auto j_cmp = info_.hash_function_(info_.key_extractor_(j));
return (i_cmp < j_cmp);
}
};
using Super::context_;
public:
/*!
* Constructor for a GroupByNode. Sets the DataManager, parent, stack,
* key_extractor and reduce_function.
*
* \param parent Parent DIA.
* and this node
* \param key_extractor Key extractor function
* \param reduce_function Reduce function
*/
GroupByNode(const ParentDIA& parent,
const KeyExtractor& key_extractor,
const GroupFunction& groupby_function,
StatsNode* stats_node,
const HashFunction& hash_function = HashFunction())
: DOpNode<ValueType>(parent.ctx(), { parent.node() }, stats_node),
key_extractor_(key_extractor),
groupby_function_(groupby_function),
hash_function_(hash_function)
{
// Hook PreOp
auto pre_op_fn = [=](const ValueIn& input) {
PreOp(input);
};
// close the function stack with our pre op and register it at
// parent node for output
auto lop_chain = parent.stack().push(pre_op_fn).emit();
parent.node()->RegisterChild(lop_chain, this->type());
stream_->OnClose([this]() {
this->WriteStreamStats(this->stream_);
});
}
/*!
* Actually executes the reduce operation. Uses the member functions PreOp,
* MainOp and PostOp.
*/
void Execute() override {
MainOp();
}
void PushData(bool consume) final {
using Iterator = thrill::core::FileIteratorWrapper<ValueIn>;
const size_t num_runs = files_.size();
// if there's only one run, call user funcs
if (num_runs == 1) {
RunUserFunc(files_[0], consume);
} // otherwise sort all runs using multiway merge
else {
std::vector<std::pair<Iterator, Iterator> > seq;
seq.reserve(num_runs);
for (size_t t = 0; t < num_runs; ++t) {
std::shared_ptr<Reader> reader = std::make_shared<Reader>(
files_[t].GetReader(consume));
Iterator s = Iterator(&files_[t], reader, 0, true);
Iterator e = Iterator(&files_[t], reader, files_[t].num_items(), false);
seq.push_back(std::make_pair(std::move(s), std::move(e)));
}
auto puller = core::get_sequential_file_multiway_merge_tree<true, false>(
seq.begin(),
seq.end(),
totalsize_,
ValueComparator(*this));
if (puller.HasNext()) {
// create iterator to pass to user_function
auto user_iterator = GroupByMultiwayMergeIterator<
ValueIn, KeyExtractor, ValueComparator>(puller, key_extractor_);
while (user_iterator.HasNextForReal()) {
// call user function
const ValueOut res = groupby_function_(
user_iterator, user_iterator.GetNextKey());
// push result to callback functions
this->PushItem(res);
}
}
}
}
void Dispose() override { }
private:
KeyExtractor key_extractor_;
GroupFunction groupby_function_;
HashFunction hash_function_;
data::CatStreamPtr stream_ { context_.GetNewCatStream() };
std::vector<data::Stream::Writer> emitter_ { stream_->OpenWriters() };
std::vector<data::File> files_;
data::File sorted_elems_ { context_.GetFile() };
size_t totalsize_ = 0;
void RunUserFunc(File& f, bool consume) {
auto r = f.GetReader(consume);
if (r.HasNext()) {
// create iterator to pass to user_function
auto user_iterator = GroupByIterator<ValueIn, KeyExtractor, ValueComparator>(r, key_extractor_);
while (user_iterator.HasNextForReal()) {
// call user function
const ValueOut res = groupby_function_(user_iterator,
user_iterator.GetNextKey());
// push result to callback functions
this->PushItem(res);
}
}
}
/*
* Send all elements to their designated PEs
*/
void PreOp(const ValueIn& v) {
const Key k = key_extractor_(v);
const auto recipient = hash_function_(k) % emitter_.size();
emitter_[recipient](v);
}
/*
* Sort and store elements in a file
*/
void FlushVectorToFile(std::vector<ValueIn>& v) {
totalsize_ += v.size();
// sort run and sort to file
std::sort(v.begin(), v.end(), ValueComparator(*this));
File f = context_.GetFile();
{
Writer w = f.GetWriter();
for (const ValueIn& e : v) {
w(e);
}
w.Close();
}
files_.emplace_back(std::move(f));
}
//! Receive elements from other workers.
auto MainOp() {
LOG << "running group by main op";
const size_t FIXED_VECTOR_SIZE = 1000000000 / sizeof(ValueIn);
// const size_t FIXED_VECTOR_SIZE = 4;
std::vector<ValueIn> incoming;
incoming.reserve(FIXED_VECTOR_SIZE);
// close all emitters
for (auto& e : emitter_) {
e.Close();
}
// get incoming elements
auto reader = stream_->OpenCatReader(true /* consume */);
while (reader.HasNext()) {
// if vector is full save to disk
if (incoming.size() == FIXED_VECTOR_SIZE) {
FlushVectorToFile(incoming);
incoming.clear();
}
// store incoming element
incoming.emplace_back(reader.template Next<ValueIn>());
}
FlushVectorToFile(incoming);
std::vector<ValueIn>().swap(incoming);
stream_->Close();
}
};
/******************************************************************************/
template <typename ValueType, typename Stack>
template <typename ValueOut,
typename KeyExtractor,
typename GroupFunction,
typename HashFunction>
auto DIA<ValueType, Stack>::GroupBy(
const KeyExtractor &key_extractor,
const GroupFunction &groupby_function) const {
using DOpResult = ValueOut;
static_assert(
std::is_same<
typename std::decay<typename common::FunctionTraits<KeyExtractor>
::template arg<0> >::type,
ValueType>::value,
"KeyExtractor has the wrong input type");
StatsNode* stats_node = AddChildStatsNode("GroupBy", DIANodeType::DOP);
using GroupByNode
= api::GroupByNode<DOpResult, DIA, KeyExtractor,
GroupFunction, HashFunction>;
auto shared_node
= std::make_shared<GroupByNode>(
*this, key_extractor, groupby_function, stats_node);
return DIA<DOpResult>(shared_node, { stats_node });
}
} // namespace api
} // namespace thrill
#endif // !THRILL_API_GROUPBY_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>/*
* File: AddressesPage.cpp
* Author: danny
*
* Created on February 16, 2015, 12:26 PM
*/
#include "AddressesPage.h"
#include "DataSubsystem.h"
#include "WebMenu.h"
#include "EditThingPage.h"
#include <Poco/Data/Session.h>
#include <Poco/Util/Application.h>
const std::string AddressesPage::Title("My Addresses");
const std::string AddressesPage::Link("addresses.bin");
AddressesPage::AddressesPage()
{
}
AddressesPage::~AddressesPage()
{
}
std::string AddressesPage::title() const
{
return Title;
}
bool AddressesPage::handleForm(Poco::Net::HTMLForm& form, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
return false;
}
void AddressesPage::renderPanelBody(std::ostream& output, Poco::Net::HTTPServerRequest& request)
{
renderTable(output);
renderScripts(output);
}
void AddressesPage::renderButtons(std::ostream& output)
{
}
std::string AddressesPage::subtitle() const
{
return "Some text goes here";
}
void AddressesPage::renderTable(std::ostream& output)
{
output << "<div class='table-responsive'>";
output << "<table id='addresses' class='table table-responsive' >";
output << " <thead>";
output << " <tr>";
output << " <th>MAC</th>";
output << " <th>IP</th>";
output << " <th>Last</th>";
output << " <th>Type</th>";
output << " <th>Name</th>";
output << " <th>Vendor</th>";
output << " <th>OS</th>";
output << " <th>Description</th>";
output << " <th>HW</th>";
output << " <th>Authorized</th>";
output << " </tr>";
output << " </thead>";
output << " <tbody>";
Poco::Data::Session session = Poco::Util::Application::instance().getSubsystem<DataSubsystem>().createSession();
Poco::Data::Statement query(session);
query << "SELECT ip.mac, ip, datetime(last_seen,'unixepoch','localtime') as last_seen, "
"thing.id, thing.type, thing.name, thing.vendor, "
"thing.os, desc, oui.vendor as hw_vendor , case when authorized.mac is null then 'no' else 'yes' end as auth "
"FROM ip LEFT JOIN thing ON ip.thingid=thing.id "
"LEFT JOIN oui ON substr(ip.mac,0,9)=oui.prefix "
"LEFT JOIN authorized on ip.mac=authorized.mac "
"ORDER BY ip.mac";
query.execute();
Poco::Data::RecordSet rs(query);
bool more = rs.moveFirst();
while (more) {
renderRow(output, rs);
more = rs.moveNext();
}
output << " </tbody>";
output << "</table>";
}
void AddressesPage::renderRow(std::ostream& output, Poco::Data::RecordSet& rs)
{
output << "<tr>";
for (size_t i = 0; i < rs.columnCount(); ++i) {
if (rs.columnName(i) == "id") {
continue;
}
output << "<td>";
if (!rs[i].isEmpty()) {
if (rs.columnName(i) == "mac") {
output << Poco::format("<a href='%s?id=%s'>", EditThingPage::Link, rs["id"].toString());
}
output << rs[i].toString();
if (rs.columnName(i) == "mac") {
output << "</a>";
}
}
output << "</td>";
}
output << "</tr>";
}
void AddressesPage::renderScripts(std::ostream& output)
{
output << "<script>";
output << " $(document).ready(function () {";
output << " $('#addresses').dataTable();";
output << " });";
output << "</script>";
}
<commit_msg>#26: Rename column headers in the "My Addresses" screen<commit_after>/*
* File: AddressesPage.cpp
* Author: danny
*
* Created on February 16, 2015, 12:26 PM
*/
#include "AddressesPage.h"
#include "DataSubsystem.h"
#include "WebMenu.h"
#include "EditThingPage.h"
#include <Poco/Data/Session.h>
#include <Poco/Util/Application.h>
const std::string AddressesPage::Title("My Addresses");
const std::string AddressesPage::Link("addresses.bin");
AddressesPage::AddressesPage()
{
}
AddressesPage::~AddressesPage()
{
}
std::string AddressesPage::title() const
{
return Title;
}
bool AddressesPage::handleForm(Poco::Net::HTMLForm& form, Poco::Net::HTTPServerRequest& request, Poco::Net::HTTPServerResponse& response)
{
return false;
}
void AddressesPage::renderPanelBody(std::ostream& output, Poco::Net::HTTPServerRequest& request)
{
renderTable(output);
renderScripts(output);
}
void AddressesPage::renderButtons(std::ostream& output)
{
}
std::string AddressesPage::subtitle() const
{
return "Some text goes here";
}
void AddressesPage::renderTable(std::ostream& output)
{
output << "<div class='table-responsive'>";
output << "<table id='addresses' class='table table-responsive' >";
output << " <thead>";
output << " <tr>";
output << " <th>MAC Address</th>";
output << " <th>IP Address</th>";
output << " <th>Last Seen</th>";
output << " <th>Type</th>";
output << " <th>Name</th>";
output << " <th>Vendor</th>";
output << " <th>Operating System</th>";
output << " <th>Description</th>";
output << " <th>Hardware Family</th>";
output << " <th>Authorized</th>";
output << " </tr>";
output << " </thead>";
output << " <tbody>";
Poco::Data::Session session = Poco::Util::Application::instance().getSubsystem<DataSubsystem>().createSession();
Poco::Data::Statement query(session);
query << "SELECT ip.mac, ip, datetime(last_seen,'unixepoch','localtime') as last_seen, "
"thing.id, thing.type, thing.name, thing.vendor, "
"thing.os, desc, oui.vendor as hw_vendor , case when authorized.mac is null then 'no' else 'yes' end as auth "
"FROM ip LEFT JOIN thing ON ip.thingid=thing.id "
"LEFT JOIN oui ON substr(ip.mac,0,9)=oui.prefix "
"LEFT JOIN authorized on ip.mac=authorized.mac "
"ORDER BY ip.mac";
query.execute();
Poco::Data::RecordSet rs(query);
bool more = rs.moveFirst();
while (more) {
renderRow(output, rs);
more = rs.moveNext();
}
output << " </tbody>";
output << "</table>";
}
void AddressesPage::renderRow(std::ostream& output, Poco::Data::RecordSet& rs)
{
output << "<tr>";
for (size_t i = 0; i < rs.columnCount(); ++i) {
if (rs.columnName(i) == "id") {
continue;
}
output << "<td>";
if (!rs[i].isEmpty()) {
if (rs.columnName(i) == "mac") {
output << Poco::format("<a href='%s?id=%s'>", EditThingPage::Link, rs["id"].toString());
}
output << rs[i].toString();
if (rs.columnName(i) == "mac") {
output << "</a>";
}
}
output << "</td>";
}
output << "</tr>";
}
void AddressesPage::renderScripts(std::ostream& output)
{
output << "<script>";
output << " $(document).ready(function () {";
output << " $('#addresses').dataTable();";
output << " });";
output << "</script>";
}
<|endoftext|> |
<commit_before>// Time: O(n)
// Space: O(c)
class Solution {
public:
/**
* @param A: A string includes Upper Case letters
* @param B: A string includes Upper Case letter
* @return: if string A contains all of the characters in B return true
* else return false
*/
bool compareStrings(string A, string B) {
// write your code here
unordered_map<char, size_t> h;
for (auto& c: B) {
++h[c];
}
size_t cnt = B.length();
for (auto& c: A) {
if (h[c] > 0) {
--h[c];
--cnt;
}
if (cnt == 0) {
return true;
}
}
if (cnt > 0) {
return false;
}
return true;
}
};
<commit_msg>Update compare-strings.cpp<commit_after>// Time: O(n)
// Space: O(c)
class Solution {
public:
/**
* @param A: A string includes Upper Case letters
* @param B: A string includes Upper Case letter
* @return: if string A contains all of the characters in B return true
* else return false
*/
bool compareStrings(string A, string B) {
unordered_map<char, int> h;
for (auto& c: A) {
++h[c];
}
for (auto& c: B) {
if (--h[c] < 0) {
return false;
}
}
return true;
}
};
class Solution2 {
public:
/**
* @param A: A string includes Upper Case letters
* @param B: A string includes Upper Case letter
* @return: if string A contains all of the characters in B return true
* else return false
*/
bool compareStrings(string A, string B) {
// write your code here
unordered_map<char, int> h;
for (auto& c: B) {
++h[c];
}
size_t cnt = B.length();
for (auto& c: A) {
if (h[c] > 0) {
--h[c];
--cnt;
}
if (cnt == 0) {
return true;
}
}
if (cnt > 0) {
return false;
}
return true;
}
};
<|endoftext|> |
<commit_before>// Time: O(n * n!)
// Space: O(n)
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of unique permutations.
*/
vector<vector<int>> permuteUnique(vector<int> &nums) {
vector<vector<int>> result;
deque<bool> used(nums.size(), false);
vector<int> ans;
sort(nums.begin(), nums.end());
permuteUniqueRecu(nums, &used, &ans, &result);
return result;
}
void permuteUniqueRecu(const vector<int> &A, deque<bool> *used,
vector<int> *ans, vector<vector<int>> *result) {
if (ans->size() == A.size()) {
result->emplace_back(*ans);
return;
}
for (size_t i = 0; i < A.size(); ++i) {
if (!(*used)[i] && !(i != 0 && A[i - 1] == A[i] && (*used)[i - 1])) {
(*used)[i] = true;
ans->emplace_back(A[i]);
permuteUniqueRecu(A, used, ans, result);
ans->pop_back();
(*used)[i] = false;
}
}
}
};
<commit_msg>Update permutations-ii.cpp<commit_after>// Time: O(n * n!)
// Space: O(n)
class Solution {
public:
/**
* @param nums: A list of integers.
* @return: A list of unique permutations.
*/
vector<vector<int>> permuteUnique(vector<int> &nums) {
vector<vector<int>> result;
deque<bool> used(nums.size(), false);
vector<int> ans;
sort(nums.begin(), nums.end());
permuteUniqueRecu(nums, &used, &ans, &result);
return result;
}
void permuteUniqueRecu(const vector<int> &A, deque<bool> *used,
vector<int> *ans, vector<vector<int>> *result) {
if (ans->size() == A.size()) {
result->emplace_back(*ans);
return;
}
for (size_t i = 0; i < A.size(); ++i) {
if (!(*used)[i] && !(i != 0 && A[i - 1] == A[i] && (*used)[i - 1])) {
(*used)[i] = true;
ans->emplace_back(A[i]);
permuteUniqueRecu(A, used, ans, result);
ans->pop_back();
(*used)[i] = false;
}
}
}
};
<|endoftext|> |
<commit_before>#include "Database.h"
#include "Task.h"
#include <assert.h>
#include <sstream>
int Database::_count = 0;
Database::Database(Task* task) {
++_count;
_task = task;
v8::Handle<v8::External> data = v8::External::New(task->getIsolate(), this);
v8::Local<v8::ObjectTemplate> databaseTemplate = v8::ObjectTemplate::New(task->getIsolate());
databaseTemplate->SetInternalFieldCount(1);
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "get"), v8::FunctionTemplate::New(task->getIsolate(), get, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "set"), v8::FunctionTemplate::New(task->getIsolate(), set, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "remove"), v8::FunctionTemplate::New(task->getIsolate(), remove, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "getAll"), v8::FunctionTemplate::New(task->getIsolate(), getAll, data));
v8::Local<v8::Object> databaseObject = databaseTemplate->NewInstance();
databaseObject->SetInternalField(0, v8::External::New(task->getIsolate(), this));
_object = v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> >(task->getIsolate(), databaseObject);
}
Database::~Database() {
--_count;
}
void Database::create(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope handleScope(args.GetIsolate());
if (Database* database = new Database(Task::get(args.GetIsolate()))) {
if (database->open(args.GetIsolate(), *v8::String::Utf8Value(args[0].As<v8::String>()))) {
v8::Handle<v8::Object> result = v8::Local<v8::Object>::New(args.GetIsolate(), database->_object);
args.GetReturnValue().Set(result);
}
database->release();
}
}
bool Database::checkError(const char* command, int result) {
bool isError = false;
if (result != MDB_SUCCESS) {
isError = true;
std::ostringstream buffer;
buffer << command << " failed (" << result << "): " << mdb_strerror(result);
_task->getIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(_task->getIsolate(), buffer.str().c_str())));
}
return isError;
}
bool Database::open(v8::Isolate* isolate, const char* path) {
int result = mdb_env_create(&_environment);
if (checkError("mdb_env_create", result)) {
return false;
}
result = mdb_env_set_maxdbs(_environment, 10);
checkError("mdb_env_set_maxdbs", result);
result = mdb_env_open(_environment, path, 0, 0644);
if (!checkError("mdb_env_open", result)) {
result = mdb_txn_begin(_environment, 0, 0, &_transaction);
if (!checkError("mdb_txn_begin", result)) {
result = mdb_dbi_open(_transaction, path, MDB_CREATE, &_database);
if (!checkError("mdb_dbi_open", result)) {
result = mdb_txn_commit(_transaction);
checkError("mdb_txn_commit", result);
}
}
if (result != MDB_SUCCESS) {
mdb_txn_abort(_transaction);
}
}
if (result != MDB_SUCCESS) {
mdb_env_close(_environment);
}
return result == MDB_SUCCESS;
}
void Database::get(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, MDB_RDONLY, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
MDB_val value;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
if (mdb_get(database->_transaction, database->_database, &key, &value) == MDB_SUCCESS) {
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(), reinterpret_cast<const char*>(value.mv_data), v8::String::kNormalString, value.mv_size));
}
mdb_txn_reset(database->_transaction);
}
}
}
void Database::set(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, 0, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
MDB_val data;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
v8::String::Utf8Value valueString(args[1]->ToString(args.GetIsolate()));
data.mv_data = *valueString;
data.mv_size = valueString.length();
result = mdb_put(database->_transaction, database->_database, &key, &data, 0);
database->checkError("mdb_put", result);
mdb_txn_commit(database->_transaction);
}
}
}
void Database::remove(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, 0, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
result = mdb_del(database->_transaction, database->_database, &key, 0);
database->checkError("mdb_del", result);
mdb_txn_commit(database->_transaction);
}
}
}
void Database::getAll(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, MDB_RDONLY, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_cursor* cursor;
result = mdb_cursor_open(database->_transaction, database->_database, &cursor);
if (!database->checkError("mdb_cursor_open", result)) {
int expectedCount = 0;
MDB_stat statistics;
if (mdb_stat(database->_transaction, database->_database, &statistics) == 0) {
expectedCount = statistics.ms_entries;
}
v8::Local<v8::Array> array = v8::Array::New(args.GetIsolate(), expectedCount);
MDB_val key;
int index = 0;
while ((result = mdb_cursor_get(cursor, &key, 0, MDB_NEXT)) == 0) {
array->Set(index++, v8::String::NewFromUtf8(args.GetIsolate(), reinterpret_cast<const char*>(key.mv_data), v8::String::kNormalString, key.mv_size));
}
if (result == MDB_NOTFOUND) {
args.GetReturnValue().Set(array);
} else {
database->checkError("mdb_cursor_get", result);
}
mdb_cursor_close(cursor);
}
mdb_txn_reset(database->_transaction);
}
}
}
void Database::onRelease(const v8::WeakCallbackData<v8::Object, Database>& data) {
data.GetParameter()->_object.Reset();
delete data.GetParameter();
}
void Database::ref() {
if (++_refCount == 1) {
_object.ClearWeak();
}
}
void Database::release() {
assert(_refCount >= 1);
if (--_refCount == 0) {
_object.SetWeak(this, onRelease);
}
}
Database* Database::get(v8::Handle<v8::Value> databaseObject) {
return reinterpret_cast<Database*>(v8::Handle<v8::External>::Cast(databaseObject)->Value());
}
<commit_msg>Augh. My databases had their paths baked in them.<commit_after>#include "Database.h"
#include "Task.h"
#include <assert.h>
#include <sstream>
int Database::_count = 0;
Database::Database(Task* task) {
++_count;
_task = task;
v8::Handle<v8::External> data = v8::External::New(task->getIsolate(), this);
v8::Local<v8::ObjectTemplate> databaseTemplate = v8::ObjectTemplate::New(task->getIsolate());
databaseTemplate->SetInternalFieldCount(1);
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "get"), v8::FunctionTemplate::New(task->getIsolate(), get, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "set"), v8::FunctionTemplate::New(task->getIsolate(), set, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "remove"), v8::FunctionTemplate::New(task->getIsolate(), remove, data));
databaseTemplate->Set(v8::String::NewFromUtf8(task->getIsolate(), "getAll"), v8::FunctionTemplate::New(task->getIsolate(), getAll, data));
v8::Local<v8::Object> databaseObject = databaseTemplate->NewInstance();
databaseObject->SetInternalField(0, v8::External::New(task->getIsolate(), this));
_object = v8::Persistent<v8::Object, v8::CopyablePersistentTraits<v8::Object> >(task->getIsolate(), databaseObject);
}
Database::~Database() {
--_count;
}
void Database::create(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::HandleScope handleScope(args.GetIsolate());
if (Database* database = new Database(Task::get(args.GetIsolate()))) {
if (database->open(args.GetIsolate(), *v8::String::Utf8Value(args[0].As<v8::String>()))) {
v8::Handle<v8::Object> result = v8::Local<v8::Object>::New(args.GetIsolate(), database->_object);
args.GetReturnValue().Set(result);
}
database->release();
}
}
bool Database::checkError(const char* command, int result) {
bool isError = false;
if (result != MDB_SUCCESS) {
isError = true;
std::ostringstream buffer;
buffer << command << " failed (" << result << "): " << mdb_strerror(result);
_task->getIsolate()->ThrowException(v8::Exception::Error(v8::String::NewFromUtf8(_task->getIsolate(), buffer.str().c_str())));
}
return isError;
}
bool Database::open(v8::Isolate* isolate, const char* path) {
int result = mdb_env_create(&_environment);
if (checkError("mdb_env_create", result)) {
return false;
}
result = mdb_env_set_maxdbs(_environment, 10);
checkError("mdb_env_set_maxdbs", result);
result = mdb_env_open(_environment, path, 0, 0644);
if (!checkError("mdb_env_open", result)) {
result = mdb_txn_begin(_environment, 0, 0, &_transaction);
if (!checkError("mdb_txn_begin", result)) {
result = mdb_dbi_open(_transaction, NULL, MDB_CREATE, &_database);
if (!checkError("mdb_dbi_open", result)) {
result = mdb_txn_commit(_transaction);
checkError("mdb_txn_commit", result);
}
}
if (result != MDB_SUCCESS) {
mdb_txn_abort(_transaction);
}
}
if (result != MDB_SUCCESS) {
mdb_env_close(_environment);
}
return result == MDB_SUCCESS;
}
void Database::get(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, MDB_RDONLY, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
MDB_val value;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
if (mdb_get(database->_transaction, database->_database, &key, &value) == MDB_SUCCESS) {
args.GetReturnValue().Set(v8::String::NewFromUtf8(args.GetIsolate(), reinterpret_cast<const char*>(value.mv_data), v8::String::kNormalString, value.mv_size));
}
mdb_txn_reset(database->_transaction);
}
}
}
void Database::set(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, 0, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
MDB_val data;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
v8::String::Utf8Value valueString(args[1]->ToString(args.GetIsolate()));
data.mv_data = *valueString;
data.mv_size = valueString.length();
result = mdb_put(database->_transaction, database->_database, &key, &data, 0);
database->checkError("mdb_put", result);
mdb_txn_commit(database->_transaction);
}
}
}
void Database::remove(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, 0, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_val key;
v8::String::Utf8Value keyString(args[0].As<v8::String>());
key.mv_data = *keyString;
key.mv_size = keyString.length();
result = mdb_del(database->_transaction, database->_database, &key, 0);
database->checkError("mdb_del", result);
mdb_txn_commit(database->_transaction);
}
}
}
void Database::getAll(const v8::FunctionCallbackInfo<v8::Value>& args) {
if (Database* database = Database::get(args.Data())) {
int result = mdb_txn_begin(database->_environment, 0, MDB_RDONLY, &database->_transaction);
if (!database->checkError("mdb_txn_begin", result)) {
MDB_cursor* cursor;
result = mdb_cursor_open(database->_transaction, database->_database, &cursor);
if (!database->checkError("mdb_cursor_open", result)) {
int expectedCount = 0;
MDB_stat statistics;
if (mdb_stat(database->_transaction, database->_database, &statistics) == 0) {
expectedCount = statistics.ms_entries;
}
v8::Local<v8::Array> array = v8::Array::New(args.GetIsolate(), expectedCount);
MDB_val key;
int index = 0;
while ((result = mdb_cursor_get(cursor, &key, 0, MDB_NEXT)) == 0) {
array->Set(index++, v8::String::NewFromUtf8(args.GetIsolate(), reinterpret_cast<const char*>(key.mv_data), v8::String::kNormalString, key.mv_size));
}
if (result == MDB_NOTFOUND) {
args.GetReturnValue().Set(array);
} else {
database->checkError("mdb_cursor_get", result);
}
mdb_cursor_close(cursor);
}
mdb_txn_reset(database->_transaction);
}
}
}
void Database::onRelease(const v8::WeakCallbackData<v8::Object, Database>& data) {
data.GetParameter()->_object.Reset();
delete data.GetParameter();
}
void Database::ref() {
if (++_refCount == 1) {
_object.ClearWeak();
}
}
void Database::release() {
assert(_refCount >= 1);
if (--_refCount == 0) {
_object.SetWeak(this, onRelease);
}
}
Database* Database::get(v8::Handle<v8::Value> databaseObject) {
return reinterpret_cast<Database*>(v8::Handle<v8::External>::Cast(databaseObject)->Value());
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRectilinearGridGeometryFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkRectilinearGridGeometryFilter.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkPolyData.h"
#include "vtkRectilinearGrid.h"
vtkStandardNewMacro(vtkRectilinearGridGeometryFilter);
// Construct with initial extent (0,100, 0,100, 0,0) (i.e., a k-plane).
vtkRectilinearGridGeometryFilter::vtkRectilinearGridGeometryFilter()
{
this->Extent[0] = 0;
this->Extent[1] = VTK_LARGE_INTEGER;
this->Extent[2] = 0;
this->Extent[3] = VTK_LARGE_INTEGER;
this->Extent[4] = 0;
this->Extent[5] = VTK_LARGE_INTEGER;
}
int vtkRectilinearGridGeometryFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkRectilinearGrid *input = vtkRectilinearGrid::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
int *dims, dimension, dir[3], diff[3];
int i, j, k, extent[6];
vtkIdType idx, startIdx, startCellIdx;
vtkIdType ptIds[4];
vtkIdType cellId;
vtkPoints *newPts=0;
vtkCellArray *newVerts=0;
vtkCellArray *newLines=0;
vtkCellArray *newPolys=0;
vtkIdType totPoints, pos;
int offset[3], numPolys;
double x[3];
vtkPointData *pd, *outPD;
vtkCellData *cd, *outCD;
vtkDebugMacro(<< "Extracting rectilinear points geometry");
pd = input->GetPointData();
outPD = output->GetPointData();
outPD->CopyNormalsOff();
cd = input->GetCellData();
outCD = output->GetCellData();
dims = input->GetDimensions();
//
// Based on the dimensions of the rectilinear data,
// and the extent of the geometry,
// compute the combined extent plus the dimensionality of the data
//
for (dimension=3, i=0; i<3; i++)
{
extent[2*i] = this->Extent[2*i] < 0 ? 0 : this->Extent[2*i];
extent[2*i] = this->Extent[2*i] >= dims[i] ? dims[i]-1 : this->Extent[2*i];
extent[2*i+1] = this->Extent[2*i+1] >= dims[i] ? dims[i]-1 : this->Extent[2*i+1];
if ( extent[2*i+1] < extent[2*i] )
{
extent[2*i+1] = extent[2*i];
}
if ( (extent[2*i+1] - extent[2*i]) == 0 )
{
dimension--;
}
}
//
// Now create polygonal data based on dimension of data
//
startIdx = extent[0] + extent[2]*dims[0] + extent[4]*dims[0]*dims[1];
// The cell index is a bit more complicated at the boundaries
if (dims[0] == 1)
{
startCellIdx = extent[0];
}
else
{
startCellIdx = (extent[0] < dims[0] - 1) ? extent[0]
: extent[0]-1;
}
if (dims[1] == 1)
{
startCellIdx += extent[2]*(dims[0]-1);
}
else
{
startCellIdx += (extent[2] < dims[1] - 1) ? extent[2]*(dims[0]-1)
: (extent[2]-1)*(dims[0]-1);
}
if (dims[2] == 1)
{
startCellIdx += extent[4]*(dims[0]-1)*(dims[1]-1);
}
else
{
startCellIdx += (extent[4] < dims[2] - 1) ? extent[4]*(dims[0]-1)*(dims[1]-1)
: (extent[4]-1)*(dims[0]-1)*(dims[1]-1);
}
switch (dimension)
{
default:
break;
case 0: // --------------------- build point -----------------------
newPts = vtkPoints::New();
newPts->Allocate(1);
newVerts = vtkCellArray::New();
newVerts->Allocate(newVerts->EstimateSize(1,1));
outPD->CopyAllocate(pd,1);
outCD->CopyAllocate(cd,1);
ptIds[0] = newPts->InsertNextPoint(input->GetPoint(startIdx));
outPD->CopyData(pd,startIdx,ptIds[0]);
cellId = newVerts->InsertNextCell(1,ptIds);
outCD->CopyData(cd,startIdx,cellId);
break;
case 1: // --------------------- build line -----------------------
for (dir[0]=dir[1]=dir[2]=totPoints=0, i=0; i<3; i++)
{
if ( (diff[i] = extent[2*i+1] - extent[2*i]) > 0 )
{
dir[0] = i;
totPoints = diff[i] + 1;
break;
}
}
newPts = vtkPoints::New();
newPts->Allocate(totPoints);
newLines = vtkCellArray::New();
newLines->Allocate(newLines->EstimateSize(totPoints-1,2));
outPD->CopyAllocate(pd,totPoints);
outCD->CopyAllocate(cd,totPoints - 1);
//
// Load data
//
if ( dir[0] == 0 )
{
offset[0] = 1;
}
else if (dir[0] == 1)
{
offset[0] = dims[0];
}
else
{
offset[0] = dims[0]*dims[1];
}
for (i=0; i<totPoints; i++)
{
idx = startIdx + i*offset[0];
input->GetPoint(idx, x);
ptIds[0] = newPts->InsertNextPoint(x);
outPD->CopyData(pd,idx,ptIds[0]);
}
if ( dir[0] == 0 )
{
offset[0] = 1;
}
else if (dir[0] == 1)
{
offset[0] = dims[0] - 1;
}
else
{
offset[0] = (dims[0] - 1) * (dims[1] - 1);
}
for (i=0; i<(totPoints-1); i++)
{
idx = startCellIdx + i*offset[0];
ptIds[0] = i;
ptIds[1] = i + 1;
cellId = newLines->InsertNextCell(2,ptIds);
outCD->CopyData(cd,idx,cellId);
}
break;
case 2: // --------------------- build plane -----------------------
//
// Create the data objects
//
for (dir[0]=dir[1]=dir[2]=idx=0,i=0; i<3; i++)
{
if ( (diff[i] = extent[2*i+1] - extent[2*i]) != 0 )
{
dir[idx++] = i;
}
else
{
dir[2] = i;
}
}
totPoints = (diff[dir[0]]+1) * (diff[dir[1]]+1);
numPolys = diff[dir[0]] * diff[dir[1]];
newPts = vtkPoints::New();
newPts->Allocate(totPoints);
newPolys = vtkCellArray::New();
newPolys->Allocate(newLines->EstimateSize(numPolys,4));
outPD->CopyAllocate(pd,totPoints);
outCD->CopyAllocate(cd,numPolys);
//
// Create polygons
//
for (i=0; i<2; i++)
{
if ( dir[i] == 0 )
{
offset[i] = 1;
}
else if ( dir[i] == 1 )
{
offset[i] = dims[0];
}
else if ( dir[i] == 2 )
{
offset[i] = dims[0]*dims[1];
}
}
// create points whether visible or not. Makes coding easier but generates
// extra data.
for (pos=startIdx, j=0; j < (diff[dir[1]]+1); j++)
{
for (i=0; i < (diff[dir[0]]+1); i++)
{
idx = pos + i*offset[0];
input->GetPoint(idx, x);
ptIds[0] = newPts->InsertNextPoint(x);
outPD->CopyData(pd,idx,ptIds[0]);
}
pos += offset[1];
}
// create any polygon who has a visible vertex. To turn off a polygon, all
// vertices have to be blanked.
for (i=0; i<2; i++)
{
if ( dir[i] == 0 )
{
offset[i] = 1;
}
else if ( dir[i] == 1 )
{
offset[i] = (dims[0] - 1);
}
else if ( dir[i] == 2 )
{
offset[i] = (dims[0] - 1) * (dims[1] - 1);
}
}
for (pos=startCellIdx, j=0; j < diff[dir[1]]; j++)
{
for (i=0; i < diff[dir[0]]; i++)
{
idx = pos + i*offset[0];
ptIds[0] = i + j*(diff[dir[0]]+1);
ptIds[1] = ptIds[0] + 1;
ptIds[2] = ptIds[1] + diff[dir[0]] + 1;
ptIds[3] = ptIds[2] - 1;
cellId = newPolys->InsertNextCell(4,ptIds);
outCD->CopyData(cd,idx,cellId);
}
pos += offset[1];
}
break;
case 3: // ------------------- grab points in volume --------------
//
// Create data objects
//
for (i=0; i<3; i++)
{
diff[i] = extent[2*i+1] - extent[2*i];
}
totPoints = (diff[0]+1) * (diff[1]+1) * (diff[2]+1);
newPts = vtkPoints::New();
newPts->Allocate(totPoints);
newVerts = vtkCellArray::New();
newVerts->Allocate(newVerts->EstimateSize(totPoints,1));
outPD->CopyAllocate(pd,totPoints);
outCD->CopyAllocate(cd,totPoints);
//
// Create vertices
//
offset[0] = dims[0];
offset[1] = dims[0]*dims[1];
for (k=0; k < (diff[2]+1); k++)
{
for (j=0; j < (diff[1]+1); j++)
{
pos = startIdx + j*offset[0] + k*offset[1];
for (i=0; i < (diff[0]+1); i++)
{
input->GetPoint(pos+i, x);
ptIds[0] = newPts->InsertNextPoint(x);
outPD->CopyData(pd,pos+i,ptIds[0]);
cellId = newVerts->InsertNextCell(1,ptIds);
outCD->CopyData(cd,pos+i,cellId);
}
}
}
break; /* end this case */
} // switch
//
// Update self and release memory
//
if (newPts)
{
output->SetPoints(newPts);
newPts->Delete();
}
if (newVerts)
{
output->SetVerts(newVerts);
newVerts->Delete();
}
if (newLines)
{
output->SetLines(newLines);
newLines->Delete();
}
if (newPolys)
{
output->SetPolys(newPolys);
newPolys->Delete();
}
return 1;
}
// Specify (imin,imax, jmin,jmax, kmin,kmax) indices.
void vtkRectilinearGridGeometryFilter::SetExtent(int iMin, int iMax, int jMin,
int jMax, int kMin, int kMax)
{
int extent[6];
extent[0] = iMin;
extent[1] = iMax;
extent[2] = jMin;
extent[3] = jMax;
extent[4] = kMin;
extent[5] = kMax;
this->SetExtent(extent);
}
// Specify (imin,imax, jmin,jmax, kmin,kmax) indices in array form.
void vtkRectilinearGridGeometryFilter::SetExtent(int extent[6])
{
int i;
if ( extent[0] != this->Extent[0] || extent[1] != this->Extent[1] ||
extent[2] != this->Extent[2] || extent[3] != this->Extent[3] ||
extent[4] != this->Extent[4] || extent[5] != this->Extent[5] )
{
this->Modified();
for (i=0; i<3; i++)
{
if ( extent[2*i] < 0 )
{
extent[2*i] = 0;
}
if ( extent[2*i+1] < extent[2*i] )
{
extent[2*i+1] = extent[2*i];
}
this->Extent[2*i] = extent[2*i];
this->Extent[2*i+1] = extent[2*i+1];
}
}
}
int vtkRectilinearGridGeometryFilter::FillInputPortInformation(
int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkRectilinearGrid");
return 1;
}
void vtkRectilinearGridGeometryFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Extent: \n";
os << indent << " Imin,Imax: (" << this->Extent[0] << ", " << this->Extent[1] << ")\n";
os << indent << " Jmin,Jmax: (" << this->Extent[2] << ", " << this->Extent[3] << ")\n";
os << indent << " Kmin,Kmax: (" << this->Extent[4] << ", " << this->Extent[5] << ")\n";
}
<commit_msg>BUG: Need to handle empty input properly.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkRectilinearGridGeometryFilter.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkRectilinearGridGeometryFilter.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkInformation.h"
#include "vtkInformationVector.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"
#include "vtkPoints.h"
#include "vtkPolyData.h"
#include "vtkRectilinearGrid.h"
vtkStandardNewMacro(vtkRectilinearGridGeometryFilter);
// Construct with initial extent (0,100, 0,100, 0,0) (i.e., a k-plane).
vtkRectilinearGridGeometryFilter::vtkRectilinearGridGeometryFilter()
{
this->Extent[0] = 0;
this->Extent[1] = VTK_LARGE_INTEGER;
this->Extent[2] = 0;
this->Extent[3] = VTK_LARGE_INTEGER;
this->Extent[4] = 0;
this->Extent[5] = VTK_LARGE_INTEGER;
}
int vtkRectilinearGridGeometryFilter::RequestData(
vtkInformation *vtkNotUsed(request),
vtkInformationVector **inputVector,
vtkInformationVector *outputVector)
{
// get the info objects
vtkInformation *inInfo = inputVector[0]->GetInformationObject(0);
vtkInformation *outInfo = outputVector->GetInformationObject(0);
// get the input and output
vtkRectilinearGrid *input = vtkRectilinearGrid::SafeDownCast(
inInfo->Get(vtkDataObject::DATA_OBJECT()));
vtkPolyData *output = vtkPolyData::SafeDownCast(
outInfo->Get(vtkDataObject::DATA_OBJECT()));
int *dims, dimension, dir[3], diff[3];
int i, j, k, extent[6];
vtkIdType idx, startIdx, startCellIdx;
vtkIdType ptIds[4];
vtkIdType cellId;
vtkPoints *newPts=0;
vtkCellArray *newVerts=0;
vtkCellArray *newLines=0;
vtkCellArray *newPolys=0;
vtkIdType totPoints, pos;
int offset[3], numPolys;
double x[3];
vtkPointData *pd, *outPD;
vtkCellData *cd, *outCD;
vtkDebugMacro(<< "Extracting rectilinear points geometry");
if (input->GetNumberOfPoints() == 0)
{
vtkDebugMacro("Empty input");
return 1;
}
pd = input->GetPointData();
outPD = output->GetPointData();
outPD->CopyNormalsOff();
cd = input->GetCellData();
outCD = output->GetCellData();
dims = input->GetDimensions();
//
// Based on the dimensions of the rectilinear data,
// and the extent of the geometry,
// compute the combined extent plus the dimensionality of the data
//
for (dimension=3, i=0; i<3; i++)
{
extent[2*i] = this->Extent[2*i] < 0 ? 0 : this->Extent[2*i];
extent[2*i] = this->Extent[2*i] >= dims[i] ? dims[i]-1 : this->Extent[2*i];
extent[2*i+1] = this->Extent[2*i+1] >= dims[i] ? dims[i]-1 : this->Extent[2*i+1];
if ( extent[2*i+1] < extent[2*i] )
{
extent[2*i+1] = extent[2*i];
}
if ( (extent[2*i+1] - extent[2*i]) == 0 )
{
dimension--;
}
}
//
// Now create polygonal data based on dimension of data
//
startIdx = extent[0] + extent[2]*dims[0] + extent[4]*dims[0]*dims[1];
// The cell index is a bit more complicated at the boundaries
if (dims[0] == 1)
{
startCellIdx = extent[0];
}
else
{
startCellIdx = (extent[0] < dims[0] - 1) ? extent[0]
: extent[0]-1;
}
if (dims[1] == 1)
{
startCellIdx += extent[2]*(dims[0]-1);
}
else
{
startCellIdx += (extent[2] < dims[1] - 1) ? extent[2]*(dims[0]-1)
: (extent[2]-1)*(dims[0]-1);
}
if (dims[2] == 1)
{
startCellIdx += extent[4]*(dims[0]-1)*(dims[1]-1);
}
else
{
startCellIdx += (extent[4] < dims[2] - 1) ? extent[4]*(dims[0]-1)*(dims[1]-1)
: (extent[4]-1)*(dims[0]-1)*(dims[1]-1);
}
switch (dimension)
{
default:
break;
case 0: // --------------------- build point -----------------------
newPts = vtkPoints::New();
newPts->Allocate(1);
newVerts = vtkCellArray::New();
newVerts->Allocate(newVerts->EstimateSize(1,1));
outPD->CopyAllocate(pd,1);
outCD->CopyAllocate(cd,1);
ptIds[0] = newPts->InsertNextPoint(input->GetPoint(startIdx));
outPD->CopyData(pd,startIdx,ptIds[0]);
cellId = newVerts->InsertNextCell(1,ptIds);
outCD->CopyData(cd,startIdx,cellId);
break;
case 1: // --------------------- build line -----------------------
for (dir[0]=dir[1]=dir[2]=totPoints=0, i=0; i<3; i++)
{
if ( (diff[i] = extent[2*i+1] - extent[2*i]) > 0 )
{
dir[0] = i;
totPoints = diff[i] + 1;
break;
}
}
newPts = vtkPoints::New();
newPts->Allocate(totPoints);
newLines = vtkCellArray::New();
newLines->Allocate(newLines->EstimateSize(totPoints-1,2));
outPD->CopyAllocate(pd,totPoints);
outCD->CopyAllocate(cd,totPoints - 1);
//
// Load data
//
if ( dir[0] == 0 )
{
offset[0] = 1;
}
else if (dir[0] == 1)
{
offset[0] = dims[0];
}
else
{
offset[0] = dims[0]*dims[1];
}
for (i=0; i<totPoints; i++)
{
idx = startIdx + i*offset[0];
input->GetPoint(idx, x);
ptIds[0] = newPts->InsertNextPoint(x);
outPD->CopyData(pd,idx,ptIds[0]);
}
if ( dir[0] == 0 )
{
offset[0] = 1;
}
else if (dir[0] == 1)
{
offset[0] = dims[0] - 1;
}
else
{
offset[0] = (dims[0] - 1) * (dims[1] - 1);
}
for (i=0; i<(totPoints-1); i++)
{
idx = startCellIdx + i*offset[0];
ptIds[0] = i;
ptIds[1] = i + 1;
cellId = newLines->InsertNextCell(2,ptIds);
outCD->CopyData(cd,idx,cellId);
}
break;
case 2: // --------------------- build plane -----------------------
//
// Create the data objects
//
for (dir[0]=dir[1]=dir[2]=idx=0,i=0; i<3; i++)
{
if ( (diff[i] = extent[2*i+1] - extent[2*i]) != 0 )
{
dir[idx++] = i;
}
else
{
dir[2] = i;
}
}
totPoints = (diff[dir[0]]+1) * (diff[dir[1]]+1);
numPolys = diff[dir[0]] * diff[dir[1]];
newPts = vtkPoints::New();
newPts->Allocate(totPoints);
newPolys = vtkCellArray::New();
newPolys->Allocate(newLines->EstimateSize(numPolys,4));
outPD->CopyAllocate(pd,totPoints);
outCD->CopyAllocate(cd,numPolys);
//
// Create polygons
//
for (i=0; i<2; i++)
{
if ( dir[i] == 0 )
{
offset[i] = 1;
}
else if ( dir[i] == 1 )
{
offset[i] = dims[0];
}
else if ( dir[i] == 2 )
{
offset[i] = dims[0]*dims[1];
}
}
// create points whether visible or not. Makes coding easier but generates
// extra data.
for (pos=startIdx, j=0; j < (diff[dir[1]]+1); j++)
{
for (i=0; i < (diff[dir[0]]+1); i++)
{
idx = pos + i*offset[0];
input->GetPoint(idx, x);
ptIds[0] = newPts->InsertNextPoint(x);
outPD->CopyData(pd,idx,ptIds[0]);
}
pos += offset[1];
}
// create any polygon who has a visible vertex. To turn off a polygon, all
// vertices have to be blanked.
for (i=0; i<2; i++)
{
if ( dir[i] == 0 )
{
offset[i] = 1;
}
else if ( dir[i] == 1 )
{
offset[i] = (dims[0] - 1);
}
else if ( dir[i] == 2 )
{
offset[i] = (dims[0] - 1) * (dims[1] - 1);
}
}
for (pos=startCellIdx, j=0; j < diff[dir[1]]; j++)
{
for (i=0; i < diff[dir[0]]; i++)
{
idx = pos + i*offset[0];
ptIds[0] = i + j*(diff[dir[0]]+1);
ptIds[1] = ptIds[0] + 1;
ptIds[2] = ptIds[1] + diff[dir[0]] + 1;
ptIds[3] = ptIds[2] - 1;
cellId = newPolys->InsertNextCell(4,ptIds);
outCD->CopyData(cd,idx,cellId);
}
pos += offset[1];
}
break;
case 3: // ------------------- grab points in volume --------------
//
// Create data objects
//
for (i=0; i<3; i++)
{
diff[i] = extent[2*i+1] - extent[2*i];
}
totPoints = (diff[0]+1) * (diff[1]+1) * (diff[2]+1);
newPts = vtkPoints::New();
newPts->Allocate(totPoints);
newVerts = vtkCellArray::New();
newVerts->Allocate(newVerts->EstimateSize(totPoints,1));
outPD->CopyAllocate(pd,totPoints);
outCD->CopyAllocate(cd,totPoints);
//
// Create vertices
//
offset[0] = dims[0];
offset[1] = dims[0]*dims[1];
for (k=0; k < (diff[2]+1); k++)
{
for (j=0; j < (diff[1]+1); j++)
{
pos = startIdx + j*offset[0] + k*offset[1];
for (i=0; i < (diff[0]+1); i++)
{
input->GetPoint(pos+i, x);
ptIds[0] = newPts->InsertNextPoint(x);
outPD->CopyData(pd,pos+i,ptIds[0]);
cellId = newVerts->InsertNextCell(1,ptIds);
outCD->CopyData(cd,pos+i,cellId);
}
}
}
break; /* end this case */
} // switch
//
// Update self and release memory
//
if (newPts)
{
output->SetPoints(newPts);
newPts->Delete();
}
if (newVerts)
{
output->SetVerts(newVerts);
newVerts->Delete();
}
if (newLines)
{
output->SetLines(newLines);
newLines->Delete();
}
if (newPolys)
{
output->SetPolys(newPolys);
newPolys->Delete();
}
return 1;
}
// Specify (imin,imax, jmin,jmax, kmin,kmax) indices.
void vtkRectilinearGridGeometryFilter::SetExtent(int iMin, int iMax, int jMin,
int jMax, int kMin, int kMax)
{
int extent[6];
extent[0] = iMin;
extent[1] = iMax;
extent[2] = jMin;
extent[3] = jMax;
extent[4] = kMin;
extent[5] = kMax;
this->SetExtent(extent);
}
// Specify (imin,imax, jmin,jmax, kmin,kmax) indices in array form.
void vtkRectilinearGridGeometryFilter::SetExtent(int extent[6])
{
int i;
if ( extent[0] != this->Extent[0] || extent[1] != this->Extent[1] ||
extent[2] != this->Extent[2] || extent[3] != this->Extent[3] ||
extent[4] != this->Extent[4] || extent[5] != this->Extent[5] )
{
this->Modified();
for (i=0; i<3; i++)
{
if ( extent[2*i] < 0 )
{
extent[2*i] = 0;
}
if ( extent[2*i+1] < extent[2*i] )
{
extent[2*i+1] = extent[2*i];
}
this->Extent[2*i] = extent[2*i];
this->Extent[2*i+1] = extent[2*i+1];
}
}
}
int vtkRectilinearGridGeometryFilter::FillInputPortInformation(
int, vtkInformation *info)
{
info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkRectilinearGrid");
return 1;
}
void vtkRectilinearGridGeometryFilter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Extent: \n";
os << indent << " Imin,Imax: (" << this->Extent[0] << ", " << this->Extent[1] << ")\n";
os << indent << " Jmin,Jmax: (" << this->Extent[2] << ", " << this->Extent[3] << ")\n";
os << indent << " Kmin,Kmax: (" << this->Extent[4] << ", " << this->Extent[5] << ")\n";
}
<|endoftext|> |
<commit_before>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <thrust/system/cuda/error.h>
#include <thrust/system/cuda/detail/guarded_cuda_runtime_api.h>
namespace thrust
{
namespace system
{
error_code make_error_code(cuda_cub::errc::errc_t e)
{
return error_code(static_cast<int>(e), cuda_category());
} // end make_error_code()
error_condition make_error_condition(cuda_cub::errc::errc_t e)
{
return error_condition(static_cast<int>(e), cuda_category());
} // end make_error_condition()
namespace cuda_cub
{
namespace detail
{
class cuda_error_category
: public error_category
{
public:
inline cuda_error_category(void) {}
inline virtual const char *name(void) const
{
return "cuda";
}
inline virtual std::string message(int ev) const
{
static const std::string unknown_err("Unknown error");
const char *c_str = ::cudaGetErrorString(static_cast<cudaError_t>(ev));
return c_str ? std::string(c_str) : unknown_err;
}
inline virtual error_condition default_error_condition(int ev) const
{
using namespace cuda_cub::errc;
if(ev < ::cudaErrorApiFailureBase)
{
return make_error_condition(static_cast<errc_t>(ev));
}
return system_category().default_error_condition(ev);
}
}; // end cuda_error_category
} // end detail
} // end namespace cuda_cub
const error_category &cuda_category(void)
{
static const thrust::system::cuda_cub::detail::cuda_error_category result;
return result;
}
} // end namespace system
} // end namespace thrust
<commit_msg>Change `thrust::system_error` in the CUDA backend to print out its `cudaError_t` enumerator in addition to the diagnostic message.<commit_after>/*
* Copyright 2008-2013 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <thrust/system/cuda/error.h>
#include <thrust/system/cuda/detail/guarded_cuda_runtime_api.h>
namespace thrust
{
namespace system
{
error_code make_error_code(cuda_cub::errc::errc_t e)
{
return error_code(static_cast<int>(e), cuda_category());
} // end make_error_code()
error_condition make_error_condition(cuda_cub::errc::errc_t e)
{
return error_condition(static_cast<int>(e), cuda_category());
} // end make_error_condition()
namespace cuda_cub
{
namespace detail
{
class cuda_error_category
: public error_category
{
public:
inline cuda_error_category(void) {}
inline virtual const char *name(void) const
{
return "cuda";
}
inline virtual std::string message(int ev) const
{
char const* const unknown_str = "unknown error";
char const* const unknown_name = "cudaErrorUnknown";
char const* c_str = ::cudaGetErrorString(static_cast<cudaError_t>(ev));
char const* c_name = ::cudaGetErrorName(static_cast<cudaError_t>(ev));
return std::string(c_name ? c_name : unknown_name)
+ ": " + (c_str ? c_str : unknown_str);
}
inline virtual error_condition default_error_condition(int ev) const
{
using namespace cuda_cub::errc;
if(ev < ::cudaErrorApiFailureBase)
{
return make_error_condition(static_cast<errc_t>(ev));
}
return system_category().default_error_condition(ev);
}
}; // end cuda_error_category
} // end detail
} // end namespace cuda_cub
const error_category &cuda_category(void)
{
static const thrust::system::cuda_cub::detail::cuda_error_category result;
return result;
}
} // end namespace system
} // end namespace thrust
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2020 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.
*
****************************************************************************/
#include "autopilot_tester.h"
TEST_CASE("Fly forward in position control", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
tester.store_home();
tester.arm();
tester.fly_forward_in_posctl();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(60);
tester.wait_until_disarmed(until_disarmed_timeout);
tester.check_home_not_within(5.f);
}
TEST_CASE("Fly forward in altitude control", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
tester.store_home();
tester.arm();
tester.fly_forward_in_altctl();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(60);
tester.wait_until_disarmed(until_disarmed_timeout);
tester.check_home_not_within(5.f);
}
<commit_msg>mavsdk_tests: increase time for manual tests<commit_after>/****************************************************************************
*
* Copyright (c) 2020 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.
*
****************************************************************************/
#include "autopilot_tester.h"
TEST_CASE("Fly forward in position control", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
tester.store_home();
tester.arm();
tester.fly_forward_in_posctl();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(90);
tester.wait_until_disarmed(until_disarmed_timeout);
tester.check_home_not_within(5.f);
}
TEST_CASE("Fly forward in altitude control", "[multicopter][vtol]")
{
AutopilotTester tester;
tester.connect(connection_url);
tester.wait_until_ready();
tester.store_home();
tester.arm();
tester.fly_forward_in_altctl();
std::chrono::seconds until_disarmed_timeout = std::chrono::seconds(90);
tester.wait_until_disarmed(until_disarmed_timeout);
tester.check_home_not_within(5.f);
}
<|endoftext|> |
<commit_before>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2021 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/globebrowsing/src/globetranslation.h>
#include <modules/globebrowsing/globebrowsingmodule.h>
#include <modules/globebrowsing/src/renderableglobe.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/query/query.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/logging/logmanager.h>
namespace {
constexpr openspace::properties::Property::PropertyInfo GlobeInfo = {
"Globe",
"Attached Globe",
"The globe on which the longitude/latitude is specified"
};
constexpr openspace::properties::Property::PropertyInfo LongitudeInfo = {
"Longitude",
"Longitude",
"The longitude of the location on the globe's surface. The value can range from "
"-180 to 180, with negative values representing the western hemisphere of the "
"globe. The default value is 0.0"
};
constexpr openspace::properties::Property::PropertyInfo LatitudeInfo = {
"Latitude",
"Latitude",
"The latitude of the location on the globe's surface. The value can range from "
"-90 to 90, with negative values representing the southern hemisphere of the "
"globe. The default value is 0.0"
};
constexpr openspace::properties::Property::PropertyInfo AltitudeInfo = {
"Altitude",
"Altitude",
"The altitude in meters. "
"If the 'UseHeightmap' property is 'true', this is an offset from the actual "
"surface of the globe. If not, this is an offset from the reference ellipsoid."
"The default value is 0.0"
};
constexpr openspace::properties::Property::PropertyInfo UseHeightmapInfo = {
"UseHeightmap",
"Use Heightmap",
"If this value is 'true', the altitude specified in 'Altitude' will be treated "
"as an offset from the heightmap. Otherwise, it will be an offset from the "
"globe's reference ellipsoid. The default value is 'false'."
};
struct [[codegen::Dictionary(GlobeTranslation)]] Parameters {
// [[codegen::verbatim(GlobeInfo.description)]]
std::string globe
[[codegen::annotation("A valid scene graph node with a RenderableGlobe")]];
// [[codegen::verbatim(LongitudeInfo.description)]]
std::optional<double> longitude;
// [[codegen::verbatim(LatitudeInfo.description)]]
std::optional<double> latitude;
// [[codegen::verbatim(AltitudeInfo.description)]]
std::optional<double> altitude;
// [[codegen::verbatim(UseHeightmapInfo.description)]]
std::optional<bool> useHeightmap;
};
#include "globetranslation_codegen.cpp"
} // namespace
namespace openspace::globebrowsing {
documentation::Documentation GlobeTranslation::Documentation() {
return codegen::doc<Parameters>("space_translation_globetranslation");
}
GlobeTranslation::GlobeTranslation(const ghoul::Dictionary& dictionary)
: _globe(GlobeInfo)
, _longitude(LongitudeInfo, 0.0, -180.0, 180.0)
, _latitude(LatitudeInfo, 0.0, -90.0, 90.0)
, _altitude(AltitudeInfo, 0.0, 0.0, 1e12)
, _useHeightmap(UseHeightmapInfo, false)
{
const Parameters p = codegen::bake<Parameters>(dictionary);
_globe = p.globe;
_globe.onChange([this]() {
fillAttachedNode();
_positionIsDirty = true;
});
_longitude = p.longitude.value_or(_longitude);
_longitude.onChange([this]() { _positionIsDirty = true; });
addProperty(_longitude);
_latitude = p.latitude.value_or(_latitude);
_latitude.onChange([this]() { _positionIsDirty = true; });
addProperty(_latitude);
_altitude = p.altitude.value_or(_altitude);
_altitude.onChange([this]() { _positionIsDirty = true; });
addProperty(_altitude);
_useHeightmap = p.useHeightmap.value_or(_useHeightmap);
_useHeightmap.onChange([this]() { _positionIsDirty = true; });
addProperty(_useHeightmap);
}
void GlobeTranslation::fillAttachedNode() {
SceneGraphNode* n = sceneGraphNode(_globe);
if (n->renderable() && dynamic_cast<RenderableGlobe*>(n->renderable())) {
_attachedNode = dynamic_cast<RenderableGlobe*>(n->renderable());
}
else {
LERRORC(
"GlobeTranslation",
"Could not set attached node as it does not have a RenderableGlobe"
);
if (_attachedNode) {
// Reset the globe name to it's previous name
_globe = _attachedNode->identifier();
}
}
}
glm::dvec3 GlobeTranslation::position(const UpdateData&) const {
if (!_attachedNode) {
// @TODO(abock): The const cast should be removed on a redesign of the translation
// to make the position function not constant. Const casting this
// away is fine as the factories that create the translations don't
// create them as constant objects
const_cast<GlobeTranslation*>(this)->fillAttachedNode();
_positionIsDirty = true;
}
if (_useHeightmap) {
// If we use the heightmap, we have to compute the height every frame
_positionIsDirty = true;
}
if (!_positionIsDirty) {
return _position;
}
GlobeBrowsingModule& mod = *(global::moduleEngine->module<GlobeBrowsingModule>());
if (_useHeightmap) {
glm::vec3 groundPos = mod.cartesianCoordinatesFromGeo(
*_attachedNode,
_latitude,
_longitude,
0.0
);
SurfacePositionHandle h =
_attachedNode->calculateSurfacePositionHandle(groundPos);
_position = mod.cartesianCoordinatesFromGeo(
*_attachedNode,
_latitude,
_longitude,
h.heightToSurface + _altitude
);
return _position;
}
else {
_position = mod.cartesianCoordinatesFromGeo(
*_attachedNode,
_latitude,
_longitude,
_altitude
);
_positionIsDirty = false;
return _position;
}
}
} // namespace openspace::globebrowsing
<commit_msg>Add exponent to GlobeTranslation altitude slider<commit_after>/*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2021 *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy of this *
* software and associated documentation files (the "Software"), to deal in the Software *
* without restriction, including without limitation the rights to use, copy, modify, *
* merge, publish, distribute, sublicense, and/or sell copies of the Software, and to *
* permit persons to whom the Software is furnished to do so, subject to the following *
* conditions: *
* *
* The above copyright notice and this permission notice shall be included in all copies *
* or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *
* PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *
* OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *
****************************************************************************************/
#include <modules/globebrowsing/src/globetranslation.h>
#include <modules/globebrowsing/globebrowsingmodule.h>
#include <modules/globebrowsing/src/renderableglobe.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
#include <openspace/engine/globals.h>
#include <openspace/engine/moduleengine.h>
#include <openspace/scene/scenegraphnode.h>
#include <openspace/query/query.h>
#include <openspace/util/updatestructures.h>
#include <ghoul/logging/logmanager.h>
namespace {
constexpr openspace::properties::Property::PropertyInfo GlobeInfo = {
"Globe",
"Attached Globe",
"The globe on which the longitude/latitude is specified"
};
constexpr openspace::properties::Property::PropertyInfo LongitudeInfo = {
"Longitude",
"Longitude",
"The longitude of the location on the globe's surface. The value can range from "
"-180 to 180, with negative values representing the western hemisphere of the "
"globe. The default value is 0.0"
};
constexpr openspace::properties::Property::PropertyInfo LatitudeInfo = {
"Latitude",
"Latitude",
"The latitude of the location on the globe's surface. The value can range from "
"-90 to 90, with negative values representing the southern hemisphere of the "
"globe. The default value is 0.0"
};
constexpr openspace::properties::Property::PropertyInfo AltitudeInfo = {
"Altitude",
"Altitude",
"The altitude in meters. "
"If the 'UseHeightmap' property is 'true', this is an offset from the actual "
"surface of the globe. If not, this is an offset from the reference ellipsoid."
"The default value is 0.0"
};
constexpr openspace::properties::Property::PropertyInfo UseHeightmapInfo = {
"UseHeightmap",
"Use Heightmap",
"If this value is 'true', the altitude specified in 'Altitude' will be treated "
"as an offset from the heightmap. Otherwise, it will be an offset from the "
"globe's reference ellipsoid. The default value is 'false'."
};
struct [[codegen::Dictionary(GlobeTranslation)]] Parameters {
// [[codegen::verbatim(GlobeInfo.description)]]
std::string globe
[[codegen::annotation("A valid scene graph node with a RenderableGlobe")]];
// [[codegen::verbatim(LongitudeInfo.description)]]
std::optional<double> longitude;
// [[codegen::verbatim(LatitudeInfo.description)]]
std::optional<double> latitude;
// [[codegen::verbatim(AltitudeInfo.description)]]
std::optional<double> altitude;
// [[codegen::verbatim(UseHeightmapInfo.description)]]
std::optional<bool> useHeightmap;
};
#include "globetranslation_codegen.cpp"
} // namespace
namespace openspace::globebrowsing {
documentation::Documentation GlobeTranslation::Documentation() {
return codegen::doc<Parameters>("space_translation_globetranslation");
}
GlobeTranslation::GlobeTranslation(const ghoul::Dictionary& dictionary)
: _globe(GlobeInfo)
, _longitude(LongitudeInfo, 0.0, -180.0, 180.0)
, _latitude(LatitudeInfo, 0.0, -90.0, 90.0)
, _altitude(AltitudeInfo, 0.0, 0.0, 1e12)
, _useHeightmap(UseHeightmapInfo, false)
{
const Parameters p = codegen::bake<Parameters>(dictionary);
_globe = p.globe;
_globe.onChange([this]() {
fillAttachedNode();
_positionIsDirty = true;
});
_longitude = p.longitude.value_or(_longitude);
_longitude.onChange([this]() { _positionIsDirty = true; });
addProperty(_longitude);
_latitude = p.latitude.value_or(_latitude);
_latitude.onChange([this]() { _positionIsDirty = true; });
addProperty(_latitude);
_altitude = p.altitude.value_or(_altitude);
_altitude.setExponent(10.f);
_altitude.onChange([this]() { _positionIsDirty = true; });
addProperty(_altitude);
_useHeightmap = p.useHeightmap.value_or(_useHeightmap);
_useHeightmap.onChange([this]() { _positionIsDirty = true; });
addProperty(_useHeightmap);
}
void GlobeTranslation::fillAttachedNode() {
SceneGraphNode* n = sceneGraphNode(_globe);
if (n->renderable() && dynamic_cast<RenderableGlobe*>(n->renderable())) {
_attachedNode = dynamic_cast<RenderableGlobe*>(n->renderable());
}
else {
LERRORC(
"GlobeTranslation",
"Could not set attached node as it does not have a RenderableGlobe"
);
if (_attachedNode) {
// Reset the globe name to it's previous name
_globe = _attachedNode->identifier();
}
}
}
glm::dvec3 GlobeTranslation::position(const UpdateData&) const {
if (!_attachedNode) {
// @TODO(abock): The const cast should be removed on a redesign of the translation
// to make the position function not constant. Const casting this
// away is fine as the factories that create the translations don't
// create them as constant objects
const_cast<GlobeTranslation*>(this)->fillAttachedNode();
_positionIsDirty = true;
}
if (_useHeightmap) {
// If we use the heightmap, we have to compute the height every frame
_positionIsDirty = true;
}
if (!_positionIsDirty) {
return _position;
}
GlobeBrowsingModule& mod = *(global::moduleEngine->module<GlobeBrowsingModule>());
if (_useHeightmap) {
glm::vec3 groundPos = mod.cartesianCoordinatesFromGeo(
*_attachedNode,
_latitude,
_longitude,
0.0
);
SurfacePositionHandle h =
_attachedNode->calculateSurfacePositionHandle(groundPos);
_position = mod.cartesianCoordinatesFromGeo(
*_attachedNode,
_latitude,
_longitude,
h.heightToSurface + _altitude
);
return _position;
}
else {
_position = mod.cartesianCoordinatesFromGeo(
*_attachedNode,
_latitude,
_longitude,
_altitude
);
_positionIsDirty = false;
return _position;
}
}
} // namespace openspace::globebrowsing
<|endoftext|> |
<commit_before>#ifndef CLIENT_SERVER_INSTANCE_HPP
#define CLIENT_SERVER_INSTANCE_HPP
#include <atomic>
#include <thread>
#include <log.hpp>
#include "client_netcom.hpp"
#include "client_server_state.hpp"
#include <server_instance.hpp>
namespace config {
class state;
}
namespace client {
class server_instance {
std::string server_ip_ = "127.0.0.1";
std::uint16_t server_port_ = 4444;
std::string admin_password_;
bool is_admin_ = false;
std::atomic<bool> shutdown_;
template<typename T, typename ... Args>
T& set_state_(Args&& ... args) {
return set_state_(std::make_unique<T>(*this, std::forward<Args>(args)...));
}
template<typename T>
T& set_state_(std::unique_ptr<T> st) {
T& ret = *st;
if (current_state_) {
current_state_->transition_to(ret);
on_state_left.dispatch(*current_state_);
}
current_state_ = std::move(st);
on_state_entered.dispatch(ret);
return ret;
}
void set_state_(server::state_id sid);
protected:
config::state& conf_;
logger& out_;
netcom net_;
scoped_connection_pool pool_;
std::unique_ptr<server_state::base> current_state_;
public :
explicit server_instance(config::state& conf, logger& log);
logger& get_log();
netcom& get_netcom();
config::state& get_conf();
bool is_running() const;
void run();
void shutdown();
bool is_admin() const;
signal_t<void()> on_iter;
// Signals for connection with server
signal_t<void(std::string, std::uint16_t)> on_connecting;
signal_t<void()> on_connected;
signal_t<void(message::server::connection_failed::reason)> on_connection_failed;
signal_t<void()> on_disconnecting;
signal_t<void()> on_disconnected;
signal_t<void()> on_unexpected_disconnected;
// Signals for server state
signal_t<void(server_state::base&)> on_state_left;
signal_t<void(server_state::base&)> on_state_entered;
// Signals for administative rights
signal_t<void(request::server::admin_rights::failure::reason)> on_admin_rights_denied;
signal_t<void()> on_admin_rights_granted;
};
}
#ifndef NO_AUTOGEN
#include "autogen/packets/client_server_instance.hpp"
#endif
#endif
<commit_msg>Added debug output<commit_after>#ifndef CLIENT_SERVER_INSTANCE_HPP
#define CLIENT_SERVER_INSTANCE_HPP
#include <atomic>
#include <thread>
#include <log.hpp>
#include "client_netcom.hpp"
#include "client_server_state.hpp"
#include <server_instance.hpp>
namespace config {
class state;
}
namespace client {
class server_instance {
std::string server_ip_ = "127.0.0.1";
std::uint16_t server_port_ = 4444;
std::string admin_password_;
bool is_admin_ = false;
std::atomic<bool> shutdown_;
template<typename T, typename ... Args>
T& set_state_(Args&& ... args) {
return set_state_(std::make_unique<T>(*this, std::forward<Args>(args)...));
}
template<typename T>
T& set_state_(std::unique_ptr<T> st) {
T& ret = *st;
if (current_state_) {
current_state_->transition_to(ret);
on_state_left.dispatch(*current_state_);
}
current_state_ = std::move(st);
on_state_entered.dispatch(ret);
return ret;
}
void set_state_(server::state_id sid);
protected:
config::state& conf_;
logger& out_;
netcom net_;
scoped_connection_pool pool_;
std::unique_ptr<server_state::base> current_state_;
public :
explicit server_instance(config::state& conf, logger& log);
logger& get_log();
netcom& get_netcom();
config::state& get_conf();
bool is_running() const;
void run();
void shutdown();
bool is_admin() const;
signal_t<void()> on_iter;
// Signals for connection with server
signal_t<void(std::string, std::uint16_t)> on_connecting;
signal_t<void()> on_connected;
signal_t<void(message::server::connection_failed::reason)> on_connection_failed;
signal_t<void()> on_disconnecting;
signal_t<void()> on_disconnected;
signal_t<void()> on_unexpected_disconnected;
// Signals for server state
signal_t<void(server_state::base&)> on_state_left;
signal_t<void(server_state::base&)> on_state_entered;
// Signals for administative rights
signal_t<void(request::server::admin_rights::failure::reason)> on_admin_rights_denied;
signal_t<void()> on_admin_rights_granted;
// Signals for debugging
signal_t<void(std::string)> on_debug_message;
};
}
#ifndef NO_AUTOGEN
#include "autogen/packets/client_server_instance.hpp"
#endif
#endif
<|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. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TNamed //
// //
// 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>Doxygen<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
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;
}
<|endoftext|> |
<commit_before><commit_msg>planning: delete obstacle history trajectory points if too old<commit_after><|endoftext|> |
<commit_before>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018 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 <modules/qtwidgets/properties/colorlineedit.h>
#include <modules/qtwidgets/inviwoqtutils.h>
#include <inviwo/core/util/colorconversion.h>
#include <inviwo/core/util/assertion.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QRegularExpressionValidator>
#include <QRegularExpression>
#include <QLocale>
#include <QStyle>
#include <QEvent>
#include <QKeyEvent>
#include <warn/pop>
namespace inviwo {
ColorLineEdit::ColorLineEdit(QWidget *parent)
: QLineEdit(parent), validator_(new QRegularExpressionValidator(this)) {
setObjectName("ColorLineEdit");
updateRegExp();
setValidator(validator_);
connect(this, &QLineEdit::editingFinished, this, &ColorLineEdit::updateColor);
connect(this, &QLineEdit::textChanged, this, [&](const QString &) {
if (hasFocus()) {
setProperty("input", hasAcceptableInput() ? "valid" : "invalid");
style()->unpolish(this);
style()->polish(this);
}
});
}
void ColorLineEdit::setColor(ivec3 v, ColorRepresentation rep) {
color_ = dvec4(glm::clamp(v, ivec3(0), ivec3(255)), 1.0) / 255.0;
hasAlpha_ = false;
representation_ = rep;
updateText();
}
void ColorLineEdit::setColor(ivec4 v, ColorRepresentation rep) {
color_ = dvec4(glm::clamp(v, ivec4(0), ivec4(255))) / 255.0;
hasAlpha_ = true;
representation_ = rep;
updateText();
}
void ColorLineEdit::setColor(vec3 v, ColorRepresentation rep) { setColor(dvec3(v), rep); }
void ColorLineEdit::setColor(vec4 v, ColorRepresentation rep) { setColor(dvec4(v), rep); }
void ColorLineEdit::setColor(dvec3 v, ColorRepresentation rep) {
color_ = dvec4(v, 1.0);
hasAlpha_ = false;
representation_ = rep;
updateText();
}
void ColorLineEdit::setColor(dvec4 v, ColorRepresentation rep) {
color_ = v;
hasAlpha_ = true;
representation_ = rep;
updateText();
}
bool ColorLineEdit::hasAlpha() const { return hasAlpha_; }
void ColorLineEdit::setRepresentation(ColorRepresentation rep) {
if (rep != representation_) {
representation_ = rep;
updateText();
}
}
ColorLineEdit::ColorRepresentation ColorLineEdit::getRepresentation() const {
return representation_;
}
void ColorLineEdit::changeEvent(QEvent *event) {
switch (event->type()) {
case QEvent::LocaleChange:
updateRegExp();
break;
default:
break;
}
QLineEdit::changeEvent(event);
}
void ColorLineEdit::focusInEvent(QFocusEvent *event) {
setProperty("input", hasAcceptableInput() ? "valid" : "invalid");
style()->unpolish(this);
style()->polish(this);
QLineEdit::focusInEvent(event);
}
void ColorLineEdit::focusOutEvent(QFocusEvent *event) {
if (!hasAcceptableInput()) {
// discard changes if invalid
updateText();
}
setProperty("input", "none");
style()->unpolish(this);
style()->polish(this);
QLineEdit::focusOutEvent(event);
}
void ColorLineEdit::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Escape) {
// discard changes
updateText();
event->accept();
}
QLineEdit::keyPressEvent(event);
}
void ColorLineEdit::updateText() {
// create appropriate textual representation
QString str;
switch (representation_) {
case inviwo::ColorLineEdit::ColorRepresentation::Integer: {
auto c = util::glm_convert<ivec4>(color_ * 255.0);
str = QString("%1 %2 %3").arg(c.r).arg(c.g).arg(c.b);
if (hasAlpha_) {
str.append(QString(" %1").arg(c.a));
}
} break;
case inviwo::ColorLineEdit::ColorRepresentation::Hexadecimal:
if (hasAlpha_) {
str = utilqt::toQString(color::rgba2hex(vec4(color_)));
} else {
str = utilqt::toQString(color::rgb2hex(vec4(color_)));
}
break;
case inviwo::ColorLineEdit::ColorRepresentation::FloatingPoint:
default:
str = QString("%L1 %L2 %L3")
.arg(color_.r, 0, 'f', 3)
.arg(color_.g, 0, 'f', 3)
.arg(color_.b, 0, 'f', 3);
if (hasAlpha_) {
str.append(QString(" %L1").arg(color_.a, 0, 'f', 3));
}
break;
}
setText(str);
}
void ColorLineEdit::updateColor() {
QStringList tokens = text().split(QRegularExpression("\\s+"));
ivwAssert((tokens.size() == 1) || (tokens.size() == 3) || (tokens.size() == 4),
"Invalid number of color components");
ivwAssert((tokens.size() == 1) && tokens.front().startsWith("#"),
"Invalid single component (expected hex color code starting with '#')");
if (tokens.size() == 1) {
// it is a hex color code
color_ = color::hex2rgba(utilqt::fromQString(tokens.front()));
} else {
auto locale = QLocale::system();
dvec4 color(0.0);
for (int i = 0; i < tokens.size(); ++i) {
color[i] = locale.toDouble(tokens[i]);
}
// detect type of representation based on first number
// If it contains a decimal point it must be a float range color, i.e. [0,1]
if (!tokens.front().contains(locale.decimalPoint())) {
// assuming uint8 representation, renormalize values to [0,1]
color /= 255.0;
}
if (!hasAlpha_) {
color.a = 1.0;
}
color_ = color;
}
// ensure that line edit shows proper color representation
updateText();
emit colorChanged();
}
void ColorLineEdit::updateRegExp() {
QString decimalPoint = QLocale::system().decimalPoint();
if (decimalPoint == ".") {
decimalPoint = "\\.";
}
// create a regular expression matching either
// - hex color codes #RRGGBB, #RRGGBBAA, #RGB, #RGBA
// - uint8 colors (rgb, rgba)
// - double colors [0,1] (rgb, rgba)
validator_->setRegularExpression(QRegularExpression(
QString("((((?:^|\\s+)#([0-9a-fA-F]{2}){3,4})|((?:^|\\s+)#[0-9a-fA-F]{3,4}))"
"|(((?:^|\\s+)([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))){3,4})"
"|((?:^|\\s+)([-+]?(((\\d+%1\\d*)|(%1\\d+))+([eE][-+]?\\d+)?|\\d+([eE][-+]?\\d+))))"
"{3,4})\\s*")
.arg(decimalPoint)));
}
template <>
dvec3 ColorLineEdit::getColor<dvec3>() const {
return color_;
}
template <>
dvec4 ColorLineEdit::getColor<dvec4>() const {
return color_;
}
} // namespace inviwo
<commit_msg>QtWidgets: assertion fix<commit_after>/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2018 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 <modules/qtwidgets/properties/colorlineedit.h>
#include <modules/qtwidgets/inviwoqtutils.h>
#include <inviwo/core/util/colorconversion.h>
#include <inviwo/core/util/assertion.h>
#include <warn/push>
#include <warn/ignore/all>
#include <QRegularExpressionValidator>
#include <QRegularExpression>
#include <QLocale>
#include <QStyle>
#include <QEvent>
#include <QKeyEvent>
#include <warn/pop>
namespace inviwo {
ColorLineEdit::ColorLineEdit(QWidget *parent)
: QLineEdit(parent), validator_(new QRegularExpressionValidator(this)) {
setObjectName("ColorLineEdit");
updateRegExp();
setValidator(validator_);
connect(this, &QLineEdit::editingFinished, this, &ColorLineEdit::updateColor);
connect(this, &QLineEdit::textChanged, this, [&](const QString &) {
if (hasFocus()) {
setProperty("input", hasAcceptableInput() ? "valid" : "invalid");
style()->unpolish(this);
style()->polish(this);
}
});
}
void ColorLineEdit::setColor(ivec3 v, ColorRepresentation rep) {
color_ = dvec4(glm::clamp(v, ivec3(0), ivec3(255)), 1.0) / 255.0;
hasAlpha_ = false;
representation_ = rep;
updateText();
}
void ColorLineEdit::setColor(ivec4 v, ColorRepresentation rep) {
color_ = dvec4(glm::clamp(v, ivec4(0), ivec4(255))) / 255.0;
hasAlpha_ = true;
representation_ = rep;
updateText();
}
void ColorLineEdit::setColor(vec3 v, ColorRepresentation rep) { setColor(dvec3(v), rep); }
void ColorLineEdit::setColor(vec4 v, ColorRepresentation rep) { setColor(dvec4(v), rep); }
void ColorLineEdit::setColor(dvec3 v, ColorRepresentation rep) {
color_ = dvec4(v, 1.0);
hasAlpha_ = false;
representation_ = rep;
updateText();
}
void ColorLineEdit::setColor(dvec4 v, ColorRepresentation rep) {
color_ = v;
hasAlpha_ = true;
representation_ = rep;
updateText();
}
bool ColorLineEdit::hasAlpha() const { return hasAlpha_; }
void ColorLineEdit::setRepresentation(ColorRepresentation rep) {
if (rep != representation_) {
representation_ = rep;
updateText();
}
}
ColorLineEdit::ColorRepresentation ColorLineEdit::getRepresentation() const {
return representation_;
}
void ColorLineEdit::changeEvent(QEvent *event) {
switch (event->type()) {
case QEvent::LocaleChange:
updateRegExp();
break;
default:
break;
}
QLineEdit::changeEvent(event);
}
void ColorLineEdit::focusInEvent(QFocusEvent *event) {
setProperty("input", hasAcceptableInput() ? "valid" : "invalid");
style()->unpolish(this);
style()->polish(this);
QLineEdit::focusInEvent(event);
}
void ColorLineEdit::focusOutEvent(QFocusEvent *event) {
if (!hasAcceptableInput()) {
// discard changes if invalid
updateText();
}
setProperty("input", "none");
style()->unpolish(this);
style()->polish(this);
QLineEdit::focusOutEvent(event);
}
void ColorLineEdit::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Escape) {
// discard changes
updateText();
event->accept();
}
QLineEdit::keyPressEvent(event);
}
void ColorLineEdit::updateText() {
// create appropriate textual representation
QString str;
switch (representation_) {
case inviwo::ColorLineEdit::ColorRepresentation::Integer: {
auto c = util::glm_convert<ivec4>(color_ * 255.0);
str = QString("%1 %2 %3").arg(c.r).arg(c.g).arg(c.b);
if (hasAlpha_) {
str.append(QString(" %1").arg(c.a));
}
} break;
case inviwo::ColorLineEdit::ColorRepresentation::Hexadecimal:
if (hasAlpha_) {
str = utilqt::toQString(color::rgba2hex(vec4(color_)));
} else {
str = utilqt::toQString(color::rgb2hex(vec4(color_)));
}
break;
case inviwo::ColorLineEdit::ColorRepresentation::FloatingPoint:
default:
str = QString("%L1 %L2 %L3")
.arg(color_.r, 0, 'f', 3)
.arg(color_.g, 0, 'f', 3)
.arg(color_.b, 0, 'f', 3);
if (hasAlpha_) {
str.append(QString(" %L1").arg(color_.a, 0, 'f', 3));
}
break;
}
setText(str);
}
void ColorLineEdit::updateColor() {
QStringList tokens = text().split(QRegularExpression("\\s+"));
ivwAssert((tokens.size() == 1) || (tokens.size() == 3) || (tokens.size() == 4),
"Invalid number of color components");
ivwAssert((tokens.size() > 1) || ((tokens.size() == 1) && tokens.front().startsWith("#")),
"Invalid single component (expected hex color code starting with '#')");
if (tokens.size() == 1) {
// it is a hex color code
color_ = color::hex2rgba(utilqt::fromQString(tokens.front()));
} else {
auto locale = QLocale::system();
dvec4 color(0.0);
for (int i = 0; i < tokens.size(); ++i) {
color[i] = locale.toDouble(tokens[i]);
}
// detect type of representation based on first number
// If it contains a decimal point it must be a float range color, i.e. [0,1]
if (!tokens.front().contains(locale.decimalPoint())) {
// assuming uint8 representation, renormalize values to [0,1]
color /= 255.0;
}
if (!hasAlpha_) {
color.a = 1.0;
}
color_ = color;
}
// ensure that line edit shows proper color representation
updateText();
emit colorChanged();
}
void ColorLineEdit::updateRegExp() {
QString decimalPoint = QLocale::system().decimalPoint();
if (decimalPoint == ".") {
decimalPoint = "\\.";
}
// create a regular expression matching either
// - hex color codes #RRGGBB, #RRGGBBAA, #RGB, #RGBA
// - uint8 colors (rgb, rgba)
// - double colors [0,1] (rgb, rgba)
validator_->setRegularExpression(QRegularExpression(
QString("((((?:^|\\s+)#([0-9a-fA-F]{2}){3,4})|((?:^|\\s+)#[0-9a-fA-F]{3,4}))"
"|(((?:^|\\s+)([0-9]|([1-9][0-9])|(1[0-9][0-9])|(2[0-4][0-9])|(25[0-5]))){3,4})"
"|((?:^|\\s+)([-+]?(((\\d+%1\\d*)|(%1\\d+))+([eE][-+]?\\d+)?|\\d+([eE][-+]?\\d+))))"
"{3,4})\\s*")
.arg(decimalPoint)));
}
template <>
dvec3 ColorLineEdit::getColor<dvec3>() const {
return color_;
}
template <>
dvec4 ColorLineEdit::getColor<dvec4>() const {
return color_;
}
} // namespace inviwo
<|endoftext|> |
<commit_before>#include <gtest/gtest.h>
#include <limits>
#include <stan/math/prim/mat.hpp>
#include <string>
#include <vector>
template <typename T_m, typename T_a>
std::string pull_msg(Eigen::Matrix<T_m, -1, -1> &mat, T_a to_add) {
std::string message;
try {
stan::math::add_diag(mat, to_add);
} catch (std::domain_error &e) {
message = e.what();
} catch (...) {
message = "Threw the wrong exection";
}
return message;
}
TEST(MathPrimMat, double_mat_double_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
double jitter = 1e-10;
Eigen::MatrixXd out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, jitter));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1.0 + jitter, out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
TEST(MathPrimMat, double_mat_double_vec_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
Eigen::Matrix<double, 1, -1> to_add(2);
to_add << 0, 1;
Eigen::MatrixXd out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, to_add));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1 + to_add[i], out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
TEST(MathPrimMat, double_mat_double_rvec_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
Eigen::Matrix<double, -1, 1> to_add(2);
to_add << 0, 1;
Eigen::MatrixXd out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, to_add));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1 + to_add[i], out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
TEST(MathPrimMat, var_mat_double_vec_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
Eigen::Matrix<double, 1, -1> to_add(2);
to_add << 0, 1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, to_add));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1 + to_add[i], out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
TEST(MathPrimMat, var_mat_double_rvec_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
Eigen::Matrix<double, -1, 1> to_add(2);
to_add << 0, 1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, to_add));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1 + to_add[i], out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
<commit_msg>Update add_diag_test.cpp<commit_after>#include <gtest/gtest.h>
#include <stan/math/prim/mat.hpp>
#include <limits>
#include <string>
#include <vector>
template <typename T_m, typename T_a>
std::string pull_msg(Eigen::Matrix<T_m, -1, -1> &mat, T_a to_add) {
std::string message;
try {
stan::math::add_diag(mat, to_add);
} catch (std::domain_error &e) {
message = e.what();
} catch (...) {
message = "Threw the wrong exection";
}
return message;
}
TEST(MathPrimMat, double_mat_double_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
double jitter = 1e-10;
Eigen::MatrixXd out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, jitter));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1.0 + jitter, out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
TEST(MathPrimMat, double_mat_double_vec_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
Eigen::Matrix<double, 1, -1> to_add(2);
to_add << 0, 1;
Eigen::MatrixXd out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, to_add));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1 + to_add[i], out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
TEST(MathPrimMat, double_mat_double_rvec_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
Eigen::Matrix<double, -1, 1> to_add(2);
to_add << 0, 1;
Eigen::MatrixXd out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, to_add));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1 + to_add[i], out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
TEST(MathPrimMat, var_mat_double_vec_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
Eigen::Matrix<double, 1, -1> to_add(2);
to_add << 0, 1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, to_add));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1 + to_add[i], out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
TEST(MathPrimMat, var_mat_double_rvec_add_diag) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> mat(2, 3);
mat << 1, 1, 1, 1, 1, 1;
Eigen::Matrix<double, -1, 1> to_add(2);
to_add << 0, 1;
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> out_mat;
EXPECT_NO_THROW(out_mat = stan::math::add_diag(mat, to_add));
for (int i = 0; i < 2; ++i)
EXPECT_FLOAT_EQ(1 + to_add[i], out_mat(i, i))
<< "index: ( " << i << ", " << i << ")";
}
<|endoftext|> |
<commit_before>// Copyright 2021 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.
#include "google/cloud/iam/iam_credentials_client.h"
#include "google/cloud/spanner/admin/instance_admin_client.h"
#include "google/cloud/common_options.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/log.h"
#include "google/cloud/project.h"
#include "google/cloud/testing_util/example_driver.h"
#include "absl/strings/str_split.h"
#include "absl/time/time.h" // NOLINT(modernize-deprecated-headers)
#include <curl/curl.h>
#include <hello_world_grpc/hello_world.grpc.pb.h>
#include <chrono>
#include <stdexcept>
#include <thread>
namespace {
auto constexpr kTokenValidationPeriod = std::chrono::seconds(30);
extern "C" size_t CurlOnWriteData(char* ptr, size_t size, size_t nmemb,
void* userdata) {
auto* buffer = reinterpret_cast<std::string*>(userdata);
buffer->append(ptr, size * nmemb);
return size * nmemb;
}
google::cloud::StatusOr<std::string> HttpGet(std::string const& url,
std::string const& token) {
static auto const kCurlInit = [] {
return curl_global_init(CURL_GLOBAL_ALL);
}();
(void)kCurlInit;
auto const authorization = "Authorization: Bearer " + token;
using Headers = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>;
auto const headers = Headers{
curl_slist_append(nullptr, authorization.c_str()), curl_slist_free_all};
using CurlHandle = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
auto curl = CurlHandle(curl_easy_init(), curl_easy_cleanup);
if (!curl) throw std::runtime_error("Failed to create CurlHandle");
std::string buffer;
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers.get());
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &CurlOnWriteData);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
CURLcode code = curl_easy_perform(curl.get());
if (code != CURLE_OK) throw std::runtime_error(curl_easy_strerror(code));
long status; // NOLINT(google-runtime-int)
code = curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &status);
if (code != CURLE_OK) throw std::runtime_error(curl_easy_strerror(code));
// Handle common errors as Status, this is not exhaustive.
using ::google::cloud::Status;
using ::google::cloud::StatusCode;
if (status == 400) return Status(StatusCode::kInvalidArgument, buffer);
if (status == 401) return Status(StatusCode::kUnauthenticated, buffer);
if (status == 403) return Status(StatusCode::kPermissionDenied, buffer);
if (status >= 500) return Status(StatusCode::kInternal, buffer);
if (status < 200 || status >= 300) {
std::ostringstream os;
os << "HTTP error [" << status << "]: " << buffer;
return Status(StatusCode::kUnknown, buffer);
}
return buffer;
}
// TODO(#6185) - this should be done by the generated code
std::set<std::string> DefaultTracingComponents() {
return absl::StrSplit(
google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_ENABLE_TRACING")
.value_or(""),
',');
}
google::iam::credentials::v1::GenerateAccessTokenResponse UseAccessToken(
google::cloud::iam::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam;
return [](iam::IAMCredentialsClient client,
std::string const& service_account, std::string const& project_id) {
google::protobuf::Duration duration;
duration.set_seconds(
std::chrono::seconds(2 * kTokenValidationPeriod).count());
auto token = client.GenerateAccessToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*scope=*/{"https://www.googleapis.com/auth/cloud-platform"}, duration);
if (!token) throw std::runtime_error(token.status().message());
auto const expiration =
std::chrono::system_clock::from_time_t(token->expire_time().seconds());
std::cout << "Fetched token starting with "
<< token->access_token().substr(0, 8)
<< ", which will expire around " << absl::FromChrono(expiration)
<< std::endl;
auto credentials = grpc::CompositeChannelCredentials(
grpc::SslCredentials({}),
grpc::AccessTokenCredentials(token->access_token()));
google::cloud::spanner_admin::InstanceAdminClient admin(
google::cloud::spanner_admin::MakeInstanceAdminConnection(
google::cloud::Options{}.set<google::cloud::GrpcCredentialOption>(
credentials)));
for (auto instance :
admin.ListInstances(google::cloud::Project(project_id).FullName())) {
if (!instance) throw std::runtime_error(instance.status().message());
std::cout << "Instance: " << instance->name() << "\n";
}
return *std::move(token);
}(std::move(client), argv.at(0), argv.at(1));
}
void UseAccessTokenUntilExpired(google::cloud::iam::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
auto token = UseAccessToken(std::move(client), argv);
auto const project_id = argv.at(1);
auto const expiration =
std::chrono::system_clock::from_time_t(token.expire_time().seconds());
auto const deadline = expiration + 4 * kTokenValidationPeriod;
std::cout << "Running until " << absl::FromChrono(deadline)
<< ". This is past the access token expiration time ("
<< absl::FromChrono(expiration) << ")" << std::endl;
auto iteration = [=](bool expired) {
auto credentials = grpc::CompositeChannelCredentials(
grpc::SslCredentials({}),
grpc::AccessTokenCredentials(token.access_token()));
google::cloud::spanner_admin::InstanceAdminClient admin(
google::cloud::spanner_admin::MakeInstanceAdminConnection(
google::cloud::Options{}.set<google::cloud::GrpcCredentialOption>(
credentials)));
for (auto instance :
admin.ListInstances(google::cloud::Project(project_id).FullName())) {
// kUnauthenticated receives special treatment, it is the error received
// when the token expires.
if (instance.status().code() ==
google::cloud::StatusCode::kUnauthenticated) {
std::cout << "error [" << instance.status() << "]";
if (!expired) {
std::cout << ": unexpected, but could be a race condition."
<< " Trying again\n";
return true;
}
std::cout << ": this is expected as the token is expired\n";
return false;
}
if (!instance) throw std::runtime_error(instance.status().message());
std::cout << "success (" << instance->name() << ")\n";
return true;
}
return false;
};
for (auto now = std::chrono::system_clock::now(); now < deadline;
now = std::chrono::system_clock::now()) {
auto const expired = (now > expiration);
std::cout << absl::FromChrono(now) << ": running iteration with "
<< (expired ? "an expired" : "a valid") << " token ";
if (!iteration(expired)) break;
std::this_thread::sleep_for(kTokenValidationPeriod);
}
}
void UseIdTokenHttp(google::cloud::iam::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam;
[](iam::IAMCredentialsClient client, std::string const& service_account,
std::string const& hello_world_url) {
auto token = client.GenerateIdToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*audience=*/{hello_world_url},
/*include_email=*/true);
if (!token) throw std::runtime_error(token.status().message());
auto backoff = std::chrono::milliseconds(250);
for (int i = 0; i != 3; ++i) {
auto text = HttpGet(hello_world_url, token->token());
if (text.ok()) {
std::cout << "Server says: " << *text << "\n";
return;
}
std::this_thread::sleep_for(backoff);
backoff *= 2;
}
throw std::runtime_error("Could not contact server after 3 attempts");
}(std::move(client), argv.at(0), argv.at(1));
}
void UseIdTokenGrpc(google::cloud::iam::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam;
[](iam::IAMCredentialsClient client, std::string const& service_account,
std::string const& url) {
auto token = client.GenerateIdToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*audience=*/{url},
/*include_email=*/true);
if (!token) throw std::runtime_error(token.status().message());
auto const prefix = std::string{"https://"};
if (url.rfind(prefix, 0) != 0) {
throw std::runtime_error("Invalid URL" + url);
}
auto endpoint = url.substr(prefix.length()) + ":443";
auto credentials = grpc::CompositeChannelCredentials(
grpc::SslCredentials(grpc::SslCredentialsOptions{}),
grpc::AccessTokenCredentials(token->token()));
auto channel = grpc::CreateChannel(endpoint, credentials);
auto stub = google::cloud::examples::Greet::NewStub(channel);
auto request = google::cloud::examples::HelloRequest{};
auto backoff = std::chrono::milliseconds(250);
for (int i = 0; i != 3; ++i) {
grpc::ClientContext context;
google::cloud::examples::HelloResponse response;
auto status = stub->Hello(&context, request, &response);
if (status.ok()) {
std::cout << "Servers says: " << response.greeting() << "\n";
return;
}
std::cout << "Server returned error=" << status.error_code()
<< ", message=" << status.error_message() << "\n";
std::this_thread::sleep_for(backoff);
backoff *= 2;
}
throw std::runtime_error("Could not contact server after 3 attempts");
}(std::move(client), argv.at(0), argv.at(1));
}
void AutoRun(std::vector<std::string> const& argv) {
namespace examples = ::google::cloud::testing_util;
using ::google::cloud::internal::GetEnv;
if (!argv.empty()) throw examples::Usage{"auto"};
examples::CheckEnvironmentVariablesAreSet({
"GOOGLE_CLOUD_PROJECT",
"GOOGLE_CLOUD_CPP_IAM_TEST_SERVICE_ACCOUNT",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_SERVICE_ACCOUNT",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_HTTP_URL",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_GRPC_URL",
});
auto project_id = GetEnv("GOOGLE_CLOUD_PROJECT").value();
auto const test_iam_service_account =
GetEnv("GOOGLE_CLOUD_CPP_IAM_TEST_SERVICE_ACCOUNT").value_or("");
auto const hello_world_service_account =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_SERVICE_ACCOUNT").value_or("");
auto const hello_world_http_url =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_HTTP_URL").value_or("");
auto const hello_world_grpc_url =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_GRPC_URL").value_or("");
auto client = google::cloud::iam::IAMCredentialsClient(
google::cloud::iam::MakeIAMCredentialsConnection(
google::cloud::Options{}
.set<google::cloud::TracingComponentsOption>(
DefaultTracingComponents())
.set<google::cloud::GrpcTracingOptionsOption>(
// There are some credentials returned by RPCs. On an error
// these are printed. This truncates them, making the output
// safe, and yet useful for debugging.
google::cloud::TracingOptions{}.SetOptions(
"truncate_string_field_longer_than=32"))));
std::cout << "\nRunning UseAccessToken() example" << std::endl;
UseAccessToken(client, {test_iam_service_account, project_id});
std::cout << "\nRunning UseAccessTokenUntilExpired() example" << std::endl;
UseAccessTokenUntilExpired(client, {test_iam_service_account, project_id});
std::cout << "\nRunning UseIdTokenHttp() example" << std::endl;
UseIdTokenHttp(client, {hello_world_service_account, hello_world_http_url});
std::cout << "\nRunning UseIdTokenGrpc() example" << std::endl;
UseIdTokenGrpc(client, {hello_world_service_account, hello_world_grpc_url});
}
} // namespace
int main(int argc, char* argv[]) { // NOLINT(bugprone-exception-escape)
using ::google::cloud::testing_util::Example;
using ClientCommand = std::function<void(
google::cloud::iam::IAMCredentialsClient, std::vector<std::string> argv)>;
auto make_entry = [](std::string name,
std::vector<std::string> const& arg_names,
ClientCommand const& command) {
auto adapter = [=](std::vector<std::string> argv) {
if ((argv.size() == 1 && argv[0] == "--help") ||
argv.size() != arg_names.size()) {
std::string usage = name;
for (auto const& a : arg_names) usage += " <" + a + ">";
throw google::cloud::testing_util::Usage{std::move(usage)};
}
auto client = google::cloud::iam::IAMCredentialsClient(
google::cloud::iam::MakeIAMCredentialsConnection(
google::cloud::Options{}
.set<google::cloud::TracingComponentsOption>(
DefaultTracingComponents())));
command(client, std::move(argv));
};
return google::cloud::testing_util::Commands::value_type(std::move(name),
adapter);
};
Example example({
make_entry("use-access-token", {"service-account", "project-id"},
UseAccessToken),
make_entry("use-access-token-until-expired",
{"service-account", "project-id"}, UseAccessTokenUntilExpired),
make_entry("use-id-token-http",
{"service-account", "hello-world-http-url"}, UseIdTokenHttp),
make_entry("use-id-token-grpc",
{"service-account", "hello-world-http-url"}, UseIdTokenGrpc),
{"auto", AutoRun},
});
return example.Run(argc, argv);
}
<commit_msg>cleanup: miscellanous clang-tidy 14 fixes (#8718)<commit_after>// Copyright 2021 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.
#include "google/cloud/iam/iam_credentials_client.h"
#include "google/cloud/spanner/admin/instance_admin_client.h"
#include "google/cloud/common_options.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/internal/getenv.h"
#include "google/cloud/log.h"
#include "google/cloud/project.h"
#include "google/cloud/testing_util/example_driver.h"
#include "absl/strings/str_split.h"
#include "absl/time/time.h" // NOLINT(modernize-deprecated-headers)
#include <curl/curl.h>
#include <hello_world_grpc/hello_world.grpc.pb.h>
#include <chrono>
#include <stdexcept>
#include <thread>
namespace {
auto constexpr kTokenValidationPeriod = std::chrono::seconds(30);
extern "C" size_t CurlOnWriteData(char* ptr, size_t size, size_t nmemb,
void* userdata) {
auto* buffer = reinterpret_cast<std::string*>(userdata);
buffer->append(ptr, size * nmemb);
return size * nmemb;
}
google::cloud::StatusOr<std::string> HttpGet(std::string const& url,
std::string const& token) {
static auto const kCurlInit = [] {
return curl_global_init(CURL_GLOBAL_ALL);
}();
(void)kCurlInit;
auto const authorization = "Authorization: Bearer " + token;
using Headers = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>;
auto const headers = Headers{
curl_slist_append(nullptr, authorization.c_str()), curl_slist_free_all};
using CurlHandle = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
auto curl = CurlHandle(curl_easy_init(), curl_easy_cleanup);
if (!curl) throw std::runtime_error("Failed to create CurlHandle");
std::string buffer;
curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, headers.get());
curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &CurlOnWriteData);
curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
CURLcode code = curl_easy_perform(curl.get());
if (code != CURLE_OK) throw std::runtime_error(curl_easy_strerror(code));
long status; // NOLINT(google-runtime-int)
code = curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &status);
if (code != CURLE_OK) throw std::runtime_error(curl_easy_strerror(code));
// Handle common errors as Status, this is not exhaustive.
using ::google::cloud::Status;
using ::google::cloud::StatusCode;
if (status == 400) return Status(StatusCode::kInvalidArgument, buffer);
if (status == 401) return Status(StatusCode::kUnauthenticated, buffer);
if (status == 403) return Status(StatusCode::kPermissionDenied, buffer);
if (status >= 500) return Status(StatusCode::kInternal, buffer);
if (status < 200 || status >= 300) {
std::ostringstream os;
os << "HTTP error [" << status << "]: " << buffer;
return Status(StatusCode::kUnknown, buffer);
}
return buffer;
}
// TODO(#6185) - this should be done by the generated code
std::set<std::string> DefaultTracingComponents() {
return absl::StrSplit(
google::cloud::internal::GetEnv("GOOGLE_CLOUD_CPP_ENABLE_TRACING")
.value_or(""),
',');
}
google::iam::credentials::v1::GenerateAccessTokenResponse UseAccessToken(
google::cloud::iam::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam;
return [](iam::IAMCredentialsClient client,
std::string const& service_account, std::string const& project_id) {
google::protobuf::Duration duration;
duration.set_seconds(
std::chrono::seconds(2 * kTokenValidationPeriod).count());
auto token = client.GenerateAccessToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*scope=*/{"https://www.googleapis.com/auth/cloud-platform"}, duration);
if (!token) throw std::runtime_error(token.status().message());
auto const expiration =
std::chrono::system_clock::from_time_t(token->expire_time().seconds());
std::cout << "Fetched token starting with "
<< token->access_token().substr(0, 8)
<< ", which will expire around " << absl::FromChrono(expiration)
<< std::endl;
auto credentials = grpc::CompositeChannelCredentials(
grpc::SslCredentials({}),
grpc::AccessTokenCredentials(token->access_token()));
google::cloud::spanner_admin::InstanceAdminClient admin(
google::cloud::spanner_admin::MakeInstanceAdminConnection(
google::cloud::Options{}.set<google::cloud::GrpcCredentialOption>(
credentials)));
for (auto instance :
admin.ListInstances(google::cloud::Project(project_id).FullName())) {
if (!instance) throw std::runtime_error(instance.status().message());
std::cout << "Instance: " << instance->name() << "\n";
}
return *std::move(token);
}(std::move(client), argv.at(0), argv.at(1));
}
void UseAccessTokenUntilExpired(google::cloud::iam::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
auto token = UseAccessToken(std::move(client), argv);
auto const& project_id = argv.at(1);
auto const expiration =
std::chrono::system_clock::from_time_t(token.expire_time().seconds());
auto const deadline = expiration + 4 * kTokenValidationPeriod;
std::cout << "Running until " << absl::FromChrono(deadline)
<< ". This is past the access token expiration time ("
<< absl::FromChrono(expiration) << ")" << std::endl;
auto iteration = [=](bool expired) {
auto credentials = grpc::CompositeChannelCredentials(
grpc::SslCredentials({}),
grpc::AccessTokenCredentials(token.access_token()));
google::cloud::spanner_admin::InstanceAdminClient admin(
google::cloud::spanner_admin::MakeInstanceAdminConnection(
google::cloud::Options{}.set<google::cloud::GrpcCredentialOption>(
credentials)));
for (auto instance :
admin.ListInstances(google::cloud::Project(project_id).FullName())) {
// kUnauthenticated receives special treatment, it is the error received
// when the token expires.
if (instance.status().code() ==
google::cloud::StatusCode::kUnauthenticated) {
std::cout << "error [" << instance.status() << "]";
if (!expired) {
std::cout << ": unexpected, but could be a race condition."
<< " Trying again\n";
return true;
}
std::cout << ": this is expected as the token is expired\n";
return false;
}
if (!instance) throw std::runtime_error(instance.status().message());
std::cout << "success (" << instance->name() << ")\n";
return true;
}
return false;
};
for (auto now = std::chrono::system_clock::now(); now < deadline;
now = std::chrono::system_clock::now()) {
auto const expired = (now > expiration);
std::cout << absl::FromChrono(now) << ": running iteration with "
<< (expired ? "an expired" : "a valid") << " token ";
if (!iteration(expired)) break;
std::this_thread::sleep_for(kTokenValidationPeriod);
}
}
void UseIdTokenHttp(google::cloud::iam::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam;
[](iam::IAMCredentialsClient client, std::string const& service_account,
std::string const& hello_world_url) {
auto token = client.GenerateIdToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*audience=*/{hello_world_url},
/*include_email=*/true);
if (!token) throw std::runtime_error(token.status().message());
auto backoff = std::chrono::milliseconds(250);
for (int i = 0; i != 3; ++i) {
auto text = HttpGet(hello_world_url, token->token());
if (text.ok()) {
std::cout << "Server says: " << *text << "\n";
return;
}
std::this_thread::sleep_for(backoff);
backoff *= 2;
}
throw std::runtime_error("Could not contact server after 3 attempts");
}(std::move(client), argv.at(0), argv.at(1));
}
void UseIdTokenGrpc(google::cloud::iam::IAMCredentialsClient client,
std::vector<std::string> const& argv) {
namespace iam = ::google::cloud::iam;
[](iam::IAMCredentialsClient client, std::string const& service_account,
std::string const& url) {
auto token = client.GenerateIdToken(
"projects/-/serviceAccounts/" + service_account, /*delegates=*/{},
/*audience=*/{url},
/*include_email=*/true);
if (!token) throw std::runtime_error(token.status().message());
auto const prefix = std::string{"https://"};
if (url.rfind(prefix, 0) != 0) {
throw std::runtime_error("Invalid URL" + url);
}
auto endpoint = url.substr(prefix.length()) + ":443";
auto credentials = grpc::CompositeChannelCredentials(
grpc::SslCredentials(grpc::SslCredentialsOptions{}),
grpc::AccessTokenCredentials(token->token()));
auto channel = grpc::CreateChannel(endpoint, credentials);
auto stub = google::cloud::examples::Greet::NewStub(channel);
auto request = google::cloud::examples::HelloRequest{};
auto backoff = std::chrono::milliseconds(250);
for (int i = 0; i != 3; ++i) {
grpc::ClientContext context;
google::cloud::examples::HelloResponse response;
auto status = stub->Hello(&context, request, &response);
if (status.ok()) {
std::cout << "Servers says: " << response.greeting() << "\n";
return;
}
std::cout << "Server returned error=" << status.error_code()
<< ", message=" << status.error_message() << "\n";
std::this_thread::sleep_for(backoff);
backoff *= 2;
}
throw std::runtime_error("Could not contact server after 3 attempts");
}(std::move(client), argv.at(0), argv.at(1));
}
void AutoRun(std::vector<std::string> const& argv) {
namespace examples = ::google::cloud::testing_util;
using ::google::cloud::internal::GetEnv;
if (!argv.empty()) throw examples::Usage{"auto"};
examples::CheckEnvironmentVariablesAreSet({
"GOOGLE_CLOUD_PROJECT",
"GOOGLE_CLOUD_CPP_IAM_TEST_SERVICE_ACCOUNT",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_SERVICE_ACCOUNT",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_HTTP_URL",
"GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_GRPC_URL",
});
auto project_id = GetEnv("GOOGLE_CLOUD_PROJECT").value();
auto const test_iam_service_account =
GetEnv("GOOGLE_CLOUD_CPP_IAM_TEST_SERVICE_ACCOUNT").value_or("");
auto const hello_world_service_account =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_SERVICE_ACCOUNT").value_or("");
auto const hello_world_http_url =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_HTTP_URL").value_or("");
auto const hello_world_grpc_url =
GetEnv("GOOGLE_CLOUD_CPP_TEST_HELLO_WORLD_GRPC_URL").value_or("");
auto client = google::cloud::iam::IAMCredentialsClient(
google::cloud::iam::MakeIAMCredentialsConnection(
google::cloud::Options{}
.set<google::cloud::TracingComponentsOption>(
DefaultTracingComponents())
.set<google::cloud::GrpcTracingOptionsOption>(
// There are some credentials returned by RPCs. On an error
// these are printed. This truncates them, making the output
// safe, and yet useful for debugging.
google::cloud::TracingOptions{}.SetOptions(
"truncate_string_field_longer_than=32"))));
std::cout << "\nRunning UseAccessToken() example" << std::endl;
UseAccessToken(client, {test_iam_service_account, project_id});
std::cout << "\nRunning UseAccessTokenUntilExpired() example" << std::endl;
UseAccessTokenUntilExpired(client, {test_iam_service_account, project_id});
std::cout << "\nRunning UseIdTokenHttp() example" << std::endl;
UseIdTokenHttp(client, {hello_world_service_account, hello_world_http_url});
std::cout << "\nRunning UseIdTokenGrpc() example" << std::endl;
UseIdTokenGrpc(client, {hello_world_service_account, hello_world_grpc_url});
}
} // namespace
int main(int argc, char* argv[]) { // NOLINT(bugprone-exception-escape)
using ::google::cloud::testing_util::Example;
using ClientCommand = std::function<void(
google::cloud::iam::IAMCredentialsClient, std::vector<std::string> argv)>;
auto make_entry = [](std::string name,
std::vector<std::string> const& arg_names,
ClientCommand const& command) {
auto adapter = [=](std::vector<std::string> argv) {
if ((argv.size() == 1 && argv[0] == "--help") ||
argv.size() != arg_names.size()) {
std::string usage = name;
for (auto const& a : arg_names) usage += " <" + a + ">";
throw google::cloud::testing_util::Usage{std::move(usage)};
}
auto client = google::cloud::iam::IAMCredentialsClient(
google::cloud::iam::MakeIAMCredentialsConnection(
google::cloud::Options{}
.set<google::cloud::TracingComponentsOption>(
DefaultTracingComponents())));
command(client, std::move(argv));
};
return google::cloud::testing_util::Commands::value_type(std::move(name),
adapter);
};
Example example({
make_entry("use-access-token", {"service-account", "project-id"},
UseAccessToken),
make_entry("use-access-token-until-expired",
{"service-account", "project-id"}, UseAccessTokenUntilExpired),
make_entry("use-id-token-http",
{"service-account", "hello-world-http-url"}, UseIdTokenHttp),
make_entry("use-id-token-grpc",
{"service-account", "hello-world-http-url"}, UseIdTokenGrpc),
{"auto", AutoRun},
});
return example.Run(argc, argv);
}
<|endoftext|> |
<commit_before>#include "OneDMomentumFriction.h"
#include "EquationOfState.h"
template<>
InputParameters validParams<OneDMomentumFriction>()
{
InputParameters params = validParams<Kernel>();
// Required coupled variables
params.addRequiredCoupledVar("rhoA", "density term");
params.addRequiredCoupledVar("rhouA", "momentum term");
params.addRequiredCoupledVar("u", "velocity");
params.addRequiredCoupledVar("hydraulic_diameter", "The hydraulic diameter. Depends on A(x).");
return params;
}
OneDMomentumFriction::OneDMomentumFriction(const std::string & name, InputParameters parameters) :
Kernel(name, parameters),
_u_vel(coupledValue("u")),
_rhouA(coupledValue("rhouA")),
_hydraulic_diameter(coupledValue("hydraulic_diameter")),
_rhoA_var_number(coupled("rhoA")),
_friction(getMaterialProperty<Real>("friction"))
{
}
Real
OneDMomentumFriction::computeQpResidual()
{
// Contribution due to friction.
return (0.5*_friction[_qp]/_hydraulic_diameter[_qp]) * _rhouA[_qp] * std::abs(_u_vel[_qp]) * _test[_i][_qp];
}
Real
OneDMomentumFriction::computeQpJacobian()
{
return (0.5*_friction[_qp]/_hydraulic_diameter[_qp]) * 2. * std::abs(_u_vel[_qp]) * _phi[_j][_qp] * _test[_i][_qp];
}
Real
OneDMomentumFriction::computeQpOffDiagJacobian(unsigned int jvar)
{
if (jvar == _rhoA_var_number)
return (0.5*_friction[_qp]/_hydraulic_diameter[_qp]) * (-_u_vel[_qp]) * std::abs(_u_vel[_qp]) * _phi[_j][_qp] * _test[_i][_qp];
else
return 0.;
}
<commit_msg>Removing EoS system from the code<commit_after>#include "OneDMomentumFriction.h"
template<>
InputParameters validParams<OneDMomentumFriction>()
{
InputParameters params = validParams<Kernel>();
// Required coupled variables
params.addRequiredCoupledVar("rhoA", "density term");
params.addRequiredCoupledVar("rhouA", "momentum term");
params.addRequiredCoupledVar("u", "velocity");
params.addRequiredCoupledVar("hydraulic_diameter", "The hydraulic diameter. Depends on A(x).");
return params;
}
OneDMomentumFriction::OneDMomentumFriction(const std::string & name, InputParameters parameters) :
Kernel(name, parameters),
_u_vel(coupledValue("u")),
_rhouA(coupledValue("rhouA")),
_hydraulic_diameter(coupledValue("hydraulic_diameter")),
_rhoA_var_number(coupled("rhoA")),
_friction(getMaterialProperty<Real>("friction"))
{
}
Real
OneDMomentumFriction::computeQpResidual()
{
// Contribution due to friction.
return (0.5*_friction[_qp]/_hydraulic_diameter[_qp]) * _rhouA[_qp] * std::abs(_u_vel[_qp]) * _test[_i][_qp];
}
Real
OneDMomentumFriction::computeQpJacobian()
{
return (0.5*_friction[_qp]/_hydraulic_diameter[_qp]) * 2. * std::abs(_u_vel[_qp]) * _phi[_j][_qp] * _test[_i][_qp];
}
Real
OneDMomentumFriction::computeQpOffDiagJacobian(unsigned int jvar)
{
if (jvar == _rhoA_var_number)
return (0.5*_friction[_qp]/_hydraulic_diameter[_qp]) * (-_u_vel[_qp]) * std::abs(_u_vel[_qp]) * _phi[_j][_qp] * _test[_i][_qp];
else
return 0.;
}
<|endoftext|> |
<commit_before>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/core/collision-validation.hh>
#include <hpp/fcl/collision.h>
#include <pinocchio/multibody/geometry.hpp>
#include <hpp/pinocchio/body.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/collision-object.hh>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/core/relative-motion.hh>
#include <hpp/core/collision-validation-report.hh>
#include <hpp/core/relative-motion.hh>
namespace hpp {
namespace core {
namespace {
inline std::size_t collide (const CollisionPairs_t::const_iterator& _colPair,
const fcl::CollisionRequest& req, fcl::CollisionResult& res) {
res.clear();
return fcl::collide (
_colPair->first ->fcl (),
_colPair->second->fcl (),
req, res);
}
inline bool collide (const CollisionPairs_t& pairs,
const fcl::CollisionRequest& req, fcl::CollisionResult& res,
CollisionPairs_t::const_iterator& _col) {
for (_col = pairs.begin (); _col != pairs.end (); ++_col)
if (collide (_col, req, res) != 0)
return true;
return false;
}
inline CollisionPair_t makeCollisionPair (const DevicePtr_t& d, const se3::CollisionPair& p)
{
CollisionObjectConstPtr_t o1 (new pinocchio::CollisionObject(d, p.first));
CollisionObjectConstPtr_t o2 (new pinocchio::CollisionObject(d, p.second));
return CollisionPair_t (o1, o2);
}
}
CollisionValidationPtr_t CollisionValidation::create
(const DevicePtr_t& robot)
{
CollisionValidation* ptr = new CollisionValidation (robot);
return CollisionValidationPtr_t (ptr);
}
bool CollisionValidation::validate (const Configuration_t& config,
ValidationReportPtr_t& validationReport)
{
robot_->currentConfiguration (config);
robot_->computeForwardKinematics ();
robot_->updateGeometryPlacements ();
fcl::CollisionResult collisionResult;
CollisionPairs_t::const_iterator _col;
if(computeAllContacts_){
hppDout(notice,"collision validation, computeAllContacts, num of pairs : "<<collisionPairs_.size());
bool firstCollision(true);
AllCollisionsValidationReportPtr_t allReport;
for (CollisionPairs_t::const_iterator _col = collisionPairs_.begin (); _col != collisionPairs_.end (); ++_col){
fcl::CollisionResult collisionResult;
if (collide (_col, collisionRequest_, collisionResult) != 0){
hppDout(notice,"in collision : "<<_col->first->name()<<" / "<<_col->second->name());
CollisionValidationReportPtr_t report (new CollisionValidationReport);
report->object1 = _col->first;
report->object2 = _col->second;
report->result = collisionResult;
if(firstCollision){
allReport = AllCollisionsValidationReportPtr_t(new AllCollisionsValidationReport);
allReport->object1 = _col->first;
allReport->object2 = _col->second;
allReport->result = collisionResult;
firstCollision = false;
}
allReport->collisionReports.push_back(report);
}
}
validationReport=allReport;
return firstCollision;
}else{
fcl::CollisionResult collisionResult;
if (collide (collisionPairs_, collisionRequest_, collisionResult, _col)
||
( checkParameterized_ &&
collide (parameterizedPairs_, collisionRequest_, collisionResult, _col)
)) {
CollisionValidationReportPtr_t report (new CollisionValidationReport);
report->object1 = _col->first;
report->object2 = _col->second;
report->result = collisionResult;
validationReport = report;
return false;
}
return true;
}
}
void CollisionValidation::addObstacle (const CollisionObjectConstPtr_t& object)
{
const JointVector_t& jv = robot_->getJointVector ();
for (JointVector_t::const_iterator it = jv.begin (); it != jv.end ();
++it) {
JointPtr_t joint = JointPtr_t (new Joint(**it));
addObstacleToJoint (object, joint, false);
}
}
void CollisionValidation::addObstacleToJoint (const CollisionObjectConstPtr_t& object,
const JointPtr_t& joint, const bool includeChildren)
{
BodyPtr_t body = joint->linkedBody ();
if (body) {
const ObjectVector_t& bodyObjects = body->innerObjects ();
for (ObjectVector_t::const_iterator itInner = bodyObjects.begin ();
itInner != bodyObjects.end (); ++itInner) {
// TODO: check the objects are not in same joint
collisionPairs_.push_back (CollisionPair_t (*itInner, object));
}
}
if(includeChildren) {
for(std::size_t i=0; i<joint->numberChildJoints(); ++i){
addObstacleToJoint (object, joint->childJoint(i),includeChildren);
}
}
}
void CollisionValidation::removeObstacleFromJoint
(const JointPtr_t& joint, const CollisionObjectConstPtr_t& obstacle)
{
BodyPtr_t body = joint->linkedBody ();
if (body) {
const ObjectVector_t& bodyObjects = body->innerObjects ();
for (ObjectVector_t::const_iterator itInner = bodyObjects.begin ();
itInner != bodyObjects.end (); ++itInner) {
CollisionPair_t colPair (*itInner, obstacle);
std::size_t nbDelPairs = 0;
CollisionPairs_t::iterator _collisionPair (collisionPairs_.begin());
while ( (_collisionPair = std::find (_collisionPair, collisionPairs_.end(), colPair))
!= collisionPairs_.end()) {
_collisionPair = collisionPairs_.erase (_collisionPair);
++nbDelPairs;
}
if (nbDelPairs == 0) {
std::ostringstream oss;
oss << "CollisionValidation::removeObstacleFromJoint: obstacle \""
<< obstacle->name () <<
"\" is not registered as obstacle for joint \"" << joint->name ()
<< "\".";
throw std::runtime_error (oss.str ());
} else if (nbDelPairs >= 2) {
hppDout (error, "obstacle "<< obstacle->name () <<
" was registered " << nbDelPairs
<< " times as obstacle for joint " << joint->name ()
<< ".");
}
}
}
}
void CollisionValidation::filterCollisionPairs (const RelativeMotion::matrix_type& matrix)
{
// Loop over collision pairs and remove disabled ones.
CollisionPairs_t::iterator _colPair = collisionPairs_.begin ();
se3::JointIndex j1, j2;
fcl::CollisionResult unused;
while (_colPair != collisionPairs_.end ()) {
j1 = _colPair->first ->jointIndex();
j2 = _colPair->second->jointIndex();
switch (matrix(j1, j2)) {
case RelativeMotion::Parameterized:
hppDout(info, "Parameterized collision pairs between "
<< _colPair->first ->name() << " and "
<< _colPair->second->name());
parameterizedPairs_.push_back (*_colPair);
_colPair = collisionPairs_.erase (_colPair);
break;
case RelativeMotion::Constrained:
hppDout(info, "Disabling collision between "
<< _colPair->first ->name() << " and "
<< _colPair->second->name());
if (collide (_colPair, collisionRequest_, unused) != 0) {
hppDout(warning, "Disabling collision detection between two "
"body in collision.");
}
disabledPairs_.push_back (*_colPair);
_colPair = collisionPairs_.erase (_colPair);
break;
case RelativeMotion::Unconstrained: ++_colPair; break;
default:
hppDout (warning, "RelativeMotionType not understood");
++_colPair;
break;
}
}
}
CollisionValidation::CollisionValidation (const DevicePtr_t& robot) :
collisionRequest_(1, false, false, 1, false, true, fcl::GST_INDEP),
robot_ (robot),
parameterizedPairs_(), disabledPairs_(),
checkParameterized_(false),
computeAllContacts_(false)
{
const se3::GeometryModel& model = robot->geomModel();
const se3::GeometryData & data = robot->geomData();
for (std::size_t i = 0; i < model.collisionPairs.size(); ++i)
if (data.activeCollisionPairs[i])
collisionPairs_.push_back(
makeCollisionPair(robot, model.collisionPairs[i])
);
}
} // namespace core
} // namespace hpp
<commit_msg>collision-validation : remove redundant variable declaration<commit_after>//
// Copyright (c) 2014 CNRS
// Authors: Florent Lamiraux
//
// This file is part of hpp-core
// hpp-core 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
// 3 of the License, or (at your option) any later version.
//
// hpp-core 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-core If not, see
// <http://www.gnu.org/licenses/>.
#include <hpp/core/collision-validation.hh>
#include <hpp/fcl/collision.h>
#include <pinocchio/multibody/geometry.hpp>
#include <hpp/pinocchio/body.hh>
#include <hpp/pinocchio/device.hh>
#include <hpp/pinocchio/collision-object.hh>
#include <hpp/pinocchio/configuration.hh>
#include <hpp/core/relative-motion.hh>
#include <hpp/core/collision-validation-report.hh>
#include <hpp/core/relative-motion.hh>
namespace hpp {
namespace core {
namespace {
inline std::size_t collide (const CollisionPairs_t::const_iterator& _colPair,
const fcl::CollisionRequest& req, fcl::CollisionResult& res) {
res.clear();
return fcl::collide (
_colPair->first ->fcl (),
_colPair->second->fcl (),
req, res);
}
inline bool collide (const CollisionPairs_t& pairs,
const fcl::CollisionRequest& req, fcl::CollisionResult& res,
CollisionPairs_t::const_iterator& _col) {
for (_col = pairs.begin (); _col != pairs.end (); ++_col)
if (collide (_col, req, res) != 0)
return true;
return false;
}
inline CollisionPair_t makeCollisionPair (const DevicePtr_t& d, const se3::CollisionPair& p)
{
CollisionObjectConstPtr_t o1 (new pinocchio::CollisionObject(d, p.first));
CollisionObjectConstPtr_t o2 (new pinocchio::CollisionObject(d, p.second));
return CollisionPair_t (o1, o2);
}
}
CollisionValidationPtr_t CollisionValidation::create
(const DevicePtr_t& robot)
{
CollisionValidation* ptr = new CollisionValidation (robot);
return CollisionValidationPtr_t (ptr);
}
bool CollisionValidation::validate (const Configuration_t& config,
ValidationReportPtr_t& validationReport)
{
robot_->currentConfiguration (config);
robot_->computeForwardKinematics ();
robot_->updateGeometryPlacements ();
fcl::CollisionResult collisionResult;
CollisionPairs_t::const_iterator _col;
if(computeAllContacts_){
hppDout(notice,"collision validation, computeAllContacts, num of pairs : "<<collisionPairs_.size());
bool firstCollision(true);
AllCollisionsValidationReportPtr_t allReport;
for (CollisionPairs_t::const_iterator _col = collisionPairs_.begin (); _col != collisionPairs_.end (); ++_col){
if (collide (_col, collisionRequest_, collisionResult) != 0){
hppDout(notice,"in collision : "<<_col->first->name()<<" / "<<_col->second->name());
CollisionValidationReportPtr_t report (new CollisionValidationReport);
report->object1 = _col->first;
report->object2 = _col->second;
report->result = collisionResult;
if(firstCollision){
allReport = AllCollisionsValidationReportPtr_t(new AllCollisionsValidationReport);
allReport->object1 = _col->first;
allReport->object2 = _col->second;
allReport->result = collisionResult;
firstCollision = false;
}
allReport->collisionReports.push_back(report);
}
}
validationReport=allReport;
return firstCollision;
}else{
fcl::CollisionResult collisionResult;
if (collide (collisionPairs_, collisionRequest_, collisionResult, _col)
||
( checkParameterized_ &&
collide (parameterizedPairs_, collisionRequest_, collisionResult, _col)
)) {
CollisionValidationReportPtr_t report (new CollisionValidationReport);
report->object1 = _col->first;
report->object2 = _col->second;
report->result = collisionResult;
validationReport = report;
return false;
}
return true;
}
}
void CollisionValidation::addObstacle (const CollisionObjectConstPtr_t& object)
{
const JointVector_t& jv = robot_->getJointVector ();
for (JointVector_t::const_iterator it = jv.begin (); it != jv.end ();
++it) {
JointPtr_t joint = JointPtr_t (new Joint(**it));
addObstacleToJoint (object, joint, false);
}
}
void CollisionValidation::addObstacleToJoint (const CollisionObjectConstPtr_t& object,
const JointPtr_t& joint, const bool includeChildren)
{
BodyPtr_t body = joint->linkedBody ();
if (body) {
const ObjectVector_t& bodyObjects = body->innerObjects ();
for (ObjectVector_t::const_iterator itInner = bodyObjects.begin ();
itInner != bodyObjects.end (); ++itInner) {
// TODO: check the objects are not in same joint
collisionPairs_.push_back (CollisionPair_t (*itInner, object));
}
}
if(includeChildren) {
for(std::size_t i=0; i<joint->numberChildJoints(); ++i){
addObstacleToJoint (object, joint->childJoint(i),includeChildren);
}
}
}
void CollisionValidation::removeObstacleFromJoint
(const JointPtr_t& joint, const CollisionObjectConstPtr_t& obstacle)
{
BodyPtr_t body = joint->linkedBody ();
if (body) {
const ObjectVector_t& bodyObjects = body->innerObjects ();
for (ObjectVector_t::const_iterator itInner = bodyObjects.begin ();
itInner != bodyObjects.end (); ++itInner) {
CollisionPair_t colPair (*itInner, obstacle);
std::size_t nbDelPairs = 0;
CollisionPairs_t::iterator _collisionPair (collisionPairs_.begin());
while ( (_collisionPair = std::find (_collisionPair, collisionPairs_.end(), colPair))
!= collisionPairs_.end()) {
_collisionPair = collisionPairs_.erase (_collisionPair);
++nbDelPairs;
}
if (nbDelPairs == 0) {
std::ostringstream oss;
oss << "CollisionValidation::removeObstacleFromJoint: obstacle \""
<< obstacle->name () <<
"\" is not registered as obstacle for joint \"" << joint->name ()
<< "\".";
throw std::runtime_error (oss.str ());
} else if (nbDelPairs >= 2) {
hppDout (error, "obstacle "<< obstacle->name () <<
" was registered " << nbDelPairs
<< " times as obstacle for joint " << joint->name ()
<< ".");
}
}
}
}
void CollisionValidation::filterCollisionPairs (const RelativeMotion::matrix_type& matrix)
{
// Loop over collision pairs and remove disabled ones.
CollisionPairs_t::iterator _colPair = collisionPairs_.begin ();
se3::JointIndex j1, j2;
fcl::CollisionResult unused;
while (_colPair != collisionPairs_.end ()) {
j1 = _colPair->first ->jointIndex();
j2 = _colPair->second->jointIndex();
switch (matrix(j1, j2)) {
case RelativeMotion::Parameterized:
hppDout(info, "Parameterized collision pairs between "
<< _colPair->first ->name() << " and "
<< _colPair->second->name());
parameterizedPairs_.push_back (*_colPair);
_colPair = collisionPairs_.erase (_colPair);
break;
case RelativeMotion::Constrained:
hppDout(info, "Disabling collision between "
<< _colPair->first ->name() << " and "
<< _colPair->second->name());
if (collide (_colPair, collisionRequest_, unused) != 0) {
hppDout(warning, "Disabling collision detection between two "
"body in collision.");
}
disabledPairs_.push_back (*_colPair);
_colPair = collisionPairs_.erase (_colPair);
break;
case RelativeMotion::Unconstrained: ++_colPair; break;
default:
hppDout (warning, "RelativeMotionType not understood");
++_colPair;
break;
}
}
}
CollisionValidation::CollisionValidation (const DevicePtr_t& robot) :
collisionRequest_(1, false, false, 1, false, true, fcl::GST_INDEP),
robot_ (robot),
parameterizedPairs_(), disabledPairs_(),
checkParameterized_(false),
computeAllContacts_(false)
{
const se3::GeometryModel& model = robot->geomModel();
const se3::GeometryData & data = robot->geomData();
for (std::size_t i = 0; i < model.collisionPairs.size(); ++i)
if (data.activeCollisionPairs[i])
collisionPairs_.push_back(
makeCollisionPair(robot, model.collisionPairs[i])
);
}
} // namespace core
} // namespace hpp
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSbrCamera.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 "vtkSbrCamera.hh"
#include "vtkSbrRenderWindow.hh"
#include "vtkSbrRenderer.hh"
// Description:
// Implement base class method.
void vtkSbrCamera::Render(vtkCamera *cam, vtkRenderer *ren)
{
this->Render(cam, (vtkSbrRenderer *)ren);
}
// Description:
// Actual camera render method.
void vtkSbrCamera::Render(vtkCamera *cam, vtkSbrRenderer *ren)
{
float aspect[3];
float viewport[4];
float *background;
int stereo;
int fd;
int *size;
int *screen_size;
vtkSbrRenderWindow *rw;
float view_size[2];
float vdc_vals[6];
fd = ren->GetFd();
vtkMatrix4x4 matrix;
// get the background color
background = ren->GetBackground();
// get size info
rw = (vtkSbrRenderWindow*)(ren->GetRenderWindow());
size = rw->GetSize();
screen_size = rw->GetScreenSize();
// find out if we should stereo render
stereo = cam->GetStereo();
// set this renderer's viewport, must turn off z-buffering when changing
// viewport
hidden_surface(fd, FALSE, FALSE);
vtkDebugMacro(<< " SB_hidden_surface: False False\n");
memcpy(viewport,ren->GetViewport(),sizeof(float)*4);
// if were on a stereo renderer draw to special parts of screen
if (stereo)
{
switch ((ren->GetRenderWindow())->GetStereoType())
{
case VTK_STEREO_CRYSTAL_EYES:
if (cam->GetLeftEye())
{
viewport[1] = 0.5 + viewport[1]*0.5;
viewport[3] = 0.5 + viewport[3]*0.5;
}
else
{
viewport[1] = viewport[1]*0.5;
viewport[3] = viewport[3]*0.5;
}
break;
}
}
view_size[0] = (viewport[2] - viewport[0])*size[0];
view_size[1] = (viewport[3] - viewport[1])*size[1];
vdc_vals[0] = -1.0 - viewport[0]*size[0]*2.0/view_size[0];
vdc_vals[3] = vdc_vals[0] + 2.0*screen_size[0]/view_size[0];
vdc_vals[4] = 1.0 + (1.0-viewport[3])*size[1]*2.0/view_size[1];
vdc_vals[1] = vdc_vals[4] - 2.0*screen_size[1]/view_size[1];
vdc_vals[2] = 0;
vdc_vals[5] = 1.0;
// make sure the aspect is up to date
if (stereo)
{
switch ((ren->GetRenderWindow())->GetStereoType())
{
case VTK_STEREO_CRYSTAL_EYES:
{
aspect[0] = view_size[0]/(2.0*view_size[1]);
aspect[1] = 1.0;
}
break;
default:
{
aspect[0] = view_size[0]/view_size[1];
aspect[1] = 1.0;
}
}
}
else
{
aspect[0] = view_size[0]/view_size[1];
aspect[1] = 1.0;
}
ren->SetAspect(aspect);
vdc_extent(fd,vdc_vals[0],vdc_vals[1],vdc_vals[2],
vdc_vals[3],vdc_vals[4],vdc_vals[5]);
vtkDebugMacro(<< " screen_size " << screen_size[0] << " "
<< screen_size[1] << endl);
vtkDebugMacro(<< " size " << size[0] << " " << size[1] << endl);
vtkDebugMacro(<< " viewport " << viewport[0] << " " << viewport[1]
<< " " << viewport[2] << " " << viewport[3] << endl);
// set viewport to clear entire window
view_port(fd,-1.0,-1.0,1.0,1.0);
hidden_surface(fd, TRUE, FALSE);
vtkDebugMacro(<< " SB_hidden_surface: True False\n");
// Set the background color and clear the display.
// Since clear control was set to clear z buffer, this is done here
// also.
background_color(fd, background[0], background[1], background[2]);
// clear the view surface so the new background color takes effect
if (rw->GetErase())
{
clear_view_surface(fd);
vtkDebugMacro(<< " SB_clear_view_surface\n");
}
hidden_surface(fd, FALSE, FALSE);
vtkDebugMacro(<< " SB_hidden_surface: False False\n");
// I think the z clipping is done before the divide by w
vdc_extent(fd,vdc_vals[0],vdc_vals[1],vdc_vals[2],
vdc_vals[3],vdc_vals[4],vdc_vals[5]);
view_port(fd,-1.0,-1.0,1.0,1.0);
hidden_surface(fd, TRUE, FALSE);
vtkDebugMacro(<< " SB_hidden_surface: True False\n");
matrix = cam->GetCompositePerspectiveTransform(aspect[0]/aspect[1],0,1);
matrix.Transpose();
// insert model transformation
view_matrix3d(fd, (float (*)[4])(matrix[0]),REPLACE_VW);
clip_depth(fd,0.0,1.0);
}
<commit_msg>fixed problems with specularities<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSbrCamera.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 "vtkSbrCamera.hh"
#include "vtkSbrRenderWindow.hh"
#include "vtkSbrRenderer.hh"
// Description:
// Implement base class method.
void vtkSbrCamera::Render(vtkCamera *cam, vtkRenderer *ren)
{
this->Render(cam, (vtkSbrRenderer *)ren);
}
// Description:
// Actual camera render method.
void vtkSbrCamera::Render(vtkCamera *cam, vtkSbrRenderer *ren)
{
float aspect[3];
float viewport[4];
float *background;
int stereo;
int fd;
int *size;
int *screen_size;
vtkSbrRenderWindow *rw;
float view_size[2];
float vdc_vals[6];
fd = ren->GetFd();
vtkMatrix4x4 matrix;
float *pos;
// get the background color
background = ren->GetBackground();
// get size info
rw = (vtkSbrRenderWindow*)(ren->GetRenderWindow());
size = rw->GetSize();
screen_size = rw->GetScreenSize();
// find out if we should stereo render
stereo = cam->GetStereo();
// set this renderer's viewport, must turn off z-buffering when changing
// viewport
hidden_surface(fd, FALSE, FALSE);
vtkDebugMacro(<< " SB_hidden_surface: False False\n");
memcpy(viewport,ren->GetViewport(),sizeof(float)*4);
// if were on a stereo renderer draw to special parts of screen
if (stereo)
{
switch ((ren->GetRenderWindow())->GetStereoType())
{
case VTK_STEREO_CRYSTAL_EYES:
if (cam->GetLeftEye())
{
viewport[1] = 0.5 + viewport[1]*0.5;
viewport[3] = 0.5 + viewport[3]*0.5;
}
else
{
viewport[1] = viewport[1]*0.5;
viewport[3] = viewport[3]*0.5;
}
break;
}
}
view_size[0] = (viewport[2] - viewport[0])*size[0];
view_size[1] = (viewport[3] - viewport[1])*size[1];
vdc_vals[0] = -1.0 - viewport[0]*size[0]*2.0/view_size[0];
vdc_vals[3] = vdc_vals[0] + 2.0*screen_size[0]/view_size[0];
vdc_vals[4] = 1.0 + (1.0-viewport[3])*size[1]*2.0/view_size[1];
vdc_vals[1] = vdc_vals[4] - 2.0*screen_size[1]/view_size[1];
vdc_vals[2] = 0;
vdc_vals[5] = 1.0;
// make sure the aspect is up to date
if (stereo)
{
switch ((ren->GetRenderWindow())->GetStereoType())
{
case VTK_STEREO_CRYSTAL_EYES:
{
aspect[0] = view_size[0]/(2.0*view_size[1]);
aspect[1] = 1.0;
}
break;
default:
{
aspect[0] = view_size[0]/view_size[1];
aspect[1] = 1.0;
}
}
}
else
{
aspect[0] = view_size[0]/view_size[1];
aspect[1] = 1.0;
}
ren->SetAspect(aspect);
vdc_extent(fd,vdc_vals[0],vdc_vals[1],vdc_vals[2],
vdc_vals[3],vdc_vals[4],vdc_vals[5]);
vtkDebugMacro(<< " screen_size " << screen_size[0] << " "
<< screen_size[1] << endl);
vtkDebugMacro(<< " size " << size[0] << " " << size[1] << endl);
vtkDebugMacro(<< " viewport " << viewport[0] << " " << viewport[1]
<< " " << viewport[2] << " " << viewport[3] << endl);
// set viewport to clear entire window
view_port(fd,-1.0,-1.0,1.0,1.0);
hidden_surface(fd, TRUE, FALSE);
vtkDebugMacro(<< " SB_hidden_surface: True False\n");
// Set the background color and clear the display.
// Since clear control was set to clear z buffer, this is done here
// also.
background_color(fd, background[0], background[1], background[2]);
// clear the view surface so the new background color takes effect
if (rw->GetErase())
{
clear_view_surface(fd);
vtkDebugMacro(<< " SB_clear_view_surface\n");
}
hidden_surface(fd, FALSE, FALSE);
vtkDebugMacro(<< " SB_hidden_surface: False False\n");
// I think the z clipping is done before the divide by w
vdc_extent(fd,vdc_vals[0],vdc_vals[1],vdc_vals[2],
vdc_vals[3],vdc_vals[4],vdc_vals[5]);
view_port(fd,-1.0,-1.0,1.0,1.0);
hidden_surface(fd, TRUE, FALSE);
vtkDebugMacro(<< " SB_hidden_surface: True False\n");
matrix = cam->GetCompositePerspectiveTransform(aspect[0]/aspect[1],0,1);
matrix.Transpose();
// insert model transformation
view_matrix3d(fd, (float (*)[4])(matrix[0]),REPLACE_VW);
pos = cam->GetPosition();
viewpoint(fd,POSITIONAL,pos[0],pos[1],pos[2]);
clip_depth(fd,0.0,1.0);
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tango_data.h"
const TangoCoordinateFramePair tango_frame_pairs_[]={{TANGO_COORDINATE_FRAME_START_OF_SERVICE,TANGO_COORDINATE_FRAME_DEVICE}};
TangoData::TangoData()
: config_(nullptr),
tango_position_(glm::vec3(0.0f, 0.0f, 0.0f)),
tango_rotation_(glm::quat(1.0f, 0.0f, 0.0f, 0.0f)) {
}
// This callback function is called when new POSE updates become available.
static void onPoseAvailable(const TangoPoseData* pose) {
TangoData::GetInstance().SetTangoPosition(
glm::vec3(pose->translation[0], pose->translation[1],
pose->translation[2]));
TangoData::GetInstance().SetTangoRotation(
glm::quat(pose->orientation[3], pose->orientation[0],
pose->orientation[1], pose->orientation[2]));
TangoData::GetInstance().SetTangoPoseStatus(pose->status_code);
// glm::vec3 euler = glm::eulerAngles(
// glm::quat(pose->orientation[3], pose->orientation[0],
// pose->orientation[1], pose->orientation[2]));
// LOGI("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f", pose->translation[0],
// pose->translation[1], pose->translation[2], euler.x * 57.32f,
// euler.y * 57.32f, euler.z * 57.32f);
// if (pose->status_code == TANGO_POSE_INITIALIZING)
// LOGI("%d", 0);
// if (pose->status_code == TANGO_POSE_VALID)
// LOGI("%d", 1);
}
bool TangoData::Initialize() {
// Initialize Tango Service.
if (TangoService_initialize() != 0) {
LOGE("TangoService_initialize(): Failed");
return false;
}
return true;
}
bool TangoData::SetConfig() {
// Allocate a TangoConfig object.
if ((config_ = TangoConfig_alloc()) == NULL) {
LOGE("TangoService_allocConfig(): Failed");
return false;
}
// Get the default TangoConfig.
if (TangoService_getConfig(TANGO_CONFIG_DEFAULT, config_) != 0) {
LOGE("TangoService_getConfig(): Failed");
return false;
}
if (TangoService_connectOnPoseAvailable(onPoseAvailable) != 0) {
LOGI("TangoService_connectOnPoseAvailable(): Failed");
return false;
}
// std::list<TangoCoordinateFramePair> list;
// TangoCoordinateFramePair frame_pair;
// frame_pair.base = TANGO_COORDINATE_FRAME_START_OF_SERVICE;
// frame_pair.target = TANGO_COORDINATE_FRAME_DEVICE;
// list.push_back(frame_pair);
if(TangoService_setPoseListenerFrames(1, tango_frame_pairs_)!=0){
LOGE("TangoService_setPoseListenerFrames(): Failed");
return false;
}
return true;
}
bool TangoData::LockConfig() {
// Lock in this configuration.
if (TangoService_lockConfig(config_) != 0) {
LOGE("TangoService_lockConfig(): Failed");
return false;
}
return true;
}
bool TangoData::UnlockConfig() {
// Unlock current configuration.
if (TangoService_unlockConfig() != 0) {
LOGE("TangoService_unlockConfig(): Failed");
return false;
}
return true;
}
// Connect to Tango Service, service will start running, and
// POSE can be queried.
bool TangoData::Connect() {
if (TangoService_connect() != 0) {
LOGE("TangoService_connect(): Failed");
return false;
}
return true;
}
void TangoData::Disconnect() {
// Disconnect Tango Service.
TangoService_disconnect();
}
glm::vec3 TangoData::GetTangoPosition() {
return tango_position_;
}
glm::quat TangoData::GetTangoRotation() {
return tango_rotation_;
}
char TangoData::GetTangoPoseStatus(){
switch (status_) {
case TANGO_POSE_INITIALIZING:
return 1;
case TANGO_POSE_VALID:
return 2;
case TANGO_POSE_INVALID:
return 3;
default:
return 0;
break;
}
}
void TangoData::SetTangoPosition(glm::vec3 position) {
tango_position_ = position;
}
void TangoData::SetTangoRotation(glm::quat rotation) {
tango_rotation_ = rotation;
}
void TangoData::SetTangoPoseStatus(TangoPoseStatusType status) {
status_ = status;
}
<commit_msg>Move the setPoseListenerFrames() after connect to Tango Service.<commit_after>/*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "tango_data.h"
TangoData::TangoData()
: config_(nullptr),
tango_position_(glm::vec3(0.0f, 0.0f, 0.0f)),
tango_rotation_(glm::quat(1.0f, 0.0f, 0.0f, 0.0f)) {
}
// This callback function is called when new POSE updates become available.
static void onPoseAvailable(const TangoPoseData* pose) {
TangoData::GetInstance().SetTangoPosition(
glm::vec3(pose->translation[0], pose->translation[1],
pose->translation[2]));
TangoData::GetInstance().SetTangoRotation(
glm::quat(pose->orientation[3], pose->orientation[0],
pose->orientation[1], pose->orientation[2]));
TangoData::GetInstance().SetTangoPoseStatus(pose->status_code);
// glm::vec3 euler = glm::eulerAngles(
// glm::quat(pose->orientation[3], pose->orientation[0],
// pose->orientation[1], pose->orientation[2]));
// LOGI("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f", pose->translation[0],
// pose->translation[1], pose->translation[2], euler.x * 57.32f,
// euler.y * 57.32f, euler.z * 57.32f);
// if (pose->status_code == TANGO_POSE_INITIALIZING)
// LOGI("%d", 0);
// if (pose->status_code == TANGO_POSE_VALID)
// LOGI("%d", 1);
}
bool TangoData::Initialize() {
// Initialize Tango Service.
if (TangoService_initialize() != 0) {
LOGE("TangoService_initialize(): Failed");
return false;
}
return true;
}
bool TangoData::SetConfig() {
// Allocate a TangoConfig object.
if ((config_ = TangoConfig_alloc()) == NULL) {
LOGE("TangoService_allocConfig(): Failed");
return false;
}
// Get the default TangoConfig.
if (TangoService_getConfig(TANGO_CONFIG_DEFAULT, config_) != 0) {
LOGE("TangoService_getConfig(): Failed");
return false;
}
if (TangoService_connectOnPoseAvailable(onPoseAvailable) != 0) {
LOGI("TangoService_connectOnPoseAvailable(): Failed");
return false;
}
return true;
}
bool TangoData::LockConfig() {
// Lock in this configuration.
if (TangoService_lockConfig(config_) != 0) {
LOGE("TangoService_lockConfig(): Failed");
return false;
}
return true;
}
bool TangoData::UnlockConfig() {
// Unlock current configuration.
if (TangoService_unlockConfig() != 0) {
LOGE("TangoService_unlockConfig(): Failed");
return false;
}
return true;
}
// Connect to Tango Service, service will start running, and
// POSE can be queried.
bool TangoData::Connect() {
if (TangoService_connect() != 0) {
LOGE("TangoService_connect(): Failed");
return false;
}
//Set the reference frame pair after connect to service.
TangoCoordinateFramePair pairs;
pairs.base = TANGO_COORDINATE_FRAME_START_OF_SERVICE;
pairs.target = TANGO_COORDINATE_FRAME_DEVICE;
if (TangoService_setPoseListenerFrames(1, &pairs) != 0) {
LOGE("TangoService_setPoseListenerFrames(): Failed");
return false;
}
return true;
}
void TangoData::Disconnect() {
// Disconnect Tango Service.
TangoService_disconnect();
}
glm::vec3 TangoData::GetTangoPosition() {
return tango_position_;
}
glm::quat TangoData::GetTangoRotation() {
return tango_rotation_;
}
char TangoData::GetTangoPoseStatus() {
switch (status_) {
case TANGO_POSE_INITIALIZING:
return 1;
case TANGO_POSE_VALID:
return 2;
case TANGO_POSE_INVALID:
return 3;
default:
return 0;
break;
}
}
void TangoData::SetTangoPosition(glm::vec3 position) {
tango_position_ = position;
}
void TangoData::SetTangoRotation(glm::quat rotation) {
tango_rotation_ = rotation;
}
void TangoData::SetTangoPoseStatus(TangoPoseStatusType status) {
status_ = status;
}
<|endoftext|> |
<commit_before><commit_msg>winlauncher: updated PATH modification order: jbr folders and then current PATH<commit_after><|endoftext|> |
<commit_before><commit_msg>Disable LoadState net unittest: it's flakey<commit_after><|endoftext|> |
<commit_before>/**
* @file statmech
* test problem for statistical mechanics in cantera
*/
// Example
//
// Test case for the statistical mechanics in cantera
//
#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
/*****************************************************************/
/*****************************************************************/
//#include "cantera/Cantera.h"
#include "cantera/transport.h"
#include "cantera/IdealGasMix.h"
#include "cantera/equil/equil.h"
#include "cantera/transport/TransportFactory.h"
using namespace std;
using namespace Cantera;
int main(int argc, char** argv)
{
try
{
int k;
IdealGasMix g("test_stat_trans.xml");
int nsp = g.nSpecies();
double pres = 1.0E5;
// init pecos transport
int log_level = 0;
Transport * tran = newTransportMgr("Pecos", &g, log_level=0);
PecosTransport * tranMix = dynamic_cast<PecosTransport *>(tran);
vector_fp Xset(nsp, 0.0);
Xset[0] = 0.5 ;
Xset[1] = 0.5;
g.setState_TPX(1500.0, pres, DATA_PTR(Xset));
equilibrate(g, "TP", -1);
vector_fp cp_R(nsp, 0.0);
g.getCp_R(DATA_PTR(cp_R));
//for(int i=0;i<nsp;i++)
//{
// std::cout.precision(10);
// std::cout << cp_R[i] << std::endl;
// }
// error check-- exactly 2.5 for atoms
if(cp_R[0] != 2.5)
{
std::cout << "Error for monotomic Species!\n";
return 1;
}
// error check: analytical result is more complicated for
// molecules. One species should suffice, lets try NO2, with
// three vibrational modes:
/// theta[0]: 1.07900e3
/// theta[1]: 1.90000e3
/// theta[2]: 2.32700e3
// at T = 1500
//
// This is precisely: 6.655804161 (e.g. 5/2 + 2 + 3.1558..)
//
double theta[3];
theta[0] = 1.07900e3;
theta[1] = 1.90000e3;
theta[2] = 2.32700e3;
double T;
T = 1500.0;
double denom;
double ctr = 0.0;
double GasConstant = 1.0;
for(int i = 0; i < 3; i++)
{
denom = exp(2*theta[i]/T) - 2* exp(theta[i]/T) + 1;
ctr += GasConstant * theta[i] * (theta[i] * exp(theta[i]/T)/(T*T))/ (denom);
//std::cout << "survey says: " << ctr << " and denom is: " << denom << std::endl;
}
//std::cout << "survey says: " << ctr << " and denom is: " << denom << std::endl;
double sol = ctr + 5/2 + 2;
double tol = 1e-9;
if(abs(cp_R[3] - sol) >= tol )
{
double diff = cp_R[3]-sol;
std::cout << "Error for Species NO2!\n";
std::cout << "Diff was: " << diff << "\n";
return 1;
}
}
catch (CanteraError)
{
showErrors(cout);
return 1;
}
// Mark it zero!
return 0;
}
<commit_msg>updating, even if it is not working... will fiddle further<commit_after>/**
* @file statmech
* test problem for statistical mechanics in cantera
*/
// Example
//
// Test case for the statistical mechanics in cantera
//
#include <iostream>
#include <string>
#include <vector>
#include <string>
#include <iomanip>
/*****************************************************************/
/*****************************************************************/
//#include "cantera/Cantera.h"
#include "cantera/transport.h"
#include "cantera/IdealGasMix.h"
#include "cantera/equil/equil.h"
#include "cantera/transport/TransportFactory.h"
using namespace std;
using namespace Cantera;
int main(int argc, char** argv)
{
try
{
int k;
IdealGasMix g("test_stat_trans.xml", "example");
int nsp = g.nSpecies();
double pres = 1.0E5;
vector_fp Xset(nsp, 0.0);
Xset[0] = 0.5 ;
Xset[1] = 0.5;
g.setState_TPX(1500.0, pres, DATA_PTR(Xset));
equilibrate(g, "TP", -1);
// init pecos transport
int log_level = 0;
Transport * tran = newTransportMgr("Pecos", &g, log_level=0);
PecosTransport * tranMix = dynamic_cast<PecosTransport *>(tran);
cout << "here";
vector_fp cp_R(nsp, 0.0);
g.getCp_R(DATA_PTR(cp_R));
//for(int i=0;i<nsp;i++)
//{
// std::cout.precision(10);
// std::cout << cp_R[i] << std::endl;
// }
// error check-- exactly 2.5 for atoms
if(cp_R[0] != 2.5)
{
std::cout << "Error for monotomic Species!\n";
return 1;
}
// error check: analytical result is more complicated for
// molecules. One species should suffice, lets try NO2, with
// three vibrational modes:
/// theta[0]: 1.07900e3
/// theta[1]: 1.90000e3
/// theta[2]: 2.32700e3
// at T = 1500
//
// This is precisely: 6.655804161 (e.g. 5/2 + 2 + 3.1558..)
//
double theta[3];
theta[0] = 1.07900e3;
theta[1] = 1.90000e3;
theta[2] = 2.32700e3;
double T;
T = 1500.0;
double denom;
double ctr = 0.0;
double GasConstant = 1.0;
for(int i = 0; i < 3; i++)
{
denom = exp(2*theta[i]/T) - 2* exp(theta[i]/T) + 1;
ctr += GasConstant * theta[i] * (theta[i] * exp(theta[i]/T)/(T*T))/ (denom);
//std::cout << "survey says: " << ctr << " and denom is: " << denom << std::endl;
}
//std::cout << "survey says: " << ctr << " and denom is: " << denom << std::endl;
double sol = ctr + 5/2 + 2;
double tol = 1e-9;
if(abs(cp_R[3] - sol) >= tol )
{
double diff = cp_R[3]-sol;
std::cout << "Error for Species NO2!\n";
std::cout << "Diff was: " << diff << "\n";
return 1;
}
}
catch (CanteraError)
{
showErrors(cout);
return 1;
}
// Mark it zero!
return 0;
}
<|endoftext|> |
<commit_before>#include "CrashHandler.h"
#include "SkTypes.h"
#include <stdlib.h>
#if defined(SK_BUILD_FOR_MAC)
// We only use local unwinding, so we can define this to select a faster implementation.
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <cxxabi.h>
static void handler(int sig) {
unw_context_t context;
unw_getcontext(&context);
unw_cursor_t cursor;
unw_init_local(&cursor, &context);
SkDebugf("\nSignal %d:\n", sig);
while (unw_step(&cursor) > 0) {
static const size_t kMax = 256;
char mangled[kMax], demangled[kMax];
unw_word_t offset;
unw_get_proc_name(&cursor, mangled, kMax, &offset);
int ok;
size_t len = kMax;
abi::__cxa_demangle(mangled, demangled, &len, &ok);
SkDebugf("%s (+0x%zx)\n", ok == 0 ? demangled : mangled, (size_t)offset);
}
SkDebugf("\n");
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_Exit(sig);
}
#elif defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL) // NACL doesn't have backtrace().
// We'd use libunwind here too, but it's a pain to get installed for both 32 and 64 bit on bots.
// Doesn't matter much: catchsegv is best anyway.
#include <execinfo.h>
static void handler(int sig) {
static const int kMax = 64;
void* stack[kMax];
const int count = backtrace(stack, kMax);
SkDebugf("\nSignal %d:\n", sig);
backtrace_symbols_fd(stack, count, 2/*stderr*/);
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_Exit(sig);
}
#endif
#if defined(SK_BUILD_FOR_MAC) || (defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL))
#include <signal.h>
void SetupCrashHandler() {
static const int kSignals[] = {
SIGABRT,
SIGBUS,
SIGFPE,
SIGILL,
SIGSEGV,
};
for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) {
// Register our signal handler unless something's already done so (e.g. catchsegv).
void (*prev)(int) = signal(kSignals[i], handler);
if (prev != SIG_DFL) {
signal(kSignals[i], prev);
}
}
}
#elif defined(SK_BUILD_FOR_WIN)
#include <DbgHelp.h>
static const struct {
const char* name;
int code;
} kExceptions[] = {
#define _(E) {#E, E}
_(EXCEPTION_ACCESS_VIOLATION),
_(EXCEPTION_BREAKPOINT),
_(EXCEPTION_INT_DIVIDE_BY_ZERO),
_(EXCEPTION_STACK_OVERFLOW),
// TODO: more?
#undef _
};
static LONG WINAPI handler(EXCEPTION_POINTERS* e) {
const DWORD code = e->ExceptionRecord->ExceptionCode;
SkDebugf("\nCaught exception %u", code);
for (size_t i = 0; i < SK_ARRAY_COUNT(kExceptions); i++) {
if (kExceptions[i].code == code) {
SkDebugf(" %s", kExceptions[i].name);
}
}
SkDebugf("\n");
// We need to run SymInitialize before doing any of the stack walking below.
HANDLE hProcess = GetCurrentProcess();
SymInitialize(hProcess, 0, true);
STACKFRAME64 frame;
sk_bzero(&frame, sizeof(frame));
// Start frame off from the frame that triggered the exception.
CONTEXT* c = e->ContextRecord;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrStack.Mode = AddrModeFlat;
frame.AddrFrame.Mode = AddrModeFlat;
#if defined(_X86_)
frame.AddrPC.Offset = c->Eip;
frame.AddrStack.Offset = c->Esp;
frame.AddrFrame.Offset = c->Ebp;
const DWORD machineType = IMAGE_FILE_MACHINE_I386;
#elif defined(_AMD64_)
frame.AddrPC.Offset = c->Rip;
frame.AddrStack.Offset = c->Rsp;
frame.AddrFrame.Offset = c->Rbp;
const DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
#endif
while (StackWalk64(machineType,
GetCurrentProcess(),
GetCurrentThread(),
&frame,
c,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL)) {
// Buffer to store symbol name in.
static const int kMaxNameLength = 1024;
uint8_t buffer[sizeof(IMAGEHLP_SYMBOL64) + kMaxNameLength];
sk_bzero(buffer, sizeof(buffer));
// We have to place IMAGEHLP_SYMBOL64 at the front, and fill in how much space it can use.
IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(&buffer);
symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol->MaxNameLength = kMaxNameLength - 1;
// Translate the current PC into a symbol and byte offset from the symbol.
DWORD64 offset;
SymGetSymFromAddr64(hProcess, frame.AddrPC.Offset, &offset, symbol);
SkDebugf("%s +%x\n", symbol->Name, offset);
}
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_exit(1);
// The compiler wants us to return something. This is what we'd do if we didn't _exit().
return EXCEPTION_EXECUTE_HANDLER;
}
void SetupCrashHandler() {
SetUnhandledExceptionFilter(handler);
}
#else
void SetupCrashHandler() { }
#endif
<commit_msg>CrashHandler calls strsignal on linux<commit_after>#include "CrashHandler.h"
#include "SkTypes.h"
#include <stdlib.h>
#if defined(SK_BUILD_FOR_MAC)
// We only use local unwinding, so we can define this to select a faster implementation.
#define UNW_LOCAL_ONLY
#include <libunwind.h>
#include <cxxabi.h>
static void handler(int sig) {
unw_context_t context;
unw_getcontext(&context);
unw_cursor_t cursor;
unw_init_local(&cursor, &context);
SkDebugf("\nSignal %d:\n", sig);
while (unw_step(&cursor) > 0) {
static const size_t kMax = 256;
char mangled[kMax], demangled[kMax];
unw_word_t offset;
unw_get_proc_name(&cursor, mangled, kMax, &offset);
int ok;
size_t len = kMax;
abi::__cxa_demangle(mangled, demangled, &len, &ok);
SkDebugf("%s (+0x%zx)\n", ok == 0 ? demangled : mangled, (size_t)offset);
}
SkDebugf("\n");
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_Exit(sig);
}
#elif defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL) // NACL doesn't have backtrace().
// We'd use libunwind here too, but it's a pain to get installed for both 32 and 64 bit on bots.
// Doesn't matter much: catchsegv is best anyway.
#include <execinfo.h>
static void handler(int sig) {
static const int kMax = 64;
void* stack[kMax];
const int count = backtrace(stack, kMax);
SkDebugf("\nSignal %d [%s]:\n", sig, strsignal(sig));
backtrace_symbols_fd(stack, count, 2/*stderr*/);
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_Exit(sig);
}
#endif
#if defined(SK_BUILD_FOR_MAC) || (defined(SK_BUILD_FOR_UNIX) && !defined(SK_BUILD_FOR_NACL))
#include <signal.h>
void SetupCrashHandler() {
static const int kSignals[] = {
SIGABRT,
SIGBUS,
SIGFPE,
SIGILL,
SIGSEGV,
};
for (size_t i = 0; i < sizeof(kSignals) / sizeof(kSignals[0]); i++) {
// Register our signal handler unless something's already done so (e.g. catchsegv).
void (*prev)(int) = signal(kSignals[i], handler);
if (prev != SIG_DFL) {
signal(kSignals[i], prev);
}
}
}
#elif defined(SK_BUILD_FOR_WIN)
#include <DbgHelp.h>
static const struct {
const char* name;
int code;
} kExceptions[] = {
#define _(E) {#E, E}
_(EXCEPTION_ACCESS_VIOLATION),
_(EXCEPTION_BREAKPOINT),
_(EXCEPTION_INT_DIVIDE_BY_ZERO),
_(EXCEPTION_STACK_OVERFLOW),
// TODO: more?
#undef _
};
static LONG WINAPI handler(EXCEPTION_POINTERS* e) {
const DWORD code = e->ExceptionRecord->ExceptionCode;
SkDebugf("\nCaught exception %u", code);
for (size_t i = 0; i < SK_ARRAY_COUNT(kExceptions); i++) {
if (kExceptions[i].code == code) {
SkDebugf(" %s", kExceptions[i].name);
}
}
SkDebugf("\n");
// We need to run SymInitialize before doing any of the stack walking below.
HANDLE hProcess = GetCurrentProcess();
SymInitialize(hProcess, 0, true);
STACKFRAME64 frame;
sk_bzero(&frame, sizeof(frame));
// Start frame off from the frame that triggered the exception.
CONTEXT* c = e->ContextRecord;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrStack.Mode = AddrModeFlat;
frame.AddrFrame.Mode = AddrModeFlat;
#if defined(_X86_)
frame.AddrPC.Offset = c->Eip;
frame.AddrStack.Offset = c->Esp;
frame.AddrFrame.Offset = c->Ebp;
const DWORD machineType = IMAGE_FILE_MACHINE_I386;
#elif defined(_AMD64_)
frame.AddrPC.Offset = c->Rip;
frame.AddrStack.Offset = c->Rsp;
frame.AddrFrame.Offset = c->Rbp;
const DWORD machineType = IMAGE_FILE_MACHINE_AMD64;
#endif
while (StackWalk64(machineType,
GetCurrentProcess(),
GetCurrentThread(),
&frame,
c,
NULL,
SymFunctionTableAccess64,
SymGetModuleBase64,
NULL)) {
// Buffer to store symbol name in.
static const int kMaxNameLength = 1024;
uint8_t buffer[sizeof(IMAGEHLP_SYMBOL64) + kMaxNameLength];
sk_bzero(buffer, sizeof(buffer));
// We have to place IMAGEHLP_SYMBOL64 at the front, and fill in how much space it can use.
IMAGEHLP_SYMBOL64* symbol = reinterpret_cast<IMAGEHLP_SYMBOL64*>(&buffer);
symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
symbol->MaxNameLength = kMaxNameLength - 1;
// Translate the current PC into a symbol and byte offset from the symbol.
DWORD64 offset;
SymGetSymFromAddr64(hProcess, frame.AddrPC.Offset, &offset, symbol);
SkDebugf("%s +%x\n", symbol->Name, offset);
}
// Exit NOW. Don't notify other threads, don't call anything registered with atexit().
_exit(1);
// The compiler wants us to return something. This is what we'd do if we didn't _exit().
return EXCEPTION_EXECUTE_HANDLER;
}
void SetupCrashHandler() {
SetUnhandledExceptionFilter(handler);
}
#else
void SetupCrashHandler() { }
#endif
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "s60devicerunconfigurationwidget.h"
#include "s60devicerunconfiguration.h"
#include "s60manager.h"
#include "launcher.h"
#include "serialdevicelister.h"
#include <utils/detailswidget.h>
#include <utils/qtcassert.h>
#include <utils/pathchooser.h>
#include <QtCore/QTimer>
#include <QtGui/QRadioButton>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QComboBox>
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QFormLayout>
#include <QtGui/QToolButton>
#include <QtGui/QStyle>
#include <QtGui/QApplication>
#include <QtGui/QSpacerItem>
namespace Qt4ProjectManager {
namespace Internal {
S60DeviceRunConfigurationWidget::S60DeviceRunConfigurationWidget(
S60DeviceRunConfiguration *runConfiguration,
QWidget *parent)
: QWidget(parent),
m_runConfiguration(runConfiguration),
m_detailsWidget(new Utils::DetailsWidget),
m_serialPortsCombo(new QComboBox),
m_nameLineEdit(new QLineEdit(m_runConfiguration->name())),
m_sisxFileLabel(new QLabel(m_runConfiguration->basePackageFilePath() + QLatin1String(".sisx"))),
m_deviceInfoButton(new QToolButton),
m_deviceInfoDescriptionLabel(new QLabel(tr("Device:"))),
m_deviceInfoLabel(new QLabel),
m_infoTimeOutTimer(0)
{
QVBoxLayout *mainBoxLayout = new QVBoxLayout();
mainBoxLayout->setMargin(0);
setLayout(mainBoxLayout);
mainBoxLayout->addWidget(m_detailsWidget);
QWidget *detailsContainer = new QWidget;
m_detailsWidget->setWidget(detailsContainer);
QVBoxLayout *detailsBoxLayout = new QVBoxLayout();
detailsBoxLayout->setMargin(0);
detailsContainer->setLayout(detailsBoxLayout);
QFormLayout *formLayout = new QFormLayout();
formLayout->setMargin(0);
detailsBoxLayout->addLayout(formLayout);
// Name control
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLabel->setBuddy(m_nameLineEdit);
formLayout->addRow(nameLabel, m_nameLineEdit);
formLayout->addRow(tr("Install File:"), m_sisxFileLabel);
updateSerialDevices();
connect(S60Manager::instance()->serialDeviceLister(), SIGNAL(updated()),
this, SLOT(updateSerialDevices()));
// Serial devices control
connect(m_serialPortsCombo, SIGNAL(activated(int)), this, SLOT(setSerialPort(int)));
QHBoxLayout *serialPortHBoxLayout = new QHBoxLayout;
serialPortHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
serialPortHBoxLayout->addWidget(m_serialPortsCombo);
formLayout->addRow(tr("Device on Serial Port:"), serialPortHBoxLayout);
// Device Info with button. Widgets are enabled in above call to updateSerialDevices()
QHBoxLayout *infoHBoxLayout = new QHBoxLayout;
m_deviceInfoLabel->setWordWrap(true);
infoHBoxLayout->addWidget(m_deviceInfoLabel);
infoHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
infoHBoxLayout->addWidget(m_deviceInfoButton);
m_deviceInfoButton->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation));
m_deviceInfoButton->setToolTip(tr("Queries the device for information"));
connect(m_deviceInfoButton, SIGNAL(clicked()), this, SLOT(updateDeviceInfo()));
formLayout->addRow(m_deviceInfoDescriptionLabel, infoHBoxLayout);
// Signature/certificate stuff.
QWidget *signatureWidget = new QWidget();
QVBoxLayout *layout = new QVBoxLayout();
signatureWidget->setLayout(layout);
detailsBoxLayout->addWidget(signatureWidget);
QRadioButton *selfSign = new QRadioButton(tr("Self-signed certificate"));
QHBoxLayout *customHBox = new QHBoxLayout();
customHBox->setMargin(0);
QVBoxLayout *radioLayout = new QVBoxLayout();
QRadioButton *customSignature = new QRadioButton();
radioLayout->addWidget(customSignature);
radioLayout->addStretch(10);
customHBox->addLayout(radioLayout);
QFormLayout *customLayout = new QFormLayout();
customLayout->setMargin(0);
customLayout->setLabelAlignment(Qt::AlignRight);
Utils::PathChooser *signaturePath = new Utils::PathChooser();
signaturePath->setExpectedKind(Utils::PathChooser::File);
signaturePath->setPromptDialogTitle(tr("Choose certificate file (.cer)"));
customLayout->addRow(new QLabel(tr("Custom certificate:")), signaturePath);
Utils::PathChooser *keyPath = new Utils::PathChooser();
keyPath->setExpectedKind(Utils::PathChooser::File);
keyPath->setPromptDialogTitle(tr("Choose key file (.key / .pem)"));
customLayout->addRow(new QLabel(tr("Key file:")), keyPath);
customHBox->addLayout(customLayout);
customHBox->addStretch(10);
layout->addWidget(selfSign);
layout->addLayout(customHBox);
layout->addStretch(10);
switch (m_runConfiguration->signingMode()) {
case S60DeviceRunConfiguration::SignSelf:
selfSign->setChecked(true);
break;
case S60DeviceRunConfiguration::SignCustom:
customSignature->setChecked(true);
break;
}
signaturePath->setPath(m_runConfiguration->customSignaturePath());
keyPath->setPath(m_runConfiguration->customKeyPath());
connect(m_nameLineEdit, SIGNAL(textEdited(QString)),
this, SLOT(nameEdited(QString)));
connect(m_runConfiguration, SIGNAL(targetInformationChanged()),
this, SLOT(updateTargetInformation()));
connect(selfSign, SIGNAL(toggled(bool)), this, SLOT(selfSignToggled(bool)));
connect(customSignature, SIGNAL(toggled(bool)), this, SLOT(customSignatureToggled(bool)));
connect(signaturePath, SIGNAL(changed(QString)), this, SLOT(signaturePathChanged(QString)));
connect(keyPath, SIGNAL(changed(QString)), this, SLOT(keyPathChanged(QString)));
updateSummary();
}
void S60DeviceRunConfigurationWidget::updateSerialDevices()
{
m_serialPortsCombo->clear();
clearDeviceInfo();
const QString previousRunConfigurationPortName = m_runConfiguration->serialPortName();
const QList<SerialDeviceLister::SerialDevice> serialDevices = S60Manager::instance()->serialDeviceLister()->serialDevices();
int newIndex = -1;
for (int i = 0; i < serialDevices.size(); ++i) {
const SerialDeviceLister::SerialDevice &device = serialDevices.at(i);
m_serialPortsCombo->addItem(device.friendlyName, device.portName);
if (device.portName == previousRunConfigurationPortName)
newIndex = i;
}
// Set new index: prefer to keep old or set to 0, if available.
if (newIndex == -1 && !serialDevices.empty())
newIndex = 0;
m_serialPortsCombo->setCurrentIndex(newIndex);
if (newIndex == -1) {
m_deviceInfoButton->setEnabled(false);
m_runConfiguration->setSerialPortName(QString());
} else {
m_deviceInfoButton->setEnabled(true);
const QString newPortName = portName(newIndex);
if (newPortName != previousRunConfigurationPortName)
m_runConfiguration->setSerialPortName(newPortName);
}
}
QString S60DeviceRunConfigurationWidget::portName(int index) const
{
return index >= 0 ? m_serialPortsCombo->itemData(index).toString() : QString();
}
QString S60DeviceRunConfigurationWidget::currentPortName() const
{
return portName(m_serialPortsCombo->currentIndex());
}
void S60DeviceRunConfigurationWidget::nameEdited(const QString &text)
{
m_runConfiguration->setName(text);
}
void S60DeviceRunConfigurationWidget::updateTargetInformation()
{
m_sisxFileLabel->setText(m_runConfiguration->basePackageFilePath() + QLatin1String(".sisx"));
}
void S60DeviceRunConfigurationWidget::setSerialPort(int index)
{
m_runConfiguration->setSerialPortName(portName(index));
m_deviceInfoButton->setEnabled(index >= 0);
clearDeviceInfo();
updateSummary();
}
void S60DeviceRunConfigurationWidget::selfSignToggled(bool toggle)
{
if (toggle)
m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignSelf);
updateSummary();
}
void S60DeviceRunConfigurationWidget::customSignatureToggled(bool toggle)
{
if (toggle)
m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignCustom);
updateSummary();
}
void S60DeviceRunConfigurationWidget::signaturePathChanged(const QString &path)
{
m_runConfiguration->setCustomSignaturePath(path);
updateSummary();
}
void S60DeviceRunConfigurationWidget::keyPathChanged(const QString &path)
{
m_runConfiguration->setCustomKeyPath(path);
updateSummary();
}
void S60DeviceRunConfigurationWidget::updateSummary()
{
//: Summary text of S60 device run configuration
const QString device = m_serialPortsCombo->currentIndex() != -1 ?
m_serialPortsCombo->currentText() :
tr("<No Device>");
const QString signature = m_runConfiguration->signingMode() == S60DeviceRunConfiguration::SignCustom ?
tr("(custom certificate)") :
tr("(self-signed certificate)");
m_detailsWidget->setSummaryText(tr("Summary: Run on '%1' %2").arg(device, signature));
}
void S60DeviceRunConfigurationWidget::clearDeviceInfo()
{
// Restore text & color
m_deviceInfoLabel->clear();
m_deviceInfoLabel->setStyleSheet(QString());
}
void S60DeviceRunConfigurationWidget::setDeviceInfoLabel(const QString &message, bool isError)
{
m_deviceInfoLabel->setStyleSheet(isError ?
QString(QLatin1String("background-color: red;")) :
QString());
m_deviceInfoLabel->setText(message);
}
void S60DeviceRunConfigurationWidget::updateDeviceInfo()
{
QString message;
setDeviceInfoLabel(tr("Connecting..."));
const bool ok = getDeviceInfo(&message);
setDeviceInfoLabel(message, !ok);
}
bool S60DeviceRunConfigurationWidget::getDeviceInfo(QString *message)
{
// Do a launcher run with the ping protocol. Instantiate launcher on heap
// as not to introduce delays when destructing a device with timeout
trk::Launcher *launcher = new trk::Launcher(trk::Launcher::ActionPingOnly, this);
launcher->setTrkServerName(currentPortName());
if (!launcher->startServer(message)) {
launcher->deleteLater();
return false;
}
// Set up event loop in the foreground with a timer to quit in case of timeout.
QEventLoop eventLoop;
if (!m_infoTimeOutTimer) {
m_infoTimeOutTimer = new QTimer(this);
m_infoTimeOutTimer->setInterval(3000);
m_infoTimeOutTimer->setSingleShot(true);
}
connect(m_infoTimeOutTimer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
connect(launcher, SIGNAL(finished()), &eventLoop, SLOT(quit()));
// Go!
QApplication::setOverrideCursor(Qt::BusyCursor);
m_infoTimeOutTimer->start();
eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
m_infoTimeOutTimer->disconnect();
QApplication::restoreOverrideCursor();
// Anything received?
*message = launcher->deviceDescription();
launcher->deleteLater();
if (message->isEmpty()) {
*message = tr("A timeout occurred while querying the device. Check whether Trk is running");
return false;
}
return true;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<commit_msg>S60: Swap spacers in device run config widget.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "s60devicerunconfigurationwidget.h"
#include "s60devicerunconfiguration.h"
#include "s60manager.h"
#include "launcher.h"
#include "serialdevicelister.h"
#include <utils/detailswidget.h>
#include <utils/qtcassert.h>
#include <utils/pathchooser.h>
#include <QtCore/QTimer>
#include <QtGui/QRadioButton>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QComboBox>
#include <QtGui/QVBoxLayout>
#include <QtGui/QHBoxLayout>
#include <QtGui/QFormLayout>
#include <QtGui/QToolButton>
#include <QtGui/QStyle>
#include <QtGui/QApplication>
#include <QtGui/QSpacerItem>
namespace Qt4ProjectManager {
namespace Internal {
S60DeviceRunConfigurationWidget::S60DeviceRunConfigurationWidget(
S60DeviceRunConfiguration *runConfiguration,
QWidget *parent)
: QWidget(parent),
m_runConfiguration(runConfiguration),
m_detailsWidget(new Utils::DetailsWidget),
m_serialPortsCombo(new QComboBox),
m_nameLineEdit(new QLineEdit(m_runConfiguration->name())),
m_sisxFileLabel(new QLabel(m_runConfiguration->basePackageFilePath() + QLatin1String(".sisx"))),
m_deviceInfoButton(new QToolButton),
m_deviceInfoDescriptionLabel(new QLabel(tr("Device:"))),
m_deviceInfoLabel(new QLabel),
m_infoTimeOutTimer(0)
{
QVBoxLayout *mainBoxLayout = new QVBoxLayout();
mainBoxLayout->setMargin(0);
setLayout(mainBoxLayout);
mainBoxLayout->addWidget(m_detailsWidget);
QWidget *detailsContainer = new QWidget;
m_detailsWidget->setWidget(detailsContainer);
QVBoxLayout *detailsBoxLayout = new QVBoxLayout();
detailsBoxLayout->setMargin(0);
detailsContainer->setLayout(detailsBoxLayout);
QFormLayout *formLayout = new QFormLayout();
formLayout->setMargin(0);
detailsBoxLayout->addLayout(formLayout);
// Name control
QLabel *nameLabel = new QLabel(tr("Name:"));
nameLabel->setBuddy(m_nameLineEdit);
formLayout->addRow(nameLabel, m_nameLineEdit);
formLayout->addRow(tr("Install File:"), m_sisxFileLabel);
updateSerialDevices();
connect(S60Manager::instance()->serialDeviceLister(), SIGNAL(updated()),
this, SLOT(updateSerialDevices()));
// Serial devices control
connect(m_serialPortsCombo, SIGNAL(activated(int)), this, SLOT(setSerialPort(int)));
QHBoxLayout *serialPortHBoxLayout = new QHBoxLayout;
serialPortHBoxLayout->addWidget(m_serialPortsCombo);
serialPortHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
formLayout->addRow(tr("Device on Serial Port:"), serialPortHBoxLayout);
// Device Info with button. Widgets are enabled in above call to updateSerialDevices()
QHBoxLayout *infoHBoxLayout = new QHBoxLayout;
m_deviceInfoLabel->setWordWrap(true);
infoHBoxLayout->addWidget(m_deviceInfoLabel);
infoHBoxLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Ignored));
infoHBoxLayout->addWidget(m_deviceInfoButton);
m_deviceInfoButton->setIcon(qApp->style()->standardIcon(QStyle::SP_MessageBoxInformation));
m_deviceInfoButton->setToolTip(tr("Queries the device for information"));
connect(m_deviceInfoButton, SIGNAL(clicked()), this, SLOT(updateDeviceInfo()));
formLayout->addRow(m_deviceInfoDescriptionLabel, infoHBoxLayout);
// Signature/certificate stuff.
QWidget *signatureWidget = new QWidget();
QVBoxLayout *layout = new QVBoxLayout();
signatureWidget->setLayout(layout);
detailsBoxLayout->addWidget(signatureWidget);
QRadioButton *selfSign = new QRadioButton(tr("Self-signed certificate"));
QHBoxLayout *customHBox = new QHBoxLayout();
customHBox->setMargin(0);
QVBoxLayout *radioLayout = new QVBoxLayout();
QRadioButton *customSignature = new QRadioButton();
radioLayout->addWidget(customSignature);
radioLayout->addStretch(10);
customHBox->addLayout(radioLayout);
QFormLayout *customLayout = new QFormLayout();
customLayout->setMargin(0);
customLayout->setLabelAlignment(Qt::AlignRight);
Utils::PathChooser *signaturePath = new Utils::PathChooser();
signaturePath->setExpectedKind(Utils::PathChooser::File);
signaturePath->setPromptDialogTitle(tr("Choose certificate file (.cer)"));
customLayout->addRow(new QLabel(tr("Custom certificate:")), signaturePath);
Utils::PathChooser *keyPath = new Utils::PathChooser();
keyPath->setExpectedKind(Utils::PathChooser::File);
keyPath->setPromptDialogTitle(tr("Choose key file (.key / .pem)"));
customLayout->addRow(new QLabel(tr("Key file:")), keyPath);
customHBox->addLayout(customLayout);
customHBox->addStretch(10);
layout->addWidget(selfSign);
layout->addLayout(customHBox);
layout->addStretch(10);
switch (m_runConfiguration->signingMode()) {
case S60DeviceRunConfiguration::SignSelf:
selfSign->setChecked(true);
break;
case S60DeviceRunConfiguration::SignCustom:
customSignature->setChecked(true);
break;
}
signaturePath->setPath(m_runConfiguration->customSignaturePath());
keyPath->setPath(m_runConfiguration->customKeyPath());
connect(m_nameLineEdit, SIGNAL(textEdited(QString)),
this, SLOT(nameEdited(QString)));
connect(m_runConfiguration, SIGNAL(targetInformationChanged()),
this, SLOT(updateTargetInformation()));
connect(selfSign, SIGNAL(toggled(bool)), this, SLOT(selfSignToggled(bool)));
connect(customSignature, SIGNAL(toggled(bool)), this, SLOT(customSignatureToggled(bool)));
connect(signaturePath, SIGNAL(changed(QString)), this, SLOT(signaturePathChanged(QString)));
connect(keyPath, SIGNAL(changed(QString)), this, SLOT(keyPathChanged(QString)));
updateSummary();
}
void S60DeviceRunConfigurationWidget::updateSerialDevices()
{
m_serialPortsCombo->clear();
clearDeviceInfo();
const QString previousRunConfigurationPortName = m_runConfiguration->serialPortName();
const QList<SerialDeviceLister::SerialDevice> serialDevices = S60Manager::instance()->serialDeviceLister()->serialDevices();
int newIndex = -1;
for (int i = 0; i < serialDevices.size(); ++i) {
const SerialDeviceLister::SerialDevice &device = serialDevices.at(i);
m_serialPortsCombo->addItem(device.friendlyName, device.portName);
if (device.portName == previousRunConfigurationPortName)
newIndex = i;
}
// Set new index: prefer to keep old or set to 0, if available.
if (newIndex == -1 && !serialDevices.empty())
newIndex = 0;
m_serialPortsCombo->setCurrentIndex(newIndex);
if (newIndex == -1) {
m_deviceInfoButton->setEnabled(false);
m_runConfiguration->setSerialPortName(QString());
} else {
m_deviceInfoButton->setEnabled(true);
const QString newPortName = portName(newIndex);
if (newPortName != previousRunConfigurationPortName)
m_runConfiguration->setSerialPortName(newPortName);
}
}
QString S60DeviceRunConfigurationWidget::portName(int index) const
{
return index >= 0 ? m_serialPortsCombo->itemData(index).toString() : QString();
}
QString S60DeviceRunConfigurationWidget::currentPortName() const
{
return portName(m_serialPortsCombo->currentIndex());
}
void S60DeviceRunConfigurationWidget::nameEdited(const QString &text)
{
m_runConfiguration->setName(text);
}
void S60DeviceRunConfigurationWidget::updateTargetInformation()
{
m_sisxFileLabel->setText(m_runConfiguration->basePackageFilePath() + QLatin1String(".sisx"));
}
void S60DeviceRunConfigurationWidget::setSerialPort(int index)
{
m_runConfiguration->setSerialPortName(portName(index));
m_deviceInfoButton->setEnabled(index >= 0);
clearDeviceInfo();
updateSummary();
}
void S60DeviceRunConfigurationWidget::selfSignToggled(bool toggle)
{
if (toggle)
m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignSelf);
updateSummary();
}
void S60DeviceRunConfigurationWidget::customSignatureToggled(bool toggle)
{
if (toggle)
m_runConfiguration->setSigningMode(S60DeviceRunConfiguration::SignCustom);
updateSummary();
}
void S60DeviceRunConfigurationWidget::signaturePathChanged(const QString &path)
{
m_runConfiguration->setCustomSignaturePath(path);
updateSummary();
}
void S60DeviceRunConfigurationWidget::keyPathChanged(const QString &path)
{
m_runConfiguration->setCustomKeyPath(path);
updateSummary();
}
void S60DeviceRunConfigurationWidget::updateSummary()
{
//: Summary text of S60 device run configuration
const QString device = m_serialPortsCombo->currentIndex() != -1 ?
m_serialPortsCombo->currentText() :
tr("<No Device>");
const QString signature = m_runConfiguration->signingMode() == S60DeviceRunConfiguration::SignCustom ?
tr("(custom certificate)") :
tr("(self-signed certificate)");
m_detailsWidget->setSummaryText(tr("Summary: Run on '%1' %2").arg(device, signature));
}
void S60DeviceRunConfigurationWidget::clearDeviceInfo()
{
// Restore text & color
m_deviceInfoLabel->clear();
m_deviceInfoLabel->setStyleSheet(QString());
}
void S60DeviceRunConfigurationWidget::setDeviceInfoLabel(const QString &message, bool isError)
{
m_deviceInfoLabel->setStyleSheet(isError ?
QString(QLatin1String("background-color: red;")) :
QString());
m_deviceInfoLabel->setText(message);
}
void S60DeviceRunConfigurationWidget::updateDeviceInfo()
{
QString message;
setDeviceInfoLabel(tr("Connecting..."));
const bool ok = getDeviceInfo(&message);
setDeviceInfoLabel(message, !ok);
}
bool S60DeviceRunConfigurationWidget::getDeviceInfo(QString *message)
{
// Do a launcher run with the ping protocol. Instantiate launcher on heap
// as not to introduce delays when destructing a device with timeout
trk::Launcher *launcher = new trk::Launcher(trk::Launcher::ActionPingOnly, this);
launcher->setTrkServerName(currentPortName());
if (!launcher->startServer(message)) {
launcher->deleteLater();
return false;
}
// Set up event loop in the foreground with a timer to quit in case of timeout.
QEventLoop eventLoop;
if (!m_infoTimeOutTimer) {
m_infoTimeOutTimer = new QTimer(this);
m_infoTimeOutTimer->setInterval(3000);
m_infoTimeOutTimer->setSingleShot(true);
}
connect(m_infoTimeOutTimer, SIGNAL(timeout()), &eventLoop, SLOT(quit()));
connect(launcher, SIGNAL(finished()), &eventLoop, SLOT(quit()));
// Go!
QApplication::setOverrideCursor(Qt::BusyCursor);
m_infoTimeOutTimer->start();
eventLoop.exec(QEventLoop::ExcludeUserInputEvents);
m_infoTimeOutTimer->disconnect();
QApplication::restoreOverrideCursor();
// Anything received?
*message = launcher->deviceDescription();
launcher->deleteLater();
if (message->isEmpty()) {
*message = tr("A timeout occurred while querying the device. Check whether Trk is running");
return false;
}
return true;
}
} // namespace Internal
} // namespace Qt4ProjectManager
<|endoftext|> |
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
#define IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
#include "iceoryx_hoofs/cxx/optional.hpp"
#include "iceoryx_hoofs/cxx/vector.hpp"
#include <cassert>
#include <iostream>
#include <limits>
namespace iox
{
namespace rp
{
constexpr uint64_t MAX_POINTER_REPO_CAPACITY{10000U};
/// @brief Allows registration of memory segments with their start pointers and size.
/// This class is used to resolve relative pointers in the corresponding address space of the application.
/// Up to CAPACITY segments can be registered with MIN_ID = 1 to MAX_ID = CAPACITY - 1
/// id 0 is reserved and allows relative pointers to behave like normal pointers
/// (which is equivalent to measure the offset relative to 0).
template <typename id_t, typename ptr_t, uint64_t CAPACITY = MAX_POINTER_REPO_CAPACITY>
class PointerRepository
{
private:
struct Info
{
ptr_t basePtr{nullptr};
ptr_t endPtr{nullptr};
};
static constexpr id_t MIN_ID{1U};
static constexpr id_t MAX_ID{CAPACITY - 1U};
static_assert(MAX_ID >= MIN_ID, "MAX_ID must be greater or equal than MIN_ID!");
static_assert(CAPACITY >= 2, "CAPACITY must be at least 2!");
public:
/// @note 0 is a special purpose id and reserved
/// id 0 is reserved to interpret the offset just as a raw pointer,
/// i.e. its corresponding base ptr is 0
static constexpr id_t RAW_POINTER_BEHAVIOUR{0};
/// @brief default constructor
PointerRepository() noexcept;
PointerRepository(const PointerRepository&) = delete;
PointerRepository(PointerRepository&&) = delete;
PointerRepository& operator=(const PointerRepository&) = delete;
PointerRepository& operator=(PointerRepository&&) = delete;
/// @brief registers the start pointer of the segment in another application with a specific id
/// @param[in] id identifies the segment which the pointer should be added to
/// @param[in] ptr is the start pointer of the segment
/// @param[in] size is the size of the segment
/// @return true if the registration was successful, otherwise false
bool registerPtrWithId(id_t id, ptr_t ptr, uint64_t size) noexcept;
/// @brief registers the start pointer of a segment with a specific size
/// @param[in] ptr is the start pointer of the segment
/// @param[in] size is the size of the segment
/// @return the segment id wrapped in an cxx::optional to which the pointer was added, cxx::nullopt if pointer was
/// not added
cxx::optional<id_t> registerPtr(const ptr_t ptr, uint64_t size = 0U) noexcept;
/// @brief unregisters the id
/// @param[in] id is the id to be unregistered
/// @return true if successful, otherwise false
/// @attention the relative pointers corresponding to this id become unsafe to use
bool unregisterPtr(id_t id) noexcept;
/// @brief unregisters all ids
/// @attention the relative pointers corresponding to this id become unsafe to use
void unregisterAll() noexcept;
/// @brief gets the base pointer, i.e. the starting address, associated with id
/// @param[in] id is the segment id
/// @return the base pointer associated with the id
ptr_t getBasePtr(id_t id) const noexcept;
/// @brief returns the id for a given pointer ptr
/// @param[in] ptr is the pointer whose corresponding id is searched for
/// @return the id the pointer was registered to
id_t searchId(ptr_t ptr) const noexcept;
private:
/// @todo: if required protect vector against concurrent modification
/// whether this is required depends on the use case, we currently do not need it
/// we control the ids, so if they are consecutive we only need a vector/array to get the address
/// this variable exists once per application using relative pointers,
/// and each needs to initialize it via register calls above
iox::cxx::vector<Info, CAPACITY> m_info;
uint64_t m_maxRegistered{0U};
};
} // namespace rp
} // namespace iox
#include "iceoryx_hoofs/internal/relocatable_pointer/pointer_repository.inl"
#endif // IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
<commit_msg>iox-#605 Fix clang-tidy warning by adding d'tor to PointerRepository<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
#define IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
#include "iceoryx_hoofs/cxx/optional.hpp"
#include "iceoryx_hoofs/cxx/vector.hpp"
#include <cassert>
#include <iostream>
#include <limits>
namespace iox
{
namespace rp
{
constexpr uint64_t MAX_POINTER_REPO_CAPACITY{10000U};
/// @brief Allows registration of memory segments with their start pointers and size.
/// This class is used to resolve relative pointers in the corresponding address space of the application.
/// Up to CAPACITY segments can be registered with MIN_ID = 1 to MAX_ID = CAPACITY - 1
/// id 0 is reserved and allows relative pointers to behave like normal pointers
/// (which is equivalent to measure the offset relative to 0).
template <typename id_t, typename ptr_t, uint64_t CAPACITY = MAX_POINTER_REPO_CAPACITY>
class PointerRepository
{
private:
struct Info
{
ptr_t basePtr{nullptr};
ptr_t endPtr{nullptr};
};
static constexpr id_t MIN_ID{1U};
static constexpr id_t MAX_ID{CAPACITY - 1U};
static_assert(MAX_ID >= MIN_ID, "MAX_ID must be greater or equal than MIN_ID!");
static_assert(CAPACITY >= 2, "CAPACITY must be at least 2!");
public:
/// @note 0 is a special purpose id and reserved
/// id 0 is reserved to interpret the offset just as a raw pointer,
/// i.e. its corresponding base ptr is 0
static constexpr id_t RAW_POINTER_BEHAVIOUR{0};
/// @brief default constructor
PointerRepository() noexcept;
~PointerRepository() noexcept = default;
PointerRepository(const PointerRepository&) = delete;
PointerRepository(PointerRepository&&) = delete;
PointerRepository& operator=(const PointerRepository&) = delete;
PointerRepository& operator=(PointerRepository&&) = delete;
/// @brief registers the start pointer of the segment in another application with a specific id
/// @param[in] id identifies the segment which the pointer should be added to
/// @param[in] ptr is the start pointer of the segment
/// @param[in] size is the size of the segment
/// @return true if the registration was successful, otherwise false
bool registerPtrWithId(id_t id, ptr_t ptr, uint64_t size) noexcept;
/// @brief registers the start pointer of a segment with a specific size
/// @param[in] ptr is the start pointer of the segment
/// @param[in] size is the size of the segment
/// @return the segment id wrapped in an cxx::optional to which the pointer was added, cxx::nullopt if pointer was
/// not added
cxx::optional<id_t> registerPtr(const ptr_t ptr, uint64_t size = 0U) noexcept;
/// @brief unregisters the id
/// @param[in] id is the id to be unregistered
/// @return true if successful, otherwise false
/// @attention the relative pointers corresponding to this id become unsafe to use
bool unregisterPtr(id_t id) noexcept;
/// @brief unregisters all ids
/// @attention the relative pointers corresponding to this id become unsafe to use
void unregisterAll() noexcept;
/// @brief gets the base pointer, i.e. the starting address, associated with id
/// @param[in] id is the segment id
/// @return the base pointer associated with the id
ptr_t getBasePtr(id_t id) const noexcept;
/// @brief returns the id for a given pointer ptr
/// @param[in] ptr is the pointer whose corresponding id is searched for
/// @return the id the pointer was registered to
id_t searchId(ptr_t ptr) const noexcept;
private:
/// @todo: if required protect vector against concurrent modification
/// whether this is required depends on the use case, we currently do not need it
/// we control the ids, so if they are consecutive we only need a vector/array to get the address
/// this variable exists once per application using relative pointers,
/// and each needs to initialize it via register calls above
iox::cxx::vector<Info, CAPACITY> m_info;
uint64_t m_maxRegistered{0U};
};
} // namespace rp
} // namespace iox
#include "iceoryx_hoofs/internal/relocatable_pointer/pointer_repository.inl"
#endif // IOX_HOOFS_RELOCATABLE_POINTER_POINTER_REPOSITORY_HPP
<|endoftext|> |
<commit_before>/*
* Runtime CPU detection
* (C) 2009-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/get_byte.h>
#include <botan/mem_ops.h>
#if defined(BOTAN_TARGET_OS_IS_DARWIN)
#include <sys/sysctl.h>
#endif
#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <intrin.h>
#define CALL_CPUID(type, out) do { __cpuid((int*)out, type); } while(0)
#elif defined(BOTAN_BUILD_COMPILER_IS_INTEL)
#include <ia32intrin.h>
#define CALL_CPUID(type, out) do { __cpuid(out, type); } while(0);
#elif (BOTAN_GCC_VERSION >= 430)
// Only available starting in GCC 4.3
#include <cpuid.h>
namespace {
/*
* Prevent inlining to work around GCC bug 44174
*/
void __attribute__((__noinline__)) call_gcc_cpuid(Botan::u32bit type,
Botan::u32bit out[4])
{
__get_cpuid(type, out, out+1, out+2, out+3);
}
#define CALL_CPUID call_gcc_cpuid
}
#else
#warning "No method of calling CPUID for this compiler"
#endif
#endif
#ifndef CALL_CPUID
// In all other cases, just zeroize the supposed cpuid output
#define CALL_CPUID(type, out) \
do { out[0] = out[1] = out[2] = out[3] = 0; } while(0);
#endif
namespace Botan {
u64bit CPUID::x86_processor_flags = 0;
size_t CPUID::cache_line = 32;
bool CPUID::altivec_capable = false;
namespace {
u32bit get_x86_cache_line_size()
{
const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };
u32bit cpuid[4] = { 0 };
CALL_CPUID(0, cpuid);
if(same_mem(cpuid + 1, INTEL_CPUID, 3))
{
CALL_CPUID(1, cpuid);
return 8 * get_byte(2, cpuid[1]);
}
else if(same_mem(cpuid + 1, AMD_CPUID, 3))
{
CALL_CPUID(0x80000005, cpuid);
return get_byte(3, cpuid[2]);
}
else
return 32; // default cache line guess
}
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
bool altivec_check_sysctl()
{
#if defined(BOTAN_TARGET_OS_IS_DARWIN)
// From Apple's docs
int sels[2] = { CTL_HW, HW_VECTORUNIT };
int vector_type = 0;
size_t length = sizeof(vector_type);
int error = sysctl(sels, 2, &vector_type, &length, NULL, 0);
if(error == 0 && vector_type > 0)
return true;
#endif
return false;
}
bool altivec_check_pvr_emul()
{
bool altivec_capable = false;
#if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_NETBSD)
/*
On PowerPC, MSR 287 is PVR, the Processor Version Number
Normally it is only accessible to ring 0, but Linux and NetBSD
(others, too, maybe?) will trap and emulate it for us.
PVR identifiers for various AltiVec enabled CPUs. Taken from
PearPC and Linux sources, mostly.
*/
const u16bit PVR_G4_7400 = 0x000C;
const u16bit PVR_G5_970 = 0x0039;
const u16bit PVR_G5_970FX = 0x003C;
const u16bit PVR_G5_970MP = 0x0044;
const u16bit PVR_G5_970GX = 0x0045;
const u16bit PVR_POWER6 = 0x003E;
const u16bit PVR_POWER7 = 0x003F;
const u16bit PVR_CELL_PPU = 0x0070;
// Motorola produced G4s with PVR 0x800[0123C] (at least)
const u16bit PVR_G4_74xx_24 = 0x800;
u32bit pvr = 0;
asm volatile("mfspr %0, 287" : "=r" (pvr));
// Top 16 bit suffice to identify model
pvr >>= 16;
altivec_capable |= (pvr == PVR_G4_7400);
altivec_capable |= ((pvr >> 4) == PVR_G4_74xx_24);
altivec_capable |= (pvr == PVR_G5_970);
altivec_capable |= (pvr == PVR_G5_970FX);
altivec_capable |= (pvr == PVR_G5_970MP);
altivec_capable |= (pvr == PVR_G5_970GX);
altivec_capable |= (pvr == PVR_POWER6);
altivec_capable |= (pvr == PVR_POWER7);
altivec_capable |= (pvr == PVR_CELL_PPU);
#endif
return altivec_capable;
}
#endif
}
void CPUID::initialize()
{
u32bit cpuid[4] = { 0 };
CALL_CPUID(1, cpuid);
x86_processor_flags = (static_cast<u64bit>(cpuid[2]) << 32) | cpuid[3];
#if defined(BOTAN_TARGET_ARCH_IS_X86_64)
/*
* If we don't have access to CPUID, we can still safely assume that
* any x86-64 processor has SSE2.
*/
if(x86_processor_flags == 0)
x86_processor_flags |= (1 << CPUID_SSE2_BIT);
#endif
cache_line = get_x86_cache_line_size();
altivec_capable = false;
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
if(altivec_check_sysctl() || altivec_check_pvr_emul())
altivec_capable = true;
#endif
}
}
<commit_msg>Call cpuid via inline asm on x86-64, so we can use it with Clang (no cpuid intrinsic) and older GCC (no cpuid.h before 4.3)<commit_after>/*
* Runtime CPU detection
* (C) 2009-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/cpuid.h>
#include <botan/types.h>
#include <botan/get_byte.h>
#include <botan/mem_ops.h>
#if defined(BOTAN_TARGET_OS_IS_DARWIN)
#include <sys/sysctl.h>
#endif
#if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY)
#if defined(BOTAN_BUILD_COMPILER_IS_MSVC)
#include <intrin.h>
#define CALL_CPUID(type, out) do { __cpuid((int*)out, type); } while(0)
#elif defined(BOTAN_BUILD_COMPILER_IS_INTEL)
#include <ia32intrin.h>
#define CALL_CPUID(type, out) do { __cpuid(out, type); } while(0)
#elif defined(BOTAN_BUILD_COMPILER_IS_GCC) && (BOTAN_GCC_VERSION >= 430)
// Only available starting in GCC 4.3
#include <cpuid.h>
namespace {
/*
* Prevent inlining to work around GCC bug 44174
*/
void __attribute__((__noinline__)) call_gcc_cpuid(Botan::u32bit type,
Botan::u32bit out[4])
{
__get_cpuid(type, out, out+1, out+2, out+3);
}
#define CALL_CPUID call_gcc_cpuid
}
#elif defined(BOTAN_TARGET_ARCH_IS_X86_64) && \
(defined(BOTAN_BUILD_COMPILER_IS_CLANG) || defined(BOTAN_BUILD_COMPILER_IS_GCC))
/*
* We can't safely use this on x86-32 as some 32-bit ABIs use ebx as
* a PIC register, and in theory there are some x86-32s still out
* there that don't support cpuid at all; it requires strange
* contortions to detect them.
*/
#define CALL_CPUID(type, out) \
asm("cpuid\n\t" : "=a" (out[0]), "=b" (out[1]), "=c" (out[2]), "=d" (out[3]) \
: "0" (type))
#else
#warning "No method of calling CPUID for this compiler"
#endif
#endif
#ifndef CALL_CPUID
// In all other cases, just zeroize the supposed cpuid output
#define CALL_CPUID(type, out) \
do { out[0] = out[1] = out[2] = out[3] = 0; } while(0);
#endif
namespace Botan {
u64bit CPUID::x86_processor_flags = 0;
size_t CPUID::cache_line = 32;
bool CPUID::altivec_capable = false;
namespace {
u32bit get_x86_cache_line_size()
{
const u32bit INTEL_CPUID[3] = { 0x756E6547, 0x6C65746E, 0x49656E69 };
const u32bit AMD_CPUID[3] = { 0x68747541, 0x444D4163, 0x69746E65 };
u32bit cpuid[4] = { 0 };
CALL_CPUID(0, cpuid);
if(same_mem(cpuid + 1, INTEL_CPUID, 3))
{
CALL_CPUID(1, cpuid);
return 8 * get_byte(2, cpuid[1]);
}
else if(same_mem(cpuid + 1, AMD_CPUID, 3))
{
CALL_CPUID(0x80000005, cpuid);
return get_byte(3, cpuid[2]);
}
else
return 32; // default cache line guess
}
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
bool altivec_check_sysctl()
{
#if defined(BOTAN_TARGET_OS_IS_DARWIN)
// From Apple's docs
int sels[2] = { CTL_HW, HW_VECTORUNIT };
int vector_type = 0;
size_t length = sizeof(vector_type);
int error = sysctl(sels, 2, &vector_type, &length, NULL, 0);
if(error == 0 && vector_type > 0)
return true;
#endif
return false;
}
bool altivec_check_pvr_emul()
{
bool altivec_capable = false;
#if defined(BOTAN_TARGET_OS_IS_LINUX) || defined(BOTAN_TARGET_OS_IS_NETBSD)
/*
On PowerPC, MSR 287 is PVR, the Processor Version Number
Normally it is only accessible to ring 0, but Linux and NetBSD
(others, too, maybe?) will trap and emulate it for us.
PVR identifiers for various AltiVec enabled CPUs. Taken from
PearPC and Linux sources, mostly.
*/
const u16bit PVR_G4_7400 = 0x000C;
const u16bit PVR_G5_970 = 0x0039;
const u16bit PVR_G5_970FX = 0x003C;
const u16bit PVR_G5_970MP = 0x0044;
const u16bit PVR_G5_970GX = 0x0045;
const u16bit PVR_POWER6 = 0x003E;
const u16bit PVR_POWER7 = 0x003F;
const u16bit PVR_CELL_PPU = 0x0070;
// Motorola produced G4s with PVR 0x800[0123C] (at least)
const u16bit PVR_G4_74xx_24 = 0x800;
u32bit pvr = 0;
asm volatile("mfspr %0, 287" : "=r" (pvr));
// Top 16 bit suffice to identify model
pvr >>= 16;
altivec_capable |= (pvr == PVR_G4_7400);
altivec_capable |= ((pvr >> 4) == PVR_G4_74xx_24);
altivec_capable |= (pvr == PVR_G5_970);
altivec_capable |= (pvr == PVR_G5_970FX);
altivec_capable |= (pvr == PVR_G5_970MP);
altivec_capable |= (pvr == PVR_G5_970GX);
altivec_capable |= (pvr == PVR_POWER6);
altivec_capable |= (pvr == PVR_POWER7);
altivec_capable |= (pvr == PVR_CELL_PPU);
#endif
return altivec_capable;
}
#endif
}
void CPUID::initialize()
{
u32bit cpuid[4] = { 0 };
CALL_CPUID(1, cpuid);
x86_processor_flags = (static_cast<u64bit>(cpuid[2]) << 32) | cpuid[3];
#if defined(BOTAN_TARGET_ARCH_IS_X86_64)
/*
* If we don't have access to CPUID, we can still safely assume that
* any x86-64 processor has SSE2.
*/
if(x86_processor_flags == 0)
x86_processor_flags |= (1 << CPUID_SSE2_BIT);
#endif
cache_line = get_x86_cache_line_size();
altivec_capable = false;
#if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY)
if(altivec_check_sysctl() || altivec_check_pvr_emul())
altivec_capable = true;
#endif
}
}
<|endoftext|> |
<commit_before>
#include "../src/clientconsole.h"
#include "../../include/catch.hpp"
#include <QFile>
/*
template<class R, class... Args >
class funcRef<R(Args...)> {
};
*/
template <class C>
class RefData {
bool topLevel;
C * data;
public:
RefData() : data(new C), topLevel(true) {};
RefData(const C & d) : data(new C(d)) {};
RefData(const RefData & o) : data(o.data), topLevel(false) {};
~RefData() {
if (topLevel) delete data;
};
RefData & operator= (const RefData &) = delete;
RefData & operator= (const C & d) {
*data = d;
return *this;
};
C & getData() { return *data; };
const C & getData() const { return *data; };
operator C &() { return *data; };
operator const C &() const { return *data; };
};
class TestParseIntercept {
bool checkType;
Messages::MsgType type;
RefData<Messages::ReceivedMessage> data;
public:
TestParseIntercept() : checkType(false) {};
TestParseIntercept(Messages::MsgType t) : type(t), checkType(true){ };
TestParseIntercept(const TestParseIntercept & o) : checkType(o.checkType), type(o.type), data(o.data) {};
~TestParseIntercept() {};
void operator()(Session & session, Messages::MsgType t, const Messages::ReceivedMessage & payload) {
if (checkType && type != t) throw MessageException("Wrong type returned!");
data = payload;
};
operator Messages::ReceivedMessage &() {
return data;
};
Messages::ReceivedMessage & getData() {
return data;
};
};
class TestSession {
Session *s1;
Session *s2;
public:
TestSession() {
mbedtls_entropy_context mtls_entropy;
mbedtls_entropy_init(&mtls_entropy);
mbedtls_entropy_gather(&mtls_entropy);
s1 = new Session("ke@##$VFSDBket", "druhykeket#@1431", &mtls_entropy);
s2 = new Session("druhykeket#@1431", "ke@##$VFSDBket", &mtls_entropy);
exchangeDH();
};
void exchangeDH() {
//get each other's Diffie Hellman
s1->getKey().setDH(s2->getKey().getDH());
s2->getKey().setDH(s1->getKey().getDH());
//generate private key
s1->getKey().generateKey();
s2->getKey().generateKey();
};
~TestSession() {
delete s1;
delete s2;
};
Session & getS1() { return *s1; };
Session & getS2() { return *s2; };
};
class TestSessionHandler {
Session & s;
public:
TestSessionHandler(Session & s) : s(s) {};
Session & operator()(const QString & name) {
if (name.compare(s.getPartnerName())) throw MessageException("Unknown sender!");
return s;
};
};
class TestDataSender {
public:
TestDataSender() {};
void operator()(const QByteArray & data) {
qDebug() << data.length();
};
};
class TestDataSender2 {
std::function<Session &(const QString &)> sessionHandler;
std::function<void(Session &, Messages::MsgType, const Messages::ReceivedMessage &)> callback;
public:
TestDataSender2(std::function<void(Session &, Messages::MsgType, const Messages::ReceivedMessage &)> cb, std::function<Session &(const QString &)> s) : callback(cb), sessionHandler(s) {};
TestDataSender2(const TestDataSender2 & o) : callback(o.callback), sessionHandler(o.sessionHandler) {};
void operator()(const QByteArray & data) {
Messages::parseMessage(sessionHandler, data, callback);
};
};
class TestDataSender3 {
std::function<void(qint64, qint64, const QByteArray &)> callback;
public:
TestDataSender3(std::function<void(qint64, qint64, const QByteArray &)> cb) : callback(cb) {};
TestDataSender3(const TestDataSender3 & o) : callback(o.callback) {};
void operator()(Session & s, Messages::MsgType t, const Messages::ReceivedMessage & data) {
QList<QByteArray> list = data.messageText.split(Messages::armaSeparator);
qint64 id = list[0].toLongLong();
qint64 start = list[1].toLongLong();
qint64 len = list[2].toLongLong();
callback(start, len, data.messageText.right(data.messageText.length() - (list[0].length() + list[1].length() + list[2].length() + 3)));
};
};
TEST_CASE("Key exchange", "[Krypto]") {
mbedtls_entropy_context mtls_entropy;
mbedtls_entropy_init(&mtls_entropy);
mbedtls_entropy_gather(&mtls_entropy);
//Create "virtual" sessions for both clients
Session s("ke@##$VFSDBket", "druhykeket#@1431", &mtls_entropy);
Session s2("druhykeket#@1431", "ke@##$VFSDBket", &mtls_entropy);
QSet<QString> usedKeys;
for (int i = 0; i < 20; ++i) {
//get each other's Diffie Hellman
s.getKey().setDH(s2.getKey().getDH());
s2.getKey().setDH(s.getKey().conditionalGetDH());
//generate private key
s.getKey().generateKey();
s2.getKey().generateKey();
//the key must be the same
REQUIRE_FALSE(usedKeys.contains(s.getKey().getSharedKey()));
usedKeys.insert(s.getKey().getSharedKey());
REQUIRE(usedKeys.contains(s.getKey().getSharedKey()));
bool same = s.getKey().getSharedKey() == s2.getKey().getSharedKey();
REQUIRE(same);
REQUIRE(s.getKey().getSharedKey().length() == 256);
}
REQUIRE(usedKeys.size() == 20);
}
TEST_CASE("Sending simple message", "[message]") {
TestSession s;
// Send simple message
Messages m(nullptr, 0);
QString sprava("TESTOVACIA SPRAVA # wlivywouihfwicdcoywgv aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas");
QByteArray encrypted = m.createRegularMessage(s.getS1(), sprava);
// Recieve simple message
TestParseIntercept received;
bool valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received);
REQUIRE(valid);
QString receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
}
TEST_CASE("Sending complex messages", "[message]") {
TestSession s;
Messages m(nullptr, 0);
QString sprava("TESTOVACIA SPRAVA");
QByteArray encrypted = m.createRegularMessage(s.getS1(), sprava);
// qDebug() << "PROTECTED: " << encrypted;
TestParseIntercept received;
bool valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received);
REQUIRE(valid);
// qDebug() << "Raw unprotected = " << received.messageText;
QString receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
sprava = "In sprva s diakritikou. # a pecilnym znakom ooooha";
encrypted = m.createRegularMessage(s.getS2(), sprava);
valid = m.parseMessage(TestSessionHandler(s.getS1()), encrypted, received);
receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
//without key change:
sprava = "Tto sprva sa pouije niekokokrt z jednej session";
for (int i = 0; i<10; ++i) {
encrypted = m.createRegularMessage(s.getS1(), sprava);
valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received);
receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
}
REQUIRE_THROWS_AS(encrypted = m.createRegularMessage(s.getS1(), sprava), KryptoOveruseException);
REQUIRE_THROWS_AS(encrypted = m.createRegularMessage(s.getS1(), sprava), KryptoOveruseException);
REQUIRE_FALSE(m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received));
REQUIRE_FALSE(m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received));
}
TEST_CASE("Sending out of order message", "[message]") {
TestSession s;
// Send simple message
Messages m(nullptr, 0);
QString sprava("TESTOVACIA SPRAVA # wlivywouihfwicdcoywgv aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas");
QByteArray encrypted = m.createRegularMessage(s.getS1(), sprava);
s.exchangeDH();
TestParseIntercept received;
bool valid;
for (int i = 0; i < 10; ++i) {
// Recieve simple message
REQUIRE_NOTHROW(valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received));
REQUIRE(valid);
QString receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
}
REQUIRE_FALSE(m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received));
}
TEST_CASE("Performance tests", "[message]") {
TestSession s;
Messages m(nullptr, 0);
QString originalMessage("ORIGINAL MESSAGE WITH SIZE = 32B");
QString sprava;
QByteArray encrypted;
bool valid;
TestParseIntercept received;
QString receivedString;
clock_t encryptStart, encryptEnd, decryptStart, decryptEnd;
double timeSpentEncrypt, timeSpentDecrypt;
for (int i = 1; i <= 0; ++i) {
sprava = originalMessage.repeated(2);
encryptStart = clock();
encrypted = m.createRegularMessage(s.getS1(), sprava);
encryptEnd = clock();
decryptStart = clock();
valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received);
decryptEnd = clock();
receivedString = QString::fromUtf8(received.getData().messageText);
timeSpentEncrypt = (encryptEnd - encryptStart) / ((double)CLOCKS_PER_SEC / 1000);
timeSpentDecrypt = (decryptEnd - decryptStart) / ((double)CLOCKS_PER_SEC / 1000);
qDebug() << "Message Size: " << sprava.size() << "B, encrypt time: " << qSetRealNumberPrecision(10) << timeSpentEncrypt
<< "ms, decrypt time: " << timeSpentDecrypt << "ms";
REQUIRE(receivedString == sprava);
originalMessage = sprava;
s.exchangeDH();
}
}
TEST_CASE("Sending file", "[File transfer]") {
static const char * path = "test.t";
QFile file(path);
file.open(QIODevice::WriteOnly);
QString testData = "ORIGINAL MESSAGE WITH SIZE = 32B\nORIGINAL MESSAGE WITH SIZE = 32B";
file.write(testData.toUtf8());
file.close();
TestSession s;
Messages::FileSendingContext test(s.getS1(), path, TestDataSender());
REQUIRE_NOTHROW(test.startSending());
QThread::sleep(3);
file.remove();
}
TEST_CASE("Sending long files", "[File transfer]") {
static const char * path = "test.t";
QFile file(path);
TestSession s;
QString testData = "My little test\nTesting\n";
for (int i = 1; i < 32; i *= 2) {
file.open(QIODevice::WriteOnly);
do {
testData += testData;
} while (testData.length() <= i * Messages::maxChunkSize);
file.write(testData.toUtf8());
file.close();
s.exchangeDH();
Messages::FileSendingContext test(s.getS1(), path, TestDataSender());
REQUIRE_NOTHROW(test.startSending());
}
QThread::sleep(5);
file.remove();
}
void helperFunction(Messages::MsgType t, const Messages::ReceivedMessage & data) {
qDebug() << "Message(" << t << "): " << data.messageText;
}
TEST_CASE("Receiving file", "[File transfer]") {
static const char * path = "test.t";
static const char * path2 = "test_r.t";
QFile file(path);
file.open(QIODevice::WriteOnly);
const QString testData = "ORIGINAL MESSAGE WITH SIZE = 32B\nORIGINAL MESSAGE WITH SIZE = 32B";
file.write(testData.toUtf8());
file.close();
TestSession s;
QByteArray msg;
Messages::FileReceivingContext testr(s.getS2(), path2);
Messages::FileSendingContext test(s.getS1(), path, TestDataSender2(TestDataSender3(testr), TestSessionHandler(s.getS2())));
REQUIRE_NOTHROW(test.startSending());
QThread::sleep(3);
file.remove();
QFile file2(path2);
file2.open(QIODevice::ReadOnly);
QString t_data = QString::fromUtf8(file2.readAll());
REQUIRE(t_data == testData);
file2.close();
file2.remove();
}
<commit_msg>Improved unit tests<commit_after>
#include <stdexcept>
#include "../src/clientconsole.h"
#include "../../include/catch.hpp"
#include <QFile>
/*
template<class R, class... Args >
class funcRef<R(Args...)> {
};
*/
template <class C>
class RefData {
bool topLevel;
C * data;
public:
RefData() : data(new C), topLevel(true) {};
RefData(const C & d) : data(new C(d)) {};
RefData(const RefData & o) : data(o.data), topLevel(false) {};
~RefData() {
if (topLevel) delete data;
};
RefData & operator= (const RefData &) = delete;
RefData & operator= (const C & d) {
*data = d;
return *this;
};
C & getData() { return *data; };
const C & getData() const { return *data; };
operator C &() { return *data; };
operator const C &() const { return *data; };
};
class TestParseIntercept {
bool checkType;
Messages::MsgType type;
RefData<Messages::ReceivedMessage> data;
public:
TestParseIntercept() : checkType(false) {};
TestParseIntercept(Messages::MsgType t) : type(t), checkType(true){ };
TestParseIntercept(const TestParseIntercept & o) : checkType(o.checkType), type(o.type), data(o.data) {};
~TestParseIntercept() {};
void operator()(Session & session, Messages::MsgType t, const Messages::ReceivedMessage & payload) {
if (checkType && type != t) throw MessageException("Wrong type returned!");
data = payload;
};
operator Messages::ReceivedMessage &() {
return data;
};
Messages::ReceivedMessage & getData() {
return data;
};
};
class TestSession {
Session *s1;
Session *s2;
public:
TestSession() {
mbedtls_entropy_context mtls_entropy;
mbedtls_entropy_init(&mtls_entropy);
mbedtls_entropy_gather(&mtls_entropy);
s1 = new Session("ke@##$VFSDBket", "druhykeket#@1431", &mtls_entropy);
s2 = new Session("druhykeket#@1431", "ke@##$VFSDBket", &mtls_entropy);
exchangeDH();
};
void exchangeDH() {
//get each other's Diffie Hellman
s1->getKey().setDH(s2->getKey().getDH());
s2->getKey().setDH(s1->getKey().getDH());
//generate private key
s1->getKey().generateKey();
s2->getKey().generateKey();
};
~TestSession() {
delete s1;
delete s2;
};
Session & getS1() { return *s1; };
Session & getS2() { return *s2; };
};
class TestSessionHandler {
Session & s;
public:
TestSessionHandler(Session & s) : s(s) {};
Session & operator()(const QString & name) {
if (name.compare(s.getPartnerName())) throw MessageException("Unknown sender!");
return s;
};
};
class TestDataSender {
public:
TestDataSender() {};
void operator()(const QByteArray & data) {
qDebug() << data.length();
};
};
class TestDataSender2 {
std::function<Session &(const QString &)> sessionHandler;
std::function<void(Session &, Messages::MsgType, const Messages::ReceivedMessage &)> callback;
public:
TestDataSender2(std::function<void(Session &, Messages::MsgType, const Messages::ReceivedMessage &)> cb, std::function<Session &(const QString &)> s) : callback(cb), sessionHandler(s) {};
TestDataSender2(const TestDataSender2 & o) : callback(o.callback), sessionHandler(o.sessionHandler) {};
void operator()(const QByteArray & data) {
Messages::parseMessage(sessionHandler, data, callback);
};
};
class TestDataSender3 {
Messages::MsgType expectedType;
std::function<void(qint64, qint64, const QByteArray &)> callback;
public:
TestDataSender3(std::function<void(qint64, qint64, const QByteArray &)> cb, Messages::MsgType expectedType = Messages::MsgType::None) : callback(cb), expectedType(expectedType) {};
TestDataSender3(const TestDataSender3 & o) : callback(o.callback), expectedType(o.expectedType) {};
void operator()(Session & s, Messages::MsgType t, const Messages::ReceivedMessage & data) {
if (expectedType != Messages::MsgType::None && expectedType != t) throw std::runtime_error("Test: Invalid message type!");
QList<QByteArray> list = data.messageText.split(Messages::armaSeparator);
qint64 id = list[0].toLongLong();
qint64 start = list[1].toLongLong();
qint64 len = list[2].toLongLong();
callback(start, len, data.messageText.right(data.messageText.length() - (list[0].length() + list[1].length() + list[2].length() + 3)));
};
};
TEST_CASE("Key exchange", "[Krypto]") {
mbedtls_entropy_context mtls_entropy;
mbedtls_entropy_init(&mtls_entropy);
mbedtls_entropy_gather(&mtls_entropy);
//Create "virtual" sessions for both clients
Session s("ke@##$VFSDBket", "druhykeket#@1431", &mtls_entropy);
Session s2("druhykeket#@1431", "ke@##$VFSDBket", &mtls_entropy);
QSet<QString> usedKeys;
for (int i = 0; i < 20; ++i) {
//get each other's Diffie Hellman
s.getKey().setDH(s2.getKey().getDH());
s2.getKey().setDH(s.getKey().conditionalGetDH());
//generate private key
s.getKey().generateKey();
s2.getKey().generateKey();
//the key must be the same
REQUIRE_FALSE(usedKeys.contains(s.getKey().getSharedKey()));
usedKeys.insert(s.getKey().getSharedKey());
REQUIRE(usedKeys.contains(s.getKey().getSharedKey()));
bool same = s.getKey().getSharedKey() == s2.getKey().getSharedKey();
REQUIRE(same);
REQUIRE(s.getKey().getSharedKey().length() == 256);
}
REQUIRE(usedKeys.size() == 20);
}
TEST_CASE("Sending simple message", "[message]") {
TestSession s;
// Send simple message
Messages m(nullptr, 0);
QString sprava("TESTOVACIA SPRAVA # wlivywouihfwicdcoywgv aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas");
QByteArray encrypted = m.createRegularMessage(s.getS1(), sprava);
// Recieve simple message
TestParseIntercept received;
bool valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received);
REQUIRE(valid);
QString receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
}
TEST_CASE("Sending complex messages", "[message]") {
TestSession s;
Messages m(nullptr, 0);
QString sprava("TESTOVACIA SPRAVA");
QByteArray encrypted = m.createRegularMessage(s.getS1(), sprava);
// qDebug() << "PROTECTED: " << encrypted;
TestParseIntercept received;
bool valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received);
REQUIRE(valid);
// qDebug() << "Raw unprotected = " << received.messageText;
QString receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
sprava = "In sprva s diakritikou. # a pecilnym znakom ooooha";
encrypted = m.createRegularMessage(s.getS2(), sprava);
valid = m.parseMessage(TestSessionHandler(s.getS1()), encrypted, received);
receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
//without key change:
sprava = "Tto sprva sa pouije niekokokrt z jednej session";
for (int i = 0; i<10; ++i) {
encrypted = m.createRegularMessage(s.getS1(), sprava);
valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received);
receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
}
REQUIRE_THROWS_AS(encrypted = m.createRegularMessage(s.getS1(), sprava), KryptoOveruseException);
REQUIRE_THROWS_AS(encrypted = m.createRegularMessage(s.getS1(), sprava), KryptoOveruseException);
REQUIRE_FALSE(m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received));
REQUIRE_FALSE(m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received));
}
TEST_CASE("Sending out of order message", "[message]") {
TestSession s;
// Send simple message
Messages m(nullptr, 0);
QString sprava("TESTOVACIA SPRAVA # wlivywouihfwicdcoywgv aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaas");
QByteArray encrypted = m.createRegularMessage(s.getS1(), sprava);
s.exchangeDH();
TestParseIntercept received;
bool valid;
for (int i = 0; i < 10; ++i) {
// Recieve simple message
REQUIRE_NOTHROW(valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received));
REQUIRE(valid);
QString receivedString = QString::fromUtf8(received.getData().messageText);
REQUIRE(receivedString == sprava);
}
REQUIRE_FALSE(m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received));
}
TEST_CASE("Performance tests", "[message]") {
TestSession s;
Messages m(nullptr, 0);
QString originalMessage("ORIGINAL MESSAGE WITH SIZE = 32B");
QString sprava;
QByteArray encrypted;
bool valid;
TestParseIntercept received;
QString receivedString;
clock_t encryptStart, encryptEnd, decryptStart, decryptEnd;
double timeSpentEncrypt, timeSpentDecrypt;
for (int i = 1; i <= 0; ++i) {
sprava = originalMessage.repeated(2);
encryptStart = clock();
encrypted = m.createRegularMessage(s.getS1(), sprava);
encryptEnd = clock();
decryptStart = clock();
valid = m.parseMessage(TestSessionHandler(s.getS2()), encrypted, received);
decryptEnd = clock();
receivedString = QString::fromUtf8(received.getData().messageText);
timeSpentEncrypt = (encryptEnd - encryptStart) / ((double)CLOCKS_PER_SEC / 1000);
timeSpentDecrypt = (decryptEnd - decryptStart) / ((double)CLOCKS_PER_SEC / 1000);
qDebug() << "Message Size: " << sprava.size() << "B, encrypt time: " << qSetRealNumberPrecision(10) << timeSpentEncrypt
<< "ms, decrypt time: " << timeSpentDecrypt << "ms";
REQUIRE(receivedString == sprava);
originalMessage = sprava;
s.exchangeDH();
}
}
TEST_CASE("Sending file", "[File transfer]") {
static const char * path = "test.t";
QFile file(path);
file.open(QIODevice::WriteOnly);
QString testData = "ORIGINAL MESSAGE WITH SIZE = 32B\nORIGINAL MESSAGE WITH SIZE = 32B";
file.write(testData.toUtf8());
file.close();
TestSession s;
Messages::FileSendingContext test(s.getS1(), path, TestDataSender());
REQUIRE_NOTHROW(test.startSending());
QThread::sleep(3);
file.remove();
}
TEST_CASE("Sending long files", "[File transfer]") {
static const char * path = "test.t";
QFile file(path);
TestSession s;
QString testData = "My little test\nTesting\n";
for (int i = 1; i < 32; i *= 2) {
file.open(QIODevice::WriteOnly);
do {
testData += testData;
} while (testData.length() <= i * Messages::maxChunkSize);
file.write(testData.toUtf8());
file.close();
s.exchangeDH();
Messages::FileSendingContext test(s.getS1(), path, TestDataSender());
REQUIRE_NOTHROW(test.startSending());
}
QThread::sleep(5);
file.remove();
}
void helperFunction(Messages::MsgType t, const Messages::ReceivedMessage & data) {
qDebug() << "Message(" << t << "): " << data.messageText;
}
TEST_CASE("Receiving file", "[File transfer]") {
static const char * path = "test.t";
static const char * path2 = "test_r.t";
QFile file(path);
file.open(QIODevice::WriteOnly);
const QString testData = "ORIGINAL MESSAGE WITH SIZE = 32B\nORIGINAL MESSAGE WITH SIZE = 32B";
file.write(testData.toUtf8());
file.close();
TestSession s;
QByteArray msg;
Messages::FileReceivingContext testr(s.getS2(), path2);
Messages::FileSendingContext test(s.getS1(), path, TestDataSender2(TestDataSender3(testr), TestSessionHandler(s.getS2())));
REQUIRE_NOTHROW(test.startSending());
QThread::sleep(3);
file.remove();
QFile file2(path2);
file2.open(QIODevice::ReadOnly);
QString t_data = QString::fromUtf8(file2.readAll());
REQUIRE(t_data == testData);
file2.close();
file2.remove();
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdint.h>
#include <math.h>
#undef DEBUG_PRINT
// For lightweight communication with the FPGA:
#define FPGA_MANAGER_BASE 0xFF706000
#define FPGA_GPO_OFFSET 0x10
#define FPGA_GPI_OFFSET 0x14
// HPS-to-FPGA:
#define H2F_DATA_READY (1 << 0)
// FPGA-to-HPS:
#define F2H_BUSY (1 << 0)
// Shared memory addresses:
#define BASE 0x38000000
#define RAM_SIZE 0x40000000
#define COLOR_BUFFER_1_OFFSET 0
#define BUFFER_SIZE (800*480*4)
#define COLOR_BUFFER_2_OFFSET (COLOR_BUFFER_1_OFFSET + BUFFER_SIZE)
#define Z_BUFFER_OFFSET (COLOR_BUFFER_2_OFFSET + BUFFER_SIZE)
#define PROTOCOL_BUFFER_OFFSET (Z_BUFFER_OFFSET + BUFFER_SIZE)
// Protocol command number:
#define CMD_CLEAR 1
#define CMD_ZCLEAR 2
#define CMD_PATTERN 3
#define CMD_DRAW 4
#define CMD_BITMAP 5
#define CMD_SWAP 6
#define CMD_END 7
// Draw type:
#define DRAW_TRIANGLES 0
#define DRAW_LINES 1
#define DRAW_POINTS 2
#define DRAW_LINE_STRIP 3
#define DRAW_TRIANGLE_STRIP 5
#define DRAW_TRIANGLE_FAN 6
void cmd_clear(volatile uint64_t **p, uint8_t red, uint8_t green, uint8_t blue)
{
*(*p)++ = CMD_CLEAR
| ((uint64_t) red << 56)
| ((uint64_t) green << 48)
| ((uint64_t) blue << 40);
}
void cmd_pattern(volatile uint64_t **p,
uint64_t pattern0,
uint64_t pattern1,
uint64_t pattern2,
uint64_t pattern3)
{
*(*p)++ = CMD_PATTERN;
*(*p)++ = pattern0;
*(*p)++ = pattern1;
*(*p)++ = pattern2;
*(*p)++ = pattern3;
}
void cmd_draw(volatile uint64_t **p, int type, int count, int pattern_enable)
{
*(*p)++ = CMD_DRAW
| ((uint64_t) type << 8)
| ((uint64_t) count << 16)
| ((uint64_t) pattern_enable << 33);
}
void vertex(volatile uint64_t **p, int x, int y, int z,
uint8_t red, uint8_t green, uint8_t blue)
{
*(*p)++ =
((uint64_t) x << 2)
| ((uint64_t) y << 15)
| ((uint64_t) red << 56)
| ((uint64_t) green << 48)
| ((uint64_t) blue << 40);
}
void cmd_swap(volatile uint64_t **p)
{
*(*p)++ = CMD_SWAP;
}
void cmd_end(volatile uint64_t **p)
{
*(*p)++ = CMD_END;
}
int main()
{
float speed = 0.001;
int dev_mem = open("/dev/mem", O_RDWR);
if(dev_mem == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// Get access to lightweight FPGA communication.
uint8_t *fpga_manager_base = (uint8_t *) mmap(0, 64,
PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem, FPGA_MANAGER_BASE);
if(fpga_manager_base == MAP_FAILED) {
perror("mmap for fpga manager base");
exit(EXIT_FAILURE);
}
volatile uint32_t *gpo = (uint32_t*)(fpga_manager_base + FPGA_GPO_OFFSET);
volatile uint32_t *gpi = (uint32_t*)(fpga_manager_base + FPGA_GPI_OFFSET);
// Get access to the various RAM buffers.
uint8_t *buffers_base = (uint8_t *) mmap(0, RAM_SIZE - BASE,
PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem, BASE);
if(buffers_base == MAP_FAILED) {
perror("mmap for buffers");
exit(EXIT_FAILURE);
}
volatile uint64_t *protocol_buffer =
(uint64_t *) (buffers_base + PROTOCOL_BUFFER_OFFSET);
*gpo = 0;
int counter = 0;
while (1) {
// Start of frame.
if ((*gpi & F2H_BUSY) != 0) {
printf("Warning: FPGA is busy at top of loop.\n");
}
// Write protocol buffer.
#ifdef DEBUG_PRINT
printf("Writing protocol buffer.\n");
#endif
volatile uint64_t *p = protocol_buffer;
if (0) {
cmd_clear(&p,
(counter & 0x04) ? 255 : 0,
(counter & 0x02) ? 255 : 0,
(counter & 0x01) ? 255 : 0);
} else {
cmd_clear(&p, 0, 0, 0);
}
cmd_pattern(&p,
0x5555aaaa5555aaaaLL,
0x5555aaaa5555aaaaLL,
0x5555aaaa5555aaaaLL,
0x5555aaaa5555aaaaLL);
int pattern_enable = (counter & 0x40) != 0;
cmd_draw(&p, DRAW_TRIANGLES, 1, pattern_enable);
vertex(&p,
800/2 + (int) (200*sin(counter*speed)),
450/2 + (int) (200*cos(counter*speed)),
0, 50, 100, 150);
vertex(&p,
800/2 + (int) (200*sin(counter*speed + M_PI*2/3)),
450/2 + (int) (200*cos(counter*speed + M_PI*2/3)),
0, 50, 100, 150);
vertex(&p,
800/2 + (int) (200*sin(counter*speed + M_PI*4/3)),
450/2 + (int) (200*cos(counter*speed + M_PI*4/3)),
0, 50, 100, 150);
cmd_swap(&p);
cmd_end(&p);
#ifdef DEBUG_PRINT
printf(" Wrote %d words:\n", p - protocol_buffer);
for (volatile uint64_t *t = protocol_buffer; t < p; t++) {
printf(" 0x%016llX\n", *t);
}
#endif
// Tell FPGA that our data is ready.
#ifdef DEBUG_PRINT
printf("Telling FPGA that the data is ready.\n");
#endif
*gpo |= H2F_DATA_READY;
// Wait until we find out that it has heard us.
#ifdef DEBUG_PRINT
printf("Waiting for FPGA to get busy.\n");
#endif
while ((*gpi & F2H_BUSY) == 0) {
// Busy loop.
}
// Let FPGA know that we know that it's busy.
#ifdef DEBUG_PRINT
printf("Telling FPGA that we know it's busy.\n");
#endif
*gpo &= ~H2F_DATA_READY;
// Wait until it's done rasterizing.
#ifdef DEBUG_PRINT
printf("Waiting for FPGA to finish rasterizing.\n");
#endif
while ((*gpi & F2H_BUSY) != 0) {
// Busy loop.
}
// usleep(1000*100);
counter++;
}
exit(EXIT_SUCCESS);
}
<commit_msg>Protocol test that spins red triangle.<commit_after>#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <stdint.h>
#include <math.h>
#undef DEBUG_PRINT
// For lightweight communication with the FPGA:
#define FPGA_MANAGER_BASE 0xFF706000
#define FPGA_GPO_OFFSET 0x10
#define FPGA_GPI_OFFSET 0x14
// HPS-to-FPGA:
#define H2F_DATA_READY (1 << 0)
// FPGA-to-HPS:
#define F2H_BUSY (1 << 0)
// Shared memory addresses:
#define BASE 0x38000000
#define RAM_SIZE 0x40000000
#define COLOR_BUFFER_1_OFFSET 0
#define BUFFER_SIZE (800*480*4)
#define COLOR_BUFFER_2_OFFSET (COLOR_BUFFER_1_OFFSET + BUFFER_SIZE)
#define Z_BUFFER_OFFSET (COLOR_BUFFER_2_OFFSET + BUFFER_SIZE)
#define PROTOCOL_BUFFER_OFFSET (Z_BUFFER_OFFSET + BUFFER_SIZE)
// Protocol command number:
#define CMD_CLEAR 1
#define CMD_ZCLEAR 2
#define CMD_PATTERN 3
#define CMD_DRAW 4
#define CMD_BITMAP 5
#define CMD_SWAP 6
#define CMD_END 7
// Draw type:
#define DRAW_TRIANGLES 0
#define DRAW_LINES 1
#define DRAW_POINTS 2
#define DRAW_LINE_STRIP 3
#define DRAW_TRIANGLE_STRIP 5
#define DRAW_TRIANGLE_FAN 6
#define TEST_PATTERN 0
#define TEST_SPINNING_TRIANGLE 1
#define TEST_TWO_TRIANGLES 0
void cmd_clear(volatile uint64_t **p, uint8_t red, uint8_t green, uint8_t blue)
{
*(*p)++ = CMD_CLEAR
| ((uint64_t) red << 56)
| ((uint64_t) green << 48)
| ((uint64_t) blue << 40);
}
void cmd_pattern(volatile uint64_t **p,
uint64_t pattern0,
uint64_t pattern1,
uint64_t pattern2,
uint64_t pattern3)
{
*(*p)++ = CMD_PATTERN;
*(*p)++ = pattern0;
*(*p)++ = pattern1;
*(*p)++ = pattern2;
*(*p)++ = pattern3;
}
void cmd_draw(volatile uint64_t **p, int type, int count, int pattern_enable)
{
*(*p)++ = CMD_DRAW
| ((uint64_t) type << 8)
| ((uint64_t) count << 16)
| ((uint64_t) pattern_enable << 33);
}
void vertex(volatile uint64_t **p, int x, int y, int z,
uint8_t red, uint8_t green, uint8_t blue)
{
*(*p)++ =
((uint64_t) x << 2)
| ((uint64_t) y << 15)
| ((uint64_t) red << 56)
| ((uint64_t) green << 48)
| ((uint64_t) blue << 40);
}
void cmd_swap(volatile uint64_t **p)
{
*(*p)++ = CMD_SWAP;
}
void cmd_end(volatile uint64_t **p)
{
*(*p)++ = CMD_END;
}
int main()
{
float speed = 0.01;
int dev_mem = open("/dev/mem", O_RDWR);
if(dev_mem == -1) {
perror("open");
exit(EXIT_FAILURE);
}
// Get access to lightweight FPGA communication.
uint8_t *fpga_manager_base = (uint8_t *) mmap(0, 64,
PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem, FPGA_MANAGER_BASE);
if(fpga_manager_base == MAP_FAILED) {
perror("mmap for fpga manager base");
exit(EXIT_FAILURE);
}
volatile uint32_t *gpo = (uint32_t*)(fpga_manager_base + FPGA_GPO_OFFSET);
volatile uint32_t *gpi = (uint32_t*)(fpga_manager_base + FPGA_GPI_OFFSET);
// Get access to the various RAM buffers.
uint8_t *buffers_base = (uint8_t *) mmap(0, RAM_SIZE - BASE,
PROT_READ | PROT_WRITE, MAP_SHARED, dev_mem, BASE);
if(buffers_base == MAP_FAILED) {
perror("mmap for buffers");
exit(EXIT_FAILURE);
}
volatile uint64_t *protocol_buffer =
(uint64_t *) (buffers_base + PROTOCOL_BUFFER_OFFSET);
int brightness = 1000;
*gpo = (brightness << 2) | (1 << 1);
int counter = 0;
while (1) {
// Start of frame.
if ((*gpi & F2H_BUSY) != 0) {
printf("Warning: FPGA is busy at top of loop.\n");
}
// Write protocol buffer.
#ifdef DEBUG_PRINT
printf("Writing protocol buffer.\n");
#endif
volatile uint64_t *p = protocol_buffer;
if (0) {
cmd_clear(&p,
(counter & 0x04) ? 255 : 0,
(counter & 0x02) ? 255 : 0,
(counter & 0x01) ? 255 : 0);
} else {
cmd_clear(&p, 0, 0, 0);
}
#if TEST_PATTERN
cmd_pattern(&p,
0x5555aaaa5555aaaaLL,
0x5555aaaa5555aaaaLL,
0x5555aaaa5555aaaaLL,
0x5555aaaa5555aaaaLL);
#endif
int pattern_enable = (counter & 0x40) != 0 && TEST_PATTERN;
#if TEST_SPINNING_TRIANGLE
cmd_draw(&p, DRAW_TRIANGLES, 1, pattern_enable);
vertex(&p,
800/2 + (int) (200*sin(counter*speed + M_PI*2/3)),
450/2 + (int) (200*cos(counter*speed + M_PI*2/3)),
0, 255, 0, 0);
vertex(&p,
800/2 + (int) (200*sin(counter*speed)),
450/2 + (int) (200*cos(counter*speed)),
0, 0, 0, 0);
vertex(&p,
800/2 + (int) (200*sin(counter*speed + M_PI*4/3)),
450/2 + (int) (200*cos(counter*speed + M_PI*4/3)),
0, 0, 0, 0);
#endif
#if TEST_TWO_TRIANGLES
cmd_draw(&p, DRAW_TRIANGLES, 2, pattern_enable);
// vertex(&p, 416, 346, 0, 255, 255, 255);
// vertex(&p, 392, 346, 0, 255, 255, 255);
// vertex(&p, 416, 321, 0, 255, 255, 255);
int dy = ((counter / 50) % 20) - 10;
// Bottom triangle.
vertex(&p, 392, 346 + dy, 0, 255, 200, 255);
vertex(&p, 416, 321 + dy, 0, 255, 200, 255);
vertex(&p, 392, 321 + dy, 0, 255, 200, 255);
// Top triangle.
vertex(&p, 416, 321 + dy, 0, 255, 255, 200);
vertex(&p, 392, 321 + dy, 0, 255, 255, 200);
vertex(&p, 416, 296 + dy, 0, 255, 255, 200);
// vertex(&p, 392, 321, 0, 200, 255, 255);
// vertex(&p, 416, 296, 0, 200, 255, 255);
// vertex(&p, 392, 297, 0, 200, 255, 255);
#endif
cmd_swap(&p);
cmd_end(&p);
#ifdef DEBUG_PRINT
printf(" Wrote %d words:\n", p - protocol_buffer);
for (volatile uint64_t *t = protocol_buffer; t < p; t++) {
printf(" 0x%016llX\n", *t);
}
#endif
// Tell FPGA that our data is ready.
#ifdef DEBUG_PRINT
printf("Telling FPGA that the data is ready.\n");
#endif
*gpo |= H2F_DATA_READY;
// Wait until we find out that it has heard us.
#ifdef DEBUG_PRINT
printf("Waiting for FPGA to get busy.\n");
#endif
while ((*gpi & F2H_BUSY) == 0) {
// Busy loop.
}
// Let FPGA know that we know that it's busy.
#ifdef DEBUG_PRINT
printf("Telling FPGA that we know it's busy.\n");
#endif
*gpo &= ~H2F_DATA_READY;
// Wait until it's done rasterizing.
#ifdef DEBUG_PRINT
printf("Waiting for FPGA to finish rasterizing.\n");
#endif
while ((*gpi & F2H_BUSY) != 0) {
// Busy loop.
}
// usleep(1000*100);
counter++;
}
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>/**
Copyright 2015 Joachim Wolff
Master Thesis
Tutors: Milad Miladi, Fabrizio Costa
Winter semester 2015/2016
Chair of Bioinformatics
Department of Computer Science
Faculty of Engineering
Albert-Ludwig-University Freiburg im Breisgau
**/
#include <iostream>
#include "minHashBase.h"
#include "sparseMatrix.h"
#ifdef OPENMP
#include <omp.h>
#endif
MinHashBase::MinHashBase(size_t pNumberOfHashFunctions, size_t pBlockSize,
size_t pNumberOfCores, size_t pChunkSize,
size_t pMaxBinSize,
size_t pSizeOfNeighborhood, size_t pMinimalBlocksInCommon,
size_t pExcessFactor, size_t pMaximalNumberOfHashCollisions,
int pFast) {
mInverseIndex = new InverseIndex(pNumberOfHashFunctions, pBlockSize,
pNumberOfCores, pChunkSize,
pMaxBinSize, pMinimalBlocksInCommon,
pExcessFactor, pMaximalNumberOfHashCollisions);
mNneighbors = pSizeOfNeighborhood;
mFast = pFast;
mNumberOfCores = pNumberOfCores;
mChunkSize = pChunkSize;
}
MinHashBase::~MinHashBase(){
delete mInverseIndex;
delete mOriginalData;
}
void MinHashBase::fit(const SparseMatrixFloat* pRawData) {
mInverseIndex->fit(pRawData);
return;
}
void MinHashBase::partialFit() {
}
neighborhood* MinHashBase::kneighbors(const SparseMatrixFloat* pRawData, size_t pNneighbors, int pFast, size_t pSimilarity) {
// std::cout << "53M" << std::endl;
if (pFast == -1) {
pFast = mFast;
}
if (pNneighbors == 0) {
pNneighbors = mNneighbors;
}
// std::cout << "61M" << std::endl;
umap_uniqueElement* X;
bool doubleElementsStorageCount = false;
if (pRawData->size() == 0) {
// no query data given, use stored signatures
X = mInverseIndex->getSignatureStorage();
doubleElementsStorageCount = true;
} else {
X = mInverseIndex->computeSignatureMap(pRawData);
}
neighborhood* neighborhood_ = mInverseIndex->kneighbors(X, pNneighbors, doubleElementsStorageCount);
if (pFast) {
return neighborhood_;
}
// std::cout << "77M" << std::endl;
neighborhood* neighborhoodExact = new neighborhood();
neighborhoodExact->neighbors = new vvint(neighborhood_->neighbors->size());
neighborhoodExact->distances = new vvfloat(neighborhood_->neighbors->size());
if (mChunkSize <= 0) {
mChunkSize = ceil(neighborhood_->neighbors->size() / static_cast<float>(mNumberOfCores));
}
#ifdef OPENMP
omp_set_dynamic(0);
#endif
// std::cout << "89M" << std::endl;
#pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores)
for (size_t i = 0; i < neighborhood_->neighbors->size(); ++i) {
// std::cout << "93M" << std::endl;
if (neighborhood_->neighbors->operator[](i).size() != 1) {
// std::cout << "96M" << std::endl;
// std::cout << "i: " << i << std::endl;
// std::cout << "size: " << neighborhood_->neighbors->size() << std::endl;
// std::cout << "start foo: " << neighborhood_->neighbors->operator[](i).size() << std::endl ;
// std::cout << "again foo: "<< neighborhood_->neighbors->operator[](i)[0] << std::endl;
std::vector<sortMapFloat>* exactNeighbors;
if (pSimilarity) {
exactNeighbors =
mOriginalData->cosineSimilarity(neighborhood_->neighbors->operator[](i), neighborhood_->neighbors->operator[](i)[0], pNneighbors);
} else {
exactNeighbors =
mOriginalData->euclidianDistance(neighborhood_->neighbors->operator[](i), neighborhood_->neighbors->operator[](i)[0], pNneighbors);
}
// std::cout << "101M" << std::endl;
std::vector<int> neighborsVector(exactNeighbors->size());
std::vector<float> distancesVector(exactNeighbors->size());
// std::cout << "104M" << std::endl;
for (size_t j = 0; j < exactNeighbors->size(); ++j) {
neighborsVector[j] = (*exactNeighbors)[j].key;
distancesVector[j] = (*exactNeighbors)[j].val;
}
// std::cout << "105M" << std::endl;
#pragma omp critical
{
// std::cout << "109M" << std::endl;
neighborhoodExact->neighbors->operator[](i) = neighborsVector;
neighborhoodExact->distances->operator[](i) = distancesVector;
}
} else {
#pragma omp critical
{
// std::cout << "117M" << std::endl;
neighborhoodExact->neighbors->operator[](i) = neighborhood_->neighbors->operator[](i);
neighborhoodExact->distances->operator[](i) = neighborhood_->distances->operator[](i);
}
}
}
// std::cout << "124M" << std::endl;
delete neighborhood_->neighbors;
delete neighborhood_->distances;
delete neighborhood_;
// std::cout << "129M" << std::endl;
return neighborhoodExact;
}
<commit_msg>Added support for query defined sparse matricies<commit_after>/**
Copyright 2015 Joachim Wolff
Master Thesis
Tutors: Milad Miladi, Fabrizio Costa
Winter semester 2015/2016
Chair of Bioinformatics
Department of Computer Science
Faculty of Engineering
Albert-Ludwig-University Freiburg im Breisgau
**/
#include <iostream>
#include "minHashBase.h"
#include "sparseMatrix.h"
#ifdef OPENMP
#include <omp.h>
#endif
MinHashBase::MinHashBase(size_t pNumberOfHashFunctions, size_t pBlockSize,
size_t pNumberOfCores, size_t pChunkSize,
size_t pMaxBinSize,
size_t pSizeOfNeighborhood, size_t pMinimalBlocksInCommon,
size_t pExcessFactor, size_t pMaximalNumberOfHashCollisions,
int pFast) {
mInverseIndex = new InverseIndex(pNumberOfHashFunctions, pBlockSize,
pNumberOfCores, pChunkSize,
pMaxBinSize, pMinimalBlocksInCommon,
pExcessFactor, pMaximalNumberOfHashCollisions);
mNneighbors = pSizeOfNeighborhood;
mFast = pFast;
mNumberOfCores = pNumberOfCores;
mChunkSize = pChunkSize;
}
MinHashBase::~MinHashBase(){
delete mInverseIndex;
delete mOriginalData;
}
void MinHashBase::fit(const SparseMatrixFloat* pRawData) {
mInverseIndex->fit(pRawData);
return;
}
void MinHashBase::partialFit() {
}
neighborhood* MinHashBase::kneighbors(const SparseMatrixFloat* pRawData, size_t pNneighbors, int pFast, size_t pSimilarity) {
// std::cout << "53M" << std::endl;
if (pFast == -1) {
pFast = mFast;
}
if (pNneighbors == 0) {
pNneighbors = mNneighbors;
}
// std::cout << "61M" << std::endl;
umap_uniqueElement* X;
bool doubleElementsStorageCount = false;
if (pRawData == NULL) {
// no query data given, use stored signatures
X = mInverseIndex->getSignatureStorage();
doubleElementsStorageCount = true;
} else {
X = mInverseIndex->computeSignatureMap(pRawData);
}
neighborhood* neighborhood_ = mInverseIndex->kneighbors(X, pNneighbors, doubleElementsStorageCount);
if (pFast) {
return neighborhood_;
}
// std::cout << "77M" << std::endl;
neighborhood* neighborhoodExact = new neighborhood();
neighborhoodExact->neighbors = new vvint(neighborhood_->neighbors->size());
neighborhoodExact->distances = new vvfloat(neighborhood_->neighbors->size());
if (mChunkSize <= 0) {
mChunkSize = ceil(neighborhood_->neighbors->size() / static_cast<float>(mNumberOfCores));
}
#ifdef OPENMP
omp_set_dynamic(0);
#endif
// std::cout << "89M" << std::endl;
#pragma omp parallel for schedule(static, mChunkSize) num_threads(mNumberOfCores)
for (size_t i = 0; i < neighborhood_->neighbors->size(); ++i) {
// std::cout << "93M" << std::endl;
if (neighborhood_->neighbors->operator[](i).size() != 1) {
// std::cout << "96M" << std::endl;
// std::cout << "i: " << i << std::endl;
// std::cout << "size: " << neighborhood_->neighbors->size() << std::endl;
// std::cout << "start foo: " << neighborhood_->neighbors->operator[](i).size() << std::endl ;
// std::cout << "again foo: "<< neighborhood_->neighbors->operator[](i)[0] << std::endl;
std::vector<sortMapFloat>* exactNeighbors;
if (pSimilarity) {
exactNeighbors =
mOriginalData->cosineSimilarity(neighborhood_->neighbors->operator[](i), neighborhood_->neighbors->operator[](i)[0], pNneighbors, pRawData);
} else {
exactNeighbors =
mOriginalData->euclidianDistance(neighborhood_->neighbors->operator[](i), neighborhood_->neighbors->operator[](i)[0], pNneighbors, pRawData);
}
// std::cout << "101M" << std::endl;
std::vector<int> neighborsVector(exactNeighbors->size());
std::vector<float> distancesVector(exactNeighbors->size());
// std::cout << "104M" << std::endl;
for (size_t j = 0; j < exactNeighbors->size(); ++j) {
neighborsVector[j] = (*exactNeighbors)[j].key;
distancesVector[j] = (*exactNeighbors)[j].val;
}
// std::cout << "105M" << std::endl;
#pragma omp critical
{
// std::cout << "109M" << std::endl;
neighborhoodExact->neighbors->operator[](i) = neighborsVector;
neighborhoodExact->distances->operator[](i) = distancesVector;
}
} else {
#pragma omp critical
{
// std::cout << "117M" << std::endl;
neighborhoodExact->neighbors->operator[](i) = neighborhood_->neighbors->operator[](i);
neighborhoodExact->distances->operator[](i) = neighborhood_->distances->operator[](i);
}
}
}
// std::cout << "124M" << std::endl;
delete neighborhood_->neighbors;
delete neighborhood_->distances;
delete neighborhood_;
// std::cout << "129M" << std::endl;
return neighborhoodExact;
}
<|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
/**
* A mesh component that specifies that the entity can be rendered.
* It contains a DrawObject instance from the renderer.
*
* License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE)
* Authors:
* - Dan Printzell
*/
#include <hydra/component/meshcomponent.hpp>
#include <imgui/imgui.h>
#include <hydra/renderer/glrenderer.hpp>
#include <hydra/engine.hpp>
using namespace Hydra::World;
using namespace Hydra::Component;
MeshComponent::~MeshComponent() {}
void MeshComponent::loadMesh(const std::string meshFile) {
this->meshFile = meshFile;
if (!Hydra::IEngine::getInstance()->getState()->getMeshLoader())
return;
drawObject = Hydra::World::World::getEntity(entityID)->addComponent<DrawObjectComponent>();
mesh = Hydra::IEngine::getInstance()->getState()->getMeshLoader()->getMesh(meshFile);
auto newMesh = drawObject->drawObject->mesh = mesh.get();
if (meshFile == "PARTICLEQUAD" || meshFile == "TEXTQUAD" || meshFile == "QUAD")
drawObject->drawObject->disable = true;
if (meshFile.find("Wall") != std::string::npos || meshFile.find("Tunnel") != std::string::npos
|| meshFile.find("Roof") != std::string::npos || meshFile.find("Floor_v") != std::string::npos
|| meshFile.find("HangingCable") != std::string::npos || meshFile.find("Monitor") != std::string::npos
|| meshFile.find("BookShelf") != std::string::npos || meshFile.find("Pillar") != std::string::npos || meshFile.find("Locker") != std::string::npos
|| meshFile.find("WaterContainer") != std::string::npos || meshFile.find("EnglishWordForHyllla") != std::string::npos
|| meshFile.find("Fridge") != std::string::npos){
drawObject->drawObject->hasShadow = false;
}
}
void MeshComponent::serialize(nlohmann::json& json) const {
json["meshFile"] = meshFile;
json["currentFrame"] = currentFrame;
json["animationIndex"] = animationIndex;
json["animationCounter"] = animationCounter;
}
void MeshComponent::deserialize(nlohmann::json& json) {
loadMesh(json["meshFile"].get<std::string>());
currentFrame = json.value<int>("currentFrame", 1);
animationIndex = json.value<int>("animationIndex", 0);
animationCounter = json.value<float>("animationCounter", 0);
}
void MeshComponent::registerUI() {
ImGui::InputText("Mesh file", (char*)meshFile.c_str(), meshFile.length(), ImGuiInputTextFlags_ReadOnly);
ImGui::DragInt("CurrentFrame", ¤tFrame);
ImGui::DragInt("AnimationIndex", &animationIndex);
ImGui::DragFloat("AnimationCounter", &animationCounter);
}
<commit_msg>Blacklisted Door for shadows.<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
/**
* A mesh component that specifies that the entity can be rendered.
* It contains a DrawObject instance from the renderer.
*
* License: Mozilla Public License Version 2.0 (https://www.mozilla.org/en-US/MPL/2.0/ OR See accompanying file LICENSE)
* Authors:
* - Dan Printzell
*/
#include <hydra/component/meshcomponent.hpp>
#include <imgui/imgui.h>
#include <hydra/renderer/glrenderer.hpp>
#include <hydra/engine.hpp>
using namespace Hydra::World;
using namespace Hydra::Component;
MeshComponent::~MeshComponent() {}
void MeshComponent::loadMesh(const std::string meshFile) {
this->meshFile = meshFile;
if (!Hydra::IEngine::getInstance()->getState()->getMeshLoader())
return;
drawObject = Hydra::World::World::getEntity(entityID)->addComponent<DrawObjectComponent>();
mesh = Hydra::IEngine::getInstance()->getState()->getMeshLoader()->getMesh(meshFile);
auto newMesh = drawObject->drawObject->mesh = mesh.get();
if (meshFile == "PARTICLEQUAD" || meshFile == "TEXTQUAD" || meshFile == "QUAD")
drawObject->drawObject->disable = true;
if (meshFile.find("Wall") != std::string::npos || meshFile.find("Tunnel") != std::string::npos
|| meshFile.find("Roof") != std::string::npos || meshFile.find("Floor_v") != std::string::npos
|| meshFile.find("HangingCable") != std::string::npos || meshFile.find("Monitor") != std::string::npos
|| meshFile.find("BookShelf") != std::string::npos || meshFile.find("Pillar") != std::string::npos || meshFile.find("Locker") != std::string::npos
|| meshFile.find("WaterContainer") != std::string::npos || meshFile.find("EnglishWordForHyllla") != std::string::npos
|| meshFile.find("Fridge") != std::string::npos || meshFile.find("Door") != std::string::npos){
drawObject->drawObject->hasShadow = false;
}
}
void MeshComponent::serialize(nlohmann::json& json) const {
json["meshFile"] = meshFile;
json["currentFrame"] = currentFrame;
json["animationIndex"] = animationIndex;
json["animationCounter"] = animationCounter;
}
void MeshComponent::deserialize(nlohmann::json& json) {
loadMesh(json["meshFile"].get<std::string>());
currentFrame = json.value<int>("currentFrame", 1);
animationIndex = json.value<int>("animationIndex", 0);
animationCounter = json.value<float>("animationCounter", 0);
}
void MeshComponent::registerUI() {
ImGui::InputText("Mesh file", (char*)meshFile.c_str(), meshFile.length(), ImGuiInputTextFlags_ReadOnly);
ImGui::DragInt("CurrentFrame", ¤tFrame);
ImGui::DragInt("AnimationIndex", &animationIndex);
ImGui::DragFloat("AnimationCounter", &animationCounter);
}
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
class DepositoSimulacion{
private:
double capital;
int interes;
public:
//Constructos
DepositoSimulacion(double dinero, int inte){
while(dinero < 0){
cout<<"Capital incorrecto,vuelva a introducir el capital: ";
cin>>dinero;
}
while(inte < 0 || inte > 100){
cout<<"El interes tiene que estar entre un 0% y un 100%, introduzcalo de nuevo: ";
cin>>inte;
}
capital = dinero;
interes = inte;
}
//Calculamos el capital que tendremos en un numero de años dados sabiento el interes
double calcularCapital(int anios){
double total=capital;
for(int i=1; i <= anios; i++){
total = total + ((capital*interes)/100.0);
cout <<"El capital en el año "<< i << " es de: "<<total<<endl;
}
return total;
}
//Calculamos los años que transcurriran hasta lograr el doble del capital
int calcularAnios(double capital){
}
};
int main(){
int opcion=0,
interes,
anios;
double capital,
totalCapital;
while(opcion != -1){
cout<<"-----------------------------------------------------------"<<endl<<
"1. Calcular nuevo capital dado un CAPITAL, NUMERO DE AÑOS y %"<<endl<<
"2. Calcular numero de años para obtener el doble de un CAPITAL dado con un %"<<endl<<
"-1. Salir"<<endl<<
"-------------------------------------------------------------"<<endl;
cin>>opcion;
if(opcion == 1){
cout<<"Introduce el capital inicial: ";
cin>>capital;
cout<<"Introduce el interes: ";
cin>>interes;
cout<<"Introduce el numero de años: ";
cin>>anios;
DepositoSimulacion deposito (capital,interes);
totalCapital = deposito.calcularCapital(anios);
cout<<"El total de capital en "<< anios << " años es de: "<< totalCapital << endl;
}
}
}
<commit_msg>Terminado ejercicio 3.19<commit_after>#include <iostream>
using namespace std;
class DepositoSimulacion{
private:
double capital;
int interes;
public:
//Constructos
DepositoSimulacion(double dinero, int inte){
while(dinero < 0){
cout<<"Capital incorrecto,vuelva a introducir el capital: ";
cin>>dinero;
}
while(inte < 0 || inte > 100){
cout<<"El interes tiene que estar entre un 0% y un 100%, introduzcalo de nuevo: ";
cin>>inte;
}
capital = dinero;
interes = inte;
}
//Calculamos el capital que tendremos en un numero de años dados sabiento el interes
double calcularCapital(int anios){
double total=capital;
for(int i=1; i <= anios; i++){
total = total + ((capital*interes)/100.0);
cout <<"El capital en el año "<< i << " es de: "<<total<<endl;
}
return total;
}
//Calculamos los años que transcurriran hasta lograr el doble del capital
int calcularAnios(){
double dobleCapital = capital * 2;
double copia = capital;
int anios=0;
while(copia < dobleCapital){
copia = copia + ((capital*interes)/100.0);
anios++;
}
return anios;
}
};
int main(){
int opcion=0,
interes,
anios;
double capital,
totalCapital;
while(opcion != -1){
cout<<"-----------------------------------------------------------"<<endl<<
"1. Calcular nuevo capital dado un CAPITAL, NUMERO DE AÑOS y %"<<endl<<
"2. Calcular numero de años para obtener el doble de un CAPITAL dado con un %"<<endl<<
"-1. Salir"<<endl<<
"-------------------------------------------------------------"<<endl;
cin>>opcion;
if(opcion == 1){
cout<<"Introduce el capital inicial: ";
cin>>capital;
cout<<"Introduce el interes: ";
cin>>interes;
cout<<"Introduce el numero de años: ";
cin>>anios;
DepositoSimulacion deposito (capital,interes);
totalCapital = deposito.calcularCapital(anios);
cout<<"El total de capital en "<< anios << " años es de: "<< totalCapital << endl;
}
if(opcion == 2){
cout<<"Introduce el capital inicial: ";
cin>>capital;
cout<<"Introduce el interes: ";
cin>>interes;
DepositoSimulacion deposito (capital, interes);
anios = deposito.calcularAnios();
cout<<"Tienen que transcurrir "<< anios << " años para tener el doble de tu capital"<<endl;
}
}
}
<|endoftext|> |
<commit_before>#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/tuple.hpp>
#include <agency/detail/arithmetic_tuple_facade.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/detail/make_tuple_if_not_nested.hpp>
namespace agency
{
namespace detail
{
// index_tuple can't just be an alias for a particular kind of tuple
// because it also requires arithmetic operators
template<class... Indices>
class index_tuple :
public agency::detail::tuple<Indices...>,
public arithmetic_tuple_facade<index_tuple<Indices...>>
{
public:
using agency::detail::tuple<Indices...>::tuple;
};
template<class... Indices>
__AGENCY_ANNOTATION
index_tuple<Indices...> make_index_tuple(const std::tuple<Indices...>& indices)
{
return index_tuple<Indices...>(indices);
}
template<class... Args>
__AGENCY_ANNOTATION
index_tuple<decay_t<Args>...> make_index_tuple(Args&&... args)
{
return index_tuple<decay_t<Args>...>(std::forward<Args>(args)...);
}
struct index_tuple_maker
{
template<class... Args>
__AGENCY_ANNOTATION
auto operator()(Args&&... args) const
-> decltype(
make_index_tuple(std::forward<Args>(args)...)
)
{
return make_index_tuple(std::forward<Args>(args)...);
}
};
template<class ExecutionCategory1,
class ExecutionCategory2,
class Index1,
class Index2>
struct nested_index
{
using type = decltype(
__tu::tuple_cat_apply(
detail::index_tuple_maker{},
detail::make_tuple_if_not_nested<ExecutionCategory1>(std::declval<Index1>()),
detail::make_tuple_if_not_nested<ExecutionCategory2>(std::declval<Index2>())
)
);
};
template<class ExecutionCategory1,
class ExecutionCategory2,
class Index1,
class Index2>
using nested_index_t = typename nested_index<
ExecutionCategory1,
ExecutionCategory2,
Index1,
Index2
>::type;
template<class ExecutionCategory1,
class ExecutionCategory2,
class Index1,
class Index2>
__AGENCY_ANNOTATION
nested_index_t<ExecutionCategory1,ExecutionCategory2,Index1,Index2> make_nested_index(const Index1& outer_idx, const Index2& inner_idx)
{
return __tu::tuple_cat_apply(
detail::index_tuple_maker{},
detail::make_tuple_if_not_nested<ExecutionCategory1>(outer_idx),
detail::make_tuple_if_not_nested<ExecutionCategory2>(inner_idx)
);
}
} // end detail
} // end agency
namespace __tu
{
// tuple_traits specializations
template<class... Indices>
struct tuple_traits<agency::detail::index_tuple<Indices...>>
: __tu::tuple_traits<agency::detail::tuple<Indices...>>
{
using tuple_type = agency::detail::tuple<Indices...>;
}; // end tuple_traits
} // end __tu
namespace std
{
template<class... Indices>
struct tuple_size<agency::detail::index_tuple<Indices...>> : std::tuple_size<agency::detail::tuple<Indices...>> {};
template<size_t i, class... Indices>
struct tuple_element<i,agency::detail::index_tuple<Indices...>> : std::tuple_element<i,agency::detail::tuple<Indices...>> {};
} // end namespace std
<commit_msg>Add agency::detail::is_bounded_by()<commit_after>#pragma once
#include <agency/detail/config.hpp>
#include <agency/detail/tuple.hpp>
#include <agency/detail/arithmetic_tuple_facade.hpp>
#include <agency/detail/type_traits.hpp>
#include <agency/detail/make_tuple_if_not_nested.hpp>
namespace agency
{
namespace detail
{
// index_tuple can't just be an alias for a particular kind of tuple
// because it also requires arithmetic operators
template<class... Indices>
class index_tuple :
public agency::detail::tuple<Indices...>,
public arithmetic_tuple_facade<index_tuple<Indices...>>
{
public:
using agency::detail::tuple<Indices...>::tuple;
};
template<class... Indices>
__AGENCY_ANNOTATION
index_tuple<Indices...> make_index_tuple(const std::tuple<Indices...>& indices)
{
return index_tuple<Indices...>(indices);
}
template<class... Args>
__AGENCY_ANNOTATION
index_tuple<decay_t<Args>...> make_index_tuple(Args&&... args)
{
return index_tuple<decay_t<Args>...>(std::forward<Args>(args)...);
}
struct index_tuple_maker
{
template<class... Args>
__AGENCY_ANNOTATION
auto operator()(Args&&... args) const
-> decltype(
make_index_tuple(std::forward<Args>(args)...)
)
{
return make_index_tuple(std::forward<Args>(args)...);
}
};
template<class ExecutionCategory1,
class ExecutionCategory2,
class Index1,
class Index2>
struct nested_index
{
using type = decltype(
__tu::tuple_cat_apply(
detail::index_tuple_maker{},
detail::make_tuple_if_not_nested<ExecutionCategory1>(std::declval<Index1>()),
detail::make_tuple_if_not_nested<ExecutionCategory2>(std::declval<Index2>())
)
);
};
template<class ExecutionCategory1,
class ExecutionCategory2,
class Index1,
class Index2>
using nested_index_t = typename nested_index<
ExecutionCategory1,
ExecutionCategory2,
Index1,
Index2
>::type;
template<class ExecutionCategory1,
class ExecutionCategory2,
class Index1,
class Index2>
__AGENCY_ANNOTATION
nested_index_t<ExecutionCategory1,ExecutionCategory2,Index1,Index2> make_nested_index(const Index1& outer_idx, const Index2& inner_idx)
{
return __tu::tuple_cat_apply(
detail::index_tuple_maker{},
detail::make_tuple_if_not_nested<ExecutionCategory1>(outer_idx),
detail::make_tuple_if_not_nested<ExecutionCategory2>(inner_idx)
);
}
// a point on the number line is bounded by another if it is strictly less than the other
template<class Integral1, class Integral2,
class = typename std::enable_if<
std::is_integral<Integral1>::value && std::is_integral<Integral2>::value
>::type>
__AGENCY_ANNOTATION
bool is_bounded_by(const Integral1& x, const Integral2& bound)
{
return x < bound;
}
// a multidimensional index is bounded by another if all of its elements are
// bounded by the corresponding element of the other
// essentially we test whether x is contained within (not lying on)
// the axis-aligned bounding box from the origin to the bound
template<class IndexTuple1, class IndexTuple2,
class = typename std::enable_if<
is_tuple<IndexTuple1>::value && is_tuple<IndexTuple2>::value
>::type,
class = typename std::enable_if<
std::tuple_size<IndexTuple1>::value == std::tuple_size<IndexTuple2>::value
>::type>
__AGENCY_ANNOTATION
bool is_bounded_by(const IndexTuple1& x, const IndexTuple2& bound);
// terminal case: x is bounded by bound
template<size_t i, class IndexTuple1, class IndexTuple2>
__AGENCY_ANNOTATION
typename std::enable_if<
std::tuple_size<IndexTuple1>::value <= i,
bool
>::type
is_bounded_by_impl(const IndexTuple1& x, const IndexTuple2& bound)
{
return true;
}
// recursive case: early out if x[i] is not bounded by bound[i]
template<size_t i, class IndexTuple1, class IndexTuple2>
__AGENCY_ANNOTATION
typename std::enable_if<
i < std::tuple_size<IndexTuple1>::value,
bool
>::type
is_bounded_by_impl(const IndexTuple1& x, const IndexTuple2& bound)
{
return detail::is_bounded_by(detail::get<i>(x), detail::get<i>(bound)) && detail::is_bounded_by_impl<i+1>(x,bound);
}
template<class IndexTuple1, class IndexTuple2,
class EnableIf1, class EnableIf2>
__AGENCY_ANNOTATION
bool is_bounded_by(const IndexTuple1& x, const IndexTuple2& bound)
{
return detail::is_bounded_by_impl<0>(x,bound);
}
} // end detail
} // end agency
namespace __tu
{
// tuple_traits specializations
template<class... Indices>
struct tuple_traits<agency::detail::index_tuple<Indices...>>
: __tu::tuple_traits<agency::detail::tuple<Indices...>>
{
using tuple_type = agency::detail::tuple<Indices...>;
}; // end tuple_traits
} // end __tu
namespace std
{
template<class... Indices>
struct tuple_size<agency::detail::index_tuple<Indices...>> : std::tuple_size<agency::detail::tuple<Indices...>> {};
template<size_t i, class... Indices>
struct tuple_element<i,agency::detail::index_tuple<Indices...>> : std::tuple_element<i,agency::detail::tuple<Indices...>> {};
} // end namespace std
<|endoftext|> |
<commit_before>#include "logging.hpp"
#include <android/log.h>
#include <cassert>
#include "../../../../../base/assert.hpp"
#include "../../../../../base/logging.hpp"
#include "../../../../../base/exception.hpp"
namespace jni
{
using namespace my;
void AndroidLogMessage(LogLevel l, SrcPoint const & src, string const & s)
{
android_LogPriority pr = ANDROID_LOG_SILENT;
switch (l)
{
case LINFO: pr = ANDROID_LOG_INFO; break;
case LDEBUG: pr = ANDROID_LOG_DEBUG; break;
case LWARNING: pr = ANDROID_LOG_WARN; break;
case LERROR: pr = ANDROID_LOG_ERROR; break;
case LCRITICAL: pr = ANDROID_LOG_FATAL; break;
}
string const out = DebugPrint(src) + " " + s;
__android_log_write(pr, "MapsWithMe_JNI", out.c_str());
}
void AndroidAssertMessage(SrcPoint const & src, string const & s)
{
AndroidLogMessage(LERROR, src, s);
#ifdef DEBUG
assert(false);
#else
MYTHROW(RootException, (s));
#endif
}
void InitSystemLog()
{
SetLogMessageFn(&AndroidLogMessage);
}
void InitAssertLog()
{
SetAssertFunction(&AndroidAssertMessage);
}
}
<commit_msg>compile time switcher to write log into file<commit_after>#include "logging.hpp"
#include <android/log.h>
#include <cassert>
#include "../../../../../base/assert.hpp"
#include "../../../../../base/logging.hpp"
#include "../../../../../base/exception.hpp"
#include "../../../../../coding/file_writer.hpp"
#include "../../../../../platform/platform.hpp"
#include "../../../../../std/scoped_ptr.hpp"
//#define MWM_LOG_TO_FILE
namespace jni
{
using namespace my;
void AndroidLogMessage(LogLevel l, SrcPoint const & src, string const & s)
{
android_LogPriority pr = ANDROID_LOG_SILENT;
switch (l)
{
case LINFO: pr = ANDROID_LOG_INFO; break;
case LDEBUG: pr = ANDROID_LOG_DEBUG; break;
case LWARNING: pr = ANDROID_LOG_WARN; break;
case LERROR: pr = ANDROID_LOG_ERROR; break;
case LCRITICAL: pr = ANDROID_LOG_FATAL; break;
}
string const out = DebugPrint(src) + " " + s;
__android_log_write(pr, "MapsWithMe_JNI", out.c_str());
}
void AndroidLogToFile(LogLevel l, SrcPoint const & src, string const & s)
{
static scoped_ptr<FileWriter> file;
if (file == NULL)
{
if (GetPlatform().WritableDir().empty())
return;
file.reset(new FileWriter(GetPlatform().WritablePathForFile("logging.txt")));
}
string srcString = DebugPrint(src) + " " + s + "\n";
file->Write(srcString.c_str(), srcString.size());
file->Flush();
}
void AndroidAssertMessage(SrcPoint const & src, string const & s)
{
#if defined(MWM_LOG_TO_FILE)
AndroidLogToFile(LERROR, src, s);
#else
AndroidLogMessage(LERROR, src, s);
#endif
#ifdef DEBUG
assert(false);
#else
MYTHROW(RootException, (s));
#endif
}
void InitSystemLog()
{
#if defined(MWM_LOG_TO_FILE)
SetLogMessageFn(&AndroidLogToFile);
#else
SetLogMessageFn(&AndroidLogMessage);
#endif
}
void InitAssertLog()
{
SetAssertFunction(&AndroidAssertMessage);
}
}
<|endoftext|> |
<commit_before>#include "MPEditor.h"
MPEditor::MPEditor(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
: BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
// initialize controls
BRect r = Bounds();
r.bottom = r.bottom - 50;
editorTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW);
backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
AddChild(backView);
// gui layout builder
backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
backView->AddChild(BGridLayoutBuilder()
.Add(new EditorMenu(), 0, 0)
.Add(new BScrollView("scroll_editor", editorTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)
.SetInsets(0, 0, 0, 0)
);
currentideaID = ideaID; // pass current idea id selected to editor window for use
if(currentideaID != -1) // if id has a real value
{
sqlObject = new SqlObject(ideaStatement, "7");
sqlObject->PrepareSql("select ideatext from ideatable where ideaid = ?");
sqlObject->BindValue(1, currentideaID);
sqlObject->StepSql();
editorTextView->SetText(sqlObject->ReturnText(0));
sqlObject->FinalizeSql();
sqlObject->CloseSql();
}
}
void MPEditor::MessageReceived(BMessage* msg)
{
BRect r(Bounds());
switch(msg->what)
{
case MENU_NEW_THT: // open another untitled editor window
tmpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled", -1);
tmpEditor->Show();
break;
case MENU_EDT_THT: // edit current idea name for editing
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
editIdeaName = new EditIdeaName(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, currentideaID);
editIdeaName->Show(); // show edit idea name window
break;
case MENU_SAV_THT: // save current idea progress
if(currentideaID == -1) // if its untitled insert new thought, then show saveidea to apply a name...
{
sqlObject = new SqlObject(ideaStatement, "8");
sqlObject->PrepareSql("insert into ideatable (ideaname, ideatext, ismp) values('untitled', ?, 0)");
sqlObject->BindValue(1, editorTextView->Text());
sqlObject->StepSql();
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
saveIdea = new SaveIdea(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, sqlObject->ReturnLastInsertRowID());
currentideaID = sqlObject->ReturnLastInsertRowID();
sqlObject->FinalizeSql();
sqlObject->CloseSql();
saveIdea->Show(); // show save window to name the untitled thought
}
else // already exists, just update ideatext and save new information
{
sqlObject = new SqlObject(ideaStatement, "9");
sqlObject->PrepareSql("update ideatable set ideatext = ? where ideaid = ?");
sqlObject->BindValue(1, editorTextView->Text());
sqlObject->BindValue(2, currentideaID);
sqlObject->StepSql();
sqlObject->FinalizeSql();
sqlObject->CloseSql();
}
break;
case MENU_PRV_THT: // preview thought in html in webpositive
printf("save data to tmp file, export to python html one and open data in preview window or webpositive\n\n");
// AM NO LONGER WRITING A FULL BLOWN PARSER AND DISPLAYER IN A TEXTVIEW. IF I DO THAT, I HAVE WRITTEN A FULL BLOWN WORD PROCESSOR.
// WILL SIMPLY USE THE PREVIEWER TO PREVIEW IN HTML WITH WEBPOSITIVE.
// FORK/EXEC IN POSIX LINUX WILL RUN AN APP FROM C++. HAVE TO RESEARCH THIS.
//mpPreview = new MPPreview(currentideaID);
//mpPreview->Show();
system("/boot/apps/WebPositive/WebPositive file:///boot/home/Projects/masterpiece/test.html &");
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is', ctime(time())\n");
Py_Finalize();
break;
case MENU_PUB_THT: // publish thought by opening publish window
printf("save data, open publish to window, export to python and save as name in publish window");
break;
case MENU_HLP_THT: // open help topic window
printf("open help topic window");
break;
case MENU_KEY_THT: // open keyboard reference window
printf("open keyboard reference window");
break;
case MENU_MRK_THT: // open markup reference window
printf("open markup reference window");
break;
case MENU_ABT_THT: // open about window
printf("open about window");
break;
case UPDATE_TITLE: // update title with the name from the saveidea window
if(msg->FindString("updatetitle", &updateTitle) == B_OK) // updated title exists in variable
{
tmpString = "Masterpiece Editor - ";
tmpString += updateTitle;
this->SetTitle(tmpString);
}
else //
{
eAlert = new ErrorAlert("3.1 Editor Error: Message not found."); // message variable not found
}
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
bool MPEditor::QuitRequested(void)
{
// on quit, show launcher by sending message
launcherMessage.MakeEmpty();
launcherMessage.AddInt64("showLauncher", 1);
launcherMessenger.SendMessage(&launcherMessage);
return true;
}
<commit_msg>got initial window shortcut working. will need to map out all functions and their respective shortcuts.<commit_after>#include "MPEditor.h"
MPEditor::MPEditor(const BMessage &msg, const BMessenger &msgr, BString windowTitle, int ideaID)
: BWindow(BRect(100, 100, 900, 700), windowTitle, B_TITLED_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS, B_CURRENT_WORKSPACE), launcherMessage(msg), launcherMessenger(msgr)
{
AddShortcut('q', B_COMMAND_KEY, new BMessage(B_QUIT_REQUESTED)); // sample window shortcut without keydown method
// initialize controls
BRect r = Bounds();
r.bottom = r.bottom - 50;
editorTextView = new BTextView(r, NULL, r, B_FOLLOW_ALL, B_WILL_DRAW);
backView = new BView(Bounds(), "backview", B_FOLLOW_ALL, B_WILL_DRAW);
backView->SetViewColor(ui_color(B_PANEL_BACKGROUND_COLOR));
AddChild(backView);
// gui layout builder
backView->SetLayout(new BGroupLayout(B_HORIZONTAL, 0.0));
backView->AddChild(BGridLayoutBuilder()
.Add(new EditorMenu(), 0, 0)
.Add(new BScrollView("scroll_editor", editorTextView, B_FOLLOW_ALL_SIDES, 0, false, true, B_FANCY_BORDER), 0, 1)
.SetInsets(0, 0, 0, 0)
);
currentideaID = ideaID; // pass current idea id selected to editor window for use
if(currentideaID != -1) // if id has a real value
{
sqlObject = new SqlObject(ideaStatement, "7");
sqlObject->PrepareSql("select ideatext from ideatable where ideaid = ?");
sqlObject->BindValue(1, currentideaID);
sqlObject->StepSql();
editorTextView->SetText(sqlObject->ReturnText(0));
sqlObject->FinalizeSql();
sqlObject->CloseSql();
}
}
void MPEditor::MessageReceived(BMessage* msg)
{
BRect r(Bounds());
switch(msg->what)
{
case MENU_NEW_THT: // open another untitled editor window
tmpEditor = new MPEditor(BMessage(SHOW_LAUNCHER), BMessenger(this), "MasterPiece Editor - untitled", -1);
tmpEditor->Show();
break;
case MENU_EDT_THT: // edit current idea name for editing
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
editIdeaName = new EditIdeaName(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, currentideaID);
editIdeaName->Show(); // show edit idea name window
break;
case MENU_SAV_THT: // save current idea progress
if(currentideaID == -1) // if its untitled insert new thought, then show saveidea to apply a name...
{
sqlObject = new SqlObject(ideaStatement, "8");
sqlObject->PrepareSql("insert into ideatable (ideaname, ideatext, ismp) values('untitled', ?, 0)");
sqlObject->BindValue(1, editorTextView->Text());
sqlObject->StepSql();
xPos = (r.right - r.left) / 2; // find xpos for window
yPos = (r.bottom - r.top) / 2; // find ypos for window
saveIdea = new SaveIdea(BMessage(UPDATE_TITLE), BMessenger(this), xPos, yPos, sqlObject->ReturnLastInsertRowID());
currentideaID = sqlObject->ReturnLastInsertRowID();
sqlObject->FinalizeSql();
sqlObject->CloseSql();
saveIdea->Show(); // show save window to name the untitled thought
}
else // already exists, just update ideatext and save new information
{
sqlObject = new SqlObject(ideaStatement, "9");
sqlObject->PrepareSql("update ideatable set ideatext = ? where ideaid = ?");
sqlObject->BindValue(1, editorTextView->Text());
sqlObject->BindValue(2, currentideaID);
sqlObject->StepSql();
sqlObject->FinalizeSql();
sqlObject->CloseSql();
}
break;
case MENU_PRV_THT: // preview thought in html in webpositive
printf("save data to tmp file, export to python html one and open data in preview window or webpositive\n\n");
// AM NO LONGER WRITING A FULL BLOWN PARSER AND DISPLAYER IN A TEXTVIEW. IF I DO THAT, I HAVE WRITTEN A FULL BLOWN WORD PROCESSOR.
// WILL SIMPLY USE THE PREVIEWER TO PREVIEW IN HTML WITH WEBPOSITIVE.
// FORK/EXEC IN POSIX LINUX WILL RUN AN APP FROM C++. HAVE TO RESEARCH THIS.
//mpPreview = new MPPreview(currentideaID);
//mpPreview->Show();
system("/boot/apps/WebPositive/WebPositive file:///boot/home/Projects/masterpiece/test.html &");
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is', ctime(time())\n");
Py_Finalize();
break;
case MENU_PUB_THT: // publish thought by opening publish window
printf("save data, open publish to window, export to python and save as name in publish window");
break;
case MENU_HLP_THT: // open help topic window
printf("open help topic window");
break;
case MENU_KEY_THT: // open keyboard reference window
printf("open keyboard reference window");
break;
case MENU_MRK_THT: // open markup reference window
printf("open markup reference window");
break;
case MENU_ABT_THT: // open about window
printf("open about window");
break;
case UPDATE_TITLE: // update title with the name from the saveidea window
if(msg->FindString("updatetitle", &updateTitle) == B_OK) // updated title exists in variable
{
tmpString = "Masterpiece Editor - ";
tmpString += updateTitle;
this->SetTitle(tmpString);
}
else //
{
eAlert = new ErrorAlert("3.1 Editor Error: Message not found."); // message variable not found
}
break;
default:
{
BWindow::MessageReceived(msg);
break;
}
}
}
bool MPEditor::QuitRequested(void)
{
// on quit, show launcher by sending message
launcherMessage.MakeEmpty();
launcherMessage.AddInt64("showLauncher", 1);
launcherMessenger.SendMessage(&launcherMessage);
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "precomp.h"
namespace Dml
{
constexpr NameAndIndex coordinateTransformationModes[] =
{
{"half_pixel", 0},
{"pytorch_half_pixel", 1},
{"align_corners", 2},
{"asymmetric", 3},
{"tf_half_pixel_for_nn", 4},
{"tf_crop_and_resize", 5},
};
constexpr NameAndIndex nearestNeighborRoundingModes[] =
{
{"", 0},
{"round_prefer_floor", 0},
{"round_prefer_ceil", 1},
{"floor", 2},
};
void ComputePixelOffsetsAndScales(
const MLOperatorKernelCreationContext& kernelCreationContext,
gsl::span<const float> regionOfInterest, // May be empty depending on mode.
gsl::span<const uint32_t> inputDimensions,
gsl::span<const uint32_t> outputDimensions,
/*inout*/ gsl::span<float> scales,
/*out*/ gsl::span<float> inputPixelOffsets,
/*out*/ gsl::span<float> outputPixelOffsets
)
{
assert(inputDimensions.size() == outputDimensions.size());
assert(inputPixelOffsets.size() == outputPixelOffsets.size());
assert(inputPixelOffsets.size() == scales.size());
assert(inputPixelOffsets.size() == inputDimensions.size());
assert(regionOfInterest.empty() || regionOfInterest.size() == inputDimensions.size() * 2);
std::string coordinateTransformationMode = kernelCreationContext.GetOptionalAttribute<std::string>(AttrName::CoordinateTransformationMode, "half_pixel");
auto optionalCoordinateTransformationModeValue = TryMapStringToIndex(coordinateTransformationMode, coordinateTransformationModes);
if (!optionalCoordinateTransformationModeValue)
{
ML_INVALID_ARGUMENT("Unsupported 'coordinate_transformation_mode'");
}
uint32_t coordinateTransformationModeValue = *optionalCoordinateTransformationModeValue;
ML_CHECK_VALID_ARGUMENT(
!regionOfInterest.empty() || coordinateTransformationModeValue != 5 /*tf_crop_and_resize*/,
"Resize expects 'roi' tensor for 'tf_crop_and_resize' mode."
);
const uint32_t rank = gsl::narrow_cast<uint32_t>(inputDimensions.size());
// Fill in all the input/output pixel offset for each axis,
// and recompute the scale for certain modes.
for (uint32_t i = 0; i < rank; ++i)
{
float inputPixelOffset = 0;
float outputPixelOffset = 0;
// All these mapping modes can be generalized to the equations:
//
// output_coordinate = (input_coordinate + input_offset ) * scale + output_offset
// input_coordinate = (output_coordinate - output_offset) / scale - input_offset
//
// With DML, a scale > 1 maps input to an upsampled output, and a positive pixel
// offset shifts the input contents to the right/down in the output.
//
// Since the equations from ONNX are in terms of mapping the output coordinate back
// to the input coordinate, any offsets need their signs flipped. e.g. For "half_pixel",
// the "x_resized" is the output coordinate, and the "+ 0.5" is the output coordinate
// adjustment which needs to be -0.5 when passed to DML.
switch (coordinateTransformationModeValue)
{
case 0:
// coordinate_transformation_mode is "half_pixel",
// x_original = (x_resized + 0.5) / scale - 0.5
inputPixelOffset = 0.5;
outputPixelOffset = -0.5;
// Keep existing scales.
break;
case 1:
// if coordinate_transformation_mode is "pytorch_half_pixel",
// x_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0
if (inputDimensions[i] <= 1)
{
inputPixelOffset = 0.0;
outputPixelOffset = 0.0;
scales[i] = FLT_MAX; // Set large scale so all output pixels map to 0th input pixel.
}
else
{
inputPixelOffset = 0.5;
outputPixelOffset = -0.5;
// Keep existing scales.
}
break;
case 2:
// if coordinate_transformation_mode is "align_corners",
// x_original = x_resized * (length_original - 1) / (length_resized - 1)
inputPixelOffset = 0.0;
outputPixelOffset = 0.0;
if (outputDimensions[i] <= 1 || inputDimensions[i] <= 1)
{
// Protect against division by zero when either input/output is a single pixel.
scales[i] = FLT_MAX;
}
else
{
// Recalcalculate scale, ignoring existing one (only used to determine output size).
scales[i] = float(outputDimensions[i] - 1) / (inputDimensions[i] - 1);
}
break;
case 3:
// if coordinate_transformation_mode is "asymmetric",
// x_original = x_resized / scale
inputPixelOffset = 0.0;
outputPixelOffset = 0.0;
// Keep existing scales.
break;
case 4:
// if coordinate_transformation_mode is "tf_half_pixel_for_nn",
// x_original = (x_resized + 0.5) / scale
inputPixelOffset = 0.0;
outputPixelOffset = -0.5;
// Keep existing scales.
break;
case 5:
// if coordinate_transformation_mode is "tf_crop_and_resize",
// x_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1)
// : 0.5 * (start_x + end_x) * (length_original - 1)
if (inputDimensions[i] > 1)
{
assert(regionOfInterest.size() == rank * 2);
// Fold this part of the equation into the input offset: start_x * (length_original - 1)
inputPixelOffset = -(regionOfInterest[i] * (inputDimensions[i] - 1));
outputPixelOffset = 0.0;
// Fold this part to scale: (end_x - start_x) * (length_original - 1) / (length_resized - 1)
float computedScale = float(outputDimensions[i] - 1)
/ std::max((regionOfInterest[i + rank] - regionOfInterest[i]) * (inputDimensions[i] - 1), 1.0f);
scales[i] = computedScale;
}
else // inputDimensions[i] <= 1
{
// 0.5 * (start_x + end_x) * (length_original - 1)
inputPixelOffset = -0.5f * (regionOfInterest[i] + regionOfInterest[i + rank]) * (inputDimensions[i] - 1);
outputPixelOffset = 0.0;
scales[i] = 1;
}
break;
default:
assert(false); // TryMapStringToIndex would have already bailed above.
}
inputPixelOffsets[i] = inputPixelOffset;
outputPixelOffsets[i] = outputPixelOffset;
}
}
class DmlOperatorResize : public DmlOperator, public ResizeHelper
{
public:
// Resample a multidimensional image to a new size.
DmlOperatorResize(const MLOperatorKernelCreationContext& kernelCreationContext, uint32_t opsetVersion)
: DmlOperator(kernelCreationContext),
ResizeHelper(kernelCreationContext, kernelCreationContext.GetTensorShapeDescription(), opsetVersion)
{
ML_CHECK_VALID_ARGUMENT(!m_scales.empty(), "Resize/Upsample expect scales, either a 2nd input tensors or 'scales' attribute.");
ML_CHECK_VALID_ARGUMENT(kernelCreationContext.GetOutputCount() == 1, "Resize/Upsample expect 1 output tensor.");
// Use only the first input tensor. In the case of Resize or the later Upsample-v9,
// the second tensor is CPU based and should not be passed to Resize.
std::vector<std::optional<uint32_t>> inputIndices = { 0 };
std::vector<std::optional<uint32_t>> outputIndices = { 0 };
DmlOperator::Initialize(kernelCreationContext, inputIndices, outputIndices);
// Because DirectML supports a limited number of dimensions, try to squeeze the dimension count
// to only those which actually matter. Models sometimes use a greater number of dimensions,
// even though those dimensions have no significance and can be elided (nop 1's), coercing the
// total dimension count back down to a supported value.
std::vector<uint32_t> squeezedInputShape = m_inputDimensions;
std::vector<uint32_t> squeezedOutputShape = m_outputDimensions;
std::vector<uint32_t> squeezableDimensionIndices;
std::vector<float> paddedScales = m_scales;
std::vector<float> inputPixelOffsets(paddedScales.size());
std::vector<float> outputPixelOffsets(paddedScales.size());
ComputePixelOffsetsAndScales(
kernelCreationContext,
m_regionOfInterest, // May be empty depending on mode.
m_inputDimensions,
m_outputDimensions,
/*inout*/ paddedScales,
/*out*/ inputPixelOffsets,
/*out*/ outputPixelOffsets
);
// Find any useless dimensions of size 1 that occur in both input and output.
for (size_t i = 0, rank = m_outputDimensions.size(); i < rank; ++i)
{
if (m_inputDimensions[i] = 1 && m_outputDimensions[i] == 1)
{
squeezableDimensionIndices.push_back(gsl::narrow_cast<uint32_t>(i));
}
}
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ squeezedInputShape);
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ paddedScales);
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ inputPixelOffsets);
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ outputPixelOffsets);
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ squeezedOutputShape);
// Update the tensor descriptions.
MLOperatorTensorDataType inputTensorDataType = kernelCreationContext.GetInputEdgeDescription(0).tensorDataType;
auto inputTensorDesc = TensorDesc(inputTensorDataType, squeezedInputShape, squeezedInputShape, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, NchwDimensionCount, 0);
auto outputTensorDesc = TensorDesc(inputTensorDataType, squeezedOutputShape, squeezedOutputShape, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, NchwDimensionCount, 0);
m_inputTensorDescs[0] = inputTensorDesc;
m_outputTensorDescs[0] = outputTensorDesc;
// If the output tensor dimension count was right-aligned to a larger size,
// then ensure that scales has the same count as the tensor rank by inserting
// leading ones, since DirectML requires the scales to have the same count.
const uint32_t squeezedDimCount = gsl::narrow_cast<uint32_t>(squeezedOutputShape.size());
const uint32_t dmlCompatibleDimCount = outputTensorDesc.GetDimensionCount();
if (dmlCompatibleDimCount > squeezedDimCount)
{
paddedScales.insert(paddedScales.begin(), dmlCompatibleDimCount - squeezedDimCount, 1.0f);
inputPixelOffsets.insert(inputPixelOffsets.begin(), dmlCompatibleDimCount - squeezedDimCount, 0.5f);
outputPixelOffsets.insert(outputPixelOffsets.begin(), dmlCompatibleDimCount - squeezedDimCount, -0.5f);
}
std::string mode = kernelCreationContext.GetOptionalAttribute<std::string>(AttrName::Mode, "NEAREST");
DML_INTERPOLATION_MODE interpolationMode = Dml::MapStringToInteropolationMode(mode);
// DML's nearest neighbor mode uses round-halves-up (or round_prefer_ceil) via floor(input.x + 0.5).
// So to support floor, adjust the input by half a pixel.
// round_prefer_floor is not supported without an API extension,
// but existing code already default to treating it as round_prefer_ceil.
// So continue that.
if (interpolationMode == DML_INTERPOLATION_MODE_NEAREST_NEIGHBOR)
{
std::string nearestMode = kernelCreationContext.GetOptionalAttribute<std::string>(AttrName::NearestMode, "round_prefer_floor");
auto optionalNearestModeValue = TryMapStringToIndex(nearestMode, nearestNeighborRoundingModes);
if (optionalNearestModeValue)
{
switch (*optionalNearestModeValue)
{
case 0: // round_prefer_floor
case 1: // round_prefer_ceil
break;
case 2: // floor
for (auto& offset : inputPixelOffsets)
{
offset += 0.5;
}
break;
default:
assert(false);
}
}
}
// Create the operator description.
std::vector<DML_TENSOR_DESC> inputDescs = GetDmlInputDescs();
std::vector<DML_TENSOR_DESC> outputDescs = GetDmlOutputDescs();
DML_RESAMPLE1_OPERATOR_DESC operatorDesc = {};
operatorDesc.InputTensor = inputDescs.data();
operatorDesc.OutputTensor = outputDescs.data();
operatorDesc.InterpolationMode = interpolationMode;
operatorDesc.Scales = paddedScales.data();
operatorDesc.DimensionCount = gsl::narrow_cast<uint32_t>(paddedScales.size());
operatorDesc.InputPixelOffsets = inputPixelOffsets.data();
operatorDesc.OutputPixelOffsets = outputPixelOffsets.data();
DML_OPERATOR_DESC opDesc = { DML_OPERATOR_RESAMPLE1, &operatorDesc };
SetDmlOperatorDesc(opDesc, kernelCreationContext);
}
};
void CALLBACK QueryResize(IMLOperatorSupportQueryContextPrivate* context, bool* isSupported)
{
*isSupported = false;
MLOperatorAttributes attributes(context);
// DML does not support cubic.
std::string mode = attributes.GetOptionalAttribute<std::string>(AttrName::Mode, "nearest");
if (mode == "cubic")
{
return;
}
// DML clamps the input coordinates to the edges and essentially repeats the last pixel.
// So rescaling the input kernel total denominator is not supported.
int32_t excludeOutside = attributes.GetOptionalAttribute<int32_t>(AttrName::ExcludeOutside, 0);
if (excludeOutside != 0)
{
return;
}
// DML does not support specifying a specific element value for reading outside the edges.
// Note the extrapolation value is only pertinent for "tf_crop_and_resize" mode.
float extrapolationValue = attributes.GetOptionalAttribute<float>(AttrName::ExtrapolationValue, 0.0);
if (extrapolationValue != 0.0)
{
return;
}
// DML's nearest neighbor mode uses half pixels rounded down.
std::string nearestMode = attributes.GetOptionalAttribute<std::string>(AttrName::NearestMode, "round_prefer_floor");
auto optionalNearestModeValue = TryMapStringToIndex(nearestMode, nearestNeighborRoundingModes);
if (!optionalNearestModeValue)
{
return;
}
// Ignore parameter "cubic_coeff_a" since Cubic interpolation unsupported in DML.
// Ignore parameter "extrapolation_value" as DML clamps to the input rather than reading black pixels.
*isSupported = true;
}
DML_OP_DEFINE_CREATION_FUNCTION(Resize10, VersionedKernel<DmlOperatorResize, 10>);
DML_OP_DEFINE_CREATION_FUNCTION(Resize11, VersionedKernel<DmlOperatorResize, 11>);
DML_OP_DEFINE_CREATION_FUNCTION(Upsample7, VersionedKernel<DmlOperatorResize, 7>);
DML_OP_DEFINE_CREATION_FUNCTION(Upsample9, VersionedKernel<DmlOperatorResize, 9>);
DML_OP_DEFINE_CREATION_FUNCTION(Upsample10, VersionedKernel<DmlOperatorResize, 10>);
} // namespace Dml
<commit_msg>Bug in DmlOperatorResize.cpp with m_inputDimensions (#9456)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "precomp.h"
namespace Dml
{
constexpr NameAndIndex coordinateTransformationModes[] =
{
{"half_pixel", 0},
{"pytorch_half_pixel", 1},
{"align_corners", 2},
{"asymmetric", 3},
{"tf_half_pixel_for_nn", 4},
{"tf_crop_and_resize", 5},
};
constexpr NameAndIndex nearestNeighborRoundingModes[] =
{
{"", 0},
{"round_prefer_floor", 0},
{"round_prefer_ceil", 1},
{"floor", 2},
};
void ComputePixelOffsetsAndScales(
const MLOperatorKernelCreationContext& kernelCreationContext,
gsl::span<const float> regionOfInterest, // May be empty depending on mode.
gsl::span<const uint32_t> inputDimensions,
gsl::span<const uint32_t> outputDimensions,
/*inout*/ gsl::span<float> scales,
/*out*/ gsl::span<float> inputPixelOffsets,
/*out*/ gsl::span<float> outputPixelOffsets
)
{
assert(inputDimensions.size() == outputDimensions.size());
assert(inputPixelOffsets.size() == outputPixelOffsets.size());
assert(inputPixelOffsets.size() == scales.size());
assert(inputPixelOffsets.size() == inputDimensions.size());
assert(regionOfInterest.empty() || regionOfInterest.size() == inputDimensions.size() * 2);
std::string coordinateTransformationMode = kernelCreationContext.GetOptionalAttribute<std::string>(AttrName::CoordinateTransformationMode, "half_pixel");
auto optionalCoordinateTransformationModeValue = TryMapStringToIndex(coordinateTransformationMode, coordinateTransformationModes);
if (!optionalCoordinateTransformationModeValue)
{
ML_INVALID_ARGUMENT("Unsupported 'coordinate_transformation_mode'");
}
uint32_t coordinateTransformationModeValue = *optionalCoordinateTransformationModeValue;
ML_CHECK_VALID_ARGUMENT(
!regionOfInterest.empty() || coordinateTransformationModeValue != 5 /*tf_crop_and_resize*/,
"Resize expects 'roi' tensor for 'tf_crop_and_resize' mode."
);
const uint32_t rank = gsl::narrow_cast<uint32_t>(inputDimensions.size());
// Fill in all the input/output pixel offset for each axis,
// and recompute the scale for certain modes.
for (uint32_t i = 0; i < rank; ++i)
{
float inputPixelOffset = 0;
float outputPixelOffset = 0;
// All these mapping modes can be generalized to the equations:
//
// output_coordinate = (input_coordinate + input_offset ) * scale + output_offset
// input_coordinate = (output_coordinate - output_offset) / scale - input_offset
//
// With DML, a scale > 1 maps input to an upsampled output, and a positive pixel
// offset shifts the input contents to the right/down in the output.
//
// Since the equations from ONNX are in terms of mapping the output coordinate back
// to the input coordinate, any offsets need their signs flipped. e.g. For "half_pixel",
// the "x_resized" is the output coordinate, and the "+ 0.5" is the output coordinate
// adjustment which needs to be -0.5 when passed to DML.
switch (coordinateTransformationModeValue)
{
case 0:
// coordinate_transformation_mode is "half_pixel",
// x_original = (x_resized + 0.5) / scale - 0.5
inputPixelOffset = 0.5;
outputPixelOffset = -0.5;
// Keep existing scales.
break;
case 1:
// if coordinate_transformation_mode is "pytorch_half_pixel",
// x_original = length_resized > 1 ? (x_resized + 0.5) / scale - 0.5 : 0
if (inputDimensions[i] <= 1)
{
inputPixelOffset = 0.0;
outputPixelOffset = 0.0;
scales[i] = FLT_MAX; // Set large scale so all output pixels map to 0th input pixel.
}
else
{
inputPixelOffset = 0.5;
outputPixelOffset = -0.5;
// Keep existing scales.
}
break;
case 2:
// if coordinate_transformation_mode is "align_corners",
// x_original = x_resized * (length_original - 1) / (length_resized - 1)
inputPixelOffset = 0.0;
outputPixelOffset = 0.0;
if (outputDimensions[i] <= 1 || inputDimensions[i] <= 1)
{
// Protect against division by zero when either input/output is a single pixel.
scales[i] = FLT_MAX;
}
else
{
// Recalcalculate scale, ignoring existing one (only used to determine output size).
scales[i] = float(outputDimensions[i] - 1) / (inputDimensions[i] - 1);
}
break;
case 3:
// if coordinate_transformation_mode is "asymmetric",
// x_original = x_resized / scale
inputPixelOffset = 0.0;
outputPixelOffset = 0.0;
// Keep existing scales.
break;
case 4:
// if coordinate_transformation_mode is "tf_half_pixel_for_nn",
// x_original = (x_resized + 0.5) / scale
inputPixelOffset = 0.0;
outputPixelOffset = -0.5;
// Keep existing scales.
break;
case 5:
// if coordinate_transformation_mode is "tf_crop_and_resize",
// x_original = length_resized > 1 ? start_x * (length_original - 1) + x_resized * (end_x - start_x) * (length_original - 1) / (length_resized - 1)
// : 0.5 * (start_x + end_x) * (length_original - 1)
if (inputDimensions[i] > 1)
{
assert(regionOfInterest.size() == rank * 2);
// Fold this part of the equation into the input offset: start_x * (length_original - 1)
inputPixelOffset = -(regionOfInterest[i] * (inputDimensions[i] - 1));
outputPixelOffset = 0.0;
// Fold this part to scale: (end_x - start_x) * (length_original - 1) / (length_resized - 1)
float computedScale = float(outputDimensions[i] - 1)
/ std::max((regionOfInterest[i + rank] - regionOfInterest[i]) * (inputDimensions[i] - 1), 1.0f);
scales[i] = computedScale;
}
else // inputDimensions[i] <= 1
{
// 0.5 * (start_x + end_x) * (length_original - 1)
inputPixelOffset = -0.5f * (regionOfInterest[i] + regionOfInterest[i + rank]) * (inputDimensions[i] - 1);
outputPixelOffset = 0.0;
scales[i] = 1;
}
break;
default:
assert(false); // TryMapStringToIndex would have already bailed above.
}
inputPixelOffsets[i] = inputPixelOffset;
outputPixelOffsets[i] = outputPixelOffset;
}
}
class DmlOperatorResize : public DmlOperator, public ResizeHelper
{
public:
// Resample a multidimensional image to a new size.
DmlOperatorResize(const MLOperatorKernelCreationContext& kernelCreationContext, uint32_t opsetVersion)
: DmlOperator(kernelCreationContext),
ResizeHelper(kernelCreationContext, kernelCreationContext.GetTensorShapeDescription(), opsetVersion)
{
ML_CHECK_VALID_ARGUMENT(!m_scales.empty(), "Resize/Upsample expect scales, either a 2nd input tensors or 'scales' attribute.");
ML_CHECK_VALID_ARGUMENT(kernelCreationContext.GetOutputCount() == 1, "Resize/Upsample expect 1 output tensor.");
// Use only the first input tensor. In the case of Resize or the later Upsample-v9,
// the second tensor is CPU based and should not be passed to Resize.
std::vector<std::optional<uint32_t>> inputIndices = { 0 };
std::vector<std::optional<uint32_t>> outputIndices = { 0 };
DmlOperator::Initialize(kernelCreationContext, inputIndices, outputIndices);
// Because DirectML supports a limited number of dimensions, try to squeeze the dimension count
// to only those which actually matter. Models sometimes use a greater number of dimensions,
// even though those dimensions have no significance and can be elided (nop 1's), coercing the
// total dimension count back down to a supported value.
std::vector<uint32_t> squeezedInputShape = m_inputDimensions;
std::vector<uint32_t> squeezedOutputShape = m_outputDimensions;
std::vector<uint32_t> squeezableDimensionIndices;
std::vector<float> paddedScales = m_scales;
std::vector<float> inputPixelOffsets(paddedScales.size());
std::vector<float> outputPixelOffsets(paddedScales.size());
ComputePixelOffsetsAndScales(
kernelCreationContext,
m_regionOfInterest, // May be empty depending on mode.
m_inputDimensions,
m_outputDimensions,
/*inout*/ paddedScales,
/*out*/ inputPixelOffsets,
/*out*/ outputPixelOffsets
);
// Find any useless dimensions of size 1 that occur in both input and output.
for (size_t i = 0, rank = m_outputDimensions.size(); i < rank; ++i)
{
if (m_inputDimensions[i] == 1 && m_outputDimensions[i] == 1)
{
squeezableDimensionIndices.push_back(gsl::narrow_cast<uint32_t>(i));
}
}
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ squeezedInputShape);
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ paddedScales);
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ inputPixelOffsets);
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ outputPixelOffsets);
RemoveValuesByIndex(squeezableDimensionIndices, /*keepOneValue*/ true, /*inout*/ squeezedOutputShape);
// Update the tensor descriptions.
MLOperatorTensorDataType inputTensorDataType = kernelCreationContext.GetInputEdgeDescription(0).tensorDataType;
auto inputTensorDesc = TensorDesc(inputTensorDataType, squeezedInputShape, squeezedInputShape, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, NchwDimensionCount, 0);
auto outputTensorDesc = TensorDesc(inputTensorDataType, squeezedOutputShape, squeezedOutputShape, TensorAxis::DoNotCoerce, TensorAxis::W, TensorAxis::RightAligned, NchwDimensionCount, 0);
m_inputTensorDescs[0] = inputTensorDesc;
m_outputTensorDescs[0] = outputTensorDesc;
// If the output tensor dimension count was right-aligned to a larger size,
// then ensure that scales has the same count as the tensor rank by inserting
// leading ones, since DirectML requires the scales to have the same count.
const uint32_t squeezedDimCount = gsl::narrow_cast<uint32_t>(squeezedOutputShape.size());
const uint32_t dmlCompatibleDimCount = outputTensorDesc.GetDimensionCount();
if (dmlCompatibleDimCount > squeezedDimCount)
{
paddedScales.insert(paddedScales.begin(), dmlCompatibleDimCount - squeezedDimCount, 1.0f);
inputPixelOffsets.insert(inputPixelOffsets.begin(), dmlCompatibleDimCount - squeezedDimCount, 0.5f);
outputPixelOffsets.insert(outputPixelOffsets.begin(), dmlCompatibleDimCount - squeezedDimCount, -0.5f);
}
std::string mode = kernelCreationContext.GetOptionalAttribute<std::string>(AttrName::Mode, "NEAREST");
DML_INTERPOLATION_MODE interpolationMode = Dml::MapStringToInteropolationMode(mode);
// DML's nearest neighbor mode uses round-halves-up (or round_prefer_ceil) via floor(input.x + 0.5).
// So to support floor, adjust the input by half a pixel.
// round_prefer_floor is not supported without an API extension,
// but existing code already default to treating it as round_prefer_ceil.
// So continue that.
if (interpolationMode == DML_INTERPOLATION_MODE_NEAREST_NEIGHBOR)
{
std::string nearestMode = kernelCreationContext.GetOptionalAttribute<std::string>(AttrName::NearestMode, "round_prefer_floor");
auto optionalNearestModeValue = TryMapStringToIndex(nearestMode, nearestNeighborRoundingModes);
if (optionalNearestModeValue)
{
switch (*optionalNearestModeValue)
{
case 0: // round_prefer_floor
case 1: // round_prefer_ceil
break;
case 2: // floor
for (auto& offset : inputPixelOffsets)
{
offset += 0.5;
}
break;
default:
assert(false);
}
}
}
// Create the operator description.
std::vector<DML_TENSOR_DESC> inputDescs = GetDmlInputDescs();
std::vector<DML_TENSOR_DESC> outputDescs = GetDmlOutputDescs();
DML_RESAMPLE1_OPERATOR_DESC operatorDesc = {};
operatorDesc.InputTensor = inputDescs.data();
operatorDesc.OutputTensor = outputDescs.data();
operatorDesc.InterpolationMode = interpolationMode;
operatorDesc.Scales = paddedScales.data();
operatorDesc.DimensionCount = gsl::narrow_cast<uint32_t>(paddedScales.size());
operatorDesc.InputPixelOffsets = inputPixelOffsets.data();
operatorDesc.OutputPixelOffsets = outputPixelOffsets.data();
DML_OPERATOR_DESC opDesc = { DML_OPERATOR_RESAMPLE1, &operatorDesc };
SetDmlOperatorDesc(opDesc, kernelCreationContext);
}
};
void CALLBACK QueryResize(IMLOperatorSupportQueryContextPrivate* context, bool* isSupported)
{
*isSupported = false;
MLOperatorAttributes attributes(context);
// DML does not support cubic.
std::string mode = attributes.GetOptionalAttribute<std::string>(AttrName::Mode, "nearest");
if (mode == "cubic")
{
return;
}
// DML clamps the input coordinates to the edges and essentially repeats the last pixel.
// So rescaling the input kernel total denominator is not supported.
int32_t excludeOutside = attributes.GetOptionalAttribute<int32_t>(AttrName::ExcludeOutside, 0);
if (excludeOutside != 0)
{
return;
}
// DML does not support specifying a specific element value for reading outside the edges.
// Note the extrapolation value is only pertinent for "tf_crop_and_resize" mode.
float extrapolationValue = attributes.GetOptionalAttribute<float>(AttrName::ExtrapolationValue, 0.0);
if (extrapolationValue != 0.0)
{
return;
}
// DML's nearest neighbor mode uses half pixels rounded down.
std::string nearestMode = attributes.GetOptionalAttribute<std::string>(AttrName::NearestMode, "round_prefer_floor");
auto optionalNearestModeValue = TryMapStringToIndex(nearestMode, nearestNeighborRoundingModes);
if (!optionalNearestModeValue)
{
return;
}
// Ignore parameter "cubic_coeff_a" since Cubic interpolation unsupported in DML.
// Ignore parameter "extrapolation_value" as DML clamps to the input rather than reading black pixels.
*isSupported = true;
}
DML_OP_DEFINE_CREATION_FUNCTION(Resize10, VersionedKernel<DmlOperatorResize, 10>);
DML_OP_DEFINE_CREATION_FUNCTION(Resize11, VersionedKernel<DmlOperatorResize, 11>);
DML_OP_DEFINE_CREATION_FUNCTION(Upsample7, VersionedKernel<DmlOperatorResize, 7>);
DML_OP_DEFINE_CREATION_FUNCTION(Upsample9, VersionedKernel<DmlOperatorResize, 9>);
DML_OP_DEFINE_CREATION_FUNCTION(Upsample10, VersionedKernel<DmlOperatorResize, 10>);
} // namespace Dml
<|endoftext|> |
<commit_before>/**
* \file
* \brief PoolAllocator class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-01-11
*/
#ifndef INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
#define INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
#include "distortos/allocators/AllocatorBase.hpp"
namespace distortos
{
namespace allocators
{
/**
* \brief PoolAllocator class is a generic allocator which uses pool.
*
* \param T is the allocated type
* \param PoolType is the type of pool used by allocator
*/
template<typename T, typename PoolType>
class PoolAllocator : public AllocatorBase<T>
{
public:
/// alias of PoolType template parameter
using Pool = PoolType;
/// base of PoolAllocator
using Base = AllocatorBase<T>;
using typename Base::value_type;
using typename Base::pointer;
using typename Base::const_pointer;
using typename Base::reference;
using typename Base::const_reference;
using typename Base::size_type;
/**
* \brief Rebinds allocator to different type.
*
* \param U is the allocated type
*/
template<typename U>
struct rebind
{
/// type of rebound allocator
using other = PoolAllocator<U, Pool>;
};
/**
* \brief PoolAllocator's constructor
*
* \param [in] pool is a reference to pool used by allocator
*/
constexpr explicit PoolAllocator(Pool& pool) :
pool_(pool)
{
}
/**
* \brief PoolAllocator's copy constructor
*
* \param U is the allocated type
*
* \param [in] other is a reference to PoolAllocator which will be copied
*/
template<typename U>
constexpr explicit PoolAllocator(const PoolAllocator<U, Pool>& other) :
pool_(other.pool_)
{
}
/**
* \brief Allocates raw storage.
*
* \param [in] size is the number of elements (each of size sizeof(value_type)) to be allocated
* \param [in] hint is the hint that may be used to improve locality
*
* \return pointer to allocated storage
*/
pointer allocate(const size_type size, const void* = nullptr)
{
return static_cast<T*>(pool_.allocate(size * sizeof(T)));
}
/**
* \brief Deallocates raw storage.
*
* \param [in] storage is the pointer to deallocated storage
* \param [in] size is the number of elements (each of size sizeof(value_type)) to be deallocated
*/
void deallocate(const pointer storage, const size_type size)
{
pool_.deallocate(storage, size * sizeof(T));
}
private:
/// reference to pool used by allocator
Pool& pool_;
template<typename U, typename OtherPoolType>
friend class PoolAllocator;
template<typename T1, typename T2, typename OtherPoolType>
friend bool operator==(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right);
};
/**
* \brief PoolAllocator operator==
*
* \param T1 is the type allocated by left PoolAllocator
* \param T2 is the type allocated by right PoolAllocator
* \param OtherPoolType is the type of pool used by both allocators
*
* \param [in] left is a reference to left PoolAllocator
* \param [in] right is a reference to right PoolAllocator
*
* \return true if the allocators are equal, false otherwise
*/
template<typename T1, typename T2, typename OtherPoolType>
inline bool operator==(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right)
{
return &left.pool_ == &right.pool_;
}
/**
* \brief PoolAllocator operator!=
*
* \param T1 is the type allocated by left PoolAllocator
* \param T2 is the type allocated by right PoolAllocator
* \param OtherPoolType is the type of pool used by both allocators
*
* \param [in] left is a reference to left PoolAllocator
* \param [in] right is a reference to right PoolAllocator
*
* \return true if the allocators are not equal, false otherwise
*/
template<typename T1, typename T2, typename OtherPoolType>
inline bool operator!=(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right)
{
return !(left == right);
}
} // namespace allocators
} // namespace distortos
#endif // INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
<commit_msg>PoolAllocator: minor style improvements<commit_after>/**
* \file
* \brief PoolAllocator class header
*
* \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info
*
* \par License
* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not
* distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* \date 2015-10-18
*/
#ifndef INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
#define INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
#include "distortos/allocators/AllocatorBase.hpp"
namespace distortos
{
namespace allocators
{
/**
* \brief PoolAllocator class is a generic allocator which uses pool.
*
* \param T is the allocated type
* \param PoolType is the type of pool used by allocator
*/
template<typename T, typename PoolType>
class PoolAllocator : public AllocatorBase<T>
{
public:
/// alias of PoolType template parameter
using Pool = PoolType;
/// base of PoolAllocator
using Base = AllocatorBase<T>;
using typename Base::value_type;
using typename Base::pointer;
using typename Base::const_pointer;
using typename Base::reference;
using typename Base::const_reference;
using typename Base::size_type;
/**
* \brief Rebinds allocator to different type.
*
* \param U is the allocated type
*/
template<typename U>
struct rebind
{
/// type of rebound allocator
using other = PoolAllocator<U, Pool>;
};
/**
* \brief PoolAllocator's constructor
*
* \param [in] pool is a reference to pool used by allocator
*/
constexpr explicit PoolAllocator(Pool& pool) :
pool_{pool}
{
}
/**
* \brief PoolAllocator's copy constructor
*
* \param U is the allocated type
*
* \param [in] other is a reference to PoolAllocator which will be copied
*/
template<typename U>
constexpr explicit PoolAllocator(const PoolAllocator<U, Pool>& other) :
pool_{other.pool_}
{
}
/**
* \brief Allocates raw storage.
*
* \param [in] size is the number of elements (each of size sizeof(value_type)) to be allocated
* \param [in] hint is the hint that may be used to improve locality
*
* \return pointer to allocated storage
*/
pointer allocate(const size_type size, const void* = {})
{
return static_cast<T*>(pool_.allocate(size * sizeof(T)));
}
/**
* \brief Deallocates raw storage.
*
* \param [in] storage is the pointer to deallocated storage
* \param [in] size is the number of elements (each of size sizeof(value_type)) to be deallocated
*/
void deallocate(const pointer storage, const size_type size)
{
pool_.deallocate(storage, size * sizeof(T));
}
private:
/// reference to pool used by allocator
Pool& pool_;
template<typename U, typename OtherPoolType>
friend class PoolAllocator;
template<typename T1, typename T2, typename OtherPoolType>
friend bool operator==(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right);
};
/**
* \brief PoolAllocator operator==
*
* \param T1 is the type allocated by left PoolAllocator
* \param T2 is the type allocated by right PoolAllocator
* \param OtherPoolType is the type of pool used by both allocators
*
* \param [in] left is a reference to left PoolAllocator
* \param [in] right is a reference to right PoolAllocator
*
* \return true if the allocators are equal, false otherwise
*/
template<typename T1, typename T2, typename OtherPoolType>
inline bool operator==(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right)
{
return &left.pool_ == &right.pool_;
}
/**
* \brief PoolAllocator operator!=
*
* \param T1 is the type allocated by left PoolAllocator
* \param T2 is the type allocated by right PoolAllocator
* \param OtherPoolType is the type of pool used by both allocators
*
* \param [in] left is a reference to left PoolAllocator
* \param [in] right is a reference to right PoolAllocator
*
* \return true if the allocators are not equal, false otherwise
*/
template<typename T1, typename T2, typename OtherPoolType>
inline bool operator!=(const PoolAllocator<T1, OtherPoolType>& left, const PoolAllocator<T2, OtherPoolType>& right)
{
return (left == right) == false;
}
} // namespace allocators
} // namespace distortos
#endif // INCLUDE_DISTORTOS_ALLOCATORS_POOLALLOCATOR_HPP_
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
Some parts of this code are derived from ITK. See ITKCopyright.txt
for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Software Guide : BeginLatex
//
// The \doxygen{itk}{PointSet} class uses an internal container to manage the storage of
// \doxygen{itk}{Point}s. It is more efficient, in general, to manage points by using the
// access methods provided directly on the points container. The following
// example illustrates how to interact with the point container and how to use
// point iterators.
//
// Software Guide : EndLatex
#include "itkPointSet.h"
int main(int, char *[])
{
typedef itk::PointSet< unsigned short, 3 > PointSetType;
// Software Guide : BeginLatex
//
// The type is defined by the \emph{traits} of the PointSet
// class. The following line conveniently takes the PointsContainer type
// from the PointSet traits and declare it in the global namespace.
//
// \index{itk::PointSet!PointsContainer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef PointSetType::PointsContainer PointsContainer;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The actual type of the PointsContainer depends on what style of
// PointSet is being used. The dynamic PointSet use the
// \doxygen{itk}{MapContainer} while the static PointSet uses the
// \doxygen{itk}{VectorContainer}. The vector and map containers are basically
// ITK wrappers around the \href{http://www.sgi.com/tech/stl/}{STL}
// classes \href{http://www.sgi.com/tech/stl/Map.html}{\code{std::map}}
// and \href{http://www.sgi.com/tech/stl/Vector.html}{\code{std::vector}}.
// By default, the PointSet uses a static style, hence the default
// type of point container is an VectorContainer. Both the map
// and vector container are templated over the type of the elements they
// contain. In this case they are templated over PointType.
// Containers are reference counted object. They are then created with the
// \code{New()} method and assigned to a \doxygen{itk}{SmartPointer} after
// creation. The following line creates a point container compatible with
// the type of the PointSet from which the trait has been taken.
//
// \index{PointsContainer!New()}
// \index{PointsContainer!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointsContainer::Pointer points = PointsContainer::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Points can now be defined using the \code{PointType} trait from the
// PointSet.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef PointSetType::PointType PointType;
PointType p0;
PointType p1;
p0[0] = -1.0; p0[1] = 0.0; // Point 0 = {-1,0 }
p1[0] = 1.0; p1[1] = 0.0; // Point 1 = { 1,0 }
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The created points can be inserted in the PointsContainer using the
// generic method \code{InsertElement()} which requires an identifier to
// be provided for each point.
//
// \index{PointsContainer!InsertElement()}
// \index{PointsContainer!InsertElement()}
// \index{itk::VectorContainer!InsertElement()}
// \index{itk::MapContainer!InsertElement()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
unsigned int pointId = 0;
points->InsertElement( pointId++ , p0 );
points->InsertElement( pointId++ , p1 );
// Software Guide : EndCodeSnippet
PointSetType::Pointer pointSet = PointSetType::New();
// Software Guide : BeginLatex
//
// Finally the PointsContainer can be assigned to the PointSet. This will
// substitute any previously existing PointsContainer on the PointSet. The
// assignment is done using the \code{SetPoints()} method.
//
// \index{itk::PointSet!SetPoints()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
pointSet->SetPoints( points );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The PointsContainer object can be obtained from the PointSet using the
// \code{GetPoints()} method. This method returns a pointer
// to the actual container owned by the PointSet which is then assigned to
// a SmartPointer.
//
// \index{itk::PointSet!GetPoints()}
// \index{PointsContainer!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointsContainer::Pointer points2 = pointSet->GetPoints();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The most efficient way to sequentially visit the points is to use the
// iterators provided by PointsContainer. The \code{Iterator} type belongs
// to the traits of the PointsContainer classes. It behaves pretty much like
// the STL iterators.\footnote{If you dig deep enough into the code, you
// will discover that these iterators are actually ITK wrappers around STL
// iterators.} The Points iterator is not a reference counted class, so it
// is created directly from the traits without using SmartPointers.
//
// \index{PointsContainer!Iterator}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef PointsContainer::Iterator PointsIterator;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The subsequent use of the iterator follows what you may expect from a STL
// iterator. The iterator to the first point is obtained from the container
// with the \code{Begin()} method and assigned to another iterator.
//
// \index{PointsContainer!Begin()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointsIterator pointIterator = points->Begin();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \code{++} operator on the iterator can be used to advance from one
// point to the next. The actual value of the Point to which the iterator is
// pointing can be obtained with the \code{Value()} method. The loop for
// walking through all the points can be controlled by comparing the current
// iterator with the iterator returned by the \code{End()} method of the
// PointsContainer. The following lines illustrate the typical loop for
// walking through the points.
//
// \index{PointsContainer!End()}
// \index{PointsContainer!Iterator}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointsIterator end = points->End();
while( pointIterator != end )
{
PointType p = pointIterator.Value(); // access the point
std::cout << p << std::endl; // print the point
++pointIterator; // advance to next point
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that as in STL, the iterator returned by the \code{End()} method is
// not a valid iterator. This is called a past-end iterator in order to
// indicate that it is the value resulting from advancing one step after
// visiting the last element in the container.
//
// The number of elements stored in a container can be queried with the
// \code{Size()} method. In the case of the PointSet, the following two
// lines of code are equivalent, both of them returning the number of points
// in the PointSet.
//
// \index{itk::PointSet!GetNumberOfPoints()}
// \index{itk::PointSet!GetPoints()}
// \index{PointsContainer!Size()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
std::cout << pointSet->GetNumberOfPoints() << std::endl;
std::cout << pointSet->GetPoints()->Size() << std::endl;
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<commit_msg>COMP: Change PointSet dimension value 3 to 2<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
Some parts of this code are derived from ITK. See ITKCopyright.txt
for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
// Software Guide : BeginLatex
//
// The \doxygen{itk}{PointSet} class uses an internal container to manage the storage of
// \doxygen{itk}{Point}s. It is more efficient, in general, to manage points by using the
// access methods provided directly on the points container. The following
// example illustrates how to interact with the point container and how to use
// point iterators.
//
// Software Guide : EndLatex
#include "itkPointSet.h"
int main(int, char *[])
{
typedef itk::PointSet< unsigned short, 2 > PointSetType;
// Software Guide : BeginLatex
//
// The type is defined by the \emph{traits} of the PointSet
// class. The following line conveniently takes the PointsContainer type
// from the PointSet traits and declare it in the global namespace.
//
// \index{itk::PointSet!PointsContainer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef PointSetType::PointsContainer PointsContainer;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The actual type of the PointsContainer depends on what style of
// PointSet is being used. The dynamic PointSet use the
// \doxygen{itk}{MapContainer} while the static PointSet uses the
// \doxygen{itk}{VectorContainer}. The vector and map containers are basically
// ITK wrappers around the \href{http://www.sgi.com/tech/stl/}{STL}
// classes \href{http://www.sgi.com/tech/stl/Map.html}{\code{std::map}}
// and \href{http://www.sgi.com/tech/stl/Vector.html}{\code{std::vector}}.
// By default, the PointSet uses a static style, hence the default
// type of point container is an VectorContainer. Both the map
// and vector container are templated over the type of the elements they
// contain. In this case they are templated over PointType.
// Containers are reference counted object. They are then created with the
// \code{New()} method and assigned to a \doxygen{itk}{SmartPointer} after
// creation. The following line creates a point container compatible with
// the type of the PointSet from which the trait has been taken.
//
// \index{PointsContainer!New()}
// \index{PointsContainer!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointsContainer::Pointer points = PointsContainer::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Points can now be defined using the \code{PointType} trait from the
// PointSet.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef PointSetType::PointType PointType;
PointType p0;
PointType p1;
p0[0] = -1.0; p0[1] = 0.0; // Point 0 = {-1,0 }
p1[0] = 1.0; p1[1] = 0.0; // Point 1 = { 1,0 }
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The created points can be inserted in the PointsContainer using the
// generic method \code{InsertElement()} which requires an identifier to
// be provided for each point.
//
// \index{PointsContainer!InsertElement()}
// \index{PointsContainer!InsertElement()}
// \index{itk::VectorContainer!InsertElement()}
// \index{itk::MapContainer!InsertElement()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
unsigned int pointId = 0;
points->InsertElement( pointId++ , p0 );
points->InsertElement( pointId++ , p1 );
// Software Guide : EndCodeSnippet
PointSetType::Pointer pointSet = PointSetType::New();
// Software Guide : BeginLatex
//
// Finally the PointsContainer can be assigned to the PointSet. This will
// substitute any previously existing PointsContainer on the PointSet. The
// assignment is done using the \code{SetPoints()} method.
//
// \index{itk::PointSet!SetPoints()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
pointSet->SetPoints( points );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The PointsContainer object can be obtained from the PointSet using the
// \code{GetPoints()} method. This method returns a pointer
// to the actual container owned by the PointSet which is then assigned to
// a SmartPointer.
//
// \index{itk::PointSet!GetPoints()}
// \index{PointsContainer!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointsContainer::Pointer points2 = pointSet->GetPoints();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The most efficient way to sequentially visit the points is to use the
// iterators provided by PointsContainer. The \code{Iterator} type belongs
// to the traits of the PointsContainer classes. It behaves pretty much like
// the STL iterators.\footnote{If you dig deep enough into the code, you
// will discover that these iterators are actually ITK wrappers around STL
// iterators.} The Points iterator is not a reference counted class, so it
// is created directly from the traits without using SmartPointers.
//
// \index{PointsContainer!Iterator}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef PointsContainer::Iterator PointsIterator;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The subsequent use of the iterator follows what you may expect from a STL
// iterator. The iterator to the first point is obtained from the container
// with the \code{Begin()} method and assigned to another iterator.
//
// \index{PointsContainer!Begin()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointsIterator pointIterator = points->Begin();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The \code{++} operator on the iterator can be used to advance from one
// point to the next. The actual value of the Point to which the iterator is
// pointing can be obtained with the \code{Value()} method. The loop for
// walking through all the points can be controlled by comparing the current
// iterator with the iterator returned by the \code{End()} method of the
// PointsContainer. The following lines illustrate the typical loop for
// walking through the points.
//
// \index{PointsContainer!End()}
// \index{PointsContainer!Iterator}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
PointsIterator end = points->End();
while( pointIterator != end )
{
PointType p = pointIterator.Value(); // access the point
std::cout << p << std::endl; // print the point
++pointIterator; // advance to next point
}
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Note that as in STL, the iterator returned by the \code{End()} method is
// not a valid iterator. This is called a past-end iterator in order to
// indicate that it is the value resulting from advancing one step after
// visiting the last element in the container.
//
// The number of elements stored in a container can be queried with the
// \code{Size()} method. In the case of the PointSet, the following two
// lines of code are equivalent, both of them returning the number of points
// in the PointSet.
//
// \index{itk::PointSet!GetNumberOfPoints()}
// \index{itk::PointSet!GetPoints()}
// \index{PointsContainer!Size()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
std::cout << pointSet->GetNumberOfPoints() << std::endl;
std::cout << pointSet->GetPoints()->Size() << std::endl;
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "../base/SRC_FIRST.hpp"
#include "framebuffer.hpp"
#include "render_target.hpp"
#include "internal/opengl.hpp"
#include "utils.hpp"
#include "../base/logging.hpp"
#include "../std/list.hpp"
namespace yg
{
namespace gl
{
list<unsigned int> frameBufferStack;
unsigned FrameBuffer::current()
{
int id;
#ifdef OMIM_GL_ES
OGLCHECK(glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &id));
#else
OGLCHECK(glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &id));
#endif
return id;
}
void FrameBuffer::pushCurrent()
{
frameBufferStack.push_back(current());
}
void FrameBuffer::popCurrent()
{
#ifdef OMIM_GL_ES
OGLCHECK(glBindFramebufferOES(GL_FRAMEBUFFER_OES, frameBufferStack.back()));
#else
OGLCHECK(glBindFramebuffer(GL_FRAMEBUFFER_EXT, frameBufferStack.back()));
#endif
frameBufferStack.pop_back();
}
FrameBuffer::FrameBuffer(bool defaultFB /*= false*/) : m_width(0), m_height(0)
{
if (defaultFB)
m_id = 0;
else
{
#ifdef OMIM_GL_ES
OGLCHECK(glGenFramebuffersOES(1, &m_id));
#else
OGLCHECK(glGenFramebuffers(1, &m_id));
#endif
}
}
FrameBuffer::~FrameBuffer()
{
if (m_id != 0)
{
#ifdef OMIM_GL_ES
OGLCHECK(glDeleteFramebuffersOES(1, &m_id));
#else
OGLCHECK(glDeleteFramebuffers(1, &m_id));
#endif
}
}
void FrameBuffer::makeCurrent()
{
if (m_id != current())
{
#ifdef OMIM_GL_ES
OGLCHECK(glBindFramebufferOES(GL_FRAMEBUFFER_OES, m_id));
#else
OGLCHECK(glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_id));
#endif
// LOG(LINFO, ("FrameBuffer::makeCurrent", m_id));
}
if (m_renderTarget)
m_renderTarget->attachToFrameBuffer();
else
utils::setupCoordinates(width(), height(), true);
if (m_depthBuffer)
m_depthBuffer->attachToFrameBuffer();
/// !!! it's a must for a correct work.
checkStatus();
}
void FrameBuffer::setRenderTarget(shared_ptr<RenderTarget> const & renderTarget)
{
m_renderTarget = renderTarget;
}
shared_ptr<RenderTarget> const & FrameBuffer::renderTarget() const
{
return m_renderTarget;
}
void FrameBuffer::resetRenderTarget()
{
m_renderTarget.reset();
}
void FrameBuffer::setDepthBuffer(shared_ptr<RenderTarget> const & depthBuffer)
{
m_depthBuffer = depthBuffer;
}
shared_ptr<RenderTarget> const & FrameBuffer::depthBuffer() const
{
return m_depthBuffer;
}
void FrameBuffer::resetDepthBuffer()
{
m_depthBuffer.reset();
}
int FrameBuffer::id() const
{
return m_id;
}
unsigned FrameBuffer::width() const
{
return m_width;
}
unsigned FrameBuffer::height() const
{
return m_height;
}
void FrameBuffer::onSize(unsigned width, unsigned height)
{
m_width = width;
m_height = height;
}
void FrameBuffer::checkStatus()
{
#ifdef OMIM_GL_ES
GLenum res = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
if (res != GL_FRAMEBUFFER_COMPLETE_OES)
LOG(LERROR, ("incomplete framebuffer"));
#else
GLenum res = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (res == GL_FRAMEBUFFER_UNSUPPORTED)
LOG(LINFO, ("unsupported combination of attached target formats. could be possibly skipped"));
else if (res != GL_FRAMEBUFFER_COMPLETE_EXT)
LOG(LERROR, ("incomplete framebuffer"));
#endif
}
}
}
<commit_msg>Fixed EGL logging<commit_after>#include "../base/SRC_FIRST.hpp"
#include "framebuffer.hpp"
#include "render_target.hpp"
#include "internal/opengl.hpp"
#include "utils.hpp"
#include "../base/logging.hpp"
#include "../std/list.hpp"
namespace yg
{
namespace gl
{
list<unsigned int> frameBufferStack;
unsigned FrameBuffer::current()
{
int id;
#ifdef OMIM_GL_ES
OGLCHECK(glGetIntegerv(GL_FRAMEBUFFER_BINDING_OES, &id));
#else
OGLCHECK(glGetIntegerv(GL_FRAMEBUFFER_BINDING_EXT, &id));
#endif
return id;
}
void FrameBuffer::pushCurrent()
{
frameBufferStack.push_back(current());
}
void FrameBuffer::popCurrent()
{
#ifdef OMIM_GL_ES
OGLCHECK(glBindFramebufferOES(GL_FRAMEBUFFER_OES, frameBufferStack.back()));
#else
OGLCHECK(glBindFramebuffer(GL_FRAMEBUFFER_EXT, frameBufferStack.back()));
#endif
frameBufferStack.pop_back();
}
FrameBuffer::FrameBuffer(bool defaultFB /*= false*/) : m_width(0), m_height(0)
{
if (defaultFB)
m_id = 0;
else
{
#ifdef OMIM_GL_ES
OGLCHECK(glGenFramebuffersOES(1, &m_id));
#else
OGLCHECK(glGenFramebuffers(1, &m_id));
#endif
}
}
FrameBuffer::~FrameBuffer()
{
if (m_id != 0)
{
#ifdef OMIM_GL_ES
OGLCHECK(glDeleteFramebuffersOES(1, &m_id));
#else
OGLCHECK(glDeleteFramebuffers(1, &m_id));
#endif
}
}
void FrameBuffer::makeCurrent()
{
if (m_id != current())
{
#ifdef OMIM_GL_ES
OGLCHECK(glBindFramebufferOES(GL_FRAMEBUFFER_OES, m_id));
#else
OGLCHECK(glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_id));
#endif
// LOG(LINFO, ("FrameBuffer::makeCurrent", m_id));
}
if (m_renderTarget)
m_renderTarget->attachToFrameBuffer();
else
utils::setupCoordinates(width(), height(), true);
if (m_depthBuffer)
m_depthBuffer->attachToFrameBuffer();
/// !!! it's a must for a correct work.
checkStatus();
}
void FrameBuffer::setRenderTarget(shared_ptr<RenderTarget> const & renderTarget)
{
m_renderTarget = renderTarget;
}
shared_ptr<RenderTarget> const & FrameBuffer::renderTarget() const
{
return m_renderTarget;
}
void FrameBuffer::resetRenderTarget()
{
m_renderTarget.reset();
}
void FrameBuffer::setDepthBuffer(shared_ptr<RenderTarget> const & depthBuffer)
{
m_depthBuffer = depthBuffer;
}
shared_ptr<RenderTarget> const & FrameBuffer::depthBuffer() const
{
return m_depthBuffer;
}
void FrameBuffer::resetDepthBuffer()
{
m_depthBuffer.reset();
}
int FrameBuffer::id() const
{
return m_id;
}
unsigned FrameBuffer::width() const
{
return m_width;
}
unsigned FrameBuffer::height() const
{
return m_height;
}
void FrameBuffer::onSize(unsigned width, unsigned height)
{
m_width = width;
m_height = height;
}
void FrameBuffer::checkStatus()
{
#ifdef OMIM_GL_ES
GLenum res = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
if (res == GL_FRAMEBUFFER_UNSUPPORTED_OES)
LOG(LINFO, ("unsupported combination of attached target formats. could be possibly skipped"));
else if (res != GL_FRAMEBUFFER_COMPLETE_OES)
LOG(LERROR, ("incomplete framebuffer"));
#else
GLenum res = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
if (res == GL_FRAMEBUFFER_UNSUPPORTED)
LOG(LINFO, ("unsupported combination of attached target formats. could be possibly skipped"));
else if (res != GL_FRAMEBUFFER_COMPLETE_EXT)
LOG(LERROR, ("incomplete framebuffer"));
#endif
}
}
}
<|endoftext|> |
<commit_before>#include "com/mapswithme/maps/Framework.hpp"
#include "com/mapswithme/core/jni_helper.hpp"
#include "map/place_page_info.hpp"
#include "ugc/api.hpp"
#include "ugc/types.hpp"
#include "indexer/feature_decl.hpp"
#include "platform/preferred_languages.hpp"
#include "coding/multilang_utf8_string.hpp"
#include "base/logging.hpp"
#include <utility>
namespace
{
class FeatureIdBuilder
{
public:
FeatureID Build(JNIEnv * env, jobject obj)
{
Init(env);
jstring jcountryName = static_cast<jstring>(env->GetObjectField(obj, m_countryName));
jlong jversion = env->GetLongField(obj, m_version);
jint jindex = env->GetIntField(obj, m_index);
auto const countryName = jni::ToNativeString(env, jcountryName);
auto const version = static_cast<int64_t>(jversion);
auto const index = static_cast<uint32_t>(jindex);
auto const & ix = g_framework->GetIndex();
auto const id = ix.GetMwmIdByCountryFile(platform::CountryFile(countryName));
return FeatureID(id, index);
}
private:
void Init(JNIEnv * env)
{
if (m_initialized)
return;
m_class = jni::GetGlobalClassRef(env, "com/mapswithme/maps/bookmarks/data/FeatureId");
m_countryName = env->GetFieldID(m_class, "mMwmName", "Ljava/lang/String;");
m_version = env->GetFieldID(m_class, "mMwmVersion", "J");
m_index = env->GetFieldID(m_class, "mFeatureIndex", "I");
m_initialized = true;
}
bool m_initialized = false;
jclass m_class;
jfieldID m_countryName;
jfieldID m_version;
jfieldID m_index;
} g_builder;
class JavaBridge
{
public:
void OnResult(JNIEnv * env, ugc::UGC const & ugc, ugc::UGCUpdate const & ugcUpdate)
{
Init(env);
jni::TScopedLocalRef ugcResult(env, ToJavaUGC(env, ugc));
jni::TScopedLocalRef ugcUpdateResult(env, ToJavaUGCUpdate(env, ugcUpdate));
std::string formattedRating = place_page::rating::GetRatingFormatted(ugc.m_totalRating);
jni::TScopedLocalRef jrating(env, jni::ToJavaString(env, formattedRating));
env->CallStaticVoidMethod(m_ugcClass, m_onResult, ugcResult.get(), ugcUpdateResult.get(),
ToImpress(ugc.m_totalRating), jrating.get());
}
const int ToImpress(float const rating)
{
return static_cast<int>(place_page::rating::GetImpress(rating));
}
ugc::UGCUpdate ToNativeUGCUpdate(JNIEnv * env, jobject ugcUpdate)
{
Init(env);
jobjectArray jratings = static_cast<jobjectArray>(env->GetObjectField(ugcUpdate, m_ratingArrayFieldId));
int const length = env->GetArrayLength(jratings);
std::vector<ugc::RatingRecord> records(length);
for (int i = 0; i < length; i++)
{
jobject jrating = env->GetObjectArrayElement(jratings, i);
jstring name = static_cast<jstring>(env->GetObjectField(jrating, m_ratingNameFieldId));
ugc::TranslationKey key(jni::ToNativeString(env, name));
jfloat value = env->GetFloatField(jrating, m_ratingValueFieldId);
auto const ratingValue = static_cast<float>(value);
records.emplace_back(std::move(key), std::move(ratingValue));
}
jstring jtext = static_cast<jstring>(env->GetObjectField(ugcUpdate, m_ratingTextFieldId));
ugc::Text text(jni::ToNativeString(env, jtext),
StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm()));
jlong jtime = env->GetLongField(ugcUpdate, m_updateTimeFieldId);
uint64_t timeSec = static_cast<uint64_t>(jtime / 1000);
return ugc::UGCUpdate(records, text, std::chrono::system_clock::from_time_t(timeSec));
}
private:
jobject ToJavaUGC(JNIEnv * env, ugc::UGC const & ugc)
{
jni::TScopedLocalObjectArrayRef ratings(env, ToJavaRatings(env, ugc.m_ratings));
jni::TScopedLocalObjectArrayRef reviews(env, ToJavaReviews(env, ugc.m_reviews));
jobject result = nullptr;
if (!ugc.IsEmpty())
result = env->NewObject(m_ugcClass, m_ugcCtor, ratings.get(), ugc.m_totalRating,
reviews.get(), ugc.m_basedOn);
return result;
}
jobject ToJavaUGCUpdate(JNIEnv * env, ugc::UGCUpdate const & ugcUpdate)
{
jni::TScopedLocalObjectArrayRef ratings(env, ToJavaRatings(env, ugcUpdate.m_ratings));
jni::TScopedLocalRef text(env, jni::ToJavaString(env, ugcUpdate.m_text.m_text));
jobject result = nullptr;
if (!ugcUpdate.IsEmpty())
result = env->NewObject(m_ugcUpdateClass, m_ugcUpdateCtor, ratings.get(),
text.get(), ugc::ToMillisecondsSinceEpoch(ugcUpdate.m_time));
return result;
}
jobjectArray ToJavaRatings(JNIEnv * env, std::vector<ugc::RatingRecord> const & ratings)
{
size_t const n = ratings.size();
jobjectArray result = env->NewObjectArray(n, g_ratingClazz, nullptr);
for (size_t i = 0; i < n; ++i)
{
jni::TScopedLocalRef rating(env, ToJavaRating(env, ratings[i]));
env->SetObjectArrayElement(result, i, rating.get());
}
return result;
}
jobjectArray ToJavaReviews(JNIEnv * env, std::vector<ugc::Review> const & reviews)
{
size_t const n = reviews.size();
jobjectArray result = env->NewObjectArray(n, m_reviewClass, nullptr);
for (size_t i = 0; i < n; ++i)
{
jni::TScopedLocalRef review(env, ToJavaReview(env, reviews[i]));
env->SetObjectArrayElement(result, i, review.get());
}
return result;
}
jobject ToJavaRating(JNIEnv * env, ugc::RatingRecord const & ratingRecord)
{
jni::TScopedLocalRef name(env, jni::ToJavaString(env, ratingRecord.m_key.m_key));
jobject result = env->NewObject(g_ratingClazz, m_ratingCtor, name.get(), ratingRecord.m_value);
ASSERT(result, ());
return result;
}
jobject ToJavaReview(JNIEnv * env, ugc::Review const & review)
{
jni::TScopedLocalRef text(env, jni::ToJavaString(env, review.m_text.m_text));
jni::TScopedLocalRef author(env, jni::ToJavaString(env, review.m_author));
jobject result = env->NewObject(m_reviewClass, m_reviewCtor, text.get(), author.get(),
ugc::ToMillisecondsSinceEpoch(review.m_time), review.m_rating,
ToImpress(review.m_rating));
ASSERT(result, ());
return result;
}
void Init(JNIEnv * env)
{
if (m_initialized)
return;
m_ugcClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/ugc/UGC");
m_ugcCtor = jni::GetConstructorID(
env, m_ugcClass,
"([Lcom/mapswithme/maps/ugc/UGC$Rating;F[Lcom/mapswithme/maps/ugc/UGC$Review;I)V");
m_onResult = jni::GetStaticMethodID(env, m_ugcClass, "onUGCReceived",
"(Lcom/mapswithme/maps/ugc/UGC;Lcom/mapswithme/maps/ugc/UGCUpdate;ILjava/lang/String;)V");
m_ratingCtor = jni::GetConstructorID(env, g_ratingClazz, "(Ljava/lang/String;F)V");
m_reviewClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/ugc/UGC$Review");
m_reviewCtor =
jni::GetConstructorID(env, m_reviewClass, "(Ljava/lang/String;Ljava/lang/String;JFI)V");
m_ugcUpdateClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/ugc/UGCUpdate");
m_ugcUpdateCtor = jni::GetConstructorID(
env, m_ugcUpdateClass, "([Lcom/mapswithme/maps/ugc/UGC$Rating;Ljava/lang/String;J)V");
m_ratingArrayFieldId = env->GetFieldID(m_ugcUpdateClass, "mRatings", "[Lcom/mapswithme/maps/ugc/UGC$Rating;");
m_ratingTextFieldId = env->GetFieldID(m_ugcUpdateClass, "mText", "Ljava/lang/String;");
m_updateTimeFieldId = env->GetFieldID(m_ugcUpdateClass, "mTimeMillis", "J");
m_ratingNameFieldId = env->GetFieldID(g_ratingClazz, "mName", "Ljava/lang/String;");
m_ratingValueFieldId = env->GetFieldID(g_ratingClazz, "mValue", "F");
m_initialized = true;
}
bool m_initialized = false;
jclass m_ugcClass;
jmethodID m_ugcCtor;
jclass m_ugcUpdateClass;
jmethodID m_ugcUpdateCtor;
jfieldID m_ratingArrayFieldId;
jfieldID m_ratingTextFieldId;
jfieldID m_updateTimeFieldId;
jfieldID m_ratingNameFieldId;
jfieldID m_ratingValueFieldId;
jmethodID m_onResult;
jmethodID m_ratingCtor;
jclass m_reviewClass;
jmethodID m_reviewCtor;
} g_bridge;
} // namespace
extern "C" {
JNIEXPORT
void JNICALL Java_com_mapswithme_maps_ugc_UGC_requestUGC(JNIEnv * env, jclass /* clazz */,
jobject featureId)
{
auto const fid = g_builder.Build(env, featureId);
g_framework->RequestUGC(fid, [&](ugc::UGC const & ugc, ugc::UGCUpdate const & update) {
JNIEnv * e = jni::GetEnv();
g_bridge.OnResult(e, ugc, update);
});
}
JNIEXPORT
void JNICALL Java_com_mapswithme_maps_ugc_UGC_setUGCUpdate(JNIEnv * env, jclass /* clazz */,
jobject featureId, jobject ugcUpdate)
{
auto const fid = g_builder.Build(env, featureId);
ugc::UGCUpdate update = g_bridge.ToNativeUGCUpdate(env, ugcUpdate);
g_framework->SetUGCUpdate(fid, update);
}
JNIEXPORT
void JNICALL Java_com_mapswithme_maps_ugc_UGC_nativeUploadUGC(JNIEnv * env, jclass /* clazz */)
{
g_framework->UploadUGC();
}
}
<commit_msg>[android] Fixed rating duplication<commit_after>#include "com/mapswithme/maps/Framework.hpp"
#include "com/mapswithme/core/jni_helper.hpp"
#include "map/place_page_info.hpp"
#include "ugc/api.hpp"
#include "ugc/types.hpp"
#include "indexer/feature_decl.hpp"
#include "platform/preferred_languages.hpp"
#include "coding/multilang_utf8_string.hpp"
#include "base/logging.hpp"
#include <utility>
namespace
{
class FeatureIdBuilder
{
public:
FeatureID Build(JNIEnv * env, jobject obj)
{
Init(env);
jstring jcountryName = static_cast<jstring>(env->GetObjectField(obj, m_countryName));
jlong jversion = env->GetLongField(obj, m_version);
jint jindex = env->GetIntField(obj, m_index);
auto const countryName = jni::ToNativeString(env, jcountryName);
auto const version = static_cast<int64_t>(jversion);
auto const index = static_cast<uint32_t>(jindex);
auto const & ix = g_framework->GetIndex();
auto const id = ix.GetMwmIdByCountryFile(platform::CountryFile(countryName));
return FeatureID(id, index);
}
private:
void Init(JNIEnv * env)
{
if (m_initialized)
return;
m_class = jni::GetGlobalClassRef(env, "com/mapswithme/maps/bookmarks/data/FeatureId");
m_countryName = env->GetFieldID(m_class, "mMwmName", "Ljava/lang/String;");
m_version = env->GetFieldID(m_class, "mMwmVersion", "J");
m_index = env->GetFieldID(m_class, "mFeatureIndex", "I");
m_initialized = true;
}
bool m_initialized = false;
jclass m_class;
jfieldID m_countryName;
jfieldID m_version;
jfieldID m_index;
} g_builder;
class JavaBridge
{
public:
void OnResult(JNIEnv * env, ugc::UGC const & ugc, ugc::UGCUpdate const & ugcUpdate)
{
Init(env);
jni::TScopedLocalRef ugcResult(env, ToJavaUGC(env, ugc));
jni::TScopedLocalRef ugcUpdateResult(env, ToJavaUGCUpdate(env, ugcUpdate));
std::string formattedRating = place_page::rating::GetRatingFormatted(ugc.m_totalRating);
jni::TScopedLocalRef jrating(env, jni::ToJavaString(env, formattedRating));
env->CallStaticVoidMethod(m_ugcClass, m_onResult, ugcResult.get(), ugcUpdateResult.get(),
ToImpress(ugc.m_totalRating), jrating.get());
}
const int ToImpress(float const rating)
{
return static_cast<int>(place_page::rating::GetImpress(rating));
}
ugc::UGCUpdate ToNativeUGCUpdate(JNIEnv * env, jobject ugcUpdate)
{
Init(env);
jobjectArray jratings = static_cast<jobjectArray>(env->GetObjectField(ugcUpdate, m_ratingArrayFieldId));
int const length = env->GetArrayLength(jratings);
std::vector<ugc::RatingRecord> records;
records.reserve(length);
for (int i = 0; i < length; i++)
{
jobject jrating = env->GetObjectArrayElement(jratings, i);
jstring name = static_cast<jstring>(env->GetObjectField(jrating, m_ratingNameFieldId));
ugc::TranslationKey key(jni::ToNativeString(env, name));
jfloat value = env->GetFloatField(jrating, m_ratingValueFieldId);
auto const ratingValue = static_cast<float>(value);
records.emplace_back(std::move(key), std::move(ratingValue));
}
jstring jtext = static_cast<jstring>(env->GetObjectField(ugcUpdate, m_ratingTextFieldId));
ugc::Text text(jni::ToNativeString(env, jtext),
StringUtf8Multilang::GetLangIndex(languages::GetCurrentNorm()));
jlong jtime = env->GetLongField(ugcUpdate, m_updateTimeFieldId);
uint64_t timeSec = static_cast<uint64_t>(jtime / 1000);
return ugc::UGCUpdate(records, text, std::chrono::system_clock::from_time_t(timeSec));
}
private:
jobject ToJavaUGC(JNIEnv * env, ugc::UGC const & ugc)
{
jni::TScopedLocalObjectArrayRef ratings(env, ToJavaRatings(env, ugc.m_ratings));
jni::TScopedLocalObjectArrayRef reviews(env, ToJavaReviews(env, ugc.m_reviews));
jobject result = nullptr;
if (!ugc.IsEmpty())
result = env->NewObject(m_ugcClass, m_ugcCtor, ratings.get(), ugc.m_totalRating,
reviews.get(), ugc.m_basedOn);
return result;
}
jobject ToJavaUGCUpdate(JNIEnv * env, ugc::UGCUpdate const & ugcUpdate)
{
jni::TScopedLocalObjectArrayRef ratings(env, ToJavaRatings(env, ugcUpdate.m_ratings));
jni::TScopedLocalRef text(env, jni::ToJavaString(env, ugcUpdate.m_text.m_text));
jobject result = nullptr;
if (!ugcUpdate.IsEmpty())
result = env->NewObject(m_ugcUpdateClass, m_ugcUpdateCtor, ratings.get(),
text.get(), ugc::ToMillisecondsSinceEpoch(ugcUpdate.m_time));
return result;
}
jobjectArray ToJavaRatings(JNIEnv * env, std::vector<ugc::RatingRecord> const & ratings)
{
size_t const n = ratings.size();
jobjectArray result = env->NewObjectArray(n, g_ratingClazz, nullptr);
for (size_t i = 0; i < n; ++i)
{
jni::TScopedLocalRef rating(env, ToJavaRating(env, ratings[i]));
env->SetObjectArrayElement(result, i, rating.get());
}
return result;
}
jobjectArray ToJavaReviews(JNIEnv * env, std::vector<ugc::Review> const & reviews)
{
size_t const n = reviews.size();
jobjectArray result = env->NewObjectArray(n, m_reviewClass, nullptr);
for (size_t i = 0; i < n; ++i)
{
jni::TScopedLocalRef review(env, ToJavaReview(env, reviews[i]));
env->SetObjectArrayElement(result, i, review.get());
}
return result;
}
jobject ToJavaRating(JNIEnv * env, ugc::RatingRecord const & ratingRecord)
{
jni::TScopedLocalRef name(env, jni::ToJavaString(env, ratingRecord.m_key.m_key));
jobject result = env->NewObject(g_ratingClazz, m_ratingCtor, name.get(), ratingRecord.m_value);
ASSERT(result, ());
return result;
}
jobject ToJavaReview(JNIEnv * env, ugc::Review const & review)
{
jni::TScopedLocalRef text(env, jni::ToJavaString(env, review.m_text.m_text));
jni::TScopedLocalRef author(env, jni::ToJavaString(env, review.m_author));
jobject result = env->NewObject(m_reviewClass, m_reviewCtor, text.get(), author.get(),
ugc::ToMillisecondsSinceEpoch(review.m_time), review.m_rating,
ToImpress(review.m_rating));
ASSERT(result, ());
return result;
}
void Init(JNIEnv * env)
{
if (m_initialized)
return;
m_ugcClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/ugc/UGC");
m_ugcCtor = jni::GetConstructorID(
env, m_ugcClass,
"([Lcom/mapswithme/maps/ugc/UGC$Rating;F[Lcom/mapswithme/maps/ugc/UGC$Review;I)V");
m_onResult = jni::GetStaticMethodID(env, m_ugcClass, "onUGCReceived",
"(Lcom/mapswithme/maps/ugc/UGC;Lcom/mapswithme/maps/ugc/UGCUpdate;ILjava/lang/String;)V");
m_ratingCtor = jni::GetConstructorID(env, g_ratingClazz, "(Ljava/lang/String;F)V");
m_reviewClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/ugc/UGC$Review");
m_reviewCtor =
jni::GetConstructorID(env, m_reviewClass, "(Ljava/lang/String;Ljava/lang/String;JFI)V");
m_ugcUpdateClass = jni::GetGlobalClassRef(env, "com/mapswithme/maps/ugc/UGCUpdate");
m_ugcUpdateCtor = jni::GetConstructorID(
env, m_ugcUpdateClass, "([Lcom/mapswithme/maps/ugc/UGC$Rating;Ljava/lang/String;J)V");
m_ratingArrayFieldId = env->GetFieldID(m_ugcUpdateClass, "mRatings", "[Lcom/mapswithme/maps/ugc/UGC$Rating;");
m_ratingTextFieldId = env->GetFieldID(m_ugcUpdateClass, "mText", "Ljava/lang/String;");
m_updateTimeFieldId = env->GetFieldID(m_ugcUpdateClass, "mTimeMillis", "J");
m_ratingNameFieldId = env->GetFieldID(g_ratingClazz, "mName", "Ljava/lang/String;");
m_ratingValueFieldId = env->GetFieldID(g_ratingClazz, "mValue", "F");
m_initialized = true;
}
bool m_initialized = false;
jclass m_ugcClass;
jmethodID m_ugcCtor;
jclass m_ugcUpdateClass;
jmethodID m_ugcUpdateCtor;
jfieldID m_ratingArrayFieldId;
jfieldID m_ratingTextFieldId;
jfieldID m_updateTimeFieldId;
jfieldID m_ratingNameFieldId;
jfieldID m_ratingValueFieldId;
jmethodID m_onResult;
jmethodID m_ratingCtor;
jclass m_reviewClass;
jmethodID m_reviewCtor;
} g_bridge;
} // namespace
extern "C" {
JNIEXPORT
void JNICALL Java_com_mapswithme_maps_ugc_UGC_requestUGC(JNIEnv * env, jclass /* clazz */,
jobject featureId)
{
auto const fid = g_builder.Build(env, featureId);
g_framework->RequestUGC(fid, [&](ugc::UGC const & ugc, ugc::UGCUpdate const & update) {
JNIEnv * e = jni::GetEnv();
g_bridge.OnResult(e, ugc, update);
});
}
JNIEXPORT
void JNICALL Java_com_mapswithme_maps_ugc_UGC_setUGCUpdate(JNIEnv * env, jclass /* clazz */,
jobject featureId, jobject ugcUpdate)
{
auto const fid = g_builder.Build(env, featureId);
ugc::UGCUpdate update = g_bridge.ToNativeUGCUpdate(env, ugcUpdate);
g_framework->SetUGCUpdate(fid, update);
}
JNIEXPORT
void JNICALL Java_com_mapswithme_maps_ugc_UGC_nativeUploadUGC(JNIEnv * env, jclass /* clazz */)
{
g_framework->UploadUGC();
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 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 <map>
#include <memory>
#include "database_fwd.hh"
#include "dht/i_partitioner.hh"
#include "schema.hh"
#include "mutation_reader.hh"
#include "db/commitlog/replay_position.hh"
#include "db/commitlog/rp_set.hh"
#include "utils/logalloc.hh"
#include "partition_version.hh"
class frozen_mutation;
namespace bi = boost::intrusive;
class memtable_entry {
bi::set_member_hook<> _link;
schema_ptr _schema;
dht::decorated_key _key;
partition_entry _pe;
public:
friend class memtable;
memtable_entry(schema_ptr s, dht::decorated_key key, mutation_partition p)
: _schema(std::move(s))
, _key(std::move(key))
, _pe(std::move(p))
{ }
memtable_entry(memtable_entry&& o) noexcept;
const dht::decorated_key& key() const { return _key; }
dht::decorated_key& key() { return _key; }
const partition_entry& partition() const { return _pe; }
partition_entry& partition() { return _pe; }
const schema_ptr& schema() const { return _schema; }
schema_ptr& schema() { return _schema; }
streamed_mutation read(lw_shared_ptr<memtable> mtbl, const schema_ptr&, const query::partition_slice&, streamed_mutation::forwarding);
size_t external_memory_usage_without_rows() const {
return _key.key().external_memory_usage();
}
struct compare {
dht::decorated_key::less_comparator _c;
compare(schema_ptr s)
: _c(std::move(s))
{}
bool operator()(const dht::decorated_key& k1, const memtable_entry& k2) const {
return _c(k1, k2._key);
}
bool operator()(const memtable_entry& k1, const memtable_entry& k2) const {
return _c(k1._key, k2._key);
}
bool operator()(const memtable_entry& k1, const dht::decorated_key& k2) const {
return _c(k1._key, k2);
}
bool operator()(const memtable_entry& k1, const dht::ring_position& k2) const {
return _c(k1._key, k2);
}
bool operator()(const dht::ring_position& k1, const memtable_entry& k2) const {
return _c(k1, k2._key);
}
};
};
class dirty_memory_manager;
// Managed by lw_shared_ptr<>.
class memtable final : public enable_lw_shared_from_this<memtable>, private logalloc::region {
public:
using partitions_type = bi::set<memtable_entry,
bi::member_hook<memtable_entry, bi::set_member_hook<>, &memtable_entry::_link>,
bi::compare<memtable_entry::compare>>;
private:
dirty_memory_manager& _dirty_mgr;
memtable_list *_memtable_list;
schema_ptr _schema;
logalloc::allocating_section _read_section;
logalloc::allocating_section _allocating_section;
partitions_type partitions;
db::replay_position _replay_position;
db::rp_set _rp_set;
// mutation source to which reads fall-back after mark_flushed()
// so that memtable contents can be moved away while there are
// still active readers. This is needed for this mutation_source
// to be monotonic (not loose writes). Monotonicity of each
// mutation_source is necessary for the combined mutation source to be
// monotonic. That combined source in this case is cache + memtable.
mutation_source_opt _underlying;
uint64_t _flushed_memory = 0;
void update(db::rp_handle&&);
friend class row_cache;
friend class memtable_entry;
friend class flush_reader;
friend class flush_memory_accounter;
private:
boost::iterator_range<partitions_type::const_iterator> slice(const dht::partition_range& r) const;
partition_entry& find_or_create_partition(const dht::decorated_key& key);
partition_entry& find_or_create_partition_slow(partition_key_view key);
void upgrade_entry(memtable_entry&);
void add_flushed_memory(uint64_t);
void remove_flushed_memory(uint64_t);
void clear() noexcept;
uint64_t dirty_size() const;
public:
explicit memtable(schema_ptr schema, dirty_memory_manager&, memtable_list *memtable_list = nullptr);
// Used for testing that want to control the flush process.
explicit memtable(schema_ptr schema);
~memtable();
// Clears this memtable gradually without consuming the whole CPU.
// Never resolves with a failed future.
future<> clear_gently() noexcept;
schema_ptr schema() const { return _schema; }
void set_schema(schema_ptr) noexcept;
future<> apply(memtable&);
// Applies mutation to this memtable.
// The mutation is upgraded to current schema.
void apply(const mutation& m, db::rp_handle&& = {});
// The mutation is upgraded to current schema.
void apply(const frozen_mutation& m, const schema_ptr& m_schema, db::rp_handle&& = {});
static memtable& from_region(logalloc::region& r) {
return static_cast<memtable&>(r);
}
const logalloc::region& region() const {
return *this;
}
logalloc::region_group* region_group() {
return group();
}
public:
memtable_list* get_memtable_list() {
return _memtable_list;
}
size_t partition_count() const;
logalloc::occupancy_stats occupancy() const;
// Creates a reader of data in this memtable for given partition range.
//
// Live readers share ownership of the memtable instance, so caller
// doesn't need to ensure that memtable remains live.
//
// The 'range' parameter must be live as long as the reader is being used
//
// Mutations returned by the reader will all have given schema.
mutation_reader make_reader(schema_ptr,
const dht::partition_range& range = query::full_partition_range,
const query::partition_slice& slice = query::full_slice,
const io_priority_class& pc = default_priority_class(),
tracing::trace_state_ptr trace_state_ptr = nullptr,
streamed_mutation::forwarding fwd = streamed_mutation::forwarding::no,
mutation_reader::forwarding fwd_mr = mutation_reader::forwarding::no);
mutation_reader make_flush_reader(schema_ptr, const io_priority_class& pc);
mutation_source as_data_source();
bool empty() const { return partitions.empty(); }
void mark_flushed(mutation_source);
bool is_flushed() const;
void on_detach_from_region_group() noexcept;
void revert_flushed_memory() noexcept;
const db::replay_position& replay_position() const {
return _replay_position;
}
const db::rp_set& rp_set() const {
return _rp_set;
}
friend class iterator_reader;
};
<commit_msg>memtable: Created readers should be fast forwardable by default<commit_after>/*
* Copyright (C) 2015 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 <map>
#include <memory>
#include "database_fwd.hh"
#include "dht/i_partitioner.hh"
#include "schema.hh"
#include "mutation_reader.hh"
#include "db/commitlog/replay_position.hh"
#include "db/commitlog/rp_set.hh"
#include "utils/logalloc.hh"
#include "partition_version.hh"
class frozen_mutation;
namespace bi = boost::intrusive;
class memtable_entry {
bi::set_member_hook<> _link;
schema_ptr _schema;
dht::decorated_key _key;
partition_entry _pe;
public:
friend class memtable;
memtable_entry(schema_ptr s, dht::decorated_key key, mutation_partition p)
: _schema(std::move(s))
, _key(std::move(key))
, _pe(std::move(p))
{ }
memtable_entry(memtable_entry&& o) noexcept;
const dht::decorated_key& key() const { return _key; }
dht::decorated_key& key() { return _key; }
const partition_entry& partition() const { return _pe; }
partition_entry& partition() { return _pe; }
const schema_ptr& schema() const { return _schema; }
schema_ptr& schema() { return _schema; }
streamed_mutation read(lw_shared_ptr<memtable> mtbl, const schema_ptr&, const query::partition_slice&, streamed_mutation::forwarding);
size_t external_memory_usage_without_rows() const {
return _key.key().external_memory_usage();
}
struct compare {
dht::decorated_key::less_comparator _c;
compare(schema_ptr s)
: _c(std::move(s))
{}
bool operator()(const dht::decorated_key& k1, const memtable_entry& k2) const {
return _c(k1, k2._key);
}
bool operator()(const memtable_entry& k1, const memtable_entry& k2) const {
return _c(k1._key, k2._key);
}
bool operator()(const memtable_entry& k1, const dht::decorated_key& k2) const {
return _c(k1._key, k2);
}
bool operator()(const memtable_entry& k1, const dht::ring_position& k2) const {
return _c(k1._key, k2);
}
bool operator()(const dht::ring_position& k1, const memtable_entry& k2) const {
return _c(k1, k2._key);
}
};
};
class dirty_memory_manager;
// Managed by lw_shared_ptr<>.
class memtable final : public enable_lw_shared_from_this<memtable>, private logalloc::region {
public:
using partitions_type = bi::set<memtable_entry,
bi::member_hook<memtable_entry, bi::set_member_hook<>, &memtable_entry::_link>,
bi::compare<memtable_entry::compare>>;
private:
dirty_memory_manager& _dirty_mgr;
memtable_list *_memtable_list;
schema_ptr _schema;
logalloc::allocating_section _read_section;
logalloc::allocating_section _allocating_section;
partitions_type partitions;
db::replay_position _replay_position;
db::rp_set _rp_set;
// mutation source to which reads fall-back after mark_flushed()
// so that memtable contents can be moved away while there are
// still active readers. This is needed for this mutation_source
// to be monotonic (not loose writes). Monotonicity of each
// mutation_source is necessary for the combined mutation source to be
// monotonic. That combined source in this case is cache + memtable.
mutation_source_opt _underlying;
uint64_t _flushed_memory = 0;
void update(db::rp_handle&&);
friend class row_cache;
friend class memtable_entry;
friend class flush_reader;
friend class flush_memory_accounter;
private:
boost::iterator_range<partitions_type::const_iterator> slice(const dht::partition_range& r) const;
partition_entry& find_or_create_partition(const dht::decorated_key& key);
partition_entry& find_or_create_partition_slow(partition_key_view key);
void upgrade_entry(memtable_entry&);
void add_flushed_memory(uint64_t);
void remove_flushed_memory(uint64_t);
void clear() noexcept;
uint64_t dirty_size() const;
public:
explicit memtable(schema_ptr schema, dirty_memory_manager&, memtable_list *memtable_list = nullptr);
// Used for testing that want to control the flush process.
explicit memtable(schema_ptr schema);
~memtable();
// Clears this memtable gradually without consuming the whole CPU.
// Never resolves with a failed future.
future<> clear_gently() noexcept;
schema_ptr schema() const { return _schema; }
void set_schema(schema_ptr) noexcept;
future<> apply(memtable&);
// Applies mutation to this memtable.
// The mutation is upgraded to current schema.
void apply(const mutation& m, db::rp_handle&& = {});
// The mutation is upgraded to current schema.
void apply(const frozen_mutation& m, const schema_ptr& m_schema, db::rp_handle&& = {});
static memtable& from_region(logalloc::region& r) {
return static_cast<memtable&>(r);
}
const logalloc::region& region() const {
return *this;
}
logalloc::region_group* region_group() {
return group();
}
public:
memtable_list* get_memtable_list() {
return _memtable_list;
}
size_t partition_count() const;
logalloc::occupancy_stats occupancy() const;
// Creates a reader of data in this memtable for given partition range.
//
// Live readers share ownership of the memtable instance, so caller
// doesn't need to ensure that memtable remains live.
//
// The 'range' parameter must be live as long as the reader is being used
//
// Mutations returned by the reader will all have given schema.
mutation_reader make_reader(schema_ptr,
const dht::partition_range& range = query::full_partition_range,
const query::partition_slice& slice = query::full_slice,
const io_priority_class& pc = default_priority_class(),
tracing::trace_state_ptr trace_state_ptr = nullptr,
streamed_mutation::forwarding fwd = streamed_mutation::forwarding::no,
mutation_reader::forwarding fwd_mr = mutation_reader::forwarding::yes);
mutation_reader make_flush_reader(schema_ptr, const io_priority_class& pc);
mutation_source as_data_source();
bool empty() const { return partitions.empty(); }
void mark_flushed(mutation_source);
bool is_flushed() const;
void on_detach_from_region_group() noexcept;
void revert_flushed_memory() noexcept;
const db::replay_position& replay_position() const {
return _replay_position;
}
const db::rp_set& rp_set() const {
return _rp_set;
}
friend class iterator_reader;
};
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// IOFacadeTest.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "IO/IO.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "IO/Stream/BinaryStreamReader.h"
#include "IO/Stream/BinaryStreamWriter.h"
#include "IO/Stream/MemoryStream.h"
using namespace Oryol;
std::atomic<int32> numGetHandled{0};
std::atomic<int32> numGetRangeHandled{0};
class TestFileSystem : public FileSystem {
OryolClassDecl(TestFileSystem);
OryolClassCreator(TestFileSystem);
public:
/// called when the IOProtocol::Get message is received
virtual void onGet(const Ptr<IOProtocol::Get>& msg) {
Log::Info("TestFileSystem::onGet() called!\n");
numGetHandled++;
// create a stream object, and just write the URL from the msg to it
Ptr<MemoryStream> stream = MemoryStream::Create();
stream->Open(OpenMode::WriteOnly);
Ptr<BinaryStreamWriter> writer = BinaryStreamWriter::Create(stream);
writer->Write(msg->GetURL().Get());
stream->Close();
msg->SetStream(stream);
msg->SetStatus(IOStatus::OK);
msg->SetHandled();
};
/// called when the IOProtocol::GetRange message is received
virtual void onGetRange(const Ptr<IOProtocol::GetRange>& msg) {
Log::Info("TestFileSystem::onGetRange() called!\n");
numGetRangeHandled++;
msg->SetHandled();
}
};
OryolClassImpl(TestFileSystem);
TEST(IOFacadeTest) {
IO::Setup(IOSetup());
// register our test file-system as URI scheme "test"
IO::RegisterFileSystem("test", TestFileSystem::Creator());
// setup an assign which resolves to the test file system
IO::SetAssign("bla:", "test://blub.com/");
// an URL which should resolve to test://blub.com/blob.txt
URL url("bla:blob.txt");
CHECK(url.IsValid());
// asynchronously 'load' a file
Ptr<IOProtocol::Get> msg = IO::LoadFile(url);
// trigger the runloop until our message is handled
while (!msg->Handled()) {
Core::PreRunLoop()->Run();
}
CHECK(numGetHandled == 1);
CHECK(numGetRangeHandled == 0);
// check the msg result
CHECK(msg->GetStream().isValid());
CHECK(msg->GetStatus() == IOStatus::OK);
const Ptr<Stream>& stream = msg->GetStream();
stream->Open(OpenMode::ReadOnly);
Ptr<BinaryStreamReader> reader = BinaryStreamReader::Create(stream);
StringAtom str;
CHECK(reader->Read(str));
stream->Close();
CHECK(str == msg->GetURL().Get());
// FIXME: dynamically add/remove/replace filesystems, ...
IO::Discard();
}
<commit_msg>Fixed IO test<commit_after>//------------------------------------------------------------------------------
// IOFacadeTest.cc
//------------------------------------------------------------------------------
#include "Pre.h"
#include "UnitTest++/src/UnitTest++.h"
#include "IO/IO.h"
#include "Core/Core.h"
#include "Core/RunLoop.h"
#include "IO/Stream/BinaryStreamReader.h"
#include "IO/Stream/BinaryStreamWriter.h"
#include "IO/Stream/MemoryStream.h"
using namespace Oryol;
std::atomic<int32> numRequestsHandled{0};
class TestFileSystem : public FileSystem {
OryolClassDecl(TestFileSystem);
OryolClassCreator(TestFileSystem);
public:
/// called when the IOProtocol::Get message is received
virtual void onRequest(const Ptr<IOProtocol::Request>& msg) {
Log::Info("TestFileSystem::onRequest() called!\n");
numRequestsHandled++;
// create a stream object, and just write the URL from the msg to it
Ptr<MemoryStream> stream = MemoryStream::Create();
stream->Open(OpenMode::WriteOnly);
Ptr<BinaryStreamWriter> writer = BinaryStreamWriter::Create(stream);
writer->Write(msg->GetURL().Get());
stream->Close();
msg->SetStream(stream);
msg->SetStatus(IOStatus::OK);
msg->SetHandled();
};
};
OryolClassImpl(TestFileSystem);
TEST(IOFacadeTest) {
IO::Setup(IOSetup());
// register our test file-system as URI scheme "test"
IO::RegisterFileSystem("test", TestFileSystem::Creator());
// setup an assign which resolves to the test file system
IO::SetAssign("bla:", "test://blub.com/");
// an URL which should resolve to test://blub.com/blob.txt
URL url("bla:blob.txt");
CHECK(url.IsValid());
// asynchronously 'load' a file
Ptr<IOProtocol::Request> msg = IO::LoadFile(url);
// trigger the runloop until our message is handled
while (!msg->Handled()) {
Core::PreRunLoop()->Run();
}
CHECK(numRequestsHandled == 1);
// check the msg result
CHECK(msg->GetStream().isValid());
CHECK(msg->GetStatus() == IOStatus::OK);
const Ptr<Stream>& stream = msg->GetStream();
stream->Open(OpenMode::ReadOnly);
Ptr<BinaryStreamReader> reader = BinaryStreamReader::Create(stream);
StringAtom str;
CHECK(reader->Read(str));
stream->Close();
CHECK(str == msg->GetURL().Get());
// FIXME: dynamically add/remove/replace filesystems, ...
IO::Discard();
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: BinaryMedianImageFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : eginCommandLineArgs
// INPUTS: {BrainProtonDensitySlice.png}
// OUTPUTS: {BinaryMedianImageFilterOutput.png}
// 2
// Software Guide : ndCommandLineArgs
// Software Guide : BeginLatex
//
// The \doxygen{BinaryMedianImageFilter} is commonly used as a robust approach
// for noise reduction. BinaryMedianImageFilter computes the value of each
// output pixel as the statistical median of the neighborhood of values around
// the corresponding input pixel. When the input images are binary, the
// implementation can be optimized by simply counting the number of pixels
// ON/OFF around the current pixel.
//
// This filter will work on images of any dimension thanks to the internal use
// of \doxygen{NeighborhoodIterator} and \doxygen{NeighborhoodOperator}. The
// size of the neighborhood over which the median is computed can be set by
// the user.
//
// \index{itk::BinaryMedianImageFilter}
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
// Software Guide : BeginLatex
//
// The header file corresponding to this filter should be included first.
//
// \index{itk::BinaryMedianImageFilter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkBinaryMedianImageFilter.h"
// Software Guide : EndCodeSnippet
int main( int argc, char * argv[] )
{
if( argc < 4 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile radiusX radiusY" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// Then the pixel and image types of the input and output must be defined.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned char InputPixelType;
typedef unsigned char OutputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::Image< OutputPixelType, 2 > OutputImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
// Software Guide : BeginLatex
//
// Using the image types, it is now possible to define the filter type
// and create the filter object.
//
// \index{itk::BinaryMedianImageFilter!instantiation}
// \index{itk::BinaryMedianImageFilter!New()}
// \index{itk::BinaryMedianImageFilter!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::BinaryMedianImageFilter<
InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The size of the neighborhood is defined along every dimension by
// passing a \code{SizeType} object with the corresponding values. The
// value on each dimension is used as the semi-size of a rectangular
// box. For example, in $2D$ a size of \(1,2\) will result in a $3 \times
// 5$ neighborhood.
//
// \index{itk::BinaryMedianImageFilter!Radius}
// \index{itk::BinaryMedianImageFilter!Neighborhood}
//
// Software Guide : EndLatex
const unsigned int radiusX = atoi( argv[3] );
const unsigned int radiusY = atoi( argv[4] );
// Software Guide : BeginCodeSnippet
InputImageType::SizeType indexRadius;
indexRadius[0] = radiusX; // radius along x
indexRadius[1] = radiusY; // radius along y
filter->SetRadius( indexRadius );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The input to the filter can be taken from any other filter, for example
// a reader. The output can be passed down the pipeline to other filters,
// for example, a writer. An update call on any downstream filter will
// trigger the execution of the median filter.
//
// \index{itk::BinaryMedianImageFilter!SetInput()}
// \index{itk::BinaryMedianImageFilter!GetOutput()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetInput( reader->GetOutput() );
writer->SetInput( filter->GetOutput() );
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps}
// \includegraphics[width=0.44\textwidth]{BinaryMedianImageFilterOutput.eps}
// \itkcaption[Effect of the BinaryMedian filter.]{Effect of the
// BinaryMedianImageFilter on a slice from a MRI proton density brain image
// that has been thresholded in order to produce a binary image.}
// \label{fig:BinaryMedianImageFilterOutput}
// \end{figure}
//
// Figure \ref{fig:BinaryMedianImageFilterOutput} illustrates the effect of
// the BinaryMedianImageFilter filter on a slice of MRI brain image using a
// neighborhood radius of \(2,2\), which corresponds to a $ 5 \times 5 $
// classical neighborhood. The filtered image demonstrates the capability
// of this filter for reducing noise both in the background and foregrund of
// the image, as well as smoothing the contours of the regions.
//
// Software Guide : EndLatex
return 0;
}
<commit_msg>ENH: Command line argument tags for automatic generation of figures for Software Guide<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: BinaryMedianImageFilter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Insight Software Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// Software Guide : BeginCommandLineArgs
// INPUTS: {BrainProtonDensitySlice.png}
// OUTPUTS: {BinaryMedianImageFilterOutput.png}
// 2
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// The \doxygen{BinaryMedianImageFilter} is commonly used as a robust approach
// for noise reduction. BinaryMedianImageFilter computes the value of each
// output pixel as the statistical median of the neighborhood of values around
// the corresponding input pixel. When the input images are binary, the
// implementation can be optimized by simply counting the number of pixels
// ON/OFF around the current pixel.
//
// This filter will work on images of any dimension thanks to the internal use
// of \doxygen{NeighborhoodIterator} and \doxygen{NeighborhoodOperator}. The
// size of the neighborhood over which the median is computed can be set by
// the user.
//
// \index{itk::BinaryMedianImageFilter}
//
// Software Guide : EndLatex
#include "itkImage.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
// Software Guide : BeginLatex
//
// The header file corresponding to this filter should be included first.
//
// \index{itk::BinaryMedianImageFilter!header}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkBinaryMedianImageFilter.h"
// Software Guide : EndCodeSnippet
int main( int argc, char * argv[] )
{
if( argc < 4 )
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " inputImageFile outputImageFile radiusX radiusY" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// Then the pixel and image types of the input and output must be defined.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef unsigned char InputPixelType;
typedef unsigned char OutputPixelType;
typedef itk::Image< InputPixelType, 2 > InputImageType;
typedef itk::Image< OutputPixelType, 2 > OutputImageType;
// Software Guide : EndCodeSnippet
typedef itk::ImageFileReader< InputImageType > ReaderType;
typedef itk::ImageFileWriter< OutputImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
WriterType::Pointer writer = WriterType::New();
reader->SetFileName( argv[1] );
writer->SetFileName( argv[2] );
// Software Guide : BeginLatex
//
// Using the image types, it is now possible to define the filter type
// and create the filter object.
//
// \index{itk::BinaryMedianImageFilter!instantiation}
// \index{itk::BinaryMedianImageFilter!New()}
// \index{itk::BinaryMedianImageFilter!Pointer}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef itk::BinaryMedianImageFilter<
InputImageType, OutputImageType > FilterType;
FilterType::Pointer filter = FilterType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The size of the neighborhood is defined along every dimension by
// passing a \code{SizeType} object with the corresponding values. The
// value on each dimension is used as the semi-size of a rectangular
// box. For example, in $2D$ a size of \(1,2\) will result in a $3 \times
// 5$ neighborhood.
//
// \index{itk::BinaryMedianImageFilter!Radius}
// \index{itk::BinaryMedianImageFilter!Neighborhood}
//
// Software Guide : EndLatex
const unsigned int radiusX = atoi( argv[3] );
const unsigned int radiusY = atoi( argv[4] );
// Software Guide : BeginCodeSnippet
InputImageType::SizeType indexRadius;
indexRadius[0] = radiusX; // radius along x
indexRadius[1] = radiusY; // radius along y
filter->SetRadius( indexRadius );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The input to the filter can be taken from any other filter, for example
// a reader. The output can be passed down the pipeline to other filters,
// for example, a writer. An update call on any downstream filter will
// trigger the execution of the median filter.
//
// \index{itk::BinaryMedianImageFilter!SetInput()}
// \index{itk::BinaryMedianImageFilter!GetOutput()}
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
filter->SetInput( reader->GetOutput() );
writer->SetInput( filter->GetOutput() );
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// \begin{figure}
// \center
// \includegraphics[width=0.44\textwidth]{BrainProtonDensitySlice.eps}
// \includegraphics[width=0.44\textwidth]{BinaryMedianImageFilterOutput.eps}
// \itkcaption[Effect of the BinaryMedian filter.]{Effect of the
// BinaryMedianImageFilter on a slice from a MRI proton density brain image
// that has been thresholded in order to produce a binary image.}
// \label{fig:BinaryMedianImageFilterOutput}
// \end{figure}
//
// Figure \ref{fig:BinaryMedianImageFilterOutput} illustrates the effect of
// the BinaryMedianImageFilter filter on a slice of MRI brain image using a
// neighborhood radius of \(2,2\), which corresponds to a $ 5 \times 5 $
// classical neighborhood. The filtered image demonstrates the capability
// of this filter for reducing noise both in the background and foregrund of
// the image, as well as smoothing the contours of the regions.
//
// Software Guide : EndLatex
return 0;
}
<|endoftext|> |
<commit_before>#include "FAST/Tests/catch.hpp"
#include "TubeSegmentationAndCenterlineExtraction.hpp"
#include "FAST/Importers/ImageFileImporter.hpp"
#include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
#include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
#include "FAST/Algorithms/ImageCropper/ImageCropper.hpp"
namespace fast {
/*
TEST_CASE("TSF", "[tsf]") {
ImageFileImporter::pointer importer = ImageFileImporter::New();
importer->setFilename("/home/smistad/Dropbox/Programmering/Tube-Segmentation-Framework/tests/data/synthetic/dataset_1/noisy.mhd");
TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
tubeExtraction->setInputConnection(importer->getOutputPort());
tubeExtraction->extractBrightTubes();
tubeExtraction->setMinimumRadius(0.5);
tubeExtraction->setMaximumRadius(8);
tubeExtraction->setSensitivity(0.99);
SliceRenderer::pointer renderer = SliceRenderer::New();
renderer->setInputConnection(tubeExtraction->getTDFOutputPort());
LineRenderer::pointer lineRenderer = LineRenderer::New();
lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
lineRenderer->setDefaultDrawOnTop(true);
SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());
MeshRenderer::pointer meshRenderer = MeshRenderer::New();
meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->addRenderer(meshRenderer);
window->addRenderer(lineRenderer);
window->start();
}
*/
TEST_CASE("TSF Airway", "[tsf][airway][visual]") {
//Report::setReportMethod(Report::COUT);
ImageFileImporter::pointer importer = ImageFileImporter::New();
importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");
ImageCropper::pointer cropper = ImageCropper::New();
cropper->setOffset(Vector3ui(56, 119, 155));
cropper->setSize(Vector3ui(400, 232, 509));
cropper->setInputConnection(importer->getOutputPort());
TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
tubeExtraction->setInputConnection(cropper->getOutputPort());
tubeExtraction->extractDarkTubes();
tubeExtraction->setMinimumIntensity(-1024);
tubeExtraction->setMaximumIntensity(100);
tubeExtraction->setMinimumRadius(0.5);
tubeExtraction->setMaximumRadius(50);
tubeExtraction->setSensitivity(0.8);
SliceRenderer::pointer renderer = SliceRenderer::New();
renderer->setInputConnection(importer->getOutputPort());
LineRenderer::pointer lineRenderer = LineRenderer::New();
lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
lineRenderer->setDefaultDrawOnTop(true);
SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());
MeshRenderer::pointer meshRenderer = MeshRenderer::New();
meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->addRenderer(meshRenderer);
window->addRenderer(lineRenderer);
window->start();
}
}
<commit_msg>added timeout to test<commit_after>#include "FAST/Tests/catch.hpp"
#include "TubeSegmentationAndCenterlineExtraction.hpp"
#include "FAST/Importers/ImageFileImporter.hpp"
#include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
#include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
#include "FAST/Algorithms/ImageCropper/ImageCropper.hpp"
namespace fast {
/*
TEST_CASE("TSF", "[tsf]") {
ImageFileImporter::pointer importer = ImageFileImporter::New();
importer->setFilename("/home/smistad/Dropbox/Programmering/Tube-Segmentation-Framework/tests/data/synthetic/dataset_1/noisy.mhd");
TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
tubeExtraction->setInputConnection(importer->getOutputPort());
tubeExtraction->extractBrightTubes();
tubeExtraction->setMinimumRadius(0.5);
tubeExtraction->setMaximumRadius(8);
tubeExtraction->setSensitivity(0.99);
SliceRenderer::pointer renderer = SliceRenderer::New();
renderer->setInputConnection(tubeExtraction->getTDFOutputPort());
LineRenderer::pointer lineRenderer = LineRenderer::New();
lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
lineRenderer->setDefaultDrawOnTop(true);
SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());
MeshRenderer::pointer meshRenderer = MeshRenderer::New();
meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->addRenderer(meshRenderer);
window->addRenderer(lineRenderer);
window->start();
}
*/
TEST_CASE("TSF Airway", "[tsf][airway][visual]") {
//Report::setReportMethod(Report::COUT);
ImageFileImporter::pointer importer = ImageFileImporter::New();
importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");
ImageCropper::pointer cropper = ImageCropper::New();
cropper->setOffset(Vector3ui(56, 119, 155));
cropper->setSize(Vector3ui(400, 232, 509));
cropper->setInputConnection(importer->getOutputPort());
TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
tubeExtraction->setInputConnection(cropper->getOutputPort());
tubeExtraction->extractDarkTubes();
tubeExtraction->setMinimumIntensity(-1024);
tubeExtraction->setMaximumIntensity(100);
tubeExtraction->setMinimumRadius(0.5);
tubeExtraction->setMaximumRadius(50);
tubeExtraction->setSensitivity(0.8);
SliceRenderer::pointer renderer = SliceRenderer::New();
renderer->setInputConnection(importer->getOutputPort());
LineRenderer::pointer lineRenderer = LineRenderer::New();
lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
lineRenderer->setDefaultDrawOnTop(true);
SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());
MeshRenderer::pointer meshRenderer = MeshRenderer::New();
meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());
SimpleWindow::pointer window = SimpleWindow::New();
window->addRenderer(renderer);
window->addRenderer(meshRenderer);
window->addRenderer(lineRenderer);
window->setTimeout(3*1000);
window->start();
}
}
<|endoftext|> |
<commit_before>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#include <QtSingleApplication>
int main(int argc, char *argv[])
{
QtSingleApplication app(argc, argv);
if (app.isRunning()) {
return 0;
}
QQmlApplicationEngine engine;
app.setWindowIcon(QIcon("resources/icons/ykman.png"));
QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
putenv(pythonNoBytecode.toUtf8().data());
QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
putenv(frameworks.toUtf8().data());
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
return app.exec();
}
<commit_msg>Raise window if new instance is started<commit_after>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <stdlib.h>
#include <QtGlobal>
#include <QtWidgets>
#include <QtSingleApplication>
int main(int argc, char *argv[])
{
// Only allow a single instance running.
QtSingleApplication app(argc, argv);
if (app.sendMessage("")) {
return 0;
}
QQmlApplicationEngine engine;
app.setWindowIcon(QIcon("resources/icons/ykman.png"));
QString pythonNoBytecode = "PYTHONDONTWRITEBYTECODE=1";
putenv(pythonNoBytecode.toUtf8().data());
QString frameworks = "DYLD_LIBRARY_PATH=" + app.applicationDirPath() + "/../Frameworks";
putenv(frameworks.toUtf8().data());
engine.load(QUrl(QLatin1String("qrc:/main.qml")));
// Raise the root window on a message from new instance.
for (auto object : engine.rootObjects()) {
if (QWindow *window = qobject_cast<QWindow*>(object)) {
QObject::connect(&app, &QtSingleApplication::messageReceived, [window]() {
window->raise();
});
}
}
return app.exec();
}
<|endoftext|> |
<commit_before>#include <GL/glew.h>
#include "SofaGL.h"
#include "VisualPickVisitor.h"
namespace sofa {
namespace simplegui {
template <typename T> inline T sqr(const T& t){ return t*t; }
SofaGL::SofaGL(SofaScene *s) :
_sofaScene(s)
{
if(!_sofaScene)
{
std::cerr << "Error: you are trying to create a SofaGL object with a null SofaScene" << std::endl;
return;
}
glewInit();
_vparams = sofa::core::visual::VisualParams::defaultInstance();
_vparams->drawTool() = &_drawToolGL;
_vparams->setSupported(sofa::core::visual::API_OpenGL);
_isPicking = false;
sofa::simulation::getSimulation()->initTextures(_sofaScene->groot().get());
}
void SofaGL::draw()
{
glGetIntegerv (GL_VIEWPORT, _viewport);
glGetDoublev (GL_MODELVIEW_MATRIX, _mvmatrix);
glGetDoublev (GL_PROJECTION_MATRIX, _projmatrix);
if(_vparams)
{
_vparams->viewport() = sofa::helper::fixed_array<int, 4>(_viewport[0], _viewport[1], _viewport[2], _viewport[3]);
_vparams->sceneBBox() = _sofaScene->groot()->f_bbox.getValue();
_vparams->setProjectionMatrix(_projmatrix);
_vparams->setModelViewMatrix(_mvmatrix);
}
sofa::simulation::getSimulation()->updateVisual(_sofaScene->groot().get()); // needed to update normals and VBOs ! (i think it should be better if updateVisual() was called from draw(), why it is not already the case ?)
if( _isPicking ){
// start picking
glSelectBuffer(BUFSIZE,selectBuf);
glRenderMode(GL_SELECT);
glInitNames();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix(pickX,_viewport[3]-pickY,5,5,_viewport);
glMultMatrixd(_projmatrix);
glMatrixMode(GL_MODELVIEW);
// draw
_vparams->pass() = sofa::core::visual::VisualParams::Std;
VisualPickVisitor pick ( _vparams );
pick.setTags(_sofaScene->groot()->getTags());
_sofaScene->groot()->execute ( &pick );
// stop picking
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glFlush();
hits = glRenderMode(GL_RENDER);
if (hits != 0)
{
GLuint* buffer = selectBuf;
// process the hits
GLint i, j, numberOfNames;
GLuint names, *ptr, minZ,*ptrNames;
ptr = (GLuint *) buffer;
minZ = 0xffffffff;
for (i = 0; i < hits; i++) {
names = *ptr;
ptr++;
if (*ptr < minZ) {
numberOfNames = names;
minZ = *ptr;
ptrNames = ptr+2;
}
ptr += names+2;
}
if (numberOfNames > 0) {
cerr << "You picked object ";
ptr = ptrNames;
for (j = 0; j < numberOfNames; j++,ptr++) {
cerr<< pick.names[*ptr] << " ";
}
}
else
cerr<<"You didn't click a snowman!";
cerr<<endl;
}
else cerr<<"no hits !" << endl;
_isPicking = false;
}
sofa::simulation::getSimulation()->draw(_vparams, _sofaScene->groot().get());
}
void SofaGL::getPickDirection( GLdouble* dx, GLdouble* dy, GLdouble* dz, int x, int y )
{
// Intersection of the ray with the near and far planes
GLint realy = _viewport[3] - (GLint) y - 1; // convert coordinates from image space (y downward) to window space (y upward)
GLdouble wx, wy, wz; /* returned world x, y, z coords */
gluUnProject ((GLdouble) x, (GLdouble) realy, 0.0, _mvmatrix, _projmatrix, _viewport, &wx, &wy, &wz); // z=0: near plane
//cout<<"World coords at z=0.0 are ("<<wx<<","<<wy<<","<<wz<<")"<<endl;
GLdouble wx1, wy1, wz1;
gluUnProject ((GLdouble) x, (GLdouble) realy, 1.0, _mvmatrix, _projmatrix, _viewport, &wx1, &wy1, &wz1); // z=1: far plane
GLdouble nrm = sqrt( sqr(wx1-wx) + sqr(wy1-wy) + sqr(wz1-wz) );
*dx = (wx1-wx)/nrm;
*dy = (wy1-wy)/nrm;
*dz = (wz1-wz)/nrm;
}
void SofaGL::glPick(int x, int y )
{
pickX = x; pickY = y;
_isPicking = true;
}
PickedPoint SofaGL::pick(GLdouble ox, GLdouble oy, GLdouble oz, int x, int y )
{
Vec3 origin(ox,oy,oz), direction;
getPickDirection(&direction[0],&direction[1],&direction[2],x,y);
double distance = 10.5, distanceGrowth = 0.1; // cone around the ray ????
// cout<< "SofaGL::rayPick from origin " << origin << ", in direction " << direction << endl;
sofa::simulation::MechanicalPickParticlesVisitor picker(sofa::core::ExecParams::defaultInstance(), origin, direction, distance, distanceGrowth );
picker.execute( _sofaScene->groot()->getContext() );
PickedPoint pickedPoint;
if (!picker.particles.empty())
{
sofa::core::behavior::BaseMechanicalState *mstate = picker.particles.begin()->second.first;
unsigned index = picker.particles.begin()->second.second;
pickedPoint.state = mstate;
pickedPoint.index = index;
pickedPoint.point = Vec3(mstate->getPX(index), mstate->getPY(index), mstate->getPZ(index));
}
return pickedPoint;
}
Interactor* SofaGL::getInteractor( const PickedPoint& glpicked )
{
cout << "SofaGL::getInteractor, looking for " << glpicked << endl;
for( Picked_to_Interactor::iterator i=_picked_to_interactor.begin(); i!=_picked_to_interactor.end(); i++ )
{
cout << "SofaGL::getInteractor, map contains " << (*i).first << endl;
}
if( _picked_to_interactor.find(glpicked)!=_picked_to_interactor.end() ) // there is already an interactor on this particle
{
return _picked_to_interactor[glpicked];
}
else { // new interactor
return NULL;
}
}
Interactor* SofaGL::pickInteractor( GLdouble ox, GLdouble oy, GLdouble oz, int x, int y )
{
Vec3 origin(ox,oy,oz), direction;
getPickDirection(&direction[0],&direction[1],&direction[2],x,y);
double distance = 10.5, distanceGrowth = 0.1; // cone around the ray ????
// cout<< "SofaScene::rayPick from origin " << origin << ", in direction " << direction << endl;
sofa::simulation::MechanicalPickParticlesVisitor picker(sofa::core::ExecParams::defaultInstance(), origin, direction, distance, distanceGrowth, Tag("!NoPicking") );
picker.execute(_sofaScene->groot()->getContext());
if (!picker.particles.empty())
{
PickedPoint pickedPoint(picker.particles.begin()->second.first, picker.particles.begin()->second.second);
if( _picked_to_interactor.find(pickedPoint)!=_picked_to_interactor.end() )
return _picked_to_interactor[pickedPoint];
}
return NULL;
}
void SofaGL::attach( Interactor* interactor )
{
interactor->attach( _sofaScene );
_picked_to_interactor[interactor->getPickedPoint()] = interactor;
// cout<<"SofaGL::attach "<< endl; _sofaScene->printGraph();
}
void SofaGL::move( Interactor* interactor, int x, int y)
{
if( !interactor )
return;
// get the distance to the current point
Vec3 current = interactor->getPoint();
GLdouble wcur[3]; // window coordinates of the current point
gluProject(current[0],current[1],current[2],_mvmatrix,_projmatrix,_viewport,wcur,wcur+1,wcur+2);
// cout << "current point = " << current << endl;
// cout<<"move anchor, distance = " << wcur[2] << endl;
// compute and set the position of the new point
GLdouble p[3];
gluUnProject ( x, _viewport[3]-y-1, wcur[2], _mvmatrix, _projmatrix, _viewport, &p[0], &p[1], &p[2]); // new position of the picked point
// cout<<"x="<< x <<", y="<< y <<", X="<<p[0]<<", Y="<<p[1]<<", Z="<<p[2]<<endl;
interactor->setPoint(Vec3(p[0], p[1], p[2]));
}
void SofaGL::detach( Interactor* drag)
{
if( !drag )
return;
// remove it from the map
Picked_to_Interactor::iterator i=_picked_to_interactor.begin();
while( i!=_picked_to_interactor.end() && (*i).second != drag )
i++;
if( i!=_picked_to_interactor.end() ){
// cout << "Deleted interactor at " << (*i).first << endl;
_picked_to_interactor.erase(i);
// cout << "new count of interactors: " << picked_to_interactor.size() << endl;
}
else assert( false && "Active interactor not found in the map" );
drag->detach();
// cout<<"SofaGL::detach "<< endl; _sofaScene->printGraph();
}
void SofaGL::getSceneBBox( float* xmin, float* ymin, float* zmin, float* xmax, float* ymax, float* zmax )
{
SReal xm, xM, ym, yM, zm, zM;
_sofaScene->getBoundingBox(&xm,&xM,&ym,&yM,&zm,&zM);
// cerr << "SofaGL::getSceneBBox, xm=" << xm <<", xM=" << xM << endl;
*xmin=xm, *xmax=xM, *ymin=ym, *ymax=yM, *zmin=zm, *zmax=zM;
}
void SofaGL::viewAll( SReal* xcam, SReal* ycam, SReal* zcam, SReal* xcen, SReal* ycen, SReal* zcen, SReal a, SReal* nearPlane, SReal* farPlane)
{
// scene center and radius
SReal xmin, xmax, ymin, ymax, zmin, zmax;
_sofaScene->getBoundingBox(&xmin,&xmax,&ymin,&ymax,&zmin,&zmax);
cout<<"SofaGL::viewAll, bounding box = ("<< xmin <<" "<<ymin<<" "<<zmin<<"),("<<xmax<<" "<<ymax<<" "<<zmax<<")"<<endl;
*xcen = (xmin+xmax)*0.5;
*ycen = (ymin+ymax)*0.5;
*zcen = (zmin+zmax)*0.5;
SReal radius = sqrt( sqr(xmin-xmax) + sqr(ymin-ymax) + sqr(zmin-zmax) );
// Desired distance: distance * tan(a) = radius
SReal distance = 2 * radius / tan(a);
// SReal ratio = ((SReal) _viewport[3] - _viewport[1])/(_viewport[2] - _viewport[0]);
// distance *= ratio;
cout<<"SofaGL::viewAll, angle = " << a << ", tan = " << tan(a) << ", distance = " << distance << endl;
cout<<"SofaGL::viewAll, xmin xmax ymin ymax zmin zmax = " << xmin << " " << xmax <<" "<<ymin<<" "<<ymax<<" "<<zmin<<" "<<zmax<< endl;
// move the camera along the current camera-center line, at the right distance
// cam = cen + distance * (cam-cen)/|cam-cen|
SReal curdist = sqrt( sqr(*xcam-*xcen)+sqr(*ycam-*ycen)+sqr(*zcam-*zcen) );
*xcam = *xcen + distance * (*xcam-*xcen) / curdist;
*ycam = *ycen + distance * (*ycam-*ycen) / curdist;
*zcam = *zcen + distance * (*zcam-*zcen) / curdist;
// update the depth bounds
*nearPlane = distance - radius*1.5;
*farPlane = distance + radius*1.5;
}
}//newgui
}//sofa
<commit_msg>CHANGE: a comment<commit_after>#include <GL/glew.h>
#include "SofaGL.h"
#include "VisualPickVisitor.h"
namespace sofa {
namespace simplegui {
template <typename T> inline T sqr(const T& t){ return t*t; }
SofaGL::SofaGL(SofaScene *s) :
_sofaScene(s)
{
if(!_sofaScene)
{
std::cerr << "Error: you are trying to create a SofaGL object with a null SofaScene" << std::endl;
return;
}
glewInit();
_vparams = sofa::core::visual::VisualParams::defaultInstance();
_vparams->drawTool() = &_drawToolGL;
_vparams->setSupported(sofa::core::visual::API_OpenGL);
_isPicking = false;
sofa::simulation::getSimulation()->initTextures(_sofaScene->groot().get());
}
void SofaGL::draw()
{
glGetIntegerv (GL_VIEWPORT, _viewport);
glGetDoublev (GL_MODELVIEW_MATRIX, _mvmatrix);
glGetDoublev (GL_PROJECTION_MATRIX, _projmatrix);
if(_vparams)
{
_vparams->viewport() = sofa::helper::fixed_array<int, 4>(_viewport[0], _viewport[1], _viewport[2], _viewport[3]);
_vparams->sceneBBox() = _sofaScene->groot()->f_bbox.getValue();
_vparams->setProjectionMatrix(_projmatrix);
_vparams->setModelViewMatrix(_mvmatrix);
}
sofa::simulation::getSimulation()->updateVisual(_sofaScene->groot().get()); // needed to update normals and VBOs !
if( _isPicking ){
// start picking
glSelectBuffer(BUFSIZE,selectBuf);
glRenderMode(GL_SELECT);
glInitNames();
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
gluPickMatrix(pickX,_viewport[3]-pickY,5,5,_viewport);
glMultMatrixd(_projmatrix);
glMatrixMode(GL_MODELVIEW);
// draw
_vparams->pass() = sofa::core::visual::VisualParams::Std;
VisualPickVisitor pick ( _vparams );
pick.setTags(_sofaScene->groot()->getTags());
_sofaScene->groot()->execute ( &pick );
// stop picking
glMatrixMode(GL_PROJECTION);
glPopMatrix();
glMatrixMode(GL_MODELVIEW);
glFlush();
hits = glRenderMode(GL_RENDER);
if (hits != 0)
{
GLuint* buffer = selectBuf;
// process the hits
GLint i, j, numberOfNames;
GLuint names, *ptr, minZ,*ptrNames;
ptr = (GLuint *) buffer;
minZ = 0xffffffff;
for (i = 0; i < hits; i++) {
names = *ptr;
ptr++;
if (*ptr < minZ) {
numberOfNames = names;
minZ = *ptr;
ptrNames = ptr+2;
}
ptr += names+2;
}
if (numberOfNames > 0) {
cerr << "You picked object ";
ptr = ptrNames;
for (j = 0; j < numberOfNames; j++,ptr++) {
cerr<< pick.names[*ptr] << " ";
}
}
else
cerr<<"You didn't click a snowman!";
cerr<<endl;
}
else cerr<<"no hits !" << endl;
_isPicking = false;
}
sofa::simulation::getSimulation()->draw(_vparams, _sofaScene->groot().get());
}
void SofaGL::getPickDirection( GLdouble* dx, GLdouble* dy, GLdouble* dz, int x, int y )
{
// Intersection of the ray with the near and far planes
GLint realy = _viewport[3] - (GLint) y - 1; // convert coordinates from image space (y downward) to window space (y upward)
GLdouble wx, wy, wz; /* returned world x, y, z coords */
gluUnProject ((GLdouble) x, (GLdouble) realy, 0.0, _mvmatrix, _projmatrix, _viewport, &wx, &wy, &wz); // z=0: near plane
//cout<<"World coords at z=0.0 are ("<<wx<<","<<wy<<","<<wz<<")"<<endl;
GLdouble wx1, wy1, wz1;
gluUnProject ((GLdouble) x, (GLdouble) realy, 1.0, _mvmatrix, _projmatrix, _viewport, &wx1, &wy1, &wz1); // z=1: far plane
GLdouble nrm = sqrt( sqr(wx1-wx) + sqr(wy1-wy) + sqr(wz1-wz) );
*dx = (wx1-wx)/nrm;
*dy = (wy1-wy)/nrm;
*dz = (wz1-wz)/nrm;
}
void SofaGL::glPick(int x, int y )
{
pickX = x; pickY = y;
_isPicking = true;
}
PickedPoint SofaGL::pick(GLdouble ox, GLdouble oy, GLdouble oz, int x, int y )
{
Vec3 origin(ox,oy,oz), direction;
getPickDirection(&direction[0],&direction[1],&direction[2],x,y);
double distance = 10.5, distanceGrowth = 0.1; // cone around the ray ????
// cout<< "SofaGL::rayPick from origin " << origin << ", in direction " << direction << endl;
sofa::simulation::MechanicalPickParticlesVisitor picker(sofa::core::ExecParams::defaultInstance(), origin, direction, distance, distanceGrowth );
picker.execute( _sofaScene->groot()->getContext() );
PickedPoint pickedPoint;
if (!picker.particles.empty())
{
sofa::core::behavior::BaseMechanicalState *mstate = picker.particles.begin()->second.first;
unsigned index = picker.particles.begin()->second.second;
pickedPoint.state = mstate;
pickedPoint.index = index;
pickedPoint.point = Vec3(mstate->getPX(index), mstate->getPY(index), mstate->getPZ(index));
}
return pickedPoint;
}
Interactor* SofaGL::getInteractor( const PickedPoint& glpicked )
{
cout << "SofaGL::getInteractor, looking for " << glpicked << endl;
for( Picked_to_Interactor::iterator i=_picked_to_interactor.begin(); i!=_picked_to_interactor.end(); i++ )
{
cout << "SofaGL::getInteractor, map contains " << (*i).first << endl;
}
if( _picked_to_interactor.find(glpicked)!=_picked_to_interactor.end() ) // there is already an interactor on this particle
{
return _picked_to_interactor[glpicked];
}
else { // new interactor
return NULL;
}
}
Interactor* SofaGL::pickInteractor( GLdouble ox, GLdouble oy, GLdouble oz, int x, int y )
{
Vec3 origin(ox,oy,oz), direction;
getPickDirection(&direction[0],&direction[1],&direction[2],x,y);
double distance = 10.5, distanceGrowth = 0.1; // cone around the ray ????
// cout<< "SofaScene::rayPick from origin " << origin << ", in direction " << direction << endl;
sofa::simulation::MechanicalPickParticlesVisitor picker(sofa::core::ExecParams::defaultInstance(), origin, direction, distance, distanceGrowth, Tag("!NoPicking") );
picker.execute(_sofaScene->groot()->getContext());
if (!picker.particles.empty())
{
PickedPoint pickedPoint(picker.particles.begin()->second.first, picker.particles.begin()->second.second);
if( _picked_to_interactor.find(pickedPoint)!=_picked_to_interactor.end() )
return _picked_to_interactor[pickedPoint];
}
return NULL;
}
void SofaGL::attach( Interactor* interactor )
{
interactor->attach( _sofaScene );
_picked_to_interactor[interactor->getPickedPoint()] = interactor;
// cout<<"SofaGL::attach "<< endl; _sofaScene->printGraph();
}
void SofaGL::move( Interactor* interactor, int x, int y)
{
if( !interactor )
return;
// get the distance to the current point
Vec3 current = interactor->getPoint();
GLdouble wcur[3]; // window coordinates of the current point
gluProject(current[0],current[1],current[2],_mvmatrix,_projmatrix,_viewport,wcur,wcur+1,wcur+2);
// cout << "current point = " << current << endl;
// cout<<"move anchor, distance = " << wcur[2] << endl;
// compute and set the position of the new point
GLdouble p[3];
gluUnProject ( x, _viewport[3]-y-1, wcur[2], _mvmatrix, _projmatrix, _viewport, &p[0], &p[1], &p[2]); // new position of the picked point
// cout<<"x="<< x <<", y="<< y <<", X="<<p[0]<<", Y="<<p[1]<<", Z="<<p[2]<<endl;
interactor->setPoint(Vec3(p[0], p[1], p[2]));
}
void SofaGL::detach( Interactor* drag)
{
if( !drag )
return;
// remove it from the map
Picked_to_Interactor::iterator i=_picked_to_interactor.begin();
while( i!=_picked_to_interactor.end() && (*i).second != drag )
i++;
if( i!=_picked_to_interactor.end() ){
// cout << "Deleted interactor at " << (*i).first << endl;
_picked_to_interactor.erase(i);
// cout << "new count of interactors: " << picked_to_interactor.size() << endl;
}
else assert( false && "Active interactor not found in the map" );
drag->detach();
// cout<<"SofaGL::detach "<< endl; _sofaScene->printGraph();
}
void SofaGL::getSceneBBox( float* xmin, float* ymin, float* zmin, float* xmax, float* ymax, float* zmax )
{
SReal xm, xM, ym, yM, zm, zM;
_sofaScene->getBoundingBox(&xm,&xM,&ym,&yM,&zm,&zM);
// cerr << "SofaGL::getSceneBBox, xm=" << xm <<", xM=" << xM << endl;
*xmin=xm, *xmax=xM, *ymin=ym, *ymax=yM, *zmin=zm, *zmax=zM;
}
void SofaGL::viewAll( SReal* xcam, SReal* ycam, SReal* zcam, SReal* xcen, SReal* ycen, SReal* zcen, SReal a, SReal* nearPlane, SReal* farPlane)
{
// scene center and radius
SReal xmin, xmax, ymin, ymax, zmin, zmax;
_sofaScene->getBoundingBox(&xmin,&xmax,&ymin,&ymax,&zmin,&zmax);
cout<<"SofaGL::viewAll, bounding box = ("<< xmin <<" "<<ymin<<" "<<zmin<<"),("<<xmax<<" "<<ymax<<" "<<zmax<<")"<<endl;
*xcen = (xmin+xmax)*0.5;
*ycen = (ymin+ymax)*0.5;
*zcen = (zmin+zmax)*0.5;
SReal radius = sqrt( sqr(xmin-xmax) + sqr(ymin-ymax) + sqr(zmin-zmax) );
// Desired distance: distance * tan(a) = radius
SReal distance = 2 * radius / tan(a);
// SReal ratio = ((SReal) _viewport[3] - _viewport[1])/(_viewport[2] - _viewport[0]);
// distance *= ratio;
cout<<"SofaGL::viewAll, angle = " << a << ", tan = " << tan(a) << ", distance = " << distance << endl;
cout<<"SofaGL::viewAll, xmin xmax ymin ymax zmin zmax = " << xmin << " " << xmax <<" "<<ymin<<" "<<ymax<<" "<<zmin<<" "<<zmax<< endl;
// move the camera along the current camera-center line, at the right distance
// cam = cen + distance * (cam-cen)/|cam-cen|
SReal curdist = sqrt( sqr(*xcam-*xcen)+sqr(*ycam-*ycen)+sqr(*zcam-*zcen) );
*xcam = *xcen + distance * (*xcam-*xcen) / curdist;
*ycam = *ycen + distance * (*ycam-*ycen) / curdist;
*zcam = *zcen + distance * (*zcam-*zcen) / curdist;
// update the depth bounds
*nearPlane = distance - radius*1.5;
*farPlane = distance + radius*1.5;
}
}//newgui
}//sofa
<|endoftext|> |
<commit_before>#include "bdb_common.hpp"
#include DB_CXX_HEADER
#include <bitcoin/utility/assert.hpp>
#include <bitcoin/utility/logger.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/address.hpp>
namespace libbitcoin {
bdb_common::bdb_common(DbEnv* env, Db* db_blocks, Db* db_blocks_hash,
Db* db_txs, Db* db_spends, Db* db_address)
: env_(env), db_blocks_(db_blocks), db_blocks_hash_(db_blocks_hash),
db_txs_(db_txs), db_spends_(db_spends), db_address_(db_address)
{
}
uint32_t bdb_common::find_last_block_depth(txn_guard_ptr txn)
{
Dbc* cursor;
db_blocks_->cursor(txn->get(), &cursor, 0);
BITCOIN_ASSERT(cursor != nullptr);
writable_data_type key, data;
if (cursor->get(key.get(), data.get(), DB_LAST) == DB_NOTFOUND)
return std::numeric_limits<uint32_t>::max();
BITCOIN_ASSERT(key.get()->get_size() == 4);
uint32_t last_block_depth = cast_chunk<uint32_t>(key.data());
cursor->close();
return last_block_depth;
}
bool bdb_common::fetch_spend(txn_guard_ptr txn,
const message::output_point& spent_output,
message::input_point& input_spend)
{
readable_data_type search_spend;
search_spend.set(create_spent_key(spent_output));
writable_data_type raw_spend;
if (db_spends_->get(txn->get(), search_spend.get(),
raw_spend.get(), 0) != 0)
return false;
const data_chunk raw_spend_data = raw_spend.data();
deserializer deserial(raw_spend_data);
input_spend.hash = deserial.read_hash();
input_spend.index = deserial.read_4_bytes();
return true;
}
bool bdb_common::save_block(txn_guard_ptr txn,
uint32_t depth, const message::block& serial_block)
{
protobuf::Block proto_block =
block_header_to_protobuf(depth, serial_block);
for (uint32_t tx_index = 0;
tx_index < serial_block.transactions.size(); ++tx_index)
{
const message::transaction& block_tx =
serial_block.transactions[tx_index];
const hash_digest& tx_hash = hash_transaction(block_tx);
if (!save_transaction(txn, depth, tx_index, tx_hash, block_tx))
{
log_fatal() << "Could not save transaction";
return false;
}
proto_block.add_transactions(
std::string(tx_hash.begin(), tx_hash.end()));
}
std::ostringstream oss;
if (!proto_block.SerializeToOstream(&oss))
{
log_fatal() << "Protobuf serialization failed";
return false;
}
readable_data_type key, value;
key.set(depth);
value.set(oss.str());
if (db_blocks_->put(txn->get(), key.get(), value.get(), 0) != 0)
{
log_fatal() << "bdb put() failed";
return false;
}
return true;
}
bool bdb_common::save_transaction(txn_guard_ptr txn, uint32_t block_depth,
uint32_t tx_index, const hash_digest& tx_hash,
const message::transaction& block_tx)
{
if (dupli_save(txn, tx_hash, block_depth, tx_index))
return true;
// Actually add block
protobuf::Transaction proto_tx = transaction_to_protobuf(block_tx);
proto_tx.set_is_coinbase(is_coinbase(block_tx));
// Add parent block to transaction
protobuf::Transaction_BlockPointer* proto_parent = proto_tx.add_parent();
proto_parent->set_depth(block_depth);
proto_parent->set_index(tx_index);
// Save tx to bdb
std::ostringstream oss;
if (!proto_tx.SerializeToOstream(&oss))
return false;
readable_data_type key, value;
key.set(tx_hash);
value.set(oss.str());
// Checks for duplicates first
if (db_txs_->put(txn->get(), key.get(), value.get(), DB_NOOVERWRITE) != 0)
return false;
if (is_coinbase(block_tx))
return true;
for (uint32_t input_index = 0; input_index < block_tx.inputs.size();
++input_index)
{
const message::transaction_input& input =
block_tx.inputs[input_index];
const message::input_point inpoint{tx_hash, input_index};
if (!mark_spent_outputs(txn, input.previous_output, inpoint))
return false;
}
for (uint32_t output_index = 0; output_index < block_tx.outputs.size();
++output_index)
{
const message::transaction_output& output =
block_tx.outputs[output_index];
if (!add_address(txn, output.output_script, {tx_hash, output_index}))
return false;
}
return true;
}
bool bdb_common::dupli_save(txn_guard_ptr txn, const hash_digest& tx_hash,
uint32_t block_depth, uint32_t tx_index)
{
protobuf::Transaction proto_tx = fetch_proto_transaction(txn, tx_hash);
if (!proto_tx.IsInitialized())
return false;
BITCOIN_ASSERT(block_depth == 91842 || block_depth == 91880);
protobuf::Transaction::BlockPointer* parent = proto_tx.add_parent();
parent->set_depth(block_depth);
parent->set_index(tx_index);
return rewrite_transaction(txn, tx_hash, proto_tx);
}
bool bdb_common::mark_spent_outputs(txn_guard_ptr txn,
const message::output_point& previous_output,
const message::input_point& current_input)
{
readable_data_type spent_key, spend_value;
spent_key.set(create_spent_key(previous_output));
spend_value.set(create_spent_key(current_input));
if (db_spends_->put(txn->get(), spent_key.get(), spend_value.get(),
DB_NOOVERWRITE) != 0)
return false;
return true;
}
bool bdb_common::add_address(txn_guard_ptr txn,
const script& output_script, const message::output_point& outpoint)
{
data_chunk raw_address = create_address_key(output_script);
if (raw_address.empty())
return true;
readable_data_type address_key, output_value;
address_key.set(raw_address);
output_value.set(create_spent_key(outpoint));
if (db_address_->put(txn->get(), address_key.get(),
output_value.get(), 0) != 0)
return false;
return true;
}
bool bdb_common::rewrite_transaction(txn_guard_ptr txn,
const hash_digest& tx_hash, const protobuf::Transaction& replace_proto_tx)
{
// Now rewrite tx
// First delete old
readable_data_type tx_key;
tx_key.set(tx_hash);
if (db_txs_->del(txn->get(), tx_key.get(), 0) != 0)
return false;
// Save tx to bdb
std::ostringstream write_oss;
if (!replace_proto_tx.SerializeToOstream(&write_oss))
return false;
readable_data_type tx_data;
tx_data.set(write_oss.str());
// Checks for duplicates first
if (db_txs_->put(txn->get(), tx_key.get(), tx_data.get(),
DB_NOOVERWRITE) != 0)
{
return false;
}
return true;
}
template<typename Index, typename ProtoType>
bool proto_read(Db* database, txn_guard_ptr txn,
const Index& index, ProtoType& proto_object)
{
readable_data_type key;
key.set(index);
writable_data_type data;
if (database->get(txn->get(), key.get(), data.get(), 0) != 0)
return false;
std::stringstream ss;
data_chunk raw_object(data.data());
std::copy(raw_object.begin(), raw_object.end(),
std::ostream_iterator<byte>(ss));
proto_object.ParseFromIstream(&ss);
return true;
}
protobuf::Block bdb_common::fetch_proto_block(txn_guard_ptr txn,
uint32_t depth)
{
protobuf::Block proto_block;
if (!proto_read(db_blocks_, txn, depth, proto_block))
return protobuf::Block();
return proto_block;
}
protobuf::Transaction bdb_common::fetch_proto_transaction(
txn_guard_ptr txn, const hash_digest& tx_hash)
{
protobuf::Transaction proto_tx;
if (!proto_read(db_txs_, txn, tx_hash, proto_tx))
return protobuf::Transaction();
return proto_tx;
}
protobuf::Block bdb_common::fetch_proto_block(txn_guard_ptr txn,
const hash_digest& block_hash)
{
protobuf::Block proto_block;
if (!proto_read(db_blocks_hash_, txn, block_hash, proto_block))
return protobuf::Block();
return proto_block;
}
bool bdb_common::reconstruct_block(txn_guard_ptr txn,
const protobuf::Block& proto_block_header,
message::block& result_block)
{
result_block = protobuf_to_block_header(proto_block_header);
for (const std::string& raw_tx_hash: proto_block_header.transactions())
{
protobuf::Transaction proto_tx;
if (!proto_read(db_txs_, txn, raw_tx_hash, proto_tx))
return false;
result_block.transactions.push_back(protobuf_to_transaction(proto_tx));
}
return true;
}
data_chunk create_address_key(const script& output_script)
{
payment_address address;
if (!extract(address, output_script))
return data_chunk();
serializer serial;
serial.write_byte(address.version());
serial.write_short_hash(address.hash());
return serial.data();
}
} // namespace libbitcoin
<commit_msg>bugfix: coinbase output addresses not getting indexed.<commit_after>#include "bdb_common.hpp"
#include DB_CXX_HEADER
#include <bitcoin/utility/assert.hpp>
#include <bitcoin/utility/logger.hpp>
#include <bitcoin/format.hpp>
#include <bitcoin/transaction.hpp>
#include <bitcoin/address.hpp>
namespace libbitcoin {
bdb_common::bdb_common(DbEnv* env, Db* db_blocks, Db* db_blocks_hash,
Db* db_txs, Db* db_spends, Db* db_address)
: env_(env), db_blocks_(db_blocks), db_blocks_hash_(db_blocks_hash),
db_txs_(db_txs), db_spends_(db_spends), db_address_(db_address)
{
}
uint32_t bdb_common::find_last_block_depth(txn_guard_ptr txn)
{
Dbc* cursor;
db_blocks_->cursor(txn->get(), &cursor, 0);
BITCOIN_ASSERT(cursor != nullptr);
writable_data_type key, data;
if (cursor->get(key.get(), data.get(), DB_LAST) == DB_NOTFOUND)
return std::numeric_limits<uint32_t>::max();
BITCOIN_ASSERT(key.get()->get_size() == 4);
uint32_t last_block_depth = cast_chunk<uint32_t>(key.data());
cursor->close();
return last_block_depth;
}
bool bdb_common::fetch_spend(txn_guard_ptr txn,
const message::output_point& spent_output,
message::input_point& input_spend)
{
readable_data_type search_spend;
search_spend.set(create_spent_key(spent_output));
writable_data_type raw_spend;
if (db_spends_->get(txn->get(), search_spend.get(),
raw_spend.get(), 0) != 0)
return false;
const data_chunk raw_spend_data = raw_spend.data();
deserializer deserial(raw_spend_data);
input_spend.hash = deserial.read_hash();
input_spend.index = deserial.read_4_bytes();
return true;
}
bool bdb_common::save_block(txn_guard_ptr txn,
uint32_t depth, const message::block& serial_block)
{
protobuf::Block proto_block =
block_header_to_protobuf(depth, serial_block);
for (uint32_t tx_index = 0;
tx_index < serial_block.transactions.size(); ++tx_index)
{
const message::transaction& block_tx =
serial_block.transactions[tx_index];
const hash_digest& tx_hash = hash_transaction(block_tx);
if (!save_transaction(txn, depth, tx_index, tx_hash, block_tx))
{
log_fatal() << "Could not save transaction";
return false;
}
proto_block.add_transactions(
std::string(tx_hash.begin(), tx_hash.end()));
}
std::ostringstream oss;
if (!proto_block.SerializeToOstream(&oss))
{
log_fatal() << "Protobuf serialization failed";
return false;
}
readable_data_type key, value;
key.set(depth);
value.set(oss.str());
if (db_blocks_->put(txn->get(), key.get(), value.get(), 0) != 0)
{
log_fatal() << "bdb put() failed";
return false;
}
return true;
}
bool bdb_common::save_transaction(txn_guard_ptr txn, uint32_t block_depth,
uint32_t tx_index, const hash_digest& tx_hash,
const message::transaction& block_tx)
{
if (dupli_save(txn, tx_hash, block_depth, tx_index))
return true;
// Actually add block
protobuf::Transaction proto_tx = transaction_to_protobuf(block_tx);
proto_tx.set_is_coinbase(is_coinbase(block_tx));
// Add parent block to transaction
protobuf::Transaction_BlockPointer* proto_parent = proto_tx.add_parent();
proto_parent->set_depth(block_depth);
proto_parent->set_index(tx_index);
// Save tx to bdb
std::ostringstream oss;
if (!proto_tx.SerializeToOstream(&oss))
return false;
readable_data_type key, value;
key.set(tx_hash);
value.set(oss.str());
// Checks for duplicates first
if (db_txs_->put(txn->get(), key.get(), value.get(), DB_NOOVERWRITE) != 0)
return false;
// Coinbase inputs do not spend anything.
if (!is_coinbase(block_tx))
for (uint32_t input_index = 0; input_index < block_tx.inputs.size();
++input_index)
{
const message::transaction_input& input =
block_tx.inputs[input_index];
const message::input_point inpoint{tx_hash, input_index};
if (!mark_spent_outputs(txn, input.previous_output, inpoint))
return false;
}
for (uint32_t output_index = 0; output_index < block_tx.outputs.size();
++output_index)
{
const message::transaction_output& output =
block_tx.outputs[output_index];
if (!add_address(txn, output.output_script, {tx_hash, output_index}))
return false;
}
return true;
}
bool bdb_common::dupli_save(txn_guard_ptr txn, const hash_digest& tx_hash,
uint32_t block_depth, uint32_t tx_index)
{
protobuf::Transaction proto_tx = fetch_proto_transaction(txn, tx_hash);
if (!proto_tx.IsInitialized())
return false;
BITCOIN_ASSERT(block_depth == 91842 || block_depth == 91880);
protobuf::Transaction::BlockPointer* parent = proto_tx.add_parent();
parent->set_depth(block_depth);
parent->set_index(tx_index);
return rewrite_transaction(txn, tx_hash, proto_tx);
}
bool bdb_common::mark_spent_outputs(txn_guard_ptr txn,
const message::output_point& previous_output,
const message::input_point& current_input)
{
readable_data_type spent_key, spend_value;
spent_key.set(create_spent_key(previous_output));
spend_value.set(create_spent_key(current_input));
if (db_spends_->put(txn->get(), spent_key.get(), spend_value.get(),
DB_NOOVERWRITE) != 0)
return false;
return true;
}
bool bdb_common::add_address(txn_guard_ptr txn,
const script& output_script, const message::output_point& outpoint)
{
data_chunk raw_address = create_address_key(output_script);
if (raw_address.empty())
return true;
readable_data_type address_key, output_value;
address_key.set(raw_address);
output_value.set(create_spent_key(outpoint));
if (db_address_->put(txn->get(), address_key.get(),
output_value.get(), 0) != 0)
return false;
return true;
}
bool bdb_common::rewrite_transaction(txn_guard_ptr txn,
const hash_digest& tx_hash, const protobuf::Transaction& replace_proto_tx)
{
// Now rewrite tx
// First delete old
readable_data_type tx_key;
tx_key.set(tx_hash);
if (db_txs_->del(txn->get(), tx_key.get(), 0) != 0)
return false;
// Save tx to bdb
std::ostringstream write_oss;
if (!replace_proto_tx.SerializeToOstream(&write_oss))
return false;
readable_data_type tx_data;
tx_data.set(write_oss.str());
// Checks for duplicates first
if (db_txs_->put(txn->get(), tx_key.get(), tx_data.get(),
DB_NOOVERWRITE) != 0)
{
return false;
}
return true;
}
template<typename Index, typename ProtoType>
bool proto_read(Db* database, txn_guard_ptr txn,
const Index& index, ProtoType& proto_object)
{
readable_data_type key;
key.set(index);
writable_data_type data;
if (database->get(txn->get(), key.get(), data.get(), 0) != 0)
return false;
std::stringstream ss;
data_chunk raw_object(data.data());
std::copy(raw_object.begin(), raw_object.end(),
std::ostream_iterator<byte>(ss));
proto_object.ParseFromIstream(&ss);
return true;
}
protobuf::Block bdb_common::fetch_proto_block(txn_guard_ptr txn,
uint32_t depth)
{
protobuf::Block proto_block;
if (!proto_read(db_blocks_, txn, depth, proto_block))
return protobuf::Block();
return proto_block;
}
protobuf::Transaction bdb_common::fetch_proto_transaction(
txn_guard_ptr txn, const hash_digest& tx_hash)
{
protobuf::Transaction proto_tx;
if (!proto_read(db_txs_, txn, tx_hash, proto_tx))
return protobuf::Transaction();
return proto_tx;
}
protobuf::Block bdb_common::fetch_proto_block(txn_guard_ptr txn,
const hash_digest& block_hash)
{
protobuf::Block proto_block;
if (!proto_read(db_blocks_hash_, txn, block_hash, proto_block))
return protobuf::Block();
return proto_block;
}
bool bdb_common::reconstruct_block(txn_guard_ptr txn,
const protobuf::Block& proto_block_header,
message::block& result_block)
{
result_block = protobuf_to_block_header(proto_block_header);
for (const std::string& raw_tx_hash: proto_block_header.transactions())
{
protobuf::Transaction proto_tx;
if (!proto_read(db_txs_, txn, raw_tx_hash, proto_tx))
return false;
result_block.transactions.push_back(protobuf_to_transaction(proto_tx));
}
return true;
}
data_chunk create_address_key(const script& output_script)
{
payment_address address;
if (!extract(address, output_script))
return data_chunk();
serializer serial;
serial.write_byte(address.version());
serial.write_short_hash(address.hash());
return serial.data();
}
} // namespace libbitcoin
<|endoftext|> |
<commit_before>#define SEQAN_PROFILE
#include <iostream>
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <seqan/system.h>
using namespace seqan;
using namespace std;
const int blockSize = 1 << 12;
const int repeats = 1 << 17;
char block1[blockSize] = "This a test string";
char block2[blockSize];
template <typename TFile>
void testThroughput(const char *fileName)
{
TFile myFile;
typename aRequest<TFile>::Type req1, req2;
if (!open(myFile, fileName, OPEN_WRONLY | OPEN_CREATE)) {
cout << "Could not open for writing" << endl;
return;
}
SEQAN_PROTIMESTART(iotime);
for (unsigned i = 0; i < repeats; ++i)
{
waitFor(req1);
awriteAt(myFile, block1, blockSize, 2*i * blockSize, req1);
waitFor(req2);
awriteAt(myFile, block2, blockSize, (2*i+1) * blockSize, req2);
}
waitFor(req1);
waitFor(req2);
cout << ((repeats*blockSize / (512.0 * 1024.0)) / SEQAN_PROTIMEDIFF(iotime));
cout << " MB/s" << endl;
close(myFile);
}
int main()
{
testThroughput< FILE* >("file_speedF.bin");
testThroughput< File< Sync<> > >("file_speedS.bin");
testThroughput< File< Async<> > >("file_speedA.bin");
return 0;
}
<commit_msg>added: Memory Mapped String<commit_after>#define SEQAN_PROFILE
//#define SEQAN_DEBUG
#include <seqan/sequence.h>
#include <seqan/file.h>
#include <iostream>
using namespace seqan;
using namespace std;
const int blockSize = 1 << 12;
const int repeats = 1 << 17;
CharString block1 = "This a test string";
CharString block2;
template <typename TFile>
void testThroughput(const char *fileName)
{
TFile myFile;
typename aRequest<TFile>::Type req1, req2;
if (!open(myFile, fileName, OPEN_WRONLY | OPEN_CREATE)) {
cout << "Could not open for writing" << endl;
return;
}
SEQAN_PROTIMESTART(iotime);
awriteAt(myFile, toCString(block1), blockSize, 0 * blockSize, req1);
awriteAt(myFile, toCString(block2), blockSize, 1 * blockSize, req2);
for (unsigned i = 1; i < repeats; ++i)
{
waitFor(req1);
awriteAt(myFile, toCString(block1), blockSize, 2*i * blockSize, req1);
waitFor(req2);
awriteAt(myFile, toCString(block2), blockSize, (2*i+1) * blockSize, req2);
}
waitFor(req1);
waitFor(req2);
cout << ((repeats*blockSize / (512.0 * 1024.0)) / SEQAN_PROTIMEDIFF(iotime));
cout << " MB/s" << endl;
close(myFile);
}
template <typename TFile>
void testExtString(const char *fileName)
{
String<char, External<ExternalConfig<TFile> > > myString;
if (!open(myString, fileName, OPEN_WRONLY | OPEN_CREATE)) {
cout << "Could not open for writing" << endl;
return;
}
SEQAN_PROTIMESTART(iotime);
for (unsigned i = 0; i < repeats; ++i)
{
append(myString, block1);
append(myString, block2);
}
cout << ((repeats*blockSize / (512.0 * 1024.0)) / SEQAN_PROTIMEDIFF(iotime));
cout << " MB/s" << endl;
}
template <typename TFile>
void testMMapString(const char *fileName)
{
String<char, MMap<ExternalConfig<TFile> > > myString;
if (!open(myString, fileName, OPEN_RDWR | OPEN_CREATE)) {
cout << "Could not open for writing" << endl;
return;
}
SEQAN_PROTIMESTART(iotime);
for (unsigned i = 0; i < repeats; ++i)
{
append(myString, block1);
append(myString, block2);
}
cout << ((repeats*blockSize / (512.0 * 1024.0)) / SEQAN_PROTIMEDIFF(iotime));
cout << " MB/s" << endl;
}
int main()
{
resize(block1, blockSize);
resize(block2, blockSize);
cout << "awrite() using FILE* "; testThroughput< FILE* > ("file_speed1.bin");
cout << "awrite() using sync. File "; testThroughput< File< Sync<> > > ("file_speed2.bin");
cout << "awrite() using async. File "; testThroughput< File< Async<> > > ("file_speed3.bin");
cout << "ExtString using FILE* "; testExtString< FILE* > ("file_speed4.bin");
cout << "ExtString using sync. File "; testExtString< File< Sync<> > > ("file_speed5.bin");
cout << "ExtString using async. File "; testExtString< File< Async<> > > ("file_speed6.bin");
cout << "Memory Mapped String "; testMMapString< File< Sync<> > > ("file_speed7.bin");
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shapeattributelayerholder.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 21:18:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX
#define _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX
#include <attributableshape.hxx>
#include <shapeattributelayer.hxx>
namespace presentation
{
namespace internal
{
/** Holds a ShapeAttributeLayer, together with the associated
Shape
Use this class to hold ShapeAttributeLayer objects the
RAII way. When this object gets deleted, it will
automatically revoke the attribute layer for the given
shape (this encapsulates the somewhat clumsy notification
process that is required for shape and attribute layer
interaction).
*/
class ShapeAttributeLayerHolder
{
public:
/** Create a ShapeAttributeLayerHolder instance.
This constructor creates an empty attribute holder, to
generate an attribute layer, you have to manually call
createAttributeLayer().
*/
ShapeAttributeLayerHolder() :
mpShape(),
mpAttributeLayer()
{
}
~ShapeAttributeLayerHolder()
{
reset(); // ensures that the last attribute layer is
// correctly deregistered from the shape.
}
void reset()
{
if( mpShape.get() && mpAttributeLayer.get() )
mpShape->revokeAttributeLayer( mpAttributeLayer );
}
/** This constructor receives a pointer to the Shape, from
which attribute layers should be generated. Initially,
this object does not create an attribute layer, you
have to manually call createAttributeLayer().
@param rShape
Shape for which attribute layers should be generated.
*/
bool createAttributeLayer( const AttributableShapeSharedPtr& rShape )
{
reset();
mpShape = rShape;
if( mpShape.get() )
mpAttributeLayer = mpShape->createAttributeLayer();
return mpAttributeLayer.get() != NULL;
}
ShapeAttributeLayerSharedPtr get() const
{
return mpAttributeLayer;
}
private:
// default: disabled copy/assignment
ShapeAttributeLayerHolder(const ShapeAttributeLayerHolder&);
ShapeAttributeLayerHolder& operator=( const ShapeAttributeLayerHolder& );
AttributableShapeSharedPtr mpShape;
ShapeAttributeLayerSharedPtr mpAttributeLayer;
};
}
}
#endif /* _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX */
<commit_msg>INTEGRATION: CWS presfixes09 (1.3.18); FILE MERGED 2006/04/12 20:40:09 thb 1.3.18.3: #i37778# Replaced all shared_ptr.get() != NULL places with the more elegant automatic-conversion-to-bool version (at least where the compiler tolerated that) 2006/03/24 18:23:36 thb 1.3.18.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006/03/23 17:22:45 thb 1.3.18.1: #i49357# Changed manual noncopyable boiler plate to boost::noncopyable<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: shapeattributelayerholder.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2006-12-13 16:01:42 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX
#define _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX
#include <attributableshape.hxx>
#include <shapeattributelayer.hxx>
#include <boost/utility.hpp>
namespace slideshow
{
namespace internal
{
/** Holds a ShapeAttributeLayer, together with the associated
Shape
Use this class to hold ShapeAttributeLayer objects the
RAII way. When this object gets deleted, it will
automatically revoke the attribute layer for the given
shape (this encapsulates the somewhat clumsy notification
process that is required for shape and attribute layer
interaction).
*/
class ShapeAttributeLayerHolder : private boost::noncopyable
{
public:
/** Create a ShapeAttributeLayerHolder instance.
This constructor creates an empty attribute holder, to
generate an attribute layer, you have to manually call
createAttributeLayer().
*/
ShapeAttributeLayerHolder() :
mpShape(),
mpAttributeLayer()
{
}
~ShapeAttributeLayerHolder()
{
reset(); // ensures that the last attribute layer is
// correctly deregistered from the shape.
}
void reset()
{
if( mpShape && mpAttributeLayer )
mpShape->revokeAttributeLayer( mpAttributeLayer );
}
/** This constructor receives a pointer to the Shape, from
which attribute layers should be generated. Initially,
this object does not create an attribute layer, you
have to manually call createAttributeLayer().
@param rShape
Shape for which attribute layers should be generated.
*/
bool createAttributeLayer( const AttributableShapeSharedPtr& rShape )
{
reset();
mpShape = rShape;
if( mpShape )
mpAttributeLayer = mpShape->createAttributeLayer();
return mpAttributeLayer;
}
ShapeAttributeLayerSharedPtr get() const
{
return mpAttributeLayer;
}
private:
AttributableShapeSharedPtr mpShape;
ShapeAttributeLayerSharedPtr mpAttributeLayer;
};
}
}
#endif /* _SLIDESHOW_SHAPEATTRIBUTELAYERHOLDER_HXX */
<|endoftext|> |
<commit_before>#ifdef COMPONENT_PARSER_H
#ifndef COMPONENT_PARSER_OPERATION_H
#define COMPONENT_PARSER_OPERATION_H
namespace Operations {
const Token nullval("null", KEYWORD, CONSTANT);
Token add(Token, Token);
Token subtract(Token, Token);
Token multiply(Token, Token);
Token divide(Token, Token);
Token modulo(Token, Token);
Token mathOperator(String, Token, Token);
Token compare(String, Token, Token);
Token logical(String, Token, Token);
int priority(String);
int comparePriority(Token, Token);
};
Token Operations::mathOperator(String op, Token a, Token b) {/*
if (op == "+") return add(a, b);
if (op == "-") return subtract(a, b);
if (op == "*") return multiply(a, b);
if (op == "/") return divide(a, b);
if (op == "%") return modulo(a, b);
*/
return nullval;
}
int Operations::priority(String op) {
if (op == ".") return 6;
if (op == "++" || op == "--") return 5;
if (op == "*" || op == "/" || op == "%") return 4;
if (op == "+" || op == "-") return 3;
if (op.substr(0,2) == "==" || op.substr(0, 2) == "!=" || op[0] == '<' || op[0] == '>') return 2;
if (op == "!" || op == "&&" || op == "||" || op == "=" || op[1] == '=') return 1;
return 0;
}
int Operations::comparePriority(Token a, Token b) {
return priority(a.value()) - priority(b.value());
}
#endif /* COMPONENT_PARSER_OPERATION_H */
#endif /* COMPONENT_PARSER_H */
<commit_msg>Operation Functions<commit_after>#ifdef COMPONENT_PARSER_H
#ifndef COMPONENT_PARSER_OPERATION_H
#define COMPONENT_PARSER_OPERATION_H
namespace Operations {
const Token nullval("null", KEYWORD, CONSTANT);
Token add(Token, Token);
Token subtract(Token, Token);
Token multiply(Token, Token);
Token divide(Token, Token);
Token modulo(Token, Token);
Token mathOperator(String, Token, Token);
Token compare(String, Token, Token);
Token logical(String, Token, Token);
int priority(String);
int comparePriority(Token, Token);
};
Token Operations::mathOperator(String op, Token a, Token b) {/*
if (op == "+") return add(a, b);
if (op == "-") return subtract(a, b);
if (op == "*") return multiply(a, b);
if (op == "/") return divide(a, b);
if (op == "%") return modulo(a, b);
*/
return nullval;
}
int Operations::priority(String op) {
if (op == ".") return 6;
if (op == "++" || op == "--") return 5;
if (op == "*" || op == "/" || op == "%") return 4;
if (op == "+" || op == "-") return 3;
if (op.substr(0,2) == "==" || op.substr(0, 2) == "!=" || op[0] == '<' || op[0] == '>') return 2;
if (op == "!" || op == "&&" || op == "||" || op == "=" || op[1] == '=') return 1;
return 0;
}
int Operations::comparePriority(Token a, Token b) {
return priority(a.value()) - priority(b.value());
}
Token Operations::add(Token t1, Token t2) {
if(t1.subtype() != t2.subtype() ) return nullToken;
if(t1.subtype() == NUMBER) {
long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
return Lexer::toToken(numberToString(a1 + a2));
}
if(t1.subtype() == STRING) {
String s1 = Lexer::tokenToString(t1),s2 = Lexer::tokenToString(t2);
return Lexer::toToken(s1 + s2);
}
}
Token Operations::subtract(Token t1, Token t2) {
if(t1.subtype() != NUMBER && t2.subtype() != NUMBER) return nullToken;
long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
return Lexer::toToken(numberToString(a1 - a2));
}
Token Operations::multiply(Token t1, Token t2) {
if(t1.subtype() != NUMBER && t2.subtype() != NUMBER) return nullToken;
long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
return Lexer::toToken(numberToString(a1 * a2));
}
Token Operations::divide(Token t1, Token t2) {
if(t1.subtype() != NUMBER && t2.subtype() != NUMBER) return nullToken;
long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
return Lexer::toToken(numberToString(a1 / a2));
}
Token Operations::modulo(Token t1, Token t2) {
if((!t1.value().isInteger()) && (!t2.value().isInteger())) return nullToken;
long a1 = t1.value().toNumber(),a2 = t2.value().toNumber();
return Lexer::toToken(integerToString(a1 / a2));
}
#endif /* COMPONENT_PARSER_OPERATION_H */
#endif /* COMPONENT_PARSER_H */
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fileobj.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2006-11-22 10:37:29 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _FILEOBJ_HXX
#define _FILEOBJ_HXX
#ifndef _STRING_HXX //autogen
#include <tools/string.hxx>
#endif
#ifndef _LINKSRC_HXX //autogen
#include <sfx2/linksrc.hxx>
#endif
#ifndef _SFXDOCFILE_HXX //autogen
#include <sfx2/docfile.hxx>
#endif
#ifndef _SVXLINKMGR_HXX
#include "linkmgr.hxx"
#endif
class Graphic;
struct Impl_DownLoadData;
namespace sfx2 { class FileDialogHelper; }
class SvFileObject : public sfx2::SvLinkSource
{
String sFileNm;
String sFilter;
String sReferer;
Link aEndEditLink;
SfxMediumRef xMed;
Impl_DownLoadData* pDownLoadData;
Window* pOldParent;
BYTE nType;
BOOL bLoadAgain : 1;
BOOL bSynchron : 1;
BOOL bLoadError : 1;
BOOL bWaitForData : 1;
BOOL bInNewData : 1;
BOOL bDataReady : 1;
BOOL bMedUseCache : 1;
BOOL bNativFormat : 1;
BOOL bClearMedium : 1;
BOOL bStateChangeCalled : 1;
BOOL bInCallDownLoad : 1;
BOOL GetGraphic_Impl( Graphic&, SvStream* pStream = 0 );
BOOL LoadFile_Impl();
void SendStateChg_Impl( LinkState nState );
DECL_STATIC_LINK( SvFileObject, DelMedium_Impl, SfxMediumRef* );
DECL_STATIC_LINK( SvFileObject, LoadGrfReady_Impl, void* );
DECL_STATIC_LINK( SvFileObject, LoadGrfNewData_Impl, void* );
DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );
protected:
virtual ~SvFileObject();
public:
SvFileObject();
virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/,
const String & rMimeType,
BOOL bSynchron = FALSE );
virtual BOOL Connect( sfx2::SvBaseLink* );
virtual void Edit( Window *, sfx2::SvBaseLink *, const Link& rEndEditHdl );
// erfrage ob das man direkt auf die Daten zugreifen kann oder ob das
// erst angestossen werden muss
virtual BOOL IsPending() const;
virtual BOOL IsDataComplete() const;
void CancelTransfers();
void SetTransferPriority( USHORT nPrio );
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.8.620); FILE MERGED 2008/04/01 15:51:46 thb 1.8.620.3: #i85898# Stripping all external header guards 2008/04/01 12:50:07 thb 1.8.620.2: #i85898# Stripping all external header guards 2008/03/31 14:24:03 rt 1.8.620.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fileobj.hxx,v $
* $Revision: 1.9 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _FILEOBJ_HXX
#define _FILEOBJ_HXX
#include <tools/string.hxx>
#include <sfx2/linksrc.hxx>
#include <sfx2/docfile.hxx>
#include "linkmgr.hxx"
class Graphic;
struct Impl_DownLoadData;
namespace sfx2 { class FileDialogHelper; }
class SvFileObject : public sfx2::SvLinkSource
{
String sFileNm;
String sFilter;
String sReferer;
Link aEndEditLink;
SfxMediumRef xMed;
Impl_DownLoadData* pDownLoadData;
Window* pOldParent;
BYTE nType;
BOOL bLoadAgain : 1;
BOOL bSynchron : 1;
BOOL bLoadError : 1;
BOOL bWaitForData : 1;
BOOL bInNewData : 1;
BOOL bDataReady : 1;
BOOL bMedUseCache : 1;
BOOL bNativFormat : 1;
BOOL bClearMedium : 1;
BOOL bStateChangeCalled : 1;
BOOL bInCallDownLoad : 1;
BOOL GetGraphic_Impl( Graphic&, SvStream* pStream = 0 );
BOOL LoadFile_Impl();
void SendStateChg_Impl( LinkState nState );
DECL_STATIC_LINK( SvFileObject, DelMedium_Impl, SfxMediumRef* );
DECL_STATIC_LINK( SvFileObject, LoadGrfReady_Impl, void* );
DECL_STATIC_LINK( SvFileObject, LoadGrfNewData_Impl, void* );
DECL_LINK( DialogClosedHdl, sfx2::FileDialogHelper* );
protected:
virtual ~SvFileObject();
public:
SvFileObject();
virtual BOOL GetData( ::com::sun::star::uno::Any & rData /*out param*/,
const String & rMimeType,
BOOL bSynchron = FALSE );
virtual BOOL Connect( sfx2::SvBaseLink* );
virtual void Edit( Window *, sfx2::SvBaseLink *, const Link& rEndEditHdl );
// erfrage ob das man direkt auf die Daten zugreifen kann oder ob das
// erst angestossen werden muss
virtual BOOL IsPending() const;
virtual BOOL IsDataComplete() const;
void CancelTransfers();
void SetTransferPriority( USHORT nPrio );
};
#endif
<|endoftext|> |
<commit_before>#undef DEBUG
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
//for connection to server
#include "../sockets/SocketW.h"
bool ready4data = false;//set to true when streaming starts
bool inited = false;
bool stopparsing = false;
timeval lastrec;
FILE * CONN = 0;
#include "parsechunks.cpp" //chunkstream parsing
#include "handshake.cpp" //handshaking
#include "../util/flv_sock.cpp" //FLV parsing with SocketW
#include "../util/ddv_socket.cpp" //DDVTech Socket wrapper
int main(){
int server_socket = DDV_Listen(1935);
int status;
while (server_socket > 0){
waitpid((pid_t)-1, &status, WNOHANG);
CONN = DDV_Accept(server_socket);
pid_t myid = fork();
if (myid == 0){
break;
}else{
printf("Spawned new process %i for incoming client\n", (int)myid);
}
}
if (server_socket <= 0){
return 0;
}
unsigned int ts;
unsigned int fts = 0;
unsigned int ftst;
SWUnixSocket ss;
//first timestamp set
firsttime = getNowMS();
#ifdef DEBUG
fprintf(stderr, "Doing handshake...\n");
#endif
if (doHandshake()){
#ifdef DEBUG
fprintf(stderr, "Handshake succcess!\n");
#endif
}else{
#ifdef DEBUG
fprintf(stderr, "Handshake fail!\n");
#endif
return 0;
}
#ifdef DEBUG
fprintf(stderr, "Starting processing...\n");
#endif
while (!ferror(stdin) && !ferror(stdout)){
//only parse input from stdin if available or not yet init'ed
//rightnow = getNowMS();
if ((!ready4data || (snd_cnt - snd_window_at >= snd_window_size)) && !stopparsing){
parseChunk();
fflush(CONN);
}
if (ready4data){
if (!inited){
//we are ready, connect the socket!
if (!ss.connect(streamname.c_str())){
#ifdef DEBUG
fprintf(stderr, "Could not connect to server!\n");
#endif
return 0;
}
FLV_Readheader(ss);//read the header, we don't want it
#ifdef DEBUG
fprintf(stderr, "Header read, starting to send video data...\n");
#endif
inited = true;
}
//only send data if previous data has been ACK'ed...
if (snd_cnt - snd_window_at < snd_window_size){
if (FLV_GetPacket(ss)){//able to read a full packet?
ts = FLVbuffer[7] * 256*256*256;
ts += FLVbuffer[4] * 256*256;
ts += FLVbuffer[5] * 256;
ts += FLVbuffer[6];
if (ts != 0){
if (fts == 0){fts = ts;ftst = getNowMS();}
ts -= fts;
FLVbuffer[7] = ts / (256*256*256);
FLVbuffer[4] = ts / (256*256);
FLVbuffer[5] = ts / 256;
FLVbuffer[6] = ts % 256;
ts += ftst;
}else{
ftst = getNowMS();
FLVbuffer[7] = ftst / (256*256*256);
FLVbuffer[4] = ftst / (256*256);
FLVbuffer[5] = ftst / 256;
FLVbuffer[6] = ftst % 256;
}
SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts);
FLV_Dump();//dump packet and get ready for next
}
if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){
#ifdef DEBUG
fprintf(stderr, "No more data! :-( (%s)\n", SWBerr.get_error().c_str());
#endif
return 0;//no more input possible! Fail immediately.
}
}
}
//send ACK if we received a whole window
if (rec_cnt - rec_window_at > rec_window_size){
rec_window_at = rec_cnt;
SendCTL(3, rec_cnt);//send ack (msg 3)
}
}
#ifdef DEBUG
fprintf(stderr, "User disconnected.\n");
#endif
return 0;
}//main
<commit_msg>Nog een poging...<commit_after>#define DEBUG
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
//for connection to server
#include "../sockets/SocketW.h"
bool ready4data = false;//set to true when streaming starts
bool inited = false;
bool stopparsing = false;
timeval lastrec;
FILE * CONN = 0;
#include "parsechunks.cpp" //chunkstream parsing
#include "handshake.cpp" //handshaking
#include "../util/flv_sock.cpp" //FLV parsing with SocketW
#include "../util/ddv_socket.cpp" //DDVTech Socket wrapper
int main(){
int server_socket = DDV_Listen(1935);
int status;
while (server_socket > 0){
waitpid((pid_t)-1, &status, WNOHANG);
CONN = DDV_Accept(server_socket);
pid_t myid = fork();
if (myid == 0){
break;
}else{
printf("Spawned new process %i for incoming client\n", (int)myid);
}
}
if (server_socket <= 0){
return 0;
}
unsigned int ts;
unsigned int fts = 0;
unsigned int ftst;
SWUnixSocket ss;
//first timestamp set
firsttime = getNowMS();
#ifdef DEBUG
fprintf(stderr, "Doing handshake...\n");
#endif
if (doHandshake()){
#ifdef DEBUG
fprintf(stderr, "Handshake succcess!\n");
#endif
}else{
#ifdef DEBUG
fprintf(stderr, "Handshake fail!\n");
#endif
return 0;
}
#ifdef DEBUG
fprintf(stderr, "Starting processing...\n");
#endif
while (!ferror(CONN)){
//only parse input if available or not yet init'ed
//rightnow = getNowMS();
if ((!ready4data || (snd_cnt - snd_window_at >= snd_window_size)) && !stopparsing){
parseChunk();
fflush(CONN);
}
if (ready4data){
if (!inited){
//we are ready, connect the socket!
if (!ss.connect(streamname.c_str())){
#ifdef DEBUG
fprintf(stderr, "Could not connect to server!\n");
#endif
return 0;
}
FLV_Readheader(ss);//read the header, we don't want it
#ifdef DEBUG
fprintf(stderr, "Header read, starting to send video data...\n");
#endif
inited = true;
}
//only send data if previous data has been ACK'ed...
if (snd_cnt - snd_window_at < snd_window_size){
if (FLV_GetPacket(ss)){//able to read a full packet?
ts = FLVbuffer[7] * 256*256*256;
ts += FLVbuffer[4] * 256*256;
ts += FLVbuffer[5] * 256;
ts += FLVbuffer[6];
if (ts != 0){
if (fts == 0){fts = ts;ftst = getNowMS();}
ts -= fts;
FLVbuffer[7] = ts / (256*256*256);
FLVbuffer[4] = ts / (256*256);
FLVbuffer[5] = ts / 256;
FLVbuffer[6] = ts % 256;
ts += ftst;
}else{
ftst = getNowMS();
FLVbuffer[7] = ftst / (256*256*256);
FLVbuffer[4] = ftst / (256*256);
FLVbuffer[5] = ftst / 256;
FLVbuffer[6] = ftst % 256;
}
SendMedia((unsigned char)FLVbuffer[0], (unsigned char *)FLVbuffer+11, FLV_len-15, ts);
FLV_Dump();//dump packet and get ready for next
}
if ((SWBerr != SWBaseSocket::ok) && (SWBerr != SWBaseSocket::notReady)){
#ifdef DEBUG
fprintf(stderr, "No more data! :-( (%s)\n", SWBerr.get_error().c_str());
#endif
return 0;//no more input possible! Fail immediately.
}
}
}
//send ACK if we received a whole window
if (rec_cnt - rec_window_at > rec_window_size){
rec_window_at = rec_cnt;
SendCTL(3, rec_cnt);//send ack (msg 3)
}
}
#ifdef DEBUG
fprintf(stderr, "User disconnected.\n");
#endif
return 0;
}//main
<|endoftext|> |
<commit_before>/* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for simulated annealing derived algorithm class
*/
#include <cmath>
#include <iostream>
#include "simulated_annealing_algorithm.hpp"
bool SimulatedAnnealing::probability(const parameter energy1,
const parameter energy2,
const parameter temperature) const {
int_dist percent(0, 100);
// mutation probability P(e1, e2, T) = e^(-c(e1 - e2)/T)
const parameter chance = 100 * // [0, 1] -> [0, 100]
std::exp(-problem.constant * (energy1 - energy2) / temperature);
return percent(rg.engine) < chance;
}
const Individual SimulatedAnnealing::solve() const {
while(true) {
// random restart
Individual best = problem.potential();
// work with "lucky" values
if (best > problem.filter) {
// actual simulated-annealing algorithm
for (long T = problem.iterations; T > 0; --T) {
// convert temperature to [0, 100]
const parameter temperature = 100. * parameter(T) / problem.iterations;
// get neighbor
const Individual neighbor = mutate(best);
// keep track of best solution
if (neighbor > best
// SA swaps in bad solutions with this probability
|| probability(best.fitness, neighbor.fitness, temperature)) {
best = neighbor;
// terminating condition
if (best > problem.goal) return best;
}
}
std::cout << "Exhausted fitness: " << best.fitness << "\n";
}
}
}
<commit_msg>Fixed call to SA's probability function (sending normalized fitness)<commit_after>/* Copyright 2014 Andrew Schwartzmeyer
*
* Source file for simulated annealing derived algorithm class
*/
#include <cmath>
#include <iostream>
#include "simulated_annealing_algorithm.hpp"
bool SimulatedAnnealing::probability(const parameter energy1,
const parameter energy2,
const parameter temperature) const {
int_dist percent(0, 100);
// mutation probability P(e1, e2, T) = e^(-c(e1 - e2)/T)
const parameter chance = 100 * // [0, 1] -> [0, 100]
std::exp(-problem.constant * (energy1 - energy2) / temperature);
return percent(rg.engine) < chance;
}
const Individual SimulatedAnnealing::solve() const {
while(true) {
// random restart
Individual best = problem.potential();
// work with "lucky" values
if (best > problem.filter) {
// actual simulated-annealing algorithm
for (long T = problem.iterations; T > 0; --T) {
// convert temperature to [0, 100]
const parameter temperature = 100. * parameter(T) / problem.iterations;
// get neighbor
const Individual neighbor = mutate(best);
// keep track of best solution
if (neighbor > best
// SA swaps in bad solutions with this probability
|| probability(problem.normal(best), problem.normal(neighbor),
temperature)) {
best = neighbor;
// terminating condition
if (best > problem.goal) return best;
}
}
std::cout << "Exhausted fitness: " << best.fitness << "\n";
}
}
}
<|endoftext|> |
<commit_before>/*
* pAlgorithm.cpp
*
* Author: Petel__
* Copyright (c) 2014-2016 HKUST SmartCar Team
* Refer to LICENSE for details
*/
#include <pSmartCar.h>
#include <libbase/k60/watchdog.h>
#include <pResource.h>
using namespace std;
using namespace libsc;
using namespace libbase::k60;
void pSmartCar::addAllRoutineToLoop(void)
{
m_loop.addFunctionToLoop(update, 5);
m_loop.addFunctionToLoop(directionControl, 10);
m_loop.addFunctionToLoop(speedControl, 100);
m_loop.addFunctionToLoop(angleControl, 5);
m_loop.addFunctionToLoop(print, 20);
// m_loop.addFunctionToLoop(safetyCheck, 200);
}
void pSmartCar::addVariablesToGrapher(void)
{
m_grapher.setOnChangedListener(pResource::grapherOnChangedListener);
}
//========================================================================================
//========================= Routine ==============================
//========================================================================================
void pSmartCar::update(void)
{
pResource::m_instance->updateSensors();
pResource::m_instance->updateState();
pResource::m_instance->updateMotors();
pResource::m_instance->m_magSen[0].updatePair();
}
void pSmartCar::angleControl(void)
{
pResource::m_instance->updatePid(pResource::m_instance->m_state[StatePos::cur].angle + pResource::m_instance->getSmoothAngleOutput() - ABS(pResource::m_instance->m_state[StatePos::cur].dYaw) * pResource::configTable.kSpinConstant, Type::Angle);
if (pResource::m_instance->m_motorEnabled && !isInRange2(pResource::m_instance->m_angle.getAngle(), pResource::configTable.kIdealAngle, pResource::configTable.kAngleRange))
{
pResource::m_instance->setMotorsEnabled(false);
pBuzzer::terminated();
pResource::m_instance->m_isReadyToRun = true;
}
pResource::m_instance->updateSpeed();
}
void pSmartCar::directionControl(void)
{
float tempResult = -pResource::m_instance->m_magSen[0].updatePair();
pResource::m_instance->updateSmoothDirectionOutput(pResource::m_instance->m_fuzzyLogic.updatePdController(tempResult));
}
void pSmartCar::speedControl(void)
{
// pResource::m_instance->smoothedIdealSpeed(2.0f);
pResource::m_instance->updatePid(pResource::m_instance->m_state[StatePos::cur].dX, Type::Speed);
pResource::m_instance->updateSmoothAngleOutput(pResource::m_instance->m_pidOutputVal[Type::Speed]);
}
void pSmartCar::print(void)
{
// pResource::m_instance->onDraw();
pResource::m_instance->m_grapher.sendWatchData();
}
//========================================================================================
//========================= | | | | | | | | | | | | | | | | ==============================
//========================= v v v v v v v v v v v v v v v v ==============================
void pSmartCar::smoothedIdealSpeed(const float &accelLimit)
{
m_curSpeed = inRange(0, m_state[cur].dX + inRange(-m_curSpeed, (m_idealSpeed - m_state[cur].dX) * pResource::configTable.kAccelSpeed, accelLimit), m_idealSpeed);
}
void pSmartCar::updateSensors(void)
{
m_angle.update();
m_motors[0].update();
m_motors[1].update();
}
void pSmartCar::updateState(void)
{
if (m_state[StatePos::prev].timeStamp)
{
m_state[StatePos::prev] = m_state[StatePos::cur];
m_state[StatePos::cur].angle = pResource::m_instance->m_angle.getAngle();
m_state[StatePos::cur].dAngle = -pResource::m_instance->m_angle.getOmega(1);
float tempDx = m_encoderLpf.filter((m_motors[0].getEncoderCount() + m_motors[1].getEncoderCount()) * 0.0523137f) / (System::Time() - m_state[StatePos::prev].timeStamp);
if (++m_ignoreSpeedCounter >= 20 || tempDx < m_state[StatePos::cur].dX * 1.5f)
{
m_state[StatePos::cur].dX = tempDx;
m_ignoreSpeedCounter = 0;
}
m_state[StatePos::cur].dYaw = m_angle.getYawOmega();
}
m_state[StatePos::prev].timeStamp = System::Time();
}
void pSmartCar::updateSmoothAngleOutput(const float newAngle)
{
m_smoothIncrement[IncrementType::SpeedIncrement] = (newAngle - m_idealAngleOffset) * 0.05f;
}
float pSmartCar::getSmoothAngleOutput(void)
{
if (isInRange2(m_state[StatePos::cur].angle + m_smoothIncrement[IncrementType::SpeedIncrement] + m_idealAngleOffset, pResource::configTable.kIdealAngle, pResource::configTable.kAngleRange))
return (m_idealAngleOffset += m_smoothIncrement[IncrementType::SpeedIncrement]);
else if (isInRange2(m_state[StatePos::cur].angle, pResource::configTable.kIdealAngle, pResource::configTable.kAngleRange))
return (m_idealAngleOffset = inRange2(m_state[StatePos::cur].angle + m_smoothIncrement[IncrementType::SpeedIncrement] + m_idealAngleOffset, pResource::configTable.kIdealAngle, pResource::configTable.kAngleRange) - pResource::configTable.kIdealAngle);
else
return m_idealAngleOffset;
}
void pSmartCar::updateSmoothDirectionOutput(const float newDirection)
{
m_smoothIncrement[IncrementType::DirectionIncrement] = (newDirection - m_directionOffset) * 0.5f;
}
float pSmartCar::getSmoothDirectionOutput(void)
{
return (m_directionOffset += m_smoothIncrement[IncrementType::DirectionIncrement]);
}
void pSmartCar::updateMotors(void)
{
m_motors[0].update();
m_motors[1].update();
}
void pSmartCar::updateSpeed(void)
{
float tempDirectionOutput = (m_directionEnabled)? getSmoothDirectionOutput() : 0.0f;
m_motors[0].setMappedPower(inRange(-9000, m_pidOutputVal[Type::Angle] + tempDirectionOutput, 9000));
m_motors[1].setMappedPower(inRange(-9000, m_pidOutputVal[Type::Angle] - tempDirectionOutput, 9000));
}
void pSmartCar::onDraw(void)
{
// m_lcd.setRow(0);
// m_lcd << m_motors[0].getEncoderCount() << '\t' << m_motors[1].getEncoderCount() << '\t' << endl
// << m_motors[0].getPower() << '\t' << m_motors[1].getPower() << '\t' << endl
// << m_state[StatePos::cur].dX << '\t' << m_state[StatePos::cur].angle << '\t' << endl
// << m_state[StatePos::cur].dYaw << '\t' << m_state[StatePos::cur].dAngle << '\t' << endl;
// << m_angle.getAccel(0) << '\t' << m_angle.getAccel(1) << '\t' << m_angle.getAccel(2) << '\t' << endl
// << m_angle.getOmega(0) << '\t' << m_angle.getOmega(1) << '\t' << m_angle.getOmega(2) << '\t' << endl
}
<commit_msg>Update speed every 20ms<commit_after>/*
* pAlgorithm.cpp
*
* Author: Petel__
* Copyright (c) 2014-2016 HKUST SmartCar Team
* Refer to LICENSE for details
*/
#include <pSmartCar.h>
#include <libbase/k60/watchdog.h>
#include <pResource.h>
using namespace std;
using namespace libsc;
using namespace libbase::k60;
void pSmartCar::addAllRoutineToLoop(void)
{
m_loop.addFunctionToLoop(update, 5);
m_loop.addFunctionToLoop(directionControl, 10);
m_loop.addFunctionToLoop(speedControl, 20);
m_loop.addFunctionToLoop(angleControl, 5);
m_loop.addFunctionToLoop(print, 20);
// m_loop.addFunctionToLoop(safetyCheck, 200);
}
void pSmartCar::addVariablesToGrapher(void)
{
m_grapher.setOnChangedListener(pResource::grapherOnChangedListener);
}
//========================================================================================
//========================= Routine ==============================
//========================================================================================
void pSmartCar::update(void)
{
pResource::m_instance->updateSensors();
pResource::m_instance->updateState();
pResource::m_instance->updateMotors();
pResource::m_instance->m_magSen[0].updatePair();
}
void pSmartCar::angleControl(void)
{
pResource::m_instance->updatePid(pResource::m_instance->m_state[StatePos::cur].angle + pResource::m_instance->getSmoothAngleOutput() - ABS(pResource::m_instance->m_state[StatePos::cur].dYaw) * pResource::configTable.kSpinConstant, Type::Angle);
if (pResource::m_instance->m_motorEnabled && !isInRange2(pResource::m_instance->m_angle.getAngle(), pResource::configTable.kIdealAngle, pResource::configTable.kAngleRange))
{
pResource::m_instance->setMotorsEnabled(false);
pBuzzer::terminated();
pResource::m_instance->m_isReadyToRun = true;
}
pResource::m_instance->updateSpeed();
}
void pSmartCar::directionControl(void)
{
float tempResult = -pResource::m_instance->m_magSen[0].updatePair();
pResource::m_instance->updateSmoothDirectionOutput(pResource::m_instance->m_fuzzyLogic.updatePdController(tempResult));
}
void pSmartCar::speedControl(void)
{
// pResource::m_instance->smoothedIdealSpeed(2.0f);
pResource::m_instance->updatePid(pResource::m_instance->m_state[StatePos::cur].dX, Type::Speed);
pResource::m_instance->updateSmoothAngleOutput(pResource::m_instance->m_pidOutputVal[Type::Speed]);
}
void pSmartCar::print(void)
{
// pResource::m_instance->onDraw();
pResource::m_instance->m_grapher.sendWatchData();
}
//========================================================================================
//========================= | | | | | | | | | | | | | | | | ==============================
//========================= v v v v v v v v v v v v v v v v ==============================
void pSmartCar::smoothedIdealSpeed(const float &accelLimit)
{
m_curSpeed = inRange(0, m_state[cur].dX + inRange(-m_curSpeed, (m_idealSpeed - m_state[cur].dX) * pResource::configTable.kAccelSpeed, accelLimit), m_idealSpeed);
}
void pSmartCar::updateSensors(void)
{
m_angle.update();
m_motors[0].update();
m_motors[1].update();
}
void pSmartCar::updateState(void)
{
if (m_state[StatePos::prev].timeStamp)
{
m_state[StatePos::prev] = m_state[StatePos::cur];
m_state[StatePos::cur].angle = pResource::m_instance->m_angle.getAngle();
m_state[StatePos::cur].dAngle = -pResource::m_instance->m_angle.getOmega(1);
float tempDx = m_encoderLpf.filter((m_motors[0].getEncoderCount() + m_motors[1].getEncoderCount()) * 0.0523137f) / (System::Time() - m_state[StatePos::prev].timeStamp);
if (++m_ignoreSpeedCounter >= 20 || tempDx < m_state[StatePos::cur].dX * 1.5f)
{
m_state[StatePos::cur].dX = tempDx;
m_ignoreSpeedCounter = 0;
}
m_state[StatePos::cur].dYaw = m_angle.getYawOmega();
}
m_state[StatePos::prev].timeStamp = System::Time();
}
void pSmartCar::updateSmoothAngleOutput(const float newAngle)
{
m_smoothIncrement[IncrementType::SpeedIncrement] = (newAngle - m_idealAngleOffset) * 0.25f;
}
float pSmartCar::getSmoothAngleOutput(void)
{
if (isInRange2(m_state[StatePos::cur].angle + m_smoothIncrement[IncrementType::SpeedIncrement] + m_idealAngleOffset, pResource::configTable.kIdealAngle, pResource::configTable.kAngleRange))
return (m_idealAngleOffset += m_smoothIncrement[IncrementType::SpeedIncrement]);
else if (isInRange2(m_state[StatePos::cur].angle, pResource::configTable.kIdealAngle, pResource::configTable.kAngleRange))
return (m_idealAngleOffset = inRange2(m_state[StatePos::cur].angle + m_smoothIncrement[IncrementType::SpeedIncrement] + m_idealAngleOffset, pResource::configTable.kIdealAngle, pResource::configTable.kAngleRange) - pResource::configTable.kIdealAngle);
else
return m_idealAngleOffset;
}
void pSmartCar::updateSmoothDirectionOutput(const float newDirection)
{
m_smoothIncrement[IncrementType::DirectionIncrement] = (newDirection - m_directionOffset) * 0.5f;
}
float pSmartCar::getSmoothDirectionOutput(void)
{
return (m_directionOffset += m_smoothIncrement[IncrementType::DirectionIncrement]);
}
void pSmartCar::updateMotors(void)
{
m_motors[0].update();
m_motors[1].update();
}
void pSmartCar::updateSpeed(void)
{
float tempDirectionOutput = (m_directionEnabled)? getSmoothDirectionOutput() : 0.0f;
m_motors[0].setMappedPower(inRange(-9000, m_pidOutputVal[Type::Angle] + tempDirectionOutput, 9000));
m_motors[1].setMappedPower(inRange(-9000, m_pidOutputVal[Type::Angle] - tempDirectionOutput, 9000));
}
void pSmartCar::onDraw(void)
{
// m_lcd.setRow(0);
// m_lcd << m_motors[0].getEncoderCount() << '\t' << m_motors[1].getEncoderCount() << '\t' << endl
// << m_motors[0].getPower() << '\t' << m_motors[1].getPower() << '\t' << endl
// << m_state[StatePos::cur].dX << '\t' << m_state[StatePos::cur].angle << '\t' << endl
// << m_state[StatePos::cur].dYaw << '\t' << m_state[StatePos::cur].dAngle << '\t' << endl;
// << m_angle.getAccel(0) << '\t' << m_angle.getAccel(1) << '\t' << m_angle.getAccel(2) << '\t' << endl
// << m_angle.getOmega(0) << '\t' << m_angle.getOmega(1) << '\t' << m_angle.getOmega(2) << '\t' << endl
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2009-2017, Albertas Vyšniauskas
* 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 software 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 "Script.h"
#include <sstream>
extern "C"{
#include <lualib.h>
#include <lauxlib.h>
}
#include <iostream>
using namespace std;
namespace lua
{
Script::Script()
{
m_state = luaL_newstate();
m_state_owned = true;
luaL_openlibs(m_state);
}
Script::Script(lua_State *state)
{
m_state = state;
m_state_owned = false;
}
Script::~Script()
{
if (m_state_owned)
lua_close(m_state);
m_state = nullptr;
}
Script::operator lua_State*()
{
return m_state;
}
void Script::setPaths(const std::vector<std::string> &include_paths)
{
string paths = ";./?.lua;";
for (vector<string>::const_iterator i = include_paths.begin(); i != include_paths.end(); i++){
paths += *i;
paths += "/?.lua;";
}
lua_getglobal(m_state, "package");
lua_pushstring(m_state, "path");
lua_pushstring(m_state, paths.c_str());
lua_settable(m_state, -3);
lua_pop(m_state, 1);
}
bool Script::load(const char *script_name)
{
int status;
lua_getglobal(m_state, "require");
lua_pushstring(m_state, script_name);
status = lua_pcall(m_state, 1, 1, 0);
if (status) {
stringstream ss;
ss << lua_tostring(m_state, -1);
m_last_error = ss.str();
return false;
}
return true;
}
bool Script::loadCode(const char *script_code)
{
int status;
status = luaL_loadstring(m_state, script_code);
if (status){
m_last_error = lua_tostring(m_state, -1);
return false;
}
return true;
}
bool Script::run(int arguments_on_stack, int results)
{
lua_State *L = m_state;
int status;
if (lua_type(L, -1) != LUA_TNIL){
if ((status = lua_pcall(L, arguments_on_stack, results, 0))){
stringstream ss;
ss << "call failed: " << lua_tostring(L, -1);
m_last_error = ss.str();
return false;
}else{
return true;
}
}else{
m_last_error = "requested function was not found";
return false;
}
}
static int registerLuaPackage(lua_State *L)
{
auto &script = *reinterpret_cast<Script*>(lua_touserdata(L, -5));
auto &extension = *reinterpret_cast<function<int(Script &)>*>(lua_touserdata(L, -4));
return extension(script);
}
bool Script::registerExtension(const char *name, std::function<int(Script &)> extension)
{
lua_State *L = m_state;
string full_name;
if (name == nullptr)
full_name = "gpick";
else
full_name = string("gpick/") + name;
lua_pushlightuserdata(L, this);
lua_pushlightuserdata(L, &extension);
luaL_requiref(m_state, full_name.c_str(), registerLuaPackage, 0);
lua_pop(L, 3);
return true;
}
std::string Script::getString(int index)
{
return lua_tostring(m_state, index);
}
void Script::createType(const char *name, const luaL_Reg *members)
{
lua_State *L = m_state;
luaL_newmetatable(L, name);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, members, 0);
lua_pop(L, 1);
}
const std::string &Script::getLastError()
{
return m_last_error;
}
}
<commit_msg>Fix extension registration crash on Lua 5.2.<commit_after>/*
* Copyright (c) 2009-2017, Albertas Vyšniauskas
* 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 software 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 "Script.h"
#include <sstream>
extern "C"{
#include <lualib.h>
#include <lauxlib.h>
}
#include <iostream>
using namespace std;
namespace lua
{
Script::Script()
{
m_state = luaL_newstate();
m_state_owned = true;
luaL_openlibs(m_state);
}
Script::Script(lua_State *state)
{
m_state = state;
m_state_owned = false;
}
Script::~Script()
{
if (m_state_owned)
lua_close(m_state);
m_state = nullptr;
}
Script::operator lua_State*()
{
return m_state;
}
void Script::setPaths(const std::vector<std::string> &include_paths)
{
string paths = ";./?.lua;";
for (vector<string>::const_iterator i = include_paths.begin(); i != include_paths.end(); i++){
paths += *i;
paths += "/?.lua;";
}
lua_getglobal(m_state, "package");
lua_pushstring(m_state, "path");
lua_pushstring(m_state, paths.c_str());
lua_settable(m_state, -3);
lua_pop(m_state, 1);
}
bool Script::load(const char *script_name)
{
int status;
lua_getglobal(m_state, "require");
lua_pushstring(m_state, script_name);
status = lua_pcall(m_state, 1, 1, 0);
if (status) {
stringstream ss;
ss << lua_tostring(m_state, -1);
m_last_error = ss.str();
return false;
}
return true;
}
bool Script::loadCode(const char *script_code)
{
int status;
status = luaL_loadstring(m_state, script_code);
if (status){
m_last_error = lua_tostring(m_state, -1);
return false;
}
return true;
}
bool Script::run(int arguments_on_stack, int results)
{
lua_State *L = m_state;
int status;
if (lua_type(L, -1) != LUA_TNIL){
if ((status = lua_pcall(L, arguments_on_stack, results, 0))){
stringstream ss;
ss << "call failed: " << lua_tostring(L, -1);
m_last_error = ss.str();
return false;
}else{
return true;
}
}else{
m_last_error = "requested function was not found";
return false;
}
}
static int registerLuaPackage(lua_State *L)
{
lua_getglobal(L, "__script");
auto &script = *reinterpret_cast<Script*>(lua_touserdata(L, -1));
lua_getglobal(L, "__extension");
auto &extension = *reinterpret_cast<function<int(Script &)>*>(lua_touserdata(L, -1));
lua_pop(L, 2);
return extension(script);
}
bool Script::registerExtension(const char *name, std::function<int(Script &)> extension)
{
lua_State *L = m_state;
string full_name;
if (name == nullptr)
full_name = "gpick";
else
full_name = string("gpick/") + name;
lua_pushlightuserdata(L, this);
lua_setglobal(L, "__script");
lua_pushlightuserdata(L, &extension);
lua_setglobal(L, "__extension");
luaL_requiref(m_state, full_name.c_str(), registerLuaPackage, 0);
lua_pushnil(L);
lua_setglobal(L, "__script");
lua_pushnil(L);
lua_setglobal(L, "__extension");
lua_pop(L, 1);
return true;
}
std::string Script::getString(int index)
{
return lua_tostring(m_state, index);
}
void Script::createType(const char *name, const luaL_Reg *members)
{
lua_State *L = m_state;
luaL_newmetatable(L, name);
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
luaL_setfuncs(L, members, 0);
lua_pop(L, 1);
}
const std::string &Script::getLastError()
{
return m_last_error;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "VSExpHack.hpp"
// make it count for arguments:
#define _ARGCNT(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, N, ...) N
#define WRD_ARGCNT(...) WRD_VS_EXP_HACK(_ARGCNT(__VA_ARGS__, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
#define _ARGCNT2(_X1, _Y1, X2, _Y2, _X3, _Y3, _X4, _Y4, _X5, _Y5, _X6, _Y6, _X7, _Y7, _X8, _Y8, _X9, _Y9, _X10, _Y10, _X11, _Y11, _X12, _Y12, _X13, _Y13, _X14, _Y14, _X15, _Y15, _X16, _Y16, N, ...) N
#define WRD_ARGCNT2(...) WRD_VS_EXP_HACK(_ARGCNT2(__VA_ARGS__, 16, 16, 15, 15, 14, 14, 13, 13, 12, 12, 11, 11, 10, 10, 9, 9, 8, 8, 7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1, 0, 0))
<commit_msg>+ [indep] improve Overload macro. it can accepts zeo argument.<commit_after>#pragma once
// make it count for arguments:
#define _ARGCNT(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, N, ...) N
#define WRD_ARGCNT(...) _ARGCNT(, ## __VA_ARGS__, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
#define _ARGCNT2(_X1, _Y1, X2, _Y2, _X3, _Y3, _X4, _Y4, _X5, _Y5, _X6, _Y6, _X7, _Y7, _X8, _Y8, _X9, _Y9, _X10, _Y10, _X11, _Y11, _X12, _Y12, _X13, _Y13, _X14, _Y14, _X15, _Y15, _X16, _Y16, N, ...) N
#define WRD_ARGCNT2(...) _ARGCNT2(__VA_ARGS__, 16, 16, 15, 15, 14, 14, 13, 13, 12, 12, 11, 11, 10, 10, 9, 9, 8, 8, 7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1, 0, 0)
<|endoftext|> |
<commit_before>/* Copyright 2019-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas ([email protected])
*
*/
#include <gmock/gmock.h>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <tuple>
#include <vector>
#include "PI/frontends/cpp/tables.h"
#include "PI/frontends/proto/device_mgr.h"
#include "PI/int/pi_int.h"
#include "src/access_arbitration.h"
#include "src/common.h"
#include "src/watch_port_enforcer.h"
#include "test_proto_fe_base.h"
namespace pi {
namespace proto {
namespace testing {
using pi::fe::proto::AccessArbitration;
using pi::fe::proto::WatchPortEnforcer;
using ::testing::_;
using ::testing::DoAll;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
class WatchPortEnforcerTest : public ProtoFrontendBaseTest {
public:
WatchPortEnforcerTest()
: watch_port_enforcer(device_tgt, &access_arbitration) {
act_prof_id = pi_p4info_act_prof_id_from_name(p4info, "ActProfWS");
}
static void SetUpTestCase() {
DeviceMgr::init(256);
std::ifstream istream(input_path);
google::protobuf::io::IstreamInputStream istream_(&istream);
google::protobuf::TextFormat::Parse(&istream_, &p4info_proto);
pi::p4info::p4info_proto_reader(p4info_proto, &p4info);
}
static void TearDownTestCase() {
DeviceMgr::destroy();
}
void SetUp() override {
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
EXPECT_EQ(mock->port_status_set(port, PI_PORT_STATUS_UP),
PI_STATUS_SUCCESS);
}
ASSERT_OK(watch_port_enforcer.p4_change(p4info));
};
mutable std::condition_variable cv;
mutable std::mutex mutex;
static constexpr size_t numPorts = 16;
static constexpr const char *input_path =
TESTDATADIR "/" "unittest.p4info.txt";
static constexpr std::chrono::milliseconds timeout{200};
static pi_p4info_t *p4info;
static p4configv1::P4Info p4info_proto;
AccessArbitration access_arbitration;
WatchPortEnforcer watch_port_enforcer;
pi_p4_id_t act_prof_id;
pi_indirect_handle_t grp_h{10};
pi_indirect_handle_t mbr_h{20};
pi_port_t watch_1{1};
pi_port_t watch_2{2};
};
/* static */ constexpr std::chrono::milliseconds WatchPortEnforcerTest::timeout;
/* static */ pi_p4info_t *WatchPortEnforcerTest::p4info = nullptr;
/* static */ p4configv1::P4Info WatchPortEnforcerTest::p4info_proto;
TEST_F(WatchPortEnforcerTest, DontUpdateHw) {
EXPECT_CALL(*mock, action_prof_group_activate_member(act_prof_id, _, _))
.Times(0);
EXPECT_CALL(*mock, action_prof_group_deactivate_member(act_prof_id, _, _))
.Times(0);
watch_port_enforcer.handle_port_status_event_sync(
watch_1, PI_PORT_STATUS_DOWN);
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_id, grp_h, mbr_h, watch_1));
// down -> up
EXPECT_OK(watch_port_enforcer.modify_member(
act_prof_id, grp_h, mbr_h, watch_1, watch_2));
// up -> down
EXPECT_OK(watch_port_enforcer.modify_member(
act_prof_id, grp_h, mbr_h, watch_2, watch_1));
EXPECT_OK(watch_port_enforcer.delete_member(
act_prof_id, grp_h, mbr_h, watch_1));
watch_port_enforcer.handle_port_status_event_sync(
watch_1, PI_PORT_STATUS_UP);
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_id, grp_h, mbr_h, watch_1));
}
TEST_F(WatchPortEnforcerTest, UpdateHw) {
::pi::fe::proto::common::SessionTemp session;
::pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id);
watch_port_enforcer.handle_port_status_event_sync(
watch_1, PI_PORT_STATUS_DOWN);
EXPECT_CALL(
*mock, action_prof_group_deactivate_member(act_prof_id, grp_h, mbr_h));
EXPECT_OK(watch_port_enforcer.add_member_and_update_hw(
&ap, grp_h, mbr_h, watch_1));
// down -> up
EXPECT_CALL(
*mock, action_prof_group_activate_member(act_prof_id, grp_h, mbr_h));
EXPECT_OK(watch_port_enforcer.modify_member_and_update_hw(
&ap, grp_h, mbr_h, watch_1, watch_2));
// up -> down
EXPECT_CALL(
*mock, action_prof_group_deactivate_member(act_prof_id, grp_h, mbr_h));
EXPECT_OK(watch_port_enforcer.modify_member_and_update_hw(
&ap, grp_h, mbr_h, watch_2, watch_1));
EXPECT_OK(watch_port_enforcer.delete_member(
act_prof_id, grp_h, mbr_h, watch_1));
watch_port_enforcer.handle_port_status_event_sync(
watch_1, PI_PORT_STATUS_UP);
EXPECT_OK(watch_port_enforcer.add_member_and_update_hw(
&ap, grp_h, mbr_h, watch_1));
}
TEST_F(WatchPortEnforcerTest, PortStatusEvents) {
std::vector<pi_indirect_handle_t> mbrs(numPorts);
pi_indirect_handle_t mbr_h = 0;
std::generate(mbrs.begin(), mbrs.end(), [&mbr_h] { return mbr_h++; });
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_id, grp_h, mbrs[i], port));
}
EXPECT_CALL(*mock, action_prof_group_deactivate_member(act_prof_id, grp_h, _))
.Times(numPorts);
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
watch_port_enforcer.handle_port_status_event_sync(
port, PI_PORT_STATUS_DOWN);
}
EXPECT_CALL(*mock, action_prof_group_activate_member(act_prof_id, grp_h, _))
.Times(numPorts);
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
watch_port_enforcer.handle_port_status_event_sync(
port, PI_PORT_STATUS_UP);
}
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
EXPECT_OK(watch_port_enforcer.delete_member(
act_prof_id, grp_h, mbrs[i], port));
}
}
TEST_F(WatchPortEnforcerTest, ConcurrentRead) {
int x = 0;
auto action = [this, &x] {
std::unique_lock<std::mutex> lock(mutex);
if (x == 0) {
x = 1;
cv.notify_one();
EXPECT_TRUE(cv.wait_for(lock, timeout, [&x] { return x == 0; }));
} else {
x = 0;
cv.notify_one();
}
};
EXPECT_CALL(*mock, action_prof_group_deactivate_member(
act_prof_id, grp_h, mbr_h))
.WillOnce(DoAll(InvokeWithoutArgs(action), Return(PI_STATUS_SUCCESS)));
std::thread thread1([this, &action] {
AccessArbitration::ReadAccess access(&access_arbitration);
action();
});
EXPECT_OK(watch_port_enforcer.add_member(act_prof_id, grp_h, mbr_h, watch_1));
EXPECT_EQ(mock->port_status_set(watch_1, PI_PORT_STATUS_DOWN),
PI_STATUS_SUCCESS);
thread1.join();
}
TEST_F(WatchPortEnforcerTest, ExclusiveWrite) {
int x = 0;
auto action = [this, &x] {
std::unique_lock<std::mutex> lock(mutex);
if (x == 0) {
x = 1;
cv.notify_one();
EXPECT_FALSE(cv.wait_for(lock, timeout, [&x] { return x == 0; }));
} else {
x = 0;
cv.notify_one();
}
};
EXPECT_CALL(*mock, action_prof_group_deactivate_member(
act_prof_id, grp_h, mbr_h))
.WillOnce(DoAll(InvokeWithoutArgs(action), Return(PI_STATUS_SUCCESS)));
std::thread thread1([this, &action] {
AccessArbitration::WriteAccess access(&access_arbitration, act_prof_id);
action();
});
EXPECT_OK(watch_port_enforcer.add_member(act_prof_id, grp_h, mbr_h, watch_1));
EXPECT_EQ(mock->port_status_set(watch_1, PI_PORT_STATUS_DOWN),
PI_STATUS_SUCCESS);
thread1.join();
}
// make sure that there is no deadlock when updating pipeline config
TEST_F(WatchPortEnforcerTest, UpdateConfig) {
EXPECT_OK(watch_port_enforcer.add_member(act_prof_id, grp_h, mbr_h, watch_1));
AccessArbitration::UpdateAccess access(&access_arbitration);
EXPECT_EQ(mock->port_status_set(watch_1, PI_PORT_STATUS_DOWN),
PI_STATUS_SUCCESS);
EXPECT_OK(watch_port_enforcer.p4_change(p4info));
}
using ::testing::WithParamInterface;
using ::testing::Values;
class WatchPortEnforcerNoWriteAccessOneOfTest
: public WatchPortEnforcerTest,
public WithParamInterface<std::tuple<const char *, const char *> > { };
// We test that when there is an ongoing WriteRequest for one action profile,
// port status events can still be processed concurrently for other action
// profiles.
TEST_P(WatchPortEnforcerNoWriteAccessOneOfTest, ConcurrentAccess) {
pi_p4_id_t act_prof_1_id = pi_p4info_act_prof_id_from_name(
p4info, std::get<0>(GetParam()));
pi_p4_id_t act_prof_2_id = pi_p4info_act_prof_id_from_name(
p4info, std::get<1>(GetParam()));
int x = 0;
auto action = [this, &x] {
std::unique_lock<std::mutex> lock(mutex);
if (x == 0) {
x = 1;
cv.notify_one();
EXPECT_TRUE(cv.wait_for(lock, timeout, [&x] { return x == 0; }));
} else {
x = 0;
cv.notify_one();
}
};
EXPECT_CALL(*mock, action_prof_group_deactivate_member(_, grp_h, mbr_h))
.WillOnce(DoAll(InvokeWithoutArgs(action), Return(PI_STATUS_SUCCESS)))
.WillOnce(Return(PI_STATUS_SUCCESS));
std::thread thread1([this, act_prof_1_id, &action] {
AccessArbitration::WriteAccess access(&access_arbitration, act_prof_1_id);
action();
});
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_1_id, grp_h, mbr_h, watch_1));
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_2_id, grp_h, mbr_h, watch_1));
EXPECT_EQ(mock->port_status_set(watch_1, PI_PORT_STATUS_DOWN),
PI_STATUS_SUCCESS);
thread1.join();
}
INSTANTIATE_TEST_CASE_P(
ConcurrentAccess, WatchPortEnforcerNoWriteAccessOneOfTest,
Values(std::make_tuple("ActProfWS", "ActProfWS2"),
std::make_tuple("ActProfWS2", "ActProfWS")));
} // namespace testing
} // namespace proto
} // namespace pi
<commit_msg>Fix one of the WatchPortEnforcer unit tests<commit_after>/* Copyright 2019-present Barefoot Networks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Antonin Bas ([email protected])
*
*/
#include <gmock/gmock.h>
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <tuple>
#include <vector>
#include "PI/frontends/cpp/tables.h"
#include "PI/frontends/proto/device_mgr.h"
#include "PI/int/pi_int.h"
#include "src/access_arbitration.h"
#include "src/common.h"
#include "src/watch_port_enforcer.h"
#include "test_proto_fe_base.h"
namespace pi {
namespace proto {
namespace testing {
using pi::fe::proto::AccessArbitration;
using pi::fe::proto::WatchPortEnforcer;
using ::testing::_;
using ::testing::DoAll;
using ::testing::InvokeWithoutArgs;
using ::testing::Return;
class WatchPortEnforcerTest : public ProtoFrontendBaseTest {
public:
WatchPortEnforcerTest()
: watch_port_enforcer(device_tgt, &access_arbitration) {
act_prof_id = pi_p4info_act_prof_id_from_name(p4info, "ActProfWS");
}
static void SetUpTestCase() {
DeviceMgr::init(256);
std::ifstream istream(input_path);
google::protobuf::io::IstreamInputStream istream_(&istream);
google::protobuf::TextFormat::Parse(&istream_, &p4info_proto);
pi::p4info::p4info_proto_reader(p4info_proto, &p4info);
}
static void TearDownTestCase() {
DeviceMgr::destroy();
}
void SetUp() override {
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
EXPECT_EQ(mock->port_status_set(port, PI_PORT_STATUS_UP),
PI_STATUS_SUCCESS);
}
ASSERT_OK(watch_port_enforcer.p4_change(p4info));
};
mutable std::condition_variable cv;
mutable std::mutex mutex;
static constexpr size_t numPorts = 16;
static constexpr const char *input_path =
TESTDATADIR "/" "unittest.p4info.txt";
static constexpr std::chrono::milliseconds timeout{200};
static pi_p4info_t *p4info;
static p4configv1::P4Info p4info_proto;
AccessArbitration access_arbitration;
WatchPortEnforcer watch_port_enforcer;
pi_p4_id_t act_prof_id;
pi_indirect_handle_t grp_h{10};
pi_indirect_handle_t mbr_h{20};
pi_port_t watch_1{1};
pi_port_t watch_2{2};
};
/* static */ constexpr std::chrono::milliseconds WatchPortEnforcerTest::timeout;
/* static */ pi_p4info_t *WatchPortEnforcerTest::p4info = nullptr;
/* static */ p4configv1::P4Info WatchPortEnforcerTest::p4info_proto;
TEST_F(WatchPortEnforcerTest, DontUpdateHw) {
EXPECT_CALL(*mock, action_prof_group_activate_member(act_prof_id, _, _))
.Times(0);
EXPECT_CALL(*mock, action_prof_group_deactivate_member(act_prof_id, _, _))
.Times(0);
watch_port_enforcer.handle_port_status_event_sync(
watch_1, PI_PORT_STATUS_DOWN);
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_id, grp_h, mbr_h, watch_1));
// down -> up
EXPECT_OK(watch_port_enforcer.modify_member(
act_prof_id, grp_h, mbr_h, watch_1, watch_2));
// up -> down
EXPECT_OK(watch_port_enforcer.modify_member(
act_prof_id, grp_h, mbr_h, watch_2, watch_1));
EXPECT_OK(watch_port_enforcer.delete_member(
act_prof_id, grp_h, mbr_h, watch_1));
watch_port_enforcer.handle_port_status_event_sync(
watch_1, PI_PORT_STATUS_UP);
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_id, grp_h, mbr_h, watch_1));
}
TEST_F(WatchPortEnforcerTest, UpdateHw) {
::pi::fe::proto::common::SessionTemp session;
::pi::ActProf ap(session.get(), device_tgt, p4info, act_prof_id);
watch_port_enforcer.handle_port_status_event_sync(
watch_1, PI_PORT_STATUS_DOWN);
EXPECT_CALL(
*mock, action_prof_group_deactivate_member(act_prof_id, grp_h, mbr_h));
EXPECT_OK(watch_port_enforcer.add_member_and_update_hw(
&ap, grp_h, mbr_h, watch_1));
// down -> up
EXPECT_CALL(
*mock, action_prof_group_activate_member(act_prof_id, grp_h, mbr_h));
EXPECT_OK(watch_port_enforcer.modify_member_and_update_hw(
&ap, grp_h, mbr_h, watch_1, watch_2));
// up -> down
EXPECT_CALL(
*mock, action_prof_group_deactivate_member(act_prof_id, grp_h, mbr_h));
EXPECT_OK(watch_port_enforcer.modify_member_and_update_hw(
&ap, grp_h, mbr_h, watch_2, watch_1));
EXPECT_OK(watch_port_enforcer.delete_member(
act_prof_id, grp_h, mbr_h, watch_1));
watch_port_enforcer.handle_port_status_event_sync(
watch_1, PI_PORT_STATUS_UP);
EXPECT_OK(watch_port_enforcer.add_member_and_update_hw(
&ap, grp_h, mbr_h, watch_1));
}
TEST_F(WatchPortEnforcerTest, PortStatusEvents) {
std::vector<pi_indirect_handle_t> mbrs(numPorts);
pi_indirect_handle_t mbr_h = 0;
std::generate(mbrs.begin(), mbrs.end(), [&mbr_h] { return mbr_h++; });
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_id, grp_h, mbrs[i], port));
}
EXPECT_CALL(*mock, action_prof_group_deactivate_member(act_prof_id, grp_h, _))
.Times(numPorts);
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
watch_port_enforcer.handle_port_status_event_sync(
port, PI_PORT_STATUS_DOWN);
}
EXPECT_CALL(*mock, action_prof_group_activate_member(act_prof_id, grp_h, _))
.Times(numPorts);
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
watch_port_enforcer.handle_port_status_event_sync(
port, PI_PORT_STATUS_UP);
}
for (size_t i = 0; i < numPorts; i++) {
auto port = static_cast<pi_port_t>(i);
EXPECT_OK(watch_port_enforcer.delete_member(
act_prof_id, grp_h, mbrs[i], port));
}
}
TEST_F(WatchPortEnforcerTest, ConcurrentRead) {
int x = 0;
auto action = [this, &x] {
std::unique_lock<std::mutex> lock(mutex);
if (x == 0) {
x = 1;
cv.notify_one();
EXPECT_TRUE(cv.wait_for(lock, timeout, [&x] { return x == 0; }));
} else {
x = 0;
cv.notify_one();
}
};
EXPECT_CALL(*mock, action_prof_group_deactivate_member(
act_prof_id, grp_h, mbr_h))
.WillOnce(DoAll(InvokeWithoutArgs(action), Return(PI_STATUS_SUCCESS)));
std::thread thread1([this, &action] {
AccessArbitration::ReadAccess access(&access_arbitration);
action();
});
EXPECT_OK(watch_port_enforcer.add_member(act_prof_id, grp_h, mbr_h, watch_1));
EXPECT_EQ(mock->port_status_set(watch_1, PI_PORT_STATUS_DOWN),
PI_STATUS_SUCCESS);
thread1.join();
}
TEST_F(WatchPortEnforcerTest, ExclusiveWrite) {
int x = 0;
auto action = [this, &x] {
std::unique_lock<std::mutex> lock(mutex);
if (x == 0) {
x = 1;
cv.notify_one();
EXPECT_FALSE(cv.wait_for(lock, timeout, [&x] { return x == 0; }));
} else {
x = 0;
cv.notify_one();
}
};
EXPECT_CALL(*mock, action_prof_group_deactivate_member(
act_prof_id, grp_h, mbr_h))
.WillOnce(DoAll(InvokeWithoutArgs(action), Return(PI_STATUS_SUCCESS)));
std::thread thread1([this, &action] {
AccessArbitration::WriteAccess access(&access_arbitration, act_prof_id);
action();
});
EXPECT_OK(watch_port_enforcer.add_member(act_prof_id, grp_h, mbr_h, watch_1));
EXPECT_EQ(mock->port_status_set(watch_1, PI_PORT_STATUS_DOWN),
PI_STATUS_SUCCESS);
thread1.join();
}
// make sure that there is no deadlock when updating pipeline config
TEST_F(WatchPortEnforcerTest, UpdateConfig) {
EXPECT_OK(watch_port_enforcer.add_member(act_prof_id, grp_h, mbr_h, watch_1));
AccessArbitration::UpdateAccess access(&access_arbitration);
EXPECT_EQ(mock->port_status_set(watch_1, PI_PORT_STATUS_DOWN),
PI_STATUS_SUCCESS);
EXPECT_OK(watch_port_enforcer.p4_change(p4info));
}
using ::testing::WithParamInterface;
using ::testing::Values;
class WatchPortEnforcerNoWriteAccessOneOfTest
: public WatchPortEnforcerTest,
public WithParamInterface<std::tuple<const char *, const char *> > { };
// We test that when there is an ongoing WriteRequest for one action profile,
// port status events can still be processed concurrently for other action
// profiles.
TEST_P(WatchPortEnforcerNoWriteAccessOneOfTest, ConcurrentAccess) {
pi_p4_id_t act_prof_1_id = pi_p4info_act_prof_id_from_name(
p4info, std::get<0>(GetParam()));
pi_p4_id_t act_prof_2_id = pi_p4info_act_prof_id_from_name(
p4info, std::get<1>(GetParam()));
int x = 0;
auto action = [this, &x] {
std::unique_lock<std::mutex> lock(mutex);
if (x == 0) {
x = 1;
cv.notify_one();
EXPECT_TRUE(cv.wait_for(lock, timeout, [&x] { return x == 0; }));
} else {
x = 0;
cv.notify_one();
}
};
EXPECT_CALL(*mock, action_prof_group_deactivate_member(_, grp_h, mbr_h))
.WillOnce(DoAll(InvokeWithoutArgs(action), Return(PI_STATUS_SUCCESS)))
.WillOnce(Return(PI_STATUS_SUCCESS));
std::thread thread1([this, act_prof_1_id, &action] {
AccessArbitration::WriteAccess access(&access_arbitration, act_prof_1_id);
action();
});
{
std::unique_lock<std::mutex> lock(mutex);
cv.wait(lock, [&x] { return x == 1; });
}
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_1_id, grp_h, mbr_h, watch_1));
EXPECT_OK(watch_port_enforcer.add_member(
act_prof_2_id, grp_h, mbr_h, watch_1));
// Make sure that thread1 has grabbed WriteAccess before we bring the port
// down. Otherwise the WatchPortEnforcer may grab access to act_prof_1 first
// and block thread1. The wait_for would then timeout in thread1 and the test
// would fail.
EXPECT_EQ(mock->port_status_set(watch_1, PI_PORT_STATUS_DOWN),
PI_STATUS_SUCCESS);
thread1.join();
}
INSTANTIATE_TEST_CASE_P(
ConcurrentAccess, WatchPortEnforcerNoWriteAccessOneOfTest,
Values(std::make_tuple("ActProfWS", "ActProfWS2"),
std::make_tuple("ActProfWS2", "ActProfWS")));
} // namespace testing
} // namespace proto
} // namespace pi
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: attributemap.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 20:23:50 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// must be first
#include <canvas/debug.hxx>
#include <attributemap.hxx>
#include <tools.hxx>
namespace presentation
{
namespace internal
{
typedef ValueMap< AttributeType > AnimateAttributeMap;
AttributeType mapAttributeName( const ::rtl::OUString& rAttrName )
{
/** Maps attribute name to AttributeType enum.
String entries are all case-insensitive and MUST
BE STORED lowercase.
String entries MUST BE SORTED in ascending order!
*/
static AnimateAttributeMap::MapEntry lcl_attributeMap[] =
{
{ "charcolor", ATTRIBUTE_CHAR_COLOR },
{ "charfontname", ATTRIBUTE_CHAR_FONT_NAME },
{ "charheight", ATTRIBUTE_CHAR_HEIGHT },
{ "charposture", ATTRIBUTE_CHAR_POSTURE },
// TODO(Q1): This should prolly be changed in PPT import
// { "charrotation", ATTRIBUTE_CHAR_ROTATION },
{ "charrotation", ATTRIBUTE_ROTATE },
{ "charunderline", ATTRIBUTE_CHAR_UNDERLINE },
{ "charweight", ATTRIBUTE_CHAR_WEIGHT },
{ "color", ATTRIBUTE_COLOR },
{ "dimcolor", ATTRIBUTE_DIMCOLOR },
{ "fillcolor", ATTRIBUTE_FILL_COLOR },
{ "fillstyle", ATTRIBUTE_FILL_STYLE },
{ "height", ATTRIBUTE_HEIGHT },
{ "linecolor", ATTRIBUTE_LINE_COLOR },
{ "linestyle", ATTRIBUTE_LINE_STYLE },
{ "opacity", ATTRIBUTE_OPACITY },
{ "rotate", ATTRIBUTE_ROTATE },
{ "skewx", ATTRIBUTE_SKEW_X },
{ "skewy", ATTRIBUTE_SKEW_Y },
{ "visibility", ATTRIBUTE_VISIBILITY },
{ "width", ATTRIBUTE_WIDTH },
{ "x", ATTRIBUTE_POS_X },
{ "y", ATTRIBUTE_POS_Y }
};
static AnimateAttributeMap aMap( lcl_attributeMap,
sizeof(lcl_attributeMap)/sizeof(AnimateAttributeMap::MapEntry),
false );
AttributeType eAttributeType;
// determine the type from the attribute name
if( !aMap.lookup( rAttrName,
eAttributeType ) )
{
OSL_TRACE( "mapAttributeName(): attribute name %s not found in map.",
::rtl::OUStringToOString( rAttrName,
RTL_TEXTENCODING_ASCII_US ).getStr() );
return ATTRIBUTE_INVALID;
}
return eAttributeType;
}
}
}
<commit_msg>INTEGRATION: CWS canvas02 (1.3.4); FILE MERGED 2005/10/19 14:41:25 thb 1.3.4.1: #i48939# Moved ValueMap from slideshow; adapted AttributeMap accordingly; added debug trigger code, which initiates a screen dump, after an animation batch has completed<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: attributemap.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: kz $ $Date: 2005-11-02 14:02:09 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// must be first
#include <canvas/debug.hxx>
#include <canvas/canvastools.hxx>
#include "attributemap.hxx"
#include "tools.hxx"
namespace presentation
{
namespace internal
{
typedef ::canvas::tools::ValueMap< AttributeType > AnimateAttributeMap;
AttributeType mapAttributeName( const ::rtl::OUString& rAttrName )
{
/** Maps attribute name to AttributeType enum.
String entries are all case-insensitive and MUST
BE STORED lowercase.
String entries MUST BE SORTED in ascending order!
*/
static AnimateAttributeMap::MapEntry lcl_attributeMap[] =
{
{ "charcolor", ATTRIBUTE_CHAR_COLOR },
{ "charfontname", ATTRIBUTE_CHAR_FONT_NAME },
{ "charheight", ATTRIBUTE_CHAR_HEIGHT },
{ "charposture", ATTRIBUTE_CHAR_POSTURE },
// TODO(Q1): This should prolly be changed in PPT import
// { "charrotation", ATTRIBUTE_CHAR_ROTATION },
{ "charrotation", ATTRIBUTE_ROTATE },
{ "charunderline", ATTRIBUTE_CHAR_UNDERLINE },
{ "charweight", ATTRIBUTE_CHAR_WEIGHT },
{ "color", ATTRIBUTE_COLOR },
{ "dimcolor", ATTRIBUTE_DIMCOLOR },
{ "fillcolor", ATTRIBUTE_FILL_COLOR },
{ "fillstyle", ATTRIBUTE_FILL_STYLE },
{ "height", ATTRIBUTE_HEIGHT },
{ "linecolor", ATTRIBUTE_LINE_COLOR },
{ "linestyle", ATTRIBUTE_LINE_STYLE },
{ "opacity", ATTRIBUTE_OPACITY },
{ "rotate", ATTRIBUTE_ROTATE },
{ "skewx", ATTRIBUTE_SKEW_X },
{ "skewy", ATTRIBUTE_SKEW_Y },
{ "visibility", ATTRIBUTE_VISIBILITY },
{ "width", ATTRIBUTE_WIDTH },
{ "x", ATTRIBUTE_POS_X },
{ "y", ATTRIBUTE_POS_Y }
};
static AnimateAttributeMap aMap( lcl_attributeMap,
sizeof(lcl_attributeMap)/sizeof(AnimateAttributeMap::MapEntry),
false );
AttributeType eAttributeType;
// determine the type from the attribute name
if( !aMap.lookup( rAttrName,
eAttributeType ) )
{
OSL_TRACE( "mapAttributeName(): attribute name %s not found in map.",
::rtl::OUStringToOString( rAttrName,
RTL_TEXTENCODING_ASCII_US ).getStr() );
return ATTRIBUTE_INVALID;
}
return eAttributeType;
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: pardlg.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:16:22 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "hintids.hxx"
#ifndef _SVX_TABSTPGE_HXX //autogen
#include <svx/tabstpge.hxx>
#endif
#ifndef _SVX_PARAGRPH_HXX //autogen
#include <svx/paragrph.hxx>
#endif
#ifndef _SVX_BACKGRND_HXX
#include <svx/backgrnd.hxx>
#endif
#ifndef _SVX_BORDER_HXX
#include <svx/border.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#ifndef _OFA_HTMLCFG_HXX //autogen
#include <offmgr/htmlcfg.hxx>
#endif
#ifndef _OFF_APP_HXX //autogen
#include <offmgr/app.hxx>
#endif
#ifndef _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_STRINGSISORTDTOR
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
#include "docsh.hxx"
#include "wrtsh.hxx"
#include "frmatr.hxx"
#include "view.hxx"
#include "globals.hrc"
#include "pardlg.hxx"
#include "pagedesc.hxx"
#include "paratr.hxx"
#include "drpcps.hxx"
#include "uitool.hxx"
#include "viewopt.hxx"
#ifndef _NUMPARA_HXX
#include <numpara.hxx>
#endif
#include "chrdlg.hrc"
#include "poolfmt.hrc"
// STATIC DATA -----------------------------------------------------------
SwParaDlg::SwParaDlg(Window *pParent,
SwView& rVw,
const SfxItemSet& rCoreSet,
BYTE nDialogMode,
const String *pTitle,
BOOL bDraw,
UINT16 nDefPage):
SfxTabDialog(pParent, bDraw ? SW_RES(DLG_DRAWPARA) : SW_RES(DLG_PARA),
&rCoreSet, 0 != pTitle),
rView(rVw),
nDlgMode(nDialogMode),
bDrawParaDlg(bDraw)
{
FreeResource();
nHtmlMode = ::GetHtmlMode(rVw.GetDocShell());
BOOL bHtmlMode = nHtmlMode & HTMLMODE_ON;
if(pTitle)
{
// Update des Titels
String aTmp( GetText() );
aTmp += SW_RESSTR(STR_TEXTCOLL_HEADER);
aTmp += *pTitle;
aTmp += ')';
SetText(aTmp);
}
AddTabPage(TP_PARA_STD, SvxStdParagraphTabPage::Create,SvxStdParagraphTabPage::GetRanges);
AddTabPage(TP_PARA_ALIGN, SvxParaAlignTabPage::Create,SvxParaAlignTabPage::GetRanges);
OfaHtmlOptions* pHtmlOpt = OFF_APP()->GetHtmlOptions();
if (!bDrawParaDlg && (!bHtmlMode || pHtmlOpt->IsPrintLayoutExtension()))
AddTabPage(TP_PARA_EXT, SvxExtParagraphTabPage::Create,SvxExtParagraphTabPage::GetRanges);
else
RemoveTabPage(TP_PARA_EXT);
SvtCJKOptions aCJKOptions;
if(!bHtmlMode && aCJKOptions.IsAsianTypographyEnabled())
AddTabPage(TP_PARA_ASIAN, SvxAsianTabPage::Create,SvxAsianTabPage::GetRanges);
else
RemoveTabPage(TP_PARA_ASIAN);
USHORT nWhich(rCoreSet.GetPool()->GetWhich(SID_ATTR_LRSPACE));
BOOL bLRValid = SFX_ITEM_AVAILABLE <= rCoreSet.GetItemState(nWhich);
if(bHtmlMode || !bLRValid)
RemoveTabPage(TP_TABULATOR);
else
AddTabPage(TP_TABULATOR, SvxTabulatorTabPage::Create, SvxTabulatorTabPage::GetRanges);
if (!bDrawParaDlg)
{
if(!(nDlgMode & DLG_ENVELOP))
AddTabPage(TP_NUMPARA, SwParagraphNumTabPage::Create,SwParagraphNumTabPage::GetRanges);
else
RemoveTabPage(TP_NUMPARA);
if(!bHtmlMode || (nHtmlMode & HTMLMODE_FULL_STYLES))
{
AddTabPage(TP_DROPCAPS, SwDropCapsPage::Create, SwDropCapsPage::GetRanges);
AddTabPage(TP_BACKGROUND,SvxBackgroundTabPage::Create, SvxBackgroundTabPage::GetRanges);
}
else
{
RemoveTabPage(TP_DROPCAPS);
RemoveTabPage(TP_BACKGROUND);
}
if(!bHtmlMode || (nHtmlMode & HTMLMODE_PARA_BORDER))
AddTabPage(TP_BORDER, SvxBorderTabPage::Create, SvxBorderTabPage::GetRanges);
else
RemoveTabPage(TP_BORDER);
}
if (nDefPage)
SetCurPageId(nDefPage);
}
__EXPORT SwParaDlg::~SwParaDlg()
{
}
void __EXPORT SwParaDlg::PageCreated(USHORT nId, SfxTabPage& rPage)
{
SwWrtShell& rSh = rView.GetWrtShell();
// Bei Tabellenumrandung kann im Writer kein Schatten eingestellt werden
if (nId == TP_BORDER)
{
((SvxBorderTabPage&) rPage).SetSWMode(SW_BORDER_MODE_PARA);
}
else if( nId == TP_PARA_STD )
{
((SvxStdParagraphTabPage&)rPage).SetPageWidth(
rSh.GetAnyCurRect(RECT_PAGE_PRT).Width());
if (!bDrawParaDlg)
{
((SvxStdParagraphTabPage&)rPage).EnableRegisterMode();
((SvxStdParagraphTabPage&)rPage).EnableAutoFirstLine();
((SvxStdParagraphTabPage&)rPage).EnableAbsLineDist(MM50/2);
((SvxStdParagraphTabPage&)rPage).EnableNegativeMode();
}
}
else if( TP_PARA_ALIGN == nId)
{
if (!bDrawParaDlg)
((SvxParaAlignTabPage&)rPage).EnableJustifyExt();
}
else if( TP_PARA_EXT == nId )
{
// Seitenumbruch nur, wenn der Cursor im Body-Bereich und nicht in
// einer Tabelle steht
const USHORT eType = rSh.GetFrmType(0,TRUE);
if( !(FRMTYPE_BODY & eType) ||
rSh.GetSelectionType() & SwWrtShell::SEL_TBL )
((SvxExtParagraphTabPage&)rPage).DisablePageBreak();
}
else if( TP_DROPCAPS == nId )
{
((SwDropCapsPage&)rPage).SetFormat(FALSE);
}
else if( TP_BACKGROUND == nId )
{
if(!( nHtmlMode & HTMLMODE_ON ) ||
nHtmlMode & HTMLMODE_SOME_STYLES)
((SvxBackgroundTabPage&)rPage).ShowSelector();
}
else if( TP_NUMPARA == nId)
{
((SwParagraphNumTabPage&)rPage).EnableNewStart();
ListBox & rBox = ((SwParagraphNumTabPage&)rPage).GetStyleBox();
SfxStyleSheetBasePool* pPool = rView.GetDocShell()->GetStyleSheetPool();
pPool->SetSearchMask(SFX_STYLE_FAMILY_PSEUDO, SFXSTYLEBIT_ALL);
const SfxStyleSheetBase* pBase = pPool->First();
SvStringsISortDtor aNames;
while(pBase)
{
aNames.Insert(new String(pBase->GetName()));
pBase = pPool->Next();
}
for(USHORT i = 0; i < aNames.Count(); i++)
rBox.InsertEntry(*aNames.GetObject(i));
}
}
<commit_msg>INTEGRATION: CWS dialogdiet (1.5.276); FILE MERGED 2003/12/01 09:07:20 mba 1.5.276.1: #i22972#: options moved from offmgr<commit_after>/*************************************************************************
*
* $RCSfile: pardlg.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2004-02-03 16:35: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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "hintids.hxx"
#ifndef _SVX_TABSTPGE_HXX //autogen
#include <svx/tabstpge.hxx>
#endif
#ifndef _SVX_PARAGRPH_HXX //autogen
#include <svx/paragrph.hxx>
#endif
#ifndef _SVX_BACKGRND_HXX
#include <svx/backgrnd.hxx>
#endif
#ifndef _SVX_BORDER_HXX
#include <svx/border.hxx>
#endif
#ifndef _SVX_HTMLMODE_HXX
#include <svx/htmlmode.hxx>
#endif
#ifndef _SFXSTYLE_HXX //autogen
#include <svtools/style.hxx>
#endif
#include <svx/htmlcfg.hxx>
#ifndef _SVSTDARR_STRINGSISORTDTOR
#define _SVSTDARR_STRINGSISORTDTOR
#include <svtools/svstdarr.hxx>
#endif
#ifndef _SVTOOLS_CJKOPTIONS_HXX
#include <svtools/cjkoptions.hxx>
#endif
#include "docsh.hxx"
#include "wrtsh.hxx"
#include "frmatr.hxx"
#include "view.hxx"
#include "globals.hrc"
#include "pardlg.hxx"
#include "pagedesc.hxx"
#include "paratr.hxx"
#include "drpcps.hxx"
#include "uitool.hxx"
#include "viewopt.hxx"
#ifndef _NUMPARA_HXX
#include <numpara.hxx>
#endif
#include "chrdlg.hrc"
#include "poolfmt.hrc"
// STATIC DATA -----------------------------------------------------------
SwParaDlg::SwParaDlg(Window *pParent,
SwView& rVw,
const SfxItemSet& rCoreSet,
BYTE nDialogMode,
const String *pTitle,
BOOL bDraw,
UINT16 nDefPage):
SfxTabDialog(pParent, bDraw ? SW_RES(DLG_DRAWPARA) : SW_RES(DLG_PARA),
&rCoreSet, 0 != pTitle),
rView(rVw),
nDlgMode(nDialogMode),
bDrawParaDlg(bDraw)
{
FreeResource();
nHtmlMode = ::GetHtmlMode(rVw.GetDocShell());
BOOL bHtmlMode = nHtmlMode & HTMLMODE_ON;
if(pTitle)
{
// Update des Titels
String aTmp( GetText() );
aTmp += SW_RESSTR(STR_TEXTCOLL_HEADER);
aTmp += *pTitle;
aTmp += ')';
SetText(aTmp);
}
AddTabPage(TP_PARA_STD, SvxStdParagraphTabPage::Create,SvxStdParagraphTabPage::GetRanges);
AddTabPage(TP_PARA_ALIGN, SvxParaAlignTabPage::Create,SvxParaAlignTabPage::GetRanges);
SvxHtmlOptions* pHtmlOpt = SvxHtmlOptions::Get();
if (!bDrawParaDlg && (!bHtmlMode || pHtmlOpt->IsPrintLayoutExtension()))
AddTabPage(TP_PARA_EXT, SvxExtParagraphTabPage::Create,SvxExtParagraphTabPage::GetRanges);
else
RemoveTabPage(TP_PARA_EXT);
SvtCJKOptions aCJKOptions;
if(!bHtmlMode && aCJKOptions.IsAsianTypographyEnabled())
AddTabPage(TP_PARA_ASIAN, SvxAsianTabPage::Create,SvxAsianTabPage::GetRanges);
else
RemoveTabPage(TP_PARA_ASIAN);
USHORT nWhich(rCoreSet.GetPool()->GetWhich(SID_ATTR_LRSPACE));
BOOL bLRValid = SFX_ITEM_AVAILABLE <= rCoreSet.GetItemState(nWhich);
if(bHtmlMode || !bLRValid)
RemoveTabPage(TP_TABULATOR);
else
AddTabPage(TP_TABULATOR, SvxTabulatorTabPage::Create, SvxTabulatorTabPage::GetRanges);
if (!bDrawParaDlg)
{
if(!(nDlgMode & DLG_ENVELOP))
AddTabPage(TP_NUMPARA, SwParagraphNumTabPage::Create,SwParagraphNumTabPage::GetRanges);
else
RemoveTabPage(TP_NUMPARA);
if(!bHtmlMode || (nHtmlMode & HTMLMODE_FULL_STYLES))
{
AddTabPage(TP_DROPCAPS, SwDropCapsPage::Create, SwDropCapsPage::GetRanges);
AddTabPage(TP_BACKGROUND,SvxBackgroundTabPage::Create, SvxBackgroundTabPage::GetRanges);
}
else
{
RemoveTabPage(TP_DROPCAPS);
RemoveTabPage(TP_BACKGROUND);
}
if(!bHtmlMode || (nHtmlMode & HTMLMODE_PARA_BORDER))
AddTabPage(TP_BORDER, SvxBorderTabPage::Create, SvxBorderTabPage::GetRanges);
else
RemoveTabPage(TP_BORDER);
}
if (nDefPage)
SetCurPageId(nDefPage);
}
__EXPORT SwParaDlg::~SwParaDlg()
{
}
void __EXPORT SwParaDlg::PageCreated(USHORT nId, SfxTabPage& rPage)
{
SwWrtShell& rSh = rView.GetWrtShell();
// Bei Tabellenumrandung kann im Writer kein Schatten eingestellt werden
if (nId == TP_BORDER)
{
((SvxBorderTabPage&) rPage).SetSWMode(SW_BORDER_MODE_PARA);
}
else if( nId == TP_PARA_STD )
{
((SvxStdParagraphTabPage&)rPage).SetPageWidth(
rSh.GetAnyCurRect(RECT_PAGE_PRT).Width());
if (!bDrawParaDlg)
{
((SvxStdParagraphTabPage&)rPage).EnableRegisterMode();
((SvxStdParagraphTabPage&)rPage).EnableAutoFirstLine();
((SvxStdParagraphTabPage&)rPage).EnableAbsLineDist(MM50/2);
((SvxStdParagraphTabPage&)rPage).EnableNegativeMode();
}
}
else if( TP_PARA_ALIGN == nId)
{
if (!bDrawParaDlg)
((SvxParaAlignTabPage&)rPage).EnableJustifyExt();
}
else if( TP_PARA_EXT == nId )
{
// Seitenumbruch nur, wenn der Cursor im Body-Bereich und nicht in
// einer Tabelle steht
const USHORT eType = rSh.GetFrmType(0,TRUE);
if( !(FRMTYPE_BODY & eType) ||
rSh.GetSelectionType() & SwWrtShell::SEL_TBL )
((SvxExtParagraphTabPage&)rPage).DisablePageBreak();
}
else if( TP_DROPCAPS == nId )
{
((SwDropCapsPage&)rPage).SetFormat(FALSE);
}
else if( TP_BACKGROUND == nId )
{
if(!( nHtmlMode & HTMLMODE_ON ) ||
nHtmlMode & HTMLMODE_SOME_STYLES)
((SvxBackgroundTabPage&)rPage).ShowSelector();
}
else if( TP_NUMPARA == nId)
{
((SwParagraphNumTabPage&)rPage).EnableNewStart();
ListBox & rBox = ((SwParagraphNumTabPage&)rPage).GetStyleBox();
SfxStyleSheetBasePool* pPool = rView.GetDocShell()->GetStyleSheetPool();
pPool->SetSearchMask(SFX_STYLE_FAMILY_PSEUDO, SFXSTYLEBIT_ALL);
const SfxStyleSheetBase* pBase = pPool->First();
SvStringsISortDtor aNames;
while(pBase)
{
aNames.Insert(new String(pBase->GetName()));
pBase = pPool->Next();
}
for(USHORT i = 0; i < aNames.Count(); i++)
rBox.InsertEntry(*aNames.GetObject(i));
}
}
<|endoftext|> |
<commit_before>
/*
* Copyright (C) 2012 - 2013 微蔡 <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <string>
#include <iostream>
#include <boost/make_shared.hpp>
#include <boost/function.hpp>
#include <boost/asio.hpp>
#include <boost/regex.hpp>
#include <boost/urlencode.hpp>
#include <boost/logger.hpp>
#include <avhttp.hpp>
#include <avhttp/async_read_body.hpp>
#include "webqq_impl.hpp"
#include "constant.hpp"
namespace webqq {
namespace qqimpl {
namespace detail {
// qq 登录办法
template<class Handler>
class SYMBOL_HIDDEN check_login_op : boost::asio::coroutine
{
public:
check_login_op( std::shared_ptr<qqimpl::WebQQ> webqq, Handler handler)
: m_webqq( webqq ), m_handler(handler)
{
// 首先登录一下 w.qq.com
stream = std::make_shared<avhttp::http_stream>( boost::ref(m_webqq->get_ioservice()));
m_buffer = std::make_shared<boost::asio::streambuf>();
m_webqq->logger.dbg() << "go w.qq.com";
avhttp::async_read_body( *stream, "http://w.qq.com", * m_buffer, *this );
}
// 在这里实现 QQ 的登录.
void operator()(const boost::system::error_code& ec, std::size_t bytes_transfered)
{
std::string response;
response.resize(bytes_transfered);
m_buffer->sgetn(&response[0], bytes_transfered);
boost::regex ex, ex2;
boost::smatch what;
std::string url;
BOOST_ASIO_CORO_REENTER(this)
{
m_webqq->m_cookie_mgr.save_cookie(*stream);
// 获得版本.
stream = std::make_shared<avhttp::http_stream>( boost::ref(m_webqq->get_ioservice()));
m_buffer = std::make_shared<boost::asio::streambuf>();
m_webqq->logger.dbg() << "Get webqq version from " << LWQQ_URL_VERSION ;
BOOST_ASIO_CORO_YIELD avhttp::async_read_body(
*stream, LWQQ_URL_VERSION, *m_buffer, *this
);
ex.set_expression("ptuiV\\(([0-9]*)\\);");
if(boost::regex_search(response, what, ex))
{
m_webqq->m_version = what[1];
}
m_webqq->logger.info() << "Get webqq version: " << m_webqq->m_version;
// 接着获得验证码.
m_webqq->m_clientid.clear();
m_webqq->m_groups.clear();
m_webqq->m_psessionid.clear();
m_webqq->m_vfwebqq.clear();
m_webqq->m_status = LWQQ_STATUS_OFFLINE;
// 获取 login_sig
stream = std::make_shared<avhttp::http_stream>(boost::ref(m_webqq->get_ioservice()));
m_buffer = std::make_shared<boost::asio::streambuf>();
BOOST_ASIO_CORO_YIELD avhttp::async_read_body(*stream,/*url*/
boost::str(
boost::format("%s?daid=164&target=self&style=5&mibao_css=m_webqq&appid=%s&enable_qlogin=0&s_url=%s&strong_login=1&login_state=10&t=20131024001")
% LWQQ_URL_CHECK_LOGIN_SIG_HOST
% APPID
% avhttp::detail::escape_string(std::string("http://w.qq.com/proxy.html"))
),
*m_buffer,
*this);
// 类似这样的
// 是一个正常的 HTML 文件, 但是内容包含
// g_login_sig=encodeURIComponent("PpbBnX213jzzSH8*xXyySm9qq1jAnP2uo1fXkGaC5t0ZDaxE5MzSR59qh1EhmjqA");
if (boost::regex_search(response, what, boost::regex("g_login_sig *= *encodeURIComponent\\(\"([^\"]*)\"\\);")))
{
m_webqq->m_login_sig = what[1];
}
else if (boost::regex_search(response, what, boost::regex("g_login_sig=encodeURIComponent\\(\"([^\"]*)\"\\);")))
{
m_webqq->m_login_sig = what[1];
}
m_webqq->logger.info() << "Get g_login_sig: " << m_webqq->m_login_sig;
//获取验证码.
stream = std::make_shared<avhttp::http_stream>(boost::ref(m_webqq->get_ioservice()));
m_buffer = std::make_shared<boost::asio::streambuf>();
stream->request_options(
avhttp::request_opts()
(avhttp::http_options::connection, "close")
(avhttp::http_options::referer, "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=16&mibao_css=m_webqq&appid=501004106&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fw.qq.com%2Fproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20131024001")
);
url = boost::str(boost::format("%s%s?pt_tea=1&uin=%s&appid=%s&js_ver=10114&js_type=0&login_sig=%s&u1=%s&r=%.16lf")
% LWQQ_URL_CHECK_HOST
% VCCHECKPATH % m_webqq->m_qqnum % APPID
% m_webqq->m_login_sig
% "http%3A%2F%2Fw.qq.com%2Fproxy.html"
% rand()
);
m_webqq->m_cookie_mgr.get_cookie(url, *stream);
BOOST_ASIO_CORO_YIELD avhttp::async_read_body(*stream, url , *m_buffer, *this);
// 解析验证码,然后带验证码登录.
/**
*
* The http message body has two format:
*
* ptui_checkVC('1','9ed32e3f644d968809e8cbeaaf2cce42de62dfee12c14b74', '\x00\x00\x00\x00\x54\xb3\x3c\x53', 'ptvfsession');
* ptui_checkVC('1','6kn6cK_Xz9skMLUNbxNq3RcG9uYR7-H2','\\x00\\x00\\x00\\x00\\x68\\xe9\\x0b\\x58', 'ptvfsession');
* ptui_checkVC('0','!IJG', '\x00\x00\x00\x00\x54\xb3\x3c\x53', 'ptvfsession');
* The former means we need verify code image and the second
* parameter is vc_type.
* The later means we don't need the verify code image. The second
* parameter is the verify code. The vc_type is in the header
* "Set-Cookie".
*/
ex.set_expression("ptui_checkVC\\('([0-9])',[ ]?'([0-9a-zA-Z!]*)',[ ]?'([0-9a-zA-Z\\\\]*)',[ ]?'([0-9a-zA-Z\\\\]*)'");
ex2.set_expression("ptui_checkVC\\('([0-9])','([_\\-0-9a-zA-Z!]*)','([0-9a-zA-Z\\\\]*)',[ ]?'([0-9a-zA-Z\\\\]*)'");
if (boost::regex_search(response, what, ex) || boost::regex_search(response, what, ex2))
{
std::string type = what[1];
std::string vc = what[2];
m_webqq->m_verifycode.uin = what[3];
std::string vfsession = what[4];
if (!vfsession.empty())
m_webqq->m_ptvfsession = vfsession;
/* We need get the ptvfsession from the header "Set-Cookie" */
if(type == "0")
{
m_webqq->m_cookie_mgr.save_cookie(*stream);
m_webqq->pt_verifysession = stream->http_cookies()["ptvfsession"];
m_handler(boost::system::error_code(), vc);
return;
}
else if(type == "1")
{
m_webqq->get_verify_image(vc , *this);
return;
}
}
// 未知错误.
m_handler(error::make_error_code(error::login_failed_other), std::string());
}
}
void operator()(boost::system::error_code ec, std::string vc)
{
if (!ec)
ec = error::login_check_need_vc;
m_webqq->pt_verifysession = m_webqq->m_cookie_mgr.get_cookie("http://qq.com")["verifysession"];
m_handler(ec, vc);
}
private:
std::shared_ptr<qqimpl::WebQQ> m_webqq;
Handler m_handler;
read_streamptr stream;
std::shared_ptr<boost::asio::streambuf> m_buffer;
};
template<class Handler>
check_login_op<Handler> make_check_login_op(std::shared_ptr<qqimpl::WebQQ> webqq, Handler handler)
{
return check_login_op<Handler>(webqq, handler);
}
} // namespace detail
template<class Handler>
void async_check_login(std::shared_ptr<qqimpl::WebQQ> webqq, Handler handler)
{
detail::make_check_login_op(webqq, handler);
}
} // namespace qqimpl
} // namespace webqq
<commit_msg>fix compile error<commit_after>
/*
* Copyright (C) 2012 - 2013 微蔡 <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
#include <string>
#include <iostream>
#include <boost/make_shared.hpp>
#include <boost/function.hpp>
#include <boost/asio.hpp>
#include <boost/regex.hpp>
#include <boost/urlencode.hpp>
#include <boost/logger.hpp>
#include <avhttp.hpp>
#include <avhttp/async_read_body.hpp>
#include "webqq_impl.hpp"
#include "constant.hpp"
namespace webqq {
namespace qqimpl {
namespace detail {
// qq 登录办法
template<class Handler>
class SYMBOL_HIDDEN check_login_op : boost::asio::coroutine
{
public:
check_login_op( std::shared_ptr<qqimpl::WebQQ> webqq, Handler handler)
: m_webqq( webqq ), m_handler(handler)
{
// 首先登录一下 w.qq.com
stream = std::make_shared<avhttp::http_stream>( boost::ref(m_webqq->get_ioservice()));
m_buffer = std::make_shared<boost::asio::streambuf>();
m_webqq->logger.dbg() << "go w.qq.com";
avhttp::async_read_body( *stream, "http://w.qq.com", * m_buffer, *this );
}
// 在这里实现 QQ 的登录.
void operator()(const boost::system::error_code& ec, std::size_t bytes_transfered)
{
std::string response;
response.resize(bytes_transfered);
m_buffer->sgetn(&response[0], bytes_transfered);
boost::regex ex, ex2;
boost::smatch what;
std::string url;
BOOST_ASIO_CORO_REENTER(this)
{
m_webqq->m_cookie_mgr.save_cookie(*stream);
// 获得版本.
stream = std::make_shared<avhttp::http_stream>( boost::ref(m_webqq->get_ioservice()));
m_buffer = std::make_shared<boost::asio::streambuf>();
m_webqq->logger.dbg() << "Get webqq version from " << LWQQ_URL_VERSION ;
BOOST_ASIO_CORO_YIELD avhttp::async_read_body(
*stream, LWQQ_URL_VERSION, *m_buffer, *this
);
ex.set_expression("ptuiV\\(([0-9]*)\\);");
if(boost::regex_search(response, what, ex))
{
m_webqq->m_version = what[1];
}
m_webqq->logger.info() << "Get webqq version: " << m_webqq->m_version;
// 接着获得验证码.
m_webqq->m_clientid.clear();
m_webqq->m_groups.clear();
m_webqq->m_psessionid.clear();
m_webqq->m_vfwebqq.clear();
m_webqq->m_status = LWQQ_STATUS_OFFLINE;
// 获取 login_sig
stream = std::make_shared<avhttp::http_stream>(boost::ref(m_webqq->get_ioservice()));
m_buffer = std::make_shared<boost::asio::streambuf>();
BOOST_ASIO_CORO_YIELD avhttp::async_read_body(*stream,/*url*/
boost::str(
boost::format("%s?daid=164&target=self&style=5&mibao_css=m_webqq&appid=%s&enable_qlogin=0&s_url=%s&strong_login=1&login_state=10&t=20131024001")
% LWQQ_URL_CHECK_LOGIN_SIG_HOST
% APPID
% avhttp::detail::escape_string(std::string("http://w.qq.com/proxy.html"))
),
*m_buffer,
*this);
// 类似这样的
// 是一个正常的 HTML 文件, 但是内容包含
// g_login_sig=encodeURIComponent("PpbBnX213jzzSH8*xXyySm9qq1jAnP2uo1fXkGaC5t0ZDaxE5MzSR59qh1EhmjqA");
if (boost::regex_search(response, what, boost::regex("g_login_sig *= *encodeURIComponent\\(\"([^\"]*)\"\\);")))
{
m_webqq->m_login_sig = what[1];
}
else if (boost::regex_search(response, what, boost::regex("g_login_sig=encodeURIComponent\\(\"([^\"]*)\"\\);")))
{
m_webqq->m_login_sig = what[1];
}
m_webqq->logger.info() << "Get g_login_sig: " << m_webqq->m_login_sig;
//获取验证码.
stream = std::make_shared<avhttp::http_stream>(boost::ref(m_webqq->get_ioservice()));
m_buffer = std::make_shared<boost::asio::streambuf>();
stream->request_options(
avhttp::request_opts()
(avhttp::http_options::connection, "close")
(avhttp::http_options::referer, "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=16&mibao_css=m_webqq&appid=501004106&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fw.qq.com%2Fproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20131024001")
);
url = boost::str(boost::format("%s%s?pt_tea=1&uin=%s&appid=%s&js_ver=10114&js_type=0&login_sig=%s&u1=%s&r=%.16lf")
% LWQQ_URL_CHECK_HOST
% VCCHECKPATH % m_webqq->m_qqnum % APPID
% m_webqq->m_login_sig
% "http%3A%2F%2Fw.qq.com%2Fproxy.html"
% rand()
);
m_webqq->m_cookie_mgr.get_cookie(url, *stream);
BOOST_ASIO_CORO_YIELD avhttp::async_read_body(*stream, url , *m_buffer, *this);
// 解析验证码,然后带验证码登录.
/**
*
* The http message body has two format:
*
* ptui_checkVC('1','9ed32e3f644d968809e8cbeaaf2cce42de62dfee12c14b74', '\x00\x00\x00\x00\x54\xb3\x3c\x53', 'ptvfsession');
* ptui_checkVC('1','6kn6cK_Xz9skMLUNbxNq3RcG9uYR7-H2','\\x00\\x00\\x00\\x00\\x68\\xe9\\x0b\\x58', 'ptvfsession');
* ptui_checkVC('0','!IJG', '\x00\x00\x00\x00\x54\xb3\x3c\x53', 'ptvfsession');
* The former means we need verify code image and the second
* parameter is vc_type.
* The later means we don't need the verify code image. The second
* parameter is the verify code. The vc_type is in the header
* "Set-Cookie".
*/
ex.set_expression("ptui_checkVC\\('([0-9])',[ ]?'([0-9a-zA-Z!]*)',[ ]?'([0-9a-zA-Z\\\\]*)',[ ]?'([0-9a-zA-Z\\\\]*)'");
ex2.set_expression("ptui_checkVC\\('([0-9])','([_\\-0-9a-zA-Z!]*)','([0-9a-zA-Z\\\\]*)',[ ]?'([0-9a-zA-Z\\\\]*)'");
if (boost::regex_search(response, what, ex) || boost::regex_search(response, what, ex2))
{
std::string type = what[1];
std::string vc = what[2];
m_webqq->m_verifycode.uin = what[3];
std::string vfsession = what[4];
if (!vfsession.empty())
m_webqq->pt_verifysession = vfsession;
/* We need get the ptvfsession from the header "Set-Cookie" */
if(type == "0")
{
m_webqq->m_cookie_mgr.save_cookie(*stream);
m_webqq->pt_verifysession = stream->http_cookies()["ptvfsession"];
m_handler(boost::system::error_code(), vc);
return;
}
else if(type == "1")
{
m_webqq->get_verify_image(vc , *this);
return;
}
}
// 未知错误.
m_handler(error::make_error_code(error::login_failed_other), std::string());
}
}
void operator()(boost::system::error_code ec, std::string vc)
{
if (!ec)
ec = error::login_check_need_vc;
m_webqq->pt_verifysession = m_webqq->m_cookie_mgr.get_cookie("http://qq.com")["verifysession"];
m_handler(ec, vc);
}
private:
std::shared_ptr<qqimpl::WebQQ> m_webqq;
Handler m_handler;
read_streamptr stream;
std::shared_ptr<boost::asio::streambuf> m_buffer;
};
template<class Handler>
check_login_op<Handler> make_check_login_op(std::shared_ptr<qqimpl::WebQQ> webqq, Handler handler)
{
return check_login_op<Handler>(webqq, handler);
}
} // namespace detail
template<class Handler>
void async_check_login(std::shared_ptr<qqimpl::WebQQ> webqq, Handler handler)
{
detail::make_check_login_op(webqq, handler);
}
} // namespace qqimpl
} // namespace webqq
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: edtwin3.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: os $ $Date: 2002-06-12 08:46:07 $
*
* 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 PRECOMPILED
#include "ui_pch.hxx"
#endif
#pragma hdrstop
#include <hintids.hxx>
#include "uiparam.hxx"
#ifndef _SV_SETTINGS_HXX
#include <vcl/settings.hxx>
#endif
#ifndef _SVX_RULER_HXX //autogen
#include <svx/ruler.hxx>
#endif
#ifndef _VIEWOPT_HXX //autogen
#include <viewopt.hxx>
#endif
#include "view.hxx"
#include "wrtsh.hxx"
#include "basesh.hxx"
#include "pview.hxx"
#include "mdiexp.hxx"
#include "edtwin.hxx"
#include "swmodule.hxx"
#include "modcfg.hxx"
#include "swtable.hxx"
#include "docsh.hxx"
#include "pagedesc.hxx" // Aktuelles Seitenformat
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _SVX_FRMDIRITEM_HXX
#include <svx/frmdiritem.hxx>
#endif
/*--------------------------------------------------------------------
Beschreibung: Core-Notify
--------------------------------------------------------------------*/
void ScrollMDI( ViewShell* pVwSh, const SwRect &rRect,
USHORT nRangeX, USHORT nRangeY)
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if (pSfxVwSh && pSfxVwSh->ISA(SwView))
((SwView *)pSfxVwSh)->Scroll( rRect.SVRect(), nRangeX, nRangeY );
}
/*--------------------------------------------------------------------
Beschreibung: Docmdi - verschiebbar
--------------------------------------------------------------------*/
BOOL IsScrollMDI( ViewShell* pVwSh, const SwRect &rRect )
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if (pSfxVwSh && pSfxVwSh->ISA(SwView))
return (((SwView *)pSfxVwSh)->IsScroll(rRect.SVRect()));
return FALSE;
}
/*--------------------------------------------------------------------
Beschreibung: Notify fuer Groessen-Aenderung
--------------------------------------------------------------------*/
void SizeNotify(ViewShell* pVwSh, const Size &rSize)
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if (pSfxVwSh)
{
if (pSfxVwSh->ISA(SwView))
((SwView *)pSfxVwSh)->DocSzChgd(rSize);
else if (pSfxVwSh->ISA(SwPagePreView))
((SwPagePreView *)pSfxVwSh)->DocSzChgd( rSize );
}
}
/*--------------------------------------------------------------------
Beschreibung: Notify fuer Seitenzahl-Update
--------------------------------------------------------------------*/
void PageNumNotify( ViewShell* pVwSh, USHORT nPhyNum, USHORT nVirtNum,
const String& rPgStr)
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if ( pSfxVwSh && pSfxVwSh->ISA(SwView) &&
((SwView*)pSfxVwSh)->GetCurShell() )
((SwView *)pSfxVwSh)->UpdatePageNums(nPhyNum, nVirtNum, rPgStr);
}
/******************************************************************************
* Methode : void FrameNotify( DocMDIBase *pWin, FlyMode eMode )
* Beschreibung:
* Erstellt : OK 08.02.94 13:49
* Aenderung :
******************************************************************************/
void FrameNotify( ViewShell* pVwSh, FlyMode eMode )
{
if ( pVwSh->ISA(SwCrsrShell) )
SwBaseShell::SetFrmMode( eMode, (SwWrtShell*)pVwSh );
}
/*--------------------------------------------------------------------
Beschreibung: Notify fuer Seitenzahl-Update
--------------------------------------------------------------------*/
BOOL SwEditWin::RulerColumnDrag( SwView& rView , const MouseEvent& rMEvt, BOOL bVerticalMode)
{
SvxRuler& rRuler = bVerticalMode ? rView.GetVLineal() : rView.GetHLineal();
return (!rRuler.StartDocDrag( rMEvt, RULER_TYPE_BORDER ) &&
!rRuler.StartDocDrag( rMEvt, RULER_TYPE_MARGIN1) &&
!rRuler.StartDocDrag( rMEvt, RULER_TYPE_MARGIN2));
}
Dialog* GetSearchDialog()
{
return SwView::GetSearchDialog();
}
void JavaScriptScrollMDI( SfxFrame* pFrame, INT32 nX, INT32 nY )
{
SfxViewShell *pSfxVwSh = pFrame->GetCurrentViewFrame()->GetViewShell();
if( pSfxVwSh && pSfxVwSh->ISA( SwView ))
{
SwView* pView = (SwView *)pSfxVwSh;
Size aSz( nX, nY );
aSz = pView->GetEditWin().PixelToLogic( aSz );
Point aTopLeft( aSz.Width(), aSz.Height() );
if( aTopLeft.X() < DOCUMENTBORDER ) aTopLeft.X() = DOCUMENTBORDER;
if( aTopLeft.Y() < DOCUMENTBORDER ) aTopLeft.Y() = DOCUMENTBORDER;
const Size& rVisSize = pView->GetVisArea().GetSize();
Size aDocSize( pView->GetDocSz() );
aDocSize.Width() += DOCUMENTBORDER;
aDocSize.Height() += DOCUMENTBORDER;
if( aTopLeft.X() + rVisSize.Width() > aDocSize.Width() )
aTopLeft.X() = rVisSize.Width() > aDocSize.Width()
? DOCUMENTBORDER
: aDocSize.Width() - rVisSize.Width();
if( aTopLeft.Y() + rVisSize.Height() > aDocSize.Height() )
aTopLeft.Y() = rVisSize.Height() > aDocSize.Height()
? DOCUMENTBORDER
: aDocSize.Height() - rVisSize.Height();
pView->SetVisArea( aTopLeft );
}
}
USHORT GetTblChgDefaultMode()
{
SwModuleOptions* pOpt = SW_MOD()->GetModuleConfig();
return pOpt ? pOpt->GetTblMode() : TBLVAR_CHGABS;
}
void RepaintPagePreview( ViewShell* pVwSh, const SwRect& rRect )
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if (pSfxVwSh && pSfxVwSh->ISA( SwPagePreView ))
((SwPagePreView *)pSfxVwSh)->RepaintCoreRect( rRect );
}
BOOL JumpToSwMark( ViewShell* pVwSh, const String& rMark )
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if( pSfxVwSh && pSfxVwSh->ISA( SwView ) )
return ((SwView *)pSfxVwSh)->JumpToSwMark( rMark );
return FALSE;
}
void SwEditWin::DataChanged( const DataChangedEvent& rDCEvt )
{
Window::DataChanged( rDCEvt );
SwWrtShell* pSh = GetView().GetWrtShellPtr();
//#99906# DataChanged() is sometimes called prior to creating
// the SwWrtShell
if(!pSh)
return;
BOOL bViewWasLocked = pSh->IsViewLocked(), bUnlockPaint = FALSE;
pSh->LockView( TRUE );
switch( rDCEvt.GetType() )
{
case DATACHANGED_SETTINGS:
// ScrollBars neu anordnen bzw. Resize ausloesen, da sich
// ScrollBar-Groesse geaendert haben kann. Dazu muss dann im
// Resize-Handler aber auch die Groesse der ScrollBars aus
// den Settings abgefragt werden.
if( rDCEvt.GetFlags() & SETTINGS_STYLE )
{
pSh->LockPaint();
bUnlockPaint = TRUE;
GetView().InvalidateBorder(); //Scrollbarbreiten
}
break;
case DATACHANGED_PRINTER:
case DATACHANGED_DISPLAY:
case DATACHANGED_FONTS:
case DATACHANGED_FONTSUBSTITUTION:
pSh->LockPaint();
bUnlockPaint = TRUE;
GetView().GetDocShell()->UpdateFontList(); //z.B. Druckerwechsel
break;
}
pSh->LockView( bViewWasLocked );
if( bUnlockPaint )
pSh->UnlockPaint();
}
<commit_msg>INTEGRATION: CWS os8 (1.5.146); FILE MERGED 2003/04/03 07:14:01 os 1.5.146.1: #108583# precompiled headers removed<commit_after>/*************************************************************************
*
* $RCSfile: edtwin3.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:23:31 $
*
* 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): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include <hintids.hxx>
#include "uiparam.hxx"
#ifndef _SV_SETTINGS_HXX
#include <vcl/settings.hxx>
#endif
#ifndef _SVX_RULER_HXX //autogen
#include <svx/ruler.hxx>
#endif
#ifndef _VIEWOPT_HXX //autogen
#include <viewopt.hxx>
#endif
#include "view.hxx"
#include "wrtsh.hxx"
#include "basesh.hxx"
#include "pview.hxx"
#include "mdiexp.hxx"
#include "edtwin.hxx"
#include "swmodule.hxx"
#include "modcfg.hxx"
#include "swtable.hxx"
#include "docsh.hxx"
#include "pagedesc.hxx" // Aktuelles Seitenformat
#ifndef _FRMATR_HXX
#include <frmatr.hxx>
#endif
#ifndef _SVX_FRMDIRITEM_HXX
#include <svx/frmdiritem.hxx>
#endif
/*--------------------------------------------------------------------
Beschreibung: Core-Notify
--------------------------------------------------------------------*/
void ScrollMDI( ViewShell* pVwSh, const SwRect &rRect,
USHORT nRangeX, USHORT nRangeY)
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if (pSfxVwSh && pSfxVwSh->ISA(SwView))
((SwView *)pSfxVwSh)->Scroll( rRect.SVRect(), nRangeX, nRangeY );
}
/*--------------------------------------------------------------------
Beschreibung: Docmdi - verschiebbar
--------------------------------------------------------------------*/
BOOL IsScrollMDI( ViewShell* pVwSh, const SwRect &rRect )
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if (pSfxVwSh && pSfxVwSh->ISA(SwView))
return (((SwView *)pSfxVwSh)->IsScroll(rRect.SVRect()));
return FALSE;
}
/*--------------------------------------------------------------------
Beschreibung: Notify fuer Groessen-Aenderung
--------------------------------------------------------------------*/
void SizeNotify(ViewShell* pVwSh, const Size &rSize)
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if (pSfxVwSh)
{
if (pSfxVwSh->ISA(SwView))
((SwView *)pSfxVwSh)->DocSzChgd(rSize);
else if (pSfxVwSh->ISA(SwPagePreView))
((SwPagePreView *)pSfxVwSh)->DocSzChgd( rSize );
}
}
/*--------------------------------------------------------------------
Beschreibung: Notify fuer Seitenzahl-Update
--------------------------------------------------------------------*/
void PageNumNotify( ViewShell* pVwSh, USHORT nPhyNum, USHORT nVirtNum,
const String& rPgStr)
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if ( pSfxVwSh && pSfxVwSh->ISA(SwView) &&
((SwView*)pSfxVwSh)->GetCurShell() )
((SwView *)pSfxVwSh)->UpdatePageNums(nPhyNum, nVirtNum, rPgStr);
}
/******************************************************************************
* Methode : void FrameNotify( DocMDIBase *pWin, FlyMode eMode )
* Beschreibung:
* Erstellt : OK 08.02.94 13:49
* Aenderung :
******************************************************************************/
void FrameNotify( ViewShell* pVwSh, FlyMode eMode )
{
if ( pVwSh->ISA(SwCrsrShell) )
SwBaseShell::SetFrmMode( eMode, (SwWrtShell*)pVwSh );
}
/*--------------------------------------------------------------------
Beschreibung: Notify fuer Seitenzahl-Update
--------------------------------------------------------------------*/
BOOL SwEditWin::RulerColumnDrag( SwView& rView , const MouseEvent& rMEvt, BOOL bVerticalMode)
{
SvxRuler& rRuler = bVerticalMode ? rView.GetVLineal() : rView.GetHLineal();
return (!rRuler.StartDocDrag( rMEvt, RULER_TYPE_BORDER ) &&
!rRuler.StartDocDrag( rMEvt, RULER_TYPE_MARGIN1) &&
!rRuler.StartDocDrag( rMEvt, RULER_TYPE_MARGIN2));
}
Dialog* GetSearchDialog()
{
return SwView::GetSearchDialog();
}
void JavaScriptScrollMDI( SfxFrame* pFrame, INT32 nX, INT32 nY )
{
SfxViewShell *pSfxVwSh = pFrame->GetCurrentViewFrame()->GetViewShell();
if( pSfxVwSh && pSfxVwSh->ISA( SwView ))
{
SwView* pView = (SwView *)pSfxVwSh;
Size aSz( nX, nY );
aSz = pView->GetEditWin().PixelToLogic( aSz );
Point aTopLeft( aSz.Width(), aSz.Height() );
if( aTopLeft.X() < DOCUMENTBORDER ) aTopLeft.X() = DOCUMENTBORDER;
if( aTopLeft.Y() < DOCUMENTBORDER ) aTopLeft.Y() = DOCUMENTBORDER;
const Size& rVisSize = pView->GetVisArea().GetSize();
Size aDocSize( pView->GetDocSz() );
aDocSize.Width() += DOCUMENTBORDER;
aDocSize.Height() += DOCUMENTBORDER;
if( aTopLeft.X() + rVisSize.Width() > aDocSize.Width() )
aTopLeft.X() = rVisSize.Width() > aDocSize.Width()
? DOCUMENTBORDER
: aDocSize.Width() - rVisSize.Width();
if( aTopLeft.Y() + rVisSize.Height() > aDocSize.Height() )
aTopLeft.Y() = rVisSize.Height() > aDocSize.Height()
? DOCUMENTBORDER
: aDocSize.Height() - rVisSize.Height();
pView->SetVisArea( aTopLeft );
}
}
USHORT GetTblChgDefaultMode()
{
SwModuleOptions* pOpt = SW_MOD()->GetModuleConfig();
return pOpt ? pOpt->GetTblMode() : TBLVAR_CHGABS;
}
void RepaintPagePreview( ViewShell* pVwSh, const SwRect& rRect )
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if (pSfxVwSh && pSfxVwSh->ISA( SwPagePreView ))
((SwPagePreView *)pSfxVwSh)->RepaintCoreRect( rRect );
}
BOOL JumpToSwMark( ViewShell* pVwSh, const String& rMark )
{
SfxViewShell *pSfxVwSh = pVwSh->GetSfxViewShell();
if( pSfxVwSh && pSfxVwSh->ISA( SwView ) )
return ((SwView *)pSfxVwSh)->JumpToSwMark( rMark );
return FALSE;
}
void SwEditWin::DataChanged( const DataChangedEvent& rDCEvt )
{
Window::DataChanged( rDCEvt );
SwWrtShell* pSh = GetView().GetWrtShellPtr();
//#99906# DataChanged() is sometimes called prior to creating
// the SwWrtShell
if(!pSh)
return;
BOOL bViewWasLocked = pSh->IsViewLocked(), bUnlockPaint = FALSE;
pSh->LockView( TRUE );
switch( rDCEvt.GetType() )
{
case DATACHANGED_SETTINGS:
// ScrollBars neu anordnen bzw. Resize ausloesen, da sich
// ScrollBar-Groesse geaendert haben kann. Dazu muss dann im
// Resize-Handler aber auch die Groesse der ScrollBars aus
// den Settings abgefragt werden.
if( rDCEvt.GetFlags() & SETTINGS_STYLE )
{
pSh->LockPaint();
bUnlockPaint = TRUE;
GetView().InvalidateBorder(); //Scrollbarbreiten
}
break;
case DATACHANGED_PRINTER:
case DATACHANGED_DISPLAY:
case DATACHANGED_FONTS:
case DATACHANGED_FONTSUBSTITUTION:
pSh->LockPaint();
bUnlockPaint = TRUE;
GetView().GetDocShell()->UpdateFontList(); //z.B. Druckerwechsel
break;
}
pSh->LockView( bViewWasLocked );
if( bUnlockPaint )
pSh->UnlockPaint();
}
<|endoftext|> |
<commit_before>/******************************************************************************\
* File: support.cpp
* Purpose: Implementation of support classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2008 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/stockitem.h> // for wxGetStockLabel
#ifndef __WXMSW__
#include "appl.xpm"
#endif
#include "support.h"
#include "defs.h"
Frame::Frame(const wxString& project_wildcard)
: ftFrame(
NULL,
wxID_ANY,
wxTheApp->GetAppName(), //title
NUMBER_RECENT_FILES, //maxFiles
4, // maxProjects
project_wildcard)
{
SetIcon(wxICON(appl));
std::vector<exPane> panes;
panes.push_back(exPane("PaneText", -3));
panes.push_back(exPane("PaneFileType", 50, _("File Type")));
panes.push_back(exPane("PaneLines", 100, _("Lines")));
// Add the lexer pane only if we have lexers.
if (!exApp::GetLexers()->Get().empty())
{
#ifdef __WXMSW__
const int lexer_size = 60;
#else
const int lexer_size = 75;
#endif
panes.push_back(exPane("PaneLexer", lexer_size, _("Lexer")));
}
panes.push_back(exPane("PaneItems", 65, _("Items")));
SetupStatusBar(panes);
wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE); // wxMB_DOCKABLE only used for GTK
SetMenuBar(menubar);
exMenu *menuFile = new exMenu();
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
menuFile->Append(ID_OPEN_LEXERS, _("Open &Lexers"));
menuFile->Append(ID_OPEN_LOGFILE, _("Open &Logfile"));
menuFile->Append(wxID_CLOSE);
menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->Append(ID_ALL_STC_PRINT, exEllipsed(_("Print A&ll")), wxEmptyString, wxITEM_NORMAL, NULL, wxART_PRINT);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
exMenu *menuEdit = new exMenu();
menuEdit->Append(wxID_UNDO);
menuEdit->Append(wxID_REDO);
menuEdit->AppendSeparator();
menuEdit->Append(wxID_CUT);
menuEdit->Append(wxID_COPY);
menuEdit->Append(wxID_PASTE);
menuEdit->AppendSeparator();
menuEdit->Append(wxID_FIND);
menuEdit->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3"));
menuEdit->Append(wxID_REPLACE);
menuEdit->Append(ID_SPECIAL_FIND_IN_FILES, exEllipsed(_("Find &In Files")));
menuEdit->AppendSeparator();
menuEdit->AppendTools(ID_STC_TOOL_MENU);
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_GOTO, exEllipsed(_("&Goto"), "Ctrl+G"));
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_CONTROL_CHAR, exEllipsed(_("&Control Char"), "Ctrl+H"));
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
menuEdit->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
menuEdit->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M"));
exMenu *menuView = new exMenu;
menuView->Append(ID_VIEW_STATUSBAR, _("&Statusbar"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_TOOLBAR, _("&Toolbar"), wxEmptyString, wxITEM_CHECK);
menuView->AppendSeparator();
menuView->Append(ID_VIEW_FILES, _("&Files"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_PROJECTS, _("&Projects"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_DIRCTRL, _("&Explorer"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_OUTPUT, _("&Output"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_ASCII_TABLE, _("&Ascii Table"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_HISTORY, _("&History"), wxEmptyString, wxITEM_CHECK);
#ifdef __WXMSW__
/// \todo Listctrl under GTK and X11 behave differently, items become non-existing by the OnIdle.
wxMenu *menuListView = new wxMenu;
menuListView->Append(wxID_VIEW_LIST, _("&List"), wxEmptyString, wxITEM_CHECK);
menuListView->Append(wxID_VIEW_DETAILS, _("&Detail"), wxEmptyString, wxITEM_CHECK);
menuListView->Append(wxID_VIEW_SMALLICONS, _("&Small Icon"), wxEmptyString, wxITEM_CHECK);
menuView->AppendSeparator();
menuView->Append(ID_VIEW_MENU, _("&Lists"), wxEmptyString, wxITEM_NORMAL, menuListView);
#endif
wxMenu *menuProcess = new wxMenu();
menuProcess->Append(ID_PROCESS_SELECT, exEllipsed(_("&Select")));
menuProcess->AppendSeparator();
menuProcess->Append(ID_PROCESS_RUN, _("&Run"));
menuProcess->Append(wxID_STOP);
exMenu *menuProject = new exMenu();
menuProject->Append(ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxITEM_NORMAL, NULL, wxART_NEW);
menuProject->Append(ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_OPEN);
UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text"));
menuProject->Append(ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE));
menuProject->AppendSeparator();
menuProject->Append(ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE);
menuProject->Append(ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE_AS);
menuProject->AppendSeparator();
menuProject->Append(ID_SORT_SYNC, _("&Auto Sort"), wxEmptyString, wxITEM_CHECK);
wxMenu *menuWindow = new wxMenu();
menuWindow->Append(ID_SPLIT, _("Split"));
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(ID_OPTION_COMPARATOR, exEllipsed(_("Set &Comparator")));
menuOptions->AppendSeparator();
menuOptions->Append(ID_OPTION_LIST_COLOUR, exEllipsed(_("Set &List Colour")));
menuOptions->Append(ID_OPTION_LIST_FONT, exEllipsed(_("Set &List Font")));
wxMenu *menuListSort = new wxMenu;
menuListSort->Append(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"), wxEmptyString, wxITEM_CHECK);
menuListSort->Append(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"), wxEmptyString, wxITEM_CHECK);
menuListSort->Append(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"), wxEmptyString, wxITEM_CHECK);
menuOptions->Append(ID_OPTION_LIST_SORT_MENU, _("Set &List Sort Method"), menuListSort);
menuOptions->AppendSeparator();
menuOptions->Append(ID_OPTION_EDITOR, exEllipsed(_("Set &Editor Options")));
wxMenu *menuHelp = new wxMenu();
// Both wxART_HELP_BOOK, and wxART_HELP_PAGE do not fit nicely on menu item.
menuHelp->Append(wxID_HELP_CONTENTS, _("&Contents"));
menuHelp->AppendSeparator();
menuHelp->Append(wxID_ABOUT);
menubar->Append(menuFile, _("&File"));
menubar->Append(menuEdit, _("&Edit"));
menubar->Append(menuView, _("&View"));
menubar->Append(menuProcess, _("&Process"));
menubar->Append(menuProject, _("&Project"));
menubar->Append(menuWindow, _("&Window"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
m_ToolBar = new exToolBar(this,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
wxNO_BORDER | wxTB_FLAT | wxTB_NODIVIDER);
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
m_ToolBar->AddTool(wxID_PRINT);
m_ToolBar->AddSeparator();
m_ToolBar->AddTool(wxID_FIND);
#ifdef __WXMSW__
const wxSize tbz(150, 20);
#else
const wxSize tbz(150, -1);
#endif
m_ToolBar->AddControl(new ftFind(m_ToolBar, this, ID_FIND_TEXT, wxDefaultPosition, tbz));
m_ToolBar->AddSeparator();
m_ToolBar->AddTool(
ID_PROJECT_OPEN,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
_("Open project..."));
m_ToolBar->AddTool(
ID_PROJECT_SAVE,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
_("Save project"));
#ifdef __WXMSW__
/// \todo See comment above.
m_ToolBar->AddCheckTool(
wxID_VIEW_LIST,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
wxNullBitmap,
_("View in list mode"));
m_ToolBar->AddCheckTool(
wxID_VIEW_DETAILS, wxEmptyString,
wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
wxNullBitmap,
_("View in detail mode"));
#endif
#if wxUSE_CHECKBOX
m_ToolBar->AddSeparator();
#ifndef __WXMSW__
wxSize size(55, 25);
#else
wxSize size = wxDefaultSize;
#endif
m_ToolBar->AddControl(
m_HexModeCheckBox = new wxCheckBox(
m_ToolBar,
ID_EDIT_HEX_MODE,
"Hex",
wxDefaultPosition,
size,
wxNO_BORDER));
m_ToolBar->AddControl(
m_SyncCheckBox = new wxCheckBox(
m_ToolBar,
ID_SYNC_MODE,
"Sync",
wxDefaultPosition,
size,
wxNO_BORDER));
m_HexModeCheckBox->SetToolTip(_("View in hex mode"));
m_HexModeCheckBox->SetValue(exApp::GetConfigBool("HexMode"));
m_SyncCheckBox->SetToolTip(_("Synchronize modified files"));
#endif // wxUSE_CHECKBOX
m_ToolBar->Realize();
}
bool Frame::AllowClose(wxWindowID id, wxWindow* page)
{
if (ftListView::ProcessIsRunning())
return false;
else if (id == NOTEBOOK_EDITORS)
return ((ftSTC*)page)->Continue();
else if (id == NOTEBOOK_PROJECTS)
return ((ftListView*)page)->Continue();
else
return ftFrame::AllowClose(id, page);
}
void Frame::OnNotebook(wxWindowID id, wxWindow* page)
{
if (id == NOTEBOOK_EDITORS)
{
((ftSTC*)page)->PropertiesMessage();
}
else if (id == NOTEBOOK_PROJECTS)
{
SetTitle(wxEmptyString, ((ftListView*)page)->GetFileName().GetName());
exStatusText(((ftListView*)page)->GetFileName());
}
}
<commit_msg>commit depends on local rcs<commit_after>/******************************************************************************\
* File: support.cpp
* Purpose: Implementation of support classes
* Author: Anton van Wezenbeek
* RCS-ID: $Id$
*
* Copyright (c) 1998-2008 Anton van Wezenbeek
* All rights are reserved. Reproduction in whole or part is prohibited
* without the written consent of the copyright owner.
\******************************************************************************/
#include <wx/stockitem.h> // for wxGetStockLabel
#ifndef __WXMSW__
#include "appl.xpm"
#endif
#include "support.h"
#include "defs.h"
Frame::Frame(const wxString& project_wildcard)
: ftFrame(
NULL,
wxID_ANY,
wxTheApp->GetAppName(), //title
NUMBER_RECENT_FILES, //maxFiles
4, // maxProjects
project_wildcard)
{
SetIcon(wxICON(appl));
std::vector<exPane> panes;
panes.push_back(exPane("PaneText", -3));
panes.push_back(exPane("PaneFileType", 50, _("File Type")));
panes.push_back(exPane("PaneLines", 100, _("Lines")));
// Add the lexer pane only if we have lexers.
if (!exApp::GetLexers()->Get().empty())
{
#ifdef __WXMSW__
const int lexer_size = 60;
#else
const int lexer_size = 75;
#endif
panes.push_back(exPane("PaneLexer", lexer_size, _("Lexer")));
}
panes.push_back(exPane("PaneItems", 65, _("Items")));
SetupStatusBar(panes);
wxMenuBar* menubar = new wxMenuBar(wxMB_DOCKABLE); // wxMB_DOCKABLE only used for GTK
SetMenuBar(menubar);
exMenu *menuFile = new exMenu();
menuFile->Append(wxID_NEW);
menuFile->Append(wxID_OPEN);
UseFileHistory(ID_RECENT_FILE_MENU, menuFile);
menuFile->Append(ID_OPEN_LEXERS, _("Open &Lexers"));
menuFile->Append(ID_OPEN_LOGFILE, _("Open &Logfile"));
menuFile->Append(wxID_CLOSE);
menuFile->Append(ID_ALL_STC_CLOSE, _("Close A&ll"));
menuFile->AppendSeparator();
menuFile->Append(wxID_SAVE);
menuFile->Append(wxID_SAVEAS);
menuFile->Append(ID_ALL_STC_SAVE, _("Save A&ll"), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE);
menuFile->AppendSeparator();
menuFile->AppendPrint();
menuFile->Append(ID_ALL_STC_PRINT, exEllipsed(_("Print A&ll")), wxEmptyString, wxITEM_NORMAL, NULL, wxART_PRINT);
menuFile->AppendSeparator();
menuFile->Append(wxID_EXIT);
exMenu *menuEdit = new exMenu();
menuEdit->Append(wxID_UNDO);
menuEdit->Append(wxID_REDO);
menuEdit->AppendSeparator();
menuEdit->Append(wxID_CUT);
menuEdit->Append(wxID_COPY);
menuEdit->Append(wxID_PASTE);
menuEdit->AppendSeparator();
menuEdit->Append(wxID_FIND);
menuEdit->Append(ID_EDIT_FIND_NEXT, _("Find &Next\tF3"));
menuEdit->Append(wxID_REPLACE);
menuEdit->Append(ID_SPECIAL_FIND_IN_FILES, exEllipsed(_("Find &In Files")));
menuEdit->AppendSeparator();
menuEdit->AppendTools(ID_STC_TOOL_MENU);
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_GOTO, exEllipsed(_("&Goto"), "Ctrl+G"));
menuEdit->AppendSeparator();
menuEdit->Append(ID_EDIT_CONTROL_CHAR, exEllipsed(_("&Control Char"), "Ctrl+H"));
menuEdit->AppendSeparator();
#ifndef LOCAL_RCS
menuEdit->Append(ID_COMMIT, _(C&ommit"));
menuEdit->AppendSeparator();
#endif
menuEdit->Append(ID_EDIT_MACRO_START_RECORD, _("Start Record"));
menuEdit->Append(ID_EDIT_MACRO_STOP_RECORD, _("Stop Record"));
menuEdit->Append(ID_EDIT_MACRO_PLAYBACK, _("Playback\tCtrl+M"));
exMenu *menuView = new exMenu;
menuView->Append(ID_VIEW_STATUSBAR, _("&Statusbar"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_TOOLBAR, _("&Toolbar"), wxEmptyString, wxITEM_CHECK);
menuView->AppendSeparator();
menuView->Append(ID_VIEW_FILES, _("&Files"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_PROJECTS, _("&Projects"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_DIRCTRL, _("&Explorer"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_OUTPUT, _("&Output"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_ASCII_TABLE, _("&Ascii Table"), wxEmptyString, wxITEM_CHECK);
menuView->Append(ID_VIEW_HISTORY, _("&History"), wxEmptyString, wxITEM_CHECK);
#ifdef __WXMSW__
/// \todo Listctrl under GTK and X11 behave differently, items become non-existing by the OnIdle.
wxMenu *menuListView = new wxMenu;
menuListView->Append(wxID_VIEW_LIST, _("&List"), wxEmptyString, wxITEM_CHECK);
menuListView->Append(wxID_VIEW_DETAILS, _("&Detail"), wxEmptyString, wxITEM_CHECK);
menuListView->Append(wxID_VIEW_SMALLICONS, _("&Small Icon"), wxEmptyString, wxITEM_CHECK);
menuView->AppendSeparator();
menuView->Append(ID_VIEW_MENU, _("&Lists"), wxEmptyString, wxITEM_NORMAL, menuListView);
#endif
wxMenu *menuProcess = new wxMenu();
menuProcess->Append(ID_PROCESS_SELECT, exEllipsed(_("&Select")));
menuProcess->AppendSeparator();
menuProcess->Append(ID_PROCESS_RUN, _("&Run"));
menuProcess->Append(wxID_STOP);
exMenu *menuProject = new exMenu();
menuProject->Append(ID_PROJECT_NEW, wxGetStockLabel(wxID_NEW), wxEmptyString, wxITEM_NORMAL, NULL, wxART_NEW);
menuProject->Append(ID_PROJECT_OPEN, wxGetStockLabel(wxID_OPEN), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_OPEN);
UseProjectHistory(ID_RECENT_PROJECT_MENU, menuProject);
menuProject->Append(ID_PROJECT_OPENTEXT, _("&Open As Text"));
menuProject->Append(ID_PROJECT_CLOSE, wxGetStockLabel(wxID_CLOSE));
menuProject->AppendSeparator();
menuProject->Append(ID_PROJECT_SAVE, wxGetStockLabel(wxID_SAVE), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE);
menuProject->Append(ID_PROJECT_SAVEAS, wxGetStockLabel(wxID_SAVEAS), wxEmptyString, wxITEM_NORMAL, NULL, wxART_FILE_SAVE_AS);
menuProject->AppendSeparator();
menuProject->Append(ID_SORT_SYNC, _("&Auto Sort"), wxEmptyString, wxITEM_CHECK);
wxMenu *menuWindow = new wxMenu();
menuWindow->Append(ID_SPLIT, _("Split"));
wxMenu* menuOptions = new wxMenu();
menuOptions->Append(ID_OPTION_COMPARATOR, exEllipsed(_("Set &Comparator")));
menuOptions->AppendSeparator();
menuOptions->Append(ID_OPTION_LIST_COLOUR, exEllipsed(_("Set &List Colour")));
menuOptions->Append(ID_OPTION_LIST_FONT, exEllipsed(_("Set &List Font")));
wxMenu *menuListSort = new wxMenu;
menuListSort->Append(ID_OPTION_LIST_SORT_ASCENDING, _("&Ascending"), wxEmptyString, wxITEM_CHECK);
menuListSort->Append(ID_OPTION_LIST_SORT_DESCENDING, _("&Descending"), wxEmptyString, wxITEM_CHECK);
menuListSort->Append(ID_OPTION_LIST_SORT_TOGGLE, _("&Toggle"), wxEmptyString, wxITEM_CHECK);
menuOptions->Append(ID_OPTION_LIST_SORT_MENU, _("Set &List Sort Method"), menuListSort);
menuOptions->AppendSeparator();
menuOptions->Append(ID_OPTION_EDITOR, exEllipsed(_("Set &Editor Options")));
wxMenu *menuHelp = new wxMenu();
// Both wxART_HELP_BOOK, and wxART_HELP_PAGE do not fit nicely on menu item.
menuHelp->Append(wxID_HELP_CONTENTS, _("&Contents"));
menuHelp->AppendSeparator();
menuHelp->Append(wxID_ABOUT);
menubar->Append(menuFile, _("&File"));
menubar->Append(menuEdit, _("&Edit"));
menubar->Append(menuView, _("&View"));
menubar->Append(menuProcess, _("&Process"));
menubar->Append(menuProject, _("&Project"));
menubar->Append(menuWindow, _("&Window"));
menubar->Append(menuOptions, _("&Options"));
menubar->Append(menuHelp, wxGetStockLabel(wxID_HELP));
m_ToolBar = new exToolBar(this,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
wxNO_BORDER | wxTB_FLAT | wxTB_NODIVIDER);
m_ToolBar->AddTool(wxID_OPEN);
m_ToolBar->AddTool(wxID_SAVE);
m_ToolBar->AddTool(wxID_PRINT);
m_ToolBar->AddSeparator();
m_ToolBar->AddTool(wxID_FIND);
#ifdef __WXMSW__
const wxSize tbz(150, 20);
#else
const wxSize tbz(150, -1);
#endif
m_ToolBar->AddControl(new ftFind(m_ToolBar, this, ID_FIND_TEXT, wxDefaultPosition, tbz));
m_ToolBar->AddSeparator();
m_ToolBar->AddTool(
ID_PROJECT_OPEN,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_FILE_OPEN, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
_("Open project..."));
m_ToolBar->AddTool(
ID_PROJECT_SAVE,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_FILE_SAVE, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
_("Save project"));
#ifdef __WXMSW__
/// \todo See comment above.
m_ToolBar->AddCheckTool(
wxID_VIEW_LIST,
wxEmptyString,
wxArtProvider::GetBitmap(wxART_LIST_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
wxNullBitmap,
_("View in list mode"));
m_ToolBar->AddCheckTool(
wxID_VIEW_DETAILS, wxEmptyString,
wxArtProvider::GetBitmap(wxART_REPORT_VIEW, wxART_TOOLBAR, m_ToolBar->GetToolBitmapSize()),
wxNullBitmap,
_("View in detail mode"));
#endif
#if wxUSE_CHECKBOX
m_ToolBar->AddSeparator();
#ifndef __WXMSW__
wxSize size(55, 25);
#else
wxSize size = wxDefaultSize;
#endif
m_ToolBar->AddControl(
m_HexModeCheckBox = new wxCheckBox(
m_ToolBar,
ID_EDIT_HEX_MODE,
"Hex",
wxDefaultPosition,
size,
wxNO_BORDER));
m_ToolBar->AddControl(
m_SyncCheckBox = new wxCheckBox(
m_ToolBar,
ID_SYNC_MODE,
"Sync",
wxDefaultPosition,
size,
wxNO_BORDER));
m_HexModeCheckBox->SetToolTip(_("View in hex mode"));
m_HexModeCheckBox->SetValue(exApp::GetConfigBool("HexMode"));
m_SyncCheckBox->SetToolTip(_("Synchronize modified files"));
#endif // wxUSE_CHECKBOX
m_ToolBar->Realize();
}
bool Frame::AllowClose(wxWindowID id, wxWindow* page)
{
if (ftListView::ProcessIsRunning())
return false;
else if (id == NOTEBOOK_EDITORS)
return ((ftSTC*)page)->Continue();
else if (id == NOTEBOOK_PROJECTS)
return ((ftListView*)page)->Continue();
else
return ftFrame::AllowClose(id, page);
}
void Frame::OnNotebook(wxWindowID id, wxWindow* page)
{
if (id == NOTEBOOK_EDITORS)
{
((ftSTC*)page)->PropertiesMessage();
}
else if (id == NOTEBOOK_PROJECTS)
{
SetTitle(wxEmptyString, ((ftListView*)page)->GetFileName().GetName());
exStatusText(((ftListView*)page)->GetFileName());
}
}
<|endoftext|> |
<commit_before>// Includes
#include "NDataManager.h"
namespace NDataManager
{
// Default initialize all data
TNavData m_navData = {};
TEnvironmentData m_environmentData = {};
TCapeData m_capeData = {};
TThrusterData m_thrusterData = {};
TCameraMountData m_cameraMountData = {};
TControllerData m_controllerData = {};
CTimer m_timer_1hz;
CTimer m_timer_10hz;
uint32_t m_loopsPerSec = 0;
// Called during Setup() to initialize any DataManager members to specific values
void Initialize()
{
Serial.println( "Systems.DataManager.Status:INIT;" );
Serial.println( "Systems.DataManager.Status:READY;" );
}
void OutputNavData()
{
// Print Nav Data on the serial line
Serial.print( F( "hdgd:" ) );
Serial.print( m_navData.HDGD );
Serial.print( ';' );
Serial.print( F( "deap:" ) );
Serial.print( m_navData.DEEP );
Serial.print( ';' );
Serial.print( F( "pitc:" ) );
Serial.print( m_navData.PITC );
Serial.print( ';' );
Serial.print( F( "roll:" ) );
Serial.print( m_navData.ROLL );
Serial.print( ';' );
Serial.print( F( "yaw:" ) );
Serial.print( m_navData.YAW );
Serial.print( ';' );
Serial.print( F( "fthr:" ) );
Serial.print( m_navData.FTHR );
Serial.println( ';' );
}
void OutputSharedData()
{
// Print all other shared data on the serial line
// Thruster Data
Serial.print( F( "motorAttached:" ) );
Serial.print( m_thrusterData.MATC );
Serial.println( ';' );
// Camera Mount Data
Serial.print( F( "servo:" ) );
Serial.print( m_cameraMountData.CMNT );
Serial.print( ';' );
Serial.print( F( "starg:" ) );
Serial.print( m_cameraMountData.CMTG );
Serial.println( ';' );
// Cape Data
Serial.print( F( "fmem:" ) );
Serial.print( m_capeData.FMEM );
Serial.print( ';' );
Serial.print( F( "vout:" ) );
Serial.print( m_capeData.VOUT );
Serial.print( ';' );
Serial.print( F( "iout:" ) );
Serial.print( m_capeData.IOUT );
Serial.print( ';' );
Serial.print( F( "btti:" ) );
Serial.print( m_capeData.BTTI );
Serial.print( ';' );
Serial.print( F( "atmp:" ) );
Serial.print( m_capeData.ATMP );
Serial.print( ';' );
Serial.print( F( "ver:" ) );
Serial.print( F( "CUSTOM_BUILD" ) );
Serial.print( ';' );
Serial.print( F( "cmpd:" ) );
Serial.print( F( __DATE__ ) );
Serial.print( F( ", " ) );
Serial.print( F( __TIME__ ) );
Serial.print( F( ", " ) );
Serial.print( F( __VERSION__ ) );
Serial.print( ';' );
Serial.print( F( "time:" ) );
Serial.print( m_capeData.UTIM );
Serial.println( ';' );
// Environment Data
Serial.print( F( "pres:" ) );
Serial.print( m_environmentData.PRES );
Serial.print( ';' );
Serial.print( F( "temp:" ) );
Serial.print( m_environmentData.TEMP );
Serial.println( ';' );
// Module loop timers in milliseconds
// Serial.print( F( "modtime:" ) );
// for( int i = 0; i < NModuleManager::m_moduleCount; ++i )
// {
// Serial.print( NModuleManager::m_pModules[ i ]->m_name );
// Serial.print( '|' );
// Serial.print( NModuleManager::m_pModules[ i ]->m_executionTime );
// Serial.print( '|' );
// }
// Serial.println( ';' );
//
}
void HandleOutputLoops()
{
++m_loopsPerSec;
// 1Hz update loop
if( m_timer_1hz.HasElapsed( 1000 ) )
{
// Send shared data to beaglebone
OutputSharedData();
// Loops per sec
Serial.print( F( "alps:" ) );
Serial.print( m_loopsPerSec );
Serial.println( ';' );
// Reset loop counter
m_loopsPerSec = 0;
}
// 10Hz Update loop
if( m_timer_10hz.HasElapsed( 100 ) )
{
// Send nav data to beaglebone
OutputNavData();
}
}
}<commit_msg>Fixed depth navdata output label<commit_after>// Includes
#include "NDataManager.h"
namespace NDataManager
{
// Default initialize all data
TNavData m_navData = {};
TEnvironmentData m_environmentData = {};
TCapeData m_capeData = {};
TThrusterData m_thrusterData = {};
TCameraMountData m_cameraMountData = {};
TControllerData m_controllerData = {};
CTimer m_timer_1hz;
CTimer m_timer_10hz;
uint32_t m_loopsPerSec = 0;
// Called during Setup() to initialize any DataManager members to specific values
void Initialize()
{
Serial.println( "Systems.DataManager.Status:INIT;" );
Serial.println( "Systems.DataManager.Status:READY;" );
}
void OutputNavData()
{
// Print Nav Data on the serial line
Serial.print( F( "hdgd:" ) );
Serial.print( m_navData.HDGD );
Serial.print( ';' );
Serial.print( F( "deep:" ) );
Serial.print( m_navData.DEEP );
Serial.print( ';' );
Serial.print( F( "pitc:" ) );
Serial.print( m_navData.PITC );
Serial.print( ';' );
Serial.print( F( "roll:" ) );
Serial.print( m_navData.ROLL );
Serial.print( ';' );
Serial.print( F( "yaw:" ) );
Serial.print( m_navData.YAW );
Serial.print( ';' );
Serial.print( F( "fthr:" ) );
Serial.print( m_navData.FTHR );
Serial.println( ';' );
}
void OutputSharedData()
{
// Print all other shared data on the serial line
// Thruster Data
Serial.print( F( "motorAttached:" ) );
Serial.print( m_thrusterData.MATC );
Serial.println( ';' );
// Camera Mount Data
Serial.print( F( "servo:" ) );
Serial.print( m_cameraMountData.CMNT );
Serial.print( ';' );
Serial.print( F( "starg:" ) );
Serial.print( m_cameraMountData.CMTG );
Serial.println( ';' );
// Cape Data
Serial.print( F( "fmem:" ) );
Serial.print( m_capeData.FMEM );
Serial.print( ';' );
Serial.print( F( "vout:" ) );
Serial.print( m_capeData.VOUT );
Serial.print( ';' );
Serial.print( F( "iout:" ) );
Serial.print( m_capeData.IOUT );
Serial.print( ';' );
Serial.print( F( "btti:" ) );
Serial.print( m_capeData.BTTI );
Serial.print( ';' );
Serial.print( F( "atmp:" ) );
Serial.print( m_capeData.ATMP );
Serial.print( ';' );
Serial.print( F( "ver:" ) );
Serial.print( F( "CUSTOM_BUILD" ) );
Serial.print( ';' );
Serial.print( F( "cmpd:" ) );
Serial.print( F( __DATE__ ) );
Serial.print( F( ", " ) );
Serial.print( F( __TIME__ ) );
Serial.print( F( ", " ) );
Serial.print( F( __VERSION__ ) );
Serial.print( ';' );
Serial.print( F( "time:" ) );
Serial.print( m_capeData.UTIM );
Serial.println( ';' );
// Environment Data
Serial.print( F( "pres:" ) );
Serial.print( m_environmentData.PRES );
Serial.print( ';' );
Serial.print( F( "temp:" ) );
Serial.print( m_environmentData.TEMP );
Serial.println( ';' );
// Module loop timers in milliseconds
// Serial.print( F( "modtime:" ) );
// for( int i = 0; i < NModuleManager::m_moduleCount; ++i )
// {
// Serial.print( NModuleManager::m_pModules[ i ]->m_name );
// Serial.print( '|' );
// Serial.print( NModuleManager::m_pModules[ i ]->m_executionTime );
// Serial.print( '|' );
// }
// Serial.println( ';' );
//
}
void HandleOutputLoops()
{
++m_loopsPerSec;
// 1Hz update loop
if( m_timer_1hz.HasElapsed( 1000 ) )
{
// Send shared data to beaglebone
OutputSharedData();
// Loops per sec
Serial.print( F( "alps:" ) );
Serial.print( m_loopsPerSec );
Serial.println( ';' );
// Reset loop counter
m_loopsPerSec = 0;
}
// 10Hz Update loop
if( m_timer_10hz.HasElapsed( 100 ) )
{
// Send nav data to beaglebone
OutputNavData();
}
}
}<|endoftext|> |
<commit_before>#include <sm/logging/LoggingGlobals.hpp>
#include <sm/logging/StdOutLogger.hpp>
namespace sm {
namespace logging {
LoggingGlobals g_logging_globals;
LoggingGlobals::LoggingGlobals()
{
_logger.reset( new StdOutLogger() );
_level = levels::Info;
enableNamedStream(SMCONSOLE_DEFAULT_NAME);
_globalCharBuffer.resize(4096);
}
LoggingGlobals::~LoggingGlobals()
{
}
void LoggingGlobals::shutdown()
{
_shutting_down = true;
}
/**
* \brief Registers a logging location with the system.
*
* This is used for the case where a logger's verbosity level changes, and we need to reset the enabled status of
* all the logging statements.
* @param loc The location to add
*/
void LoggingGlobals::registerLogLocation(LogLocation* loc) {
boost::mutex::scoped_lock lock(_locations_mutex);
_log_locations.push_back(loc);
}
void LoggingGlobals::checkLogLocationEnabledNoLock(LogLocation* loc) {
loc->_loggerEnabled = loc->_level >= _level && (loc->_streamName.size() == 0 || isNamedStreamEnabled(loc->_streamName));
}
void LoggingGlobals::initializeLogLocation(LogLocation* loc, const std::string& name, Level level){
boost::mutex::scoped_lock lock(_locations_mutex);
if (loc->_initialized)
{
return;
}
loc->_streamName = name;
loc->_level = level;
_log_locations.push_back(loc);
checkLogLocationEnabledNoLock(loc);
loc->_initialized = true;
}
void LoggingGlobals::setLogLocationLevel(LogLocation* loc, Level level)
{
boost::mutex::scoped_lock lock(_locations_mutex);
loc->_level = level;
}
void LoggingGlobals::checkLogLocationEnabled(LogLocation* loc)
{
boost::mutex::scoped_lock lock(_locations_mutex);
checkLogLocationEnabledNoLock(loc);
}
/**
* \brief Tells the system that a logger's level has changed
*
* This must be called if a log4cxx::Logger's level has been changed in the middle of an application run.
* Because of the way the static guard for enablement works, if a logger's level is changed and this
* function is not called, only logging statements which are first hit *after* the change will be correct wrt
* that logger.
*/
void LoggingGlobals::notifyLoggerLevelsChanged()
{
boost::mutex::scoped_lock lock(_locations_mutex);
V_LogLocation::iterator it = _log_locations.begin();
V_LogLocation::iterator end = _log_locations.end();
for ( ; it != end; ++it )
{
LogLocation* loc = *it;
checkLogLocationEnabledNoLock(loc);
}
}
bool LoggingGlobals::isNamedStreamEnabled( const std::string & name ){
boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
std::set< std::string >::iterator it = _namedStreamsEnabled.find(name);
return it != _namedStreamsEnabled.end();
}
void LoggingGlobals::enableNamedStream( const std::string & name ) {
boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
_namedStreamsEnabled.insert(name);
notifyLoggerLevelsChanged();
}
void LoggingGlobals::disableNamedStream( const std::string & name ) {
boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
std::set< std::string >::iterator it = _namedStreamsEnabled.find(name);
if(it != _namedStreamsEnabled.end())
{
_namedStreamsEnabled.erase(it);
notifyLoggerLevelsChanged();
}
}
void LoggingGlobals::vformatToBuffer(const char* fmt, va_list args)
{
#ifdef _MSC_VER
va_list arg_copy = args; // dangerous?
#else
va_list arg_copy;
va_copy(arg_copy, args);
#endif
#ifdef _MSC_VER
size_t total = vsnprintf_s(&_globalCharBuffer[0], _globalCharBuffer.size(), _globalCharBuffer.size(), fmt, args);
#else
size_t total = vsnprintf(&_globalCharBuffer[0], _globalCharBuffer.size(), fmt, args);
#endif
if (total >= _globalCharBuffer.size())
{
_globalCharBuffer.resize(total + 2);
#ifdef _MSC_VER
total = vsnprintf_s(&_globalCharBuffer[0], _globalCharBuffer.size(), _globalCharBuffer.size(), fmt, arg_copy);
#else
total = vsnprintf(&_globalCharBuffer[0], _globalCharBuffer.size(), fmt, arg_copy);
#endif
}
va_end(arg_copy);
}
void LoggingGlobals::formatToBuffer(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vformatToBuffer(fmt, args);
va_end(args);
}
void LoggingGlobals::print(const char * streamName, Level level, const char* file, int line, const char* function, const char* fmt, ...)
{
if (_shutting_down)
return;
if (_printing_thread_id == boost::this_thread::get_id())
{
fprintf(stderr, "Warning: recursive print statement has occurred. Throwing out recursive print.\n");
return;
}
boost::mutex::scoped_lock lock(_print_mutex);
_printing_thread_id = boost::this_thread::get_id();
va_list args;
va_start(args, fmt);
vformatToBuffer(fmt, args);
va_end(args);
try
{
_logger->log( LoggingEvent( streamName, level, file, line, function, &_globalCharBuffer[0], _logger->currentTimeString() ) );
}
catch (std::exception& e)
{
fprintf(stderr, "Caught exception while logging: [%s]\n", e.what());
}
_printing_thread_id = boost::thread::id();
}
void LoggingGlobals::print(const char * streamName, Level level,
vectorstream & ss, const char* file, int line, const char* function)
{
if (_shutting_down)
return;
if (_printing_thread_id == boost::this_thread::get_id())
{
fprintf(stderr, "Warning: recursive print statement has occurred. Throwing out recursive print.\n");
return;
}
std::vector<char> str;
ss.swap_vector(str);
boost::mutex::scoped_lock lock(_print_mutex);
_printing_thread_id = boost::this_thread::get_id();
try
{
_logger->log( LoggingEvent( streamName, level, file, line, function, &str[0], _logger->currentTimeString() ) );
}
catch (std::exception& e)
{
fprintf(stderr, "Caught exception while logging: [%s]\n", e.what());
}
_printing_thread_id = boost::thread::id();
}
sm::logging::levels::Level LoggingGlobals::getLevel()
{
// \todo is this thread safe?
return _level;
}
void LoggingGlobals::setLevel( sm::logging::levels::Level level )
{
// \todo is this thread safe?
if(level != _level)
{
_level = level;
notifyLoggerLevelsChanged();
}
}
void LoggingGlobals::setLogger( boost::shared_ptr<Logger> logger )
{
if(logger.get())
{
_logger = logger;
}
}
boost::shared_ptr<Logger> LoggingGlobals::getLogger()
{
return _logger;
}
sm::logging::levels::Level getLevel()
{
return g_logging_globals.getLevel();
}
void setLevel( sm::logging::levels::Level level )
{
g_logging_globals.setLevel(level);
}
void setLogger( boost::shared_ptr<Logger> logger )
{
g_logging_globals.setLogger(logger);
}
boost::shared_ptr<Logger> getLogger()
{
return g_logging_globals.getLogger();
}
bool isNamedStreamEnabled( const std::string & name )
{
return g_logging_globals.isNamedStreamEnabled( std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
}
void enableNamedStream( const std::string & name )
{
g_logging_globals.enableNamedStream( std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
}
void disableNamedStream( const std::string & name )
{
g_logging_globals.disableNamedStream(std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
}
} // namespace logging
} // namespace sm
<commit_msg>Hopefully got rid of the extra characters in the logging when using streams<commit_after>#include <sm/logging/LoggingGlobals.hpp>
#include <sm/logging/StdOutLogger.hpp>
namespace sm {
namespace logging {
LoggingGlobals g_logging_globals;
LoggingGlobals::LoggingGlobals()
{
_logger.reset( new StdOutLogger() );
_level = levels::Info;
enableNamedStream(SMCONSOLE_DEFAULT_NAME);
_globalCharBuffer.resize(4096);
}
LoggingGlobals::~LoggingGlobals()
{
}
void LoggingGlobals::shutdown()
{
_shutting_down = true;
}
/**
* \brief Registers a logging location with the system.
*
* This is used for the case where a logger's verbosity level changes, and we need to reset the enabled status of
* all the logging statements.
* @param loc The location to add
*/
void LoggingGlobals::registerLogLocation(LogLocation* loc) {
boost::mutex::scoped_lock lock(_locations_mutex);
_log_locations.push_back(loc);
}
void LoggingGlobals::checkLogLocationEnabledNoLock(LogLocation* loc) {
loc->_loggerEnabled = loc->_level >= _level && (loc->_streamName.size() == 0 || isNamedStreamEnabled(loc->_streamName));
}
void LoggingGlobals::initializeLogLocation(LogLocation* loc, const std::string& name, Level level){
boost::mutex::scoped_lock lock(_locations_mutex);
if (loc->_initialized)
{
return;
}
loc->_streamName = name;
loc->_level = level;
_log_locations.push_back(loc);
checkLogLocationEnabledNoLock(loc);
loc->_initialized = true;
}
void LoggingGlobals::setLogLocationLevel(LogLocation* loc, Level level)
{
boost::mutex::scoped_lock lock(_locations_mutex);
loc->_level = level;
}
void LoggingGlobals::checkLogLocationEnabled(LogLocation* loc)
{
boost::mutex::scoped_lock lock(_locations_mutex);
checkLogLocationEnabledNoLock(loc);
}
/**
* \brief Tells the system that a logger's level has changed
*
* This must be called if a log4cxx::Logger's level has been changed in the middle of an application run.
* Because of the way the static guard for enablement works, if a logger's level is changed and this
* function is not called, only logging statements which are first hit *after* the change will be correct wrt
* that logger.
*/
void LoggingGlobals::notifyLoggerLevelsChanged()
{
boost::mutex::scoped_lock lock(_locations_mutex);
V_LogLocation::iterator it = _log_locations.begin();
V_LogLocation::iterator end = _log_locations.end();
for ( ; it != end; ++it )
{
LogLocation* loc = *it;
checkLogLocationEnabledNoLock(loc);
}
}
bool LoggingGlobals::isNamedStreamEnabled( const std::string & name ){
boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
std::set< std::string >::iterator it = _namedStreamsEnabled.find(name);
return it != _namedStreamsEnabled.end();
}
void LoggingGlobals::enableNamedStream( const std::string & name ) {
boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
_namedStreamsEnabled.insert(name);
notifyLoggerLevelsChanged();
}
void LoggingGlobals::disableNamedStream( const std::string & name ) {
boost::recursive_mutex::scoped_lock lock(_named_stream_mutex);
std::set< std::string >::iterator it = _namedStreamsEnabled.find(name);
if(it != _namedStreamsEnabled.end())
{
_namedStreamsEnabled.erase(it);
notifyLoggerLevelsChanged();
}
}
void LoggingGlobals::vformatToBuffer(const char* fmt, va_list args)
{
#ifdef _MSC_VER
va_list arg_copy = args; // dangerous?
#else
va_list arg_copy;
va_copy(arg_copy, args);
#endif
#ifdef _MSC_VER
size_t total = vsnprintf_s(&_globalCharBuffer[0], _globalCharBuffer.size(), _globalCharBuffer.size(), fmt, args);
#else
size_t total = vsnprintf(&_globalCharBuffer[0], _globalCharBuffer.size(), fmt, args);
#endif
if (total >= _globalCharBuffer.size())
{
_globalCharBuffer.resize(total + 2);
#ifdef _MSC_VER
total = vsnprintf_s(&_globalCharBuffer[0], _globalCharBuffer.size(), _globalCharBuffer.size(), fmt, arg_copy);
#else
total = vsnprintf(&_globalCharBuffer[0], _globalCharBuffer.size(), fmt, arg_copy);
#endif
}
va_end(arg_copy);
}
void LoggingGlobals::formatToBuffer(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vformatToBuffer(fmt, args);
va_end(args);
}
void LoggingGlobals::print(const char * streamName, Level level, const char* file, int line, const char* function, const char* fmt, ...)
{
if (_shutting_down)
return;
if (_printing_thread_id == boost::this_thread::get_id())
{
fprintf(stderr, "Warning: recursive print statement has occurred. Throwing out recursive print.\n");
return;
}
boost::mutex::scoped_lock lock(_print_mutex);
_printing_thread_id = boost::this_thread::get_id();
va_list args;
va_start(args, fmt);
vformatToBuffer(fmt, args);
va_end(args);
try
{
_logger->log( LoggingEvent( streamName, level, file, line, function, &_globalCharBuffer[0], _logger->currentTimeString() ) );
}
catch (std::exception& e)
{
fprintf(stderr, "Caught exception while logging: [%s]\n", e.what());
}
_printing_thread_id = boost::thread::id();
}
void LoggingGlobals::print(const char * streamName, Level level,
vectorstream & ss, const char* file, int line, const char* function)
{
if (_shutting_down)
return;
if (_printing_thread_id == boost::this_thread::get_id())
{
fprintf(stderr, "Warning: recursive print statement has occurred. Throwing out recursive print.\n");
return;
}
std::vector<char> str;
ss.swap_vector(str);
// make sure the string is null terminated.
str.push_back('\0');
boost::mutex::scoped_lock lock(_print_mutex);
_printing_thread_id = boost::this_thread::get_id();
try
{
_logger->log( LoggingEvent( streamName, level, file, line, function, &str[0], _logger->currentTimeString() ) );
}
catch (std::exception& e)
{
fprintf(stderr, "Caught exception while logging: [%s]\n", e.what());
}
_printing_thread_id = boost::thread::id();
}
sm::logging::levels::Level LoggingGlobals::getLevel()
{
// \todo is this thread safe?
return _level;
}
void LoggingGlobals::setLevel( sm::logging::levels::Level level )
{
// \todo is this thread safe?
if(level != _level)
{
_level = level;
notifyLoggerLevelsChanged();
}
}
void LoggingGlobals::setLogger( boost::shared_ptr<Logger> logger )
{
if(logger.get())
{
_logger = logger;
}
}
boost::shared_ptr<Logger> LoggingGlobals::getLogger()
{
return _logger;
}
sm::logging::levels::Level getLevel()
{
return g_logging_globals.getLevel();
}
void setLevel( sm::logging::levels::Level level )
{
g_logging_globals.setLevel(level);
}
void setLogger( boost::shared_ptr<Logger> logger )
{
g_logging_globals.setLogger(logger);
}
boost::shared_ptr<Logger> getLogger()
{
return g_logging_globals.getLogger();
}
bool isNamedStreamEnabled( const std::string & name )
{
return g_logging_globals.isNamedStreamEnabled( std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
}
void enableNamedStream( const std::string & name )
{
g_logging_globals.enableNamedStream( std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
}
void disableNamedStream( const std::string & name )
{
g_logging_globals.disableNamedStream(std::string(SMCONSOLE_NAME_PREFIX) + "." + name);
}
} // namespace logging
} // namespace sm
<|endoftext|> |
<commit_before>/* Copyright 2014 - 2015 CyberTech Labs Ltd.
*
* 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 "trikJavaScriptRunner.h"
#include <trikKernel/fileUtils.h>
#include <trikKernel/paths.h>
#include "src/scriptEngineWorker.h"
#include "src/scriptExecutionControl.h"
#include <QsLog.h>
using namespace trikScriptRunner;
TrikJavaScriptRunner::TrikJavaScriptRunner(trikControl::BrickInterface &brick
, trikNetwork::MailboxInterface * const mailbox
)
: mScriptController(new ScriptExecutionControl())
, mScriptEngineWorker(new ScriptEngineWorker(brick, mailbox, *mScriptController))
, mMaxScriptId(0)
, mVariablesServer(new TrikVariablesServer())
{
connect(&mWorkerThread, &QThread::finished, &mWorkerThread, &QThread::deleteLater);
mScriptEngineWorker->moveToThread(&mWorkerThread);
connect(&mWorkerThread, &QThread::finished, mScriptEngineWorker, &QThread::deleteLater);
connect(mScriptEngineWorker, &ScriptEngineWorker::completed, this, &TrikJavaScriptRunner::completed);
connect(mScriptEngineWorker, &ScriptEngineWorker::startedScript, this, &TrikJavaScriptRunner::onScriptStart);
connect(mScriptController.data(), &ScriptExecutionControl::textInStdOut, this, &TrikJavaScriptRunner::textInStdOut);
connect(mVariablesServer.data(), &TrikVariablesServer::getVariables, mScriptEngineWorker, &ScriptEngineWorker::getVariables);
connect(mScriptEngineWorker, &ScriptEngineWorker::variablesReady
, mVariablesServer.data(), &TrikVariablesServer::sendHTTPResponse);
QLOG_INFO() << "Starting TrikJavaScriptRunner worker thread" << &mWorkerThread;
mWorkerThread.start();
}
TrikJavaScriptRunner::~TrikJavaScriptRunner()
{
mScriptEngineWorker->stopScript();
QMetaObject::invokeMethod(&mWorkerThread, "quit");
mWorkerThread.wait(1000);
}
void TrikJavaScriptRunner::registerUserFunction(const QString &name, QScriptEngine::FunctionSignature function)
{
mScriptEngineWorker->registerUserFunction(name, function);
}
void TrikJavaScriptRunner::addCustomEngineInitStep(const std::function<void (QScriptEngine *)> &step)
{
mScriptEngineWorker->addCustomEngineInitStep(step);
}
void TrikJavaScriptRunner::brickBeep()
{
QMetaObject::invokeMethod(mScriptEngineWorker, "brickBeep");
}
void TrikJavaScriptRunner::run(const QString &script, const QString &fileName)
{
const int scriptId = mMaxScriptId++;
QLOG_INFO() << "TrikJavaScriptRunner: new script" << scriptId << "from file" << fileName;
mScriptEngineWorker->stopScript();
if (!fileName.isEmpty()) {
mScriptFileNames[scriptId] = fileName;
}
mScriptEngineWorker->run(script, (fileName.isEmpty() ? -1 : scriptId));
}
void TrikJavaScriptRunner::runDirectCommand(const QString &command)
{
QLOG_INFO() << "TrikJavaScriptRunner: new direct command" << command;
mScriptEngineWorker->runDirect(command, mMaxScriptId++);
}
void TrikJavaScriptRunner::abort()
{
mScriptEngineWorker->stopScript();
mScriptEngineWorker->resetBrick();
}
void TrikJavaScriptRunner::onScriptStart(int scriptId)
{
if (scriptId != -1 && mScriptFileNames.contains(scriptId)) {
emit startedScript(mScriptFileNames[scriptId], scriptId);
} else {
emit startedDirectScript(scriptId);
}
}
QStringList TrikJavaScriptRunner::knownMethodNames() const
{
return mScriptEngineWorker->knownMethodNames();
}
<commit_msg>Fix line length<commit_after>/* Copyright 2014 - 2015 CyberTech Labs Ltd.
*
* 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 "trikJavaScriptRunner.h"
#include <trikKernel/fileUtils.h>
#include <trikKernel/paths.h>
#include "src/scriptEngineWorker.h"
#include "src/scriptExecutionControl.h"
#include <QsLog.h>
using namespace trikScriptRunner;
TrikJavaScriptRunner::TrikJavaScriptRunner(trikControl::BrickInterface &brick
, trikNetwork::MailboxInterface * const mailbox
)
: mScriptController(new ScriptExecutionControl())
, mScriptEngineWorker(new ScriptEngineWorker(brick, mailbox, *mScriptController))
, mMaxScriptId(0)
, mVariablesServer(new TrikVariablesServer())
{
connect(&mWorkerThread, &QThread::finished, &mWorkerThread, &QThread::deleteLater);
mScriptEngineWorker->moveToThread(&mWorkerThread);
connect(&mWorkerThread, &QThread::finished, mScriptEngineWorker, &QThread::deleteLater);
connect(mScriptEngineWorker, &ScriptEngineWorker::completed, this, &TrikJavaScriptRunner::completed);
connect(mScriptEngineWorker, &ScriptEngineWorker::startedScript, this, &TrikJavaScriptRunner::onScriptStart);
connect(mScriptController.data(), &ScriptExecutionControl::textInStdOut,
this, &TrikJavaScriptRunner::textInStdOut);
connect(mVariablesServer.data(), &TrikVariablesServer::getVariables
, mScriptEngineWorker, &ScriptEngineWorker::getVariables);
connect(mScriptEngineWorker, &ScriptEngineWorker::variablesReady
, mVariablesServer.data(), &TrikVariablesServer::sendHTTPResponse);
QLOG_INFO() << "Starting TrikJavaScriptRunner worker thread" << &mWorkerThread;
mWorkerThread.start();
}
TrikJavaScriptRunner::~TrikJavaScriptRunner()
{
mScriptEngineWorker->stopScript();
QMetaObject::invokeMethod(&mWorkerThread, "quit");
mWorkerThread.wait(1000);
}
void TrikJavaScriptRunner::registerUserFunction(const QString &name, QScriptEngine::FunctionSignature function)
{
mScriptEngineWorker->registerUserFunction(name, function);
}
void TrikJavaScriptRunner::addCustomEngineInitStep(const std::function<void (QScriptEngine *)> &step)
{
mScriptEngineWorker->addCustomEngineInitStep(step);
}
void TrikJavaScriptRunner::brickBeep()
{
QMetaObject::invokeMethod(mScriptEngineWorker, "brickBeep");
}
void TrikJavaScriptRunner::run(const QString &script, const QString &fileName)
{
const int scriptId = mMaxScriptId++;
QLOG_INFO() << "TrikJavaScriptRunner: new script" << scriptId << "from file" << fileName;
mScriptEngineWorker->stopScript();
if (!fileName.isEmpty()) {
mScriptFileNames[scriptId] = fileName;
}
mScriptEngineWorker->run(script, (fileName.isEmpty() ? -1 : scriptId));
}
void TrikJavaScriptRunner::runDirectCommand(const QString &command)
{
QLOG_INFO() << "TrikJavaScriptRunner: new direct command" << command;
mScriptEngineWorker->runDirect(command, mMaxScriptId++);
}
void TrikJavaScriptRunner::abort()
{
mScriptEngineWorker->stopScript();
mScriptEngineWorker->resetBrick();
}
void TrikJavaScriptRunner::onScriptStart(int scriptId)
{
if (scriptId != -1 && mScriptFileNames.contains(scriptId)) {
emit startedScript(mScriptFileNames[scriptId], scriptId);
} else {
emit startedDirectScript(scriptId);
}
}
QStringList TrikJavaScriptRunner::knownMethodNames() const
{
return mScriptEngineWorker->knownMethodNames();
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
///
/// Generic version of the x86 CPU extension detection routine.
///
/// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp'
/// for the Microsoft compiler version.
///
/// Author : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
// SoundTouch audio processing library
// Copyright (c) Olli Parviainen
//
// 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
//
////////////////////////////////////////////////////////////////////////////////
#include <stdexcept>
#include <string>
#include "cpu_detect.h"
#include "STTypes.h"
using namespace std;
#include <stdio.h>
//////////////////////////////////////////////////////////////////////////////
//
// processor instructions extension detection routines
//
//////////////////////////////////////////////////////////////////////////////
// Flag variable indicating whick ISA extensions are disabled (for debugging)
static uint _dwDisabledISA = 0x00; // 0xffffffff; //<- use this to disable all extensions
// Disables given set of instruction extensions. See SUPPORT_... defines.
void disableExtensions(uint dwDisableMask)
{
_dwDisabledISA = dwDisableMask;
}
/// Checks which instruction set extensions are supported by the CPU.
uint detectCPUextensions(void)
{
#if (!(ALLOW_X86_OPTIMIZATIONS) || !(__GNUC__))
return 0; // always disable extensions on non-x86 platforms.
#else
uint res = 0;
if (_dwDisabledISA == 0xffffffff) return 0;
asm volatile(
#ifndef __x86_64__
// Check if 'cpuid' instructions is available by toggling eflags bit 21.
// Skip this for x86-64 as they always have cpuid while stack manipulation
// differs from 16/32bit ISA.
"\n\txor %%esi, %%esi" // clear %%esi = result register
"\n\tpushf" // save eflags to stack
"\n\tmovl (%%esp), %%eax" // load eax from stack (with eflags)
"\n\tmovl %%eax, %%ecx" // save the original eflags values to ecx
"\n\txor $0x00200000, %%eax" // toggle bit 21
"\n\tmovl %%eax, (%%esp)" // store toggled eflags to stack
"\n\tpopf" // load eflags from stack
"\n\tpushf" // save updated eflags to stack
"\n\tmovl (%%esp), %%eax" // load eax from stack
"\n\tpopf" // pop stack to restore esp
"\n\txor %%edx, %%edx" // clear edx for defaulting no mmx
"\n\tcmp %%ecx, %%eax" // compare to original eflags values
"\n\tjz end" // jumps to 'end' if cpuid not present
#endif // __x86_64__
// cpuid instruction available, test for presence of mmx instructions
"\n\tmovl $1, %%eax"
"\n\tcpuid"
"\n\ttest $0x00800000, %%edx"
"\n\tjz end" // branch if MMX not available
"\n\tor $0x01, %%esi" // otherwise add MMX support bit
"\n\ttest $0x02000000, %%edx"
"\n\tjz test3DNow" // branch if SSE not available
"\n\tor $0x08, %%esi" // otherwise add SSE support bit
"\n\ttest3DNow:"
// test for precense of AMD extensions
"\n\tmov $0x80000000, %%eax"
"\n\tcpuid"
"\n\tcmp $0x80000000, %%eax"
"\n\tjbe end" // branch if no AMD extensions detected
// test for precense of 3DNow! extension
"\n\tmov $0x80000001, %%eax"
"\n\tcpuid"
"\n\ttest $0x80000000, %%edx"
"\n\tjz end" // branch if 3DNow! not detected
"\n\tor $0x02, %%esi" // otherwise add 3DNow support bit
"\n\tend:"
"\n\tmov %%esi, %0"
: "=r" (res)
: /* no inputs */
: "%edx", "%eax", "%ecx", "%esi" );
return res & ~_dwDisabledISA;
#endif
}
<commit_msg>Fixed #ifdefs<commit_after>////////////////////////////////////////////////////////////////////////////////
///
/// Generic version of the x86 CPU extension detection routine.
///
/// This file is for GNU & other non-Windows compilers, see 'cpu_detect_x86_win.cpp'
/// for the Microsoft compiler version.
///
/// Author : Copyright (c) Olli Parviainen
/// Author e-mail : oparviai 'at' iki.fi
/// SoundTouch WWW: http://www.surina.net/soundtouch
///
////////////////////////////////////////////////////////////////////////////////
//
// Last changed : $Date$
// File revision : $Revision: 4 $
//
// $Id$
//
////////////////////////////////////////////////////////////////////////////////
//
// License :
//
// SoundTouch audio processing library
// Copyright (c) Olli Parviainen
//
// 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
//
////////////////////////////////////////////////////////////////////////////////
#include <stdexcept>
#include <string>
#include "cpu_detect.h"
#include "STTypes.h"
using namespace std;
#include <stdio.h>
//////////////////////////////////////////////////////////////////////////////
//
// processor instructions extension detection routines
//
//////////////////////////////////////////////////////////////////////////////
// Flag variable indicating whick ISA extensions are disabled (for debugging)
static uint _dwDisabledISA = 0x00; // 0xffffffff; //<- use this to disable all extensions
// Disables given set of instruction extensions. See SUPPORT_... defines.
void disableExtensions(uint dwDisableMask)
{
_dwDisabledISA = dwDisableMask;
}
/// Checks which instruction set extensions are supported by the CPU.
uint detectCPUextensions(void)
{
#if (!(SOUNDTOUCH_ALLOW_X86_OPTIMIZATIONS) || !(__GNUC__))
return 0; // always disable extensions on non-x86 platforms.
#else
uint res = 0;
if (_dwDisabledISA == 0xffffffff) return 0;
asm volatile(
#ifndef __x86_64__
// Check if 'cpuid' instructions is available by toggling eflags bit 21.
// Skip this for x86-64 as they always have cpuid while stack manipulation
// differs from 16/32bit ISA.
"\n\txor %%esi, %%esi" // clear %%esi = result register
"\n\tpushf" // save eflags to stack
"\n\tmovl (%%esp), %%eax" // load eax from stack (with eflags)
"\n\tmovl %%eax, %%ecx" // save the original eflags values to ecx
"\n\txor $0x00200000, %%eax" // toggle bit 21
"\n\tmovl %%eax, (%%esp)" // store toggled eflags to stack
"\n\tpopf" // load eflags from stack
"\n\tpushf" // save updated eflags to stack
"\n\tmovl (%%esp), %%eax" // load eax from stack
"\n\tpopf" // pop stack to restore esp
"\n\txor %%edx, %%edx" // clear edx for defaulting no mmx
"\n\tcmp %%ecx, %%eax" // compare to original eflags values
"\n\tjz end" // jumps to 'end' if cpuid not present
#endif // __x86_64__
// cpuid instruction available, test for presence of mmx instructions
"\n\tmovl $1, %%eax"
"\n\tcpuid"
"\n\ttest $0x00800000, %%edx"
"\n\tjz end" // branch if MMX not available
"\n\tor $0x01, %%esi" // otherwise add MMX support bit
"\n\ttest $0x02000000, %%edx"
"\n\tjz test3DNow" // branch if SSE not available
"\n\tor $0x08, %%esi" // otherwise add SSE support bit
"\n\ttest3DNow:"
// test for precense of AMD extensions
"\n\tmov $0x80000000, %%eax"
"\n\tcpuid"
"\n\tcmp $0x80000000, %%eax"
"\n\tjbe end" // branch if no AMD extensions detected
// test for precense of 3DNow! extension
"\n\tmov $0x80000001, %%eax"
"\n\tcpuid"
"\n\ttest $0x80000000, %%edx"
"\n\tjz end" // branch if 3DNow! not detected
"\n\tor $0x02, %%esi" // otherwise add 3DNow support bit
"\n\tend:"
"\n\tmov %%esi, %0"
: "=r" (res)
: /* no inputs */
: "%edx", "%eax", "%ecx", "%esi" );
return res & ~_dwDisabledISA;
#endif
}
<|endoftext|> |
<commit_before>// $Id: residueChecker.C,v 1.13 2000/10/30 00:19:59 amoll Exp $
#include <BALL/STRUCTURE/residueChecker.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/chain.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/DATATYPE/hashSet.h>
using namespace std;
namespace BALL
{
ResidueChecker::ResidueChecker()
: fragment_db_(0),
status_(true)
{
}
ResidueChecker::ResidueChecker(FragmentDB& fragment_db)
: fragment_db_(&fragment_db),
status_(true)
{
}
ResidueChecker::ResidueChecker(const ResidueChecker& residue_checker , bool /* deep */)
: UnaryProcessor<Residue>(),
fragment_db_(residue_checker.fragment_db_),
status_(residue_checker.status_)
{
}
ResidueChecker::~ResidueChecker()
{
}
bool ResidueChecker::getStatus() const
{
return status_;
}
bool ResidueChecker::start()
{
status_ = true;
return true;
}
bool ResidueChecker::finish()
{
return true;
}
Processor::Result ResidueChecker::operator () (Residue& residue)
{
String res_name;
if ((residue.getChain() != 0) && (residue.getChain()->getName() != BALL_CHAIN_DEFAULT_NAME))
{
res_name = residue.getChain()->getName() + ":";
}
res_name += residue.getName() + ":" + residue.getID();
// checking charge: charge should be integral and -2 <= charge <= 2
float total_charge = 0.0;
AtomIterator atom_it = residue.beginAtom();
for (; +atom_it; ++atom_it)
{
total_charge += atom_it->getCharge();
}
// check for very large absolute charges
if (total_charge < -2.0)
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": total charge of "
<< total_charge << " is too negative." << endl;
status_ = false;
}
if (total_charge > 2.0)
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": total charge of "
<< total_charge << " is too positive." << endl;
status_ = false;
}
// check for integrality of charges
float tmp = fabs(fabs(total_charge) - (float)((int)(fabs(total_charge) + 0.5)));
if (tmp > 0.05)
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": residue total charge of "
<< total_charge << " is not integral." << endl;
status_ = false;
}
// if a fragment data base is defined, check for completeness
// of the residue
if (fragment_db_ != 0)
{
const Residue* reference = dynamic_cast<const Residue*>(fragment_db_->getReferenceFragment(residue));
if (reference == 0)
{
Log.warn() << "ResidueChecker: didn't find a reference fragment for " << res_name << endl;
status_ = false;
}
else
{
// first, check for completeness
HashSet<String> reference_names;
for (atom_it = reference->beginAtom(); +atom_it; ++atom_it)
{
reference_names.insert(atom_it->getName());
}
for (atom_it = residue.beginAtom(); +atom_it; ++atom_it)
{
if (reference_names.has(atom_it->getName()))
{
reference_names.erase(atom_it->getName());
}
else
{
Log.warn() << "ResidueChecker: did not find atom " << atom_it->getName() << " of "
<< res_name << " in the reference residue " << reference->getName() << endl;
status_ = false;
}
}
if (reference_names.size() > 0)
{
Log.warn() << "ResidueChecker: did not find the following atoms in " << res_name << " : ";
HashSet<String>::Iterator set_it = reference_names.begin();
for (; set_it != reference_names.end(); ++set_it)
{
Log.warn() << *set_it << " ";
}
Log.warn() << endl;
status_ = false;
}
// check bond lengths (should be within +/- 15% of reference values)
Atom::BondIterator bond_it;
AtomIterator bond_atom_it;
Residue res(*reference);
BALL_FOREACH_BOND(res, bond_atom_it, bond_it)
{
Atom* first = 0;
Atom* second = 0;
for (atom_it = residue.beginAtom(); +atom_it && (first == 0 || second == 0); ++atom_it)
{
if (atom_it->getName() == bond_it->getFirstAtom()->getName())
{
first = &*atom_it;
}
if (atom_it->getName() == bond_it->getSecondAtom()->getName())
{
second = &*atom_it;
}
}
// if we found the bond atoms in residue, check the atom distance
if ((first != 0) && (second != 0))
{
float distance = first->getPosition().getDistance(second->getPosition());
float deviation = fabs(distance - bond_it->getLength()) / bond_it->getLength();
if (deviation > 0.15)
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": atom distance "
<< "between " << first->getName() << " and " << second->getName() << " suspect: "
<< distance << " A instead of " << bond_it->getLength() << " A" << endl;
status_ = false;
}
// check for the element type of each atom
if (first->getElement() != bond_it->getFirstAtom()->getElement())
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": atom "
<< first->getName() << " is "
<< first->getElement().getSymbol() << " should be "
<< bond_it->getFirstAtom()->getElement().getSymbol() << endl;
status_ = false;
}
if (second->getElement() != bond_it->getSecondAtom()->getElement())
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": atom "
<< second->getName() << " is "
<< second->getElement().getSymbol() << " should be "
<< bond_it->getSecondAtom()->getElement().getSymbol() << endl;
status_ = false;
}
}
}
}
}
return Processor::CONTINUE;
}
} // namespace BALL
<commit_msg>added: additional information is printed for missing atoms (template name)<commit_after>// $Id: residueChecker.C,v 1.14 2000/11/14 12:38:31 oliver Exp $
#include <BALL/STRUCTURE/residueChecker.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/chain.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/DATATYPE/hashSet.h>
using namespace std;
namespace BALL
{
ResidueChecker::ResidueChecker()
: fragment_db_(0),
status_(true)
{
}
ResidueChecker::ResidueChecker(FragmentDB& fragment_db)
: fragment_db_(&fragment_db),
status_(true)
{
}
ResidueChecker::ResidueChecker(const ResidueChecker& residue_checker , bool /* deep */)
: UnaryProcessor<Residue>(),
fragment_db_(residue_checker.fragment_db_),
status_(residue_checker.status_)
{
}
ResidueChecker::~ResidueChecker()
{
}
bool ResidueChecker::getStatus() const
{
return status_;
}
bool ResidueChecker::start()
{
status_ = true;
return true;
}
bool ResidueChecker::finish()
{
return true;
}
Processor::Result ResidueChecker::operator () (Residue& residue)
{
String res_name;
if ((residue.getChain() != 0) && (residue.getChain()->getName() != BALL_CHAIN_DEFAULT_NAME))
{
res_name = residue.getChain()->getName() + ":";
}
res_name += residue.getName() + ":" + residue.getID();
// checking charge: charge should be integral and -2 <= charge <= 2
float total_charge = 0.0;
AtomIterator atom_it = residue.beginAtom();
for (; +atom_it; ++atom_it)
{
total_charge += atom_it->getCharge();
}
// check for very large absolute charges
if (total_charge < -2.0)
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": total charge of "
<< total_charge << " is too negative." << endl;
status_ = false;
}
if (total_charge > 2.0)
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": total charge of "
<< total_charge << " is too positive." << endl;
status_ = false;
}
// check for integrality of charges
float tmp = fabs(fabs(total_charge) - (float)((int)(fabs(total_charge) + 0.5)));
if (tmp > 0.05)
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": residue total charge of "
<< total_charge << " is not integral." << endl;
status_ = false;
}
// if a fragment data base is defined, check for completeness
// of the residue
if (fragment_db_ != 0)
{
const Residue* reference = dynamic_cast<const Residue*>(fragment_db_->getReferenceFragment(residue));
if (reference == 0)
{
Log.warn() << "ResidueChecker: didn't find a reference fragment for " << res_name << endl;
status_ = false;
}
else
{
// first, check for completeness
HashSet<String> reference_names;
for (atom_it = reference->beginAtom(); +atom_it; ++atom_it)
{
reference_names.insert(atom_it->getName());
}
for (atom_it = residue.beginAtom(); +atom_it; ++atom_it)
{
if (reference_names.has(atom_it->getName()))
{
reference_names.erase(atom_it->getName());
}
else
{
Log.warn() << "ResidueChecker: did not find atom " << atom_it->getName() << " of "
<< res_name << " in the reference residue " << reference->getName() << endl;
status_ = false;
}
}
if (reference_names.size() > 0)
{
Log.warn() << "ResidueChecker: did not find the following atoms in " << res_name << " : ";
HashSet<String>::Iterator set_it = reference_names.begin();
for (; set_it != reference_names.end(); ++set_it)
{
Log.warn() << *set_it << " ";
}
Log.warn() << " (template was " << reference->getName() << ")" << endl;
status_ = false;
}
// check bond lengths (should be within +/- 15% of reference values)
Atom::BondIterator bond_it;
AtomIterator bond_atom_it;
Residue res(*reference);
BALL_FOREACH_BOND(res, bond_atom_it, bond_it)
{
Atom* first = 0;
Atom* second = 0;
for (atom_it = residue.beginAtom(); +atom_it && (first == 0 || second == 0); ++atom_it)
{
if (atom_it->getName() == bond_it->getFirstAtom()->getName())
{
first = &*atom_it;
}
if (atom_it->getName() == bond_it->getSecondAtom()->getName())
{
second = &*atom_it;
}
}
// if we found the bond atoms in residue, check the atom distance
if ((first != 0) && (second != 0))
{
float distance = first->getPosition().getDistance(second->getPosition());
float deviation = fabs(distance - bond_it->getLength()) / bond_it->getLength();
if (deviation > 0.15)
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": atom distance "
<< "between " << first->getName() << " and " << second->getName() << " suspect: "
<< distance << " A instead of " << bond_it->getLength() << " A" << endl;
status_ = false;
}
// check for the element type of each atom
if (first->getElement() != bond_it->getFirstAtom()->getElement())
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": atom "
<< first->getName() << " is "
<< first->getElement().getSymbol() << " should be "
<< bond_it->getFirstAtom()->getElement().getSymbol() << endl;
status_ = false;
}
if (second->getElement() != bond_it->getSecondAtom()->getElement())
{
Log.warn() << "ResidueChecker: in residue " << res_name << ": atom "
<< second->getName() << " is "
<< second->getElement().getSymbol() << " should be "
<< bond_it->getSecondAtom()->getElement().getSymbol() << endl;
status_ = false;
}
}
}
}
}
return Processor::CONTINUE;
}
} // namespace BALL
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "selxBlueprintImpl.h"
#include "selxBlueprint.h"
#include "selxDataManager.h"
#include "gtest/gtest.h"
using namespace selx;
class BlueprintTest : public ::testing::Test
{
public:
typedef BlueprintImpl::ParameterMapType ParameterMapType;
typedef BlueprintImpl::ParameterValueType ParameterValueType;
virtual void SetUp()
{
parameterMap[ "NameOfClass" ] = ParameterValueType( 1, "TestClassName" );
anotherParameterMap[ "NameOfClass" ] = ParameterValueType( 1, "AnotherTestClassName" );
dataManager = DataManager::New();
}
typedef Blueprint::Pointer BlueprintPointer;
DataManager::Pointer dataManager;
ParameterMapType parameterMap;
ParameterMapType anotherParameterMap;
};
TEST_F( BlueprintTest, SetGetDeleteComponent )
{
auto blueprint = Blueprint::New();
bool success0;
EXPECT_NO_THROW( success0 = blueprint->SetComponent( "MyComponentName", parameterMap ) );
EXPECT_TRUE( success0 );
bool success1;
EXPECT_NO_THROW( blueprint->SetComponent( "MyComponentName", parameterMap ) );
EXPECT_NO_THROW( success1 = blueprint->SetComponent( "MyComponentName", anotherParameterMap ) );
EXPECT_TRUE( success1 );
EXPECT_EQ( anotherParameterMap, blueprint->GetComponent( "MyComponentName" ) );
}
TEST_F( BlueprintTest, BlueprintObjectSetGetDeleteComponent )
{
BlueprintPointer blueprint;
EXPECT_NO_THROW( blueprint = Blueprint::New() );
bool success0;
EXPECT_NO_THROW( success0 = blueprint->SetComponent( "MyComponentName", parameterMap ) );
EXPECT_TRUE( success0 );
bool success1;
EXPECT_NO_THROW( blueprint->SetComponent( "MyComponentName", parameterMap ) );
EXPECT_NO_THROW( success1 = blueprint->SetComponent( "MyComponentName", anotherParameterMap ) );
EXPECT_TRUE( success1 );
EXPECT_EQ( anotherParameterMap, blueprint->GetComponent( "MyComponentName" ) );
}
TEST_F( BlueprintTest, SetGetDeleteConnection )
{
auto blueprint = Blueprint::New();
blueprint->SetComponent( "Component0", parameterMap );
blueprint->SetComponent( "Component1", parameterMap );
blueprint->SetComponent( "Component2", parameterMap );
// Connection should not exist
bool connectionExists;
EXPECT_NO_THROW( connectionExists = blueprint->ConnectionExists( "Component0", "Component1" ) );
EXPECT_FALSE( connectionExists );
// Connection should be set
bool connectionSet;
EXPECT_NO_THROW( connectionSet = blueprint->SetConnection( "Component0", "Component1", parameterMap ) );
EXPECT_TRUE( connectionSet );
// Connection should now exist
bool connectionNowExists;
EXPECT_NO_THROW( connectionNowExists = blueprint->ConnectionExists( "Component0", "Component1" ) );
EXPECT_TRUE( connectionNowExists );
// Connection should have parameter map
ParameterMapType parameterMap0;
EXPECT_NO_THROW( parameterMap0 = blueprint->GetConnection( "Component0", "Component1" ) );
EXPECT_EQ( parameterMap[ "NameOfClass" ], parameterMap0[ "NameOfClass" ] );
// Another parameter map should transparently added
bool anotherParameterMapSet;
EXPECT_NO_THROW( anotherParameterMapSet = blueprint->SetConnection( "Component0", "Component1", anotherParameterMap ) );
EXPECT_TRUE( anotherParameterMapSet );
EXPECT_EQ( anotherParameterMap, blueprint->GetConnection( "Component0", "Component1" ) );
// Connection should be deleted
bool connectionDeleted;
EXPECT_NO_THROW( connectionDeleted = blueprint->DeleteConnection( "Component0", "Component1" ) );
EXPECT_TRUE( connectionDeleted );
// Connection should not exist
EXPECT_FALSE( blueprint->ConnectionExists( "Component0", "Component1" ) );
EXPECT_THROW( blueprint->GetConnection( "Component0", "Component1" ), std::runtime_error );
}
//TEST_F( BlueprintTest, CopyConstuctor )
//{
// std::unique_ptr< BlueprintImpl > baseBlueprint;
// EXPECT_NO_THROW( baseBlueprint = std::unique_ptr< BlueprintImpl >( new BlueprintImpl() ) );
//
// baseBlueprint->SetComponent( "Component0", { { "OperationType", { "Transform" } } } );
// std::unique_ptr< BlueprintImpl > clonedBaseBlueprint;
// EXPECT_NO_THROW( clonedBaseBlueprint = std::make_unique< BlueprintImpl >( *baseBlueprint.get() ) );
//
// EXPECT_NO_THROW( clonedBaseBlueprint->SetComponent( "Component1", { { "OperationType", { "Source" } }, { "Dimensionality", { "3" } } } ) );
//
// BlueprintImpl::ParameterMapType clonedComponent0;
// EXPECT_NO_THROW( clonedComponent0 = clonedBaseBlueprint->GetComponent( "Component0" ) );
//
// BlueprintImpl::ParameterMapType component1;
// EXPECT_THROW( component1 = baseBlueprint->GetComponent( "Component1" ), std::runtime_error );
//}
TEST_F( BlueprintTest, Compose )
{
auto baseBlueprint = Blueprint::New();
baseBlueprint->SetComponent( "Component0", { { "OperationType", { "Transform" } } } );
baseBlueprint->SetComponent( "Component1", { { "OperationType", { "Source" } }, { "Dimensionality", { "3" } } } );
// compose-in a new 3rd component Component2
auto nonConflictingBlueprint0 = Blueprint::New();
nonConflictingBlueprint0->SetComponent( "Component2", { { "OperationType", { "Sink" } } } );
EXPECT_TRUE( baseBlueprint->ComposeWith( nonConflictingBlueprint0 ) );
EXPECT_STREQ( "Sink", baseBlueprint->GetComponent( "Component2" )[ "OperationType" ][ 0 ].c_str() );
// compose-in additional properties of Component0 and Component1
auto nonConflictingBlueprint1 = Blueprint::New();
nonConflictingBlueprint1->SetComponent( "Component0", { { "TranformationGroup", { "Diffeomorphic" } }, { "PixelType", { "float" } } } );
nonConflictingBlueprint1->SetComponent( "Component1", { { "NameOfClass", { "ImageSourceClass" } } } );
EXPECT_TRUE( baseBlueprint->ComposeWith( nonConflictingBlueprint1 ) );
EXPECT_STREQ( "Transform", baseBlueprint->GetComponent( "Component0" )[ "OperationType" ][ 0 ].c_str() );
EXPECT_STREQ( "Diffeomorphic", baseBlueprint->GetComponent( "Component0" )[ "TranformationGroup" ][ 0 ].c_str() );
EXPECT_STREQ( "ImageSourceClass", baseBlueprint->GetComponent( "Component1" )[ "NameOfClass" ][ 0 ].c_str() );
// compose-in existing component with existing property key, but equal property value(s). Nothing happens actually (i.e. idempotency)
auto nonConflictingBlueprint2 = Blueprint::New();
nonConflictingBlueprint2->SetComponent( "Component0", { { "PixelType", { "float" } } } );
EXPECT_TRUE( baseBlueprint->ComposeWith( nonConflictingBlueprint2 ) );
// trying to overwrite properties fails
auto conflictingBlueprint0 = Blueprint::New();
conflictingBlueprint0->SetComponent( "Component1", { { "Dimensionality", { "2" } }, { "InternalComputationValueType", { "float" } } } );
// Compose fails and returns false
EXPECT_FALSE( baseBlueprint->ComposeWith( conflictingBlueprint0 ) );
//baseBlueprint should not have been altered by a failing compose operation
EXPECT_STREQ( "3", baseBlueprint->GetComponent( "Component1" )[ "Dimensionality" ][ 0 ].c_str() );
EXPECT_EQ( 0, baseBlueprint->GetComponent( "Component1" ).count( "InternalComputationValueType" ) );
}
//TEST_F( BlueprintTest, WriteBlueprint )
//{
// std::unique_ptr< BlueprintImpl > blueprint;
// EXPECT_NO_THROW( blueprint = std::unique_ptr< BlueprintImpl >( new BlueprintImpl() ) );
//
// // create some made up configuration to show graphviz output
// ParameterMapType component0Parameters;
// component0Parameters[ "NameOfClass" ] = { "MyMetric" };
// component0Parameters[ "Dimensionality" ] = { "3" };
// component0Parameters[ "Kernel" ] = { "5", "5", "5" };
// blueprint->SetComponent( "Metric", component0Parameters );
//
// ParameterMapType component1Parameters;
// component1Parameters[ "NameOfClass" ] = { "MyFiniteDifferenceCalculator" };
// component1Parameters[ "Delta" ] = { "0.01" };
// blueprint->SetComponent( "MetricGradient", component1Parameters );
//
// ParameterMapType component2Parameters;
// component2Parameters[ "NameOfClass" ] = { "MyOptimizer" };
// blueprint->SetComponent( "Optimizer", component2Parameters );
//
// ParameterMapType component3Parameters;
// component3Parameters[ "NameOfClass" ] = { "MyTransform" };
// blueprint->SetComponent( "Transform", component3Parameters );
//
// blueprint->SetConnection( "Metric", "MetricGradient", parameterMap );
// blueprint->SetConnection( "MetricGradient", "Optimizer", parameterMap );
//
// ParameterMapType connection0Parameters;
// // Example use case: The connection between the metric and optimizer should
// // only be by "MetricValue", not by "MetricDerivative" as well. Since we want
// // to redirect the "MetricDerivative" through the MetricGradient component,
// // we need to specify "NameOfInterface" otherwise there is an ambiguity in
// // which "MetricDerivative" to connect to the optimizer.
//
// connection0Parameters[ "NameOfInterface" ] = { "MetricValue" };
// blueprint->SetConnection( "Metric", "Optimizer", connection0Parameters );
//
// blueprint->SetConnection( "MetricGradient", "Optimizer", parameterMap );
// blueprint->SetConnection( "Optimizer", "Transform", parameterMap );
// blueprint->SetConnection( "Transform", "Metric", parameterMap );
//
// EXPECT_NO_THROW( blueprint->Write( "blueprint.dot" ) );
//}
TEST_F(BlueprintTest, ReadXML)
{
auto blueprint = Blueprint::New();
EXPECT_NO_THROW(blueprint->MergeFromFile(this->dataManager->GetConfigurationFile("itkv4_SVF_ANTsCC.xml")));
blueprint->Write(this->dataManager->GetOutputFile("configurationReaderTest_itkv4_SVF_ANTsCC.xml.dot"));
}
TEST_F(BlueprintTest, ReadJson)
{
auto blueprint = Blueprint::New();
EXPECT_NO_THROW(blueprint->MergeFromFile(this->dataManager->GetConfigurationFile("itkv4_SVF_ANTsCC.json")));
blueprint->Write(this->dataManager->GetOutputFile("configurationReaderTest_itkv4_SVF_ANTsCC.json.dot"));
}<commit_msg>ENH: restored copy constructor test Blueprint<commit_after>/*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "selxBlueprintImpl.h"
#include "selxBlueprint.h"
#include "selxDataManager.h"
#include "gtest/gtest.h"
using namespace selx;
class BlueprintTest : public ::testing::Test
{
public:
typedef BlueprintImpl::ParameterMapType ParameterMapType;
typedef BlueprintImpl::ParameterValueType ParameterValueType;
virtual void SetUp()
{
parameterMap[ "NameOfClass" ] = ParameterValueType( 1, "TestClassName" );
anotherParameterMap[ "NameOfClass" ] = ParameterValueType( 1, "AnotherTestClassName" );
dataManager = DataManager::New();
}
typedef Blueprint::Pointer BlueprintPointer;
DataManager::Pointer dataManager;
ParameterMapType parameterMap;
ParameterMapType anotherParameterMap;
};
TEST_F( BlueprintTest, SetGetDeleteComponent )
{
auto blueprint = Blueprint::New();
bool success0;
EXPECT_NO_THROW( success0 = blueprint->SetComponent( "MyComponentName", parameterMap ) );
EXPECT_TRUE( success0 );
bool success1;
EXPECT_NO_THROW( blueprint->SetComponent( "MyComponentName", parameterMap ) );
EXPECT_NO_THROW( success1 = blueprint->SetComponent( "MyComponentName", anotherParameterMap ) );
EXPECT_TRUE( success1 );
EXPECT_EQ( anotherParameterMap, blueprint->GetComponent( "MyComponentName" ) );
}
TEST_F( BlueprintTest, BlueprintObjectSetGetDeleteComponent )
{
BlueprintPointer blueprint;
EXPECT_NO_THROW( blueprint = Blueprint::New() );
bool success0;
EXPECT_NO_THROW( success0 = blueprint->SetComponent( "MyComponentName", parameterMap ) );
EXPECT_TRUE( success0 );
bool success1;
EXPECT_NO_THROW( blueprint->SetComponent( "MyComponentName", parameterMap ) );
EXPECT_NO_THROW( success1 = blueprint->SetComponent( "MyComponentName", anotherParameterMap ) );
EXPECT_TRUE( success1 );
EXPECT_EQ( anotherParameterMap, blueprint->GetComponent( "MyComponentName" ) );
}
TEST_F( BlueprintTest, SetGetDeleteConnection )
{
auto blueprint = Blueprint::New();
blueprint->SetComponent( "Component0", parameterMap );
blueprint->SetComponent( "Component1", parameterMap );
blueprint->SetComponent( "Component2", parameterMap );
// Connection should not exist
bool connectionExists;
EXPECT_NO_THROW( connectionExists = blueprint->ConnectionExists( "Component0", "Component1" ) );
EXPECT_FALSE( connectionExists );
// Connection should be set
bool connectionSet;
EXPECT_NO_THROW( connectionSet = blueprint->SetConnection( "Component0", "Component1", parameterMap ) );
EXPECT_TRUE( connectionSet );
// Connection should now exist
bool connectionNowExists;
EXPECT_NO_THROW( connectionNowExists = blueprint->ConnectionExists( "Component0", "Component1" ) );
EXPECT_TRUE( connectionNowExists );
// Connection should have parameter map
ParameterMapType parameterMap0;
EXPECT_NO_THROW( parameterMap0 = blueprint->GetConnection( "Component0", "Component1" ) );
EXPECT_EQ( parameterMap[ "NameOfClass" ], parameterMap0[ "NameOfClass" ] );
// Another parameter map should transparently added
bool anotherParameterMapSet;
EXPECT_NO_THROW( anotherParameterMapSet = blueprint->SetConnection( "Component0", "Component1", anotherParameterMap ) );
EXPECT_TRUE( anotherParameterMapSet );
EXPECT_EQ( anotherParameterMap, blueprint->GetConnection( "Component0", "Component1" ) );
// Connection should be deleted
bool connectionDeleted;
EXPECT_NO_THROW( connectionDeleted = blueprint->DeleteConnection( "Component0", "Component1" ) );
EXPECT_TRUE( connectionDeleted );
// Connection should not exist
EXPECT_FALSE( blueprint->ConnectionExists( "Component0", "Component1" ) );
EXPECT_THROW( blueprint->GetConnection( "Component0", "Component1" ), std::runtime_error );
}
TEST_F( BlueprintTest, CopyConstuctor )
{
auto baseBlueprint = Blueprint::New();
baseBlueprint->SetComponent( "Component0", { { "OperationType", { "Transform" } } } );
auto baseBlueprintImpl = baseBlueprint->GetBlueprintImpl();
std::unique_ptr< BlueprintImpl > clonedBaseBlueprint;
EXPECT_NO_THROW( clonedBaseBlueprint = std::make_unique< BlueprintImpl >( baseBlueprintImpl ) );
EXPECT_NO_THROW( clonedBaseBlueprint->SetComponent( "Component1", { { "OperationType", { "Source" } }, { "Dimensionality", { "3" } } } ) );
BlueprintImpl::ParameterMapType clonedComponent0;
EXPECT_NO_THROW( clonedComponent0 = clonedBaseBlueprint->GetComponent( "Component0" ) );
BlueprintImpl::ParameterMapType component1;
EXPECT_THROW( component1 = baseBlueprint->GetComponent( "Component1" ), std::runtime_error );
}
TEST_F( BlueprintTest, Compose )
{
auto baseBlueprint = Blueprint::New();
baseBlueprint->SetComponent( "Component0", { { "OperationType", { "Transform" } } } );
baseBlueprint->SetComponent( "Component1", { { "OperationType", { "Source" } }, { "Dimensionality", { "3" } } } );
// compose-in a new 3rd component Component2
auto nonConflictingBlueprint0 = Blueprint::New();
nonConflictingBlueprint0->SetComponent( "Component2", { { "OperationType", { "Sink" } } } );
EXPECT_TRUE( baseBlueprint->ComposeWith( nonConflictingBlueprint0 ) );
EXPECT_STREQ( "Sink", baseBlueprint->GetComponent( "Component2" )[ "OperationType" ][ 0 ].c_str() );
// compose-in additional properties of Component0 and Component1
auto nonConflictingBlueprint1 = Blueprint::New();
nonConflictingBlueprint1->SetComponent( "Component0", { { "TranformationGroup", { "Diffeomorphic" } }, { "PixelType", { "float" } } } );
nonConflictingBlueprint1->SetComponent( "Component1", { { "NameOfClass", { "ImageSourceClass" } } } );
EXPECT_TRUE( baseBlueprint->ComposeWith( nonConflictingBlueprint1 ) );
EXPECT_STREQ( "Transform", baseBlueprint->GetComponent( "Component0" )[ "OperationType" ][ 0 ].c_str() );
EXPECT_STREQ( "Diffeomorphic", baseBlueprint->GetComponent( "Component0" )[ "TranformationGroup" ][ 0 ].c_str() );
EXPECT_STREQ( "ImageSourceClass", baseBlueprint->GetComponent( "Component1" )[ "NameOfClass" ][ 0 ].c_str() );
// compose-in existing component with existing property key, but equal property value(s). Nothing happens actually (i.e. idempotency)
auto nonConflictingBlueprint2 = Blueprint::New();
nonConflictingBlueprint2->SetComponent( "Component0", { { "PixelType", { "float" } } } );
EXPECT_TRUE( baseBlueprint->ComposeWith( nonConflictingBlueprint2 ) );
// trying to overwrite properties fails
auto conflictingBlueprint0 = Blueprint::New();
conflictingBlueprint0->SetComponent( "Component1", { { "Dimensionality", { "2" } }, { "InternalComputationValueType", { "float" } } } );
// Compose fails and returns false
EXPECT_FALSE( baseBlueprint->ComposeWith( conflictingBlueprint0 ) );
//baseBlueprint should not have been altered by a failing compose operation
EXPECT_STREQ( "3", baseBlueprint->GetComponent( "Component1" )[ "Dimensionality" ][ 0 ].c_str() );
EXPECT_EQ( 0, baseBlueprint->GetComponent( "Component1" ).count( "InternalComputationValueType" ) );
}
//TEST_F( BlueprintTest, WriteBlueprint )
//{
// std::unique_ptr< BlueprintImpl > blueprint;
// EXPECT_NO_THROW( blueprint = std::unique_ptr< BlueprintImpl >( new BlueprintImpl() ) );
//
// // create some made up configuration to show graphviz output
// ParameterMapType component0Parameters;
// component0Parameters[ "NameOfClass" ] = { "MyMetric" };
// component0Parameters[ "Dimensionality" ] = { "3" };
// component0Parameters[ "Kernel" ] = { "5", "5", "5" };
// blueprint->SetComponent( "Metric", component0Parameters );
//
// ParameterMapType component1Parameters;
// component1Parameters[ "NameOfClass" ] = { "MyFiniteDifferenceCalculator" };
// component1Parameters[ "Delta" ] = { "0.01" };
// blueprint->SetComponent( "MetricGradient", component1Parameters );
//
// ParameterMapType component2Parameters;
// component2Parameters[ "NameOfClass" ] = { "MyOptimizer" };
// blueprint->SetComponent( "Optimizer", component2Parameters );
//
// ParameterMapType component3Parameters;
// component3Parameters[ "NameOfClass" ] = { "MyTransform" };
// blueprint->SetComponent( "Transform", component3Parameters );
//
// blueprint->SetConnection( "Metric", "MetricGradient", parameterMap );
// blueprint->SetConnection( "MetricGradient", "Optimizer", parameterMap );
//
// ParameterMapType connection0Parameters;
// // Example use case: The connection between the metric and optimizer should
// // only be by "MetricValue", not by "MetricDerivative" as well. Since we want
// // to redirect the "MetricDerivative" through the MetricGradient component,
// // we need to specify "NameOfInterface" otherwise there is an ambiguity in
// // which "MetricDerivative" to connect to the optimizer.
//
// connection0Parameters[ "NameOfInterface" ] = { "MetricValue" };
// blueprint->SetConnection( "Metric", "Optimizer", connection0Parameters );
//
// blueprint->SetConnection( "MetricGradient", "Optimizer", parameterMap );
// blueprint->SetConnection( "Optimizer", "Transform", parameterMap );
// blueprint->SetConnection( "Transform", "Metric", parameterMap );
//
// EXPECT_NO_THROW( blueprint->Write( "blueprint.dot" ) );
//}
TEST_F(BlueprintTest, ReadXML)
{
auto blueprint = Blueprint::New();
EXPECT_NO_THROW(blueprint->MergeFromFile(this->dataManager->GetConfigurationFile("itkv4_SVF_ANTsCC.xml")));
blueprint->Write(this->dataManager->GetOutputFile("configurationReaderTest_itkv4_SVF_ANTsCC.xml.dot"));
}
TEST_F(BlueprintTest, ReadJson)
{
auto blueprint = Blueprint::New();
EXPECT_NO_THROW(blueprint->MergeFromFile(this->dataManager->GetConfigurationFile("itkv4_SVF_ANTsCC.json")));
blueprint->Write(this->dataManager->GetOutputFile("configurationReaderTest_itkv4_SVF_ANTsCC.json.dot"));
}<|endoftext|> |
<commit_before>#include "KeyboardInputComponent.h"
#include "SDL2/SDL_events.h"
#include "SDL2/SDL_keyboard.h"
#include "SDL2/SDL_keycode.h"
void KeyboardInputComponent::Init()
{
//init keys I want to use for the game....
//should probably read from some file what keys I want to bind to..
//but this should be good enough for now..
keys["left"] = KeyStates::NA;
keys["right"] = KeyStates::NA;
keys["up"] = KeyStates::NA;
keys["down"] = KeyStates::NA;
keys["a"] = KeyStates::NA;
keys["s"] = KeyStates::NA;
keys["d"] = KeyStates::NA;
keys["space"] = KeyStates::NA;
startPressedTime = 0;
counter = 0;
}
bool KeyboardInputComponent::KeyPressed(std::string keyName)
{
return keys.at(keyName) == KeyStates::PRESSED;
}
bool KeyboardInputComponent::KeyHeld(std::string keyName)
{
return keys.at(keyName) == KeyStates::HELD;
}
bool KeyboardInputComponent::KeyReleased(std::string keyName)
{
return keys.at(keyName) == KeyStates::RELEASED;
}
//may need to rewrite this component since multiple functions that poll for events
//may have the information this keyboard component needs e.g. if I did not hit x to exit the application and have hit a keybinding instead,
//it may not record the keybinding in a separate event poll...
//the subtle difference between gamepad controller events
//and key events is that key events get checked every update
//e.g. if key is down for more than 1 frame, it will continue to
//process that input as a key down again...
void KeyboardInputComponent::Update(float deltaTime)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)//this statement will be true as long as a key is held down...
{
SDL_Keycode keycode = event.key.keysym.sym;
//y-axis movement
if (keycode == SDLK_UP)
{
if (keys["up"] == KeyStates::RELEASED)
keys["up"] = KeyStates::PRESSED;
else
keys["up"] = KeyStates::HELD;
}
else if (keycode == SDLK_DOWN)
{
if (keys["down"] == KeyStates::RELEASED)
keys["down"] = KeyStates::PRESSED;
else
keys["down"] = KeyStates::HELD;
}
//x-axis movement
if (keycode == SDLK_LEFT)
{
if (keys["left"] == KeyStates::RELEASED)
keys["left"] = KeyStates::PRESSED;
else
keys["left"] = KeyStates::HELD;
}
else if (keycode == SDLK_RIGHT)
{
if (keys["right"] == KeyStates::RELEASED)
keys["right"] = KeyStates::PRESSED;
else
keys["right"] = KeyStates::HELD;
}
//action keys and space
if (keycode == SDLK_a)
{
if (keys["a"] == KeyStates::RELEASED)
keys["a"] = KeyStates::PRESSED;
else
keys["a"] = KeyStates::HELD;
}
if (keycode == SDLK_s)
{
if (keys["s"] == KeyStates::RELEASED)
keys["s"] = KeyStates::PRESSED;
else
keys["s"] = KeyStates::HELD;
}
if (keycode == SDLK_d)
{
if (keys["d"] == KeyStates::RELEASED)
keys["d"] = KeyStates::PRESSED;
else
keys["d"] = KeyStates::HELD;
}
if (keycode == SDLK_SPACE)
{
if (keys["space"] == KeyStates::RELEASED)
keys["space"] = KeyStates::PRESSED;
else
keys["space"] = KeyStates::HELD;
}
}
if (event.type == SDL_KEYUP)
{
SDL_Keycode keycode = event.key.keysym.sym;
//y-axis movement
if (keycode == SDLK_UP)
{
keys["up"] = KeyStates::RELEASED;
}
if (keycode == SDLK_DOWN)
{
keys["down"] = KeyStates::RELEASED;
}
//x-axis movement
if (keycode == SDLK_LEFT)
{
keys["left"] = KeyStates::RELEASED;
}
if (keycode == SDLK_RIGHT)
{
keys["right"] = KeyStates::RELEASED;
}
//action keys and space
if (keycode == SDLK_a)
{
keys["a"] = KeyStates::RELEASED;
}
if (keycode == SDLK_s)
{
keys["s"] = KeyStates::RELEASED;
}
if (keycode == SDLK_d)
{
keys["d"] = KeyStates::RELEASED;
}
if (keycode == SDLK_SPACE)
{
keys["space"] = KeyStates::RELEASED;
}
}
else //if key was released for more than one frame set it back to NA
{
if (keys["up"] == KeyStates::RELEASED)
keys["up"] = KeyStates::NA;
if (keys["down"] == KeyStates::RELEASED)
keys["down"] = KeyStates::NA;
if (keys["left"] == KeyStates::RELEASED)
keys["left"] = KeyStates::NA;
if (keys["right"] == KeyStates::RELEASED)
keys["right"] = KeyStates::NA;
}
}
}
<commit_msg>Minor tweaks<commit_after>#include "KeyboardInputComponent.h"
#include "SDL2/SDL_events.h"
#include "SDL2/SDL_keyboard.h"
#include "SDL2/SDL_keycode.h"
void KeyboardInputComponent::Init()
{
//init keys I want to use for the game....
//should probably read from some file what keys I want to bind to..
//but this should be good enough for now..
keys["left"] = KeyStates::NA;
keys["right"] = KeyStates::NA;
keys["up"] = KeyStates::NA;
keys["down"] = KeyStates::NA;
keys["a"] = KeyStates::NA;
keys["s"] = KeyStates::NA;
keys["d"] = KeyStates::NA;
keys["space"] = KeyStates::NA;
startPressedTime = 0;
counter = 0;
}
bool KeyboardInputComponent::KeyPressed(std::string keyName)
{
return keys.at(keyName) == KeyStates::PRESSED;
}
bool KeyboardInputComponent::KeyHeld(std::string keyName)
{
return keys.at(keyName) == KeyStates::HELD;
}
bool KeyboardInputComponent::KeyReleased(std::string keyName)
{
return keys.at(keyName) == KeyStates::RELEASED;
}
//may need to rewrite this component since multiple functions that poll for events
//may have the information this keyboard component needs e.g. if I did not hit x to exit the application and have hit a keybinding instead,
//it may not record the keybinding in a separate event poll...
//the subtle difference between gamepad controller events
//and key events is that key events get checked every update
//e.g. if key is down for more than 1 frame, it will continue to
//process that input as a key down again...
void KeyboardInputComponent::Update(float deltaTime)
{
SDL_Event event;
while(SDL_PollEvent(&event))
{
if (event.type == SDL_KEYDOWN)//this statement will be true as long as a key is held down...
{
SDL_Keycode keycode = event.key.keysym.sym;
//y-axis movement
if (keycode == SDLK_UP)
{
if (keys["up"] == KeyStates::RELEASED)
keys["up"] = KeyStates::PRESSED;
else
keys["up"] = KeyStates::HELD;
}
if (keycode == SDLK_DOWN)
{
if (keys["down"] == KeyStates::RELEASED)
keys["down"] = KeyStates::PRESSED;
else
keys["down"] = KeyStates::HELD;
}
//x-axis movement
if (keycode == SDLK_LEFT)
{
if (keys["left"] == KeyStates::RELEASED)
keys["left"] = KeyStates::PRESSED;
else
keys["left"] = KeyStates::HELD;
}
if (keycode == SDLK_RIGHT)
{
if (keys["right"] == KeyStates::RELEASED)
keys["right"] = KeyStates::PRESSED;
else
keys["right"] = KeyStates::HELD;
}
//action keys and space
if (keycode == SDLK_a)
{
if (keys["a"] == KeyStates::RELEASED)
keys["a"] = KeyStates::PRESSED;
else
keys["a"] = KeyStates::HELD;
}
if (keycode == SDLK_s)
{
if (keys["s"] == KeyStates::RELEASED)
keys["s"] = KeyStates::PRESSED;
else
keys["s"] = KeyStates::HELD;
}
if (keycode == SDLK_d)
{
if (keys["d"] == KeyStates::RELEASED)
keys["d"] = KeyStates::PRESSED;
else
keys["d"] = KeyStates::HELD;
}
if (keycode == SDLK_SPACE)
{
if (keys["space"] == KeyStates::RELEASED)
keys["space"] = KeyStates::PRESSED;
else
keys["space"] = KeyStates::HELD;
}
}
if (event.type == SDL_KEYUP)
{
SDL_Keycode keycode = event.key.keysym.sym;
//y-axis movement
if (keycode == SDLK_UP)
{
keys["up"] = KeyStates::RELEASED;
}
if (keycode == SDLK_DOWN)
{
keys["down"] = KeyStates::RELEASED;
}
//x-axis movement
if (keycode == SDLK_LEFT)
{
keys["left"] = KeyStates::RELEASED;
}
if (keycode == SDLK_RIGHT)
{
keys["right"] = KeyStates::RELEASED;
}
//action keys and space
if (keycode == SDLK_a)
{
keys["a"] = KeyStates::RELEASED;
}
if (keycode == SDLK_s)
{
keys["s"] = KeyStates::RELEASED;
}
if (keycode == SDLK_d)
{
keys["d"] = KeyStates::RELEASED;
}
if (keycode == SDLK_SPACE)
{
keys["space"] = KeyStates::RELEASED;
}
}
else //if key was released for more than one frame set it back to NA
{
if (keys["up"] == KeyStates::RELEASED)
keys["up"] = KeyStates::NA;
if (keys["down"] == KeyStates::RELEASED)
keys["down"] = KeyStates::NA;
if (keys["left"] == KeyStates::RELEASED)
keys["left"] = KeyStates::NA;
if (keys["right"] == KeyStates::RELEASED)
keys["right"] = KeyStates::NA;
}
}
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2012-2013, Jack Poulson
All rights reserved.
This file is part of Choice and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#ifndef CHOICE_H
#define CHOICE_H 1
#include <algorithm>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <typeinfo>
#include <vector>
namespace choice {
template<typename TOut,typename TIn>
TOut Cast( const TIn& input )
{
std::stringstream stream;
TOut output;
stream << input;
stream >> output;
return output;
}
template<>
bool Cast( const std::string& input )
{
std::string trueString("true");
std::string falseString("false");
if( input.compare(trueString) == 0 )
return true;
else if( input.compare(falseString) == 0 )
return false;
else
{
bool output;
std::stringstream stream;
stream << input;
stream >> output;
return output;
}
}
class ArgException : public std::logic_error
{
public:
ArgException( const char* msg="Argument exception" )
: std::logic_error( msg ) { }
};
class Args
{
public:
Args( int argc, char** argv, std::ostream& error=std::cerr );
template<typename T>
T Input( std::string name, std::string desc );
template<typename T>
T Input( std::string name, std::string desc, T defaultVal );
void Process( std::ostream& output=std::cout ) const;
void PrintReport( std::ostream& output=std::cout ) const;
private:
int argc_;
char** argv_;
std::vector<bool> usedArgs_;
std::ostream& error_;
struct RequiredArg
{
std::string name, desc, typeInfo, usedVal;
bool found;
RequiredArg
( std::string n, std::string d, std::string t, std::string uv, bool f )
: name(n), desc(d), typeInfo(t), usedVal(uv), found(f) { };
};
struct OptionalArg
{
std::string name, desc, typeInfo, defaultVal, usedVal;
bool found;
OptionalArg
( std::string n, std::string d, std::string t,
std::string dv, std::string uv, bool f )
: name(n), desc(d), typeInfo(t),
defaultVal(dv), usedVal(uv), found(f) { }
};
std::vector<RequiredArg> requiredArgs_;
std::vector<OptionalArg> optionalArgs_;
};
inline
Args::Args( int argc, char** argv, std::ostream& error )
: argc_(argc), argv_(argv), usedArgs_(argc,false), error_(error)
{ }
template<typename T>
inline T
Args::Input( std::string name, std::string desc )
{
char** arg = std::find( argv_, argv_+argc_, name );
const bool found = ( arg != argv_+argc_ );
const bool invalidFound = ( arg == argv_+argc_-1 );
if( invalidFound )
{
error_ << "Missing value for last command-line argument" << std::endl;
throw ArgException();
}
std::string typeInfo( typeid(T).name() );
std::string usedVal = ( found ? arg[1] : "N/A" );
requiredArgs_.push_back( RequiredArg(name,desc,typeInfo,usedVal,found) );
// Before returning, store the used indices and check for duplication
if( found )
{
const int offset = arg - argv_;
if( usedArgs_[offset] || usedArgs_[offset+1] )
{
error_ << "WARNING: conflict with " << name << " detected at ";
if( usedArgs_[offset] && usedArgs_[offset+1] )
error_ << "arguments " << offset << " and " << offset+1
<< std::endl;
else if( usedArgs_[offset] )
error_ << "argument " << offset << std::endl;
else
error_ << "argument " << offset+1 << std::endl;
error_ << "Please ensure that you did request argument "
<< name << " multiple times" << std::endl;
}
usedArgs_[offset+0] = true;
usedArgs_[offset+1] = true;
arg = std::find( arg+1, argv_+argc_, name );
if( arg != argv_+argc_ )
error_ << "WARNING: " << name << " was specified twice and only "
<< "the first instance is used" << std::endl;
}
return Cast<T>( usedVal );
}
template<typename T>
inline T
Args::Input( std::string name, std::string desc, T defaultVal )
{
char** arg = std::find( argv_, argv_+argc_, name );
const bool found = ( arg != argv_+argc_ );
const bool invalidFound = ( arg == argv_+argc_-1 );
if( invalidFound )
{
error_ << "Missing value for last command-line argument" << std::endl;
throw ArgException();
}
std::string typeInfo( typeid(T).name() );
std::string defValString = Cast<std::string>( defaultVal );
std::string usedVal = ( found ? arg[1] : defValString );
optionalArgs_.push_back
( OptionalArg(name,desc,typeInfo,defValString,usedVal,found) );
// Before returning, store the used indices and check for duplication
if( found )
{
const int offset = arg - argv_;
if( usedArgs_[offset] || usedArgs_[offset+1] )
{
error_ << "WARNING: conflict with " << name << " detected at ";
if( usedArgs_[offset] && usedArgs_[offset+1] )
error_ << "arguments " << offset << " and " << offset+1
<< std::endl;
else if( usedArgs_[offset] )
error_ << "argument " << offset << std::endl;
else
error_ << "argument " << offset+1 << std::endl;
error_ << "Please ensure that you did request argument "
<< name << " multiple times" << std::endl;
}
usedArgs_[offset+0] = true;
usedArgs_[offset+1] = true;
arg = std::find( arg+1, argv_+argc_, name );
if( arg != argv_+argc_ )
error_ << "WARNING: " << name << " was specified twice and only "
<< "the first instance is used" << std::endl;
}
if( found )
return Cast<T>( usedVal );
else
return defaultVal; // avoid the double-cast
}
inline void
Args::Process( std::ostream& output ) const
{
std::string help = "--help";
char** arg = std::find( argv_, argv_+argc_, help );
const bool foundHelp = ( arg != argv_+argc_ );
int numFailed = 0;
const int numRequired = requiredArgs_.size();
for( int i=0; i<numRequired; ++i )
if( !requiredArgs_[i].found )
++numFailed;
if( numFailed > 0 || foundHelp )
{
PrintReport( output );
throw ArgException();
}
}
inline void
Args::PrintReport( std::ostream& output ) const
{
const int numRequired = requiredArgs_.size();
const int numOptional = optionalArgs_.size();
if( numRequired > 0 )
output << "Required arguments:\n";
int numReqFailed = 0;
for( int i=0; i<numRequired; ++i )
{
const RequiredArg& reqArg = requiredArgs_[i];
if( !reqArg.found )
++numReqFailed;
std::string foundString = ( reqArg.found ? "found" : "NOT found" );
output << " " << reqArg.name
<< " [" << reqArg.typeInfo << "," << reqArg.usedVal << ","
<< foundString << "]\n"
<< " " << reqArg.desc << "\n\n";
}
if( numOptional > 0 )
output << "Optional arguments:\n";
int numOptFailed = 0;
for( int i=0; i<numOptional; ++i )
{
const OptionalArg& optArg = optionalArgs_[i];
if( !optArg.found )
++numOptFailed;
std::string foundString = ( optArg.found ? "found" : "NOT found" );
output << " " << optArg.name
<< " [" << optArg.typeInfo
<< "," << optArg.defaultVal << "," << optArg.usedVal << ","
<< foundString << "]\n"
<< " " << optArg.desc << "\n\n";
}
output << "Out of " << numRequired << " required arguments, "
<< numReqFailed << " were not specified." << std::endl;
output << "Out of " << numOptional << " optional arguments, "
<< numOptFailed << " were not specified.\n" << std::endl;
}
} // namespace choice
#endif // ifndef CHOICE_H
<commit_msg>Adding missing inline qualifiers for Cast function<commit_after>/*
Copyright (c) 2012-2013, Jack Poulson
All rights reserved.
This file is part of Choice and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#ifndef CHOICE_H
#define CHOICE_H 1
#include <algorithm>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <typeinfo>
#include <vector>
namespace choice {
template<typename TOut,typename TIn>
inline TOut Cast( const TIn& input )
{
std::stringstream stream;
TOut output;
stream << input;
stream >> output;
return output;
}
template<>
inline bool Cast( const std::string& input )
{
std::string trueString("true");
std::string falseString("false");
if( input.compare(trueString) == 0 )
return true;
else if( input.compare(falseString) == 0 )
return false;
else
{
bool output;
std::stringstream stream;
stream << input;
stream >> output;
return output;
}
}
class ArgException : public std::logic_error
{
public:
ArgException( const char* msg="Argument exception" )
: std::logic_error( msg ) { }
};
class Args
{
public:
Args( int argc, char** argv, std::ostream& error=std::cerr );
template<typename T>
T Input( std::string name, std::string desc );
template<typename T>
T Input( std::string name, std::string desc, T defaultVal );
void Process( std::ostream& output=std::cout ) const;
void PrintReport( std::ostream& output=std::cout ) const;
private:
int argc_;
char** argv_;
std::vector<bool> usedArgs_;
std::ostream& error_;
struct RequiredArg
{
std::string name, desc, typeInfo, usedVal;
bool found;
RequiredArg
( std::string n, std::string d, std::string t, std::string uv, bool f )
: name(n), desc(d), typeInfo(t), usedVal(uv), found(f) { };
};
struct OptionalArg
{
std::string name, desc, typeInfo, defaultVal, usedVal;
bool found;
OptionalArg
( std::string n, std::string d, std::string t,
std::string dv, std::string uv, bool f )
: name(n), desc(d), typeInfo(t),
defaultVal(dv), usedVal(uv), found(f) { }
};
std::vector<RequiredArg> requiredArgs_;
std::vector<OptionalArg> optionalArgs_;
};
inline
Args::Args( int argc, char** argv, std::ostream& error )
: argc_(argc), argv_(argv), usedArgs_(argc,false), error_(error)
{ }
template<typename T>
inline T
Args::Input( std::string name, std::string desc )
{
char** arg = std::find( argv_, argv_+argc_, name );
const bool found = ( arg != argv_+argc_ );
const bool invalidFound = ( arg == argv_+argc_-1 );
if( invalidFound )
{
error_ << "Missing value for last command-line argument" << std::endl;
throw ArgException();
}
std::string typeInfo( typeid(T).name() );
std::string usedVal = ( found ? arg[1] : "N/A" );
requiredArgs_.push_back( RequiredArg(name,desc,typeInfo,usedVal,found) );
// Before returning, store the used indices and check for duplication
if( found )
{
const int offset = arg - argv_;
if( usedArgs_[offset] || usedArgs_[offset+1] )
{
error_ << "WARNING: conflict with " << name << " detected at ";
if( usedArgs_[offset] && usedArgs_[offset+1] )
error_ << "arguments " << offset << " and " << offset+1
<< std::endl;
else if( usedArgs_[offset] )
error_ << "argument " << offset << std::endl;
else
error_ << "argument " << offset+1 << std::endl;
error_ << "Please ensure that you did request argument "
<< name << " multiple times" << std::endl;
}
usedArgs_[offset+0] = true;
usedArgs_[offset+1] = true;
arg = std::find( arg+1, argv_+argc_, name );
if( arg != argv_+argc_ )
error_ << "WARNING: " << name << " was specified twice and only "
<< "the first instance is used" << std::endl;
}
return Cast<T>( usedVal );
}
template<typename T>
inline T
Args::Input( std::string name, std::string desc, T defaultVal )
{
char** arg = std::find( argv_, argv_+argc_, name );
const bool found = ( arg != argv_+argc_ );
const bool invalidFound = ( arg == argv_+argc_-1 );
if( invalidFound )
{
error_ << "Missing value for last command-line argument" << std::endl;
throw ArgException();
}
std::string typeInfo( typeid(T).name() );
std::string defValString = Cast<std::string>( defaultVal );
std::string usedVal = ( found ? arg[1] : defValString );
optionalArgs_.push_back
( OptionalArg(name,desc,typeInfo,defValString,usedVal,found) );
// Before returning, store the used indices and check for duplication
if( found )
{
const int offset = arg - argv_;
if( usedArgs_[offset] || usedArgs_[offset+1] )
{
error_ << "WARNING: conflict with " << name << " detected at ";
if( usedArgs_[offset] && usedArgs_[offset+1] )
error_ << "arguments " << offset << " and " << offset+1
<< std::endl;
else if( usedArgs_[offset] )
error_ << "argument " << offset << std::endl;
else
error_ << "argument " << offset+1 << std::endl;
error_ << "Please ensure that you did request argument "
<< name << " multiple times" << std::endl;
}
usedArgs_[offset+0] = true;
usedArgs_[offset+1] = true;
arg = std::find( arg+1, argv_+argc_, name );
if( arg != argv_+argc_ )
error_ << "WARNING: " << name << " was specified twice and only "
<< "the first instance is used" << std::endl;
}
if( found )
return Cast<T>( usedVal );
else
return defaultVal; // avoid the double-cast
}
inline void
Args::Process( std::ostream& output ) const
{
std::string help = "--help";
char** arg = std::find( argv_, argv_+argc_, help );
const bool foundHelp = ( arg != argv_+argc_ );
int numFailed = 0;
const int numRequired = requiredArgs_.size();
for( int i=0; i<numRequired; ++i )
if( !requiredArgs_[i].found )
++numFailed;
if( numFailed > 0 || foundHelp )
{
PrintReport( output );
throw ArgException();
}
}
inline void
Args::PrintReport( std::ostream& output ) const
{
const int numRequired = requiredArgs_.size();
const int numOptional = optionalArgs_.size();
if( numRequired > 0 )
output << "Required arguments:\n";
int numReqFailed = 0;
for( int i=0; i<numRequired; ++i )
{
const RequiredArg& reqArg = requiredArgs_[i];
if( !reqArg.found )
++numReqFailed;
std::string foundString = ( reqArg.found ? "found" : "NOT found" );
output << " " << reqArg.name
<< " [" << reqArg.typeInfo << "," << reqArg.usedVal << ","
<< foundString << "]\n"
<< " " << reqArg.desc << "\n\n";
}
if( numOptional > 0 )
output << "Optional arguments:\n";
int numOptFailed = 0;
for( int i=0; i<numOptional; ++i )
{
const OptionalArg& optArg = optionalArgs_[i];
if( !optArg.found )
++numOptFailed;
std::string foundString = ( optArg.found ? "found" : "NOT found" );
output << " " << optArg.name
<< " [" << optArg.typeInfo
<< "," << optArg.defaultVal << "," << optArg.usedVal << ","
<< foundString << "]\n"
<< " " << optArg.desc << "\n\n";
}
output << "Out of " << numRequired << " required arguments, "
<< numReqFailed << " were not specified." << std::endl;
output << "Out of " << numOptional << " optional arguments, "
<< numOptFailed << " were not specified.\n" << std::endl;
}
} // namespace choice
#endif // ifndef CHOICE_H
<|endoftext|> |
<commit_before>/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2015 Imperial College London
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/InterpolateImageFunction.hxx"
#include "mirtk/GenericImage.h"
namespace mirtk {
// =============================================================================
// Construction/Destruction
// =============================================================================
// -----------------------------------------------------------------------------
InterpolateImageFunction::InterpolateImageFunction()
:
_NumberOfDimensions(0),
_InfiniteInput (NULL),
_InfiniteInputOwner(false),
_x1(.0), _y1(.0), _z1(.0), _t1(.0),
_x2(.0), _y2(.0), _z2(.0), _t2(.0)
{
}
// -----------------------------------------------------------------------------
InterpolateImageFunction::~InterpolateImageFunction()
{
if (_InfiniteInputOwner) delete _InfiniteInput;
}
// -----------------------------------------------------------------------------
template <class TImage>
InterpolateImageFunction *NewInterpolator(enum InterpolationMode mode, int dim = 0)
{
if (mode == Interpolation_Default) {
mode = DefaultInterpolationMode();
} else {
mode = InterpolationWithoutPadding(mode);
}
switch (dim) {
case 2: {
switch (mode) {
case Interpolation_NN: return new GenericNearestNeighborInterpolateImageFunction<TImage>();
case Interpolation_Linear: return new GenericLinearInterpolateImageFunction2D<TImage>();
case Interpolation_FastLinear: return new GenericLinearInterpolateImageFunction2D<TImage>();
case Interpolation_BSpline: return new GenericBSplineInterpolateImageFunction2D<TImage>();
case Interpolation_CubicBSpline: return new GenericCubicBSplineInterpolateImageFunction2D<TImage>();
case Interpolation_FastCubicBSpline: return new GenericFastCubicBSplineInterpolateImageFunction2D<TImage>();
case Interpolation_CSpline: return new GenericCSplineInterpolateImageFunction2D<TImage>();
case Interpolation_Gaussian: return new GenericGaussianInterpolateImageFunction2D<TImage>();
case Interpolation_Sinc: return new GenericSincInterpolateImageFunction2D<TImage>();
default: return NULL;
}
}
case 3: {
switch (mode) {
case Interpolation_NN: return new GenericNearestNeighborInterpolateImageFunction<TImage>();
case Interpolation_Linear: return new GenericLinearInterpolateImageFunction3D<TImage>();
case Interpolation_FastLinear: return new GenericLinearInterpolateImageFunction3D<TImage>();
case Interpolation_BSpline: return new GenericBSplineInterpolateImageFunction3D<TImage>();
case Interpolation_CubicBSpline: return new GenericCubicBSplineInterpolateImageFunction3D<TImage>();
case Interpolation_FastCubicBSpline: return new GenericFastCubicBSplineInterpolateImageFunction3D<TImage>();
case Interpolation_CSpline: return new GenericCSplineInterpolateImageFunction3D<TImage>();
case Interpolation_Gaussian: return new GenericGaussianInterpolateImageFunction3D<TImage>();
case Interpolation_Sinc: return new GenericSincInterpolateImageFunction3D<TImage>();
default: return NULL;
}
}
case 4: {
switch (mode) {
case Interpolation_NN: return new GenericNearestNeighborInterpolateImageFunction<TImage>();
case Interpolation_Linear: return new GenericLinearInterpolateImageFunction4D<TImage>();
case Interpolation_FastLinear: return new GenericLinearInterpolateImageFunction4D<TImage>();
case Interpolation_BSpline: return new GenericBSplineInterpolateImageFunction4D<TImage>();
case Interpolation_CubicBSpline: return new GenericCubicBSplineInterpolateImageFunction4D<TImage>();
case Interpolation_FastCubicBSpline: return new GenericFastCubicBSplineInterpolateImageFunction4D<TImage>();
case Interpolation_CSpline: return new GenericCSplineInterpolateImageFunction4D<TImage>();
case Interpolation_Gaussian: return new GenericGaussianInterpolateImageFunction4D<TImage>();
case Interpolation_Sinc: return new GenericSincInterpolateImageFunction4D<TImage>();
default: return NULL;
}
}
default: {
switch (mode) {
case Interpolation_NN: return new GenericNearestNeighborInterpolateImageFunction<TImage>();
case Interpolation_Linear: return new GenericLinearInterpolateImageFunction<TImage>();
case Interpolation_FastLinear: return new GenericLinearInterpolateImageFunction<TImage>();
case Interpolation_BSpline: return new GenericBSplineInterpolateImageFunction<TImage>();
case Interpolation_CubicBSpline: return new GenericCubicBSplineInterpolateImageFunction<TImage>();
case Interpolation_FastCubicBSpline: return new GenericFastCubicBSplineInterpolateImageFunction<TImage>();
case Interpolation_CSpline: return new GenericCSplineInterpolateImageFunction<TImage>();
case Interpolation_Gaussian: return new GenericGaussianInterpolateImageFunction<TImage>();
case Interpolation_Sinc: return new GenericSincInterpolateImageFunction<TImage>();
default: return NULL;
}
}
}
}
// -----------------------------------------------------------------------------
InterpolateImageFunction *
InterpolateImageFunction::New(enum InterpolationMode mode, const BaseImage *image)
{
InterpolateImageFunction *p = NULL;
if (mode == Interpolation_Default) {
mode = DefaultInterpolationMode();
} else {
mode = InterpolationWithoutPadding(mode);
}
// Dimensionality of image to interpolate
int dim = 0;
if (image) {
if (image->Z() == 1) dim = 2;
else if (image->T() == 1 || image->GetTSize() == .0) dim = 3;
else dim = 4;
}
// Instantiate special purpose interpolators
if (mode == Interpolation_SBased) {
// Only implemented for 3D scalar images
if (dim == 3 && (!image || image->N() == 1)) {
p = new ShapeBasedInterpolateImageFunction();
}
}
// Instantiate interpolator for generic image (i.e., instance of GenericImage)
if (!p && image) {
typedef GenericImage<char> CharImage;
typedef GenericImage<unsigned char> UCharImage;
typedef GenericImage<short> ShortImage;
typedef GenericImage<unsigned short> UShortImage;
typedef GenericImage<int> IntImage;
typedef GenericImage<unsigned int> UIntImage;
typedef GenericImage<float> FloatImage;
typedef GenericImage<double> DoubleImage;
if (dynamic_cast<const CharImage *>(image)) p = NewInterpolator<CharImage> (mode, dim);
else if (dynamic_cast<const UCharImage *>(image)) p = NewInterpolator<UCharImage> (mode, dim);
else if (dynamic_cast<const ShortImage *>(image)) p = NewInterpolator<ShortImage> (mode, dim);
else if (dynamic_cast<const UShortImage *>(image)) p = NewInterpolator<UShortImage>(mode, dim);
else if (dynamic_cast<const IntImage *>(image)) p = NewInterpolator<IntImage> (mode, dim);
else if (dynamic_cast<const UIntImage *>(image)) p = NewInterpolator<UIntImage> (mode, dim);
else if (dynamic_cast<const FloatImage *>(image)) p = NewInterpolator<FloatImage> (mode, dim);
else if (dynamic_cast<const DoubleImage *>(image)) p = NewInterpolator<DoubleImage>(mode, dim);
}
// Instantiate interpolator for general image (i.e., subclass of BaseImage)
if (!p) p = NewInterpolator<BaseImage>(mode, dim);
// Initialize interpolator
if (p) {
p->NumberOfDimensions(dim);
p->Input(image);
// Throw error if no suitable interpolator available
} else {
cerr << "InterpolateImageFunction::New: Interpolation mode (" << mode;
cerr << ") not supported for " << (dim ? ToString(dim) : "N") << "D images" << endl;
exit(1);
}
return p;
}
// -----------------------------------------------------------------------------
ExtrapolateImageFunction *
InterpolateImageFunction::New(enum ExtrapolationMode mode, const BaseImage *image)
{
return ExtrapolateImageFunction::New(mode, image);
}
// -----------------------------------------------------------------------------
InterpolateImageFunction *
InterpolateImageFunction::New(enum InterpolationMode imode,
enum ExtrapolationMode emode, const BaseImage *image)
{
InterpolateImageFunction *p = InterpolateImageFunction::New(imode, image);
if (emode != Extrapolation_Default) p->Extrapolator(p->New(emode, image), true);
return p;
}
// -----------------------------------------------------------------------------
void InterpolateImageFunction::Initialize(bool)
{
// Initialize image function
ImageFunction::Initialize();
// Check if input is a valid image
if (Input()->IsEmpty()) {
cerr << this->NameOfClass() << "::Initialize: Input image has zero extent" << endl;
exit(1);
}
// Determine dimensionality of input (if not specified by subclass/New)
if (_NumberOfDimensions == 0) {
if (Input()->Z() > 1) {
if (Input()->T() > 1 && Input()->GetTSize() != .0) _NumberOfDimensions = 4;
else _NumberOfDimensions = 3;
} else _NumberOfDimensions = 2;
}
// Default domain within which interpolation can be performed is assumed
// to be identical to the entire finite image domain
_x1 = .0;
_y1 = .0;
_z1 = .0;
_t1 = .0;
_x2 = Input()->X() - 1;
_y2 = Input()->Y() - 1;
_z2 = Input()->Z() - 1;
_t2 = Input()->T() - 1;
// Initialize extrapolator, i.e., infinite discrete image
if (_InfiniteInput) {
_InfiniteInput->Input(this->Input());
_InfiniteInput->Initialize();
}
}
} // namespace mirtk
////////////////////////////////////////////////////////////////////////////////
// Explicit instantiations
////////////////////////////////////////////////////////////////////////////////
// ND
#include "mirtk/NearestNeighborInterpolateImageFunction.hxx"
#include "mirtk/LinearInterpolateImageFunction.hxx"
#include "mirtk/BSplineInterpolateImageFunction.hxx"
#include "mirtk/CubicBSplineInterpolateImageFunction.hxx"
#include "mirtk/FastCubicBSplineInterpolateImageFunction.hxx"
#include "mirtk/CSplineInterpolateImageFunction.hxx"
#include "mirtk/GaussianInterpolateImageFunction.hxx"
#include "mirtk/SincInterpolateImageFunction.hxx"
// 2D
#include "mirtk/LinearInterpolateImageFunction2D.hxx"
#include "mirtk/BSplineInterpolateImageFunction2D.hxx"
#include "mirtk/CubicBSplineInterpolateImageFunction2D.hxx"
#include "mirtk/FastCubicBSplineInterpolateImageFunction2D.hxx"
#include "mirtk/CSplineInterpolateImageFunction2D.hxx"
#include "mirtk/GaussianInterpolateImageFunction2D.hxx"
#include "mirtk/SincInterpolateImageFunction2D.hxx"
// 3D
#include "mirtk/LinearInterpolateImageFunction3D.hxx"
#include "mirtk/BSplineInterpolateImageFunction3D.hxx"
#include "mirtk/CubicBSplineInterpolateImageFunction3D.hxx"
#include "mirtk/FastCubicBSplineInterpolateImageFunction3D.hxx"
#include "mirtk/CSplineInterpolateImageFunction3D.hxx"
#include "mirtk/GaussianInterpolateImageFunction3D.hxx"
#include "mirtk/SincInterpolateImageFunction3D.hxx"
// 4D
#include "mirtk/LinearInterpolateImageFunction4D.hxx"
#include "mirtk/BSplineInterpolateImageFunction4D.hxx"
#include "mirtk/CubicBSplineInterpolateImageFunction4D.hxx"
#include "mirtk/FastCubicBSplineInterpolateImageFunction4D.hxx"
#include "mirtk/CSplineInterpolateImageFunction4D.hxx"
#include "mirtk/GaussianInterpolateImageFunction4D.hxx"
#include "mirtk/SincInterpolateImageFunction4D.hxx"
namespace mirtk {
// Base class
mirtkInterpolatorInstantiations(GenericInterpolateImageFunction);
// ND
template class GenericNearestNeighborInterpolateImageFunction<ByteImage>;
mirtkInterpolatorInstantiations(GenericNearestNeighborInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericLinearInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericBSplineInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericCubicBSplineInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericFastCubicBSplineInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericCSplineInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericGaussianInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericSincInterpolateImageFunction);
// 2D
mirtkInterpolatorInstantiations(GenericLinearInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericBSplineInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericCubicBSplineInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericFastCubicBSplineInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericCSplineInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericGaussianInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericSincInterpolateImageFunction2D);
// 3D
mirtkInterpolatorInstantiations(GenericLinearInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericBSplineInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericCubicBSplineInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericFastCubicBSplineInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericCSplineInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericGaussianInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericSincInterpolateImageFunction3D);
// 4D
mirtkInterpolatorInstantiations(GenericLinearInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericBSplineInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericCubicBSplineInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericFastCubicBSplineInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericCSplineInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericGaussianInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericSincInterpolateImageFunction4D);
} // namespace mirtk
<commit_msg>enh: Add template instantiations for linear interpolation of ByteImage [Image]<commit_after>/*
* Medical Image Registration ToolKit (MIRTK)
*
* Copyright 2013-2015 Imperial College London
* Copyright 2013-2015 Andreas Schuh
*
* 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 "mirtk/InterpolateImageFunction.hxx"
#include "mirtk/GenericImage.h"
namespace mirtk {
// =============================================================================
// Construction/Destruction
// =============================================================================
// -----------------------------------------------------------------------------
InterpolateImageFunction::InterpolateImageFunction()
:
_NumberOfDimensions(0),
_InfiniteInput (NULL),
_InfiniteInputOwner(false),
_x1(.0), _y1(.0), _z1(.0), _t1(.0),
_x2(.0), _y2(.0), _z2(.0), _t2(.0)
{
}
// -----------------------------------------------------------------------------
InterpolateImageFunction::~InterpolateImageFunction()
{
if (_InfiniteInputOwner) delete _InfiniteInput;
}
// -----------------------------------------------------------------------------
template <class TImage>
InterpolateImageFunction *NewInterpolator(enum InterpolationMode mode, int dim = 0)
{
if (mode == Interpolation_Default) {
mode = DefaultInterpolationMode();
} else {
mode = InterpolationWithoutPadding(mode);
}
switch (dim) {
case 2: {
switch (mode) {
case Interpolation_NN: return new GenericNearestNeighborInterpolateImageFunction<TImage>();
case Interpolation_Linear: return new GenericLinearInterpolateImageFunction2D<TImage>();
case Interpolation_FastLinear: return new GenericLinearInterpolateImageFunction2D<TImage>();
case Interpolation_BSpline: return new GenericBSplineInterpolateImageFunction2D<TImage>();
case Interpolation_CubicBSpline: return new GenericCubicBSplineInterpolateImageFunction2D<TImage>();
case Interpolation_FastCubicBSpline: return new GenericFastCubicBSplineInterpolateImageFunction2D<TImage>();
case Interpolation_CSpline: return new GenericCSplineInterpolateImageFunction2D<TImage>();
case Interpolation_Gaussian: return new GenericGaussianInterpolateImageFunction2D<TImage>();
case Interpolation_Sinc: return new GenericSincInterpolateImageFunction2D<TImage>();
default: return NULL;
}
}
case 3: {
switch (mode) {
case Interpolation_NN: return new GenericNearestNeighborInterpolateImageFunction<TImage>();
case Interpolation_Linear: return new GenericLinearInterpolateImageFunction3D<TImage>();
case Interpolation_FastLinear: return new GenericLinearInterpolateImageFunction3D<TImage>();
case Interpolation_BSpline: return new GenericBSplineInterpolateImageFunction3D<TImage>();
case Interpolation_CubicBSpline: return new GenericCubicBSplineInterpolateImageFunction3D<TImage>();
case Interpolation_FastCubicBSpline: return new GenericFastCubicBSplineInterpolateImageFunction3D<TImage>();
case Interpolation_CSpline: return new GenericCSplineInterpolateImageFunction3D<TImage>();
case Interpolation_Gaussian: return new GenericGaussianInterpolateImageFunction3D<TImage>();
case Interpolation_Sinc: return new GenericSincInterpolateImageFunction3D<TImage>();
default: return NULL;
}
}
case 4: {
switch (mode) {
case Interpolation_NN: return new GenericNearestNeighborInterpolateImageFunction<TImage>();
case Interpolation_Linear: return new GenericLinearInterpolateImageFunction4D<TImage>();
case Interpolation_FastLinear: return new GenericLinearInterpolateImageFunction4D<TImage>();
case Interpolation_BSpline: return new GenericBSplineInterpolateImageFunction4D<TImage>();
case Interpolation_CubicBSpline: return new GenericCubicBSplineInterpolateImageFunction4D<TImage>();
case Interpolation_FastCubicBSpline: return new GenericFastCubicBSplineInterpolateImageFunction4D<TImage>();
case Interpolation_CSpline: return new GenericCSplineInterpolateImageFunction4D<TImage>();
case Interpolation_Gaussian: return new GenericGaussianInterpolateImageFunction4D<TImage>();
case Interpolation_Sinc: return new GenericSincInterpolateImageFunction4D<TImage>();
default: return NULL;
}
}
default: {
switch (mode) {
case Interpolation_NN: return new GenericNearestNeighborInterpolateImageFunction<TImage>();
case Interpolation_Linear: return new GenericLinearInterpolateImageFunction<TImage>();
case Interpolation_FastLinear: return new GenericLinearInterpolateImageFunction<TImage>();
case Interpolation_BSpline: return new GenericBSplineInterpolateImageFunction<TImage>();
case Interpolation_CubicBSpline: return new GenericCubicBSplineInterpolateImageFunction<TImage>();
case Interpolation_FastCubicBSpline: return new GenericFastCubicBSplineInterpolateImageFunction<TImage>();
case Interpolation_CSpline: return new GenericCSplineInterpolateImageFunction<TImage>();
case Interpolation_Gaussian: return new GenericGaussianInterpolateImageFunction<TImage>();
case Interpolation_Sinc: return new GenericSincInterpolateImageFunction<TImage>();
default: return NULL;
}
}
}
}
// -----------------------------------------------------------------------------
InterpolateImageFunction *
InterpolateImageFunction::New(enum InterpolationMode mode, const BaseImage *image)
{
InterpolateImageFunction *p = NULL;
if (mode == Interpolation_Default) {
mode = DefaultInterpolationMode();
} else {
mode = InterpolationWithoutPadding(mode);
}
// Dimensionality of image to interpolate
int dim = 0;
if (image) {
if (image->Z() == 1) dim = 2;
else if (image->T() == 1 || image->GetTSize() == .0) dim = 3;
else dim = 4;
}
// Instantiate special purpose interpolators
if (mode == Interpolation_SBased) {
// Only implemented for 3D scalar images
if (dim == 3 && (!image || image->N() == 1)) {
p = new ShapeBasedInterpolateImageFunction();
}
}
// Instantiate interpolator for generic image (i.e., instance of GenericImage)
if (!p && image) {
typedef GenericImage<char> CharImage;
typedef GenericImage<unsigned char> UCharImage;
typedef GenericImage<short> ShortImage;
typedef GenericImage<unsigned short> UShortImage;
typedef GenericImage<int> IntImage;
typedef GenericImage<unsigned int> UIntImage;
typedef GenericImage<float> FloatImage;
typedef GenericImage<double> DoubleImage;
if (dynamic_cast<const CharImage *>(image)) p = NewInterpolator<CharImage> (mode, dim);
else if (dynamic_cast<const UCharImage *>(image)) p = NewInterpolator<UCharImage> (mode, dim);
else if (dynamic_cast<const ShortImage *>(image)) p = NewInterpolator<ShortImage> (mode, dim);
else if (dynamic_cast<const UShortImage *>(image)) p = NewInterpolator<UShortImage>(mode, dim);
else if (dynamic_cast<const IntImage *>(image)) p = NewInterpolator<IntImage> (mode, dim);
else if (dynamic_cast<const UIntImage *>(image)) p = NewInterpolator<UIntImage> (mode, dim);
else if (dynamic_cast<const FloatImage *>(image)) p = NewInterpolator<FloatImage> (mode, dim);
else if (dynamic_cast<const DoubleImage *>(image)) p = NewInterpolator<DoubleImage>(mode, dim);
}
// Instantiate interpolator for general image (i.e., subclass of BaseImage)
if (!p) p = NewInterpolator<BaseImage>(mode, dim);
// Initialize interpolator
if (p) {
p->NumberOfDimensions(dim);
p->Input(image);
// Throw error if no suitable interpolator available
} else {
cerr << "InterpolateImageFunction::New: Interpolation mode (" << mode;
cerr << ") not supported for " << (dim ? ToString(dim) : "N") << "D images" << endl;
exit(1);
}
return p;
}
// -----------------------------------------------------------------------------
ExtrapolateImageFunction *
InterpolateImageFunction::New(enum ExtrapolationMode mode, const BaseImage *image)
{
return ExtrapolateImageFunction::New(mode, image);
}
// -----------------------------------------------------------------------------
InterpolateImageFunction *
InterpolateImageFunction::New(enum InterpolationMode imode,
enum ExtrapolationMode emode, const BaseImage *image)
{
InterpolateImageFunction *p = InterpolateImageFunction::New(imode, image);
if (emode != Extrapolation_Default) p->Extrapolator(p->New(emode, image), true);
return p;
}
// -----------------------------------------------------------------------------
void InterpolateImageFunction::Initialize(bool)
{
// Initialize image function
ImageFunction::Initialize();
// Check if input is a valid image
if (Input()->IsEmpty()) {
cerr << this->NameOfClass() << "::Initialize: Input image has zero extent" << endl;
exit(1);
}
// Determine dimensionality of input (if not specified by subclass/New)
if (_NumberOfDimensions == 0) {
if (Input()->Z() > 1) {
if (Input()->T() > 1 && Input()->GetTSize() != .0) _NumberOfDimensions = 4;
else _NumberOfDimensions = 3;
} else _NumberOfDimensions = 2;
}
// Default domain within which interpolation can be performed is assumed
// to be identical to the entire finite image domain
_x1 = .0;
_y1 = .0;
_z1 = .0;
_t1 = .0;
_x2 = Input()->X() - 1;
_y2 = Input()->Y() - 1;
_z2 = Input()->Z() - 1;
_t2 = Input()->T() - 1;
// Initialize extrapolator, i.e., infinite discrete image
if (_InfiniteInput) {
_InfiniteInput->Input(this->Input());
_InfiniteInput->Initialize();
}
}
} // namespace mirtk
////////////////////////////////////////////////////////////////////////////////
// Explicit instantiations
////////////////////////////////////////////////////////////////////////////////
// ND
#include "mirtk/NearestNeighborInterpolateImageFunction.hxx"
#include "mirtk/LinearInterpolateImageFunction.hxx"
#include "mirtk/BSplineInterpolateImageFunction.hxx"
#include "mirtk/CubicBSplineInterpolateImageFunction.hxx"
#include "mirtk/FastCubicBSplineInterpolateImageFunction.hxx"
#include "mirtk/CSplineInterpolateImageFunction.hxx"
#include "mirtk/GaussianInterpolateImageFunction.hxx"
#include "mirtk/SincInterpolateImageFunction.hxx"
// 2D
#include "mirtk/LinearInterpolateImageFunction2D.hxx"
#include "mirtk/BSplineInterpolateImageFunction2D.hxx"
#include "mirtk/CubicBSplineInterpolateImageFunction2D.hxx"
#include "mirtk/FastCubicBSplineInterpolateImageFunction2D.hxx"
#include "mirtk/CSplineInterpolateImageFunction2D.hxx"
#include "mirtk/GaussianInterpolateImageFunction2D.hxx"
#include "mirtk/SincInterpolateImageFunction2D.hxx"
// 3D
#include "mirtk/LinearInterpolateImageFunction3D.hxx"
#include "mirtk/BSplineInterpolateImageFunction3D.hxx"
#include "mirtk/CubicBSplineInterpolateImageFunction3D.hxx"
#include "mirtk/FastCubicBSplineInterpolateImageFunction3D.hxx"
#include "mirtk/CSplineInterpolateImageFunction3D.hxx"
#include "mirtk/GaussianInterpolateImageFunction3D.hxx"
#include "mirtk/SincInterpolateImageFunction3D.hxx"
// 4D
#include "mirtk/LinearInterpolateImageFunction4D.hxx"
#include "mirtk/BSplineInterpolateImageFunction4D.hxx"
#include "mirtk/CubicBSplineInterpolateImageFunction4D.hxx"
#include "mirtk/FastCubicBSplineInterpolateImageFunction4D.hxx"
#include "mirtk/CSplineInterpolateImageFunction4D.hxx"
#include "mirtk/GaussianInterpolateImageFunction4D.hxx"
#include "mirtk/SincInterpolateImageFunction4D.hxx"
namespace mirtk {
// Base class
mirtkInterpolatorInstantiations(GenericInterpolateImageFunction);
// ND
template class GenericNearestNeighborInterpolateImageFunction<ByteImage>;
template class GenericLinearInterpolateImageFunction<ByteImage>;
mirtkInterpolatorInstantiations(GenericNearestNeighborInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericLinearInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericBSplineInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericCubicBSplineInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericFastCubicBSplineInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericCSplineInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericGaussianInterpolateImageFunction);
mirtkInterpolatorInstantiations(GenericSincInterpolateImageFunction);
// 2D
template class GenericLinearInterpolateImageFunction2D<ByteImage>;
mirtkInterpolatorInstantiations(GenericLinearInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericBSplineInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericCubicBSplineInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericFastCubicBSplineInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericCSplineInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericGaussianInterpolateImageFunction2D);
mirtkInterpolatorInstantiations(GenericSincInterpolateImageFunction2D);
// 3D
template class GenericLinearInterpolateImageFunction3D<ByteImage>;
mirtkInterpolatorInstantiations(GenericLinearInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericBSplineInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericCubicBSplineInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericFastCubicBSplineInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericCSplineInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericGaussianInterpolateImageFunction3D);
mirtkInterpolatorInstantiations(GenericSincInterpolateImageFunction3D);
// 4D
template class GenericLinearInterpolateImageFunction4D<ByteImage>;
mirtkInterpolatorInstantiations(GenericLinearInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericBSplineInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericCubicBSplineInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericFastCubicBSplineInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericCSplineInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericGaussianInterpolateImageFunction4D);
mirtkInterpolatorInstantiations(GenericSincInterpolateImageFunction4D);
} // namespace mirtk
<|endoftext|> |
<commit_before>#include "TMessage.h"
#include "TBenchmark.h"
#include "TSocket.h"
#include "TH2.h"
#include "TTree.h"
#include "TMemFile.h"
#include "TRandom.h"
#include "TError.h"
#include "TFileMerger.h"
#include "TServerSocket.h"
#include "TPad.h"
#include "TCanvas.h"
#include "TMonitor.h"
#include "TFileCacheWrite.h"
#include "TSystem.h"
#include "THashTable.h"
#include "TMath.h"
#include "TTimeStamp.h"
const int kIncremental = 0;
const int kReplaceImmediately = 1;
const int kReplaceWait = 2;
#include "TKey.h"
static Bool_t R__NeedInitialMerge(TDirectory *dir)
{
if (dir==0) return kFALSE;
TIter nextkey(dir->GetListOfKeys());
TKey *key;
while( (key = (TKey*)nextkey()) ) {
TClass *cl = TClass::GetClass(key->GetClassName());
if (cl->InheritsFrom(TDirectory::Class())) {
TDirectory *subdir = (TDirectory *)dir->GetList()->FindObject(key->GetName());
if (!subdir) {
subdir = (TDirectory *)key->ReadObj();
}
if (R__NeedInitialMerge(subdir)) {
return kTRUE;
}
} else {
if (0 != cl->GetResetAfterMerge()) {
return kTRUE;
}
}
}
return kFALSE;
}
static void R__DeleteObject(TDirectory *dir, Bool_t withReset)
{
if (dir==0) return;
TIter nextkey(dir->GetListOfKeys());
TKey *key;
while( (key = (TKey*)nextkey()) ) {
TClass *cl = TClass::GetClass(key->GetClassName());
if (cl->InheritsFrom(TDirectory::Class())) {
TDirectory *subdir = (TDirectory *)dir->GetList()->FindObject(key->GetName());
if (!subdir) {
subdir = (TDirectory *)key->ReadObj();
}
R__DeleteObject(subdir,withReset);
} else {
Bool_t todelete = kFALSE;
if (withReset) {
todelete = (0 != cl->GetResetAfterMerge());
} else {
todelete = (0 == cl->GetResetAfterMerge());
}
if (todelete) {
key->Delete();
dir->GetListOfKeys()->Remove(key);
delete key;
}
}
}
}
static void R__MigrateKey(TDirectory *destination, TDirectory *source)
{
if (destination==0 || source==0) return;
TIter nextkey(source->GetListOfKeys());
TKey *key;
while( (key = (TKey*)nextkey()) ) {
TClass *cl = TClass::GetClass(key->GetClassName());
if (cl->InheritsFrom(TDirectory::Class())) {
TDirectory *source_subdir = (TDirectory *)source->GetList()->FindObject(key->GetName());
if (!source_subdir) {
source_subdir = (TDirectory *)key->ReadObj();
}
TDirectory *destination_subdir = destination->GetDirectory(key->GetName());
if (!destination_subdir) {
destination_subdir = destination->mkdir(key->GetName());
}
R__MigrateKey(destination,source);
} else {
TKey *oldkey = destination->GetKey(key->GetName());
if (oldkey) {
oldkey->Delete();
delete oldkey;
}
TKey *newkey = new TKey(destination,*key,0 /* pidoffset */); // a priori the file are from the same client ..
destination->GetFile()->SumBuffer(newkey->GetObjlen());
newkey->WriteFile(0);
if (destination->GetFile()->TestBit(TFile::kWriteError)) {
return;
}
}
}
destination->SaveSelf();
}
struct ClientInfo
{
TFile *fFile; // This object does *not* own the file, it will be own by the owner of the ClientInfo.
TString fLocalName;
UInt_t fContactsCount;
TTimeStamp fLastContact;
Double_t fTimeSincePrevContact;
ClientInfo() : fFile(0), fLocalName(), fContactsCount(0), fTimeSincePrevContact(0) {}
ClientInfo(const char *filename, UInt_t clientId) : fFile(0), fContactsCount(0), fTimeSincePrevContact(0) {
fLocalName.Form("%s-%d-%d",filename,clientId,gSystem->GetPid());
}
void Set(TFile *file)
{
// Register the new file as coming from this client.
if (file != fFile) {
// We need to keep any of the keys from the previous file that
// are not in the new file.
if (fFile) {
R__MigrateKey(fFile,file);
// delete the previous memory file (if any)
delete file;
} else {
fFile = file;
}
}
TTimeStamp now;
fTimeSincePrevContact = now.AsDouble() - fLastContact.AsDouble();
fLastContact = now;
++fContactsCount;
}
};
struct ParallelFileMerger : public TObject
{
typedef std::vector<ClientInfo> ClientColl_t;
TString fFilename;
TBits fClientsContact; //
UInt_t fNClientsContact; //
ClientColl_t fClients;
TTimeStamp fLastMerge;
TFileMerger fMerger;
ParallelFileMerger(const char *filename, Bool_t writeCache = kFALSE) : fFilename(filename), fNClientsContact(0), fMerger(kFALSE,kTRUE)
{
// Default constructor.
fMerger.SetPrintLevel(0);
fMerger.OutputFile(filename,"RECREATE");
if (writeCache) new TFileCacheWrite(fMerger.GetOutputFile(),32*1024*1024);
}
~ParallelFileMerger()
{
// Destructor.
for(unsigned int f = 0 ; f < fClients.size(); ++f) {
fprintf(stderr,"Client %d reported %u times\n",f,fClients[f].fContactsCount);
}
for( ClientColl_t::iterator iter = fClients.begin();
iter != fClients.end();
++iter)
{
delete iter->fFile;
}
}
ULong_t Hash() const
{
// Return hash value for this object.
return fFilename.Hash();
}
const char *GetName() const
{
// Return the name of the object which is the name of the output file.
return fFilename;
}
Bool_t InitialMerge(TFile *input)
{
// Initial merge of the input to copy the resetable object (TTree) into the output
// and remove them from the input file.
fMerger.AddFile(input);
Bool_t result = fMerger.PartialMerge(TFileMerger::kIncremental | TFileMerger::kResetable);
R__DeleteObject(input,kTRUE);
return result;
}
Bool_t Merge()
{
// Merge the current inputs into the output file.
R__DeleteObject(fMerger.GetOutputFile(),kFALSE); // Remove object that can *not* be incrementally merge and will *not* be reset by the client code.
for(unsigned int f = 0 ; f < fClients.size(); ++f) {
fMerger.AddFile(fClients[f].fFile);
}
Bool_t result = fMerger.PartialMerge(TFileMerger::kAllIncremental);
// Remove any 'resetable' object (like TTree) from the input file so that they will not
// be re-merged. Keep only the object that always need to be re-merged (Histograms).
for(unsigned int f = 0 ; f < fClients.size(); ++f) {
if (fClients[f].fFile) {
R__DeleteObject(fClients[f].fFile,kTRUE);
} else {
// We back up the file (probably due to memory constraint)
TFile *file = TFile::Open(fClients[f].fLocalName,"UPDATE");
R__DeleteObject(file,kTRUE); // Remove object that can be incrementally merge and will be reset by the client code.
file->Write();
delete file;
}
}
fLastMerge = TTimeStamp();
fNClientsContact = 0;
fClientsContact.Clear();
return result;
}
Bool_t NeedFinalMerge()
{
// Return true, if there is any data that has not been merged.
return fClientsContact.CountBits() > 0;
}
Bool_t NeedMerge(Float_t clientThreshold)
{
// Return true, if enough client have reported
if (fClients.size()==0) {
return kFALSE;
}
// Calculate average and rms of the time between the last 2 contacts.
Double_t sum = 0;
Double_t sum2 = 0;
for(unsigned int c = 0 ; c < fClients.size(); ++c) {
sum += fClients[c].fTimeSincePrevContact;
sum2 += fClients[c].fTimeSincePrevContact*fClients[c].fTimeSincePrevContact;
}
Double_t avg = sum / fClients.size();
Double_t sigma = sum2 ? TMath::Sqrt( sum2 / fClients.size() - avg*avg) : 0;
Double_t target = avg + 2*sigma;
TTimeStamp now;
if ( (now.AsDouble() - fLastMerge.AsDouble()) > target) {
// Float_t cut = clientThreshold * fClients.size();
// if (!(fClientsContact.CountBits() > cut )) {
// for(unsigned int c = 0 ; c < fClients.size(); ++c) {
// fprintf(stderr,"%d:%f ",c,fClients[c].fTimeSincePrevContact);
// }
// fprintf(stderr,"merge:%f avg:%f target:%f\n",(now.AsDouble() - fLastMerge.AsDouble()),avg,target);
// }
return kTRUE;
}
Float_t cut = clientThreshold * fClients.size();
return fClientsContact.CountBits() > cut || fNClientsContact > 2*cut;
}
void RegisterClient(UInt_t clientId, TFile *file)
{
// Register that a client has sent a file.
++fNClientsContact;
fClientsContact.SetBitNumber(clientId);
if (fClients.size() < clientId+1) {
fClients.push_back( ClientInfo(fFilename,clientId) );
}
fClients[clientId].Set(file);
}
ClassDef(ParallelFileMerger,0);
};
void parallelMergeServer(bool cache = false) {
// This script shows how to make a simple iterative server that
// can accept connections while handling currently open connections.
// Compare this script to hserv.C that blocks on accept.
// In this script a server socket is created and added to a monitor.
// A monitor object is used to monitor connection requests on
// the server socket. After accepting the connection
// the new socket is added to the monitor and immediately ready
// for use. Once two connections are accepted the server socket
// is removed from the monitor and closed. The monitor continues
// monitoring the sockets.
//
// To run this demo do the following:
// - Open three windows
// - Start ROOT in all three windows
// - Execute in the first window: .x hserv2.C
// - Execute in the second and third windows: .x hclient.C
//Author: Fons Rademakers
// Open a server socket looking for connections on a named service or
// on a specified port.
//TServerSocket *ss = new TServerSocket("rootserv", kTRUE);
TServerSocket *ss = new TServerSocket(1095, kTRUE);
if (!ss->IsValid()) {
return;
}
TMonitor *mon = new TMonitor;
mon->Add(ss);
UInt_t clientCount = 0;
THashTable mergers;
enum StatusKind {
kStartConnection = 0,
kProtocol = 1,
kProtocolVersion = 1
};
printf("fastMergeServerHist ready to accept connections\n");
while (1) {
TMessage *mess;
TSocket *s;
// NOTE: this needs to be update to handle the case where the client
// dies.
s = mon->Select();
if (s->IsA() == TServerSocket::Class()) {
if (clientCount > 100) {
printf("only accept 100 clients connections\n");
mon->Remove(ss);
ss->Close();
} else {
TSocket *client = ((TServerSocket *)s)->Accept();
client->Send(clientCount, kStartConnection);
client->Send(kProtocolVersion, kProtocol);
++clientCount;
mon->Add(client);
printf("Accept %d connections\n",clientCount);
}
continue;
}
s->Recv(mess);
if (mess==0) {
Error("fastMergeServer","The client did not send a message\n");
} else if (mess->What() == kMESS_STRING) {
char str[64];
mess->ReadString(str, 64);
printf("Client %d: %s\n", clientCount, str);
mon->Remove(s);
printf("Client %d: bytes recv = %d, bytes sent = %d\n", clientCount, s->GetBytesRecv(),
s->GetBytesSent());
s->Close();
--clientCount;
if (mon->GetActive() == 0 || clientCount == 0) {
printf("No more active clients... stopping\n");
break;
}
} else if (mess->What() == kMESS_ANY) {
Long64_t length;
TString filename;
Int_t clientId;
mess->ReadInt(clientId);
mess->ReadTString(filename);
mess->ReadLong64(length); // '*mess >> length;' is broken in CINT for Long64_t.
// Info("fastMergeServerHist","Received input from client %d for %s",clientId,filename.Data());
TMemFile *transient = new TMemFile(filename,mess->Buffer() + mess->Length(),length,"UPDATE"); // UPDATE because we need to remove the TTree after merging them.
mess->SetBufferOffset(mess->Length()+length);
const Float_t clientThreshold = 0.75; // control how often the histogram are merged. Here as soon as half the clients have reported.
ParallelFileMerger *info = (ParallelFileMerger*)mergers.FindObject(filename);
if (!info) {
info = new ParallelFileMerger(filename,cache);
mergers.Add(info);
}
if (R__NeedInitialMerge(transient)) {
info->InitialMerge(transient);
}
info->RegisterClient(clientId,transient);
if (info->NeedMerge(clientThreshold)) {
// Enough clients reported.
Info("fastMergeServerHist","Merging input from %ld clients (%d)",info->fClients.size(),clientId);
info->Merge();
}
transient = 0;
} else if (mess->What() == kMESS_OBJECT) {
printf("got object of class: %s\n", mess->GetClass()->GetName());
} else {
printf("*** Unexpected message ***\n");
}
delete mess;
}
TIter next(&mergers);
ParallelFileMerger *info;
while ( (info = (ParallelFileMerger*)next()) ) {
if (info->NeedFinalMerge())
{
info->Merge();
}
}
mergers.Delete();
delete mon;
delete ss;
}
<commit_msg>separate the clientCount from the clientIdx<commit_after>#include "TMessage.h"
#include "TBenchmark.h"
#include "TSocket.h"
#include "TH2.h"
#include "TTree.h"
#include "TMemFile.h"
#include "TRandom.h"
#include "TError.h"
#include "TFileMerger.h"
#include "TServerSocket.h"
#include "TPad.h"
#include "TCanvas.h"
#include "TMonitor.h"
#include "TFileCacheWrite.h"
#include "TSystem.h"
#include "THashTable.h"
#include "TMath.h"
#include "TTimeStamp.h"
const int kIncremental = 0;
const int kReplaceImmediately = 1;
const int kReplaceWait = 2;
#include "TKey.h"
static Bool_t R__NeedInitialMerge(TDirectory *dir)
{
if (dir==0) return kFALSE;
TIter nextkey(dir->GetListOfKeys());
TKey *key;
while( (key = (TKey*)nextkey()) ) {
TClass *cl = TClass::GetClass(key->GetClassName());
if (cl->InheritsFrom(TDirectory::Class())) {
TDirectory *subdir = (TDirectory *)dir->GetList()->FindObject(key->GetName());
if (!subdir) {
subdir = (TDirectory *)key->ReadObj();
}
if (R__NeedInitialMerge(subdir)) {
return kTRUE;
}
} else {
if (0 != cl->GetResetAfterMerge()) {
return kTRUE;
}
}
}
return kFALSE;
}
static void R__DeleteObject(TDirectory *dir, Bool_t withReset)
{
if (dir==0) return;
TIter nextkey(dir->GetListOfKeys());
TKey *key;
while( (key = (TKey*)nextkey()) ) {
TClass *cl = TClass::GetClass(key->GetClassName());
if (cl->InheritsFrom(TDirectory::Class())) {
TDirectory *subdir = (TDirectory *)dir->GetList()->FindObject(key->GetName());
if (!subdir) {
subdir = (TDirectory *)key->ReadObj();
}
R__DeleteObject(subdir,withReset);
} else {
Bool_t todelete = kFALSE;
if (withReset) {
todelete = (0 != cl->GetResetAfterMerge());
} else {
todelete = (0 == cl->GetResetAfterMerge());
}
if (todelete) {
key->Delete();
dir->GetListOfKeys()->Remove(key);
delete key;
}
}
}
}
static void R__MigrateKey(TDirectory *destination, TDirectory *source)
{
if (destination==0 || source==0) return;
TIter nextkey(source->GetListOfKeys());
TKey *key;
while( (key = (TKey*)nextkey()) ) {
TClass *cl = TClass::GetClass(key->GetClassName());
if (cl->InheritsFrom(TDirectory::Class())) {
TDirectory *source_subdir = (TDirectory *)source->GetList()->FindObject(key->GetName());
if (!source_subdir) {
source_subdir = (TDirectory *)key->ReadObj();
}
TDirectory *destination_subdir = destination->GetDirectory(key->GetName());
if (!destination_subdir) {
destination_subdir = destination->mkdir(key->GetName());
}
R__MigrateKey(destination,source);
} else {
TKey *oldkey = destination->GetKey(key->GetName());
if (oldkey) {
oldkey->Delete();
delete oldkey;
}
TKey *newkey = new TKey(destination,*key,0 /* pidoffset */); // a priori the file are from the same client ..
destination->GetFile()->SumBuffer(newkey->GetObjlen());
newkey->WriteFile(0);
if (destination->GetFile()->TestBit(TFile::kWriteError)) {
return;
}
}
}
destination->SaveSelf();
}
struct ClientInfo
{
TFile *fFile; // This object does *not* own the file, it will be own by the owner of the ClientInfo.
TString fLocalName;
UInt_t fContactsCount;
TTimeStamp fLastContact;
Double_t fTimeSincePrevContact;
ClientInfo() : fFile(0), fLocalName(), fContactsCount(0), fTimeSincePrevContact(0) {}
ClientInfo(const char *filename, UInt_t clientId) : fFile(0), fContactsCount(0), fTimeSincePrevContact(0) {
fLocalName.Form("%s-%d-%d",filename,clientId,gSystem->GetPid());
}
void Set(TFile *file)
{
// Register the new file as coming from this client.
if (file != fFile) {
// We need to keep any of the keys from the previous file that
// are not in the new file.
if (fFile) {
R__MigrateKey(fFile,file);
// delete the previous memory file (if any)
delete file;
} else {
fFile = file;
}
}
TTimeStamp now;
fTimeSincePrevContact = now.AsDouble() - fLastContact.AsDouble();
fLastContact = now;
++fContactsCount;
}
};
struct ParallelFileMerger : public TObject
{
typedef std::vector<ClientInfo> ClientColl_t;
TString fFilename;
TBits fClientsContact; //
UInt_t fNClientsContact; //
ClientColl_t fClients;
TTimeStamp fLastMerge;
TFileMerger fMerger;
ParallelFileMerger(const char *filename, Bool_t writeCache = kFALSE) : fFilename(filename), fNClientsContact(0), fMerger(kFALSE,kTRUE)
{
// Default constructor.
fMerger.SetPrintLevel(0);
fMerger.OutputFile(filename,"RECREATE");
if (writeCache) new TFileCacheWrite(fMerger.GetOutputFile(),32*1024*1024);
}
~ParallelFileMerger()
{
// Destructor.
for(unsigned int f = 0 ; f < fClients.size(); ++f) {
fprintf(stderr,"Client %d reported %u times\n",f,fClients[f].fContactsCount);
}
for( ClientColl_t::iterator iter = fClients.begin();
iter != fClients.end();
++iter)
{
delete iter->fFile;
}
}
ULong_t Hash() const
{
// Return hash value for this object.
return fFilename.Hash();
}
const char *GetName() const
{
// Return the name of the object which is the name of the output file.
return fFilename;
}
Bool_t InitialMerge(TFile *input)
{
// Initial merge of the input to copy the resetable object (TTree) into the output
// and remove them from the input file.
fMerger.AddFile(input);
Bool_t result = fMerger.PartialMerge(TFileMerger::kIncremental | TFileMerger::kResetable);
R__DeleteObject(input,kTRUE);
return result;
}
Bool_t Merge()
{
// Merge the current inputs into the output file.
R__DeleteObject(fMerger.GetOutputFile(),kFALSE); // Remove object that can *not* be incrementally merge and will *not* be reset by the client code.
for(unsigned int f = 0 ; f < fClients.size(); ++f) {
fMerger.AddFile(fClients[f].fFile);
}
Bool_t result = fMerger.PartialMerge(TFileMerger::kAllIncremental);
// Remove any 'resetable' object (like TTree) from the input file so that they will not
// be re-merged. Keep only the object that always need to be re-merged (Histograms).
for(unsigned int f = 0 ; f < fClients.size(); ++f) {
if (fClients[f].fFile) {
R__DeleteObject(fClients[f].fFile,kTRUE);
} else {
// We back up the file (probably due to memory constraint)
TFile *file = TFile::Open(fClients[f].fLocalName,"UPDATE");
R__DeleteObject(file,kTRUE); // Remove object that can be incrementally merge and will be reset by the client code.
file->Write();
delete file;
}
}
fLastMerge = TTimeStamp();
fNClientsContact = 0;
fClientsContact.Clear();
return result;
}
Bool_t NeedFinalMerge()
{
// Return true, if there is any data that has not been merged.
return fClientsContact.CountBits() > 0;
}
Bool_t NeedMerge(Float_t clientThreshold)
{
// Return true, if enough client have reported
if (fClients.size()==0) {
return kFALSE;
}
// Calculate average and rms of the time between the last 2 contacts.
Double_t sum = 0;
Double_t sum2 = 0;
for(unsigned int c = 0 ; c < fClients.size(); ++c) {
sum += fClients[c].fTimeSincePrevContact;
sum2 += fClients[c].fTimeSincePrevContact*fClients[c].fTimeSincePrevContact;
}
Double_t avg = sum / fClients.size();
Double_t sigma = sum2 ? TMath::Sqrt( sum2 / fClients.size() - avg*avg) : 0;
Double_t target = avg + 2*sigma;
TTimeStamp now;
if ( (now.AsDouble() - fLastMerge.AsDouble()) > target) {
// Float_t cut = clientThreshold * fClients.size();
// if (!(fClientsContact.CountBits() > cut )) {
// for(unsigned int c = 0 ; c < fClients.size(); ++c) {
// fprintf(stderr,"%d:%f ",c,fClients[c].fTimeSincePrevContact);
// }
// fprintf(stderr,"merge:%f avg:%f target:%f\n",(now.AsDouble() - fLastMerge.AsDouble()),avg,target);
// }
return kTRUE;
}
Float_t cut = clientThreshold * fClients.size();
return fClientsContact.CountBits() > cut || fNClientsContact > 2*cut;
}
void RegisterClient(UInt_t clientId, TFile *file)
{
// Register that a client has sent a file.
++fNClientsContact;
fClientsContact.SetBitNumber(clientId);
if (fClients.size() < clientId+1) {
fClients.push_back( ClientInfo(fFilename,clientId) );
}
fClients[clientId].Set(file);
}
ClassDef(ParallelFileMerger,0);
};
void parallelMergeServer(bool cache = false) {
// This script shows how to make a simple iterative server that
// can accept connections while handling currently open connections.
// Compare this script to hserv.C that blocks on accept.
// In this script a server socket is created and added to a monitor.
// A monitor object is used to monitor connection requests on
// the server socket. After accepting the connection
// the new socket is added to the monitor and immediately ready
// for use. Once two connections are accepted the server socket
// is removed from the monitor and closed. The monitor continues
// monitoring the sockets.
//
// To run this demo do the following:
// - Open three windows
// - Start ROOT in all three windows
// - Execute in the first window: .x hserv2.C
// - Execute in the second and third windows: .x hclient.C
//Author: Fons Rademakers
// Open a server socket looking for connections on a named service or
// on a specified port.
//TServerSocket *ss = new TServerSocket("rootserv", kTRUE);
TServerSocket *ss = new TServerSocket(1095, kTRUE);
if (!ss->IsValid()) {
return;
}
TMonitor *mon = new TMonitor;
mon->Add(ss);
UInt_t clientCount = 0;
UInt_t clientIndex = 0;
THashTable mergers;
enum StatusKind {
kStartConnection = 0,
kProtocol = 1,
kProtocolVersion = 1
};
printf("fastMergeServerHist ready to accept connections\n");
while (1) {
TMessage *mess;
TSocket *s;
// NOTE: this needs to be update to handle the case where the client
// dies.
s = mon->Select();
if (s->IsA() == TServerSocket::Class()) {
if (clientCount > 100) {
printf("only accept 100 clients connections\n");
mon->Remove(ss);
ss->Close();
} else {
TSocket *client = ((TServerSocket *)s)->Accept();
client->Send(clientIndex, kStartConnection);
client->Send(kProtocolVersion, kProtocol);
++clientCount;
++clientIndex;
mon->Add(client);
printf("Accept %d connections\n",clientCount);
}
continue;
}
s->Recv(mess);
if (mess==0) {
Error("fastMergeServer","The client did not send a message\n");
} else if (mess->What() == kMESS_STRING) {
char str[64];
mess->ReadString(str, 64);
printf("Client %d: %s\n", clientCount, str);
mon->Remove(s);
printf("Client %d: bytes recv = %d, bytes sent = %d\n", clientCount, s->GetBytesRecv(),
s->GetBytesSent());
s->Close();
--clientCount;
if (mon->GetActive() == 0 || clientCount == 0) {
printf("No more active clients... stopping\n");
break;
}
} else if (mess->What() == kMESS_ANY) {
Long64_t length;
TString filename;
Int_t clientId;
mess->ReadInt(clientId);
mess->ReadTString(filename);
mess->ReadLong64(length); // '*mess >> length;' is broken in CINT for Long64_t.
// Info("fastMergeServerHist","Received input from client %d for %s",clientId,filename.Data());
TMemFile *transient = new TMemFile(filename,mess->Buffer() + mess->Length(),length,"UPDATE"); // UPDATE because we need to remove the TTree after merging them.
mess->SetBufferOffset(mess->Length()+length);
const Float_t clientThreshold = 0.75; // control how often the histogram are merged. Here as soon as half the clients have reported.
ParallelFileMerger *info = (ParallelFileMerger*)mergers.FindObject(filename);
if (!info) {
info = new ParallelFileMerger(filename,cache);
mergers.Add(info);
}
if (R__NeedInitialMerge(transient)) {
info->InitialMerge(transient);
}
info->RegisterClient(clientId,transient);
if (info->NeedMerge(clientThreshold)) {
// Enough clients reported.
Info("fastMergeServerHist","Merging input from %ld clients (%d)",info->fClients.size(),clientId);
info->Merge();
}
transient = 0;
} else if (mess->What() == kMESS_OBJECT) {
printf("got object of class: %s\n", mess->GetClass()->GetName());
} else {
printf("*** Unexpected message ***\n");
}
delete mess;
}
TIter next(&mergers);
ParallelFileMerger *info;
while ( (info = (ParallelFileMerger*)next()) ) {
if (info->NeedFinalMerge())
{
info->Merge();
}
}
mergers.Delete();
delete mon;
delete ss;
}
<|endoftext|> |
<commit_before>#include "base64.hpp"
std::string base64_encode(const std::string &in)
{
char *map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string result;
int len = (int)in.size();
unsigned long value;
for(int i=0; i<len;)
{
switch(len-i)
{
case 1:
// There's only one character left, so I have to pad with two '='
value = 0xff & in[i];
result += map[0x3f & (value >> 2)];
result += map[0x3f & (value << 4)];
result += "==";
i = len;
break;
case 2:;
// There's only one character left, so I have to pad with one '='
value = ((0xff & in[i]) << 8) | (0xff & in[i+1]);
result += map[0x3f & (value >> 10)];
result += map[0x3f & (value >> 4)];
result += map[0x3f & (value << 2)];
result += "=";
i = len;
break;
default:
// I encode three characters in four
value = ((0xff & in[i]) << 16) | ((0xff & in[i+1]) << 8) | (0xff & in[i+2]);
result += map[0x3f & (value >> 18)];
result += map[0x3f & (value >> 12)];
result += map[0x3f & (value >> 6)];
result += map[0x3f & (value >> 0)];
i += 3;
break;
}
}
return result;
}
static short base64_char_decode_map(const char c)
{
short result;
if (isupper(c))
{
result = c - 'A';
}
else
{
if (islower(c))
{
result = 26 + c - 'a';
}
else
{
if (isdigit(c))
{
result = 52 + c - '0';
}
else
{
if ('+' == c)
{
result = 62;
}
else
{
if ('/' == c)
{
result = 63;
}
else
{
result = -1;
}
}
}
}
}
return result;
}
std::string base64_decode(const std::string &s)
{
std::string result;
unsigned long value;
short m;
int len, not_there, accumulated;
len = s.size();
not_there = 0;
accumulated = 0;
for (int i=0; i<len; ++i)
{
if ('=' != s[i])
{
m= base64_char_decode_map(s[i]);
if (0 <= m)
{
++accumulated;
value = (value << 6) | m;
}
}
else
{
m = 0;
++accumulated;
++not_there;
value = (value << 6) | m;
}
if (4 == accumulated)
{
switch(not_there)
{
case 1:
result += (unsigned char)(0xff & (value>>16));
result += (unsigned char)(0xff & (value>>8));
break;
case 2:
result += (unsigned char)(0xff & (value>>16));
break;
default:
result += (unsigned char)(0xff & (value>>16));
result += (unsigned char)(0xff & (value>>8));
result += (unsigned char)(0xff & (value>>0));
break;
}
accumulated = 0;
not_there = 0;
}
}
return result;
}
#ifdef DEBUG_BASE64
#include <iostream>
int
main (int argc, char *argv[]) {
CStdString s;
s += '\0';
s += "jguthrie";
s += '\0';
s += "test";
CStdString e = base64_encode(s);
std::cout << "Encoding the string gets \"" << e << "\"\n";
std::cout << "Decoding \"" << e << "\"\n";
s = base64_decode(e);
for (unsigned i=0; i<s.size(); ++i) {
printf("Character s[%d] = '%c' (0x%02x)\n", i, isprint(s[i]) ? s[i] : '.',
s[i]);
}
}
#endif
#ifdef UTILITY
#include <iostream>
int
main(int argc, char **argv) {
if (argc > 1) {
CStdString s(argv[1]);
CStdString e = base64_encode(s);
std::cout << "Encoding the string \"" << s << "\" gives \"" << e << "\"\n";
e = base64_decode(s);
std::cout << "Decoding the string \"" << s << "\" gives \"" << e << "\"\n";
}
return 0;
}
#endif /* utility */
<commit_msg>Fix a warning in base64.cpp<commit_after>#include "base64.hpp"
std::string base64_encode(const std::string &in)
{
const std::string map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
std::string result;
int len = (int)in.size();
unsigned long value;
for(int i=0; i<len;)
{
switch(len-i)
{
case 1:
// There's only one character left, so I have to pad with two '='
value = 0xff & in[i];
result += map[0x3f & (value >> 2)];
result += map[0x3f & (value << 4)];
result += "==";
i = len;
break;
case 2:;
// There's only one character left, so I have to pad with one '='
value = ((0xff & in[i]) << 8) | (0xff & in[i+1]);
result += map[0x3f & (value >> 10)];
result += map[0x3f & (value >> 4)];
result += map[0x3f & (value << 2)];
result += "=";
i = len;
break;
default:
// I encode three characters in four
value = ((0xff & in[i]) << 16) | ((0xff & in[i+1]) << 8) | (0xff & in[i+2]);
result += map[0x3f & (value >> 18)];
result += map[0x3f & (value >> 12)];
result += map[0x3f & (value >> 6)];
result += map[0x3f & (value >> 0)];
i += 3;
break;
}
}
return result;
}
static short base64_char_decode_map(const char c)
{
short result;
if (isupper(c))
{
result = c - 'A';
}
else
{
if (islower(c))
{
result = 26 + c - 'a';
}
else
{
if (isdigit(c))
{
result = 52 + c - '0';
}
else
{
if ('+' == c)
{
result = 62;
}
else
{
if ('/' == c)
{
result = 63;
}
else
{
result = -1;
}
}
}
}
}
return result;
}
std::string base64_decode(const std::string &s)
{
std::string result;
unsigned long value;
short m;
int len, not_there, accumulated;
len = s.size();
not_there = 0;
accumulated = 0;
for (int i=0; i<len; ++i)
{
if ('=' != s[i])
{
m= base64_char_decode_map(s[i]);
if (0 <= m)
{
++accumulated;
value = (value << 6) | m;
}
}
else
{
m = 0;
++accumulated;
++not_there;
value = (value << 6) | m;
}
if (4 == accumulated)
{
switch(not_there)
{
case 1:
result += (unsigned char)(0xff & (value>>16));
result += (unsigned char)(0xff & (value>>8));
break;
case 2:
result += (unsigned char)(0xff & (value>>16));
break;
default:
result += (unsigned char)(0xff & (value>>16));
result += (unsigned char)(0xff & (value>>8));
result += (unsigned char)(0xff & (value>>0));
break;
}
accumulated = 0;
not_there = 0;
}
}
return result;
}
#ifdef DEBUG_BASE64
#include <iostream>
int
main (int argc, char *argv[]) {
CStdString s;
s += '\0';
s += "jguthrie";
s += '\0';
s += "test";
CStdString e = base64_encode(s);
std::cout << "Encoding the string gets \"" << e << "\"\n";
std::cout << "Decoding \"" << e << "\"\n";
s = base64_decode(e);
for (unsigned i=0; i<s.size(); ++i) {
printf("Character s[%d] = '%c' (0x%02x)\n", i, isprint(s[i]) ? s[i] : '.',
s[i]);
}
}
#endif
#ifdef UTILITY
#include <iostream>
int
main(int argc, char **argv) {
if (argc > 1) {
CStdString s(argv[1]);
CStdString e = base64_encode(s);
std::cout << "Encoding the string \"" << s << "\" gives \"" << e << "\"\n";
e = base64_decode(s);
std::cout << "Decoding the string \"" << s << "\" gives \"" << e << "\"\n";
}
return 0;
}
#endif /* utility */
<|endoftext|> |
<commit_before><commit_msg>Bugfix: `load_DDS_texture`: Fix integer overflow of `bufsize`.<commit_after><|endoftext|> |
<commit_before>#include "starlight_renderer.h"
#if defined(_WIN32) && defined(STARLIGHT_D3D10)
#include "starlight_d3d_shared.h"
#include "starlight_d3d10.h"
#include "starlight_renderer_windows.h"
#include <imgui.h>
#include "imgui_impl_dx10.h"
#include <d3d10_1.h>
#include <d3d10.h>
#include <d3dcompiler.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>
// Data
static ID3D10Device* g_pd3dDevice = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr;
static ID3D10RenderTargetView* g_mainRenderTargetView = nullptr;
void CreateRenderTarget()
{
DXGI_SWAP_CHAIN_DESC sd;
g_pSwapChain->GetDesc(&sd);
// Create the render target
ID3D10Texture2D* pBackBuffer;
D3D10_RENDER_TARGET_VIEW_DESC render_target_view_desc;
ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc));
render_target_view_desc.Format = sd.BufferDesc.Format;
render_target_view_desc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer);
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr);
pBackBuffer->Release();
}
void CleanupRenderTarget()
{
if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; }
}
HRESULT CreateDeviceD3D(HWND hWnd)
{
// Setup swap chain
DXGI_SWAP_CHAIN_DESC sd;
{
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
}
UINT createDeviceFlags = 0;
//createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
if (D3D10CreateDeviceAndSwapChain(nullptr, D3D10_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice) != S_OK)
return E_FAIL;
// Setup rasterizer
{
D3D10_RASTERIZER_DESC RSDesc;
memset(&RSDesc, 0, sizeof(D3D10_RASTERIZER_DESC));
RSDesc.FillMode = D3D10_FILL_SOLID;
RSDesc.CullMode = D3D10_CULL_NONE;
RSDesc.FrontCounterClockwise = FALSE;
RSDesc.DepthBias = 0;
RSDesc.SlopeScaledDepthBias = 0.0f;
RSDesc.DepthBiasClamp = 0;
RSDesc.DepthClipEnable = TRUE;
RSDesc.ScissorEnable = TRUE;
RSDesc.AntialiasedLineEnable = FALSE;
RSDesc.MultisampleEnable = (sd.SampleDesc.Count > 1) ? TRUE : FALSE;
ID3D10RasterizerState* pRState = nullptr;
g_pd3dDevice->CreateRasterizerState(&RSDesc, &pRState);
g_pd3dDevice->RSSetState(pRState);
pRState->Release();
}
CreateRenderTarget();
return S_OK;
}
extern LRESULT ImGui_ImplDX10_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
bool renderer::D3D10::ImGuiHandleEvent(WindowEvent* e) {
return (ImGui_ImplDX10_WndProcHandler(e->hWnd, e->msg, e->wParam, e->lParam) == 1);
}
void renderer::D3D10::Resize(int32_t width, int32_t height) {
ImGui_ImplDX10_InvalidateDeviceObjects();
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0, (UINT) width, (UINT) height, DXGI_FORMAT_UNKNOWN, 0);
CreateRenderTarget();
ImGui_ImplDX10_CreateDeviceObjects();
}
extern void ImGui_ImplDX10_NewFrame();
void renderer::D3D10::ImGuiNewFrame() {
ImGui_ImplDX10_NewFrame();
}
void CleanupDeviceD3D() {
CleanupRenderTarget();
SafeRelease(g_pSwapChain);
SafeRelease(g_pd3dDevice);
}
bool renderer::D3D10::Init(PlatformData* data)
{
if (CreateDeviceD3D(data->hWnd) != S_OK) {
CleanupDeviceD3D();
return false;
}
ImGui_ImplDX10_Init(data->hWnd, g_pd3dDevice);
return true;
}
void renderer::D3D10::Render() {
// Clear
ImVec4 clear_col = ImColor(114, 144, 154);
g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, (float*) &clear_col);
// TODO: Game rendering here
ImGui::Render();
// Present
g_pSwapChain->Present(0, 0);
}
void renderer::D3D10::Destroy() {
ImGui_ImplDX10_Shutdown();
CleanupDeviceD3D();
}
void renderer::D3D10::Update() {
// TODO
}
void renderer::D3D10::SetPlayerCameraViewMatrix(glm::mat4 matrix) {
// TODO
}
void renderer::D3D10::SetProjectionMatrix(glm::mat4 matrix) {
// TODO
}
int32_t renderer::D3D10::UploadMesh(Vertex* vertices, int32_t numVertices, int32_t* indices, int32_t numIndices) {
// TOOD
return -1;
}
#endif
<commit_msg>Fix DX10 resize crash<commit_after>#include "starlight_renderer.h"
#if defined(_WIN32) && defined(STARLIGHT_D3D10)
#include "starlight_d3d_shared.h"
#include "starlight_d3d10.h"
#include "starlight_renderer_windows.h"
#include <imgui.h>
#include "imgui_impl_dx10.h"
#include <d3d10_1.h>
#include <d3d10.h>
#include <d3dcompiler.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>
// Data
static ID3D10Device* g_pd3dDevice = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr;
static ID3D10RenderTargetView* g_mainRenderTargetView = nullptr;
void CreateRenderTarget()
{
DXGI_SWAP_CHAIN_DESC sd;
g_pSwapChain->GetDesc(&sd);
// Create the render target
ID3D10Texture2D* pBackBuffer;
D3D10_RENDER_TARGET_VIEW_DESC render_target_view_desc;
ZeroMemory(&render_target_view_desc, sizeof(render_target_view_desc));
render_target_view_desc.Format = sd.BufferDesc.Format;
render_target_view_desc.ViewDimension = D3D10_RTV_DIMENSION_TEXTURE2D;
g_pSwapChain->GetBuffer(0, __uuidof(ID3D10Texture2D), (LPVOID*)&pBackBuffer);
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, &render_target_view_desc, &g_mainRenderTargetView);
g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, nullptr);
pBackBuffer->Release();
}
void CleanupRenderTarget()
{
if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = nullptr; }
}
HRESULT CreateDeviceD3D(HWND hWnd)
{
// Setup swap chain
DXGI_SWAP_CHAIN_DESC sd;
{
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
}
UINT createDeviceFlags = 0;
//createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
if (D3D10CreateDeviceAndSwapChain(nullptr, D3D10_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice) != S_OK)
return E_FAIL;
// Setup rasterizer
{
D3D10_RASTERIZER_DESC RSDesc;
memset(&RSDesc, 0, sizeof(D3D10_RASTERIZER_DESC));
RSDesc.FillMode = D3D10_FILL_SOLID;
RSDesc.CullMode = D3D10_CULL_NONE;
RSDesc.FrontCounterClockwise = FALSE;
RSDesc.DepthBias = 0;
RSDesc.SlopeScaledDepthBias = 0.0f;
RSDesc.DepthBiasClamp = 0;
RSDesc.DepthClipEnable = TRUE;
RSDesc.ScissorEnable = TRUE;
RSDesc.AntialiasedLineEnable = FALSE;
RSDesc.MultisampleEnable = (sd.SampleDesc.Count > 1) ? TRUE : FALSE;
ID3D10RasterizerState* pRState = nullptr;
g_pd3dDevice->CreateRasterizerState(&RSDesc, &pRState);
g_pd3dDevice->RSSetState(pRState);
pRState->Release();
}
CreateRenderTarget();
return S_OK;
}
extern LRESULT ImGui_ImplDX10_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
bool renderer::D3D10::ImGuiHandleEvent(WindowEvent* e) {
return (ImGui_ImplDX10_WndProcHandler(e->hWnd, e->msg, e->wParam, e->lParam) == 1);
}
void renderer::D3D10::Resize(int32_t width, int32_t height) {
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0, 0, 0, DXGI_FORMAT_UNKNOWN, 0);
CreateRenderTarget();
}
extern void ImGui_ImplDX10_NewFrame();
void renderer::D3D10::ImGuiNewFrame() {
ImGui_ImplDX10_NewFrame();
}
void CleanupDeviceD3D() {
CleanupRenderTarget();
SafeRelease(g_pSwapChain);
SafeRelease(g_pd3dDevice);
}
bool renderer::D3D10::Init(PlatformData* data)
{
if (CreateDeviceD3D(data->hWnd) != S_OK) {
CleanupDeviceD3D();
return false;
}
ImGui_ImplDX10_Init(data->hWnd, g_pd3dDevice);
return true;
}
void renderer::D3D10::Render() {
// Clear
ImVec4 clear_col = ImColor(114, 144, 154);
g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, (float*) &clear_col);
// TODO: Game rendering here
ImGui::Render();
// Present
g_pSwapChain->Present(0, 0);
}
void renderer::D3D10::Destroy() {
ImGui_ImplDX10_Shutdown();
CleanupDeviceD3D();
}
void renderer::D3D10::Update() {
// TODO
}
void renderer::D3D10::SetPlayerCameraViewMatrix(glm::mat4 matrix) {
// TODO
}
void renderer::D3D10::SetProjectionMatrix(glm::mat4 matrix) {
// TODO
}
int32_t renderer::D3D10::UploadMesh(Vertex* vertices, int32_t numVertices, int32_t* indices, int32_t numIndices) {
// TOOD
return -1;
}
#endif
<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <stdio.h>
#include <tf/transform_listener.h>
#include "std_msgs/String.h"
//#include <cob_object_detection_msg/Detection.msg>
//#include <cob_object_detection_msgs/DetectObjects.h>
#include "geometry_msgs/PoseStamped.h"
#include <cob_object_detection_msgs/DetectionArray.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>
//void Callback(const cob_object_detection_msgs::Detection::Detection_::_pose_type msg) //You cannot subscribe just to the pose, you subscribe to the whole message. Therefore, the types must match
void Callback(const cob_object_detection_msgs::DetectionArray &msg) //const because we are just reading it, & to pass by reference
{
//int nvmark=0; //Visible markers
//ROS_INFO_STREAM("I heard " << msg); //"<<
//ROS_INFO_STREAM("Message 1: " << msg.detections[0].label);
//if (msg.detections.empty() != true) ROS_INFO_STREAM(msg.detections.size());
//char buffer [50];
if (msg.detections.empty() != true){
for (int i=0; i <= msg.detections.size()-1; i++){ //msg.detections.size()
try{
//ROS_INFO_STREAM("Message 1: " << msg.detections[i]); //Displays the whole detection information
switch (msg.detections[i].id){ //We do this so that we know that we can address the pose to the right marker. Will be replaced
case 0: {ROS_INFO("CF 0:"); break;};
case 1: {ROS_INFO("CF 1:"); break;};
case 2: {ROS_INFO("CF 2:"); break;};
case 3: {ROS_INFO("CF 3:"); break;};
}
ROS_INFO_STREAM(msg.detections[i].pose.pose);
}
catch(...){
//ROS_INFO("Failed to send Marker [%s]", i); //sprintf(buffer, i)
}
}
}
//else ROS_INFO("No Marker");
/* **** **** */
/* **** Function to chop the Detection Array into several Detection, so that they can be treated and sent separately**** */
/* **** Function to chop the Detection into the different datatypes and publish it **** */
/*for (int i=1; i<=nvmark+1; i++) //For all visible markers:
{
try{
ROS_INFO("Marker [s%]", i); //We could chop this marker
//Here we should chop the data that interests us, taking just the geometry_msgs::PoseStamped and send it to the
}
catch(){
ROS_INFO("Failed to send Marker [s%]", i);
}
}*/
}
int main(int argc, char **argv)
{
/**
* The ros::init() function needs to see argc and argv so that it can perform
* any ROS arguments and name remapping that were provided at the command line.
* For programmatic remappings you can use a different version of init() which takes
* remappings directly, but for most command-line programs, passing argc and argv is
* the easiest way to do it. The third argument to init() is the name of the node.
*
* You must call one of the versions of ros::init() before using any other
* part of the ROS system.
*/
ros::init(argc, argv, "listener");
/**
* NodeHandle is the main access point to communications with the ROS system.
* The first NodeHandle constructed will fully initialize this node, and the last
* NodeHandle destructed will close down the node.
*/
ros::NodeHandle nh;
/**
* The subscribe() call is how you tell ROS that you want to receive messages
* on a given topic. This invokes a call to the ROS
* master node, which keeps a registry of who is publishing and who
* is subscribing. Messages are passed to a callback function, here
* called chatterCallback. subscribe() returns a Subscriber object that you
* must hold on to until you want to unsubscribe. When all copies of the Subscriber
* object go out of scope, this callback will automatically be unsubscribed from
* this topic.
*
* The second parameter to the subscribe() function is the size of the message
* queue. If messages are arriving faster than they are being processed, this
* is the number of messages that will be buffered up before beginning to throw
* away the oldest ones.
*/
ros::Subscriber sub = nh.subscribe("/fiducials/fiducial_detection_array",1,Callback); //Basic subscriber. Just has the topic it is subscribed to, the callback function and how many messages it caches
/**
* ros::spin() will enter a loop, pumping callbacks. With this version, all
* callbacks will be called from within this thread (the main one). ros::spin()
* will exit when Ctrl-C is pressed, or the node is shutdown by the master.
*/
while(nh.ok()){
ros::spinOnce();
}
return 0;
}
<commit_msg>Irrelevant comments and failed attempts erased, cleaner code<commit_after>#include <ros/ros.h>
#include <stdio.h>
#include <tf/transform_listener.h>
#include "std_msgs/String.h"
#include "geometry_msgs/PoseStamped.h"
#include <cob_object_detection_msgs/DetectionArray.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>
void Callback(const cob_object_detection_msgs::DetectionArray &msg) //const because we are just reading it, & to pass by reference
{
if (msg.detections.empty() != true){
for (int i=0; i <= msg.detections.size()-1; i++){ //msg.detections.size()
try{
//ROS_INFO_STREAM("Message 1: " << msg.detections[i]); //Displays the whole detection information
switch (msg.detections[i].id){ //We do this so that we know that we can address the pose to the right marker. Will be replaced
case 0: {ROS_INFO("CF 0:"); break;};
case 1: {ROS_INFO("CF 1:"); break;};
case 2: {ROS_INFO("CF 2:"); break;};
case 3: {ROS_INFO("CF 3:"); break;};
default:{ROS_INFO("ID Fail"); break;}; //If an error occurs and the detections[i] is accessed erronially
}
ROS_INFO_STREAM(msg.detections[i].pose.pose);
}
catch(...){
ROS_INFO("Failed to send Marker "); //sprintf(buffer, i)); //Need to find how to efficiently convert int to string without too much pain
}
}
}
//else ROS_INFO("No Marker");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("/fiducials/fiducial_detection_array",1,Callback); //Basic subscriber. Just has the topic it is subscribed to, the callback function and how many messages it caches
while(nh.ok()){
ros::spinOnce();
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Bugfix: `loaders::load_FBX_texture`: PNG loading loplaceholder code.<commit_after><|endoftext|> |
<commit_before>#include "party.h"
std::shared_ptr<Party> cache_fetch_party(uint32_t charId) {
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::Party partyTable{};
Core::PartyMembers partyMembersTable{};
auto res = conn(sqlpp::select(sqlpp::all_of(partyTable)).from(
partyMembersTable.join(partyTable).on(partyMembersTable.id == partyTable.id))
.where(partyMembersTable.memberId == charId));
if (res.empty()) {
return {};
}
auto result = res.front();
Party party;
party.id = result.id;
party.name = result.name;
party.leader = result.leaderId;
party.options = result.options;
party.level = result.level;
party.last_got_item_index = result.lastGotItemIndex;
party.last_got_zuly_index = result.lastGotZulyIndex;
party.last_got_etc_index = result.lastGotEtcIndex;
// now we fetch all party members
auto res2 = conn(sqlpp::select(partyMembersTable.memberId).from(partyMembersTable)
.where(partyMembersTable.id == party.id).order_by(partyMembersTable.rank.desc()));
if (res.empty()) {
return {};
}
for (auto& r : res2) {
party.members.push_back(r.memberId);
}
return std::make_shared<Party>(party);
}
void cache_write_party(std::shared_ptr<Party> party) {
}
void cache_write_party_members(std::shared_ptr<Party> party) {
}
void cache_remove_party(std::shared_ptr<Party> party) {
}
<commit_msg>Update party.cpp<commit_after>#include "party.h"
std::shared_ptr<Party> cache_fetch_party(uint32_t charId) {
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::Party partyTable{};
Core::PartyMembers partyMembersTable{};
auto res = conn(sqlpp::select(sqlpp::all_of(partyTable)).from(
partyMembersTable.join(partyTable).on(partyMembersTable.id == partyTable.id))
.where(partyMembersTable.memberId == charId));
if (res.empty()) {
return {};
}
auto result = res.front();
Party party;
party.id = result.id;
party.name = result.name;
party.leader = result.leaderId;
party.options = result.options;
party.level = result.level;
party.last_got_item_index = result.lastGotItemIndex;
party.last_got_zuly_index = result.lastGotZulyIndex;
party.last_got_etc_index = result.lastGotEtcIndex;
// now we fetch all party members
auto res2 = conn(sqlpp::select(partyMembersTable.memberId).from(partyMembersTable)
.where(partyMembersTable.id == party.id).order_by(partyMembersTable.rank.desc()));
if (res.empty()) {
return {};
}
for (const auto& r : res2) {
party.members.push_back(r.memberId);
}
return {party};
}
void cache_create_party(std::shared_ptr<Party> party) {
if (!party) return;
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::Party partyTable{};
conn(sqlpp::insert_into(partyTable)
.set(partyTable.name = party->name)
.set(partyTable.leaderId = party->leader)
.set(partyTable.options = party->options)
.set(partyTable.level = party->level)
.set(partyTable.lastGotItemIndex = party->last_got_item_index)
.set(partyTable.lastGotEtcIndex = party->last_got_etc_index)
.set(partyTable.lastGotZulyIndex = party->last_got_zuly_index));
}
void cache_write_party(std::shared_ptr<Party> party) {
if (!party) return;
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::Party partyTable{};
conn(sqlpp::update(partyTable)
.set(partyTable.name = party->name)
.set(partyTable.leaderId = party->leader)
.set(partyTable.options = party->options)
.set(partyTable.level = party->level)
.set(partyTable.lastGotItemIndex = party->last_got_item_index)
.set(partyTable.lastGotEtcIndex = party->last_got_etc_index)
.set(partyTable.lastGotZulyIndex = party->last_got_zuly_index)
.where(partyTable.id == party->id));
}
void cache_write_party_members(std::shared_ptr<Party> party) {
if (!party) return;
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::PartyMembers partyMembersTable{};
conn(sqlpp::remove_from(partyMembersTable).where(partyMembersTable.id == party->id));
auto insert = sqlpp::insert_into(partyMembersTable).columns(partyMembersTable.id, partyMembersTable.memberId);
for (auto m : party-> members) {
multi_insert.values.add(partyMembersTable.id = party->id, partyMembersTable.memberId = m);
}
conn(insert);
}
void cache_remove_party(std::shared_ptr<Party> party) {
if (!party) return;
auto conn = Core::connectionPool.getConnection<Core::Osirose>();
Core::Party partyTable{};
conn(sqlpp::remove_from(partyTable).where(partyTable.id == party->id));
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperOutputImageParameter.h"
#include "otbClampImageFilter.h"
#include "otbImageIOFactory.h"
#include "itksys/SystemTools.hxx"
#ifdef OTB_USE_MPI
#include "otbMPIConfig.h"
#include "otbMPIVrtWriter.h"
#ifdef OTB_USE_SPTW
#include "otbSimpleParallelTiffWriter.h"
#endif
#endif
#define CAST_IMAGE_BASE( T, image_base ) \
{ \
T * img = dynamic_cast< T * >( image_base ); \
\
if( img ) \
{ \
SwitchInput< T >( img ); \
\
return; \
} \
}
namespace otb
{
namespace Wrapper
{
// Declare specialisation for UInt8RGBAImageType
template<>
void OutputImageParameter::SwitchInput(UInt8RGBAImageType * );
// Declare specialisation for UInt8RGBImageType
template <>
void OutputImageParameter::SwitchInput( UInt8RGBImageType * );
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float),
m_DefaultPixelType(ImagePixelType_float),
m_RAMValue(0)
{
SetName("Output Image");
SetKey("out");
}
OutputImageParameter::~OutputImageParameter()
{
}
std::string OutputImageParameter::ConvertPixelTypeToString(ImagePixelType type)
{
// TODO: Could be replaced by constant static string array e.g.:
// return PIXEL_TYPE_NAME[ type ];
std::string ret;
switch(type)
{
case ImagePixelType_uint8:
{
ret = "uint8";
break;
}
case ImagePixelType_int16:
{
ret = "int16";
break;
}
case ImagePixelType_uint16:
{
ret = "uint16";
break;
}
case ImagePixelType_int32:
{
ret = "int32";
break;
}
case ImagePixelType_uint32:
{
ret = "uint32";
break;
}
case ImagePixelType_float:
{
ret = "float";
break;
}
case ImagePixelType_double:
{
ret = "double";
break;
}
case ImagePixelType_cint16:
{
ret = "cint16";
break;
}
case ImagePixelType_cint32:
{
ret = "cint32";
break;
}
case ImagePixelType_cfloat:
{
ret = "cfloat";
break;
}
case ImagePixelType_cdouble:
{
ret = "cdouble";
break;
}
}
return ret;
}
bool
OutputImageParameter::ConvertStringToPixelType(const std::string &value, ImagePixelType &type)
{
// TODO: Could be replaced std::find_if() in constant static string
// array (see ::ConvertPixelTypeToString().
if (value == "uint8")
type = ImagePixelType_uint8;
else if (value == "int16")
type = ImagePixelType_int16;
else if (value == "uint16")
type = ImagePixelType_uint16;
else if (value == "int32")
type = ImagePixelType_int32;
else if (value == "uint32")
type = ImagePixelType_uint32;
else if (value == "float")
type = ImagePixelType_float;
else if (value == "double")
type = ImagePixelType_double;
else if (value == "cint16")
type = ImagePixelType_cint16;
else if (value == "cint32")
type = ImagePixelType_cint32;
else if (value == "cfloat")
type = ImagePixelType_cfloat;
else if (value == "cdouble")
type = ImagePixelType_cdouble;
else
return false;
return true;
}
void
OutputImageParameter
::InitializeWriters()
{
ImageBaseType * image = m_Image.GetPointer();
CAST_IMAGE_BASE( UInt8VectorImageType, image );
CAST_IMAGE_BASE( Int16VectorImageType, image );
CAST_IMAGE_BASE( UInt16VectorImageType, image );
CAST_IMAGE_BASE( Int32VectorImageType, image );
CAST_IMAGE_BASE( UInt32VectorImageType, image );
CAST_IMAGE_BASE( FloatVectorImageType, image );
CAST_IMAGE_BASE( DoubleVectorImageType, image );
CAST_IMAGE_BASE( ComplexInt16VectorImageType, image );
CAST_IMAGE_BASE( ComplexInt32VectorImageType, image );
CAST_IMAGE_BASE( ComplexFloatVectorImageType, image );
CAST_IMAGE_BASE( ComplexDoubleVectorImageType, image );
CAST_IMAGE_BASE( UInt8ImageType, image );
CAST_IMAGE_BASE( Int16ImageType, image );
CAST_IMAGE_BASE( UInt16ImageType, image );
CAST_IMAGE_BASE( Int32ImageType, image );
CAST_IMAGE_BASE( UInt32ImageType, image );
CAST_IMAGE_BASE( FloatImageType, image );
CAST_IMAGE_BASE( DoubleImageType, image );
CAST_IMAGE_BASE( ComplexInt16ImageType, image );
CAST_IMAGE_BASE( ComplexInt32ImageType, image );
CAST_IMAGE_BASE( ComplexFloatImageType, image );
CAST_IMAGE_BASE( ComplexDoubleImageType, image );
CAST_IMAGE_BASE( UInt8RGBImageType, image );
CAST_IMAGE_BASE( UInt8RGBAImageType, image );
itkExceptionMacro( "Unknown image-base type." );
}
namespace details
{
template< typename TOutputImage,
typename TInputImage >
struct Clamp
{
using InputClampImageFilter =
ClampImageFilter< TInputImage, DoubleVectorImageType >;
using OutputClampImageFilter =
ClampImageFilter< DoubleVectorImageType , TOutputImage >;
Clamp( TInputImage * in ) :
icif( InputClampImageFilter::New() ),
ocif( OutputClampImageFilter::New() ),
out( ocif->GetOutput() )
{
assert( in );
icif->SetInput( in );
ocif->SetInput( icif->GetOutput() );
}
typename InputClampImageFilter::Pointer icif;
typename OutputClampImageFilter::Pointer ocif;
TOutputImage * out;
};
template< typename TOutputImage >
struct Clamp< TOutputImage,
DoubleVectorImageType >
{
using OutputClampImageFilter =
ClampImageFilter< DoubleVectorImageType , TOutputImage >;
Clamp( DoubleVectorImageType * in ) :
ocif( OutputClampImageFilter::New() ),
out( ocif->GetOutput() )
{
assert( in );
ocif->SetInput( in );
}
itk::ProcessObject::Pointer icif;
typename OutputClampImageFilter::Pointer ocif;
TOutputImage * out;
};
template<>
struct Clamp< DoubleVectorImageType,
DoubleVectorImageType >
{
Clamp( DoubleVectorImageType * in ) :
out( in )
{
assert( in );
}
itk::ProcessObject::Pointer icif;
itk::ProcessObject::Pointer ocif;
DoubleVectorImageType * out;
};
} // namespace details.
template< typename TOutputImage,
typename TInputImage >
void
OutputImageParameter
::ClampAndWriteVectorImage( TInputImage * in )
{
assert( in );
assert( !m_FileName.empty() );
// Use metaprogramming to choose optimized pipeline.
details::Clamp< TOutputImage, TInputImage > clamp( in );
#ifdef OTB_USE_MPI
otb::MPIConfig::Pointer mpiConfig = otb::MPIConfig::Instance();
if( mpiConfig->GetNbProcs() > 1 )
{
std::string extension =
itksys::SystemTools::GetFilenameExtension( m_FileName );
if(extension == ".vrt")
{
// Use the MPIVrtWriter
auto vrtWriter =
otb::MPIVrtWriter< TOutputImage >::New();
vrtWriter->SetInput( clamp.out );
vrtWriter->SetFileName( m_FileName );
vrtWriter->SetAvailableRAM( m_RAMValue);
// Change internal state only when everything has been setup
// without raising exception.
m_InputCaster = clamp.icif;
m_OutputCaster = clamp.ocif;
m_Writer = vrtWriter;
return;
}
#ifdef OTB_USE_SPTW
else if (extension == ".tif")
{
// Use simple parallel tiff writer
auto sptWriter =
otb::SimpleParallelTiffWriter< TOutputImage >::New();
sptWriter->SetFileName( m_FileName );
sptWriter->SetInput( clamp.out );
sptWriter->GetStreamingManager()->SetDefaultRAM( m_RAMValue );
// Change internal state only when everything has been setup
// without raising exception.
m_InputCaster = clamp.icif;
m_OutputCaster = clamp.ocif;
m_Writer = sptWriter;
return;
}
#endif // OTB_USE_SPTW
else
{
itkGenericExceptionMacro(
"File format "
<< extension
<< " not supported for parallel writing with MPI. Supported formats are "
".vrt and .tif. Extended filenames are not supported."
);
}
}
#endif // OTB_USE_MPI
//
// Use default OTB writer.
auto writer = otb::ImageFileWriter< TOutputImage >::New();
writer->SetFileName( m_FileName );
writer->SetInput( clamp.out );
writer->GetStreamingManager()->SetDefaultRAM( m_RAMValue );
// Change internal state only when everything has been setup
// without raising exception.
m_InputCaster = clamp.icif;
m_OutputCaster = clamp.ocif;
m_Writer = writer;
}
template< typename TInputImage >
void
OutputImageParameter
::SwitchInput( TInputImage * image )
{
assert( image );
switch( m_PixelType )
{
case ImagePixelType_uint8:
ClampAndWriteVectorImage< UInt8VectorImageType >( image );
break;
case ImagePixelType_int16:
ClampAndWriteVectorImage< Int16VectorImageType >( image );
break;
case ImagePixelType_uint16:
ClampAndWriteVectorImage< UInt16VectorImageType >( image );
break;
case ImagePixelType_int32:
ClampAndWriteVectorImage< Int32VectorImageType >( image );
break;
case ImagePixelType_uint32:
ClampAndWriteVectorImage< UInt32VectorImageType >( image );
break;
case ImagePixelType_float:
ClampAndWriteVectorImage< FloatVectorImageType >( image );
break;
case ImagePixelType_double:
ClampAndWriteVectorImage< DoubleVectorImageType >( image );
break;
case ImagePixelType_cint16:
ClampAndWriteVectorImage < ComplexInt16VectorImageType >( image );
break;
case ImagePixelType_cint32:
ClampAndWriteVectorImage < ComplexInt32VectorImageType >( image );
break;
case ImagePixelType_cfloat:
ClampAndWriteVectorImage< ComplexFloatVectorImageType >( image );
break;
case ImagePixelType_cdouble:
ClampAndWriteVectorImage < ComplexDoubleVectorImageType >( image );
break;
default:
assert( false && "Unexpected image-type." );
break;
}
}
void
OutputImageParameter::Write()
{
m_Writer->Update();
// Clean internal filters
m_InputCaster = nullptr;
m_OutputCaster = nullptr;
m_Writer = nullptr;
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
return m_Writer;
}
ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter
::HasValue() const
{
return !m_FileName.empty();
}
std::string
OutputImageParameter::CheckFileName(bool fixMissingExtension)
{
std::string ret("");
// Check that there is an ImageIO capable of writing the file
otb::ExtendedFilenameToWriterOptions::Pointer filenameHelper =
otb::ExtendedFilenameToWriterOptions::New();
filenameHelper->SetExtendedFileName(this->GetFileName());
std::string simpleFilename = filenameHelper->GetSimpleFileName();
// TODO : check if simpleFilename is empty
otb::ImageIOBase::Pointer imageIO =
otb::ImageIOFactory::CreateImageIO(simpleFilename.c_str(),
otb::ImageIOFactory::WriteMode);
if(imageIO.IsNull())
{
// check for missing extension
std::string outExt = itksys::SystemTools::GetFilenameLastExtension(simpleFilename);
if (outExt.empty())
{
if (fixMissingExtension)
{
// try with .tif
std::string fullFileName(this->GetFileName());
std::string extendedPart = fullFileName.substr(simpleFilename.size());
this->SetFileName(simpleFilename+std::string(".tif")+extendedPart);
ret += std::string("no extension detected, using TIF as default.");
}
else
{
// TODO : call exception here?
}
}
else
{
// TODO : call exception here?
}
}
return ret;
}
// Specialization for UInt8RGBAImageType
template<>
void
OutputImageParameter
::SwitchInput( UInt8RGBAImageType * img )
{
assert( img );
if( m_PixelType != ImagePixelType_uint8 )
itkExceptionMacro("Unknown PixelType for RGBA Image. Only uint8 is supported.");
auto writer =
otb::ImageFileWriter< UInt8RGBAImageType >::New();
writer->SetFileName( GetFileName() );
writer->SetInput( img );
writer->GetStreamingManager()->SetDefaultRAM( m_RAMValue );
m_Writer = writer;
}
// Specialization for UInt8RGBImageType
template<>
void
OutputImageParameter
::SwitchInput( UInt8RGBImageType * img )
{
if( m_PixelType != ImagePixelType_uint8 )
itkExceptionMacro("Unknown PixelType for RGB Image. Only uint8 is supported.");
auto writer = otb::ImageFileWriter< UInt8RGBImageType >::New();
writer->SetFileName( GetFileName() );
writer->SetInput( img );
writer->GetStreamingManager()->SetDefaultRAM( m_RAMValue );
m_Writer = writer;
}
void OutputImageParameter::SetFileName (const char* filename)
{
this->SetFileName(std::string(filename));
}
void OutputImageParameter::SetFileName (const std::string& filename)
{
m_FileName = filename;
SetActive(true);
}
}
}
<commit_msg>ENH: 1649: Factorized otb::Wrapper::ClampAndWriteVectorImage<>().<commit_after>/*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbWrapperOutputImageParameter.h"
#include "otbClampImageFilter.h"
#include "otbImageIOFactory.h"
#include "otbWrapperCastImage.h"
#ifdef OTB_USE_MPI
# include "otbMPIConfig.h"
# include "otbMPIVrtWriter.h"
# ifdef OTB_USE_SPTW
# include "otbSimpleParallelTiffWriter.h"
# endif
#endif
#include "itksys/SystemTools.hxx"
#define CAST_IMAGE_BASE( T, image_base ) \
{ \
T * img = dynamic_cast< T * >( image_base ); \
\
if( img ) \
{ \
SwitchInput< T >( img ); \
\
return; \
} \
}
namespace otb
{
namespace Wrapper
{
// Declare specialisation for UInt8RGBAImageType
template<>
void OutputImageParameter::SwitchInput(UInt8RGBAImageType * );
// Declare specialisation for UInt8RGBImageType
template <>
void OutputImageParameter::SwitchInput( UInt8RGBImageType * );
OutputImageParameter::OutputImageParameter()
: m_PixelType(ImagePixelType_float),
m_DefaultPixelType(ImagePixelType_float),
m_RAMValue(0)
{
SetName("Output Image");
SetKey("out");
}
OutputImageParameter::~OutputImageParameter()
{
}
std::string OutputImageParameter::ConvertPixelTypeToString(ImagePixelType type)
{
// TODO: Could be replaced by constant static string array e.g.:
// return PIXEL_TYPE_NAME[ type ];
std::string ret;
switch(type)
{
case ImagePixelType_uint8:
{
ret = "uint8";
break;
}
case ImagePixelType_int16:
{
ret = "int16";
break;
}
case ImagePixelType_uint16:
{
ret = "uint16";
break;
}
case ImagePixelType_int32:
{
ret = "int32";
break;
}
case ImagePixelType_uint32:
{
ret = "uint32";
break;
}
case ImagePixelType_float:
{
ret = "float";
break;
}
case ImagePixelType_double:
{
ret = "double";
break;
}
case ImagePixelType_cint16:
{
ret = "cint16";
break;
}
case ImagePixelType_cint32:
{
ret = "cint32";
break;
}
case ImagePixelType_cfloat:
{
ret = "cfloat";
break;
}
case ImagePixelType_cdouble:
{
ret = "cdouble";
break;
}
}
return ret;
}
bool
OutputImageParameter::ConvertStringToPixelType(const std::string &value, ImagePixelType &type)
{
// TODO: Could be replaced std::find_if() in constant static string
// array (see ::ConvertPixelTypeToString().
if (value == "uint8")
type = ImagePixelType_uint8;
else if (value == "int16")
type = ImagePixelType_int16;
else if (value == "uint16")
type = ImagePixelType_uint16;
else if (value == "int32")
type = ImagePixelType_int32;
else if (value == "uint32")
type = ImagePixelType_uint32;
else if (value == "float")
type = ImagePixelType_float;
else if (value == "double")
type = ImagePixelType_double;
else if (value == "cint16")
type = ImagePixelType_cint16;
else if (value == "cint32")
type = ImagePixelType_cint32;
else if (value == "cfloat")
type = ImagePixelType_cfloat;
else if (value == "cdouble")
type = ImagePixelType_cdouble;
else
return false;
return true;
}
void
OutputImageParameter
::InitializeWriters()
{
ImageBaseType * image = m_Image.GetPointer();
CAST_IMAGE_BASE( UInt8VectorImageType, image );
CAST_IMAGE_BASE( Int16VectorImageType, image );
CAST_IMAGE_BASE( UInt16VectorImageType, image );
CAST_IMAGE_BASE( Int32VectorImageType, image );
CAST_IMAGE_BASE( UInt32VectorImageType, image );
CAST_IMAGE_BASE( FloatVectorImageType, image );
CAST_IMAGE_BASE( DoubleVectorImageType, image );
CAST_IMAGE_BASE( ComplexInt16VectorImageType, image );
CAST_IMAGE_BASE( ComplexInt32VectorImageType, image );
CAST_IMAGE_BASE( ComplexFloatVectorImageType, image );
CAST_IMAGE_BASE( ComplexDoubleVectorImageType, image );
CAST_IMAGE_BASE( UInt8ImageType, image );
CAST_IMAGE_BASE( Int16ImageType, image );
CAST_IMAGE_BASE( UInt16ImageType, image );
CAST_IMAGE_BASE( Int32ImageType, image );
CAST_IMAGE_BASE( UInt32ImageType, image );
CAST_IMAGE_BASE( FloatImageType, image );
CAST_IMAGE_BASE( DoubleImageType, image );
CAST_IMAGE_BASE( ComplexInt16ImageType, image );
CAST_IMAGE_BASE( ComplexInt32ImageType, image );
CAST_IMAGE_BASE( ComplexFloatImageType, image );
CAST_IMAGE_BASE( ComplexDoubleImageType, image );
CAST_IMAGE_BASE( UInt8RGBImageType, image );
CAST_IMAGE_BASE( UInt8RGBAImageType, image );
itkExceptionMacro( "Unknown image-base type." );
}
template< typename TOutputImage,
typename TInputImage >
void
OutputImageParameter
::ClampAndWriteVectorImage( TInputImage * in )
{
assert( in );
assert( !m_FileName.empty() );
// Use metaprogramming to choose optimized pipeline.
details::CastImage< TOutputImage, TInputImage > clamp( in );
#ifdef OTB_USE_MPI
otb::MPIConfig::Pointer mpiConfig = otb::MPIConfig::Instance();
if( mpiConfig->GetNbProcs() > 1 )
{
std::string extension =
itksys::SystemTools::GetFilenameExtension( m_FileName );
if(extension == ".vrt")
{
// Use the MPIVrtWriter
auto vrtWriter =
otb::MPIVrtWriter< TOutputImage >::New();
vrtWriter->SetInput( clamp.out );
vrtWriter->SetFileName( m_FileName );
vrtWriter->SetAvailableRAM( m_RAMValue);
// Change internal state only when everything has been setup
// without raising exception.
m_InputCaster = clamp.icif;
m_OutputCaster = clamp.ocif;
m_Writer = vrtWriter;
return;
}
#ifdef OTB_USE_SPTW
else if (extension == ".tif")
{
// Use simple parallel tiff writer
auto sptWriter =
otb::SimpleParallelTiffWriter< TOutputImage >::New();
sptWriter->SetFileName( m_FileName );
sptWriter->SetInput( clamp.out );
sptWriter->GetStreamingManager()->SetDefaultRAM( m_RAMValue );
// Change internal state only when everything has been setup
// without raising exception.
m_InputCaster = clamp.icif;
m_OutputCaster = clamp.ocif;
m_Writer = sptWriter;
return;
}
#endif // OTB_USE_SPTW
else
{
itkGenericExceptionMacro(
"File format "
<< extension
<< " not supported for parallel writing with MPI. Supported formats are "
".vrt and .tif. Extended filenames are not supported."
);
}
}
#endif // OTB_USE_MPI
//
// Use default OTB writer.
auto writer = otb::ImageFileWriter< TOutputImage >::New();
writer->SetFileName( m_FileName );
writer->SetInput( clamp.out );
writer->GetStreamingManager()->SetDefaultRAM( m_RAMValue );
// Change internal state only when everything has been setup
// without raising exception.
m_InputCaster = clamp.icif;
m_OutputCaster = clamp.ocif;
m_Writer = writer;
}
template< typename TInputImage >
void
OutputImageParameter
::SwitchInput( TInputImage * image )
{
assert( image );
switch( m_PixelType )
{
case ImagePixelType_uint8:
ClampAndWriteVectorImage< UInt8VectorImageType >( image );
break;
case ImagePixelType_int16:
ClampAndWriteVectorImage< Int16VectorImageType >( image );
break;
case ImagePixelType_uint16:
ClampAndWriteVectorImage< UInt16VectorImageType >( image );
break;
case ImagePixelType_int32:
ClampAndWriteVectorImage< Int32VectorImageType >( image );
break;
case ImagePixelType_uint32:
ClampAndWriteVectorImage< UInt32VectorImageType >( image );
break;
case ImagePixelType_float:
ClampAndWriteVectorImage< FloatVectorImageType >( image );
break;
case ImagePixelType_double:
ClampAndWriteVectorImage< DoubleVectorImageType >( image );
break;
case ImagePixelType_cint16:
ClampAndWriteVectorImage < ComplexInt16VectorImageType >( image );
break;
case ImagePixelType_cint32:
ClampAndWriteVectorImage < ComplexInt32VectorImageType >( image );
break;
case ImagePixelType_cfloat:
ClampAndWriteVectorImage< ComplexFloatVectorImageType >( image );
break;
case ImagePixelType_cdouble:
ClampAndWriteVectorImage < ComplexDoubleVectorImageType >( image );
break;
default:
assert( false && "Unexpected image-type." );
break;
}
}
void
OutputImageParameter::Write()
{
m_Writer->Update();
// Clean internal filters
m_InputCaster = nullptr;
m_OutputCaster = nullptr;
m_Writer = nullptr;
}
itk::ProcessObject*
OutputImageParameter::GetWriter()
{
return m_Writer;
}
ImageBaseType*
OutputImageParameter::GetValue( )
{
return m_Image;
}
void
OutputImageParameter::SetValue(ImageBaseType* image)
{
m_Image = image;
SetActive(true);
}
bool
OutputImageParameter
::HasValue() const
{
return !m_FileName.empty();
}
std::string
OutputImageParameter::CheckFileName(bool fixMissingExtension)
{
std::string ret("");
// Check that there is an ImageIO capable of writing the file
otb::ExtendedFilenameToWriterOptions::Pointer filenameHelper =
otb::ExtendedFilenameToWriterOptions::New();
filenameHelper->SetExtendedFileName(this->GetFileName());
std::string simpleFilename = filenameHelper->GetSimpleFileName();
// TODO : check if simpleFilename is empty
otb::ImageIOBase::Pointer imageIO =
otb::ImageIOFactory::CreateImageIO(simpleFilename.c_str(),
otb::ImageIOFactory::WriteMode);
if(imageIO.IsNull())
{
// check for missing extension
std::string outExt = itksys::SystemTools::GetFilenameLastExtension(simpleFilename);
if (outExt.empty())
{
if (fixMissingExtension)
{
// try with .tif
std::string fullFileName(this->GetFileName());
std::string extendedPart = fullFileName.substr(simpleFilename.size());
this->SetFileName(simpleFilename+std::string(".tif")+extendedPart);
ret += std::string("no extension detected, using TIF as default.");
}
else
{
// TODO : call exception here?
}
}
else
{
// TODO : call exception here?
}
}
return ret;
}
// Specialization for UInt8RGBAImageType
template<>
void
OutputImageParameter
::SwitchInput( UInt8RGBAImageType * img )
{
assert( img );
if( m_PixelType != ImagePixelType_uint8 )
itkExceptionMacro("Unknown PixelType for RGBA Image. Only uint8 is supported.");
auto writer =
otb::ImageFileWriter< UInt8RGBAImageType >::New();
writer->SetFileName( GetFileName() );
writer->SetInput( img );
writer->GetStreamingManager()->SetDefaultRAM( m_RAMValue );
m_Writer = writer;
}
// Specialization for UInt8RGBImageType
template<>
void
OutputImageParameter
::SwitchInput( UInt8RGBImageType * img )
{
if( m_PixelType != ImagePixelType_uint8 )
itkExceptionMacro("Unknown PixelType for RGB Image. Only uint8 is supported.");
auto writer = otb::ImageFileWriter< UInt8RGBImageType >::New();
writer->SetFileName( GetFileName() );
writer->SetInput( img );
writer->GetStreamingManager()->SetDefaultRAM( m_RAMValue );
m_Writer = writer;
}
void OutputImageParameter::SetFileName (const char* filename)
{
this->SetFileName(std::string(filename));
}
void OutputImageParameter::SetFileName (const std::string& filename)
{
m_FileName = filename;
SetActive(true);
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonPropFindRequest.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: hr $ $Date: 2006-06-20 05:36:43 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _NEONTYPES_HXX_
#include "NeonTypes.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _NEONPROPFINDREQUEST_HXX_
#include "NeonPropFindRequest.hxx"
#endif
#ifndef _LINKSEQUENCE_HXX_
#include "LinkSequence.hxx"
#endif
#ifndef _LOCKSEQUENCE_HXX_
#include "LockSequence.hxx"
#endif
#ifndef _LOCKENTRYSEQUENCE_HXX_
#include "LockEntrySequence.hxx"
#endif
#ifndef _UCBDEADPROPERTYVALUE_HXX_
#include "UCBDeadPropertyValue.hxx"
#endif
using namespace rtl;
using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace std;
using namespace webdav_ucp;
// -------------------------------------------------------------------
extern "C" int NPFR_propfind_iter( void* userdata,
const NeonPropName* pname,
const char* value,
const HttpStatus* status )
{
/*
HTTP Response Status Classes:
- 1: Informational - Request received, continuing process
- 2: Success - The action was successfully received,
understood, and accepted
- 3: Redirection - Further action must be taken in order to
complete the request
- 4: Client Error - The request contains bad syntax or cannot
be fulfilled
- 5: Server Error - The server failed to fulfill an apparently
valid request
*/
if ( status->klass > 2 )
return 0; // Error getting this property. Go on.
// Create & set the PropertyValue
PropertyValue thePropertyValue;
thePropertyValue.Handle = -1;
thePropertyValue.State = PropertyState_DIRECT_VALUE;
DAVProperties::createUCBPropName( pname->nspace,
pname->name,
thePropertyValue.Name );
bool bHasValue = false;
if ( DAVProperties::isUCBDeadProperty( *pname ) )
{
// DAV dead property added by WebDAV UCP?
if ( UCBDeadPropertyValue::createFromXML(
value, thePropertyValue.Value ) )
OSL_ENSURE( thePropertyValue.Value.hasValue(),
"NeonPropFindRequest::propfind_iter - No value!" );
bHasValue = true;
}
if ( !bHasValue )
{
if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "resourcetype" ) == 0 )
{
OString aValue( value );
aValue = aValue.trim(); // #107358# remove leading/trailing spaces
if ( aValue.getLength() )
{
aValue = aValue.toAsciiLowerCase();
if ( aValue.compareTo(
RTL_CONSTASCII_STRINGPARAM( "<collection" ) ) == 0 )
{
thePropertyValue.Value
<<= OUString::createFromAscii( "collection" );
}
}
if ( !thePropertyValue.Value.hasValue() )
{
// Take over the value exactly as supplied by the server.
thePropertyValue.Value <<= OUString::createFromAscii( value );
}
}
else if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "supportedlock" ) == 0 )
{
Sequence< LockEntry > aEntries;
LockEntrySequence::createFromXML( value, aEntries );
thePropertyValue.Value <<= aEntries;
}
else if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "lockdiscovery" ) == 0 )
{
Sequence< Lock > aLocks;
LockSequence::createFromXML( value, aLocks );
thePropertyValue.Value <<= aLocks;
}
else if ( rtl_str_compareIgnoreAsciiCase( pname->name, "source" ) == 0 )
{
Sequence< Link > aLinks;
LinkSequence::createFromXML( value, aLinks );
thePropertyValue.Value <<= aLinks;
}
else
{
thePropertyValue.Value
<<= OStringToOUString( value, RTL_TEXTENCODING_UTF8 );
}
}
// Add the newly created PropertyValue
DAVResource* theResource = static_cast< DAVResource * >( userdata );
theResource->properties.push_back( thePropertyValue );
return 0; // Go on.
}
// -------------------------------------------------------------------
extern "C" void NPFR_propfind_results( void* userdata,
const char* href,
const NeonPropFindResultSet* set )
{
// @@@ href is not the uri! DAVResource ctor wants uri!
DAVResource theResource(
OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
ne_propset_iterate( set, NPFR_propfind_iter, &theResource );
// Add entry to resources list.
vector< DAVResource > * theResources
= static_cast< vector< DAVResource > * >( userdata );
theResources->push_back( theResource );
}
// -------------------------------------------------------------------
extern "C" int NPFR_propnames_iter( void* userdata,
const NeonPropName* pname,
const char* /*value*/,
const HttpStatus* /*status*/ )
{
OUString aFullName;
DAVProperties::createUCBPropName( pname->nspace,
pname->name,
aFullName );
DAVResourceInfo* theResource = static_cast< DAVResourceInfo * >( userdata );
theResource->properties.push_back( aFullName );
return 0;
}
// -------------------------------------------------------------------
extern "C" void NPFR_propnames_results( void* userdata,
const char* href,
const NeonPropFindResultSet* results )
{
// @@@ href is not the uri! DAVResourceInfo ctor wants uri!
// Create entry for the resource.
DAVResourceInfo theResource(
OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
// Fill entry.
ne_propset_iterate( results, NPFR_propnames_iter, &theResource );
// Add entry to resources list.
vector< DAVResourceInfo > * theResources
= static_cast< vector< DAVResourceInfo > * >( userdata );
theResources->push_back( theResource );
}
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
NeonPropFindRequest::NeonPropFindRequest( HttpSession* inSession,
const char* inPath,
const Depth inDepth,
const vector< OUString >& inPropNames,
vector< DAVResource >& ioResources,
int & nError )
{
// Generate the list of properties we're looking for
int thePropCount = inPropNames.size();
if ( thePropCount > 0 )
{
NeonPropName* thePropNames = new NeonPropName[ thePropCount + 1 ];
int theIndex;
for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
{
// Split fullname into namespace and name!
DAVProperties::createNeonPropName(
inPropNames[ theIndex ], thePropNames[ theIndex ] );
}
thePropNames[ theIndex ].nspace = NULL;
thePropNames[ theIndex ].name = NULL;
nError = ne_simple_propfind( inSession,
inPath,
inDepth,
thePropNames,
NPFR_propfind_results,
&ioResources );
for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
free( (void *)thePropNames[ theIndex ].name );
delete [] thePropNames;
}
else
{
// ALLPROP
nError = ne_simple_propfind( inSession,
inPath,
inDepth,
NULL, // 0 == allprop
NPFR_propfind_results,
&ioResources );
}
// #87585# - Sometimes neon lies (because some servers lie).
if ( ( nError == NE_OK ) && ioResources.empty() )
nError = NE_ERROR;
}
// -------------------------------------------------------------------
// Constructor
// - obtains property names
// -------------------------------------------------------------------
NeonPropFindRequest::NeonPropFindRequest(
HttpSession* inSession,
const char* inPath,
const Depth inDepth,
std::vector< DAVResourceInfo > & ioResInfo,
int & nError )
{
nError = ne_propnames( inSession,
inPath,
inDepth,
NPFR_propnames_results,
&ioResInfo );
// #87585# - Sometimes neon lies (because some servers lie).
if ( ( nError == NE_OK ) && ioResInfo.empty() )
nError = NE_ERROR;
}
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonPropFindRequest::~NeonPropFindRequest( )
{
}
<commit_msg>INTEGRATION: CWS configure18 (1.15.6); FILE MERGED 2006/07/13 15:18:19 rene 1.15.6.1: #i64798# system neon 0.26.x support, by geki<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: NeonPropFindRequest.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: kz $ $Date: 2006-07-19 09:35:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _NEONTYPES_HXX_
#include "NeonTypes.hxx"
#endif
#ifndef _DAVEXCEPTION_HXX_
#include "DAVException.hxx"
#endif
#ifndef _DAVPROPERTIES_HXX_
#include "DAVProperties.hxx"
#endif
#ifndef _NEONPROPFINDREQUEST_HXX_
#include "NeonPropFindRequest.hxx"
#endif
#ifndef _LINKSEQUENCE_HXX_
#include "LinkSequence.hxx"
#endif
#ifndef _LOCKSEQUENCE_HXX_
#include "LockSequence.hxx"
#endif
#ifndef _LOCKENTRYSEQUENCE_HXX_
#include "LockEntrySequence.hxx"
#endif
#ifndef _UCBDEADPROPERTYVALUE_HXX_
#include "UCBDeadPropertyValue.hxx"
#endif
using namespace rtl;
using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace std;
using namespace webdav_ucp;
// -------------------------------------------------------------------
extern "C" int NPFR_propfind_iter( void* userdata,
const NeonPropName* pname,
const char* value,
const HttpStatus* status )
{
/*
HTTP Response Status Classes:
- 1: Informational - Request received, continuing process
- 2: Success - The action was successfully received,
understood, and accepted
- 3: Redirection - Further action must be taken in order to
complete the request
- 4: Client Error - The request contains bad syntax or cannot
be fulfilled
- 5: Server Error - The server failed to fulfill an apparently
valid request
*/
if ( status->klass > 2 )
return 0; // Error getting this property. Go on.
// Create & set the PropertyValue
PropertyValue thePropertyValue;
thePropertyValue.Handle = -1;
thePropertyValue.State = PropertyState_DIRECT_VALUE;
DAVProperties::createUCBPropName( pname->nspace,
pname->name,
thePropertyValue.Name );
bool bHasValue = false;
if ( DAVProperties::isUCBDeadProperty( *pname ) )
{
// DAV dead property added by WebDAV UCP?
if ( UCBDeadPropertyValue::createFromXML(
value, thePropertyValue.Value ) )
OSL_ENSURE( thePropertyValue.Value.hasValue(),
"NeonPropFindRequest::propfind_iter - No value!" );
bHasValue = true;
}
if ( !bHasValue )
{
if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "resourcetype" ) == 0 )
{
OString aValue( value );
aValue = aValue.trim(); // #107358# remove leading/trailing spaces
if ( aValue.getLength() )
{
aValue = aValue.toAsciiLowerCase();
if ( aValue.compareTo(
RTL_CONSTASCII_STRINGPARAM( "<collection" ) ) == 0 )
{
thePropertyValue.Value
<<= OUString::createFromAscii( "collection" );
}
}
if ( !thePropertyValue.Value.hasValue() )
{
// Take over the value exactly as supplied by the server.
thePropertyValue.Value <<= OUString::createFromAscii( value );
}
}
else if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "supportedlock" ) == 0 )
{
Sequence< LockEntry > aEntries;
LockEntrySequence::createFromXML( value, aEntries );
thePropertyValue.Value <<= aEntries;
}
else if ( rtl_str_compareIgnoreAsciiCase(
pname->name, "lockdiscovery" ) == 0 )
{
Sequence< Lock > aLocks;
LockSequence::createFromXML( value, aLocks );
thePropertyValue.Value <<= aLocks;
}
else if ( rtl_str_compareIgnoreAsciiCase( pname->name, "source" ) == 0 )
{
Sequence< Link > aLinks;
LinkSequence::createFromXML( value, aLinks );
thePropertyValue.Value <<= aLinks;
}
else
{
thePropertyValue.Value
<<= OStringToOUString( value, RTL_TEXTENCODING_UTF8 );
}
}
// Add the newly created PropertyValue
DAVResource* theResource = static_cast< DAVResource * >( userdata );
theResource->properties.push_back( thePropertyValue );
return 0; // Go on.
}
// -------------------------------------------------------------------
extern "C" void NPFR_propfind_results( void* userdata,
#if NEON_VERSION >= 0260
const ne_uri* href_uri,
#else
const char* href,
#endif
const NeonPropFindResultSet* set )
{
// @@@ href is not the uri! DAVResource ctor wants uri!
#if NEON_VERSION >= 0260
// href should be free'd? says header ...
char* href = ne_uri_unparse(href_uri);
#endif
DAVResource theResource(
OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
ne_propset_iterate( set, NPFR_propfind_iter, &theResource );
// Add entry to resources list.
vector< DAVResource > * theResources
= static_cast< vector< DAVResource > * >( userdata );
theResources->push_back( theResource );
}
// -------------------------------------------------------------------
extern "C" int NPFR_propnames_iter( void* userdata,
const NeonPropName* pname,
const char* /*value*/,
const HttpStatus* /*status*/ )
{
OUString aFullName;
DAVProperties::createUCBPropName( pname->nspace,
pname->name,
aFullName );
DAVResourceInfo* theResource = static_cast< DAVResourceInfo * >( userdata );
theResource->properties.push_back( aFullName );
return 0;
}
// -------------------------------------------------------------------
extern "C" void NPFR_propnames_results( void* userdata,
#if NEON_VERSION >= 0260
const ne_uri* href_uri,
#else
const char* href,
#endif
const NeonPropFindResultSet* results )
{
// @@@ href is not the uri! DAVResourceInfo ctor wants uri!
#if NEON_VERSION >= 0260
// href should be free'd? says header ...
char* href = ne_uri_unparse(href_uri);
#endif
// Create entry for the resource.
DAVResourceInfo theResource(
OStringToOUString( href, RTL_TEXTENCODING_UTF8 ) );
// Fill entry.
ne_propset_iterate( results, NPFR_propnames_iter, &theResource );
// Add entry to resources list.
vector< DAVResourceInfo > * theResources
= static_cast< vector< DAVResourceInfo > * >( userdata );
theResources->push_back( theResource );
}
// -------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------
NeonPropFindRequest::NeonPropFindRequest( HttpSession* inSession,
const char* inPath,
const Depth inDepth,
const vector< OUString >& inPropNames,
vector< DAVResource >& ioResources,
int & nError )
{
// Generate the list of properties we're looking for
int thePropCount = inPropNames.size();
if ( thePropCount > 0 )
{
NeonPropName* thePropNames = new NeonPropName[ thePropCount + 1 ];
int theIndex;
for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
{
// Split fullname into namespace and name!
DAVProperties::createNeonPropName(
inPropNames[ theIndex ], thePropNames[ theIndex ] );
}
thePropNames[ theIndex ].nspace = NULL;
thePropNames[ theIndex ].name = NULL;
nError = ne_simple_propfind( inSession,
inPath,
inDepth,
thePropNames,
NPFR_propfind_results,
&ioResources );
for ( theIndex = 0; theIndex < thePropCount; theIndex ++ )
free( (void *)thePropNames[ theIndex ].name );
delete [] thePropNames;
}
else
{
// ALLPROP
nError = ne_simple_propfind( inSession,
inPath,
inDepth,
NULL, // 0 == allprop
NPFR_propfind_results,
&ioResources );
}
// #87585# - Sometimes neon lies (because some servers lie).
if ( ( nError == NE_OK ) && ioResources.empty() )
nError = NE_ERROR;
}
// -------------------------------------------------------------------
// Constructor
// - obtains property names
// -------------------------------------------------------------------
NeonPropFindRequest::NeonPropFindRequest(
HttpSession* inSession,
const char* inPath,
const Depth inDepth,
std::vector< DAVResourceInfo > & ioResInfo,
int & nError )
{
nError = ne_propnames( inSession,
inPath,
inDepth,
NPFR_propnames_results,
&ioResInfo );
// #87585# - Sometimes neon lies (because some servers lie).
if ( ( nError == NE_OK ) && ioResInfo.empty() )
nError = NE_ERROR;
}
// -------------------------------------------------------------------
// Destructor
// -------------------------------------------------------------------
NeonPropFindRequest::~NeonPropFindRequest( )
{
}
<|endoftext|> |
<commit_before>//===-- PathMappingList.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
#include <limits.h>
#include <string.h>
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/Error.h"
#include "lldb/Core/Stream.h"
#include "lldb/Host/FileSpec.h"
#include "lldb/Target/PathMappingList.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// PathMappingList constructor
//----------------------------------------------------------------------
PathMappingList::PathMappingList () :
m_pairs (),
m_callback (NULL),
m_callback_baton (NULL)
{
}
PathMappingList::PathMappingList
(
ChangedCallback callback,
void *callback_baton
) :
m_pairs (),
m_callback (callback),
m_callback_baton (callback_baton)
{
}
PathMappingList::PathMappingList (const PathMappingList &rhs) :
m_pairs (rhs.m_pairs),
m_callback (NULL),
m_callback_baton (NULL)
{
}
const PathMappingList &
PathMappingList::operator =(const PathMappingList &rhs)
{
if (this != &rhs)
{
m_pairs = rhs.m_pairs;
m_callback = NULL;
m_callback_baton = NULL;
}
return *this;
}
//----------------------------------------------------------------------
// Destructor
//----------------------------------------------------------------------
PathMappingList::~PathMappingList ()
{
}
void
PathMappingList::Append (const ConstString &path,
const ConstString &replacement,
bool notify)
{
m_pairs.push_back(pair(path, replacement));
if (notify && m_callback)
m_callback (*this, m_callback_baton);
}
void
PathMappingList::Append (const PathMappingList &rhs, bool notify)
{
if (!rhs.m_pairs.empty())
{
const_iterator pos, end = rhs.m_pairs.end();
for (pos = rhs.m_pairs.begin(); pos != end; ++pos)
m_pairs.push_back(*pos);
if (notify && m_callback)
m_callback (*this, m_callback_baton);
}
}
void
PathMappingList::Insert (const ConstString &path,
const ConstString &replacement,
uint32_t index,
bool notify)
{
iterator insert_iter;
if (index >= m_pairs.size())
insert_iter = m_pairs.end();
else
insert_iter = m_pairs.begin() + index;
m_pairs.insert(insert_iter, pair(path, replacement));
if (notify && m_callback)
m_callback (*this, m_callback_baton);
}
bool
PathMappingList::Replace (const ConstString &path,
const ConstString &replacement,
uint32_t index,
bool notify)
{
iterator insert_iter;
if (index >= m_pairs.size())
return false;
m_pairs[index] = pair(path, replacement);
if (notify && m_callback)
m_callback (*this, m_callback_baton);
return true;
}
bool
PathMappingList::Remove (off_t index, bool notify)
{
if (index >= m_pairs.size())
return false;
iterator iter = m_pairs.begin() + index;
m_pairs.erase(iter);
if (notify && m_callback)
m_callback (*this, m_callback_baton);
return true;
}
// For clients which do not need the pair index dumped, pass a pair_index >= 0
// to only dump the indicated pair.
void
PathMappingList::Dump (Stream *s, int pair_index)
{
unsigned int numPairs = m_pairs.size();
if (pair_index < 0)
{
unsigned int index;
for (index = 0; index < numPairs; ++index)
s->Printf("[%d] \"%s\" -> \"%s\"\n",
index, m_pairs[index].first.GetCString(), m_pairs[index].second.GetCString());
}
else
{
if (pair_index < numPairs)
s->Printf("%s -> %s",
m_pairs[pair_index].first.GetCString(), m_pairs[pair_index].second.GetCString());
}
}
void
PathMappingList::Clear (bool notify)
{
m_pairs.clear();
if (notify && m_callback)
m_callback (*this, m_callback_baton);
}
bool
PathMappingList::RemapPath (const ConstString &path, ConstString &new_path) const
{
const_iterator pos, end = m_pairs.end();
for (pos = m_pairs.begin(); pos != end; ++pos)
{
const size_t prefixLen = pos->first.GetLength();
if (::strncmp (pos->first.GetCString(), path.GetCString(), prefixLen) == 0)
{
std::string new_path_str (pos->second.GetCString());
new_path_str.append(path.GetCString() + prefixLen);
new_path.SetCString(new_path_str.c_str());
return true;
}
}
return false;
}
bool
PathMappingList::RemapPath (const char *path, std::string &new_path) const
{
if (m_pairs.empty() || path == NULL || path[0] == '\0')
return false;
const_iterator pos, end = m_pairs.end();
for (pos = m_pairs.begin(); pos != end; ++pos)
{
const size_t prefix_len = pos->first.GetLength();
if (::strncmp (pos->first.GetCString(), path, prefix_len) == 0)
{
new_path = pos->second.GetCString();
new_path.append(path + prefix_len);
return true;
}
}
return false;
}
bool
PathMappingList::FindFile (const FileSpec &orig_spec, FileSpec &new_spec) const
{
if (!m_pairs.empty())
{
char orig_path[PATH_MAX];
char new_path[PATH_MAX];
const size_t orig_path_len = orig_spec.GetPath (orig_path, sizeof(orig_path));
if (orig_path_len > 0)
{
const_iterator pos, end = m_pairs.end();
for (pos = m_pairs.begin(); pos != end; ++pos)
{
const size_t prefix_len = pos->first.GetLength();
if (orig_path_len >= prefix_len)
{
if (::strncmp (pos->first.GetCString(), orig_path, prefix_len) == 0)
{
const size_t new_path_len = snprintf(new_path, sizeof(new_path), "%s/%s", pos->second.GetCString(), orig_path + prefix_len);
if (new_path_len < sizeof(new_path))
{
new_spec.SetFile (new_path, true);
if (new_spec.Exists())
return true;
}
}
}
}
}
}
new_spec.Clear();
return false;
}
bool
PathMappingList::Replace (const ConstString &path, const ConstString &new_path, bool notify)
{
uint32_t idx = FindIndexForPath (path);
if (idx < m_pairs.size())
{
m_pairs[idx].second = new_path;
if (notify && m_callback)
m_callback (*this, m_callback_baton);
return true;
}
return false;
}
bool
PathMappingList::Remove (const ConstString &path, bool notify)
{
iterator pos = FindIteratorForPath (path);
if (pos != m_pairs.end())
{
m_pairs.erase (pos);
if (notify && m_callback)
m_callback (*this, m_callback_baton);
return true;
}
return false;
}
PathMappingList::const_iterator
PathMappingList::FindIteratorForPath (const ConstString &path) const
{
const_iterator pos;
const_iterator begin = m_pairs.begin();
const_iterator end = m_pairs.end();
for (pos = begin; pos != end; ++pos)
{
if (pos->first == path)
break;
}
return pos;
}
PathMappingList::iterator
PathMappingList::FindIteratorForPath (const ConstString &path)
{
iterator pos;
iterator begin = m_pairs.begin();
iterator end = m_pairs.end();
for (pos = begin; pos != end; ++pos)
{
if (pos->first == path)
break;
}
return pos;
}
bool
PathMappingList::GetPathsAtIndex (uint32_t idx, ConstString &path, ConstString &new_path) const
{
if (idx < m_pairs.size())
{
path = m_pairs[idx].first;
new_path = m_pairs[idx].second;
return true;
}
return false;
}
uint32_t
PathMappingList::FindIndexForPath (const ConstString &path) const
{
const_iterator pos;
const_iterator begin = m_pairs.begin();
const_iterator end = m_pairs.end();
for (pos = begin; pos != end; ++pos)
{
if (pos->first == path)
return std::distance (begin, pos);
}
return UINT32_MAX;
}
<commit_msg>Fixed a bug in the path remapper that caused a crash if the path to be remaped was NULL.<commit_after>//===-- PathMappingList.cpp -------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// C Includes
#include <limits.h>
#include <string.h>
// C++ Includes
// Other libraries and framework includes
// Project includes
#include "lldb/Core/Error.h"
#include "lldb/Core/Stream.h"
#include "lldb/Host/FileSpec.h"
#include "lldb/Target/PathMappingList.h"
using namespace lldb;
using namespace lldb_private;
//----------------------------------------------------------------------
// PathMappingList constructor
//----------------------------------------------------------------------
PathMappingList::PathMappingList () :
m_pairs (),
m_callback (NULL),
m_callback_baton (NULL)
{
}
PathMappingList::PathMappingList
(
ChangedCallback callback,
void *callback_baton
) :
m_pairs (),
m_callback (callback),
m_callback_baton (callback_baton)
{
}
PathMappingList::PathMappingList (const PathMappingList &rhs) :
m_pairs (rhs.m_pairs),
m_callback (NULL),
m_callback_baton (NULL)
{
}
const PathMappingList &
PathMappingList::operator =(const PathMappingList &rhs)
{
if (this != &rhs)
{
m_pairs = rhs.m_pairs;
m_callback = NULL;
m_callback_baton = NULL;
}
return *this;
}
//----------------------------------------------------------------------
// Destructor
//----------------------------------------------------------------------
PathMappingList::~PathMappingList ()
{
}
void
PathMappingList::Append (const ConstString &path,
const ConstString &replacement,
bool notify)
{
m_pairs.push_back(pair(path, replacement));
if (notify && m_callback)
m_callback (*this, m_callback_baton);
}
void
PathMappingList::Append (const PathMappingList &rhs, bool notify)
{
if (!rhs.m_pairs.empty())
{
const_iterator pos, end = rhs.m_pairs.end();
for (pos = rhs.m_pairs.begin(); pos != end; ++pos)
m_pairs.push_back(*pos);
if (notify && m_callback)
m_callback (*this, m_callback_baton);
}
}
void
PathMappingList::Insert (const ConstString &path,
const ConstString &replacement,
uint32_t index,
bool notify)
{
iterator insert_iter;
if (index >= m_pairs.size())
insert_iter = m_pairs.end();
else
insert_iter = m_pairs.begin() + index;
m_pairs.insert(insert_iter, pair(path, replacement));
if (notify && m_callback)
m_callback (*this, m_callback_baton);
}
bool
PathMappingList::Replace (const ConstString &path,
const ConstString &replacement,
uint32_t index,
bool notify)
{
iterator insert_iter;
if (index >= m_pairs.size())
return false;
m_pairs[index] = pair(path, replacement);
if (notify && m_callback)
m_callback (*this, m_callback_baton);
return true;
}
bool
PathMappingList::Remove (off_t index, bool notify)
{
if (index >= m_pairs.size())
return false;
iterator iter = m_pairs.begin() + index;
m_pairs.erase(iter);
if (notify && m_callback)
m_callback (*this, m_callback_baton);
return true;
}
// For clients which do not need the pair index dumped, pass a pair_index >= 0
// to only dump the indicated pair.
void
PathMappingList::Dump (Stream *s, int pair_index)
{
unsigned int numPairs = m_pairs.size();
if (pair_index < 0)
{
unsigned int index;
for (index = 0; index < numPairs; ++index)
s->Printf("[%d] \"%s\" -> \"%s\"\n",
index, m_pairs[index].first.GetCString(), m_pairs[index].second.GetCString());
}
else
{
if (pair_index < numPairs)
s->Printf("%s -> %s",
m_pairs[pair_index].first.GetCString(), m_pairs[pair_index].second.GetCString());
}
}
void
PathMappingList::Clear (bool notify)
{
m_pairs.clear();
if (notify && m_callback)
m_callback (*this, m_callback_baton);
}
bool
PathMappingList::RemapPath (const ConstString &path, ConstString &new_path) const
{
const char *path_cstr = path.GetCString();
if (!path_cstr)
return false;
const_iterator pos, end = m_pairs.end();
for (pos = m_pairs.begin(); pos != end; ++pos)
{
const size_t prefixLen = pos->first.GetLength();
if (::strncmp (pos->first.GetCString(), path_cstr, prefixLen) == 0)
{
std::string new_path_str (pos->second.GetCString());
new_path_str.append(path.GetCString() + prefixLen);
new_path.SetCString(new_path_str.c_str());
return true;
}
}
return false;
}
bool
PathMappingList::RemapPath (const char *path, std::string &new_path) const
{
if (m_pairs.empty() || path == NULL || path[0] == '\0')
return false;
const_iterator pos, end = m_pairs.end();
for (pos = m_pairs.begin(); pos != end; ++pos)
{
const size_t prefix_len = pos->first.GetLength();
if (::strncmp (pos->first.GetCString(), path, prefix_len) == 0)
{
new_path = pos->second.GetCString();
new_path.append(path + prefix_len);
return true;
}
}
return false;
}
bool
PathMappingList::FindFile (const FileSpec &orig_spec, FileSpec &new_spec) const
{
if (!m_pairs.empty())
{
char orig_path[PATH_MAX];
char new_path[PATH_MAX];
const size_t orig_path_len = orig_spec.GetPath (orig_path, sizeof(orig_path));
if (orig_path_len > 0)
{
const_iterator pos, end = m_pairs.end();
for (pos = m_pairs.begin(); pos != end; ++pos)
{
const size_t prefix_len = pos->first.GetLength();
if (orig_path_len >= prefix_len)
{
if (::strncmp (pos->first.GetCString(), orig_path, prefix_len) == 0)
{
const size_t new_path_len = snprintf(new_path, sizeof(new_path), "%s/%s", pos->second.GetCString(), orig_path + prefix_len);
if (new_path_len < sizeof(new_path))
{
new_spec.SetFile (new_path, true);
if (new_spec.Exists())
return true;
}
}
}
}
}
}
new_spec.Clear();
return false;
}
bool
PathMappingList::Replace (const ConstString &path, const ConstString &new_path, bool notify)
{
uint32_t idx = FindIndexForPath (path);
if (idx < m_pairs.size())
{
m_pairs[idx].second = new_path;
if (notify && m_callback)
m_callback (*this, m_callback_baton);
return true;
}
return false;
}
bool
PathMappingList::Remove (const ConstString &path, bool notify)
{
iterator pos = FindIteratorForPath (path);
if (pos != m_pairs.end())
{
m_pairs.erase (pos);
if (notify && m_callback)
m_callback (*this, m_callback_baton);
return true;
}
return false;
}
PathMappingList::const_iterator
PathMappingList::FindIteratorForPath (const ConstString &path) const
{
const_iterator pos;
const_iterator begin = m_pairs.begin();
const_iterator end = m_pairs.end();
for (pos = begin; pos != end; ++pos)
{
if (pos->first == path)
break;
}
return pos;
}
PathMappingList::iterator
PathMappingList::FindIteratorForPath (const ConstString &path)
{
iterator pos;
iterator begin = m_pairs.begin();
iterator end = m_pairs.end();
for (pos = begin; pos != end; ++pos)
{
if (pos->first == path)
break;
}
return pos;
}
bool
PathMappingList::GetPathsAtIndex (uint32_t idx, ConstString &path, ConstString &new_path) const
{
if (idx < m_pairs.size())
{
path = m_pairs[idx].first;
new_path = m_pairs[idx].second;
return true;
}
return false;
}
uint32_t
PathMappingList::FindIndexForPath (const ConstString &path) const
{
const_iterator pos;
const_iterator begin = m_pairs.begin();
const_iterator end = m_pairs.end();
for (pos = begin; pos != end; ++pos)
{
if (pos->first == path)
return std::distance (begin, pos);
}
return UINT32_MAX;
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-2000, 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. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////////
// //
// Forward Multiplicity Detector based on Silicon plates //
// This class contains the procedures simulation ADC signal for //
// the Forward Multiplicity detector : hits -> digits //
// ADC signal consists //
// - number of detector; //
// - number of ring; //
// - number of sector; //
// - ADC signal in this channel //
// //
//////////////////////////////////////////////////////////////////////////////
#include <TTree.h>
#include <TVector.h>
#include <TObjArray.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TRandom.h>
#include "AliFMDDigitizer.h"
#include "AliFMD.h"
#include "AliFMDhit.h"
#include "AliFMDdigit.h"
#include "AliRunDigitizer.h"
#include "AliRun.h"
#include "AliPDG.h"
#include "AliLoader.h"
#include "AliRunLoader.h"
#include <stdlib.h>
#include <Riostream.h>
#include <Riostream.h>
ClassImp(AliFMDDigitizer)
//___________________________________________
AliFMDDigitizer::AliFMDDigitizer() :AliDigitizer()
{
// Default ctor - don't use it
;
}
//___________________________________________
AliFMDDigitizer::AliFMDDigitizer(AliRunDigitizer* manager)
:AliDigitizer(manager)
{
// ctor which should be used
// fDebug =0;
// if (GetDebug()>2)
// cerr<<"AliFMDDigitizer::AliFMDDigitizer"
// <<"(AliRunDigitizer* manager) was processed"<<endl;
}
//------------------------------------------------------------------------
AliFMDDigitizer::~AliFMDDigitizer()
{
// Destructor
}
//------------------------------------------------------------------------
Bool_t AliFMDDigitizer::Init()
{
// Initialization
// cout<<"AliFMDDigitizer::Init"<<endl;
return kTRUE;
}
//---------------------------------------------------------------------
void AliFMDDigitizer::Exec(Option_t * /*option*/)
{
/*
Conver hits to digits:
- number of detector;
- number of ring;
- number of sector;
- ADC signal in this channel
*/
AliRunLoader *inRL, *outRL;//in and out Run Loaders
AliLoader *ingime, *outgime;// in and out ITSLoaders
outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
outgime = outRL->GetLoader("FMDLoader");
#ifdef DEBUG
cout<<"AliFMDDigitizer::>SDigits2Digits start...\n";
#endif
Int_t volume, sector, ring, charge;
Float_t e;
Float_t de[10][50][520];
Int_t hit;
Int_t digit[5];
Int_t ivol, iSector, iRing;
for (Int_t i=0; i<10; i++)
for(Int_t j=0; j<50; j++)
for(Int_t ij=0; ij<520; ij++)
de[i][j][ij]=0;
Int_t numberOfRings[5]=
{512,256,512,256,512};
Int_t numberOfSector[5]=
{20,40,20,40,20};
AliFMDhit *fmdHit=0;
TTree *tH=0;
TBranch *brHits=0;
TBranch *brD=0;
inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(0));
if (inRL == 0x0)
{
Error("Exec","Can not find Run Loader for input stream 0");
return;
}
// Info("Exec","inRL->GetAliRun() %#x",inRL->GetAliRun());
if (!inRL->GetAliRun()) inRL->LoadgAlice();
AliFMD * fFMD = (AliFMD *) inRL->GetAliRun()->GetDetector("FMD");
// Info("Exec","inRL->GetAliRun(): %#x, FMD: %#x, InRL %#x.",inRL->GetAliRun(),fFMD,inRL);
if (fFMD == 0x0)
{
Error("Exec","Can not get FMD from gAlice");
return;
}
// Loop over files to digitize
Int_t nFiles=GetManager()->GetNinputs();
for (Int_t inputFile=0; inputFile<nFiles;inputFile++)
{
cout<<" event "<<fManager->GetOutputEventNr()<<endl;
if (fFMD)
{
inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
ingime = inRL->GetLoader("FMDLoader");
ingime->LoadHits("READ");//probably it is necessary to load them before
tH = ingime->TreeH();
if (tH == 0x0)
{
ingime->LoadHits("read");
tH = ingime->TreeH();
}
brHits = tH->GetBranch("FMD");
if (brHits) {
// brHits->SetAddress(&fHits);
fFMD->SetHitsAddressBranch(brHits);
}else{
Fatal("Exec","EXEC Branch FMD hit not found");
}
TClonesArray *fFMDhits = fFMD->Hits ();
Int_t ntracks = (Int_t) tH->GetEntries();
cout<<"Number of tracks TreeH"<<ntracks<<endl;
for (Int_t track = 0; track < ntracks; track++)
{
brHits->GetEntry(track);
Int_t nhits = fFMDhits->GetEntries ();
// if(nhits>0) cout<<"nhits "<<nhits<<endl;
for (hit = 0; hit < nhits; hit++)
{
fmdHit = (AliFMDhit *) fFMDhits->UncheckedAt(hit);
volume = fmdHit->Volume ();
sector = fmdHit->NumberOfSector ();
ring = fmdHit->NumberOfRing ();
e = fmdHit->Edep ();
de[volume][sector][ring] += e;
// if (fManager->GetOutputEventNr()>1)
// cout<<" "<<volume<<" "<<sector<<" "<<ring<<endl;
} //hit loop
} //track loop
}
//if FMD
// Put noise and make ADC signal
Float_t mipI = 1.664 * 0.04 * 2.33 / 22400; // = 6.923e-6;
for ( ivol=1; ivol<=5; ivol++){
for ( iSector=1; iSector<=numberOfSector[ivol-1]; iSector++){
for ( iRing=1; iRing<=numberOfRings[ivol-1]; iRing++){
digit[0]=ivol;
digit[1]=iSector;
digit[2]=iRing;
charge = Int_t (de[ivol][iSector][iRing] / mipI);
Int_t pedestal=Int_t(gRandom->Gaus(500,250));
// digit[3]=PutNoise(charge);
digit[3]=charge + pedestal;
if(digit[3]<= 500) digit[3]=500;
//dynamic range from MIP(0.155MeV) to 30MIP(4.65MeV)
//1024 ADC channels
Float_t channelWidth=(22400*50)/1024;
digit[4]=Int_t(digit[3]/channelWidth);
if (digit[4]>1024) digit[4]=1024;
fFMD->AddDigit(digit);
} //ivol
} //iSector
} //iRing
TTree* treeD = outgime->TreeD();
cout<<" treeD "<<treeD;
if (treeD == 0x0) {
outgime->MakeTree("D");
treeD = outgime->TreeD();
cout<<" After MakeTree "<<treeD<<endl;
}
cout<<" Before reset "<<treeD<<endl;
// treeD->Clear();
treeD->Reset();
fFMD->MakeBranchInTreeD(treeD);
brD = treeD->GetBranch("FMD");
cout<<" Make branch "<<brD<<endl;
treeD->Fill(); //this operator does not work for events >1
//PH treeD->Print();
outgime->WriteDigits("OVERWRITE");
gAlice->ResetDigits();
}
}
<commit_msg>Reducing printout<commit_after>/**************************************************************************
* Copyright(c) 1998-2000, 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. *
**************************************************************************/
//////////////////////////////////////////////////////////////////////////////
// //
// Forward Multiplicity Detector based on Silicon plates //
// This class contains the procedures simulation ADC signal for //
// the Forward Multiplicity detector : hits -> digits //
// ADC signal consists //
// - number of detector; //
// - number of ring; //
// - number of sector; //
// - ADC signal in this channel //
// //
//////////////////////////////////////////////////////////////////////////////
#include <TTree.h>
#include <TVector.h>
#include <TObjArray.h>
#include <TFile.h>
#include <TDirectory.h>
#include <TRandom.h>
#include "AliFMDDigitizer.h"
#include "AliFMD.h"
#include "AliFMDhit.h"
#include "AliFMDdigit.h"
#include "AliRunDigitizer.h"
#include "AliRun.h"
#include "AliPDG.h"
#include "AliLoader.h"
#include "AliRunLoader.h"
#include <stdlib.h>
#include <Riostream.h>
#include <Riostream.h>
ClassImp(AliFMDDigitizer)
//___________________________________________
AliFMDDigitizer::AliFMDDigitizer() :AliDigitizer()
{
// Default ctor - don't use it
;
}
//___________________________________________
AliFMDDigitizer::AliFMDDigitizer(AliRunDigitizer* manager)
:AliDigitizer(manager)
{
// ctor which should be used
// fDebug =0;
// if (GetDebug()>2)
// cerr<<"AliFMDDigitizer::AliFMDDigitizer"
// <<"(AliRunDigitizer* manager) was processed"<<endl;
}
//------------------------------------------------------------------------
AliFMDDigitizer::~AliFMDDigitizer()
{
// Destructor
}
//------------------------------------------------------------------------
Bool_t AliFMDDigitizer::Init()
{
// Initialization
// cout<<"AliFMDDigitizer::Init"<<endl;
return kTRUE;
}
//---------------------------------------------------------------------
void AliFMDDigitizer::Exec(Option_t * /*option*/)
{
/*
Conver hits to digits:
- number of detector;
- number of ring;
- number of sector;
- ADC signal in this channel
*/
AliRunLoader *inRL, *outRL;//in and out Run Loaders
AliLoader *ingime, *outgime;// in and out ITSLoaders
outRL = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName());
outgime = outRL->GetLoader("FMDLoader");
#ifdef DEBUG
cout<<"AliFMDDigitizer::>SDigits2Digits start...\n";
#endif
Int_t volume, sector, ring, charge;
Float_t e;
Float_t de[10][50][520];
Int_t hit;
Int_t digit[5];
Int_t ivol, iSector, iRing;
for (Int_t i=0; i<10; i++)
for(Int_t j=0; j<50; j++)
for(Int_t ij=0; ij<520; ij++)
de[i][j][ij]=0;
Int_t numberOfRings[5]=
{512,256,512,256,512};
Int_t numberOfSector[5]=
{20,40,20,40,20};
AliFMDhit *fmdHit=0;
TTree *tH=0;
TBranch *brHits=0;
TBranch *brD=0;
inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(0));
if (inRL == 0x0)
{
Error("Exec","Can not find Run Loader for input stream 0");
return;
}
// Info("Exec","inRL->GetAliRun() %#x",inRL->GetAliRun());
if (!inRL->GetAliRun()) inRL->LoadgAlice();
AliFMD * fFMD = (AliFMD *) inRL->GetAliRun()->GetDetector("FMD");
// Info("Exec","inRL->GetAliRun(): %#x, FMD: %#x, InRL %#x.",inRL->GetAliRun(),fFMD,inRL);
if (fFMD == 0x0)
{
Error("Exec","Can not get FMD from gAlice");
return;
}
// Loop over files to digitize
Int_t nFiles=GetManager()->GetNinputs();
for (Int_t inputFile=0; inputFile<nFiles;inputFile++)
{
// cout<<" event "<<fManager->GetOutputEventNr()<<endl;
if (fFMD)
{
inRL = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inputFile));
ingime = inRL->GetLoader("FMDLoader");
ingime->LoadHits("READ");//probably it is necessary to load them before
tH = ingime->TreeH();
if (tH == 0x0)
{
ingime->LoadHits("read");
tH = ingime->TreeH();
}
brHits = tH->GetBranch("FMD");
if (brHits) {
// brHits->SetAddress(&fHits);
fFMD->SetHitsAddressBranch(brHits);
}else{
Fatal("Exec","EXEC Branch FMD hit not found");
}
TClonesArray *fFMDhits = fFMD->Hits ();
Int_t ntracks = (Int_t) tH->GetEntries();
// cout<<"Number of tracks TreeH"<<ntracks<<endl;
for (Int_t track = 0; track < ntracks; track++)
{
brHits->GetEntry(track);
Int_t nhits = fFMDhits->GetEntries ();
// if(nhits>0) cout<<"nhits "<<nhits<<endl;
for (hit = 0; hit < nhits; hit++)
{
fmdHit = (AliFMDhit *) fFMDhits->UncheckedAt(hit);
volume = fmdHit->Volume ();
sector = fmdHit->NumberOfSector ();
ring = fmdHit->NumberOfRing ();
e = fmdHit->Edep ();
de[volume][sector][ring] += e;
// if (fManager->GetOutputEventNr()>1)
// cout<<" "<<volume<<" "<<sector<<" "<<ring<<endl;
} //hit loop
} //track loop
}
//if FMD
// Put noise and make ADC signal
Float_t mipI = 1.664 * 0.04 * 2.33 / 22400; // = 6.923e-6;
for ( ivol=1; ivol<=5; ivol++){
for ( iSector=1; iSector<=numberOfSector[ivol-1]; iSector++){
for ( iRing=1; iRing<=numberOfRings[ivol-1]; iRing++){
digit[0]=ivol;
digit[1]=iSector;
digit[2]=iRing;
charge = Int_t (de[ivol][iSector][iRing] / mipI);
Int_t pedestal=Int_t(gRandom->Gaus(500,250));
// digit[3]=PutNoise(charge);
digit[3]=charge + pedestal;
if(digit[3]<= 500) digit[3]=500;
//dynamic range from MIP(0.155MeV) to 30MIP(4.65MeV)
//1024 ADC channels
Float_t channelWidth=(22400*50)/1024;
digit[4]=Int_t(digit[3]/channelWidth);
if (digit[4]>1024) digit[4]=1024;
fFMD->AddDigit(digit);
} //ivol
} //iSector
} //iRing
TTree* treeD = outgime->TreeD();
// cout<<" treeD "<<treeD;
if (treeD == 0x0) {
outgime->MakeTree("D");
treeD = outgime->TreeD();
// cout<<" After MakeTree "<<treeD<<endl;
}
// cout<<" Before reset "<<treeD<<endl;
// treeD->Clear();
treeD->Reset();
fFMD->MakeBranchInTreeD(treeD);
brD = treeD->GetBranch("FMD");
// cout<<" Make branch "<<brD<<endl;
treeD->Fill(); //this operator does not work for events >1
//PH treeD->Print();
outgime->WriteDigits("OVERWRITE");
gAlice->ResetDigits();
}
}
<|endoftext|> |