text
stringlengths 54
60.6k
|
---|
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) University College London (UCL).
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkDataStorageComboBoxWithSelectNone.h"
#include <QDebug>
const QString QmitkDataStorageComboBoxWithSelectNone::ZERO_ENTRY_STRING = "please select";
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
QWidget* parent,
bool autoSelectNewNodes )
: QmitkDataStorageComboBox(parent, autoSelectNewNodes)
, m_CurrentPath("")
{
}
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
mitk::DataStorage* dataStorage,
const mitk::NodePredicateBase* predicate,
QWidget* parent, bool autoSelectNewNodes )
: QmitkDataStorageComboBox(dataStorage, predicate, parent, autoSelectNewNodes)
{
}
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::~QmitkDataStorageComboBoxWithSelectNone()
{
}
//-----------------------------------------------------------------------------
int QmitkDataStorageComboBoxWithSelectNone::Find( const mitk::DataNode* dataNode ) const
{
int index = QmitkDataStorageComboBox::Find(dataNode);
if (index != -1)
{
index += 1;
}
return index;
}
//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetNode( int index ) const
{
mitk::DataNode::Pointer result = NULL;
if (this->HasIndex(index))
{
if (index != 0)
{
result = m_Nodes.at(index - 1);
}
}
return result;
}
//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetSelectedNode() const
{
return this->GetNode(this->currentIndex());
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetSelectedNode(const mitk::DataNode::Pointer& node)
{
int currentIndex = -1;
for (int i = 0; i < m_Nodes.size(); i++)
{
if (m_Nodes[i] == node.GetPointer())
{
currentIndex = i;
break;
}
}
if (currentIndex == -1)
{
// didn't find it, so set the value to 0.
currentIndex = 0;
}
else
{
currentIndex += 1; // because the combo box contains "please select" at position zero.
}
this->setCurrentIndex(currentIndex);
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::RemoveNode( int index )
{
if(index > 0 && this->HasIndex(index))
{
// remove itk::Event observer
mitk::DataNode* dataNode = m_Nodes.at(index - 1);
// get name property first
mitk::BaseProperty* nameProperty = dataNode->GetProperty("name");
// if prop exists remove modified listener
if(nameProperty)
{
nameProperty->RemoveObserver(m_NodesModifiedObserverTags[index-1]);
// remove name property map
m_PropertyToNode.erase(dataNode);
}
// then remove delete listener on the node itself
dataNode->RemoveObserver(m_NodesDeleteObserverTags[index-1]);
// remove observer tags from lists
m_NodesModifiedObserverTags.erase(m_NodesModifiedObserverTags.begin()+index-1);
m_NodesDeleteObserverTags.erase(m_NodesDeleteObserverTags.begin()+index-1);
// remove node name from combobox
this->removeItem(index);
// remove node from node vector
m_Nodes.erase(m_Nodes.begin()+index-1);
}
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetNode(int index, const mitk::DataNode* dataNode)
{
if(index > 0 && this->HasIndex(index))
{
QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
}
}
//-----------------------------------------------------------------------------
bool QmitkDataStorageComboBoxWithSelectNone::HasIndex(unsigned int index) const
{
return (m_Nodes.size() > 0 && index <= m_Nodes.size());
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::InsertNode(int index, const mitk::DataNode* dataNode)
{
if (index != 0)
{
QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
}
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::Reset()
{
QmitkDataStorageComboBox::Reset();
this->insertItem(0, ZERO_ENTRY_STRING);
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetZeroEntryText(const QString& zeroEntryString)
{
this->setItemText(0, zeroEntryString);
}
//-----------------------------------------------------------------------------
QString QmitkDataStorageComboBoxWithSelectNone::currentValue() const
{
return m_CurrentPath;
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::setCurrentValue(const QString& path)
{
m_CurrentPath = path;
}
<commit_msg>Add checks for node renaming<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) University College London (UCL).
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkDataStorageComboBoxWithSelectNone.h"
#include <QDebug>
const QString QmitkDataStorageComboBoxWithSelectNone::ZERO_ENTRY_STRING = "please select";
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
QWidget* parent,
bool autoSelectNewNodes )
: QmitkDataStorageComboBox(parent, autoSelectNewNodes)
, m_CurrentPath("")
{
}
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::QmitkDataStorageComboBoxWithSelectNone(
mitk::DataStorage* dataStorage,
const mitk::NodePredicateBase* predicate,
QWidget* parent, bool autoSelectNewNodes )
: QmitkDataStorageComboBox(dataStorage, predicate, parent, autoSelectNewNodes)
{
}
//-----------------------------------------------------------------------------
QmitkDataStorageComboBoxWithSelectNone::~QmitkDataStorageComboBoxWithSelectNone()
{
}
//-----------------------------------------------------------------------------
int QmitkDataStorageComboBoxWithSelectNone::Find( const mitk::DataNode* dataNode ) const
{
int index = QmitkDataStorageComboBox::Find(dataNode);
if (index != -1)
{
index += 1;
}
return index;
}
//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetNode( int index ) const
{
mitk::DataNode::Pointer result = NULL;
if (this->HasIndex(index))
{
if (index != 0)
{
result = m_Nodes.at(index - 1);
}
}
return result;
}
//-----------------------------------------------------------------------------
mitk::DataNode::Pointer QmitkDataStorageComboBoxWithSelectNone::GetSelectedNode() const
{
return this->GetNode(this->currentIndex());
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetSelectedNode(const mitk::DataNode::Pointer& node)
{
int currentIndex = -1;
for (int i = 0; i < m_Nodes.size(); i++)
{
if (m_Nodes[i] == node.GetPointer())
{
currentIndex = i;
break;
}
}
if (currentIndex == -1)
{
// didn't find it, so set the value to 0.
currentIndex = 0;
}
else
{
currentIndex += 1; // because the combo box contains "please select" at position zero.
}
this->setCurrentIndex(currentIndex);
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::RemoveNode( int index )
{
if(index > 0 && this->HasIndex(index))
{
// remove itk::Event observer
mitk::DataNode* dataNode = m_Nodes.at(index - 1);
// get name property first
mitk::BaseProperty* nameProperty = dataNode->GetProperty("name");
// if prop exists remove modified listener
if(nameProperty)
{
nameProperty->RemoveObserver(m_NodesModifiedObserverTags[index-1]);
// remove name property map
m_PropertyToNode.erase(dataNode);
}
// then remove delete listener on the node itself
dataNode->RemoveObserver(m_NodesDeleteObserverTags[index-1]);
// remove observer tags from lists
m_NodesModifiedObserverTags.erase(m_NodesModifiedObserverTags.begin()+index-1);
m_NodesDeleteObserverTags.erase(m_NodesDeleteObserverTags.begin()+index-1);
// remove node name from combobox
this->removeItem(index);
// remove node from node vector
m_Nodes.erase(m_Nodes.begin()+index-1);
}
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetNode(int index, const mitk::DataNode* dataNode)
{
if(index > 0 && this->HasIndex(index))
{
// if node identical, we only update the name in the QComboBoxItem
if( dataNode == this->m_Nodes.at(index-1 ) )
{
mitk::BaseProperty* nameProperty = dataNode->GetProperty("name");
std::string dataNodeNameStr = nameProperty->GetValueAsString();
this->setItemText(index, QString::fromStdString( dataNodeNameStr) );
}
else
QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
}
}
//-----------------------------------------------------------------------------
bool QmitkDataStorageComboBoxWithSelectNone::HasIndex(unsigned int index) const
{
return (m_Nodes.size() > 0 && index <= m_Nodes.size());
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::InsertNode(int index, const mitk::DataNode* dataNode)
{
if (index != 0)
{
QmitkDataStorageComboBox::InsertNode(index - 1, dataNode);
}
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::Reset()
{
QmitkDataStorageComboBox::Reset();
this->insertItem(0, ZERO_ENTRY_STRING);
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::SetZeroEntryText(const QString& zeroEntryString)
{
this->setItemText(0, zeroEntryString);
}
//-----------------------------------------------------------------------------
QString QmitkDataStorageComboBoxWithSelectNone::currentValue() const
{
return m_CurrentPath;
}
//-----------------------------------------------------------------------------
void QmitkDataStorageComboBoxWithSelectNone::setCurrentValue(const QString& path)
{
m_CurrentPath = path;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pwd.h>
#include <fcntl.h>
using namespace std;
static int *glob_flag;
//output login @ machine $
void prompt(){
struct passwd *log;
int pid = fork();
if(pid == -1){
perror("fork() presented error");
exit(1);
}
else if(pid==0){
char host[50];
if ((gethostname(host, sizeof(host)-1))==-1) {
host[0] = 'h';
host[1] = 'o';
host[2] = 's';
host[3] = 't';
host[4] = '\0';
perror("Error trying to get hostname");
}
log = getpwuid(getuid());
if(log == '\0'){
perror("Error trying to get user login");
}
cout << log->pw_name << "@" << host << "$ ";
exit(1);
}else if(pid>0){
if(-1 == wait(0))
perror("wait() presented error");
}
}
void execute(char *str[], int size){
char * newstr[512];
char * connector;
int i, j, aux;
for (i = 0; i<size; i++){
*glob_flag = 0;
//newstr[0] receives commands, first parameter after a connector
newstr[0] = str[i];
if(memcmp(newstr[0],"exit",4)==0) exit(0);
aux = 1;
//test command without flags carryng a ';'
connector = strchr(newstr[0], ';');
if (connector != NULL) newstr[0][connector - newstr[0]] = '\0';
else
for (j = i + 1; j<size; j++){
connector = strchr(str[j], ';');
if (connector != NULL){
//erase the last character if ';'
str[j][connector - str[j]] = '\0';
}
//check for && setting a flag to 1
if (memcmp(str[j], "&&", 2) == 0){
*glob_flag = 1;
i = j;
break;
}
//check for || setting a flag to 3
if (memcmp(str[j], "||", 2) == 0){
*glob_flag = 3;
i = j;
break;
}
//add flags to newstr
newstr[aux] = str[j];
aux++;
i = j;
if (connector != NULL) break;
}
int pid = fork();
if (pid == -1){
perror("fork() presented error");
exit(1);
}
else if (pid == 0){
if (-1 == execvp(newstr[0], newstr)){
perror("There was an error");
//flag 1 means, first command must be successfull to apply the second
if (*glob_flag == 1) *glob_flag = 2;
//flag 3 means, first command must be failed to apply the second
//number 5 won't pass in the breaking loop
if (*glob_flag == 3) *glob_flag = 5;
}
exit(1);
}
else if (pid>0){
int status;
wait(&status);
if (-1 == status)
perror("wait() presented error");
else if (status>0){
//flag 1 means, first command must be successfull to apply the second
if (*glob_flag == 1){
int flag2 = 0;
for (int p = i; p<size; p++){
//in case command fails look for a semicolon to reestart from there
connector = strchr(str[p], ';');
if (connector != NULL){
i = p;
//changing this flag will make the parent loop do not break because a semicolon was found
flag2 = 1;
break;
}
}
//if there is no more semicolons parent loop will break
if (flag2 == 0) *glob_flag = 2;
}
//flag 3 means, first command must be failed to apply the second
//number 5 won't pass in the breaking loop
if (*glob_flag == 3) *glob_flag = 5;
}
}
// clear the vector newstr in order to execute new commands
for (int k = 0; k<aux; k++)newstr[k] = '\0';
//break loop due to a non valid previous command connected by &&
if (*glob_flag == 2) break;
//break loop due to a valid previous command connected by ||
if (*glob_flag == 3) break;
}
}
void out(char *str[], int size){
int i;
int fdo;
char * newstr[512];
for(i=0;i<size;i++){
if (memcmp(str[i], ">\0", 2) == 0){
//open file descriptor as the argument after '>'
fdo = open(str[i+1], O_WRONLY);
if(fdo == -1){
perror("open failed");
exit(1);
}
if(dup2(fdo,1) == -1){
perror("dup failed");
exit(1);
}
break;
}
//newstr receive arguments before '>'
newstr[i] = str[i];
}
if (execvp(newstr[0], newstr) == -1)
perror("execvp 'out' failed");
}
void in(char * str[], int size){
int i;
int fdi;
char * newstr[512];
for(i=0;i<size;i++){
if (memcmp(str[i], "<\0", 2) == 0){
cerr<<"achei"<<endl;
//open file descriptor as the argument after '>'
fdi = open(str[i+1], O_RDONLY);
if(fdi == -1){
perror("open failed");
exit(1);
}
if(dup2(fdi,0) == -1){
perror("dup failed");
exit(1);
}
break;
}
//newstr receive arguments before '<'
newstr[i] = str[i];
}
if (execvp(newstr[0], newstr) == -1)
perror("execvp 'in' failed");
}
//checks which procedure it should follows for I/O redirection
int checkline(char *str[], int size){
int r=-1;
for(int i=0; i<size; i++){
if (memcmp(str[i], "|\0", 2) == 0){
return 0;
}
if (memcmp(str[i], "<\0", 2) == 0){
r = 1;
}
if (memcmp(str[i], ">\0", 2) == 0){
r = 2;
}
if (memcmp(str[i], ">>\0", 2) == 0){
r = 3;
}
}
return r;
}
int main(){
int index;
string line;
char * str[512];
char * pch;
while (true){
do{
//output login @ machine $
prompt();
getline(cin, line);
} while (line[0] == '#');
//look for '#', if find erase everything until the end of line
size_t found = line.find('#');
if (found != std::string::npos)
line.erase(found, line.length() - found);
//create a dynamic char that is a copy of input
char * input = new char[line.length() + 1];
strcpy(input, line.c_str());
//built in function to finish program when typed 'EXIT'
if (memcmp(input, "exit", 4) == 0) exit(0);
index = 0;
pch = strtok(input, " ");
while (pch != NULL){
str[index] = pch;
pch = strtok(NULL, " ");
index++;
}
str[index] = NULL;
//create a shared memory to be accessed from child and process
glob_flag = (int*)mmap(NULL, sizeof *glob_flag, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
int pos = checkline(str, index);
int fid = fork();
if(fid<0){
perror("fork failed");
exit(1);
}
if(fid == 0) {
if(pos==0){}
else if(pos == 1) in(str, index);
else if(pos == 2) out(str,index);
else if(pos == 3){}
else if(pos == -1)
execute(str, index);
exit(1);
}else if(fid>0){
if(wait(0) == -1)
perror("wait failed");
}
}
return 0;
}
<commit_msg>simple >> redirection working<commit_after>#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <pwd.h>
#include <fcntl.h>
using namespace std;
static int *glob_flag;
//output login @ machine $
void prompt(){
struct passwd *log;
int pid = fork();
if(pid == -1){
perror("fork() presented error");
exit(1);
}
else if(pid==0){
char host[50];
if ((gethostname(host, sizeof(host)-1))==-1) {
host[0] = 'h';
host[1] = 'o';
host[2] = 's';
host[3] = 't';
host[4] = '\0';
perror("Error trying to get hostname");
}
log = getpwuid(getuid());
if(log == '\0'){
perror("Error trying to get user login");
}
cout << log->pw_name << "@" << host << "$ ";
exit(1);
}else if(pid>0){
if(-1 == wait(0))
perror("wait() presented error");
}
}
void execute(char *str[], int size){
char * newstr[512];
char * connector;
int i, j, aux;
for (i = 0; i<size; i++){
*glob_flag = 0;
//newstr[0] receives commands, first parameter after a connector
newstr[0] = str[i];
if(memcmp(newstr[0],"exit",4)==0) exit(0);
aux = 1;
//test command without flags carryng a ';'
connector = strchr(newstr[0], ';');
if (connector != NULL) newstr[0][connector - newstr[0]] = '\0';
else
for (j = i + 1; j<size; j++){
connector = strchr(str[j], ';');
if (connector != NULL){
//erase the last character if ';'
str[j][connector - str[j]] = '\0';
}
//check for && setting a flag to 1
if (memcmp(str[j], "&&", 2) == 0){
*glob_flag = 1;
i = j;
break;
}
//check for || setting a flag to 3
if (memcmp(str[j], "||", 2) == 0){
*glob_flag = 3;
i = j;
break;
}
//add flags to newstr
newstr[aux] = str[j];
aux++;
i = j;
if (connector != NULL) break;
}
int pid = fork();
if (pid == -1){
perror("fork() presented error");
exit(1);
}
else if (pid == 0){
if (-1 == execvp(newstr[0], newstr)){
perror("There was an error");
//flag 1 means, first command must be successfull to apply the second
if (*glob_flag == 1) *glob_flag = 2;
//flag 3 means, first command must be failed to apply the second
//number 5 won't pass in the breaking loop
if (*glob_flag == 3) *glob_flag = 5;
}
exit(1);
}
else if (pid>0){
int status;
wait(&status);
if (-1 == status)
perror("wait() presented error");
else if (status>0){
//flag 1 means, first command must be successfull to apply the second
if (*glob_flag == 1){
int flag2 = 0;
for (int p = i; p<size; p++){
//in case command fails look for a semicolon to reestart from there
connector = strchr(str[p], ';');
if (connector != NULL){
i = p;
//changing this flag will make the parent loop do not break because a semicolon was found
flag2 = 1;
break;
}
}
//if there is no more semicolons parent loop will break
if (flag2 == 0) *glob_flag = 2;
}
//flag 3 means, first command must be failed to apply the second
//number 5 won't pass in the breaking loop
if (*glob_flag == 3) *glob_flag = 5;
}
}
// clear the vector newstr in order to execute new commands
for (int k = 0; k<aux; k++)newstr[k] = '\0';
//break loop due to a non valid previous command connected by &&
if (*glob_flag == 2) break;
//break loop due to a valid previous command connected by ||
if (*glob_flag == 3) break;
}
}
void out(char *str[], int size, bool symbol){
int i;
int fdo;
char * newstr[512];
for(i=0;i<size;i++){
if (memcmp(str[i], ">", 1) == 0){
//open file descriptor as the argument after '>'
if(symbol){
fdo = open(str[i+1], O_RDWR|O_CREAT|O_APPEND, 0666);
if(fdo == -1){
perror("open failed");
exit(1);
}
}
else{
fdo = open(str[i+1], O_RDWR|O_CREAT, 0666);
if(fdo == -1){
perror("open failed");
exit(1);
}
}
if(dup2(fdo,1) == -1){
perror("dup failed");
exit(1);
}
break;
}
//newstr receive arguments before '>'
newstr[i] = str[i];
}
if (execvp(newstr[0], newstr) == -1)
perror("execvp 'out' failed");
}
void in(char * str[], int size){
int i;
int fdi;
char * newstr[512];
for(i=0;i<size;i++){
if (memcmp(str[i], "<\0", 2) == 0){
cerr<<"achei"<<endl;
//open file descriptor as the argument after '>'
fdi = open(str[i+1], O_RDONLY);
if(fdi == -1){
perror("open failed");
exit(1);
}
if(dup2(fdi,0) == -1){
perror("dup failed");
exit(1);
}
break;
}
//newstr receive arguments before '<'
newstr[i] = str[i];
}
if (execvp(newstr[0], newstr) == -1)
perror("execvp 'in' failed");
}
//checks which procedure it should follows for I/O redirection
int checkline(char *str[], int size){
int r=-1;
for(int i=0; i<size; i++){
if (memcmp(str[i], "|\0", 2) == 0){
return 0;
}
if (memcmp(str[i], "<\0", 2) == 0){
r = 1;
}
if (memcmp(str[i], ">\0", 2) == 0){
r = 2;
}
if (memcmp(str[i], ">>\0", 3) == 0){
r = 3;
}
}
return r;
}
int main(){
int index;
string line;
char * str[512];
char * pch;
while (true){
do{
//output login @ machine $
prompt();
getline(cin, line);
} while (line[0] == '#');
//look for '#', if find erase everything until the end of line
size_t found = line.find('#');
if (found != std::string::npos)
line.erase(found, line.length() - found);
//create a dynamic char that is a copy of input
char * input = new char[line.length() + 1];
strcpy(input, line.c_str());
//built in function to finish program when typed 'EXIT'
if (memcmp(input, "exit", 4) == 0) exit(0);
index = 0;
pch = strtok(input, " ");
while (pch != NULL){
str[index] = pch;
pch = strtok(NULL, " ");
index++;
}
str[index] = NULL;
//create a shared memory to be accessed from child and process
glob_flag = (int*)mmap(NULL, sizeof *glob_flag, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
int pos = checkline(str, index);
int fid = fork();
if(fid<0){
perror("fork failed");
exit(1);
}
if(fid == 0) {
if(pos==0){}
else if(pos == 1) in(str, index);
else if(pos == 2) out(str,index, false);
else if(pos == 3) out(str,index, true);
else if(pos == -1)
execute(str, index);
exit(1);
}else if(fid>0){
if(wait(0) == -1)
perror("wait failed");
}
}
return 0;
}
<|endoftext|> |
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
#define SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
#include <sofa/component/topology/TopologySubsetDataHandler.h>
namespace sofa
{
namespace component
{
namespace topology
{
///////////////////// Private functions on TopologySubsetDataHandler changes /////////////////////////////
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::swap( unsigned int i1, unsigned int i2 )
{
container_type& data = *(m_topologyData->beginEdit());
iterator it= std::find(data.begin(),data.end(),i1);
if (it!=data.end())
(*it)=i2;
m_topologyData->endEdit();
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::add(unsigned int nbElements,
const sofa::helper::vector<sofa::helper::vector<unsigned int> > &ancestors,
const sofa::helper::vector<sofa::helper::vector<double> > &coefs)
{
// Using default values
container_type& data = *(m_topologyData->beginEdit());
unsigned int size = data.size();
bool test;
for (unsigned int i = 0; i < nbElements; ++i)
{
if (ancestors.empty() || coefs.empty())
{
const sofa::helper::vector< unsigned int > empty_vecint;
const sofa::helper::vector< double > empty_vecdouble;
test = this->applyTestCreateFunction(size + i, empty_vecint, empty_vecdouble);
}
else
test = this->applyTestCreateFunction(size + i, ancestors[i], coefs[i]);
if (test)
data.push_back( size+i );
}
this->lastElementIndex+=nbElements;
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::add(unsigned int nbElements,
const sofa::helper::vector< TopologyElementType >& ,
const sofa::helper::vector<sofa::helper::vector<unsigned int> > &ancestors,
const sofa::helper::vector<sofa::helper::vector<double> > &coefs)
{
this->add(nbElements, ancestors, coefs);
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::move( const sofa::helper::vector<unsigned int> &,
const sofa::helper::vector< sofa::helper::vector< unsigned int > >& ,
const sofa::helper::vector< sofa::helper::vector< double > >& )
{
std::cerr << "WARNING: move event on topology subsetData is not yet handled" << std::endl;
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::remove( const sofa::helper::vector<unsigned int> &index )
{
container_type& data = *(m_topologyData->beginEdit());
unsigned int it1;
unsigned int it2;
for (unsigned int i = 0; i < index.size(); ++i)
{
it1=0;
while(it1<data.size())
{
if(data[it1]==index[i])
break;
else
it1+=1;
}
if (it1<data.size())
{
it2=0;
while(it2<data.size())
{
if(data[it2]==this->lastElementIndex)
break;
else
it2+=1;
}
if (it2<data.size())
data[it2]=index[i];
data[it1]=data[data.size()-1];
this->applyDestroyFunction(index[i], data[index[i]]);
// Fix "vector size specified is too large" exception.
if (data.size() > 0)
data.resize(data.size() - 1);
else
data.resize(0);
}
else
{
it2=0;
while(it2<data.size())
{
if(data[it2]==this->lastElementIndex)
break;
else
it2+=1;
}
if (it2<data.size())
{
data[it2]=index[i];
}
}
--this->lastElementIndex;
}
m_topologyData->endEdit();
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::renumber( const sofa::helper::vector<unsigned int> &index )
{
container_type& data = *(m_topologyData->beginEdit());
container_type copy = m_topologyData->getValue(); // not very efficient memory-wise, but I can see no better solution...
for (unsigned int i = 0; i < data.size(); ++i)
{
data[i] = copy[ index[i] ];
}
m_topologyData->endEdit();
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::addOnMovedPosition(const sofa::helper::vector<unsigned int> &,
const sofa::helper::vector<TopologyElementType> &)
{
std::cerr << "WARNING: addOnMovedPosition event on topology subsetData is not yet handled" << std::endl;
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::removeOnMovedPosition(const sofa::helper::vector<unsigned int> &)
{
std::cerr << "WARNING: removeOnMovedPosition event on topology subsetData is not yet handled" << std::endl;
}
} // namespace topology
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
<commit_msg>r11554/sofa-dev : FIX: problem of double suppression of elements while handling topology event using handlers.<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1 *
* (c) 2006-2011 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Modules *
* *
* Authors: The SOFA Team and external contributors (see Authors.txt) *
* *
* Contact information: [email protected] *
******************************************************************************/
#ifndef SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
#define SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
#include <sofa/component/topology/TopologySubsetDataHandler.h>
namespace sofa
{
namespace component
{
namespace topology
{
///////////////////// Private functions on TopologySubsetDataHandler changes /////////////////////////////
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::swap( unsigned int i1, unsigned int i2 )
{
container_type& data = *(m_topologyData->beginEdit());
iterator it= std::find(data.begin(),data.end(),i1);
if (it!=data.end())
(*it)=i2;
m_topologyData->endEdit();
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::add(unsigned int nbElements,
const sofa::helper::vector<sofa::helper::vector<unsigned int> > &ancestors,
const sofa::helper::vector<sofa::helper::vector<double> > &coefs)
{
// Using default values
container_type& data = *(m_topologyData->beginEdit());
unsigned int size = data.size();
bool test;
for (unsigned int i = 0; i < nbElements; ++i)
{
if (ancestors.empty() || coefs.empty())
{
const sofa::helper::vector< unsigned int > empty_vecint;
const sofa::helper::vector< double > empty_vecdouble;
test = this->applyTestCreateFunction(size + i, empty_vecint, empty_vecdouble);
}
else
test = this->applyTestCreateFunction(size + i, ancestors[i], coefs[i]);
if (test)
data.push_back( size+i );
}
this->lastElementIndex+=nbElements;
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::add(unsigned int nbElements,
const sofa::helper::vector< TopologyElementType >& ,
const sofa::helper::vector<sofa::helper::vector<unsigned int> > &ancestors,
const sofa::helper::vector<sofa::helper::vector<double> > &coefs)
{
this->add(nbElements, ancestors, coefs);
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::move( const sofa::helper::vector<unsigned int> &,
const sofa::helper::vector< sofa::helper::vector< unsigned int > >& ,
const sofa::helper::vector< sofa::helper::vector< double > >& )
{
std::cerr << "WARNING: move event on topology subsetData is not yet handled" << std::endl;
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::remove( const sofa::helper::vector<unsigned int> &index )
{
container_type& data = *(m_topologyData->beginEdit());
unsigned int it1;
unsigned int it2;
for (unsigned int i = 0; i < index.size(); ++i)
{
it1=0;
while(it1<data.size())
{
if(data[it1]==index[i])
break;
else
it1+=1;
}
if (it1<data.size())
{
it2=0;
while(it2<data.size())
{
if(data[it2]==this->lastElementIndex)
break;
else
it2+=1;
}
if (it2<data.size())
data[it2]=index[i];
data[it1]=data[data.size()-1];
unsigned int size_before = data.size();
// Call destroy function implemented in specific component
this->applyDestroyFunction(index[i], data[index[i]]);
// As applyDestroyFunction could already perfom the suppression, if implemented. Size is checked again. If no change this handler really perform the suppresion
if (size_before == data.size())
data.resize(data.size() - 1);
}
else
{
it2=0;
while(it2<data.size())
{
if(data[it2]==this->lastElementIndex)
break;
else
it2+=1;
}
if (it2<data.size())
{
data[it2]=index[i];
}
}
--this->lastElementIndex;
}
m_topologyData->endEdit();
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::renumber( const sofa::helper::vector<unsigned int> &index )
{
container_type& data = *(m_topologyData->beginEdit());
container_type copy = m_topologyData->getValue(); // not very efficient memory-wise, but I can see no better solution...
for (unsigned int i = 0; i < data.size(); ++i)
{
data[i] = copy[ index[i] ];
}
m_topologyData->endEdit();
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::addOnMovedPosition(const sofa::helper::vector<unsigned int> &,
const sofa::helper::vector<TopologyElementType> &)
{
std::cerr << "WARNING: addOnMovedPosition event on topology subsetData is not yet handled" << std::endl;
}
template <typename TopologyElementType, typename VecT>
void TopologySubsetDataHandler <TopologyElementType, VecT>::removeOnMovedPosition(const sofa::helper::vector<unsigned int> &)
{
std::cerr << "WARNING: removeOnMovedPosition event on topology subsetData is not yet handled" << std::endl;
}
} // namespace topology
} // namespace component
} // namespace sofa
#endif // SOFA_COMPONENT_TOPOLOGY_TOPOLOGYSUBSETDATAHANDLER_INL
<|endoftext|> |
<commit_before>#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include "defs.h"
#include "prbg.h"
#define MAX_PASSWD 128
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
using namespace std;
int main(int argc, char* argv[]){
//Checking input
if(!(argc==3 && atoi(argv[1]))){
//perror("Incorrect arguments");
printf("\nCorrect usage:\n%s <KEY> [input file]\n\n<KEY>\n Can be any integer with more than 4 digits which is not symetrical\n (not like this: 321321).\n\n[file]\n Name of the input file.\n ",argv[0]);
return -1;
}
//initializations and checks
const int key1size=strlen(argv[1])/2;
char ckey1[key1size];
char ckey2[key1size+1];
if(strlen(argv[1])%2==0){
for(int i=0;i<key1size;++i){
ckey1[i]=argv[1][i];
ckey2[i]=argv[1][key1size+i];
}
}
else{
for(int i=0;i<key1size;++i){
ckey1[i]=argv[1][i];
ckey2[i]=argv[1][key1size+i];
}
ckey2[key1size]=argv[1][2*key1size];
}
double key1=(double)atoi(ckey1), key2=(double)atoi(ckey2);
if(key1==key2){perror("Key cannot be symmetrical! Use your imagination!\n"); return -1;}
//end of initializations of key1, key2
double eskey1=pow(key1,2)*pow(10,((-1)*cdigits(pow(key1,2)))+1),
eskey2=pow(key2,2)*pow(10,((-1)*cdigits(pow(key2,2)))+1);
Y1[0]=eskey1-floor(eskey1);
Y2[0]=eskey2-floor(eskey2);
//end initializations and checks
//eskey = key^2*10^(-keydigits+1)
FILE *fin,*fout;
_byte c=0;
char *pch=strstr(argv[2],".hid");
char *outpfile;
if(pch==NULL){
int maxsize = MIN(strlen(argv[2])+4,MAX_PASSWD);
outpfile= (char*) calloc(maxsize,sizeof(char));
strncpy(outpfile,argv[2], maxsize);
strcat(outpfile,".hid");
}
else {
int maxsize = MIN(strlen(argv[2])-4,MAX_PASSWD);
outpfile= (char*) calloc(maxsize,sizeof(char));
for(int i = 0; i<maxsize; ++i)
outpfile[i]=argv[2][i];
}
if((fin=fopen(argv[2],"rb"))!=NULL){
if((fout=fopen(outpfile,"wb"))!=NULL){
free(outpfile);
while(!feof(fin)){
c=getc(fin);
c^=prbg(&eskey1,&eskey2);
putc(c,fout);
}
fclose(fout);
}
else{
printf("No output file\n");
}
fclose(fin);
}
else{
printf("No input file\n");
}
return 0;
}
<commit_msg>Fixed indentaiton<commit_after>#include<cstdio>
#include<cmath>
#include<cstdlib>
#include<cstring>
#include "defs.h"
#include "prbg.h"
#define MAX_PASSWD 128
#define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
using namespace std;
int main(int argc, char* argv[]){
//Checking input
if(!(argc==3 && atoi(argv[1]))){
//perror("Incorrect arguments");
printf("\nCorrect usage:\n%s <KEY> [input file]\n\n<KEY>\n Can be any integer with more than 4 digits which is not symetrical\n (not like this: 321321).\n\n[file]\n Name of the input file.\n ",argv[0]);
return -1;
}
//initializations and checks
const int key1size=strlen(argv[1])/2;
char ckey1[key1size];
char ckey2[key1size+1];
if (strlen(argv[1])%2==0) {
for (int i=0;i<key1size;++i) {
ckey1[i]=argv[1][i];
ckey2[i]=argv[1][key1size+i];
}
}
else {
for (int i=0;i<key1size;++i){
ckey1[i]=argv[1][i];
ckey2[i]=argv[1][key1size+i];
}
ckey2[key1size]=argv[1][2*key1size];
}
double key1=(double)atoi(ckey1), key2=(double)atoi(ckey2);
if (key1==key2) { perror("Key cannot be symmetrical! Use your imagination!\n"); return -1; }
//end of initializations of key1, key2
double eskey1=pow(key1,2)*pow(10,((-1)*cdigits(pow(key1,2)))+1),
eskey2=pow(key2,2)*pow(10,((-1)*cdigits(pow(key2,2)))+1);
Y1[0]=eskey1-floor(eskey1);
Y2[0]=eskey2-floor(eskey2);
//end initializations and checks
//eskey = key^2*10^(-keydigits+1)
FILE *fin,*fout;
_byte c=0;
char *pch=strstr(argv[2],".hid");
char *outpfile;
if(pch==NULL){
int maxsize = MIN(strlen(argv[2])+4,MAX_PASSWD);
outpfile= (char*) calloc(maxsize,sizeof(char));
strncpy(outpfile,argv[2], maxsize);
strcat(outpfile,".hid");
}
else {
int maxsize = MIN(strlen(argv[2])-4,MAX_PASSWD);
outpfile= (char*) calloc(maxsize,sizeof(char));
for(int i = 0; i<maxsize; ++i)
outpfile[i]=argv[2][i];
}
if ((fin=fopen(argv[2],"rb"))!=NULL) {
if ((fout=fopen(outpfile,"wb"))!=NULL) {
free(outpfile);
while (!feof(fin)) {
c=getc(fin);
c^=prbg(&eskey1,&eskey2);
putc(c,fout);
}
fclose(fout);
}
else {
printf("No output file\n");
}
fclose(fin);
}
else {
printf("No input file\n");
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* libcec-daemon
* A simple daemon to connect libcec to uinput. That is, using your TV to control your PC!
* by Andrew Brampton
*
* TODO
*
*/
#include "main.h"
#define VERSION "libcec-daemon v0.9"
#define CEC_NAME "linux PC"
#define UINPUT_NAME "libcec-daemon"
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstdint>
#include <cstddef>
#include <csignal>
#include <vector>
#include <boost/program_options.hpp>
#include "accumulator.hpp"
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
using namespace CEC;
using namespace log4cplus;
using std::cout;
using std::cerr;
using std::endl;
using std::min;
using std::string;
using std::vector;
static Logger logger = Logger::getInstance("main");
const vector<__u16> Main::uinputCecMap = Main::setupUinputMap();
Main & Main::instance() {
// Singleton pattern so we can use main from a sighandle
static Main main;
return main;
}
Main::Main() : cec(CEC_NAME, this), uinput(UINPUT_NAME, uinputCecMap), running(true) {
LOG4CPLUS_TRACE_STR(logger, "Main::Main()");
signal (SIGINT, &Main::signalHandler);
signal (SIGTERM, &Main::signalHandler);
}
Main::~Main() {
LOG4CPLUS_TRACE_STR(logger, "Main::~Main()");
stop();
}
void Main::loop() {
LOG4CPLUS_TRACE_STR(logger, "Main::loop()");
cec.open();
while (running) {
LOG4CPLUS_TRACE_STR(logger, "Loop");
sleep(1);
}
cec.close();
}
void Main::stop() {
LOG4CPLUS_TRACE_STR(logger, "Main::stop()");
running = false;
}
void Main::listDevices() {
LOG4CPLUS_TRACE_STR(logger, "Main::listDevices()");
cec.listDevices(cout);
}
void Main::signalHandler(int sigNum) {
LOG4CPLUS_DEBUG_STR(logger, "Main::signalHandler()");
Main::instance().stop();
}
const std::vector<__u16> & Main::setupUinputMap() {
static std::vector<__u16> uinputCecMap;
if (uinputCecMap.empty()) {
uinputCecMap.resize(CEC_USER_CONTROL_CODE_MAX + 1, 0);
uinputCecMap[CEC_USER_CONTROL_CODE_SELECT ] = KEY_ENTER;
uinputCecMap[CEC_USER_CONTROL_CODE_UP ] = KEY_UP;
uinputCecMap[CEC_USER_CONTROL_CODE_DOWN ] = KEY_DOWN;
uinputCecMap[CEC_USER_CONTROL_CODE_LEFT ] = KEY_LEFT;
uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT ] = KEY_RIGHT;
uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_UP ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_DOWN ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_UP ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_DOWN ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_ROOT_MENU ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SETUP_MENU ] = KEY_SETUP;
uinputCecMap[CEC_USER_CONTROL_CODE_CONTENTS_MENU ] = KEY_MENU;
uinputCecMap[CEC_USER_CONTROL_CODE_FAVORITE_MENU ] = KEY_FAVORITES;
uinputCecMap[CEC_USER_CONTROL_CODE_EXIT ] = KEY_BACKSPACE;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER0 ] = KEY_0;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER1 ] = KEY_1;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER2 ] = KEY_2;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER3 ] = KEY_3;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER4 ] = KEY_4;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER5 ] = KEY_5;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER6 ] = KEY_6;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER7 ] = KEY_7;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER8 ] = KEY_8;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER9 ] = KEY_9;
uinputCecMap[CEC_USER_CONTROL_CODE_DOT ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_ENTER ] = KEY_ENTER;
uinputCecMap[CEC_USER_CONTROL_CODE_CLEAR ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_NEXT_FAVORITE ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_UP ] = KEY_CHANNELUP;
uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_DOWN ] = KEY_CHANNELDOWN;
uinputCecMap[CEC_USER_CONTROL_CODE_PREVIOUS_CHANNEL ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SOUND_SELECT ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_INPUT_SELECT ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_DISPLAY_INFORMATION ] = KEY_INFO;
uinputCecMap[CEC_USER_CONTROL_CODE_HELP ] = KEY_HELP;
uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_UP ] = KEY_PAGEUP;
uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_DOWN ] = KEY_PAGEDOWN;
uinputCecMap[CEC_USER_CONTROL_CODE_POWER ] = KEY_POWER;
uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_UP ] = KEY_VOLUMEUP;
uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_DOWN ] = KEY_VOLUMEDOWN;
uinputCecMap[CEC_USER_CONTROL_CODE_MUTE ] = KEY_MUTE;
uinputCecMap[CEC_USER_CONTROL_CODE_PLAY ] = KEY_PLAY;
uinputCecMap[CEC_USER_CONTROL_CODE_STOP ] = KEY_STOP;
uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE ] = KEY_PAUSE;
uinputCecMap[CEC_USER_CONTROL_CODE_RECORD ] = KEY_RECORD;
uinputCecMap[CEC_USER_CONTROL_CODE_REWIND ] = KEY_REWIND;
uinputCecMap[CEC_USER_CONTROL_CODE_FAST_FORWARD ] = KEY_FASTFORWARD;
uinputCecMap[CEC_USER_CONTROL_CODE_EJECT ] = KEY_EJECTCD;
uinputCecMap[CEC_USER_CONTROL_CODE_FORWARD ] = KEY_NEXTSONG;
uinputCecMap[CEC_USER_CONTROL_CODE_BACKWARD ] = KEY_PREVIOUSSONG;
uinputCecMap[CEC_USER_CONTROL_CODE_STOP_RECORD ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_ANGLE ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SUB_PICTURE ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_VIDEO_ON_DEMAND ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_ELECTRONIC_PROGRAM_GUIDE ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_TIMER_PROGRAMMING ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_INITIAL_CONFIGURATION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_PLAY_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_PLAY_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_RECORD_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_STOP_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_MUTE_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_RESTORE_VOLUME_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_TUNE_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_MEDIA_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AV_INPUT_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AUDIO_INPUT_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_POWER_TOGGLE_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_POWER_ON_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_F1_BLUE ] = KEY_BLUE;
uinputCecMap[CEC_USER_CONTROL_CODE_F2_RED ] = KEY_RED;
uinputCecMap[CEC_USER_CONTROL_CODE_F3_GREEN ] = KEY_GREEN;
uinputCecMap[CEC_USER_CONTROL_CODE_F4_YELLOW ] = KEY_YELLOW;
uinputCecMap[CEC_USER_CONTROL_CODE_F5 ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_DATA ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_AN_RETURN ] = 0;
}
return uinputCecMap;
}
int Main::onCecLogMessage(const cec_log_message &message) {
LOG4CPLUS_DEBUG(logger, "Main::onCecLogMessage(" << message << ")");
return 1;
}
int Main::onCecKeyPress(const cec_keypress &key) {
LOG4CPLUS_DEBUG(logger, "Main::onCecKeyPress(" << key << ")");
int uinputKey = 0;
// Check bounds and find uinput code for this cec keypress
if (key.keycode >= 0 && key.keycode <= CEC_USER_CONTROL_CODE_MAX)
uinputKey = uinputCecMap[key.keycode];
if (uinputKey != 0) {
LOG4CPLUS_DEBUG(logger, "sent " << uinputKey);
uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 1 : 0);
uinput.sync();
}
return 1;
}
int Main::onCecCommand(const cec_command & command) {
LOG4CPLUS_DEBUG(logger, "Main::onCecCommand(" << command << ")");
return 1;
}
int Main::onCecConfigurationChanged(const libcec_configuration & configuration) {
LOG4CPLUS_DEBUG(logger, "Main::onCecConfigurationChanged(" << configuration << ")");
return 1;
}
int main (int argc, char *argv[]) {
BasicConfigurator config;
config.configure();
int loglevel = 0;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "show help message")
("version,V", "show version (and exit)")
("daemon,d", "daemon mode, run in background")
("list,l", "list available CEC adapters and devices")
("verbose,v", accumulator<int>(&loglevel)->implicit_value(1), "verbose output (use -vv for more)")
("quiet,q", "quiet output (print almost nothing)")
("usb", po::value<std::string>(), "USB adapter path (as shown by --list)")
;
po::positional_options_description p;
p.add("usb", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help")) {
cout << "Usage: " << argv[0] << " [-h] [-v] [-d] [usb]" << endl << endl;
cout << desc << endl;
return 0;
}
if (vm.count("version")) {
cout << VERSION << endl;
return 0;
}
if(vm.count("quiet")) {
loglevel = -1;
} else {
loglevel = min(loglevel, 2);
}
switch (loglevel) {
case 2: logger.setLogLevel(TRACE_LOG_LEVEL); break;
case 1: logger.setLogLevel(DEBUG_LOG_LEVEL); break;
default: logger.setLogLevel(INFO_LOG_LEVEL); break;
case -1: logger.setLogLevel(FATAL_LOG_LEVEL); break;
}
try {
// Create the main
Main & main = Main::instance();
if (vm.count("list")) {
main.listDevices();
return 0;
}
if (vm.count("usb")) {
cout << vm["usb"].as< string >() << endl;
}
if (vm.count("daemon")) {
daemon(0, 0);
}
main.loop();
} catch (std::exception & e) {
cerr << e.what() << endl;
return -1;
}
return 0;
}
<commit_msg>Ensure the root logger's log level is set.<commit_after>/**
* libcec-daemon
* A simple daemon to connect libcec to uinput. That is, using your TV to control your PC!
* by Andrew Brampton
*
* TODO
*
*/
#include "main.h"
#define VERSION "libcec-daemon v0.9"
#define CEC_NAME "linux PC"
#define UINPUT_NAME "libcec-daemon"
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <cstdint>
#include <cstddef>
#include <csignal>
#include <vector>
#include <boost/program_options.hpp>
#include "accumulator.hpp"
#include <log4cplus/logger.h>
#include <log4cplus/loggingmacros.h>
#include <log4cplus/configurator.h>
using namespace CEC;
using namespace log4cplus;
using std::cout;
using std::cerr;
using std::endl;
using std::min;
using std::string;
using std::vector;
static Logger logger = Logger::getInstance("main");
const vector<__u16> Main::uinputCecMap = Main::setupUinputMap();
Main & Main::instance() {
// Singleton pattern so we can use main from a sighandle
static Main main;
return main;
}
Main::Main() : cec(CEC_NAME, this), uinput(UINPUT_NAME, uinputCecMap), running(true) {
LOG4CPLUS_TRACE_STR(logger, "Main::Main()");
signal (SIGINT, &Main::signalHandler);
signal (SIGTERM, &Main::signalHandler);
}
Main::~Main() {
LOG4CPLUS_TRACE_STR(logger, "Main::~Main()");
stop();
}
void Main::loop() {
LOG4CPLUS_TRACE_STR(logger, "Main::loop()");
cec.open();
while (running) {
LOG4CPLUS_TRACE_STR(logger, "Loop");
sleep(1);
}
cec.close();
}
void Main::stop() {
LOG4CPLUS_TRACE_STR(logger, "Main::stop()");
running = false;
}
void Main::listDevices() {
LOG4CPLUS_TRACE_STR(logger, "Main::listDevices()");
cec.listDevices(cout);
}
void Main::signalHandler(int sigNum) {
LOG4CPLUS_DEBUG_STR(logger, "Main::signalHandler()");
Main::instance().stop();
}
const std::vector<__u16> & Main::setupUinputMap() {
static std::vector<__u16> uinputCecMap;
if (uinputCecMap.empty()) {
uinputCecMap.resize(CEC_USER_CONTROL_CODE_MAX + 1, 0);
uinputCecMap[CEC_USER_CONTROL_CODE_SELECT ] = KEY_ENTER;
uinputCecMap[CEC_USER_CONTROL_CODE_UP ] = KEY_UP;
uinputCecMap[CEC_USER_CONTROL_CODE_DOWN ] = KEY_DOWN;
uinputCecMap[CEC_USER_CONTROL_CODE_LEFT ] = KEY_LEFT;
uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT ] = KEY_RIGHT;
uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_UP ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_RIGHT_DOWN ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_UP ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_LEFT_DOWN ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_ROOT_MENU ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SETUP_MENU ] = KEY_SETUP;
uinputCecMap[CEC_USER_CONTROL_CODE_CONTENTS_MENU ] = KEY_MENU;
uinputCecMap[CEC_USER_CONTROL_CODE_FAVORITE_MENU ] = KEY_FAVORITES;
uinputCecMap[CEC_USER_CONTROL_CODE_EXIT ] = KEY_BACKSPACE;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER0 ] = KEY_0;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER1 ] = KEY_1;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER2 ] = KEY_2;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER3 ] = KEY_3;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER4 ] = KEY_4;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER5 ] = KEY_5;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER6 ] = KEY_6;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER7 ] = KEY_7;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER8 ] = KEY_8;
uinputCecMap[CEC_USER_CONTROL_CODE_NUMBER9 ] = KEY_9;
uinputCecMap[CEC_USER_CONTROL_CODE_DOT ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_ENTER ] = KEY_ENTER;
uinputCecMap[CEC_USER_CONTROL_CODE_CLEAR ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_NEXT_FAVORITE ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_UP ] = KEY_CHANNELUP;
uinputCecMap[CEC_USER_CONTROL_CODE_CHANNEL_DOWN ] = KEY_CHANNELDOWN;
uinputCecMap[CEC_USER_CONTROL_CODE_PREVIOUS_CHANNEL ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SOUND_SELECT ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_INPUT_SELECT ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_DISPLAY_INFORMATION ] = KEY_INFO;
uinputCecMap[CEC_USER_CONTROL_CODE_HELP ] = KEY_HELP;
uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_UP ] = KEY_PAGEUP;
uinputCecMap[CEC_USER_CONTROL_CODE_PAGE_DOWN ] = KEY_PAGEDOWN;
uinputCecMap[CEC_USER_CONTROL_CODE_POWER ] = KEY_POWER;
uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_UP ] = KEY_VOLUMEUP;
uinputCecMap[CEC_USER_CONTROL_CODE_VOLUME_DOWN ] = KEY_VOLUMEDOWN;
uinputCecMap[CEC_USER_CONTROL_CODE_MUTE ] = KEY_MUTE;
uinputCecMap[CEC_USER_CONTROL_CODE_PLAY ] = KEY_PLAY;
uinputCecMap[CEC_USER_CONTROL_CODE_STOP ] = KEY_STOP;
uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE ] = KEY_PAUSE;
uinputCecMap[CEC_USER_CONTROL_CODE_RECORD ] = KEY_RECORD;
uinputCecMap[CEC_USER_CONTROL_CODE_REWIND ] = KEY_REWIND;
uinputCecMap[CEC_USER_CONTROL_CODE_FAST_FORWARD ] = KEY_FASTFORWARD;
uinputCecMap[CEC_USER_CONTROL_CODE_EJECT ] = KEY_EJECTCD;
uinputCecMap[CEC_USER_CONTROL_CODE_FORWARD ] = KEY_NEXTSONG;
uinputCecMap[CEC_USER_CONTROL_CODE_BACKWARD ] = KEY_PREVIOUSSONG;
uinputCecMap[CEC_USER_CONTROL_CODE_STOP_RECORD ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_ANGLE ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SUB_PICTURE ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_VIDEO_ON_DEMAND ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_ELECTRONIC_PROGRAM_GUIDE ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_TIMER_PROGRAMMING ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_INITIAL_CONFIGURATION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_PLAY_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_PLAY_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_RECORD_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_PAUSE_RECORD_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_STOP_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_MUTE_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_RESTORE_VOLUME_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_TUNE_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_MEDIA_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AV_INPUT_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_SELECT_AUDIO_INPUT_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_POWER_TOGGLE_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_POWER_OFF_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_POWER_ON_FUNCTION ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_F1_BLUE ] = KEY_BLUE;
uinputCecMap[CEC_USER_CONTROL_CODE_F2_RED ] = KEY_RED;
uinputCecMap[CEC_USER_CONTROL_CODE_F3_GREEN ] = KEY_GREEN;
uinputCecMap[CEC_USER_CONTROL_CODE_F4_YELLOW ] = KEY_YELLOW;
uinputCecMap[CEC_USER_CONTROL_CODE_F5 ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_DATA ] = 0;
uinputCecMap[CEC_USER_CONTROL_CODE_AN_RETURN ] = 0;
}
return uinputCecMap;
}
int Main::onCecLogMessage(const cec_log_message &message) {
LOG4CPLUS_DEBUG(logger, "Main::onCecLogMessage(" << message << ")");
return 1;
}
int Main::onCecKeyPress(const cec_keypress &key) {
LOG4CPLUS_DEBUG(logger, "Main::onCecKeyPress(" << key << ")");
int uinputKey = 0;
// Check bounds and find uinput code for this cec keypress
if (key.keycode >= 0 && key.keycode <= CEC_USER_CONTROL_CODE_MAX)
uinputKey = uinputCecMap[key.keycode];
if (uinputKey != 0) {
LOG4CPLUS_DEBUG(logger, "sent " << uinputKey);
uinput.send_event(EV_KEY, uinputKey, key.duration == 0 ? 1 : 0);
uinput.sync();
}
return 1;
}
int Main::onCecCommand(const cec_command & command) {
LOG4CPLUS_DEBUG(logger, "Main::onCecCommand(" << command << ")");
return 1;
}
int Main::onCecConfigurationChanged(const libcec_configuration & configuration) {
LOG4CPLUS_DEBUG(logger, "Main::onCecConfigurationChanged(" << configuration << ")");
return 1;
}
int main (int argc, char *argv[]) {
BasicConfigurator config;
config.configure();
int loglevel = 0;
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "show help message")
("version,V", "show version (and exit)")
("daemon,d", "daemon mode, run in background")
("list,l", "list available CEC adapters and devices")
("verbose,v", accumulator<int>(&loglevel)->implicit_value(1), "verbose output (use -vv for more)")
("quiet,q", "quiet output (print almost nothing)")
("usb", po::value<std::string>(), "USB adapter path (as shown by --list)")
;
po::positional_options_description p;
p.add("usb", 1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help")) {
cout << "Usage: " << argv[0] << " [-h] [-v] [-d] [usb]" << endl << endl;
cout << desc << endl;
return 0;
}
if (vm.count("version")) {
cout << VERSION << endl;
return 0;
}
if(vm.count("quiet")) {
loglevel = -1;
} else {
loglevel = min(loglevel, 2);
}
Logger root = Logger::getRoot();
switch (loglevel) {
case 2: root.setLogLevel(TRACE_LOG_LEVEL); break;
case 1: root.setLogLevel(DEBUG_LOG_LEVEL); break;
default: root.setLogLevel(INFO_LOG_LEVEL); break;
case -1: root.setLogLevel(FATAL_LOG_LEVEL); break;
}
try {
// Create the main
Main & main = Main::instance();
if (vm.count("list")) {
main.listDevices();
return 0;
}
if (vm.count("usb")) {
cout << vm["usb"].as< string >() << endl;
}
if (vm.count("daemon")) {
daemon(0, 0);
}
main.loop();
} catch (std::exception & e) {
cerr << e.what() << endl;
return -1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include "MuMaterial.h"
#include "rhythm.hpp"
using namespace std;
void PrintVector (vector<float> v, string message);
int main ()
{
MuInit();
Rhythm rhythm(4, 4, 60);
rhythm.GenerateBaseRhythm(2);
vector<float> base_rhythm = rhythm.base_rhythm;
PrintVector(rhythm.base_rhythm, "base_rhythm");
cout << endl << "Ok!" << endl;
return 0;
}
void PrintVector (vector<float> v, string message)
{
cout << message << ": ";
for (unsigned int index = 0; index < v.size(); index++)
{
cout << v[index] << " ";
}
cout << endl;
}
<commit_msg>Make print vector as auto function<commit_after>#include <iostream>
#include <vector>
#include "MuMaterial.h"
#include "rhythm.hpp"
using namespace std;
void PrintVector (auto const v, string message);
int main ()
{
MuInit();
Rhythm rhythm(4, 4, 60);
rhythm.GenerateBaseRhythm(2);
vector<float> base_rhythm = rhythm.base_rhythm;
PrintVector(rhythm.base_rhythm, "base_rhythm");
cout << endl << "Ok!" << endl;
return 0;
}
void PrintVector (auto const v, string message)
{
cout << message << ": ";
for (unsigned int index = 0; index < v.size(); index++)
{
cout << v[index] << " ";
}
cout << endl;
}
<|endoftext|> |
<commit_before>#include <cstdint>
#include <chrono>
#include <thread>
#include <future>
#include <functional>
#include <random>
#include <iostream>
#include <vector>
#include <algorithm>
using microsec = std::chrono::microseconds;
using millisec = std::chrono::milliseconds;
using nanosec = std::chrono::nanoseconds;
using resolution = nanosec;
using my_clock = std::chrono::steady_clock;
#define INTERVAL_PERIOD resolution(10000000)
#define JITTER_MIN 100000
#define JITTER_MAX 1000000
#define ITERATION_MAX 400
#define RUNTIME_LIMIT resolution(4000000000)
template <int IntervalMin, int IntervalMax>
class PeriodicTimer {
private:
volatile bool is_running_ = false;
std::future<int> pending_;
my_clock::time_point firstInterval_;
my_clock::time_point lastInterval_;
//! @brief call doIt until stop() is called, and return the number of
// iterations for which doIt was called.
int doItTimed(std::function<void(resolution)> doIt) {
int result = 0;
std::random_device seedGenerator;
std::mt19937 gen(seedGenerator());
std::uniform_int_distribution<> distribution(IntervalMin,
IntervalMax);
resolution jitter = resolution(distribution(gen));
firstInterval_ = my_clock::now();
my_clock::time_point start{firstInterval_};
my_clock::time_point startNext{firstInterval_};
while (is_running_) {
// Delay the function call for a small random amount of time.
std::this_thread::sleep_for(jitter);
doIt(jitter);
++result;
// Calculate the next time we want to iterate
startNext = start + INTERVAL_PERIOD;
auto currentTime = my_clock::now();
if (currentTime < startNext) {
// Wait for the next period start time
std::this_thread::sleep_until(startNext);
} else {
std::cout << "Warning: Missed interval " << result << std::endl;
}
// Get a new jitter and start time for the next iteration
jitter = resolution(distribution(gen));
start = startNext;
}
lastInterval_ = startNext;
return result;
}
public:
//! @brief call doIt for repeat_count iterations.
// A random delay (jitter) is calculated for each call to doIt. If doIt
// runs for less than the delay, doItCount will wait for the remaining time
// before the next interval. If doIt takes more time than the delay, the
// next iteration takes place immediately. This way, doIt is called no more
// often than
void doItCount(std::function<void(resolution)> doIt,
uint32_t repeat_count) {
std::random_device seedGenerator;
std::mt19937 gen(seedGenerator());
std::uniform_int_distribution<> distribution(IntervalMin,
IntervalMax);
resolution jitterNext = resolution(distribution(gen));
resolution jitter;
firstInterval_ = my_clock::now();
my_clock::time_point start{firstInterval_};
my_clock::time_point startNext{start};
uint32_t itr = 0;
while (itr < repeat_count) {
jitter = jitterNext;
// Delay the function call for a small random amount of time.
std::this_thread::sleep_for(jitter);
doIt(jitter);
++itr;
// Get a new jitter for the next iteration
jitterNext = resolution(distribution(gen));
// Calculate the next time we want to iterate
startNext = start + INTERVAL_PERIOD;
// Wait for the next period start time
std::this_thread::sleep_until(startNext);
start = startNext;
}
lastInterval_ = my_clock::now();
}
void start(std::function<void(resolution)> doIt) {
is_running_ = true;
// Run doItTimed on another thread, passing the "this" pointer and the
// function doItTimed must run until stop() is executed.
auto f = std::async(std::launch::async,
&PeriodicTimer::doItTimed,
this,
doIt);
// Move the future to another variable so we don't wait for it here.
pending_ = std::move(f);
}
int stop() {
// Allow doItTimed to exit its while-loop
is_running_ = false;
// Return the number of iterations
return pending_.get();
}
my_clock::duration runtime() const {
return lastInterval_ - firstInterval_;
}
};
class Jitters {
std::vector<resolution> jitters_;
resolution smallest_;
resolution largest_;
public:
Jitters()
: jitters_(ITERATION_MAX)
, smallest_(resolution::max())
, largest_(resolution::min()) {
}
void
insert(resolution j) {
jitters_.push_back(j);
if (j < smallest_) {
smallest_ = j;
}
if (j > largest_) {
largest_ = j;
}
}
resolution
average() {
resolution result(0);
for (auto j : jitters_) {
result = result + j;
}
result /= jitters_.size();
return result;
}
resolution
largest() {
return largest_;
}
resolution
smallest() {
return smallest_;
}
resolution
median() {
std::sort(jitters_.begin(), jitters_.end());
return jitters_[jitters_.size() / 2];
}
};
void main() {
Jitters jitter1;
const resolution jitterMin = resolution(JITTER_MIN);
const resolution jitterMax = resolution(JITTER_MAX);
const resolution repeatInterval = INTERVAL_PERIOD;
PeriodicTimer<JITTER_MIN, JITTER_MAX> timer;
std::cout << "The resolution of the high-resolution clock is: "
<< (static_cast<double>(std::chrono::high_resolution_clock::period::num)
/ std::chrono::high_resolution_clock::period::den) << " sec"
<< std::endl;
std::cout << "The resolution of the steady clock is: "
<< (static_cast<double>(std::chrono::steady_clock::period::num)
/ std::chrono::steady_clock::period::den)
<< " sec" << std::endl;
std::cout << "The resolution of the system clock is: "
<< (static_cast<double>(std::chrono::system_clock::period::num)
/ std::chrono::system_clock::period::den)
<< " sec" << std::endl << std::endl;
std::cout << "Jitter Tests." << std::endl
<< " Interval: "
<< std::chrono::duration_cast<millisec>(repeatInterval).count()
<< " ms" << std::endl
<< " Min Jitter: "
<< std::chrono::duration_cast<microsec>(jitterMin).count() << " us"
<< std::endl
<< " Max Jitter: "
<< std::chrono::duration_cast<microsec>(jitterMax).count() << " us"
<< std::endl << std::endl;
/*** Iteration Test ***/
std::cout << "Jitter test 1. Iterations: " << ITERATION_MAX << std::endl;
timer.doItCount(std::bind(&Jitters::insert, &jitter1, std::placeholders::_1), ITERATION_MAX);
auto runtime = timer.runtime();
std::cout << "Iterations " << ITERATION_MAX << std::endl;
std::cout << "Expected elapsed time "
<< (ITERATION_MAX * std::chrono::duration_cast<millisec>(repeatInterval).count())
<< " ms" << std::endl;
std::cout << "Actual elapsed time "
<< std::chrono::duration_cast<millisec>(runtime).count()
<< " ms" << std::endl;
std::cout << "Smallest jitter is "
<< std::chrono::duration_cast<microsec>(jitter1.smallest()).count()
<< " us" << std::endl;
std::cout << "Largest jitter is "
<< std::chrono::duration_cast<microsec>(jitter1.largest()).count()
<< " us" << std::endl;
std::cout << "Average jitter is "
<< std::chrono::duration_cast<microsec>(jitter1.average()).count()
<< " us" << std::endl;
std::cout << "Median jitter is "
<< std::chrono::duration_cast<microsec>(jitter1.median()).count()
<< " us" << std::endl;
std::cout << std::endl;
/*** Timed Test ***/
Jitters jitter2;
const resolution iterationTimeLimit = RUNTIME_LIMIT;
std::cout << "Jitter test 2. Timed : "
<< std::chrono::duration_cast<millisec>(iterationTimeLimit).count() << " ms" << std::endl;
timer.start(std::bind(&Jitters::insert, &jitter2, std::placeholders::_1));
std::this_thread::sleep_for(iterationTimeLimit);
int iterations = timer.stop();
runtime = timer.runtime();
std::cout << "Expected iterations " << runtime / repeatInterval
<< std::endl;
std::cout << "Actual iterations " << iterations << std::endl;
std::cout << "Elapsed time "
<< std::chrono::duration_cast<millisec>(runtime).count()
<< " ms" << std::endl;
std::cout << "Smallest jitter is "
<< std::chrono::duration_cast<microsec>(jitter2.smallest()).count()
<< " us" << std::endl;
std::cout << "Largest jitter is "
<< std::chrono::duration_cast<microsec>(jitter2.largest()).count()
<< " us" << std::endl;
std::cout << "Average jitter is "
<< std::chrono::duration_cast<microsec>(jitter2.average()).count()
<< " us" << std::endl;
std::cout << "Median jitter is: "
<< std::chrono::duration_cast<microsec>(jitter2.median()).count()
<< " us" << std::endl;
}
<commit_msg>Added diagnostics to show when the actual interval exceeds the desired limit<commit_after>#include <cstdint>
#include <chrono>
#include <thread>
#include <future>
#include <functional>
#include <random>
#include <iostream>
#include <vector>
#include <algorithm>
using microsec = std::chrono::microseconds;
using millisec = std::chrono::milliseconds;
using nanosec = std::chrono::nanoseconds;
using resolution = nanosec;
using my_clock = std::chrono::steady_clock;
using duration = my_clock::duration;
#define INTERVAL_PERIOD resolution(10000000)
#define JITTER_MIN 100000
#define JITTER_MAX 1000000
#define ITERATION_MAX 400
#define RUNTIME_LIMIT resolution(4000000000)
class TimeDurations {
std::vector<duration> jitters_;
duration smallest_;
duration largest_;
public:
TimeDurations()
: jitters_(ITERATION_MAX)
, smallest_(resolution::max())
, largest_(resolution::min()) {
}
void
insert(duration j) {
jitters_.push_back(j);
if (j < smallest_) {
smallest_ = j;
}
if (j > largest_) {
largest_ = j;
}
}
duration average() {
duration result(0);
for (auto j : jitters_) {
result = result + j;
}
result /= jitters_.size();
return result;
}
duration
largest() {
return largest_;
}
duration
smallest() {
return smallest_;
}
duration
median() {
std::sort(jitters_.begin(), jitters_.end());
return jitters_[jitters_.size() / 2];
}
};
template <int IntervalMin, int IntervalMax>
class PeriodicTimer {
private:
volatile bool is_running_ = false;
std::future<int> pending_;
my_clock::time_point firstInterval_;
my_clock::time_point lastInterval_;
//! @brief call doIt until stop() is called, and return the number of
// iterations for which doIt was called.
int doItTimed(std::function<void(duration)> doIt) {
TimeDurations durations;
int result = 0;
std::random_device seedGenerator;
std::mt19937 gen(seedGenerator());
std::uniform_int_distribution<> distribution(IntervalMin,
IntervalMax);
resolution jitter = resolution(distribution(gen));
firstInterval_ = my_clock::now();
my_clock::time_point start{firstInterval_};
my_clock::time_point startNext{firstInterval_};
while (is_running_) {
// Delay the function call for a small random amount of time.
std::this_thread::sleep_for(jitter);
doIt(jitter);
++result;
// Calculate the next time we want to iterate
startNext = start + INTERVAL_PERIOD;
auto currentTime = my_clock::now();
durations.insert(currentTime - start);
std::chrono::steady_clock::time_point jitter_time = start + jitter;
std::chrono::duration<double> time_span_jitter
= std::chrono::duration_cast<std::chrono::duration<double>>(
jitter_time - start);
std::chrono::duration<double> time_span_actual
= std::chrono::duration_cast<std::chrono::duration<double>>(
currentTime - start);
std::chrono::duration<double> time_span_expected
= std::chrono::duration_cast<std::chrono::duration<double>>(
startNext - start);
/* Some days it takes just over 10 ms to run doIt(), so it helps
to see what's happening. As it is, doIt() regularly takes over 3 ms
on my old 2.4 GHz core i5 desktop, running Windows 10. That seems
excessive.
*/
if (currentTime < startNext) {
// Wait for the next period start time
std::this_thread::sleep_until(startNext);
} else {
std::cout << "Warning: Missed interval " << result
<< ". Jitter: " << jitter.count() << ". Jitter duration: "
<< time_span_jitter.count() << ". Duration: "
<< time_span_actual.count() << ". Interval Limit: "
<< time_span_expected.count() << std::endl;
}
// Get a new jitter and start time for the next iteration
jitter = resolution(distribution(gen));
start = startNext;
}
lastInterval_ = startNext;
std::cout << "Shortest interval is "
<< std::chrono::duration_cast<microsec>(durations.smallest()).count()
<< " us" << std::endl;
std::cout << "Longest interval is "
<< std::chrono::duration_cast<microsec>(durations.largest()).count()
<< " us" << std::endl;
std::cout << "Average interval is "
<< std::chrono::duration_cast<microsec>(durations.average()).count()
<< " us" << std::endl;
std::cout << "Median interval is: "
<< std::chrono::duration_cast<microsec>(durations.median()).count()
<< " us" << std::endl << std::endl;
return result;
}
public:
//! @brief call doIt for repeat_count iterations.
// A random delay (jitter) is calculated for each call to doIt. If doIt
// runs for less than the delay, doItCount will wait for the remaining time
// before the next interval. If doIt takes more time than the delay, the
// next iteration takes place immediately. This way, doIt is called no more
// often than
void doItCount(std::function<void(resolution)> doIt,
uint32_t repeat_count) {
TimeDurations durations;
std::random_device seedGenerator;
std::mt19937 gen(seedGenerator());
std::uniform_int_distribution<> distribution(IntervalMin,
IntervalMax);
resolution jitter = resolution(distribution(gen));
firstInterval_ = my_clock::now();
my_clock::time_point start{firstInterval_};
my_clock::time_point startNext{firstInterval_};
uint32_t itr = 0;
while (itr < repeat_count) {
// Delay the function call for a small random amount of time.
std::this_thread::sleep_for(jitter);
doIt(jitter);
++itr;
// Collect some stats
startNext = start + INTERVAL_PERIOD;
auto currentTime = my_clock::now();
durations.insert(currentTime - start);
std::chrono::steady_clock::time_point jitter_time = start + jitter;
std::chrono::duration<double> time_span_jitter
= std::chrono::duration_cast<std::chrono::duration<double>>(
jitter_time - start);
std::chrono::duration<double> time_span_actual
= std::chrono::duration_cast<std::chrono::duration<double>>(
currentTime - start);
std::chrono::duration<double> time_span_expected
= std::chrono::duration_cast<std::chrono::duration<double>>(
startNext - start);
if (currentTime < startNext) {
// Wait for the next period start time
std::this_thread::sleep_until(startNext);
} else {
std::cout << "Warning: Missed interval " << itr
<< ". Jitter: " << jitter.count() << ". Jitter duration: "
<< time_span_jitter.count() << ". Duration: "
<< time_span_actual.count() << ". Interval Limit: "
<< time_span_expected.count() << std::endl;
}
// Get a new jitter for the next iteration
jitter = resolution(distribution(gen));
start = startNext;
}
lastInterval_ = my_clock::now();
std::cout << "Shortest interval is "
<< std::chrono::duration_cast<microsec>(durations.smallest()).count()
<< " us" << std::endl;
std::cout << "Longest interval is "
<< std::chrono::duration_cast<microsec>(durations.largest()).count()
<< " us" << std::endl;
std::cout << "Average interval is "
<< std::chrono::duration_cast<microsec>(durations.average()).count()
<< " us" << std::endl;
std::cout << "Median interval is: "
<< std::chrono::duration_cast<microsec>(durations.median()).count()
<< " us" << std::endl << std::endl;
}
void start(std::function<void(resolution)> doIt) {
is_running_ = true;
// Run doItTimed on another thread, passing the "this" pointer and the
// function doItTimed must run until stop() is executed.
auto f = std::async(std::launch::async,
&PeriodicTimer::doItTimed,
this,
doIt);
// Move the future to another variable so we don't wait for it here.
pending_ = std::move(f);
}
int stop() {
// Allow doItTimed to exit its while-loop
is_running_ = false;
// Return the number of iterations
return pending_.get();
}
my_clock::duration runtime() const {
return lastInterval_ - firstInterval_;
}
};
void main() {
TimeDurations jitter1;
const resolution jitterMin = resolution(JITTER_MIN);
const resolution jitterMax = resolution(JITTER_MAX);
const resolution repeatInterval = INTERVAL_PERIOD;
PeriodicTimer<JITTER_MIN, JITTER_MAX> timer;
std::cout << "The resolution of the high-resolution clock is: "
<< (static_cast<double>(std::chrono::high_resolution_clock::period::num)
/ std::chrono::high_resolution_clock::period::den) << " sec"
<< std::endl;
std::cout << "The resolution of the steady clock is: "
<< (static_cast<double>(std::chrono::steady_clock::period::num)
/ std::chrono::steady_clock::period::den)
<< " sec" << std::endl;
std::cout << "The resolution of the system clock is: "
<< (static_cast<double>(std::chrono::system_clock::period::num)
/ std::chrono::system_clock::period::den)
<< " sec" << std::endl << std::endl;
std::cout << "Jitter Tests." << std::endl
<< " Interval: "
<< std::chrono::duration_cast<millisec>(repeatInterval).count()
<< " ms" << std::endl
<< " Min Jitter: "
<< std::chrono::duration_cast<microsec>(jitterMin).count() << " us"
<< std::endl
<< " Max Jitter: "
<< std::chrono::duration_cast<microsec>(jitterMax).count() << " us"
<< std::endl << std::endl;
/*** Iteration Test ***/
std::cout << "Jitter test 1. Iterations: " << ITERATION_MAX << std::endl;
timer.doItCount(std::bind(&TimeDurations::insert, &jitter1, std::placeholders::_1), ITERATION_MAX);
auto runtime = timer.runtime();
std::cout << "Iterations " << ITERATION_MAX << std::endl;
std::cout << "Expected elapsed time "
<< (ITERATION_MAX * std::chrono::duration_cast<millisec>(repeatInterval).count())
<< " ms" << std::endl;
std::cout << "Actual elapsed time "
<< std::chrono::duration_cast<millisec>(runtime).count()
<< " ms" << std::endl;
std::cout << "Smallest jitter is "
<< std::chrono::duration_cast<microsec>(jitter1.smallest()).count()
<< " us" << std::endl;
std::cout << "Largest jitter is "
<< std::chrono::duration_cast<microsec>(jitter1.largest()).count()
<< " us" << std::endl;
std::cout << "Average jitter is "
<< std::chrono::duration_cast<microsec>(jitter1.average()).count()
<< " us" << std::endl;
std::cout << "Median jitter is "
<< std::chrono::duration_cast<microsec>(jitter1.median()).count()
<< " us" << std::endl;
std::cout << std::endl;
/*** Timed Test ***/
TimeDurations jitter2;
const resolution iterationTimeLimit = RUNTIME_LIMIT;
std::cout << "Jitter test 2. Timed : "
<< std::chrono::duration_cast<millisec>(iterationTimeLimit).count() << " ms" << std::endl;
timer.start(std::bind(&TimeDurations::insert, &jitter2, std::placeholders::_1));
std::this_thread::sleep_for(iterationTimeLimit);
int iterations = timer.stop();
runtime = timer.runtime();
std::cout << "Expected iterations " << runtime / repeatInterval
<< std::endl;
std::cout << "Actual iterations " << iterations << std::endl;
std::cout << "Elapsed time "
<< std::chrono::duration_cast<millisec>(runtime).count()
<< " ms" << std::endl;
std::cout << "Smallest jitter is "
<< std::chrono::duration_cast<microsec>(jitter2.smallest()).count()
<< " us" << std::endl;
std::cout << "Largest jitter is "
<< std::chrono::duration_cast<microsec>(jitter2.largest()).count()
<< " us" << std::endl;
std::cout << "Average jitter is "
<< std::chrono::duration_cast<microsec>(jitter2.average()).count()
<< " us" << std::endl;
std::cout << "Median jitter is: "
<< std::chrono::duration_cast<microsec>(jitter2.median()).count()
<< " us" << std::endl;
}
<|endoftext|> |
<commit_before>#include <string.h>
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
using namespace std;
int check_connect(const string& str, int& pos, int start){
unsigned found = 0;
found = str.find_first_of(";&|#",start);
cout << "FLAG: entering check function" << endl;
if (found >= str.size()){
pos = -1;
return -1;
}
else{
cout << "FLAG: checking connectors" << endl;
if (str.at(found) == ';'){
pos = found;
return 1;
}
else if (str.at(found) == '&'){
//FIX check for next &
cout << "FLAG: found &" << endl;
if (str.at(found+1) == '&'){
pos = found;
return 2;
}
else{
cout << "flag: about to recursively call" << endl;
return check_connect(str,pos,found+1);
}
}
else if (str.at(found) == '|'){
//FIX check for next |
if (str.at(found+1) == '|'){
pos = found;
return 3;
}
else{
cout << "flag: about to recursively call 2" << endl;
return check_connect(str,pos,found+1);
}
}
else if (str.at(found) == '#'){
pos = found;
return 4;
}
}
return -1;
}
int main()
{
int start = 0;
int c_stat;
int pos = -1;
vector<string> str;
str.push_back("The first string, no connectors");
str.push_back("Second string; Semicolon included");
str.push_back("&Third: && got that ampersand");
str.push_back("We has | in i||t");
str.push_back("This has a #comment");
cout << "entering for loop" << endl;
for (int i = 0; i < 5; ++i){
c_stat = check_connect(str.at(i), pos, start);
cout << "string " << i << ": " << c_stat << " at: " << pos << endl;
}
return 0;
}
<commit_msg>clean up connector function before merge<commit_after>#include <string.h>
#include <iostream>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
using namespace std;
int check_connect(const string& str, int& pos, int start){
unsigned found = 0;
found = str.find_first_of(";&|#",start);
if (found >= str.size()){
pos = -1;
return -1;
}
else{
if (str.at(found) == ';'){
pos = found;
return 1;
}
else if (str.at(found) == '&'){
if (str.at(found+1) == '&'){
pos = found;
return 2;
}
else{
return check_connect(str,pos,found+1);
}
}
else if (str.at(found) == '|'){
if (str.at(found+1) == '|'){
pos = found;
return 3;
}
else{
return check_connect(str,pos,found+1);
}
}
else if (str.at(found) == '#'){
pos = found;
return 4;
}
}
return -1;
}
int main()
{
int start = 0;
int c_stat;
int pos = -1;
vector<string> str;
str.push_back("The first string, no connectors");
str.push_back("Second string; Semicolon included");
str.push_back("&Third: && got that ampersand");
str.push_back("We has | in i||t");
str.push_back("This has a #comment");
cout << "entering for loop" << endl;
for (int i = 0; i < 5; ++i){
c_stat = check_connect(str.at(i), pos, start);
cout << "string " << i << ": " << c_stat << " at: " << pos << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#include <Bounce2.h>
#include "FastLED.h"
#include <EEPROM.h>
// Digital PINs
#define LED_PIN_CH1 4
#define LED_PIN_CH2 2
#define MODE_BUTTON_PIN 6
#define BRIGHTNESS_BUTTON_PIN 8
#define BEAT_BUTTON_PIN 10
// Analog PINs
#define ACCELX_PIN 0
#define ACCELY_PIN 2
#define ACCELZ_PIN 4
// Other constants
#define BAUD_RATE 9600
#define NUM_LEDS_CH1 120
#define NUM_LEDS_CH2 29
#define FRAMES_PER_SECOND 30
// ui
int mode = 1;
int modeCount = 4;
Bounce modeButton;
Bounce brightnessButton;
Bounce beatButton;
// config
int currentBrightnessIndex = 1; // start with medium brightness
byte brightnesses[] = {30,60,90};
int staticBpm = 60; // in case no pulse is found
int pulseBpm = 0; // actually detected value
int maxBpm = 180; // avoids the system going crazy
byte beat[] = {2,2,2,2,3,4,3,2,1,0,10,2,2,3,4,6,8,5,3,3,3,3}; // From http://ecg.utah.edu/img/items/Normal%2012_Lead%20ECG.jpg
byte beatLength = 22;
int beatMaxIntensity = 10; // max value in beat array
int movesPerBeat = 4;
int minMagnitude = 0;
int maxMagnitude = 50; // max difference between two magnitude measurements from accelerometer at which we show maxHue
int minBrightnessDivisor= 150; // lower = brighter
int maxBrightnessDivisor = 300; // higher = dimmer
int minHue = 160; // hue value under low motion, as defined through minMagnitude (from 0-255)
int maxHue = 255; // hue value under high motion, as defined through maxMagnitude (from 0-255)
int gainRatePerBeat = 6; // change towards new target magnitude
int decayRatePerBeat = 2; // move back towards minMagnitude
int sampleSize = 8; // smooth out accelerometer readings
int samplePerBeat = 1;
// state
int bpm = staticBpm;
byte bufr[NUM_LEDS_CH1];
byte offset = 0;
int currentMagnitude;
int targetMagnitude = maxMagnitude;
int adjustedMagnitude = maxMagnitude;
// pulse state
volatile boolean pulseFound = false; // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean pulseBeatFound = false; // becomes true when Arduoino finds a beat.
volatile boolean hasPulse = false; //
CRGB leds[2][NUM_LEDS_CH1];
void setup() {
FastLED.addLeds<NEOPIXEL, LED_PIN_CH1>(leds[0], NUM_LEDS_CH1);
FastLED.addLeds<NEOPIXEL, LED_PIN_CH2>(leds[1], NUM_LEDS_CH2);
Serial.begin(BAUD_RATE);
pinMode(MODE_BUTTON_PIN, INPUT_PULLUP);
modeButton.attach(MODE_BUTTON_PIN);
modeButton.interval(50);
pinMode(BRIGHTNESS_BUTTON_PIN, INPUT_PULLUP);
brightnessButton.attach(BRIGHTNESS_BUTTON_PIN);
brightnessButton.interval(50);
pinMode(BEAT_BUTTON_PIN, INPUT_PULLUP);
beatButton.attach(BEAT_BUTTON_PIN);
beatButton.interval(50);
updateModeFromEEPROM();
}
// other pattern config
uint8_t gHue = 0; // rotating "base color" used by many of the patterns
// Cycle mode in persistent memory on every on switch.
// More resilient against hardware failures than a button.
void updateModeFromEEPROM() {
mode = EEPROM.read(0);
if(!mode) {
mode = 1;
}
mode = (mode % modeCount) + 1;
EEPROM.write(0, mode);
}
void updateModeFromButton() {
modeButton.update();
int current = modeButton.read();
if(modeButton.fell()) {
mode = (mode % modeCount) + 1;
Serial.print("mode: ");
Serial.println(mode);
}
}
void updateBrightnessFromButton() {
brightnessButton.update();
int current = brightnessButton.read();
if(brightnessButton.fell()) {
currentBrightnessIndex = ((currentBrightnessIndex + 1) % 3);
Serial.print("currentBrightnessIndex: ");
Serial.println(currentBrightnessIndex);
}
}
void moveBuffer() {
int i;
byte c = (int) beat[offset] * 255 / beatMaxIntensity;
int midPoint = NUM_LEDS_CH1/2;
// Move current beat intensity from middle to beginning of strip (backward in buffer)
bufr[midPoint - 1] = c;
for (i=0;i<midPoint - 1;i++){
bufr[i] = bufr[i+1];
}
// Move current beat intensity from middle to end of strip (forward in buffer)
bufr[midPoint] = c;
for (i=NUM_LEDS_CH1 - 1;i>midPoint;i--){
bufr[i] = bufr[i-1];
}
}
void draw() {
int i;
// Go from a cool color on low to a warm color on high activity
int hue = map(
adjustedMagnitude,
minMagnitude,
maxMagnitude,
minHue,
maxHue
);
// Lower magnitude means more brightness reduction
int brightnessFactor = map(
adjustedMagnitude,
minMagnitude,
maxMagnitude,
maxBrightnessDivisor,
minBrightnessDivisor
);
// Channel 1
for (i=0;i<NUM_LEDS_CH1;i++){
leds[0][i] = CHSV(hue, bufr[i], bufr[i]/(brightnessFactor/100));
}
// Channel 2
int halfPoint = (int)sizeof(bufr)/2;
for (i=0;i<NUM_LEDS_CH2;i++){
leds[1][i] = CHSV(hue, bufr[halfPoint], bufr[halfPoint]/(brightnessFactor/100));
}
FastLED.show();
}
int calcAdjustedMagnitude() {
int newMagnitude = getMagnitude();
int magnitudeDiff = abs(currentMagnitude - newMagnitude);
// Get new target (smoothed out over a couple of readings)
targetMagnitude = max(
constrain(magnitudeDiff, minMagnitude, maxMagnitude),
targetMagnitude
);
// Slowly work towards new target (either increasing or decreasing)
if(adjustedMagnitude <= targetMagnitude) {
adjustedMagnitude = constrain(
constrain(
targetMagnitude + gainRatePerBeat,
minMagnitude,
maxMagnitude
),
minMagnitude,
maxMagnitude
);
} else {
adjustedMagnitude = constrain(
constrain(
targetMagnitude - gainRatePerBeat,
minMagnitude,
maxMagnitude
),
minMagnitude,
maxMagnitude
);
}
// Slowly decay max target
targetMagnitude = targetMagnitude - decayRatePerBeat;
targetMagnitude = constrain(
targetMagnitude,
minMagnitude,
maxMagnitude
);
// Serial.print(magnitudeDiff);
// Serial.print("\t");
// Serial.print(targetMagnitude);
// Serial.print("\t");
// Serial.print(adjustedMagnitude);
// Serial.println();
currentMagnitude = newMagnitude;
}
// Get a magnitude across all vectors.
// Smooth out result through a rolling average
int getMagnitude() {
float avgMag = 0;
for(int x = 0 ; x < sampleSize ; x++) {
float aX = analogRead(ACCELX_PIN);
float aY = analogRead(ACCELY_PIN);
float aZ = analogRead(ACCELZ_PIN);
float magnitude = sqrt((aX * aX) + (aY * aY) + (aZ * aZ));
avgMag += magnitude;
}
avgMag /= sampleSize;
return avgMag;
}
void loopHeartRate() {
offset = (offset + 1) % beatLength;
if (pulseFound == true && pulseBpm <= maxBpm) {
bpm = pulseBpm;
} else {
bpm = staticBpm;
}
// TODO Fix BPM noise
bpm = staticBpm;
if (pulseBeatFound == true){
pulseBeatFound = false;
}
int i;
for (i=0;i<movesPerBeat;i++){
// Delay in milliseconds. BPM are measured by minute, so divide accordingly.
delay((float) 1 / (bpm * 60 * 1000) / beatLength / movesPerBeat);
moveBuffer();
draw();
}
// Measure only a few times per beat to avoid slowdowns
if(offset % round(beatLength/samplePerBeat) == 0) {
calcAdjustedMagnitude();
}
}
void rainbow(int ledIndex, int num)
{
// FastLED's built-in rainbow generator
fill_rainbow( leds[ledIndex], num, gHue, 7);
}
void rainbowWithGlitter(int ledIndex, int num)
{
// built-in FastLED rainbow, plus some random sparkly glitter
rainbow(ledIndex, num);
addGlitter(80, ledIndex, num);
}
void addGlitter( fract8 chanceOfGlitter, int ledIndex, int num)
{
if( random8() < chanceOfGlitter) {
leds[ledIndex][ random16(num) ] += CRGB::White;
}
}
void confetti(int ledIndex, int num)
{
// random colored speckles that blink in and fade smoothly
fadeToBlackBy( leds[ledIndex], num, 10);
int pos = random16(num);
leds[ledIndex][pos] += CHSV( gHue + random8(64), 200, 255);
}
void sinelon(int ledIndex, int num)
{
// a colored dot sweeping back and forth, with fading trails
fadeToBlackBy( leds[ledIndex], num, 20);
int pos = beatsin16(13,0,num);
leds[ledIndex][pos] += CHSV( gHue, 255, 192);
}
void juggle(int ledIndex, int num) {
// eight colored dots, weaving in and out of sync with each other
fadeToBlackBy( leds[ledIndex], num, 20);
byte dothue = 0;
for( int i = 0; i < 8; i++) {
leds[ledIndex][beatsin16(i+7,0,num)] |= CHSV(dothue, 200, 255);
dothue += 32;
}
}
void loop() {
updateModeFromButton();
updateBrightnessFromButton();
int brightness = brightnesses[currentBrightnessIndex];
// Activate effect based on mode
if(mode == 1) {
// Bright pulse meter
minBrightnessDivisor = 200;
maxBrightnessDivisor = 400;
loopHeartRate();
} else if (mode == 2) {
FastLED.setBrightness(brightness);
confetti(0, NUM_LEDS_CH1);
confetti(1, NUM_LEDS_CH2);
FastLED.show();
FastLED.delay(1000/FRAMES_PER_SECOND);
EVERY_N_MILLISECONDS( 20 ) { gHue++; }
} else if (mode == 3) {
FastLED.setBrightness(brightness);
sinelon(0, NUM_LEDS_CH1);
sinelon(1, NUM_LEDS_CH2);
FastLED.show();
FastLED.delay(1000/FRAMES_PER_SECOND);
EVERY_N_MILLISECONDS( 20 ) { gHue++; }
} else if (mode == 4) {
FastLED.setBrightness(brightness);
juggle(0, NUM_LEDS_CH1);
juggle(1, NUM_LEDS_CH2);
FastLED.show();
FastLED.delay(1000/FRAMES_PER_SECOND);
EVERY_N_MILLISECONDS( 20 ) { gHue++; }
}
}
<commit_msg>Moved function declarations around to shut up linter<commit_after>#include <Bounce2.h>
#include "FastLED.h"
#include <EEPROM.h>
// Digital PINs
#define LED_PIN_CH1 4
#define LED_PIN_CH2 2
#define MODE_BUTTON_PIN 6
#define BRIGHTNESS_BUTTON_PIN 8
#define BEAT_BUTTON_PIN 10
// Analog PINs
#define ACCELX_PIN 0
#define ACCELY_PIN 2
#define ACCELZ_PIN 4
// Other constants
#define BAUD_RATE 9600
#define NUM_LEDS_CH1 120
#define NUM_LEDS_CH2 29
#define FRAMES_PER_SECOND 30
// ui
int mode = 1;
int modeCount = 4;
Bounce modeButton;
Bounce brightnessButton;
Bounce beatButton;
// config
int currentBrightnessIndex = 1; // start with medium brightness
byte brightnesses[] = {30,60,90};
int staticBpm = 60; // in case no pulse is found
int pulseBpm = 0; // actually detected value
int maxBpm = 180; // avoids the system going crazy
byte beat[] = {2,2,2,2,3,4,3,2,1,0,10,2,2,3,4,6,8,5,3,3,3,3}; // From http://ecg.utah.edu/img/items/Normal%2012_Lead%20ECG.jpg
byte beatLength = 22;
int beatMaxIntensity = 10; // max value in beat array
int movesPerBeat = 4;
int minMagnitude = 0;
int maxMagnitude = 50; // max difference between two magnitude measurements from accelerometer at which we show maxHue
int minBrightnessDivisor= 150; // lower = brighter
int maxBrightnessDivisor = 300; // higher = dimmer
int minHue = 160; // hue value under low motion, as defined through minMagnitude (from 0-255)
int maxHue = 255; // hue value under high motion, as defined through maxMagnitude (from 0-255)
int gainRatePerBeat = 6; // change towards new target magnitude
int decayRatePerBeat = 2; // move back towards minMagnitude
int sampleSize = 8; // smooth out accelerometer readings
int samplePerBeat = 1;
// state
int bpm = staticBpm;
byte bufr[NUM_LEDS_CH1];
byte offset = 0;
int currentMagnitude;
int targetMagnitude = maxMagnitude;
int adjustedMagnitude = maxMagnitude;
// pulse state
volatile boolean pulseFound = false; // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean pulseBeatFound = false; // becomes true when Arduoino finds a beat.
volatile boolean hasPulse = false; //
CRGB leds[2][NUM_LEDS_CH1];
// other pattern config
uint8_t gHue = 0; // rotating "base color" used by many of the patterns
// Cycle mode in persistent memory on every on switch.
// More resilient against hardware failures than a button.
void updateModeFromEEPROM() {
mode = EEPROM.read(0);
if(!mode) {
mode = 1;
}
mode = (mode % modeCount) + 1;
EEPROM.write(0, mode);
}
void updateModeFromButton() {
modeButton.update();
if(modeButton.fell()) {
mode = (mode % modeCount) + 1;
Serial.print("mode: ");
Serial.println(mode);
}
}
void updateBrightnessFromButton() {
brightnessButton.update();
if(brightnessButton.fell()) {
currentBrightnessIndex = ((currentBrightnessIndex + 1) % 3);
Serial.print("currentBrightnessIndex: ");
Serial.println(currentBrightnessIndex);
}
}
void moveBuffer() {
int i;
byte c = (int) beat[offset] * 255 / beatMaxIntensity;
int midPoint = NUM_LEDS_CH1/2;
// Move current beat intensity from middle to beginning of strip (backward in buffer)
bufr[midPoint - 1] = c;
for (i=0;i<midPoint - 1;i++){
bufr[i] = bufr[i+1];
}
// Move current beat intensity from middle to end of strip (forward in buffer)
bufr[midPoint] = c;
for (i=NUM_LEDS_CH1 - 1;i>midPoint;i--){
bufr[i] = bufr[i-1];
}
}
void draw() {
int i;
// Go from a cool color on low to a warm color on high activity
int hue = map(
adjustedMagnitude,
minMagnitude,
maxMagnitude,
minHue,
maxHue
);
// Lower magnitude means more brightness reduction
int brightnessFactor = map(
adjustedMagnitude,
minMagnitude,
maxMagnitude,
maxBrightnessDivisor,
minBrightnessDivisor
);
// Channel 1
for (i=0;i<NUM_LEDS_CH1;i++){
leds[0][i] = CHSV(hue, bufr[i], bufr[i]/(brightnessFactor/100));
}
// Channel 2
int halfPoint = (int)sizeof(bufr)/2;
for (i=0;i<NUM_LEDS_CH2;i++){
leds[1][i] = CHSV(hue, bufr[halfPoint], bufr[halfPoint]/(brightnessFactor/100));
}
FastLED.show();
}
// Get a magnitude across all vectors.
// Smooth out result through a rolling average
int getMagnitude() {
float avgMag = 0;
for(int x = 0 ; x < sampleSize ; x++) {
float aX = analogRead(ACCELX_PIN);
float aY = analogRead(ACCELY_PIN);
float aZ = analogRead(ACCELZ_PIN);
float magnitude = sqrt((aX * aX) + (aY * aY) + (aZ * aZ));
avgMag += magnitude;
}
avgMag /= sampleSize;
return avgMag;
}
void calcAdjustedMagnitude() {
int newMagnitude = getMagnitude();
int magnitudeDiff = abs(currentMagnitude - newMagnitude);
// Get new target (smoothed out over a couple of readings)
targetMagnitude = max(
constrain(magnitudeDiff, minMagnitude, maxMagnitude),
targetMagnitude
);
// Slowly work towards new target (either increasing or decreasing)
if(adjustedMagnitude <= targetMagnitude) {
adjustedMagnitude = constrain(
constrain(
targetMagnitude + gainRatePerBeat,
minMagnitude,
maxMagnitude
),
minMagnitude,
maxMagnitude
);
} else {
adjustedMagnitude = constrain(
constrain(
targetMagnitude - gainRatePerBeat,
minMagnitude,
maxMagnitude
),
minMagnitude,
maxMagnitude
);
}
// Slowly decay max target
targetMagnitude = targetMagnitude - decayRatePerBeat;
targetMagnitude = constrain(
targetMagnitude,
minMagnitude,
maxMagnitude
);
// Serial.print(magnitudeDiff);
// Serial.print("\t");
// Serial.print(targetMagnitude);
// Serial.print("\t");
// Serial.print(adjustedMagnitude);
// Serial.println();
currentMagnitude = newMagnitude;
}
void loopHeartRate() {
offset = (offset + 1) % beatLength;
if (pulseFound == true && pulseBpm <= maxBpm) {
bpm = pulseBpm;
} else {
bpm = staticBpm;
}
// TODO Fix BPM noise
bpm = staticBpm;
if (pulseBeatFound == true){
pulseBeatFound = false;
}
int i;
for (i=0;i<movesPerBeat;i++){
// Delay in milliseconds. BPM are measured by minute, so divide accordingly.
delay((float) 1 / (bpm * 60 * 1000) / beatLength / movesPerBeat);
moveBuffer();
draw();
}
// Measure only a few times per beat to avoid slowdowns
if(offset % round(beatLength/samplePerBeat) == 0) {
calcAdjustedMagnitude();
}
}
void rainbow(int ledIndex, int num)
{
// FastLED's built-in rainbow generator
fill_rainbow( leds[ledIndex], num, gHue, 7);
}
void addGlitter( fract8 chanceOfGlitter, int ledIndex, int num)
{
if( random8() < chanceOfGlitter) {
leds[ledIndex][ random16(num) ] += CRGB::White;
}
}
void rainbowWithGlitter(int ledIndex, int num)
{
// built-in FastLED rainbow, plus some random sparkly glitter
rainbow(ledIndex, num);
addGlitter(80, ledIndex, num);
}
void confetti(int ledIndex, int num)
{
// random colored speckles that blink in and fade smoothly
fadeToBlackBy( leds[ledIndex], num, 10);
int pos = random16(num);
leds[ledIndex][pos] += CHSV( gHue + random8(64), 200, 255);
}
void sinelon(int ledIndex, int num)
{
// a colored dot sweeping back and forth, with fading trails
fadeToBlackBy( leds[ledIndex], num, 20);
int pos = beatsin16(13,0,num);
leds[ledIndex][pos] += CHSV( gHue, 255, 192);
}
void juggle(int ledIndex, int num) {
// eight colored dots, weaving in and out of sync with each other
fadeToBlackBy( leds[ledIndex], num, 20);
byte dothue = 0;
for( int i = 0; i < 8; i++) {
leds[ledIndex][beatsin16(i+7,0,num)] |= CHSV(dothue, 200, 255);
dothue += 32;
}
}
void setup() {
FastLED.addLeds<NEOPIXEL, LED_PIN_CH1>(leds[0], NUM_LEDS_CH1);
FastLED.addLeds<NEOPIXEL, LED_PIN_CH2>(leds[1], NUM_LEDS_CH2);
Serial.begin(BAUD_RATE);
pinMode(MODE_BUTTON_PIN, INPUT_PULLUP);
modeButton.attach(MODE_BUTTON_PIN);
modeButton.interval(50);
pinMode(BRIGHTNESS_BUTTON_PIN, INPUT_PULLUP);
brightnessButton.attach(BRIGHTNESS_BUTTON_PIN);
brightnessButton.interval(50);
pinMode(BEAT_BUTTON_PIN, INPUT_PULLUP);
beatButton.attach(BEAT_BUTTON_PIN);
beatButton.interval(50);
updateModeFromEEPROM();
}
void loop() {
updateModeFromButton();
updateBrightnessFromButton();
int brightness = brightnesses[currentBrightnessIndex];
// Activate effect based on mode
if(mode == 1) {
// Bright pulse meter
minBrightnessDivisor = 200;
maxBrightnessDivisor = 400;
loopHeartRate();
} else if (mode == 2) {
FastLED.setBrightness(brightness);
confetti(0, NUM_LEDS_CH1);
confetti(1, NUM_LEDS_CH2);
FastLED.show();
FastLED.delay(1000/FRAMES_PER_SECOND);
EVERY_N_MILLISECONDS( 20 ) { gHue++; }
} else if (mode == 3) {
FastLED.setBrightness(brightness);
sinelon(0, NUM_LEDS_CH1);
sinelon(1, NUM_LEDS_CH2);
FastLED.show();
FastLED.delay(1000/FRAMES_PER_SECOND);
EVERY_N_MILLISECONDS( 20 ) { gHue++; }
} else if (mode == 4) {
FastLED.setBrightness(brightness);
juggle(0, NUM_LEDS_CH1);
juggle(1, NUM_LEDS_CH2);
FastLED.show();
FastLED.delay(1000/FRAMES_PER_SECOND);
EVERY_N_MILLISECONDS( 20 ) { gHue++; }
}
}
<|endoftext|> |
<commit_before>#define DISTANCECMCRITICAL 20
#define DISTANCECMWARNING 30
#define PUBLSIHINTERVAL 1000
#define TRYFOLLOWLINEINTERVAL 3000
#define WAITINTERVAL 5000
#define MOVESPEED 100
#include <Arduino.h>
#include <Streaming.h>
#include <ArduinoJson.h>
#include <MeMCore.h>
enum direction { FORWARD, BACKWARD, LEFT, RIGHT, STOP } moveDirection = STOP;
MeDCMotor motorL(M1);
MeDCMotor motorR(M2);
MeLineFollower lineFollower(PORT_2);
MeTemperature temperature(PORT_1, SLOT2);
MeUltrasonicSensor ultrasonicSensor(PORT_3);
MeLightSensor lightSensor(PORT_6);
MeIR ir;
MeRGBLed rgbLed(PORT_7, 2);
MeBuzzer buzzer;
double distanceCm = 0.0;
int moveSpeed = 100;
int lineFollowFlag = 0;
byte readSensors = 0;
bool start = false;
bool moveBot = false;
bool makeNoise = false;
bool obstacle = false;
unsigned long publishTimer = millis();
bool wait = false;
unsigned long waitTimer = millis();
bool tryFollowLine = true;
unsigned long tryFollowLineTimer = millis();
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
void forward() {
moveBot = true;
motorL.run(-MOVESPEED);
motorR.run(MOVESPEED);
}
void backward() {
moveBot = true;
motorL.run(MOVESPEED);
motorR.run(-MOVESPEED);
}
void turnLeft() {
moveBot = true;
motorL.run(-MOVESPEED / 10);
motorR.run(MOVESPEED);
}
void turnRight() {
moveBot = true;
motorL.run(-MOVESPEED);
motorR.run(MOVESPEED / 10);
}
void stop() {
moveBot = false;
motorL.run(0);
motorR.run(0);
}
bool distanceCheck(double distanceCmLimit) {
if (distanceCm < distanceCmLimit) {
return false;
} else {
return true;
}
}
void move() {
if (distanceCheck(DISTANCECMCRITICAL)) {
switch (moveDirection) {
case FORWARD:
forward();
break;
case BACKWARD:
backward();
break;
case LEFT:
turnLeft();
break;
case RIGHT:
turnRight();
break;
case STOP:
stop();
break;
}
} else {
switch (moveDirection) {
case BACKWARD:
backward();
break;
default:
moveDirection = STOP;
stop();
break;
}
}
}
void toggleStart() {
start = !start;
if (start) {
rgbLed.setColor(1, 0, 10, 0);
rgbLed.show();
} else {
rgbLed.setColor(1, 0, 0, 0);
rgbLed.show();
moveDirection = STOP;
}
delay(250);
}
void bottomCheck() {
if (analogRead(A7) == 0) {
toggleStart();
}
}
void irCheck() {
unsigned long value;
if (ir.decode()) {
value = ir.value;
switch (value >> 16 & 0xff) {
case IR_BUTTON_LEFT:
moveDirection = LEFT;
break;
case IR_BUTTON_RIGHT:
moveDirection = RIGHT;
break;
case IR_BUTTON_DOWN:
moveDirection = BACKWARD;
break;
case IR_BUTTON_UP:
moveDirection = FORWARD;
break;
case IR_BUTTON_SETTING:
moveDirection = STOP;
break;
case IR_BUTTON_A:
toggleStart();
break;
}
}
}
void noiseCheck() {
if (!moveBot and start) {
if (wait == false) {
wait = true;
waitTimer = millis();
}
if (wait and millis() - waitTimer > WAITINTERVAL) {
makeNoise = true;
//buzzer.tone(262, 100);
rgbLed.setColor(2, 10, 0, 0);
rgbLed.show();
} else {
rgbLed.setColor(2, 0, 0, 10);
rgbLed.show();
}
} else {
wait = false;
makeNoise = false;
buzzer.noTone();
rgbLed.setColor(2, 0, 0, 0);
rgbLed.show();
}
}
void autonomous() {
byte randNumber;
randomSeed(analogRead(6));
randNumber = random(2);
if (distanceCheck(DISTANCECMCRITICAL) and !obstacle) {
moveDirection = FORWARD;
} else {
obstacle = true;
}
if (obstacle) {
if (!distanceCheck(DISTANCECMWARNING)) {
moveDirection = BACKWARD;
} else {
switch (randNumber) {
case 0:
moveDirection = LEFT;
turnLeft();
delay(200);
break;
case 1:
moveDirection = RIGHT;
turnRight();
delay(200);
break;
}
obstacle = false;
}
}
}
void readData() {
readSensors = lineFollower.readSensors();
distanceCm = ultrasonicSensor.distanceCm();
}
void sendData() {
if (millis() - publishTimer > PUBLSIHINTERVAL) {
publishTimer = millis();
root["moveBot"] = moveBot;
root["makeNoise"] = makeNoise;
root["distanceCm"] = distanceCm;
root["temperature"] = temperature.temperature();
root["lightSensor"] = lightSensor.read();
Serial << endl;
root.prettyPrintTo(Serial);
}
}
void setup() {
Serial.begin(115200);
Serial << endl << endl;
pinMode(A7, INPUT);
ir.begin();
rgbLed.setColor(0, 0, 0, 0);
rgbLed.show();
}
void loop() {
bottomCheck();
irCheck();
readData();
sendData();
noiseCheck();
move();
if (start) {
switch (readSensors) {
case S1_IN_S2_IN:
tryFollowLine = true;
moveDirection = FORWARD;
lineFollowFlag = 10;
break;
case S1_IN_S2_OUT:
tryFollowLine = true;
moveDirection = FORWARD;
if (lineFollowFlag > 1) lineFollowFlag--;
break;
case S1_OUT_S2_IN:
tryFollowLine = true;
moveDirection = FORWARD;
if (lineFollowFlag < 20) lineFollowFlag++;
break;
case S1_OUT_S2_OUT:
if (tryFollowLine) {
tryFollowLine = !tryFollowLine;
tryFollowLineTimer = millis();
}
if (millis() - tryFollowLineTimer < TRYFOLLOWLINEINTERVAL) {
if (lineFollowFlag == 10) moveDirection = BACKWARD;
if (lineFollowFlag < 10) moveDirection = LEFT;
if (lineFollowFlag > 10) moveDirection = RIGHT;
} else {
autonomous();
}
break;
}
}
}
<commit_msg>cleanup, bugfix, readability<commit_after>#define DISTANCECMCRITICAL 20
#define DISTANCECMWARNING 30
#define PUBLSIHINTERVAL 1000
#define TRYFOLLOWLINEINTERVAL 3000
#define WAITINTERVAL 5000
#define MOVESPEED 100
#include <Arduino.h>
#include <Streaming.h>
#include <ArduinoJson.h>
#include <MeMCore.h>
enum direction { STOP, FORWARD, BACKWARD, LEFT, RIGHT } moveDirection = STOP;
MeDCMotor motorL(M1);
MeDCMotor motorR(M2);
MeLineFollower lineFollower(PORT_2);
MeTemperature temperature(PORT_4, SLOT2);
MeUltrasonicSensor ultrasonicSensor(PORT_3);
MeLightSensor lightSensor(PORT_6);
MeIR ir;
MeRGBLed rgbLed(PORT_7, 2);
MeBuzzer buzzer;
int moveSpeed = 100;
int lineFollowFlag = 0;
bool start = false;
bool makeNoise = false;
bool obstacle = false;
unsigned long publishTimer = millis();
bool wait = false;
unsigned long waitTimer = millis();
bool tryFollowLine = true;
unsigned long tryFollowLineTimer = millis();
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.createObject();
void forward() {
motorL.run(-MOVESPEED);
motorR.run(MOVESPEED);
}
void backward() {
motorL.run(MOVESPEED);
motorR.run(-MOVESPEED);
}
void turnLeft() {
motorL.run(-MOVESPEED / 10);
motorR.run(MOVESPEED);
}
void turnRight() {
motorL.run(-MOVESPEED);
motorR.run(MOVESPEED / 10);
}
void stop() {
moveDirection = STOP;
motorL.run(0);
motorR.run(0);
}
bool distanceWarning(double distanceCmLimit) {
if (ultrasonicSensor.distanceCm() < distanceCmLimit) {
return true;
} else {
return false;
}
}
void move() {
if (distanceWarning(DISTANCECMCRITICAL)) {
if (moveDirection == BACKWARD) {
backward();
} else {
stop();
}
} else {
switch (moveDirection) {
case FORWARD:
forward();
break;
case BACKWARD:
backward();
break;
case LEFT:
turnLeft();
break;
case RIGHT:
turnRight();
break;
case STOP:
stop();
break;
}
}
}
void toggleStart() {
start = !start;
if (start) {
rgbLed.setColor(1, 0, 10, 0);
rgbLed.show();
} else {
rgbLed.setColor(1, 0, 0, 0);
rgbLed.show();
moveDirection = STOP;
}
delay(250);
}
void bottomCheck() {
if (analogRead(A7) == 0) {
toggleStart();
}
}
void irCheck() {
unsigned long value;
if (ir.decode()) {
value = ir.value;
switch (value >> 16 & 0xff) {
case IR_BUTTON_LEFT:
moveDirection = LEFT;
break;
case IR_BUTTON_RIGHT:
moveDirection = RIGHT;
break;
case IR_BUTTON_DOWN:
moveDirection = BACKWARD;
break;
case IR_BUTTON_UP:
moveDirection = FORWARD;
break;
case IR_BUTTON_SETTING:
moveDirection = STOP;
break;
case IR_BUTTON_A:
toggleStart();
break;
}
}
}
void silent() {
buzzer.noTone();
rgbLed.setColor(2, 0, 0, 0);
rgbLed.show();
}
void warning() {
rgbLed.setColor(2, 0, 0, 10);
rgbLed.show();
}
void alarm() {
//buzzer.tone(262, 100);
rgbLed.setColor(2, 10, 0, 0);
rgbLed.show();
}
void noiseCheck() {
if (start and distanceWarning(DISTANCECMCRITICAL)) {
if (wait == false) {
wait = true;
waitTimer = millis();
}
if (wait and millis() - waitTimer > WAITINTERVAL) {
makeNoise = true;
alarm();
} else {
warning();
}
} else {
wait = false;
makeNoise = false;
silent();
}
}
void autonomous() {
byte randNumber;
randomSeed(analogRead(6));
randNumber = random(2);
if (!distanceWarning(DISTANCECMCRITICAL) and !obstacle) {
moveDirection = FORWARD;
} else {
obstacle = true;
}
if (obstacle) {
if (distanceWarning(DISTANCECMWARNING)) {
moveDirection = BACKWARD;
} else {
switch (randNumber) {
case 0:
moveDirection = LEFT;
turnLeft();
delay(400);
break;
case 1:
moveDirection = RIGHT;
turnRight();
delay(400);
break;
}
obstacle = false;
}
}
}
void sendData() {
if (millis() - publishTimer > PUBLSIHINTERVAL) {
publishTimer = millis();
root["start"] = start;
root["moveDirection"] = moveDirection;
root["wait"] = wait;
root["makeNoise"] = makeNoise;
root["distanceCm"] = ultrasonicSensor.distanceCm();
root["lightSensor"] = lightSensor.read();
root["temperature"] = temperature.temperature();
root.prettyPrintTo(Serial);
Serial << endl;
}
}
void setup() {
Serial.begin(115200);
Serial << endl << endl;
pinMode(A7, INPUT);
ir.begin();
rgbLed.setColor(0, 0, 0, 0);
rgbLed.show();
}
void loop() {
bottomCheck();
irCheck();
noiseCheck();
sendData();
move();
if (start) {
switch (lineFollower.readSensors()) {
case S1_IN_S2_IN:
tryFollowLine = true;
moveDirection = FORWARD;
lineFollowFlag = 10;
break;
case S1_IN_S2_OUT:
tryFollowLine = true;
moveDirection = FORWARD;
if (lineFollowFlag > 1) lineFollowFlag--;
break;
case S1_OUT_S2_IN:
tryFollowLine = true;
moveDirection = FORWARD;
if (lineFollowFlag < 20) lineFollowFlag++;
break;
case S1_OUT_S2_OUT:
if (tryFollowLine) {
tryFollowLine = !tryFollowLine;
tryFollowLineTimer = millis();
}
if (millis() - tryFollowLineTimer < TRYFOLLOWLINEINTERVAL) {
if (lineFollowFlag == 10) moveDirection = BACKWARD;
if (lineFollowFlag < 10) moveDirection = LEFT;
if (lineFollowFlag > 10) moveDirection = RIGHT;
} else {
autonomous();
}
break;
}
}
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <cstdlib>
using namespace std;
const int MAX_ARGS = 256;
int runCommands(char **argv) {
int status;
pid_t pid;
pid = fork();
if(pid < 0) {
perror("Error: pid < 0!");
return 0;
}
else if(pid == 0) {
if(execvp(*argv, argv) < 0) {
perror("execvp error!");
return 0;
}
}
while(wait(&status) != pid)
;
return 1;
}
void verificationConnector(int value, char **parsedTokens, char *statements) {
if(strcmp(statements, "&&") == 0) {
if(value){
verificationConnector(1, parsedTokens, strtok(0, " "));
}
} else if(strcmp(statements, "||") == 0) {
if(!value){
verificationConnector(1, parsedTokens, strtok(0, " "));
}
} else if(statements == 0 || *statements == '#') {
return;
} else if(strcmp(statements, "exit") == 0) {
exit(0);
} else {
int i;
char *next = strtok(0, " ");
*parsedTokens = statements;
for(i = 1; next && *next != '#' && strcmp(next, "&&") && strcmp(next, "||"); i++) {
parsedTokens[i] = next;
next = strtok(0, " ");
}
verificationConnector(runCommands(parsedTokens), parsedTokens + i + 1, next);
}
}
void handleCommands(char *commands) {
char *statements[MAX_ARGS] = {0};
char *parsedTokens[MAX_ARGS] = {0};
int i = 0;
for(char *tok = strtok(commands, ";"); tok; tok = strtok(0, ";")) {
statements[i] = tok;
i++;
}
for(int i = 0; statements[i]; i++) {
verificationConnector(1, parsedTokens, strtok(statements[i], " "));
for(int j = 0; parsedTokens[j]; j++) {
parsedTokens[j] = 0;
}
}
}
void changeBuffer(string &buffer) {
for(size_t i = 2; i < buffer.length(); i++) {
if(buffer[i] == '&' && buffer[i - 1] == '&' && buffer[i - 2] != ' ') {
buffer = buffer.substr(0, i - 1) + " && " + buffer.substr(i + 1);
i+=2;
} else if(buffer[i] == '|' && buffer[i - 1] == '|' && buffer[i - 2] != ' ') {
buffer = buffer.substr(0, i - 1) + " || " + buffer.substr(i + 1);
i+=2;
} else if(buffer[i] == '#' && buffer[i - 1] != ' ') {
buffer = buffer.substr(0, i - 1) + + " #" + buffer.substr(i + 1);
i+=2;
}
}
}
int main() {
string buffer;
while(true) {
cout << "$ ";
getline(cin,buffer);
changeBuffer(buffer);
char *temp = (char *)buffer.c_str();
handleCommands(temp);
}
return 0;
}
<commit_msg>updated the main file: have the DealCommand class<commit_after>#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <cstdlib>
#include "DealCommand.h"
using namespace std;
int main() {
string buffer;
DealCommand* deal = new DealCommand;
while(true) {
cout << "$ ";
getline(cin,buffer);
deal->changeBuffer(buffer);
char *temp = (char *)buffer.c_str();
deal->handleCommands(temp);
}
return 0;
}
<|endoftext|> |
<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <e_line_judge/user_calibration.h>
#include <e_line_judge/ball_detection.h>
#include <e_line_judge/ball_tracking.h>
#include <e_line_judge/line_decision.h>
#include <e_line_judge/pre_processing.h>
#include <e_line_judge/surface_contact_detection.h>
#include <iostream>
cv::Point2i ball_center;
void mouseCallback(int event, int x, int y, int flags, void *param)
{
if (event == CV_EVENT_LBUTTONDOWN)
{
ball_center.x = x;
ball_center.y = y;
}
}
int main(int argc, char** argv)
{
UserCalibration uc;
cv::Mat image;
int frame_calibration_number;
bool slow_motion = false;
bool live_video = false;
bool rotate_image = true;
bool hardcoded_calibration = true;
//reading example image, uncomment for debugging
//image = cv::imread("../images/big_yellow_ball.jpg");
cv::VideoCapture vidCap;
if(argc == 1)
{
std::cout << "Using ball falling on the left video" << std::endl;
vidCap = cv::VideoCapture("../data/video/left.MOV");
}
if(argc > 1)
{
std::cout << "argv = " << argv[1] << std::endl;
if(!strcmp(argv[1], "left"))
{
std::cout << "Using ball falling on the left video" << std::endl;
vidCap = cv::VideoCapture("../data/video/left.MOV");
}
else if(!strcmp(argv[1], "right"))
{
std::cout << "Using ball falling on the right video" << std::endl;
vidCap = cv::VideoCapture("../data/video/right.MOV");
}
else if(!strcmp(argv[1], "center"))
{
std::cout << "Using ball falling on the center video" << std::endl;
vidCap = cv::VideoCapture("../data/video/center.MOV");
}
else if (!strcmp(argv[1], "live"))
{
std::cout << "Using live video" << std::endl;
vidCap = cv::VideoCapture(1);
live_video = true;
rotate_image = false;
}
else if(!strcmp(argv[1], "file"))
{
if (argc > 2)
{
vidCap = cv::VideoCapture(argv[2]);
if (!vidCap.isOpened())
{
std::cout << "Cannot open file " << argv[2] << std::endl;
exit(0);
}
}
else
{
std::cout << "Specify a filename " << std::endl;
exit(0);
}
}
if(argc > 3)
{
slow_motion = true;
}
}
//rotating the image
PreProcessing pp;
if (!live_video)
{
frame_calibration_number = uc.getBallFrameEstimate();
for(int i = 0; i < frame_calibration_number; i++)
{
vidCap >> image;
}
vidCap.set(CV_CAP_PROP_POS_AVI_RATIO, 0);
}
else
{
vidCap >> image;
}
std::cout << "Video size: " << image.cols << "x" << image.rows << std::endl;
if (rotate_image)
{
std::cout << "Rotating and resizing video to: 360x640" << std::endl;
pp.rotateImage(image, 360, 640);
}
std::cout << "Showing calibration frame" << std::endl;
//get HSV range for the ball to calibrate
cv::Scalar lower_range;
cv::Scalar upper_range;
double radius_estimate;
if (!hardcoded_calibration)
{
uc.getBallHSVRange(image, lower_range, upper_range, radius_estimate, false);
}
else
{
//lower_range = cv::Scalar(12, 119, 200, 0);
//upper_range = cv::Scalar(18, 249, 255, 0);
lower_range = cv::Scalar(11, 118, 225, 0);
upper_range = cv::Scalar(18, 249, 255, 0);
radius_estimate = 10.0;
}
//get line coordinates
std::vector<cv::Point2i> lines;
uc.getLineLimits(image, lines);
//Displaying the input lines
/*
cv::Mat img_copy;
image.copyTo(img_copy);
cv::line(img_copy, lines[0], lines[1], cv::Scalar(0,0,255));
cv::line(img_copy, lines[1], lines[2], cv::Scalar(0,0,255));
cv::line(img_copy, lines[2], lines[3], cv::Scalar(0,0,255));
cv::line(img_copy, lines[3], lines[0], cv::Scalar(0,0,255));
cv::imshow("Lines", img_copy);
*/
uc.setDisplay("Starting Electronic Line Judge...");
//tracking the ball
//restarting the video capture to frame 0
//creating instance of tracking class
BallDetection bd(lower_range, upper_range, radius_estimate);
cv::Point2i ball_center;
LineDecision ld(lines);
int decision_result = 0;
double ball_radius;
std::queue<cv::Mat> last_frames;
int frames_back = 1; //taking one frame back for the decision after the change in direction has been detected
SurfaceContactDetection scd;
cv::Point2i previous_ball_center(0.0, 0.0);
int ball_detection_iteration = 0;
bool made_decision = false;
while (true)
{
// Read a video frame
vidCap >> image;
cv::Mat image_copy;
if(!image.empty())
{
//rotating frame
if (rotate_image)
{
pp.rotateImage(image, 360, 640);
}
//avoiding pushing a pointer (gives runtime error) and pushing a copy instead
image.copyTo(image_copy);
last_frames.push(image_copy);
if(last_frames.size() > frames_back + 1)
{
last_frames.pop();
}
//do stuff
if(bd.detect_ball(image, ball_center, ball_radius))
{
//after detection of the ball, print its value on y
//std::cout << "ball y coordinate : " << ball_center.y << std::endl;
//drawing detected circles
// circle center
cv::circle(image, ball_center, 3, cv::Scalar(0,255,0), -1, 8, 0);
// circle outline
cv::circle(image, ball_center, ball_radius, cv::Scalar(0,0,255), 3, 8, 0);
std::cout << "prev: " << previous_ball_center.y << ", curr: " << ball_center.y << std::endl;
if(!made_decision && ball_detection_iteration != 0 && scd.hasTrayectoryChanged(previous_ball_center.y, ball_center.y))
{
//taking two frames back
cv::Mat decision_frame;
last_frames.front().copyTo(decision_frame);
//result image will store lines and marked ball with the decision
cv::Mat result_image;
//detect ball on decision frame
if(bd.detect_ball(decision_frame, ball_center, ball_radius))
{
//testing the line decision, uncomment for debugging
cv::Point2i projected_ball_center = ball_center;
projected_ball_center.y += ball_radius;
cv::circle(decision_frame, projected_ball_center, 3, cv::Scalar(255,0,0), -1, 8, 0);
decision_result = ld.getDecision(decision_frame, projected_ball_center, ball_radius);
// result image
decision_frame.copyTo(result_image);
cv::line(result_image, lines[0], lines[1], cv::Scalar(0,0,255));
cv::line(result_image, lines[1], lines[2], cv::Scalar(0,0,255));
cv::line(result_image, lines[2], lines[3], cv::Scalar(0,0,255));
cv::line(result_image, lines[3], lines[0], cv::Scalar(0,0,255));
}
else
{
std::cout << "Error : ball does not exist in decision frame" << std::endl;
}
if(decision_result == -1)
{
uc.setDisplay("Decision: LEFT");
std::cout << "Left" << std::endl;
cv::putText(result_image, "LEFT", cv::Point(5,result_image.rows - 20),
CV_FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,255),1,8,false);
if (!live_video)
{
made_decision = true;
}
}
else if(decision_result == 0)
{
if (live_video)
{
uc.setDisplay("Decision: LEFT");
cv::putText(result_image, "LEFT", cv::Point(5,result_image.rows - 20),
CV_FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,255),1,8,false);
std::cout << "Left" << std::endl;
}
else
{
uc.setDisplay("Decision: ON LINE");
cv::putText(result_image, "ON LINE", cv::Point(5,result_image.rows - 20),
CV_FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,255),1,8,false);
std::cout << "On Line" << std::endl;
}
if (!live_video)
{
made_decision = true;
}
}
else
{
uc.setDisplay("Decision: RIGHT");
cv::putText(result_image, "RIGHT", cv::Point(5,result_image.rows - 20),
CV_FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,255),1,8,false);
std::cout << "Right" << std::endl;
if (!live_video)
{
made_decision = true;
}
}
cv::imshow("Result", result_image);
}
ball_detection_iteration++;
previous_ball_center = ball_center;
}
cv::line(image, lines[0], lines[1], cv::Scalar(0,0,255));
cv::line(image, lines[1], lines[2], cv::Scalar(0,0,255));
cv::line(image, lines[2], lines[3], cv::Scalar(0,0,255));
cv::line(image, lines[3], lines[0], cv::Scalar(0,0,255));
cv::imshow("Ball detection", image);
// Quit the loop when a key is pressed, also give a delay on the video
int wait_time = 5;
if (slow_motion)
{
wait_time = 500;
}
int keyPressed = cv::waitKey(wait_time);
if (keyPressed != -1) break;
}
else
{
vidCap.set(CV_CAP_PROP_POS_AVI_RATIO , 0);
std::cout << "Reached end of video, playing again" << std::endl;
uc.setDisplay("Starting Electronic Line Judge...");
made_decision = false;
previous_ball_center.x = 0.0;
previous_ball_center.y = 0.0;
ball_detection_iteration = 0;
cv::destroyWindow("Result");
}
}
return 0;
}
<commit_msg>using current frame if previous frame contains no ball<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <e_line_judge/user_calibration.h>
#include <e_line_judge/ball_detection.h>
#include <e_line_judge/ball_tracking.h>
#include <e_line_judge/line_decision.h>
#include <e_line_judge/pre_processing.h>
#include <e_line_judge/surface_contact_detection.h>
#include <iostream>
cv::Point2i ball_center;
void mouseCallback(int event, int x, int y, int flags, void *param)
{
if (event == CV_EVENT_LBUTTONDOWN)
{
ball_center.x = x;
ball_center.y = y;
}
}
int main(int argc, char** argv)
{
UserCalibration uc;
cv::Mat image;
int frame_calibration_number;
bool slow_motion = false;
bool live_video = false;
bool rotate_image = true;
bool hardcoded_calibration = true;
//reading example image, uncomment for debugging
//image = cv::imread("../images/big_yellow_ball.jpg");
cv::VideoCapture vidCap;
if(argc == 1)
{
std::cout << "Using ball falling on the left video" << std::endl;
vidCap = cv::VideoCapture("../data/video/devel_videos/left.MOV");
}
if(argc > 1)
{
std::cout << "argv = " << argv[1] << std::endl;
if(!strcmp(argv[1], "left"))
{
std::cout << "Using ball falling on the left video" << std::endl;
vidCap = cv::VideoCapture("../data/video/devel_videos/left.MOV");
}
else if(!strcmp(argv[1], "right"))
{
std::cout << "Using ball falling on the right video" << std::endl;
vidCap = cv::VideoCapture("../data/video/devel_videos/right.MOV");
}
else if(!strcmp(argv[1], "center"))
{
std::cout << "Using ball falling on the center video" << std::endl;
vidCap = cv::VideoCapture("../data/video/devel_videos/center.MOV");
}
else if (!strcmp(argv[1], "live"))
{
std::cout << "Using live video" << std::endl;
vidCap = cv::VideoCapture(1);
live_video = true;
rotate_image = false;
}
else if(!strcmp(argv[1], "file"))
{
if (argc > 2)
{
vidCap = cv::VideoCapture(argv[2]);
if (!vidCap.isOpened())
{
std::cout << "Cannot open file " << argv[2] << std::endl;
exit(0);
}
}
else
{
std::cout << "Specify a filename " << std::endl;
exit(0);
}
}
if(argc > 3)
{
slow_motion = true;
}
}
//rotating the image
PreProcessing pp;
if (!live_video)
{
frame_calibration_number = uc.getBallFrameEstimate();
for(int i = 0; i < frame_calibration_number; i++)
{
vidCap >> image;
}
vidCap.set(CV_CAP_PROP_POS_AVI_RATIO, 0);
}
else
{
vidCap >> image;
}
std::cout << "Video size: " << image.cols << "x" << image.rows << std::endl;
if (rotate_image)
{
std::cout << "Rotating and resizing video to: 360x640" << std::endl;
pp.rotateImage(image, 360, 640);
}
std::cout << "Showing calibration frame" << std::endl;
//get HSV range for the ball to calibrate
cv::Scalar lower_range;
cv::Scalar upper_range;
double radius_estimate;
if (!hardcoded_calibration)
{
uc.getBallHSVRange(image, lower_range, upper_range, radius_estimate, false);
}
else
{
//lower_range = cv::Scalar(12, 119, 200, 0);
//upper_range = cv::Scalar(18, 249, 255, 0);
lower_range = cv::Scalar(11, 118, 225, 0);
upper_range = cv::Scalar(18, 249, 255, 0);
radius_estimate = 10.0;
}
//get line coordinates
std::vector<cv::Point2i> lines;
uc.getLineLimits(image, lines);
//Displaying the input lines
/*
cv::Mat img_copy;
image.copyTo(img_copy);
cv::line(img_copy, lines[0], lines[1], cv::Scalar(0,0,255));
cv::line(img_copy, lines[1], lines[2], cv::Scalar(0,0,255));
cv::line(img_copy, lines[2], lines[3], cv::Scalar(0,0,255));
cv::line(img_copy, lines[3], lines[0], cv::Scalar(0,0,255));
cv::imshow("Lines", img_copy);
*/
uc.setDisplay("Starting Electronic Line Judge...");
//tracking the ball
//restarting the video capture to frame 0
//creating instance of tracking class
BallDetection bd(lower_range, upper_range, radius_estimate);
cv::Point2i ball_center;
LineDecision ld(lines);
int decision_result = 0;
double ball_radius;
std::queue<cv::Mat> last_frames;
int frames_back = 1; //taking one frame back for the decision after the change in direction has been detected
SurfaceContactDetection scd;
cv::Point2i previous_ball_center(0.0, 0.0);
int ball_detection_iteration = 0;
bool made_decision = false;
while (true)
{
// Read a video frame
vidCap >> image;
cv::Mat image_copy;
if(!image.empty())
{
//rotating frame
if (rotate_image)
{
pp.rotateImage(image, 360, 640);
}
//avoiding pushing a pointer (gives runtime error) and pushing a copy instead
image.copyTo(image_copy);
last_frames.push(image_copy);
if(last_frames.size() > frames_back + 1)
{
last_frames.pop();
}
//do stuff
if(bd.detect_ball(image, ball_center, ball_radius))
{
//after detection of the ball, print its value on y
//std::cout << "ball y coordinate : " << ball_center.y << std::endl;
std::cout << "prev: " << previous_ball_center.y << ", curr: " << ball_center.y << std::endl;
if(!made_decision && ball_detection_iteration != 0 && scd.hasTrayectoryChanged(previous_ball_center.y, ball_center.y))
{
//taking two frames back
cv::Mat decision_frame;
last_frames.front().copyTo(decision_frame);
//result image will store lines and marked ball with the decision
cv::Mat result_image;
//detect ball on decision frame
if(bd.detect_ball(decision_frame, ball_center, ball_radius))
{
//testing the line decision, uncomment for debugging
cv::Point2i projected_ball_center = ball_center;
projected_ball_center.y += ball_radius;
cv::circle(decision_frame, projected_ball_center, 3, cv::Scalar(255,0,0), -1, 8, 0);
decision_result = ld.getDecision(decision_frame, projected_ball_center, ball_radius);
// result image
decision_frame.copyTo(result_image);
cv::line(result_image, lines[0], lines[1], cv::Scalar(0,0,255));
cv::line(result_image, lines[1], lines[2], cv::Scalar(0,0,255));
cv::line(result_image, lines[2], lines[3], cv::Scalar(0,0,255));
cv::line(result_image, lines[3], lines[0], cv::Scalar(0,0,255));
//drawing detected circles
// circle center
cv::circle(result_image, ball_center, 3, cv::Scalar(0,255,0), -1, 8, 0);
// circle outline
cv::circle(result_image, ball_center, ball_radius, cv::Scalar(0,0,255), 3, 8, 0);
}
else
{
std::cout << "Error : ball does not exist in decision frame" << std::endl;
//if ball does not exist in the decision frame, then we use the current frame
std::cout << "Using current frame" << std::endl;
if(bd.detect_ball(image, ball_center, ball_radius))
{
//testing the line decision, uncomment for debugging
cv::Point2i projected_ball_center = ball_center;
projected_ball_center.y += ball_radius;
cv::circle(image, projected_ball_center, 3, cv::Scalar(255,0,0), -1, 8, 0);
decision_result = ld.getDecision(image, projected_ball_center, ball_radius);
// result image
image.copyTo(result_image);
cv::line(result_image, lines[0], lines[1], cv::Scalar(0,0,255));
cv::line(result_image, lines[1], lines[2], cv::Scalar(0,0,255));
cv::line(result_image, lines[2], lines[3], cv::Scalar(0,0,255));
cv::line(result_image, lines[3], lines[0], cv::Scalar(0,0,255));
//drawing detected circles
// circle center
cv::circle(result_image, ball_center, 3, cv::Scalar(0,255,0), -1, 8, 0);
// circle outline
cv::circle(result_image, ball_center, ball_radius, cv::Scalar(0,0,255), 3, 8, 0);
}
else
{
std::cout << "Error : ball does not exist in current frame" << std::endl;
}
}
if(decision_result == -1)
{
uc.setDisplay("Decision: LEFT");
std::cout << "Left" << std::endl;
cv::putText(result_image, "LEFT", cv::Point(5,result_image.rows - 20),
CV_FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,255),1,8,false);
if (!live_video)
{
made_decision = true;
}
}
else if(decision_result == 0)
{
if (live_video)
{
uc.setDisplay("Decision: LEFT");
cv::putText(result_image, "LEFT", cv::Point(5,result_image.rows - 20),
CV_FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,255),1,8,false);
std::cout << "Left" << std::endl;
}
else
{
uc.setDisplay("Decision: ON LINE");
cv::putText(result_image, "ON LINE", cv::Point(5,result_image.rows - 20),
CV_FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,255),1,8,false);
std::cout << "On Line" << std::endl;
}
if (!live_video)
{
made_decision = true;
}
}
else
{
uc.setDisplay("Decision: RIGHT");
cv::putText(result_image, "RIGHT", cv::Point(5,result_image.rows - 20),
CV_FONT_HERSHEY_SIMPLEX, 0.7, cv::Scalar(0,0,255),1,8,false);
std::cout << "Right" << std::endl;
if (!live_video)
{
made_decision = true;
}
}
cv::imshow("Result", result_image);
}
ball_detection_iteration++;
previous_ball_center = ball_center;
}
cv::line(image, lines[0], lines[1], cv::Scalar(0,0,255));
cv::line(image, lines[1], lines[2], cv::Scalar(0,0,255));
cv::line(image, lines[2], lines[3], cv::Scalar(0,0,255));
cv::line(image, lines[3], lines[0], cv::Scalar(0,0,255));
cv::imshow("Ball detection", image);
// Quit the loop when a key is pressed, also give a delay on the video
int wait_time = 5;
if (slow_motion)
{
wait_time = 500;
}
int keyPressed = cv::waitKey(wait_time);
if (keyPressed != -1) break;
}
else
{
vidCap.set(CV_CAP_PROP_POS_AVI_RATIO , 0);
std::cout << "Reached end of video, playing again" << std::endl;
uc.setDisplay("Starting Electronic Line Judge...");
made_decision = false;
previous_ball_center.x = 0.0;
previous_ball_center.y = 0.0;
ball_detection_iteration = 0;
cv::destroyWindow("Result");
}
}
return 0;
}
<|endoftext|> |
<commit_before>#pragma GCC diagnostic ignored "-Wswitch"
#define GLEW_STATIC
#define MICRO_SECONDS_PER_FRAME 16667
#include <GL/glew.h>
#include <SFML/Window.hpp>
#include <chrono>
#include <unistd.h>
std::chrono::steady_clock::time_point start;
std::chrono::steady_clock::time_point end;
//-----------------------------------------------------
// SFML setup
//-----------------------------------------------------
sf::Window window(sf::VideoMode(1280, 720), "OpenGL", sf::Style::Close);
bool running = true;
void process_input(){
sf::Event windowEvent;
while (window.pollEvent(windowEvent)) {
switch (windowEvent.type) {
case sf::Event::Closed:
running = false;
break;
}
}
}
void update(){
}
void render(){
window.display();
}
int main() {
//-----------------------------------------------------
// Glew setup
//-----------------------------------------------------
glewExperimental = GL_TRUE;
glewInit();
//-----------------------------------------------------
// Main game loop
//-----------------------------------------------------
while (running) {
//Get the time at the beginning of the frame
start = std::chrono::steady_clock::now();
process_input();
update();
render();
//Calculate how long the frame took to process
end = std::chrono::steady_clock::now();
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
//Sleep if the processing took less than what is necessary to achieve 60 FPS
if(( MICRO_SECONDS_PER_FRAME - microseconds ) > 0){
usleep((MICRO_SECONDS_PER_FRAME - microseconds));
}
}
return 0;
}
<commit_msg>More complete setup for SFML. Must test on desktop<commit_after>#pragma GCC diagnostic ignored "-Wswitch"
#define GLEW_STATIC
#define MICRO_SECONDS_PER_FRAME 16667
#include <GL/glew.h>
#include <SFML/Window.hpp>
#include <chrono>
#include <unistd.h>
//Global variables
std::chrono::steady_clock::time_point start;
std::chrono::steady_clock::time_point end;
sf::Window *window;
bool running = true;
void setup_SFML(){
sf::ContextSettings settings;
settings.antialiasingLevel = 4;
settings.majorVersion = 3;
settings.minorVersion = 3;
window = new sf::Window(sf::VideoMode(1280, 720), "OpenGL", sf::Style::Close,settings);
}
void process_input(){
sf::Event windowEvent;
while (window->pollEvent(windowEvent)) {
switch (windowEvent.type) {
case sf::Event::Closed:
running = false;
break;
}
}
}
void update(){
}
void render(){
window->display();
}
int main() {
setup_SFML();
//-----------------------------------------------------
// Glew setup
//-----------------------------------------------------
glewExperimental = GL_TRUE;
glewInit();
//-----------------------------------------------------
// Main game loop
//-----------------------------------------------------
while (running) {
//Get the time at the beginning of the frame
start = std::chrono::steady_clock::now();
process_input();
update();
render();
//Calculate how long the frame took to process
end = std::chrono::steady_clock::now();
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
//Sleep if the processing took less than what is necessary to achieve 60 FPS
if(( MICRO_SECONDS_PER_FRAME - microseconds ) > 0){
usleep((MICRO_SECONDS_PER_FRAME - microseconds));
}
}
delete window;
return 0;
}
<|endoftext|> |
<commit_before>#include "userinterface.hpp"
int main(int argc, char *argv[])
{
std::vector<std::string> arg;
for(int i = 0; i < argc; i++)
{
arg.push_back(argv[i]);
}
UserInterface ui(arg);
}
<commit_msg>add top level exception handling<commit_after>#include "userinterface.hpp"
int main(int argc, char * argv[])
{
try
{
std::vector<std::string> arg;
for (int i = 0; i < argc; i++)
{
arg.push_back(argv[i]);
}
UserInterface ui(arg);
}
catch (...)
{
std::cout << "Unknown error!" << std::endl;
}
}
<|endoftext|> |
<commit_before>#include <dmc/dmc.hpp>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <chrono>
template <class Scalar>
struct test_object : dmc::dual_object<Scalar, test_object<Scalar>>
{
public:
typedef dmc::object<Scalar> base_type;
using typename base_type::scalar_type;
using typename base_type::vector_type;
explicit test_object(scalar_type radius)
: radius_(radius)
{
}
template <class T>
T templated_value(const Eigen::Matrix<T, 3, 1>& p) const
{
auto cube1 = 1.0 - p.cwiseAbs().maxCoeff();
auto cube2 = 1.0 - (p - Eigen::Matrix<T, 3, 1>(0.5, 0.5, 0.5)).cwiseAbs().maxCoeff();
return std::min(cube1, -cube2);
}
private:
scalar_type radius_;
};
int main(int /*argc*/, char* /*argv*/ [])
{
dmc::tree_config<double> config;
config.grid_width = 0.1;
config.tolerance = 0.001;
auto start_time = std::chrono::high_resolution_clock::now();
dmc::tree<double> t({-3.0, -3.0, -3.0}, {3.0, 3.0, 3.0}, config);
double last_progress = 0.0;
t.generate(test_object<double>(1.5f), [&](double progress) {
if (progress > last_progress + 0.01)
{
std::cout << std::fixed << std::setprecision(3) << progress << std::endl;
last_progress = progress;
}
});
auto generated_time = std::chrono::high_resolution_clock::now();
auto triangles = t.enumerate();
auto enumerated_time = std::chrono::high_resolution_clock::now();
std::cout << "Generation: " << std::fixed << std::setprecision(2) << std::chrono::duration<double>(generated_time - start_time).count() << "s" << std::endl;
std::cout << "Enumeration: " << std::fixed << std::setprecision(2) << std::chrono::duration<double>(enumerated_time - generated_time).count() << "s" << std::endl;
std::ofstream os("a.stl", std::ios::binary);
write_stl(os, triangles);
}
<commit_msg>Refactoring<commit_after>#include <dmc/dmc.hpp>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <chrono>
template <class Scalar>
struct test_object : dmc::dual_object<Scalar, test_object<Scalar>>
{
private:
typedef dmc::object<Scalar> base_type;
public:
using typename base_type::scalar_type;
using typename base_type::vector_type;
template <class T>
T templated_value(const Eigen::Matrix<T, 3, 1>& p) const
{
auto cube1 = 1.0 - p.cwiseAbs().maxCoeff();
auto cube2 = 1.0 - (p - Eigen::Matrix<T, 3, 1>(0.5, 0.5, 0.5)).cwiseAbs().maxCoeff();
return std::min(cube1, -cube2);
}
};
int main(int /*argc*/, char* /*argv*/ [])
{
dmc::tree_config<double> config;
config.grid_width = 0.1;
config.tolerance = 0.001;
auto start_time = std::chrono::high_resolution_clock::now();
dmc::tree<double> t({-3.0, -3.0, -3.0}, {3.0, 3.0, 3.0}, config);
double last_progress = 0.0;
test_object<double> obj;
t.generate(obj, [&](double progress) {
if (progress > last_progress + 0.01)
{
std::cout << std::fixed << std::setprecision(3) << progress << std::endl;
last_progress = progress;
}
});
auto generated_time = std::chrono::high_resolution_clock::now();
auto triangles = t.enumerate();
auto enumerated_time = std::chrono::high_resolution_clock::now();
std::cout << "Generation: " << std::fixed << std::setprecision(2) << std::chrono::duration<double>(generated_time - start_time).count() << "s" << std::endl;
std::cout << "Enumeration: " << std::fixed << std::setprecision(2) << std::chrono::duration<double>(enumerated_time - generated_time).count() << "s" << std::endl;
std::ofstream os("a.stl", std::ios::binary);
write_stl(os, triangles);
}
<|endoftext|> |
<commit_before>#include "bcm2835/rpiemulator.h"
#include <getopt.h>
/**
* Prints the command line options
*/
static void
cmdline_usage(int argc, char **argv)
{
printf("%s [options] image\n", argc > 0 ? argv[0] : "emulate");
printf("Options:\n");
printf(" --quiet Does not dump CPU state\n");
printf(" --graphics Emulate framebuffer\n");
printf(" --memory=size Specify memory size in bytes\n");
printf(" --addr=addr Specify kernel start address\n");
printf(" --help Print this message\n");
}
/**
* Parses command line arguments using getopt
* @param opt Reference to the options struct
* @param argc Number of command line arguments
* @param argv Argument values
* @param usage Pointer to usage value
* @return Nonzero if arguments are valid
*/
static int
cmdline_parse(remu::EmulatorOptions &opt, int argc, char **argv, int *usage)
{
struct option options[] =
{
{ "help", no_argument, usage, 1 },
{ "quiet", no_argument, &opt.quiet, 1 },
{ "nes", no_argument, &opt.nes_enabled, 1 },
{ "memory", required_argument, 0, 'm' },
{ "addr", required_argument, 0, 'a' },
{ "gpio-test", required_argument, 0, 'i' },
{ 0, 0, 0, 0 }
};
int c, index;
/* Default args */
opt.mem_size = 256 * 1024 * 1024;
opt.start_addr = 0x10000;
/* Read all arguments */
while ((c = getopt_long(argc, argv, "vghsm:a:", options, &index)) != -1)
{
switch (c)
{
case 'q': opt.quiet = 1; break;
case 'h': *usage = 1; break;
case 'm':
{
/* Handle prefixes */
int length = strlen(optarg);
switch (optarg[length - 1])
{
case 'm': case 'M':
{
optarg[length - 1] = '\0';
sscanf(optarg, "%zu", &opt.mem_size);
opt.mem_size *= 1024 * 1024;
break;
}
case 'k': case 'K':
{
optarg[length - 1] = '\0';
sscanf(optarg, "%zu", &opt.mem_size);
opt.mem_size *= 1024;
break;
}
default:
{
sscanf(optarg, "%zu", &opt.mem_size);
}
}
break;
}
case 'a':
{
sscanf(optarg, "%u", &opt.start_addr);
break;
}
case 'i':
{
sscanf(optarg, "%u", &opt.gpio_test_offset);
break;
}
case 0:
{
/* Flag set */
break;
}
case '?':
{
/* Error */
return 0;
}
}
}
/* Read image source */
opt.image = optind >= argc ? NULL : argv[optind];
return 1;
}
/**
* Checks the validity of the arguments
* @param opt Reference to the options struct
* @param argc Number of command line arguments
* @param argv Argument values
* @return Nonzero if arguments are valid
*/
static int
cmdline_check(remu::EmulatorOptions &opt)
{
/* Image source */
if (!opt.image)
{
fprintf(stderr, "No kernel image specified.\n");
return 0;
}
/* Memory size at least 64kb */
if (opt.mem_size < 0x10000)
{
fprintf(stderr, "Must specify a minimum of 64kb of memory.\n");
return 0;
}
return 1;
}
/**
* Entry point of the application
* @param argc Number of command line arguments
* @param argv Argument values
* @return EXIT_SUCCESS if everything goes fine
*/
int
main(int argc, char **argv)
{
/* Parse command line arguments */
remu::EmulatorOptions opt;
int usage = 0;
if (!cmdline_parse(opt, argc, argv, &usage))
{
return EXIT_FAILURE;
}
if (usage)
{
cmdline_usage(argc, argv);
return EXIT_SUCCESS;
}
if (!cmdline_check(opt))
{
return EXIT_FAILURE;
}
try {
remu::bcm2835::RPiEmulator emu(opt);
/* Run the emulator */
emu.load();
emu.execute();
} catch(const std::exception &exc) {
fprintf(stderr, "Fatal Error: %s\n", exc.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Convert cmdline_check to return bool<commit_after>#include "bcm2835/rpiemulator.h"
#include <getopt.h>
/**
* Prints the command line options
*/
static void
cmdline_usage(int argc, char **argv)
{
printf("%s [options] image\n", argc > 0 ? argv[0] : "emulate");
printf("Options:\n");
printf(" --quiet Does not dump CPU state\n");
printf(" --graphics Emulate framebuffer\n");
printf(" --memory=size Specify memory size in bytes\n");
printf(" --addr=addr Specify kernel start address\n");
printf(" --help Print this message\n");
}
/**
* Parses command line arguments using getopt
* @param opt Reference to the options struct
* @param argc Number of command line arguments
* @param argv Argument values
* @param usage Pointer to usage value
* @return Nonzero if arguments are valid
*/
static int
cmdline_parse(remu::EmulatorOptions &opt, int argc, char **argv, int *usage)
{
struct option options[] =
{
{ "help", no_argument, usage, 1 },
{ "quiet", no_argument, &opt.quiet, 1 },
{ "nes", no_argument, &opt.nes_enabled, 1 },
{ "memory", required_argument, 0, 'm' },
{ "addr", required_argument, 0, 'a' },
{ "gpio-test", required_argument, 0, 'i' },
{ 0, 0, 0, 0 }
};
int c, index;
/* Default args */
opt.mem_size = 256 * 1024 * 1024;
opt.start_addr = 0x10000;
/* Read all arguments */
while ((c = getopt_long(argc, argv, "vghsm:a:", options, &index)) != -1)
{
switch (c)
{
case 'q': opt.quiet = 1; break;
case 'h': *usage = 1; break;
case 'm':
{
/* Handle prefixes */
int length = strlen(optarg);
switch (optarg[length - 1])
{
case 'm': case 'M':
{
optarg[length - 1] = '\0';
sscanf(optarg, "%zu", &opt.mem_size);
opt.mem_size *= 1024 * 1024;
break;
}
case 'k': case 'K':
{
optarg[length - 1] = '\0';
sscanf(optarg, "%zu", &opt.mem_size);
opt.mem_size *= 1024;
break;
}
default:
{
sscanf(optarg, "%zu", &opt.mem_size);
}
}
break;
}
case 'a':
{
sscanf(optarg, "%u", &opt.start_addr);
break;
}
case 'i':
{
sscanf(optarg, "%u", &opt.gpio_test_offset);
break;
}
case 0:
{
/* Flag set */
break;
}
case '?':
{
/* Error */
return 0;
}
}
}
/* Read image source */
opt.image = optind >= argc ? NULL : argv[optind];
return 1;
}
/**
* Checks the validity of the arguments
* @param opt Reference to the options struct
* @param argc Number of command line arguments
* @param argv Argument values
* @return Nonzero if arguments are valid
*/
static bool
cmdline_check(remu::EmulatorOptions &opt)
{
/* Image source */
if (!opt.image)
{
fprintf(stderr, "No kernel image specified.\n");
return false;
}
/* Memory size at least 64kb */
if (opt.mem_size < 0x10000)
{
fprintf(stderr, "Must specify a minimum of 64kb of memory.\n");
return false;
}
return true;
}
/**
* Entry point of the application
* @param argc Number of command line arguments
* @param argv Argument values
* @return EXIT_SUCCESS if everything goes fine
*/
int
main(int argc, char **argv)
{
/* Parse command line arguments */
remu::EmulatorOptions opt;
int usage = 0;
if (!cmdline_parse(opt, argc, argv, &usage))
{
return EXIT_FAILURE;
}
if (usage)
{
cmdline_usage(argc, argv);
return EXIT_SUCCESS;
}
if (!cmdline_check(opt))
{
return EXIT_FAILURE;
}
try {
remu::bcm2835::RPiEmulator emu(opt);
/* Run the emulator */
emu.load();
emu.execute();
} catch(const std::exception &exc) {
fprintf(stderr, "Fatal Error: %s\n", exc.what());
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <cstdlib>
#include <fstream>
#include <memory>
#include <boost/program_options.hpp>
#include "UI/ui_factory.hpp"
#include "player_factory.hpp"
#include "exception.hpp"
#include "logger.hpp"
#include "state/main_menu_state.hpp"
#include "state/game_state.hpp"
#include "state/state_manager.hpp"
namespace po = boost::program_options;
namespace logging = boost::log;
struct game_opts_t {
std::string ui_type;
};
static int init(int argc, char **argv, game_opts_t *game_opts);
static void init_logging(const std::string &logfile);
int main(int argc, char **argv)
{
game_opts_t game_opts;
if (init(argc, argv, &game_opts) < 0) {
return EXIT_FAILURE;
}
boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
BOOST_LOG_SEV(lg, logging::trivial::info) << "Creating "
<< game_opts.ui_type << " UI";
Quoridor::StateManager stm;
Quoridor::UI::UIFactory uif;
stm.create_ui(uif, game_opts.ui_type);
std::shared_ptr<Quoridor::IState> menu_state(new Quoridor::MainMenuState(stm.ui()));
stm.change_state(std::shared_ptr<Quoridor::IState>(menu_state));
stm.draw();
while (stm.is_running()) {
stm.handle_events();
stm.update();
stm.draw();
}
return EXIT_SUCCESS;
}
static int init(int argc, char **argv, game_opts_t *game_opts)
{
std::string logfile;
po::options_description options("Options");
options.add_options()
(
"ui,i",
po::value<std::string>(&game_opts->ui_type)->default_value("ncurses"),
"user interface"
)
(
"log,l",
po::value<std::string>(&logfile)->default_value("quoridor.log"),
"logging file"
)
(
"help,h",
"show help message"
);
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, options), vm);
}
catch (po::error &e) {
std::cerr << e.what() << std::endl;
return -1;
}
po::notify(vm);
if (vm.count("help")) {
std::cout << options << std::endl;
return -1;
}
init_logging(logfile);
return 0;
}
static void init_logging(const std::string &logfile)
{
boost::log::add_file_log(
boost::log::keywords::file_name = logfile,
boost::log::keywords::open_mode = std::ios_base::app,
boost::log::keywords::auto_flush = true,
boost::log::keywords::format = (
boost::log::expressions::stream
<< boost::log::expressions::format_date_time<
boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S")
<< " [" << boost::log::trivial::severity << "] "
<< boost::log::expressions::smessage
)
);
boost::log::add_console_log(
std::clog,
boost::log::keywords::format = (
boost::log::expressions::stream
<< boost::log::expressions::format_named_scope("Scope", boost::log::keywords::format = "%n")
<< ": [" << boost::log::trivial::severity << "] "
<< boost::log::expressions::smessage
)
);
boost::log::add_common_attributes();
boost::log::core::get()->add_global_attribute("Scope",
boost::log::attributes::named_scope());
}
<commit_msg>Remove named scope from console logger<commit_after>#include <cstdlib>
#include <fstream>
#include <memory>
#include <boost/program_options.hpp>
#include "UI/ui_factory.hpp"
#include "player_factory.hpp"
#include "exception.hpp"
#include "logger.hpp"
#include "state/main_menu_state.hpp"
#include "state/game_state.hpp"
#include "state/state_manager.hpp"
namespace po = boost::program_options;
namespace logging = boost::log;
struct game_opts_t {
std::string ui_type;
};
static int init(int argc, char **argv, game_opts_t *game_opts);
static void init_logging(const std::string &logfile);
int main(int argc, char **argv)
{
game_opts_t game_opts;
if (init(argc, argv, &game_opts) < 0) {
return EXIT_FAILURE;
}
boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg;
BOOST_LOG_SEV(lg, logging::trivial::info) << "Creating "
<< game_opts.ui_type << " UI";
Quoridor::StateManager stm;
Quoridor::UI::UIFactory uif;
stm.create_ui(uif, game_opts.ui_type);
std::shared_ptr<Quoridor::IState> menu_state(new Quoridor::MainMenuState(stm.ui()));
stm.change_state(std::shared_ptr<Quoridor::IState>(menu_state));
stm.draw();
while (stm.is_running()) {
stm.handle_events();
stm.update();
stm.draw();
}
return EXIT_SUCCESS;
}
static int init(int argc, char **argv, game_opts_t *game_opts)
{
std::string logfile;
po::options_description options("Options");
options.add_options()
(
"ui,i",
po::value<std::string>(&game_opts->ui_type)->default_value("ncurses"),
"user interface"
)
(
"log,l",
po::value<std::string>(&logfile)->default_value("quoridor.log"),
"logging file"
)
(
"help,h",
"show help message"
);
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, options), vm);
}
catch (po::error &e) {
std::cerr << e.what() << std::endl;
return -1;
}
po::notify(vm);
if (vm.count("help")) {
std::cout << options << std::endl;
return -1;
}
init_logging(logfile);
return 0;
}
static void init_logging(const std::string &logfile)
{
boost::log::add_file_log(
boost::log::keywords::file_name = logfile,
boost::log::keywords::open_mode = std::ios_base::app,
boost::log::keywords::auto_flush = true,
boost::log::keywords::format = (
boost::log::expressions::stream
<< boost::log::expressions::format_date_time<
boost::posix_time::ptime>("TimeStamp", "%Y-%m-%d %H:%M:%S")
<< " [" << boost::log::trivial::severity << "] "
<< boost::log::expressions::smessage
)
);
boost::log::add_console_log(
std::clog,
boost::log::keywords::format = (
boost::log::expressions::stream
<< "[" << boost::log::trivial::severity << "] "
<< boost::log::expressions::smessage
)
);
boost::log::add_common_attributes();
boost::log::core::get()->add_global_attribute("Scope",
boost::log::attributes::named_scope());
}
<|endoftext|> |
<commit_before>#include "ui/mainwindow.h"
#include <QApplication>
#include <QStyleFactory>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setStyle(QStyleFactory::create("Fusion"));
QPalette dark;
dark.setColor(QPalette::Window, QColor(53, 53, 53));
dark.setColor(QPalette::WindowText, Qt::white);
dark.setColor(QPalette::Base, QColor(25, 25, 25));
dark.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
dark.setColor(QPalette::ToolTipBase, Qt::white);
dark.setColor(QPalette::ToolTipText, Qt::white);
dark.setColor(QPalette::Text, Qt::white);
dark.setColor(QPalette::Button, QColor(53, 53, 53));
dark.setColor(QPalette::ButtonText, Qt::white);
dark.setColor(QPalette::BrightText, Qt::red);
dark.setColor(QPalette::Link, QColor(42, 130, 218));
dark.setColor(QPalette::Highlight, QColor(254,165,0));
dark.setColor(QPalette::HighlightedText, Qt::black);
a.setPalette(dark);
Main_window w;
w.show();
return a.exec();
}
<commit_msg>Set locale<commit_after>#include "ui/mainwindow.h"
#include <QApplication>
#include <QLocale>
#include <QStyleFactory>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setStyle(QStyleFactory::create("Fusion"));
QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
QPalette dark;
dark.setColor(QPalette::Window, QColor(53, 53, 53));
dark.setColor(QPalette::WindowText, Qt::white);
dark.setColor(QPalette::Base, QColor(25, 25, 25));
dark.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
dark.setColor(QPalette::ToolTipBase, Qt::white);
dark.setColor(QPalette::ToolTipText, Qt::white);
dark.setColor(QPalette::Text, Qt::white);
dark.setColor(QPalette::Button, QColor(53, 53, 53));
dark.setColor(QPalette::ButtonText, Qt::white);
dark.setColor(QPalette::BrightText, Qt::red);
dark.setColor(QPalette::Link, QColor(42, 130, 218));
dark.setColor(QPalette::Highlight, QColor(51,231,247));
dark.setColor(QPalette::HighlightedText, Qt::black);
a.setPalette(dark);
Main_window w;
w.show();
return a.exec();
}
<|endoftext|> |
<commit_before><commit_msg>Fix declaration<commit_after><|endoftext|> |
<commit_before>// MAIN SOURCE
#include <iostream>
#include <fstream>
#include "checker.h"
#include "include/configuration.h"
#include "gflags/gflags.h"
namespace sqlcheck {
Configuration state;
} // namespace sqlcheck
DEFINE_bool(c, false, "Display warnings in color mode");
DEFINE_bool(v, false, "Display verbose warnings");
DEFINE_uint64(r, sqlcheck::RISK_LEVEL_ALL,
"Set of anti-patterns to check \n"
"1 (all anti-patterns, default) \n"
"2 (only medium and high risk anti-patterns) \n"
"3 (only high risk anti-patterns) \n");
DEFINE_string(f, "", "SQL file name"); // standard input
void ConfigureChecker(sqlcheck::Configuration &state) {
// Default Values
state.risk_level = sqlcheck::RISK_LEVEL_ALL;
state.file_name = "";
state.testing_mode = false;
state.verbose = false;
state.color_mode = false;
// Configure checker
state.color_mode = FLAGS_c;
state.verbose = FLAGS_v;
state.file_name = FLAGS_f;
state.risk_level = (sqlcheck::RiskLevel) FLAGS_r;
// Run validators
std::cout << "+-------------------------------------------------+\n"
<< "| SQLCHECK |\n"
<< "+-------------------------------------------------+\n";
ValidateRiskLevel(state);
ValidateFileName(state);
std::cout << "-------------------------------------------------\n";
}
int main(int argc, char **argv) {
try {
// Parse the input arguments from the user
gflags::SetUsageMessage("");
gflags::SetVersionString("1.2");
gflags::ParseCommandLineFlags(&argc, &argv, true);
// Customize the checker configuration
ConfigureChecker(sqlcheck::state);
// Invoke the checker
sqlcheck::Check(sqlcheck::state);
}
// Catching at the top level ensures that
// destructors are always called
catch (std::exception& exc) {
std::cerr << exc.what() << std::endl;
gflags::ShutDownCommandLineFlags();
exit(EXIT_FAILURE);
}
gflags::ShutDownCommandLineFlags();
return (EXIT_SUCCESS);
}
<commit_msg>Updated help message<commit_after>// MAIN SOURCE
#include <iostream>
#include <fstream>
#include "checker.h"
#include "include/configuration.h"
#include "gflags/gflags.h"
namespace sqlcheck {
Configuration state;
} // namespace sqlcheck
DEFINE_bool(c, false, "Display warnings in color mode");
DEFINE_bool(color_mode, false, "Display warnings in color mode");
DEFINE_bool(v, false, "Display verbose warnings");
DEFINE_bool(verbose, false, "Display verbose warnings");
DEFINE_bool(h, false, "Print help message");
DEFINE_uint64(r, sqlcheck::RISK_LEVEL_ALL,
"Set of anti-patterns to check \n"
"1 (all anti-patterns, default) \n"
"2 (only medium and high risk anti-patterns) \n"
"3 (only high risk anti-patterns) \n");
DEFINE_uint64(risk_level, sqlcheck::RISK_LEVEL_ALL,
"Set of anti-patterns to check \n"
"1 (all anti-patterns, default) \n"
"2 (only medium and high risk anti-patterns) \n"
"3 (only high risk anti-patterns) \n");
DEFINE_string(f, "", "SQL file name"); // standard input
DEFINE_string(file_name, "", "SQL file name"); // standard input
void ConfigureChecker(sqlcheck::Configuration &state) {
// Default Values
state.risk_level = sqlcheck::RISK_LEVEL_ALL;
state.file_name = "";
state.testing_mode = false;
state.verbose = false;
state.color_mode = false;
// Configure checker
state.color_mode = FLAGS_c || FLAGS_color_mode;
state.verbose = FLAGS_v || FLAGS_verbose;
if(FLAGS_f.empty() == false){
state.file_name = FLAGS_f;
}
if(FLAGS_file_name.empty() == false){
state.file_name = FLAGS_file_name;
}
if(FLAGS_r != 0){
state.risk_level = (sqlcheck::RiskLevel) FLAGS_r;
}
if(FLAGS_risk_level != 0){
state.risk_level = (sqlcheck::RiskLevel) FLAGS_risk_level;
}
// Run validators
std::cout << "+-------------------------------------------------+\n"
<< "| SQLCHECK |\n"
<< "+-------------------------------------------------+\n";
ValidateRiskLevel(state);
ValidateFileName(state);
std::cout << "-------------------------------------------------\n";
}
void Usage() {
std::cout <<
"Command line options : sqlcheck <options>\n"
" -f -file_name : SQL file name\n"
" -r -risk_level : Set of anti-patterns to check\n"
" : 1 (all anti-patterns, default) \n"
" : 2 (only medium and high risk anti-patterns) \n"
" : 3 (only high risk anti-patterns) \n"
" -c -color_mode : Display warnings in color mode \n"
" -v -verbose : Display verbose warnings \n"
" -h -help : Print help message \n";
exit(EXIT_SUCCESS);
}
int main(int argc, char **argv) {
try {
// Parse the input arguments from the user
gflags::SetUsageMessage("");
gflags::SetVersionString("1.2");
gflags::ParseCommandLineFlags(&argc, &argv, true);
// Print help message
if(FLAGS_h == true){
FLAGS_h = false;
Usage();
gflags::ShutDownCommandLineFlags();
return (EXIT_SUCCESS);
}
// Customize the checker configuration
ConfigureChecker(sqlcheck::state);
// Invoke the checker
sqlcheck::Check(sqlcheck::state);
}
// Catching at the top level ensures that
// destructors are always called
catch (std::exception& exc) {
std::cerr << exc.what() << std::endl;
gflags::ShutDownCommandLineFlags();
exit(EXIT_FAILURE);
}
gflags::ShutDownCommandLineFlags();
return (EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <QListView>
#include <QApplication>
#include <memory>
#include "./window.h"
#include "./scene.h"
#include "./nodes.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"
#include "./mouse_shape_controller.h"
#include "./labeller_context.h"
int main(int argc, char **argv)
{
qputenv("QT_MESSAGE_PATTERN",
QString("%{time [yyyy'-'MM'-'dd' 'hh':'mm':'ss]} - %{threadid} "
"%{if-category}%{category}: %{endif}%{message}").toUtf8());
if (qgetenv("QT_LOGGING_CONF").size() == 0)
qputenv("QT_LOGGING_CONF", "../config/logging.ini");
// QApplication application(argc, argv);
QGuiApplication application(argc, argv);
auto invokeManager = std::shared_ptr<InvokeManager>(new InvokeManager());
auto nodes = std::make_shared<Nodes>();
auto labeller = std::make_shared<Forces::Labeller>();
auto scene = std::make_shared<Scene>(invokeManager, nodes, labeller);
/*
QListView *view = new QListView;
view->setWindowTitle("View onto a string list model");
LabellerContext labellerContext(labeller);
view->setModel(&labellerContext);
view->show();
*/
Window window(scene);
// QQuickView window;
window.rootContext()->setContextProperty("window", &window);
window.rootContext()->setContextProperty("nodes", nodes.get());
LabellerContext labellerContext(labeller);
window.rootContext()->setContextProperty("labeller", &labellerContext);
window.setSource(QUrl("qrc:ui.qml"));
MouseShapeController mouseShapeController(window);
auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"),
invokeManager, signalManager);
invokeManager->addHandler(&window);
invokeManager->addHandler("mouseShape", &mouseShapeController);
signalManager->addSender("KeyboardEventSender", &window);
auto stateMachine = importer.import();
// just for printCurrentState slot for debugging
window.stateMachine = stateMachine;
stateMachine->start();
window.show();
return application.exec();
}
<commit_msg>Remove debugging code.<commit_after>#include <QtGui/QGuiApplication>
#include <QQmlContext>
#include <QStateMachine>
#include <QDebug>
#include <memory>
#include "./window.h"
#include "./scene.h"
#include "./nodes.h"
#include "./input/invoke_manager.h"
#include "./input/signal_manager.h"
#include "./input/scxml_importer.h"
#include "./mouse_shape_controller.h"
#include "./labeller_context.h"
int main(int argc, char **argv)
{
qputenv("QT_MESSAGE_PATTERN",
QString("%{time [yyyy'-'MM'-'dd' 'hh':'mm':'ss]} - %{threadid} "
"%{if-category}%{category}: %{endif}%{message}").toUtf8());
if (qgetenv("QT_LOGGING_CONF").size() == 0)
qputenv("QT_LOGGING_CONF", "../config/logging.ini");
QGuiApplication application(argc, argv);
auto invokeManager = std::shared_ptr<InvokeManager>(new InvokeManager());
auto nodes = std::make_shared<Nodes>();
auto labeller = std::make_shared<Forces::Labeller>();
auto scene = std::make_shared<Scene>(invokeManager, nodes, labeller);
Window window(scene);
window.rootContext()->setContextProperty("window", &window);
window.rootContext()->setContextProperty("nodes", nodes.get());
LabellerContext labellerContext(labeller);
window.rootContext()->setContextProperty("labeller", &labellerContext);
window.setSource(QUrl("qrc:ui.qml"));
MouseShapeController mouseShapeController(window);
auto signalManager = std::shared_ptr<SignalManager>(new SignalManager());
ScxmlImporter importer(QUrl::fromLocalFile("config/states.xml"),
invokeManager, signalManager);
invokeManager->addHandler(&window);
invokeManager->addHandler("mouseShape", &mouseShapeController);
signalManager->addSender("KeyboardEventSender", &window);
auto stateMachine = importer.import();
// just for printCurrentState slot for debugging
window.stateMachine = stateMachine;
stateMachine->start();
window.show();
return application.exec();
}
<|endoftext|> |
<commit_before>#include <cstdio>
#include <string>
#ifdef __APPLE__
#include <OpenGL/glu.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#else
#include "GL/glu.h"
#include "SDL2/SDL.h"
#include "SD2/SDL_opengl.h"
#endif
namespace evil {
static const char* lastError = "";
const char *GetError() {
return lastError;
}
void SetError(const char *error) {
lastError = error;
}
void SetError( const unsigned char* error) {
lastError = (const char*)error;
}
void error(const char *fmt, ... )
{
char buffer[512];
va_list args;
va_start(args, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, args);
va_end(args);
fprintf(stderr, "%s\n", buffer);
}
static SDL_Window *window = nullptr;
static SDL_GLContext context = nullptr;
static bool initGL()
{
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
GLenum error = glGetError();
if( error != GL_NO_ERROR ) {
SetError( gluErrorString(error));
return false;
}
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
error = glGetError();
if( error != GL_NO_ERROR ) {
SetError( gluErrorString(error));
return false;
}
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
error = glGetError();
if( error != GL_NO_ERROR ) {
SetError( gluErrorString(error));
return false;
}
return true;
}
static bool init()
{
if( SDL_Init(SDL_INIT_EVERYTHING ) < 0 ) {
error("SDL init failed: %s", SDL_GetError());
return false;
}
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1);
window = SDL_CreateWindow( "Evil", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );
if( !window ) {
error( "Couldn't create Window: %s", SDL_GetError());
return false;
}
context = SDL_GL_CreateContext( window );
if( !context ) {
error("Couldnt' create GL context: %s", SDL_GetError());
return false;
}
if( SDL_GL_SetSwapInterval(1) < 0 ) {
error("Couldn't set VSYNC: %s", SDL_GetError());
return false;
}
if( !initGL()) {
error("Couldn't initialize OpenGL: %s", GetError());
return false;
}
return true;
}
static void render() {
glClear(GL_COLOR_BUFFER_BIT);
}
static void close() {
if( context ) {
SDL_GL_DeleteContext( context );
context = nullptr;
}
if( window ) {
SDL_DestroyWindow( window );
window = nullptr;
}
SDL_Quit();
}
}
using namespace std;
using namespace evil;
int main(int argc, char** argv)
{
if( !init() ) {
return 1;
}
SDL_StartTextInput();
bool running = true;
while(running) {
SDL_Event e;
while( SDL_PollEvent(&e) ) {
switch( e.type ) {
case SDL_QUIT:
running = false;
break;
case SDL_TEXTINPUT:
// do stuff
break;
}
}
render();
SDL_GL_SwapWindow( window );
}
SDL_StopTextInput();
close();
return 0;
}
<commit_msg>stuff<commit_after>#include <cstdio>
#include <string>
#ifdef __APPLE__
#include <OpenGL/glu.h>
#include <SDL2/SDL.h>
#include <SDL2/SDL_opengl.h>
#else
#include "GL/glu.h"
#include "SDL2/SDL.h"
#include "SDL2/SDL_opengl.h"
#endif
namespace evil {
static const char* lastError = "";
const char *GetError() {
return lastError;
}
void SetError(const char *error) {
lastError = error;
}
void SetError( const unsigned char* error) {
lastError = (const char*)error;
}
void error(const char *fmt, ... )
{
char buffer[512];
va_list args;
va_start(args, fmt);
vsnprintf(buffer, sizeof(buffer), fmt, args);
va_end(args);
fprintf(stderr, "%s\n", buffer);
}
static SDL_Window *window = nullptr;
static SDL_GLContext context = nullptr;
static bool initGL()
{
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
GLenum error = glGetError();
if( error != GL_NO_ERROR ) {
SetError( gluErrorString(error));
return false;
}
glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
error = glGetError();
if( error != GL_NO_ERROR ) {
SetError( gluErrorString(error));
return false;
}
glClearColor( 0.0f, 0.0f, 0.0f, 1.0f );
error = glGetError();
if( error != GL_NO_ERROR ) {
SetError( gluErrorString(error));
return false;
}
return true;
}
static bool init()
{
if( SDL_Init(SDL_INIT_EVERYTHING ) < 0 ) {
error("SDL init failed: %s", SDL_GetError());
return false;
}
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 1);
window = SDL_CreateWindow( "Evil", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN );
if( !window ) {
error( "Couldn't create Window: %s", SDL_GetError());
return false;
}
context = SDL_GL_CreateContext( window );
if( !context ) {
error("Couldnt' create GL context: %s", SDL_GetError());
return false;
}
if( SDL_GL_SetSwapInterval(1) < 0 ) {
error("Couldn't set VSYNC: %s", SDL_GetError());
return false;
}
if( !initGL()) {
error("Couldn't initialize OpenGL: %s", GetError());
return false;
}
return true;
}
static void render() {
glClear(GL_COLOR_BUFFER_BIT);
}
static void close() {
if( context ) {
SDL_GL_DeleteContext( context );
context = nullptr;
}
if( window ) {
SDL_DestroyWindow( window );
window = nullptr;
}
SDL_Quit();
}
}
using namespace std;
using namespace evil;
int main(int argc, char** argv)
{
if( !init() ) {
return 1;
}
SDL_StartTextInput();
bool running = true;
while(running) {
SDL_Event e;
while( SDL_PollEvent(&e) ) {
switch( e.type ) {
case SDL_QUIT:
running = false;
break;
case SDL_TEXTINPUT:
// do stuff
break;
}
}
render();
SDL_GL_SwapWindow( window );
}
SDL_StopTextInput();
close();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Worldvisions Weaver Software:
* Copyright (C) 1997-2003 Net Integration Technologies, Inc.
*
* WvDial configuration utility. Generates a basic wvdial.conf file.
*/
#include "wvmodemscan.h"
#include "wvfile.h"
#include "wvconf.h"
#include <ctype.h>
void check_ppp_options()
{
WvFile file("/etc/ppp/options", O_RDONLY);
char *line;
while ((line = file.getline(0)) != NULL)
{
line = trim_string(line);
// comments and blank lines are ignored
if (line[0] == '#' || !line[0])
continue;
// IP addresses are allowed
if (strchr(line, '.') || strchr(line, ':'))
continue;
// but baud rates and tty names are not!
// a 'connect' line is usually bad too.
if (isdigit(line[0])
|| !strncmp(line, "/dev", 4)
|| !strncmp(line, "tty", 3)
|| !strncmp(line, "cua", 3)
|| !strncmp(line, "connect", 7))
{
wvcon->print("\n*** WARNING! Line \"%s\"\n"
" in /etc/ppp/options may conflict with wvdial!\n\n", line);
}
}
}
int main(int argc, char **argv)
{
#if DEBUG
free(malloc(1)); // for electric fence
#endif
if (argc != 2 || argv[1][0]=='-')
{
wvcon->print("Usage: %s <configfile-name>\n"
"\t(create/update a wvdial.conf file automatically)\n",
argv[0]);
return 1;
}
wvcon->print("Scanning your serial ports for a modem.\n\n");
WvModemScanList l;
while (!l.isdone())
l.execute();
if (l.count() < 1)
{
wvcon->print("\n\n"
"Sorry, no modem was detected! "
"Is it in use by another program?\n"
"Did you configure it properly with setserial?\n\n"
"Please read the FAQ at http://open.nit.ca/wvdial/\n\n"
"If you still have problems, send mail to "
"[email protected].\n");
return 1;
}
WvModemScanList::Iter i(l);
i.rewind(); i.next();
WvModemScan &m = *i;
WvString fn = m.filename(), init = m.initstr();
wvcon->print("\nFound %s on %s",
m.is_isdn() ? "an ISDN TA" :
strncmp("/dev/ttyACM",fn,11) ? "a modem" : "an USB modem", (const char *)fn);
if (m.use_modem_link) {
wvcon->print(", using link /dev/modem in config.\n");
fn = "/dev/modem";
} else {
wvcon->print(".\n");
}
WvConf cfg(argv[1],0660); // Create it read/write owner and group only
static char s[]="Dialer Defaults";
cfg.set(s, "Modem", fn);
cfg.setint(s, "Baud", m.maxbaud());
cfg.set(s, "Init1", m.is_isdn() ? "AT&F" : "ATZ");
cfg.set(s, "Init2", init);
cfg.set(s, "ISDN", m.use_default_asyncmap() ? "1" : "0");
cfg.set(s, "Modem Name", m.modem_name ? (const char *)m.modem_name : "");
cfg.set(s, "Modem Type", m.is_isdn() ? "ISDN Terminal Adapter" :
strncmp("/dev/ttyACM",fn,11) ? "Analog Modem" : "USB Modem");
if (m.modem_name)
wvcon->print("Config for %s written to %s.\n", (const char *)m.modem_name, argv[1]);
else
wvcon->print("Modem configuration written to %s.\n", argv[1]);
// insert some entries to let people know what they need to edit
if (!cfg.get(s, "Phone"))
cfg.set(s, "; Phone", "<Target Phone Number>");
if (!cfg.get(s, "Username"))
cfg.set(s, "; Username", "<Your Login Name>");
if (!cfg.get(s, "Password"))
cfg.set(s, "; Password", "<Your Password>");
check_ppp_options();
return 0;
}
<commit_msg>Removed the mixing of WvConfEmu and WvConf in WvDial.<commit_after>/*
* Worldvisions Weaver Software:
* Copyright (C) 1997-2003 Net Integration Technologies, Inc.
*
* WvDial configuration utility. Generates a basic wvdial.conf file.
*/
#include "uniconfroot.h"
#include "wvconfemu.h"
#include "wvfile.h"
#include "wvmodemscan.h"
#include "wvstrutils.h"
#include <ctype.h>
void check_ppp_options()
{
WvFile file("/etc/ppp/options", O_RDONLY);
char *line;
while ((line = file.getline(0)) != NULL)
{
line = trim_string(line);
// comments and blank lines are ignored
if (line[0] == '#' || !line[0])
continue;
// IP addresses are allowed
if (strchr(line, '.') || strchr(line, ':'))
continue;
// but baud rates and tty names are not!
// a 'connect' line is usually bad too.
if (isdigit(line[0])
|| !strncmp(line, "/dev", 4)
|| !strncmp(line, "tty", 3)
|| !strncmp(line, "cua", 3)
|| !strncmp(line, "connect", 7))
{
wvcon->print("\n*** WARNING! Line \"%s\"\n"
" in /etc/ppp/options may conflict with wvdial!\n\n", line);
}
}
}
int main(int argc, char **argv)
{
#if DEBUG
free(malloc(1)); // for electric fence
#endif
if (argc != 2 || argv[1][0]=='-')
{
wvcon->print("Usage: %s <configfile-name>\n"
"\t(create/update a wvdial.conf file automatically)\n",
argv[0]);
return 1;
}
wvcon->print("Scanning your serial ports for a modem.\n\n");
WvModemScanList l;
while (!l.isdone())
l.execute();
if (l.count() < 1)
{
wvcon->print("\n\n"
"Sorry, no modem was detected! "
"Is it in use by another program?\n"
"Did you configure it properly with setserial?\n\n"
"Please read the FAQ at http://open.nit.ca/wvdial/\n\n"
"If you still have problems, send mail to "
"[email protected].\n");
return 1;
}
WvModemScanList::Iter i(l);
i.rewind(); i.next();
WvModemScan &m = *i;
WvString fn = m.filename(), init = m.initstr();
wvcon->print("\nFound %s on %s",
m.is_isdn() ? "an ISDN TA" :
strncmp("/dev/ttyACM",fn,11) ? "a modem" : "an USB modem", (const char *)fn);
if (m.use_modem_link) {
wvcon->print(", using link /dev/modem in config.\n");
fn = "/dev/modem";
} else {
wvcon->print(".\n");
}
UniConfRoot uni(WvString("ini:%s", argv[1]), 0660);
WvConfEmu cfg(uni); // Create it read/write owner and group only
static char s[]="Dialer Defaults";
cfg.set(s, "Modem", fn);
cfg.setint(s, "Baud", m.maxbaud());
cfg.set(s, "Init1", m.is_isdn() ? "AT&F" : "ATZ");
cfg.set(s, "Init2", init);
cfg.set(s, "ISDN", m.use_default_asyncmap() ? "1" : "0");
cfg.set(s, "Modem Name", m.modem_name ? (const char *)m.modem_name : "");
cfg.set(s, "Modem Type", m.is_isdn() ? "ISDN Terminal Adapter" :
strncmp("/dev/ttyACM",fn,11) ? "Analog Modem" : "USB Modem");
if (m.modem_name)
wvcon->print("Config for %s written to %s.\n", (const char *)m.modem_name, argv[1]);
else
wvcon->print("Modem configuration written to %s.\n", argv[1]);
// insert some entries to let people know what they need to edit
if (!cfg.get(s, "Phone"))
cfg.set(s, "; Phone", "<Target Phone Number>");
if (!cfg.get(s, "Username"))
cfg.set(s, "; Username", "<Your Login Name>");
if (!cfg.get(s, "Password"))
cfg.set(s, "; Password", "<Your Password>");
check_ppp_options();
return 0;
}
<|endoftext|> |
<commit_before>//
// DIYSeqEngine.cpp
// AudioKit
//
// Created by Jeff Cooper on 1/25/19.
// Copyright © 2019 AudioKit. All rights reserved.
//
#include <stdio.h>
#pragma once
#import "AKSoundpipeKernel.hpp"
#define NOTEON 0x90
#define NOTEOFF 0x80
#define INITVALUE -1.0
#define MIDINOTECOUNT 128
struct MIDIEvent {
uint8_t status;
uint8_t data1;
uint8_t data2;
double beat;
double duration;
};
struct MIDINote {
struct MIDIEvent noteOn;
struct MIDIEvent noteOff;
};
enum {
startPointAddress = 0,
};
class AKDIYSeqEngineDSPKernel : public AKSoundpipeKernel, public AKOutputBuffered {
public:
// MARK: Member Functions
AKDIYSeqEngineDSPKernel() {}
void init(int channelCount, double sampleRate) override {
printf("deboog: inited diyseqengine\n");
AKSoundpipeKernel::init(channelCount, sampleRate);
}
void setTargetAU(AudioUnit target) {
targetAU = target;
}
void start() {
resetPlaybackVariables();
started = true;
isPlaying = true;
}
// void playFrom(double beat) {
// int position = beat;
// }
void stop() {
printf("deboog: stopped diyseqengine\n");
started = false;
isPlaying = false;
}
void reset() {
printf("deboog: resetted diyseqengine\n");
resetted = true;
startPointRamper.reset();
}
void destroy() {
AKSoundpipeKernel::destroy();
}
void setStartPoint(float value) {
startPoint = value;
}
void setParameter(AUParameterAddress address, AUValue value) {
switch (address) {
case startPointAddress:
startPointRamper.setUIValue(clamp(value, 0.0f, 10.0f));
break;
}
}
AUValue getParameter(AUParameterAddress address) {
switch (address) {
case startPointAddress:
return startPointRamper.getUIValue();
default: return 0.0f;
}
}
void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
switch (address) {
case startPointAddress:
startPointRamper.startRamp(clamp(value, 0.0f, 10.0f), duration);
break;
}
}
void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
if (isPlaying) {
if (positionInSamples >= lengthInSamples()){
if (loopEnabled) {
positionInSamples = 0;
} else {
printf("deboog: seq finished %i \n", lengthInSamples());
stop();
return;
}
}
UInt64 currentStartSample = positionModulo();
UInt64 currentEndSample = currentStartSample + frameCount;
for (int i = 0; i < eventCount; i++) {
int triggerTime = beatToSamples(events[i].beat);
if ((currentStartSample <= triggerTime && triggerTime < currentEndSample)
&& stopAfterCurrentNotes == false) {
int offset = (int)(triggerTime - currentStartSample);
sendMidiData(events[i].status, events[i].data1, events[i].data2,
offset, events[i].beat);
//printf("deboog event %i will fire at %i offset %i \n", i, triggerTime, offset);
}
// if (((startSample <= triggerTime && triggerTime <= endSample)) && *stopAfterCurrentNotes == false)
// {
// int time = triggerTime - startSample + offset;
// if (self->_eventCallback != NULL) {
// self->_eventCallback(events[i].status, events[i].data1, events[i].data2);
// }
// }
}
positionInSamples += frameCount;
}
framesCounted += frameCount;
}
int addMIDIEvent(uint8_t status, uint8_t data1, uint8_t data2, double beat) {
events[eventCount].status = status;
events[eventCount].data1 = data1;
events[eventCount].data2 = data2;
events[eventCount].beat = beat;
eventCount += 1;
return eventCount;
}
private:
void sendMidiData(UInt8 status, UInt8 data1, UInt8 data2, double offset, double time) {
// printf("deboog: sending: %i %i at %f\n", status, data1, time);
if (midiPort == 0 || midiEndpoint == 0) {
MusicDeviceMIDIEvent(targetAU, status, data1, data2, offset);
} else {
MIDIPacketList packetList;
packetList.numPackets = 1;
MIDIPacket* firstPacket = &packetList.packet[0];
firstPacket->length = 3;
firstPacket->data[0] = status;
firstPacket->data[1] = data1;
firstPacket->data[2] = data2;
firstPacket->timeStamp = offset;
MIDISend(midiPort, midiEndpoint, &packetList);
}
}
int lengthInSamples() {
return beatToSamples(lengthInBeats);
}
void resetPlaybackVariables() {
positionInSamples = 0;
}
int beatToSamples(double beat) {
return (int)(beat / bpm * 60 * sampleRate);
}
int positionModulo() {
return positionInSamples % lengthInSamples();
}
bool validTriggerTime(double beat){
return true;
}
private:
float startPoint = 0;
AudioUnit targetAU;
UInt64 framesCounted = 0;
UInt64 positionInSamples = 0;
public:
bool started = false;
bool resetted = false;
ParameterRamper startPointRamper = 1;
bool isPlaying = false;
MIDIPortRef midiPort;
MIDIEndpointRef midiEndpoint;
AKCCallback loopCallback = nullptr;
MIDIEvent events[512];
int eventCount = 0;
double lengthInBeats = 4.0;
double bpm = 120.0;
bool stopAfterCurrentNotes = false;
bool loopEnabled = true;
};
<commit_msg>remove aksoundpipekernel<commit_after>//
// DIYSeqEngine.cpp
// AudioKit
//
// Created by Jeff Cooper on 1/25/19.
// Copyright © 2019 AudioKit. All rights reserved.
//
#include <stdio.h>
#pragma once
#define NOTEON 0x90
#define NOTEOFF 0x80
#define INITVALUE -1.0
#define MIDINOTECOUNT 128
struct MIDIEvent {
uint8_t status;
uint8_t data1;
uint8_t data2;
double beat;
double duration;
};
struct MIDINote {
struct MIDIEvent noteOn;
struct MIDIEvent noteOff;
};
enum {
startPointAddress = 0,
};
class AKDIYSeqEngineDSPKernel : public AKDSPKernel, public AKOutputBuffered {
public:
// MARK: Member Functions
AKDIYSeqEngineDSPKernel() {}
void init(int channelCount, double sampleRate) override {
printf("deboog: inited diyseqengine\n");
}
void setTargetAU(AudioUnit target) {
targetAU = target;
}
void start() {
resetPlaybackVariables();
started = true;
isPlaying = true;
}
// void playFrom(double beat) {
// int position = beat;
// }
void stop() {
printf("deboog: stopped diyseqengine\n");
started = false;
isPlaying = false;
}
void reset() {
printf("deboog: resetted diyseqengine\n");
resetted = true;
startPointRamper.reset();
}
void destroy() {
}
void setStartPoint(float value) {
startPoint = value;
}
void setParameter(AUParameterAddress address, AUValue value) {
switch (address) {
case startPointAddress:
startPointRamper.setUIValue(clamp(value, 0.0f, 10.0f));
break;
}
}
AUValue getParameter(AUParameterAddress address) {
switch (address) {
case startPointAddress:
return startPointRamper.getUIValue();
default: return 0.0f;
}
}
void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
switch (address) {
case startPointAddress:
startPointRamper.startRamp(clamp(value, 0.0f, 10.0f), duration);
break;
}
}
void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
if (isPlaying) {
if (positionInSamples >= lengthInSamples()){
if (loopEnabled) {
positionInSamples = 0;
} else {
printf("deboog: seq finished %i \n", lengthInSamples());
stop();
return;
}
}
UInt64 currentStartSample = positionModulo();
UInt64 currentEndSample = currentStartSample + frameCount;
for (int i = 0; i < eventCount; i++) {
int triggerTime = beatToSamples(events[i].beat);
if ((currentStartSample <= triggerTime && triggerTime < currentEndSample)
&& stopAfterCurrentNotes == false) {
int offset = (int)(triggerTime - currentStartSample);
sendMidiData(events[i].status, events[i].data1, events[i].data2,
offset, events[i].beat);
//printf("deboog event %i will fire at %i offset %i \n", i, triggerTime, offset);
}
// if (((startSample <= triggerTime && triggerTime <= endSample)) && *stopAfterCurrentNotes == false)
// {
// int time = triggerTime - startSample + offset;
// if (self->_eventCallback != NULL) {
// self->_eventCallback(events[i].status, events[i].data1, events[i].data2);
// }
// }
}
positionInSamples += frameCount;
}
framesCounted += frameCount;
}
int addMIDIEvent(uint8_t status, uint8_t data1, uint8_t data2, double beat) {
events[eventCount].status = status;
events[eventCount].data1 = data1;
events[eventCount].data2 = data2;
events[eventCount].beat = beat;
eventCount += 1;
return eventCount;
}
private:
void sendMidiData(UInt8 status, UInt8 data1, UInt8 data2, double offset, double time) {
// printf("deboog: sending: %i %i at %f\n", status, data1, time);
if (midiPort == 0 || midiEndpoint == 0) {
MusicDeviceMIDIEvent(targetAU, status, data1, data2, offset);
} else {
MIDIPacketList packetList;
packetList.numPackets = 1;
MIDIPacket* firstPacket = &packetList.packet[0];
firstPacket->length = 3;
firstPacket->data[0] = status;
firstPacket->data[1] = data1;
firstPacket->data[2] = data2;
firstPacket->timeStamp = offset;
MIDISend(midiPort, midiEndpoint, &packetList);
}
}
int lengthInSamples() {
return beatToSamples(lengthInBeats);
}
void resetPlaybackVariables() {
positionInSamples = 0;
}
int beatToSamples(double beat) {
return (int)(beat / bpm * 60 * sampleRate);
}
int positionModulo() {
return positionInSamples % lengthInSamples();
}
bool validTriggerTime(double beat){
return true;
}
private:
float startPoint = 0;
AudioUnit targetAU;
UInt64 framesCounted = 0;
UInt64 positionInSamples = 0;
public:
bool started = false;
bool resetted = false;
ParameterRamper startPointRamper = 1;
bool isPlaying = false;
MIDIPortRef midiPort;
MIDIEndpointRef midiEndpoint;
AKCCallback loopCallback = nullptr;
MIDIEvent events[512];
int eventCount = 0;
double lengthInBeats = 4.0;
double bpm = 120.0;
bool stopAfterCurrentNotes = false;
bool loopEnabled = true;
};
<|endoftext|> |
<commit_before><commit_msg>coverity#735764 Unchecked dynamic_cast<commit_after><|endoftext|> |
<commit_before>#include <EXTERN.h> // from the Perl distribution
#include <perl.h> // from the Perl distribution
#ifdef WIN32
// Perl win32 specific includes, found in perl\\lib\\CORE\\win32.h
// Defines the windows specific convenience RunPerl() function,
// which is not available on other operating systems.
#include <win32.h>
#include <wchar.h>
#endif
#include <cstdio>
#include <cstdlib>
#ifdef WIN32
int main(int argc, char **argv, char **env)
{
SetCurrentDirectory("libexec");
// If the Slic3r is installed in a localized directory (containing non-iso
// characters), spaces or semicolons, use short file names.
char exe_path[MAX_PATH] = {0};
char script_path[MAX_PATH];
char gui_flag[6] = {"--gui"};
#ifdef FORCE_GUI
char** command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 2));
#else
char** command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 1));
#endif
{
// Unicode path. This will not be used directly, but to test, whether
// there are any non-ISO characters, in which case the path is converted to a
// short path (using 8.3 directory names).
wchar_t exe_path_w[MAX_PATH] = {0};
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
bool needs_short_paths = false;
int len;
int i;
GetModuleFileNameA(NULL, exe_path, MAX_PATH-1);
GetModuleFileNameW(NULL, exe_path_w, MAX_PATH-1);
len = strlen(exe_path);
if (len != wcslen(exe_path_w)) {
needs_short_paths = true;
} else {
for (i = 0; i < len; ++ i)
if ((wchar_t)exe_path[i] != exe_path_w[i] || exe_path[i] == ' ' ||
exe_path[i] == ';') {
needs_short_paths = true;
break;
}
}
if (needs_short_paths) {
wchar_t exe_path_short[MAX_PATH] = {0};
GetShortPathNameW(exe_path_w, exe_path_short, MAX_PATH);
len = wcslen(exe_path_short);
for (i = 0; i <= len; ++ i)
exe_path[i] = (char)exe_path_short[i];
}
_splitpath(exe_path, drive, dir, fname, ext);
_makepath(script_path, drive, dir, NULL, NULL);
if (needs_short_paths)
printf("Slic3r installed in a loclized path. Using an 8.3 path: \"%s\"\n",
script_path);
SetDllDirectoryA(script_path);
strcat(dir, "libexec\\");
_makepath(script_path, drive, dir, "slic3r", "pl");
command_line[0] = exe_path;
command_line[1] = script_path;
memcpy(command_line + 2, argv + 1, sizeof(char*) * (argc - 2));
#ifdef FORCE_GUI
command_line[argc] = gui_flag;
command_line[argc+1] = NULL;
#else
command_line[argc] = NULL;
#endif
// Unset the PERL5LIB and PERLLIB environment variables.
SetEnvironmentVariable("PERL5LIB", NULL);
SetEnvironmentVariable("PERLLIB", NULL);
#if 0
printf("Arguments: \r\n");
for (size_t i = 0; i < argc + 1; ++ i)
printf(" %d: %s\r\n", i, command_line[i]);
#endif
}
#ifdef FORCE_GUI
RunPerl(argc+1, command_line, NULL);
#else
RunPerl(argc, command_line, NULL);
#endif
free(command_line);
}
#else
int main(int argc, char **argv, char **env)
{
PerlInterpreter *my_perl = perl_alloc();
if (my_perl == NULL) {
fprintf(stderr, "Cannot start perl interpreter. Exiting.\n");
return -1;
}
perl_construct(my_perl);
#ifdef FORCE_GUI
char* command_line[] = { "slic3r", "slic3r.pl", "--gui" };
#else
char* command_line[] = { "slic3r", "slic3r.pl" };
#endif
perl_parse(my_perl, NULL, 3, command_line, (char **)NULL);
perl_run(my_perl);
perl_destruct(my_perl);
perl_free(my_perl);
}
#endif
<commit_msg>Revert "Append libexec to the slic3r.pl path"<commit_after>#include <EXTERN.h> // from the Perl distribution
#include <perl.h> // from the Perl distribution
#ifdef WIN32
// Perl win32 specific includes, found in perl\\lib\\CORE\\win32.h
// Defines the windows specific convenience RunPerl() function,
// which is not available on other operating systems.
#include <win32.h>
#include <wchar.h>
#endif
#include <cstdio>
#include <cstdlib>
#ifdef WIN32
int main(int argc, char **argv, char **env)
{
SetCurrentDirectory("libexec");
// If the Slic3r is installed in a localized directory (containing non-iso
// characters), spaces or semicolons, use short file names.
char exe_path[MAX_PATH] = {0};
char script_path[MAX_PATH];
char gui_flag[6] = {"--gui"};
#ifdef FORCE_GUI
char** command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 2));
#else
char** command_line = (char**)malloc(sizeof(char*) * ((++ argc) + 1));
#endif
{
// Unicode path. This will not be used directly, but to test, whether
// there are any non-ISO characters, in which case the path is converted to a
// short path (using 8.3 directory names).
wchar_t exe_path_w[MAX_PATH] = {0};
char drive[_MAX_DRIVE];
char dir[_MAX_DIR];
char fname[_MAX_FNAME];
char ext[_MAX_EXT];
bool needs_short_paths = false;
int len;
int i;
GetModuleFileNameA(NULL, exe_path, MAX_PATH-1);
GetModuleFileNameW(NULL, exe_path_w, MAX_PATH-1);
len = strlen(exe_path);
if (len != wcslen(exe_path_w)) {
needs_short_paths = true;
} else {
for (i = 0; i < len; ++ i)
if ((wchar_t)exe_path[i] != exe_path_w[i] || exe_path[i] == ' ' ||
exe_path[i] == ';') {
needs_short_paths = true;
break;
}
}
if (needs_short_paths) {
wchar_t exe_path_short[MAX_PATH] = {0};
GetShortPathNameW(exe_path_w, exe_path_short, MAX_PATH);
len = wcslen(exe_path_short);
for (i = 0; i <= len; ++ i)
exe_path[i] = (char)exe_path_short[i];
}
_splitpath(exe_path, drive, dir, fname, ext);
_makepath(script_path, drive, dir, NULL, NULL);
if (needs_short_paths)
printf("Slic3r installed in a loclized path. Using an 8.3 path: \"%s\"\n",
script_path);
SetDllDirectoryA(script_path);
_makepath(script_path, drive, dir, "slic3r", "pl");
command_line[0] = exe_path;
command_line[1] = script_path;
memcpy(command_line + 2, argv + 1, sizeof(char*) * (argc - 2));
#ifdef FORCE_GUI
command_line[argc] = gui_flag;
command_line[argc+1] = NULL;
#else
command_line[argc] = NULL;
#endif
// Unset the PERL5LIB and PERLLIB environment variables.
SetEnvironmentVariable("PERL5LIB", NULL);
SetEnvironmentVariable("PERLLIB", NULL);
#if 0
printf("Arguments: \r\n");
for (size_t i = 0; i < argc + 1; ++ i)
printf(" %d: %s\r\n", i, command_line[i]);
#endif
}
#ifdef FORCE_GUI
RunPerl(argc+1, command_line, NULL);
#else
RunPerl(argc, command_line, NULL);
#endif
free(command_line);
}
#else
int main(int argc, char **argv, char **env)
{
PerlInterpreter *my_perl = perl_alloc();
if (my_perl == NULL) {
fprintf(stderr, "Cannot start perl interpreter. Exiting.\n");
return -1;
}
perl_construct(my_perl);
#ifdef FORCE_GUI
char* command_line[] = { "slic3r", "slic3r.pl", "--gui" };
#else
char* command_line[] = { "slic3r", "slic3r.pl" };
#endif
perl_parse(my_perl, NULL, 3, command_line, (char **)NULL);
perl_run(my_perl);
perl_destruct(my_perl);
perl_free(my_perl);
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuarea.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2005-12-14 16:54:33 $
*
* 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
*
************************************************************************/
#pragma hdrstop
#include "fuarea.hxx"
#include <svx/svxids.hrc>
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "drawdoc.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "app.hrc"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
namespace sd {
TYPEINIT1( FuArea, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuArea::FuArea( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuArea::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuArea( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuArea::DoExecute( SfxRequest& rReq )
{
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
// erst einmal alle eingabeparameter fuer den dialog retten
SfxItemSet aInputAttr( pDoc->GetPool() );
pView->GetAttributes( aInputAttr );
const XFillStyleItem &rIFillStyleItem = (const XFillStyleItem &) aInputAttr.Get (XATTR_FILLSTYLE);
const XFillColorItem &rIFillColorItem = (const XFillColorItem &) aInputAttr.Get (XATTR_FILLCOLOR);
const XFillGradientItem &rIFillGradientItem = (const XFillGradientItem &) aInputAttr.Get (XATTR_FILLGRADIENT);
const XFillHatchItem &rIFillHatchItem = (const XFillHatchItem &) aInputAttr.Get (XATTR_FILLHATCH);
const XFillBitmapItem &rIXFillBitmapItem = (const XFillBitmapItem &) aInputAttr.Get (XATTR_FILLBITMAP);
SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
pView->GetAttributes( *pNewAttr );
//CHINA001 SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, pNewAttr, pDoc, pView );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
AbstractSvxAreaTabDialog * pDlg = pFact->CreateSvxAreaTabDialog( NULL,
pNewAttr,
pDoc,
ResId(RID_SVXDLG_AREA),
pView);
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
if ( pDlg->Execute() == RET_OK )
{
pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
}
// Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
static USHORT SidArray[] = {
SID_ATTR_FILL_STYLE,
SID_ATTR_FILL_COLOR,
SID_ATTR_FILL_GRADIENT,
SID_ATTR_FILL_HATCH,
SID_ATTR_FILL_BITMAP,
0 };
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
delete pDlg;
delete pNewAttr;
}
rReq.Ignore ();
}
void FuArea::Activate()
{
}
void FuArea::Deactivate()
{
}
} // end of namespace sd
<commit_msg>INTEGRATION: CWS pchfix02 (1.6.214); FILE MERGED 2006/09/01 17:37:04 kaib 1.6.214.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: fuarea.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2006-09-16 18:46: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_sd.hxx"
#include "fuarea.hxx"
#include <svx/svxids.hrc>
#ifndef _SVX_TAB_AREA_HXX //autogen
#include <svx/tabarea.hxx>
#endif
#ifndef _SV_MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#ifndef _SFXINTITEM_HXX //autogen
#include <svtools/intitem.hxx>
#endif
#ifndef _SFXSTRITEM_HXX //autogen
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXREQUEST_HXX //autogen
#include <sfx2/request.hxx>
#endif
#ifndef _SFXVIEWFRM_HXX
#include <sfx2/viewfrm.hxx>
#endif
#ifndef _SFX_BINDINGS_HXX //autogen
#include <sfx2/bindings.hxx>
#endif
#ifndef SD_VIEW_SHELL_HXX
#include "ViewShell.hxx"
#endif
#include "drawdoc.hxx"
#ifndef SD_VIEW_HXX
#include "View.hxx"
#endif
#ifndef SD_WINDOW_HXX
#include "Window.hxx"
#endif
#include "app.hrc"
#include <svx/svxdlg.hxx> //CHINA001
#include <svx/dialogs.hrc> //CHINA001
namespace sd {
TYPEINIT1( FuArea, FuPoor );
/*************************************************************************
|*
|* Konstruktor
|*
\************************************************************************/
FuArea::FuArea( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq)
: FuPoor(pViewSh, pWin, pView, pDoc, rReq)
{
}
FunctionReference FuArea::Create( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq )
{
FunctionReference xFunc( new FuArea( pViewSh, pWin, pView, pDoc, rReq ) );
xFunc->DoExecute(rReq);
return xFunc;
}
void FuArea::DoExecute( SfxRequest& rReq )
{
const SfxItemSet* pArgs = rReq.GetArgs();
if( !pArgs )
{
// erst einmal alle eingabeparameter fuer den dialog retten
SfxItemSet aInputAttr( pDoc->GetPool() );
pView->GetAttributes( aInputAttr );
const XFillStyleItem &rIFillStyleItem = (const XFillStyleItem &) aInputAttr.Get (XATTR_FILLSTYLE);
const XFillColorItem &rIFillColorItem = (const XFillColorItem &) aInputAttr.Get (XATTR_FILLCOLOR);
const XFillGradientItem &rIFillGradientItem = (const XFillGradientItem &) aInputAttr.Get (XATTR_FILLGRADIENT);
const XFillHatchItem &rIFillHatchItem = (const XFillHatchItem &) aInputAttr.Get (XATTR_FILLHATCH);
const XFillBitmapItem &rIXFillBitmapItem = (const XFillBitmapItem &) aInputAttr.Get (XATTR_FILLBITMAP);
SfxItemSet* pNewAttr = new SfxItemSet( pDoc->GetPool() );
pView->GetAttributes( *pNewAttr );
//CHINA001 SvxAreaTabDialog* pDlg = new SvxAreaTabDialog( NULL, pNewAttr, pDoc, pView );
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "Dialogdiet Factory fail!");//CHINA001
AbstractSvxAreaTabDialog * pDlg = pFact->CreateSvxAreaTabDialog( NULL,
pNewAttr,
pDoc,
ResId(RID_SVXDLG_AREA),
pView);
DBG_ASSERT(pDlg, "Dialogdiet fail!");//CHINA001
if ( pDlg->Execute() == RET_OK )
{
pView->SetAttributes (*(pDlg->GetOutputItemSet ()));
}
// Attribute wurden geaendert, Listboxes in Objectbars muessen aktualisiert werden
static USHORT SidArray[] = {
SID_ATTR_FILL_STYLE,
SID_ATTR_FILL_COLOR,
SID_ATTR_FILL_GRADIENT,
SID_ATTR_FILL_HATCH,
SID_ATTR_FILL_BITMAP,
0 };
pViewShell->GetViewFrame()->GetBindings().Invalidate( SidArray );
delete pDlg;
delete pNewAttr;
}
rReq.Ignore ();
}
void FuArea::Activate()
{
}
void FuArea::Deactivate()
{
}
} // end of namespace sd
<|endoftext|> |
<commit_before>#include <stdexcept>
#include <limits>
#include <algorithm>
#include <array>
#include <memory>
#include <iomanip>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/
#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif
#if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H)
#include "win_error_string.hpp"
#endif
const std::string version("0.1.0");
const std::string listing("http://nwn.efupw.com/rootdir/index.dat");
const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/");
const std::string file_checksum(const std::string &path);
std::vector<std::string> &split(const std::string &s, char delim,
std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim)
{
std::vector<std::string> elems;
return split(s, delim, elems);
}
void make_dir(const std::string &path)
{
#ifdef _WIN32
unsigned file_start = path.find_last_of("/\\");
if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr))
{
WinErrorString wes;
if (wes.code() != ERROR_ALREADY_EXISTS)
{
throw std::ios_base::failure("sdf" + wes.str());
}
}
#else
auto elems = split(path, '/');
std::string descend;
for (size_t i = 0, k = elems.size() - 1; i < k; ++i)
{
const std::string &s(elems[i]);
if (s.size() && s != ".")
{
descend.append((i > 0 ? "/" : "") + s);
auto status = mkdir(descend.c_str(), S_IRWXU);
if (status == -1)
{
std::error_code err(errno, std::generic_category());
if (err != std::errc::file_exists)
{
std::cout << "error making dir: "
<< descend << ": "
<< err.message() << std::endl;
}
}
}
}
#endif
}
// TODO
#ifdef CPP11_ENUM_CLASS
#define ENUM_CLASS enum class
#else
#define ENUM_CLASS enum
#endif
class Target
{
public:
ENUM_CLASS Status {
Nonexistent,
Outdated,
Current
};
explicit Target(const std::string &name, const std::string &checksum):
m_name(name.find_first_of('/') == std::string::npos ? name :
name, name.find_first_of('/') + 1, name.size() - 1),
m_checksum(checksum)
{}
std::string name() const { return m_name; }
const std::string checksum() const { return m_checksum; }
void fetch()
{
std::cout << "Statting target " << name() << "...";
std::fstream fs(name(), std::ios_base::in);
if (!fs.good())
{
fs.close();
std::cout << " doesn't exist, creating new." << std::endl;
make_dir(name());
fs.open(name(), std::ios_base::out);
if (!fs.good())
{
fs.close();
std::cout << "Failed to create file: " << name() << std::endl;
}
else
{
fs.close();
do_fetch();
return;
}
}
if (fs.good())
{
fs.close();
if (status() == Status::Current)
{
std::cout << " already up to date." << std::endl;
}
else
{
std::cout << " outdated, downloading new." << std::endl;
do_fetch();
}
}
}
Status status()
{
std::ifstream is(name());
if (!is.good())
{
return Status::Nonexistent;
}
is.close();
auto calcsum(file_checksum(name()));
if (calcsum == checksum())
{
return Status::Current;
}
else
{
return Status::Outdated;
}
}
private:
void do_fetch()
{
std::ofstream ofs(name(), std::ios::binary);
if (ofs.good())
{
std::string s;
std::string url(patch_dir + name());
CurlEasy curl(url);
curl.write_to(s);
curl.progressbar(true);
curl.perform();
ofs << s;
ofs.close();
std::cout << "Finished downloading " << name() << std::endl;
}
else
{
std::cout << "Couldn't write to " << name() << std::endl;
}
}
std::string m_name;
std::string m_checksum;
};
std::ostream& operator<<(std::ostream &os, const Target &t)
{
return os << "name: " << t.name() << ", checksum: " << t.checksum();
}
const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
auto md = EVP_md5();
const int md_len = MD5_DIGEST_LENGTH;
#else
auto md = EVP_sha1();
const int md_len = SHA_DIGEST_LENGTH;
#endif
std::array<unsigned char, md_len> result;
EVP_MD_CTX *mdctx = nullptr;
std::ifstream is(path, std::ios::binary);
if (!is.good())
{
std::cout << "Couldn't open file " << path
<< " for checksumming." << std::endl;
return std::string();
}
const int length = 8192;
std::array<unsigned char, length> buffer;
auto buf = reinterpret_cast<char *>(buffer.data());
mdctx = EVP_MD_CTX_create();
int status = EVP_DigestInit_ex(mdctx, md, nullptr);
while (status && is)
{
is.read(buf, length);
status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount());
}
status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
EVP_MD_CTX_destroy(mdctx);
std::stringstream calcsum;
calcsum << std::setfill('0');
#ifdef CPP11_FOR_EACH
for (const unsigned char c : result)
#else
std::for_each(std::begin(result), std::end(result),
[&calcsum](const unsigned char c)
#endif
{
calcsum << std::hex << std::setw(2)
<< static_cast<unsigned int>(c);
}
#ifndef CPP11_FOR_EACH
);
#endif
return calcsum.str();
}
namespace Options
{
bool version(const std::string &val)
{
return val == "version";
}
bool update_path(const std::string &val)
{
return val == "update path";
}
};
bool confirm()
{
char c;
do
{
std::cin >> c;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
c = static_cast<char>(tolower(c));
} while (c != 'y' && c != 'n');
return c == 'y';
}
class EfuLauncher
{
public:
explicit EfuLauncher(const std::string path,
const std::string update_check):
m_path(path),
m_update_check(update_check),
m_has_update(false)
{}
bool has_update()
{
if (m_has_update)
{
return m_has_update;
}
std::string fetch;
CurlEasy curl(m_update_check.c_str());
curl.write_to(fetch);
//TODO
try
{
curl.perform();
}
catch (CurlEasyException &e)
{
std::cout << e.what() << std::endl;
}
std::vector<std::string> lines(split(fetch, '\n'));
fetch.clear();
for (auto beg = std::begin(lines), end = std::end(lines);
beg != end; ++beg)
{
auto keyvals(split(*beg, '='));
if (keyvals.size() != 2)
{
std::cerr << "Malformed option: " + *beg +
", aborting launcher update check." << std::endl;
return m_has_update = false;
}
if (Options::version(keyvals[0]))
{
const std::string version_test(keyvals[1]);
m_has_update = version_test != version;
}
else if (Options::update_path(keyvals[0]))
{
m_update_path = keyvals[1];
}
}
return m_has_update;
}
bool get_update()
{
if (!m_has_update || m_update_path.empty())
{
return m_has_update = false;
}
return !(m_has_update = false);
}
void stat_targets()
{
std::string fetch;
CurlEasy curl(listing);
curl.write_to(fetch);
curl.perform();
auto lines(split(fetch, '\n'));
std::vector<Target> new_targets, old_targets;
for (auto beg = std::begin(lines), end = std::end(lines);
beg != end; ++beg)
{
auto data(split(*beg, '@'));
Target t(data[0], data[data.size() - 1]);
auto status = t.status();
// TODO
#ifdef CPP11_ENUM_CLASS
if (status == Target::Status::Nonexistent)
#else
if (status == Target::Nonexistent)
#endif
{
new_targets.push_back(std::move(t));
}
// TODO
#ifdef CPP11_ENUM_CLASS
else if (status == Target::Status::Outdated)
#else
else if (status == Target::Outdated)
#endif
{
old_targets.push_back(std::move(t));
}
}
if (new_targets.size())
{
std::cout << "New targets: " << new_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
for (auto &t : new_targets)
#else
std::for_each(new_targets.cbegin(), new_targets.cend(),
[](const Target &t)
#endif
{
std::cout << "- " << t.name() << std::endl;
}
#ifndef CPP11_FOR_EACH
);
#endif
}
else
{
std::cout << "No new targets." << std::endl;
}
if (old_targets.size())
{
std::cout << "Outdated targets: " << old_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
for (auto &t : old_targets)
#else
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](const Target &t)
#endif
{
std::cout << "- " << t.name() << std::endl;
}
#ifndef CPP11_FOR_EACH
);
#endif
}
else
{
std::cout << "No targets out of date." << std::endl;
}
#ifndef DEBUG
#ifdef CPP11_FOR_EACH
for (auto &t : old_targets)
#else
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](Target &t)
#endif
{
t.fetch();
}
#ifndef CPP11_FOR_EACH
);
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](Target &t)
#else
for (auto &t : old_targets)
#endif
{
t.fetch();
}
#ifndef CPP11_FOR_EACH
);
#endif
#endif
}
private:
const std::string path() const { return m_path; }
const std::string m_path;
const std::string m_update_check;
std::string m_update_path;
bool m_has_update;
};
int main(int argc, char *argv[])
{
CurlGlobalInit curl_global;
EfuLauncher l(argv[0],
"https://raw.github.com/commonquail/efulauncher/"\
"master/versioncheck");
if (l.has_update())
{
std::cout << "A new version of the launcher is available."\
" Would you like to download it (y/n)?" << std::endl;
bool download(confirm());
if (!download)
{
std::cout << "It is strongly recommended to always use"\
" the latest launcher. Would you like to download it (y/n)?"
<< std::endl;
download = confirm();
}
if (download)
{
// Download.
std::cout << "Downloading new launcher..." << std::endl;
if (l.get_update())
{
std::cout << "Done. Please extract and run the new launcher." << std::endl;
}
return 0;
}
}
try
{
l.stat_targets();
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
<commit_msg>Add a TODO I'm sick of seeing in git diff.<commit_after>#include <stdexcept>
#include <limits>
#include <algorithm>
#include <array>
#include <memory>
#include <iomanip>
#include <string>
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>
//#include <sys/stat.h>
#include <cerrno>
#include <cstring>
#include <system_error>
#include <openssl/md5.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
/*
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
*/
#ifndef EFU_CURLEASY_H
#include "curleasy.h"
#endif
#if defined(_WIN32) && !defined(EFU_WINERRORSTRING_H)
#include "win_error_string.hpp"
#endif
const std::string version("0.1.0");
const std::string listing("http://nwn.efupw.com/rootdir/index.dat");
const std::string patch_dir("http://nwn.efupw.com/rootdir/patch/");
const std::string file_checksum(const std::string &path);
std::vector<std::string> &split(const std::string &s, char delim,
std::vector<std::string> &elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
std::vector<std::string> split(const std::string &s, char delim)
{
std::vector<std::string> elems;
return split(s, delim, elems);
}
void make_dir(const std::string &path)
{
#ifdef _WIN32
unsigned file_start = path.find_last_of("/\\");
if (!CreateDirectory(path.substr(0, file_start).c_str(), nullptr))
{
WinErrorString wes;
if (wes.code() != ERROR_ALREADY_EXISTS)
{
throw std::ios_base::failure("sdf" + wes.str());
}
}
#else
auto elems = split(path, '/');
std::string descend;
for (size_t i = 0, k = elems.size() - 1; i < k; ++i)
{
const std::string &s(elems[i]);
if (s.size() && s != ".")
{
descend.append((i > 0 ? "/" : "") + s);
auto status = mkdir(descend.c_str(), S_IRWXU);
if (status == -1)
{
std::error_code err(errno, std::generic_category());
if (err != std::errc::file_exists)
{
std::cout << "error making dir: "
<< descend << ": "
<< err.message() << std::endl;
}
}
}
}
#endif
}
// TODO
#ifdef CPP11_ENUM_CLASS
#define ENUM_CLASS enum class
#else
#define ENUM_CLASS enum
#endif
class Target
{
public:
ENUM_CLASS Status {
Nonexistent,
Outdated,
Current
};
explicit Target(const std::string &name, const std::string &checksum):
m_name(name.find_first_of('/') == std::string::npos ? name :
name, name.find_first_of('/') + 1, name.size() - 1),
m_checksum(checksum)
{}
std::string name() const { return m_name; }
const std::string checksum() const { return m_checksum; }
void fetch()
{
std::cout << "Statting target " << name() << "...";
std::fstream fs(name(), std::ios_base::in);
if (!fs.good())
{
fs.close();
std::cout << " doesn't exist, creating new." << std::endl;
make_dir(name());
fs.open(name(), std::ios_base::out);
if (!fs.good())
{
fs.close();
std::cout << "Failed to create file: " << name() << std::endl;
}
else
{
fs.close();
do_fetch();
return;
}
}
if (fs.good())
{
fs.close();
if (status() == Status::Current)
{
std::cout << " already up to date." << std::endl;
}
else
{
std::cout << " outdated, downloading new." << std::endl;
do_fetch();
}
}
}
Status status()
{
std::ifstream is(name());
if (!is.good())
{
return Status::Nonexistent;
}
is.close();
auto calcsum(file_checksum(name()));
if (calcsum == checksum())
{
return Status::Current;
}
else
{
return Status::Outdated;
}
}
private:
void do_fetch()
{
std::ofstream ofs(name(), std::ios::binary);
if (ofs.good())
{
std::string s;
std::string url(patch_dir + name());
CurlEasy curl(url);
curl.write_to(s);
curl.progressbar(true);
curl.perform();
ofs << s;
ofs.close();
std::cout << "Finished downloading " << name() << std::endl;
}
else
{
std::cout << "Couldn't write to " << name() << std::endl;
}
}
std::string m_name;
std::string m_checksum;
};
std::ostream& operator<<(std::ostream &os, const Target &t)
{
return os << "name: " << t.name() << ", checksum: " << t.checksum();
}
const std::string file_checksum(const std::string &path)
{
#ifdef md_md5
auto md = EVP_md5();
const int md_len = MD5_DIGEST_LENGTH;
#else
auto md = EVP_sha1();
const int md_len = SHA_DIGEST_LENGTH;
#endif
std::array<unsigned char, md_len> result;
EVP_MD_CTX *mdctx = nullptr;
std::ifstream is(path, std::ios::binary);
if (!is.good())
{
std::cout << "Couldn't open file " << path
<< " for checksumming." << std::endl;
return std::string();
}
const int length = 8192;
std::array<unsigned char, length> buffer;
auto buf = reinterpret_cast<char *>(buffer.data());
mdctx = EVP_MD_CTX_create();
int status = EVP_DigestInit_ex(mdctx, md, nullptr);
while (status && is)
{
is.read(buf, length);
status = EVP_DigestUpdate(mdctx, buffer.data(), is.gcount());
}
status = EVP_DigestFinal_ex(mdctx, result.data(), nullptr);
EVP_MD_CTX_destroy(mdctx);
std::stringstream calcsum;
calcsum << std::setfill('0');
#ifdef CPP11_FOR_EACH
for (const unsigned char c : result)
#else
std::for_each(std::begin(result), std::end(result),
[&calcsum](const unsigned char c)
#endif
{
calcsum << std::hex << std::setw(2)
<< static_cast<unsigned int>(c);
}
#ifndef CPP11_FOR_EACH
);
#endif
return calcsum.str();
}
namespace Options
{
bool version(const std::string &val)
{
return val == "version";
}
bool update_path(const std::string &val)
{
return val == "update path";
}
};
bool confirm()
{
char c;
do
{
std::cin >> c;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
c = static_cast<char>(tolower(c));
} while (c != 'y' && c != 'n');
return c == 'y';
}
class EfuLauncher
{
public:
// TODO: assignment, copy operator
explicit EfuLauncher(const std::string path,
const std::string update_check):
m_path(path),
m_update_check(update_check),
m_has_update(false)
{}
bool has_update()
{
if (m_has_update)
{
return m_has_update;
}
std::string fetch;
CurlEasy curl(m_update_check.c_str());
curl.write_to(fetch);
//TODO
try
{
curl.perform();
}
catch (CurlEasyException &e)
{
std::cout << e.what() << std::endl;
}
std::vector<std::string> lines(split(fetch, '\n'));
fetch.clear();
for (auto beg = std::begin(lines), end = std::end(lines);
beg != end; ++beg)
{
auto keyvals(split(*beg, '='));
if (keyvals.size() != 2)
{
std::cerr << "Malformed option: " + *beg +
", aborting launcher update check." << std::endl;
return m_has_update = false;
}
if (Options::version(keyvals[0]))
{
const std::string version_test(keyvals[1]);
m_has_update = version_test != version;
}
else if (Options::update_path(keyvals[0]))
{
m_update_path = keyvals[1];
}
}
return m_has_update;
}
bool get_update()
{
if (!m_has_update || m_update_path.empty())
{
return m_has_update = false;
}
return !(m_has_update = false);
}
void stat_targets()
{
std::string fetch;
CurlEasy curl(listing);
curl.write_to(fetch);
curl.perform();
auto lines(split(fetch, '\n'));
std::vector<Target> new_targets, old_targets;
for (auto beg = std::begin(lines), end = std::end(lines);
beg != end; ++beg)
{
auto data(split(*beg, '@'));
Target t(data[0], data[data.size() - 1]);
auto status = t.status();
// TODO
#ifdef CPP11_ENUM_CLASS
if (status == Target::Status::Nonexistent)
#else
if (status == Target::Nonexistent)
#endif
{
new_targets.push_back(std::move(t));
}
// TODO
#ifdef CPP11_ENUM_CLASS
else if (status == Target::Status::Outdated)
#else
else if (status == Target::Outdated)
#endif
{
old_targets.push_back(std::move(t));
}
}
if (new_targets.size())
{
std::cout << "New targets: " << new_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
for (auto &t : new_targets)
#else
std::for_each(new_targets.cbegin(), new_targets.cend(),
[](const Target &t)
#endif
{
std::cout << "- " << t.name() << std::endl;
}
#ifndef CPP11_FOR_EACH
);
#endif
}
else
{
std::cout << "No new targets." << std::endl;
}
if (old_targets.size())
{
std::cout << "Outdated targets: " << old_targets.size() << std::endl;
#ifdef CPP11_FOR_EACH
for (auto &t : old_targets)
#else
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](const Target &t)
#endif
{
std::cout << "- " << t.name() << std::endl;
}
#ifndef CPP11_FOR_EACH
);
#endif
}
else
{
std::cout << "No targets out of date." << std::endl;
}
#ifndef DEBUG
#ifdef CPP11_FOR_EACH
for (auto &t : old_targets)
#else
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](Target &t)
#endif
{
t.fetch();
}
#ifndef CPP11_FOR_EACH
);
std::for_each(old_targets.cbegin(), old_targets.cend(),
[](Target &t)
#else
for (auto &t : old_targets)
#endif
{
t.fetch();
}
#ifndef CPP11_FOR_EACH
);
#endif
#endif
}
private:
const std::string path() const { return m_path; }
const std::string m_path;
const std::string m_update_check;
std::string m_update_path;
bool m_has_update;
};
int main(int argc, char *argv[])
{
CurlGlobalInit curl_global;
EfuLauncher l(argv[0],
"https://raw.github.com/commonquail/efulauncher/"\
"master/versioncheck");
if (l.has_update())
{
std::cout << "A new version of the launcher is available."\
" Would you like to download it (y/n)?" << std::endl;
bool download(confirm());
if (!download)
{
std::cout << "It is strongly recommended to always use"\
" the latest launcher. Would you like to download it (y/n)?"
<< std::endl;
download = confirm();
}
if (download)
{
// Download.
std::cout << "Downloading new launcher..." << std::endl;
if (l.get_update())
{
std::cout << "Done. Please extract and run the new launcher." << std::endl;
}
return 0;
}
}
try
{
l.stat_targets();
}
catch (std::exception &e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <unordered_map>
#include <memory>
#include "SurgSim/DataStructures/PlyReader.h"
#include "SurgSim/Framework/Assert.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Timer.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/Fem3DPlyReaderDelegate.h"
#include "SurgSim/Physics/Fem3DRepresentation.h"
#include "SurgSim/Physics/Fem3DElementCube.h"
#include "SurgSim/Physics/PerformanceTests/DivisibleCubeRepresentation.h"
#include "SurgSim/Testing/MockPhysicsManager.h"
using SurgSim::Math::Vector3d;
namespace
{
static const double dt = 0.001;
static const int frameCount = 10;
static std::unordered_map<SurgSim::Math::IntegrationScheme, std::string, std::hash<int>> getIntegrationSchemeNames()
{
std::unordered_map<SurgSim::Math::IntegrationScheme, std::string, std::hash<int>> result;
#define FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(map, name) (map)[name] = #name
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_EXPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_MODIFIED_EXPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_IMPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_STATIC);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_STATIC);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_RUNGE_KUTTA_4);
#undef FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME
return result;
}
static std::unordered_map<SurgSim::Math::IntegrationScheme, std::string, std::hash<int>> IntegrationSchemeNames
= getIntegrationSchemeNames();
}
namespace SurgSim
{
namespace Physics
{
class Fem3DSolutionComponentsTestBase : public ::testing::Test
{
public:
virtual void SetUp()
{
m_physicsManager = std::make_shared<SurgSim::Testing::MockPhysicsManager>();
m_physicsManager->doInitialize();
m_physicsManager->doStartUp();
}
void timeInitializeRepresentation(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->initializeNoWakeUp();
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void timeMatrixAssembly(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->getOdeSolver()->computeMatrices(dt, *(fem->getInitialState()));
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void timeComputeLinearSystem(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
fem->getOdeSolver()->computeMatrices(dt, *(fem->getInitialState()));
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->getOdeSolver()->getLinearSolver()->setMatrix(fem->getOdeSolver()->getSystemMatrix());
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void timeSolveSystem(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
fem->getOdeSolver()->computeMatrices(dt, *(fem->getInitialState()));
fem->getOdeSolver()->getLinearSolver()->setMatrix(fem->getOdeSolver()->getSystemMatrix());
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->getOdeSolver()->getLinearSolver()->solve(Math::Vector::Ones(fem->getInitialState()->getNumDof()));
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void timeInvertSystem(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
fem->getOdeSolver()->computeMatrices(dt, *(fem->getInitialState()));
fem->getOdeSolver()->getLinearSolver()->setMatrix(fem->getOdeSolver()->getSystemMatrix());
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->getOdeSolver()->getLinearSolver()->getInverse();
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void initializeRepresentation(std::shared_ptr<Fem3DRepresentation> fem)
{
fem->initialize(std::make_shared<SurgSim::Framework::Runtime>());
fem->wakeUp();
m_physicsManager->executeAdditions(fem);
}
protected:
std::shared_ptr<SurgSim::Testing::MockPhysicsManager> m_physicsManager;
};
class ComponentIntegrationSchemeAndCountParamTest
: public Fem3DSolutionComponentsTestBase,
public ::testing::WithParamInterface<std::tuple<SurgSim::Math::IntegrationScheme, int>>
{
};
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeMatrixInitialization)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
timeInitializeRepresentation(fem);
}
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeMatrixAssembly)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
initializeRepresentation(fem);
timeMatrixAssembly(fem);
}
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeComputeLinearSystem)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
initializeRepresentation(fem);
timeComputeLinearSystem(fem);
}
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeSolveSystem)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
initializeRepresentation(fem);
timeSolveSystem(fem);
}
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeInvertSystem)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
initializeRepresentation(fem);
timeInvertSystem(fem);
}
INSTANTIATE_TEST_CASE_P(
Fem3DSolutionComponentsTest,
ComponentIntegrationSchemeAndCountParamTest,
::testing::Combine(::testing::Values(SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_EXPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_MODIFIED_EXPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_IMPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_STATIC,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_STATIC,
SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_RUNGE_KUTTA_4),
::testing::Values(2, 3, 4, 5, 6, 7, 8)));
} // namespace Physics
} // namespace SurgSim
<commit_msg>Fix other performance test as well (same fix)<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <gtest/gtest.h>
#include <unordered_map>
#include <memory>
#include "SurgSim/DataStructures/PlyReader.h"
#include "SurgSim/Framework/Assert.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Timer.h"
#include "SurgSim/Math/OdeState.h"
#include "SurgSim/Math/Vector.h"
#include "SurgSim/Physics/Fem3DPlyReaderDelegate.h"
#include "SurgSim/Physics/Fem3DRepresentation.h"
#include "SurgSim/Physics/Fem3DElementCube.h"
#include "SurgSim/Physics/PerformanceTests/DivisibleCubeRepresentation.h"
#include "SurgSim/Testing/MockPhysicsManager.h"
using SurgSim::Math::Vector3d;
namespace
{
static const double dt = 0.001;
static const int frameCount = 10;
static std::unordered_map<SurgSim::Math::IntegrationScheme, std::string, std::hash<int>> getIntegrationSchemeNames()
{
std::unordered_map<SurgSim::Math::IntegrationScheme, std::string, std::hash<int>> result;
#define FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(map, name) (map)[name] = #name
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_EXPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_MODIFIED_EXPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_IMPLICIT_EULER);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_STATIC);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_STATIC);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4);
FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME(result, SurgSim::Math::INTEGRATIONSCHEME_LINEAR_RUNGE_KUTTA_4);
#undef FEM3DSOLUTIONCOMPONEMENTSTEST_MAP_NAME
return result;
}
static std::unordered_map<SurgSim::Math::IntegrationScheme, std::string, std::hash<int>> IntegrationSchemeNames
= getIntegrationSchemeNames();
}
namespace SurgSim
{
namespace Physics
{
class Fem3DSolutionComponentsTestBase : public ::testing::Test
{
public:
virtual void SetUp()
{
m_physicsManager = std::make_shared<SurgSim::Testing::MockPhysicsManager>();
m_physicsManager->doInitialize();
m_physicsManager->doStartUp();
}
void timeInitializeRepresentation(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->initializeNoWakeUp();
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void timeMatrixAssembly(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->getOdeSolver()->computeMatrices(dt, *(fem->getInitialState()));
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void timeComputeLinearSystem(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
fem->getOdeSolver()->computeMatrices(dt, *(fem->getInitialState()));
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->getOdeSolver()->getLinearSolver()->setMatrix(fem->getOdeSolver()->getSystemMatrix());
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void timeSolveSystem(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
fem->getOdeSolver()->computeMatrices(dt, *(fem->getInitialState()));
fem->getOdeSolver()->getLinearSolver()->setMatrix(fem->getOdeSolver()->getSystemMatrix());
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->getOdeSolver()->getLinearSolver()->solve(Math::Vector::Ones(fem->getInitialState()->getNumDof()));
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void timeInvertSystem(std::shared_ptr<DivisibleCubeRepresentation> fem)
{
fem->getOdeSolver()->computeMatrices(dt, *(fem->getInitialState()));
fem->getOdeSolver()->getLinearSolver()->setMatrix(fem->getOdeSolver()->getSystemMatrix());
SurgSim::Framework::Timer totalTime;
totalTime.beginFrame();
for (int i = 0; i < frameCount; i++)
{
fem->getOdeSolver()->getLinearSolver()->getInverse();
}
totalTime.endFrame();
RecordProperty("Duration", boost::to_string(totalTime.getCumulativeTime()));
}
void initializeRepresentation(std::shared_ptr<Fem3DRepresentation> fem)
{
fem->initialize(std::make_shared<SurgSim::Framework::Runtime>());
fem->wakeUp();
m_physicsManager->executeAdditions(fem);
}
protected:
std::shared_ptr<SurgSim::Testing::MockPhysicsManager> m_physicsManager;
};
class ComponentIntegrationSchemeAndCountParamTest
: public Fem3DSolutionComponentsTestBase,
public ::testing::WithParamInterface<std::tuple<SurgSim::Math::IntegrationScheme, int>>
{
};
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeMatrixInitialization)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
// We need to add some boundary conditions for the static solver to not run into a singular matrix
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(0);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(1);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(2);
fem->setIntegrationScheme(integrationScheme);
timeInitializeRepresentation(fem);
}
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeMatrixAssembly)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
// We need to add some boundary conditions for the static solver to not run into a singular matrix
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(0);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(1);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(2);
initializeRepresentation(fem);
timeMatrixAssembly(fem);
}
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeComputeLinearSystem)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
// We need to add some boundary conditions for the static solver to not run into a singular matrix
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(0);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(1);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(2);
initializeRepresentation(fem);
timeComputeLinearSystem(fem);
}
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeSolveSystem)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
// We need to add some boundary conditions for the static solver to not run into a singular matrix
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(0);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(1);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(2);
initializeRepresentation(fem);
timeSolveSystem(fem);
}
TEST_P(ComponentIntegrationSchemeAndCountParamTest, TimeInvertSystem)
{
int numCubes;
SurgSim::Math::IntegrationScheme integrationScheme;
std::tie(integrationScheme, numCubes) = GetParam();
RecordProperty("IntegrationScheme", IntegrationSchemeNames[integrationScheme]);
RecordProperty("CubeDivisions", boost::to_string(numCubes));
auto fem = std::make_shared<DivisibleCubeRepresentation>("cube", numCubes);
fem->setIntegrationScheme(integrationScheme);
// We need to add some boundary conditions for the static solver to not run into a singular matrix
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(0);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(1);
std::const_pointer_cast<SurgSim::Math::OdeState>(fem->getInitialState())->addBoundaryCondition(2);
initializeRepresentation(fem);
timeInvertSystem(fem);
}
INSTANTIATE_TEST_CASE_P(
Fem3DSolutionComponentsTest,
ComponentIntegrationSchemeAndCountParamTest,
::testing::Combine(::testing::Values(SurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_EXPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_MODIFIED_EXPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_IMPLICIT_EULER,
SurgSim::Math::INTEGRATIONSCHEME_STATIC,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_STATIC,
SurgSim::Math::INTEGRATIONSCHEME_RUNGE_KUTTA_4,
SurgSim::Math::INTEGRATIONSCHEME_LINEAR_RUNGE_KUTTA_4),
::testing::Values(2, 3, 4, 5, 6, 7, 8)));
} // namespace Physics
} // namespace SurgSim
<|endoftext|> |
<commit_before>//
// AKPannerDSPKernel.hpp
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
#pragma once
#import "AKSoundpipeKernel.hpp"
enum {
panAddress = 0
};
class AKPannerDSPKernel : public AKSoundpipeKernel, public AKBuffered {
public:
// MARK: Member Functions
AKPannerDSPKernel() {}
void init(int _channels, double _sampleRate) override {
AKSoundpipeKernel::init(_channels, _sampleRate);
sp_panst_create(&panst);
sp_panst_init(sp, panst);
panst->pan = 0;
panRamper.init();
}
void start() {
started = true;
}
void stop() {
started = false;
}
void destroy() {
sp_panst_destroy(&panst);
AKSoundpipeKernel::destroy();
}
void reset() {
resetted = true;
panRamper.reset();
}
void setPan(float value) {
pan = clamp(value, -1.0f, 1.0f);
panRamper.setImmediate(pan);
}
void setParameter(AUParameterAddress address, AUValue value) {
switch (address) {
case panAddress:
panRamper.setUIValue(clamp(value, -1.0f, 1.0f));
break;
}
}
AUValue getParameter(AUParameterAddress address) {
switch (address) {
case panAddress:
return panRamper.getUIValue();
default: return 0.0f;
}
}
void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
switch (address) {
case panAddress:
panRamper.startRamp(clamp(value, -1.0f, 1.0f), duration);
break;
}
}
void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
int frameOffset = int(frameIndex + bufferOffset);
pan = panRamper.getAndStep();
panst->pan = (float)pan;
if (!started) {
outBufferListPtr->mBuffers[0] = inBufferListPtr->mBuffers[0];
outBufferListPtr->mBuffers[1] = inBufferListPtr->mBuffers[1];
return;
}
float *tmpin[2];
float *tmpout[2];
for (int channel = 0; channel < channels; ++channel) {
float *in = (float *)inBufferListPtr->mBuffers[channel].mData + frameOffset;
float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
if (channel < 2) {
tmpin[channel] = in;
tmpout[channel] = out;
}
}
sp_panst_compute(sp, panst, tmpin[0], tmpin[1], tmpout[0], tmpout[1]);
}
}
// MARK: Member Variables
private:
sp_panst *panst;
float pan = 0.0;
public:
bool started = true;
bool resetted = false;
ParameterRamper panRamper = 0;
};
<commit_msg>Addresses https://github.com/AudioKit/AudioKit/issues/953<commit_after>//
// AKPannerDSPKernel.hpp
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright © 2017 Aurelius Prochazka. All rights reserved.
//
#pragma once
#import "AKSoundpipeKernel.hpp"
enum {
panAddress = 0
};
class AKPannerDSPKernel : public AKSoundpipeKernel, public AKBuffered {
public:
// MARK: Member Functions
AKPannerDSPKernel() {}
void init(int _channels, double _sampleRate) override {
AKSoundpipeKernel::init(_channels, _sampleRate);
sp_panst_create(&panst);
sp_panst_init(sp, panst);
panst->pan = 0;
panRamper.init();
}
void start() {
started = true;
}
void stop() {
started = false;
}
void destroy() {
sp_panst_destroy(&panst);
AKSoundpipeKernel::destroy();
}
void reset() {
resetted = true;
panRamper.reset();
}
void setPan(float value) {
pan = clamp(value, -1.0f, 1.0f);
panRamper.setImmediate(pan);
}
void setParameter(AUParameterAddress address, AUValue value) {
switch (address) {
case panAddress:
panRamper.setUIValue(clamp(value, -1.0f, 1.0f));
break;
}
}
AUValue getParameter(AUParameterAddress address) {
switch (address) {
case panAddress:
return panRamper.getUIValue();
default: return 0.0f;
}
}
void startRamp(AUParameterAddress address, AUValue value, AUAudioFrameCount duration) override {
switch (address) {
case panAddress:
panRamper.startRamp(clamp(value, -1.0f, 1.0f), duration);
break;
}
}
void process(AUAudioFrameCount frameCount, AUAudioFrameCount bufferOffset) override {
for (int frameIndex = 0; frameIndex < frameCount; ++frameIndex) {
int frameOffset = int(frameIndex + bufferOffset);
pan = panRamper.getAndStep();
panst->pan = (float)pan;
if (!started || AKSettings.numberOfChannels != 2) {
outBufferListPtr->mBuffers[0] = inBufferListPtr->mBuffers[0];
outBufferListPtr->mBuffers[1] = inBufferListPtr->mBuffers[1];
return;
}
float *tmpin[2];
float *tmpout[2];
for (int channel = 0; channel < channels; ++channel) {
float *in = (float *)inBufferListPtr->mBuffers[channel].mData + frameOffset;
float *out = (float *)outBufferListPtr->mBuffers[channel].mData + frameOffset;
if (channel < 2) {
tmpin[channel] = in;
tmpout[channel] = out;
}
}
sp_panst_compute(sp, panst, tmpin[0], tmpin[1], tmpout[0], tmpout[1]);
}
}
// MARK: Member Variables
private:
sp_panst *panst;
float pan = 0.0;
public:
bool started = true;
bool resetted = false;
ParameterRamper panRamper = 0;
};
<|endoftext|> |
<commit_before>/*
* Recognizer.cc
*
* Copyright (C) 2015 Linas Vepstas
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/core/FindUtils.h>
#include "Recognizer.h"
using namespace opencog;
// Uncomment below to enable debug print
#define DEBUG 1
#ifdef DEBUG
#define dbgprt(f, varargs...) logger().fine(f, ##varargs)
#else
#define dbgprt(f, varargs...)
#endif
/* ======================================================== */
bool Recognizer::do_search(PatternMatchEngine* pme, const Handle& top)
{
if (top->is_link())
{
// Recursively drill down and explore every possible node as
// a search starting point. This is needed, as the patterns we
// compare against might not be connected.
for (const Handle& h : top->getOutgoingSet())
{
_starter_term = top;
bool found = do_search(pme, h);
if (found) return true;
}
return false;
}
IncomingSet iset = get_incoming_set(top);
size_t sz = iset.size();
for (size_t i = 0; i < sz; i++)
{
Handle h(iset[i]);
dbgprt("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\n");
dbgprt("Loop candidate (%lu - %s):\n%s\n", _cnt++,
top->to_short_string().c_str(),
h->to_short_string().c_str());
bool found = pme->explore_neighborhood(_root, _starter_term, h);
// Terminate search if satisfied.
if (found) return true;
}
return false;
}
bool Recognizer::initiate_search(PatternMatchEngine* pme)
{
const HandleSeq& clauses = _pattern->cnf_clauses;
_cnt = 0;
for (const Handle& h: clauses)
{
_root = h;
bool found = do_search(pme, h);
if (found) return true;
}
return false;
}
bool Recognizer::node_match(const Handle& npat_h, const Handle& nsoln_h)
{
// If it's a match, we can accept it right away, the comparison
// is done already, see link_match below.
if (match) return true;
if (npat_h == nsoln_h) return true;
if (VARIABLE_NODE == nsoln_h->get_type()) return true;
return false;
}
bool Recognizer::link_match(const PatternTermPtr& ptm, const Handle& lsoln)
{
match = false;
const Handle& lpat = ptm->getHandle();
// Self-compares always proceed.
if (lpat == lsoln) return true;
// mis-matched types are a dead-end.
if (lpat->get_type() != lsoln->get_type()) return false;
// TODO: Change to something better if possible...
// What is happening here is to manually call the
// fuzzy_match callback immediately if and only if
// lsoln has one or more GlobNodes AND lpat and lsoln
// have the same arity.
// The reason is, if the pat and soln are having the
// size, pattern matcher will then do a side-by-side
// comparison on their outgoing atoms.
// In the typical use cases we have at the moment,
// the comparison will be done in the node_match
// callback. However that will cause problems in some
// situations, for example if we have:
// === lpat === === lsoln ===
// Concept "A" Glob $x
// Concept "B" Concept "A"
// Concept "C" Glob $y
// and both of the globs $x and $y have an interval
// restriction of zero to infinity, it should be a
// match by grounding $x to nothing and $y to Concept
// "B" and "C". But a side-by-side comparison here
// only compares their nodes at the same position
// (i.e. A-$x, B-A, C-$y), and decide whether to
// reject it when there is a mis-match. As a result
// a lot of candidates that we are expecting are
// rejected...
// And the reason of going to fuzzy_match is that
// all the glob-matching logic is there, so it
// should be able to handle this better.
if (contains_atomtype(lsoln, GLOB_NODE) and
lpat->get_arity() == lsoln->get_arity())
{
if (fuzzy_match(lpat, lsoln))
{
match = true;
return true;
}
else return false;
}
return true;
}
bool Recognizer::loose_match(const Handle& npat_h, const Handle& nsoln_h)
{
Type gtype = nsoln_h->get_type();
// Variable matches anything; move to next.
if (VARIABLE_NODE == gtype) return true;
// Strict match for link types.
if (npat_h->get_type() != gtype) return false;
if (not npat_h->is_node()) return true;
// If we are here, we know we have nodes. Ask for a strict match.
if (npat_h != nsoln_h) return false;
return true;
}
bool Recognizer::fuzzy_match(const Handle& npat_h, const Handle& nsoln_h)
{
// If we are here, then there are probably glob nodes in the soln.
// Try to match them, fairly rigorously. Exactly what constitutes
// an OK match is still a bit up in the air.
if (not npat_h->is_link() or not nsoln_h->is_link()) return false;
const HandleSeq &osg = nsoln_h->getOutgoingSet();
size_t osg_size = osg.size();
// Lets not waste time, if there's no glob there.
bool have_glob = false;
for (size_t j=0; j<osg_size; j++)
{
if (osg[j]->get_type() == GLOB_NODE)
{
have_glob = true;
break;
}
}
if (not have_glob) return false;
const HandleSeq &osp = npat_h->getOutgoingSet();
size_t osp_size = osp.size();
// Do a side-by-side compare. This is not as rigorous as
// PatternMatchEngine::tree_compare() nor does it handle the bells
// and whistles (ChoiceLink, QuoteLink, etc).
size_t ip=0, jg=0;
for (; ip<osp_size or jg<osg_size; ip++, jg++)
{
if (ip == osp_size) ip--;
if (jg == osg_size) jg--;
if (GLOB_NODE != osg[jg]->get_type())
{
if (loose_match(osp[ip], osg[jg])) continue;
return false;
}
// If we are here, we have a glob in the soln. If the glob is at
// the end, it eats everything, so its a match. Else, resume
// matching at the end of the glob.
if ((jg+1) == osg_size) return true;
const Handle& post(osg[jg+1]);
// If the post is also a GlobNode, we are done for this one.
if (GLOB_NODE == post->get_type()) return true;
// Match as many as possible.
while (ip < osp_size and not loose_match(osp[ip], post))
{
ip++;
}
// Go around again, look for more GlobNodes. Back up by one, so
// that the for-loop increment gets us back on track.
ip--;
}
// If we are here, then we should have matched up all the atoms.
return true;
}
bool Recognizer::grounding(const HandleMap& var_soln,
const HandleMap& term_soln)
{
Handle rule = term_soln.at(_root);
if (rule != _root) {
_rules.insert(rule);
}
// Look for more groundings.
return false;
}
<commit_msg>Search only the mandatory clauses.<commit_after>/*
* Recognizer.cc
*
* Copyright (C) 2015 Linas Vepstas
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the
* exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <opencog/atoms/core/FindUtils.h>
#include "Recognizer.h"
using namespace opencog;
// Uncomment below to enable debug print
#define DEBUG 1
#ifdef DEBUG
#define dbgprt(f, varargs...) logger().fine(f, ##varargs)
#else
#define dbgprt(f, varargs...)
#endif
/* ======================================================== */
bool Recognizer::do_search(PatternMatchEngine* pme, const Handle& top)
{
if (top->is_link())
{
// Recursively drill down and explore every possible node as
// a search starting point. This is needed, as the patterns we
// compare against might not be connected.
for (const Handle& h : top->getOutgoingSet())
{
_starter_term = top;
bool found = do_search(pme, h);
if (found) return true;
}
return false;
}
IncomingSet iset = get_incoming_set(top);
size_t sz = iset.size();
for (size_t i = 0; i < sz; i++)
{
Handle h(iset[i]);
dbgprt("rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr\n");
dbgprt("Loop candidate (%lu - %s):\n%s\n", _cnt++,
top->to_short_string().c_str(),
h->to_short_string().c_str());
bool found = pme->explore_neighborhood(_root, _starter_term, h);
// Terminate search if satisfied.
if (found) return true;
}
return false;
}
bool Recognizer::initiate_search(PatternMatchEngine* pme)
{
const HandleSeq& clauses = _pattern->mandatory;
_cnt = 0;
for (const Handle& h: clauses)
{
_root = h;
bool found = do_search(pme, h);
if (found) return true;
}
return false;
}
bool Recognizer::node_match(const Handle& npat_h, const Handle& nsoln_h)
{
// If it's a match, we can accept it right away, the comparison
// is done already, see link_match below.
if (match) return true;
if (npat_h == nsoln_h) return true;
if (VARIABLE_NODE == nsoln_h->get_type()) return true;
return false;
}
bool Recognizer::link_match(const PatternTermPtr& ptm, const Handle& lsoln)
{
match = false;
const Handle& lpat = ptm->getHandle();
// Self-compares always proceed.
if (lpat == lsoln) return true;
// mis-matched types are a dead-end.
if (lpat->get_type() != lsoln->get_type()) return false;
// TODO: Change to something better if possible...
// What is happening here is to manually call the
// fuzzy_match callback immediately if and only if
// lsoln has one or more GlobNodes AND lpat and lsoln
// have the same arity.
// The reason is, if the pat and soln are having the
// size, pattern matcher will then do a side-by-side
// comparison on their outgoing atoms.
// In the typical use cases we have at the moment,
// the comparison will be done in the node_match
// callback. However that will cause problems in some
// situations, for example if we have:
// === lpat === === lsoln ===
// Concept "A" Glob $x
// Concept "B" Concept "A"
// Concept "C" Glob $y
// and both of the globs $x and $y have an interval
// restriction of zero to infinity, it should be a
// match by grounding $x to nothing and $y to Concept
// "B" and "C". But a side-by-side comparison here
// only compares their nodes at the same position
// (i.e. A-$x, B-A, C-$y), and decide whether to
// reject it when there is a mis-match. As a result
// a lot of candidates that we are expecting are
// rejected...
// And the reason of going to fuzzy_match is that
// all the glob-matching logic is there, so it
// should be able to handle this better.
if (contains_atomtype(lsoln, GLOB_NODE) and
lpat->get_arity() == lsoln->get_arity())
{
if (fuzzy_match(lpat, lsoln))
{
match = true;
return true;
}
else return false;
}
return true;
}
bool Recognizer::loose_match(const Handle& npat_h, const Handle& nsoln_h)
{
Type gtype = nsoln_h->get_type();
// Variable matches anything; move to next.
if (VARIABLE_NODE == gtype) return true;
// Strict match for link types.
if (npat_h->get_type() != gtype) return false;
if (not npat_h->is_node()) return true;
// If we are here, we know we have nodes. Ask for a strict match.
if (npat_h != nsoln_h) return false;
return true;
}
bool Recognizer::fuzzy_match(const Handle& npat_h, const Handle& nsoln_h)
{
// If we are here, then there are probably glob nodes in the soln.
// Try to match them, fairly rigorously. Exactly what constitutes
// an OK match is still a bit up in the air.
if (not npat_h->is_link() or not nsoln_h->is_link()) return false;
const HandleSeq &osg = nsoln_h->getOutgoingSet();
size_t osg_size = osg.size();
// Lets not waste time, if there's no glob there.
bool have_glob = false;
for (size_t j=0; j<osg_size; j++)
{
if (osg[j]->get_type() == GLOB_NODE)
{
have_glob = true;
break;
}
}
if (not have_glob) return false;
const HandleSeq &osp = npat_h->getOutgoingSet();
size_t osp_size = osp.size();
// Do a side-by-side compare. This is not as rigorous as
// PatternMatchEngine::tree_compare() nor does it handle the bells
// and whistles (ChoiceLink, QuoteLink, etc).
size_t ip=0, jg=0;
for (; ip<osp_size or jg<osg_size; ip++, jg++)
{
if (ip == osp_size) ip--;
if (jg == osg_size) jg--;
if (GLOB_NODE != osg[jg]->get_type())
{
if (loose_match(osp[ip], osg[jg])) continue;
return false;
}
// If we are here, we have a glob in the soln. If the glob is at
// the end, it eats everything, so its a match. Else, resume
// matching at the end of the glob.
if ((jg+1) == osg_size) return true;
const Handle& post(osg[jg+1]);
// If the post is also a GlobNode, we are done for this one.
if (GLOB_NODE == post->get_type()) return true;
// Match as many as possible.
while (ip < osp_size and not loose_match(osp[ip], post))
{
ip++;
}
// Go around again, look for more GlobNodes. Back up by one, so
// that the for-loop increment gets us back on track.
ip--;
}
// If we are here, then we should have matched up all the atoms.
return true;
}
bool Recognizer::grounding(const HandleMap& var_soln,
const HandleMap& term_soln)
{
Handle rule = term_soln.at(_root);
if (rule != _root) {
_rules.insert(rule);
}
// Look for more groundings.
return false;
}
<|endoftext|> |
<commit_before>#include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"
Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);
void CalibrationLaser::device_setup(){
Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
claser.write(0);
}
void CalibrationLaser::device_loop(Command command){
if( command.cmp("claser")){
int value = command.args[1];
claser.write(value);
claser.send(value);
}
}
#endif
<commit_msg>Revert "Adding laser indicator"<commit_after>#include "AConfig.h"
#if(HAS_STD_CALIBRATIONLASERS)
#include "Device.h"
#include "Pin.h"
#include "CalibrationLaser.h"
#include "Settings.h"
Pin claser("claser", CALIBRATIONLASERS_PIN, claser.analog, claser.out);
void CalibrationLaser::device_setup(){
Settings::capability_bitarray |= (1 << CALIBRATION_LASERS_CAPABLE);
claser.write(0);
}
void CalibrationLaser::device_loop(Command command){
if( command.cmp("claser")){
int value = command.args[1];
claser.write(value);
}
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: HashMaps.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: mtg $ $Date: 2001-07-04 14:56:13 $
*
* 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): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _HASHMAPS_HXX
#define _HASHMAPS_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEl_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#include <hash_map>
struct eqFunc
{
sal_Bool operator()( const rtl::OUString &r1,
const rtl::OUString &r2) const
{
return r1 == r2;
}
};
typedef std::hash_map < rtl::OUString,
com::sun::star::uno::Reference < com::sun::star::lang::XUnoTunnel >,
::rtl::OUStringHash,
eqFunc > TunnelHash;
typedef std::hash_map < rtl::OUString,
com::sun::star::uno::Reference < com::sun::star::container::XNameContainer >,
::rtl::OUStringHash,
eqFunc > NameHash;
#endif
<commit_msg>#89303# optimise hash maps for speed (and put them all in one place)<commit_after>/*************************************************************************
*
* $RCSfile: HashMaps.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mtg $ $Date: 2001-09-14 14:38:16 $
*
* 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): Martin Gallwey ([email protected])
*
*
************************************************************************/
#ifndef _HASHMAPS_HXX
#define _HASHMAPS_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEl_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif
#ifndef _ZIP_ENTRY_HXX_
#include <ZipEntry.hxx>
#endif
#include <hash_map>
struct eqFunc
{
sal_Bool operator()( const rtl::OUString &r1,
const rtl::OUString &r2) const
{
return r1 == r2;
}
};
class ZipPackageFolder;
struct ContentInfo;
typedef std::hash_map < rtl::OUString,
ZipPackageFolder *,
::rtl::OUStringHash,
eqFunc > FolderHash;
typedef std::hash_map < rtl::OUString,
ContentInfo *,
::rtl::OUStringHash,
eqFunc > ContentHash;
typedef std::hash_map < rtl::OUString,
ZipEntry,
rtl::OUStringHash,
eqFunc > EntryHash;
#endif
<|endoftext|> |
<commit_before>// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;
// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static llvm::cl::OptionCategory MyToolCategory("my-tool options");
// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("\nMore help text...");
namespace {
bool areSameVariable(const ValueDecl *First, const ValueDecl *Second) {
return First && Second &&
First->getCanonicalDecl() == Second->getCanonicalDecl();
}
bool areSameExpr(ASTContext *Context, const Expr *First, const Expr *Second) {
if (!First || !Second)
return false;
llvm::FoldingSetNodeID FirstID, SecondID;
First->Profile(FirstID, *Context, true);
Second->Profile(SecondID, *Context, true);
return FirstID == SecondID;
}
std::string getName(const CXXRecordDecl &RD) {
std::string NameWithTemplateArgs;
llvm::raw_string_ostream OS(NameWithTemplateArgs);
RD.getNameForDiagnostic(OS, RD.getASTContext().getPrintingPolicy(), true);
return OS.str();
}
std::string stringRemove(const std::string &S, const std::string &ToRemove) {
std::string Result;
size_t Index = 0, Off = 0;
while ((Index = S.find(ToRemove, Off)) != -1) {
Result += S.substr(Off, Index - Off);
Off = Index + ToRemove.length();
}
Result += S.substr(Off, S.length() - Off);
return Result;
}
std::string getName(const TemplateArgument &TA) {
auto Name = TA.getAsType().getAsString();
return stringRemove(stringRemove(Name, "struct "), "clang ");
}
} // namespace
enum class TransitionType {
Sibling,
Inner,
InnerEntry,
No,
};
static const char *TransitionTypeString[] = {"Sibling", "Inner", "InnerEntry",
"No"};
static const char *TransitionTypeVisualString[] = {"--->", "==>>", "===>",
"XXXX"};
inline TransitionType fuzzyNameToTransitionType(const StringRef &Name) {
auto contains = [](auto stringRef, auto s) {
return stringRef.find(s) != StringRef::npos;
};
if (contains(Name, "SiblingTransition"))
return TransitionType::Sibling;
if (contains(Name, "InnerTransition"))
return TransitionType::Inner;
if (contains(Name, "InnerEntryTransition"))
return TransitionType::InnerEntry;
assert(contains(Name, "No"));
return TransitionType::No;
}
// Matches declaration of transition functions that actually cause a transition
// to occur (i.e. everything except NoTransition)
const auto TransitionFunctionDecl = hasDeclaration(eachOf(
functionDecl(hasName("InnerTransition")).bind("trans_func_decl"),
functionDecl(hasName("InnerEntryTransition")).bind("trans_func_decl"),
functionDecl(hasName("SiblingTransition")).bind("trans_func_decl")));
// Matches transition function expressions (i.e. calls to transition functions)
const auto TransitionFunctionMatcher = callExpr(
expr().bind("call_expr"),
// Look for calls to transition functions
TransitionFunctionDecl,
// We track ancestor call expressions to determine if the call is actually a
// state arg
anyOf(hasAncestor(
callExpr(TransitionFunctionDecl).bind("arg_parent_call_expr")),
anything()));
// Matches transition function expressions within states
const auto StateTransitionMatcher =
cxxRecordDecl(decl().bind("state"), isDerivedFrom("hsm::State"),
forEachDescendant(TransitionFunctionMatcher));
class StateTransitionMapper : public MatchFinder::MatchCallback {
using TargetStateName = std::string;
std::map<const CallExpr *, TargetStateName> _callExprToTargetState;
public:
virtual void run(const MatchFinder::MatchResult &Result) {
const auto StateDecl = Result.Nodes.getNodeAs<CXXRecordDecl>("state");
const auto TransCallExpr = Result.Nodes.getNodeAs<CallExpr>("call_expr");
const auto TransitionFuncDecl =
Result.Nodes.getNodeAs<FunctionDecl>("trans_func_decl");
const auto ArgParentCallExpr =
Result.Nodes.getNodeAs<CallExpr>("arg_parent_call_expr");
assert(StateDecl);
assert(TransCallExpr);
assert(TransitionFuncDecl);
const auto TransType = fuzzyNameToTransitionType(
TransitionFuncDecl->getCanonicalDecl()->getName());
auto SourceStateName = getName(*StateDecl);
// We only match transition functions that accept target state as a template
// parameter
// @TODO: support transition functions that accept StateFactory?
assert(TransitionFuncDecl->getTemplateSpecializationInfo());
const auto TSI = TransitionFuncDecl->getTemplateSpecializationInfo();
const TemplateArgument &TA = TSI->TemplateArguments->get(0);
const auto TargetStateName = getName(TA);
// If our transition is a state arg, we get the top-most transition's
// target state and assume that this target state is the one that will
// return the current transition. To do this, we track the top-most
// CallExpr -> TargetStateName mapping.
if (!ArgParentCallExpr) {
// We're top-most, remember current target state
assert(_callExprToTargetState.find(TransCallExpr) ==
_callExprToTargetState.end());
_callExprToTargetState[TransCallExpr] = TargetStateName;
} else {
// Othwerise, use immediate parent CallExpr's target state as our
// source state, and remember it for potential child CallExprs
auto iter = _callExprToTargetState.find(ArgParentCallExpr);
assert(iter != _callExprToTargetState.end());
_callExprToTargetState[TransCallExpr] = iter->second;
// Override the source state name with the top-most CallExpr one
SourceStateName = iter->second;
}
llvm::outs() << SourceStateName << " "
<< TransitionTypeVisualString[static_cast<int>(TransType)]
<< " " << TargetStateName << "\n";
}
};
int main(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
StateTransitionMapper Mapper;
MatchFinder Finder;
Finder.addMatcher(StateTransitionMatcher, &Mapper);
return Tool.run(newFrontendActionFactory(&Finder).get());
}
<commit_msg>Fix assert on non-templated transition functions (e.g. state overrides)<commit_after>// Declares clang::SyntaxOnlyAction.
#include "clang/Frontend/FrontendActions.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
// Declares llvm::cl::extrahelp.
#include "llvm/Support/CommandLine.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
using namespace clang;
using namespace clang::ast_matchers;
using namespace clang::tooling;
using namespace llvm;
// Apply a custom category to all command-line options so that they are the
// only ones displayed.
static llvm::cl::OptionCategory MyToolCategory("my-tool options");
// CommonOptionsParser declares HelpMessage with a description of the common
// command-line options related to the compilation database and input files.
// It's nice to have this help message in all tools.
static cl::extrahelp CommonHelp(CommonOptionsParser::HelpMessage);
// A help message for this specific tool can be added afterwards.
static cl::extrahelp MoreHelp("\nMore help text...");
namespace {
bool areSameVariable(const ValueDecl *First, const ValueDecl *Second) {
return First && Second &&
First->getCanonicalDecl() == Second->getCanonicalDecl();
}
bool areSameExpr(ASTContext *Context, const Expr *First, const Expr *Second) {
if (!First || !Second)
return false;
llvm::FoldingSetNodeID FirstID, SecondID;
First->Profile(FirstID, *Context, true);
Second->Profile(SecondID, *Context, true);
return FirstID == SecondID;
}
std::string getName(const CXXRecordDecl &RD) {
std::string NameWithTemplateArgs;
llvm::raw_string_ostream OS(NameWithTemplateArgs);
RD.getNameForDiagnostic(OS, RD.getASTContext().getPrintingPolicy(), true);
return OS.str();
}
std::string stringRemove(const std::string &S, const std::string &ToRemove) {
std::string Result;
size_t Index = 0, Off = 0;
while ((Index = S.find(ToRemove, Off)) != -1) {
Result += S.substr(Off, Index - Off);
Off = Index + ToRemove.length();
}
Result += S.substr(Off, S.length() - Off);
return Result;
}
std::string getName(const TemplateArgument &TA) {
auto Name = TA.getAsType().getAsString();
return stringRemove(stringRemove(Name, "struct "), "clang ");
}
} // namespace
enum class TransitionType {
Sibling,
Inner,
InnerEntry,
No,
};
static const char *TransitionTypeString[] = {"Sibling", "Inner", "InnerEntry",
"No"};
static const char *TransitionTypeVisualString[] = {"--->", "==>>", "===>",
"XXXX"};
inline TransitionType fuzzyNameToTransitionType(const StringRef &Name) {
auto contains = [](auto stringRef, auto s) {
return stringRef.find(s) != StringRef::npos;
};
if (contains(Name, "SiblingTransition"))
return TransitionType::Sibling;
if (contains(Name, "InnerTransition"))
return TransitionType::Inner;
if (contains(Name, "InnerEntryTransition"))
return TransitionType::InnerEntry;
assert(contains(Name, "No"));
return TransitionType::No;
}
// Matches declaration of transition functions that actually cause a transition
// to occur (i.e. everything except NoTransition)
const auto TransitionFunctionDecl = hasDeclaration(eachOf(
functionDecl(hasName("InnerTransition")).bind("trans_func_decl"),
functionDecl(hasName("InnerEntryTransition")).bind("trans_func_decl"),
functionDecl(hasName("SiblingTransition")).bind("trans_func_decl")));
// Matches transition function expressions (i.e. calls to transition functions)
const auto TransitionFunctionMatcher = callExpr(
expr().bind("call_expr"),
// Look for calls to transition functions
TransitionFunctionDecl,
// We track ancestor call expressions to determine if the call is actually a
// state arg
anyOf(hasAncestor(
callExpr(TransitionFunctionDecl).bind("arg_parent_call_expr")),
anything()));
// Matches transition function expressions within states
const auto StateTransitionMatcher =
cxxRecordDecl(decl().bind("state"), isDerivedFrom("hsm::State"),
forEachDescendant(TransitionFunctionMatcher));
class StateTransitionMapper : public MatchFinder::MatchCallback {
using TargetStateName = std::string;
std::map<const CallExpr *, TargetStateName> _callExprToTargetState;
public:
virtual void run(const MatchFinder::MatchResult &Result) {
const auto StateDecl = Result.Nodes.getNodeAs<CXXRecordDecl>("state");
const auto TransCallExpr = Result.Nodes.getNodeAs<CallExpr>("call_expr");
const auto TransitionFuncDecl =
Result.Nodes.getNodeAs<FunctionDecl>("trans_func_decl");
const auto ArgParentCallExpr =
Result.Nodes.getNodeAs<CallExpr>("arg_parent_call_expr");
assert(StateDecl);
assert(TransCallExpr);
assert(TransitionFuncDecl);
const auto TransType = fuzzyNameToTransitionType(
TransitionFuncDecl->getCanonicalDecl()->getName());
auto SourceStateName = getName(*StateDecl);
// We currently only support transition functions that accept target state
// as a template parameter.
// @TODO: support transition functions that accept StateFactory (e.g. state
// overrides).
const auto TSI = TransitionFuncDecl->getTemplateSpecializationInfo();
if (!TSI)
return;
const TemplateArgument &TA = TSI->TemplateArguments->get(0);
const auto TargetStateName = getName(TA);
// If our transition is a state arg, we get the top-most transition's
// target state and assume that this target state is the one that will
// return the current transition. To do this, we track the top-most
// CallExpr -> TargetStateName mapping.
if (!ArgParentCallExpr) {
// We're top-most, remember current target state
assert(_callExprToTargetState.find(TransCallExpr) ==
_callExprToTargetState.end());
_callExprToTargetState[TransCallExpr] = TargetStateName;
} else {
// Othwerise, use immediate parent CallExpr's target state as our
// source state, and remember it for potential child CallExprs
auto iter = _callExprToTargetState.find(ArgParentCallExpr);
assert(iter != _callExprToTargetState.end());
_callExprToTargetState[TransCallExpr] = iter->second;
// Override the source state name with the top-most CallExpr one
SourceStateName = iter->second;
}
llvm::outs() << SourceStateName << " "
<< TransitionTypeVisualString[static_cast<int>(TransType)]
<< " " << TargetStateName << "\n";
}
};
int main(int argc, const char **argv) {
CommonOptionsParser OptionsParser(argc, argv, MyToolCategory);
ClangTool Tool(OptionsParser.getCompilations(),
OptionsParser.getSourcePathList());
StateTransitionMapper Mapper;
MatchFinder Finder;
Finder.addMatcher(StateTransitionMatcher, &Mapper);
return Tool.run(newFrontendActionFactory(&Finder).get());
}
<|endoftext|> |
<commit_before>#include "pch.hpp"
#include "DependentGraphics.hpp"
#include "GameWindow.hpp"
#include "D3DHelpers.hpp"
#include <d3d11.h>
using namespace std::literals;
namespace dx
{
namespace Internal
{
template<typename T>
wrl::ComPtr<T> GetParent(IDXGIObject& object)
{
void* ptr;
TryHR(object.GetParent(__uuidof(T), &ptr));
return { static_cast<T*>(ptr) };
}
}
SwapChain::SwapChain(ID3D11Device& device, const GameWindow& window, const SwapChainOptions& options)
: options_{ options }
{
wrl::ComPtr<IDXGIDevice1> dxgiDevice;
TryHR(device.QueryInterface(dxgiDevice.GetAddressOf()));
const auto adapter = Internal::GetParent<IDXGIAdapter1>(Ref(dxgiDevice));
const auto factory = Internal::GetParent<IDXGIFactory1>(Ref(adapter));
DXGI_SWAP_CHAIN_DESC desc = {};
desc.BufferCount = gsl::narrow<UINT>(options.CountOfBackBuffers);
desc.BufferDesc.Width = gsl::narrow<UINT>(window.GetWidth());
desc.BufferDesc.Height = gsl::narrow<UINT>(window.GetHeight());
desc.BufferDesc.Format = static_cast<DXGI_FORMAT>(options.BackBufferFormat);
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.OutputWindow = window.NativeHandle();
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Windowed = options.Windowed == true ? TRUE : FALSE;
TryHR(factory->CreateSwapChain(&device, &desc, swapChain_.GetAddressOf()));
UpdateBuffers(device);
}
SwapChain::~SwapChain()
{
}
auto SwapChain::Front() -> BackBuffer&
{
return backBuffer_;
}
void SwapChain::Present()
{
TryHR(swapChain_->Present(0, 0));
}
void SwapChain::Reset()
{
backBuffer_.Reset();
}
//https://stackoverflow.com/questions/28095798/how-to-change-window-size-in-directx-11-desktop-application
void SwapChain::Resize(ID3D11Device& device, std::uint32_t height, std::uint32_t width)
{
TryHR(swapChain_->ResizeBuffers(options_.CountOfBackBuffers, gsl::narrow<UINT>(height), gsl::narrow<UINT>(width), static_cast<DXGI_FORMAT>(options_.BackBufferFormat), 0));
UpdateBuffers(device);
}
void SwapChain::UpdateBuffers(ID3D11Device& device)
{
//https://msdn.microsoft.com/en-us/library/windows/desktop/mt427784%28v=vs.85%29.aspx
//In Direct3D 11, applications could call GetBuffer(0, ) only once.Every call to Present implicitly changed the resource identity of the returned interface.
backBuffer_ = BackBuffer{device, GetBuffer(Ref(swapChain_), 0) };
}
wrl::ComPtr<ID3D11Texture2D> GetBuffer(IDXGISwapChain& swapChain, std::uint32_t index)
{
wrl::ComPtr<ID3D11Texture2D> tex;
void* ptr;
TryHR(swapChain.GetBuffer(gsl::narrow<UINT>(index), __uuidof(ID3D11Texture2D), &ptr));
tex.Attach(static_cast<ID3D11Texture2D*>(ptr));
//leak: return wrl::ComPtr<ID3D11Texture2D>{static_cast<ID3D11Texture2D*>(ptr)}
return tex;
}
BackBuffer::BackBuffer(ID3D11Device& device, wrl::ComPtr<ID3D11Texture2D> tex)
: tex_{std::move(tex)}
{
TryHR(device.CreateRenderTargetView(tex_.Get(), {}, rtView_.ReleaseAndGetAddressOf()));
SetName(Ref(tex_), "BackBuffer"sv);
}
void BackBuffer::Clear(ID3D11DeviceContext& context, DirectX::XMVECTOR color)
{
DirectX::XMFLOAT4 colorFloats;
DirectX::XMStoreFloat4(&colorFloats, color);
context.ClearRenderTargetView(rtView_.Get(), reinterpret_cast<const float*>(&colorFloats));
}
void BackBuffer::Reset() noexcept
{
rtView_.Reset();
tex_.Reset();
}
DepthStencil::DepthStencil(ID3D11Device & device, std::uint32_t width, std::uint32_t height, DxgiFormat format)
{
CD3D11_TEXTURE2D_DESC desc{
static_cast<DXGI_FORMAT>(format),
width,
height
};
desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
TryHR(device.CreateTexture2D(&desc, {}, tex_.GetAddressOf()));
SetName(Ref(tex_), "Depth Buffer");
D3D11_DEPTH_STENCIL_VIEW_DESC depthDesc{};
depthDesc.Format = static_cast<DXGI_FORMAT>(format);
depthDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
TryHR(device.CreateDepthStencilView(tex_.Get(), &depthDesc, view_.GetAddressOf()));
}
void DepthStencil::ClearDepth(ID3D11DeviceContext & context, float depth)
{
context.ClearDepthStencilView(&View(), D3D11_CLEAR_DEPTH, depth, {});
}
void DepthStencil::ClearStencil(ID3D11DeviceContext & context, std::uint8_t stencil)
{
context.ClearDepthStencilView(&View(), D3D11_CLEAR_STENCIL, {}, stencil);
}
void DepthStencil::ClearBoth(ID3D11DeviceContext& context, float depth, std::uint8_t stencil)
{
context.ClearDepthStencilView(&View(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, depth, stencil);
}
void DepthStencil::Reset()
{
view_.Reset();
tex_.Reset();
}
void DependentGraphics::Bind(ID3D11DeviceContext& context3D)
{
auto& backBuffer = SwapChain_.Front();
ID3D11RenderTargetView* views[] = { &backBuffer.RtView() };
context3D.OMSetRenderTargets(gsl::narrow<UINT>(std::size(views)), views, &DepthStencil_.View());
}
}<commit_msg>Fix a leak.<commit_after>#include "pch.hpp"
#include "DependentGraphics.hpp"
#include "GameWindow.hpp"
#include "D3DHelpers.hpp"
#include <d3d11.h>
using namespace std::literals;
namespace dx
{
namespace Internal
{
template<typename T>
wrl::ComPtr<T> GetParent(IDXGIObject& object)
{
void* ptr;
TryHR(object.GetParent(__uuidof(T), &ptr));
wrl::ComPtr<T> result;
result.Attach(static_cast<T*>(ptr));
return result;
}
}
SwapChain::SwapChain(ID3D11Device& device, const GameWindow& window, const SwapChainOptions& options)
: options_{ options }
{
wrl::ComPtr<IDXGIDevice1> dxgiDevice;
TryHR(device.QueryInterface(dxgiDevice.GetAddressOf()));
const auto adapter = Internal::GetParent<IDXGIAdapter1>(Ref(dxgiDevice));
const auto factory = Internal::GetParent<IDXGIFactory1>(Ref(adapter));
DXGI_SWAP_CHAIN_DESC desc = {};
desc.BufferCount = gsl::narrow<UINT>(options.CountOfBackBuffers);
desc.BufferDesc.Width = gsl::narrow<UINT>(window.GetWidth());
desc.BufferDesc.Height = gsl::narrow<UINT>(window.GetHeight());
desc.BufferDesc.Format = static_cast<DXGI_FORMAT>(options.BackBufferFormat);
desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.OutputWindow = window.NativeHandle();
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.Windowed = options.Windowed == true ? TRUE : FALSE;
TryHR(factory->CreateSwapChain(&device, &desc, swapChain_.GetAddressOf()));
UpdateBuffers(device);
}
SwapChain::~SwapChain()
{
}
auto SwapChain::Front() -> BackBuffer&
{
return backBuffer_;
}
void SwapChain::Present()
{
TryHR(swapChain_->Present(0, 0));
}
void SwapChain::Reset()
{
backBuffer_.Reset();
}
//https://stackoverflow.com/questions/28095798/how-to-change-window-size-in-directx-11-desktop-application
void SwapChain::Resize(ID3D11Device& device, std::uint32_t height, std::uint32_t width)
{
TryHR(swapChain_->ResizeBuffers(options_.CountOfBackBuffers, gsl::narrow<UINT>(height), gsl::narrow<UINT>(width), static_cast<DXGI_FORMAT>(options_.BackBufferFormat), 0));
UpdateBuffers(device);
}
void SwapChain::UpdateBuffers(ID3D11Device& device)
{
//https://msdn.microsoft.com/en-us/library/windows/desktop/mt427784%28v=vs.85%29.aspx
//In Direct3D 11, applications could call GetBuffer(0, ) only once.Every call to Present implicitly changed the resource identity of the returned interface.
backBuffer_ = BackBuffer{device, GetBuffer(Ref(swapChain_), 0) };
}
wrl::ComPtr<ID3D11Texture2D> GetBuffer(IDXGISwapChain& swapChain, std::uint32_t index)
{
wrl::ComPtr<ID3D11Texture2D> tex;
void* ptr;
TryHR(swapChain.GetBuffer(gsl::narrow<UINT>(index), __uuidof(ID3D11Texture2D), &ptr));
tex.Attach(static_cast<ID3D11Texture2D*>(ptr));
//leak: return wrl::ComPtr<ID3D11Texture2D>{static_cast<ID3D11Texture2D*>(ptr)}
return tex;
}
BackBuffer::BackBuffer(ID3D11Device& device, wrl::ComPtr<ID3D11Texture2D> tex)
: tex_{std::move(tex)}
{
TryHR(device.CreateRenderTargetView(tex_.Get(), {}, rtView_.ReleaseAndGetAddressOf()));
SetName(Ref(tex_), "BackBuffer"sv);
}
void BackBuffer::Clear(ID3D11DeviceContext& context, DirectX::XMVECTOR color)
{
DirectX::XMFLOAT4 colorFloats;
DirectX::XMStoreFloat4(&colorFloats, color);
context.ClearRenderTargetView(rtView_.Get(), reinterpret_cast<const float*>(&colorFloats));
}
void BackBuffer::Reset() noexcept
{
rtView_.Reset();
tex_.Reset();
}
DepthStencil::DepthStencil(ID3D11Device & device, std::uint32_t width, std::uint32_t height, DxgiFormat format)
{
CD3D11_TEXTURE2D_DESC desc{
static_cast<DXGI_FORMAT>(format),
width,
height
};
desc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
TryHR(device.CreateTexture2D(&desc, {}, tex_.GetAddressOf()));
SetName(Ref(tex_), "Depth Buffer");
D3D11_DEPTH_STENCIL_VIEW_DESC depthDesc{};
depthDesc.Format = static_cast<DXGI_FORMAT>(format);
depthDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
TryHR(device.CreateDepthStencilView(tex_.Get(), &depthDesc, view_.GetAddressOf()));
}
void DepthStencil::ClearDepth(ID3D11DeviceContext & context, float depth)
{
context.ClearDepthStencilView(&View(), D3D11_CLEAR_DEPTH, depth, {});
}
void DepthStencil::ClearStencil(ID3D11DeviceContext & context, std::uint8_t stencil)
{
context.ClearDepthStencilView(&View(), D3D11_CLEAR_STENCIL, {}, stencil);
}
void DepthStencil::ClearBoth(ID3D11DeviceContext& context, float depth, std::uint8_t stencil)
{
context.ClearDepthStencilView(&View(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, depth, stencil);
}
void DepthStencil::Reset()
{
view_.Reset();
tex_.Reset();
}
void DependentGraphics::Bind(ID3D11DeviceContext& context3D)
{
auto& backBuffer = SwapChain_.Front();
ID3D11RenderTargetView* views[] = { &backBuffer.RtView() };
context3D.OMSetRenderTargets(gsl::narrow<UINT>(std::size(views)), views, &DepthStencil_.View());
}
}<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "PostprocessWindow.h"
#include <thread>
#include <Commdlg.h> // openfile
#include <WinBase.h>
using namespace std;
using namespace wiGraphicsTypes;
PostprocessWindow::PostprocessWindow(wiGUI* gui, Renderable3DComponent* comp) : GUI(gui), component(comp)
{
assert(component && "PostprocessWnd invalid component!");
assert(GUI && "Invalid GUI!");
float screenW = (float)wiRenderer::GetDevice()->GetScreenWidth();
float screenH = (float)wiRenderer::GetDevice()->GetScreenHeight();
ppWindow = new wiWindow(GUI, "PostProcess Window");
ppWindow->SetSize(XMFLOAT2(360, 520));
GUI->AddWidget(ppWindow);
float x = 110;
float y = 0;
lensFlareCheckBox = new wiCheckBox("LensFlare: ");
lensFlareCheckBox->SetTooltip("Toggle visibility of light source flares. Additional setup needed per light for a lensflare to be visible.");
lensFlareCheckBox->SetScriptTip("Renderable3DComponent::SetLensFlareEnabled(bool value)");
lensFlareCheckBox->SetPos(XMFLOAT2(x, y += 35));
lensFlareCheckBox->SetCheck(component->getLensFlareEnabled());
lensFlareCheckBox->OnClick([&](wiEventArgs args) {
component->setLensFlareEnabled(args.bValue);
});
ppWindow->AddWidget(lensFlareCheckBox);
lightShaftsCheckBox = new wiCheckBox("LightShafts: ");
lightShaftsCheckBox->SetTooltip("Enable light shaft for directional light sources.");
lightShaftsCheckBox->SetScriptTip("Renderable3DComponent::SetLightShaftsEnabled(bool value)");
lightShaftsCheckBox->SetPos(XMFLOAT2(x, y += 35));
lightShaftsCheckBox->SetCheck(component->getLightShaftsEnabled());
lightShaftsCheckBox->OnClick([&](wiEventArgs args) {
component->setLightShaftsEnabled(args.bValue);
});
ppWindow->AddWidget(lightShaftsCheckBox);
ssaoCheckBox = new wiCheckBox("SSAO: ");
ssaoCheckBox->SetTooltip("Enable Screen Space Ambient Occlusion. (Deferred only for now)");
ssaoCheckBox->SetScriptTip("Renderable3DComponent::SetSSAOEnabled(bool value)");
ssaoCheckBox->SetPos(XMFLOAT2(x, y += 35));
ssaoCheckBox->SetCheck(component->getSSAOEnabled());
ssaoCheckBox->OnClick([&](wiEventArgs args) {
component->setSSAOEnabled(args.bValue);
});
ppWindow->AddWidget(ssaoCheckBox);
ssrCheckBox = new wiCheckBox("SSR: ");
ssrCheckBox->SetTooltip("Enable Screen Space Reflections. (Deferred only for now)");
ssrCheckBox->SetScriptTip("Renderable3DComponent::SetSSREnabled(bool value)");
ssrCheckBox->SetPos(XMFLOAT2(x, y += 35));
ssrCheckBox->SetCheck(component->getSSREnabled());
ssrCheckBox->OnClick([&](wiEventArgs args) {
component->setSSREnabled(args.bValue);
});
ppWindow->AddWidget(ssrCheckBox);
sssCheckBox = new wiCheckBox("SSS: ");
sssCheckBox->SetTooltip("Enable Subsurface Scattering. (Deferred only for now)");
sssCheckBox->SetScriptTip("Renderable3DComponent::SetSSSEnabled(bool value)");
sssCheckBox->SetPos(XMFLOAT2(x, y += 35));
sssCheckBox->SetCheck(component->getSSSEnabled());
sssCheckBox->OnClick([&](wiEventArgs args) {
component->setSSSEnabled(args.bValue);
});
ppWindow->AddWidget(sssCheckBox);
eyeAdaptionCheckBox = new wiCheckBox("EyeAdaption: ");
eyeAdaptionCheckBox->SetTooltip("Enable eye adaption for the overall screen luminance");
eyeAdaptionCheckBox->SetPos(XMFLOAT2(x, y += 35));
eyeAdaptionCheckBox->SetCheck(component->getEyeAdaptionEnabled());
eyeAdaptionCheckBox->OnClick([&](wiEventArgs args) {
component->setEyeAdaptionEnabled(args.bValue);
});
ppWindow->AddWidget(eyeAdaptionCheckBox);
motionBlurCheckBox = new wiCheckBox("MotionBlur: ");
motionBlurCheckBox->SetTooltip("Enable motion blur for camera movement and animated meshes.");
motionBlurCheckBox->SetScriptTip("Renderable3DComponent::SetMotionBlurEnabled(bool value)");
motionBlurCheckBox->SetPos(XMFLOAT2(x, y += 35));
motionBlurCheckBox->SetCheck(component->getMotionBlurEnabled());
motionBlurCheckBox->OnClick([&](wiEventArgs args) {
component->setMotionBlurEnabled(args.bValue);
});
ppWindow->AddWidget(motionBlurCheckBox);
depthOfFieldCheckBox = new wiCheckBox("DepthOfField: ");
depthOfFieldCheckBox->SetTooltip("Enable Depth of field effect. Additional focus and strength setup required.");
depthOfFieldCheckBox->SetScriptTip("Renderable3DComponent::SetDepthOfFieldEnabled(bool value)");
depthOfFieldCheckBox->SetPos(XMFLOAT2(x, y += 35));
depthOfFieldCheckBox->SetCheck(component->getDepthOfFieldEnabled());
depthOfFieldCheckBox->OnClick([&](wiEventArgs args) {
component->setDepthOfFieldEnabled(args.bValue);
});
ppWindow->AddWidget(depthOfFieldCheckBox);
depthOfFieldFocusSlider = new wiSlider(0.01f, 600, 100, 10000, "Focus: ");
depthOfFieldFocusSlider->SetTooltip("Set the focus distance from the camera. The picture will be sharper near the focus, and blurrier further from it.");
depthOfFieldFocusSlider->SetScriptTip("Renderable3DComponent::SetDepthOfFieldFocus(float value)");
depthOfFieldFocusSlider->SetSize(XMFLOAT2(100, 20));
depthOfFieldFocusSlider->SetPos(XMFLOAT2(x + 100, y));
depthOfFieldFocusSlider->SetValue(component->getDepthOfFieldFocus());
depthOfFieldFocusSlider->OnSlide([&](wiEventArgs args) {
component->setDepthOfFieldFocus(args.fValue);
});
ppWindow->AddWidget(depthOfFieldFocusSlider);
depthOfFieldStrengthSlider = new wiSlider(0.01f, 4, 100, 1000, "Strength: ");
depthOfFieldStrengthSlider->SetTooltip("Set depth of field blur strength.");
depthOfFieldStrengthSlider->SetScriptTip("Renderable3DComponent::SetDepthOfFieldStrength(float value)");
depthOfFieldStrengthSlider->SetSize(XMFLOAT2(100, 20));
depthOfFieldStrengthSlider->SetPos(XMFLOAT2(x + 100, y += 35));
depthOfFieldStrengthSlider->SetValue(component->getDepthOfFieldStrength());
depthOfFieldStrengthSlider->OnSlide([&](wiEventArgs args) {
component->setDepthOfFieldStrength(args.fValue);
});
ppWindow->AddWidget(depthOfFieldStrengthSlider);
bloomCheckBox = new wiCheckBox("Bloom: ");
bloomCheckBox->SetTooltip("Enable bloom. The effect adds color bleeding to the brightest parts of the scene.");
bloomCheckBox->SetScriptTip("Renderable3DComponent::SetBloomEnabled(bool value)");
bloomCheckBox->SetPos(XMFLOAT2(x, y += 35));
bloomCheckBox->SetCheck(component->getBloomEnabled());
bloomCheckBox->OnClick([&](wiEventArgs args) {
component->setBloomEnabled(args.bValue);
});
ppWindow->AddWidget(bloomCheckBox);
fxaaCheckBox = new wiCheckBox("FXAA: ");
fxaaCheckBox->SetTooltip("Fast Approximate Anti Aliasing. A fast antialiasing method, but can be a bit too blurry.");
fxaaCheckBox->SetScriptTip("Renderable3DComponent::SetFXAAEnabled(bool value)");
fxaaCheckBox->SetPos(XMFLOAT2(x, y += 35));
fxaaCheckBox->SetCheck(component->getFXAAEnabled());
fxaaCheckBox->OnClick([&](wiEventArgs args) {
component->setFXAAEnabled(args.bValue);
});
ppWindow->AddWidget(fxaaCheckBox);
colorGradingCheckBox = new wiCheckBox("Color Grading: ");
colorGradingCheckBox->SetTooltip("Enable color grading of the final render. An additional lookup texture must be set for it to take effect.");
colorGradingCheckBox->SetScriptTip("Renderable3DComponent::SetColorGradingEnabled(bool value)");
colorGradingCheckBox->SetPos(XMFLOAT2(x, y += 35));
colorGradingCheckBox->SetCheck(component->getColorGradingEnabled());
colorGradingCheckBox->OnClick([&](wiEventArgs args) {
component->setColorGradingEnabled(args.bValue);
});
ppWindow->AddWidget(colorGradingCheckBox);
colorGradingButton = new wiButton("Load Color Grading LUT...");
colorGradingButton->SetTooltip("Load a color grading lookup texture...");
colorGradingButton->SetPos(XMFLOAT2(x + 35, y));
colorGradingButton->SetSize(XMFLOAT2(200, 18));
colorGradingButton->OnClick([=](wiEventArgs args) {
auto x = wiRenderer::GetColorGrading();
if (x == nullptr)
{
thread([&] {
char szFile[260];
OPENFILENAMEA ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = nullptr;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Color Grading texture\0*.dds;*.png;*.tga\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileNameA(&ofn) == TRUE) {
string fileName = ofn.lpstrFile;
wiRenderer::SetColorGrading((Texture2D*)wiResourceManager::GetGlobal()->add(fileName));
colorGradingButton->SetText(fileName);
}
}).detach();
}
else
{
wiRenderer::SetColorGrading(nullptr);
colorGradingButton->SetText("Load Color Grading LUT...");
}
});
ppWindow->AddWidget(colorGradingButton);
stereogramCheckBox = new wiCheckBox("Stereogram: ");
stereogramCheckBox->SetTooltip("Compute a stereogram from the depth buffer. It produces a 3D sihouette image when viewed cross eyed.");
stereogramCheckBox->SetScriptTip("Renderable3DComponent::SetStereogramEnabled(bool value)");
stereogramCheckBox->SetPos(XMFLOAT2(x, y += 35));
stereogramCheckBox->SetCheck(component->getStereogramEnabled());
stereogramCheckBox->OnClick([&](wiEventArgs args) {
component->setStereogramEnabled(args.bValue);
});
ppWindow->AddWidget(stereogramCheckBox);
sharpenFilterCheckBox = new wiCheckBox("Sharpen Filter: ");
sharpenFilterCheckBox->SetTooltip("Toggle sharpening post process of the final image.");
sharpenFilterCheckBox->SetScriptTip("Renderable3DComponent::SetSharpenFilterEnabled(bool value)");
sharpenFilterCheckBox->SetPos(XMFLOAT2(x, y += 35));
sharpenFilterCheckBox->SetCheck(component->getSharpenFilterEnabled());
sharpenFilterCheckBox->OnClick([&](wiEventArgs args) {
component->setSharpenFilterEnabled(args.bValue);
});
ppWindow->AddWidget(sharpenFilterCheckBox);
sharpenFilterAmountSlider = new wiSlider(0, 4, 1, 1000, "Amount: ");
sharpenFilterAmountSlider->SetTooltip("Set sharpness filter strength.");
sharpenFilterAmountSlider->SetScriptTip("Renderable3DComponent::SetSharpenFilterAmount(float value)");
sharpenFilterAmountSlider->SetSize(XMFLOAT2(100, 20));
sharpenFilterAmountSlider->SetPos(XMFLOAT2(x + 100, y));
sharpenFilterAmountSlider->SetValue(component->getSharpenFilterAmount());
sharpenFilterAmountSlider->OnSlide([&](wiEventArgs args) {
component->setSharpenFilterAmount(args.fValue);
});
ppWindow->AddWidget(sharpenFilterAmountSlider);
ppWindow->Translate(XMFLOAT3(screenW - 380, 50, 0));
ppWindow->SetVisible(false);
}
PostprocessWindow::~PostprocessWindow()
{
ppWindow->RemoveWidgets(true);
GUI->RemoveWidget(ppWindow);
SAFE_DELETE(ppWindow);
}
<commit_msg>ssr and ssao no longer deferred only<commit_after>#include "stdafx.h"
#include "PostprocessWindow.h"
#include <thread>
#include <Commdlg.h> // openfile
#include <WinBase.h>
using namespace std;
using namespace wiGraphicsTypes;
PostprocessWindow::PostprocessWindow(wiGUI* gui, Renderable3DComponent* comp) : GUI(gui), component(comp)
{
assert(component && "PostprocessWnd invalid component!");
assert(GUI && "Invalid GUI!");
float screenW = (float)wiRenderer::GetDevice()->GetScreenWidth();
float screenH = (float)wiRenderer::GetDevice()->GetScreenHeight();
ppWindow = new wiWindow(GUI, "PostProcess Window");
ppWindow->SetSize(XMFLOAT2(360, 520));
GUI->AddWidget(ppWindow);
float x = 110;
float y = 0;
lensFlareCheckBox = new wiCheckBox("LensFlare: ");
lensFlareCheckBox->SetTooltip("Toggle visibility of light source flares. Additional setup needed per light for a lensflare to be visible.");
lensFlareCheckBox->SetScriptTip("Renderable3DComponent::SetLensFlareEnabled(bool value)");
lensFlareCheckBox->SetPos(XMFLOAT2(x, y += 35));
lensFlareCheckBox->SetCheck(component->getLensFlareEnabled());
lensFlareCheckBox->OnClick([&](wiEventArgs args) {
component->setLensFlareEnabled(args.bValue);
});
ppWindow->AddWidget(lensFlareCheckBox);
lightShaftsCheckBox = new wiCheckBox("LightShafts: ");
lightShaftsCheckBox->SetTooltip("Enable light shaft for directional light sources.");
lightShaftsCheckBox->SetScriptTip("Renderable3DComponent::SetLightShaftsEnabled(bool value)");
lightShaftsCheckBox->SetPos(XMFLOAT2(x, y += 35));
lightShaftsCheckBox->SetCheck(component->getLightShaftsEnabled());
lightShaftsCheckBox->OnClick([&](wiEventArgs args) {
component->setLightShaftsEnabled(args.bValue);
});
ppWindow->AddWidget(lightShaftsCheckBox);
ssaoCheckBox = new wiCheckBox("SSAO: ");
ssaoCheckBox->SetTooltip("Enable Screen Space Ambient Occlusion.");
ssaoCheckBox->SetScriptTip("Renderable3DComponent::SetSSAOEnabled(bool value)");
ssaoCheckBox->SetPos(XMFLOAT2(x, y += 35));
ssaoCheckBox->SetCheck(component->getSSAOEnabled());
ssaoCheckBox->OnClick([&](wiEventArgs args) {
component->setSSAOEnabled(args.bValue);
});
ppWindow->AddWidget(ssaoCheckBox);
ssrCheckBox = new wiCheckBox("SSR: ");
ssrCheckBox->SetTooltip("Enable Screen Space Reflections.");
ssrCheckBox->SetScriptTip("Renderable3DComponent::SetSSREnabled(bool value)");
ssrCheckBox->SetPos(XMFLOAT2(x, y += 35));
ssrCheckBox->SetCheck(component->getSSREnabled());
ssrCheckBox->OnClick([&](wiEventArgs args) {
component->setSSREnabled(args.bValue);
});
ppWindow->AddWidget(ssrCheckBox);
sssCheckBox = new wiCheckBox("SSS: ");
sssCheckBox->SetTooltip("Enable Subsurface Scattering. (Deferred only for now)");
sssCheckBox->SetScriptTip("Renderable3DComponent::SetSSSEnabled(bool value)");
sssCheckBox->SetPos(XMFLOAT2(x, y += 35));
sssCheckBox->SetCheck(component->getSSSEnabled());
sssCheckBox->OnClick([&](wiEventArgs args) {
component->setSSSEnabled(args.bValue);
});
ppWindow->AddWidget(sssCheckBox);
eyeAdaptionCheckBox = new wiCheckBox("EyeAdaption: ");
eyeAdaptionCheckBox->SetTooltip("Enable eye adaption for the overall screen luminance");
eyeAdaptionCheckBox->SetPos(XMFLOAT2(x, y += 35));
eyeAdaptionCheckBox->SetCheck(component->getEyeAdaptionEnabled());
eyeAdaptionCheckBox->OnClick([&](wiEventArgs args) {
component->setEyeAdaptionEnabled(args.bValue);
});
ppWindow->AddWidget(eyeAdaptionCheckBox);
motionBlurCheckBox = new wiCheckBox("MotionBlur: ");
motionBlurCheckBox->SetTooltip("Enable motion blur for camera movement and animated meshes.");
motionBlurCheckBox->SetScriptTip("Renderable3DComponent::SetMotionBlurEnabled(bool value)");
motionBlurCheckBox->SetPos(XMFLOAT2(x, y += 35));
motionBlurCheckBox->SetCheck(component->getMotionBlurEnabled());
motionBlurCheckBox->OnClick([&](wiEventArgs args) {
component->setMotionBlurEnabled(args.bValue);
});
ppWindow->AddWidget(motionBlurCheckBox);
depthOfFieldCheckBox = new wiCheckBox("DepthOfField: ");
depthOfFieldCheckBox->SetTooltip("Enable Depth of field effect. Additional focus and strength setup required.");
depthOfFieldCheckBox->SetScriptTip("Renderable3DComponent::SetDepthOfFieldEnabled(bool value)");
depthOfFieldCheckBox->SetPos(XMFLOAT2(x, y += 35));
depthOfFieldCheckBox->SetCheck(component->getDepthOfFieldEnabled());
depthOfFieldCheckBox->OnClick([&](wiEventArgs args) {
component->setDepthOfFieldEnabled(args.bValue);
});
ppWindow->AddWidget(depthOfFieldCheckBox);
depthOfFieldFocusSlider = new wiSlider(0.01f, 600, 100, 10000, "Focus: ");
depthOfFieldFocusSlider->SetTooltip("Set the focus distance from the camera. The picture will be sharper near the focus, and blurrier further from it.");
depthOfFieldFocusSlider->SetScriptTip("Renderable3DComponent::SetDepthOfFieldFocus(float value)");
depthOfFieldFocusSlider->SetSize(XMFLOAT2(100, 20));
depthOfFieldFocusSlider->SetPos(XMFLOAT2(x + 100, y));
depthOfFieldFocusSlider->SetValue(component->getDepthOfFieldFocus());
depthOfFieldFocusSlider->OnSlide([&](wiEventArgs args) {
component->setDepthOfFieldFocus(args.fValue);
});
ppWindow->AddWidget(depthOfFieldFocusSlider);
depthOfFieldStrengthSlider = new wiSlider(0.01f, 4, 100, 1000, "Strength: ");
depthOfFieldStrengthSlider->SetTooltip("Set depth of field blur strength.");
depthOfFieldStrengthSlider->SetScriptTip("Renderable3DComponent::SetDepthOfFieldStrength(float value)");
depthOfFieldStrengthSlider->SetSize(XMFLOAT2(100, 20));
depthOfFieldStrengthSlider->SetPos(XMFLOAT2(x + 100, y += 35));
depthOfFieldStrengthSlider->SetValue(component->getDepthOfFieldStrength());
depthOfFieldStrengthSlider->OnSlide([&](wiEventArgs args) {
component->setDepthOfFieldStrength(args.fValue);
});
ppWindow->AddWidget(depthOfFieldStrengthSlider);
bloomCheckBox = new wiCheckBox("Bloom: ");
bloomCheckBox->SetTooltip("Enable bloom. The effect adds color bleeding to the brightest parts of the scene.");
bloomCheckBox->SetScriptTip("Renderable3DComponent::SetBloomEnabled(bool value)");
bloomCheckBox->SetPos(XMFLOAT2(x, y += 35));
bloomCheckBox->SetCheck(component->getBloomEnabled());
bloomCheckBox->OnClick([&](wiEventArgs args) {
component->setBloomEnabled(args.bValue);
});
ppWindow->AddWidget(bloomCheckBox);
fxaaCheckBox = new wiCheckBox("FXAA: ");
fxaaCheckBox->SetTooltip("Fast Approximate Anti Aliasing. A fast antialiasing method, but can be a bit too blurry.");
fxaaCheckBox->SetScriptTip("Renderable3DComponent::SetFXAAEnabled(bool value)");
fxaaCheckBox->SetPos(XMFLOAT2(x, y += 35));
fxaaCheckBox->SetCheck(component->getFXAAEnabled());
fxaaCheckBox->OnClick([&](wiEventArgs args) {
component->setFXAAEnabled(args.bValue);
});
ppWindow->AddWidget(fxaaCheckBox);
colorGradingCheckBox = new wiCheckBox("Color Grading: ");
colorGradingCheckBox->SetTooltip("Enable color grading of the final render. An additional lookup texture must be set for it to take effect.");
colorGradingCheckBox->SetScriptTip("Renderable3DComponent::SetColorGradingEnabled(bool value)");
colorGradingCheckBox->SetPos(XMFLOAT2(x, y += 35));
colorGradingCheckBox->SetCheck(component->getColorGradingEnabled());
colorGradingCheckBox->OnClick([&](wiEventArgs args) {
component->setColorGradingEnabled(args.bValue);
});
ppWindow->AddWidget(colorGradingCheckBox);
colorGradingButton = new wiButton("Load Color Grading LUT...");
colorGradingButton->SetTooltip("Load a color grading lookup texture...");
colorGradingButton->SetPos(XMFLOAT2(x + 35, y));
colorGradingButton->SetSize(XMFLOAT2(200, 18));
colorGradingButton->OnClick([=](wiEventArgs args) {
auto x = wiRenderer::GetColorGrading();
if (x == nullptr)
{
thread([&] {
char szFile[260];
OPENFILENAMEA ofn;
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = nullptr;
ofn.lpstrFile = szFile;
// Set lpstrFile[0] to '\0' so that GetOpenFileName does not
// use the contents of szFile to initialize itself.
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Color Grading texture\0*.dds;*.png;*.tga\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileNameA(&ofn) == TRUE) {
string fileName = ofn.lpstrFile;
wiRenderer::SetColorGrading((Texture2D*)wiResourceManager::GetGlobal()->add(fileName));
colorGradingButton->SetText(fileName);
}
}).detach();
}
else
{
wiRenderer::SetColorGrading(nullptr);
colorGradingButton->SetText("Load Color Grading LUT...");
}
});
ppWindow->AddWidget(colorGradingButton);
stereogramCheckBox = new wiCheckBox("Stereogram: ");
stereogramCheckBox->SetTooltip("Compute a stereogram from the depth buffer. It produces a 3D sihouette image when viewed cross eyed.");
stereogramCheckBox->SetScriptTip("Renderable3DComponent::SetStereogramEnabled(bool value)");
stereogramCheckBox->SetPos(XMFLOAT2(x, y += 35));
stereogramCheckBox->SetCheck(component->getStereogramEnabled());
stereogramCheckBox->OnClick([&](wiEventArgs args) {
component->setStereogramEnabled(args.bValue);
});
ppWindow->AddWidget(stereogramCheckBox);
sharpenFilterCheckBox = new wiCheckBox("Sharpen Filter: ");
sharpenFilterCheckBox->SetTooltip("Toggle sharpening post process of the final image.");
sharpenFilterCheckBox->SetScriptTip("Renderable3DComponent::SetSharpenFilterEnabled(bool value)");
sharpenFilterCheckBox->SetPos(XMFLOAT2(x, y += 35));
sharpenFilterCheckBox->SetCheck(component->getSharpenFilterEnabled());
sharpenFilterCheckBox->OnClick([&](wiEventArgs args) {
component->setSharpenFilterEnabled(args.bValue);
});
ppWindow->AddWidget(sharpenFilterCheckBox);
sharpenFilterAmountSlider = new wiSlider(0, 4, 1, 1000, "Amount: ");
sharpenFilterAmountSlider->SetTooltip("Set sharpness filter strength.");
sharpenFilterAmountSlider->SetScriptTip("Renderable3DComponent::SetSharpenFilterAmount(float value)");
sharpenFilterAmountSlider->SetSize(XMFLOAT2(100, 20));
sharpenFilterAmountSlider->SetPos(XMFLOAT2(x + 100, y));
sharpenFilterAmountSlider->SetValue(component->getSharpenFilterAmount());
sharpenFilterAmountSlider->OnSlide([&](wiEventArgs args) {
component->setSharpenFilterAmount(args.fValue);
});
ppWindow->AddWidget(sharpenFilterAmountSlider);
ppWindow->Translate(XMFLOAT3(screenW - 380, 50, 0));
ppWindow->SetVisible(false);
}
PostprocessWindow::~PostprocessWindow()
{
ppWindow->RemoveWidgets(true);
GUI->RemoveWidget(ppWindow);
SAFE_DELETE(ppWindow);
}
<|endoftext|> |
<commit_before>#include <string>
#include <mutex>
#include <queue>
#include <vector>
#include <cstdint>
#include <iostream>
#include <pthread.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
typedef enum
{
extract_image,
extract_audio,
upscale_image,
render_video
} work_t;
typedef struct
{
uint64_t id;
std::string *working_dir;
std::string *command;
std::mutex *work_lock;
std::queue<uint64_t> *deps;
work_t type;
bool done;
} work_unit_t;
void create_thread(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
{
int rc = pthread_create(thread, attr, start_routine, arg);
if (rc)
{
std::cerr << "Could not create thread." << std::endl;
exit(1);
}
}
bool valid(const std::string &file)
{
std::vector<std::string> extensions = {"mp4", "mkv", "m4v", "avi"};
for (auto itr = extensions.begin(); itr != extensions.end(); itr++)
{
if (file.size() >= itr -> size() && file.compare(file.size() - itr -> size(), itr -> size(), *itr) == 0) { return true; }
}
return false;
}
bool valid(const char *file)
{
std::string temp = std::string(file);
return valid(temp);
}
bool isext(const char *file, const char *ext)
{
size_t file_len = strlen(file);
size_t ext_len = strlen(ext);
if (file_len < ext_len) { return false; }
if (strcmp((const char *) file + file_len - ext_len, ext))
{
return false;
}
return true;
}
bool dir_exists(const char *path)
{
DIR *dir = opendir(path);
if (dir)
{
closedir(dir);
return true;
}
else if (errno == ENOENT)
{
return false;
}
else
{
std::cerr << std::strerror(errno) << std::endl;
exit(errno);
}
}
void create_dir_tree(const char *base_path, const char *data_path)
{
std::string ptemp = base_path;
std::vector<std::string> to_create = {"/images", "/out", "/images/original", "/images/upscaled"};
ptemp += "/";
ptemp += data_path;
if (mkdir(ptemp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
{
if (errno != EEXIST)
{
std::cerr << std::strerror(errno) << std::endl;
exit(errno);
}
}
for (auto itr = to_create.begin(); itr != to_create.end(); itr++)
{
ptemp = base_path;
ptemp += "/";
ptemp += data_path;
ptemp += *itr;
if (mkdir(ptemp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
{
if (errno != EEXIST)
{
std::cerr << std::strerror(errno) << std::endl;
exit(errno);
}
}
}
}
void make_work(std::vector<work_unit_t *> *work, DIR *dir, const char *base_path)
{
dirent *dp = NULL;
struct stat st;
std::vector<std::string> dirs;
std::vector<std::string> files;
//bool match_dir;
std::string dtemp;
std::string ftemp;
std::string ptemp;
std::string data_dir;
std::string original_image_dir;
std::string upscaled_image_dir;
std::string output_dir;
bool orig_img;
bool upscale_img;
bool video;
bool audio;
work_unit_t *wtemp;
uint64_t orig_img_id;
uint64_t audio_id;
uint64_t upscale_img_id;
DIR *dptemp;
while (dir)
{
dp = readdir(dir);
if (dp != NULL)
{
ptemp = base_path;
ptemp += "/";
ptemp += dp -> d_name;
if (lstat(ptemp.c_str(), &st) == 0)
{
if (S_ISDIR(st.st_mode))
{
dirs.push_back(std::string(dp -> d_name));
}
else
{
files.push_back(std::string(dp -> d_name));
}
}
else
{
std::cerr << std::strerror(errno) << std::endl;
closedir(dir);
exit(errno);
}
}
else
{
closedir(dir); //ensure that this gets called - errors from lstat or readdir may cause this to fail
break;
}
}
//if (dp) { delete dp; }
for (auto fitr = files.begin(); fitr != files.end(); fitr++)
{
if (valid(*fitr))
{
create_dir_tree(base_path, fitr -> substr(0, fitr -> find_last_of(".")).c_str());
data_dir = base_path;
data_dir += "/";
data_dir += fitr -> substr(0, fitr -> find_last_of("."));
original_image_dir = data_dir;
original_image_dir += "/images/original";
upscaled_image_dir = data_dir;
upscaled_image_dir += "/images/upscaled";
output_dir = data_dir;
output_dir += "/out";
orig_img = false;
upscale_img = false;
video = false;
audio = false;
//check for existing extracted images
dptemp = opendir(original_image_dir.c_str());
while (dptemp)
{
dp = readdir(dptemp);
if (dp != NULL)
{
if (isext(dp -> d_name, "png"))
{
orig_img = true;
closedir(dptemp);
break;
}
}
else
{
closedir(dptemp);
break;
}
}
//check for any upscaled images
dptemp = opendir(upscaled_image_dir.c_str());
while (dptemp)
{
dp = readdir(dptemp);
if (dp != NULL)
{
if (isext(dp -> d_name, "png"))
{
upscale_img = true;
closedir(dptemp);
break;
}
}
else
{
closedir(dptemp);
break;
}
}
//check for video
dptemp = opendir(output_dir.c_str());
while (dptemp)
{
dp = readdir(dptemp);
if (dp != NULL)
{
if (valid(dp -> d_name))
{
video = true;
closedir(dptemp);
break;
}
}
else
{
closedir(dptemp);
break;
}
}
dptemp = opendir(data_dir.c_str());
while (dptemp)
{
dp = readdir(dptemp);
if (dp != NULL)
{
if (strcmp("audio", dp -> d_name) == 0)
{
audio = true;
closedir(dptemp);
break;
}
}
else
{
closedir(dptemp);
break;
}
}
if (!orig_img && !video)
{
wtemp = new work_unit_t;
wtemp -> id = work -> size();
orig_img_id = wtemp -> id;
wtemp -> working_dir = new std::string(original_image_dir);
wtemp -> command = new std::string("ffmpeg -i ../../");
*(wtemp -> command) += *fitr;
*(wtemp -> command) += " %05d.png";
wtemp -> work_lock = new std::mutex;
wtemp -> deps = new std::queue<uint64_t>;
wtemp -> type = extract_image;
wtemp -> done = false;
work -> push_back(wtemp);
}
if (!upscale_img && !video)
{
wtemp = new work_unit_t;
wtemp -> id = work -> size();
upscale_img_id = wtemp -> id;
wtemp -> working_dir = new std::string(original_image_dir);
wtemp -> command = new std::string("for f in *; do waifu2x -i $f -o ../upscaled/$f; done");
wtemp -> work_lock = new std::mutex;
wtemp -> deps = new std::queue<uint64_t>;
wtemp -> type = upscale_image;
wtemp -> done = false;
if (!orig_img)
{
wtemp -> deps -> push(orig_img_id);
}
work -> push_back(wtemp);
}
if (!audio && !video)
{
wtemp = new work_unit_t;
wtemp -> id = work -> size();
audio_id = wtemp -> id;
wtemp -> working_dir = new std::string(data_dir);
wtemp -> command = new std::string("ffmpeg -i ../");
*(wtemp -> command) += *fitr;
*(wtemp -> command) += " -vn -acodec copy audio.ext";
wtemp -> work_lock = new std::mutex;
wtemp -> deps = new std::queue<uint64_t>;
wtemp -> type = extract_audio;
wtemp -> done = false;
work -> push_back(wtemp);
}
if (!video)
{
wtemp = new work_unit_t;
wtemp -> id = work -> size();
wtemp -> working_dir = new std::string(output_dir);
wtemp -> command = new std::string("ffmpeg -framerate 30 -i ../images/upscaled/%05d.png -i ../audio.ext -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -pix_fmt yuv420p");
*(wtemp -> command) += *fitr;
wtemp -> work_lock = new std::mutex;
wtemp -> deps = new std::queue<uint64_t>;
wtemp -> type = render_video;
wtemp -> done = false;
if (!orig_img)
{
wtemp -> deps -> push(orig_img_id);
}
if (!upscale_img)
{
wtemp -> deps -> push(upscale_img_id);
}
if (!audio)
{
wtemp -> deps -> push(audio_id);
}
work -> push_back(wtemp);
}
}
}
/* a miracle happens */
for (auto ditr = dirs.begin(); ditr != dirs.end(); ditr++)
{
if (ditr -> compare(".") && ditr -> compare(".."))
{
ptemp = base_path;
ptemp += "/";
ptemp += *ditr;
dptemp = opendir(ptemp.c_str());
make_work(work, dptemp, ptemp.c_str());
}
}
//if (dp) { delete dp; }
}
void do_work(std::vector<work_unit_t *> *work, std::mutex *vector_lock)
{
for (auto itr = work -> begin(); itr != work -> end(); itr++)
{
std::cout << *((*itr) -> command);
}
}
int main(int argc, char** argv)
{
std::vector<work_unit_t*> work;
std::mutex vector_lock;
size_t buf_size = 1024;
char* buf = new char[buf_size];
if (argc > 1)
{
strcpy(buf, argv[1]);
}
else if (getcwd(buf, buf_size) == NULL)
{
std::cerr << std::strerror(errno) << std::endl;
return errno;
}
DIR *dir = opendir(buf);
make_work(&work, dir, buf);
do_work(&work, &vector_lock);
delete[] buf;
return 0;
}
<commit_msg>fixed quotes<commit_after>#include <string>
#include <mutex>
#include <queue>
#include <vector>
#include <cstdint>
#include <iostream>
#include <pthread.h>
#include <dirent.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <cerrno>
#include <cstring>
typedef enum
{
extract_image,
extract_audio,
upscale_image,
render_video
} work_t;
typedef struct
{
uint64_t id;
std::string *working_dir;
std::string *command;
std::mutex *work_lock;
std::queue<uint64_t> *deps;
work_t type;
bool done;
} work_unit_t;
void create_thread(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg)
{
int rc = pthread_create(thread, attr, start_routine, arg);
if (rc)
{
std::cerr << "Could not create thread." << std::endl;
exit(1);
}
}
bool valid(const std::string &file)
{
std::vector<std::string> extensions = {"mp4", "mkv", "m4v", "avi"};
for (auto itr = extensions.begin(); itr != extensions.end(); itr++)
{
if (file.size() >= itr -> size() && file.compare(file.size() - itr -> size(), itr -> size(), *itr) == 0) { return true; }
}
return false;
}
bool valid(const char *file)
{
std::string temp = std::string(file);
return valid(temp);
}
bool isext(const char *file, const char *ext)
{
size_t file_len = strlen(file);
size_t ext_len = strlen(ext);
if (file_len < ext_len) { return false; }
if (strcmp((const char *) file + file_len - ext_len, ext))
{
return false;
}
return true;
}
bool dir_exists(const char *path)
{
DIR *dir = opendir(path);
if (dir)
{
closedir(dir);
return true;
}
else if (errno == ENOENT)
{
return false;
}
else
{
std::cerr << std::strerror(errno) << std::endl;
exit(errno);
}
}
void create_dir_tree(const char *base_path, const char *data_path)
{
std::string ptemp = base_path;
std::vector<std::string> to_create = {"/images", "/out", "/images/original", "/images/upscaled"};
ptemp += "/";
ptemp += data_path;
if (mkdir(ptemp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
{
if (errno != EEXIST)
{
std::cerr << std::strerror(errno) << std::endl;
exit(errno);
}
}
for (auto itr = to_create.begin(); itr != to_create.end(); itr++)
{
ptemp = base_path;
ptemp += "/";
ptemp += data_path;
ptemp += *itr;
if (mkdir(ptemp.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))
{
if (errno != EEXIST)
{
std::cerr << std::strerror(errno) << std::endl;
exit(errno);
}
}
}
}
void make_work(std::vector<work_unit_t *> *work, DIR *dir, const char *base_path)
{
dirent *dp = NULL;
struct stat st;
std::vector<std::string> dirs;
std::vector<std::string> files;
//bool match_dir;
std::string dtemp;
std::string ftemp;
std::string ptemp;
std::string data_dir;
std::string original_image_dir;
std::string upscaled_image_dir;
std::string output_dir;
bool orig_img;
bool upscale_img;
bool video;
bool audio;
work_unit_t *wtemp;
uint64_t orig_img_id;
uint64_t audio_id;
uint64_t upscale_img_id;
DIR *dptemp;
while (dir)
{
dp = readdir(dir);
if (dp != NULL)
{
ptemp = base_path;
ptemp += "/";
ptemp += dp -> d_name;
if (lstat(ptemp.c_str(), &st) == 0)
{
if (S_ISDIR(st.st_mode))
{
dirs.push_back(std::string(dp -> d_name));
}
else
{
files.push_back(std::string(dp -> d_name));
}
}
else
{
std::cerr << std::strerror(errno) << std::endl;
closedir(dir);
exit(errno);
}
}
else
{
closedir(dir); //ensure that this gets called - errors from lstat or readdir may cause this to fail
break;
}
}
//if (dp) { delete dp; }
for (auto fitr = files.begin(); fitr != files.end(); fitr++)
{
if (valid(*fitr))
{
create_dir_tree(base_path, fitr -> substr(0, fitr -> find_last_of(".")).c_str());
data_dir = base_path;
data_dir += "/";
data_dir += fitr -> substr(0, fitr -> find_last_of("."));
original_image_dir = data_dir;
original_image_dir += "/images/original";
upscaled_image_dir = data_dir;
upscaled_image_dir += "/images/upscaled";
output_dir = data_dir;
output_dir += "/out";
orig_img = false;
upscale_img = false;
video = false;
audio = false;
//check for existing extracted images
dptemp = opendir(original_image_dir.c_str());
while (dptemp)
{
dp = readdir(dptemp);
if (dp != NULL)
{
if (isext(dp -> d_name, "png"))
{
orig_img = true;
closedir(dptemp);
break;
}
}
else
{
closedir(dptemp);
break;
}
}
//check for any upscaled images
dptemp = opendir(upscaled_image_dir.c_str());
while (dptemp)
{
dp = readdir(dptemp);
if (dp != NULL)
{
if (isext(dp -> d_name, "png"))
{
upscale_img = true;
closedir(dptemp);
break;
}
}
else
{
closedir(dptemp);
break;
}
}
//check for video
dptemp = opendir(output_dir.c_str());
while (dptemp)
{
dp = readdir(dptemp);
if (dp != NULL)
{
if (valid(dp -> d_name))
{
video = true;
closedir(dptemp);
break;
}
}
else
{
closedir(dptemp);
break;
}
}
dptemp = opendir(data_dir.c_str());
while (dptemp)
{
dp = readdir(dptemp);
if (dp != NULL)
{
if (strcmp("audio", dp -> d_name) == 0)
{
audio = true;
closedir(dptemp);
break;
}
}
else
{
closedir(dptemp);
break;
}
}
if (!orig_img && !video)
{
wtemp = new work_unit_t;
wtemp -> id = work -> size();
orig_img_id = wtemp -> id;
wtemp -> working_dir = new std::string(original_image_dir);
wtemp -> command = new std::string("ffmpeg -i \"../../");
*(wtemp -> command) += *fitr;
*(wtemp -> command) += "\" %05d.png";
wtemp -> work_lock = new std::mutex;
wtemp -> deps = new std::queue<uint64_t>;
wtemp -> type = extract_image;
wtemp -> done = false;
work -> push_back(wtemp);
}
if (!upscale_img && !video)
{
wtemp = new work_unit_t;
wtemp -> id = work -> size();
upscale_img_id = wtemp -> id;
wtemp -> working_dir = new std::string(original_image_dir);
wtemp -> command = new std::string("for f in *; do waifu2x -i $f -o ../upscaled/$f; done");
wtemp -> work_lock = new std::mutex;
wtemp -> deps = new std::queue<uint64_t>;
wtemp -> type = upscale_image;
wtemp -> done = false;
if (!orig_img)
{
wtemp -> deps -> push(orig_img_id);
}
work -> push_back(wtemp);
}
if (!audio && !video)
{
wtemp = new work_unit_t;
wtemp -> id = work -> size();
audio_id = wtemp -> id;
wtemp -> working_dir = new std::string(data_dir);
wtemp -> command = new std::string("ffmpeg -i \"../");
*(wtemp -> command) += *fitr;
*(wtemp -> command) += "\" -vn -acodec copy audio.ext";
wtemp -> work_lock = new std::mutex;
wtemp -> deps = new std::queue<uint64_t>;
wtemp -> type = extract_audio;
wtemp -> done = false;
work -> push_back(wtemp);
}
if (!video)
{
wtemp = new work_unit_t;
wtemp -> id = work -> size();
wtemp -> working_dir = new std::string(output_dir);
wtemp -> command = new std::string("ffmpeg -framerate 30 -i ../images/upscaled/%05d.png -i ../audio.ext -c:v libx264 -c:a aac -strict experimental -b:a 192k -shortest -pix_fmt yuv420p \"");
*(wtemp -> command) += *fitr;
*(wtemp -> command) += "\"";
wtemp -> work_lock = new std::mutex;
wtemp -> deps = new std::queue<uint64_t>;
wtemp -> type = render_video;
wtemp -> done = false;
if (!orig_img)
{
wtemp -> deps -> push(orig_img_id);
}
if (!upscale_img)
{
wtemp -> deps -> push(upscale_img_id);
}
if (!audio)
{
wtemp -> deps -> push(audio_id);
}
work -> push_back(wtemp);
}
}
}
/* a miracle happens */
for (auto ditr = dirs.begin(); ditr != dirs.end(); ditr++)
{
if (ditr -> compare(".") && ditr -> compare(".."))
{
ptemp = base_path;
ptemp += "/";
ptemp += *ditr;
dptemp = opendir(ptemp.c_str());
make_work(work, dptemp, ptemp.c_str());
}
}
//if (dp) { delete dp; }
}
void do_work(std::vector<work_unit_t *> *work, std::mutex *vector_lock)
{
for (auto itr = work -> begin(); itr != work -> end(); itr++)
{
std::cout << *((*itr) -> command);
}
}
int main(int argc, char** argv)
{
std::vector<work_unit_t*> work;
std::mutex vector_lock;
size_t buf_size = 1024;
char* buf = new char[buf_size];
if (argc > 1)
{
strcpy(buf, argv[1]);
}
else if (getcwd(buf, buf_size) == NULL)
{
std::cerr << std::strerror(errno) << std::endl;
return errno;
}
DIR *dir = opendir(buf);
make_work(&work, dir, buf);
do_work(&work, &vector_lock);
delete[] buf;
return 0;
}
<|endoftext|> |
<commit_before>#include <itomp_cio_planner/visualization/new_viz_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>
#include <itomp_cio_planner/contact/ground_manager.h>
#include <ros/node_handle.h>
#include <boost/lexical_cast.hpp>
using namespace std;
namespace itomp_cio_planner
{
NewVizManager::NewVizManager()
{
}
NewVizManager::~NewVizManager()
{
}
void NewVizManager::initialize(const ItompRobotModelConstPtr& robot_model)
{
ros::NodeHandle node_handle;
vis_marker_array_publisher_ = node_handle.advertise<
visualization_msgs::MarkerArray>(
"itomp_planner/visualization_marker_array", 10);
vis_marker_publisher_ = node_handle.advertise<visualization_msgs::Marker>(
"itomp_planner/visualization_marker", 10);
robot_model_ = robot_model;
reference_frame_ = robot_model->getReferenceFrame();
colors_.resize(8);
for (int i = 0; i < 8; ++i)
{
colors_[i].a = 1.0;
colors_[i].b = (i % 2 == 0) ? 0.0 : 1.0;
colors_[i].g = ((i / 2) % 2 == 0) ? 0.0 : 1.0;
colors_[i].r = ((i / 4) % 2 == 0) ? 0.0 : 1.0;
}
}
void NewVizManager::setPlanningGroup(
const ItompPlanningGroupConstPtr& planning_group)
{
planning_group_ = planning_group;
const multimap<string, string>& endeffector_names =
PlanningParameters::getInstance()->getGroupEndeffectorNames();
std::pair<multimap<string, string>::const_iterator,
multimap<string, string>::const_iterator> ret =
endeffector_names.equal_range(planning_group_->name_);
endeffector_rbdl_indices_.clear();
for (multimap<string, string>::const_iterator it = ret.first;
it != ret.second; ++it)
{
string endeffector_name = it->second;
unsigned int rbdl_link_index =
robot_model_->getRBDLRobotModel().GetBodyId(
endeffector_name.c_str());
endeffector_rbdl_indices_.push_back(rbdl_link_index);
}
}
void NewVizManager::renderOneTime()
{
//renderGround();
//renderEnvironment(); // rendered in move_itomp
}
void NewVizManager::renderEnvironment()
{
string environment_file =
PlanningParameters::getInstance()->getEnvironmentModel();
if (environment_file.empty())
return;
vector<double> environment_position =
PlanningParameters::getInstance()->getEnvironmentModelPosition();
double scale =
PlanningParameters::getInstance()->getEnvironmentModelScale();
environment_position.resize(3, 0);
visualization_msgs::MarkerArray ma;
visualization_msgs::Marker msg;
msg.header.frame_id = reference_frame_;
msg.header.stamp = ros::Time::now();
msg.ns = "environment";
msg.type = visualization_msgs::Marker::MESH_RESOURCE;
msg.action = visualization_msgs::Marker::ADD;
msg.scale.x = scale;
msg.scale.y = scale;
msg.scale.z = scale;
msg.id = 0;
msg.pose.position.x = environment_position[0];
msg.pose.position.y = environment_position[1];
msg.pose.position.z = environment_position[2];
/*
msg.pose.orientation.x = sqrt(0.5);
msg.pose.orientation.y = 0.0;
msg.pose.orientation.z = 0.0;
msg.pose.orientation.w = sqrt(0.5);
*/
msg.pose.orientation.x = 0.0;
msg.pose.orientation.y = 0.0;
msg.pose.orientation.z = 0.0;
msg.pose.orientation.w = 1.0;
msg.color.a = 1.0;
msg.color.r = 0.5;
msg.color.g = 0.5;
msg.color.b = 0.5;
msg.mesh_resource = environment_file;
ma.markers.push_back(msg);
vis_marker_array_publisher_.publish(ma);
}
void NewVizManager::renderGround()
{
}
void NewVizManager::animateEndeffectors(
const FullTrajectoryConstPtr& full_trajectory,
const std::vector<RigidBodyDynamics::Model>& models, bool is_best)
{
const double scale_keyframe = 0.03;
const double scale_line = 0.005;
geometry_msgs::Point point;
visualization_msgs::Marker msg;
msg.header.frame_id = reference_frame_;
msg.header.stamp = ros::Time::now();
msg.ns = is_best ? "itomp_best_ee" : "itomp_ee";
msg.action = visualization_msgs::Marker::ADD;
msg.pose.orientation.w = 1.0;
// render keyframe endeffectors
msg.type = visualization_msgs::Marker::SPHERE_LIST;
msg.scale.x = scale_keyframe;
msg.scale.y = scale_keyframe;
msg.scale.z = scale_keyframe;
msg.points.resize(0);
msg.color = is_best ? colors_[GREEN] : colors_[BLUE];
msg.id = 0;
for (int i = full_trajectory->getKeyframeStartIndex();
i < full_trajectory->getNumPoints();
i += full_trajectory->getNumKeyframeIntervalPoints())
{
for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j)
{
int rbdl_index = endeffector_rbdl_indices_[j];
Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r;
point.x = endeffector_pos(0);
point.y = endeffector_pos(1);
point.z = endeffector_pos(2);
msg.points.push_back(point);
}
}
vis_marker_publisher_.publish(msg);
// render endeffector path
msg.type = visualization_msgs::Marker::LINE_STRIP;
msg.scale.x = scale_line;
msg.scale.y = scale_line;
msg.scale.z = scale_line;
msg.color = is_best ? colors_[GREEN] : colors_[BLUE];
for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j)
{
++msg.id;
msg.points.resize(0);
int rbdl_index = endeffector_rbdl_indices_[j];
for (int i = 0; i < full_trajectory->getNumPoints(); ++i)
{
Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r;
point.x = endeffector_pos(0);
point.y = endeffector_pos(1);
point.z = endeffector_pos(2);
msg.points.push_back(point);
}
vis_marker_publisher_.publish(msg);
}
}
void NewVizManager::animatePath(const FullTrajectoryConstPtr& full_trajectory,
const robot_state::RobotStatePtr& robot_state, bool is_best)
{
if (!is_best)
return;
geometry_msgs::Point point;
visualization_msgs::MarkerArray ma;
std::vector<std::string> link_names =
robot_model_->getMoveitRobotModel()->getLinkModelNames();
std_msgs::ColorRGBA color = colors_[WHITE];
color.a = 0.1;
ros::Duration dur(100.0);
for (int point = full_trajectory->getKeyframeStartIndex();
point < full_trajectory->getNumPoints();
point += full_trajectory->getNumKeyframeIntervalPoints())
{
ma.markers.clear();
const Eigen::MatrixXd mat = full_trajectory->getTrajectory(
Trajectory::TRAJECTORY_TYPE_POSITION).row(point);
robot_state->setVariablePositions(mat.data());
std::string ns = "kf_" + boost::lexical_cast<std::string>(point);
robot_state->getRobotMarkers(ma, link_names, color, ns, dur);
vis_marker_array_publisher_.publish(ma);
}
}
void NewVizManager::animateContactForces(
const FullTrajectoryConstPtr& full_trajectory,
const std::vector<std::vector<ContactVariables> >& contact_variables,
bool is_best, bool keyframe_only)
{
const double scale_line = 0.005;
const double scale_keyframe = 0.03;
geometry_msgs::Point point_from, point_to;
visualization_msgs::Marker msg, msg2, msg3, msg4;
msg.header.frame_id = reference_frame_;
msg.header.stamp = ros::Time::now();
msg.ns = is_best ? "itomp_best_cf" : "itomp_cf";
msg.action = visualization_msgs::Marker::ADD;
msg.pose.orientation.w = 1.0;
msg.type = visualization_msgs::Marker::LINE_LIST;
msg.scale.x = scale_line;
msg.scale.y = scale_line;
msg.scale.z = scale_line;
msg.color = is_best ? colors_[YELLOW] : colors_[MAGENTA];
msg.id = 0;
msg.points.resize(0);
msg2 = msg;
msg2.ns = is_best ? "itomp_best_cp" : "itomp_cp";
msg2.type = visualization_msgs::Marker::SPHERE_LIST;
msg2.scale.x = scale_keyframe;
msg2.scale.y = scale_keyframe;
msg2.scale.z = scale_keyframe;
// inactive
msg3 = msg;
msg3.id = 0;
msg3.color = is_best ? colors_[RED] : colors_[MAGENTA];
msg3.ns = is_best ? "itomp_best_cf_ia" : "itomp_cf_ia";
msg4 = msg2;
msg4.id = 0;
msg4.color = is_best ? colors_[RED] : colors_[MAGENTA];
msg4.ns = is_best ? "itomp_best_cp_ia" : "itomp_cp_ia";
int begin, end, step;
if (keyframe_only)
{
begin = full_trajectory->getKeyframeStartIndex();
end = full_trajectory->getNumPoints();
step = full_trajectory->getNumKeyframeIntervalPoints();
}
else
{
begin = 0;
end = full_trajectory->getNumPoints();
step = 1;
}
int num_contacts = contact_variables[0].size();
for (int point = begin; point < end; point += step)
{
for (int i = 0; i < num_contacts; ++i)
{
double contact_v = contact_variables[point][i].getVariable();
for (int c = 0; c < NUM_ENDEFFECTOR_CONTACT_POINTS; ++c)
{
Eigen::Vector3d point_position =
contact_variables[point][i].projected_point_positions_[c];
Eigen::Vector3d contact_force =
contact_variables[point][i].getPointForce(c);
contact_force *= contact_v;
point_from.x = point_position(0);
point_from.y = point_position(1);
point_from.z = point_position(2);
point_to.x = contact_force(0) * 0.001 + point_from.x;
point_to.y = contact_force(1) * 0.001 + point_from.y;
point_to.z = contact_force(2) * 0.001 + point_from.z;
const double k1 = 0.01; //10.0;
const double k2 = 3; //3.0;
double contact_variable = contact_v;
if (contact_variable > 0.0)
{
msg.points.push_back(point_from);
msg.points.push_back(point_to);
msg2.points.push_back(point_from);
}
else
{
msg3.points.push_back(point_from);
msg3.points.push_back(point_to);
msg4.points.push_back(point_from);
}
}
}
}
vis_marker_publisher_.publish(msg);
vis_marker_publisher_.publish(msg2);
vis_marker_publisher_.publish(msg3);
vis_marker_publisher_.publish(msg4);
}
}
<commit_msg>update viz manager<commit_after>#include <itomp_cio_planner/visualization/new_viz_manager.h>
#include <itomp_cio_planner/util/planning_parameters.h>
#include <itomp_cio_planner/contact/ground_manager.h>
#include <ros/node_handle.h>
#include <boost/lexical_cast.hpp>
using namespace std;
namespace itomp_cio_planner
{
NewVizManager::NewVizManager()
{
}
NewVizManager::~NewVizManager()
{
}
void NewVizManager::initialize(const ItompRobotModelConstPtr& robot_model)
{
ros::NodeHandle node_handle;
vis_marker_array_publisher_ = node_handle.advertise<
visualization_msgs::MarkerArray>(
"itomp_planner/visualization_marker_array", 10);
vis_marker_publisher_ = node_handle.advertise<visualization_msgs::Marker>(
"itomp_planner/visualization_marker", 10);
robot_model_ = robot_model;
reference_frame_ = robot_model->getReferenceFrame();
colors_.resize(8);
for (int i = 0; i < 8; ++i)
{
colors_[i].a = 1.0;
colors_[i].b = (i % 2 == 0) ? 0.0 : 1.0;
colors_[i].g = ((i / 2) % 2 == 0) ? 0.0 : 1.0;
colors_[i].r = ((i / 4) % 2 == 0) ? 0.0 : 1.0;
}
}
void NewVizManager::setPlanningGroup(
const ItompPlanningGroupConstPtr& planning_group)
{
planning_group_ = planning_group;
const multimap<string, string>& endeffector_names =
PlanningParameters::getInstance()->getGroupEndeffectorNames();
std::pair<multimap<string, string>::const_iterator,
multimap<string, string>::const_iterator> ret =
endeffector_names.equal_range(planning_group_->name_);
endeffector_rbdl_indices_.clear();
for (multimap<string, string>::const_iterator it = ret.first;
it != ret.second; ++it)
{
string endeffector_name = it->second;
unsigned int rbdl_link_index =
robot_model_->getRBDLRobotModel().GetBodyId(
endeffector_name.c_str());
endeffector_rbdl_indices_.push_back(rbdl_link_index);
}
}
void NewVizManager::renderOneTime()
{
//renderGround();
//renderEnvironment(); // rendered in move_itomp
}
void NewVizManager::renderEnvironment()
{
string environment_file =
PlanningParameters::getInstance()->getEnvironmentModel();
if (environment_file.empty())
return;
vector<double> environment_position =
PlanningParameters::getInstance()->getEnvironmentModelPosition();
double scale =
PlanningParameters::getInstance()->getEnvironmentModelScale();
environment_position.resize(3, 0);
visualization_msgs::MarkerArray ma;
visualization_msgs::Marker msg;
msg.header.frame_id = reference_frame_;
msg.header.stamp = ros::Time::now();
msg.ns = "environment";
msg.type = visualization_msgs::Marker::MESH_RESOURCE;
msg.action = visualization_msgs::Marker::ADD;
msg.scale.x = scale;
msg.scale.y = scale;
msg.scale.z = scale;
msg.id = 0;
msg.pose.position.x = environment_position[0];
msg.pose.position.y = environment_position[1];
msg.pose.position.z = environment_position[2];
/*
msg.pose.orientation.x = sqrt(0.5);
msg.pose.orientation.y = 0.0;
msg.pose.orientation.z = 0.0;
msg.pose.orientation.w = sqrt(0.5);
*/
msg.pose.orientation.x = 0.0;
msg.pose.orientation.y = 0.0;
msg.pose.orientation.z = 0.0;
msg.pose.orientation.w = 1.0;
msg.color.a = 1.0;
msg.color.r = 0.5;
msg.color.g = 0.5;
msg.color.b = 0.5;
msg.mesh_resource = environment_file;
ma.markers.push_back(msg);
vis_marker_array_publisher_.publish(ma);
}
void NewVizManager::renderGround()
{
}
void NewVizManager::animateEndeffectors(
const FullTrajectoryConstPtr& full_trajectory,
const std::vector<RigidBodyDynamics::Model>& models, bool is_best)
{
const double scale_keyframe = 0.03;
const double scale_line = 0.005;
geometry_msgs::Point point;
visualization_msgs::Marker msg;
msg.header.frame_id = reference_frame_;
msg.header.stamp = ros::Time::now();
msg.ns = is_best ? "itomp_best_ee" : "itomp_ee";
msg.action = visualization_msgs::Marker::ADD;
msg.pose.orientation.w = 1.0;
// render keyframe endeffectors
msg.type = visualization_msgs::Marker::SPHERE_LIST;
msg.scale.x = scale_keyframe;
msg.scale.y = scale_keyframe;
msg.scale.z = scale_keyframe;
msg.points.resize(0);
msg.color = is_best ? colors_[GREEN] : colors_[BLUE];
msg.id = 0;
for (int i = full_trajectory->getKeyframeStartIndex();
i < full_trajectory->getNumPoints();
i += full_trajectory->getNumKeyframeIntervalPoints())
{
for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j)
{
int rbdl_index = endeffector_rbdl_indices_[j];
Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r;
point.x = endeffector_pos(0);
point.y = endeffector_pos(1);
point.z = endeffector_pos(2);
msg.points.push_back(point);
}
}
vis_marker_publisher_.publish(msg);
// render endeffector path
msg.type = visualization_msgs::Marker::LINE_STRIP;
msg.scale.x = scale_line;
msg.scale.y = scale_line;
msg.scale.z = scale_line;
msg.color = is_best ? colors_[GREEN] : colors_[BLUE];
for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j)
{
++msg.id;
msg.points.resize(0);
int rbdl_index = endeffector_rbdl_indices_[j];
for (int i = 0; i < full_trajectory->getNumPoints(); ++i)
{
Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r;
point.x = endeffector_pos(0);
point.y = endeffector_pos(1);
point.z = endeffector_pos(2);
msg.points.push_back(point);
}
vis_marker_publisher_.publish(msg);
}
}
void NewVizManager::animatePath(const FullTrajectoryConstPtr& full_trajectory,
const robot_state::RobotStatePtr& robot_state, bool is_best)
{
if (!is_best)
return;
geometry_msgs::Point point;
visualization_msgs::MarkerArray ma;
std::vector<std::string> link_names =
robot_model_->getMoveitRobotModel()->getLinkModelNames();
std_msgs::ColorRGBA color = colors_[WHITE];
color.a = 0.1;
ros::Duration dur(3600.0);
for (int point = full_trajectory->getKeyframeStartIndex();
point < full_trajectory->getNumPoints();
point += full_trajectory->getNumKeyframeIntervalPoints())
{
ma.markers.clear();
const Eigen::MatrixXd mat = full_trajectory->getTrajectory(
Trajectory::TRAJECTORY_TYPE_POSITION).row(point);
robot_state->setVariablePositions(mat.data());
std::string ns = "kf_" + boost::lexical_cast<std::string>(point);
robot_state->getRobotMarkers(ma, link_names, color, ns, dur);
vis_marker_array_publisher_.publish(ma);
}
}
void NewVizManager::animateContactForces(
const FullTrajectoryConstPtr& full_trajectory,
const std::vector<std::vector<ContactVariables> >& contact_variables,
bool is_best, bool keyframe_only)
{
const double scale_line = 0.005;
const double scale_keyframe = 0.03;
geometry_msgs::Point point_from, point_to;
visualization_msgs::Marker msg, msg2, msg3, msg4;
msg.header.frame_id = reference_frame_;
msg.header.stamp = ros::Time::now();
msg.ns = is_best ? "itomp_best_cf" : "itomp_cf";
msg.action = visualization_msgs::Marker::ADD;
msg.pose.orientation.w = 1.0;
msg.type = visualization_msgs::Marker::LINE_LIST;
msg.scale.x = scale_line;
msg.scale.y = scale_line;
msg.scale.z = scale_line;
msg.color = is_best ? colors_[YELLOW] : colors_[MAGENTA];
msg.id = 0;
msg.points.resize(0);
msg2 = msg;
msg2.ns = is_best ? "itomp_best_cp" : "itomp_cp";
msg2.type = visualization_msgs::Marker::SPHERE_LIST;
msg2.scale.x = scale_keyframe;
msg2.scale.y = scale_keyframe;
msg2.scale.z = scale_keyframe;
// inactive
msg3 = msg;
msg3.id = 0;
msg3.color = is_best ? colors_[RED] : colors_[MAGENTA];
msg3.ns = is_best ? "itomp_best_cf_ia" : "itomp_cf_ia";
msg4 = msg2;
msg4.id = 0;
msg4.color = is_best ? colors_[RED] : colors_[MAGENTA];
msg4.ns = is_best ? "itomp_best_cp_ia" : "itomp_cp_ia";
int begin, end, step;
if (keyframe_only)
{
begin = full_trajectory->getKeyframeStartIndex();
end = full_trajectory->getNumPoints();
step = full_trajectory->getNumKeyframeIntervalPoints();
}
else
{
begin = 0;
end = full_trajectory->getNumPoints();
step = 1;
}
int num_contacts = contact_variables[0].size();
for (int point = begin; point < end; point += step)
{
for (int i = 0; i < num_contacts; ++i)
{
double contact_v = contact_variables[point][i].getVariable();
for (int c = 0; c < NUM_ENDEFFECTOR_CONTACT_POINTS; ++c)
{
Eigen::Vector3d point_position =
contact_variables[point][i].projected_point_positions_[c];
Eigen::Vector3d contact_force =
contact_variables[point][i].getPointForce(c);
contact_force *= contact_v;
point_from.x = point_position(0);
point_from.y = point_position(1);
point_from.z = point_position(2);
point_to.x = contact_force(0) * 0.001 + point_from.x;
point_to.y = contact_force(1) * 0.001 + point_from.y;
point_to.z = contact_force(2) * 0.001 + point_from.z;
const double k1 = 0.01; //10.0;
const double k2 = 3; //3.0;
double contact_variable = contact_v;
if (contact_variable > 0.0)
{
msg.points.push_back(point_from);
msg.points.push_back(point_to);
msg2.points.push_back(point_from);
}
else
{
msg3.points.push_back(point_from);
msg3.points.push_back(point_to);
msg4.points.push_back(point_from);
}
}
}
}
vis_marker_publisher_.publish(msg);
vis_marker_publisher_.publish(msg2);
vis_marker_publisher_.publish(msg3);
vis_marker_publisher_.publish(msg4);
}
}
<|endoftext|> |
<commit_before>#include <BWAPI.h>
#include <BWAPI/Client.h>
#include <iostream>
#include <thread>
#include <chrono>
#include <string>
using namespace BWAPI;
void drawStats();
void drawBullets();
void drawVisibilityData();
void showPlayers();
void showForces();
bool show_bullets;
bool show_visibility_data;
void reconnect()
{
while(!BWAPIClient.connect())
{
std::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });
}
}
int main(int argc, const char* argv[])
{
std::cout << "Connecting..." << std::endl;;
reconnect();
while(true)
{
std::cout << "waiting to enter match" << std::endl;
while ( !Broodwar->isInGame() )
{
BWAPI::BWAPIClient.update();
if (!BWAPI::BWAPIClient.isConnected())
{
std::cout << "Reconnecting..." << std::endl;;
reconnect();
}
}
std::cout << "starting match!" << std::endl;
Broodwar->sendText("Hello world!");
Broodwar << "The map is " << Broodwar->mapName() << ", a " << Broodwar->getStartLocations().size() << " player map" << std::endl;
// Enable some cheat flags
Broodwar->enableFlag(Flag::UserInput);
// Uncomment to enable complete map information
//Broodwar->enableFlag(Flag::CompleteMapInformation);
show_bullets=false;
show_visibility_data=false;
if (Broodwar->isReplay())
{
Broodwar << "The following players are in this replay:" << std::endl;;
Playerset players = Broodwar->getPlayers();
for(auto p : players)
{
if ( !p->getUnits().empty() && !p->isNeutral() )
Broodwar << p->getName() << ", playing as " << p->getRace() << std::endl;
}
}
else
{
if (Broodwar->enemy())
Broodwar << "The match up is " << Broodwar->self()->getRace() << " vs " << Broodwar->enemy()->getRace() << std::endl;
//send each worker to the mineral field that is closest to it
Unitset units = Broodwar->self()->getUnits();
Unitset minerals = Broodwar->getMinerals();
for ( auto &u : units )
{
if ( u->getType().isWorker() )
{
Unit closestMineral = nullptr;
for (auto &m : minerals)
{
if ( !closestMineral || u->getDistance(m) < u->getDistance(closestMineral))
closestMineral = m;
}
if ( closestMineral )
u->rightClick(closestMineral);
}
else if ( u->getType().isResourceDepot() )
{
//if this is a center, tell it to build the appropiate type of worker
u->train(Broodwar->self()->getRace().getWorker());
}
}
}
while(Broodwar->isInGame())
{
for(auto &e : Broodwar->getEvents())
{
switch(e.getType())
{
case EventType::MatchEnd:
if (e.isWinner())
Broodwar << "I won the game" << std::endl;
else
Broodwar << "I lost the game" << std::endl;
break;
case EventType::SendText:
if (e.getText()=="/show bullets")
{
show_bullets=!show_bullets;
} else if (e.getText()=="/show players")
{
showPlayers();
} else if (e.getText()=="/show forces")
{
showForces();
} else if (e.getText()=="/show visibility")
{
show_visibility_data=!show_visibility_data;
}
else
{
Broodwar << "You typed \"" << e.getText() << "\"!" << std::endl;
}
break;
case EventType::ReceiveText:
Broodwar << e.getPlayer()->getName() << " said \"" << e.getText() << "\"" << std::endl;
break;
case EventType::PlayerLeft:
Broodwar << e.getPlayer()->getName() << " left the game." << std::endl;
break;
case EventType::NukeDetect:
if (e.getPosition()!=Positions::Unknown)
{
Broodwar->drawCircleMap(e.getPosition(), 40, Colors::Red, true);
Broodwar << "Nuclear Launch Detected at " << e.getPosition() << std::endl;
}
else
Broodwar << "Nuclear Launch Detected" << std::endl;
break;
case EventType::UnitCreate:
if (!Broodwar->isReplay())
Broodwar << "A " << e.getUnit()->getType() << " [" << e.getUnit() << "] has been created at " << e.getUnit()->getPosition() << std::endl;
else
{
// if we are in a replay, then we will print out the build order
// (just of the buildings, not the units).
if (e.getUnit()->getType().isBuilding() && e.getUnit()->getPlayer()->isNeutral()==false)
{
int seconds=Broodwar->getFrameCount()/24;
int minutes=seconds/60;
seconds%=60;
Broodwar->sendText("%.2d:%.2d: %s creates a %s", minutes, seconds, e.getUnit()->getPlayer()->getName().c_str(), e.getUnit()->getType().c_str());
}
}
break;
case EventType::UnitDestroy:
if (!Broodwar->isReplay())
Broodwar->sendText("A %s [%p] has been destroyed at (%d,%d)",e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPosition().x, e.getUnit()->getPosition().y);
break;
case EventType::UnitMorph:
if (!Broodwar->isReplay())
Broodwar->sendText("A %s [%p] has been morphed at (%d,%d)",e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPosition().x, e.getUnit()->getPosition().y);
else
{
// if we are in a replay, then we will print out the build order
// (just of the buildings, not the units).
if (e.getUnit()->getType().isBuilding() && e.getUnit()->getPlayer()->isNeutral()==false)
{
int seconds=Broodwar->getFrameCount()/24;
int minutes=seconds/60;
seconds%=60;
Broodwar->sendText("%.2d:%.2d: %s morphs a %s" ,minutes, seconds, e.getUnit()->getPlayer()->getName().c_str(), e.getUnit()->getType().c_str());
}
}
break;
case EventType::UnitShow:
if (!Broodwar->isReplay())
Broodwar->sendText("A %s [%p] has been spotted at (%d,%d)", e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPosition().x, e.getUnit()->getPosition().y);
break;
case EventType::UnitHide:
if (!Broodwar->isReplay())
Broodwar->sendText("A %s [%p] was last seen at (%d,%d)", e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPosition().x, e.getUnit()->getPosition().y);
break;
case EventType::UnitRenegade:
if (!Broodwar->isReplay())
Broodwar->sendText("A %s [%p] is now owned by %s", e.getUnit()->getType().c_str(), e.getUnit(), e.getUnit()->getPlayer()->getName().c_str());
break;
case EventType::SaveGame:
Broodwar->sendText("The game was saved to \"%s\".", e.getText().c_str());
break;
}
}
if (show_bullets)
drawBullets();
if (show_visibility_data)
drawVisibilityData();
drawStats();
Broodwar->drawTextScreen(300,0,"FPS: %f",Broodwar->getAverageFPS());
BWAPI::BWAPIClient.update();
if (!BWAPI::BWAPIClient.isConnected())
{
std::cout << "Reconnecting..." << std::endl;
reconnect();
}
}
std::cout << "Game ended" << std::endl;
}
std::cout << "Press ENTER to continue..." << std::endl;
std::cin.ignore();
return 0;
}
void drawStats()
{
int line = 0;
Broodwar->drawTextScreen(5, 0, "I have %d units:", Broodwar->self()->allUnitCount() );
for (auto& unitType : UnitTypes::allUnitTypes())
{
int count = Broodwar->self()->allUnitCount(unitType);
if ( count )
{
Broodwar->drawTextScreen(5, 16*line, "- %d %s%c", count, unitType.c_str(), count == 1 ? ' ' : 's');
++line;
}
}
}
void drawBullets()
{
for (auto &b : Broodwar->getBullets())
{
Position p = b->getPosition();
double velocityX = b->getVelocityX();
double velocityY = b->getVelocityY();
Broodwar->drawLineMap(p, p + Position((int)velocityX, (int)velocityY), b->getPlayer() == Broodwar->self() ? Colors::Green : Colors::Red);
Broodwar->drawTextMap(p, "%c%s", b->getPlayer() == Broodwar->self() ? Text::Green : Text::Red, b->getType().c_str());
}
}
void drawVisibilityData()
{
int wid = Broodwar->mapHeight(), hgt = Broodwar->mapWidth();
for ( int x = 0; x < wid; ++x )
for ( int y = 0; y < hgt; ++y )
{
if ( Broodwar->isExplored(x, y) )
Broodwar->drawDotMap(x*32+16, y*32+16, Broodwar->isVisible(x, y) ? Colors::Green : Colors::Blue);
else
Broodwar->drawDotMap(x*32+16, y*32+16, Colors::Red);
}
}
void showPlayers()
{
Playerset players = Broodwar->getPlayers();
for(auto p : players)
Broodwar << "Player [" << p->getID() << "]: " << p->getName() << " is in force: " << p->getForce()->getName() << std::endl;
}
void showForces()
{
Forceset forces=Broodwar->getForces();
for(auto f : forces)
{
Playerset players = f->getPlayers();
Broodwar << "Force " << f->getName() << " has the following players:" << std::endl;
for(auto p : players)
Broodwar << " - Player [" << p->getID() << "]: " << p->getName() << std::endl;
}
}
<commit_msg>Dispatch all events to KBot.<commit_after>#include <BWAPI.h>
#include <BWAPI/Client.h>
#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include "KBot.h"
using namespace BWAPI;
static void busy_wait_connect()
{
while(!BWAPIClient.connect())
{
std::this_thread::sleep_for(std::chrono::milliseconds{ 1000 });
}
}
int main(int argc, const char** argv)
{
std::cout << "Connecting..." << std::endl;
busy_wait_connect();
while(true)
{
std::cout << "waiting to enter match" << std::endl;
while ( !Broodwar->isInGame() )
{
BWAPI::BWAPIClient.update();
if (!BWAPI::BWAPIClient.isConnected())
{
std::cout << "Reconnecting..." << std::endl;;
busy_wait_connect();
}
}
// if (Broodwar->isReplay()) // TODO: Handle here?
std::cout << "starting match!" << std::endl;
KBot::KBot bot;
while(Broodwar->isInGame())
{
for(auto &e : Broodwar->getEvents())
{
switch(e.getType())
{
case EventType::MatchStart:
bot.onStart();
break;
case EventType::MatchEnd:
bot.onEnd(e.isWinner());
break;
case EventType::MatchFrame:
bot.onFrame();
break;
case EventType::MenuFrame:
bot.onFrame(); // TODO: skip these?
break;
case EventType::SendText:
bot.onSendText(e.getText());
break;
case EventType::ReceiveText:
bot.onReceiveText(e.getPlayer(), e.getText());
break;
case EventType::PlayerLeft:
bot.onPlayerLeft(e.getPlayer());
break;
case EventType::NukeDetect:
bot.onNukeDetect(e.getPosition());
break;
case EventType::UnitDiscover:
bot.onUnitDiscover(e.getUnit());
break;
case EventType::UnitEvade:
bot.onUnitEvade(e.getUnit());
break;
case EventType::UnitShow:
bot.onUnitShow(e.getUnit());
break;
case EventType::UnitHide:
bot.onUnitHide(e.getUnit());
break;
case EventType::UnitCreate:
bot.onUnitCreate(e.getUnit());
break;
case EventType::UnitDestroy:
bot.onUnitDestroy(e.getUnit());
break;
case EventType::UnitMorph:
bot.onUnitMorph(e.getUnit());
break;
case EventType::UnitRenegade:
bot.onUnitRenegade(e.getUnit());
break;
case EventType::SaveGame:
bot.onSaveGame(e.getText());
break;
case EventType::UnitComplete:
bot.onUnitComplete(e.getUnit());
break;
}
}
BWAPI::BWAPIClient.update();
if (!BWAPI::BWAPIClient.isConnected())
{
std::cout << "Reconnecting..." << std::endl;
busy_wait_connect();
}
}
std::cout << "Game ended" << std::endl;
}
std::cout << "Press ENTER to continue..." << std::endl;
std::cin.ignore();
return 0;
}
<|endoftext|> |
<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#include "flesch-index_config.h"
#include "flesch-index.hpp"
int main (int argc, char *argv[]) {
if (argc != 2) {
fprintf(stdout,"%s Version %d.%d.%d\n",
argv[0], flesch_index_VERSION_MAJOR,
flesch_index_VERSION_MINOR, flesch_index_VERSION_PATCH);
fprintf(stdout,"Usage: %s [FILEIN]\n",argv[0]);
exit(EXIT_FAILURE);
}
std::string filename = argv[1];
fi::Flesch_Index fi = fi::Flesch_Index(filename);
fi.Read();
exit(EXIT_SUCCESS);
}
<commit_msg>Updated main to run updated in flesch-index.cxx<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string>
#include "flesch-index_config.h"
#include "flesch-index.hpp"
int main (int argc, char *argv[]) {
if (argc != 2) {
fprintf(stdout,"%s Version %d.%d.%d\n",
argv[0], flesch_index_VERSION_MAJOR,
flesch_index_VERSION_MINOR, flesch_index_VERSION_PATCH);
fprintf(stdout,"Usage: %s [FILEIN]\n",argv[0]);
exit(EXIT_FAILURE);
}
std::string filename = argv[1];
fi::Flesch_Index fi = fi::Flesch_Index(filename);
fi.Read();
fi.Analyze();
fi.Print();
exit(EXIT_SUCCESS);
}
<|endoftext|> |
<commit_before>#ifndef BFC_DEAD_LOOPS_VISITOR_HPP
#define BFC_DEAD_LOOPS_VISITOR_HPP
namespace bfc {
namespace ast {
class dead_loops_visitor : public opt_seq_base_visitor {
public:
status visit(loop &node) {
// test if previous node make this a dead loop
test_dead_loop_visitor v;
node prev_node = opt_seq.back();
if (prev_node.accept(v) == CONTINUE) {
// no-op to remove this loop from the sequence
return CONTINUE;
}
// else optimize inner sequence
return opt_seq_base_visitor::handle_loop(node);
}
status visit(const loop &node) {
// test if previous node make this a dead loop
test_dead_loop_visitor v;
node prev_node = opt_seq.back();
if (prev_node.accept(v) == CONTINUE) {
// no-op to remove this loop from the sequence
return CONTINUE;
}
// else optimize inner sequence
return opt_seq_base_visitor::handle_loop(node);
}
private:
class test_dead_loop_visitor : public visitor {
public:
status visit(set &node) {
return (node.value() == 0 && node.offset() == 0) ? CONTINUE : BREAK;
}
status visit(const set &node) {
return (node.value() == 0 && node.offset() == 0) ? CONTINUE : BREAK;
}
// Loops only terminate when the current cell reaches 0
// Thus loops following loops are dead
status visit(loop &node) { return CONTINUE; }
status visit(const loop &node) { return CONTINUE; }
};
};
}
}
#endif /* !BFC_DEAD_LOOPS_VISITOR_HPP */
<commit_msg>Dead loop visitor now account for dead starting loops<commit_after>#ifndef BFC_DEAD_LOOPS_VISITOR_HPP
#define BFC_DEAD_LOOPS_VISITOR_HPP
namespace bfc {
namespace ast {
class dead_loops_visitor : public opt_seq_base_visitor {
public:
dead_loops_visitor(void) : maybeProgramStart(true) {}
status visit(loop &node) {
// test if this is the first node of a program sequence
if (maybeProgramStart && opt_seq.empty()) {
// cells init to 0 on start, this loop is dead
return CONTINUE;
}
// mark that we are past the start of the program
maybeProgramStart = false;
// test if previous node makes this a dead loop
test_dead_loop_visitor v;
node prev_node = opt_seq.back();
if (prev_node.accept(v) == CONTINUE) {
// no-op to remove this loop from the sequence
return CONTINUE;
}
// else optimize inner sequence
return opt_seq_base_visitor::handle_loop(node);
}
status visit(const loop &node) {
// test if this is the first node of a program sequence
if (maybeProgramStart && opt_seq.empty()) {
// cells init to 0 on start, this loop is dead
return CONTINUE;
}
// mark that we are past the start of the program
maybeProgramStart = false;
// test if previous node makes this a dead loop
test_dead_loop_visitor v;
node prev_node = opt_seq.back();
if (prev_node.accept(v) == CONTINUE) {
// no-op to remove this loop from the sequence
return CONTINUE;
}
// else optimize inner sequence
return opt_seq_base_visitor::handle_loop(node);
}
private:
bool maybeProgramStart;
class test_dead_loop_visitor : public visitor {
public:
status visit(set &node) {
return (node.value() == 0 && node.offset() == 0) ? CONTINUE : BREAK;
}
status visit(const set &node) {
return (node.value() == 0 && node.offset() == 0) ? CONTINUE : BREAK;
}
// Loops only terminate when the current cell reaches 0
// Thus loops following loops are dead
status visit(loop &node) { return CONTINUE; }
status visit(const loop &node) { return CONTINUE; }
};
};
}
}
#endif /* !BFC_DEAD_LOOPS_VISITOR_HPP */
<|endoftext|> |
<commit_before>/*
* Runtime CPU detection for ARM
* (C) 2009,2010,2013,2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/cpuid.h>
#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)
#if defined(BOTAN_TARGET_OS_IS_IOS)
#include <sys/types.h>
#include <sys/sysctl.h>
#else
#include <botan/internal/os_utils.h>
#endif
#endif
namespace Botan {
#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)
#if defined(BOTAN_TARGET_OS_IS_IOS)
namespace {
uint64_t flags_by_ios_machine_type(const std::string& machine)
{
/*
* This relies on a map of known machine names to features. This
* will quickly grow out of date as new products are introduced, but
* is apparently the best we can do for iOS.
*/
struct version_info {
std::string name;
size_t min_version_neon;
size_t min_version_armv8;
};
static const version_info min_versions[] = {
{ "iPhone", 2, 6 },
{ "iPad", 1, 4 },
{ "iPod", 4, 7 },
{ "AppleTV", 2, 5 },
};
if(machine.size() < 3)
return 0;
auto comma = machine.find(',');
// Simulator, or something we don't know about
if(comma == std::string::npos)
return 0;
std::string product = machine.substr(0, comma);
size_t version = 0;
size_t place = 1;
while(product.size() > 1 && ::isdigit(product.back()))
{
const size_t digit = product.back() - '0';
version += digit * place;
place *= 10;
product.pop_back();
}
if(version == 0)
return 0;
for(const version_info& info : min_versions)
{
if(info.name != product)
continue;
if(version >= info.min_version_armv8)
{
return CPUID::CPUID_ARM_AES_BIT |
CPUID::CPUID_ARM_PMULL_BIT |
CPUID::CPUID_ARM_SHA1_BIT |
CPUID::CPUID_ARM_SHA2_BIT |
CPUID::CPUID_ARM_NEON_BIT;
}
if(version >= info.min_version_neon)
return CPUID::CPUID_ARM_NEON_BIT;
}
// Some other product we don't know about
return 0;
}
}
#endif
uint64_t CPUID::CPUID_Data::detect_cpu_features(size_t* cache_line_size)
{
BOTAN_UNUSED(cache_line_size);
uint64_t detected_features = 0;
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
/*
* On systems with getauxval these bits should normally be defined
* in bits/auxv.h but some buggy? glibc installs seem to miss them.
* These following values are all fixed, for the Linux ELF format,
* so we just hardcode them in ARM_hwcap_bit enum.
*/
enum ARM_hwcap_bit {
#if defined(BOTAN_TARGET_ARCH_IS_ARM32)
NEON_bit = (1 << 12),
AES_bit = (1 << 0),
PMULL_bit = (1 << 1),
SHA1_bit = (1 << 2),
SHA2_bit = (1 << 3),
ARCH_hwcap_neon = 16, // AT_HWCAP
ARCH_hwcap_crypto = 26, // AT_HWCAP2
#elif defined(BOTAN_TARGET_ARCH_IS_ARM64)
NEON_bit = (1 << 1),
AES_bit = (1 << 3),
PMULL_bit = (1 << 4),
SHA1_bit = (1 << 5),
SHA2_bit = (1 << 6),
SHA3_bit = (1 << 17),
SM3_bit = (1 << 18),
SM4_bit = (1 << 19),
SHA2_512_bit = (1 << 21),
SVE_bit = (1 << 22),
ARCH_hwcap_neon = 16, // AT_HWCAP
ARCH_hwcap_crypto = 16, // AT_HWCAP
#endif
};
#if defined(AT_DCACHEBSIZE)
// Exists only on Linux
const unsigned long dcache_line = ::getauxval(AT_DCACHEBSIZE);
// plausibility check
if(dcache_line == 32 || dcache_line == 64 || dcache_line == 128)
*cache_line_size = static_cast<size_t>(dcache_line);
#endif
const unsigned long hwcap_neon = OS::get_auxval(ARM_hwcap_bit::ARCH_hwcap_neon);
if(hwcap_neon & ARM_hwcap_bit::NEON_bit)
detected_features |= CPUID::CPUID_ARM_NEON_BIT;
/*
On aarch64 this ends up calling getauxval twice with AT_HWCAP
It doesn't seem worth optimizing this out, since getauxval is
just reading a field in the ELF header.
*/
const unsigned long hwcap_crypto = OS::get_auxval(ARM_hwcap_bit::ARCH_hwcap_crypto);
if(hwcap_crypto & ARM_hwcap_bit::AES_bit)
detected_features |= CPUID::CPUID_ARM_AES_BIT;
if(hwcap_crypto & ARM_hwcap_bit::PMULL_bit)
detected_features |= CPUID::CPUID_ARM_PMULL_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SHA1_bit)
detected_features |= CPUID::CPUID_ARM_SHA1_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SHA2_bit)
detected_features |= CPUID::CPUID_ARM_SHA2_BIT;
#if defined(BOTAN_TARGET_ARCH_IS_ARM64)
if(hwcap_crypto & ARM_hwcap_bit::SHA3_bit)
detected_features |= CPUID::CPUID_ARM_SHA3_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SM3_bit)
detected_features |= CPUID::CPUID_ARM_SM3_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SM4_bit)
detected_features |= CPUID::CPUID_ARM_SM4_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SHA2_512_bit)
detected_features |= CPUID::CPUID_ARM_SHA2_512_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SVE_bit)
detected_features |= CPUID::CPUID_ARM_SVE_BIT;
#endif
#elif defined(BOTAN_TARGET_OS_IS_IOS)
char machine[64] = { 0 };
size_t size = sizeof(machine) - 1;
::sysctlbyname("hw.machine", machine, &size, nullptr, 0);
detected_features = flags_by_ios_machine_type(machine);
// No way to detect cache line size on iOS?
#elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_ARCH_IS_ARM64)
/*
No getauxval API available, fall back on probe functions. We only
bother with Aarch64 here to simplify the code and because going to
extreme contortions to support detect NEON on devices that probably
don't support it doesn't seem worthwhile.
NEON registers v0-v7 are caller saved in Aarch64
*/
auto neon_probe = []() noexcept -> int { asm("and v0.16b, v0.16b, v0.16b"); return 1; };
auto aes_probe = []() noexcept -> int { asm(".word 0x4e284800"); return 1; };
auto pmull_probe = []() noexcept -> int { asm(".word 0x0ee0e000"); return 1; };
auto sha1_probe = []() noexcept -> int { asm(".word 0x5e280800"); return 1; };
auto sha2_probe = []() noexcept -> int { asm(".word 0x5e282800"); return 1; };
// Only bother running the crypto detection if we found NEON
if(OS::run_cpu_instruction_probe(neon_probe) == 1)
{
detected_features |= CPUID::CPUID_ARM_NEON_BIT;
if(OS::run_cpu_instruction_probe(aes_probe) == 1)
detected_features |= CPUID::CPUID_ARM_AES_BIT;
if(OS::run_cpu_instruction_probe(pmull_probe) == 1)
detected_features |= CPUID::CPUID_ARM_PMULL_BIT;
if(OS::run_cpu_instruction_probe(sha1_probe) == 1)
detected_features |= CPUID::CPUID_ARM_SHA1_BIT;
if(OS::run_cpu_instruction_probe(sha2_probe) == 1)
detected_features |= CPUID::CPUID_ARM_SHA2_BIT;
}
#endif
return detected_features;
}
#endif
}
<commit_msg>cpu arm: Dead code as the symbol was never defined.<commit_after>/*
* Runtime CPU detection for ARM
* (C) 2009,2010,2013,2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/cpuid.h>
#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)
#if defined(BOTAN_TARGET_OS_IS_IOS)
#include <sys/types.h>
#include <sys/sysctl.h>
#else
#include <botan/internal/os_utils.h>
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
#include <sys/auxv.h>
#endif
#endif
#endif
namespace Botan {
#if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY)
#if defined(BOTAN_TARGET_OS_IS_IOS)
namespace {
uint64_t flags_by_ios_machine_type(const std::string& machine)
{
/*
* This relies on a map of known machine names to features. This
* will quickly grow out of date as new products are introduced, but
* is apparently the best we can do for iOS.
*/
struct version_info {
std::string name;
size_t min_version_neon;
size_t min_version_armv8;
};
static const version_info min_versions[] = {
{ "iPhone", 2, 6 },
{ "iPad", 1, 4 },
{ "iPod", 4, 7 },
{ "AppleTV", 2, 5 },
};
if(machine.size() < 3)
return 0;
auto comma = machine.find(',');
// Simulator, or something we don't know about
if(comma == std::string::npos)
return 0;
std::string product = machine.substr(0, comma);
size_t version = 0;
size_t place = 1;
while(product.size() > 1 && ::isdigit(product.back()))
{
const size_t digit = product.back() - '0';
version += digit * place;
place *= 10;
product.pop_back();
}
if(version == 0)
return 0;
for(const version_info& info : min_versions)
{
if(info.name != product)
continue;
if(version >= info.min_version_armv8)
{
return CPUID::CPUID_ARM_AES_BIT |
CPUID::CPUID_ARM_PMULL_BIT |
CPUID::CPUID_ARM_SHA1_BIT |
CPUID::CPUID_ARM_SHA2_BIT |
CPUID::CPUID_ARM_NEON_BIT;
}
if(version >= info.min_version_neon)
return CPUID::CPUID_ARM_NEON_BIT;
}
// Some other product we don't know about
return 0;
}
}
#endif
uint64_t CPUID::CPUID_Data::detect_cpu_features(size_t* cache_line_size)
{
BOTAN_UNUSED(cache_line_size);
uint64_t detected_features = 0;
#if defined(BOTAN_TARGET_OS_HAS_GETAUXVAL) || defined(BOTAN_TARGET_OS_HAS_ELF_AUX_INFO)
/*
* On systems with getauxval these bits should normally be defined
* in bits/auxv.h but some buggy? glibc installs seem to miss them.
* These following values are all fixed, for the Linux ELF format,
* so we just hardcode them in ARM_hwcap_bit enum.
*/
enum ARM_hwcap_bit {
#if defined(BOTAN_TARGET_ARCH_IS_ARM32)
NEON_bit = (1 << 12),
AES_bit = (1 << 0),
PMULL_bit = (1 << 1),
SHA1_bit = (1 << 2),
SHA2_bit = (1 << 3),
ARCH_hwcap_neon = 16, // AT_HWCAP
ARCH_hwcap_crypto = 26, // AT_HWCAP2
#elif defined(BOTAN_TARGET_ARCH_IS_ARM64)
NEON_bit = (1 << 1),
AES_bit = (1 << 3),
PMULL_bit = (1 << 4),
SHA1_bit = (1 << 5),
SHA2_bit = (1 << 6),
SHA3_bit = (1 << 17),
SM3_bit = (1 << 18),
SM4_bit = (1 << 19),
SHA2_512_bit = (1 << 21),
SVE_bit = (1 << 22),
ARCH_hwcap_neon = 16, // AT_HWCAP
ARCH_hwcap_crypto = 16, // AT_HWCAP
#endif
};
#if defined(AT_DCACHEBSIZE)
// Exists only on Linux
const unsigned long dcache_line = OS::get_auxval(AT_DCACHEBSIZE);
// plausibility check
if(dcache_line == 32 || dcache_line == 64 || dcache_line == 128)
*cache_line_size = static_cast<size_t>(dcache_line);
#endif
const unsigned long hwcap_neon = OS::get_auxval(ARM_hwcap_bit::ARCH_hwcap_neon);
if(hwcap_neon & ARM_hwcap_bit::NEON_bit)
detected_features |= CPUID::CPUID_ARM_NEON_BIT;
/*
On aarch64 this ends up calling getauxval twice with AT_HWCAP
It doesn't seem worth optimizing this out, since getauxval is
just reading a field in the ELF header.
*/
const unsigned long hwcap_crypto = OS::get_auxval(ARM_hwcap_bit::ARCH_hwcap_crypto);
if(hwcap_crypto & ARM_hwcap_bit::AES_bit)
detected_features |= CPUID::CPUID_ARM_AES_BIT;
if(hwcap_crypto & ARM_hwcap_bit::PMULL_bit)
detected_features |= CPUID::CPUID_ARM_PMULL_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SHA1_bit)
detected_features |= CPUID::CPUID_ARM_SHA1_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SHA2_bit)
detected_features |= CPUID::CPUID_ARM_SHA2_BIT;
#if defined(BOTAN_TARGET_ARCH_IS_ARM64)
if(hwcap_crypto & ARM_hwcap_bit::SHA3_bit)
detected_features |= CPUID::CPUID_ARM_SHA3_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SM3_bit)
detected_features |= CPUID::CPUID_ARM_SM3_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SM4_bit)
detected_features |= CPUID::CPUID_ARM_SM4_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SHA2_512_bit)
detected_features |= CPUID::CPUID_ARM_SHA2_512_BIT;
if(hwcap_crypto & ARM_hwcap_bit::SVE_bit)
detected_features |= CPUID::CPUID_ARM_SVE_BIT;
#endif
#elif defined(BOTAN_TARGET_OS_IS_IOS)
char machine[64] = { 0 };
size_t size = sizeof(machine) - 1;
::sysctlbyname("hw.machine", machine, &size, nullptr, 0);
detected_features = flags_by_ios_machine_type(machine);
// No way to detect cache line size on iOS?
#elif defined(BOTAN_USE_GCC_INLINE_ASM) && defined(BOTAN_TARGET_ARCH_IS_ARM64)
/*
No getauxval API available, fall back on probe functions. We only
bother with Aarch64 here to simplify the code and because going to
extreme contortions to support detect NEON on devices that probably
don't support it doesn't seem worthwhile.
NEON registers v0-v7 are caller saved in Aarch64
*/
auto neon_probe = []() noexcept -> int { asm("and v0.16b, v0.16b, v0.16b"); return 1; };
auto aes_probe = []() noexcept -> int { asm(".word 0x4e284800"); return 1; };
auto pmull_probe = []() noexcept -> int { asm(".word 0x0ee0e000"); return 1; };
auto sha1_probe = []() noexcept -> int { asm(".word 0x5e280800"); return 1; };
auto sha2_probe = []() noexcept -> int { asm(".word 0x5e282800"); return 1; };
// Only bother running the crypto detection if we found NEON
if(OS::run_cpu_instruction_probe(neon_probe) == 1)
{
detected_features |= CPUID::CPUID_ARM_NEON_BIT;
if(OS::run_cpu_instruction_probe(aes_probe) == 1)
detected_features |= CPUID::CPUID_ARM_AES_BIT;
if(OS::run_cpu_instruction_probe(pmull_probe) == 1)
detected_features |= CPUID::CPUID_ARM_PMULL_BIT;
if(OS::run_cpu_instruction_probe(sha1_probe) == 1)
detected_features |= CPUID::CPUID_ARM_SHA1_BIT;
if(OS::run_cpu_instruction_probe(sha2_probe) == 1)
detected_features |= CPUID::CPUID_ARM_SHA2_BIT;
}
#endif
return detected_features;
}
#endif
}
<|endoftext|> |
<commit_before>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "ApplicationPrivateData.hpp"
#include "../Window.hpp"
#include "pugl.hpp"
#include <ctime>
START_NAMESPACE_DGL
typedef std::list<DGL_NAMESPACE::Window*>::reverse_iterator WindowListReverseIterator;
// --------------------------------------------------------------------------------------------------------------------
Application::PrivateData::PrivateData(const bool standalone)
: world(puglNewWorld(standalone ? PUGL_PROGRAM : PUGL_MODULE,
standalone ? PUGL_WORLD_THREADS : 0x0)),
isStandalone(standalone),
isQuitting(false),
isStarting(true),
visibleWindows(0),
windows(),
idleCallbacks()
{
DISTRHO_SAFE_ASSERT_RETURN(world != nullptr,);
puglSetWorldHandle(world, this);
// FIXME
static int wc_count = 0;
char classNameBuf[256];
std::srand((std::time(NULL)));
std::snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d-%d-%p",
DISTRHO_MACRO_AS_STRING(DGL_NAMESPACE), std::rand(), ++wc_count, this);
classNameBuf[sizeof(classNameBuf)-1] = '\0';
d_stderr("--------------------------------------------------------------- className is %s", classNameBuf);
puglSetClassName(world, classNameBuf);
#ifdef HAVE_X11
sofdFileDialogSetup(world);
#endif
}
Application::PrivateData::~PrivateData()
{
DISTRHO_SAFE_ASSERT(isStarting || isQuitting);
DISTRHO_SAFE_ASSERT(visibleWindows == 0);
windows.clear();
idleCallbacks.clear();
if (world != nullptr)
puglFreeWorld(world);
}
// --------------------------------------------------------------------------------------------------------------------
void Application::PrivateData::oneWindowShown() noexcept
{
if (++visibleWindows == 1)
{
isQuitting = false;
isStarting = false;
}
}
void Application::PrivateData::oneWindowClosed() noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(visibleWindows != 0,);
if (--visibleWindows == 0)
isQuitting = true;
}
// --------------------------------------------------------------------------------------------------------------------
void Application::PrivateData::idle(const uint timeoutInMs)
{
if (world != nullptr)
{
const double timeoutInSeconds = timeoutInMs != 0
? static_cast<double>(timeoutInMs) / 1000.0
: 0.0;
puglUpdate(world, timeoutInSeconds);
}
for (std::list<IdleCallback*>::iterator it = idleCallbacks.begin(), ite = idleCallbacks.end(); it != ite; ++it)
{
IdleCallback* const idleCallback(*it);
idleCallback->idleCallback();
}
}
void Application::PrivateData::quit()
{
DISTRHO_SAFE_ASSERT_RETURN(isStandalone,);
isQuitting = true;
#ifndef DPF_TEST_APPLICATION_CPP
for (WindowListReverseIterator rit = windows.rbegin(), rite = windows.rend(); rit != rite; ++rit)
{
DGL_NAMESPACE::Window* const window(*rit);
window->close();
}
#endif
}
// --------------------------------------------------------------------------------------------------------------------
END_NAMESPACE_DGL
<commit_msg>testing<commit_after>/*
* DISTRHO Plugin Framework (DPF)
* Copyright (C) 2012-2021 Filipe Coelho <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any purpose with
* or without fee is hereby granted, provided that the above copyright notice and this
* permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
* TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
* NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
* IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "ApplicationPrivateData.hpp"
#include "../Window.hpp"
#include "pugl.hpp"
#include <ctime>
START_NAMESPACE_DGL
typedef std::list<DGL_NAMESPACE::Window*>::reverse_iterator WindowListReverseIterator;
// --------------------------------------------------------------------------------------------------------------------
Application::PrivateData::PrivateData(const bool standalone)
: world(puglNewWorld(standalone ? PUGL_PROGRAM : PUGL_MODULE,
standalone ? PUGL_WORLD_THREADS : 0x0)),
isStandalone(standalone),
isQuitting(false),
isStarting(true),
visibleWindows(0),
windows(),
idleCallbacks()
{
DISTRHO_SAFE_ASSERT_RETURN(world != nullptr,);
puglSetWorldHandle(world, this);
// FIXME
static int wc_count = 0;
char classNameBuf[256];
std::srand((std::time(NULL)));
std::snprintf(classNameBuf, sizeof(classNameBuf), "%s_%d-%d-%p",
"TESTING", std::rand(), ++wc_count, this);
// DISTRHO_MACRO_AS_STRING(DGL_NAMESPACE)
classNameBuf[sizeof(classNameBuf)-1] = '\0';
d_stderr("--------------------------------------------------------------- className is %s", classNameBuf);
puglSetClassName(world, classNameBuf);
#ifdef HAVE_X11
sofdFileDialogSetup(world);
#endif
}
Application::PrivateData::~PrivateData()
{
DISTRHO_SAFE_ASSERT(isStarting || isQuitting);
DISTRHO_SAFE_ASSERT(visibleWindows == 0);
windows.clear();
idleCallbacks.clear();
if (world != nullptr)
puglFreeWorld(world);
}
// --------------------------------------------------------------------------------------------------------------------
void Application::PrivateData::oneWindowShown() noexcept
{
if (++visibleWindows == 1)
{
isQuitting = false;
isStarting = false;
}
}
void Application::PrivateData::oneWindowClosed() noexcept
{
DISTRHO_SAFE_ASSERT_RETURN(visibleWindows != 0,);
if (--visibleWindows == 0)
isQuitting = true;
}
// --------------------------------------------------------------------------------------------------------------------
void Application::PrivateData::idle(const uint timeoutInMs)
{
if (world != nullptr)
{
const double timeoutInSeconds = timeoutInMs != 0
? static_cast<double>(timeoutInMs) / 1000.0
: 0.0;
puglUpdate(world, timeoutInSeconds);
}
for (std::list<IdleCallback*>::iterator it = idleCallbacks.begin(), ite = idleCallbacks.end(); it != ite; ++it)
{
IdleCallback* const idleCallback(*it);
idleCallback->idleCallback();
}
}
void Application::PrivateData::quit()
{
DISTRHO_SAFE_ASSERT_RETURN(isStandalone,);
isQuitting = true;
#ifndef DPF_TEST_APPLICATION_CPP
for (WindowListReverseIterator rit = windows.rbegin(), rite = windows.rend(); rit != rite; ++rit)
{
DGL_NAMESPACE::Window* const window(*rit);
window->close();
}
#endif
}
// --------------------------------------------------------------------------------------------------------------------
END_NAMESPACE_DGL
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkBSplineBaseTransform_hxx
#define __itkBSplineBaseTransform_hxx
#include "itkBSplineBaseTransform.h"
#include "itkContinuousIndex.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIteratorWithIndex.h"
namespace itk
{
// Constructor with default arguments
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::BSplineBaseTransform() : Superclass( 0 ),
m_CoefficientImages( this->ArrayOfImagePointerGeneratorHelper() )
{
this->m_InternalParametersBuffer = ParametersType( 0 );
// Instantiate a weights function
this->m_WeightsFunction = WeightsFunctionType::New();
}
// Destructor
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::~BSplineBaseTransform()
{
}
// Set the parameters
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::SetIdentity()
{
if( this->m_InternalParametersBuffer.Size() != this->GetNumberOfParameters() )
{
this->m_InternalParametersBuffer.SetSize( this->GetNumberOfParameters() );
}
this->m_InternalParametersBuffer.Fill( 0.0 );
this->SetParameters( this->m_InternalParametersBuffer );
this->Modified();
}
// Set the parameters
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::SetParameters( const ParametersType & parameters )
{
// check if the number of parameters match the
// expected number of parameters
if( parameters.Size() != this->GetNumberOfParameters() )
{
itkExceptionMacro( << "Mismatch between parameters size "
<< parameters.Size() << " and expected number of parameters "
<< this->GetNumberOfParameters()
<< ( this->m_CoefficientImages[0]->GetLargestPossibleRegion().GetNumberOfPixels() == 0 ?
". \nSince the size of the grid region is 0, perhaps you forgot to "
"SetGridRegion or SetFixedParameters before setting the Parameters."
: "" ) );
}
if( ¶meters != &( this->m_InternalParametersBuffer ) )
{
// Clean up this->m_InternalParametersBuffer because we will
// use an externally supplied set of parameters as the buffer
this->m_InternalParametersBuffer = parameters;
}
// Wrap flat array as images of coefficients
this->WrapAsImages();
// Modified is always called since we just have a pointer to the
// parameters and cannot know if the parameters have changed.
this->Modified();
}
// Set the parameters by value
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::SetParametersByValue( const ParametersType & parameters )
{
// check if the number of parameters match the
// expected number of parameters
if( parameters.Size() != this->GetNumberOfParameters() )
{
itkExceptionMacro( << "Mismatched between parameters size "
<< parameters.size() << " and region size "
<< this->GetNumberOfParameters() );
}
// copy parameters to this->m_InternalParametersBuffer
this->m_InternalParametersBuffer = parameters;
this->SetParameters( this->m_InternalParametersBuffer );
}
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::SetFixedParametersFromTransformDomainInformation() const
{
// Fixed Parameters store the following information:
// Grid Size
// Grid Origin
// Grid Spacing
// Grid Direction
// The size of each of these is equal to NDimensions
this->m_FixedParameters.SetSize( NDimensions * ( NDimensions + 3 ) );
this->SetFixedParametersGridSizeFromTransformDomainInformation();
this->SetFixedParametersGridOriginFromTransformDomainInformation();
this->SetFixedParametersGridSpacingFromTransformDomainInformation();
this->SetFixedParametersGridDirectionFromTransformDomainInformation();
this->Modified();
}
/**
* UpdateTransformParameters
*/
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::UpdateTransformParameters( const DerivativeType & update, TScalar factor )
{
NumberOfParametersType numberOfParameters = this->GetNumberOfParameters();
if( update.Size() != numberOfParameters )
{
itkExceptionMacro("Parameter update size, " << update.Size() << ", must "
" be same as transform parameter size, "
<< numberOfParameters << std::endl);
}
/* Make sure m_Parameters is updated to reflect the current values in
* the transform's other parameter-related variables. This is effective for
* managing the parallel variables used for storing parameter data,
* but inefficient. However for small global transforms, shouldn't be
* too bad. Dense-field transform will want to make sure m_Parameters
* is always updated whenever the transform is changed, so GetParameters
* can be skipped in their implementations of UpdateTransformParameters. */
if( factor == 1.0 )
{
for( NumberOfParametersType k = 0; k < numberOfParameters; k++ )
{
this->m_InternalParametersBuffer[k] += update[k];
}
}
else
{
for( NumberOfParametersType k = 0; k < numberOfParameters; k++ )
{
this->m_InternalParametersBuffer[k] += update[k] * factor;
}
}
/* Call SetParameters with the updated parameters.
* SetParameters in most transforms is used to assign the input params
* to member variables, possibly with some processing. The member variables
* are then used in TransformPoint.
* In the case of dense-field transforms that are updated in blocks from
* a threaded implementation, SetParameters doesn't do this, and is
* optimized to not copy the input parameters when == m_Parameters.
*/
this->SetParameters( this->m_InternalParametersBuffer );
/* Call Modified, following behavior of other transform when their
* parameters change, e.g. MatrixOffsetTransformBase */
this->Modified();
}
// Wrap flat parameters as images
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::WrapAsImages()
{
/**
* Wrap flat parameters array into SpaceDimension number of ITK images
* NOTE: For efficiency, parameters are not copied locally. The parameters
* are assumed to be maintained by the caller.
*/
PixelType *dataPointer = const_cast<PixelType *>( this->m_InternalParametersBuffer.data_block() );
const NumberOfParametersType numberOfPixels = this->GetNumberOfParametersPerDimension();
for( unsigned int j = 0; j < SpaceDimension; j++ )
{
this->m_CoefficientImages[j]->GetPixelContainer()->
SetImportPointer( dataPointer + j * numberOfPixels, numberOfPixels );
}
}
// Get the parameters
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
const typename BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>::ParametersType &
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::GetParameters() const
{
return this->m_InternalParametersBuffer;
}
// Get the parameters
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
const typename BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>::ParametersType &
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::GetFixedParameters() const
{
// HACK: This should not be necessary if the
// class is kept in a consistent state
// this->SetFixedParametersFromCoefficientImageInformation();
return this->m_FixedParameters;
}
// Print self
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::PrintSelf( std::ostream & os, Indent indent ) const
{
this->Superclass::PrintSelf(os, indent);
os << indent << "CoefficientImage: [ ";
for( unsigned int j = 0; j < SpaceDimension - 1; j++ )
{
os << this->m_CoefficientImages[j].GetPointer() << ", ";
}
os << this->m_CoefficientImages[SpaceDimension - 1].GetPointer()
<< " ]" << std::endl;
}
/** Get Jacobian at a point. A very specialized function just for BSplines */
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::ComputeJacobianFromBSplineWeightsWithRespectToPosition(
const InputPointType & point, WeightsType & weights,
ParameterIndexArrayType & indexes ) const
{
ContinuousIndexType index;
this->m_CoefficientImages[0]->TransformPhysicalPointToContinuousIndex( point, index );
// NOTE: if the support region does not lie totally within the grid
// we assume zero displacement and return the input point
if( !this->InsideValidRegion( index ) )
{
weights.Fill( 0.0 );
indexes.Fill( 0 );
return;
}
// Compute interpolation weights
IndexType supportIndex;
this->m_WeightsFunction->Evaluate(index, weights, supportIndex);
// For each dimension, copy the weight to the support region
RegionType supportRegion;
SizeType supportSize;
supportSize.Fill( SplineOrder + 1 );
supportRegion.SetSize( supportSize );
supportRegion.SetIndex( supportIndex );
unsigned long counter = 0;
typedef ImageRegionIterator<ImageType> IteratorType;
IteratorType coeffIterator = IteratorType(
this->m_CoefficientImages[0], supportRegion );
const ParametersValueType *basePointer =
this->m_CoefficientImages[0]->GetBufferPointer();
while( !coeffIterator.IsAtEnd() )
{
indexes[counter] = &( coeffIterator.Value() ) - basePointer;
// go to next coefficient in the support region
++counter;
++coeffIterator;
}
}
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
unsigned int
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::GetNumberOfAffectedWeights() const
{
return this->m_WeightsFunction->GetNumberOfWeights();
}
// This helper class is used to work around a race condition where the dynamically
// generated images must exist before the references to the sub-sections are created.
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
typename BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>::CoefficientImageArray
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::ArrayOfImagePointerGeneratorHelper(void) const
{
CoefficientImageArray tempArrayOfPointers;
for( unsigned int j = 0; j < SpaceDimension; j++ )
{
tempArrayOfPointers[j] = ImageType::New();
}
return tempArrayOfPointers;
}
// Transform a point
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
typename BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::OutputPointType
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::TransformPoint(const InputPointType & point) const
{
WeightsType weights( this->m_WeightsFunction->GetNumberOfWeights() );
ParameterIndexArrayType indices( this->m_WeightsFunction->GetNumberOfWeights() );
OutputPointType outputPoint;
bool inside;
this->TransformPoint( point, outputPoint, weights, indices, inside );
return outputPoint;
}
} // namespace
#endif
<commit_msg>STYLE: Fix initialization list in BSplineBaseTransform constructor<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef __itkBSplineBaseTransform_hxx
#define __itkBSplineBaseTransform_hxx
#include "itkBSplineBaseTransform.h"
#include "itkContinuousIndex.h"
#include "itkImageRegionIterator.h"
#include "itkImageRegionConstIteratorWithIndex.h"
namespace itk
{
// Constructor with default arguments
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::BSplineBaseTransform() :
Superclass( 0 ),
m_CoefficientImages( this->ArrayOfImagePointerGeneratorHelper() )
{
this->m_InternalParametersBuffer = ParametersType( 0 );
// Instantiate a weights function
this->m_WeightsFunction = WeightsFunctionType::New();
}
// Destructor
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::~BSplineBaseTransform()
{
}
// Set the parameters
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::SetIdentity()
{
if( this->m_InternalParametersBuffer.Size() != this->GetNumberOfParameters() )
{
this->m_InternalParametersBuffer.SetSize( this->GetNumberOfParameters() );
}
this->m_InternalParametersBuffer.Fill( 0.0 );
this->SetParameters( this->m_InternalParametersBuffer );
this->Modified();
}
// Set the parameters
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::SetParameters( const ParametersType & parameters )
{
// check if the number of parameters match the
// expected number of parameters
if( parameters.Size() != this->GetNumberOfParameters() )
{
itkExceptionMacro( << "Mismatch between parameters size "
<< parameters.Size() << " and expected number of parameters "
<< this->GetNumberOfParameters()
<< ( this->m_CoefficientImages[0]->GetLargestPossibleRegion().GetNumberOfPixels() == 0 ?
". \nSince the size of the grid region is 0, perhaps you forgot to "
"SetGridRegion or SetFixedParameters before setting the Parameters."
: "" ) );
}
if( ¶meters != &( this->m_InternalParametersBuffer ) )
{
// Clean up this->m_InternalParametersBuffer because we will
// use an externally supplied set of parameters as the buffer
this->m_InternalParametersBuffer = parameters;
}
// Wrap flat array as images of coefficients
this->WrapAsImages();
// Modified is always called since we just have a pointer to the
// parameters and cannot know if the parameters have changed.
this->Modified();
}
// Set the parameters by value
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::SetParametersByValue( const ParametersType & parameters )
{
// check if the number of parameters match the
// expected number of parameters
if( parameters.Size() != this->GetNumberOfParameters() )
{
itkExceptionMacro( << "Mismatched between parameters size "
<< parameters.size() << " and region size "
<< this->GetNumberOfParameters() );
}
// copy parameters to this->m_InternalParametersBuffer
this->m_InternalParametersBuffer = parameters;
this->SetParameters( this->m_InternalParametersBuffer );
}
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::SetFixedParametersFromTransformDomainInformation() const
{
// Fixed Parameters store the following information:
// Grid Size
// Grid Origin
// Grid Spacing
// Grid Direction
// The size of each of these is equal to NDimensions
this->m_FixedParameters.SetSize( NDimensions * ( NDimensions + 3 ) );
this->SetFixedParametersGridSizeFromTransformDomainInformation();
this->SetFixedParametersGridOriginFromTransformDomainInformation();
this->SetFixedParametersGridSpacingFromTransformDomainInformation();
this->SetFixedParametersGridDirectionFromTransformDomainInformation();
this->Modified();
}
/**
* UpdateTransformParameters
*/
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::UpdateTransformParameters( const DerivativeType & update, TScalar factor )
{
NumberOfParametersType numberOfParameters = this->GetNumberOfParameters();
if( update.Size() != numberOfParameters )
{
itkExceptionMacro("Parameter update size, " << update.Size() << ", must "
" be same as transform parameter size, "
<< numberOfParameters << std::endl);
}
/* Make sure m_Parameters is updated to reflect the current values in
* the transform's other parameter-related variables. This is effective for
* managing the parallel variables used for storing parameter data,
* but inefficient. However for small global transforms, shouldn't be
* too bad. Dense-field transform will want to make sure m_Parameters
* is always updated whenever the transform is changed, so GetParameters
* can be skipped in their implementations of UpdateTransformParameters. */
if( factor == 1.0 )
{
for( NumberOfParametersType k = 0; k < numberOfParameters; k++ )
{
this->m_InternalParametersBuffer[k] += update[k];
}
}
else
{
for( NumberOfParametersType k = 0; k < numberOfParameters; k++ )
{
this->m_InternalParametersBuffer[k] += update[k] * factor;
}
}
/* Call SetParameters with the updated parameters.
* SetParameters in most transforms is used to assign the input params
* to member variables, possibly with some processing. The member variables
* are then used in TransformPoint.
* In the case of dense-field transforms that are updated in blocks from
* a threaded implementation, SetParameters doesn't do this, and is
* optimized to not copy the input parameters when == m_Parameters.
*/
this->SetParameters( this->m_InternalParametersBuffer );
/* Call Modified, following behavior of other transform when their
* parameters change, e.g. MatrixOffsetTransformBase */
this->Modified();
}
// Wrap flat parameters as images
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::WrapAsImages()
{
/**
* Wrap flat parameters array into SpaceDimension number of ITK images
* NOTE: For efficiency, parameters are not copied locally. The parameters
* are assumed to be maintained by the caller.
*/
PixelType *dataPointer = const_cast<PixelType *>( this->m_InternalParametersBuffer.data_block() );
const NumberOfParametersType numberOfPixels = this->GetNumberOfParametersPerDimension();
for( unsigned int j = 0; j < SpaceDimension; j++ )
{
this->m_CoefficientImages[j]->GetPixelContainer()->
SetImportPointer( dataPointer + j * numberOfPixels, numberOfPixels );
}
}
// Get the parameters
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
const typename BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>::ParametersType &
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::GetParameters() const
{
return this->m_InternalParametersBuffer;
}
// Get the parameters
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
const typename BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>::ParametersType &
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::GetFixedParameters() const
{
// HACK: This should not be necessary if the
// class is kept in a consistent state
// this->SetFixedParametersFromCoefficientImageInformation();
return this->m_FixedParameters;
}
// Print self
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::PrintSelf( std::ostream & os, Indent indent ) const
{
this->Superclass::PrintSelf(os, indent);
os << indent << "CoefficientImage: [ ";
for( unsigned int j = 0; j < SpaceDimension - 1; j++ )
{
os << this->m_CoefficientImages[j].GetPointer() << ", ";
}
os << this->m_CoefficientImages[SpaceDimension - 1].GetPointer()
<< " ]" << std::endl;
}
/** Get Jacobian at a point. A very specialized function just for BSplines */
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
void
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::ComputeJacobianFromBSplineWeightsWithRespectToPosition(
const InputPointType & point, WeightsType & weights,
ParameterIndexArrayType & indexes ) const
{
ContinuousIndexType index;
this->m_CoefficientImages[0]->TransformPhysicalPointToContinuousIndex( point, index );
// NOTE: if the support region does not lie totally within the grid
// we assume zero displacement and return the input point
if( !this->InsideValidRegion( index ) )
{
weights.Fill( 0.0 );
indexes.Fill( 0 );
return;
}
// Compute interpolation weights
IndexType supportIndex;
this->m_WeightsFunction->Evaluate(index, weights, supportIndex);
// For each dimension, copy the weight to the support region
RegionType supportRegion;
SizeType supportSize;
supportSize.Fill( SplineOrder + 1 );
supportRegion.SetSize( supportSize );
supportRegion.SetIndex( supportIndex );
unsigned long counter = 0;
typedef ImageRegionIterator<ImageType> IteratorType;
IteratorType coeffIterator = IteratorType(
this->m_CoefficientImages[0], supportRegion );
const ParametersValueType *basePointer =
this->m_CoefficientImages[0]->GetBufferPointer();
while( !coeffIterator.IsAtEnd() )
{
indexes[counter] = &( coeffIterator.Value() ) - basePointer;
// go to next coefficient in the support region
++counter;
++coeffIterator;
}
}
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
unsigned int
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::GetNumberOfAffectedWeights() const
{
return this->m_WeightsFunction->GetNumberOfWeights();
}
// This helper class is used to work around a race condition where the dynamically
// generated images must exist before the references to the sub-sections are created.
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
typename BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>::CoefficientImageArray
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::ArrayOfImagePointerGeneratorHelper(void) const
{
CoefficientImageArray tempArrayOfPointers;
for( unsigned int j = 0; j < SpaceDimension; j++ )
{
tempArrayOfPointers[j] = ImageType::New();
}
return tempArrayOfPointers;
}
// Transform a point
template <typename TScalar, unsigned int NDimensions, unsigned int VSplineOrder>
typename BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::OutputPointType
BSplineBaseTransform<TScalar, NDimensions, VSplineOrder>
::TransformPoint(const InputPointType & point) const
{
WeightsType weights( this->m_WeightsFunction->GetNumberOfWeights() );
ParameterIndexArrayType indices( this->m_WeightsFunction->GetNumberOfWeights() );
OutputPointType outputPoint;
bool inside;
this->TransformPoint( point, outputPoint, weights, indices, inside );
return outputPoint;
}
} // namespace
#endif
<|endoftext|> |
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkAbstractNodeSelectionWidget.h"
#include "QmitkModelViewSelectionConnector.h"
QmitkAbstractNodeSelectionWidget::QmitkAbstractNodeSelectionWidget(QWidget* parent) : QWidget(parent), m_InvalidInfo("Error. Select data."),
m_EmptyInfo("Empty. Make a selection."), m_PopUpTitel("Select a data node"), m_PopUpHint(""),
m_IsOptional(false), m_SelectOnlyVisibleNodes(true), m_DataStorageDeletedTag(0), m_LastEmissionAllowance(true), m_RecursionGuard(false)
{
}
QmitkAbstractNodeSelectionWidget::~QmitkAbstractNodeSelectionWidget()
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNotNull())
{
// remove Listener for the data storage itself
dataStorage->RemoveObserver(m_DataStorageDeletedTag);
// remove "add node listener" from data storage
dataStorage->AddNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// remove "remove node listener" from data storage
dataStorage->RemoveNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
for (auto& node : m_CurrentInternalSelection)
{
this->RemoveNodeObserver(node);
}
}
QmitkAbstractNodeSelectionWidget::NodeList QmitkAbstractNodeSelectionWidget::GetSelectedNodes() const
{
return this->CompileEmitSelection();
}
QmitkAbstractNodeSelectionWidget::ConstNodeStdVector QmitkAbstractNodeSelectionWidget::GetSelectedNodesStdVector() const
{
auto result = this->GetSelectedNodes();
return ConstNodeStdVector(result.begin(), result.end());
}
void QmitkAbstractNodeSelectionWidget::SetDataStorage(mitk::DataStorage* dataStorage)
{
if (m_DataStorage == dataStorage)
{
return;
}
auto oldStorage = m_DataStorage.Lock();
if (oldStorage.IsNotNull())
{
// remove Listener for the data storage itself
oldStorage->RemoveObserver(m_DataStorageDeletedTag);
// remove "add node listener" from old data storage
oldStorage->AddNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// remove "remove node listener" from old data storage
oldStorage->RemoveNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
m_DataStorage = dataStorage;
auto newStorage = m_DataStorage.Lock();
if (newStorage.IsNotNull())
{
// add Listener for the data storage itself
auto command = itk::SimpleMemberCommand<QmitkAbstractNodeSelectionWidget>::New();
command->SetCallbackFunction(this, &QmitkAbstractNodeSelectionWidget::SetDataStorageDeleted);
m_DataStorageDeletedTag = newStorage->AddObserver(itk::DeleteEvent(), command);
// add "add node listener" for new data storage
newStorage->AddNodeEvent.AddListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// add remove node listener for new data storage
newStorage->RemoveNodeEvent.AddListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
this->OnDataStorageChanged();
this->HandleChangeOfInternalSelection({});
}
void QmitkAbstractNodeSelectionWidget::SetNodePredicate(const mitk::NodePredicateBase* nodePredicate)
{
if (m_NodePredicate != nodePredicate)
{
m_NodePredicate = nodePredicate;
this->OnNodePredicateChanged();
NodeList newInternalNodes;
for (auto& node : m_CurrentInternalSelection)
{
if (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node))
{
newInternalNodes.append(node);
}
}
if (!m_SelectOnlyVisibleNodes)
{
for (auto& node : m_CurrentExternalSelection)
{
if (!newInternalNodes.contains(node) && (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node)))
{
newInternalNodes.append(node);
}
}
}
this->HandleChangeOfInternalSelection(newInternalNodes);
}
}
void QmitkAbstractNodeSelectionWidget::HandleChangeOfInternalSelection(NodeList newInternalSelection)
{
this->ReviseSelectionChanged(m_CurrentInternalSelection, newInternalSelection);
this->SetCurrentInternalSelection(newInternalSelection);
this->OnInternalSelectionChanged();
auto newEmission = this->CompileEmitSelection();
this->EmitSelection(newEmission);
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetCurrentSelection(NodeList selectedNodes)
{
if (!m_RecursionGuard)
{
m_CurrentExternalSelection = selectedNodes;
auto dataStorage = m_DataStorage.Lock();
NodeList newInternalSelection;
for (auto node : selectedNodes)
{
if (dataStorage.IsNotNull() && dataStorage->Exists(node) && (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node)))
{
newInternalSelection.append(node);
}
}
this->HandleChangeOfInternalSelection(newInternalSelection);
}
}
const mitk::NodePredicateBase* QmitkAbstractNodeSelectionWidget::GetNodePredicate() const
{
return m_NodePredicate;
}
QString QmitkAbstractNodeSelectionWidget::GetInvalidInfo() const
{
return m_InvalidInfo;
}
QString QmitkAbstractNodeSelectionWidget::GetEmptyInfo() const
{
return m_EmptyInfo;
}
QString QmitkAbstractNodeSelectionWidget::GetPopUpTitel() const
{
return m_PopUpTitel;
}
QString QmitkAbstractNodeSelectionWidget::GetPopUpHint() const
{
return m_PopUpHint;
}
bool QmitkAbstractNodeSelectionWidget::GetSelectionIsOptional() const
{
return m_IsOptional;
}
bool QmitkAbstractNodeSelectionWidget::GetSelectOnlyVisibleNodes() const
{
return m_SelectOnlyVisibleNodes;
}
void QmitkAbstractNodeSelectionWidget::SetSelectOnlyVisibleNodes(bool selectOnlyVisibleNodes)
{
if (m_SelectOnlyVisibleNodes != selectOnlyVisibleNodes)
{
m_SelectOnlyVisibleNodes = selectOnlyVisibleNodes;
auto newEmission = this->CompileEmitSelection();
this->EmitSelection(newEmission);
}
}
void QmitkAbstractNodeSelectionWidget::SetInvalidInfo(QString info)
{
m_InvalidInfo = info;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetEmptyInfo(QString info)
{
m_EmptyInfo = info;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetPopUpTitel(QString info)
{
m_PopUpTitel = info;
}
void QmitkAbstractNodeSelectionWidget::SetPopUpHint(QString info)
{
m_PopUpHint = info;
}
void QmitkAbstractNodeSelectionWidget::SetSelectionIsOptional(bool isOptional)
{
m_IsOptional = isOptional;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetDataStorageDeleted()
{
this->OnDataStorageChanged();
this->HandleChangeOfInternalSelection({});
}
void QmitkAbstractNodeSelectionWidget::ReviseSelectionChanged(const NodeList& /*oldInternalSelection*/, NodeList& /*newInternalSelection*/)
{
}
bool QmitkAbstractNodeSelectionWidget::AllowEmissionOfSelection(const NodeList& /*emissionCandidates*/) const
{
return true;
}
void QmitkAbstractNodeSelectionWidget::EmitSelection(const NodeList& emissionCandidates)
{
m_LastEmissionAllowance = this->AllowEmissionOfSelection(emissionCandidates);
if (m_LastEmissionAllowance && !EqualNodeSelections(m_LastEmission, emissionCandidates))
{
m_RecursionGuard = true;
emit CurrentSelectionChanged(emissionCandidates);
m_RecursionGuard = false;
m_LastEmission = emissionCandidates;
}
}
void QmitkAbstractNodeSelectionWidget::SetCurrentInternalSelection(NodeList selectedNodes)
{
for (auto& node : m_CurrentInternalSelection)
{
this->RemoveNodeObserver(node);
}
m_CurrentInternalSelection = selectedNodes;
for (auto& node : m_CurrentInternalSelection)
{
this->AddNodeObserver(node);
}
}
const QmitkAbstractNodeSelectionWidget::NodeList& QmitkAbstractNodeSelectionWidget::GetCurrentInternalSelection() const
{
return m_CurrentInternalSelection;
}
const QmitkAbstractNodeSelectionWidget::NodeList& QmitkAbstractNodeSelectionWidget::GetCurrentExternalSelection() const
{
return m_CurrentExternalSelection;
}
void QmitkAbstractNodeSelectionWidget::OnNodePredicateChanged()
{
}
void QmitkAbstractNodeSelectionWidget::OnDataStorageChanged()
{
}
void QmitkAbstractNodeSelectionWidget::OnInternalSelectionChanged()
{
}
void QmitkAbstractNodeSelectionWidget::NodeAddedToStorage(const mitk::DataNode* node)
{
this->OnNodeAddedToStorage(node);
}
void QmitkAbstractNodeSelectionWidget::OnNodeAddedToStorage(const mitk::DataNode* /*node*/)
{
}
void QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage(const mitk::DataNode* node)
{
this->OnNodeRemovedFromStorage(node);
this->RemoveNodeFromSelection(node);
}
void QmitkAbstractNodeSelectionWidget::OnNodeRemovedFromStorage(const mitk::DataNode* /*node*/)
{
}
QmitkAbstractNodeSelectionWidget::NodeList QmitkAbstractNodeSelectionWidget::CompileEmitSelection() const
{
NodeList result = m_CurrentInternalSelection;
if (!m_SelectOnlyVisibleNodes)
{
for (auto node : m_CurrentExternalSelection)
{
if (!result.contains(node) && m_NodePredicate.IsNotNull() && !m_NodePredicate->CheckNode(node))
{
result.append(node);
}
}
}
return result;
}
void QmitkAbstractNodeSelectionWidget::RemoveNodeFromSelection(const mitk::DataNode* node)
{
auto newSelection = m_CurrentInternalSelection;
auto finding = std::find(std::begin(newSelection), std::end(newSelection), node);
if (finding != std::end(newSelection))
{
newSelection.erase(finding);
this->HandleChangeOfInternalSelection(newSelection);
}
}
void QmitkAbstractNodeSelectionWidget::OnNodeModified(const itk::Object * caller, const itk::EventObject & event)
{
if (itk::ModifiedEvent().CheckEvent(&event))
{
auto node = dynamic_cast<const mitk::DataNode*>(caller);
if (node)
{
if (m_NodePredicate.IsNotNull() && !m_NodePredicate->CheckNode(node))
{
this->RemoveNodeFromSelection(node);
}
else
{
auto oldAllowance = m_LastEmissionAllowance;
auto newEmission = this->CompileEmitSelection();
auto nonConstNode = const_cast<mitk::DataNode*>(node);
if (newEmission.contains(nonConstNode) && (oldAllowance != this->AllowEmissionOfSelection(newEmission)))
{
this->EmitSelection(newEmission);
this->UpdateInfo();
}
}
}
}
}
void QmitkAbstractNodeSelectionWidget::AddNodeObserver(mitk::DataNode* node)
{
if (node)
{
auto modifiedCommand = itk::MemberCommand<QmitkAbstractNodeSelectionWidget>::New();
modifiedCommand->SetCallbackFunction(this, &QmitkAbstractNodeSelectionWidget::OnNodeModified);
auto nodeModifiedObserverTag = node->AddObserver(itk::ModifiedEvent(), modifiedCommand);
m_NodeObserverTags.insert(std::make_pair(node, nodeModifiedObserverTag));
}
}
void QmitkAbstractNodeSelectionWidget::RemoveNodeObserver(mitk::DataNode* node)
{
if (node)
{
auto finding = m_NodeObserverTags.find(node);
if (finding != std::end(m_NodeObserverTags))
{
node->RemoveObserver(finding->second);
}
else
{
MITK_ERROR << "Selection widget is in a wrong state. A node should be removed from the internal selection but seems to have no observer. Node:" << node;
}
m_NodeObserverTags.erase(node);
}
}
<commit_msg>Fixed T27200<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "QmitkAbstractNodeSelectionWidget.h"
#include "QmitkModelViewSelectionConnector.h"
QmitkAbstractNodeSelectionWidget::QmitkAbstractNodeSelectionWidget(QWidget* parent) : QWidget(parent), m_InvalidInfo("Error. Select data."),
m_EmptyInfo("Empty. Make a selection."), m_PopUpTitel("Select a data node"), m_PopUpHint(""),
m_IsOptional(false), m_SelectOnlyVisibleNodes(true), m_DataStorageDeletedTag(0), m_LastEmissionAllowance(true), m_RecursionGuard(false)
{
}
QmitkAbstractNodeSelectionWidget::~QmitkAbstractNodeSelectionWidget()
{
auto dataStorage = m_DataStorage.Lock();
if (dataStorage.IsNotNull())
{
// remove Listener for the data storage itself
dataStorage->RemoveObserver(m_DataStorageDeletedTag);
// remove "add node listener" from data storage
dataStorage->AddNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// remove "remove node listener" from data storage
dataStorage->RemoveNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
for (auto& node : m_CurrentInternalSelection)
{
this->RemoveNodeObserver(node);
}
}
QmitkAbstractNodeSelectionWidget::NodeList QmitkAbstractNodeSelectionWidget::GetSelectedNodes() const
{
return this->CompileEmitSelection();
}
QmitkAbstractNodeSelectionWidget::ConstNodeStdVector QmitkAbstractNodeSelectionWidget::GetSelectedNodesStdVector() const
{
auto result = this->GetSelectedNodes();
return ConstNodeStdVector(result.begin(), result.end());
}
void QmitkAbstractNodeSelectionWidget::SetDataStorage(mitk::DataStorage* dataStorage)
{
if (m_DataStorage == dataStorage)
{
return;
}
auto oldStorage = m_DataStorage.Lock();
if (oldStorage.IsNotNull())
{
// remove Listener for the data storage itself
oldStorage->RemoveObserver(m_DataStorageDeletedTag);
// remove "add node listener" from old data storage
oldStorage->AddNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// remove "remove node listener" from old data storage
oldStorage->RemoveNodeEvent.RemoveListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
m_DataStorage = dataStorage;
auto newStorage = m_DataStorage.Lock();
if (newStorage.IsNotNull())
{
// add Listener for the data storage itself
auto command = itk::SimpleMemberCommand<QmitkAbstractNodeSelectionWidget>::New();
command->SetCallbackFunction(this, &QmitkAbstractNodeSelectionWidget::SetDataStorageDeleted);
m_DataStorageDeletedTag = newStorage->AddObserver(itk::DeleteEvent(), command);
// add "add node listener" for new data storage
newStorage->AddNodeEvent.AddListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeAddedToStorage));
// add remove node listener for new data storage
newStorage->RemoveNodeEvent.AddListener(
mitk::MessageDelegate1<QmitkAbstractNodeSelectionWidget, const mitk::DataNode*>(this, &QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage));
}
this->OnDataStorageChanged();
this->HandleChangeOfInternalSelection({});
}
void QmitkAbstractNodeSelectionWidget::SetNodePredicate(const mitk::NodePredicateBase* nodePredicate)
{
if (m_NodePredicate != nodePredicate)
{
m_NodePredicate = nodePredicate;
this->OnNodePredicateChanged();
NodeList newInternalNodes;
for (auto& node : m_CurrentInternalSelection)
{
if (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node))
{
newInternalNodes.append(node);
}
}
if (!m_SelectOnlyVisibleNodes)
{
for (auto& node : m_CurrentExternalSelection)
{
if (!newInternalNodes.contains(node) && (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node)))
{
newInternalNodes.append(node);
}
}
}
this->HandleChangeOfInternalSelection(newInternalNodes);
}
}
void QmitkAbstractNodeSelectionWidget::HandleChangeOfInternalSelection(NodeList newInternalSelection)
{
if (!EqualNodeSelections(m_CurrentInternalSelection, newInternalSelection))
{
this->ReviseSelectionChanged(m_CurrentInternalSelection, newInternalSelection);
this->SetCurrentInternalSelection(newInternalSelection);
this->OnInternalSelectionChanged();
auto newEmission = this->CompileEmitSelection();
this->EmitSelection(newEmission);
this->UpdateInfo();
}
}
void QmitkAbstractNodeSelectionWidget::SetCurrentSelection(NodeList selectedNodes)
{
if (!m_RecursionGuard)
{
m_CurrentExternalSelection = selectedNodes;
auto dataStorage = m_DataStorage.Lock();
NodeList newInternalSelection;
for (auto node : selectedNodes)
{
if (dataStorage.IsNotNull() && dataStorage->Exists(node) && (m_NodePredicate.IsNull() || m_NodePredicate->CheckNode(node)))
{
newInternalSelection.append(node);
}
}
this->HandleChangeOfInternalSelection(newInternalSelection);
}
}
const mitk::NodePredicateBase* QmitkAbstractNodeSelectionWidget::GetNodePredicate() const
{
return m_NodePredicate;
}
QString QmitkAbstractNodeSelectionWidget::GetInvalidInfo() const
{
return m_InvalidInfo;
}
QString QmitkAbstractNodeSelectionWidget::GetEmptyInfo() const
{
return m_EmptyInfo;
}
QString QmitkAbstractNodeSelectionWidget::GetPopUpTitel() const
{
return m_PopUpTitel;
}
QString QmitkAbstractNodeSelectionWidget::GetPopUpHint() const
{
return m_PopUpHint;
}
bool QmitkAbstractNodeSelectionWidget::GetSelectionIsOptional() const
{
return m_IsOptional;
}
bool QmitkAbstractNodeSelectionWidget::GetSelectOnlyVisibleNodes() const
{
return m_SelectOnlyVisibleNodes;
}
void QmitkAbstractNodeSelectionWidget::SetSelectOnlyVisibleNodes(bool selectOnlyVisibleNodes)
{
if (m_SelectOnlyVisibleNodes != selectOnlyVisibleNodes)
{
m_SelectOnlyVisibleNodes = selectOnlyVisibleNodes;
auto newEmission = this->CompileEmitSelection();
this->EmitSelection(newEmission);
}
}
void QmitkAbstractNodeSelectionWidget::SetInvalidInfo(QString info)
{
m_InvalidInfo = info;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetEmptyInfo(QString info)
{
m_EmptyInfo = info;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetPopUpTitel(QString info)
{
m_PopUpTitel = info;
}
void QmitkAbstractNodeSelectionWidget::SetPopUpHint(QString info)
{
m_PopUpHint = info;
}
void QmitkAbstractNodeSelectionWidget::SetSelectionIsOptional(bool isOptional)
{
m_IsOptional = isOptional;
this->UpdateInfo();
}
void QmitkAbstractNodeSelectionWidget::SetDataStorageDeleted()
{
this->OnDataStorageChanged();
this->HandleChangeOfInternalSelection({});
}
void QmitkAbstractNodeSelectionWidget::ReviseSelectionChanged(const NodeList& /*oldInternalSelection*/, NodeList& /*newInternalSelection*/)
{
}
bool QmitkAbstractNodeSelectionWidget::AllowEmissionOfSelection(const NodeList& /*emissionCandidates*/) const
{
return true;
}
void QmitkAbstractNodeSelectionWidget::EmitSelection(const NodeList& emissionCandidates)
{
m_LastEmissionAllowance = this->AllowEmissionOfSelection(emissionCandidates);
if (m_LastEmissionAllowance && !EqualNodeSelections(m_LastEmission, emissionCandidates))
{
m_RecursionGuard = true;
emit CurrentSelectionChanged(emissionCandidates);
m_RecursionGuard = false;
m_LastEmission = emissionCandidates;
}
}
void QmitkAbstractNodeSelectionWidget::SetCurrentInternalSelection(NodeList selectedNodes)
{
for (auto& node : m_CurrentInternalSelection)
{
this->RemoveNodeObserver(node);
}
m_CurrentInternalSelection = selectedNodes;
for (auto& node : m_CurrentInternalSelection)
{
this->AddNodeObserver(node);
}
}
const QmitkAbstractNodeSelectionWidget::NodeList& QmitkAbstractNodeSelectionWidget::GetCurrentInternalSelection() const
{
return m_CurrentInternalSelection;
}
const QmitkAbstractNodeSelectionWidget::NodeList& QmitkAbstractNodeSelectionWidget::GetCurrentExternalSelection() const
{
return m_CurrentExternalSelection;
}
void QmitkAbstractNodeSelectionWidget::OnNodePredicateChanged()
{
}
void QmitkAbstractNodeSelectionWidget::OnDataStorageChanged()
{
}
void QmitkAbstractNodeSelectionWidget::OnInternalSelectionChanged()
{
}
void QmitkAbstractNodeSelectionWidget::NodeAddedToStorage(const mitk::DataNode* node)
{
this->OnNodeAddedToStorage(node);
}
void QmitkAbstractNodeSelectionWidget::OnNodeAddedToStorage(const mitk::DataNode* /*node*/)
{
}
void QmitkAbstractNodeSelectionWidget::NodeRemovedFromStorage(const mitk::DataNode* node)
{
this->OnNodeRemovedFromStorage(node);
this->RemoveNodeFromSelection(node);
}
void QmitkAbstractNodeSelectionWidget::OnNodeRemovedFromStorage(const mitk::DataNode* /*node*/)
{
}
QmitkAbstractNodeSelectionWidget::NodeList QmitkAbstractNodeSelectionWidget::CompileEmitSelection() const
{
NodeList result = m_CurrentInternalSelection;
if (!m_SelectOnlyVisibleNodes)
{
for (auto node : m_CurrentExternalSelection)
{
if (!result.contains(node) && m_NodePredicate.IsNotNull() && !m_NodePredicate->CheckNode(node))
{
result.append(node);
}
}
}
return result;
}
void QmitkAbstractNodeSelectionWidget::RemoveNodeFromSelection(const mitk::DataNode* node)
{
auto newSelection = m_CurrentInternalSelection;
auto finding = std::find(std::begin(newSelection), std::end(newSelection), node);
if (finding != std::end(newSelection))
{
newSelection.erase(finding);
this->HandleChangeOfInternalSelection(newSelection);
}
}
void QmitkAbstractNodeSelectionWidget::OnNodeModified(const itk::Object * caller, const itk::EventObject & event)
{
if (itk::ModifiedEvent().CheckEvent(&event))
{
auto node = dynamic_cast<const mitk::DataNode*>(caller);
if (node)
{
if (m_NodePredicate.IsNotNull() && !m_NodePredicate->CheckNode(node))
{
this->RemoveNodeFromSelection(node);
}
else
{
auto oldAllowance = m_LastEmissionAllowance;
auto newEmission = this->CompileEmitSelection();
auto nonConstNode = const_cast<mitk::DataNode*>(node);
if (newEmission.contains(nonConstNode) && (oldAllowance != this->AllowEmissionOfSelection(newEmission)))
{
this->EmitSelection(newEmission);
this->UpdateInfo();
}
}
}
}
}
void QmitkAbstractNodeSelectionWidget::AddNodeObserver(mitk::DataNode* node)
{
if (node)
{
auto modifiedCommand = itk::MemberCommand<QmitkAbstractNodeSelectionWidget>::New();
modifiedCommand->SetCallbackFunction(this, &QmitkAbstractNodeSelectionWidget::OnNodeModified);
auto nodeModifiedObserverTag = node->AddObserver(itk::ModifiedEvent(), modifiedCommand);
m_NodeObserverTags.insert(std::make_pair(node, nodeModifiedObserverTag));
}
}
void QmitkAbstractNodeSelectionWidget::RemoveNodeObserver(mitk::DataNode* node)
{
if (node)
{
auto finding = m_NodeObserverTags.find(node);
if (finding != std::end(m_NodeObserverTags))
{
node->RemoveObserver(finding->second);
}
else
{
MITK_ERROR << "Selection widget is in a wrong state. A node should be removed from the internal selection but seems to have no observer. Node:" << node;
}
m_NodeObserverTags.erase(node);
}
}
<|endoftext|> |
<commit_before>#include "../ClipperUtils.hpp"
#include "../PolylineCollection.hpp"
#include "../Surface.hpp"
#include <cmath>
#include <algorithm>
#include <iostream>
#include "FillGyroid.hpp"
namespace Slic3r {
static inline double f(double x, double z_sin, double z_cos, bool vertical, bool flip)
{
if (vertical) {
double phase_offset = (z_cos < 0 ? M_PI : 0) + M_PI;
double a = sin(x + phase_offset);
double b = - z_cos;
double res = z_sin * cos(x + phase_offset + (flip ? M_PI : 0.));
double r = sqrt(sqr(a) + sqr(b));
return asin(a/r) + asin(res/r) + M_PI;
}
else {
double phase_offset = z_sin < 0 ? M_PI : 0.;
double a = cos(x + phase_offset);
double b = - z_sin;
double res = z_cos * sin(x + phase_offset + (flip ? 0 : M_PI));
double r = sqrt(sqr(a) + sqr(b));
return (asin(a/r) + asin(res/r) + 0.5 * M_PI);
}
}
static inline Polyline make_wave(
const std::vector<Vec2d>& one_period, double width, double height, double offset, double scaleFactor,
double z_cos, double z_sin, bool vertical, bool flip)
{
std::vector<Vec2d> points = one_period;
double period = points.back()(0);
if (width != period) // do not extend if already truncated
{
points.reserve(one_period.size() * floor(width / period));
points.pop_back();
int n = points.size();
do {
points.emplace_back(Vec2d(points[points.size()-n](0) + period, points[points.size()-n](1)));
} while (points.back()(0) < width - EPSILON);
points.emplace_back(Vec2d(width, f(width, z_sin, z_cos, vertical, flip)));
}
// and construct the final polyline to return:
Polyline polyline;
polyline.points.reserve(points.size());
for (auto& point : points) {
point(1) += offset;
point(1) = clamp(0., height, double(point(1)));
if (vertical)
std::swap(point(0), point(1));
polyline.points.emplace_back((point * scaleFactor).cast<coord_t>());
}
return polyline;
}
static std::vector<Vec2d> make_one_period(double width, double scaleFactor, double z_cos, double z_sin, bool vertical, bool flip, double tolerance)
{
std::vector<Vec2d> points;
double dx = M_PI_2; // exact coordinates on main inflexion lobes
double limit = std::min(2*M_PI, width);
points.reserve(ceil(limit / tolerance / 3));
for (double x = 0.; x < limit - EPSILON; x += dx) {
points.emplace_back(Vec2d(x, f(x, z_sin, z_cos, vertical, flip)));
}
points.emplace_back(Vec2d(limit, f(limit, z_sin, z_cos, vertical, flip)));
// piecewise increase in resolution up to requested tolerance
for(;;)
{
size_t size = points.size();
for (unsigned int i = 1;i < size; ++i) {
auto& lp = points[i-1]; // left point
auto& rp = points[i]; // right point
double x = lp(0) + (rp(0) - lp(0)) / 2;
double y = f(x, z_sin, z_cos, vertical, flip);
Vec2d ip = {x, y};
if (std::abs(cross2(Vec2d(ip - lp), Vec2d(ip - rp))) > sqr(tolerance)) {
points.emplace_back(std::move(ip));
}
}
if (size == points.size())
break;
else
{
// insert new points in order
std::sort(points.begin(), points.end(),
[](const Vec2d &lhs, const Vec2d &rhs) { return lhs(0) < rhs(0); });
}
}
return points;
}
static Polylines make_gyroid_waves(double gridZ, double density_adjusted, double line_spacing, double width, double height)
{
const double scaleFactor = scale_(line_spacing) / density_adjusted;
// tolerance (in scaled units)
// TODO: should consider layer thickness
const double tolerance = line_spacing / 2 / unscale<double>(scaleFactor);
//scale factor for 5% : 8 712 388
// 1z = 10^-6 mm ?
const double z = gridZ / scaleFactor;
const double z_sin = sin(z);
const double z_cos = cos(z);
bool vertical = (std::abs(z_sin) <= std::abs(z_cos));
double lower_bound = 0.;
double upper_bound = height;
bool flip = true;
if (vertical) {
flip = false;
lower_bound = -M_PI;
upper_bound = width - M_PI_2;
std::swap(width,height);
}
std::vector<Vec2d> one_period_odd = make_one_period(width, scaleFactor, z_cos, z_sin, vertical, flip, tolerance); // creates one period of the waves, so it doesn't have to be recalculated all the time
flip = !flip; // even polylines are a bit shifted
std::vector<Vec2d> one_period_even = make_one_period(width, scaleFactor, z_cos, z_sin, vertical, flip, tolerance);
Polylines result;
for (double y0 = lower_bound; y0 < upper_bound + EPSILON; y0 += M_PI) {
// creates odd polylines
result.emplace_back(make_wave(one_period_odd, width, height, y0, scaleFactor, z_cos, z_sin, vertical, flip));
// creates even polylines
y0 += M_PI;
if (y0 < upper_bound + EPSILON) {
result.emplace_back(make_wave(one_period_even, width, height, y0, scaleFactor, z_cos, z_sin, vertical, flip));
}
}
return result;
}
void FillGyroid::_fill_surface_single(
const FillParams ¶ms,
unsigned int thickness_layers,
const std::pair<float, Point> &direction,
ExPolygon &expolygon,
Polylines &polylines_out)
{
// no rotation is supported for this infill pattern (yet)
BoundingBox bb = expolygon.contour.bounding_box();
// Density adjusted to have a good %of weight.
double density_adjusted = std::max(0., params.density * 2.44);
// Distance between the gyroid waves in scaled coordinates.
coord_t distance = coord_t(scale_(this->spacing) / density_adjusted);
// align bounding box to a multiple of our grid module
bb.merge(_align_to_grid(bb.min, Point(2.*M_PI*distance, 2.*M_PI*distance)));
// generate pattern
Polylines polylines_square = make_gyroid_waves(
scale_(this->z),
density_adjusted,
this->spacing,
ceil(bb.size()(0) / distance) + 1.,
ceil(bb.size()(1) / distance) + 1.);
// move pattern in place
for (Polyline &polyline : polylines_square)
polyline.translate(bb.min(0), bb.min(1));
// clip pattern to boundaries, keeping the polyline order & ordering the fragment to be able to join them easily
//Polylines polylines = intersection_pl(polylines_square, (Polygons)expolygon);
Polylines polylines_chained;
for (size_t idx_polyline = 0; idx_polyline < polylines_square.size(); ++idx_polyline) {
Polyline &poly_to_cut = polylines_square[idx_polyline];
Polylines polylines_to_sort = intersection_pl(Polylines() = { poly_to_cut }, (Polygons)expolygon);
for (Polyline &polyline : polylines_to_sort) {
//TODO: replace by closest_index_point()
if (idx_polyline % 2 == 0) {
if (poly_to_cut.points.front().distance_to_square(polyline.points.front()) > poly_to_cut.points.front().distance_to_square(polyline.points.back())) {
polyline.reverse();
}
} else {
if (poly_to_cut.points.back().distance_to_square(polyline.points.front()) > poly_to_cut.points.back().distance_to_square(polyline.points.back())) {
polyline.reverse();
}
}
}
if (polylines_to_sort.size() > 1) {
Point nearest = poly_to_cut.points.front();
if (idx_polyline % 2 != 0) {
nearest = poly_to_cut.points.back();
}
//Bubble sort
for (size_t idx_sort = polylines_to_sort.size() - 1; idx_sort > 0; idx_sort--) {
for (size_t idx_bubble = 0; idx_bubble < idx_sort; idx_bubble++) {
if (polylines_to_sort[idx_bubble + 1].points.front().distance_to_square(nearest) < polylines_to_sort[idx_bubble].points.front().distance_to_square(nearest)) {
iter_swap(polylines_to_sort.begin() + idx_bubble, polylines_to_sort.begin() + idx_bubble + 1);
}
}
}
}
polylines_chained.insert(polylines_chained.end(), polylines_to_sort.begin(), polylines_to_sort.end());
}
size_t polylines_out_first_idx = polylines_out.size();
if (!polylines_chained.empty()) {
// connect lines
if (params.dont_connect) {
polylines_out.insert(polylines_out.end(), polylines_chained.begin(), polylines_chained.end());
} else {
this->connect_infill(polylines_chained, expolygon, polylines_out, params);
}
}
//remove too small bits (larger than longer);
for (size_t idx = polylines_out_first_idx; idx < polylines_out.size(); idx++) {
if (polylines_out[idx].length() < scale_(this->spacing * 3)) {
polylines_out.erase(polylines_out.begin() + idx);
idx--;
}
}
}
} // namespace Slic3r
<commit_msg>Allow gyroid pattern rotation over Z<commit_after>#include "../ClipperUtils.hpp"
#include "../PolylineCollection.hpp"
#include "../Surface.hpp"
#include <cmath>
#include <algorithm>
#include <iostream>
#include "FillGyroid.hpp"
namespace Slic3r {
static inline double f(double x, double z_sin, double z_cos, bool vertical, bool flip)
{
if (vertical) {
double phase_offset = (z_cos < 0 ? M_PI : 0) + M_PI;
double a = sin(x + phase_offset);
double b = - z_cos;
double res = z_sin * cos(x + phase_offset + (flip ? M_PI : 0.));
double r = sqrt(sqr(a) + sqr(b));
return asin(a/r) + asin(res/r) + M_PI;
}
else {
double phase_offset = z_sin < 0 ? M_PI : 0.;
double a = cos(x + phase_offset);
double b = - z_sin;
double res = z_cos * sin(x + phase_offset + (flip ? 0 : M_PI));
double r = sqrt(sqr(a) + sqr(b));
return (asin(a/r) + asin(res/r) + 0.5 * M_PI);
}
}
static inline Polyline make_wave(
const std::vector<Vec2d>& one_period, double width, double height, double offset, double scaleFactor,
double z_cos, double z_sin, bool vertical, bool flip)
{
std::vector<Vec2d> points = one_period;
double period = points.back()(0);
if (width != period) // do not extend if already truncated
{
points.reserve(one_period.size() * floor(width / period));
points.pop_back();
int n = points.size();
do {
points.emplace_back(Vec2d(points[points.size()-n](0) + period, points[points.size()-n](1)));
} while (points.back()(0) < width - EPSILON);
points.emplace_back(Vec2d(width, f(width, z_sin, z_cos, vertical, flip)));
}
// and construct the final polyline to return:
Polyline polyline;
polyline.points.reserve(points.size());
for (auto& point : points) {
point(1) += offset;
point(1) = clamp(0., height, double(point(1)));
if (vertical)
std::swap(point(0), point(1));
polyline.points.emplace_back((point * scaleFactor).cast<coord_t>());
}
return polyline;
}
static std::vector<Vec2d> make_one_period(double width, double scaleFactor, double z_cos, double z_sin, bool vertical, bool flip, double tolerance)
{
std::vector<Vec2d> points;
double dx = M_PI_2; // exact coordinates on main inflexion lobes
double limit = std::min(2*M_PI, width);
points.reserve(ceil(limit / tolerance / 3));
for (double x = 0.; x < limit - EPSILON; x += dx) {
points.emplace_back(Vec2d(x, f(x, z_sin, z_cos, vertical, flip)));
}
points.emplace_back(Vec2d(limit, f(limit, z_sin, z_cos, vertical, flip)));
// piecewise increase in resolution up to requested tolerance
for(;;)
{
size_t size = points.size();
for (unsigned int i = 1;i < size; ++i) {
auto& lp = points[i-1]; // left point
auto& rp = points[i]; // right point
double x = lp(0) + (rp(0) - lp(0)) / 2;
double y = f(x, z_sin, z_cos, vertical, flip);
Vec2d ip = {x, y};
if (std::abs(cross2(Vec2d(ip - lp), Vec2d(ip - rp))) > sqr(tolerance)) {
points.emplace_back(std::move(ip));
}
}
if (size == points.size())
break;
else
{
// insert new points in order
std::sort(points.begin(), points.end(),
[](const Vec2d &lhs, const Vec2d &rhs) { return lhs(0) < rhs(0); });
}
}
return points;
}
static Polylines make_gyroid_waves(double gridZ, double density_adjusted, double line_spacing, double width, double height)
{
const double scaleFactor = scale_(line_spacing) / density_adjusted;
// tolerance (in scaled units)
// TODO: should consider layer thickness
const double tolerance = line_spacing / 2 / unscale<double>(scaleFactor);
//scale factor for 5% : 8 712 388
// 1z = 10^-6 mm ?
const double z = gridZ / scaleFactor;
const double z_sin = sin(z);
const double z_cos = cos(z);
bool vertical = (std::abs(z_sin) <= std::abs(z_cos));
double lower_bound = 0.;
double upper_bound = height;
bool flip = true;
if (vertical) {
flip = false;
lower_bound = -M_PI;
upper_bound = width - M_PI_2;
std::swap(width,height);
}
std::vector<Vec2d> one_period_odd = make_one_period(width, scaleFactor, z_cos, z_sin, vertical, flip, tolerance); // creates one period of the waves, so it doesn't have to be recalculated all the time
flip = !flip; // even polylines are a bit shifted
std::vector<Vec2d> one_period_even = make_one_period(width, scaleFactor, z_cos, z_sin, vertical, flip, tolerance);
Polylines result;
for (double y0 = lower_bound; y0 < upper_bound + EPSILON; y0 += M_PI) {
// creates odd polylines
result.emplace_back(make_wave(one_period_odd, width, height, y0, scaleFactor, z_cos, z_sin, vertical, flip));
// creates even polylines
y0 += M_PI;
if (y0 < upper_bound + EPSILON) {
result.emplace_back(make_wave(one_period_even, width, height, y0, scaleFactor, z_cos, z_sin, vertical, flip));
}
}
return result;
}
void FillGyroid::_fill_surface_single(
const FillParams ¶ms,
unsigned int thickness_layers,
const std::pair<float, Point> &direction,
ExPolygon &expolygon,
Polylines &polylines_out)
{
expolygon.rotate(-this->angle);
BoundingBox bb = expolygon.contour.bounding_box();
// Density adjusted to have a good %of weight.
double density_adjusted = std::max(0., params.density * 2.44);
// Distance between the gyroid waves in scaled coordinates.
coord_t distance = coord_t(scale_(this->spacing) / density_adjusted);
// align bounding box to a multiple of our grid module
bb.merge(_align_to_grid(bb.min, Point(2*M_PI*distance, 2*M_PI*distance)));
// generate pattern
Polylines polylines_square = make_gyroid_waves(
scale_(this->z),
density_adjusted,
this->spacing,
ceil(bb.size()(0) / distance) + 1.,
ceil(bb.size()(1) / distance) + 1.);
// clip pattern to boundaries, keeping the polyline order & ordering the fragment to be able to join them easily
Polylines polylines_chained;
for (size_t idx_polyline = 0; idx_polyline < polylines_square.size(); ++idx_polyline) {
// shift the polyline to the grid origin
Polyline &poly_to_cut = polylines_square[idx_polyline];
poly_to_cut.translate(bb.min);
// intersect
Polylines polylines_to_sort = intersection_pl(Polylines() = { poly_to_cut }, (Polygons)expolygon);
for (Polyline &polyline : polylines_to_sort) {
//TODO: replace by closest_index_point()
if (idx_polyline % 2 == 0) {
if (poly_to_cut.points.front().distance_to_square(polyline.points.front()) > poly_to_cut.points.front().distance_to_square(polyline.points.back())) {
polyline.reverse();
}
} else {
if (poly_to_cut.points.back().distance_to_square(polyline.points.front()) > poly_to_cut.points.back().distance_to_square(polyline.points.back())) {
polyline.reverse();
}
}
}
if (polylines_to_sort.size() > 1) {
Point nearest = poly_to_cut.points.front();
if (idx_polyline % 2 != 0) {
nearest = poly_to_cut.points.back();
}
//Bubble sort
for (size_t idx_sort = polylines_to_sort.size() - 1; idx_sort > 0; idx_sort--) {
for (size_t idx_bubble = 0; idx_bubble < idx_sort; idx_bubble++) {
if (polylines_to_sort[idx_bubble + 1].points.front().distance_to_square(nearest) < polylines_to_sort[idx_bubble].points.front().distance_to_square(nearest)) {
iter_swap(polylines_to_sort.begin() + idx_bubble, polylines_to_sort.begin() + idx_bubble + 1);
}
}
}
}
polylines_chained.insert(polylines_chained.end(), polylines_to_sort.begin(), polylines_to_sort.end());
}
size_t polylines_out_first_idx = polylines_out.size();
if (!polylines_chained.empty()) {
// connect lines
if (params.dont_connect) {
polylines_out.insert(polylines_out.end(), polylines_chained.begin(), polylines_chained.end());
} else {
this->connect_infill(polylines_chained, expolygon, polylines_out, params);
}
}
//remove too small bits (larger than longer);
for (size_t idx = polylines_out_first_idx; idx < polylines_out.size(); idx++) {
if (polylines_out[idx].length() < scale_(this->spacing * 3)) {
polylines_out.erase(polylines_out.begin() + idx);
idx--;
}
}
// new paths must be rotated back
for (Polylines::iterator it = polylines_out.begin() + polylines_out_first_idx;
it != polylines_out.end(); ++it) {
it->rotate(this->angle);
}
}
} // namespace Slic3r
<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGuiOgreBaseApplication.cpp
created: 9/3/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
// this controls conditional compile of file for Apple
#include "CEGUISamplesConfig.h"
#ifdef CEGUI_SAMPLES_USE_OGRE
#include "CEGuiOgreBaseApplication.h"
#include "CEGuiSample.h"
#include <OgreKeyEvent.h>
CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() :
d_ogreRoot(0),
d_renderer(0),
d_initialised(false),
d_frameListener(0)
{
using namespace Ogre;
d_ogreRoot = new Root();
initialiseResources();
if (d_ogreRoot->showConfigDialog())
{
// initialise system according to user options.
d_window = d_ogreRoot->initialise(true);
// Create and initialise the camera
d_camera = d_ogreRoot->getSceneManagerIterator().getNext()->createCamera("PlayerCam");
d_camera->setPosition(Vector3(0,0,500));
d_camera->lookAt(Vector3(0,0,-300));
d_camera->setNearClipDistance(5);
// Create a viewport covering whole window
Viewport* vp = d_window->addViewport(d_camera);
vp->setBackgroundColour(ColourValue(0,0,0));
// Update the camera aspect ratio to that of the viewport
d_camera->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
// initialise resources
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// initialise GUI system
d_renderer = new CEGUI::OgreCEGUIRenderer(d_window);
new CEGUI::System(d_renderer);
// create frame listener
d_frameListener= new CEGuiDemoFrameListener(this, d_window, d_camera);
d_ogreRoot->addFrameListener(d_frameListener);
d_initialised = true;
}
else
{
// aborted. Clean up and set root to 0 so when app attempts to run it knows what happened here.
delete d_ogreRoot;
d_ogreRoot = 0;
}
}
CEGuiOgreBaseApplication::~CEGuiOgreBaseApplication()
{
delete d_frameListener;
delete CEGUI::System::getSingletonPtr();
delete d_renderer;
delete d_ogreRoot;
}
bool CEGuiOgreBaseApplication::execute(CEGuiSample* sampleApp)
{
// if initialisation failed or was cancelled by user, bail out now.
if (d_ogreRoot && d_initialised)
{
// perform sample initialisation
sampleApp->initialiseSample();
// start rendering via Ogre3D engine.
try
{
d_ogreRoot->startRendering();
}
catch(Ogre::Exception&)
{
return false;
}
catch(CEGUI::Exception&)
{
return false;
}
return true;
}
else
{
return false;
}
}
void CEGuiOgreBaseApplication::cleanup()
{
// nothing to do here.
}
void CEGuiOgreBaseApplication::initialiseResources(void)
{
using namespace Ogre;
ResourceGroupManager& rgm = ResourceGroupManager::getSingleton();
// add resource groups that we use
rgm.createResourceGroup("imagesets");
rgm.createResourceGroup("fonts");
rgm.createResourceGroup("layouts");
rgm.createResourceGroup("schemes");
rgm.createResourceGroup("looknfeels");
// add CEGUI sample framework datafile dirs as resource locations
ResourceGroupManager::getSingleton().addResourceLocation("./", "FileSystem");
#ifndef __APPLE__
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/fonts", "FileSystem", "fonts");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/imagesets", "FileSystem", "imagesets");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/layouts", "FileSystem", "layouts");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/looknfeel", "FileSystem", "looknfeels");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/schemes", "FileSystem", "schemes");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/configs", "FileSystem");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/lua_scripts", "FileSystem");
#else
// Because Ogre/Mac looks in the bundle's Resources folder by default...
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/fonts", "FileSystem", "fonts");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/imagesets", "FileSystem", "imagesets");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/layouts", "FileSystem", "layouts");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/looknfeel", "FileSystem", "looknfeels");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/schemes", "FileSystem", "schemes");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/configs", "FileSystem");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/lua_scripts", "FileSystem");
#endif
}
////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
Start of CEGuiDemoFrameListener mehods
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiBaseApplication* baseApp, Ogre::RenderWindow* window, Ogre::Camera* camera, bool useBufferedInputKeys, bool useBufferedInputMouse)
{
// create and initialise events processor
d_eventProcessor = new Ogre::EventProcessor();
d_eventProcessor->initialise(window);
d_eventProcessor->addKeyListener(this);
d_eventProcessor->addMouseMotionListener(this);
d_eventProcessor->addMouseListener(this);
d_eventProcessor->startProcessingEvents();
// store inputs we want to make use of
d_camera = camera;
d_window = window;
// we've not quit yet.
d_quit = false;
// setup base app ptr
d_baseApp = baseApp;
}
CEGuiDemoFrameListener::~CEGuiDemoFrameListener()
{
delete d_eventProcessor;
}
bool CEGuiDemoFrameListener::frameStarted(const Ogre::FrameEvent& evt)
{
if(d_window->isClosed() || d_quit || d_baseApp->isQuitting())
{
return false;
}
else
{
// always inject a time pulse to enable widget automation
CEGUI::System::getSingleton().injectTimePulse(static_cast<float>(evt.timeSinceLastFrame));
return true;
}
}
bool CEGuiDemoFrameListener::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
}
void CEGuiDemoFrameListener::mouseMoved(Ogre::MouseEvent *e)
{
CEGUI::Renderer* rend = CEGUI::System::getSingleton().getRenderer();
CEGUI::System::getSingleton().injectMouseMove(e->getRelX() * rend->getWidth(), e->getRelY() * rend->getHeight());
float wheel = e->getRelZ();
if (wheel != 0)
{
CEGUI::System::getSingleton().injectMouseWheelChange(wheel * 10);
}
e->consume();
}
void CEGuiDemoFrameListener::mouseDragged(Ogre::MouseEvent *e)
{
mouseMoved(e);
}
void CEGuiDemoFrameListener::keyPressed(Ogre::KeyEvent *e)
{
// give 'quitting' priority
if (e->getKey() == Ogre::KC_ESCAPE)
{
d_quit = true;
e->consume();
return;
}
// do event injection
CEGUI::System& cegui = CEGUI::System::getSingleton();
// key down
cegui.injectKeyDown(e->getKey());
// now character
cegui.injectChar(e->getKeyChar());
e->consume();
}
void CEGuiDemoFrameListener::keyReleased(Ogre::KeyEvent *e)
{
CEGUI::System::getSingleton().injectKeyUp(e->getKey());
}
void CEGuiDemoFrameListener::mousePressed(Ogre::MouseEvent *e)
{
CEGUI::System::getSingleton().injectMouseButtonDown(convertOgreButtonToCegui(e->getButtonID()));
e->consume();
}
void CEGuiDemoFrameListener::mouseReleased(Ogre::MouseEvent *e)
{
CEGUI::System::getSingleton().injectMouseButtonUp(convertOgreButtonToCegui(e->getButtonID()));
e->consume();
}
void CEGuiDemoFrameListener::keyClicked(Ogre::KeyEvent *e)
{}
void CEGuiDemoFrameListener::mouseClicked(Ogre::MouseEvent *e)
{}
void CEGuiDemoFrameListener::mouseEntered(Ogre::MouseEvent *e)
{}
void CEGuiDemoFrameListener::mouseExited(Ogre::MouseEvent *e)
{}
CEGUI::MouseButton CEGuiDemoFrameListener::convertOgreButtonToCegui(int ogre_button_id)
{
switch (ogre_button_id)
{
case Ogre::MouseEvent::BUTTON0_MASK:
return CEGUI::LeftButton;
break;
case Ogre::MouseEvent::BUTTON1_MASK:
return CEGUI::RightButton;
break;
case Ogre::MouseEvent::BUTTON2_MASK:
return CEGUI::MiddleButton;
break;
case Ogre::MouseEvent::BUTTON3_MASK:
return CEGUI::X1Button;
break;
default:
return CEGUI::LeftButton;
break;
}
}
#endif
<commit_msg>Bug Fix: Support was broken in the Samples framework for newer versions of Ogre.<commit_after>/***********************************************************************
filename: CEGuiOgreBaseApplication.cpp
created: 9/3/2004
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* 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 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.
***************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
// this controls conditional compile of file for Apple
#include "CEGUISamplesConfig.h"
#ifdef CEGUI_SAMPLES_USE_OGRE
#include "CEGuiOgreBaseApplication.h"
#include "CEGuiSample.h"
#include <OgreKeyEvent.h>
CEGuiOgreBaseApplication::CEGuiOgreBaseApplication() :
d_ogreRoot(0),
d_renderer(0),
d_initialised(false),
d_frameListener(0)
{
using namespace Ogre;
d_ogreRoot = new Root();
initialiseResources();
if (d_ogreRoot->showConfigDialog())
{
// initialise system according to user options.
d_window = d_ogreRoot->initialise(true);
// Create the scene manager
SceneManager* sm = d_ogreRoot->
createSceneManager(ST_GENERIC, "SampleSceneMgr");
// Create and initialise the camera
d_camera = sm->createCamera("SampleCam");
d_camera->setPosition(Vector3(0,0,500));
d_camera->lookAt(Vector3(0,0,-300));
d_camera->setNearClipDistance(5);
// Create a viewport covering whole window
Viewport* vp = d_window->addViewport(d_camera);
vp->setBackgroundColour(ColourValue(0,0,0));
// Update the camera aspect ratio to that of the viewport
d_camera->setAspectRatio(Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
// initialise resources
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
// initialise GUI system
d_renderer = new CEGUI::OgreCEGUIRenderer(d_window, RENDER_QUEUE_OVERLAY, false, 0, sm);
new CEGUI::System(d_renderer);
// create frame listener
d_frameListener= new CEGuiDemoFrameListener(this, d_window, d_camera);
d_ogreRoot->addFrameListener(d_frameListener);
d_initialised = true;
}
else
{
// aborted. Clean up and set root to 0 so when app attempts to run it knows what happened here.
delete d_ogreRoot;
d_ogreRoot = 0;
}
}
CEGuiOgreBaseApplication::~CEGuiOgreBaseApplication()
{
delete d_frameListener;
delete CEGUI::System::getSingletonPtr();
delete d_renderer;
delete d_ogreRoot;
}
bool CEGuiOgreBaseApplication::execute(CEGuiSample* sampleApp)
{
// if initialisation failed or was cancelled by user, bail out now.
if (d_ogreRoot && d_initialised)
{
// perform sample initialisation
sampleApp->initialiseSample();
// start rendering via Ogre3D engine.
try
{
d_ogreRoot->startRendering();
}
catch(Ogre::Exception&)
{
return false;
}
catch(CEGUI::Exception&)
{
return false;
}
return true;
}
else
{
return false;
}
}
void CEGuiOgreBaseApplication::cleanup()
{
// nothing to do here.
}
void CEGuiOgreBaseApplication::initialiseResources(void)
{
using namespace Ogre;
ResourceGroupManager& rgm = ResourceGroupManager::getSingleton();
// add resource groups that we use
rgm.createResourceGroup("imagesets");
rgm.createResourceGroup("fonts");
rgm.createResourceGroup("layouts");
rgm.createResourceGroup("schemes");
rgm.createResourceGroup("looknfeels");
// add CEGUI sample framework datafile dirs as resource locations
ResourceGroupManager::getSingleton().addResourceLocation("./", "FileSystem");
#ifndef __APPLE__
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/fonts", "FileSystem", "fonts");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/imagesets", "FileSystem", "imagesets");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/layouts", "FileSystem", "layouts");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/looknfeel", "FileSystem", "looknfeels");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/schemes", "FileSystem", "schemes");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/configs", "FileSystem");
ResourceGroupManager::getSingleton().addResourceLocation("../datafiles/lua_scripts", "FileSystem");
#else
// Because Ogre/Mac looks in the bundle's Resources folder by default...
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/fonts", "FileSystem", "fonts");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/imagesets", "FileSystem", "imagesets");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/layouts", "FileSystem", "layouts");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/looknfeel", "FileSystem", "looknfeels");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/schemes", "FileSystem", "schemes");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/configs", "FileSystem");
ResourceGroupManager::getSingleton().addResourceLocation("datafiles/lua_scripts", "FileSystem");
#endif
}
////////////////////////////////////////////////////////////////////////////////
/*******************************************************************************
Start of CEGuiDemoFrameListener mehods
*******************************************************************************/
////////////////////////////////////////////////////////////////////////////////
CEGuiDemoFrameListener::CEGuiDemoFrameListener(CEGuiBaseApplication* baseApp, Ogre::RenderWindow* window, Ogre::Camera* camera, bool useBufferedInputKeys, bool useBufferedInputMouse)
{
// create and initialise events processor
d_eventProcessor = new Ogre::EventProcessor();
d_eventProcessor->initialise(window);
d_eventProcessor->addKeyListener(this);
d_eventProcessor->addMouseMotionListener(this);
d_eventProcessor->addMouseListener(this);
d_eventProcessor->startProcessingEvents();
// store inputs we want to make use of
d_camera = camera;
d_window = window;
// we've not quit yet.
d_quit = false;
// setup base app ptr
d_baseApp = baseApp;
}
CEGuiDemoFrameListener::~CEGuiDemoFrameListener()
{
delete d_eventProcessor;
}
bool CEGuiDemoFrameListener::frameStarted(const Ogre::FrameEvent& evt)
{
if(d_window->isClosed() || d_quit || d_baseApp->isQuitting())
{
return false;
}
else
{
// always inject a time pulse to enable widget automation
CEGUI::System::getSingleton().injectTimePulse(static_cast<float>(evt.timeSinceLastFrame));
return true;
}
}
bool CEGuiDemoFrameListener::frameEnded(const Ogre::FrameEvent& evt)
{
return true;
}
void CEGuiDemoFrameListener::mouseMoved(Ogre::MouseEvent *e)
{
CEGUI::Renderer* rend = CEGUI::System::getSingleton().getRenderer();
CEGUI::System::getSingleton().injectMouseMove(e->getRelX() * rend->getWidth(), e->getRelY() * rend->getHeight());
float wheel = e->getRelZ();
if (wheel != 0)
{
CEGUI::System::getSingleton().injectMouseWheelChange(wheel * 10);
}
e->consume();
}
void CEGuiDemoFrameListener::mouseDragged(Ogre::MouseEvent *e)
{
mouseMoved(e);
}
void CEGuiDemoFrameListener::keyPressed(Ogre::KeyEvent *e)
{
// give 'quitting' priority
if (e->getKey() == Ogre::KC_ESCAPE)
{
d_quit = true;
e->consume();
return;
}
// do event injection
CEGUI::System& cegui = CEGUI::System::getSingleton();
// key down
cegui.injectKeyDown(e->getKey());
// now character
cegui.injectChar(e->getKeyChar());
e->consume();
}
void CEGuiDemoFrameListener::keyReleased(Ogre::KeyEvent *e)
{
CEGUI::System::getSingleton().injectKeyUp(e->getKey());
}
void CEGuiDemoFrameListener::mousePressed(Ogre::MouseEvent *e)
{
CEGUI::System::getSingleton().injectMouseButtonDown(convertOgreButtonToCegui(e->getButtonID()));
e->consume();
}
void CEGuiDemoFrameListener::mouseReleased(Ogre::MouseEvent *e)
{
CEGUI::System::getSingleton().injectMouseButtonUp(convertOgreButtonToCegui(e->getButtonID()));
e->consume();
}
void CEGuiDemoFrameListener::keyClicked(Ogre::KeyEvent *e)
{}
void CEGuiDemoFrameListener::mouseClicked(Ogre::MouseEvent *e)
{}
void CEGuiDemoFrameListener::mouseEntered(Ogre::MouseEvent *e)
{}
void CEGuiDemoFrameListener::mouseExited(Ogre::MouseEvent *e)
{}
CEGUI::MouseButton CEGuiDemoFrameListener::convertOgreButtonToCegui(int ogre_button_id)
{
switch (ogre_button_id)
{
case Ogre::MouseEvent::BUTTON0_MASK:
return CEGUI::LeftButton;
break;
case Ogre::MouseEvent::BUTTON1_MASK:
return CEGUI::RightButton;
break;
case Ogre::MouseEvent::BUTTON2_MASK:
return CEGUI::MiddleButton;
break;
case Ogre::MouseEvent::BUTTON3_MASK:
return CEGUI::X1Button;
break;
default:
return CEGUI::LeftButton;
break;
}
}
#endif
<|endoftext|> |
<commit_before>//-----------------------------------------------
//
// This file is part of the HamFramework for Siv3D.
//
// Copyright (C) 2014-2016 Hamukun
// Copyright (C) 2014-2016 Ryo Suzuki
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
//# include "../Siv3D.hpp"
# include <Siv3D.hpp>
namespace ham
{
enum class TransitionState
{
None,
FadeIn,
Active,
FadeOut,
FadeInOut,
};
template<class State, class Data> class LayerManager;
template<class State, class Data>
class LayerBase : public std::enable_shared_from_this<LayerBase<State, Data>>, s3d::Uncopyable
{
public:
using Manager_t = LayerManager<State, Data>;
using State_t = State;
using Data_t = Data;
virtual ~LayerBase() = default;
void setData(Manager_t* pManager, const std::shared_ptr<Data>& data)
{
m_manager = pManager;
m_data = data;
}
void setTransitionValue(int transitionTimeMillisec)
{
m_transitionTimeMillisec = transitionTimeMillisec;
m_transitionState = TransitionState::FadeIn;
m_stopwatch.restart();
}
s3d::Stopwatch& getStopwatch()
{
return m_stopwatch;
}
int32 getTransitionTimeMillisec() const
{
return m_transitionTimeMillisec;
}
void setTransitionState(const TransitionState& transitionState)
{
m_transitionState = transitionState;
}
const TransitionState& getTransitionState() const
{
return m_transitionState;
}
bool isDestroyed() const
{
return m_isDestroyed;
}
void setDestroyed(bool isDestroyed)
{
m_isDestroyed = isDestroyed;
}
virtual void init() {}
virtual bool input() { return false; }
virtual bool inputFadeIn(double) { return false; }
virtual bool inputFadeOut(double) { return false; }
virtual void updateFadeIn(double) {}
virtual void update() = 0;
virtual void updateFadeOut(double) {}
virtual void draw() const = 0;
virtual void drawFadeIn(double) const
{
draw();
}
virtual void drawFadeOut(double) const
{
draw();
}
protected:
std::shared_ptr<Data> m_data;
bool pushLayer(const State& state, int transitionTimeMillisec = 200)
{
return m_manager->pushLayer(state, transitionTimeMillisec);
}
bool popThisLayer()
{
return m_manager->popLayer(shared_from_this());
}
private:
Manager_t* m_manager = nullptr;
s3d::Stopwatch m_stopwatch;
int32 m_transitionTimeMillisec = 0;
TransitionState m_transitionState = TransitionState::None;
bool m_isDestroyed = false;
};
template<class State, class Data> class LayerManager
{
private:
using Layer_t = std::shared_ptr<LayerBase<State, Data>>;
using FactoryFunction_t = std::function<Layer_t()>;
std::unordered_map<State, FactoryFunction_t> m_factories;
std::shared_ptr<Data> m_data;
Array<Layer_t> m_layers;
Array<Layer_t> m_tLayers;
s3d::Optional<State> m_first;
bool m_error = false;
template<class Type>
std::shared_ptr<Type> MakeShared() const
{
return std::make_shared<Data>();
}
template<>
std::shared_ptr<void> MakeShared() const
{
return std::shared_ptr<void>(nullptr);
}
public:
using Layer = LayerBase<State, Data>;
LayerManager()
: m_data(MakeShared<Data>())
{
}
LayerManager(const std::shared_ptr<Data>& data)
: m_data(data)
{
}
template<class Layer> bool add(const State& state)
{
if (m_factories.find(state) != m_factories.end())
{
return false;
}
m_factories.emplace(state, [&]()
{
auto m = std::make_shared<Layer>();
m->setData(this, m_data);
return m;
});
if (!m_first)
{
m_first = state;
}
return true;
}
bool init(const State& state)
{
if (m_layers.size() != 0)
{
m_layers.clear();
}
auto it = m_factories.find(state);
if (it == m_factories.end())
{
return false;
}
auto newLayer = it->second();
newLayer->init();
m_layers.push_back(newLayer);
return true;
}
bool input()
{
for (auto i = m_layers.rbegin(); i != m_layers.rend(); ++i)
{
auto& layer = *i;
const auto state = layer->getTransitionState();
if (state == TransitionState::FadeIn || state == TransitionState::Active)
{
if (layer->input())
{
break;
}
}
}
if (m_tLayers.size() > 0)
{
m_layers.insert(m_layers.end(), m_tLayers.begin(), m_tLayers.end());
m_tLayers.clear();
}
return true;
}
bool update()
{
if (m_layers.size() == 0 && !init(m_first.value()))
{
return false;
}
for (auto& layer : m_layers)
{
const int32 elapsed = layer->getStopwatch().ms();
switch (layer->getTransitionState())
{
case TransitionState::FadeIn:
layer->updateFadeIn(static_cast<double>(elapsed) / layer->getTransitionTimeMillisec());
if (elapsed > layer->getTransitionTimeMillisec())
{
layer->getStopwatch().reset();
layer->setTransitionState(TransitionState::Active);
}
break;
case TransitionState::Active:
layer->update();
break;
case TransitionState::FadeOut:
layer->updateFadeOut(static_cast<double>(elapsed) / layer->getTransitionTimeMillisec());
if (elapsed > layer->getTransitionTimeMillisec())
{
layer->setDestroyed(true);
}
break;
default:
break;
}
}
Erase_if(m_layers, [&](const Layer_t& layer)
{
return layer->isDestroyed();
});
if (m_tLayers.size() > 0)
{
m_layers.insert(m_layers.end(), m_tLayers.begin(), m_tLayers.end());
m_tLayers.clear();
}
return true;
}
void draw() const
{
for (const auto& layer : m_layers)
{
const int32 elapsed = layer->getStopwatch().ms();
switch (layer->getTransitionState())
{
case TransitionState::FadeIn:
layer->drawFadeIn(static_cast<double>(elapsed) / layer->getTransitionTimeMillisec());
break;
case TransitionState::Active:
layer->draw();
break;
case TransitionState::FadeOut:
layer->drawFadeOut(static_cast<double>(elapsed) / layer->getTransitionTimeMillisec());
break;
default:
break;
}
}
}
bool inputAndUpdateAndDraw()
{
if (!input())
{
return false;
}
if (!update())
{
return false;
}
draw();
return true;
}
std::shared_ptr<Data> get()
{
return m_data;
}
bool pushLayer(const State& state, int transitionTimeMillisec = 200)
{
if (m_factories.find(state) == m_factories.end())
{
return false;
}
auto newLayer = m_factories[state]();
newLayer->setTransitionValue(transitionTimeMillisec);
newLayer->init();
m_tLayers.push_back(newLayer);
return true;
}
bool popLayer(const std::shared_ptr<Layer>& layer)
{
auto it = std::find(m_layers.begin(), m_layers.end(), layer);
if (it == m_layers.end())
{
return false;
}
(*it)->setTransitionState(TransitionState::FadeOut);
(*it)->getStopwatch().restart();
return true;
}
};
}
<commit_msg>fix init<commit_after>//-----------------------------------------------
//
// This file is part of the HamFramework for Siv3D.
//
// Copyright (C) 2014-2016 Hamukun
// Copyright (C) 2014-2016 Ryo Suzuki
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
//# include "../Siv3D.hpp"
# include <Siv3D.hpp>
namespace ham
{
enum class TransitionState
{
None,
FadeIn,
Active,
FadeOut,
FadeInOut,
};
template<class State, class Data> class LayerManager;
template<class State, class Data>
class LayerBase : public std::enable_shared_from_this<LayerBase<State, Data>>, s3d::Uncopyable
{
public:
using Manager_t = LayerManager<State, Data>;
using State_t = State;
using Data_t = Data;
virtual ~LayerBase() = default;
void setData(Manager_t* pManager, const std::shared_ptr<Data>& data)
{
m_manager = pManager;
m_data = data;
}
void setTransitionValue(int transitionTimeMillisec)
{
m_transitionTimeMillisec = transitionTimeMillisec;
m_transitionState = TransitionState::FadeIn;
m_stopwatch.restart();
}
s3d::Stopwatch& getStopwatch()
{
return m_stopwatch;
}
int32 getTransitionTimeMillisec() const
{
return m_transitionTimeMillisec;
}
void setTransitionState(const TransitionState& transitionState)
{
m_transitionState = transitionState;
}
const TransitionState& getTransitionState() const
{
return m_transitionState;
}
bool isDestroyed() const
{
return m_isDestroyed;
}
void setDestroyed(bool isDestroyed)
{
m_isDestroyed = isDestroyed;
}
virtual void init() {}
virtual bool input() { return false; }
virtual bool inputFadeIn(double) { return false; }
virtual bool inputFadeOut(double) { return false; }
virtual void updateFadeIn(double) {}
virtual void update() = 0;
virtual void updateFadeOut(double) {}
virtual void draw() const = 0;
virtual void drawFadeIn(double) const
{
draw();
}
virtual void drawFadeOut(double) const
{
draw();
}
protected:
std::shared_ptr<Data> m_data;
bool pushLayer(const State& state, int transitionTimeMillisec = 200)
{
return m_manager->pushLayer(state, transitionTimeMillisec);
}
bool popThisLayer()
{
return m_manager->popLayer(shared_from_this());
}
private:
Manager_t* m_manager = nullptr;
s3d::Stopwatch m_stopwatch;
int32 m_transitionTimeMillisec = 0;
TransitionState m_transitionState = TransitionState::None;
bool m_isDestroyed = false;
};
template<class State, class Data> class LayerManager
{
private:
using Layer_t = std::shared_ptr<LayerBase<State, Data>>;
using FactoryFunction_t = std::function<Layer_t()>;
std::unordered_map<State, FactoryFunction_t> m_factories;
std::shared_ptr<Data> m_data;
Array<Layer_t> m_layers;
Array<Layer_t> m_tLayers;
s3d::Optional<State> m_first;
bool m_error = false;
template<class Type>
std::shared_ptr<Type> MakeShared() const
{
return std::make_shared<Data>();
}
template<>
std::shared_ptr<void> MakeShared() const
{
return std::shared_ptr<void>(nullptr);
}
public:
using Layer = LayerBase<State, Data>;
LayerManager()
: m_data(MakeShared<Data>())
{
}
LayerManager(const std::shared_ptr<Data>& data)
: m_data(data)
{
}
template<class Layer> bool add(const State& state)
{
if (m_factories.find(state) != m_factories.end())
{
return false;
}
m_factories.emplace(state, [&]()
{
auto m = std::make_shared<Layer>();
m->setData(this, m_data);
return m;
});
if (!m_first)
{
m_first = state;
}
return true;
}
bool init(const State& state)
{
if (m_layers.size() != 0)
{
m_layers.clear();
}
auto it = m_factories.find(state);
if (it == m_factories.end())
{
return false;
}
auto newLayer = it->second();
newLayer->init();
m_layers.push_back(newLayer);
return true;
}
bool input()
{
for (auto i = m_layers.rbegin(); i != m_layers.rend(); ++i)
{
auto& layer = *i;
const auto state = layer->getTransitionState();
if (state == TransitionState::FadeIn || state == TransitionState::Active)
{
if (layer->input())
{
break;
}
}
}
if (m_tLayers.size() > 0)
{
m_layers.insert(m_layers.end(), m_tLayers.begin(), m_tLayers.end());
m_tLayers.clear();
}
return true;
}
bool update()
{
if (m_layers.size() == 0 && !init(m_first.value()))
{
return false;
}
for (auto& layer : m_layers)
{
const int32 elapsed = layer->getStopwatch().ms();
switch (layer->getTransitionState())
{
case TransitionState::FadeIn:
layer->updateFadeIn(static_cast<double>(elapsed) / layer->getTransitionTimeMillisec());
if (elapsed > layer->getTransitionTimeMillisec())
{
layer->getStopwatch().reset();
layer->setTransitionState(TransitionState::Active);
}
break;
case TransitionState::Active:
layer->update();
break;
case TransitionState::FadeOut:
layer->updateFadeOut(static_cast<double>(elapsed) / layer->getTransitionTimeMillisec());
if (elapsed > layer->getTransitionTimeMillisec())
{
layer->setDestroyed(true);
}
break;
default:
break;
}
}
Erase_if(m_layers, [&](const Layer_t& layer)
{
return layer->isDestroyed();
});
if (m_tLayers.size() > 0)
{
m_layers.insert(m_layers.end(), m_tLayers.begin(), m_tLayers.end());
m_tLayers.clear();
}
return true;
}
void draw() const
{
for (const auto& layer : m_layers)
{
const int32 elapsed = layer->getStopwatch().ms();
switch (layer->getTransitionState())
{
case TransitionState::FadeIn:
layer->drawFadeIn(static_cast<double>(elapsed) / layer->getTransitionTimeMillisec());
break;
case TransitionState::Active:
layer->draw();
break;
case TransitionState::FadeOut:
layer->drawFadeOut(static_cast<double>(elapsed) / layer->getTransitionTimeMillisec());
break;
default:
break;
}
}
}
bool inputAndUpdateAndDraw()
{
if (!input())
{
return false;
}
if (!update())
{
return false;
}
draw();
return true;
}
std::shared_ptr<Data> get()
{
return m_data;
}
bool pushLayer(const State& state, int transitionTimeMillisec = 200)
{
if (m_factories.find(state) == m_factories.end())
{
return false;
}
auto newLayer = m_factories[state]();
newLayer->setTransitionValue(transitionTimeMillisec);
m_tLayers.push_back(newLayer);
newLayer->init();
return true;
}
bool popLayer(const std::shared_ptr<Layer>& layer)
{
auto it = std::find(m_layers.begin(), m_layers.end(), layer);
if (it == m_layers.end())
{
return false;
}
(*it)->setTransitionState(TransitionState::FadeOut);
(*it)->getStopwatch().restart();
return true;
}
};
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "CodeComposite.h"
#include "Export/src/tree/CompositeFragment.h"
#include "OOModel/src/declarations/Class.h"
namespace CppExport {
CodeComposite::CodeComposite(const QString& name) : name_{name} {}
void CodeComposite::addUnit(CodeUnit* unit)
{
units_.append(unit);
// assert every unit belongs to only one composite
Q_ASSERT(!unit->composite());
unit->setComposite(this);
}
QString CodeComposite::relativePath(CodeComposite* other)
{
QStringList otherName = other->name().split("/");
if (name() == other->name()) return otherName.last();
QStringList thisName = name().split("/");
while (thisName.first() == otherName.first())
{
thisName.takeFirst();
otherName.takeFirst();
}
int backSteps = thisName.size() - otherName.size();
for (auto i = 0; i < backSteps; i++) otherName.prepend("..");
return otherName.join("/");
}
QSet<Model::Node*> CodeComposite::reduceSoftDependencies(QSet<CodeComposite*> hardDependencies,
QSet<Model::Node*> softDependencies)
{
auto result = softDependencies;
auto workList = QList<CodeComposite*>::fromSet(hardDependencies);
QSet<CodeComposite*> processed;
while (!workList.empty())
{
auto hardDependency = workList.takeFirst();
if (!processed.contains(hardDependency))
{
for (auto unit : hardDependency->units())
{
for (auto transitiveDependencyHeaderPart : unit->headerPart()->dependencies())
workList.append(transitiveDependencyHeaderPart->parent()->composite());
for (auto softDependency : softDependencies)
if (result.contains(softDependency))
if (unit->node() == softDependency || unit->node()->isAncestorOf(softDependency))
result.remove(softDependency);
}
processed.insert(hardDependency);
}
}
return result;
}
Export::SourceFragment* CodeComposite::partFragment(CodeUnitPart* (CodeUnit::*part) ())
{
Q_ASSERT(!units().empty());
QSet<Model::Node*> softDependencies;
QSet<CodeComposite*> compositeDependencies;
for (auto unit : units())
for (CodeUnitPart* dependency : (unit->*part)()->dependencies())
{
softDependencies.unite(dependency->softDependencies());
compositeDependencies.insert(dependency->parent()->composite());
}
auto composite = new Export::CompositeFragment(units().first()->node());
if (!compositeDependencies.empty())
{
for (auto compositeDependency : compositeDependencies)
*composite << "#include \"" + relativePath(compositeDependency) + ".h\"\n";
*composite << "\n";
}
auto softDependenciesReduced = reduceSoftDependencies(compositeDependencies, softDependencies);
if (!softDependenciesReduced.empty())
{
for (auto softDependency : softDependenciesReduced)
{
if (auto classs = DCast<OOModel::Class>(softDependency))
{
if (OOModel::Class::ConstructKind::Class == classs->constructKind()) *composite << "class ";
else if (OOModel::Class::ConstructKind::Struct == classs->constructKind()) *composite << "struct ";
else if (OOModel::Class::ConstructKind::Enum == classs->constructKind()) *composite << "enum ";
else Q_ASSERT(false);
}
else
Q_ASSERT(false);
*composite << softDependency->symbolName() + ";\n";
}
*composite << "\n";
}
if (!units().isEmpty())
{
OOModel::Module* currentNamespace{};
for (auto unit : units())
{
auto neededNamespace = unit->node()->firstAncestorOfType<OOModel::Module>();
if (neededNamespace != currentNamespace)
{
if (currentNamespace) *composite << "\n}\n\n";
if (neededNamespace) *composite << "namespace " << neededNamespace->symbolName() << " {\n\n";
currentNamespace = neededNamespace;
}
composite->append((unit->*part)()->sourceFragment());
}
if (currentNamespace) *composite << "\n}";
}
return composite;
}
Export::SourceFragment* CodeComposite::addPragmaOnce(Export::SourceFragment* fragment)
{
auto compositeFragment = new Export::CompositeFragment(fragment->node());
*compositeFragment << "#pragma once\n\n" << fragment;
return compositeFragment;
}
void CodeComposite::sortUnits()
{
if (units().size() <= 1) return;
QHash<CodeUnitPart*, QSet<CodeUnitPart*>> headerPartDependencies;
for (auto unit : units()) headerPartDependencies.insert(unit->headerPart(), unit->headerPart()->dependencies());
units_.clear();
for (auto headerPart : topologicalSort(headerPartDependencies)) units_.append(headerPart->parent());
}
void CodeComposite::fragments(Export::SourceFragment*& header, Export::SourceFragment*& source)
{
sortUnits();
header = headerFragment();
source = sourceFragment();
}
template <typename T>
QList<T*> CodeComposite::topologicalSort(QHash<T*, QSet<T*>> dependsOn)
{
// calculate a list of elements with no dependencies.
// calculate a map that maps from an element to all elements that depend on it.
QList<T*> noPendingDependencies;
QHash<T*, QSet<T*>> neededFor;
for (auto it = dependsOn.begin(); it != dependsOn.end(); it++)
if (it.value().empty())
// this element depends on no other elements
noPendingDependencies.append(it.key());
else
// for every other element this element depends on add it to the neededFor map for said other element
for (auto dependency : it.value())
neededFor[dependency].insert(it.key());
QList<T*> result;
while (!noPendingDependencies.empty())
{
// take any item form the list of item with no more dependencies and add it to the result
auto n = noPendingDependencies.takeFirst();
result.append(n);
// check if we are neededFor another node
auto it = neededFor.find(n);
if (it == neededFor.end()) continue;
// for every node we are neededFor
for (auto m : *it)
{
// find the nodes the node we are needed for dependsOn
auto dIt = dependsOn.find(m);
Q_ASSERT(dIt != dependsOn.end());
// remove us from its dependencies
dIt->remove(n);
// if this node has no more dependencies add it to the list of items with no more dependencies
if (dIt->size() == 0)
noPendingDependencies.append(m);
}
}
// test graph for cycles
for (auto dependencies : dependsOn.values())
Q_ASSERT(dependencies.empty());
return result;
}
}
<commit_msg>prevent file creation for empty files<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "CodeComposite.h"
#include "Export/src/tree/CompositeFragment.h"
#include "OOModel/src/declarations/Class.h"
namespace CppExport {
CodeComposite::CodeComposite(const QString& name) : name_{name} {}
void CodeComposite::addUnit(CodeUnit* unit)
{
units_.append(unit);
// assert every unit belongs to only one composite
Q_ASSERT(!unit->composite());
unit->setComposite(this);
}
QString CodeComposite::relativePath(CodeComposite* other)
{
QStringList otherName = other->name().split("/");
if (name() == other->name()) return otherName.last();
QStringList thisName = name().split("/");
while (thisName.first() == otherName.first())
{
thisName.takeFirst();
otherName.takeFirst();
}
int backSteps = thisName.size() - otherName.size();
for (auto i = 0; i < backSteps; i++) otherName.prepend("..");
return otherName.join("/");
}
QSet<Model::Node*> CodeComposite::reduceSoftDependencies(QSet<CodeComposite*> hardDependencies,
QSet<Model::Node*> softDependencies)
{
auto result = softDependencies;
auto workList = QList<CodeComposite*>::fromSet(hardDependencies);
QSet<CodeComposite*> processed;
while (!workList.empty())
{
auto hardDependency = workList.takeFirst();
if (!processed.contains(hardDependency))
{
for (auto unit : hardDependency->units())
{
for (auto transitiveDependencyHeaderPart : unit->headerPart()->dependencies())
workList.append(transitiveDependencyHeaderPart->parent()->composite());
for (auto softDependency : softDependencies)
if (result.contains(softDependency))
if (unit->node() == softDependency || unit->node()->isAncestorOf(softDependency))
result.remove(softDependency);
}
processed.insert(hardDependency);
}
}
return result;
}
Export::SourceFragment* CodeComposite::partFragment(CodeUnitPart* (CodeUnit::*part) ())
{
Q_ASSERT(!units().empty());
QSet<Model::Node*> softDependencies;
QSet<CodeComposite*> compositeDependencies;
for (auto unit : units())
for (CodeUnitPart* dependency : (unit->*part)()->dependencies())
{
softDependencies.unite(dependency->softDependencies());
compositeDependencies.insert(dependency->parent()->composite());
}
auto composite = new Export::CompositeFragment(units().first()->node());
if (!compositeDependencies.empty())
{
for (auto compositeDependency : compositeDependencies)
*composite << "#include \"" + relativePath(compositeDependency) + ".h\"\n";
*composite << "\n";
}
auto softDependenciesReduced = reduceSoftDependencies(compositeDependencies, softDependencies);
if (!softDependenciesReduced.empty())
{
for (auto softDependency : softDependenciesReduced)
{
if (auto classs = DCast<OOModel::Class>(softDependency))
{
if (OOModel::Class::ConstructKind::Class == classs->constructKind()) *composite << "class ";
else if (OOModel::Class::ConstructKind::Struct == classs->constructKind()) *composite << "struct ";
else if (OOModel::Class::ConstructKind::Enum == classs->constructKind()) *composite << "enum ";
else Q_ASSERT(false);
}
else
Q_ASSERT(false);
*composite << softDependency->symbolName() + ";\n";
}
*composite << "\n";
}
bool hasMeaningfulContent = false;
if (!units().isEmpty())
{
OOModel::Module* currentNamespace{};
for (auto unit : units())
{
auto codeUnitPart = (unit->*part)();
if (codeUnitPart->isSourceFragmentEmpty()) continue;
auto neededNamespace = unit->node()->firstAncestorOfType<OOModel::Module>();
if (neededNamespace != currentNamespace)
{
if (currentNamespace) *composite << "\n}\n\n";
if (neededNamespace) *composite << "namespace " << neededNamespace->symbolName() << " {\n\n";
currentNamespace = neededNamespace;
}
composite->append(codeUnitPart->sourceFragment());
hasMeaningfulContent = true;
}
if (currentNamespace) *composite << "\n}";
}
if (!hasMeaningfulContent)
{
SAFE_DELETE(composite);
return nullptr;
}
return composite;
}
Export::SourceFragment* CodeComposite::addPragmaOnce(Export::SourceFragment* fragment)
{
auto compositeFragment = new Export::CompositeFragment(fragment->node());
*compositeFragment << "#pragma once\n\n" << fragment;
return compositeFragment;
}
void CodeComposite::sortUnits()
{
if (units().size() <= 1) return;
QHash<CodeUnitPart*, QSet<CodeUnitPart*>> headerPartDependencies;
for (auto unit : units()) headerPartDependencies.insert(unit->headerPart(), unit->headerPart()->dependencies());
units_.clear();
for (auto headerPart : topologicalSort(headerPartDependencies)) units_.append(headerPart->parent());
}
void CodeComposite::fragments(Export::SourceFragment*& header, Export::SourceFragment*& source)
{
sortUnits();
header = headerFragment();
source = sourceFragment();
}
template <typename T>
QList<T*> CodeComposite::topologicalSort(QHash<T*, QSet<T*>> dependsOn)
{
// calculate a list of elements with no dependencies.
// calculate a map that maps from an element to all elements that depend on it.
QList<T*> noPendingDependencies;
QHash<T*, QSet<T*>> neededFor;
for (auto it = dependsOn.begin(); it != dependsOn.end(); it++)
if (it.value().empty())
// this element depends on no other elements
noPendingDependencies.append(it.key());
else
// for every other element this element depends on add it to the neededFor map for said other element
for (auto dependency : it.value())
neededFor[dependency].insert(it.key());
QList<T*> result;
while (!noPendingDependencies.empty())
{
// take any item form the list of item with no more dependencies and add it to the result
auto n = noPendingDependencies.takeFirst();
result.append(n);
// check if we are neededFor another node
auto it = neededFor.find(n);
if (it == neededFor.end()) continue;
// for every node we are neededFor
for (auto m : *it)
{
// find the nodes the node we are needed for dependsOn
auto dIt = dependsOn.find(m);
Q_ASSERT(dIt != dependsOn.end());
// remove us from its dependencies
dIt->remove(n);
// if this node has no more dependencies add it to the list of items with no more dependencies
if (dIt->size() == 0)
noPendingDependencies.append(m);
}
}
// test graph for cycles
for (auto dependencies : dependsOn.values())
Q_ASSERT(dependencies.empty());
return result;
}
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <algorithm>
#include <fstream>
#include <iostream>
#include "paddle/fluid/inference/tests/api/tester_helper.h"
namespace paddle {
namespace inference {
namespace analysis {
struct OneSlotInBatch {
std::string name;
std::vector<std::vector<float>> data;
std::vector<int> shape;
std::vector<size_t> lod;
};
struct DataRecord {
std::vector<std::vector<OneSlotInBatch>> batched_data;
std::map<std::string, std::vector<std::vector<float>>> datasets;
size_t batch_iter{0}, num_samples; // total number of samples
DataRecord() = default;
explicit DataRecord(const std::string &path, int batch_size = 1) {
Load(path);
Prepare(batch_size);
}
void Load(const std::string &path) {
std::ifstream file(path);
constexpr int num_slots = 154;
std::string line;
int num_lines = 0;
while (std::getline(file, line)) {
num_lines++;
std::vector<std::string> data;
split(line, '\t', &data);
std::vector<float> slot_data;
split_to_float(data[1], ' ', &slot_data);
std::string name = data[0];
PADDLE_ENFORCE_EQ(slot_data.size() % 11, 0,
"line %d, %s should be divisible", num_lines, name);
datasets[name].emplace_back(std::move(slot_data));
}
num_samples = num_lines / num_slots;
PADDLE_ENFORCE_EQ(num_samples * num_slots, static_cast<size_t>(num_lines),
"num samples should be divisible");
PADDLE_ENFORCE_GT(num_samples, 0);
}
void Prepare(int bs) {
for (auto it = datasets.begin(); it != datasets.end(); ++it) {
PADDLE_ENFORCE_EQ(it->second.size(), num_samples,
"size of each slot should be equal");
}
size_t num_batches = num_samples / bs;
EXPECT_GT(num_batches, 0);
batched_data.resize(num_batches);
for (auto &one_batch : batched_data) {
one_batch.resize(datasets.size());
size_t i = 0;
for (auto it = datasets.begin(); it != datasets.end(); ++it) {
auto &slot = one_batch[i];
slot.name = it->first;
slot.data.resize(bs);
slot.lod.resize(bs + 1);
slot.lod[0] = 0;
auto &lod = slot.lod;
auto &datas = it->second;
for (int k = 0; k < bs; ++k) {
size_t id = k + batch_iter * bs;
std::copy(datas[id].begin(), datas[id].end(),
std::back_inserter(slot.data[k]));
size_t len = datas[id].size() / 11;
PADDLE_ENFORCE_EQ(len * 11, datas[id].size(),
"%s %d size should be divisible", slot.name, id);
lod[k + 1] = lod[k] + len;
}
slot.shape.assign({static_cast<int>(lod[bs]), 11});
i++;
}
}
}
const std::vector<OneSlotInBatch> &NextBatch() {
if (batch_iter >= batched_data.size() - 1) {
batch_iter = -1;
}
return batched_data[++batch_iter];
}
};
static void TensorAssignSlot(PaddleTensor *tensor, const OneSlotInBatch &slot) {
tensor->name = slot.name + "_embed";
tensor->shape = slot.shape;
tensor->dtype = PaddleDType::FLOAT32;
tensor->lod.clear();
tensor->lod.emplace_back(slot.lod);
TensorAssignData(tensor, slot.data);
}
void PrepareInputs(std::vector<PaddleTensor> *input_slots, DataRecord *data) {
const auto &one_batch = data->NextBatch();
input_slots->resize(one_batch.size());
for (size_t i = 0; i < one_batch.size(); ++i) {
auto &slot = one_batch[i];
TensorAssignSlot(&((*input_slots)[i]), slot);
}
}
void SetInput(std::vector<std::vector<PaddleTensor>> *inputs) {
DataRecord data(FLAGS_infer_data, FLAGS_batch_size);
std::vector<PaddleTensor> input_slots;
int epoch = FLAGS_test_all_data ? data.batched_data.size() : 1;
LOG(INFO) << "number of samples: "
<< data.batched_data.size() * FLAGS_batch_size;
for (int bid = 0; bid < epoch; ++bid) {
PrepareInputs(&input_slots, &data);
(*inputs).emplace_back(input_slots);
}
}
void SetConfig(AnalysisConfig *cfg, bool use_mkldnn = false) {
cfg->SetModel(FLAGS_infer_model + "/model", FLAGS_infer_model + "/params");
cfg->DisableGpu();
cfg->SwitchSpecifyInputNames();
cfg->pass_builder()->TurnOnDebug();
cfg->SetCpuMathLibraryNumThreads(FLAGS_paddle_num_threads);
if (use_mkldnn) {
cfg->EnableMKLDNN();
}
}
void profile(bool use_mkldnn = false) {
AnalysisConfig cfg;
SetConfig(&cfg, use_mkldnn);
std::vector<PaddleTensor> outputs;
std::vector<std::vector<PaddleTensor>> input_slots_all;
SetInput(&input_slots_all);
TestPrediction(reinterpret_cast<const PaddlePredictor::Config *>(&cfg),
input_slots_all, &outputs, FLAGS_num_threads);
}
TEST(Analyzer_seq_pool1, profile) { profile(); }
// Compare result of NativeConfig and AnalysisConfig
TEST(Analyzer_seq_pool1, compare) {
AnalysisConfig cfg;
SetConfig(&cfg);
std::vector<std::vector<PaddleTensor>> input_slots_all;
SetInput(&input_slots_all);
CompareNativeAndAnalysis(
reinterpret_cast<const PaddlePredictor::Config *>(&cfg), input_slots_all);
}
void analysis_fuse_statis(bool use_zerocopy) {
AnalysisConfig cfg;
SetConfig(&cfg);
cfg.SwitchUseFeedFetchOps(!use_zerocopy);
int num_ops;
auto predictor = CreatePaddlePredictor<AnalysisConfig>(cfg);
auto fuse_statis = GetFuseStatis(predictor.get(), &num_ops);
ASSERT_TRUE(fuse_statis.count("fc_fuse"));
ASSERT_EQ(fuse_statis.at("fc_fuse"), 10);
ASSERT_TRUE(fuse_statis.count("seqpool_concat_fuse"));
EXPECT_EQ(fuse_statis.at("seqpool_concat_fuse"), 2);
LOG(INFO) << "num_ops: " << num_ops;
EXPECT_EQ(num_ops, 195);
}
// Check the fuse status
TEST(Analyzer_seq_pool1, fuse_statis) { analysis_fuse_statis(false); }
void PrepareZeroCopyInputs(
const std::unique_ptr<PaddlePredictor> &predictor,
std::vector<std::unique_ptr<ZeroCopyTensor>> *inputs) {
DataRecord data(FLAGS_infer_data, FLAGS_batch_size);
// only feed one batch
const auto &one_batch = data.NextBatch();
inputs->clear();
for (size_t i = 0; i < one_batch.size(); ++i) {
auto &slot = one_batch[i];
auto tensor = predictor->GetInputTensor(slot.name + "_embed");
tensor->Reshape(slot.shape);
tensor->SetLoD({slot.lod});
ZeroCopyTensorAssignData<float>(tensor.get(), slot.data);
inputs->emplace_back(std::move(tensor));
}
}
// return the output values
std::vector<float> zerocopy_profile(int repeat_times) {
AnalysisConfig config;
SetConfig(&config);
config.SwitchUseFeedFetchOps(false);
auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
std::vector<std::unique_ptr<ZeroCopyTensor>> inputs;
PrepareZeroCopyInputs(predictor, &inputs);
auto output_tensor = predictor->GetOutputTensor("reduce_sum_0.tmp_0");
Timer timer;
LOG(INFO) << "Warm up run...";
timer.tic();
predictor->ZeroCopyRun();
PrintTime(FLAGS_batch_size, 1, 1, 0, timer.toc(), 1);
if (FLAGS_profile) {
paddle::platform::ResetProfiler();
}
LOG(INFO) << "Run " << repeat_times << " times...";
timer.tic();
for (int i = 0; i < repeat_times; i++) {
predictor->ZeroCopyRun();
}
PrintTime(FLAGS_batch_size, repeat_times, 1, 0, timer.toc() / repeat_times,
1);
VLOG(3) << "ZeroCopy output: " << DescribeZeroCopyTensor(*output_tensor);
PaddlePlace place;
int output_size{0};
auto *pdata = output_tensor->data<float>(&place, &output_size);
std::vector<float> res(output_size);
for (int i = 0; i < output_size; ++i) {
res[i] = pdata[i];
}
return res;
}
TEST(Analyzer_seq_pool1, zerocopy_profile) { zerocopy_profile(FLAGS_repeat); }
TEST(Analyzer_seq_pool1, zerocopy_fuse_statis) { analysis_fuse_statis(true); }
TEST(Analyzer_seq_pool1, zerocopy_compare_native) {
AnalysisConfig config;
SetConfig(&config);
config.SwitchUseFeedFetchOps(true);
auto predictor = CreatePaddlePredictor<NativeConfig>(config.ToNativeConfig());
std::vector<PaddleTensor> native_outputs;
std::vector<std::vector<PaddleTensor>> input_slots_all;
SetInput(&input_slots_all);
ASSERT_TRUE(predictor->Run(input_slots_all[0], &native_outputs));
EXPECT_EQ(native_outputs.size(), 1UL);
auto zerocopy_output = zerocopy_profile(1);
EXPECT_EQ(zerocopy_output.size() * sizeof(float),
native_outputs.front().data.length());
auto *native_data = static_cast<float *>(native_outputs.front().data.data());
for (size_t i = 0; i < zerocopy_output.size(); ++i) {
EXPECT_NEAR(zerocopy_output[i], native_data[i], 1e-3);
}
}
} // namespace analysis
} // namespace inference
} // namespace paddle
<commit_msg>add compare_determine of seqpool1 test<commit_after>/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <algorithm>
#include <fstream>
#include <iostream>
#include "paddle/fluid/inference/tests/api/tester_helper.h"
namespace paddle {
namespace inference {
namespace analysis {
struct OneSlotInBatch {
std::string name;
std::vector<std::vector<float>> data;
std::vector<int> shape;
std::vector<size_t> lod;
};
struct DataRecord {
std::vector<std::vector<OneSlotInBatch>> batched_data;
std::map<std::string, std::vector<std::vector<float>>> datasets;
size_t batch_iter{0}, num_samples; // total number of samples
DataRecord() = default;
explicit DataRecord(const std::string &path, int batch_size = 1) {
Load(path);
Prepare(batch_size);
}
void Load(const std::string &path) {
std::ifstream file(path);
constexpr int num_slots = 154;
std::string line;
int num_lines = 0;
while (std::getline(file, line)) {
num_lines++;
std::vector<std::string> data;
split(line, '\t', &data);
std::vector<float> slot_data;
split_to_float(data[1], ' ', &slot_data);
std::string name = data[0];
PADDLE_ENFORCE_EQ(slot_data.size() % 11, 0,
"line %d, %s should be divisible", num_lines, name);
datasets[name].emplace_back(std::move(slot_data));
}
num_samples = num_lines / num_slots;
PADDLE_ENFORCE_EQ(num_samples * num_slots, static_cast<size_t>(num_lines),
"num samples should be divisible");
PADDLE_ENFORCE_GT(num_samples, 0);
}
void Prepare(int bs) {
for (auto it = datasets.begin(); it != datasets.end(); ++it) {
PADDLE_ENFORCE_EQ(it->second.size(), num_samples,
"size of each slot should be equal");
}
size_t num_batches = num_samples / bs;
EXPECT_GT(num_batches, 0);
batched_data.resize(num_batches);
for (auto &one_batch : batched_data) {
one_batch.resize(datasets.size());
size_t i = 0;
for (auto it = datasets.begin(); it != datasets.end(); ++it) {
auto &slot = one_batch[i];
slot.name = it->first;
slot.data.resize(bs);
slot.lod.resize(bs + 1);
slot.lod[0] = 0;
auto &lod = slot.lod;
auto &datas = it->second;
for (int k = 0; k < bs; ++k) {
size_t id = k + batch_iter * bs;
std::copy(datas[id].begin(), datas[id].end(),
std::back_inserter(slot.data[k]));
size_t len = datas[id].size() / 11;
PADDLE_ENFORCE_EQ(len * 11, datas[id].size(),
"%s %d size should be divisible", slot.name, id);
lod[k + 1] = lod[k] + len;
}
slot.shape.assign({static_cast<int>(lod[bs]), 11});
i++;
}
}
}
const std::vector<OneSlotInBatch> &NextBatch() {
if (batch_iter >= batched_data.size() - 1) {
batch_iter = -1;
}
return batched_data[++batch_iter];
}
};
static void TensorAssignSlot(PaddleTensor *tensor, const OneSlotInBatch &slot) {
tensor->name = slot.name + "_embed";
tensor->shape = slot.shape;
tensor->dtype = PaddleDType::FLOAT32;
tensor->lod.clear();
tensor->lod.emplace_back(slot.lod);
TensorAssignData(tensor, slot.data);
}
void PrepareInputs(std::vector<PaddleTensor> *input_slots, DataRecord *data) {
const auto &one_batch = data->NextBatch();
input_slots->resize(one_batch.size());
for (size_t i = 0; i < one_batch.size(); ++i) {
auto &slot = one_batch[i];
TensorAssignSlot(&((*input_slots)[i]), slot);
}
}
void SetInput(std::vector<std::vector<PaddleTensor>> *inputs) {
DataRecord data(FLAGS_infer_data, FLAGS_batch_size);
std::vector<PaddleTensor> input_slots;
int epoch = FLAGS_test_all_data ? data.batched_data.size() : 1;
LOG(INFO) << "number of samples: "
<< data.batched_data.size() * FLAGS_batch_size;
for (int bid = 0; bid < epoch; ++bid) {
PrepareInputs(&input_slots, &data);
(*inputs).emplace_back(input_slots);
}
}
void SetConfig(AnalysisConfig *cfg, bool use_mkldnn = false) {
cfg->SetModel(FLAGS_infer_model + "/model", FLAGS_infer_model + "/params");
cfg->DisableGpu();
cfg->SwitchSpecifyInputNames();
cfg->pass_builder()->TurnOnDebug();
cfg->SetCpuMathLibraryNumThreads(FLAGS_paddle_num_threads);
if (use_mkldnn) {
cfg->EnableMKLDNN();
}
}
void profile(bool use_mkldnn = false) {
AnalysisConfig cfg;
SetConfig(&cfg, use_mkldnn);
std::vector<PaddleTensor> outputs;
std::vector<std::vector<PaddleTensor>> input_slots_all;
SetInput(&input_slots_all);
TestPrediction(reinterpret_cast<const PaddlePredictor::Config *>(&cfg),
input_slots_all, &outputs, FLAGS_num_threads);
}
TEST(Analyzer_seq_pool1, profile) { profile(); }
// Compare result of NativeConfig and AnalysisConfig
TEST(Analyzer_seq_pool1, compare) {
AnalysisConfig cfg;
SetConfig(&cfg);
std::vector<std::vector<PaddleTensor>> input_slots_all;
SetInput(&input_slots_all);
CompareNativeAndAnalysis(
reinterpret_cast<const PaddlePredictor::Config *>(&cfg), input_slots_all);
}
// Compare Deterministic result
TEST(Analyzer_seq_pool1, compare_determine) {
AnalysisConfig cfg;
SetConfig(&cfg);
std::vector<std::vector<PaddleTensor>> input_slots_all;
SetInput(&input_slots_all);
CompareDeterministic(reinterpret_cast<const PaddlePredictor::Config *>(&cfg),
input_slots_all);
}
void analysis_fuse_statis(bool use_zerocopy) {
AnalysisConfig cfg;
SetConfig(&cfg);
cfg.SwitchUseFeedFetchOps(!use_zerocopy);
int num_ops;
auto predictor = CreatePaddlePredictor<AnalysisConfig>(cfg);
auto fuse_statis = GetFuseStatis(predictor.get(), &num_ops);
ASSERT_TRUE(fuse_statis.count("fc_fuse"));
ASSERT_EQ(fuse_statis.at("fc_fuse"), 10);
ASSERT_TRUE(fuse_statis.count("seqpool_concat_fuse"));
EXPECT_EQ(fuse_statis.at("seqpool_concat_fuse"), 2);
LOG(INFO) << "num_ops: " << num_ops;
EXPECT_EQ(num_ops, 195);
}
// Check the fuse status
TEST(Analyzer_seq_pool1, fuse_statis) { analysis_fuse_statis(false); }
void PrepareZeroCopyInputs(
const std::unique_ptr<PaddlePredictor> &predictor,
std::vector<std::unique_ptr<ZeroCopyTensor>> *inputs) {
DataRecord data(FLAGS_infer_data, FLAGS_batch_size);
// only feed one batch
const auto &one_batch = data.NextBatch();
inputs->clear();
for (size_t i = 0; i < one_batch.size(); ++i) {
auto &slot = one_batch[i];
auto tensor = predictor->GetInputTensor(slot.name + "_embed");
tensor->Reshape(slot.shape);
tensor->SetLoD({slot.lod});
ZeroCopyTensorAssignData<float>(tensor.get(), slot.data);
inputs->emplace_back(std::move(tensor));
}
}
// return the output values
std::vector<float> zerocopy_profile(int repeat_times) {
AnalysisConfig config;
SetConfig(&config);
config.SwitchUseFeedFetchOps(false);
auto predictor = CreatePaddlePredictor<AnalysisConfig>(config);
std::vector<std::unique_ptr<ZeroCopyTensor>> inputs;
PrepareZeroCopyInputs(predictor, &inputs);
auto output_tensor = predictor->GetOutputTensor("reduce_sum_0.tmp_0");
Timer timer;
LOG(INFO) << "Warm up run...";
timer.tic();
predictor->ZeroCopyRun();
PrintTime(FLAGS_batch_size, 1, 1, 0, timer.toc(), 1);
if (FLAGS_profile) {
paddle::platform::ResetProfiler();
}
LOG(INFO) << "Run " << repeat_times << " times...";
timer.tic();
for (int i = 0; i < repeat_times; i++) {
predictor->ZeroCopyRun();
}
PrintTime(FLAGS_batch_size, repeat_times, 1, 0, timer.toc() / repeat_times,
1);
VLOG(3) << "ZeroCopy output: " << DescribeZeroCopyTensor(*output_tensor);
PaddlePlace place;
int output_size{0};
auto *pdata = output_tensor->data<float>(&place, &output_size);
std::vector<float> res(output_size);
for (int i = 0; i < output_size; ++i) {
res[i] = pdata[i];
}
return res;
}
TEST(Analyzer_seq_pool1, zerocopy_profile) { zerocopy_profile(FLAGS_repeat); }
TEST(Analyzer_seq_pool1, zerocopy_fuse_statis) { analysis_fuse_statis(true); }
TEST(Analyzer_seq_pool1, zerocopy_compare_native) {
AnalysisConfig config;
SetConfig(&config);
config.SwitchUseFeedFetchOps(true);
auto predictor = CreatePaddlePredictor<NativeConfig>(config.ToNativeConfig());
std::vector<PaddleTensor> native_outputs;
std::vector<std::vector<PaddleTensor>> input_slots_all;
SetInput(&input_slots_all);
ASSERT_TRUE(predictor->Run(input_slots_all[0], &native_outputs));
EXPECT_EQ(native_outputs.size(), 1UL);
auto zerocopy_output = zerocopy_profile(1);
EXPECT_EQ(zerocopy_output.size() * sizeof(float),
native_outputs.front().data.length());
auto *native_data = static_cast<float *>(native_outputs.front().data.data());
for (size_t i = 0; i < zerocopy_output.size(); ++i) {
EXPECT_NEAR(zerocopy_output[i], native_data[i], 1e-3);
}
}
} // namespace analysis
} // namespace inference
} // namespace paddle
<|endoftext|> |
<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "diagnosticsurfaceshader.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/ambientocclusion.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/kernel/shading/shadingresult.h"
#include "renderer/modeling/camera/camera.h"
#include "renderer/modeling/input/inputarray.h"
#include "renderer/modeling/input/source.h"
#include "renderer/modeling/scene/scene.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
#include "foundation/math/distance.h"
#include "foundation/math/hash.h"
#include "foundation/math/minmax.h"
#include "foundation/math/scalar.h"
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
// Utility function to compute a color from a given normal vector.
inline void normal_to_color(const Vector3d& n, Spectrum& output)
{
assert(abs(n[0]) <= 1.0);
assert(abs(n[1]) <= 1.0);
assert(abs(n[2]) <= 1.0);
output[0] = static_cast<float>((n[0] + 1.0) * 0.5);
output[1] = static_cast<float>((n[1] + 1.0) * 0.5);
output[2] = static_cast<float>((n[2] + 1.0) * 0.5);
}
// Utility function to compute a color from a given integer value.
template <typename T>
inline void integer_to_color(const T i, Spectrum& output)
{
const uint32 u = static_cast<uint32>(i); // keep the low 32 bits
const uint32 x = hashint32(u);
const uint32 y = hashint32(u + 1);
const uint32 z = hashint32(u + 2);
output[0] = static_cast<float>(x) * (1.0f / 4294967295.0f);
output[1] = static_cast<float>(y) * (1.0f / 4294967295.0f);
output[2] = static_cast<float>(z) * (1.0f / 4294967295.0f);
}
}
//
// Diagnostic surface shader.
//
struct DiagnosticSurfaceShader::Impl
{
string m_name;
ShadingMode m_shading_mode;
double m_ao_max_distance;
size_t m_ao_samples;
};
const KeyValuePair<const char*, DiagnosticSurfaceShader::ShadingMode>
DiagnosticSurfaceShader::ShadingModeValues[] =
{
{ "coverage", Coverage },
{ "barycentric", Barycentric },
{ "uv", UV },
{ "geometric_normal", GeometricNormal },
{ "shading_normal", ShadingNormal },
{ "assembly_instances", AssemblyInstances },
{ "object_instances", ObjectInstances },
{ "regions", Regions },
{ "triangles", Triangles },
{ "materials", Materials },
{ "ambient_occlusion", AmbientOcclusion },
{ "wireframe" , Wireframe }
};
const KeyValuePair<const char*, const char*> DiagnosticSurfaceShader::ShadingModeNames[] =
{
{ "coverage", "Coverage" },
{ "barycentric", "Barycentric Coordinates" },
{ "uv", "UV Coordinates" },
{ "geometric_normal", "Geometric Normals" },
{ "shading_normal", "Shading Normals" },
{ "assembly_instances", "Assembly Instances" },
{ "object_instances", "Object Instances" },
{ "regions", "Regions" },
{ "triangles", "Triangles" },
{ "materials", "Materials" },
{ "ambient_occlusion", "Ambient Occlusion" },
{ "wireframe" , "Wireframe" }
};
// Constructor.
DiagnosticSurfaceShader::DiagnosticSurfaceShader(
const char* name,
const ParamArray& params)
: SurfaceShader(params)
, impl(new Impl())
{
impl->m_name = name;
extract_parameters();
}
// Delete this instance.
void DiagnosticSurfaceShader::release()
{
delete this;
}
// Return a string identifying the model of this surface shader.
const char* DiagnosticSurfaceShader::get_model() const
{
return DiagnosticSurfaceShaderFactory::get_model();
}
// Return the name of this surface shader.
const char* DiagnosticSurfaceShader::get_name() const
{
return impl->m_name.c_str();
}
// Evaluate the shading at a given point.
void DiagnosticSurfaceShader::evaluate(
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
ShadingResult& shading_result) const
{
// Set color space to linear RGB.
shading_result.m_color_space = ColorSpaceLinearRGB;
switch (impl->m_shading_mode)
{
// Shade according to pixel coverage
case Coverage:
shading_result.m_color[0] = 1.0f;
shading_result.m_color[1] = 1.0f;
shading_result.m_color[2] = 1.0f;
break;
// Shade according to barycentric coordinates.
case Barycentric:
{
const Vector2d& bary = shading_point.get_bary();
const double w = 1.0 - bary[0] - bary[1];
shading_result.m_color[0] = static_cast<float>(w);
shading_result.m_color[1] = static_cast<float>(bary[0]);
shading_result.m_color[2] = static_cast<float>(bary[1]);
}
break;
// Shade according to UV coordinates from UV set #0.
case UV:
{
const Vector2d& uv0 = shading_point.get_uv(0);
const double w = 1.0 - uv0[0] - uv0[1];
shading_result.m_color[0] = static_cast<float>(w);
shading_result.m_color[1] = static_cast<float>(uv0[0]);
shading_result.m_color[2] = static_cast<float>(uv0[1]);
}
break;
// Shade according to the geometric normal.
case GeometricNormal:
normal_to_color(
shading_point.get_geometric_normal(),
shading_result.m_color);
break;
// Shade according to the shading normal.
case ShadingNormal:
normal_to_color(
shading_point.get_shading_normal(),
shading_result.m_color);
break;
// Assign an unique color to each assembly instance.
case AssemblyInstances:
integer_to_color(
shading_point.get_assembly_instance_uid(),
shading_result.m_color);
break;
// Assign an unique color to each object instance.
case ObjectInstances:
{
const uint32 h = mix32(
static_cast<uint32>(shading_point.get_assembly_instance_uid()),
static_cast<uint32>(shading_point.get_object_instance_index()));
integer_to_color(h, shading_result.m_color);
}
break;
// Assign an unique color to each region.
case Regions:
{
const uint32 h = mix32(
static_cast<uint32>(shading_point.get_assembly_instance_uid()),
static_cast<uint32>(shading_point.get_object_instance_index()),
static_cast<uint32>(shading_point.get_region_index()));
integer_to_color(h, shading_result.m_color);
}
break;
// Assign an unique color to each triangle.
case Triangles:
{
const uint32 h = mix32(
static_cast<uint32>(shading_point.get_assembly_instance_uid()),
static_cast<uint32>(shading_point.get_object_instance_index()),
static_cast<uint32>(shading_point.get_region_index()),
static_cast<uint32>(shading_point.get_triangle_index()));
integer_to_color(h, shading_result.m_color);
}
break;
// Assign an unique color to each material.
case Materials:
{
const ObjectInstance& object_instance = shading_point.get_object_instance();
const MaterialIndexArray& material_indices = object_instance.get_material_indices();
const size_t pa_index = shading_point.get_primitive_attribute_index();
if (pa_index < material_indices.size())
{
const size_t material_index = material_indices[pa_index];
const uint32 h = mix32(
static_cast<uint32>(shading_point.get_assembly_instance_uid()),
static_cast<uint32>(material_index));
integer_to_color(h, shading_result.m_color);
}
else
{
shading_result.m_color[0] = 1.0f;
shading_result.m_color[1] = 0.0f;
shading_result.m_color[2] = 1.0f;
}
}
break;
// Ambient occlusion.
case AmbientOcclusion:
{
// Compute the occlusion.
const double occlusion =
compute_ambient_occlusion(
sampling_context,
shading_context.get_intersector(),
shading_point.get_point(),
shading_point.get_geometric_normal(),
shading_point.get_shading_basis(),
impl->m_ao_max_distance,
impl->m_ao_samples,
&shading_point);
// Return a gray scale value proportional to the accessibility.
const float accessibility = static_cast<float>(1.0 - occlusion);
shading_result.m_color[0] = accessibility;
shading_result.m_color[1] = accessibility;
shading_result.m_color[2] = accessibility;
}
break;
// Wireframe.
case Wireframe:
{
// Retrieve the camera.
const Scene& scene = shading_point.get_scene();
const Camera* camera = scene.get_camera();
assert(camera);
// Retrieve the camera transformation.
const Transformd& camera_transform = camera->get_transform();
// Retrieve world space triangle vertices.
const Vector3d& v0 = shading_point.get_vertex(0);
const Vector3d& v1 = shading_point.get_vertex(1);
const Vector3d& v2 = shading_point.get_vertex(2);
// Transform triangle vertices to camera space.
const Vector3d v0_cs = camera_transform.transform_point_to_local(v0);
const Vector3d v1_cs = camera_transform.transform_point_to_local(v1);
const Vector3d v2_cs = camera_transform.transform_point_to_local(v2);
// Project triangle vertices to film space.
const Vector2d v0_fs = camera->project(v0_cs);
const Vector2d v1_fs = camera->project(v1_cs);
const Vector2d v2_fs = camera->project(v2_cs);
// Retrieve world space intersection point.
const Vector3d& point = shading_point.get_point();
// Transform intersection point to camera space.
const Vector3d point_cs = camera_transform.transform_point_to_local(point);
// Project intersection point to film space.
const Vector2d point_fs = camera->project(point_cs);
// Compute film space distance from intersection point to triangle edges.
const double d0 = square_distance_point_segment(point_fs, v0_fs, v1_fs);
const double d1 = square_distance_point_segment(point_fs, v1_fs, v2_fs);
const double d2 = square_distance_point_segment(point_fs, v2_fs, v0_fs);
// Film space thickness of the wires.
const double SquareWireThickness = square(0.002);
if (min(d0, d1, d2) < SquareWireThickness)
{
shading_result.m_color[0] = 1.0f;
shading_result.m_color[1] = 1.0f;
shading_result.m_color[2] = 1.0f;
}
else
{
shading_result.m_color[0] = 0.0f;
shading_result.m_color[1] = 0.0f;
shading_result.m_color[2] = 0.8f;
}
}
break;
// Invalid shader.
default:
assert(false);
shading_result.m_color[0] = 1.0f;
shading_result.m_color[1] = 0.0f;
shading_result.m_color[2] = 1.0f;
break;
}
// Set alpha channel to full opacity.
shading_result.m_alpha = Alpha(1.0);
}
void DiagnosticSurfaceShader::extract_parameters()
{
// Retrieve shading mode.
const string mode_string = m_params.get_required<string>("mode", "coverage");
const KeyValuePair<const char*, ShadingMode>* mode_pair =
lookup_kvpair_array(ShadingModeValues, ShadingModeCount, mode_string);
if (mode_pair)
{
impl->m_shading_mode = mode_pair->m_value;
}
else
{
RENDERER_LOG_ERROR(
"invalid shading mode \"%s\", using default value \"coverage\"",
mode_string.c_str());
impl->m_shading_mode = Coverage;
}
// Retrieve ambient occlusion parameters.
if (impl->m_shading_mode == AmbientOcclusion)
{
const ParamArray& ao_params = m_params.child("ambient_occlusion");
impl->m_ao_max_distance = ao_params.get_required<double>("max_distance", 1.0);
impl->m_ao_samples = ao_params.get_required<size_t>("samples", 16);
}
}
//
// DiagnosticSurfaceShaderFactory class implementation.
//
// Return a string identifying this surface shader model.
const char* DiagnosticSurfaceShaderFactory::get_model()
{
return "diagnostic_surface_shader";
}
// Create a new diagnostic surface shader.
auto_release_ptr<SurfaceShader> DiagnosticSurfaceShaderFactory::create(
const char* name,
const ParamArray& params)
{
return
auto_release_ptr<SurfaceShader>(
new DiagnosticSurfaceShader(name, params));
}
} // namespace renderer
<commit_msg>decreased the thickness of the wires in the "wireframe" mode of the diagnostic shader.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Interface header.
#include "diagnosticsurfaceshader.h"
// appleseed.renderer headers.
#include "renderer/kernel/shading/ambientocclusion.h"
#include "renderer/kernel/shading/shadingcontext.h"
#include "renderer/kernel/shading/shadingpoint.h"
#include "renderer/kernel/shading/shadingresult.h"
#include "renderer/modeling/camera/camera.h"
#include "renderer/modeling/input/inputarray.h"
#include "renderer/modeling/input/source.h"
#include "renderer/modeling/scene/scene.h"
// appleseed.foundation headers.
#include "foundation/image/colorspace.h"
#include "foundation/math/distance.h"
#include "foundation/math/hash.h"
#include "foundation/math/minmax.h"
#include "foundation/math/scalar.h"
using namespace foundation;
using namespace std;
namespace renderer
{
namespace
{
// Utility function to compute a color from a given normal vector.
inline void normal_to_color(const Vector3d& n, Spectrum& output)
{
assert(abs(n[0]) <= 1.0);
assert(abs(n[1]) <= 1.0);
assert(abs(n[2]) <= 1.0);
output[0] = static_cast<float>((n[0] + 1.0) * 0.5);
output[1] = static_cast<float>((n[1] + 1.0) * 0.5);
output[2] = static_cast<float>((n[2] + 1.0) * 0.5);
}
// Utility function to compute a color from a given integer value.
template <typename T>
inline void integer_to_color(const T i, Spectrum& output)
{
const uint32 u = static_cast<uint32>(i); // keep the low 32 bits
const uint32 x = hashint32(u);
const uint32 y = hashint32(u + 1);
const uint32 z = hashint32(u + 2);
output[0] = static_cast<float>(x) * (1.0f / 4294967295.0f);
output[1] = static_cast<float>(y) * (1.0f / 4294967295.0f);
output[2] = static_cast<float>(z) * (1.0f / 4294967295.0f);
}
}
//
// Diagnostic surface shader.
//
struct DiagnosticSurfaceShader::Impl
{
string m_name;
ShadingMode m_shading_mode;
double m_ao_max_distance;
size_t m_ao_samples;
};
const KeyValuePair<const char*, DiagnosticSurfaceShader::ShadingMode>
DiagnosticSurfaceShader::ShadingModeValues[] =
{
{ "coverage", Coverage },
{ "barycentric", Barycentric },
{ "uv", UV },
{ "geometric_normal", GeometricNormal },
{ "shading_normal", ShadingNormal },
{ "assembly_instances", AssemblyInstances },
{ "object_instances", ObjectInstances },
{ "regions", Regions },
{ "triangles", Triangles },
{ "materials", Materials },
{ "ambient_occlusion", AmbientOcclusion },
{ "wireframe" , Wireframe }
};
const KeyValuePair<const char*, const char*> DiagnosticSurfaceShader::ShadingModeNames[] =
{
{ "coverage", "Coverage" },
{ "barycentric", "Barycentric Coordinates" },
{ "uv", "UV Coordinates" },
{ "geometric_normal", "Geometric Normals" },
{ "shading_normal", "Shading Normals" },
{ "assembly_instances", "Assembly Instances" },
{ "object_instances", "Object Instances" },
{ "regions", "Regions" },
{ "triangles", "Triangles" },
{ "materials", "Materials" },
{ "ambient_occlusion", "Ambient Occlusion" },
{ "wireframe" , "Wireframe" }
};
// Constructor.
DiagnosticSurfaceShader::DiagnosticSurfaceShader(
const char* name,
const ParamArray& params)
: SurfaceShader(params)
, impl(new Impl())
{
impl->m_name = name;
extract_parameters();
}
// Delete this instance.
void DiagnosticSurfaceShader::release()
{
delete this;
}
// Return a string identifying the model of this surface shader.
const char* DiagnosticSurfaceShader::get_model() const
{
return DiagnosticSurfaceShaderFactory::get_model();
}
// Return the name of this surface shader.
const char* DiagnosticSurfaceShader::get_name() const
{
return impl->m_name.c_str();
}
// Evaluate the shading at a given point.
void DiagnosticSurfaceShader::evaluate(
SamplingContext& sampling_context,
const ShadingContext& shading_context,
const ShadingPoint& shading_point,
ShadingResult& shading_result) const
{
// Set color space to linear RGB.
shading_result.m_color_space = ColorSpaceLinearRGB;
switch (impl->m_shading_mode)
{
// Shade according to pixel coverage
case Coverage:
shading_result.m_color[0] = 1.0f;
shading_result.m_color[1] = 1.0f;
shading_result.m_color[2] = 1.0f;
break;
// Shade according to barycentric coordinates.
case Barycentric:
{
const Vector2d& bary = shading_point.get_bary();
const double w = 1.0 - bary[0] - bary[1];
shading_result.m_color[0] = static_cast<float>(w);
shading_result.m_color[1] = static_cast<float>(bary[0]);
shading_result.m_color[2] = static_cast<float>(bary[1]);
}
break;
// Shade according to UV coordinates from UV set #0.
case UV:
{
const Vector2d& uv0 = shading_point.get_uv(0);
const double w = 1.0 - uv0[0] - uv0[1];
shading_result.m_color[0] = static_cast<float>(w);
shading_result.m_color[1] = static_cast<float>(uv0[0]);
shading_result.m_color[2] = static_cast<float>(uv0[1]);
}
break;
// Shade according to the geometric normal.
case GeometricNormal:
normal_to_color(
shading_point.get_geometric_normal(),
shading_result.m_color);
break;
// Shade according to the shading normal.
case ShadingNormal:
normal_to_color(
shading_point.get_shading_normal(),
shading_result.m_color);
break;
// Assign an unique color to each assembly instance.
case AssemblyInstances:
integer_to_color(
shading_point.get_assembly_instance_uid(),
shading_result.m_color);
break;
// Assign an unique color to each object instance.
case ObjectInstances:
{
const uint32 h = mix32(
static_cast<uint32>(shading_point.get_assembly_instance_uid()),
static_cast<uint32>(shading_point.get_object_instance_index()));
integer_to_color(h, shading_result.m_color);
}
break;
// Assign an unique color to each region.
case Regions:
{
const uint32 h = mix32(
static_cast<uint32>(shading_point.get_assembly_instance_uid()),
static_cast<uint32>(shading_point.get_object_instance_index()),
static_cast<uint32>(shading_point.get_region_index()));
integer_to_color(h, shading_result.m_color);
}
break;
// Assign an unique color to each triangle.
case Triangles:
{
const uint32 h = mix32(
static_cast<uint32>(shading_point.get_assembly_instance_uid()),
static_cast<uint32>(shading_point.get_object_instance_index()),
static_cast<uint32>(shading_point.get_region_index()),
static_cast<uint32>(shading_point.get_triangle_index()));
integer_to_color(h, shading_result.m_color);
}
break;
// Assign an unique color to each material.
case Materials:
{
const ObjectInstance& object_instance = shading_point.get_object_instance();
const MaterialIndexArray& material_indices = object_instance.get_material_indices();
const size_t pa_index = shading_point.get_primitive_attribute_index();
if (pa_index < material_indices.size())
{
const size_t material_index = material_indices[pa_index];
const uint32 h = mix32(
static_cast<uint32>(shading_point.get_assembly_instance_uid()),
static_cast<uint32>(material_index));
integer_to_color(h, shading_result.m_color);
}
else
{
shading_result.m_color[0] = 1.0f;
shading_result.m_color[1] = 0.0f;
shading_result.m_color[2] = 1.0f;
}
}
break;
// Ambient occlusion.
case AmbientOcclusion:
{
// Compute the occlusion.
const double occlusion =
compute_ambient_occlusion(
sampling_context,
shading_context.get_intersector(),
shading_point.get_point(),
shading_point.get_geometric_normal(),
shading_point.get_shading_basis(),
impl->m_ao_max_distance,
impl->m_ao_samples,
&shading_point);
// Return a gray scale value proportional to the accessibility.
const float accessibility = static_cast<float>(1.0 - occlusion);
shading_result.m_color[0] = accessibility;
shading_result.m_color[1] = accessibility;
shading_result.m_color[2] = accessibility;
}
break;
// Wireframe.
case Wireframe:
{
// Retrieve the camera.
const Scene& scene = shading_point.get_scene();
const Camera* camera = scene.get_camera();
assert(camera);
// Retrieve the camera transformation.
const Transformd& camera_transform = camera->get_transform();
// Retrieve world space triangle vertices.
const Vector3d& v0 = shading_point.get_vertex(0);
const Vector3d& v1 = shading_point.get_vertex(1);
const Vector3d& v2 = shading_point.get_vertex(2);
// Transform triangle vertices to camera space.
const Vector3d v0_cs = camera_transform.transform_point_to_local(v0);
const Vector3d v1_cs = camera_transform.transform_point_to_local(v1);
const Vector3d v2_cs = camera_transform.transform_point_to_local(v2);
// Project triangle vertices to film space.
const Vector2d v0_fs = camera->project(v0_cs);
const Vector2d v1_fs = camera->project(v1_cs);
const Vector2d v2_fs = camera->project(v2_cs);
// Retrieve world space intersection point.
const Vector3d& point = shading_point.get_point();
// Transform intersection point to camera space.
const Vector3d point_cs = camera_transform.transform_point_to_local(point);
// Project intersection point to film space.
const Vector2d point_fs = camera->project(point_cs);
// Compute film space distance from intersection point to triangle edges.
const double d0 = square_distance_point_segment(point_fs, v0_fs, v1_fs);
const double d1 = square_distance_point_segment(point_fs, v1_fs, v2_fs);
const double d2 = square_distance_point_segment(point_fs, v2_fs, v0_fs);
// Film space thickness of the wires.
const double SquareWireThickness = square(0.0005);
if (min(d0, d1, d2) < SquareWireThickness)
{
shading_result.m_color[0] = 1.0f;
shading_result.m_color[1] = 1.0f;
shading_result.m_color[2] = 1.0f;
}
else
{
shading_result.m_color[0] = 0.0f;
shading_result.m_color[1] = 0.0f;
shading_result.m_color[2] = 0.8f;
}
}
break;
// Invalid shader.
default:
assert(false);
shading_result.m_color[0] = 1.0f;
shading_result.m_color[1] = 0.0f;
shading_result.m_color[2] = 1.0f;
break;
}
// Set alpha channel to full opacity.
shading_result.m_alpha = Alpha(1.0);
}
void DiagnosticSurfaceShader::extract_parameters()
{
// Retrieve shading mode.
const string mode_string = m_params.get_required<string>("mode", "coverage");
const KeyValuePair<const char*, ShadingMode>* mode_pair =
lookup_kvpair_array(ShadingModeValues, ShadingModeCount, mode_string);
if (mode_pair)
{
impl->m_shading_mode = mode_pair->m_value;
}
else
{
RENDERER_LOG_ERROR(
"invalid shading mode \"%s\", using default value \"coverage\"",
mode_string.c_str());
impl->m_shading_mode = Coverage;
}
// Retrieve ambient occlusion parameters.
if (impl->m_shading_mode == AmbientOcclusion)
{
const ParamArray& ao_params = m_params.child("ambient_occlusion");
impl->m_ao_max_distance = ao_params.get_required<double>("max_distance", 1.0);
impl->m_ao_samples = ao_params.get_required<size_t>("samples", 16);
}
}
//
// DiagnosticSurfaceShaderFactory class implementation.
//
// Return a string identifying this surface shader model.
const char* DiagnosticSurfaceShaderFactory::get_model()
{
return "diagnostic_surface_shader";
}
// Create a new diagnostic surface shader.
auto_release_ptr<SurfaceShader> DiagnosticSurfaceShaderFactory::create(
const char* name,
const ParamArray& params)
{
return
auto_release_ptr<SurfaceShader>(
new DiagnosticSurfaceShader(name, params));
}
} // namespace renderer
<|endoftext|> |
<commit_before>#define GUILITE_ON //Do not define this macro once more!!!
#include "GuiLite.h"
#define UI_WIDTH 240
#define UI_HEIGHT 320
#define LAYER_1_X 70
#define LAYER_1_Y 110
#define LAYER_1_WIDTH 100
#define LAYER_1_HEIGHT 80
static c_surface* s_surface;
static c_display* s_display;
//////////////////////// start UI ////////////////////////
void draw_on_layer_0()
{
s_surface->fill_rect(0, 0, UI_WIDTH - 1, UI_HEIGHT - 1, 0, Z_ORDER_LEVEL_0);
c_word::draw_string(s_surface, Z_ORDER_LEVEL_0, "layer 0: the bottom", 30, LAYER_1_Y + 30, c_theme::get_font(FONT_DEFAULT), GL_RGB(255, 255, 255), GL_ARGB(0, 0, 0, 0));
}
void draw_on_layer_1()
{
s_surface->fill_rect(LAYER_1_X, LAYER_1_Y, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - 1, GL_RGB(69, 75, 91), Z_ORDER_LEVEL_1);
c_word::draw_string(s_surface, Z_ORDER_LEVEL_1, "layer 1:", LAYER_1_X + 10, LAYER_1_Y + 19, c_theme::get_font(FONT_DEFAULT), GL_RGB(255, 255, 255), GL_RGB(69, 75, 91));
c_word::draw_string(s_surface, Z_ORDER_LEVEL_1, "the top", LAYER_1_X + 10, LAYER_1_Y + 38, c_theme::get_font(FONT_DEFAULT), GL_RGB(255, 255, 255), GL_RGB(69, 75, 91));
}
void clear_layer_1()
{
#if 0
//no animation
c_rect overlapped_rect(LAYER_1_X, LAYER_1_Y, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - 1);
s_surface->show_overlapped_rect(overlapped_rect, Z_ORDER_LEVEL_0);
#else
//animation
for (int offset = 0; offset < LAYER_1_HEIGHT / 2; offset++)
{
c_rect overlapped_rect_top(LAYER_1_X, LAYER_1_Y + offset, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + offset + 1);
s_surface->show_overlapped_rect(overlapped_rect_top, Z_ORDER_LEVEL_0);
c_rect overlapped_rect_bottom(LAYER_1_X, LAYER_1_Y + LAYER_1_HEIGHT - offset - 2, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - offset - 1);
s_surface->show_overlapped_rect(overlapped_rect_bottom, Z_ORDER_LEVEL_0);
thread_sleep(5);
}
#endif
}
extern const FONT_INFO Consolas_19;
void load_resource()
{
c_theme::add_font(FONT_DEFAULT, &Consolas_19);
}
void create_ui(void* phy_fb, int screen_width, int screen_height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op) {
if (phy_fb)
{
static c_surface surface(UI_WIDTH, UI_HEIGHT, color_bytes, Z_ORDER_LEVEL_1, c_rect(LAYER_1_X, LAYER_1_Y, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - 1));
static c_display display(phy_fb, screen_width, screen_height, &surface);
s_surface = &surface;
s_display = &display;
}
else
{//for MCU without framebuffer
static c_surface_no_fb surface_no_fb(UI_WIDTH, UI_HEIGHT, color_bytes, gfx_op, Z_ORDER_LEVEL_1, c_rect(LAYER_1_X, LAYER_1_Y, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - 1));
static c_display display(phy_fb, screen_width, screen_height, &surface_no_fb);
s_surface = &surface_no_fb;
s_display = &display;
}
load_resource();
draw_on_layer_0();
while(1) {
draw_on_layer_1();
thread_sleep(3000);
clear_layer_1();
thread_sleep(3000);
}
}
//////////////////////// interface for all platform ////////////////////////
extern "C" void startHelloLayers(void* phy_fb, int width, int height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op) {
create_ui(phy_fb, width, height, color_bytes, gfx_op);
}
void* getUiOfHelloLayers(int* width, int* height, bool force_update)
{
if (s_display)
{
return s_display->get_updated_fb(width, height, force_update);
}
return NULL;
}
<commit_msg>add shutter effect for helloLayers<commit_after>#define GUILITE_ON //Do not define this macro once more!!!
#include "GuiLite.h"
#define UI_WIDTH 240
#define UI_HEIGHT 320
#define LAYER_1_X 70
#define LAYER_1_Y 110
#define SHADES_CNT 10
#define SHADE_HEIGHT 10
#define LAYER_1_WIDTH 80
#define LAYER_1_HEIGHT SHADES_CNT * SHADE_HEIGHT
static c_surface* s_surface;
static c_display* s_display;
//////////////////////// start UI ////////////////////////
void draw_on_layer_0()
{
s_surface->fill_rect(0, 0, UI_WIDTH - 1, UI_HEIGHT - 1, 0, Z_ORDER_LEVEL_0);
c_word::draw_string(s_surface, Z_ORDER_LEVEL_0, "layer 0: the bottom", 30, LAYER_1_Y + 30, c_theme::get_font(FONT_DEFAULT), GL_RGB(255, 255, 255), GL_ARGB(0, 0, 0, 0));
}
void draw_on_layer_1()
{
s_surface->fill_rect(LAYER_1_X, LAYER_1_Y, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - 1, GL_RGB(0, 122, 204), Z_ORDER_LEVEL_1);
c_word::draw_string(s_surface, Z_ORDER_LEVEL_1, "layer 1:", LAYER_1_X + 5, LAYER_1_Y + 19, c_theme::get_font(FONT_DEFAULT), GL_RGB(255, 255, 255), GL_RGB(0, 122, 204));
c_word::draw_string(s_surface, Z_ORDER_LEVEL_1, "the top", LAYER_1_X + 5, LAYER_1_Y + 38, c_theme::get_font(FONT_DEFAULT), GL_RGB(255, 255, 255), GL_RGB(0, 122, 204));
}
void clear_layer_1()
{
#if 0
//no animation
c_rect overlapped_rect(LAYER_1_X, LAYER_1_Y, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - 1);
s_surface->show_overlapped_rect(overlapped_rect, Z_ORDER_LEVEL_0);
#else
//animation
for (int offset = 0; offset < SHADE_HEIGHT; offset++)
{
for (int i = 0; i < SHADES_CNT; i++)
{
c_rect overlapped_rect_top(LAYER_1_X, LAYER_1_Y + (SHADE_HEIGHT * i) + offset, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + (SHADE_HEIGHT * i) + offset);
s_surface->show_overlapped_rect(overlapped_rect_top, Z_ORDER_LEVEL_0);
}
thread_sleep(5);
}
#endif
}
extern const FONT_INFO Consolas_19;
void load_resource()
{
c_theme::add_font(FONT_DEFAULT, &Consolas_19);
}
void create_ui(void* phy_fb, int screen_width, int screen_height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op) {
if (phy_fb)
{
static c_surface surface(UI_WIDTH, UI_HEIGHT, color_bytes, Z_ORDER_LEVEL_1, c_rect(LAYER_1_X, LAYER_1_Y, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - 1));
static c_display display(phy_fb, screen_width, screen_height, &surface);
s_surface = &surface;
s_display = &display;
}
else
{//for MCU without framebuffer
static c_surface_no_fb surface_no_fb(UI_WIDTH, UI_HEIGHT, color_bytes, gfx_op, Z_ORDER_LEVEL_1, c_rect(LAYER_1_X, LAYER_1_Y, LAYER_1_X + LAYER_1_WIDTH - 1, LAYER_1_Y + LAYER_1_HEIGHT - 1));
static c_display display(phy_fb, screen_width, screen_height, &surface_no_fb);
s_surface = &surface_no_fb;
s_display = &display;
}
load_resource();
draw_on_layer_0();
while(1) {
draw_on_layer_1();
thread_sleep(3000);
clear_layer_1();
thread_sleep(3000);
}
}
//////////////////////// interface for all platform ////////////////////////
extern "C" void startHelloLayers(void* phy_fb, int width, int height, int color_bytes, struct EXTERNAL_GFX_OP* gfx_op) {
create_ui(phy_fb, width, height, color_bytes, gfx_op);
}
void* getUiOfHelloLayers(int* width, int* height, bool force_update)
{
if (s_display)
{
return s_display->get_updated_fb(width, height, force_update);
}
return NULL;
}
<|endoftext|> |
<commit_before>/*
The MIT License
Copyright (c) 2009 Institut of Mechanics and Fluid Dynamics,
TU Bergakademie Freiberg.
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.
*/
/**
\file REKConverter.cpp
\author Andre Liebscher
Institut of Mechanics and Fluid Dynamics
TU Bergakademie Freiberg
\date March 2009
*/
#include <fstream>
#include <sstream>
#include <cstring>
#include "REKConverter.h"
#include "Controller/Controller.h"
#include "boost/cstdint.hpp"
using namespace std;
REKConverter::REKConverter()
{
m_vConverterDesc = "Fraunhofer EZRT Volume";
m_vSupportedExt.push_back("REK");
}
bool
REKConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string&,
bool, UINT64& iHeaderSkip,
UINT64& iComponentSize,
UINT64& iComponentCount,
bool& bConvertEndianess, bool& bSigned,
bool& bIsFloat, UINTVECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::string& strTitle,
UVFTables::ElementSemanticTable& eType,
std::string& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
MESSAGE("Attempting to convert REK dataset %s", strSourceFilename.c_str());
// Read header an check for "magic" values of the REK file
ifstream fileData(strSourceFilename.c_str(), ifstream::in | ifstream::binary);
char buffer[2048];
if(fileData.is_open()) {
fileData.read( buffer, sizeof(buffer) );
char ff[] = { 255, 255, 255, 255 };
if( memcmp(&buffer[116], &ff, 4) != 0 ) {
WARNING("The file %s is not a REK file", strSourceFilename.c_str());
fileData.close();
return false;
}
} else {
WARNING("Could not open REK file %s", strSourceFilename.c_str());
return false;
}
fileData.close();
// standard values which are always true (I guess)
strTitle = "Fraunhofer EZRT";
eType = UVFTables::ES_UNDEFINED;
vVolumeAspect = FLOATVECTOR3(1,1,1);
bSigned = false;
bIsFloat = false;
iComponentCount = 1;
strIntermediateFile = strSourceFilename;
bDeleteIntermediateFile = false;
// read file format from header - first try to guess endieness from offset 4-5 (bits per pixel)
// Anyway, I do not think that anyone would ever encounter such a file stored in big endian encoding.
bConvertEndianess = Parse<boost::uint16_t, 2>( &buffer[4] ) > 32;
vVolumeSize[0] = Parse<boost::uint16_t, 2>( &buffer[0], bConvertEndianess );
vVolumeSize[1] = Parse<boost::uint16_t, 2>( &buffer[2], bConvertEndianess );
vVolumeSize[2] = Parse<boost::uint16_t, 2>( &buffer[6], bConvertEndianess );
iComponentSize = Parse<boost::uint16_t, 2>( &buffer[4], bConvertEndianess );
iHeaderSkip = Parse<boost::uint16_t, 2>( &buffer[8], bConvertEndianess );
return true;
}
// unimplemented!
bool
REKConverter::ConvertToNative(const std::string&,
const std::string&,
UINT64, UINT64,
UINT64, bool,
bool,
UINTVECTOR3,
FLOATVECTOR3,
bool)
{
return false;
}
<commit_msg>Fix a warning on windows.<commit_after>/*
The MIT License
Copyright (c) 2009 Institut of Mechanics and Fluid Dynamics,
TU Bergakademie Freiberg.
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.
*/
/**
\file REKConverter.cpp
\author Andre Liebscher
Institut of Mechanics and Fluid Dynamics
TU Bergakademie Freiberg
\date March 2009
*/
#include <fstream>
#include <sstream>
#include <cstring>
#include "REKConverter.h"
#include "Controller/Controller.h"
#include "boost/cstdint.hpp"
using namespace std;
REKConverter::REKConverter()
{
m_vConverterDesc = "Fraunhofer EZRT Volume";
m_vSupportedExt.push_back("REK");
}
bool
REKConverter::ConvertToRAW(const std::string& strSourceFilename,
const std::string&,
bool, UINT64& iHeaderSkip,
UINT64& iComponentSize,
UINT64& iComponentCount,
bool& bConvertEndianess, bool& bSigned,
bool& bIsFloat, UINTVECTOR3& vVolumeSize,
FLOATVECTOR3& vVolumeAspect,
std::string& strTitle,
UVFTables::ElementSemanticTable& eType,
std::string& strIntermediateFile,
bool& bDeleteIntermediateFile)
{
MESSAGE("Attempting to convert REK dataset %s", strSourceFilename.c_str());
// Read header an check for "magic" values of the REK file
ifstream fileData(strSourceFilename.c_str(), ifstream::in | ifstream::binary);
char buffer[2048];
if(fileData.is_open()) {
fileData.read( buffer, sizeof(buffer) );
unsigned char ff[] = { 255, 255, 255, 255 };
if( memcmp(&buffer[116], &ff, 4) != 0 ) {
WARNING("The file %s is not a REK file", strSourceFilename.c_str());
fileData.close();
return false;
}
} else {
WARNING("Could not open REK file %s", strSourceFilename.c_str());
return false;
}
fileData.close();
// standard values which are always true (I guess)
strTitle = "Fraunhofer EZRT";
eType = UVFTables::ES_UNDEFINED;
vVolumeAspect = FLOATVECTOR3(1,1,1);
bSigned = false;
bIsFloat = false;
iComponentCount = 1;
strIntermediateFile = strSourceFilename;
bDeleteIntermediateFile = false;
// read file format from header - first try to guess endieness from offset 4-5 (bits per pixel)
// Anyway, I do not think that anyone would ever encounter such a file stored in big endian encoding.
bConvertEndianess = Parse<boost::uint16_t, 2>( &buffer[4] ) > 32;
vVolumeSize[0] = Parse<boost::uint16_t, 2>( &buffer[0], bConvertEndianess );
vVolumeSize[1] = Parse<boost::uint16_t, 2>( &buffer[2], bConvertEndianess );
vVolumeSize[2] = Parse<boost::uint16_t, 2>( &buffer[6], bConvertEndianess );
iComponentSize = Parse<boost::uint16_t, 2>( &buffer[4], bConvertEndianess );
iHeaderSkip = Parse<boost::uint16_t, 2>( &buffer[8], bConvertEndianess );
return true;
}
// unimplemented!
bool
REKConverter::ConvertToNative(const std::string&,
const std::string&,
UINT64, UINT64,
UINT64, bool,
bool,
UINTVECTOR3,
FLOATVECTOR3,
bool)
{
return false;
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkBYUWriter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 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 "vtkBYUWriter.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkBYUWriter, "1.42");
vtkStandardNewMacro(vtkBYUWriter);
// Create object so that it writes displacement, scalar, and texture files
// (if data is available).
vtkBYUWriter::vtkBYUWriter()
{
this->GeometryFileName = NULL;
this->DisplacementFileName = NULL;
this->ScalarFileName = NULL;
this->TextureFileName = NULL;
this->WriteDisplacement = 1;
this->WriteScalar = 1;
this->WriteTexture = 1;
}
vtkBYUWriter::~vtkBYUWriter()
{
if ( this->GeometryFileName )
{
delete [] this->GeometryFileName;
}
if ( this->DisplacementFileName )
{
delete [] this->DisplacementFileName;
}
if ( this->ScalarFileName )
{
delete [] this->ScalarFileName;
}
if ( this->TextureFileName )
{
delete [] this->TextureFileName;
}
}
// Write out data in MOVIE.BYU format.
void vtkBYUWriter::WriteData()
{
FILE *geomFp;
vtkPolyData *input= this->GetInput();
int numPts=input->GetNumberOfPoints();
if ( numPts < 1 )
{
vtkErrorMacro(<<"No data to write!");
return;
}
if ((geomFp = fopen(this->GeometryFileName, "w")) == NULL)
{
vtkErrorMacro(<< "Couldn't open geometry file: " << this->GeometryFileName);
return;
}
else
{
this->WriteGeometryFile(geomFp,numPts);
}
this->WriteDisplacementFile(numPts);
this->WriteScalarFile(numPts);
this->WriteTextureFile(numPts);
// Close the file
fclose (geomFp);
}
void vtkBYUWriter::WriteGeometryFile(FILE *geomFile, int numPts)
{
int numPolys, numEdges;
int i;
float *x;
vtkIdType npts;
vtkIdType *pts;
vtkPoints *inPts;
vtkCellArray *inPolys;
vtkPolyData *input= this->GetInput();
//
// Check input
//
inPolys=input->GetPolys();
if ( (inPts=input->GetPoints()) == NULL || inPolys == NULL )
{
vtkErrorMacro(<<"No data to write!");
return;
}
//
// Write header (not using fixed format! - potential problem in some files.)
//
numPolys = input->GetPolys()->GetNumberOfCells();
for (numEdges=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
{
numEdges += npts;
}
fprintf (geomFile, "%d %d %d %d\n", 1, numPts, numPolys, numEdges);
fprintf (geomFile, "%d %d\n", 1, numPolys);
//
// Write data
//
// write point coordinates
for (i=0; i < numPts; i++)
{
x = inPts->GetPoint(i);
fprintf(geomFile, "%e %e %e ", x[0], x[1], x[2]);
if ( (i % 2) )
{
fprintf(geomFile, "\n");
}
}
if ( (numPts % 2) )
{
fprintf(geomFile, "\n");
}
// write poly data. Remember 1-offset.
for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
{
// write this polygon
// treating vtkIdType as int
for (i=0; i < (npts-1); i++)
{
fprintf (geomFile, "%d ", (int)(pts[i]+1));
}
fprintf (geomFile, "%d\n", (int)(-(pts[npts-1]+1)));
}
vtkDebugMacro(<<"Wrote " << numPts << " points, " << numPolys << " polygons");
}
void vtkBYUWriter::WriteDisplacementFile(int numPts)
{
FILE *dispFp;
int i;
float *v;
vtkDataArray *inVectors;
vtkPolyData *input= this->GetInput();
if ( this->WriteDisplacement && this->DisplacementFileName &&
(inVectors = input->GetPointData()->GetVectors()) != NULL )
{
if ( !(dispFp = fopen(this->DisplacementFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open displacement file");
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
v = inVectors->GetTuple(i);
fprintf(dispFp, "%e %e %e", v[0], v[1], v[2]);
if ( (i % 2) )
{
fprintf (dispFp, "\n");
}
}
vtkDebugMacro(<<"Wrote " << numPts << " displacements");
fclose (dispFp);
}
void vtkBYUWriter::WriteScalarFile(int numPts)
{
FILE *scalarFp;
int i;
float s;
vtkDataArray *inScalars;
vtkPolyData *input= this->GetInput();
if ( this->WriteScalar && this->ScalarFileName &&
(inScalars = input->GetPointData()->GetScalars()) != NULL )
{
if ( !(scalarFp = fopen(this->ScalarFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open scalar file");
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
s = inScalars->GetComponent(i,0);
fprintf(scalarFp, "%e ", s);
if ( i != 0 && !(i % 6) )
{
fprintf (scalarFp, "\n");
}
}
fclose (scalarFp);
vtkDebugMacro(<<"Wrote " << numPts << " scalars");
}
void vtkBYUWriter::WriteTextureFile(int numPts)
{
FILE *textureFp;
int i;
float *t;
vtkDataArray *inTCoords;
vtkPolyData *input= this->GetInput();
if ( this->WriteTexture && this->TextureFileName &&
(inTCoords = input->GetPointData()->GetTCoords()) != NULL )
{
if ( !(textureFp = fopen(this->TextureFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open texture file");
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
if ( i != 0 && !(i % 3) )
{
fprintf (textureFp, "\n");
}
t = inTCoords->GetTuple(i);
fprintf(textureFp, "%e %e", t[0], t[1]);
}
fclose (textureFp);
vtkDebugMacro(<<"Wrote " << numPts << " texture coordinates");
}
void vtkBYUWriter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Geometry File Name: "
<< (this->GeometryFileName ? this->GeometryFileName : "(none)") << "\n";
os << indent << "Write Displacement: " << (this->WriteDisplacement ? "On\n" : "Off\n");
os << indent << "Displacement File Name: "
<< (this->DisplacementFileName ? this->DisplacementFileName : "(none)") << "\n";
os << indent << "Write Scalar: " << (this->WriteScalar ? "On\n" : "Off\n");
os << indent << "Scalar File Name: "
<< (this->ScalarFileName ? this->ScalarFileName : "(none)") << "\n";
os << indent << "Write Texture: " << (this->WriteTexture ? "On\n" : "Off\n");
os << indent << "Texture File Name: "
<< (this->TextureFileName ? this->TextureFileName : "(none)") << "\n";
}
<commit_msg>Add error checking<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkBYUWriter.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2002 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 "vtkBYUWriter.h"
#include "vtkObjectFactory.h"
vtkCxxRevisionMacro(vtkBYUWriter, "1.43");
vtkStandardNewMacro(vtkBYUWriter);
// Create object so that it writes displacement, scalar, and texture files
// (if data is available).
vtkBYUWriter::vtkBYUWriter()
{
this->GeometryFileName = NULL;
this->DisplacementFileName = NULL;
this->ScalarFileName = NULL;
this->TextureFileName = NULL;
this->WriteDisplacement = 1;
this->WriteScalar = 1;
this->WriteTexture = 1;
}
vtkBYUWriter::~vtkBYUWriter()
{
if ( this->GeometryFileName )
{
delete [] this->GeometryFileName;
}
if ( this->DisplacementFileName )
{
delete [] this->DisplacementFileName;
}
if ( this->ScalarFileName )
{
delete [] this->ScalarFileName;
}
if ( this->TextureFileName )
{
delete [] this->TextureFileName;
}
}
// Write out data in MOVIE.BYU format.
void vtkBYUWriter::WriteData()
{
FILE *geomFp;
vtkPolyData *input= this->GetInput();
int numPts=input->GetNumberOfPoints();
if ( numPts < 1 )
{
vtkErrorMacro(<<"No data to write!");
return;
}
if ( !this->GeometryFileName )
{
vtkErrorMacro(<< "Geometry file name was not specified");
return;
}
if ((geomFp = fopen(this->GeometryFileName, "w")) == NULL)
{
vtkErrorMacro(<< "Couldn't open geometry file: " << this->GeometryFileName);
return;
}
else
{
this->WriteGeometryFile(geomFp,numPts);
}
this->WriteDisplacementFile(numPts);
this->WriteScalarFile(numPts);
this->WriteTextureFile(numPts);
// Close the file
fclose (geomFp);
}
void vtkBYUWriter::WriteGeometryFile(FILE *geomFile, int numPts)
{
int numPolys, numEdges;
int i;
float *x;
vtkIdType npts;
vtkIdType *pts;
vtkPoints *inPts;
vtkCellArray *inPolys;
vtkPolyData *input= this->GetInput();
//
// Check input
//
inPolys=input->GetPolys();
if ( (inPts=input->GetPoints()) == NULL || inPolys == NULL )
{
vtkErrorMacro(<<"No data to write!");
return;
}
//
// Write header (not using fixed format! - potential problem in some files.)
//
numPolys = input->GetPolys()->GetNumberOfCells();
for (numEdges=0, inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
{
numEdges += npts;
}
fprintf (geomFile, "%d %d %d %d\n", 1, numPts, numPolys, numEdges);
fprintf (geomFile, "%d %d\n", 1, numPolys);
//
// Write data
//
// write point coordinates
for (i=0; i < numPts; i++)
{
x = inPts->GetPoint(i);
fprintf(geomFile, "%e %e %e ", x[0], x[1], x[2]);
if ( (i % 2) )
{
fprintf(geomFile, "\n");
}
}
if ( (numPts % 2) )
{
fprintf(geomFile, "\n");
}
// write poly data. Remember 1-offset.
for (inPolys->InitTraversal(); inPolys->GetNextCell(npts,pts); )
{
// write this polygon
// treating vtkIdType as int
for (i=0; i < (npts-1); i++)
{
fprintf (geomFile, "%d ", (int)(pts[i]+1));
}
fprintf (geomFile, "%d\n", (int)(-(pts[npts-1]+1)));
}
vtkDebugMacro(<<"Wrote " << numPts << " points, " << numPolys << " polygons");
}
void vtkBYUWriter::WriteDisplacementFile(int numPts)
{
FILE *dispFp;
int i;
float *v;
vtkDataArray *inVectors;
vtkPolyData *input= this->GetInput();
if ( this->WriteDisplacement && this->DisplacementFileName &&
(inVectors = input->GetPointData()->GetVectors()) != NULL )
{
if ( !(dispFp = fopen(this->DisplacementFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open displacement file");
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
v = inVectors->GetTuple(i);
fprintf(dispFp, "%e %e %e", v[0], v[1], v[2]);
if ( (i % 2) )
{
fprintf (dispFp, "\n");
}
}
vtkDebugMacro(<<"Wrote " << numPts << " displacements");
fclose (dispFp);
}
void vtkBYUWriter::WriteScalarFile(int numPts)
{
FILE *scalarFp;
int i;
float s;
vtkDataArray *inScalars;
vtkPolyData *input= this->GetInput();
if ( this->WriteScalar && this->ScalarFileName &&
(inScalars = input->GetPointData()->GetScalars()) != NULL )
{
if ( !(scalarFp = fopen(this->ScalarFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open scalar file");
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
s = inScalars->GetComponent(i,0);
fprintf(scalarFp, "%e ", s);
if ( i != 0 && !(i % 6) )
{
fprintf (scalarFp, "\n");
}
}
fclose (scalarFp);
vtkDebugMacro(<<"Wrote " << numPts << " scalars");
}
void vtkBYUWriter::WriteTextureFile(int numPts)
{
FILE *textureFp;
int i;
float *t;
vtkDataArray *inTCoords;
vtkPolyData *input= this->GetInput();
if ( this->WriteTexture && this->TextureFileName &&
(inTCoords = input->GetPointData()->GetTCoords()) != NULL )
{
if ( !(textureFp = fopen(this->TextureFileName, "w")) )
{
vtkErrorMacro (<<"Couldn't open texture file");
return;
}
}
else
{
return;
}
//
// Write data
//
for (i=0; i < numPts; i++)
{
if ( i != 0 && !(i % 3) )
{
fprintf (textureFp, "\n");
}
t = inTCoords->GetTuple(i);
fprintf(textureFp, "%e %e", t[0], t[1]);
}
fclose (textureFp);
vtkDebugMacro(<<"Wrote " << numPts << " texture coordinates");
}
void vtkBYUWriter::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "Geometry File Name: "
<< (this->GeometryFileName ? this->GeometryFileName : "(none)") << "\n";
os << indent << "Write Displacement: " << (this->WriteDisplacement ? "On\n" : "Off\n");
os << indent << "Displacement File Name: "
<< (this->DisplacementFileName ? this->DisplacementFileName : "(none)") << "\n";
os << indent << "Write Scalar: " << (this->WriteScalar ? "On\n" : "Off\n");
os << indent << "Scalar File Name: "
<< (this->ScalarFileName ? this->ScalarFileName : "(none)") << "\n";
os << indent << "Write Texture: " << (this->WriteTexture ? "On\n" : "Off\n");
os << indent << "Texture File Name: "
<< (this->TextureFileName ? this->TextureFileName : "(none)") << "\n";
}
<|endoftext|> |
<commit_before>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "Framework.h"
#include "ModuleManager.h"
#include "ConfigurationManager.h"
namespace fs = boost::filesystem;
namespace Foundation
{
ModuleManager::ModuleManager(Framework *framework) :
framework_(framework)
, DEFAULT_MODULES_PATH(framework->GetDefaultConfig().DeclareSetting("ModuleManager", "Default_Modules_Path", "./modules"))
{
}
ModuleManager::~ModuleManager()
{
}
void ModuleManager::DeclareStaticModule(ModuleInterface *module)
{
assert (module);
if (IsExcluded(module->Name()) == false && HasModule(module) == false)
{
Module::Entry entry = { module, module->Name(), Module::SharedLibraryPtr() };
modules_.push_back(entry);
#ifndef _DEBUG
// make it so debug messages are not logged in release mode
std::string log_level = framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "log_level");
Poco::Logger::get(module->Name()).setLevel(log_level);
#endif
module->SetFramework(framework_);
module->LoadInternal();
} else
{
Foundation::RootLogInfo("Module: " + module->Name() + " is excluded and not loaded.");
}
}
void ModuleManager::LoadAvailableModules()
{
// Find all shared modules and load them
Core::StringVectorPtr files;
try
{
files = GetXmlFiles(DEFAULT_MODULES_PATH);
} catch (Core::Exception)
{
throw Core::Exception("Failed to load modules, modules directory not found."); // can be considered fatal
}
for (size_t i = 0 ; i < files->size() ; ++i)
{
const fs::path path((*files)[i]);
try
{
LoadModule(path, files);
} catch (std::exception &e) // may not be fatal, depending on which module failed
{
Foundation::RootLogError(std::string("Exception: ") + e.what());
Foundation::RootLogError("Failed to load module.");
}
}
}
void ModuleManager::InitializeModules()
{
for (size_t i=0 ; i<modules_.size() ; ++i)
{
PreInitializeModule(modules_[i].module_);
}
for (size_t i=0 ; i<modules_.size() ; ++i)
{
InitializeModule(modules_[i].module_);
}
for (size_t i=0 ; i<modules_.size() ; ++i)
{
PostInitializeModule(modules_[i].module_);
}
}
void ModuleManager::UninitializeModules()
{
for (ModuleVector::reverse_iterator it = modules_.rbegin() ;
it != modules_.rend() ;
++it)
{
UninitializeModule(it->module_);
}
}
void ModuleManager::UpdateModules(Core::f64 frametime)
{
for (size_t i=0 ; i<modules_.size() ; ++i)
{
modules_[i].module_->Update(frametime);
}
}
bool ModuleManager::LoadModuleByName(const std::string &lib, const std::string &module)
{
assert (lib.empty() == false);
assert (module.empty() == false);
Core::StringVector current_modules;
for (size_t i = 0 ; i < modules_.size() ; ++i)
current_modules.push_back(modules_[i].entry_);
Core::StringVectorPtr files = GetXmlFiles(DEFAULT_MODULES_PATH);
for (size_t i = 0 ; i < files->size() ; ++i)
{
fs::path path((*files)[i]);
const fs::path orig_path = path;
path.replace_extension("");
std::string filename = path.filename();
if (filename == lib)
{
LoadModule(orig_path, files);
break;
}
}
for (size_t i = 0 ; i < modules_.size() ; ++i)
{
if (modules_[i].module_->State() == Module::MS_Loaded && std::find(current_modules.begin(), current_modules.end(), modules_[i].entry_) == current_modules.end())
{
modules_[i].module_->PreInitialize();
modules_[i].module_->InitializeInternal();
modules_[i].module_->PostInitialize();
if (modules_[i].entry_ == module)
return true;
}
}
return false;
}
bool ModuleManager::UnloadModuleByName(const std::string &module)
{
for ( ModuleVector::iterator it = modules_.begin() ;
it != modules_.end() ;
++it )
{
if (it->module_->Name() == module)
{
UninitializeModule(it->module_);
UnloadModule(*it);
modules_.erase(it);
return true;
}
}
return false;
}
void ModuleManager::LoadModule(const fs::path &path, Core::StringVectorPtr all_files)
{
assert (path.has_filename());
std::string ext = path.extension();
boost::algorithm::to_lower(ext);
if (ext == ".xml")
{
Foundation::RootLogInfo("Attempting to load module definition file: " + path.file_string());
fs::path modulePath(path);
modulePath.replace_extension("");
Core::StringVector entries;
Core::StringVector dependencies;
Poco::AutoPtr<Poco::Util::XMLConfiguration> config;
try
{
config = new Poco::Util::XMLConfiguration(path.native_directory_string());
Poco::Util::AbstractConfiguration::Keys keys;
config->keys(keys);
for ( Poco::Util::AbstractConfiguration::Keys::const_iterator it = keys.begin() ;
it != keys.end() ;
it++ )
{
if ((*it).find("entry") != std::string::npos)
entries.push_back( config->getString(*it) );
if ((*it).find("dependency") != std::string::npos)
dependencies.push_back( config->getString(*it) );
}
}
catch(std::exception)
{
}
if (entries.empty())
entries.push_back(modulePath.filename());
// Recurse to load dependencies (if any)
for ( Core::StringVector::const_iterator it = dependencies.begin() ;
it != dependencies.end() ; ++it )
{
bool found = false;
// Try to find the dependency from the all module paths list
for (Core::StringVector::const_iterator it2 = all_files->begin();
it2 != all_files->end(); ++it2)
{
if ((*it2).find((*it)) != std::string::npos)
{
const fs::path path((*it2));
LoadModule(path, all_files);
found = true;
}
}
if (!found)
Foundation::RootLogWarning("Failed to find dependency " + *it + ".");
}
// Then load the module itself
LoadModule(modulePath.native_directory_string(), entries);
}
}
void ModuleManager::LoadModule(const std::string &moduleName, const Core::StringVector &entries)
{
assert(moduleName.empty() == false);
std::string path(moduleName);
path.append(Poco::SharedLibrary::suffix());
Module::SharedLibraryPtr library;
// See if shared library is already loaded, and if it is, use it
for ( ModuleVector::const_iterator it = modules_.begin() ;
it != modules_.end() ;
++it )
{
if (it->shared_library_ && it->shared_library_->path_ == path)
{
library = it->shared_library_;
}
}
if (!library)
{
try
{
library = Module::SharedLibraryPtr(new Module::SharedLibrary(path));
} catch (std::exception &e)
{
Foundation::RootLogError(e.what());
Foundation::RootLogError("Failed to load dynamic library: " + moduleName + ".");
return;
}
}
for ( Core::StringVector::const_iterator it = entries.begin() ;
it != entries.end() ;
++it )
{
if (HasModuleEntry(*it))
{
Foundation::RootLogDebug("Module " + *it + " already loaded.");
continue;
}
Foundation::RootLogInfo("Attempting to load module: " + *it + ".");
if (library->cl_.findClass(*it) == NULL)
{
throw Core::Exception("Entry class not found from module.");
}
ModuleInterface* module = library->cl_.create(*it);
if (IsExcluded(module->Name()) == false)
{
assert (HasModule(module) == false);
#ifndef _DEBUG
// make it so debug messages are not logged in release mode
std::string log_level = framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "log_level");
Poco::Logger::get(module->Name()).setLevel(log_level);
#endif
module->SetFramework(framework_);
module->LoadInternal();
Module::Entry entry = { module, *it, library };
modules_.push_back(entry);
Foundation::RootLogInfo("Module " + *it + " loaded.");
} else
{
Foundation::RootLogInfo("Module " + module->Name() + " is excluded and not loaded.");
SAFE_DELETE (module);
}
}
}
void ModuleManager::UnloadModules()
{
for (ModuleVector::reverse_iterator it = modules_.rbegin() ;
it != modules_.rend() ;
++it)
{
UnloadModule(*it);
}
modules_.clear();
assert (modules_.empty());
}
void ModuleManager::PreInitializeModule(ModuleInterface *module)
{
assert(module);
module->PreInitialize();
}
void ModuleManager::InitializeModule(ModuleInterface *module)
{
assert(module);
Foundation::RootLogInfo("Initializing module " + module->Name() + ".");
module->InitializeInternal();
}
void ModuleManager::PostInitializeModule(ModuleInterface *module)
{
assert(module);
module->PostInitialize();
}
void ModuleManager::UninitializeModule(ModuleInterface *module)
{
assert(module);
Foundation::RootLogInfo("Uninitializing module " + module->Name() + ".");
module->UninitializeInternal();
}
void ModuleManager::UnloadModule(Module::Entry &entry)
{
assert(entry.module_);
entry.module_->UnloadInternal();
if (!entry.shared_library_)
{
delete entry.module_;
}
else
{
entry.shared_library_->cl_.destroy(entry.entry_, entry.module_);
SAFE_DELETE(entry.module_);
}
}
bool ModuleManager::HasModule(ModuleInterface *module) const
{
assert (module);
for ( ModuleVector::const_iterator it = modules_.begin() ;
it != modules_.end() ;
++it )
{
if (it->module_->Name() == module->Name())
return true;
}
return false;
}
Core::StringVectorPtr ModuleManager::GetXmlFiles(const std::string &path)
{
Core::StringVectorPtr files(new Core::StringVector);
// Find all xml files recursively
fs::path full_path = fs::system_complete(fs::path(DEFAULT_MODULES_PATH));
if ( !fs::exists( full_path ) || !fs::is_directory( full_path ))
throw Core::Exception("Path not found!"); // can be considered fatal
fs::recursive_directory_iterator iter( full_path );
fs::recursive_directory_iterator end_iter;
for ( ; iter != end_iter ; ++iter )
{
if ( fs::is_regular_file( iter->status() ) )
{
std::string ext = iter->path().extension();
boost::algorithm::to_lower(ext);
if (ext == ".xml")
{
files->push_back(iter->path().string());
}
}
}
return files;
}
}
<commit_msg>[FIX] Cleared out one memory leak --> added UnloadModules() into ModuleManager class destructor. Fix does not clear out all memory leaks. <commit_after>// For conditions of distribution and use, see copyright notice in license.txt
#include "StableHeaders.h"
#include "Framework.h"
#include "ModuleManager.h"
#include "ConfigurationManager.h"
namespace fs = boost::filesystem;
namespace Foundation
{
ModuleManager::ModuleManager(Framework *framework) :
framework_(framework)
, DEFAULT_MODULES_PATH(framework->GetDefaultConfig().DeclareSetting("ModuleManager", "Default_Modules_Path", "./modules"))
{
}
ModuleManager::~ModuleManager()
{
//Unload all loaded modules if object is truely destroyed.
UnloadModules();
}
void ModuleManager::DeclareStaticModule(ModuleInterface *module)
{
assert (module);
if (IsExcluded(module->Name()) == false && HasModule(module) == false)
{
Module::Entry entry = { module, module->Name(), Module::SharedLibraryPtr() };
modules_.push_back(entry);
#ifndef _DEBUG
// make it so debug messages are not logged in release mode
std::string log_level = framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "log_level");
Poco::Logger::get(module->Name()).setLevel(log_level);
#endif
module->SetFramework(framework_);
module->LoadInternal();
} else
{
Foundation::RootLogInfo("Module: " + module->Name() + " is excluded and not loaded.");
}
}
void ModuleManager::LoadAvailableModules()
{
// Find all shared modules and load them
Core::StringVectorPtr files;
try
{
files = GetXmlFiles(DEFAULT_MODULES_PATH);
} catch (Core::Exception)
{
throw Core::Exception("Failed to load modules, modules directory not found."); // can be considered fatal
}
for (size_t i = 0 ; i < files->size() ; ++i)
{
const fs::path path((*files)[i]);
try
{
LoadModule(path, files);
} catch (std::exception &e) // may not be fatal, depending on which module failed
{
Foundation::RootLogError(std::string("Exception: ") + e.what());
Foundation::RootLogError("Failed to load module.");
}
}
}
void ModuleManager::InitializeModules()
{
for (size_t i=0 ; i<modules_.size() ; ++i)
{
PreInitializeModule(modules_[i].module_);
}
for (size_t i=0 ; i<modules_.size() ; ++i)
{
InitializeModule(modules_[i].module_);
}
for (size_t i=0 ; i<modules_.size() ; ++i)
{
PostInitializeModule(modules_[i].module_);
}
}
void ModuleManager::UninitializeModules()
{
for (ModuleVector::reverse_iterator it = modules_.rbegin() ;
it != modules_.rend() ;
++it)
{
UninitializeModule(it->module_);
}
}
void ModuleManager::UpdateModules(Core::f64 frametime)
{
for (size_t i=0 ; i<modules_.size() ; ++i)
{
modules_[i].module_->Update(frametime);
}
}
bool ModuleManager::LoadModuleByName(const std::string &lib, const std::string &module)
{
assert (lib.empty() == false);
assert (module.empty() == false);
Core::StringVector current_modules;
for (size_t i = 0 ; i < modules_.size() ; ++i)
current_modules.push_back(modules_[i].entry_);
Core::StringVectorPtr files = GetXmlFiles(DEFAULT_MODULES_PATH);
for (size_t i = 0 ; i < files->size() ; ++i)
{
fs::path path((*files)[i]);
const fs::path orig_path = path;
path.replace_extension("");
std::string filename = path.filename();
if (filename == lib)
{
LoadModule(orig_path, files);
break;
}
}
for (size_t i = 0 ; i < modules_.size() ; ++i)
{
if (modules_[i].module_->State() == Module::MS_Loaded && std::find(current_modules.begin(), current_modules.end(), modules_[i].entry_) == current_modules.end())
{
modules_[i].module_->PreInitialize();
modules_[i].module_->InitializeInternal();
modules_[i].module_->PostInitialize();
if (modules_[i].entry_ == module)
return true;
}
}
return false;
}
bool ModuleManager::UnloadModuleByName(const std::string &module)
{
for ( ModuleVector::iterator it = modules_.begin() ;
it != modules_.end() ;
++it )
{
if (it->module_->Name() == module)
{
UninitializeModule(it->module_);
UnloadModule(*it);
modules_.erase(it);
return true;
}
}
return false;
}
void ModuleManager::LoadModule(const fs::path &path, Core::StringVectorPtr all_files)
{
assert (path.has_filename());
std::string ext = path.extension();
boost::algorithm::to_lower(ext);
if (ext == ".xml")
{
Foundation::RootLogInfo("Attempting to load module definition file: " + path.file_string());
fs::path modulePath(path);
modulePath.replace_extension("");
Core::StringVector entries;
Core::StringVector dependencies;
Poco::AutoPtr<Poco::Util::XMLConfiguration> config;
try
{
config = new Poco::Util::XMLConfiguration(path.native_directory_string());
Poco::Util::AbstractConfiguration::Keys keys;
config->keys(keys);
for ( Poco::Util::AbstractConfiguration::Keys::const_iterator it = keys.begin() ;
it != keys.end() ;
it++ )
{
if ((*it).find("entry") != std::string::npos)
entries.push_back( config->getString(*it) );
if ((*it).find("dependency") != std::string::npos)
dependencies.push_back( config->getString(*it) );
}
}
catch(std::exception)
{
}
if (entries.empty())
entries.push_back(modulePath.filename());
// Recurse to load dependencies (if any)
for ( Core::StringVector::const_iterator it = dependencies.begin() ;
it != dependencies.end() ; ++it )
{
bool found = false;
// Try to find the dependency from the all module paths list
for (Core::StringVector::const_iterator it2 = all_files->begin();
it2 != all_files->end(); ++it2)
{
if ((*it2).find((*it)) != std::string::npos)
{
const fs::path path((*it2));
LoadModule(path, all_files);
found = true;
}
}
if (!found)
Foundation::RootLogWarning("Failed to find dependency " + *it + ".");
}
// Then load the module itself
LoadModule(modulePath.native_directory_string(), entries);
}
}
void ModuleManager::LoadModule(const std::string &moduleName, const Core::StringVector &entries)
{
assert(moduleName.empty() == false);
std::string path(moduleName);
path.append(Poco::SharedLibrary::suffix());
Module::SharedLibraryPtr library;
// See if shared library is already loaded, and if it is, use it
for ( ModuleVector::const_iterator it = modules_.begin() ;
it != modules_.end() ;
++it )
{
if (it->shared_library_ && it->shared_library_->path_ == path)
{
library = it->shared_library_;
}
}
if (!library)
{
try
{
library = Module::SharedLibraryPtr(new Module::SharedLibrary(path));
} catch (std::exception &e)
{
Foundation::RootLogError(e.what());
Foundation::RootLogError("Failed to load dynamic library: " + moduleName + ".");
return;
}
}
for ( Core::StringVector::const_iterator it = entries.begin() ;
it != entries.end() ;
++it )
{
if (HasModuleEntry(*it))
{
Foundation::RootLogDebug("Module " + *it + " already loaded.");
continue;
}
Foundation::RootLogInfo("Attempting to load module: " + *it + ".");
if (library->cl_.findClass(*it) == NULL)
{
throw Core::Exception("Entry class not found from module.");
}
ModuleInterface* module = library->cl_.create(*it);
if (IsExcluded(module->Name()) == false)
{
assert (HasModule(module) == false);
#ifndef _DEBUG
// make it so debug messages are not logged in release mode
std::string log_level = framework_->GetDefaultConfig().GetString(Framework::ConfigurationGroup(), "log_level");
Poco::Logger::get(module->Name()).setLevel(log_level);
#endif
module->SetFramework(framework_);
module->LoadInternal();
Module::Entry entry = { module, *it, library };
modules_.push_back(entry);
Foundation::RootLogInfo("Module " + *it + " loaded.");
} else
{
Foundation::RootLogInfo("Module " + module->Name() + " is excluded and not loaded.");
SAFE_DELETE (module);
}
}
}
void ModuleManager::UnloadModules()
{
for (ModuleVector::reverse_iterator it = modules_.rbegin() ;
it != modules_.rend() ;
++it)
{
UnloadModule(*it);
}
modules_.clear();
assert (modules_.empty());
}
void ModuleManager::PreInitializeModule(ModuleInterface *module)
{
assert(module);
module->PreInitialize();
}
void ModuleManager::InitializeModule(ModuleInterface *module)
{
assert(module);
Foundation::RootLogInfo("Initializing module " + module->Name() + ".");
module->InitializeInternal();
}
void ModuleManager::PostInitializeModule(ModuleInterface *module)
{
assert(module);
module->PostInitialize();
}
void ModuleManager::UninitializeModule(ModuleInterface *module)
{
assert(module);
Foundation::RootLogInfo("Uninitializing module " + module->Name() + ".");
module->UninitializeInternal();
}
void ModuleManager::UnloadModule(Module::Entry &entry)
{
assert(entry.module_);
entry.module_->UnloadInternal();
if (!entry.shared_library_)
{
delete entry.module_;
}
else
{
entry.shared_library_->cl_.destroy(entry.entry_, entry.module_);
SAFE_DELETE(entry.module_);
}
}
bool ModuleManager::HasModule(ModuleInterface *module) const
{
assert (module);
for ( ModuleVector::const_iterator it = modules_.begin() ;
it != modules_.end() ;
++it )
{
if (it->module_->Name() == module->Name())
return true;
}
return false;
}
Core::StringVectorPtr ModuleManager::GetXmlFiles(const std::string &path)
{
Core::StringVectorPtr files(new Core::StringVector);
// Find all xml files recursively
fs::path full_path = fs::system_complete(fs::path(DEFAULT_MODULES_PATH));
if ( !fs::exists( full_path ) || !fs::is_directory( full_path ))
throw Core::Exception("Path not found!"); // can be considered fatal
fs::recursive_directory_iterator iter( full_path );
fs::recursive_directory_iterator end_iter;
for ( ; iter != end_iter ; ++iter )
{
if ( fs::is_regular_file( iter->status() ) )
{
std::string ext = iter->path().extension();
boost::algorithm::to_lower(ext);
if (ext == ".xml")
{
files->push_back(iter->path().string());
}
}
}
return files;
}
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2004
*
*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
*
* "@(#) $Id: taskStaticContainer.cpp,v 1.14 2006/10/09 09:08:03 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2004-09-27 created
*/
#include <acsContainerServices.h>
#include "taskStaticContainer.h"
#include "taskComponentS.h"
#include <acscomponentImpl.h>
#include <maciContainerServices.h>
#include "taskStaticContainerServices.h"
#ifdef _TASK_LIB
extern "C" PortableServer::Servant ConstructComponent( maci::Handle h,
const char * name,
const char * type,
maci::ContainerServices * containerServices
);
#endif //_TASK_LIB
StaticContainer::StaticContainer():
m_logger(0), services_m(true)
{
}
void StaticContainer::initCORBA(int &argc, char **argv)
{
ACE_TRACE("StaticContainer::initCORBA");
try
{
orb_m = CORBA::ORB_init(argc, argv);
if(orb_m.ptr() == CORBA::ORB::_nil())
return; //TBD: EH
CORBA::Object_var objRootPOA =
orb_m->resolve_initial_references("RootPOA");
poaRoot_m = PortableServer::POA::_narrow(objRootPOA.in());
if (poaRoot_m.ptr() == PortableServer::POA::_nil())
return; //TBD: EH
poaManager_m = poaRoot_m->the_POAManager();
PortableServer::IdAssignmentPolicy_var user_id_policy =
poaRoot_m->create_id_assignment_policy(PortableServer::USER_ID);
CORBA::PolicyList policies;
policies.length(1);
policies[0] = PortableServer::IdAssignmentPolicy::_duplicate(user_id_policy.in());
componentPOA_m = poaRoot_m->create_POA("ContainerPOA",
poaManager_m.in(),
policies);
if (componentPOA_m.ptr() == PortableServer::POA::_nil())
return; //TBD: EH
user_id_policy->destroy();
poaManager_m->activate();
}
catch(...)
{
printf("exception in initCORBA\n");
}
}
/*******************************************************************************************/
void StaticContainer::doneCORBA()
{
ACE_TRACE("StaticContainer::doneCORBA");
try
{
if(poaRoot_m.ptr() != PortableServer::POA::_nil())
{
poaRoot_m->destroy(1, 1);
}
if(orb_m.ptr() != CORBA::ORB::_nil())
{
orb_m->destroy();
}
}
catch(CORBA::Exception &ex)
{
ex._tao_print_exception ("occured in StaticContainer::doneCORBA");
}
catch(...)
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::doneCORBA",
(LM_ERROR, "Unexpected exception"));
}
}
/*******************************************************************************************/
void StaticContainer::init(int argc, char **argv, const char *containerName)
{
if ( containerName!=0 && ACE_OS::strlen(containerName)!=0 )
{
containerName_m = containerName;
}
else
{
ACE_Time_Value tv = ACE_OS::gettimeofday();
char timeBuf[25];
sprintf(timeBuf, "%ld", tv.sec());
containerName_m += "Container-";
containerName_m += timeBuf;
}//if-else
//TBD: container name from cmd line
containerArgv.add(argv[0]);
containerArgv.add(containerName_m.c_str()); //first comes container name
for(int i=1; i<argc; i++)
{
if (ACE_OS::strcmp(argv[i], "-nosvcs") == 0)
{
services_m = false;
}
else
{
containerArgv.add(argv[i]);
ACE_OS::printf("argv[%d]=%s\n", i, argv[i]);
}///if
}//for
try
{
if ((services_m == true) && container_m.init(containerArgv.argc(), containerArgv.argv())==true )
{
container_m.connect(); //error handling
services_m = true;
componentPOA_m = container_m.getContainerPOA();
orb_m = container_m.getContainerORB();
}
else
{
services_m = false;
m_logger = new LoggingProxy(0, 0, 31);
LoggingProxy::init (m_logger);
ACSError::init();
initCORBA(argc, argv);
}//if-else
}
catch(...)
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaicContainer::init", (LM_ERROR, "unknown exception"));
}
}
/***************************************************************************************/
void StaticContainer::done()
{
ACE_TRACE("StaticContainer::done");
if ( services_m == true)
{
/* ACS_DEBUG_PARAM("main", "deactivating the component %s", componentName.c_str());
servant->_remove_ref();
container.deactivateCORBAObject(obj);
*/
container_m.shutdown(CONTAINER_EXIT << 8);
container_m.done();
}
else
{
/* ACS_DEBUG_PARAM("main", "deleting the component %s", argv[1]);
*/
doneCORBA();
m_logger->flush();
LoggingProxy::done();
delete m_logger;
ACS_TRACE("szxsadasdasd");
ACSError::done();
}
}
/*****************************************************************************/
CORBA::Object_ptr StaticContainer::createComponentWithName(const char *name)
{
const char *libname;
if ( ACE_OS::strlen(name) == 0 )
{
#ifndef _TASK_LIB
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponentWithName",
(LM_ERROR, "component could not be created just with name (name of library needed)"));
return CORBA::Object::_nil();
#else
ACE_CString compName = "Component-";
ACE_Time_Value tv = ACE_OS::gettimeofday();
char timeBuf[25];
sprintf(timeBuf, "%ld", tv.sec());
compName+=timeBuf;
libname = 0; // here libray name can be NULL since the library is linked by linker and nota loaded on demand
return createComponent(compName.c_str(), libname);
#endif
}
else
{
// reteive libname from CDB
libname = "SDFSDS";
return createComponent(name, libname);
}
}
/*****************************************************************************/
CORBA::Object_ptr StaticContainer::createComponent(const char *libname)
{
ACE_CString compName = "Component-";
ACE_Time_Value tv = ACE_OS::gettimeofday();
char timeBuf[25];
sprintf(timeBuf, "%ld", tv.sec());
compName+=timeBuf;
return createComponent(compName.c_str(), libname);
}
/*****************************************************************************/
CORBA::Object_ptr StaticContainer::createComponent(const char* compName, const char *libname)
{
CORBA::Object_var obj = CORBA::Object::_nil();
ACE_CString cn = "Component-";
ACE_TRACE("StaticContainer::createComponent");
if ( ACE_OS::strlen(compName)!=0 )
{
#ifndef _TASK_LIB
if (ACE_OS::strlen(libname)==0)
{
if (services_m == true )
{
// try to read libname from CDB
}
else
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponent",
(LM_ERROR, "component could not be created w/o providing library name"));
return obj._retn();
}
}
#endif
}
else
{
#ifndef _TASK_LIB
if (ACE_OS::strlen(libname) == 0 )
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponent",
(LM_ERROR, "component could not be created w/o providing library name"));
return obj._retn();
}
#endif
// create unique component name
ACE_Time_Value tv = ACE_OS::gettimeofday();
char timeBuf[25];
sprintf(timeBuf, "%ld", tv.sec());
cn+=timeBuf;
compName = cn.c_str();
}
#ifndef _TASK_LIB
if (services_m==true) // if we have services (i.e. also the manager) we can create and activate the component by using concept of dynamic component
{
ACS_DEBUG("StaticContainer::createComponent", "Activating component");
ComponentSpec_var compSpec = new ComponentSpec();
compSpec->component_name = CORBA::string_dup(compName);
compSpec->component_type = CORBA::string_dup("IDL:alma/ACS/Task:1.0"); //TBD:: IFR ?
compSpec->component_code = CORBA::string_dup(libname);
compSpec->container_name = CORBA::string_dup(containerName_m.c_str());
/// @todo get_dynamic_component can throw an exception which should be caught!
ComponentInfo_var compInfo =
container_m.getManager()->get_dynamic_component(container_m.getHandle(),
compSpec.in(),
false);
// at this point we have done everything so we can return
return compInfo->reference._retn();
}//if
// otherwise we have to load the library and find ConstructComponent function in the library
ACS_DEBUG_PARAM("StaticContainer::createComponent", "loading library: %s", libname);
ACE_CString strDLLPath(ACE_OS::getenv ("LD_LIBRARY_PATH"));
dllmgr_m.setSearchPath(strDLLPath.c_str());
int libHandle = 0;
libHandle = dllmgr_m.load(libname);
if (libHandle == 0)
{
printf("error loading the library\n");
return 0; // -1;
}
ACS_DEBUG_PARAM("StaticContainer::createComponent", "Library: %s has been loaded", libname);
ConstructComponentFunc ConstructComponent =
(ConstructComponentFunc)(dllmgr_m.getSymbol(libHandle, "ConstructComponent"));
if (ConstructComponent == 0)
{
printf("error finding the constructor for the component\n");
return 0;// -1;
}
#endif //!_TASK_LIB
ACS_DEBUG_PARAM("StaticContainer::createComponent", "Creating component: %s", compName);
ContainerServices* acsCS = 0;
ACE_CString cmpName(compName);
if (services_m == true)
{
acsCS = new MACIContainerServices(0/*handel*/, cmpName, container_m.getContainerPOA().in());
if (acsCS==0)
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::createComponent",
(LM_ERROR, "Error creating the ContainerServices"));
return 0;
}
}
else
{
acsCS = new StaticContainerServices(0/*handel*/, cmpName, container_m.getContainerPOA().in(), orb_m.in());
if (acsCS==0)
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::createComponent",
(LM_ERROR, "Error creating the ContainerServices"));
return 0;
}
}
PortableServer::Servant servant = ConstructComponent(0/*handel*/, compName, "ANY", acsCS);
if (servant == 0)
{
printf("error constructing the component\n");
return 0;// -1;
}
// life cycle
ACS_DEBUG("StaticContainer::createComponent", "Component Life Cycle");
acscomponent::ACSComponentImpl *acsComponent =
dynamic_cast<acscomponent::ACSComponentImpl*>(servant);
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_INITIALIZING);
acsComponent->__initialize();
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_INITIALIZED);
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_OPERATIONAL);
acsComponent->__execute();
ACS_DEBUG("StaticContainer::createComponent", "Activating the component");
try
{
if (services_m==true )
{
obj = container_m.activateCORBAObject(servant, componentName_m.c_str());
}
else
{
PortableServer::ObjectId_var id =
PortableServer::string_to_ObjectId(componentName_m.c_str());
componentPOA_m->activate_object_with_id(id.in(), servant);
obj = componentPOA_m->servant_to_reference(servant);
servant->_remove_ref();
}
}
catch(CORBA::Exception &ex)
{
ex._tao_print_exception ("occured");
return CORBA::Object::_nil();
}
return obj._retn();
}//createComponent
/**************************************************************************************/
void StaticContainer::destroyComponent(CORBA::Object_ptr obj)
{
ACS::ACSComponent_var acscomp;
try
{
acscomp = ACS::ACSComponent::_narrow(obj);
if ( acscomp.ptr() == ACS::ACSComponent::_nil() )
{
}
}
catch(...)
{
}
#ifndef _TASK_LIB
if ( services_m == true )
{
ACE_CString compNam = acscomp->name();
ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "releasing the component %s via the manager", compNam.c_str());
container_m.getManager()->release_component(container_m.getHandle(), acscomp->name());
return;
}
#endif // !_TASK_LIB
PortableServer::Servant servant;
servant = componentPOA_m->reference_to_servant(obj);
// life cycle
ACS_DEBUG("StaticContainer::destroyComponent", "Component Life Cycle");
acscomponent::ACSComponentImpl *acsComponent =
dynamic_cast<acscomponent::ACSComponentImpl*>(servant);
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_DESTROYING);
acsComponent->__cleanUp();
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_DEFUNCT);
// ContainerServices is deleted in the destructor of ComponentImpl
if ( services_m == true)
{
ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "deactivating the component %s", acscomp->name());
container_m.deactivateCORBAObject(obj);
}
else
{
ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "deleting the component %s", acscomp->name());
servant->_remove_ref();
}//if-else
}//destroyComponenet
/*___oOo___*/
<commit_msg>Replaced non portable comparing with _nil() with CORBA::is_nil(x)<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2004
*
*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
*
* "@(#) $Id: taskStaticContainer.cpp,v 1.15 2008/07/15 06:44:51 bjeram Exp $"
*
* who when what
* -------- -------- ----------------------------------------------
* bjeram 2004-09-27 created
*/
#include <acsContainerServices.h>
#include "taskStaticContainer.h"
#include "taskComponentS.h"
#include <acscomponentImpl.h>
#include <maciContainerServices.h>
#include "taskStaticContainerServices.h"
#ifdef _TASK_LIB
extern "C" PortableServer::Servant ConstructComponent( maci::Handle h,
const char * name,
const char * type,
maci::ContainerServices * containerServices
);
#endif //_TASK_LIB
StaticContainer::StaticContainer():
m_logger(0), services_m(true)
{
}
void StaticContainer::initCORBA(int &argc, char **argv)
{
ACE_TRACE("StaticContainer::initCORBA");
try
{
orb_m = CORBA::ORB_init(argc, argv);
if(CORBA::is_nil(orb_m.ptr()))
return; //TBD: EH
CORBA::Object_var objRootPOA =
orb_m->resolve_initial_references("RootPOA");
poaRoot_m = PortableServer::POA::_narrow(objRootPOA.in());
if (CORBA::is_nil(poaRoot_m.ptr()))
return; //TBD: EH
poaManager_m = poaRoot_m->the_POAManager();
PortableServer::IdAssignmentPolicy_var user_id_policy =
poaRoot_m->create_id_assignment_policy(PortableServer::USER_ID);
CORBA::PolicyList policies;
policies.length(1);
policies[0] = PortableServer::IdAssignmentPolicy::_duplicate(user_id_policy.in());
componentPOA_m = poaRoot_m->create_POA("ContainerPOA",
poaManager_m.in(),
policies);
if (CORBA::is_nil(componentPOA_m.ptr()))
return; //TBD: EH
user_id_policy->destroy();
poaManager_m->activate();
}
catch(...)
{
printf("exception in initCORBA\n");
}
}
/*******************************************************************************************/
void StaticContainer::doneCORBA()
{
ACE_TRACE("StaticContainer::doneCORBA");
try
{
if(poaRoot_m.ptr() != PortableServer::POA::_nil())
{
poaRoot_m->destroy(1, 1);
}
if(orb_m.ptr() != CORBA::ORB::_nil())
{
orb_m->destroy();
}
}
catch(CORBA::Exception &ex)
{
ex._tao_print_exception ("occured in StaticContainer::doneCORBA");
}
catch(...)
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::doneCORBA",
(LM_ERROR, "Unexpected exception"));
}
}
/*******************************************************************************************/
void StaticContainer::init(int argc, char **argv, const char *containerName)
{
if ( containerName!=0 && ACE_OS::strlen(containerName)!=0 )
{
containerName_m = containerName;
}
else
{
ACE_Time_Value tv = ACE_OS::gettimeofday();
char timeBuf[25];
sprintf(timeBuf, "%ld", tv.sec());
containerName_m += "Container-";
containerName_m += timeBuf;
}//if-else
//TBD: container name from cmd line
containerArgv.add(argv[0]);
containerArgv.add(containerName_m.c_str()); //first comes container name
for(int i=1; i<argc; i++)
{
if (ACE_OS::strcmp(argv[i], "-nosvcs") == 0)
{
services_m = false;
}
else
{
containerArgv.add(argv[i]);
ACE_OS::printf("argv[%d]=%s\n", i, argv[i]);
}///if
}//for
try
{
if ((services_m == true) && container_m.init(containerArgv.argc(), containerArgv.argv())==true )
{
container_m.connect(); //error handling
services_m = true;
componentPOA_m = container_m.getContainerPOA();
orb_m = container_m.getContainerORB();
}
else
{
services_m = false;
m_logger = new LoggingProxy(0, 0, 31);
LoggingProxy::init (m_logger);
ACSError::init();
initCORBA(argc, argv);
}//if-else
}
catch(...)
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaicContainer::init", (LM_ERROR, "unknown exception"));
}
}
/***************************************************************************************/
void StaticContainer::done()
{
ACE_TRACE("StaticContainer::done");
if ( services_m == true)
{
/* ACS_DEBUG_PARAM("main", "deactivating the component %s", componentName.c_str());
servant->_remove_ref();
container.deactivateCORBAObject(obj);
*/
container_m.shutdown(CONTAINER_EXIT << 8);
container_m.done();
}
else
{
/* ACS_DEBUG_PARAM("main", "deleting the component %s", argv[1]);
*/
doneCORBA();
m_logger->flush();
LoggingProxy::done();
delete m_logger;
ACS_TRACE("szxsadasdasd");
ACSError::done();
}
}
/*****************************************************************************/
CORBA::Object_ptr StaticContainer::createComponentWithName(const char *name)
{
const char *libname;
if ( ACE_OS::strlen(name) == 0 )
{
#ifndef _TASK_LIB
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponentWithName",
(LM_ERROR, "component could not be created just with name (name of library needed)"));
return CORBA::Object::_nil();
#else
ACE_CString compName = "Component-";
ACE_Time_Value tv = ACE_OS::gettimeofday();
char timeBuf[25];
sprintf(timeBuf, "%ld", tv.sec());
compName+=timeBuf;
libname = 0; // here libray name can be NULL since the library is linked by linker and nota loaded on demand
return createComponent(compName.c_str(), libname);
#endif
}
else
{
// reteive libname from CDB
libname = "SDFSDS";
return createComponent(name, libname);
}
}
/*****************************************************************************/
CORBA::Object_ptr StaticContainer::createComponent(const char *libname)
{
ACE_CString compName = "Component-";
ACE_Time_Value tv = ACE_OS::gettimeofday();
char timeBuf[25];
sprintf(timeBuf, "%ld", tv.sec());
compName+=timeBuf;
return createComponent(compName.c_str(), libname);
}
/*****************************************************************************/
CORBA::Object_ptr StaticContainer::createComponent(const char* compName, const char *libname)
{
CORBA::Object_var obj = CORBA::Object::_nil();
ACE_CString cn = "Component-";
ACE_TRACE("StaticContainer::createComponent");
if ( ACE_OS::strlen(compName)!=0 )
{
#ifndef _TASK_LIB
if (ACE_OS::strlen(libname)==0)
{
if (services_m == true )
{
// try to read libname from CDB
}
else
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponent",
(LM_ERROR, "component could not be created w/o providing library name"));
return obj._retn();
}
}
#endif
}
else
{
#ifndef _TASK_LIB
if (ACE_OS::strlen(libname) == 0 )
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticComponenet::createComponent",
(LM_ERROR, "component could not be created w/o providing library name"));
return obj._retn();
}
#endif
// create unique component name
ACE_Time_Value tv = ACE_OS::gettimeofday();
char timeBuf[25];
sprintf(timeBuf, "%ld", tv.sec());
cn+=timeBuf;
compName = cn.c_str();
}
#ifndef _TASK_LIB
if (services_m==true) // if we have services (i.e. also the manager) we can create and activate the component by using concept of dynamic component
{
ACS_DEBUG("StaticContainer::createComponent", "Activating component");
ComponentSpec_var compSpec = new ComponentSpec();
compSpec->component_name = CORBA::string_dup(compName);
compSpec->component_type = CORBA::string_dup("IDL:alma/ACS/Task:1.0"); //TBD:: IFR ?
compSpec->component_code = CORBA::string_dup(libname);
compSpec->container_name = CORBA::string_dup(containerName_m.c_str());
/// @todo get_dynamic_component can throw an exception which should be caught!
ComponentInfo_var compInfo =
container_m.getManager()->get_dynamic_component(container_m.getHandle(),
compSpec.in(),
false);
// at this point we have done everything so we can return
return compInfo->reference._retn();
}//if
// otherwise we have to load the library and find ConstructComponent function in the library
ACS_DEBUG_PARAM("StaticContainer::createComponent", "loading library: %s", libname);
ACE_CString strDLLPath(ACE_OS::getenv ("LD_LIBRARY_PATH"));
dllmgr_m.setSearchPath(strDLLPath.c_str());
int libHandle = 0;
libHandle = dllmgr_m.load(libname);
if (libHandle == 0)
{
printf("error loading the library\n");
return 0; // -1;
}
ACS_DEBUG_PARAM("StaticContainer::createComponent", "Library: %s has been loaded", libname);
ConstructComponentFunc ConstructComponent =
(ConstructComponentFunc)(dllmgr_m.getSymbol(libHandle, "ConstructComponent"));
if (ConstructComponent == 0)
{
printf("error finding the constructor for the component\n");
return 0;// -1;
}
#endif //!_TASK_LIB
ACS_DEBUG_PARAM("StaticContainer::createComponent", "Creating component: %s", compName);
ContainerServices* acsCS = 0;
ACE_CString cmpName(compName);
if (services_m == true)
{
acsCS = new MACIContainerServices(0/*handel*/, cmpName, container_m.getContainerPOA().in());
if (acsCS==0)
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::createComponent",
(LM_ERROR, "Error creating the ContainerServices"));
return 0;
}
}
else
{
acsCS = new StaticContainerServices(0/*handel*/, cmpName, container_m.getContainerPOA().in(), orb_m.in());
if (acsCS==0)
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::createComponent",
(LM_ERROR, "Error creating the ContainerServices"));
return 0;
}
}
PortableServer::Servant servant = ConstructComponent(0/*handel*/, compName, "ANY", acsCS);
if (servant == 0)
{
printf("error constructing the component\n");
return 0;// -1;
}
// life cycle
ACS_DEBUG("StaticContainer::createComponent", "Component Life Cycle");
acscomponent::ACSComponentImpl *acsComponent =
dynamic_cast<acscomponent::ACSComponentImpl*>(servant);
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_INITIALIZING);
acsComponent->__initialize();
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_INITIALIZED);
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_OPERATIONAL);
acsComponent->__execute();
ACS_DEBUG("StaticContainer::createComponent", "Activating the component");
try
{
if (services_m==true )
{
obj = container_m.activateCORBAObject(servant, componentName_m.c_str());
}
else
{
PortableServer::ObjectId_var id =
PortableServer::string_to_ObjectId(componentName_m.c_str());
componentPOA_m->activate_object_with_id(id.in(), servant);
obj = componentPOA_m->servant_to_reference(servant);
servant->_remove_ref();
}
}
catch(CORBA::Exception &ex)
{
ex._tao_print_exception ("occured");
return CORBA::Object::_nil();
}
return obj._retn();
}//createComponent
/**************************************************************************************/
void StaticContainer::destroyComponent(CORBA::Object_ptr obj)
{
ACS::ACSComponent_var acscomp;
try
{
acscomp = ACS::ACSComponent::_narrow(obj);
if ( CORBA::is_nil(acscomp.ptr()) )
{
ACS_LOG(LM_RUNTIME_CONTEXT, "StaticContainer::destroyComponent",
(LM_ERROR, "component narrowed to nil!!"));
}
}
catch(...)
{
}
#ifndef _TASK_LIB
if ( services_m == true )
{
ACE_CString compNam = acscomp->name();
ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "releasing the component %s via the manager", compNam.c_str());
container_m.getManager()->release_component(container_m.getHandle(), acscomp->name());
return;
}
#endif // !_TASK_LIB
PortableServer::Servant servant;
servant = componentPOA_m->reference_to_servant(obj);
// life cycle
ACS_DEBUG("StaticContainer::destroyComponent", "Component Life Cycle");
acscomponent::ACSComponentImpl *acsComponent =
dynamic_cast<acscomponent::ACSComponentImpl*>(servant);
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_DESTROYING);
acsComponent->__cleanUp();
acsComponent->getContainerServices()->getComponentStateManager()->setState(ACS::COMPSTATE_DEFUNCT);
// ContainerServices is deleted in the destructor of ComponentImpl
if ( services_m == true)
{
ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "deactivating the component %s", acscomp->name());
container_m.deactivateCORBAObject(obj);
}
else
{
ACS_DEBUG_PARAM("StaticContainer::destroyComponent", "deleting the component %s", acscomp->name());
servant->_remove_ref();
}//if-else
}//destroyComponenet
/*___oOo___*/
<|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.
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.
=========================================================================*/
#ifndef __otbInverseCosSpectralAngleKernelFunctor_txx
#define __otbInverseCosSpectralAngleKernelFunctor_txx
#include <cmath>
#include <cfloat>
#include "otbInverseCosSpectralAngleKernelFunctor.h"
namespace otb {
InverseCosSpectralAngleKernelFunctor
::InverseCosSpectralAngleKernelFunctor ()
: GenericKernelFunctorBase ()
{
m_Coef = 2.0;
SetValue( "Coef", m_Coef );
}
void
InverseCosSpectralAngleKernelFunctor
::Update ()
{
m_Coef = GetValue<double>( "Coef" );
}
double
InverseCosSpectralAngleKernelFunctor
::operator()( const svm_node * x, const svm_node * y,
const svm_parameter & param ) const
{
double mq = m_Coef + SAM( x, y );
if ( mq == 0.0 )
return DBL_MAX;
return 1.0 / sqrt( mq );
}
double
InverseCosSpectralAngleKernelFunctor
::SAM ( const svm_node * x, const svm_node * y ) const
{
double den = dot(x,x) * dot(y,y);
if ( den <= 0.0 )
return 0.0;
double ss = dot(x,y);
return /*acos*/( ss / sqrt( den ) );
}
}
#endif
<commit_msg>ENH: inverse cos SAM real computation<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.
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.
=========================================================================*/
#ifndef __otbInverseCosSpectralAngleKernelFunctor_txx
#define __otbInverseCosSpectralAngleKernelFunctor_txx
#include <cmath>
#include <cfloat>
#include "otbInverseCosSpectralAngleKernelFunctor.h"
namespace otb {
InverseCosSpectralAngleKernelFunctor
::InverseCosSpectralAngleKernelFunctor ()
: GenericKernelFunctorBase ()
{
m_Coef = 1.0;
SetValue( "Coef", m_Coef );
}
void
InverseCosSpectralAngleKernelFunctor
::Update ()
{
m_Coef = GetValue<double>( "Coef" );
}
double
InverseCosSpectralAngleKernelFunctor
::operator()( const svm_node * x, const svm_node * y,
const svm_parameter & param ) const
{
double mq = m_Coef - vcl_cos( SAM( x, y ));
if ( mq == 0.0 )
return DBL_MAX;
return 1.0 / sqrt( mq );
}
double
InverseCosSpectralAngleKernelFunctor
::SAM ( const svm_node * x, const svm_node * y ) const
{
double den = dot(x,x) * dot(y,y);
if ( den <= 0.0 )
return 0.0;
double ss = dot(x,y);
return /*acos*/( ss / sqrt( den ) );
}
}
#endif
<|endoftext|> |
<commit_before>#include "Result.h"
#include "ResultText.h"
#include "MonsterFadeInEffect.h"
#include "../../Button/ButtonManager.h"
#include "../../Drawable/DrawableAssetTexture.h"
#include "../../Button/TextureAssetButton.h"
using namespace scene::result;
scene::result::Result::Result()
{
}
void Result::init()
{
auto changeScene = [this](String sceneName) {
SoundAsset(L"Result_ButtonSE").play();
(this->*&Scene::changeScene)(sceneName, 500, false);
ButtonManager::clearAll();
SoundAsset(L"Result_BGM").stop();
};
// {^̏
ButtonManager::clearAll();
ButtonManager::update();
std::shared_ptr<TextureAssetButton> button;
button = std::make_shared<TextureAssetButton>(Vec2(300, 610), L"Result_RetryButton", [changeScene]() {
changeScene(L"Battle");
});
ButtonManager::add(button);
drawables_m.add(button, 2);
button = std::make_shared<TextureAssetButton>(Vec2(980, 610), L"Result_TitleButton", [changeScene]() {
changeScene(L"Title");
});
ButtonManager::add(button);
drawables_m.add(button, 2);
// wi̐ݒ
drawables_m.add(std::make_shared<DrawableAssetTexture>(L"Result_Background", Window::Center()), 0);
// eLXg̏
int numOfdefeatedEnemy = static_cast<int>(m_data->defeatedEnemyList.size());
int remainingTime = m_data->time;
drawables_m.add(std::make_shared<DrawableAssetTexture>(L"Result_Logo", Window::Center().moveBy(0, -230), 0.7), 3);
drawables_m.add(std::make_shared<ResultText>(L"|G: ", L"Result_Font", Window::Center().moveBy(-50, -80)), 3);
enemyNum_m = std::make_shared<ResultText>(Format(numOfdefeatedEnemy), L"Result_Font", Window::Center().moveBy(150, -80));
drawables_m.add(enemyNum_m, 3);
enemyNum_m->hide();
drawables_m.add(std::make_shared<ResultText>(L"c莞: ", L"Result_Font", Window::Center().moveBy(-50, 20)), 3);
drawables_m.add(std::make_shared<ResultText>(Format(remainingTime / 100, L".", Pad(remainingTime % 100, {2, L'0'})), L"Result_Font", Window::Center().moveBy(150, 20)), 3);
score_m = std::make_shared<ResultText>(Format(numOfdefeatedEnemy, L" ~ 100 + ", remainingTime , L" = ", numOfdefeatedEnemy * 100 + remainingTime), L"Result_Font", Window::Center().moveBy(0, 120));
drawables_m.add(score_m, 3);
score_m->hide();
// ^C}[n
stopwatch_m.start();
// BGMĐ
SoundAsset(L"Result_BGM").play();
}
void Result::update()
{
static int counter = 0;
// GtFNg
if(counter < m_data->defeatedEnemyList.size()) {
if(stopwatch_m.elapsed() >= 150ms) {
effect_m.add<MonsterFadeInEffect>(TextureAsset(Format(L"Enemy", m_data->defeatedEnemyList[counter])));
stopwatch_m.restart();
++counter;
}
}
else {
if(effect_m.num_effects == 0) {
enemyNum_m->show();
score_m->show();
stopwatch_m.reset();
counter = 0;
}
}
}
void Result::draw() const
{
drawables_m.drawAll();
effect_m.update();
}<commit_msg>残り時間表示を修正<commit_after>#include "Result.h"
#include "ResultText.h"
#include "MonsterFadeInEffect.h"
#include "../../Button/ButtonManager.h"
#include "../../Drawable/DrawableAssetTexture.h"
#include "../../Button/TextureAssetButton.h"
using namespace scene::result;
scene::result::Result::Result()
{
}
void Result::init()
{
auto changeScene = [this](String sceneName) {
SoundAsset(L"Result_ButtonSE").play();
(this->*&Scene::changeScene)(sceneName, 500, false);
ButtonManager::clearAll();
SoundAsset(L"Result_BGM").stop();
};
// {^̏
ButtonManager::clearAll();
ButtonManager::update();
std::shared_ptr<TextureAssetButton> button;
button = std::make_shared<TextureAssetButton>(Vec2(300, 610), L"Result_RetryButton", [changeScene]() {
changeScene(L"Battle");
});
ButtonManager::add(button);
drawables_m.add(button, 2);
button = std::make_shared<TextureAssetButton>(Vec2(980, 610), L"Result_TitleButton", [changeScene]() {
changeScene(L"Title");
});
ButtonManager::add(button);
drawables_m.add(button, 2);
// wi̐ݒ
drawables_m.add(std::make_shared<DrawableAssetTexture>(L"Result_Background", Window::Center()), 0);
// eLXg̏
int numOfdefeatedEnemy = static_cast<int>(m_data->defeatedEnemyList.size());
int remainingTime = m_data->time;
drawables_m.add(std::make_shared<DrawableAssetTexture>(L"Result_Logo", Window::Center().moveBy(0, -230), 0.7), 3);
drawables_m.add(std::make_shared<ResultText>(L"|G: ", L"Result_Font", Window::Center().moveBy(-50, -80)), 3);
enemyNum_m = std::make_shared<ResultText>(Format(numOfdefeatedEnemy), L"Result_Font", Window::Center().moveBy(150, -80));
drawables_m.add(enemyNum_m, 3);
enemyNum_m->hide();
drawables_m.add(std::make_shared<ResultText>(L"c莞: ", L"Result_Font", Window::Center().moveBy(-50, 20)), 3);
if(remainingTime == 0) {
drawables_m.add(std::make_shared<ResultText>(L"0", L"Result_Font", Window::Center().moveBy(150, 20)), 3);
}
else {
drawables_m.add(std::make_shared<ResultText>(Format(remainingTime / 100, L".", Pad(remainingTime % 100, {2, L'0'})), L"Result_Font", Window::Center().moveBy(150, 20)), 3);
}
score_m = std::make_shared<ResultText>(Format(numOfdefeatedEnemy, L" ~ 100 + ", remainingTime , L" = ", numOfdefeatedEnemy * 100 + remainingTime), L"Result_Font", Window::Center().moveBy(0, 120));
drawables_m.add(score_m, 3);
score_m->hide();
// ^C}[n
stopwatch_m.start();
// BGMĐ
SoundAsset(L"Result_BGM").play();
}
void Result::update()
{
static int counter = 0;
// GtFNg
if(counter < m_data->defeatedEnemyList.size()) {
if(stopwatch_m.elapsed() >= 150ms) {
effect_m.add<MonsterFadeInEffect>(TextureAsset(Format(L"Enemy", m_data->defeatedEnemyList[counter])));
stopwatch_m.restart();
++counter;
}
}
else {
if(effect_m.num_effects == 0) {
enemyNum_m->show();
score_m->show();
stopwatch_m.reset();
counter = 0;
}
}
}
void Result::draw() const
{
drawables_m.drawAll();
effect_m.update();
}<|endoftext|> |
<commit_before>/*
Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
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 of J.D. Koftinoff Software, Ltd. 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.
*/
#pragma once
#include "jdksavdecc-c/include/jdksavdecc.h"
#include "jdksavdecc-c/include/jdksavdecc_print.h"
#include "jdksavdecc-c/include/jdksavdecc_pdu_print.h"
#if defined(__AVR__)
#include "SPI.h"
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
return millis();
}
#elif defined(__APPLE__) || defined(__linux__)
#include <sys/time.h>
#include <iostream>
#include <iomanip>
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
timeval tv;
gettimeofday(&tv,0);
return jdksavdecc_timestamp_in_milliseconds(tv.tv_usec/1000) +
jdksavdecc_timestamp_in_milliseconds(tv.tv_sec*1000);
}
#elif defined(WIN32)
#include <iostream>
#include <iomanip>
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
return jdksavdecc_timestamp_in_milliseconds(GetTickCount());
}
#endif
#if defined(__AVR__)
extern "C" {
void avr_debug_log(const char *str, uint16_t v );
}
#endif
<commit_msg>Add jdks include to top level<commit_after>/*
Copyright (c) 2014, J.D. Koftinoff Software, Ltd.
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 of J.D. Koftinoff Software, Ltd. 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.
*/
#pragma once
#include "jdksavdecc-c/include/jdksavdecc.h"
#include "jdksavdecc-c/include/jdksavdecc_jdks.h"
#include "jdksavdecc-c/include/jdksavdecc_print.h"
#include "jdksavdecc-c/include/jdksavdecc_pdu_print.h"
#if defined(__AVR__)
#include "SPI.h"
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
return millis();
}
#elif defined(__APPLE__) || defined(__linux__)
#include <sys/time.h>
#include <iostream>
#include <iomanip>
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
timeval tv;
gettimeofday(&tv,0);
return jdksavdecc_timestamp_in_milliseconds(tv.tv_usec/1000) +
jdksavdecc_timestamp_in_milliseconds(tv.tv_sec*1000);
}
#elif defined(WIN32)
#include <iostream>
#include <iomanip>
inline jdksavdecc_timestamp_in_milliseconds GetTimeInMs() {
return jdksavdecc_timestamp_in_milliseconds(GetTickCount());
}
#endif
#if defined(__AVR__)
extern "C" {
void avr_debug_log(const char *str, uint16_t v );
}
#endif
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractEdges.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkExtractEdges.h"
#include "vtkEdgeTable.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"
//-------------------------------------------------------------------------
vtkExtractEdges* vtkExtractEdges::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkExtractEdges");
if(ret)
{
return (vtkExtractEdges*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkExtractEdges;
}
// Construct object.
vtkExtractEdges::vtkExtractEdges()
{
this->Locator = NULL;
}
vtkExtractEdges::~vtkExtractEdges()
{
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
}
// Generate feature edges for mesh
void vtkExtractEdges::Execute()
{
vtkDataSet *input= this->GetInput();
vtkPolyData *output= this->GetOutput();
vtkPoints *newPts;
vtkCellArray *newLines;
vtkIdType numCells, cellNum, numPts, newId;
int edgeNum, numEdgePts, numCellEdges;
int i;
vtkIdType pts[2];
vtkIdType pt1 = 0, pt2;
float *x;
vtkEdgeTable *edgeTable;
vtkCell *cell, *edge;
vtkPointData *pd, *outPD;
vtkCellData *cd, *outCD;
vtkDebugMacro(<<"Executing edge extractor");
// Check input
//
numPts=input->GetNumberOfPoints();
if ( (numCells=input->GetNumberOfCells()) < 1 || numPts < 1 )
{
vtkErrorMacro(<<"No input data!");
return;
}
// Set up processing
//
edgeTable = vtkEdgeTable::New();
edgeTable->InitEdgeInsertion(numPts);
newPts = vtkPoints::New();
newPts->Allocate(numPts);
newLines = vtkCellArray::New();
newLines->EstimateSize(numPts*4,2);
pd = input->GetPointData();
outPD = output->GetPointData();
outPD->CopyAllocate(pd,numPts);
cd = input->GetCellData();
outCD = output->GetCellData();
outCD->CopyAllocate(cd,numCells);
// Get our locator for merging points
//
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (newPts, input->GetBounds());
// Loop over all cells, extracting non-visited edges.
//
for (cellNum=0; cellNum < numCells; cellNum++ )
{
if ( ! (cellNum % 10000) ) //manage progress reports / early abort
{
this->UpdateProgress ((float)cellNum / numCells);
if ( this->GetAbortExecute() )
{
break;
}
}
cell = input->GetCell(cellNum);
numCellEdges = cell->GetNumberOfEdges();
for (edgeNum=0; edgeNum < numCellEdges; edgeNum++ )
{
edge = cell->GetEdge(edgeNum);
numEdgePts = edge->GetNumberOfPoints();
for ( i=0; i < numEdgePts; i++, pt1=pt2, pts[0]=pts[1] )
{
pt2 = edge->PointIds->GetId(i);
x = input->GetPoint(pt2);
if ( this->Locator->InsertUniquePoint(x, pts[1]) )
{
outPD->CopyData (pd,pt2,pts[1]);
}
if ( i > 0 && edgeTable->IsEdge(pt1,pt2) == -1 )
{
edgeTable->InsertEdge(pt1, pt2);
newId = newLines->InsertNextCell(2,pts);
outCD->CopyData(cd, cellNum, newId);
}
}
}//for all edges of cell
}//for all cells
vtkDebugMacro(<<"Created " << newLines->GetNumberOfCells() << " edges");
// Update ourselves.
//
edgeTable->Delete();
output->SetPoints(newPts);
newPts->Delete();
output->SetLines(newLines);
newLines->Delete();
output->Squeeze();
}
// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
void vtkExtractEdges::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkExtractEdges::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
void vtkExtractEdges::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyDataFilter::PrintSelf(os,indent);
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
unsigned long int vtkExtractEdges::GetMTime()
{
unsigned long mTime=this-> vtkDataSetToPolyDataFilter::GetMTime();
unsigned long time;
if ( this->Locator != NULL )
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
<commit_msg>ENH:Updated GetCell method for thread safety<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkExtractEdges.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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 "vtkExtractEdges.h"
#include "vtkEdgeTable.h"
#include "vtkMergePoints.h"
#include "vtkObjectFactory.h"
//-------------------------------------------------------------------------
vtkExtractEdges* vtkExtractEdges::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkExtractEdges");
if(ret)
{
return (vtkExtractEdges*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkExtractEdges;
}
// Construct object.
vtkExtractEdges::vtkExtractEdges()
{
this->Locator = NULL;
}
vtkExtractEdges::~vtkExtractEdges()
{
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
}
// Generate feature edges for mesh
void vtkExtractEdges::Execute()
{
vtkDataSet *input= this->GetInput();
vtkPolyData *output= this->GetOutput();
vtkPoints *newPts;
vtkCellArray *newLines;
vtkIdType numCells, cellNum, numPts, newId;
int edgeNum, numEdgePts, numCellEdges;
int i;
vtkIdType pts[2];
vtkIdType pt1 = 0, pt2;
float *x;
vtkEdgeTable *edgeTable;
vtkGenericCell *cell;
vtkCell *edge;
vtkPointData *pd, *outPD;
vtkCellData *cd, *outCD;
vtkDebugMacro(<<"Executing edge extractor");
// Check input
//
numPts=input->GetNumberOfPoints();
if ( (numCells=input->GetNumberOfCells()) < 1 || numPts < 1 )
{
vtkErrorMacro(<<"No input data!");
return;
}
// Set up processing
//
edgeTable = vtkEdgeTable::New();
edgeTable->InitEdgeInsertion(numPts);
newPts = vtkPoints::New();
newPts->Allocate(numPts);
newLines = vtkCellArray::New();
newLines->EstimateSize(numPts*4,2);
pd = input->GetPointData();
outPD = output->GetPointData();
outPD->CopyAllocate(pd,numPts);
cd = input->GetCellData();
outCD = output->GetCellData();
outCD->CopyAllocate(cd,numCells);
cell = vtkGenericCell::New();
// Get our locator for merging points
//
if ( this->Locator == NULL )
{
this->CreateDefaultLocator();
}
this->Locator->InitPointInsertion (newPts, input->GetBounds());
// Loop over all cells, extracting non-visited edges.
//
for (cellNum=0; cellNum < numCells; cellNum++ )
{
if ( ! (cellNum % 10000) ) //manage progress reports / early abort
{
this->UpdateProgress ((float)cellNum / numCells);
if ( this->GetAbortExecute() )
{
break;
}
}
input->GetCell(cellNum,cell);
numCellEdges = cell->GetNumberOfEdges();
for (edgeNum=0; edgeNum < numCellEdges; edgeNum++ )
{
edge = cell->GetEdge(edgeNum);
numEdgePts = edge->GetNumberOfPoints();
for ( i=0; i < numEdgePts; i++, pt1=pt2, pts[0]=pts[1] )
{
pt2 = edge->PointIds->GetId(i);
x = input->GetPoint(pt2);
if ( this->Locator->InsertUniquePoint(x, pts[1]) )
{
outPD->CopyData (pd,pt2,pts[1]);
}
if ( i > 0 && edgeTable->IsEdge(pt1,pt2) == -1 )
{
edgeTable->InsertEdge(pt1, pt2);
newId = newLines->InsertNextCell(2,pts);
outCD->CopyData(cd, cellNum, newId);
}
}
}//for all edges of cell
}//for all cells
vtkDebugMacro(<<"Created " << newLines->GetNumberOfCells() << " edges");
// Update ourselves.
//
edgeTable->Delete();
cell->Delete();
output->SetPoints(newPts);
newPts->Delete();
output->SetLines(newLines);
newLines->Delete();
output->Squeeze();
}
// Specify a spatial locator for merging points. By
// default an instance of vtkMergePoints is used.
void vtkExtractEdges::SetLocator(vtkPointLocator *locator)
{
if ( this->Locator == locator )
{
return;
}
if ( this->Locator )
{
this->Locator->UnRegister(this);
this->Locator = NULL;
}
if ( locator )
{
locator->Register(this);
}
this->Locator = locator;
this->Modified();
}
void vtkExtractEdges::CreateDefaultLocator()
{
if ( this->Locator == NULL )
{
this->Locator = vtkMergePoints::New();
}
}
void vtkExtractEdges::PrintSelf(ostream& os, vtkIndent indent)
{
vtkDataSetToPolyDataFilter::PrintSelf(os,indent);
if ( this->Locator )
{
os << indent << "Locator: " << this->Locator << "\n";
}
else
{
os << indent << "Locator: (none)\n";
}
}
unsigned long int vtkExtractEdges::GetMTime()
{
unsigned long mTime=this-> vtkDataSetToPolyDataFilter::GetMTime();
unsigned long time;
if ( this->Locator != NULL )
{
time = this->Locator->GetMTime();
mTime = ( time > mTime ? time : mTime );
}
return mTime;
}
<|endoftext|> |
<commit_before>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <[email protected]>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "Prague/Sys/Signal.hh"
#include "Prague/IPC/Dispatcher.hh"
#include <queue>
#include <algorithm>
#include <ctime>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
using namespace Prague;
Dispatcher *Dispatcher::dispatcher = 0;
Mutex Dispatcher::singletonMutex;
Dispatcher::Cleaner Dispatcher::cleaner;
struct SignalNotifier : Signal::Notifier
{
virtual void notify(int signum)
{
cerr << Signal::name(signum) << endl;
exit(1);
}
};
Dispatcher::Cleaner::~Cleaner()
{
// MutexGuard guard(singletonMutex);
delete dispatcher;
}
Dispatcher *Dispatcher::instance()
{
MutexGuard guard(singletonMutex);
if (!dispatcher) dispatcher = new Dispatcher;
return dispatcher;
}
Dispatcher::Dispatcher()
//. create a queue of up to 64 tasks
//. and a thread pool with 16 threads
: notifier(new SignalNotifier),
tasks(64),
workers(tasks, acceptor, 4),
server(&Dispatcher::dispatch, this)
{
Signal::mask(Signal::pipe);
Signal::set(Signal::hangup, notifier);
Signal::set(Signal::interrupt, notifier);
Signal::set(Signal::quit, notifier);
Signal::set(Signal::illegal, notifier);
Signal::set(Signal::abort, notifier);
Signal::set(Signal::fpe, notifier);
Signal::set(Signal::bus, notifier);
// Signal::set(Signal::segv, notifier);
Signal::set(Signal::iotrap, notifier);
Signal::set(Signal::terminate, notifier);
}
Dispatcher::~Dispatcher()
{
}
void Dispatcher::bind(int fd, Agent *agent, Agent::iomask_t mask)
{
if (server.state() != Thread::running)
{
pipe(wakeup);
rfds.set(wakeup[0]);
server.start();
}
// Signal::Guard sguard(Signal::child);
MutexGuard guard(mutex);
if (find(agents.begin(), agents.end(), agent) == agents.end())
agents.push_back(agent);
if (mask & Agent::in)
{
if (mask & Agent::inready)
{
wfds.set(fd);
if (wchannel.find(fd) == wchannel.end()) wchannel[fd] = task(fd, agent, Agent::inready);
else cerr << "Dispatcher::bind() : Error : file descriptor already in use" << endl;
}
if (mask & Agent::inexc)
{
xfds.set(fd);
if (xchannel.find(fd) == xchannel.end()) xchannel[fd] = task(fd, agent, Agent::inexc);
}
}
if (mask & Agent::out)
{
if (mask & Agent::outready)
{
rfds.set(fd);
if (rchannel.find(fd) == rchannel.end()) rchannel[fd] = task(fd, agent, Agent::outready);
else cerr << "Dispatcher::bind() : Error : file descriptor already in use" << endl;
}
if (mask & Agent::outexc)
{
xfds.set(fd);
if (xchannel.find(fd) == xchannel.end()) xchannel[fd] = task(fd, agent, Agent::outexc);
}
}
if (mask & Agent::err)
{
if (mask & Agent::errready)
{
rfds.set(fd);
if (rchannel.find(fd) == rchannel.end()) rchannel[fd] = task(fd, agent, Agent::errready);
else cerr << "Dispatcher::bind() : Error : file descriptor already in use" << endl;
}
if (mask & Agent::errexc)
{
xfds.set(fd);
if (xchannel.find(fd) == xchannel.end()) xchannel[fd] = task(fd, agent, Agent::errexc);
}
}
}
void Dispatcher::release(int fd)
{
MutexGuard guard(mutex);
dictionary_t::iterator c;
if ((c = rchannel.find(fd)) != rchannel.end())
{
rchannel.erase(c);
rfds.clear(fd);
}
if ((c = wchannel.find(fd)) != wchannel.end())
{
wchannel.erase(c);
wfds.clear(fd);
}
if ((c = xchannel.find(fd)) != xchannel.end())
{
xchannel.erase(c);
xfds.clear(fd);
}
}
void Dispatcher::release(Agent *agent)
{
// Signal::Guard guard(Signal::child);
MutexGuard guard(mutex);
for (dictionary_t::iterator i = rchannel.begin(); i != rchannel.end(); i++)
if ((*i).second.agent == agent) rchannel.erase(i);
for (dictionary_t::iterator i = wchannel.begin(); i != wchannel.end(); i++)
if ((*i).second.agent == agent) wchannel.erase(i);
for (dictionary_t::iterator i = xchannel.begin(); i != xchannel.end(); i++)
if ((*i).second.agent == agent) xchannel.erase(i);
alist_t::iterator i = find(agents.begin(), agents.end(), agent);
if (i != agents.end()) agents.erase(i);
}
void *Dispatcher::dispatch(void *X)
{
Dispatcher *dispatcher = reinterpret_cast<Dispatcher *>(X);
dispatcher->workers.start();
do dispatcher->wait();
while (true);
return 0;
};
void Dispatcher::process(const task &t)
{
if (t.agent->processIO(t.fd, t.mask)) activate(t);
}
void Dispatcher::deactivate(const task &t)
{
switch (t.mask)
{
case Agent::inready: wfds.clear(t.fd); break;
case Agent::outready:
case Agent::errready: rfds.clear(t.fd); break;
case Agent::inexc:
case Agent::outexc:
case Agent::errexc: xfds.clear(t.fd); break;
default: break;
}
}
void Dispatcher::activate(const task &t)
{
switch (t.mask)
{
case Agent::inready: wfds.set(t.fd); break;
case Agent::outready:
case Agent::errready: rfds.set(t.fd); break;
case Agent::inexc:
case Agent::outexc:
case Agent::errexc: xfds.set(t.fd); break;
default: break;
}
char *c = "c";
write(wakeup[1], c, 1);
}
void Dispatcher::wait()
{
FdSet tmprfds = rfds;
FdSet tmpwfds = wfds;
FdSet tmpxfds = xfds;
unsigned int fdsize = max(max(tmprfds.max(), tmpwfds.max()), tmpxfds.max()) + 1;
int nsel = select(fdsize, tmprfds, tmpwfds, tmpxfds, 0);
if (nsel == -1)
{
if (errno == EINTR || errno == EAGAIN) errno = 0;
}
else if (nsel > 0 && fdsize)
{
tlist_t t;
for (dictionary_t::iterator i = rchannel.begin(); i != rchannel.end(); i++)
if (tmprfds.isset((*i).first))
{
t.push_back((*i).second);
deactivate((*i).second);
}
for (dictionary_t::iterator i = wchannel.begin(); i != wchannel.end(); i++)
if (tmpwfds.isset((*i).first))
{
t.push_back((*i).second);
deactivate((*i).second);
}
for (dictionary_t::iterator i = xchannel.begin(); i != xchannel.end(); i++)
if (tmpxfds.isset((*i).first))
{
t.push_back((*i).second);
deactivate((*i).second);
}
if (tmprfds.isset(wakeup[0]))
{
char c[1];
read(wakeup[0],c,1);
}
for (tlist_t::const_iterator i = t.begin(); i != t.end(); i++)
tasks.push(*i);
}
};
<commit_msg>added cancelation point (work around linux/thread bug)<commit_after>/*$Id$
*
* This source file is a part of the Berlin Project.
* Copyright (C) 1999 Stefan Seefeld <[email protected]>
* http://www.berlin-consortium.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include "Prague/Sys/Signal.hh"
#include "Prague/IPC/Dispatcher.hh"
#include <queue>
#include <algorithm>
#include <ctime>
#include <cerrno>
#include <unistd.h>
#include <sys/types.h>
using namespace Prague;
Dispatcher *Dispatcher::dispatcher = 0;
Mutex Dispatcher::singletonMutex;
Dispatcher::Cleaner Dispatcher::cleaner;
struct SignalNotifier : Signal::Notifier
{
virtual void notify(int signum)
{
cerr << Signal::name(signum) << endl;
exit(1);
}
};
Dispatcher::Cleaner::~Cleaner()
{
// MutexGuard guard(singletonMutex);
delete dispatcher;
}
Dispatcher *Dispatcher::instance()
{
MutexGuard guard(singletonMutex);
if (!dispatcher) dispatcher = new Dispatcher;
return dispatcher;
}
Dispatcher::Dispatcher()
//. create a queue of up to 64 tasks
//. and a thread pool with 16 threads
: notifier(new SignalNotifier),
tasks(64),
workers(tasks, acceptor, 4),
server(&Dispatcher::dispatch, this)
{
Signal::mask(Signal::pipe);
Signal::set(Signal::hangup, notifier);
Signal::set(Signal::interrupt, notifier);
Signal::set(Signal::quit, notifier);
Signal::set(Signal::illegal, notifier);
Signal::set(Signal::abort, notifier);
Signal::set(Signal::fpe, notifier);
Signal::set(Signal::bus, notifier);
// Signal::set(Signal::segv, notifier);
Signal::set(Signal::iotrap, notifier);
Signal::set(Signal::terminate, notifier);
}
Dispatcher::~Dispatcher()
{
}
void Dispatcher::bind(int fd, Agent *agent, Agent::iomask_t mask)
{
if (server.state() != Thread::running)
{
pipe(wakeup);
rfds.set(wakeup[0]);
server.start();
}
// Signal::Guard sguard(Signal::child);
MutexGuard guard(mutex);
if (find(agents.begin(), agents.end(), agent) == agents.end())
agents.push_back(agent);
if (mask & Agent::in)
{
if (mask & Agent::inready)
{
wfds.set(fd);
if (wchannel.find(fd) == wchannel.end()) wchannel[fd] = task(fd, agent, Agent::inready);
else cerr << "Dispatcher::bind() : Error : file descriptor already in use" << endl;
}
if (mask & Agent::inexc)
{
xfds.set(fd);
if (xchannel.find(fd) == xchannel.end()) xchannel[fd] = task(fd, agent, Agent::inexc);
}
}
if (mask & Agent::out)
{
if (mask & Agent::outready)
{
rfds.set(fd);
if (rchannel.find(fd) == rchannel.end()) rchannel[fd] = task(fd, agent, Agent::outready);
else cerr << "Dispatcher::bind() : Error : file descriptor already in use" << endl;
}
if (mask & Agent::outexc)
{
xfds.set(fd);
if (xchannel.find(fd) == xchannel.end()) xchannel[fd] = task(fd, agent, Agent::outexc);
}
}
if (mask & Agent::err)
{
if (mask & Agent::errready)
{
rfds.set(fd);
if (rchannel.find(fd) == rchannel.end()) rchannel[fd] = task(fd, agent, Agent::errready);
else cerr << "Dispatcher::bind() : Error : file descriptor already in use" << endl;
}
if (mask & Agent::errexc)
{
xfds.set(fd);
if (xchannel.find(fd) == xchannel.end()) xchannel[fd] = task(fd, agent, Agent::errexc);
}
}
}
void Dispatcher::release(int fd)
{
MutexGuard guard(mutex);
dictionary_t::iterator c;
if ((c = rchannel.find(fd)) != rchannel.end())
{
rchannel.erase(c);
rfds.clear(fd);
}
if ((c = wchannel.find(fd)) != wchannel.end())
{
wchannel.erase(c);
wfds.clear(fd);
}
if ((c = xchannel.find(fd)) != xchannel.end())
{
xchannel.erase(c);
xfds.clear(fd);
}
}
void Dispatcher::release(Agent *agent)
{
// Signal::Guard guard(Signal::child);
MutexGuard guard(mutex);
for (dictionary_t::iterator i = rchannel.begin(); i != rchannel.end(); i++)
if ((*i).second.agent == agent) rchannel.erase(i);
for (dictionary_t::iterator i = wchannel.begin(); i != wchannel.end(); i++)
if ((*i).second.agent == agent) wchannel.erase(i);
for (dictionary_t::iterator i = xchannel.begin(); i != xchannel.end(); i++)
if ((*i).second.agent == agent) xchannel.erase(i);
alist_t::iterator i = find(agents.begin(), agents.end(), agent);
if (i != agents.end()) agents.erase(i);
}
void *Dispatcher::dispatch(void *X)
{
Dispatcher *dispatcher = reinterpret_cast<Dispatcher *>(X);
dispatcher->workers.start();
do dispatcher->wait();
while (true);
return 0;
};
void Dispatcher::process(const task &t)
{
if (t.agent->processIO(t.fd, t.mask)) activate(t);
}
void Dispatcher::deactivate(const task &t)
{
switch (t.mask)
{
case Agent::inready: wfds.clear(t.fd); break;
case Agent::outready:
case Agent::errready: rfds.clear(t.fd); break;
case Agent::inexc:
case Agent::outexc:
case Agent::errexc: xfds.clear(t.fd); break;
default: break;
}
}
void Dispatcher::activate(const task &t)
{
switch (t.mask)
{
case Agent::inready: wfds.set(t.fd); break;
case Agent::outready:
case Agent::errready: rfds.set(t.fd); break;
case Agent::inexc:
case Agent::outexc:
case Agent::errexc: xfds.set(t.fd); break;
default: break;
}
char *c = "c";
write(wakeup[1], c, 1);
}
void Dispatcher::wait()
{
FdSet tmprfds = rfds;
FdSet tmpwfds = wfds;
FdSet tmpxfds = xfds;
unsigned int fdsize = max(max(tmprfds.max(), tmpwfds.max()), tmpxfds.max()) + 1;
int nsel = select(fdsize, tmprfds, tmpwfds, tmpxfds, 0);
pthread_testcancel();
if (nsel == -1)
{
if (errno == EINTR || errno == EAGAIN) errno = 0;
}
else if (nsel > 0 && fdsize)
{
tlist_t t;
for (dictionary_t::iterator i = rchannel.begin(); i != rchannel.end(); i++)
if (tmprfds.isset((*i).first))
{
t.push_back((*i).second);
deactivate((*i).second);
}
for (dictionary_t::iterator i = wchannel.begin(); i != wchannel.end(); i++)
if (tmpwfds.isset((*i).first))
{
t.push_back((*i).second);
deactivate((*i).second);
}
for (dictionary_t::iterator i = xchannel.begin(); i != xchannel.end(); i++)
if (tmpxfds.isset((*i).first))
{
t.push_back((*i).second);
deactivate((*i).second);
}
if (tmprfds.isset(wakeup[0]))
{
char c[1];
read(wakeup[0],c,1);
}
for (tlist_t::const_iterator i = t.begin(); i != t.end(); i++)
tasks.push(*i);
}
};
<|endoftext|> |
<commit_before>#include "../Flare.h"
#include "FlareSectorInterface.h"
#include "FlareSimulatedSector.h"
#include "../Spacecrafts/FlareSpacecraftInterface.h"
#define LOCTEXT_NAMESPACE "FlareSectorInterface"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
UFlareSectorInterface::UFlareSectorInterface(const class FObjectInitializer& PCIP)
: Super(PCIP)
{
}
FText UFlareSectorInterface::GetSectorName()
{
if (SectorData.GivenName.ToString().Len())
{
return SectorData.GivenName;
}
else if (SectorDescription->Name.ToString().Len())
{
return SectorDescription->Name;
}
else
{
return FText::FromString(GetSectorCode());
}
}
FString UFlareSectorInterface::GetSectorCode()
{
// TODO cache ?
return SectorOrbitParameters.CelestialBodyIdentifier.ToString() + "-" + FString::FromInt(SectorOrbitParameters.Altitude) + "-" + FString::FromInt(SectorOrbitParameters.Phase);
}
EFlareSectorFriendlyness::Type UFlareSectorInterface::GetSectorFriendlyness(UFlareCompany* Company)
{
if (!Company->HasVisitedSector(GetSimulatedSector()))
{
return EFlareSectorFriendlyness::NotVisited;
}
if (GetSimulatedSector()->GetSectorSpacecrafts().Num() == 0)
{
return EFlareSectorFriendlyness::Neutral;
}
int HostileSpacecraftCount = 0;
int NeutralSpacecraftCount = 0;
int FriendlySpacecraftCount = 0;
for (int SpacecraftIndex = 0 ; SpacecraftIndex < GetSimulatedSector()->GetSectorSpacecrafts().Num(); SpacecraftIndex++)
{
UFlareCompany* OtherCompany = GetSimulatedSector()->GetSectorSpacecrafts()[SpacecraftIndex]->GetCompany();
if (OtherCompany == Company)
{
FriendlySpacecraftCount++;
}
else if (OtherCompany->GetWarState(Company) == EFlareHostility::Hostile)
{
HostileSpacecraftCount++;
}
else
{
NeutralSpacecraftCount++;
}
}
if (FriendlySpacecraftCount > 0 && HostileSpacecraftCount > 0)
{
return EFlareSectorFriendlyness::Contested;
}
if (FriendlySpacecraftCount > 0)
{
return EFlareSectorFriendlyness::Friendly;
}
else if (HostileSpacecraftCount > 0)
{
return EFlareSectorFriendlyness::Hostile;
}
else
{
return EFlareSectorFriendlyness::Neutral;
}
}
EFlareSectorBattleState::Type UFlareSectorInterface::GetSectorBattleState(UFlareCompany* Company)
{
if (GetSectorShipInterfaces().Num() == 0)
{
return EFlareSectorBattleState::NoBattle;
}
int HostileSpacecraftCount = 0;
int DangerousHostileSpacecraftCount = 0;
int FriendlySpacecraftCount = 0;
int DangerousFriendlySpacecraftCount = 0;
int CrippledFriendlySpacecraftCount = 0;
for (int SpacecraftIndex = 0 ; SpacecraftIndex < GetSectorShipInterfaces().Num(); SpacecraftIndex++)
{
IFlareSpacecraftInterface* Spacecraft = GetSectorShipInterfaces()[SpacecraftIndex];
UFlareCompany* OtherCompany = Spacecraft->GetCompany();
if (!Spacecraft->GetDamageSystem()->IsAlive())
{
continue;
}
if (OtherCompany == Company)
{
FriendlySpacecraftCount++;
if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Weapon) > 0)
{
DangerousFriendlySpacecraftCount++;
}
if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Propulsion) == 0)
{
CrippledFriendlySpacecraftCount++;
}
}
else if (OtherCompany->GetWarState(Company) == EFlareHostility::Hostile)
{
HostileSpacecraftCount++;
if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Weapon) > 0)
{
DangerousHostileSpacecraftCount++;
}
}
}
// No friendly or no hostile ship
if (FriendlySpacecraftCount == 0 || HostileSpacecraftCount == 0)
{
return EFlareSectorBattleState::NoBattle;
}
// No friendly and hostile ship are not dangerous
if (DangerousFriendlySpacecraftCount == 0 && DangerousHostileSpacecraftCount == 0)
{
return EFlareSectorBattleState::NoBattle;
}
// No friendly dangerous ship so the enemy have one. Battle is lost
if (DangerousFriendlySpacecraftCount == 0)
{
if (CrippledFriendlySpacecraftCount == FriendlySpacecraftCount)
{
return EFlareSectorBattleState::BattleLostNoRetreat;
}
else
{
return EFlareSectorBattleState::BattleLost;
}
}
if (DangerousHostileSpacecraftCount == 0)
{
return EFlareSectorBattleState::BattleWon;
}
if (CrippledFriendlySpacecraftCount == FriendlySpacecraftCount)
{
return EFlareSectorBattleState::BattleNoRetreat;
}
else
{
return EFlareSectorBattleState::Battle;
}
}
FText UFlareSectorInterface::GetSectorFriendlynessText(UFlareCompany* Company)
{
FText Status;
switch (GetSectorFriendlyness(Company))
{
case EFlareSectorFriendlyness::NotVisited:
Status = LOCTEXT("Unknown", "UNKNOWN");
break;
case EFlareSectorFriendlyness::Neutral:
Status = LOCTEXT("Neutral", "NEUTRAL");
break;
case EFlareSectorFriendlyness::Friendly:
Status = LOCTEXT("Friendly", "FRIENDLY");
break;
case EFlareSectorFriendlyness::Contested:
Status = LOCTEXT("Contested", "CONTESTED");
break;
case EFlareSectorFriendlyness::Hostile:
Status = LOCTEXT("Hostile", "HOSTILE");
break;
}
return Status;
}
FLinearColor UFlareSectorInterface::GetSectorFriendlynessColor(UFlareCompany* Company)
{
FLinearColor Color;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
switch (GetSectorFriendlyness(Company))
{
case EFlareSectorFriendlyness::NotVisited:
Color = Theme.UnknownColor;
break;
case EFlareSectorFriendlyness::Neutral:
Color = Theme.NeutralColor;
break;
case EFlareSectorFriendlyness::Friendly:
Color = Theme.FriendlyColor;
break;
case EFlareSectorFriendlyness::Contested:
Color = Theme.DisputedColor;
break;
case EFlareSectorFriendlyness::Hostile:
Color = Theme.EnemyColor;
break;
}
return Color;
}
uint32 UFlareSectorInterface::GetResourcePrice(FFlareResourceDescription* Resource)
{
// DEBUGInflation
float Inflation = 1.5;
// TODO better
if (Resource->Identifier == "h2")
{
return 25 * Inflation;
}
else if (Resource->Identifier == "feo")
{
return 100 * Inflation;
}
else if (Resource->Identifier == "ch4")
{
return 50 * Inflation;
}
else if (Resource->Identifier == "sio2")
{
return 100 * Inflation;
}
else if (Resource->Identifier == "he3")
{
return 100 * Inflation;
}
else if (Resource->Identifier == "h2o")
{
return 250 * Inflation;
}
else if (Resource->Identifier == "steel")
{
return 500 * Inflation;
}
else if (Resource->Identifier == "c")
{
return 300 * Inflation;
}
else if (Resource->Identifier == "plastics")
{
return 300 * Inflation;
}
else if (Resource->Identifier == "fleet-supply")
{
return 1800 * Inflation;
}
else if (Resource->Identifier == "food")
{
return 600 * Inflation;
}
else if (Resource->Identifier == "fuel")
{
return 260 * Inflation;
}
else if (Resource->Identifier == "tools")
{
return 1000 * Inflation;
}
else if (Resource->Identifier == "tech")
{
return 1300 * Inflation;
}
else
{
FLOGV("Unknown resource %s", *Resource->Identifier.ToString());
return 0;
}
}
bool UFlareSectorInterface::CanUpgrade(UFlareCompany* Company)
{
EFlareSectorBattleState::Type BattleState = GetSectorBattleState(Company);
if(BattleState != EFlareSectorBattleState::NoBattle
&& BattleState != EFlareSectorBattleState::BattleWon)
{
return false;
}
for(int StationIndex = 0 ; StationIndex < GetSectorStationInterfaces().Num(); StationIndex ++ )
{
IFlareSpacecraftInterface* StationInterface = GetSectorStationInterfaces()[StationIndex];
if (StationInterface->GetCompany()->GetWarState(Company) != EFlareHostility::Hostile)
{
return true;
}
}
return false;
}
#undef LOCTEXT_NAMESPACE
<commit_msg>Refactor static prices to ensure positive margins<commit_after>#include "../Flare.h"
#include "FlareSectorInterface.h"
#include "FlareSimulatedSector.h"
#include "../Spacecrafts/FlareSpacecraftInterface.h"
#define LOCTEXT_NAMESPACE "FlareSectorInterface"
/*----------------------------------------------------
Constructor
----------------------------------------------------*/
UFlareSectorInterface::UFlareSectorInterface(const class FObjectInitializer& PCIP)
: Super(PCIP)
{
}
FText UFlareSectorInterface::GetSectorName()
{
if (SectorData.GivenName.ToString().Len())
{
return SectorData.GivenName;
}
else if (SectorDescription->Name.ToString().Len())
{
return SectorDescription->Name;
}
else
{
return FText::FromString(GetSectorCode());
}
}
FString UFlareSectorInterface::GetSectorCode()
{
// TODO cache ?
return SectorOrbitParameters.CelestialBodyIdentifier.ToString() + "-" + FString::FromInt(SectorOrbitParameters.Altitude) + "-" + FString::FromInt(SectorOrbitParameters.Phase);
}
EFlareSectorFriendlyness::Type UFlareSectorInterface::GetSectorFriendlyness(UFlareCompany* Company)
{
if (!Company->HasVisitedSector(GetSimulatedSector()))
{
return EFlareSectorFriendlyness::NotVisited;
}
if (GetSimulatedSector()->GetSectorSpacecrafts().Num() == 0)
{
return EFlareSectorFriendlyness::Neutral;
}
int HostileSpacecraftCount = 0;
int NeutralSpacecraftCount = 0;
int FriendlySpacecraftCount = 0;
for (int SpacecraftIndex = 0 ; SpacecraftIndex < GetSimulatedSector()->GetSectorSpacecrafts().Num(); SpacecraftIndex++)
{
UFlareCompany* OtherCompany = GetSimulatedSector()->GetSectorSpacecrafts()[SpacecraftIndex]->GetCompany();
if (OtherCompany == Company)
{
FriendlySpacecraftCount++;
}
else if (OtherCompany->GetWarState(Company) == EFlareHostility::Hostile)
{
HostileSpacecraftCount++;
}
else
{
NeutralSpacecraftCount++;
}
}
if (FriendlySpacecraftCount > 0 && HostileSpacecraftCount > 0)
{
return EFlareSectorFriendlyness::Contested;
}
if (FriendlySpacecraftCount > 0)
{
return EFlareSectorFriendlyness::Friendly;
}
else if (HostileSpacecraftCount > 0)
{
return EFlareSectorFriendlyness::Hostile;
}
else
{
return EFlareSectorFriendlyness::Neutral;
}
}
EFlareSectorBattleState::Type UFlareSectorInterface::GetSectorBattleState(UFlareCompany* Company)
{
if (GetSectorShipInterfaces().Num() == 0)
{
return EFlareSectorBattleState::NoBattle;
}
int HostileSpacecraftCount = 0;
int DangerousHostileSpacecraftCount = 0;
int FriendlySpacecraftCount = 0;
int DangerousFriendlySpacecraftCount = 0;
int CrippledFriendlySpacecraftCount = 0;
for (int SpacecraftIndex = 0 ; SpacecraftIndex < GetSectorShipInterfaces().Num(); SpacecraftIndex++)
{
IFlareSpacecraftInterface* Spacecraft = GetSectorShipInterfaces()[SpacecraftIndex];
UFlareCompany* OtherCompany = Spacecraft->GetCompany();
if (!Spacecraft->GetDamageSystem()->IsAlive())
{
continue;
}
if (OtherCompany == Company)
{
FriendlySpacecraftCount++;
if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Weapon) > 0)
{
DangerousFriendlySpacecraftCount++;
}
if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Propulsion) == 0)
{
CrippledFriendlySpacecraftCount++;
}
}
else if (OtherCompany->GetWarState(Company) == EFlareHostility::Hostile)
{
HostileSpacecraftCount++;
if (Spacecraft->GetDamageSystem()->GetSubsystemHealth(EFlareSubsystem::SYS_Weapon) > 0)
{
DangerousHostileSpacecraftCount++;
}
}
}
// No friendly or no hostile ship
if (FriendlySpacecraftCount == 0 || HostileSpacecraftCount == 0)
{
return EFlareSectorBattleState::NoBattle;
}
// No friendly and hostile ship are not dangerous
if (DangerousFriendlySpacecraftCount == 0 && DangerousHostileSpacecraftCount == 0)
{
return EFlareSectorBattleState::NoBattle;
}
// No friendly dangerous ship so the enemy have one. Battle is lost
if (DangerousFriendlySpacecraftCount == 0)
{
if (CrippledFriendlySpacecraftCount == FriendlySpacecraftCount)
{
return EFlareSectorBattleState::BattleLostNoRetreat;
}
else
{
return EFlareSectorBattleState::BattleLost;
}
}
if (DangerousHostileSpacecraftCount == 0)
{
return EFlareSectorBattleState::BattleWon;
}
if (CrippledFriendlySpacecraftCount == FriendlySpacecraftCount)
{
return EFlareSectorBattleState::BattleNoRetreat;
}
else
{
return EFlareSectorBattleState::Battle;
}
}
FText UFlareSectorInterface::GetSectorFriendlynessText(UFlareCompany* Company)
{
FText Status;
switch (GetSectorFriendlyness(Company))
{
case EFlareSectorFriendlyness::NotVisited:
Status = LOCTEXT("Unknown", "UNKNOWN");
break;
case EFlareSectorFriendlyness::Neutral:
Status = LOCTEXT("Neutral", "NEUTRAL");
break;
case EFlareSectorFriendlyness::Friendly:
Status = LOCTEXT("Friendly", "FRIENDLY");
break;
case EFlareSectorFriendlyness::Contested:
Status = LOCTEXT("Contested", "CONTESTED");
break;
case EFlareSectorFriendlyness::Hostile:
Status = LOCTEXT("Hostile", "HOSTILE");
break;
}
return Status;
}
FLinearColor UFlareSectorInterface::GetSectorFriendlynessColor(UFlareCompany* Company)
{
FLinearColor Color;
const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme();
switch (GetSectorFriendlyness(Company))
{
case EFlareSectorFriendlyness::NotVisited:
Color = Theme.UnknownColor;
break;
case EFlareSectorFriendlyness::Neutral:
Color = Theme.NeutralColor;
break;
case EFlareSectorFriendlyness::Friendly:
Color = Theme.FriendlyColor;
break;
case EFlareSectorFriendlyness::Contested:
Color = Theme.DisputedColor;
break;
case EFlareSectorFriendlyness::Hostile:
Color = Theme.EnemyColor;
break;
}
return Color;
}
uint32 UFlareSectorInterface::GetResourcePrice(FFlareResourceDescription* Resource)
{
// DEBUGInflation
float Margin = 1.2;
// Raw
static float H2Price = 25 * Margin;
static float FeoPrice = 100 * Margin;
static float Ch4Price = 50 * Margin;
static float Sio2Price = 100 * Margin;
static float He3Price = 100 * Margin;
static float H2oPrice = 250 * Margin;
// Product
static float FuelPrice = (H2oPrice + 10) * Margin;
static float EnergyPrice = FuelPrice - H2oPrice;
static float SteelPrice = (2 * FeoPrice + 4 * H2oPrice + EnergyPrice * 2 - 2 * H2oPrice + 100) * Margin;
static float CPrice = (Ch4Price + 5 * EnergyPrice + 50) * Margin;
static float PlasticPrice = (Ch4Price + 5 * EnergyPrice + 50) * Margin;
static float FSPrice = (SteelPrice + 2 * PlasticPrice + FuelPrice + 10 * EnergyPrice + 100) * Margin;
static float FoodPrice = (5 * CPrice + FuelPrice + 49 * EnergyPrice + 500) / 5.0 * Margin;
static float ToolsPrice = (SteelPrice + PlasticPrice + 10 * EnergyPrice + 100) * Margin;
static float TechPrice = (2 * Sio2Price + 4 * H2Price + 50 * EnergyPrice - 2 * H2oPrice + 500) * Margin;
// TODO better
if (Resource->Identifier == "h2")
{
return H2Price;
}
else if (Resource->Identifier == "feo")
{
return FeoPrice;
}
else if (Resource->Identifier == "ch4")
{
return Ch4Price;
}
else if (Resource->Identifier == "sio2")
{
return Sio2Price;
}
else if (Resource->Identifier == "he3")
{
return He3Price;
}
else if (Resource->Identifier == "h2o")
{
return H2oPrice;
}
else if (Resource->Identifier == "steel")
{
return SteelPrice;
}
else if (Resource->Identifier == "c")
{
return CPrice;
}
else if (Resource->Identifier == "plastics")
{
return PlasticPrice;
}
else if (Resource->Identifier == "fleet-supply")
{
return FSPrice;
}
else if (Resource->Identifier == "food")
{
return FoodPrice;
}
else if (Resource->Identifier == "fuel")
{
return FuelPrice;
}
else if (Resource->Identifier == "tools")
{
return ToolsPrice;
}
else if (Resource->Identifier == "tech")
{
return TechPrice;
}
else
{
FLOGV("Unknown resource %s", *Resource->Identifier.ToString());
return 0;
}
}
bool UFlareSectorInterface::CanUpgrade(UFlareCompany* Company)
{
EFlareSectorBattleState::Type BattleState = GetSectorBattleState(Company);
if(BattleState != EFlareSectorBattleState::NoBattle
&& BattleState != EFlareSectorBattleState::BattleWon)
{
return false;
}
for(int StationIndex = 0 ; StationIndex < GetSectorStationInterfaces().Num(); StationIndex ++ )
{
IFlareSpacecraftInterface* StationInterface = GetSectorStationInterfaces()[StationIndex];
if (StationInterface->GetCompany()->GetWarState(Company) != EFlareHostility::Hostile)
{
return true;
}
}
return false;
}
#undef LOCTEXT_NAMESPACE
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file frequencyspectrummodel.cpp
* @author Christoph Dinh <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date May, 2014
*
* @section LICENSE
*
* Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief Implementation of the FrequencySpectrumModel Class.
*
*/
#include "frequencyspectrummodel.h"
#include <QDebug>
#include <QBrush>
#include <QThread>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace XDISPLIB;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
FrequencySpectrumModel::FrequencySpectrumModel(QObject *parent)
: QAbstractTableModel(parent)
, m_fSps(1024.0f)
, m_iT(10)
, m_bIsFreezed(false)
{
}
//*************************************************************************************************************
//virtual functions
int FrequencySpectrumModel::rowCount(const QModelIndex & /*parent*/) const
{
if(!m_qMapIdxRowSelection.empty())
return m_qMapIdxRowSelection.size();
else
return 0;
}
//*************************************************************************************************************
int FrequencySpectrumModel::columnCount(const QModelIndex & /*parent*/) const
{
return 2;
}
//*************************************************************************************************************
QVariant FrequencySpectrumModel::data(const QModelIndex &index, int role) const
{
if(role != Qt::DisplayRole && role != Qt::BackgroundRole)
return QVariant();
if (index.isValid()) {
qint32 r = m_qMapIdxRowSelection[index.row()];
//******** first column (chname) ********
if(index.column() == 0 && role == Qt::DisplayRole)
if(m_pFiffInfo)
return QVariant(m_pFiffInfo->chs[r].ch_name);
//******** second column (data plot) ********
if(index.column()==1) {
QVariant v;
switch(role) {
case Qt::DisplayRole: {
//pack all adjacent (after reload) RowVectorPairs into a QList
RowVectorXd vec;
if(m_bIsFreezed)
{
// data freeze
vec = m_dataCurrentFreeze.row(r);
v.setValue(vec);
}
else
{
// data
vec = m_dataCurrent.row(r);
v.setValue(vec);
}
return v;
break;
}
case Qt::BackgroundRole: {
// if(m_fiffInfo.bads.contains(m_chInfolist[row].ch_name)) {
// QBrush brush;
// brush.setStyle(Qt::SolidPattern);
// // qDebug() << m_chInfolist[row].ch_name << "is marked as bad, index:" << row;
// brush.setColor(Qt::red);
// return QVariant(brush);
// }
// else
return QVariant();
break;
}
} // end role switch
} // end column check
} // end index.valid() check
return QVariant();
}
//*************************************************************************************************************
QVariant FrequencySpectrumModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(role != Qt::DisplayRole && role != Qt::TextAlignmentRole)
return QVariant();
if(orientation == Qt::Horizontal) {
switch(section) {
case 0: //chname column
return QVariant();
case 1: //data plot column
return QVariant("data plot");
switch(role) {
case Qt::DisplayRole:
return QVariant("data plot");
case Qt::TextAlignmentRole:
return QVariant(Qt::AlignLeft);
}
}
}
else if(orientation == Qt::Vertical) {
QModelIndex chname = createIndex(section,0);
switch(role) {
case Qt::DisplayRole:
return QVariant(data(chname).toString());
}
}
return QVariant();
}
//*************************************************************************************************************
void FrequencySpectrumModel::setInfo(FiffInfo::SPtr &info)
{
beginResetModel();
m_pFiffInfo = info;
endResetModel();
resetSelection();
}
//*************************************************************************************************************
void FrequencySpectrumModel::addData(const MatrixXd &data)
{
m_dataCurrent = data;
if(m_vecFreqScale.size() != m_dataCurrent.cols() && m_pFiffInfo)
{
double freqRes = (m_pFiffInfo->sfreq/2) / m_dataCurrent.cols();
double k = 1.0;
m_vecFreqScale.resize(1,m_dataCurrent.cols());
double currFreq = freqRes;
for(qint32 i = 0; i < m_dataCurrent.cols(); ++i)
{
m_vecFreqScale[i] = log10(currFreq+k);
currFreq += freqRes;
}
double max = m_vecFreqScale.maxCoeff();
m_vecFreqScale /= max;
}
//Update data content
QModelIndex topLeft = this->index(0,1);
QModelIndex bottomRight = this->index(m_dataCurrent.rows()-1,1);
QVector<int> roles; roles << Qt::DisplayRole;
emit dataChanged(topLeft, bottomRight, roles);
}
//*************************************************************************************************************
void FrequencySpectrumModel::selectRows(const QList<qint32> &selection)
{
beginResetModel();
m_qMapIdxRowSelection.clear();
qint32 count = 0;
for(qint32 i = 0; i < selection.size(); ++i)
{
if(selection[i] < m_pFiffInfo->chs.size())
{
m_qMapIdxRowSelection.insert(count,selection[i]);
++count;
}
}
emit newSelection(selection);
endResetModel();
}
//*************************************************************************************************************
void FrequencySpectrumModel::resetSelection()
{
beginResetModel();
m_qMapIdxRowSelection.clear();
for(qint32 i = 0; i < m_pFiffInfo->chs.size(); ++i)
m_qMapIdxRowSelection.insert(i,i);
endResetModel();
}
//*************************************************************************************************************
void FrequencySpectrumModel::toggleFreeze(const QModelIndex &)
{
m_bIsFreezed = !m_bIsFreezed;
if(m_bIsFreezed)
m_dataCurrentFreeze = m_dataCurrent;
//Update data content
QModelIndex topLeft = this->index(0,1);
QModelIndex bottomRight = this->index(m_dataCurrent.rows()-1,1);
QVector<int> roles; roles << Qt::DisplayRole;
emit dataChanged(topLeft, bottomRight, roles);
}
<commit_msg>frequency fix<commit_after>//=============================================================================================================
/**
* @file frequencyspectrummodel.cpp
* @author Christoph Dinh <[email protected]>;
* Matti Hamalainen <[email protected]>
* @version 1.0
* @date May, 2014
*
* @section LICENSE
*
* Copyright (C) 2014, Christoph Dinh and Matti Hamalainen. 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 MNE-CPP authors 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.
*
*
* @brief Implementation of the FrequencySpectrumModel Class.
*
*/
#include "frequencyspectrummodel.h"
#include <QDebug>
#include <QBrush>
#include <QThread>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace XDISPLIB;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
FrequencySpectrumModel::FrequencySpectrumModel(QObject *parent)
: QAbstractTableModel(parent)
, m_fSps(1024.0f)
, m_iT(10)
, m_bIsFreezed(false)
{
}
//*************************************************************************************************************
//virtual functions
int FrequencySpectrumModel::rowCount(const QModelIndex & /*parent*/) const
{
if(!m_qMapIdxRowSelection.empty())
return m_qMapIdxRowSelection.size();
else
return 0;
}
//*************************************************************************************************************
int FrequencySpectrumModel::columnCount(const QModelIndex & /*parent*/) const
{
return 2;
}
//*************************************************************************************************************
QVariant FrequencySpectrumModel::data(const QModelIndex &index, int role) const
{
if(role != Qt::DisplayRole && role != Qt::BackgroundRole)
return QVariant();
if (index.isValid()) {
qint32 r = m_qMapIdxRowSelection[index.row()];
//******** first column (chname) ********
if(index.column() == 0 && role == Qt::DisplayRole)
if(m_pFiffInfo)
return QVariant(m_pFiffInfo->chs[r].ch_name);
//******** second column (data plot) ********
if(index.column()==1) {
QVariant v;
switch(role) {
case Qt::DisplayRole: {
//pack all adjacent (after reload) RowVectorPairs into a QList
RowVectorXd vec;
if(m_bIsFreezed)
{
// data freeze
vec = m_dataCurrentFreeze.row(r);
v.setValue(vec);
}
else
{
// data
vec = m_dataCurrent.row(r);
v.setValue(vec);
}
return v;
break;
}
case Qt::BackgroundRole: {
// if(m_fiffInfo.bads.contains(m_chInfolist[row].ch_name)) {
// QBrush brush;
// brush.setStyle(Qt::SolidPattern);
// // qDebug() << m_chInfolist[row].ch_name << "is marked as bad, index:" << row;
// brush.setColor(Qt::red);
// return QVariant(brush);
// }
// else
return QVariant();
break;
}
} // end role switch
} // end column check
} // end index.valid() check
return QVariant();
}
//*************************************************************************************************************
QVariant FrequencySpectrumModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if(role != Qt::DisplayRole && role != Qt::TextAlignmentRole)
return QVariant();
if(orientation == Qt::Horizontal) {
switch(section) {
case 0: //chname column
return QVariant();
case 1: //data plot column
return QVariant("data plot");
switch(role) {
case Qt::DisplayRole:
return QVariant("data plot");
case Qt::TextAlignmentRole:
return QVariant(Qt::AlignLeft);
}
}
}
else if(orientation == Qt::Vertical) {
QModelIndex chname = createIndex(section,0);
switch(role) {
case Qt::DisplayRole:
return QVariant(data(chname).toString());
}
}
return QVariant();
}
//*************************************************************************************************************
void FrequencySpectrumModel::setInfo(FiffInfo::SPtr &info)
{
beginResetModel();
m_pFiffInfo = info;
endResetModel();
resetSelection();
}
//*************************************************************************************************************
void FrequencySpectrumModel::addData(const MatrixXd &data)
{
m_dataCurrent = data;
if(m_vecFreqScale.size() != m_dataCurrent.cols() && m_pFiffInfo)
{
double freqRes = (m_pFiffInfo->sfreq/2) / m_dataCurrent.cols();
double k = 1.0;
m_vecFreqScale.resize(1,m_dataCurrent.cols());
double currFreq = 0;
for(qint32 i = 0; i < m_dataCurrent.cols(); ++i)
{
m_vecFreqScale[i] = log10(currFreq+k);
currFreq += freqRes;
}
double max = m_vecFreqScale.maxCoeff();
m_vecFreqScale /= max;
}
//Update data content
QModelIndex topLeft = this->index(0,1);
QModelIndex bottomRight = this->index(m_dataCurrent.rows()-1,1);
QVector<int> roles; roles << Qt::DisplayRole;
emit dataChanged(topLeft, bottomRight, roles);
}
//*************************************************************************************************************
void FrequencySpectrumModel::selectRows(const QList<qint32> &selection)
{
beginResetModel();
m_qMapIdxRowSelection.clear();
qint32 count = 0;
for(qint32 i = 0; i < selection.size(); ++i)
{
if(selection[i] < m_pFiffInfo->chs.size())
{
m_qMapIdxRowSelection.insert(count,selection[i]);
++count;
}
}
emit newSelection(selection);
endResetModel();
}
//*************************************************************************************************************
void FrequencySpectrumModel::resetSelection()
{
beginResetModel();
m_qMapIdxRowSelection.clear();
for(qint32 i = 0; i < m_pFiffInfo->chs.size(); ++i)
m_qMapIdxRowSelection.insert(i,i);
endResetModel();
}
//*************************************************************************************************************
void FrequencySpectrumModel::toggleFreeze(const QModelIndex &)
{
m_bIsFreezed = !m_bIsFreezed;
if(m_bIsFreezed)
m_dataCurrentFreeze = m_dataCurrent;
//Update data content
QModelIndex topLeft = this->index(0,1);
QModelIndex bottomRight = this->index(m_dataCurrent.rows()-1,1);
QVector<int> roles; roles << Qt::DisplayRole;
emit dataChanged(topLeft, bottomRight, roles);
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2006
*
* 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
*
* "@(#) $Id$"
*
* who when what
* -------- -------- ----------------------------------------------
* acaproni 2006-07-12 created
*/
#include "vltPort.h"
#include <iostream>
#include "ConfigPropertyGetter.h"
#include <acsutilORBHelper.h>
#include <cdb.h>
#include <cdbDALaccess.h>
#include <cdbErrType.h>
// The following defines, remeber what we'are parsing
#define NO_TAG 0
#define PROP_TAG 1
typedef struct {
// The list of the properties
std::list<Property>* props;
// The name of the property
std::string pName;
// The tag we're parsing (see defines above)
short actualTag;
} ParserStruct;
ConfigPropertyGetter::ConfigPropertyGetter(maci::Manager_ptr manager):m_properties(NULL)
{
m_dao = getDAO(manager);
if (m_dao.size()>0) {
parseDAO();
}
}
ConfigPropertyGetter::~ConfigPropertyGetter() {
if (m_properties!=NULL) {
m_properties->clear();
m_properties=NULL;
}
}
std::string ConfigPropertyGetter::getDAO(maci::Manager_ptr manager) {
CDB::DAL_var cdbDAL;
CORBA::Object_var cdb;
try
{
cdb = manager->get_service(0, "CDB", true);
if (CORBA::is_nil(cdb.in()))
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(__FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
}
catch(maciErrType::CannotGetComponentEx &ex)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(ex, __FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
catch(maciErrType::ComponentNotAlreadyActivatedEx &ex)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(ex, __FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
catch(maciErrType::ComponentConfigurationNotFoundEx &ex)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(ex, __FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
catch(CORBA::Exception &ex)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(__FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
catch(...)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(__FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}//try-catch
cdbDAL = CDB::DAL::_narrow(cdb.in());
DALaccess::forceDAL(cdbDAL.in());
// Get the DAO
try {
return cdbDAL->get_DAO("Alarms/AlarmSystemConfiguration");
} catch (cdbErrType::CDBRecordDoesNotExistEx) {
return "";
}
}
void ConfigPropertyGetter::parseDAO() {
if (m_dao.size()==0) {
return;
}
XML_Parser p = XML_ParserCreate(NULL);
if (! p)
{
return ;
}
//Connect to the parser the handler for the end and the start of a tag
XML_SetElementHandler(p, start_hndl, end_hndl);
m_properties = new std::list<Property>();
ParserStruct commonData;
commonData.props=m_properties;
commonData.actualTag=NO_TAG;
// Connect the char handler
XML_SetCharacterDataHandler(p,char_hndl);
XML_SetUserData(p,&commonData);
// We have all the xml in the string so we parse all the document
// with just one call
if (XML_Parse(p,m_dao.c_str(),m_dao.size(),TRUE)==0)
{
return;
}
// Release the memory used by the parser
XML_ParserFree(p);
m_properties = commonData.props;
}
std::string ConfigPropertyGetter::getProperty(std::string propName) {
if (m_properties==NULL || propName.size()==0) {
return "";
}
std::list<Property>::iterator iter;
for (iter=m_properties->begin(); iter!=m_properties->end(); iter++) {
Property p = (*iter);
if (p.key==propName) {
return p.value;
}
}
return "";
}
void ConfigPropertyGetter::start_hndl(void *data, const XML_Char *el, const XML_Char **attr) {
ParserStruct* ps = (ParserStruct*)data;
if (strcmp(el,"configuration-property")==0) {
ps->actualTag=PROP_TAG;
ps->pName=(char*)attr[1];
}
}
void ConfigPropertyGetter::end_hndl(void *data, const XML_Char *el) {
ParserStruct* ps = (ParserStruct*)data;
ps->actualTag=NO_TAG;
}
void ConfigPropertyGetter::char_hndl(void *data, const XML_Char *s, int len) {
ParserStruct* ps = (ParserStruct*)data;
if (ps->actualTag==PROP_TAG) {
Property p;
p.key=ps->pName;
for (int t=0; t<len; t++) {
p.value+=s[t];
}
ps->props->push_back(p);
}
}
<commit_msg>The path of the alarm configuration file in the CDB has changed.<commit_after>/*******************************************************************************
* ALMA - Atacama Large Millimiter Array
* (c) European Southern Observatory, 2006
*
* 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
*
* "@(#) $Id$"
*
* who when what
* -------- -------- ----------------------------------------------
* acaproni 2006-07-12 created
*/
#include "vltPort.h"
#include <iostream>
#include "ConfigPropertyGetter.h"
#include <acsutilORBHelper.h>
#include <cdb.h>
#include <cdbDALaccess.h>
#include <cdbErrType.h>
// The following defines, remeber what we'are parsing
#define NO_TAG 0
#define PROP_TAG 1
typedef struct {
// The list of the properties
std::list<Property>* props;
// The name of the property
std::string pName;
// The tag we're parsing (see defines above)
short actualTag;
} ParserStruct;
ConfigPropertyGetter::ConfigPropertyGetter(maci::Manager_ptr manager):m_properties(NULL)
{
m_dao = getDAO(manager);
if (m_dao.size()>0) {
parseDAO();
}
}
ConfigPropertyGetter::~ConfigPropertyGetter() {
if (m_properties!=NULL) {
m_properties->clear();
m_properties=NULL;
}
}
std::string ConfigPropertyGetter::getDAO(maci::Manager_ptr manager) {
CDB::DAL_var cdbDAL;
CORBA::Object_var cdb;
try
{
cdb = manager->get_service(0, "CDB", true);
if (CORBA::is_nil(cdb.in()))
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(__FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
}
catch(maciErrType::CannotGetComponentEx &ex)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(ex, __FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
catch(maciErrType::ComponentNotAlreadyActivatedEx &ex)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(ex, __FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
catch(maciErrType::ComponentConfigurationNotFoundEx &ex)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(ex, __FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
catch(CORBA::Exception &ex)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(__FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}
catch(...)
{
throw acsErrTypeAlarmSourceFactory::ErrorGettingDALExImpl(__FILE__,__LINE__,"ConfigPropertyGetter::getDAO");
}//try-catch
cdbDAL = CDB::DAL::_narrow(cdb.in());
DALaccess::forceDAL(cdbDAL.in());
// Get the DAO
try {
return cdbDAL->get_DAO("Alarms/Administrative/AlarmSystemConfiguration");
} catch (cdbErrType::CDBRecordDoesNotExistEx) {
return "";
}
}
void ConfigPropertyGetter::parseDAO() {
if (m_dao.size()==0) {
return;
}
XML_Parser p = XML_ParserCreate(NULL);
if (! p)
{
return ;
}
//Connect to the parser the handler for the end and the start of a tag
XML_SetElementHandler(p, start_hndl, end_hndl);
m_properties = new std::list<Property>();
ParserStruct commonData;
commonData.props=m_properties;
commonData.actualTag=NO_TAG;
// Connect the char handler
XML_SetCharacterDataHandler(p,char_hndl);
XML_SetUserData(p,&commonData);
// We have all the xml in the string so we parse all the document
// with just one call
if (XML_Parse(p,m_dao.c_str(),m_dao.size(),TRUE)==0)
{
return;
}
// Release the memory used by the parser
XML_ParserFree(p);
m_properties = commonData.props;
}
std::string ConfigPropertyGetter::getProperty(std::string propName) {
if (m_properties==NULL || propName.size()==0) {
return "";
}
std::list<Property>::iterator iter;
for (iter=m_properties->begin(); iter!=m_properties->end(); iter++) {
Property p = (*iter);
if (p.key==propName) {
return p.value;
}
}
return "";
}
void ConfigPropertyGetter::start_hndl(void *data, const XML_Char *el, const XML_Char **attr) {
ParserStruct* ps = (ParserStruct*)data;
if (strcmp(el,"configuration-property")==0) {
ps->actualTag=PROP_TAG;
ps->pName=(char*)attr[1];
}
}
void ConfigPropertyGetter::end_hndl(void *data, const XML_Char *el) {
ParserStruct* ps = (ParserStruct*)data;
ps->actualTag=NO_TAG;
}
void ConfigPropertyGetter::char_hndl(void *data, const XML_Char *s, int len) {
ParserStruct* ps = (ParserStruct*)data;
if (ps->actualTag==PROP_TAG) {
Property p;
p.key=ps->pName;
for (int t=0; t<len; t++) {
p.value+=s[t];
}
ps->props->push_back(p);
}
}
<|endoftext|> |
<commit_before>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkContourModelUtils.h>
#include <mitkContourModelToSurfaceFilter.h>
#include <mitkLabelSetImage.h>
#include <mitkSurface.h>
#include <vtkImageStencil.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkPolyDataToImageStencil.h>
mitk::ContourModelUtils::ContourModelUtils()
{
}
mitk::ContourModelUtils::~ContourModelUtils()
{
}
mitk::ContourModel::Pointer mitk::ContourModelUtils::ProjectContourTo2DSlice(
const Image *slice, const ContourModel *contourIn3D, bool, bool)
{
if (nullptr == slice || nullptr == contourIn3D)
return nullptr;
auto projectedContour = ContourModel::New();
projectedContour->Initialize(*contourIn3D);
auto sliceGeometry = slice->GetGeometry();
auto numberOfTimesteps = static_cast<TimeStepType>(contourIn3D->GetTimeSteps());
for (decltype(numberOfTimesteps) t = 0; t < numberOfTimesteps; ++t)
{
auto iter = contourIn3D->Begin(t);
auto end = contourIn3D->End(t);
while (iter != end)
{
const auto ¤tPointIn3D = (*iter)->Coordinates;
Point3D projectedPointIn2D;
projectedPointIn2D.Fill(0.0);
sliceGeometry->WorldToIndex(currentPointIn3D, projectedPointIn2D);
projectedContour->AddVertex(projectedPointIn2D, t);
++iter;
}
}
return projectedContour;
}
mitk::ContourModel::Pointer mitk::ContourModelUtils::BackProjectContourFrom2DSlice(
const BaseGeometry *sliceGeometry, const ContourModel *contourIn2D, bool)
{
if (nullptr == sliceGeometry || nullptr == contourIn2D)
return nullptr;
auto worldContour = ContourModel::New();
worldContour->Initialize(*contourIn2D);
auto numberOfTimesteps = static_cast<TimeStepType>(contourIn2D->GetTimeSteps());
for (decltype(numberOfTimesteps) t = 0; t < numberOfTimesteps; ++t)
{
auto iter = contourIn2D->Begin(t);
auto end = contourIn2D->End(t);
while (iter != end)
{
const auto ¤tPointIn2D = (*iter)->Coordinates;
Point3D worldPointIn3D;
worldPointIn3D.Fill(0.0);
sliceGeometry->IndexToWorld(currentPointIn2D, worldPointIn3D);
worldContour->AddVertex(worldPointIn3D, t);
++iter;
}
}
return worldContour;
}
void mitk::ContourModelUtils::FillContourInSlice(
const ContourModel *projectedContour, Image *sliceImage, const Image* workingImage, int paintingPixelValue)
{
FillContourInSlice(projectedContour, 0, sliceImage, workingImage, paintingPixelValue);
}
void mitk::ContourModelUtils::FillContourInSlice(
const ContourModel *projectedContour, TimeStepType contourTimeStep, Image *sliceImage, const Image* workingImage, int paintingPixelValue)
{
if (nullptr == projectedContour)
{
mitkThrow() << "Cannot fill contour in slice. Passed contour is invalid";
}
if (nullptr == sliceImage)
{
mitkThrow() << "Cannot fill contour in slice. Passed slice is invalid";
}
auto contourModelFilter = mitk::ContourModelToSurfaceFilter::New();
contourModelFilter->SetInput(projectedContour);
contourModelFilter->Update();
auto surface = mitk::Surface::New();
surface = contourModelFilter->GetOutput();
if (nullptr == surface->GetVtkPolyData(contourTimeStep))
{
MITK_WARN << "Could not create surface from contour model.";
return;
}
auto surface2D = vtkSmartPointer<vtkPolyData>::New();
surface2D->SetPoints(surface->GetVtkPolyData(contourTimeStep)->GetPoints());
surface2D->SetLines(surface->GetVtkPolyData(contourTimeStep)->GetLines());
auto image = vtkSmartPointer<vtkImageData>::New();
image->DeepCopy(sliceImage->GetVtkImageData());
const double FOREGROUND_VALUE = 255.0;
const double BACKGROUND_VALUE = 0.0;
vtkIdType count = image->GetNumberOfPoints();
for (decltype(count) i = 0; i < count; ++i)
image->GetPointData()->GetScalars()->SetTuple1(i, FOREGROUND_VALUE);
auto polyDataToImageStencil = vtkSmartPointer<vtkPolyDataToImageStencil>::New();
// Set a minimal tolerance, so that clipped pixels will be added to contour as well.
polyDataToImageStencil->SetTolerance(mitk::eps);
polyDataToImageStencil->SetInputData(surface2D);
polyDataToImageStencil->Update();
auto imageStencil = vtkSmartPointer<vtkImageStencil>::New();
imageStencil->SetInputData(image);
imageStencil->SetStencilConnection(polyDataToImageStencil->GetOutputPort());
imageStencil->ReverseStencilOff();
imageStencil->SetBackgroundValue(BACKGROUND_VALUE);
imageStencil->Update();
vtkSmartPointer<vtkImageData> filledImage = imageStencil->GetOutput();
vtkSmartPointer<vtkImageData> resultImage = sliceImage->GetVtkImageData();
FillSliceInSlice(filledImage, resultImage, workingImage, paintingPixelValue);
sliceImage->SetVolume(resultImage->GetScalarPointer());
}
void mitk::ContourModelUtils::FillSliceInSlice(
vtkSmartPointer<vtkImageData> filledImage, vtkSmartPointer<vtkImageData> resultImage, const Image* image, int paintingPixelValue, double fillForegroundThreshold)
{
auto labelImage = dynamic_cast<const LabelSetImage *>(image);
const auto numberOfPoints = filledImage->GetNumberOfPoints();
if (nullptr == labelImage)
{
for (auto i = decltype(numberOfPoints){0}; i < numberOfPoints; ++i)
{
if (fillForegroundThreshold <= filledImage->GetPointData()->GetScalars()->GetTuple1(i))
resultImage->GetPointData()->GetScalars()->SetTuple1(i, paintingPixelValue);
}
}
else
{
const auto backgroundValue = labelImage->GetExteriorLabel()->GetValue();
if (paintingPixelValue != backgroundValue)
{
for (auto i = decltype(numberOfPoints){0}; i < numberOfPoints; ++i)
{
const auto filledValue = filledImage->GetPointData()->GetScalars()->GetTuple1(i);
if (fillForegroundThreshold <= filledValue)
{
const auto existingValue = resultImage->GetPointData()->GetScalars()->GetTuple1(i);
if (!labelImage->GetLabel(existingValue, labelImage->GetActiveLayer())->GetLocked())
resultImage->GetPointData()->GetScalars()->SetTuple1(i, paintingPixelValue);
}
}
}
else
{
const auto activePixelValue = labelImage->GetActiveLabel(labelImage->GetActiveLayer())->GetValue();
for (auto i = decltype(numberOfPoints){0}; i < numberOfPoints; ++i)
{
if (fillForegroundThreshold <= filledImage->GetPointData()->GetScalars()->GetTuple1(i))
{
if (resultImage->GetPointData()->GetScalars()->GetTuple1(i) == activePixelValue)
resultImage->GetPointData()->GetScalars()->SetTuple1(i, paintingPixelValue);
}
}
}
}
}
mitk::ContourModel::Pointer mitk::ContourModelUtils::MoveZerothContourTimeStep(const ContourModel *contour, TimeStepType t)
{
if (nullptr == contour)
return nullptr;
auto resultContour = ContourModel::New();
resultContour->Expand(t + 1);
std::for_each(contour->Begin(), contour->End(), [&resultContour, t](ContourElement::VertexType *vertex) {
resultContour->AddVertex(*vertex, t);
});
return resultContour;
}
int mitk::ContourModelUtils::GetActivePixelValue(const Image* workingImage)
{
auto labelSetImage = dynamic_cast<const LabelSetImage*>(workingImage);
int activePixelValue = 1;
if (nullptr != labelSetImage)
{
activePixelValue = labelSetImage->GetActiveLabel(labelSetImage->GetActiveLayer())->GetValue();
}
return activePixelValue;
}
<commit_msg>Fixed review feedback.<commit_after>/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include <mitkContourModelUtils.h>
#include <mitkContourModelToSurfaceFilter.h>
#include <mitkLabelSetImage.h>
#include <mitkSurface.h>
#include <vtkImageStencil.h>
#include <vtkPointData.h>
#include <vtkPolyData.h>
#include <vtkPolyDataToImageStencil.h>
mitk::ContourModelUtils::ContourModelUtils()
{
}
mitk::ContourModelUtils::~ContourModelUtils()
{
}
mitk::ContourModel::Pointer mitk::ContourModelUtils::ProjectContourTo2DSlice(
const Image *slice, const ContourModel *contourIn3D, bool, bool)
{
if (nullptr == slice || nullptr == contourIn3D)
return nullptr;
auto projectedContour = ContourModel::New();
projectedContour->Initialize(*contourIn3D);
auto sliceGeometry = slice->GetGeometry();
const auto numberOfTimesteps = static_cast<TimeStepType>(contourIn3D->GetTimeSteps());
for (std::remove_const_t<decltype(numberOfTimesteps)> t = 0; t < numberOfTimesteps; ++t)
{
auto iter = contourIn3D->Begin(t);
auto end = contourIn3D->End(t);
while (iter != end)
{
const auto ¤tPointIn3D = (*iter)->Coordinates;
Point3D projectedPointIn2D;
projectedPointIn2D.Fill(0.0);
sliceGeometry->WorldToIndex(currentPointIn3D, projectedPointIn2D);
projectedContour->AddVertex(projectedPointIn2D, t);
++iter;
}
}
return projectedContour;
}
mitk::ContourModel::Pointer mitk::ContourModelUtils::BackProjectContourFrom2DSlice(
const BaseGeometry *sliceGeometry, const ContourModel *contourIn2D, bool)
{
if (nullptr == sliceGeometry || nullptr == contourIn2D)
return nullptr;
auto worldContour = ContourModel::New();
worldContour->Initialize(*contourIn2D);
const auto numberOfTimesteps = static_cast<TimeStepType>(contourIn2D->GetTimeSteps());
for (std::remove_const_t<decltype(numberOfTimesteps)> t = 0; t < numberOfTimesteps; ++t)
{
auto iter = contourIn2D->Begin(t);
auto end = contourIn2D->End(t);
while (iter != end)
{
const auto ¤tPointIn2D = (*iter)->Coordinates;
Point3D worldPointIn3D;
worldPointIn3D.Fill(0.0);
sliceGeometry->IndexToWorld(currentPointIn2D, worldPointIn3D);
worldContour->AddVertex(worldPointIn3D, t);
++iter;
}
}
return worldContour;
}
void mitk::ContourModelUtils::FillContourInSlice(
const ContourModel *projectedContour, Image *sliceImage, const Image* workingImage, int paintingPixelValue)
{
FillContourInSlice(projectedContour, 0, sliceImage, workingImage, paintingPixelValue);
}
void mitk::ContourModelUtils::FillContourInSlice(
const ContourModel *projectedContour, TimeStepType contourTimeStep, Image *sliceImage, const Image* workingImage, int paintingPixelValue)
{
if (nullptr == projectedContour)
{
mitkThrow() << "Cannot fill contour in slice. Passed contour is invalid";
}
if (nullptr == sliceImage)
{
mitkThrow() << "Cannot fill contour in slice. Passed slice is invalid";
}
auto contourModelFilter = mitk::ContourModelToSurfaceFilter::New();
contourModelFilter->SetInput(projectedContour);
contourModelFilter->Update();
auto surface = mitk::Surface::New();
surface = contourModelFilter->GetOutput();
if (nullptr == surface->GetVtkPolyData(contourTimeStep))
{
MITK_WARN << "Could not create surface from contour model.";
return;
}
auto surface2D = vtkSmartPointer<vtkPolyData>::New();
surface2D->SetPoints(surface->GetVtkPolyData(contourTimeStep)->GetPoints());
surface2D->SetLines(surface->GetVtkPolyData(contourTimeStep)->GetLines());
auto image = vtkSmartPointer<vtkImageData>::New();
image->DeepCopy(sliceImage->GetVtkImageData());
const double FOREGROUND_VALUE = 255.0;
const double BACKGROUND_VALUE = 0.0;
const vtkIdType count = image->GetNumberOfPoints();
for (std::remove_const_t<decltype(count)> i = 0; i < count; ++i)
image->GetPointData()->GetScalars()->SetTuple1(i, FOREGROUND_VALUE);
auto polyDataToImageStencil = vtkSmartPointer<vtkPolyDataToImageStencil>::New();
// Set a minimal tolerance, so that clipped pixels will be added to contour as well.
polyDataToImageStencil->SetTolerance(mitk::eps);
polyDataToImageStencil->SetInputData(surface2D);
polyDataToImageStencil->Update();
auto imageStencil = vtkSmartPointer<vtkImageStencil>::New();
imageStencil->SetInputData(image);
imageStencil->SetStencilConnection(polyDataToImageStencil->GetOutputPort());
imageStencil->ReverseStencilOff();
imageStencil->SetBackgroundValue(BACKGROUND_VALUE);
imageStencil->Update();
vtkSmartPointer<vtkImageData> filledImage = imageStencil->GetOutput();
vtkSmartPointer<vtkImageData> resultImage = sliceImage->GetVtkImageData();
FillSliceInSlice(filledImage, resultImage, workingImage, paintingPixelValue);
sliceImage->SetVolume(resultImage->GetScalarPointer());
}
void mitk::ContourModelUtils::FillSliceInSlice(
vtkSmartPointer<vtkImageData> filledImage, vtkSmartPointer<vtkImageData> resultImage, const Image* image, int paintingPixelValue, double fillForegroundThreshold)
{
auto labelImage = dynamic_cast<const LabelSetImage *>(image);
const auto numberOfPoints = filledImage->GetNumberOfPoints();
if (nullptr == labelImage)
{
for (std::remove_const_t<decltype(numberOfPoints)> i = 0; i < numberOfPoints; ++i)
{
if (fillForegroundThreshold <= filledImage->GetPointData()->GetScalars()->GetTuple1(i))
resultImage->GetPointData()->GetScalars()->SetTuple1(i, paintingPixelValue);
}
}
else
{
const auto backgroundValue = labelImage->GetExteriorLabel()->GetValue();
if (paintingPixelValue != backgroundValue)
{
for (std::remove_const_t<decltype(numberOfPoints)> i = 0; i < numberOfPoints; ++i)
{
const auto filledValue = filledImage->GetPointData()->GetScalars()->GetTuple1(i);
if (fillForegroundThreshold <= filledValue)
{
const auto existingValue = resultImage->GetPointData()->GetScalars()->GetTuple1(i);
if (!labelImage->GetLabel(existingValue, labelImage->GetActiveLayer())->GetLocked())
resultImage->GetPointData()->GetScalars()->SetTuple1(i, paintingPixelValue);
}
}
}
else
{
const auto activePixelValue = labelImage->GetActiveLabel(labelImage->GetActiveLayer())->GetValue();
for (std::remove_const_t<decltype(numberOfPoints)> i = 0; i < numberOfPoints; ++i)
{
if (fillForegroundThreshold <= filledImage->GetPointData()->GetScalars()->GetTuple1(i))
{
if (resultImage->GetPointData()->GetScalars()->GetTuple1(i) == activePixelValue)
resultImage->GetPointData()->GetScalars()->SetTuple1(i, paintingPixelValue);
}
}
}
}
}
mitk::ContourModel::Pointer mitk::ContourModelUtils::MoveZerothContourTimeStep(const ContourModel *contour, TimeStepType t)
{
if (nullptr == contour)
return nullptr;
auto resultContour = ContourModel::New();
resultContour->Expand(t + 1);
std::for_each(contour->Begin(), contour->End(), [&resultContour, t](ContourElement::VertexType *vertex) {
resultContour->AddVertex(*vertex, t);
});
return resultContour;
}
int mitk::ContourModelUtils::GetActivePixelValue(const Image* workingImage)
{
auto labelSetImage = dynamic_cast<const LabelSetImage*>(workingImage);
int activePixelValue = 1;
if (nullptr != labelSetImage)
{
activePixelValue = labelSetImage->GetActiveLabel(labelSetImage->GetActiveLayer())->GetValue();
}
return activePixelValue;
}
<|endoftext|> |
<commit_before>#include "itkArrowSpatialObject.h"
namespace itk
{
// This is the 3D implementation of the ArrowSpatialObject.
/** Update the local transform from the position and the direction */
// Parial specialization for TDimension = 3
template< >
void
ArrowSpatialObject< 3 >
::UpdateTransform()
{
VectorType offset;
for ( unsigned int i = 0; i < 3; i++ )
{
offset[i] = m_Position[i];
}
this->GetObjectToParentTransform()->SetOffset(offset);
// If the given direction is not normalized we set the length of the vector
// as the length of the arrow
m_Length = m_Direction.GetSquaredNorm();
if ( m_Length != 0.0 )
{
m_Length = vcl_sqrt(m_Length);
}
else
{
this->Modified();
return;
}
m_Direction.Normalize();
double anglez = 0;
if ( m_Direction[0] == 0.0 )
{
if ( m_Direction[1] > 0.0 )
{
anglez = vnl_math::pi / 2;
}
else if ( m_Direction[1] < 0.0 )
{
anglez = -vnl_math::pi / 2;
}
//NOTE: else if m_Direction[1] == 0, anglez = 0;
}
else
{
if ( m_Direction[0] < 0.0 )
{
anglez = vnl_math::pi + vcl_atan(m_Direction[1] / m_Direction[0]);
}
else
{
anglez = vcl_atan(m_Direction[1] / m_Direction[0]);
}
}
const double angley = -asin(m_Direction[2]);
typedef itk::Euler3DTransform< double > EulerTransformType;
EulerTransformType::Pointer euler = EulerTransformType::New();
euler->SetRotation(0, angley, anglez);
this->GetObjectToParentTransform()->SetMatrix( euler->GetRotationMatrix() );
this->Modified();
}
}
<commit_msg>STYLE: Add license header to itkArrowSpatialObject.cxx.<commit_after>/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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 "itkArrowSpatialObject.h"
namespace itk
{
// This is the 3D implementation of the ArrowSpatialObject.
/** Update the local transform from the position and the direction */
// Parial specialization for TDimension = 3
template< >
void
ArrowSpatialObject< 3 >
::UpdateTransform()
{
VectorType offset;
for ( unsigned int i = 0; i < 3; i++ )
{
offset[i] = m_Position[i];
}
this->GetObjectToParentTransform()->SetOffset(offset);
// If the given direction is not normalized we set the length of the vector
// as the length of the arrow
m_Length = m_Direction.GetSquaredNorm();
if ( m_Length != 0.0 )
{
m_Length = vcl_sqrt(m_Length);
}
else
{
this->Modified();
return;
}
m_Direction.Normalize();
double anglez = 0;
if ( m_Direction[0] == 0.0 )
{
if ( m_Direction[1] > 0.0 )
{
anglez = vnl_math::pi / 2;
}
else if ( m_Direction[1] < 0.0 )
{
anglez = -vnl_math::pi / 2;
}
//NOTE: else if m_Direction[1] == 0, anglez = 0;
}
else
{
if ( m_Direction[0] < 0.0 )
{
anglez = vnl_math::pi + vcl_atan(m_Direction[1] / m_Direction[0]);
}
else
{
anglez = vcl_atan(m_Direction[1] / m_Direction[0]);
}
}
const double angley = -asin(m_Direction[2]);
typedef itk::Euler3DTransform< double > EulerTransformType;
EulerTransformType::Pointer euler = EulerTransformType::New();
euler->SetRotation(0, angley, anglez);
this->GetObjectToParentTransform()->SetMatrix( euler->GetRotationMatrix() );
this->Modified();
}
}
<|endoftext|> |
<commit_before>#include "riptide_teleop/ps3_control.h"
int main(int argc, char** argv)
{
ros::init(argc, argv, "joy_accel");
Accel accel;
accel.loop();
}
Accel::Accel()
{
js = nh.subscribe<sensor_msgs::Joy>("joy", 1, &Accel::joy_callback, this);
accels = nh.advertise<geometry_msgs::Accel>("command/accel", 1);
}
void Accel::joy_callback(const sensor_msgs::Joy::ConstPtr& joy)
{
accel.linear.x = 0.75 * joy->axes[1]; // Left joystick vertical
accel.linear.y = joy->axes[0]; // Left joystick horizontal
accel.linear.z = 0.25 * (joy->buttons[11] - joy->buttons[10]); // R1 L1
accel.angular.x = 2.0 * 3.14159 * joy->axes[2] * -1;// Right joystick horizontal
accel.angular.y = 1.2 * 3.14159 * joy->axes[3]; // Right joystick vertical
accel.angular.z = 0.25 * 3.14159 * (joy->buttons[9] - joy->buttons[8]); // R2 L2
accels.publish(accel);
}
void Accel::loop()
{
ros::Rate rate(10);
while (ros::ok())
{
ros::spinOnce();
rate.sleep();
}
}
<commit_msg>Reduce max accel<commit_after>#include "riptide_teleop/ps3_control.h"
int main(int argc, char** argv)
{
ros::init(argc, argv, "joy_accel");
Accel accel;
accel.loop();
}
Accel::Accel()
{
js = nh.subscribe<sensor_msgs::Joy>("joy", 1, &Accel::joy_callback, this);
accels = nh.advertise<geometry_msgs::Accel>("command/accel", 1);
}
void Accel::joy_callback(const sensor_msgs::Joy::ConstPtr& joy)
{
accel.linear.x = 0.75 * joy->axes[1]; // Left joystick vertical
accel.linear.y = joy->axes[0]; // Left joystick horizontal
accel.linear.z = 0.175 * (joy->buttons[11] - joy->buttons[10]); // R1 L1
accel.angular.x = 2.0 * 3.14159 * joy->axes[2] * -1;// Right joystick horizontal
accel.angular.y = 1.2 * 3.14159 * joy->axes[3]; // Right joystick vertical
accel.angular.z = 0.25 * 3.14159 * (joy->buttons[9] - joy->buttons[8]); // R2 L2
accels.publish(accel);
}
void Accel::loop()
{
ros::Rate rate(10);
while (ros::ok())
{
ros::spinOnce();
rate.sleep();
}
}
<|endoftext|> |
<commit_before>
#include "stdlib.h"
#include "TFile.h"
#include "TTimeStamp.h"
#include "RooStats/HistFactory/HistFactoryException.h"
#include "RooStats/HistFactory/Channel.h"
RooStats::HistFactory::Channel::Channel() :
fName( "" ) { ; }
RooStats::HistFactory::Channel::Channel(std::string ChanName, std::string ChanInputFile) :
fName( ChanName ), fInputFile( ChanInputFile ) { ; }
namespace RooStats{
namespace HistFactory{
//BadChannel = Channel();
Channel BadChannel;
// BadChannel.Name = "BadChannel"; // = Channel(); //.Name = "BadChannel";
}
}
void RooStats::HistFactory::Channel::AddSample( RooStats::HistFactory::Sample sample ) {
sample.SetChannelName( GetName() );
fSamples.push_back( sample );
}
void RooStats::HistFactory::Channel::Print( std::ostream& stream ) {
stream << "\t Channel Name: " << fName
<< "\t InputFile: " << fInputFile
<< std::endl;
stream << "\t Data:" << std::endl;
fData.Print( stream );
stream << "\t statErrorConfig:" << std::endl;
fStatErrorConfig.Print( stream );
if( fSamples.size() != 0 ) {
stream << "\t Samples: " << std::endl;
for( unsigned int i = 0; i < fSamples.size(); ++i ) {
fSamples.at(i).Print( stream );
}
}
stream << "\t End of Channel " << fName << std::endl;
}
void RooStats::HistFactory::Channel::PrintXML( std::string Directory, std::string Prefix ) {
// Create an XML file for this channel
std::cout << "Printing XML Files for channel: " << GetName() << std::endl;
std::string XMLName = Prefix + fName + ".xml";
if( Directory != "" ) XMLName = Directory + "/" + XMLName;
ofstream xml( XMLName.c_str() );
// Add the time
xml << "<!--" << std::endl;
xml << "This xml file created automatically on: " << std::endl;
/*
time_t t = time(0); // get time now
struct tm * now = localtime( &t );
xml << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< std::endl;
*/
// LM: use TTimeStamp since time_t does not work on Windows
TTimeStamp t;
UInt_t year = 0;
UInt_t month = 0;
UInt_t day = 0;
t.GetDate(true, 0, &year, &month, &day);
xml << year << '-'
<< month << '-'
<< day
<< std::endl;
xml << "-->" << std::endl;
// Add the DOCTYPE
xml << "<!DOCTYPE Channel SYSTEM 'HistFactorySchema.dtd'> " << std::endl << std::endl;
// Add the Channel
xml << " <Channel Name=\"" << fName << "\" InputFile=\"" << fInputFile << "\" >" << std::endl << std::endl;
xml << " <Data HistoName=\"" << fData.GetHistoName() << "\" "
<< "InputFile=\"" << fData.GetInputFile() << "\" "
<< "HistoPath=\"" << fData.GetHistoPath() << "\" "
<< " /> " << std::endl << std::endl;
xml << " <StatErrorConfig RelErrorThreshold=\"" << fStatErrorConfig.GetRelErrorThreshold() << "\" "
<< "ConstraintType=\"" << Constraint::Name( fStatErrorConfig.GetConstraintType() ) << "\" "
<< "/> " << std::endl << std::endl;
for( unsigned int i = 0; i < fSamples.size(); ++i ) {
fSamples.at(i).PrintXML( xml );
xml << std::endl << std::endl;
}
xml << std::endl;
xml << " </Channel> " << std::endl;
xml.close();
std::cout << "Finished printing XML files" << std::endl;
}
void RooStats::HistFactory::Channel::SetData( std::string DataHistoName, std::string DataInputFile, std::string DataHistoPath ) {
fData.SetHistoName( DataHistoName );
fData.SetInputFile( DataInputFile );
fData.SetHistoPath( DataHistoPath );
}
void RooStats::HistFactory::Channel::SetData( TH1* hData ) {
fData.SetHisto( hData );
}
void RooStats::HistFactory::Channel::SetData( double val ) {
// For a NumberCounting measurement only
// Set the value of data in a particular channel
//
// Internally, this simply creates a 1-bin TH1F for you
std::string DataHistName = fName + "_data";
// Histogram has 1-bin (hard-coded)
TH1F* hData = new TH1F( DataHistName.c_str(), DataHistName.c_str(), 1, 0, 1 );
hData->SetBinContent( 1, val );
// Set the histogram of the internally held data
// node of this channel to this newly created histogram
SetData( hData );
}
void RooStats::HistFactory::Channel::SetStatErrorConfig( double StatRelErrorThreshold, Constraint::Type StatConstraintType ) {
fStatErrorConfig.SetRelErrorThreshold( StatRelErrorThreshold );
fStatErrorConfig.SetConstraintType( StatConstraintType );
}
void RooStats::HistFactory::Channel::SetStatErrorConfig( double StatRelErrorThreshold, std::string StatConstraintType ) {
fStatErrorConfig.SetRelErrorThreshold( StatRelErrorThreshold );
fStatErrorConfig.SetConstraintType( Constraint::GetType(StatConstraintType) );
}
void RooStats::HistFactory::Channel::CollectHistograms() {
// Loop through all Samples and Systematics
// and collect all necessary histograms
// Get the Data Histogram:
fData.SetHisto( GetHistogram(fData.GetInputFile(),
fData.GetHistoPath(),
fData.GetHistoName()) );
// Get the histograms for the samples:
for( unsigned int sampItr = 0; sampItr < fSamples.size(); ++sampItr ) {
RooStats::HistFactory::Sample& sample = fSamples.at( sampItr );
// Get the nominal histogram:
std::cout << "Collecting Nominal Histogram" << std::endl;
TH1* Nominal = GetHistogram(sample.GetInputFile(),
sample.GetHistoPath(),
sample.GetHistoName());
sample.SetHisto( Nominal );
// Get the StatError Histogram (if necessary)
if( sample.GetStatError().GetUseHisto() ) {
sample.GetStatError().SetErrorHist( GetHistogram(sample.GetStatError().GetInputFile(),
sample.GetStatError().GetHistoPath(),
sample.GetStatError().GetHistoName()) );
}
// Get the HistoSys Variations:
for( unsigned int histoSysItr = 0; histoSysItr < sample.GetHistoSysList().size(); ++histoSysItr ) {
RooStats::HistFactory::HistoSys& histoSys = sample.GetHistoSysList().at( histoSysItr );
histoSys.SetHistoLow( GetHistogram(histoSys.GetInputFileLow(),
histoSys.GetHistoPathLow(),
histoSys.GetHistoNameLow()) );
histoSys.SetHistoHigh( GetHistogram(histoSys.GetInputFileHigh(),
histoSys.GetHistoPathHigh(),
histoSys.GetHistoNameHigh()) );
} // End Loop over HistoSys
// Get the HistoFactor Variations:
for( unsigned int histoFactorItr = 0; histoFactorItr < sample.GetHistoFactorList().size(); ++histoFactorItr ) {
RooStats::HistFactory::HistoFactor& histoFactor = sample.GetHistoFactorList().at( histoFactorItr );
histoFactor.SetHistoLow( GetHistogram(histoFactor.GetInputFileLow(),
histoFactor.GetHistoPathLow(),
histoFactor.GetHistoNameLow()) );
histoFactor.SetHistoHigh( GetHistogram(histoFactor.GetInputFileHigh(),
histoFactor.GetHistoPathHigh(),
histoFactor.GetHistoNameHigh()) );
} // End Loop over HistoFactor
// Get the ShapeSys Variations:
for( unsigned int shapeSysItr = 0; shapeSysItr < sample.GetShapeSysList().size(); ++shapeSysItr ) {
RooStats::HistFactory::ShapeSys& shapeSys = sample.GetShapeSysList().at( shapeSysItr );
shapeSys.SetErrorHist( GetHistogram(shapeSys.GetInputFile(),
shapeSys.GetHistoPath(),
shapeSys.GetHistoName()) );
} // End Loop over ShapeSys
} // End Loop over Samples
return;
}
bool RooStats::HistFactory::Channel::CheckHistograms() {
// Check that all internal histogram pointers
// are properly configured (ie that they're not NULL)
try {
if( fData.GetHisto() == NULL ) {
std::cout << "Error: Data Histogram for channel " << GetName() << " is NULL." << std::endl;
throw bad_hf;
}
// Get the histograms for the samples:
for( unsigned int sampItr = 0; sampItr < fSamples.size(); ++sampItr ) {
RooStats::HistFactory::Sample& sample = fSamples.at( sampItr );
// Get the nominal histogram:
if( sample.GetHisto() == NULL ) {
std::cout << "Error: Nominal Histogram for sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
// Get the StatError Histogram (if necessary)
if( sample.GetStatError().GetUseHisto() ) {
if( sample.GetStatError().GetErrorHist() == NULL ) {
std::cout << "Error: Statistical Error Histogram for sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
}
// Get the HistoSys Variations:
for( unsigned int histoSysItr = 0; histoSysItr < sample.GetHistoSysList().size(); ++histoSysItr ) {
RooStats::HistFactory::HistoSys& histoSys = sample.GetHistoSysList().at( histoSysItr );
if( histoSys.GetHistoLow() == NULL ) {
std::cout << "Error: HistoSyst Low for Systematic " << histoSys.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
if( histoSys.GetHistoHigh() == NULL ) {
std::cout << "Error: HistoSyst High for Systematic " << histoSys.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
} // End Loop over HistoSys
// Get the HistoFactor Variations:
for( unsigned int histoFactorItr = 0; histoFactorItr < sample.GetHistoFactorList().size(); ++histoFactorItr ) {
RooStats::HistFactory::HistoFactor& histoFactor = sample.GetHistoFactorList().at( histoFactorItr );
if( histoFactor.GetHistoLow() == NULL ) {
std::cout << "Error: HistoSyst Low for Systematic " << histoFactor.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
if( histoFactor.GetHistoHigh() == NULL ) {
std::cout << "Error: HistoSyst High for Systematic " << histoFactor.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
} // End Loop over HistoFactor
// Get the ShapeSys Variations:
for( unsigned int shapeSysItr = 0; shapeSysItr < sample.GetShapeSysList().size(); ++shapeSysItr ) {
RooStats::HistFactory::ShapeSys& shapeSys = sample.GetShapeSysList().at( shapeSysItr );
if( shapeSys.GetErrorHist() == NULL ) {
std::cout << "Error: HistoSyst High for Systematic " << shapeSys.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
} // End Loop over ShapeSys
} // End Loop over Samples
}
catch(exception& e)
{
std::cout << e.what() << std::endl;
return false;
}
return true;
}
TH1* RooStats::HistFactory::Channel::GetHistogram(std::string InputFile, std::string HistoPath, std::string HistoName) {
std::cout << "Getting histogram. "
<< " InputFile " << InputFile
<< " HistoPath " << HistoPath
<< " HistoName " << HistoName
<< std::endl;
// TFile* file = TFile::Open( InputFile.c_str() );
TFile* inFile = TFile::Open( InputFile.c_str() );
if( !inFile ) {
std::cout << "Error: Unable to open input file: " << InputFile << std::endl;
throw bad_hf;
}
std::cout << "Opened input file: " << InputFile << ": " << inFile << std::endl;
std::string HistNameFull = HistoPath + HistoName;
if( HistoPath != std::string("") ) {
if( HistoPath[ HistoPath.length()-1 ] != std::string("/") ) {
std::cout << "WARNING: Histogram path is set to: " << HistoPath
<< " but it should end with a '/' " << std::endl;
std::cout << "Total histogram path is now: " << HistNameFull << std::endl;
}
}
TH1* hist = NULL;
try{
hist = dynamic_cast<TH1*>( inFile->Get( HistNameFull.c_str() ) );
}
catch(std::exception& e)
{
std::cout << "Failed to cast object to TH1*" << std::endl;
std::cout << e.what() << std::endl;
throw bad_hf;
}
if( !hist ) {
std::cout << "Failed to get histogram: " << HistNameFull
<< " in file: " << InputFile << std::endl;
throw bad_hf;
}
TH1 * ptr = (TH1 *) hist->Clone();
if(!ptr){
std::cerr << "Not all necessary info are set to access the input file. Check your config" << std::endl;
std::cerr << "filename: " << InputFile
<< "path: " << HistoPath
<< "obj: " << HistoName << std::endl;
throw bad_hf;
}
else {
ptr->SetDirectory(0); // for the current histogram h
}
#ifdef DEBUG
std::cout << "Found Histogram: " << HistoName " at address: " << ptr
<< " with integral " << ptr->Integral() << " and mean " << ptr->GetMean()
<< std::endl;
#endif
inFile->Close();
// Done
return ptr;
}
<commit_msg>Last missing std::.<commit_after>
#include "stdlib.h"
#include "TFile.h"
#include "TTimeStamp.h"
#include "RooStats/HistFactory/HistFactoryException.h"
#include "RooStats/HistFactory/Channel.h"
RooStats::HistFactory::Channel::Channel() :
fName( "" ) { ; }
RooStats::HistFactory::Channel::Channel(std::string ChanName, std::string ChanInputFile) :
fName( ChanName ), fInputFile( ChanInputFile ) { ; }
namespace RooStats{
namespace HistFactory{
//BadChannel = Channel();
Channel BadChannel;
// BadChannel.Name = "BadChannel"; // = Channel(); //.Name = "BadChannel";
}
}
void RooStats::HistFactory::Channel::AddSample( RooStats::HistFactory::Sample sample ) {
sample.SetChannelName( GetName() );
fSamples.push_back( sample );
}
void RooStats::HistFactory::Channel::Print( std::ostream& stream ) {
stream << "\t Channel Name: " << fName
<< "\t InputFile: " << fInputFile
<< std::endl;
stream << "\t Data:" << std::endl;
fData.Print( stream );
stream << "\t statErrorConfig:" << std::endl;
fStatErrorConfig.Print( stream );
if( fSamples.size() != 0 ) {
stream << "\t Samples: " << std::endl;
for( unsigned int i = 0; i < fSamples.size(); ++i ) {
fSamples.at(i).Print( stream );
}
}
stream << "\t End of Channel " << fName << std::endl;
}
void RooStats::HistFactory::Channel::PrintXML( std::string Directory, std::string Prefix ) {
// Create an XML file for this channel
std::cout << "Printing XML Files for channel: " << GetName() << std::endl;
std::string XMLName = Prefix + fName + ".xml";
if( Directory != "" ) XMLName = Directory + "/" + XMLName;
ofstream xml( XMLName.c_str() );
// Add the time
xml << "<!--" << std::endl;
xml << "This xml file created automatically on: " << std::endl;
/*
time_t t = time(0); // get time now
struct tm * now = localtime( &t );
xml << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday
<< std::endl;
*/
// LM: use TTimeStamp since time_t does not work on Windows
TTimeStamp t;
UInt_t year = 0;
UInt_t month = 0;
UInt_t day = 0;
t.GetDate(true, 0, &year, &month, &day);
xml << year << '-'
<< month << '-'
<< day
<< std::endl;
xml << "-->" << std::endl;
// Add the DOCTYPE
xml << "<!DOCTYPE Channel SYSTEM 'HistFactorySchema.dtd'> " << std::endl << std::endl;
// Add the Channel
xml << " <Channel Name=\"" << fName << "\" InputFile=\"" << fInputFile << "\" >" << std::endl << std::endl;
xml << " <Data HistoName=\"" << fData.GetHistoName() << "\" "
<< "InputFile=\"" << fData.GetInputFile() << "\" "
<< "HistoPath=\"" << fData.GetHistoPath() << "\" "
<< " /> " << std::endl << std::endl;
xml << " <StatErrorConfig RelErrorThreshold=\"" << fStatErrorConfig.GetRelErrorThreshold() << "\" "
<< "ConstraintType=\"" << Constraint::Name( fStatErrorConfig.GetConstraintType() ) << "\" "
<< "/> " << std::endl << std::endl;
for( unsigned int i = 0; i < fSamples.size(); ++i ) {
fSamples.at(i).PrintXML( xml );
xml << std::endl << std::endl;
}
xml << std::endl;
xml << " </Channel> " << std::endl;
xml.close();
std::cout << "Finished printing XML files" << std::endl;
}
void RooStats::HistFactory::Channel::SetData( std::string DataHistoName, std::string DataInputFile, std::string DataHistoPath ) {
fData.SetHistoName( DataHistoName );
fData.SetInputFile( DataInputFile );
fData.SetHistoPath( DataHistoPath );
}
void RooStats::HistFactory::Channel::SetData( TH1* hData ) {
fData.SetHisto( hData );
}
void RooStats::HistFactory::Channel::SetData( double val ) {
// For a NumberCounting measurement only
// Set the value of data in a particular channel
//
// Internally, this simply creates a 1-bin TH1F for you
std::string DataHistName = fName + "_data";
// Histogram has 1-bin (hard-coded)
TH1F* hData = new TH1F( DataHistName.c_str(), DataHistName.c_str(), 1, 0, 1 );
hData->SetBinContent( 1, val );
// Set the histogram of the internally held data
// node of this channel to this newly created histogram
SetData( hData );
}
void RooStats::HistFactory::Channel::SetStatErrorConfig( double StatRelErrorThreshold, Constraint::Type StatConstraintType ) {
fStatErrorConfig.SetRelErrorThreshold( StatRelErrorThreshold );
fStatErrorConfig.SetConstraintType( StatConstraintType );
}
void RooStats::HistFactory::Channel::SetStatErrorConfig( double StatRelErrorThreshold, std::string StatConstraintType ) {
fStatErrorConfig.SetRelErrorThreshold( StatRelErrorThreshold );
fStatErrorConfig.SetConstraintType( Constraint::GetType(StatConstraintType) );
}
void RooStats::HistFactory::Channel::CollectHistograms() {
// Loop through all Samples and Systematics
// and collect all necessary histograms
// Get the Data Histogram:
fData.SetHisto( GetHistogram(fData.GetInputFile(),
fData.GetHistoPath(),
fData.GetHistoName()) );
// Get the histograms for the samples:
for( unsigned int sampItr = 0; sampItr < fSamples.size(); ++sampItr ) {
RooStats::HistFactory::Sample& sample = fSamples.at( sampItr );
// Get the nominal histogram:
std::cout << "Collecting Nominal Histogram" << std::endl;
TH1* Nominal = GetHistogram(sample.GetInputFile(),
sample.GetHistoPath(),
sample.GetHistoName());
sample.SetHisto( Nominal );
// Get the StatError Histogram (if necessary)
if( sample.GetStatError().GetUseHisto() ) {
sample.GetStatError().SetErrorHist( GetHistogram(sample.GetStatError().GetInputFile(),
sample.GetStatError().GetHistoPath(),
sample.GetStatError().GetHistoName()) );
}
// Get the HistoSys Variations:
for( unsigned int histoSysItr = 0; histoSysItr < sample.GetHistoSysList().size(); ++histoSysItr ) {
RooStats::HistFactory::HistoSys& histoSys = sample.GetHistoSysList().at( histoSysItr );
histoSys.SetHistoLow( GetHistogram(histoSys.GetInputFileLow(),
histoSys.GetHistoPathLow(),
histoSys.GetHistoNameLow()) );
histoSys.SetHistoHigh( GetHistogram(histoSys.GetInputFileHigh(),
histoSys.GetHistoPathHigh(),
histoSys.GetHistoNameHigh()) );
} // End Loop over HistoSys
// Get the HistoFactor Variations:
for( unsigned int histoFactorItr = 0; histoFactorItr < sample.GetHistoFactorList().size(); ++histoFactorItr ) {
RooStats::HistFactory::HistoFactor& histoFactor = sample.GetHistoFactorList().at( histoFactorItr );
histoFactor.SetHistoLow( GetHistogram(histoFactor.GetInputFileLow(),
histoFactor.GetHistoPathLow(),
histoFactor.GetHistoNameLow()) );
histoFactor.SetHistoHigh( GetHistogram(histoFactor.GetInputFileHigh(),
histoFactor.GetHistoPathHigh(),
histoFactor.GetHistoNameHigh()) );
} // End Loop over HistoFactor
// Get the ShapeSys Variations:
for( unsigned int shapeSysItr = 0; shapeSysItr < sample.GetShapeSysList().size(); ++shapeSysItr ) {
RooStats::HistFactory::ShapeSys& shapeSys = sample.GetShapeSysList().at( shapeSysItr );
shapeSys.SetErrorHist( GetHistogram(shapeSys.GetInputFile(),
shapeSys.GetHistoPath(),
shapeSys.GetHistoName()) );
} // End Loop over ShapeSys
} // End Loop over Samples
return;
}
bool RooStats::HistFactory::Channel::CheckHistograms() {
// Check that all internal histogram pointers
// are properly configured (ie that they're not NULL)
try {
if( fData.GetHisto() == NULL ) {
std::cout << "Error: Data Histogram for channel " << GetName() << " is NULL." << std::endl;
throw bad_hf;
}
// Get the histograms for the samples:
for( unsigned int sampItr = 0; sampItr < fSamples.size(); ++sampItr ) {
RooStats::HistFactory::Sample& sample = fSamples.at( sampItr );
// Get the nominal histogram:
if( sample.GetHisto() == NULL ) {
std::cout << "Error: Nominal Histogram for sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
// Get the StatError Histogram (if necessary)
if( sample.GetStatError().GetUseHisto() ) {
if( sample.GetStatError().GetErrorHist() == NULL ) {
std::cout << "Error: Statistical Error Histogram for sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
}
// Get the HistoSys Variations:
for( unsigned int histoSysItr = 0; histoSysItr < sample.GetHistoSysList().size(); ++histoSysItr ) {
RooStats::HistFactory::HistoSys& histoSys = sample.GetHistoSysList().at( histoSysItr );
if( histoSys.GetHistoLow() == NULL ) {
std::cout << "Error: HistoSyst Low for Systematic " << histoSys.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
if( histoSys.GetHistoHigh() == NULL ) {
std::cout << "Error: HistoSyst High for Systematic " << histoSys.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
} // End Loop over HistoSys
// Get the HistoFactor Variations:
for( unsigned int histoFactorItr = 0; histoFactorItr < sample.GetHistoFactorList().size(); ++histoFactorItr ) {
RooStats::HistFactory::HistoFactor& histoFactor = sample.GetHistoFactorList().at( histoFactorItr );
if( histoFactor.GetHistoLow() == NULL ) {
std::cout << "Error: HistoSyst Low for Systematic " << histoFactor.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
if( histoFactor.GetHistoHigh() == NULL ) {
std::cout << "Error: HistoSyst High for Systematic " << histoFactor.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
} // End Loop over HistoFactor
// Get the ShapeSys Variations:
for( unsigned int shapeSysItr = 0; shapeSysItr < sample.GetShapeSysList().size(); ++shapeSysItr ) {
RooStats::HistFactory::ShapeSys& shapeSys = sample.GetShapeSysList().at( shapeSysItr );
if( shapeSys.GetErrorHist() == NULL ) {
std::cout << "Error: HistoSyst High for Systematic " << shapeSys.GetName()
<< " in sample " << sample.GetName() << " is NULL." << std::endl;
throw bad_hf;
}
} // End Loop over ShapeSys
} // End Loop over Samples
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
return false;
}
return true;
}
TH1* RooStats::HistFactory::Channel::GetHistogram(std::string InputFile, std::string HistoPath, std::string HistoName) {
std::cout << "Getting histogram. "
<< " InputFile " << InputFile
<< " HistoPath " << HistoPath
<< " HistoName " << HistoName
<< std::endl;
// TFile* file = TFile::Open( InputFile.c_str() );
TFile* inFile = TFile::Open( InputFile.c_str() );
if( !inFile ) {
std::cout << "Error: Unable to open input file: " << InputFile << std::endl;
throw bad_hf;
}
std::cout << "Opened input file: " << InputFile << ": " << inFile << std::endl;
std::string HistNameFull = HistoPath + HistoName;
if( HistoPath != std::string("") ) {
if( HistoPath[ HistoPath.length()-1 ] != std::string("/") ) {
std::cout << "WARNING: Histogram path is set to: " << HistoPath
<< " but it should end with a '/' " << std::endl;
std::cout << "Total histogram path is now: " << HistNameFull << std::endl;
}
}
TH1* hist = NULL;
try{
hist = dynamic_cast<TH1*>( inFile->Get( HistNameFull.c_str() ) );
}
catch(std::exception& e)
{
std::cout << "Failed to cast object to TH1*" << std::endl;
std::cout << e.what() << std::endl;
throw bad_hf;
}
if( !hist ) {
std::cout << "Failed to get histogram: " << HistNameFull
<< " in file: " << InputFile << std::endl;
throw bad_hf;
}
TH1 * ptr = (TH1 *) hist->Clone();
if(!ptr){
std::cerr << "Not all necessary info are set to access the input file. Check your config" << std::endl;
std::cerr << "filename: " << InputFile
<< "path: " << HistoPath
<< "obj: " << HistoName << std::endl;
throw bad_hf;
}
else {
ptr->SetDirectory(0); // for the current histogram h
}
#ifdef DEBUG
std::cout << "Found Histogram: " << HistoName " at address: " << ptr
<< " with integral " << ptr->Integral() << " and mean " << ptr->GetMean()
<< std::endl;
#endif
inFile->Close();
// Done
return ptr;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, 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 "security_manager/security_manager_impl.h"
#include "security_manager/crypto_manager_impl.h"
#include "protocol_handler/protocol_packet.h"
#include "utils/logger.h"
#include "utils/byte_order.h"
#include "json/json.h"
namespace security_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "SecurityManager")
static const char* kErrId = "id";
static const char* kErrText = "text";
SecurityManagerImpl::SecurityManagerImpl()
: security_messages_("SecurityManager", this),
session_observer_(NULL), crypto_manager_(NULL), protocol_handler_(NULL) {
}
void SecurityManagerImpl::OnMessageReceived(
const ::protocol_handler::RawMessagePtr message) {
if (message->service_type() != protocol_handler::kControl) {
return;
}
SecurityMessage securityMessagePtr(new SecurityQuery());
const bool result = securityMessagePtr->SerializeQuery(
message->data(), message->data_size());
if (!result) {
// result will be false only if data less then query header
const std::string error_text("Incorrect message received");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(message->connection_key(),
ERROR_INVALID_QUERY_SIZE, error_text);
return;
}
securityMessagePtr->set_connection_key(message->connection_key());
// Post message to message query for next processing in thread
security_messages_.PostMessage(securityMessagePtr);
}
void SecurityManagerImpl::OnMobileMessageSent(
const ::protocol_handler::RawMessagePtr ) {
}
void SecurityManagerImpl::set_session_observer(
protocol_handler::SessionObserver *observer) {
if (!observer) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SessionObserver.");
return;
}
session_observer_ = observer;
}
void SecurityManagerImpl::set_protocol_handler(
protocol_handler::ProtocolHandler *handler) {
if (!handler) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to ProtocolHandler.");
return;
}
protocol_handler_ = handler;
}
void SecurityManagerImpl::set_crypto_manager(CryptoManager *crypto_manager) {
if (!crypto_manager) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to CryptoManager.");
return;
}
crypto_manager_ = crypto_manager;
}
void SecurityManagerImpl::Handle(const SecurityMessage message) {
DCHECK(message);
LOG4CXX_INFO(logger_, "Received Security message from Mobile side");
if (!crypto_manager_) {
const std::string error_text("Invalid (NULL) CryptoManager.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(message->get_connection_key(),
ERROR_NOT_SUPPORTED, error_text);
return;
}
switch (message->get_header().query_id) {
case SecurityQuery::SEND_HANDSHAKE_DATA:
if (!ProccessHandshakeData(message)) {
LOG4CXX_ERROR(logger_, "Proccess HandshakeData failed");
}
break;
case SecurityQuery::SEND_INTERNAL_ERROR:
if (!ProccessInternalError(message)) {
LOG4CXX_ERROR(logger_, "Processing income InternalError failed");
}
break;
default: {
// SecurityQuery::InvalidQuery
const std::string error_text("Unknown query identifier.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(message->get_connection_key(),
ERROR_INVALID_QUERY_ID, error_text,
message->get_header().seq_number);
}
break;
}
}
security_manager::SSLContext *SecurityManagerImpl::CreateSSLContext(
const uint32_t &connection_key) {
LOG4CXX_INFO(logger_, "ProtectService processing");
DCHECK(session_observer_);
DCHECK(crypto_manager_);
security_manager::SSLContext *ssl_context =
session_observer_->GetSSLContext(connection_key, protocol_handler::kControl);
// return exists SSLCOntext for current connection/session
if (ssl_context) {
return ssl_context;
}
ssl_context = crypto_manager_->CreateSSLContext();
if (!ssl_context) {
const std::string error_text("CryptoManager could not create SSL context.");
LOG4CXX_ERROR(logger_, error_text);
// Generate response query and post to security_messages_
SendInternalError(connection_key, ERROR_INTERNAL,
error_text);
return NULL;
}
const int result = session_observer_->SetSSLContext(connection_key, ssl_context);
if (ERROR_SUCCESS != result) {
// delete SSLContext on any error
crypto_manager_->ReleaseSSLContext(ssl_context);
SendInternalError(connection_key, result, "");
return NULL;
}
DCHECK(session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl));
LOG4CXX_DEBUG(logger_, "Set SSL context to connection_key " << connection_key);
return ssl_context;
}
void SecurityManagerImpl::StartHandshake(uint32_t connection_key) {
DCHECK(session_observer_);
LOG4CXX_INFO(logger_, "StartHandshake: connection_key " << connection_key);
security_manager::SSLContext *ssl_context =
session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl);
if (!ssl_context) {
const std::string error_text("StartHandshake failed, "
"connection is not protected");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
if (ssl_context->IsInitCompleted()) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
return;
}
ssl_context->SetHandshakeContext(
session_observer_->GetHandshakeContext(connection_key));
size_t data_size = 0;
const uint8_t *data = NULL;
const security_manager::SSLContext::HandshakeResult result =
ssl_context->StartHandshake(&data, &data_size);
if (security_manager::SSLContext::Handshake_Result_Success != result) {
const std::string error_text("StartHandshake failed, handshake step fail");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
// for client mode will be generated output data
if (data != NULL && data_size != 0) {
SendHandshakeBinData(connection_key, data, data_size);
}
}
void SecurityManagerImpl::AddListener(SecurityManagerListener *const listener) {
if (!listener) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.push_back(listener);
}
void SecurityManagerImpl::RemoveListener(SecurityManagerListener *const listener) {
if (!listener) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.remove(listener);
}
void SecurityManagerImpl::NotifyListenersOnHandshakeDone(
const uint32_t &connection_key,
SSLContext::HandshakeResult error) {
LOG4CXX_AUTO_TRACE(logger_);
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
if ((*it)->OnHandshakeDone(connection_key, error)) {
// On get notification remove listener
it = listeners_.erase(it);
} else {
++it;
}
}
}
bool SecurityManagerImpl::ProccessHandshakeData(const SecurityMessage &inMessage) {
LOG4CXX_INFO(logger_, "SendHandshakeData processing");
DCHECK(inMessage);
DCHECK(inMessage->get_header().query_id == SecurityQuery::SEND_HANDSHAKE_DATA);
const uint32_t seqNumber = inMessage->get_header().seq_number;
const uint32_t connection_key = inMessage->get_connection_key();
LOG4CXX_DEBUG(logger_, "Received " << inMessage->get_data_size()
<< " bytes handshake data ");
if (!inMessage->get_data_size()) {
const std::string error_text("SendHandshakeData: null arguments size.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INVALID_QUERY_SIZE,
error_text, seqNumber);
return false;
}
DCHECK(session_observer_);
SSLContext *sslContext =
session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl);
if (!sslContext) {
const std::string error_text("SendHandshakeData: No ssl context.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_SERVICE_NOT_PROTECTED,
error_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return false;
}
size_t out_data_size;
const uint8_t *out_data;
const SSLContext::HandshakeResult handshake_result =
sslContext->DoHandshakeStep(inMessage->get_data(), inMessage->get_data_size(),
&out_data, &out_data_size);
if (handshake_result == SSLContext::Handshake_Result_AbnormalFail) {
// Do not return handshake data on AbnormalFail or null returned values
const std::string erorr_text(sslContext->LastError());
LOG4CXX_ERROR(logger_, "SendHandshakeData: Handshake failed: " << erorr_text);
SendInternalError(connection_key,
ERROR_SSL_INVALID_DATA, erorr_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
// no handshake data to send
return false;
}
if (sslContext->IsInitCompleted()) {
// On handshake success
LOG4CXX_DEBUG(logger_, "SSL initialization finished success.");
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
} else if (handshake_result != SSLContext::Handshake_Result_Success){
// On handshake fail
LOG4CXX_WARN(logger_, "SSL initialization finished with fail.");
NotifyListenersOnHandshakeDone(connection_key, handshake_result);
}
if (out_data && out_data_size) {
// answer with the same seqNumber as income message
SendHandshakeBinData(connection_key, out_data, out_data_size,
seqNumber);
}
return true;
}
bool SecurityManagerImpl::ProccessInternalError(const SecurityMessage &inMessage) {
LOG4CXX_INFO(logger_, "Received InternalError with Json message"
<< inMessage->get_json_message());
Json::Value root;
Json::Reader reader;
const bool parsingSuccessful =
reader.parse(inMessage->get_json_message(), root);
if (!parsingSuccessful)
return false;
LOG4CXX_DEBUG(logger_, "Received InternalError id " << root[kErrId].asString()
<< ", text: " << root[kErrText].asString());
return true;
}
void SecurityManagerImpl::SendHandshakeBinData(
const uint32_t connection_key, const uint8_t *const data,
const size_t data_size, const uint32_t seq_number) {
const SecurityQuery::QueryHeader header(
SecurityQuery::NOTIFICATION,
SecurityQuery::SEND_HANDSHAKE_DATA, seq_number);
DCHECK(data_size < 1024 * 1024 *1024 );
const SecurityQuery query = SecurityQuery(header, connection_key, data, data_size);
SendQuery(query, connection_key);
LOG4CXX_DEBUG(logger_, "Sent " << data_size << " bytes handshake data ");
}
void SecurityManagerImpl::SendInternalError(const uint32_t connection_key,
const uint8_t &error_id,
const std::string &erorr_text,
const uint32_t seq_number) {
Json::Value value;
value[kErrId] = error_id;
value[kErrText] = erorr_text;
const std::string error_str = value.toStyledString();
SecurityQuery::QueryHeader header(SecurityQuery::NOTIFICATION,
SecurityQuery::SEND_INTERNAL_ERROR,
// header save json size only (exclude last byte)
seq_number, error_str.size());
// Raw data is json string and error id at last byte
std::vector<uint8_t> data_sending(error_str.size() + 1);
memcpy(&data_sending[0], error_str.c_str(), error_str.size());
data_sending[data_sending.size()-1] = error_id;
const SecurityQuery query(header, connection_key,
&data_sending[0], data_sending.size());
SendQuery(query, connection_key);
LOG4CXX_DEBUG(logger_, "Sent Internal error id " << static_cast<int>(error_id)
<< " : \"" << erorr_text << "\".");
}
void SecurityManagerImpl::SendQuery(const SecurityQuery& query,
const uint32_t connection_key) {
const std::vector<uint8_t> data_sending = query.DeserializeQuery();
uint32_t connection_handle = 0;
uint8_t sessionID = 0;
uint8_t protocol_version;
session_observer_->PairFromKey(connection_key, &connection_handle,
&sessionID);
if (session_observer_->ProtocolVersionUsed(connection_handle, sessionID,
protocol_version)) {
const ::protocol_handler::RawMessagePtr rawMessagePtr(
new protocol_handler::RawMessage(connection_key,
protocol_version,
&data_sending[0], data_sending.size(),
protocol_handler::kControl));
DCHECK(protocol_handler_);
// Add RawMessage to ProtocolHandler message query
protocol_handler_->SendMessageToMobileApp(rawMessagePtr, false);
}
}
const char *SecurityManagerImpl::ConfigSection() {
return "Security Manager";
}
} // namespace security_manager
<commit_msg>Move check of expired certificate to start of hanshake<commit_after>/*
* Copyright (c) 2014, 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 "security_manager/security_manager_impl.h"
#include "security_manager/crypto_manager_impl.h"
#include "protocol_handler/protocol_packet.h"
#include "utils/logger.h"
#include "utils/byte_order.h"
#include "json/json.h"
namespace security_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "SecurityManager")
static const char* kErrId = "id";
static const char* kErrText = "text";
SecurityManagerImpl::SecurityManagerImpl()
: security_messages_("SecurityManager", this),
session_observer_(NULL), crypto_manager_(NULL), protocol_handler_(NULL) {
}
void SecurityManagerImpl::OnMessageReceived(
const ::protocol_handler::RawMessagePtr message) {
if (message->service_type() != protocol_handler::kControl) {
return;
}
SecurityMessage securityMessagePtr(new SecurityQuery());
const bool result = securityMessagePtr->SerializeQuery(
message->data(), message->data_size());
if (!result) {
// result will be false only if data less then query header
const std::string error_text("Incorrect message received");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(message->connection_key(),
ERROR_INVALID_QUERY_SIZE, error_text);
return;
}
securityMessagePtr->set_connection_key(message->connection_key());
// Post message to message query for next processing in thread
security_messages_.PostMessage(securityMessagePtr);
}
void SecurityManagerImpl::OnMobileMessageSent(
const ::protocol_handler::RawMessagePtr ) {
}
void SecurityManagerImpl::set_session_observer(
protocol_handler::SessionObserver *observer) {
if (!observer) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SessionObserver.");
return;
}
session_observer_ = observer;
}
void SecurityManagerImpl::set_protocol_handler(
protocol_handler::ProtocolHandler *handler) {
if (!handler) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to ProtocolHandler.");
return;
}
protocol_handler_ = handler;
}
void SecurityManagerImpl::set_crypto_manager(CryptoManager *crypto_manager) {
if (!crypto_manager) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to CryptoManager.");
return;
}
crypto_manager_ = crypto_manager;
}
void SecurityManagerImpl::Handle(const SecurityMessage message) {
DCHECK(message);
LOG4CXX_INFO(logger_, "Received Security message from Mobile side");
if (!crypto_manager_) {
const std::string error_text("Invalid (NULL) CryptoManager.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(message->get_connection_key(),
ERROR_NOT_SUPPORTED, error_text);
return;
}
switch (message->get_header().query_id) {
case SecurityQuery::SEND_HANDSHAKE_DATA:
if (!ProccessHandshakeData(message)) {
LOG4CXX_ERROR(logger_, "Proccess HandshakeData failed");
}
break;
case SecurityQuery::SEND_INTERNAL_ERROR:
if (!ProccessInternalError(message)) {
LOG4CXX_ERROR(logger_, "Processing income InternalError failed");
}
break;
default: {
// SecurityQuery::InvalidQuery
const std::string error_text("Unknown query identifier.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(message->get_connection_key(),
ERROR_INVALID_QUERY_ID, error_text,
message->get_header().seq_number);
}
break;
}
}
security_manager::SSLContext *SecurityManagerImpl::CreateSSLContext(
const uint32_t &connection_key) {
LOG4CXX_INFO(logger_, "ProtectService processing");
DCHECK(session_observer_);
DCHECK(crypto_manager_);
security_manager::SSLContext *ssl_context =
session_observer_->GetSSLContext(connection_key, protocol_handler::kControl);
// return exists SSLCOntext for current connection/session
if (ssl_context) {
return ssl_context;
}
ssl_context = crypto_manager_->CreateSSLContext();
if (!ssl_context) {
const std::string error_text("CryptoManager could not create SSL context.");
LOG4CXX_ERROR(logger_, error_text);
// Generate response query and post to security_messages_
SendInternalError(connection_key, ERROR_INTERNAL,
error_text);
return NULL;
}
const int result = session_observer_->SetSSLContext(connection_key, ssl_context);
if (ERROR_SUCCESS != result) {
// delete SSLContext on any error
crypto_manager_->ReleaseSSLContext(ssl_context);
SendInternalError(connection_key, result, "");
return NULL;
}
DCHECK(session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl));
LOG4CXX_DEBUG(logger_, "Set SSL context to connection_key " << connection_key);
return ssl_context;
}
void SecurityManagerImpl::StartHandshake(uint32_t connection_key) {
DCHECK(session_observer_);
LOG4CXX_INFO(logger_, "StartHandshake: connection_key " << connection_key);
security_manager::SSLContext *ssl_context =
session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl);
if (!ssl_context) {
const std::string error_text("StartHandshake failed, "
"connection is not protected");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
if(crypto_manager_->IsCertificateUpdateRequired()) {
NotifyOnCertififcateUpdateRequired();
}
if (ssl_context->IsInitCompleted()) {
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
return;
}
ssl_context->SetHandshakeContext(
session_observer_->GetHandshakeContext(connection_key));
size_t data_size = 0;
const uint8_t *data = NULL;
const security_manager::SSLContext::HandshakeResult result =
ssl_context->StartHandshake(&data, &data_size);
if (security_manager::SSLContext::Handshake_Result_Success != result) {
const std::string error_text("StartHandshake failed, handshake step fail");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return;
}
// for client mode will be generated output data
if (data != NULL && data_size != 0) {
SendHandshakeBinData(connection_key, data, data_size);
}
}
void SecurityManagerImpl::AddListener(SecurityManagerListener *const listener) {
if (!listener) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.push_back(listener);
}
void SecurityManagerImpl::RemoveListener(SecurityManagerListener *const listener) {
if (!listener) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.remove(listener);
}
void SecurityManagerImpl::NotifyListenersOnHandshakeDone(
const uint32_t &connection_key,
SSLContext::HandshakeResult error) {
LOG4CXX_AUTO_TRACE(logger_);
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
if ((*it)->OnHandshakeDone(connection_key, error)) {
// On get notification remove listener
it = listeners_.erase(it);
} else {
++it;
}
}
}
bool SecurityManagerImpl::ProccessHandshakeData(const SecurityMessage &inMessage) {
LOG4CXX_INFO(logger_, "SendHandshakeData processing");
DCHECK(inMessage);
DCHECK(inMessage->get_header().query_id == SecurityQuery::SEND_HANDSHAKE_DATA);
const uint32_t seqNumber = inMessage->get_header().seq_number;
const uint32_t connection_key = inMessage->get_connection_key();
LOG4CXX_DEBUG(logger_, "Received " << inMessage->get_data_size()
<< " bytes handshake data ");
if (!inMessage->get_data_size()) {
const std::string error_text("SendHandshakeData: null arguments size.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INVALID_QUERY_SIZE,
error_text, seqNumber);
return false;
}
DCHECK(session_observer_);
SSLContext *sslContext =
session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl);
if (!sslContext) {
const std::string error_text("SendHandshakeData: No ssl context.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_SERVICE_NOT_PROTECTED,
error_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
return false;
}
size_t out_data_size;
const uint8_t *out_data;
const SSLContext::HandshakeResult handshake_result =
sslContext->DoHandshakeStep(inMessage->get_data(), inMessage->get_data_size(),
&out_data, &out_data_size);
if (handshake_result == SSLContext::Handshake_Result_AbnormalFail) {
// Do not return handshake data on AbnormalFail or null returned values
const std::string erorr_text(sslContext->LastError());
LOG4CXX_ERROR(logger_, "SendHandshakeData: Handshake failed: " << erorr_text);
SendInternalError(connection_key,
ERROR_SSL_INVALID_DATA, erorr_text, seqNumber);
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Fail);
// no handshake data to send
return false;
}
if (sslContext->IsInitCompleted()) {
// On handshake success
LOG4CXX_DEBUG(logger_, "SSL initialization finished success.");
NotifyListenersOnHandshakeDone(connection_key,
SSLContext::Handshake_Result_Success);
} else if (handshake_result != SSLContext::Handshake_Result_Success){
// On handshake fail
LOG4CXX_WARN(logger_, "SSL initialization finished with fail.");
NotifyListenersOnHandshakeDone(connection_key, handshake_result);
}
if (out_data && out_data_size) {
// answer with the same seqNumber as income message
SendHandshakeBinData(connection_key, out_data, out_data_size,
seqNumber);
}
return true;
}
bool SecurityManagerImpl::ProccessInternalError(const SecurityMessage &inMessage) {
LOG4CXX_INFO(logger_, "Received InternalError with Json message"
<< inMessage->get_json_message());
Json::Value root;
Json::Reader reader;
const bool parsingSuccessful =
reader.parse(inMessage->get_json_message(), root);
if (!parsingSuccessful)
return false;
LOG4CXX_DEBUG(logger_, "Received InternalError id " << root[kErrId].asString()
<< ", text: " << root[kErrText].asString());
return true;
}
void SecurityManagerImpl::SendHandshakeBinData(
const uint32_t connection_key, const uint8_t *const data,
const size_t data_size, const uint32_t seq_number) {
const SecurityQuery::QueryHeader header(
SecurityQuery::NOTIFICATION,
SecurityQuery::SEND_HANDSHAKE_DATA, seq_number);
DCHECK(data_size < 1024 * 1024 *1024 );
const SecurityQuery query = SecurityQuery(header, connection_key, data, data_size);
SendQuery(query, connection_key);
LOG4CXX_DEBUG(logger_, "Sent " << data_size << " bytes handshake data ");
}
void SecurityManagerImpl::SendInternalError(const uint32_t connection_key,
const uint8_t &error_id,
const std::string &erorr_text,
const uint32_t seq_number) {
Json::Value value;
value[kErrId] = error_id;
value[kErrText] = erorr_text;
const std::string error_str = value.toStyledString();
SecurityQuery::QueryHeader header(SecurityQuery::NOTIFICATION,
SecurityQuery::SEND_INTERNAL_ERROR,
// header save json size only (exclude last byte)
seq_number, error_str.size());
// Raw data is json string and error id at last byte
std::vector<uint8_t> data_sending(error_str.size() + 1);
memcpy(&data_sending[0], error_str.c_str(), error_str.size());
data_sending[data_sending.size()-1] = error_id;
const SecurityQuery query(header, connection_key,
&data_sending[0], data_sending.size());
SendQuery(query, connection_key);
LOG4CXX_DEBUG(logger_, "Sent Internal error id " << static_cast<int>(error_id)
<< " : \"" << erorr_text << "\".");
}
void SecurityManagerImpl::SendQuery(const SecurityQuery& query,
const uint32_t connection_key) {
const std::vector<uint8_t> data_sending = query.DeserializeQuery();
uint32_t connection_handle = 0;
uint8_t sessionID = 0;
uint8_t protocol_version;
session_observer_->PairFromKey(connection_key, &connection_handle,
&sessionID);
if (session_observer_->ProtocolVersionUsed(connection_handle, sessionID,
protocol_version)) {
const ::protocol_handler::RawMessagePtr rawMessagePtr(
new protocol_handler::RawMessage(connection_key,
protocol_version,
&data_sending[0], data_sending.size(),
protocol_handler::kControl));
DCHECK(protocol_handler_);
// Add RawMessage to ProtocolHandler message query
protocol_handler_->SendMessageToMobileApp(rawMessagePtr, false);
}
}
const char *SecurityManagerImpl::ConfigSection() {
return "Security Manager";
}
} // namespace security_manager
<|endoftext|> |
<commit_before>/*
* fujimapBlock.hpp
* Copyright (c) 2010 Daisuke Okanohara All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef FUJIMAP_BLOCK_HPP__
#define FUJIMAP_BLOCK_HPP__
#include "keyedge.hpp"
#include "bitvec.hpp"
#include <queue>
NS_IZENELIB_AM_BEGIN
namespace succinct{ namespace fujimap{
/*
* Minimum Perfect Associative Array
* used in Fujimap
*/
template <class ValueType>
class FujimapBlock
{
static const double C_R = 1.3; ///< Redundancy for bit array (>1.3)
static const uint64_t intercept = 10;
public:
FujimapBlock(); ///< Default Constructor
~FujimapBlock(); ///< Default Destructor
int build(std::vector<KeyEdge<ValueType> >& keyEdges,
const uint64_t seed, const uint64_t fpLen,
const EncodeType et); ///< build an associative map
ValueType getVal(const KeyEdge<ValueType>& ke) const; ///< return a value corresponding to the given KeyEdge
void save(std::ofstream& ofs) const; ///< save the status in ofs
void load(std::ifstream& ifs); ///< load the status from ifs
uint64_t getSeed() const;
size_t getKeyNum() const; ///<return the number of registered keys
size_t getWorkingSize() const; ///<return the current working size
private:
void test();
BitVec<ValueType> B_;
uint64_t keyNum_;
ValueType minCodeVal_;
ValueType maxCodeVal_;
uint64_t maxCodeLen_;
uint64_t fpLen_;
uint64_t seed_;
uint64_t bn_;
EncodeType et_;
};
template <class ValueType>
FujimapBlock<ValueType>::FujimapBlock()
: keyNum_(0)
, minCodeVal_(0)
, maxCodeVal_(0)
, maxCodeLen_(0)
, fpLen_(FPLEN)
, seed_(0x12345678)
, bn_(0)
, et_(BINARY)
{
}
template <class ValueType>
FujimapBlock<ValueType>::~FujimapBlock()
{
}
template <class ValueType>
ValueType FujimapBlock<ValueType>::getVal(const KeyEdge<ValueType>& ke) const
{
if (B_.bvBitSize() == 0)
{
return (ValueType)NOTFOUND;
}
uint64_t blockSize = (et_ == BINARY) ? (maxCodeLen_ + fpLen_) : 1;
if (fpLen_ != 0)
{
uint64_t fpCheck = 0;
for (uint64_t i = 0; i < R; ++i)
{
fpCheck ^= B_.get64Bits(ke.get(i, bn_) * blockSize, fpLen_);
}
if (fpCheck != FujimapCommon::maskCheckLen(ke.v[0] ^ ke.v[1], fpLen_))
{
return (ValueType)NOTFOUND;
}
}
ValueType code = 0;
for (uint64_t i = 0; i < R; ++i)
{
code ^= B_.getBits(ke.get(i, bn_) * blockSize + fpLen_, maxCodeLen_);
}
if (et_ == GAMMA)
{
code = FujimapCommon::gammaDecode(code);
}
if (code > maxCodeVal_)
{
return (ValueType)NOTFOUND;
}
return code + minCodeVal_;
}
template <class ValueType>
uint64_t FujimapBlock<ValueType>::getSeed() const
{
return seed_;
}
template <class ValueType>
int FujimapBlock<ValueType>::build(
std::vector<KeyEdge<ValueType> >& keyEdges,
const uint64_t seed, const uint64_t fpLen,
const EncodeType et)
{
keyNum_ = static_cast<uint64_t>(keyEdges.size());
seed_ = seed;
fpLen_ = fpLen;
et_ = et;
minCodeVal_ = (ValueType)-1;
maxCodeVal_ = 0;
for (size_t i = 0; i < keyEdges.size(); ++i)
{
if (keyEdges[i].code < minCodeVal_)
{
minCodeVal_ = keyEdges[i].code;
}
}
for (size_t i = 0; i < keyEdges.size(); ++i)
{
keyEdges[i].code -= minCodeVal_;
if (keyEdges[i].code > maxCodeVal_)
{
maxCodeVal_ = keyEdges[i].code;
}
}
uint64_t totalCodeLen = 0;
if (et_ == BINARY)
{
maxCodeLen_ = FujimapCommon::log2(maxCodeVal_);
totalCodeLen = (maxCodeLen_ + fpLen_) * keyNum_;
bn_ = (uint64_t)(keyNum_ * C_R / (double)R + intercept);
}
else if (et_ == GAMMA)
{
for (size_t i = 0; i < keyEdges.size(); ++i)
{
totalCodeLen += FujimapCommon::gammaLen(keyEdges[i].code);
}
totalCodeLen += fpLen_ * keyNum_;
maxCodeLen_ = FujimapCommon::gammaLen(maxCodeVal_);
bn_ = totalCodeLen * C_R / R + intercept; // <= keyNum_ * maxCodeLen_ * C_R / R + 10
}
else
{
assert(false);
}
uint64_t maxCodeFPLen = maxCodeLen_ + fpLen_;
uint64_t pointsPerKey = (et_ == BINARY) ? 1 : maxCodeFPLen;
// set_ keyEdge
uint64_t space = (et_ == BINARY) ? 0 : maxCodeFPLen;
std::vector<uint8_t> degs(bn_ * R + space);
std::vector<uint64_t> offset_s(bn_ * R + space + 1);
for (size_t i = 0; i < keyEdges.size(); ++i)
{
const KeyEdge<ValueType>& ke(keyEdges[i]);
uint64_t len = (et_ == BINARY) ? 1 : FujimapCommon::gammaLen(ke.code) + fpLen_;
for (uint64_t j = 0; j < R; ++j)
{
uint64_t t = ke.get(j, bn_);
for (uint64_t k = 0; k < len; ++k)
{
if (degs[t + k] == 0xFF)
{
return -1;
}
++degs[t + k];
}
}
}
// set_ offset_s
uint64_t sum = 0;
for (size_t i = 0; i < degs.size(); ++i)
{
offset_s[i] = sum;
sum += degs[i];
degs[i] = 0;
}
offset_s.back() = sum;
// set_ edges
uint64_t totalEdgeNum = (et_ == BINARY) ? keyNum_ * R : totalCodeLen * R;
std::vector<uint64_t> edges(totalEdgeNum);
for (size_t i = 0; i < keyEdges.size(); ++i)
{
const KeyEdge<ValueType>& ke(keyEdges[i]);
uint64_t len = (et_ == BINARY) ? 1 : FujimapCommon::gammaLen(ke.code) + fpLen_;
for (uint64_t j = 0; j < R; ++j)
{
uint64_t t = ke.get(j, bn_);
for (uint64_t k = 0; k < len; ++k)
{
edges[offset_s[t + k] + degs[t + k]++] = i * pointsPerKey + k;
}
}
}
// init q
std::queue<uint64_t> q;
for (size_t i = 0; i < degs.size(); ++i)
{
if (degs[i] == 1)
{
q.push(edges[offset_s[i]]);
}
}
std::vector<std::pair<uint64_t, uint8_t> > extractedEdges;
uint64_t assignNum = keyNum_ * pointsPerKey;
BitVec<uint64_t> visitedEdges(assignNum);
uint64_t deletedNum = 0;
while (!q.empty())
{
uint64_t v = q.front();
q.pop();
if (visitedEdges.getBit(v)) continue;
visitedEdges.setBit(v);
++deletedNum;
uint64_t keyID = v / pointsPerKey;
uint64_t offset = v % pointsPerKey;
const KeyEdge<ValueType>& ke(keyEdges[keyID]);
int choosed = -1;
for (uint64_t i = 0; i < R; ++i)
{
const uint64_t t = ke.get(i, bn_);
--degs[t + offset];
if (degs[t + offset] == 0)
{
choosed = i;
continue;
}
else if (degs[t + offset] >= 2)
{
continue;
}
// degs[t] == 1
const uint64_t end = offset_s[t + offset + 1];
for (uint64_t j = offset_s[t + offset]; j < end; ++j)
{
if (!visitedEdges.getBit(edges[j]))
{
q.push(edges[j]);
break;
}
}
}
assert(choosed != -1);
extractedEdges.push_back(std::make_pair(v, choosed));
}
if (et_ == BINARY && deletedNum != keyNum_)
{
return -1;
}
else if (et_ == GAMMA && deletedNum != totalCodeLen)
{
return -1;
}
assert(q.empty());
if (et_ == BINARY)
{
B_.resize(bn_ * maxCodeFPLen * R);
}
else if (et_ == GAMMA)
{
B_.resize(bn_ * R + space);
}
else
{
assert(false);
}
uint64_t blockSize = (et_ == BINARY ) ? maxCodeFPLen : 1;
BitVec<uint64_t> visitedVerticies(assignNum * R);
std::reverse(extractedEdges.begin(), extractedEdges.end());
for (std::vector<std::pair<uint64_t, uint8_t> >::const_iterator it =
extractedEdges.begin(); it != extractedEdges.end(); ++it)
{
const uint64_t v = it->first;
uint64_t keyID = v / pointsPerKey;
uint64_t offset = v % pointsPerKey;
const KeyEdge<ValueType>& ke(keyEdges[keyID]);
uint64_t signature = FujimapCommon::maskCheckLen(ke.v[0] ^ ke.v[1], fpLen_);
if (et_ == BINARY)
{
ValueType bits = ke.code;
for (uint64_t i = 0; i < R; ++i)
{
const uint64_t t = ke.get(i, bn_);
if (!(visitedVerticies.getBit(t + offset)))
{
continue;
}
signature ^= B_.get64Bits(t * blockSize + offset, fpLen_);
bits ^= B_.getBits(t * blockSize + offset + fpLen_, maxCodeLen_);
}
const uint64_t set_Pos = ke.get(it->second, bn_);
B_.set64Bits(set_Pos * blockSize + offset, fpLen_, signature);
B_.setBits(set_Pos * blockSize + offset + fpLen_, maxCodeLen_, bits);
visitedVerticies.setBit(set_Pos + offset);
}
else if (et_ == GAMMA)
{
bool bit;
if (offset < fpLen_)
{
bit = (signature >> offset) & 1;
}
else
{
bit = FujimapCommon::gammaEncodeBit(offset - fpLen_, ke.code);
}
for (uint64_t i = 0; i < R; ++i)
{
const uint64_t t = ke.get(i, bn_);
if (!(visitedVerticies.getBit(t + offset)))
{
continue;
}
bit ^= B_.getBit(t * blockSize + offset);
}
const uint64_t set_Pos = ke.get(it->second, bn_);
B_.set64Bits(set_Pos * blockSize + offset, 1, bit);
visitedVerticies.setBit(set_Pos + offset);
}
else
{
assert(false);
}
}
return 0;
}
template <class ValueType>
size_t FujimapBlock<ValueType>::getKeyNum() const
{
return keyNum_;
}
template <class ValueType>
size_t FujimapBlock<ValueType>::getWorkingSize() const
{
return B_.bvBitSize();
}
template <class ValueType>
void FujimapBlock<ValueType>::save(std::ofstream& ofs) const
{
ofs.write((const char*)(&keyNum_), sizeof(keyNum_));
ofs.write((const char*)(&minCodeVal_), sizeof(minCodeVal_));
ofs.write((const char*)(&maxCodeVal_), sizeof(maxCodeVal_));
ofs.write((const char*)(&maxCodeLen_), sizeof(maxCodeLen_));
ofs.write((const char*)(&fpLen_), sizeof(fpLen_));
ofs.write((const char*)(&seed_), sizeof(seed_));
ofs.write((const char*)(&bn_), sizeof(bn_));
ofs.write((const char*)(&et_), sizeof(et_));
B_.write(ofs);
}
template <class ValueType>
void FujimapBlock<ValueType>::load(std::ifstream& ifs)
{
ifs.read((char*)(&keyNum_), sizeof(keyNum_));
ifs.read((char*)(&minCodeVal_), sizeof(minCodeVal_));
ifs.read((char*)(&maxCodeVal_), sizeof(maxCodeVal_));
ifs.read((char*)(&maxCodeLen_), sizeof(maxCodeLen_));
ifs.read((char*)(&fpLen_), sizeof(fpLen_));
ifs.read((char*)(&seed_), sizeof(seed_));
ifs.read((char*)(&bn_), sizeof(bn_));
ifs.read((char*)(&et_), sizeof(et_));
B_.read(ifs);
}
}}
NS_IZENELIB_AM_END
#endif // FUJIMAP_BLOCK_HPP__
<commit_msg>constexpr is required by c++11 for fujimap<commit_after>/*
* fujimapBlock.hpp
* Copyright (c) 2010 Daisuke Okanohara All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef FUJIMAP_BLOCK_HPP__
#define FUJIMAP_BLOCK_HPP__
#include "keyedge.hpp"
#include "bitvec.hpp"
#include <queue>
NS_IZENELIB_AM_BEGIN
namespace succinct{ namespace fujimap{
/*
* Minimum Perfect Associative Array
* used in Fujimap
*/
template <class ValueType>
class FujimapBlock
{
static constexpr double C_R = 1.3; ///< Redundancy for bit array (>1.3)
static constexpr uint64_t intercept = 10;
public:
FujimapBlock(); ///< Default Constructor
~FujimapBlock(); ///< Default Destructor
int build(std::vector<KeyEdge<ValueType> >& keyEdges,
const uint64_t seed, const uint64_t fpLen,
const EncodeType et); ///< build an associative map
ValueType getVal(const KeyEdge<ValueType>& ke) const; ///< return a value corresponding to the given KeyEdge
void save(std::ofstream& ofs) const; ///< save the status in ofs
void load(std::ifstream& ifs); ///< load the status from ifs
uint64_t getSeed() const;
size_t getKeyNum() const; ///<return the number of registered keys
size_t getWorkingSize() const; ///<return the current working size
private:
void test();
BitVec<ValueType> B_;
uint64_t keyNum_;
ValueType minCodeVal_;
ValueType maxCodeVal_;
uint64_t maxCodeLen_;
uint64_t fpLen_;
uint64_t seed_;
uint64_t bn_;
EncodeType et_;
};
template <class ValueType>
FujimapBlock<ValueType>::FujimapBlock()
: keyNum_(0)
, minCodeVal_(0)
, maxCodeVal_(0)
, maxCodeLen_(0)
, fpLen_(FPLEN)
, seed_(0x12345678)
, bn_(0)
, et_(BINARY)
{
}
template <class ValueType>
FujimapBlock<ValueType>::~FujimapBlock()
{
}
template <class ValueType>
ValueType FujimapBlock<ValueType>::getVal(const KeyEdge<ValueType>& ke) const
{
if (B_.bvBitSize() == 0)
{
return (ValueType)NOTFOUND;
}
uint64_t blockSize = (et_ == BINARY) ? (maxCodeLen_ + fpLen_) : 1;
if (fpLen_ != 0)
{
uint64_t fpCheck = 0;
for (uint64_t i = 0; i < R; ++i)
{
fpCheck ^= B_.get64Bits(ke.get(i, bn_) * blockSize, fpLen_);
}
if (fpCheck != FujimapCommon::maskCheckLen(ke.v[0] ^ ke.v[1], fpLen_))
{
return (ValueType)NOTFOUND;
}
}
ValueType code = 0;
for (uint64_t i = 0; i < R; ++i)
{
code ^= B_.getBits(ke.get(i, bn_) * blockSize + fpLen_, maxCodeLen_);
}
if (et_ == GAMMA)
{
code = FujimapCommon::gammaDecode(code);
}
if (code > maxCodeVal_)
{
return (ValueType)NOTFOUND;
}
return code + minCodeVal_;
}
template <class ValueType>
uint64_t FujimapBlock<ValueType>::getSeed() const
{
return seed_;
}
template <class ValueType>
int FujimapBlock<ValueType>::build(
std::vector<KeyEdge<ValueType> >& keyEdges,
const uint64_t seed, const uint64_t fpLen,
const EncodeType et)
{
keyNum_ = static_cast<uint64_t>(keyEdges.size());
seed_ = seed;
fpLen_ = fpLen;
et_ = et;
minCodeVal_ = (ValueType)-1;
maxCodeVal_ = 0;
for (size_t i = 0; i < keyEdges.size(); ++i)
{
if (keyEdges[i].code < minCodeVal_)
{
minCodeVal_ = keyEdges[i].code;
}
}
for (size_t i = 0; i < keyEdges.size(); ++i)
{
keyEdges[i].code -= minCodeVal_;
if (keyEdges[i].code > maxCodeVal_)
{
maxCodeVal_ = keyEdges[i].code;
}
}
uint64_t totalCodeLen = 0;
if (et_ == BINARY)
{
maxCodeLen_ = FujimapCommon::log2(maxCodeVal_);
totalCodeLen = (maxCodeLen_ + fpLen_) * keyNum_;
bn_ = (uint64_t)(keyNum_ * C_R / (double)R + intercept);
}
else if (et_ == GAMMA)
{
for (size_t i = 0; i < keyEdges.size(); ++i)
{
totalCodeLen += FujimapCommon::gammaLen(keyEdges[i].code);
}
totalCodeLen += fpLen_ * keyNum_;
maxCodeLen_ = FujimapCommon::gammaLen(maxCodeVal_);
bn_ = totalCodeLen * C_R / R + intercept; // <= keyNum_ * maxCodeLen_ * C_R / R + 10
}
else
{
assert(false);
}
uint64_t maxCodeFPLen = maxCodeLen_ + fpLen_;
uint64_t pointsPerKey = (et_ == BINARY) ? 1 : maxCodeFPLen;
// set_ keyEdge
uint64_t space = (et_ == BINARY) ? 0 : maxCodeFPLen;
std::vector<uint8_t> degs(bn_ * R + space);
std::vector<uint64_t> offset_s(bn_ * R + space + 1);
for (size_t i = 0; i < keyEdges.size(); ++i)
{
const KeyEdge<ValueType>& ke(keyEdges[i]);
uint64_t len = (et_ == BINARY) ? 1 : FujimapCommon::gammaLen(ke.code) + fpLen_;
for (uint64_t j = 0; j < R; ++j)
{
uint64_t t = ke.get(j, bn_);
for (uint64_t k = 0; k < len; ++k)
{
if (degs[t + k] == 0xFF)
{
return -1;
}
++degs[t + k];
}
}
}
// set_ offset_s
uint64_t sum = 0;
for (size_t i = 0; i < degs.size(); ++i)
{
offset_s[i] = sum;
sum += degs[i];
degs[i] = 0;
}
offset_s.back() = sum;
// set_ edges
uint64_t totalEdgeNum = (et_ == BINARY) ? keyNum_ * R : totalCodeLen * R;
std::vector<uint64_t> edges(totalEdgeNum);
for (size_t i = 0; i < keyEdges.size(); ++i)
{
const KeyEdge<ValueType>& ke(keyEdges[i]);
uint64_t len = (et_ == BINARY) ? 1 : FujimapCommon::gammaLen(ke.code) + fpLen_;
for (uint64_t j = 0; j < R; ++j)
{
uint64_t t = ke.get(j, bn_);
for (uint64_t k = 0; k < len; ++k)
{
edges[offset_s[t + k] + degs[t + k]++] = i * pointsPerKey + k;
}
}
}
// init q
std::queue<uint64_t> q;
for (size_t i = 0; i < degs.size(); ++i)
{
if (degs[i] == 1)
{
q.push(edges[offset_s[i]]);
}
}
std::vector<std::pair<uint64_t, uint8_t> > extractedEdges;
uint64_t assignNum = keyNum_ * pointsPerKey;
BitVec<uint64_t> visitedEdges(assignNum);
uint64_t deletedNum = 0;
while (!q.empty())
{
uint64_t v = q.front();
q.pop();
if (visitedEdges.getBit(v)) continue;
visitedEdges.setBit(v);
++deletedNum;
uint64_t keyID = v / pointsPerKey;
uint64_t offset = v % pointsPerKey;
const KeyEdge<ValueType>& ke(keyEdges[keyID]);
int choosed = -1;
for (uint64_t i = 0; i < R; ++i)
{
const uint64_t t = ke.get(i, bn_);
--degs[t + offset];
if (degs[t + offset] == 0)
{
choosed = i;
continue;
}
else if (degs[t + offset] >= 2)
{
continue;
}
// degs[t] == 1
const uint64_t end = offset_s[t + offset + 1];
for (uint64_t j = offset_s[t + offset]; j < end; ++j)
{
if (!visitedEdges.getBit(edges[j]))
{
q.push(edges[j]);
break;
}
}
}
assert(choosed != -1);
extractedEdges.push_back(std::make_pair(v, choosed));
}
if (et_ == BINARY && deletedNum != keyNum_)
{
return -1;
}
else if (et_ == GAMMA && deletedNum != totalCodeLen)
{
return -1;
}
assert(q.empty());
if (et_ == BINARY)
{
B_.resize(bn_ * maxCodeFPLen * R);
}
else if (et_ == GAMMA)
{
B_.resize(bn_ * R + space);
}
else
{
assert(false);
}
uint64_t blockSize = (et_ == BINARY ) ? maxCodeFPLen : 1;
BitVec<uint64_t> visitedVerticies(assignNum * R);
std::reverse(extractedEdges.begin(), extractedEdges.end());
for (std::vector<std::pair<uint64_t, uint8_t> >::const_iterator it =
extractedEdges.begin(); it != extractedEdges.end(); ++it)
{
const uint64_t v = it->first;
uint64_t keyID = v / pointsPerKey;
uint64_t offset = v % pointsPerKey;
const KeyEdge<ValueType>& ke(keyEdges[keyID]);
uint64_t signature = FujimapCommon::maskCheckLen(ke.v[0] ^ ke.v[1], fpLen_);
if (et_ == BINARY)
{
ValueType bits = ke.code;
for (uint64_t i = 0; i < R; ++i)
{
const uint64_t t = ke.get(i, bn_);
if (!(visitedVerticies.getBit(t + offset)))
{
continue;
}
signature ^= B_.get64Bits(t * blockSize + offset, fpLen_);
bits ^= B_.getBits(t * blockSize + offset + fpLen_, maxCodeLen_);
}
const uint64_t set_Pos = ke.get(it->second, bn_);
B_.set64Bits(set_Pos * blockSize + offset, fpLen_, signature);
B_.setBits(set_Pos * blockSize + offset + fpLen_, maxCodeLen_, bits);
visitedVerticies.setBit(set_Pos + offset);
}
else if (et_ == GAMMA)
{
bool bit;
if (offset < fpLen_)
{
bit = (signature >> offset) & 1;
}
else
{
bit = FujimapCommon::gammaEncodeBit(offset - fpLen_, ke.code);
}
for (uint64_t i = 0; i < R; ++i)
{
const uint64_t t = ke.get(i, bn_);
if (!(visitedVerticies.getBit(t + offset)))
{
continue;
}
bit ^= B_.getBit(t * blockSize + offset);
}
const uint64_t set_Pos = ke.get(it->second, bn_);
B_.set64Bits(set_Pos * blockSize + offset, 1, bit);
visitedVerticies.setBit(set_Pos + offset);
}
else
{
assert(false);
}
}
return 0;
}
template <class ValueType>
size_t FujimapBlock<ValueType>::getKeyNum() const
{
return keyNum_;
}
template <class ValueType>
size_t FujimapBlock<ValueType>::getWorkingSize() const
{
return B_.bvBitSize();
}
template <class ValueType>
void FujimapBlock<ValueType>::save(std::ofstream& ofs) const
{
ofs.write((const char*)(&keyNum_), sizeof(keyNum_));
ofs.write((const char*)(&minCodeVal_), sizeof(minCodeVal_));
ofs.write((const char*)(&maxCodeVal_), sizeof(maxCodeVal_));
ofs.write((const char*)(&maxCodeLen_), sizeof(maxCodeLen_));
ofs.write((const char*)(&fpLen_), sizeof(fpLen_));
ofs.write((const char*)(&seed_), sizeof(seed_));
ofs.write((const char*)(&bn_), sizeof(bn_));
ofs.write((const char*)(&et_), sizeof(et_));
B_.write(ofs);
}
template <class ValueType>
void FujimapBlock<ValueType>::load(std::ifstream& ifs)
{
ifs.read((char*)(&keyNum_), sizeof(keyNum_));
ifs.read((char*)(&minCodeVal_), sizeof(minCodeVal_));
ifs.read((char*)(&maxCodeVal_), sizeof(maxCodeVal_));
ifs.read((char*)(&maxCodeLen_), sizeof(maxCodeLen_));
ifs.read((char*)(&fpLen_), sizeof(fpLen_));
ifs.read((char*)(&seed_), sizeof(seed_));
ifs.read((char*)(&bn_), sizeof(bn_));
ifs.read((char*)(&et_), sizeof(et_));
B_.read(ifs);
}
}}
NS_IZENELIB_AM_END
#endif // FUJIMAP_BLOCK_HPP__
<|endoftext|> |
<commit_before><commit_msg>Re-enable TAA & SSAO by default<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"
class InfoCdbBackendUnitTest : public QObject
{
Q_OBJECT
InfoCdbBackend *backend;
private slots:
void initTestCase();
void listKeys();
void listPlugins();
};
void InfoCdbBackendUnitTest::initTestCase()
{
// FIXME: LOCAL_DIR
CDBWriter writer("cache.cdb");
writer.add("KEYS", "Battery.Charging");
writer.add("KEYS", "Internet.BytesOut");
writer.add("PLUGINS", "contextkit-dbus");
writer.close();
utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
backend = new InfoCdbBackend();
}
void InfoCdbBackendUnitTest::listKeys()
{
QStringList keys = backend->listKeys();
QCOMPARE(keys.count(), 2);
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Internet.BytesOut"));
}
void InfoCdbBackendUnitTest::listPlugins()
{
QStringList plugins = backend->listPlugins();
QCOMPARE(plugins.count(), 1);
QVERIFY(plugins.contains("contextkit-dbus"));
}
#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<commit_msg>listKeysForPlugin.<commit_after>/*
* Copyright (C) 2008, 2009 Nokia Corporation.
*
* Contact: Marius Vollmer <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtTest/QtTest>
#include <QtCore>
#include "fileutils.h"
#include "infocdbbackend.h"
#include "cdbwriter.h"
class InfoCdbBackendUnitTest : public QObject
{
Q_OBJECT
InfoCdbBackend *backend;
private slots:
void initTestCase();
void listKeys();
void listPlugins();
void listKeysForPlugin();
};
void InfoCdbBackendUnitTest::initTestCase()
{
// FIXME: LOCAL_DIR
CDBWriter writer("cache.cdb");
writer.add("KEYS", "Battery.Charging");
writer.add("KEYS", "Internet.BytesOut");
writer.add("PLUGINS", "contextkit-dbus");
writer.add("contextkit-dbus:KEYS", "Battery.Charging");
writer.add("contextkit-dbus:KEYS", "Battery.BytesOut");
writer.close();
utilSetEnv("CONTEXT_PROVIDERS", LOCAL_DIR);
utilSetEnv("CONTEXT_CORE_DECLARATIONS", "/dev/null");
backend = new InfoCdbBackend();
}
void InfoCdbBackendUnitTest::listKeys()
{
QStringList keys = backend->listKeys();
QCOMPARE(keys.count(), 2);
QVERIFY(keys.contains("Battery.Charging"));
QVERIFY(keys.contains("Internet.BytesOut"));
}
void InfoCdbBackendUnitTest::listPlugins()
{
QStringList plugins = backend->listPlugins();
QCOMPARE(plugins.count(), 1);
QVERIFY(plugins.contains("contextkit-dbus"));
}
void InfoCdbBackendUnitTest::listKeysForPlugin()
{
QStringList keys1 = backend->listKeysForPlugin("contextkit-dbus");
QCOMPARE(keys1.count(), 2);
QVERIFY(keys1.contains("Battery.Charging"));
QVERIFY(keys1.contains("Internet.BytesOut"));
QStringList keys2 = backend->listKeysForPlugin("non-existant");
QCOMPARE(keys2.count(), 1);
}
#include "infocdbbackendunittest.moc"
QTEST_MAIN(InfoCdbBackendUnitTest);
<|endoftext|> |
<commit_before>/*
* SessionPanmirrorPandoc.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionPanmirrorPandoc.hpp"
#include <shared_core/Error.hpp>
#include <core/Exec.hpp>
#include <core/Algorithm.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Process.hpp>
#include <session/SessionModuleContext.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {
namespace pandoc {
namespace {
Error readOptionsParam(const json::Array& options, std::vector<std::string>* pOptions)
{
for(json::Array::Iterator
it = options.begin();
it != options.end();
++it)
{
if ((*it).getType() != json::Type::STRING)
return Error(json::errc::ParamTypeMismatch, ERROR_LOCATION);
std::string option = (*it).getString();
pOptions->push_back(option);
}
return Success();
}
void endAstToMarkdown(const json::JsonRpcFunctionContinuation& cont,
const core::system::ProcessResult& result)
{
json::JsonRpcResponse response;
if (result.exitStatus == EXIT_SUCCESS)
{
response.setResult(result.stdOut);
}
else
{
json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
}
cont(Success(), &response);
}
void pandocAstToMarkdown(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
// response object
json::JsonRpcResponse response;
// extract params
json::Object jsonAst;
std::string format;
json::Array jsonOptions;
Error error = json::readParams(request.params, &jsonAst, &format, &jsonOptions);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
std::vector<std::string> options;
error = readOptionsParam(jsonOptions, &options);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// build args
std::vector<std::string> args;
args.push_back("--from");
args.push_back("json");
args.push_back("--to");
args.push_back(format);
std::copy(options.begin(), options.end(), std::back_inserter(args));
// run pandoc (async)
error = module_context::runPandocAsync(args, jsonAst.write(), boost::bind(endAstToMarkdown, cont, _1));
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
}
}
void endHeadingIds(json::Object astJson,
const core::system::ProcessResult& result,
const json::JsonRpcFunctionContinuation& cont)
{
json::JsonRpcResponse response;
if (result.exitStatus == EXIT_SUCCESS)
{
std::vector<std::string> lines;
boost::algorithm::split(lines, result.stdOut, boost::algorithm::is_any_of("\n\r"));
json::Array jsonHeadingsIds;
std::for_each(lines.begin(), lines.end(), [&jsonHeadingsIds](std::string line) {
boost::algorithm::trim(line);
if (!line.empty())
jsonHeadingsIds.push_back(line);
});
astJson["heading_ids"] = jsonHeadingsIds;
response.setResult(astJson);
cont(Success(), &response);
}
else
{
json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
cont(Success(), &response);
}
}
void endMarkdownToAst(std::string markdown,
std::string format,
const core::system::ProcessResult& result,
const json::JsonRpcFunctionContinuation& cont)
{
json::JsonRpcResponse response;
if (result.exitStatus == EXIT_SUCCESS)
{
json::Object jsonObject;
if (json::parseJsonForResponse(result.stdOut, &jsonObject, &response))
{
// got ast, now extract heading ids
// disable auto identifiers so we can discover *only* explicit ids
format += "-auto_identifiers-gfm_auto_identifiers";
// path to lua filter
FilePath resPath = session::options().rResourcesPath();
FilePath headingIdsLuaPath = resPath.completePath("heading_ids.lua");
std::string headingIdsLua = string_utils::utf8ToSystem(headingIdsLuaPath.getAbsolutePath());
// build args
std::vector<std::string> args;
args.push_back("--from");
args.push_back(format);
args.push_back("--to");
args.push_back(headingIdsLua);
// run pandoc
core::system::ProcessResult result;
Error error = module_context::runPandocAsync(args, markdown, boost::bind(endHeadingIds, jsonObject, _1, cont));
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
}
}
else
{
cont(Success(), &response);
}
}
else
{
json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
cont(Success(), &response);
}
}
void pandocMarkdownToAst(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
// response object
json::JsonRpcResponse response;
// extract params
json::Array jsonOptions;
std::string markdown, format;
Error error = json::readParams(request.params, &markdown, &format, &jsonOptions);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
std::vector<std::string> options;
error = readOptionsParam(jsonOptions, &options);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// build args
std::vector<std::string> args;
args.push_back("--from");
args.push_back(format);
args.push_back("--to");
args.push_back("json");
std::copy(options.begin(), options.end(), std::back_inserter(args));
// run pandoc
core::system::ProcessResult result;
error = module_context::runPandocAsync(args, markdown, boost::bind(endMarkdownToAst, markdown, format, _1, cont));
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
}
bool pandocCaptureOutput(const std::vector<std::string>& args,
const std::string& input,
std::string* pOutput,
json::JsonRpcResponse* pResponse)
{
// run pandoc
core::system::ProcessResult result;
Error error = module_context::runPandoc(args, input, &result);
if (error)
{
json::setErrorResponse(error, pResponse);
return false;
}
else if (result.exitStatus != EXIT_SUCCESS)
{
json::setProcessErrorResponse(result, ERROR_LOCATION, pResponse);
return false;
}
else
{
*pOutput = result.stdOut;
return true;
}
}
bool pandocCaptureOutput(const std::string& arg, std::string* pOutput, json::JsonRpcResponse* pResponse)
{
std::vector<std::string> args;
args.push_back(arg);
return pandocCaptureOutput(args, "", pOutput, pResponse);
}
void pandocGetCapabilities(const json::JsonRpcRequest&,
const json::JsonRpcFunctionContinuation& cont)
{
// response object
json::JsonRpcResponse response;
// version
std::string version;
if (!pandocCaptureOutput("--version", &version, &response))
{
cont(Success(), &response);
return;
}
// try for hit from cache of capabilities by version
static std::map<std::string,json::Object> s_capabilitiesCache;
std::map<std::string,json::Object>::const_iterator it = s_capabilitiesCache.find(version);
if (it != s_capabilitiesCache.end())
{
response.setResult(it->second);
cont(Success(), &response);
return;
}
// api version
std::vector<std::string> apiArgs;
apiArgs.push_back("--to");
apiArgs.push_back("json");
std::string apiOutput;
if (!pandocCaptureOutput(apiArgs, " ", &apiOutput, &response))
{
cont(Success(), &response);
return;
}
json::Object jsonAst;
if (!json::parseJsonForResponse(apiOutput, &jsonAst, &response))
{
cont(Success(), &response);
return;
}
// output formats
json::Array apiVersion = jsonAst["pandoc-api-version"].getArray();
std::string outputFormats;
if (!pandocCaptureOutput("--list-output-formats", &outputFormats, &response))
{
cont(Success(), &response);
return;
}
// highlight languages
std::string highlightLanguages;
if (!pandocCaptureOutput("--list-highlight-languages", &highlightLanguages, &response))
{
cont(Success(), &response);
return;
}
// build capabilities response
json::Object capabilities;
capabilities["version"] = version;
capabilities["api_version"] = apiVersion;
capabilities["output_formats"] = outputFormats;
capabilities["highlight_languages"] = highlightLanguages;
// cache by version
s_capabilitiesCache[version] = capabilities;
// set response
response.setResult(capabilities);
cont(Success(), &response);
}
void pandocListExtensions(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
// response object
json::JsonRpcResponse response;
// extract format
std::string format;
Error error = json::readParams(request.params, &format);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// build arg
std::string arg = "--list-extensions";
if (!format.empty())
arg += ('=' + format);
std::string extensions;
if (pandocCaptureOutput(arg, &extensions, &response))
{
response.setResult(extensions);
cont(Success(), &response);
}
}
} // end anonymous namespace
Error initialize()
{
ExecBlock initBlock;
initBlock.addFunctions()
(boost::bind(module_context::registerAsyncRpcMethod, "pandoc_get_capabilities", pandocGetCapabilities))
(boost::bind(module_context::registerAsyncRpcMethod, "pandoc_ast_to_markdown", pandocAstToMarkdown))
(boost::bind(module_context::registerAsyncRpcMethod, "pandoc_markdown_to_ast", pandocMarkdownToAst))
(boost::bind(module_context::registerAsyncRpcMethod, "pandoc_list_extensions", pandocListExtensions))
;
return initBlock.execute();
}
} // end namespace pandoc
} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<commit_msg>Pass through error calling pandoc<commit_after>/*
* SessionPanmirrorPandoc.cpp
*
* Copyright (C) 2009-16 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
#include "SessionPanmirrorPandoc.hpp"
#include <shared_core/Error.hpp>
#include <core/Exec.hpp>
#include <core/Algorithm.hpp>
#include <core/json/JsonRpc.hpp>
#include <core/StringUtils.hpp>
#include <core/system/Process.hpp>
#include <session/SessionModuleContext.hpp>
using namespace rstudio::core;
namespace rstudio {
namespace session {
namespace modules {
namespace panmirror {
namespace pandoc {
namespace {
Error readOptionsParam(const json::Array& options, std::vector<std::string>* pOptions)
{
for(json::Array::Iterator
it = options.begin();
it != options.end();
++it)
{
if ((*it).getType() != json::Type::STRING)
return Error(json::errc::ParamTypeMismatch, ERROR_LOCATION);
std::string option = (*it).getString();
pOptions->push_back(option);
}
return Success();
}
void endAstToMarkdown(const json::JsonRpcFunctionContinuation& cont,
const core::system::ProcessResult& result)
{
json::JsonRpcResponse response;
if (result.exitStatus == EXIT_SUCCESS)
{
response.setResult(result.stdOut);
}
else
{
json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
}
cont(Success(), &response);
}
void pandocAstToMarkdown(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
// response object
json::JsonRpcResponse response;
// extract params
json::Object jsonAst;
std::string format;
json::Array jsonOptions;
Error error = json::readParams(request.params, &jsonAst, &format, &jsonOptions);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
std::vector<std::string> options;
error = readOptionsParam(jsonOptions, &options);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// build args
std::vector<std::string> args;
args.push_back("--from");
args.push_back("json");
args.push_back("--to");
args.push_back(format);
std::copy(options.begin(), options.end(), std::back_inserter(args));
// run pandoc (async)
error = module_context::runPandocAsync(args, jsonAst.write(), boost::bind(endAstToMarkdown, cont, _1));
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
}
}
void endHeadingIds(json::Object astJson,
const core::system::ProcessResult& result,
const json::JsonRpcFunctionContinuation& cont)
{
json::JsonRpcResponse response;
if (result.exitStatus == EXIT_SUCCESS)
{
std::vector<std::string> lines;
boost::algorithm::split(lines, result.stdOut, boost::algorithm::is_any_of("\n\r"));
json::Array jsonHeadingsIds;
std::for_each(lines.begin(), lines.end(), [&jsonHeadingsIds](std::string line) {
boost::algorithm::trim(line);
if (!line.empty())
jsonHeadingsIds.push_back(line);
});
astJson["heading_ids"] = jsonHeadingsIds;
response.setResult(astJson);
cont(Success(), &response);
}
else
{
json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
cont(Success(), &response);
}
}
void endMarkdownToAst(std::string markdown,
std::string format,
const core::system::ProcessResult& result,
const json::JsonRpcFunctionContinuation& cont)
{
json::JsonRpcResponse response;
if (result.exitStatus == EXIT_SUCCESS)
{
json::Object jsonObject;
if (json::parseJsonForResponse(result.stdOut, &jsonObject, &response))
{
// got ast, now extract heading ids
// disable auto identifiers so we can discover *only* explicit ids
format += "-auto_identifiers-gfm_auto_identifiers";
// path to lua filter
FilePath resPath = session::options().rResourcesPath();
FilePath headingIdsLuaPath = resPath.completePath("heading_ids.lua");
std::string headingIdsLua = string_utils::utf8ToSystem(headingIdsLuaPath.getAbsolutePath());
// build args
std::vector<std::string> args;
args.push_back("--from");
args.push_back(format);
args.push_back("--to");
args.push_back(headingIdsLua);
// run pandoc
core::system::ProcessResult result;
Error error = module_context::runPandocAsync(args, markdown, boost::bind(endHeadingIds, jsonObject, _1, cont));
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
}
}
else
{
cont(Success(), &response);
}
}
else
{
json::setProcessErrorResponse(result, ERROR_LOCATION, &response);
cont(Success(), &response);
}
}
void pandocMarkdownToAst(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
// response object
json::JsonRpcResponse response;
// extract params
json::Array jsonOptions;
std::string markdown, format;
Error error = json::readParams(request.params, &markdown, &format, &jsonOptions);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
std::vector<std::string> options;
error = readOptionsParam(jsonOptions, &options);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// build args
std::vector<std::string> args;
args.push_back("--from");
args.push_back(format);
args.push_back("--to");
args.push_back("json");
std::copy(options.begin(), options.end(), std::back_inserter(args));
// run pandoc
core::system::ProcessResult result;
error = module_context::runPandocAsync(args, markdown, boost::bind(endMarkdownToAst, markdown, format, _1, cont));
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
}
bool pandocCaptureOutput(const std::vector<std::string>& args,
const std::string& input,
std::string* pOutput,
json::JsonRpcResponse* pResponse)
{
// run pandoc
core::system::ProcessResult result;
Error error = module_context::runPandoc(args, input, &result);
if (error)
{
json::setErrorResponse(error, pResponse);
return false;
}
else if (result.exitStatus != EXIT_SUCCESS)
{
json::setProcessErrorResponse(result, ERROR_LOCATION, pResponse);
return false;
}
else
{
*pOutput = result.stdOut;
return true;
}
}
bool pandocCaptureOutput(const std::string& arg, std::string* pOutput, json::JsonRpcResponse* pResponse)
{
std::vector<std::string> args;
args.push_back(arg);
return pandocCaptureOutput(args, "", pOutput, pResponse);
}
void pandocGetCapabilities(const json::JsonRpcRequest&,
const json::JsonRpcFunctionContinuation& cont)
{
// response object
json::JsonRpcResponse response;
// version
std::string version;
if (!pandocCaptureOutput("--version", &version, &response))
{
cont(Success(), &response);
return;
}
// try for hit from cache of capabilities by version
static std::map<std::string,json::Object> s_capabilitiesCache;
std::map<std::string,json::Object>::const_iterator it = s_capabilitiesCache.find(version);
if (it != s_capabilitiesCache.end())
{
response.setResult(it->second);
cont(Success(), &response);
return;
}
// api version
std::vector<std::string> apiArgs;
apiArgs.push_back("--to");
apiArgs.push_back("json");
std::string apiOutput;
if (!pandocCaptureOutput(apiArgs, " ", &apiOutput, &response))
{
cont(Success(), &response);
return;
}
json::Object jsonAst;
if (!json::parseJsonForResponse(apiOutput, &jsonAst, &response))
{
cont(Success(), &response);
return;
}
// output formats
json::Array apiVersion = jsonAst["pandoc-api-version"].getArray();
std::string outputFormats;
if (!pandocCaptureOutput("--list-output-formats", &outputFormats, &response))
{
cont(Success(), &response);
return;
}
// highlight languages
std::string highlightLanguages;
if (!pandocCaptureOutput("--list-highlight-languages", &highlightLanguages, &response))
{
cont(Success(), &response);
return;
}
// build capabilities response
json::Object capabilities;
capabilities["version"] = version;
capabilities["api_version"] = apiVersion;
capabilities["output_formats"] = outputFormats;
capabilities["highlight_languages"] = highlightLanguages;
// cache by version
s_capabilitiesCache[version] = capabilities;
// set response
response.setResult(capabilities);
cont(Success(), &response);
}
void pandocListExtensions(const json::JsonRpcRequest& request,
const json::JsonRpcFunctionContinuation& cont)
{
// response object
json::JsonRpcResponse response;
// extract format
std::string format;
Error error = json::readParams(request.params, &format);
if (error)
{
json::setErrorResponse(error, &response);
cont(Success(), &response);
return;
}
// build arg
std::string arg = "--list-extensions";
if (!format.empty())
arg += ('=' + format);
std::string extensions;
if (pandocCaptureOutput(arg, &extensions, &response))
{
response.setResult(extensions);
cont(Success(), &response);
}
else
{
// Pandoc failed for some reason
cont(Error(), &response);
}
}
} // end anonymous namespace
Error initialize()
{
ExecBlock initBlock;
initBlock.addFunctions()
(boost::bind(module_context::registerAsyncRpcMethod, "pandoc_get_capabilities", pandocGetCapabilities))
(boost::bind(module_context::registerAsyncRpcMethod, "pandoc_ast_to_markdown", pandocAstToMarkdown))
(boost::bind(module_context::registerAsyncRpcMethod, "pandoc_markdown_to_ast", pandocMarkdownToAst))
(boost::bind(module_context::registerAsyncRpcMethod, "pandoc_list_extensions", pandocListExtensions))
;
return initBlock.execute();
}
} // end namespace pandoc
} // end namespace panmirror
} // end namespace modules
} // end namespace session
} // end namespace rstudio
<|endoftext|> |
<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "ModularGapConductanceConstraint.h"
#include "GapFluxModelBase.h"
registerMooseObject("HeatConductionApp", ModularGapConductanceConstraint);
InputParameters
ModularGapConductanceConstraint::validParams()
{
InputParameters params = ADMortarConstraint::validParams();
params.addClassDescription(
"Computes the residual and Jacobian contributions for the 'Lagrange Multiplier' "
"implementation of the thermal contact problem. For more information, see the "
"detailed description here: http://tinyurl.com/gmmhbe9");
params.addParam<std::vector<UserObjectName>>("gap_flux_models",
"List of GapFluxModel user objects");
params.addCoupledVar("displacements", "Displacement variables");
return params;
}
ModularGapConductanceConstraint::ModularGapConductanceConstraint(const InputParameters & parameters)
: ADMortarConstraint(parameters),
_gap_flux_model_names(getParam<std::vector<UserObjectName>>("gap_flux_models")),
_disp_name(parameters.getVecMooseType("displacements")),
_n_disp(_disp_name.size()),
_disp_secondary(_n_disp),
_disp_primary(_n_disp)
{
for (unsigned int i = 0; i < _n_disp; ++i)
{
auto & disp_var = _subproblem.getStandardVariable(_tid, _disp_name[i]);
_disp_secondary[i] = &disp_var.adSln();
_disp_primary[i] = &disp_var.adSlnNeighbor();
}
for (const auto & name : _gap_flux_model_names)
{
const auto & gap_model = getUserObjectByName<GapFluxModelBase>(name);
// pass variable dependencies through
const auto & var_dependencies = gap_model.getMooseVariableDependencies();
for (const auto & var : var_dependencies)
addMooseVariableDependency(var);
// add gap model to list
_gap_flux_models.push_back(&gap_model);
}
}
ADReal
ModularGapConductanceConstraint::computeQpResidual(Moose::MortarType mortar_type)
{
switch (mortar_type)
{
case Moose::MortarType::Primary:
return _lambda[_qp] * _test_primary[_i][_qp];
case Moose::MortarType::Secondary:
return -_lambda[_qp] * _test_secondary[_i][_qp];
case Moose::MortarType::Lower:
{
// we are creating an AD version of phys points primary and secondary here...
ADRealVectorValue ad_phys_points_primary = _phys_points_primary[_qp];
ADRealVectorValue ad_phys_points_secondary = _phys_points_secondary[_qp];
// ...which uses the derivative vector of the primary and secondary displacements as
// an approximation of the true phys points derivatives when the mesh is displacing
if (_displaced)
for (unsigned int i = 0; i < _n_disp; ++i)
{
ad_phys_points_primary(i).derivatives() = (*_disp_primary[i])[_qp].derivatives();
ad_phys_points_secondary(i).derivatives() = (*_disp_secondary[i])[_qp].derivatives();
}
const auto gap_width = (ad_phys_points_primary - ad_phys_points_secondary) * _normals[_qp];
ADReal flux = 0.0;
for (auto & model : _gap_flux_models)
flux += model->computeFlux(gap_width, _qp);
return (_lambda[_qp] - flux) * _test[_i][_qp];
}
default:
return 0;
}
}
<commit_msg>Add material dependencies (#19229)<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html
#include "ModularGapConductanceConstraint.h"
#include "GapFluxModelBase.h"
registerMooseObject("HeatConductionApp", ModularGapConductanceConstraint);
InputParameters
ModularGapConductanceConstraint::validParams()
{
InputParameters params = ADMortarConstraint::validParams();
params.addClassDescription(
"Computes the residual and Jacobian contributions for the 'Lagrange Multiplier' "
"implementation of the thermal contact problem. For more information, see the "
"detailed description here: http://tinyurl.com/gmmhbe9");
params.addParam<std::vector<UserObjectName>>("gap_flux_models",
"List of GapFluxModel user objects");
params.addCoupledVar("displacements", "Displacement variables");
return params;
}
ModularGapConductanceConstraint::ModularGapConductanceConstraint(const InputParameters & parameters)
: ADMortarConstraint(parameters),
_gap_flux_model_names(getParam<std::vector<UserObjectName>>("gap_flux_models")),
_disp_name(parameters.getVecMooseType("displacements")),
_n_disp(_disp_name.size()),
_disp_secondary(_n_disp),
_disp_primary(_n_disp)
{
for (unsigned int i = 0; i < _n_disp; ++i)
{
auto & disp_var = _subproblem.getStandardVariable(_tid, _disp_name[i]);
_disp_secondary[i] = &disp_var.adSln();
_disp_primary[i] = &disp_var.adSlnNeighbor();
}
for (const auto & name : _gap_flux_model_names)
{
const auto & gap_model = getUserObjectByName<GapFluxModelBase>(name);
// pass variable dependencies through
const auto & var_dependencies = gap_model.getMooseVariableDependencies();
for (const auto & var : var_dependencies)
addMooseVariableDependency(var);
// pass material property dependencies through
const auto & mat_dependencies = gap_model.getMatPropDependencies();
_material_property_dependencies.insert(mat_dependencies.begin(), mat_dependencies.end());
// add gap model to list
_gap_flux_models.push_back(&gap_model);
}
}
ADReal
ModularGapConductanceConstraint::computeQpResidual(Moose::MortarType mortar_type)
{
switch (mortar_type)
{
case Moose::MortarType::Primary:
return _lambda[_qp] * _test_primary[_i][_qp];
case Moose::MortarType::Secondary:
return -_lambda[_qp] * _test_secondary[_i][_qp];
case Moose::MortarType::Lower:
{
// we are creating an AD version of phys points primary and secondary here...
ADRealVectorValue ad_phys_points_primary = _phys_points_primary[_qp];
ADRealVectorValue ad_phys_points_secondary = _phys_points_secondary[_qp];
// ...which uses the derivative vector of the primary and secondary displacements as
// an approximation of the true phys points derivatives when the mesh is displacing
if (_displaced)
for (unsigned int i = 0; i < _n_disp; ++i)
{
ad_phys_points_primary(i).derivatives() = (*_disp_primary[i])[_qp].derivatives();
ad_phys_points_secondary(i).derivatives() = (*_disp_secondary[i])[_qp].derivatives();
}
const auto gap_width = (ad_phys_points_primary - ad_phys_points_secondary) * _normals[_qp];
ADReal flux = 0.0;
for (auto & model : _gap_flux_models)
flux += model->computeFlux(gap_width, _qp);
return (_lambda[_qp] - flux) * _test[_i][_qp];
}
default:
return 0;
}
}
<|endoftext|> |
<commit_before>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Implementation of the AliKalmanTrack class
// that is the base for AliTPCtrack, AliITStrackV2 and AliTRDtrack
// Origin: Iouri Belikov, CERN, [email protected]
//-------------------------------------------------------------------------
#include <TGeoManager.h>
#include "AliKalmanTrack.h"
ClassImp(AliKalmanTrack)
//_______________________________________________________________________
AliKalmanTrack::AliKalmanTrack():AliExternalTrackParam(),
fFakeRatio(0),
fChi2(0),
fMass(AliPID::ParticleMass(AliPID::kPion)),
fLab(-3141593),
fN(0),
fStartTimeIntegral(kFALSE),
fIntegratedLength(0)
{
//
// Default constructor
//
for(Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i] = 0;
}
AliKalmanTrack::AliKalmanTrack(const AliKalmanTrack &t):
AliExternalTrackParam(t),
fFakeRatio(t.fFakeRatio),
fChi2(t.fChi2),
fMass(t.fMass),
fLab(t.fLab),
fN(t.fN),
fStartTimeIntegral(t.fStartTimeIntegral),
fIntegratedLength(t.fIntegratedLength)
{
//
// Copy constructor
//
for (Int_t i=0; i<AliPID::kSPECIES; i++)
fIntegratedTime[i] = t.fIntegratedTime[i];
}
AliKalmanTrack& AliKalmanTrack::operator=(const AliKalmanTrack&o){
if(this!=&o){
AliExternalTrackParam::operator=(o);
fLab = o.fLab;
fFakeRatio = o.fFakeRatio;
fChi2 = o.fChi2;
fMass = o.fMass;
fN = o.fN;
fStartTimeIntegral = o.fStartTimeIntegral;
for(Int_t i = 0;i<AliPID::kSPECIES;++i)fIntegratedTime[i] = o.fIntegratedTime[i];
fIntegratedLength = o.fIntegratedLength;
}
return *this;
}
//_______________________________________________________________________
void AliKalmanTrack::StartTimeIntegral()
{
// Sylwester Radomski, GSI
// [email protected]
//
// Start time integration
// To be called at Vertex by ITS tracker
//
//if (fStartTimeIntegral)
// AliWarning("Reseting Recorded Time.");
fStartTimeIntegral = kTRUE;
for(Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i] = 0;
fIntegratedLength = 0;
}
//_______________________________________________________________________
void AliKalmanTrack:: AddTimeStep(Double_t length)
{
//
// Add step to integrated time
// this method should be called by a sublasses at the end
// of the PropagateTo function or by a tracker
// each time step is made.
//
// If integration not started function does nothing
//
// Formula
// dt = dl * sqrt(p^2 + m^2) / p
// p = pT * (1 + tg^2 (lambda) )
//
// pt = 1/external parameter [4]
// tg lambda = external parameter [3]
//
//
// Sylwester Radomski, GSI
// [email protected]
//
static const Double_t kcc = 2.99792458e-2;
if (!fStartTimeIntegral) return;
fIntegratedLength += length;
Double_t xr, param[5];
Double_t pt, tgl;
GetExternalParameters(xr, param);
pt = 1/param[4] ;
tgl = param[3];
Double_t p = TMath::Abs(pt * TMath::Sqrt(1+tgl*tgl));
if (length > 100) return;
for (Int_t i=0; i<AliPID::kSPECIES; i++) {
Double_t mass = AliPID::ParticleMass(i);
Double_t correction = TMath::Sqrt( pt*pt * (1 + tgl*tgl) + mass * mass ) / p;
Double_t time = length * correction / kcc;
fIntegratedTime[i] += time;
}
}
//_______________________________________________________________________
Double_t AliKalmanTrack::GetIntegratedTime(Int_t pdg) const
{
// Sylwester Radomski, GSI
// [email protected]
//
// Return integrated time hypothesis for a given particle
// type assumption.
//
// Input parameter:
// pdg - Pdg code of a particle type
//
if (!fStartTimeIntegral) {
AliWarning("Time integration not started");
return 0.;
}
for (Int_t i=0; i<AliPID::kSPECIES; i++)
if (AliPID::ParticleCode(i) == TMath::Abs(pdg)) return fIntegratedTime[i];
AliWarning(Form("Particle type [%d] not found", pdg));
return 0;
}
void AliKalmanTrack::GetIntegratedTimes(Double_t *times) const {
for (Int_t i=0; i<AliPID::kSPECIES; i++) times[i]=fIntegratedTime[i];
}
void AliKalmanTrack::SetIntegratedTimes(const Double_t *times) {
for (Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i]=times[i];
}
<commit_msg>AddTimeStamp was always increasing track length but accounting corresponding tof only for steps<100 cm. Commented out this condition<commit_after>/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-------------------------------------------------------------------------
// Implementation of the AliKalmanTrack class
// that is the base for AliTPCtrack, AliITStrackV2 and AliTRDtrack
// Origin: Iouri Belikov, CERN, [email protected]
//-------------------------------------------------------------------------
#include <TGeoManager.h>
#include "AliKalmanTrack.h"
ClassImp(AliKalmanTrack)
//_______________________________________________________________________
AliKalmanTrack::AliKalmanTrack():AliExternalTrackParam(),
fFakeRatio(0),
fChi2(0),
fMass(AliPID::ParticleMass(AliPID::kPion)),
fLab(-3141593),
fN(0),
fStartTimeIntegral(kFALSE),
fIntegratedLength(0)
{
//
// Default constructor
//
for(Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i] = 0;
}
AliKalmanTrack::AliKalmanTrack(const AliKalmanTrack &t):
AliExternalTrackParam(t),
fFakeRatio(t.fFakeRatio),
fChi2(t.fChi2),
fMass(t.fMass),
fLab(t.fLab),
fN(t.fN),
fStartTimeIntegral(t.fStartTimeIntegral),
fIntegratedLength(t.fIntegratedLength)
{
//
// Copy constructor
//
for (Int_t i=0; i<AliPID::kSPECIES; i++)
fIntegratedTime[i] = t.fIntegratedTime[i];
}
AliKalmanTrack& AliKalmanTrack::operator=(const AliKalmanTrack&o){
if(this!=&o){
AliExternalTrackParam::operator=(o);
fLab = o.fLab;
fFakeRatio = o.fFakeRatio;
fChi2 = o.fChi2;
fMass = o.fMass;
fN = o.fN;
fStartTimeIntegral = o.fStartTimeIntegral;
for(Int_t i = 0;i<AliPID::kSPECIES;++i)fIntegratedTime[i] = o.fIntegratedTime[i];
fIntegratedLength = o.fIntegratedLength;
}
return *this;
}
//_______________________________________________________________________
void AliKalmanTrack::StartTimeIntegral()
{
// Sylwester Radomski, GSI
// [email protected]
//
// Start time integration
// To be called at Vertex by ITS tracker
//
//if (fStartTimeIntegral)
// AliWarning("Reseting Recorded Time.");
fStartTimeIntegral = kTRUE;
for(Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i] = 0;
fIntegratedLength = 0;
}
//_______________________________________________________________________
void AliKalmanTrack:: AddTimeStep(Double_t length)
{
//
// Add step to integrated time
// this method should be called by a sublasses at the end
// of the PropagateTo function or by a tracker
// each time step is made.
//
// If integration not started function does nothing
//
// Formula
// dt = dl * sqrt(p^2 + m^2) / p
// p = pT * (1 + tg^2 (lambda) )
//
// pt = 1/external parameter [4]
// tg lambda = external parameter [3]
//
//
// Sylwester Radomski, GSI
// [email protected]
//
static const Double_t kcc = 2.99792458e-2;
if (!fStartTimeIntegral) return;
fIntegratedLength += length;
Double_t xr, param[5];
Double_t pt, tgl;
GetExternalParameters(xr, param);
pt = 1/param[4] ;
tgl = param[3];
Double_t p = TMath::Abs(pt * TMath::Sqrt(1+tgl*tgl));
// if (length > 100) return;
for (Int_t i=0; i<AliPID::kSPECIES; i++) {
Double_t mass = AliPID::ParticleMass(i);
Double_t correction = TMath::Sqrt( pt*pt * (1 + tgl*tgl) + mass * mass ) / p;
Double_t time = length * correction / kcc;
fIntegratedTime[i] += time;
}
}
//_______________________________________________________________________
Double_t AliKalmanTrack::GetIntegratedTime(Int_t pdg) const
{
// Sylwester Radomski, GSI
// [email protected]
//
// Return integrated time hypothesis for a given particle
// type assumption.
//
// Input parameter:
// pdg - Pdg code of a particle type
//
if (!fStartTimeIntegral) {
AliWarning("Time integration not started");
return 0.;
}
for (Int_t i=0; i<AliPID::kSPECIES; i++)
if (AliPID::ParticleCode(i) == TMath::Abs(pdg)) return fIntegratedTime[i];
AliWarning(Form("Particle type [%d] not found", pdg));
return 0;
}
void AliKalmanTrack::GetIntegratedTimes(Double_t *times) const {
for (Int_t i=0; i<AliPID::kSPECIES; i++) times[i]=fIntegratedTime[i];
}
void AliKalmanTrack::SetIntegratedTimes(const Double_t *times) {
for (Int_t i=0; i<AliPID::kSPECIES; i++) fIntegratedTime[i]=times[i];
}
<|endoftext|> |
<commit_before>/*The following code simulates the *Bounded* (single-single) Producer-Consumer problem using Standard Library threads. A producer thread produces a shared resource and then sleeps for a second.
The consumer thread consumes the resource and then sleeps for a second. How much of the resource is produced or consumed is dictated by a pseudo-random subroutine.*/
#include <iostream>
#include <thread>
#include <mutex>
#include <random>
#include <chrono>
#include <atomic>
#include <condition_variable>
const int MAXSIZE = 10;
std::mutex resourceMutex;
std::atomic<int> resource(1); // simulates the shared buffer of produced resource
std::condition_variable cv;
size_t getRandUnitSize(std::default_random_engine &seed)
{
std::uniform_real_distribution<double> rnd(0.0, 1.0);
double trial = rnd(seed);
return static_cast<size_t>(trial * 10);
}
void produce()
{
size_t tid = std::hash<std::thread::id>()(std::this_thread::get_id());
std::default_random_engine seed(tid * static_cast<uint64_t>(std::chrono::system_clock::to_time_t((std::chrono::system_clock::now()))));
while (true)
{
std::unique_lock<std::mutex> lock(resourceMutex);
std::cout << "Lock acquired by producer..." << std::endl;
size_t units = 0;
cv.wait(lock, [&]()
{
units = getRandUnitSize(seed);
std::cout << "Available: " << resource << std::endl;
std::cout << "Units to produce: " << units << std::endl;
int newAmount = resource.load() + units;
std::cout << "Projected amount after production: " << newAmount << std::endl;
bool predicate = (newAmount <= MAXSIZE);
if (!predicate)
{
std::cout << "Produced resource limit reached. Sleeping...\n\n" << std::endl;
cv.notify_one();
}
return predicate;
});
resource += units;
std::cout << "Produced " << units << " units." << std::endl;
std::cout << "Total: " << resource << "\n\n" << std::endl;
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void consume()
{
size_t tid = std::hash<std::thread::id>()(std::this_thread::get_id());
std::default_random_engine seed(tid * static_cast<uint64_t>(std::chrono::system_clock::to_time_t((std::chrono::system_clock::now()))));
while (true)
{
std::unique_lock<std::mutex> lock(resourceMutex);
std::cout << "Lock acquired by consumer..." << std::endl;
size_t units = 0;
cv.wait(lock, [&]()
{
units = getRandUnitSize(seed);
std::cout << "Available: " << resource << std::endl;
std::cout << "Units to consume: " << units << std::endl;
int newAmount = resource.load() - units;
std::cout << "Projected amount after consumption: " << newAmount << std::endl;
bool predicate = (newAmount >= 0);
if (!predicate)
{
std::cout << "Not enough resources to consume. Sleeping...\n\n" << std::endl;
cv.notify_one();
}
return predicate;
});
resource -= units;
std::cout << "Consumed " << units << " units." << std::endl;
std::cout << "Total: " << resource << "\n\n" << std::endl;
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::thread producer(produce);
std::thread consumer(consume);
producer.join();
consumer.join();
}<commit_msg>Added support for multiple producers and consumers<commit_after>/*The following code simulates the *Bounded* Producer-Consumer (supporting arbitrary number of producers
and consumers) problem using Standard Library threads. A producer thread produces a shared resource and
then sleeps for a second. The consumer thread consumes the resource and then sleeps for a second. How
much of the resource is produced or consumed is dictated by a pseudo-random number generator subroutine.
Compile using flags to enable C++11 and link to pthread if necessary.
On GCC this is done using the flags -std=c++11 -pthread passed to the compiler*/
#include <iostream>
#include <thread>
#include <mutex>
#include <random>
#include <chrono>
#include <atomic>
#include <condition_variable>
const int nProd = 4;
const int nCon = 4;
const int MAXSIZE = 10;
std::mutex resourceMutex;
std::atomic<int> resource(1); // simulates the shared buffer of produced resource
std::condition_variable cv;
size_t getRandUnitSize(std::default_random_engine &seed)
{
std::uniform_real_distribution<double> rnd(0.0, 1.0);
double trial = rnd(seed);
return static_cast<size_t>(trial * MAXSIZE);
}
void produce(int id)
{
size_t tid = std::hash<std::thread::id>()(std::this_thread::get_id());
// seeds the rng using the thread id and current time
std::default_random_engine seed(tid * static_cast<uint64_t>(std::chrono::system_clock::to_time_t((std::chrono::system_clock::now()))));
while (true)
{
std::unique_lock<std::mutex> lock(resourceMutex);
std::cout << "Lock acquired by producer " << id << " ... " << std::endl;
size_t units = 0;
cv.wait(lock, [&]()
{
units = getRandUnitSize(seed);
std::cout << "Available: " << resource << std::endl;
std::cout << "Units to produce: " << units << std::endl;
int newAmount = resource.load() + units;
std::cout << "Projected amount after production: " << newAmount << std::endl;
bool predicate = (newAmount <= MAXSIZE);
if (!predicate)
{
std::cout << "Produced resource limit reached. Sleeping...\n\n" << std::endl;
cv.notify_one();
}
return predicate;
});
resource += units;
std::cout << "Produced " << units << " units." << std::endl;
std::cout << "Total: " << resource << "\n\n" << std::endl;
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void consume(int id)
{
size_t tid = std::hash<std::thread::id>()(std::this_thread::get_id());
// seeds the rng using the thread id and current time
std::default_random_engine seed(tid * static_cast<uint64_t>(std::chrono::system_clock::to_time_t((std::chrono::system_clock::now()))));
while (true)
{
std::unique_lock<std::mutex> lock(resourceMutex);
std::cout << "Lock acquired by consumer " << id << " ... " << std::endl;
size_t units = 0;
cv.wait(lock, [&]()
{
units = getRandUnitSize(seed);
std::cout << "Available: " << resource << std::endl;
std::cout << "Units to consume: " << units << std::endl;
int newAmount = resource.load() - units;
std::cout << "Projected amount after consumption: " << newAmount << std::endl;
bool predicate = (newAmount >= 0);
if (!predicate)
{
std::cout << "Not enough resources to consume. Sleeping...\n\n" << std::endl;
cv.notify_one();
}
return predicate;
});
resource -= units;
std::cout << "Consumed " << units << " units." << std::endl;
std::cout << "Total: " << resource << "\n\n" << std::endl;
cv.notify_one();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::thread producers[nProd];
std::thread consumers[nCon];
for (int i = 0; i < nProd; ++i)
producers[i] = std::thread(produce, i);
for (int i = 0; i < nProd; ++i)
consumers[i] = std::thread(consume, i);
for (int i = 0; i < nProd; ++i)
producers[i].join();
for (int i = 0; i < nProd; ++i)
consumers[i].join();
}<|endoftext|> |
<commit_before>#include "Scene.h"
Scene::Scene()
{
//Generate the world on launch
resetScene();
}
void Scene::resetScene()
{
int count = PLANET_COUNT;
bool hit = false;
Planet* tempPlanet;
while(count > 0)
{
--count;
tempPlanet = new Planet( Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT) ), randomRange(100,250 ) ) ;
//Check that the planet is not on top of other planes
for( int i = 0; i < planets.size(); ++i)
{
Vector vec = tempPlanet->position - planets[i]->position;
float dist = abs ( vec.getLenght() );
dist -= planets[i]->size;
dist -= tempPlanet->size;
if(dist < 0){
//Hit! break from the loop
hit = true;
}
}
if(hit)
{
printf("planet collision!");
delete tempPlanet;
}
else
{
printf("planet creation");
planets.push_back(tempPlanet);
}
hit = false;
}
//Then add the pickups.
count = SCENE_PICKUP_COUNT; //10 pickups
hit = false;
Entity *ent;
while( count > 0 )
{
//Entity *ent = new Entity(Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT)), ENTITYTYPE_PICKUP);
ent = new Entity();
ent->position = Vector( (float)randomRange(0,WORLD_WIDTH), (float)randomRange(0,WORLD_HEIGHT));
ent->type = ENTITYTYPE_PICKUP;
printf("|%f %f|\n",ent->position.x,ent->position.y);
//Check that the pickup is not inside a planet
for( int i = 0; i < planets.size(); ++i)
{
Vector vec = ent->position - planets[i]->position;
float dist = abs ( vec.getLenght() );
dist -= planets[i]->size;
dist -= 150; //Some space between the planets and pickups...
if(dist < 0){
//Hit! break from the loop
printf("planet collision!");
hit = true;
}
}
if(hit)
{
delete ent;
}
else
{
printf("|%f %f|\n",ent->position.x,ent->position.y);
entities.push_back(ent);
printf("|%f %f|\n",ent->position.x,ent->position.y);
}
printf("|%f %f|\n",ent->position.x,ent->position.y);
--count;
hit = false;
}
printf("entities.size() : %i \n", entities.size());
count = SCENE_FUEL_COUNT; //5 fuel
/*
while( count > 0 )
{
Entity *ent = new Entity(Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT)), ENTITYTYPE_FUEL);
//Check that the pickup is not inside a planet
for( int i = 0; i < planets.size(); ++i)
{
Vector vec = ent->position - planets[i]->position;
float dist = abs ( vec.getLenght() );
dist -= planets[i]->size;
ent -= 150; //Some space between the planets and pickups...
if(dist < 0){
//Hit! break from the loop
printf("planet collision!");
delete ent; //entity is not used
break;
}
}
entities.push_back(ent);
--count;
}
*/
printf("entities.size() : %i \n", entities.size());
}
void Scene::update()
{
//calculate gravity from nearby planets
for(int i = 0; i < planets.size(); ++i)
{
//get distance from player
Vector vec = planets[i]->position - player.position;
int dist = abs( vec.getLenght() );
int radius = planets[i]->size;
//#######################
//Planets generate particles!
//particleSystem.addParticles(1,4,planets[i]->position,0,0,-2,2,radius / 10,radius / 5 + radius / 2, sf::Color::Red,3);
//Disabled because it would "eat" all the avaivable slots with current setup.
//#######################
//TODO: Kill player if it collides with a planet, fix the hit detection! the origin is invalid
if(dist < radius)
printf("KILL");
//if distance is larger than the size, no gravity applies
if(dist / GRAVITY_MULTIPLIER > radius)
continue;
dist -= radius / 2; //gravity "starts" from the surface, not center
float str = dist / (1000000.f / 0.8);
printf("# %f #\n",str);
if(str < 0)
continue;
//apply force
player.impulse(vec,str);
}
//Check the entities
for ( int i = 0; i < entities.size(); ++i )
{
Vector vec = entities[i]->position - player.position;
int dist = abs( vec.getLenght() );
if(dist < 10)
{
//printf("PICKUP!");
printf("dist: %i", dist);
}
}
//get player input, apply velocity
player.update();
}<commit_msg>Collecting entities is possible!<commit_after>#include "Scene.h"
Scene::Scene()
{
//Generate the world on launch
resetScene();
}
void Scene::resetScene()
{
int count = PLANET_COUNT;
bool hit = false;
Planet* tempPlanet;
while(count > 0)
{
--count;
tempPlanet = new Planet( Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT) ), randomRange(100,250 ) ) ;
//Check that the planet is not on top of other planes
for( int i = 0; i < planets.size(); ++i)
{
Vector vec = tempPlanet->position - planets[i]->position;
float dist = abs ( vec.getLenght() );
dist -= planets[i]->size;
dist -= tempPlanet->size;
if(dist < 0){
//Hit! break from the loop
hit = true;
}
}
if(hit)
{
printf("planet collision!");
delete tempPlanet;
}
else
{
printf("planet creation");
planets.push_back(tempPlanet);
}
hit = false;
}
//Then add the pickups.
count = SCENE_PICKUP_COUNT; //10 pickups
hit = false;
Entity *ent;
while( count > 0 )
{
//Entity *ent = new Entity(Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT)), ENTITYTYPE_PICKUP);
ent = new Entity();
ent->position = Vector( (float)randomRange(0,WORLD_WIDTH), (float)randomRange(0,WORLD_HEIGHT));
ent->type = ENTITYTYPE_PICKUP;
printf("|%f %f|\n",ent->position.x,ent->position.y);
//Check that the pickup is not inside a planet
for( int i = 0; i < planets.size(); ++i)
{
Vector vec = ent->position - planets[i]->position;
float dist = abs ( vec.getLenght() );
dist -= planets[i]->size;
dist -= 150; //Some space between the planets and pickups...
if(dist < 0){
//Hit! break from the loop
printf("planet collision!");
hit = true;
}
}
if(hit)
{
delete ent;
}
else
{
printf("|%f %f|\n",ent->position.x,ent->position.y);
entities.push_back(ent);
printf("|%f %f|\n",ent->position.x,ent->position.y);
}
printf("|%f %f|\n",ent->position.x,ent->position.y);
--count;
hit = false;
}
printf("entities.size() : %i \n", entities.size());
count = SCENE_FUEL_COUNT; //5 fuel
/*
while( count > 0 )
{
Entity *ent = new Entity(Vector( randomRange(0,WORLD_WIDTH), randomRange(0,WORLD_HEIGHT)), ENTITYTYPE_FUEL);
//Check that the pickup is not inside a planet
for( int i = 0; i < planets.size(); ++i)
{
Vector vec = ent->position - planets[i]->position;
float dist = abs ( vec.getLenght() );
dist -= planets[i]->size;
ent -= 150; //Some space between the planets and pickups...
if(dist < 0){
//Hit! break from the loop
printf("planet collision!");
delete ent; //entity is not used
break;
}
}
entities.push_back(ent);
--count;
}
*/
printf("entities.size() : %i \n", entities.size());
}
void Scene::update()
{
//calculate gravity from nearby planets
for(int i = 0; i < planets.size(); ++i)
{
//get distance from player
Vector vec = planets[i]->position - player.position;
int dist = abs( vec.getLenght() );
int radius = planets[i]->size;
//#######################
//Planets generate particles!
//particleSystem.addParticles(1,4,planets[i]->position,0,0,-2,2,radius / 10,radius / 5 + radius / 2, sf::Color::Red,3);
//Disabled because it would "eat" all the avaivable slots with current setup.
//#######################
//TODO: Kill player if it collides with a planet, fix the hit detection! the origin is invalid
if(dist < radius)
printf("KILL");
//if distance is larger than the size, no gravity applies
if(dist / GRAVITY_MULTIPLIER > radius)
continue;
dist -= radius / 2; //gravity "starts" from the surface, not center
float str = dist / (1000000.f / 0.8);
printf("# %f #\n",str);
if(str < 0)
continue;
//apply force
player.impulse(vec,str);
}
//Check the entities
for ( int i = 0; i < entities.size(); ++i )
{
Vector vec = entities[i]->position - player.position;
int dist = abs( vec.getLenght() );
if(dist < 40)
{
//printf("PICKUP!");
printf("dist: %i", dist);
particleSystem.addParticles(200, 200, entities[i]->position , Vector(0,1) ,360,30,50,50,100,sf::Color::Green,4);
delete entities[i];
entities.erase(entities.begin() + i);
--i;
}
}
//get player input, apply velocity
player.update();
}<|endoftext|> |
<commit_before><commit_msg>Fix MSVC build<commit_after><|endoftext|> |
<commit_before>/*
Copyright 2017 creatorlxd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "../Include/ObjectConnection.h"
using namespace SpaceGameEngine;
REGISTERCOMPONENTCLASS(ConnectComponent);
SpaceGameEngine::ConnectComponent::ConnectComponent()
{
m_TypeName = STRING(ConnectComponent);
m_pFatherTransform = nullptr;
m_pChildTransform = nullptr;
m_IfInit = false;
}
void SpaceGameEngine::ConnectComponent::Run(float DeltaTime)
{
if (m_IfInit == false)
ThrowError("ConnectComponentҪSetTransform");
else
{
if (m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::PositionChange) ||
m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::RotationChange) ||
m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::ScaleChange))
{
m_pChildTransform->SetPosition(Add(m_pChildTransform->GetPosition(),Substract(m_pFatherTransform->GetPosition(),m_PositionBuffer)));
m_pChildTransform->SetScale(Add(m_pChildTransform->GetScale(), Substract(m_pFatherTransform->GetScale(), m_ScaleBuffer)));
if (m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::RotationChange))
{
auto dis = Substract(m_pFatherTransform->GetPosition(), m_pChildTransform->GetPosition());
auto angle = Substract(m_pFatherTransform->GetRotation(), m_RotationBuffer);
dis = RotationVector(angle, dis);
m_pChildTransform->SetPosition(Add(m_pChildTransform->GetPosition(), dis));
m_pChildTransform->SetRotation(Add(m_pChildTransform->GetRotation(), angle));
}
m_PositionBuffer = m_pFatherTransform->GetPosition();
m_RotationBuffer = m_pFatherTransform->GetRotation();
m_ScaleBuffer = m_pFatherTransform->GetScale();
}
}
}
void SpaceGameEngine::ConnectComponent::SetTransform(TransformComponent * father, TransformComponent * child)
{
m_pFatherTransform = father;
m_pChildTransform = child;
if (father)
{
m_PositionBuffer = father->GetPosition();
m_RotationBuffer = father->GetRotation();
m_ScaleBuffer = father->GetScale();
}
m_IfInit = true;
}
void SpaceGameEngine::ConnectObject(Object * father, Object * child)
{
child->Attach(father);
child->AddComponent(ConnectComponent::NewComponent());
child->GetComponent<ConnectComponent>()->SetTransform(father->GetComponent<TransformComponent>(), child->GetComponent<TransformComponent>());
if (child->GetRootComponent() != nullptr)
{
child->GetRootComponent()->Attach(child->GetComponent(STRING(ConnectComponent)));
child->SetRootComponent(STRING(ConnectComponent));
}
else
ThrowError("RootComponentΪnullptr");
}
void SpaceGameEngine::DisconObject(Object * child)
{
if (child == nullptr)
{
ThrowError("childΪnullptr");
return;
}
if (child->GetRootComponent()->GetTypeName() != STRING(ConnectComponent))
{
ThrowError("DisconObjectӦConnectObjectʹ||ʹConnectObjectĶRootComponentΪConnectComponent");
return;
}
child->Discon();
auto children_component = child->GetRootComponent()->GetChildrenComponent();
if (children_component.size() >= 1)
{
child->SetRootComponent(children_component[0]->GetTypeName());
}
child->DeleteComponent(STRING(ConnectComponent));
}
<commit_msg>fix a bug in object connection<commit_after>/*
Copyright 2017 creatorlxd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "stdafx.h"
#include "../Include/ObjectConnection.h"
using namespace SpaceGameEngine;
REGISTERCOMPONENTCLASS(ConnectComponent);
SpaceGameEngine::ConnectComponent::ConnectComponent()
{
m_TypeName = STRING(ConnectComponent);
m_pFatherTransform = nullptr;
m_pChildTransform = nullptr;
m_IfInit = false;
}
void SpaceGameEngine::ConnectComponent::Run(float DeltaTime)
{
if (m_IfInit == false)
ThrowError("ConnectComponentҪSetTransform");
else
{
if (m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::PositionChange) ||
m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::RotationChange) ||
m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::ScaleChange))
{
m_pChildTransform->SetPosition(Add(m_pChildTransform->GetPosition(), Substract(m_pFatherTransform->GetPosition(), m_PositionBuffer)));
m_pChildTransform->SetScale(Add(m_pChildTransform->GetScale(), Substract(m_pFatherTransform->GetScale(), m_ScaleBuffer)));
if (m_pFatherTransform->GetFatherObject()->GetComponentByMessage(Event::RotationChange))
{
auto dis = Substract(m_pChildTransform->GetPosition(), m_pFatherTransform->GetPosition());
auto angle = Substract(m_pFatherTransform->GetRotation(), m_RotationBuffer);
dis = RotationVector(angle, dis);
m_pChildTransform->SetPosition(Add(dis,m_pFatherTransform->GetPosition()));
m_pChildTransform->SetRotation(Add(m_pChildTransform->GetRotation(), angle));
}
m_PositionBuffer = m_pFatherTransform->GetPosition();
m_RotationBuffer = m_pFatherTransform->GetRotation();
m_ScaleBuffer = m_pFatherTransform->GetScale();
}
}
}
void SpaceGameEngine::ConnectComponent::SetTransform(TransformComponent * father, TransformComponent * child)
{
m_pFatherTransform = father;
m_pChildTransform = child;
if (father)
{
m_PositionBuffer = father->GetPosition();
m_RotationBuffer = father->GetRotation();
m_ScaleBuffer = father->GetScale();
}
m_IfInit = true;
}
void SpaceGameEngine::ConnectObject(Object * father, Object * child)
{
child->Attach(father);
child->AddComponent(ConnectComponent::NewComponent());
child->GetComponent<ConnectComponent>()->SetTransform(father->GetComponent<TransformComponent>(), child->GetComponent<TransformComponent>());
if (child->GetRootComponent() != nullptr)
{
child->GetRootComponent()->Attach(child->GetComponent(STRING(ConnectComponent)));
child->SetRootComponent(STRING(ConnectComponent));
}
else
ThrowError("RootComponentΪnullptr");
}
void SpaceGameEngine::DisconObject(Object * child)
{
if (child == nullptr)
{
ThrowError("childΪnullptr");
return;
}
if (child->GetRootComponent()->GetTypeName() != STRING(ConnectComponent))
{
ThrowError("DisconObjectӦConnectObjectʹ||ʹConnectObjectĶRootComponentΪConnectComponent");
return;
}
child->Discon();
auto children_component = child->GetRootComponent()->GetChildrenComponent();
if (children_component.size() >= 1)
{
child->SetRootComponent(children_component[0]->GetTypeName());
}
child->DeleteComponent(STRING(ConnectComponent));
}
<|endoftext|> |
<commit_before>/*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2006 by the OpenSG Forum *
* *
* contact: [email protected], [email protected], [email protected] *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
/*****************************************************************************\
*****************************************************************************
** **
** This file is automatically generated. **
** **
** Any changes made to this file WILL be lost when it is **
** regenerated, which can become necessary at any time. **
** **
** Do not change this file, changes should be done in the derived **
** class StageData!
** **
*****************************************************************************
\*****************************************************************************/
OSG_BEGIN_NAMESPACE
//! access the type of the class
inline
OSG::FieldBundleType &StageDataBase::getClassType(void)
{
return _type;
}
//! access the numerical type of the class
inline
OSG::UInt32 StageDataBase::getClassTypeId(void)
{
return _type.getId();
}
inline
OSG::UInt16 StageDataBase::getClassGroupId(void)
{
return _type.getGroupId();
}
/*------------------------------ get -----------------------------------*/
//! Get the value of the StageData::_sfPartitionRangeBegin field.
inline
Int32 &StageDataBase::editPartitionRangeBegin(void)
{
editSField(PartitionRangeBeginFieldMask);
return _sfPartitionRangeBegin.getValue();
}
//! Get the value of the StageData::_sfPartitionRangeBegin field.
inline
const Int32 &StageDataBase::getPartitionRangeBegin(void) const
{
return _sfPartitionRangeBegin.getValue();
}
#ifdef OSG_1_COMPAT
inline
Int32 &StageDataBase::getPartitionRangeBegin(void)
{
return this->editPartitionRangeBegin();
}
#endif
//! Set the value of the StageData::_sfPartitionRangeBegin field.
inline
void StageDataBase::setPartitionRangeBegin(const Int32 &value)
{
editSField(PartitionRangeBeginFieldMask);
_sfPartitionRangeBegin.setValue(value);
}
//! Get the value of the StageData::_sfPartitionRangeEnd field.
inline
Int32 &StageDataBase::editPartitionRangeEnd(void)
{
editSField(PartitionRangeEndFieldMask);
return _sfPartitionRangeEnd.getValue();
}
//! Get the value of the StageData::_sfPartitionRangeEnd field.
inline
const Int32 &StageDataBase::getPartitionRangeEnd(void) const
{
return _sfPartitionRangeEnd.getValue();
}
#ifdef OSG_1_COMPAT
inline
Int32 &StageDataBase::getPartitionRangeEnd(void)
{
return this->editPartitionRangeEnd();
}
#endif
//! Set the value of the StageData::_sfPartitionRangeEnd field.
inline
void StageDataBase::setPartitionRangeEnd(const Int32 &value)
{
editSField(PartitionRangeEndFieldMask);
_sfPartitionRangeEnd.setValue(value);
}
//! Get the value of the StageData::_sfGroupMode field.
inline
Int32 &StageDataBase::editGroupMode(void)
{
editSField(GroupModeFieldMask);
return _sfGroupMode.getValue();
}
//! Get the value of the StageData::_sfGroupMode field.
inline
const Int32 &StageDataBase::getGroupMode(void) const
{
return _sfGroupMode.getValue();
}
#ifdef OSG_1_COMPAT
inline
Int32 &StageDataBase::getGroupMode (void)
{
return this->editGroupMode ();
}
#endif
//! Set the value of the StageData::_sfGroupMode field.
inline
void StageDataBase::setGroupMode(const Int32 &value)
{
editSField(GroupModeFieldMask);
_sfGroupMode.setValue(value);
}
//! create a new instance of the class
inline
StageDataP StageDataBase::create(void)
{
StageDataP fc;
if(getClassType().getPrototype() != NULL)
{
fc = dynamic_cast<StageData::ObjPtr>(
getClassType().getPrototype()-> shallowCopy());
}
return fc;
}
inline
Char8 *StageDataBase::getClassname(void)
{
return "StageData";
}
typedef BundlePointerBuilder<
StageData>::ObjPtr StageDataP;
typedef BundlePointerBuilder<
StageData>::ObjPtrConst StageDataPConst;
typedef BundlePointerBuilder<
StageData>::ObjConstPtr StageDataConstP;
typedef BundlePointerBuilder<
StageData>::ObjPtrArg StageDataPArg;
typedef BundlePointerBuilder<
StageData>::ObjConstPtrArg StageDataConstPArg;
typedef BundlePointerBuilder<
StageData>::ObjPtrConstArg StageDataPConstArg;
OSG_END_NAMESPACE
<commit_msg>Silence a compiler warning about a variable possibly being used without being initialized.<commit_after>/*---------------------------------------------------------------------------*\
* OpenSG *
* *
* *
* Copyright (C) 2000-2006 by the OpenSG Forum *
* *
* contact: [email protected], [email protected], [email protected] *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* License *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Library General Public License as published *
* by the Free Software Foundation, version 2. *
* *
* This library is distributed in the hope that it will be useful, but *
* WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *
* Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
* *
\*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*\
* Changes *
* *
* *
* *
* *
* *
* *
\*---------------------------------------------------------------------------*/
/*****************************************************************************\
*****************************************************************************
** **
** This file is automatically generated. **
** **
** Any changes made to this file WILL be lost when it is **
** regenerated, which can become necessary at any time. **
** **
** Do not change this file, changes should be done in the derived **
** class StageData!
** **
*****************************************************************************
\*****************************************************************************/
OSG_BEGIN_NAMESPACE
//! access the type of the class
inline
OSG::FieldBundleType &StageDataBase::getClassType(void)
{
return _type;
}
//! access the numerical type of the class
inline
OSG::UInt32 StageDataBase::getClassTypeId(void)
{
return _type.getId();
}
inline
OSG::UInt16 StageDataBase::getClassGroupId(void)
{
return _type.getGroupId();
}
/*------------------------------ get -----------------------------------*/
//! Get the value of the StageData::_sfPartitionRangeBegin field.
inline
Int32 &StageDataBase::editPartitionRangeBegin(void)
{
editSField(PartitionRangeBeginFieldMask);
return _sfPartitionRangeBegin.getValue();
}
//! Get the value of the StageData::_sfPartitionRangeBegin field.
inline
const Int32 &StageDataBase::getPartitionRangeBegin(void) const
{
return _sfPartitionRangeBegin.getValue();
}
#ifdef OSG_1_COMPAT
inline
Int32 &StageDataBase::getPartitionRangeBegin(void)
{
return this->editPartitionRangeBegin();
}
#endif
//! Set the value of the StageData::_sfPartitionRangeBegin field.
inline
void StageDataBase::setPartitionRangeBegin(const Int32 &value)
{
editSField(PartitionRangeBeginFieldMask);
_sfPartitionRangeBegin.setValue(value);
}
//! Get the value of the StageData::_sfPartitionRangeEnd field.
inline
Int32 &StageDataBase::editPartitionRangeEnd(void)
{
editSField(PartitionRangeEndFieldMask);
return _sfPartitionRangeEnd.getValue();
}
//! Get the value of the StageData::_sfPartitionRangeEnd field.
inline
const Int32 &StageDataBase::getPartitionRangeEnd(void) const
{
return _sfPartitionRangeEnd.getValue();
}
#ifdef OSG_1_COMPAT
inline
Int32 &StageDataBase::getPartitionRangeEnd(void)
{
return this->editPartitionRangeEnd();
}
#endif
//! Set the value of the StageData::_sfPartitionRangeEnd field.
inline
void StageDataBase::setPartitionRangeEnd(const Int32 &value)
{
editSField(PartitionRangeEndFieldMask);
_sfPartitionRangeEnd.setValue(value);
}
//! Get the value of the StageData::_sfGroupMode field.
inline
Int32 &StageDataBase::editGroupMode(void)
{
editSField(GroupModeFieldMask);
return _sfGroupMode.getValue();
}
//! Get the value of the StageData::_sfGroupMode field.
inline
const Int32 &StageDataBase::getGroupMode(void) const
{
return _sfGroupMode.getValue();
}
#ifdef OSG_1_COMPAT
inline
Int32 &StageDataBase::getGroupMode (void)
{
return this->editGroupMode ();
}
#endif
//! Set the value of the StageData::_sfGroupMode field.
inline
void StageDataBase::setGroupMode(const Int32 &value)
{
editSField(GroupModeFieldMask);
_sfGroupMode.setValue(value);
}
//! create a new instance of the class
inline
StageDataP StageDataBase::create(void)
{
StageDataP fc(NULL);
if(getClassType().getPrototype() != NULL)
{
fc = dynamic_cast<StageData::ObjPtr>(
getClassType().getPrototype()-> shallowCopy());
}
return fc;
}
inline
Char8 *StageDataBase::getClassname(void)
{
return "StageData";
}
typedef BundlePointerBuilder<
StageData>::ObjPtr StageDataP;
typedef BundlePointerBuilder<
StageData>::ObjPtrConst StageDataPConst;
typedef BundlePointerBuilder<
StageData>::ObjConstPtr StageDataConstP;
typedef BundlePointerBuilder<
StageData>::ObjPtrArg StageDataPArg;
typedef BundlePointerBuilder<
StageData>::ObjConstPtrArg StageDataConstPArg;
typedef BundlePointerBuilder<
StageData>::ObjPtrConstArg StageDataPConstArg;
OSG_END_NAMESPACE
<|endoftext|> |
<commit_before>//===- ObjCARCAliasAnalysis.cpp - ObjC ARC Optimization -*- mode: c++ -*---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines a simple ARC-aware AliasAnalysis using special knowledge
/// of Objective C to enhance other optimization passes which rely on the Alias
/// Analysis infrastructure.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "objc-arc-aa"
#include "ObjCARC.h"
#include "ObjCARCAliasAnalysis.h"
#include "llvm/IR/Instruction.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassSupport.h"
namespace llvm {
class Function;
class Value;
}
#include "llvm/IR/Instruction.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassSupport.h"
namespace llvm {
class Function;
class Value;
}
using namespace llvm;
using namespace llvm::objcarc;
// Register this pass...
char ObjCARCAliasAnalysis::ID = 0;
INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
"ObjC-ARC-Based Alias Analysis", false, true, false)
ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
return new ObjCARCAliasAnalysis();
}
void
ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AliasAnalysis::getAnalysisUsage(AU);
}
AliasAnalysis::AliasResult
ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
if (!EnableARCOpts)
return AliasAnalysis::alias(LocA, LocB);
// First, strip off no-ops, including ObjC-specific no-ops, and try making a
// precise alias query.
const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
AliasResult Result =
AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
Location(SB, LocB.Size, LocB.TBAATag));
if (Result != MayAlias)
return Result;
// If that failed, climb to the underlying object, including climbing through
// ObjC-specific no-ops, and try making an imprecise alias query.
const Value *UA = GetUnderlyingObjCPtr(SA);
const Value *UB = GetUnderlyingObjCPtr(SB);
if (UA != SA || UB != SB) {
Result = AliasAnalysis::alias(Location(UA), Location(UB));
// We can't use MustAlias or PartialAlias results here because
// GetUnderlyingObjCPtr may return an offsetted pointer value.
if (Result == NoAlias)
return NoAlias;
}
// If that failed, fail. We don't need to chain here, since that's covered
// by the earlier precise query.
return MayAlias;
}
bool
ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
bool OrLocal) {
if (!EnableARCOpts)
return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
// First, strip off no-ops, including ObjC-specific no-ops, and try making
// a precise alias query.
const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
OrLocal))
return true;
// If that failed, climb to the underlying object, including climbing through
// ObjC-specific no-ops, and try making an imprecise alias query.
const Value *U = GetUnderlyingObjCPtr(S);
if (U != S)
return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
// If that failed, fail. We don't need to chain here, since that's covered
// by the earlier precise query.
return false;
}
AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
// We have nothing to do. Just chain to the next AliasAnalysis.
return AliasAnalysis::getModRefBehavior(CS);
}
AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
if (!EnableARCOpts)
return AliasAnalysis::getModRefBehavior(F);
switch (GetFunctionClass(F)) {
case IC_NoopCast:
return DoesNotAccessMemory;
default:
break;
}
return AliasAnalysis::getModRefBehavior(F);
}
AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
if (!EnableARCOpts)
return AliasAnalysis::getModRefInfo(CS, Loc);
switch (GetBasicInstructionClass(CS.getInstruction())) {
case IC_Retain:
case IC_RetainRV:
case IC_Autorelease:
case IC_AutoreleaseRV:
case IC_NoopCast:
case IC_AutoreleasepoolPush:
case IC_FusedRetainAutorelease:
case IC_FusedRetainAutoreleaseRV:
// These functions don't access any memory visible to the compiler.
// Note that this doesn't include objc_retainBlock, because it updates
// pointers when it copies block data.
return NoModRef;
default:
break;
}
return AliasAnalysis::getModRefInfo(CS, Loc);
}
AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
ImmutableCallSite CS2) {
// TODO: Theoretically we could check for dependencies between objc_* calls
// and OnlyAccessesArgumentPointees calls or other well-behaved calls.
return AliasAnalysis::getModRefInfo(CS1, CS2);
}
<commit_msg>Removed some cruft from ObjCARCAliasAnalysis.cpp.<commit_after>//===- ObjCARCAliasAnalysis.cpp - ObjC ARC Optimization -*- mode: c++ -*---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file defines a simple ARC-aware AliasAnalysis using special knowledge
/// of Objective C to enhance other optimization passes which rely on the Alias
/// Analysis infrastructure.
///
/// WARNING: This file knows about certain library functions. It recognizes them
/// by name, and hardwires knowledge of their semantics.
///
/// WARNING: This file knows about how certain Objective-C library functions are
/// used. Naive LLVM IR transformations which would otherwise be
/// behavior-preserving may break these assumptions.
///
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "objc-arc-aa"
#include "ObjCARC.h"
#include "ObjCARCAliasAnalysis.h"
#include "llvm/IR/Instruction.h"
#include "llvm/InitializePasses.h"
#include "llvm/PassAnalysisSupport.h"
#include "llvm/PassSupport.h"
namespace llvm {
class Function;
class Value;
}
using namespace llvm;
using namespace llvm::objcarc;
// Register this pass...
char ObjCARCAliasAnalysis::ID = 0;
INITIALIZE_AG_PASS(ObjCARCAliasAnalysis, AliasAnalysis, "objc-arc-aa",
"ObjC-ARC-Based Alias Analysis", false, true, false)
ImmutablePass *llvm::createObjCARCAliasAnalysisPass() {
return new ObjCARCAliasAnalysis();
}
void
ObjCARCAliasAnalysis::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AliasAnalysis::getAnalysisUsage(AU);
}
AliasAnalysis::AliasResult
ObjCARCAliasAnalysis::alias(const Location &LocA, const Location &LocB) {
if (!EnableARCOpts)
return AliasAnalysis::alias(LocA, LocB);
// First, strip off no-ops, including ObjC-specific no-ops, and try making a
// precise alias query.
const Value *SA = StripPointerCastsAndObjCCalls(LocA.Ptr);
const Value *SB = StripPointerCastsAndObjCCalls(LocB.Ptr);
AliasResult Result =
AliasAnalysis::alias(Location(SA, LocA.Size, LocA.TBAATag),
Location(SB, LocB.Size, LocB.TBAATag));
if (Result != MayAlias)
return Result;
// If that failed, climb to the underlying object, including climbing through
// ObjC-specific no-ops, and try making an imprecise alias query.
const Value *UA = GetUnderlyingObjCPtr(SA);
const Value *UB = GetUnderlyingObjCPtr(SB);
if (UA != SA || UB != SB) {
Result = AliasAnalysis::alias(Location(UA), Location(UB));
// We can't use MustAlias or PartialAlias results here because
// GetUnderlyingObjCPtr may return an offsetted pointer value.
if (Result == NoAlias)
return NoAlias;
}
// If that failed, fail. We don't need to chain here, since that's covered
// by the earlier precise query.
return MayAlias;
}
bool
ObjCARCAliasAnalysis::pointsToConstantMemory(const Location &Loc,
bool OrLocal) {
if (!EnableARCOpts)
return AliasAnalysis::pointsToConstantMemory(Loc, OrLocal);
// First, strip off no-ops, including ObjC-specific no-ops, and try making
// a precise alias query.
const Value *S = StripPointerCastsAndObjCCalls(Loc.Ptr);
if (AliasAnalysis::pointsToConstantMemory(Location(S, Loc.Size, Loc.TBAATag),
OrLocal))
return true;
// If that failed, climb to the underlying object, including climbing through
// ObjC-specific no-ops, and try making an imprecise alias query.
const Value *U = GetUnderlyingObjCPtr(S);
if (U != S)
return AliasAnalysis::pointsToConstantMemory(Location(U), OrLocal);
// If that failed, fail. We don't need to chain here, since that's covered
// by the earlier precise query.
return false;
}
AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(ImmutableCallSite CS) {
// We have nothing to do. Just chain to the next AliasAnalysis.
return AliasAnalysis::getModRefBehavior(CS);
}
AliasAnalysis::ModRefBehavior
ObjCARCAliasAnalysis::getModRefBehavior(const Function *F) {
if (!EnableARCOpts)
return AliasAnalysis::getModRefBehavior(F);
switch (GetFunctionClass(F)) {
case IC_NoopCast:
return DoesNotAccessMemory;
default:
break;
}
return AliasAnalysis::getModRefBehavior(F);
}
AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS, const Location &Loc) {
if (!EnableARCOpts)
return AliasAnalysis::getModRefInfo(CS, Loc);
switch (GetBasicInstructionClass(CS.getInstruction())) {
case IC_Retain:
case IC_RetainRV:
case IC_Autorelease:
case IC_AutoreleaseRV:
case IC_NoopCast:
case IC_AutoreleasepoolPush:
case IC_FusedRetainAutorelease:
case IC_FusedRetainAutoreleaseRV:
// These functions don't access any memory visible to the compiler.
// Note that this doesn't include objc_retainBlock, because it updates
// pointers when it copies block data.
return NoModRef;
default:
break;
}
return AliasAnalysis::getModRefInfo(CS, Loc);
}
AliasAnalysis::ModRefResult
ObjCARCAliasAnalysis::getModRefInfo(ImmutableCallSite CS1,
ImmutableCallSite CS2) {
// TODO: Theoretically we could check for dependencies between objc_* calls
// and OnlyAccessesArgumentPointees calls or other well-behaved calls.
return AliasAnalysis::getModRefInfo(CS1, CS2);
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkBlobSpatialObject.txx"
#include "itkEllipseSpatialObject.txx"
#include "itkGroupSpatialObject.txx"
#include "itkImageSpatialObject.txx"
#include "itkLandmarkSpatialObject.txx"
#include "itkLineSpatialObject.txx"
#include "itkLineSpatialObjectPoint.txx"
#include "itkPlaneSpatialObject.txx"
#include "itkScene.txx"
#include "itkSpatialObject.txx"
#include "itkSpatialObjectPoint.txx"
#include "itkSpatialObjectProperty.txx"
#include "itkSurfaceSpatialObject.txx"
#include "itkSurfaceSpatialObjectPoint.txx"
#include "itkTubeSpatialObject.txx"
#include "itkTubeSpatialObjectPoint.txx"
int main ( int , char* )
{
return 0;
}
<commit_msg>ENH: Updated to latest headers<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit (ITK)
Module:
Language: C++
Date:
Version:
Copyright (c) 2000 National Library of Medicine
All rights reserved.
See COPYRIGHT.txt for copyright details.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <iostream>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight
#include "itkBlobSpatialObject.txx"
#include "itkEllipseSpatialObject.txx"
#include "itkGroupSpatialObject.txx"
#include "itkImageSpatialObject.txx"
#include "itkLandmarkSpatialObject.txx"
#include "itkLineSpatialObject.txx"
#include "itkLineSpatialObjectPoint.txx"
#include "itkNDimensionalSpatialObject.txx"
#include "itkPlaneSpatialObject.txx"
#include "itkScene.txx"
#include "itkSpatialObject.txx"
#include "itkSpatialObjectPoint.txx"
#include "itkSpatialObjectProperty.txx"
#include "itkSurfaceSpatialObject.txx"
#include "itkSurfaceSpatialObjectPoint.txx"
#include "itkTubeSpatialObject.txx"
#include "itkTubeSpatialObjectPoint.txx"
int main ( int , char* )
{
return 0;
}
<|endoftext|> |
<commit_before>#include "test_helper.h"
#include "uTensor/loaders/tensorIdxImporter.hpp"
#include "uTensor/ops/ArrayOps.hpp"
#include <iostream>
using std::cout;
using std::endl;
TensorIdxImporter t_import;
Context ctx;
// Default to using GTest like asserts and expects as these give more info that unity
// We will forward these commands to unity in test_helper.h
void test_operators_quantizeV2(){
S_TENSOR b_q_ref = ctx.addCached(hold(t_import.float_import ("/fs/constants/qB/in/Cast_1_0.idx")), "b_q_ref");
S_TENSOR b_min_q_ref = ctx.addCached(hold(t_import.float_import("/fs/constants/qB/in/Min_1_0.idx")), "b_min_q_ref");
S_TENSOR b_max_q_ref = ctx.addCached(hold(t_import.float_import("/fs/constants/qB/in/Max_1_0.idx")), "b_max_q_ref");
//reference outputs
S_TENSOR ref_b_q = ctx.addCached(hold(t_import.ubyte_import("/fs/constants/qB/out/qB_0.idx")), "ref_b_q");
S_TENSOR ref_b_min_q = ctx.addCached(hold(t_import.float_import("/fs/constants/qB/out/qB_1.idx")), "ref_b_min_q");
S_TENSOR ref_b_max_q = ctx.addCached(hold(t_import.float_import("/fs/constants/qB/out/qB_2.idx")), "ref_b_max_q");
S_TENSOR out_b_q = ctx.addCached(hold(new RamTensor<unsigned char>(b_q_ref->getShape())), "b_q");
S_TENSOR out_b_min_q = ctx.addCached(hold(new RamTensor<float>(b_min_q_ref->getShape())), "b_min_q");
S_TENSOR out_b_max_q = ctx.addCached(hold(new RamTensor<float>(b_max_q_ref->getShape())), "b_max_q");
//Implementation goes here
ctx.push_static(hold(new QuantizeV2Op()), "QuantizeV2Op", {"b_q_ref", "b_min_q_ref", "b_max_q_ref"}, {"b_q", "b_min_q", "b_max_q"});
ctx.eval();
double result = meanPercentErr<unsigned char>(ref_b_q.get(), out_b_q.get()) + meanPercentErr<float>(ref_b_min_q.get(), out_b_min_q.get()) + meanPercentErr<float>(ref_b_max_q.get(), out_b_max_q.get());
EXPECT_EQ(result, 0);
}
void test_operators_dequantize(void) {
//reference inputs
S_TENSOR a = ctx.addCached(hold(t_import.ubyte_import("/fs/constants/deQ/in/rQ_0.idx")), "a");
S_TENSOR a_min = ctx.addCached(hold(t_import.float_import("/fs/constants/deQ/in/rQ_1.idx")), "a_min");
S_TENSOR a_max = ctx.addCached(hold(t_import.float_import("/fs/constants/deQ/in/rQ_2.idx")), "a_max");
//reference outputs
S_TENSOR out_ref = ctx.addCached(hold(t_import.float_import("/fs/constants/deQ/out/deQ_0.idx")), "out_ref");
//modify the checks below:
S_TENSOR out = ctx.addCached(hold(new RamTensor<float>(out_ref->getShape())), "out");
ctx.push_static(hold(new DequantizeOp()), "DequantizeOp", {"a", "a_min", "a_max"}, {"out"});
ctx.eval();
double result = meanPercentErr<float>(out.get(), out_ref.get());
EXPECT_EQ(result, 0);
}
void test_operators_reshape(void) {
//reference inputs
S_TENSOR ref_a = ctx.addCached(hold(t_import.float_import("/fs/constants/ref_reshape/in/Const_0.idx")), "ref_a");
S_TENSOR ref_dim = ctx.addCached(hold(t_import.int_import("/fs/constants/ref_reshape/in/Const_1_0.idx")), "ref_dim");
//reference outputs
S_TENSOR out_ref_2 = ctx.addCached(hold(t_import.float_import("/fs/constants/ref_reshape/out/ref_reshape_0.idx")), "out_ref_2");
//modify the checks below:
S_TENSOR out_2 = ctx.addCached(hold(new RamTensor<float>(out_ref_2->getShape())), "out_2");
ctx.push_static(hold(new ReshapeOp()), "ReshapeOp", {"ref_a", "ref_dim"}, {"out_2"});
ctx.eval();
double result = meanPercentErr<float>(out_2.get(), out_ref_2.get());
EXPECT_EQ(result, 0);
}
// First configure the uTensor test runner
UTENSOR_TEST_CONFIGURE()
// Second declare tests to run
UTENSOR_TEST(operators, quantizeV2, "Quantize V2 test")
UTENSOR_TEST(operators, dequantize, "Dequantization Test")
UTENSOR_TEST(operators, reshape, "Reshape Test")
// Third, run like hell
UTENSOR_TEST_RUN()
<commit_msg>Add gather test<commit_after>#include "test_helper.h"
#include "uTensor/loaders/tensorIdxImporter.hpp"
#include "uTensor/ops/ArrayOps.hpp"
#include <iostream>
using std::cout;
using std::endl;
TensorIdxImporter t_import;
Context ctx;
// Default to using GTest like asserts and expects as these give more info that unity
// We will forward these commands to unity in test_helper.h
void test_operators_quantizeV2(){
S_TENSOR b_q_ref = ctx.addCached(hold(t_import.float_import ("/fs/constants/qB/in/Cast_1_0.idx")), "b_q_ref");
S_TENSOR b_min_q_ref = ctx.addCached(hold(t_import.float_import("/fs/constants/qB/in/Min_1_0.idx")), "b_min_q_ref");
S_TENSOR b_max_q_ref = ctx.addCached(hold(t_import.float_import("/fs/constants/qB/in/Max_1_0.idx")), "b_max_q_ref");
//reference outputs
S_TENSOR ref_b_q = ctx.addCached(hold(t_import.ubyte_import("/fs/constants/qB/out/qB_0.idx")), "ref_b_q");
S_TENSOR ref_b_min_q = ctx.addCached(hold(t_import.float_import("/fs/constants/qB/out/qB_1.idx")), "ref_b_min_q");
S_TENSOR ref_b_max_q = ctx.addCached(hold(t_import.float_import("/fs/constants/qB/out/qB_2.idx")), "ref_b_max_q");
S_TENSOR out_b_q = ctx.addCached(hold(new RamTensor<unsigned char>(b_q_ref->getShape())), "b_q");
S_TENSOR out_b_min_q = ctx.addCached(hold(new RamTensor<float>(b_min_q_ref->getShape())), "b_min_q");
S_TENSOR out_b_max_q = ctx.addCached(hold(new RamTensor<float>(b_max_q_ref->getShape())), "b_max_q");
//Implementation goes here
ctx.push_static(hold(new QuantizeV2Op()), "QuantizeV2Op", {"b_q_ref", "b_min_q_ref", "b_max_q_ref"}, {"b_q", "b_min_q", "b_max_q"});
ctx.eval();
double result = meanPercentErr<unsigned char>(ref_b_q.get(), out_b_q.get()) + meanPercentErr<float>(ref_b_min_q.get(), out_b_min_q.get()) + meanPercentErr<float>(ref_b_max_q.get(), out_b_max_q.get());
EXPECT_EQ(result, 0);
}
void test_operators_dequantize(void) {
//reference inputs
S_TENSOR a = ctx.addCached(hold(t_import.ubyte_import("/fs/constants/deQ/in/rQ_0.idx")), "a");
S_TENSOR a_min = ctx.addCached(hold(t_import.float_import("/fs/constants/deQ/in/rQ_1.idx")), "a_min");
S_TENSOR a_max = ctx.addCached(hold(t_import.float_import("/fs/constants/deQ/in/rQ_2.idx")), "a_max");
//reference outputs
S_TENSOR out_ref = ctx.addCached(hold(t_import.float_import("/fs/constants/deQ/out/deQ_0.idx")), "out_ref");
//modify the checks below:
S_TENSOR out = ctx.addCached(hold(new RamTensor<float>(out_ref->getShape())), "out");
ctx.push_static(hold(new DequantizeOp()), "DequantizeOp", {"a", "a_min", "a_max"}, {"out"});
ctx.eval();
double result = meanPercentErr<float>(out.get(), out_ref.get());
EXPECT_EQ(result, 0);
}
void test_operators_reshape(void) {
//reference inputs
S_TENSOR ref_a = ctx.addCached(hold(t_import.float_import("/fs/constants/ref_reshape/in/Const_0.idx")), "ref_a");
S_TENSOR ref_dim = ctx.addCached(hold(t_import.int_import("/fs/constants/ref_reshape/in/Const_1_0.idx")), "ref_dim");
//reference outputs
S_TENSOR out_ref_2 = ctx.addCached(hold(t_import.float_import("/fs/constants/ref_reshape/out/ref_reshape_0.idx")), "out_ref_2");
//modify the checks below:
S_TENSOR out_2 = ctx.addCached(hold(new RamTensor<float>(out_ref_2->getShape())), "out_2");
ctx.push_static(hold(new ReshapeOp()), "ReshapeOp", {"ref_a", "ref_dim"}, {"out_2"});
ctx.eval();
double result = meanPercentErr<float>(out_2.get(), out_ref_2.get());
EXPECT_EQ(result, 0);
}
void test_operators_gather(void) {
Tensor* input = new RamTensor<float>();
Tensor* output = new RamTensor<float>();
Tensor* out_ref = new RamTensor<float>();
Tensor* indices = new RamTensor<uint32_t>();
TensorShape tmp({2, 2});
TensorShape tmp2({3});
input->init(tmp);
output->init(tmp2);
indices->init(tmp2);
out_ref->init(tmp2);
input->write<float>(0,0)[0] = 100.0;
input->write<float>(0,0)[1] = 11.0;
input->write<float>(0,0)[2] = 12.0;
input->write<float>(0,0)[3] = 13.0;
indices->write<uint32_t>(0,0)[0] = 1;
indices->write<uint32_t>(0,0)[1] = 2;
indices->write<uint32_t>(0,0)[2] = 1;
out_ref->write<float>(0,0)[0] = 11.0;
out_ref->write<float>(0,0)[1] = 12.0;
out_ref->write<float>(0,0)[2] = 11.0;
ctx.add(input, "g_input");
ctx.add(output, "g_output");
ctx.add(indices, "g_indices");
ctx.push(new GatherOp<float>(),
{"g_input", "g_indices"},
{"g_output"});
ctx.eval();
double result = meanPercentErr<float>(output, out_ref);
EXPECT_EQ(result, 0);
}
// First configure the uTensor test runner
UTENSOR_TEST_CONFIGURE()
// Second declare tests to run
UTENSOR_TEST(operators, quantizeV2, "Quantize V2 test")
UTENSOR_TEST(operators, dequantize, "Dequantization Test")
UTENSOR_TEST(operators, reshape, "Reshape Test")
// Third, run like hell
UTENSOR_TEST_RUN()
<|endoftext|> |
<commit_before>#include <chrono>
#include <iostream>
#include <fstream>
#include <numeric>
#include <math.h>
#include <string>
#include <time.h>
#include "mkldnn.hpp"
#include "configure.h"
using namespace mkldnn;
using namespace std;
void maxpool()
{
auto cpu_engine = engine(engine::cpu, 0);
std::vector<float> net_src(BATCH_SIZE * FIn * N * N);
std::vector<float> net_dst(BATCH_SIZE * FIn * ((N - K_Y + 2 * P_Y) / S_Y + 1) * ((N - K_X + 2 * P_X) / S_X + 1));
/* Initializing non-zero values for src */
srand(1);
for (size_t i = 0; i < net_src.size(); ++i)
net_src[i] = rand() % 10;
memory::dims src_tz = {BATCH_SIZE, FIn, N, N};
/* Create memory for user data */
auto user_src_memory = memory(
{{{src_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
net_src.data());
/* Create mmemory descriptors for source data */
auto src_md = memory::desc({src_tz}, memory::data_type::f32,
memory::format::nchw);
/* Pool */
memory::dims pool_dst_tz = {BATCH_SIZE, FIn, ((N - K_Y + 2 * P_Y) / S_Y + 1), ((N - K_X + 2 * P_X) / S_X + 1)};
memory::dims pool_kernel = {K_Y, K_X};
memory::dims pool_strides = {S_Y, S_X};
auto pool_padding = {P_Y, P_X};
/* Create memory for pool dst data in user format */
auto pool_user_dst_memory = memory(
{{{pool_dst_tz}, memory::data_type::f32, memory::format::nchw},
cpu_engine},
net_dst.data());
/* Create pool dst memory descriptor in format any */
auto pool_dst_md = memory::desc({pool_dst_tz}, memory::data_type::f32,
memory::format::any);
/* Create a pooling primitive descriptor */
auto pool_desc = pooling_forward::desc(
prop_kind::forward, pooling_max,
src_md, pool_dst_md,
pool_strides, pool_kernel, pool_padding, pool_padding,
padding_kind::zero);
auto pool_pd = pooling_forward::primitive_desc(pool_desc, cpu_engine);
/* Create reorder primitive between pool dst and user dst format if needed */
auto pool_dst_memory = pool_user_dst_memory;
bool reorder_pool_dst = false;
primitive pool_reorder_dst;
if (memory::primitive_desc(pool_pd.dst_primitive_desc()) != pool_user_dst_memory.get_primitive_desc())
{
pool_dst_memory = memory(pool_pd.dst_primitive_desc());
pool_reorder_dst = reorder(pool_dst_memory, pool_user_dst_memory);
reorder_pool_dst = true;
}
/* Create pooling workspace memory if training */
auto pool_workspace_memory = memory(pool_pd.workspace_primitive_desc());
/* Finally create a pooling primitive */
auto pool = pooling_forward(pool_pd, user_src_memory, pool_dst_memory,
pool_workspace_memory);
/* Build forward net */
std::vector<primitive> net_fwd;
net_fwd.push_back(pool);
if (reorder_pool_dst)
net_fwd.push_back(pool_reorder_dst);
std::vector<std::chrono::duration<double, std::milli>> duration_vector_2;
for (int i = 0; i < NB_TESTS; i++)
{
auto start1 = std::chrono::high_resolution_clock::now();
stream(stream::kind::eager).submit(net_fwd).wait();
auto end1 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> duration = end1 - start1;
duration_vector_2.push_back(duration);
}
std::cout << "\t\tMKL-DNN maxpool duration"
<< ": " << median(duration_vector_2) << "; " << std::endl;
printf("writing result in file\n");
ofstream resultfile;
resultfile.open("mkldnn_result.txt");
float *poolres = (float *)pool_dst_memory.get_data_handle();
for (size_t i = 0; i < BATCH_SIZE; ++i)
for (size_t j = 0; j < FIn; ++j)
for (size_t k = 0; k < ((N - K_Y + 2 * P_Y) / S_Y + 1); ++k)
for (size_t l = 0; l < ((N - K_X + 2 * P_X) / S_X + 1); ++l)
resultfile << poolres[i * FIn * ((N - K_Y + 2 * P_Y) / S_Y + 1) * ((N - K_X + 2 * P_X) / S_X + 1) + j * ((N - K_Y + 2 * P_Y) / S_Y + 1) * ((N - K_X + 2 * P_X) / S_X + 1) + k * ((N - K_X + 2 * P_X) / S_X + 1) + l];
resultfile.close();
}
int main(int argc, char **argv)
{
try
{
maxpool();
}
catch (error &e)
{
std::cerr << "status: " << e.status << std::endl;
std::cerr << "message: " << e.message << std::endl;
}
return 0;
}
<commit_msg>Delete maxpool_layer_generator_mkldnn.cpp<commit_after><|endoftext|> |
<commit_before>#include "twitchuser.h"
namespace chatterino {
namespace twitch {
TwitchUser::TwitchUser(const QString &username, const QString &oauthToken,
const QString &oauthClient)
: IrcUser2(username, username, username, "oauth:" + oauthToken)
{
_oauthClient = oauthClient;
_oauthToken = oauthToken;
}
const QString &TwitchUser::getOAuthClient() const
{
return _oauthClient;
}
const QString &TwitchUser::getOAuthToken() const
{
return _oauthToken;
}
bool TwitchUser::isAnon() const
{
return IrcUser2::getNickName().startsWith("justinfan");
}
}
}
<commit_msg>moved stuff to the thing where it should be<commit_after>#include "twitchuser.h"
namespace chatterino {
namespace twitch {
TwitchUser::TwitchUser(const QString &username, const QString &oauthToken,
const QString &oauthClient)
: IrcUser2(username, username, username, "oauth:" + oauthToken)
, _oauthClient(oauthClient)
, _oauthToken(oauthToken)
{
}
const QString &TwitchUser::getOAuthClient() const
{
return _oauthClient;
}
const QString &TwitchUser::getOAuthToken() const
{
return _oauthToken;
}
bool TwitchUser::isAnon() const
{
return IrcUser2::getNickName().startsWith("justinfan");
}
}
}
<|endoftext|> |
<commit_before>/*
** network-thread.cpp
** Login : <hcuche@hcuche-de>
** Started on Tue Jan 10 11:41:39 2012 Herve Cuche
** $Id$
**
** Author(s):
** - Herve Cuche <[email protected]>
**
** Copyright (C) 2012 Herve Cuche
*/
#include <iostream>
#include <qi/log.hpp>
#include <qimessaging/transport/network_thread.hpp>
namespace qi {
static void errorcb(struct bufferevent *bev,
short error,
void *ctx)
{
if (error & BEV_EVENT_EOF)
{
// connection has been closed, do any clean up here
qiLogError("qimessaging.TransportSocket") << "connection has been closed, do any clean up here" << std::endl;
}
else if (error & BEV_EVENT_ERROR)
{
// check errno to see what error occurred
qiLogError("qimessaging.TransportSocket") << "check errno to see what error occurred" << std::endl;
}
else if (error & BEV_EVENT_TIMEOUT)
{
// must be a timeout event handle, handle it
qiLogError("qimessaging.TransportSocket") << "must be a timeout event handle, handle it" << std::endl;
}
}
NetworkThread::NetworkThread()
{
if (!(_base = event_base_new()))
return;
_thd = boost::thread(&NetworkThread::run, this);
}
NetworkThread::~NetworkThread()
{
event_base_free(_base);
}
void NetworkThread::run()
{
struct bufferevent *bev = bufferevent_socket_new(_base, -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, NULL, NULL, ::qi::errorcb, this);
bufferevent_enable(bev, EV_READ|EV_WRITE);
event_base_dispatch(_base);
}
struct event_base* NetworkThread::getEventBase()
{
return _base;
}
}
<commit_msg>Dubious commit: WSASTARTUP and WSACLEANUP<commit_after>/*
** network-thread.cpp
** Login : <hcuche@hcuche-de>
** Started on Tue Jan 10 11:41:39 2012 Herve Cuche
** $Id$
**
** Author(s):
** - Herve Cuche <[email protected]>
**
** Copyright (C) 2012 Herve Cuche
*/
#include <iostream>
#include <qi/log.hpp>
#include <qimessaging/transport/network_thread.hpp>
namespace qi {
static void errorcb(struct bufferevent *bev,
short error,
void *ctx)
{
if (error & BEV_EVENT_EOF)
{
// connection has been closed, do any clean up here
qiLogError("qimessaging.TransportSocket") << "connection has been closed, do any clean up here" << std::endl;
}
else if (error & BEV_EVENT_ERROR)
{
// check errno to see what error occurred
qiLogError("qimessaging.TransportSocket") << "check errno to see what error occurred" << std::endl;
}
else if (error & BEV_EVENT_TIMEOUT)
{
// must be a timeout event handle, handle it
qiLogError("qimessaging.TransportSocket") << "must be a timeout event handle, handle it" << std::endl;
}
}
NetworkThread::NetworkThread()
{
#ifdef _WIN32
// libevent does not call WSAStartup
WSADATA WSAData;
// TODO: handle return code
::WSAStartup(MAKEWORD(1, 0), &WSAData);
#endif
if (!(_base = event_base_new()))
return;
_thd = boost::thread(&NetworkThread::run, this);
}
NetworkThread::~NetworkThread()
{
event_base_free(_base);
#ifdef _WIN32
// TODO handle return code
::WSACleanup();
#endif
}
void NetworkThread::run()
{
struct bufferevent *bev = bufferevent_socket_new(_base, -1, BEV_OPT_CLOSE_ON_FREE);
bufferevent_setcb(bev, NULL, NULL, ::qi::errorcb, this);
bufferevent_enable(bev, EV_READ|EV_WRITE);
event_base_dispatch(_base);
}
struct event_base* NetworkThread::getEventBase()
{
return _base;
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2012-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file Subscription.hpp
*
*/
#pragma once
#include <uORB/uORB.h>
#include <px4_defines.h>
#include "uORBDeviceNode.hpp"
#include "uORBManager.hpp"
#include "uORBUtils.hpp"
namespace uORB
{
// Base subscription wrapper class
class Subscription
{
public:
/**
* Constructor
*
* @param meta The uORB metadata (usually from the ORB_ID() macro) for the topic.
* @param instance The instance for multi sub.
*/
Subscription(const orb_metadata *meta, uint8_t instance = 0) : _meta(meta), _instance(instance)
{
init();
}
virtual ~Subscription() { unsubscribe(); }
bool init();
bool forceInit();
bool valid() const { return _node != nullptr; }
bool published() { return valid() ? _node->is_published() : init(); }
/**
* Check if there is a new update.
* */
virtual bool updated() { return published() ? (_node->published_message_count() != _last_generation) : false; }
/**
* Update the struct
* @param data The uORB message struct we are updating.
*/
virtual bool update(void *dst) { return updated() ? copy(dst) : false; }
/**
* Check if subscription updated based on timestamp.
*
* @return true only if topic was updated based on a timestamp and
* copied to buffer successfully.
* If topic was not updated since last check it will return false but
* still copy the data.
* If no data available data buffer will be filled with zeros.
*/
bool update(uint64_t *time, void *dst);
/**
* Copy the struct
* @param data The uORB message struct we are updating.
*/
bool copy(void *dst) { return published() ? _node->copy(dst, _last_generation) : false; }
hrt_abstime last_update() { return published() ? _node->last_update() : 0; }
uint8_t get_instance() const { return _instance; }
orb_id_t get_topic() const { return _meta; }
protected:
bool subscribe();
void unsubscribe();
DeviceNode *_node{nullptr};
const orb_metadata *_meta{nullptr};
/**
* Subscription's latest data generation.
* Also used to track (and rate limit) subscription
* attempts if the topic has not yet been published.
*/
unsigned _last_generation{0};
uint8_t _instance{0};
};
// Subscription wrapper class with configured interval
class SubscriptionInterval : public Subscription
{
public:
/**
* Constructor
*
* @param meta The uORB metadata (usually from the ORB_ID() macro) for the topic.
* @param interval The minimum interval in milliseconds between updates
* @param instance The instance for multi sub.
*/
SubscriptionInterval(const orb_metadata *meta, unsigned interval = 0, uint8_t instance = 0) :
Subscription(meta, instance),
_interval(interval)
{}
virtual ~SubscriptionInterval() = default;
bool updated() override
{
if (hrt_elapsed_time(&_last_update) >= (_interval * 1000)) {
return Subscription::updated();
}
return false;
}
bool update(void *dst) override
{
if (updated()) {
if (copy(dst)) {
_last_update = hrt_absolute_time();
return true;
}
}
return false;
}
int get_interval() const { return _interval; }
void set_interval(unsigned interval) { _interval = interval; }
protected:
uint64_t _last_update{0}; // last update in microseconds
unsigned _interval{0}; // interval in milliseconds
};
// Subscription wrapper class with data
template<class T>
class SubscriptionData : public Subscription
{
public:
/**
* Constructor
*
* @param meta The uORB metadata (usually from the ORB_ID() macro) for the topic.
* @param instance The instance for multi sub.
*/
SubscriptionData(const orb_metadata *meta, uint8_t instance = 0) :
Subscription(meta, instance)
{
copy(&_data);
}
virtual ~SubscriptionData() = default;
// no copy, assignment, move, move assignment
SubscriptionData(const SubscriptionData &) = delete;
SubscriptionData &operator=(const SubscriptionData &) = delete;
SubscriptionData(SubscriptionData &&) = delete;
SubscriptionData &operator=(SubscriptionData &&) = delete;
// update the embedded struct.
bool update() { return Subscription::update((void *)(&_data)); }
const T &get() const { return _data; }
private:
T _data{};
};
// Subscription wrapper class with data and configured interval
template<class T>
class SubscriptionIntervalData : public SubscriptionInterval
{
public:
/**
* Constructor
*
* @param meta The uORB metadata (usually from the ORB_ID() macro) for the topic.
* @param interval The minimum interval in milliseconds between updates
* @param instance The instance for multi sub.
*/
SubscriptionIntervalData(const orb_metadata *meta, unsigned interval = 0, uint8_t instance = 0) :
SubscriptionInterval(meta, interval, instance)
{
copy(&_data);
}
~SubscriptionIntervalData() override = default;
// no copy, assignment, move, move assignment
SubscriptionIntervalData(const SubscriptionIntervalData &) = delete;
SubscriptionIntervalData &operator=(const SubscriptionIntervalData &) = delete;
SubscriptionIntervalData(SubscriptionIntervalData &&) = delete;
SubscriptionIntervalData &operator=(SubscriptionIntervalData &&) = delete;
// update the embedded struct.
bool update() { return SubscriptionInterval::update((void *)(&_data)); }
const T &get() const { return _data; }
private:
T _data{};
};
} // namespace uORB
<commit_msg>uORB remove unused SubscriptionInterval and SubscriptionIntervalData<commit_after>/****************************************************************************
*
* Copyright (c) 2012-2019 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file Subscription.hpp
*
*/
#pragma once
#include <uORB/uORB.h>
#include <px4_defines.h>
#include "uORBDeviceNode.hpp"
#include "uORBManager.hpp"
#include "uORBUtils.hpp"
namespace uORB
{
// Base subscription wrapper class
class Subscription
{
public:
/**
* Constructor
*
* @param meta The uORB metadata (usually from the ORB_ID() macro) for the topic.
* @param instance The instance for multi sub.
*/
Subscription(const orb_metadata *meta, uint8_t instance = 0) : _meta(meta), _instance(instance)
{
init();
}
~Subscription() { unsubscribe(); }
bool init();
bool forceInit();
bool valid() const { return _node != nullptr; }
bool published() { return valid() ? _node->is_published() : init(); }
/**
* Check if there is a new update.
* */
bool updated() { return published() ? (_node->published_message_count() != _last_generation) : false; }
/**
* Update the struct
* @param data The uORB message struct we are updating.
*/
bool update(void *dst) { return updated() ? copy(dst) : false; }
/**
* Check if subscription updated based on timestamp.
*
* @return true only if topic was updated based on a timestamp and
* copied to buffer successfully.
* If topic was not updated since last check it will return false but
* still copy the data.
* If no data available data buffer will be filled with zeros.
*/
bool update(uint64_t *time, void *dst);
/**
* Copy the struct
* @param data The uORB message struct we are updating.
*/
bool copy(void *dst) { return published() ? _node->copy(dst, _last_generation) : false; }
hrt_abstime last_update() { return published() ? _node->last_update() : 0; }
uint8_t get_instance() const { return _instance; }
orb_id_t get_topic() const { return _meta; }
protected:
bool subscribe();
void unsubscribe();
DeviceNode *_node{nullptr};
const orb_metadata *_meta{nullptr};
/**
* Subscription's latest data generation.
* Also used to track (and rate limit) subscription
* attempts if the topic has not yet been published.
*/
unsigned _last_generation{0};
uint8_t _instance{0};
};
// Subscription wrapper class with data
template<class T>
class SubscriptionData : public Subscription
{
public:
/**
* Constructor
*
* @param meta The uORB metadata (usually from the ORB_ID() macro) for the topic.
* @param instance The instance for multi sub.
*/
SubscriptionData(const orb_metadata *meta, uint8_t instance = 0) :
Subscription(meta, instance)
{
copy(&_data);
}
~SubscriptionData() = default;
// no copy, assignment, move, move assignment
SubscriptionData(const SubscriptionData &) = delete;
SubscriptionData &operator=(const SubscriptionData &) = delete;
SubscriptionData(SubscriptionData &&) = delete;
SubscriptionData &operator=(SubscriptionData &&) = delete;
// update the embedded struct.
bool update() { return Subscription::update((void *)(&_data)); }
const T &get() const { return _data; }
private:
T _data{};
};
} // namespace uORB
<|endoftext|> |
<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <algorithm>
#include <iostream>
#include <regex>
#include <unordered_set>
#include <vector>
#include "graph_rewrite.hpp"
#include "ngraph/log.hpp"
using namespace std;
using namespace ngraph;
// GraphRewrite algorithm:
// GraphRewrite processes an input graph in an topological order(i.e. args before users)
// Given the following graph: Abs2
// / \
// Constant1 Add4 - Result5
// \ /
// Neg3
//
// The topological order would be : `Constant1`, `Abs2`, `Neg3`, `Add4`, `Result5`
// Note, `Abs2` comes before `Neg3` as `Abs2`'s id = 2 is *less* than `Neg3`'s one (id = 3)
// Next, GraphRewrite will invoke matchers registered in an order registered in a c-tor
// i.e. if a c-tor calls `construct_m1()`; `construct_m2()`; `construct_m3()`;
// Matchers will be called as follows: `m1`, `m2`, `m3`
// Matchers should only replace nodes in the graph that come before the current root
// node in the topological order. For example, if Matcher matches Neg3, it should only
// replace nodes `Abs2` and `Constant1` if needed
// This gives Matchers a nice cascading property. For example, if m1 folds `Abs2(Constant1)`
// and `m2` folds `Neg3(Constant1)` when `m3` is called on `Add4` it will discover that
// both `Abs2` and `Neg3` were already replaced by constants, so `Add4` will also be folded into one.
// If any Matcher succeeds the rest of the matchers will **not** be called.
// E.g. if `m1` succeeds and replaces `Abs2` with a new constant, nor `m2` or `m3` will be called
// However, sometimes, you will need more than one fusion occur on the same node.
// In this case, you should be able to request another pass of GraphRewrite.
// To request another pass, you will need to register fusions in a callback:
// i.e. you will need to pass `this` into a callback and then call `this->construct_X`
// This will schedule another pass of GraphRewrite with the following fusion.
// This approach should only be used if you are either:
// a) need more than one fusion occur on the same node
// b) you are modifying nodes after the current node in the topological order
// c) there's no linear order of fusions which will give
// the correct final fusion. i.e. the same fusion needs to occur before and after some other fusion
bool pass::GraphRewrite::run_on_function(shared_ptr<Function> f)
{
bool rewritten = false;
const size_t NUM_TRIES = 10;
size_t tries = NUM_TRIES;
vector<MatchClosure> original_matchers{m_matchers};
bool is_dyn_func = f->is_dynamic();
do
{
rewritten = false;
// m_matchers may contain newly constructed matchers for matchers
// that need multiple passes. See comments above.
vector<MatchClosure> matchers_to_run{m_matchers};
m_matchers.clear();
for (auto node : f->get_ordered_ops())
{
for (auto& closure : matchers_to_run)
{
if (is_dyn_func && closure.property[PassProperty::REQUIRE_STATIC_SHAPE])
{
NGRAPH_DEBUG << "matcher callback requires static shape but the "
"function is dynamic, skipping this "
"optimization till the shapes are fully "
"materialized";
continue;
}
NGRAPH_DEBUG << "Running matcher " << closure.matcher->get_name() << "("
<< closure.matcher->get_pattern()->get_name() << ") on "
<< node->get_name();
if (closure.matcher->match(node))
{
NGRAPH_DEBUG << "Matcher " << closure.matcher << closure.matcher->get_name()
<< " matched " << node->get_name();
if (closure.callback(*closure.matcher.get()))
{
rewritten = true;
// If call back may change function's is_dynamic state, we need to
// update the cached value.
if (closure.property.is_set(PassProperty::CHANGE_DYNAMIC_STATE))
{
is_dyn_func = f->is_dynamic();
}
break;
}
}
}
}
} while (rewritten && m_matchers.size() > 0 && tries--);
m_matchers.assign(original_matchers.begin(), original_matchers.end());
return (NUM_TRIES - tries) > 1; //this means a graph was transformed
}
static vector<regex> initialize_fusion_regexes()
{
const char* cnsf = getenv("NGRAPH_DISABLED_FUSIONS");
vector<regex> regexes;
if (cnsf)
{
const string nsf = cnsf;
const auto sregexes = split(nsf, ';');
transform(sregexes.begin(),
sregexes.end(),
back_inserter(regexes),
[](const string& c) -> regex { return regex(c); });
}
return regexes;
}
bool pass::GraphRewrite::is_enabled(const shared_ptr<pattern::Matcher>& m) const
{
//note, regexes are static to avoid re-initialization
static const auto regexes = initialize_fusion_regexes();
for (const auto& regex : regexes)
{
if (regex_match(m->get_name(), regex))
{
NGRAPH_DEBUG << "Disabling matcher " << m->get_name();
return false;
}
}
return true;
}
void pass::GraphRewrite::add_matcher(const shared_ptr<pattern::Matcher>& m,
const graph_rewrite_callback& callback,
const PassPropertyMask& property)
{
if (is_enabled(m))
{
m_matchers.push_back({m, callback, property});
// If any matcher call back may change dynamic state, we need to
// update the pass property.
if (property.is_set(PassProperty::CHANGE_DYNAMIC_STATE))
{
set_property(PassProperty::CHANGE_DYNAMIC_STATE, true);
}
}
}
void pass::GraphRewrite::add_matcher(const shared_ptr<pattern::Matcher>& m,
const graph_rewrite_callback& callback)
{
// TODO: before deprecate this function, by default expect the
// callback require static shape.
add_matcher(m, callback, {PassProperty::REQUIRE_STATIC_SHAPE});
}
void pass::RecurrentGraphRewrite::add_matcher(
const std::shared_ptr<pattern::RecurrentMatcher>& m,
const ngraph::recurrent_graph_rewrite_callback& callback,
const PassPropertyMask& property)
{
m_matchers.push_back({m, callback, property});
// If any matcher call back may change dynamic state, we need to
// update the pass property.
if (property.is_set(PassProperty::CHANGE_DYNAMIC_STATE))
{
set_property(PassProperty::CHANGE_DYNAMIC_STATE, true);
}
}
void pass::RecurrentGraphRewrite::add_matcher(
const std::shared_ptr<pattern::RecurrentMatcher>& m,
const ngraph::recurrent_graph_rewrite_callback& callback)
{
// TODO: before deprecate this function, by default expect the
// callback require static shape.
add_matcher(m, callback, {PassProperty::REQUIRE_STATIC_SHAPE});
}
bool pass::RecurrentGraphRewrite::run_on_function(shared_ptr<Function> f)
{
bool changed = false;
size_t i = 0;
auto run_matchers = [&]() -> bool {
bool is_dyn_func = f->is_dynamic();
for (auto node : f->get_ops())
{
for (auto& closure : m_matchers)
{
if (is_dyn_func && closure.property[PassProperty::REQUIRE_STATIC_SHAPE])
{
NGRAPH_DEBUG << "matcher callback requires static shape but the "
"function is dynamic, skipping this "
"optimization till the shapes are fully "
"materialized";
continue;
}
NGRAPH_DEBUG << "Running matcher " << closure.matcher << " on " << node->get_name();
if (closure.matcher->match(node))
{
NGRAPH_DEBUG << "Matcher " << closure.matcher << " matched "
<< node->get_name();
if (closure.callback(*closure.matcher.get()))
{
// If call back may change function's is_dynamic state, we need to
// update the cached value.
if (closure.property.is_set(PassProperty::CHANGE_DYNAMIC_STATE))
{
is_dyn_func = f->is_dynamic();
}
return true;
}
}
}
}
return false;
};
do
{
changed = run_matchers();
i++;
} while (changed && i < m_num_iters);
return changed;
}
<commit_msg>Backport fix from #2973 (#2976)<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <algorithm>
#include <iostream>
#include <regex>
#include <unordered_set>
#include <vector>
#include "graph_rewrite.hpp"
#include "ngraph/log.hpp"
using namespace std;
using namespace ngraph;
// GraphRewrite algorithm:
// GraphRewrite processes an input graph in an topological order(i.e. args before users)
// Given the following graph: Abs2
// / \
// Constant1 Add4 - Result5
// \ /
// Neg3
//
// The topological order would be : `Constant1`, `Abs2`, `Neg3`, `Add4`, `Result5`
// Note, `Abs2` comes before `Neg3` as `Abs2`'s id = 2 is *less* than `Neg3`'s one (id = 3)
// Next, GraphRewrite will invoke matchers registered in an order registered in a c-tor
// i.e. if a c-tor calls `construct_m1()`; `construct_m2()`; `construct_m3()`;
// Matchers will be called as follows: `m1`, `m2`, `m3`
// Matchers should only replace nodes in the graph that come before the current root
// node in the topological order. For example, if Matcher matches Neg3, it should only
// replace nodes `Abs2` and `Constant1` if needed
// This gives Matchers a nice cascading property. For example, if m1 folds `Abs2(Constant1)`
// and `m2` folds `Neg3(Constant1)` when `m3` is called on `Add4` it will discover that
// both `Abs2` and `Neg3` were already replaced by constants, so `Add4` will also be folded into one.
// If any Matcher succeeds the rest of the matchers will **not** be called.
// E.g. if `m1` succeeds and replaces `Abs2` with a new constant, nor `m2` or `m3` will be called
// However, sometimes, you will need more than one fusion occur on the same node.
// In this case, you should be able to request another pass of GraphRewrite.
// To request another pass, you will need to register fusions in a callback:
// i.e. you will need to pass `this` into a callback and then call `this->construct_X`
// This will schedule another pass of GraphRewrite with the following fusion.
// This approach should only be used if you are either:
// a) need more than one fusion occur on the same node
// b) you are modifying nodes after the current node in the topological order
// c) there's no linear order of fusions which will give
// the correct final fusion. i.e. the same fusion needs to occur before and after some other fusion
bool pass::GraphRewrite::run_on_function(shared_ptr<Function> f)
{
bool rewritten = false;
const size_t NUM_TRIES = 10;
size_t tries = NUM_TRIES;
vector<MatchClosure> original_matchers{m_matchers};
// This check is very expensive and is only needed for experimental features, so we will hide
// it behind an environment variable for now. TODO: Find a less expensive way to handle this.
static bool s_rerun_dynamic_check =
(std::getenv("NGRAPH_GRAPH_REWRITE_RERUN_DYNAMIC_CHECK") != nullptr);
bool is_dyn_func = s_rerun_dynamic_check && f->is_dynamic();
do
{
rewritten = false;
// m_matchers may contain newly constructed matchers for matchers
// that need multiple passes. See comments above.
vector<MatchClosure> matchers_to_run{m_matchers};
m_matchers.clear();
for (auto node : f->get_ordered_ops())
{
for (auto& closure : matchers_to_run)
{
if (is_dyn_func && closure.property[PassProperty::REQUIRE_STATIC_SHAPE])
{
NGRAPH_DEBUG << "matcher callback requires static shape but the "
"function is dynamic, skipping this "
"optimization till the shapes are fully "
"materialized";
continue;
}
NGRAPH_DEBUG << "Running matcher " << closure.matcher->get_name() << "("
<< closure.matcher->get_pattern()->get_name() << ") on "
<< node->get_name();
if (closure.matcher->match(node))
{
NGRAPH_DEBUG << "Matcher " << closure.matcher << closure.matcher->get_name()
<< " matched " << node->get_name();
if (closure.callback(*closure.matcher.get()))
{
rewritten = true;
// If call back may change function's is_dynamic state, we need to
// update the cached value.
if (closure.property.is_set(PassProperty::CHANGE_DYNAMIC_STATE))
{
is_dyn_func = s_rerun_dynamic_check && f->is_dynamic();
}
break;
}
}
}
}
} while (rewritten && m_matchers.size() > 0 && tries--);
m_matchers.assign(original_matchers.begin(), original_matchers.end());
return (NUM_TRIES - tries) > 1; //this means a graph was transformed
}
static vector<regex> initialize_fusion_regexes()
{
const char* cnsf = getenv("NGRAPH_DISABLED_FUSIONS");
vector<regex> regexes;
if (cnsf)
{
const string nsf = cnsf;
const auto sregexes = split(nsf, ';');
transform(sregexes.begin(),
sregexes.end(),
back_inserter(regexes),
[](const string& c) -> regex { return regex(c); });
}
return regexes;
}
bool pass::GraphRewrite::is_enabled(const shared_ptr<pattern::Matcher>& m) const
{
//note, regexes are static to avoid re-initialization
static const auto regexes = initialize_fusion_regexes();
for (const auto& regex : regexes)
{
if (regex_match(m->get_name(), regex))
{
NGRAPH_DEBUG << "Disabling matcher " << m->get_name();
return false;
}
}
return true;
}
void pass::GraphRewrite::add_matcher(const shared_ptr<pattern::Matcher>& m,
const graph_rewrite_callback& callback,
const PassPropertyMask& property)
{
if (is_enabled(m))
{
m_matchers.push_back({m, callback, property});
// If any matcher call back may change dynamic state, we need to
// update the pass property.
if (property.is_set(PassProperty::CHANGE_DYNAMIC_STATE))
{
set_property(PassProperty::CHANGE_DYNAMIC_STATE, true);
}
}
}
void pass::GraphRewrite::add_matcher(const shared_ptr<pattern::Matcher>& m,
const graph_rewrite_callback& callback)
{
// TODO: before deprecate this function, by default expect the
// callback require static shape.
add_matcher(m, callback, {PassProperty::REQUIRE_STATIC_SHAPE});
}
void pass::RecurrentGraphRewrite::add_matcher(
const std::shared_ptr<pattern::RecurrentMatcher>& m,
const ngraph::recurrent_graph_rewrite_callback& callback,
const PassPropertyMask& property)
{
m_matchers.push_back({m, callback, property});
// If any matcher call back may change dynamic state, we need to
// update the pass property.
if (property.is_set(PassProperty::CHANGE_DYNAMIC_STATE))
{
set_property(PassProperty::CHANGE_DYNAMIC_STATE, true);
}
}
void pass::RecurrentGraphRewrite::add_matcher(
const std::shared_ptr<pattern::RecurrentMatcher>& m,
const ngraph::recurrent_graph_rewrite_callback& callback)
{
// TODO: before deprecate this function, by default expect the
// callback require static shape.
add_matcher(m, callback, {PassProperty::REQUIRE_STATIC_SHAPE});
}
bool pass::RecurrentGraphRewrite::run_on_function(shared_ptr<Function> f)
{
bool changed = false;
size_t i = 0;
// This check is very expensive and is only needed for experimental features, so we will hide
// it behind an environment variable for now. TODO: Find a less expensive way to handle this.
static bool s_rerun_dynamic_check =
(std::getenv("NGRAPH_GRAPH_REWRITE_RERUN_DYNAMIC_CHECK") != nullptr);
auto run_matchers = [&]() -> bool {
bool is_dyn_func = s_rerun_dynamic_check && f->is_dynamic();
for (auto node : f->get_ops())
{
for (auto& closure : m_matchers)
{
if (is_dyn_func && closure.property[PassProperty::REQUIRE_STATIC_SHAPE])
{
NGRAPH_DEBUG << "matcher callback requires static shape but the "
"function is dynamic, skipping this "
"optimization till the shapes are fully "
"materialized";
continue;
}
NGRAPH_DEBUG << "Running matcher " << closure.matcher << " on " << node->get_name();
if (closure.matcher->match(node))
{
NGRAPH_DEBUG << "Matcher " << closure.matcher << " matched "
<< node->get_name();
if (closure.callback(*closure.matcher.get()))
{
// If call back may change function's is_dynamic state, we need to
// update the cached value.
if (closure.property.is_set(PassProperty::CHANGE_DYNAMIC_STATE))
{
is_dyn_func = s_rerun_dynamic_check && f->is_dynamic();
}
return true;
}
}
}
}
return false;
};
do
{
changed = run_matchers();
i++;
} while (changed && i < m_num_iters);
return changed;
}
<|endoftext|> |
<commit_before>extern "C" {
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
/* Directive handlers */
static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue
static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
/* Directives */
static ngx_command_t ngx_http_lmdb_queue_commands[] = {
{ ngx_string("lmdb_queue"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2,
ngx_http_lmdb_queue,
NGX_HTTP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("lmdb_queue_topic"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE3,
ngx_http_lmdb_queue_topic,
NGX_HTTP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("lmdb_queue_push"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2,
ngx_http_lmdb_queue_push,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_lmdb_queue_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
NULL, /* create location configuration */
NULL /* merge location configuration */
};
ngx_module_t ngx_http_lmdb_queue_module = {
NGX_MODULE_V1,
&ngx_http_lmdb_queue_module_ctx, /* module context */
ngx_http_lmdb_queue_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
return NGX_CONF_OK;
}
static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
return NGX_CONF_OK;
}
static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
return NGX_CONF_OK;
}
}<commit_msg>fix config pos<commit_after>extern "C" {
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
/* Directive handlers */
static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue
static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf); // Declare lmdb_queue topic
/* Directives */
static ngx_command_t ngx_http_lmdb_queue_commands[] = {
{ ngx_string("lmdb_queue"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE2,
ngx_http_lmdb_queue,
NGX_HTTP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("lmdb_queue_topic"),
NGX_HTTP_MAIN_CONF | NGX_CONF_TAKE3,
ngx_http_lmdb_queue_topic,
NGX_HTTP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("lmdb_queue_push"),
NGX_HTTP_SRV_CONF | NGX_HTTP_LOC_CONF | NGX_CONF_TAKE2,
ngx_http_lmdb_queue_push,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_lmdb_queue_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
NULL, /* create location configuration */
NULL /* merge location configuration */
};
ngx_module_t ngx_http_lmdb_queue_module = {
NGX_MODULE_V1,
&ngx_http_lmdb_queue_module_ctx, /* module context */
ngx_http_lmdb_queue_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static char *ngx_http_lmdb_queue(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
return NGX_CONF_OK;
}
static char *ngx_http_lmdb_queue_topic(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
return NGX_CONF_OK;
}
static char *ngx_http_lmdb_queue_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf) {
return NGX_CONF_OK;
}
}<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ImpressModule.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2007-04-03 15:52:53 $
*
* 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
*
************************************************************************/
#include "precompiled_sd.hxx"
#include "framework/ImpressModule.hxx"
#include "framework/FrameworkHelper.hxx"
#include "ViewTabBarModule.hxx"
#include "CenterViewFocusModule.hxx"
#include "SlideSorterModule.hxx"
#include "TaskPaneModule.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace sd { namespace framework {
void ImpressModule::Initialize (Reference<frame::XController>& rxController)
{
new CenterViewFocusModule(rxController);
new ViewTabBarModule(
rxController,
FrameworkHelper::CreateResourceId(
FrameworkHelper::msViewTabBarURL,
FrameworkHelper::msCenterPaneURL));
new SlideSorterModule(
rxController,
FrameworkHelper::msLeftImpressPaneURL);
TaskPaneModule::Initialize(rxController);
}
} } // end of namespace sd::framework
<commit_msg>INTEGRATION: CWS impress124 (1.2.84); FILE MERGED 2007/07/19 15:41:32 af 1.2.84.1: #i77179# Added ShellStackGuard.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ImpressModule.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: vg $ $Date: 2008-01-29 08:19:48 $
*
* 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
*
************************************************************************/
#include "precompiled_sd.hxx"
#include "framework/ImpressModule.hxx"
#include "framework/FrameworkHelper.hxx"
#include "ViewTabBarModule.hxx"
#include "CenterViewFocusModule.hxx"
#include "SlideSorterModule.hxx"
#include "TaskPaneModule.hxx"
#include "ShellStackGuard.hxx"
using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
namespace sd { namespace framework {
void ImpressModule::Initialize (Reference<frame::XController>& rxController)
{
new CenterViewFocusModule(rxController);
new ViewTabBarModule(
rxController,
FrameworkHelper::CreateResourceId(
FrameworkHelper::msViewTabBarURL,
FrameworkHelper::msCenterPaneURL));
new SlideSorterModule(
rxController,
FrameworkHelper::msLeftImpressPaneURL);
TaskPaneModule::Initialize(rxController);
new ShellStackGuard(rxController);
}
} } // end of namespace sd::framework
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 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 "propertyeditorvalue.h"
#include <abstractview.h>
#include <nodeabstractproperty.h>
#include <nodeproperty.h>
#include <model.h>
#include <nodemetainfo.h>
#include <metainfo.h>
#include <propertymetainfo.h>
#include <nodeproperty.h>
#include <qmlobjectnode.h>
//using namespace QmlDesigner;
PropertyEditorValue::PropertyEditorValue(QObject *parent)
: QObject(parent),
m_isInSubState(false),
m_isInModel(false),
m_isBound(false),
m_isValid(false),
m_complexNode(new PropertyEditorNodeWrapper(this))
{
}
QVariant PropertyEditorValue::value() const
{
QVariant returnValue = m_value;
if (modelNode().isValid() && modelNode().metaInfo().isValid() && modelNode().metaInfo().property(name()).isValid())
if (modelNode().metaInfo().property(name()).type() == QLatin1String("QUrl")) {
returnValue = returnValue.toUrl().toString();
}
return returnValue;
}
static bool cleverDoubleCompare(QVariant value1, QVariant value2)
{ //we ignore slight changes on doubles
if ((value1.type() == QVariant::Double) && (value2.type() == QVariant::Double)) {
int a = value1.toDouble() * 100;
int b = value2.toDouble() * 100;
if (qFuzzyCompare((qreal(a) / 100), (qreal(b) / 100))) {
return true;
}
}
return false;
}
void PropertyEditorValue::setValueWithEmit(const QVariant &value)
{
if ( m_value != value) {
QVariant newValue = value;
if (modelNode().isValid() && modelNode().metaInfo().isValid() && modelNode().metaInfo().property(name()).isValid())
if (modelNode().metaInfo().property(name()).type() == QLatin1String("QUrl")) {
newValue = QUrl(newValue.toString());
}
if (cleverDoubleCompare(newValue, m_value))
return;
setValue(newValue);
m_isBound = false;
emit valueChanged(name(), value);
emit isBoundChanged();
}
}
void PropertyEditorValue::setValue(const QVariant &value)
{
if ( m_value != value) {
m_value = value;
emit valueChanged(QString(), value);
}
emit isBoundChanged();
}
QString PropertyEditorValue::expression() const
{
return m_expression;
}
void PropertyEditorValue::setExpressionWithEmit(const QString &expression)
{
if ( m_expression != expression) {
setExpression(expression);
emit expressionChanged(name());
}
}
void PropertyEditorValue::setExpression(const QString &expression)
{
if ( m_expression != expression) {
m_expression = expression;
emit expressionChanged(QString());
}
}
bool PropertyEditorValue::isInSubState() const
{
const QmlDesigner::QmlObjectNode objectNode(modelNode());
return objectNode.isValid() && objectNode.propertyAffectedByCurrentState(name());
}
bool PropertyEditorValue::isBound() const
{
return modelNode().isValid() && modelNode().property(name()).isValid() && modelNode().property(name()).isBindingProperty();
}
bool PropertyEditorValue::isInModel() const
{
return modelNode().isValid() && modelNode().hasProperty(name());
}
QString PropertyEditorValue::name() const
{
return m_name;
}
void PropertyEditorValue::setName(const QString &name)
{
m_name = name;
}
bool PropertyEditorValue::isValid() const
{
return m_isValid;
}
void PropertyEditorValue::setIsValid(bool valid)
{
m_isValid = valid;
}
ModelNode PropertyEditorValue::modelNode() const
{
return m_modelNode;
}
void PropertyEditorValue::setModelNode(const ModelNode &modelNode)
{
if (modelNode != m_modelNode) {
m_modelNode = modelNode;
m_complexNode->update();
emit modelNodeChanged();
}
}
PropertyEditorNodeWrapper* PropertyEditorValue::complexNode()
{
return m_complexNode;
}
void PropertyEditorValue::resetValue()
{
if (m_value.isValid()) {
setValue(QVariant());
m_isBound = false;
emit valueChanged(name(), QVariant());
}
}
void PropertyEditorValue::registerDeclarativeTypes()
{
qmlRegisterType<PropertyEditorValue>("Bauhaus",1,0,"PropertyEditorValue");
qmlRegisterType<PropertyEditorNodeWrapper>("Bauhaus",1,0,"PropertyEditorNodeWrapper");
qmlRegisterType<QDeclarativePropertyMap>("Bauhaus",1,0,"QDeclarativePropertyMap");
}
PropertyEditorNodeWrapper::PropertyEditorNodeWrapper(PropertyEditorValue* parent) : m_valuesPropertyMap(this)
{
m_editorValue = parent;
connect(m_editorValue, SIGNAL(modelNodeChanged()), this, SLOT(update()));
}
PropertyEditorNodeWrapper::PropertyEditorNodeWrapper(QObject *parent) : QObject(parent)
{
}
bool PropertyEditorNodeWrapper::exists()
{
if (!(m_editorValue && m_editorValue->modelNode().isValid()))
return false;
return m_modelNode.isValid();
}
QString PropertyEditorNodeWrapper::type()
{
if (!(m_modelNode.isValid()))
return QString("");
return m_modelNode.simplifiedTypeName();
}
ModelNode PropertyEditorNodeWrapper::parentModelNode() const
{
return m_editorValue->modelNode();
}
QString PropertyEditorNodeWrapper::propertyName() const
{
return m_editorValue->name();
}
QDeclarativePropertyMap* PropertyEditorNodeWrapper::properties()
{
return &m_valuesPropertyMap;
}
void PropertyEditorNodeWrapper::add(const QString &type)
{
QString propertyType = type;
if ((m_editorValue && m_editorValue->modelNode().isValid())) {
if (propertyType.isEmpty())
propertyType = m_editorValue->modelNode().metaInfo().property(m_editorValue->name()).type();
while (propertyType.contains('*')) //strip star
propertyType.chop(1);
m_modelNode = m_editorValue->modelNode().view()->createModelNode(propertyType, 4, 6);
m_editorValue->modelNode().nodeAbstractProperty(m_editorValue->name()).reparentHere(m_modelNode);
if (!m_modelNode.isValid()) {
qWarning("PropertyEditorNodeWrapper::add failed");
}
} else {
qWarning("PropertyEditorNodeWrapper::add failed - node invalid");
}
setup();
}
void PropertyEditorNodeWrapper::remove()
{
if ((m_editorValue && m_editorValue->modelNode().isValid())) {
if (QmlDesigner::QmlObjectNode(m_modelNode).isValid())
QmlDesigner::QmlObjectNode(m_modelNode).destroy();
m_editorValue->modelNode().removeProperty(m_editorValue->name());
} else {
qWarning("PropertyEditorNodeWrapper::remove failed - node invalid");
}
m_modelNode = QmlDesigner::ModelNode();
foreach (const QString &propertyName, m_valuesPropertyMap.keys())
m_valuesPropertyMap.clear(propertyName);
foreach (QObject *object, m_valuesPropertyMap.children())
delete object;
emit propertiesChanged();
emit existsChanged();
}
void PropertyEditorNodeWrapper::changeValue(const QString &name)
{
if (name.isNull())
return;
if (m_modelNode.isValid()) {
QmlDesigner::QmlObjectNode fxObjectNode(m_modelNode);
PropertyEditorValue *valueObject = qvariant_cast<PropertyEditorValue *>(m_valuesPropertyMap.value(name));
if (valueObject->value().isValid())
fxObjectNode.setVariantProperty(name, valueObject->value());
else
fxObjectNode.removeVariantProperty(name);
}
}
void PropertyEditorNodeWrapper::setup()
{
Q_ASSERT(m_editorValue);
Q_ASSERT(m_editorValue->modelNode().isValid());
if ((m_editorValue->modelNode().isValid() && m_modelNode.isValid())) {
QmlDesigner::QmlObjectNode fxObjectNode(m_modelNode);
foreach ( const QString &propertyName, m_valuesPropertyMap.keys())
m_valuesPropertyMap.clear(propertyName);
foreach (QObject *object, m_valuesPropertyMap.children())
delete object;
foreach (const QString &propertyName, m_modelNode.metaInfo().properties().keys()) {
PropertyEditorValue *valueObject = new PropertyEditorValue(&m_valuesPropertyMap);
valueObject->setName(propertyName);
valueObject->setValue(fxObjectNode.instanceValue(propertyName));
connect(valueObject, SIGNAL(valueChanged(QString, const QVariant&)), &m_valuesPropertyMap, SIGNAL(valueChanged(QString, const QVariant&)));
m_valuesPropertyMap.insert(propertyName, QVariant::fromValue(valueObject));
}
}
connect(&m_valuesPropertyMap, SIGNAL(valueChanged(const QString &, const QVariant&)), this, SLOT(changeValue(const QString&)));
emit propertiesChanged();
emit existsChanged();
}
void PropertyEditorNodeWrapper::update()
{
if (m_editorValue && m_editorValue->modelNode().isValid()) {
if (m_editorValue->modelNode().hasProperty(m_editorValue->name()) && m_editorValue->modelNode().property(m_editorValue->name()).isNodeProperty()) {
m_modelNode = m_editorValue->modelNode().nodeProperty(m_editorValue->name()).modelNode();
}
setup();
emit existsChanged();
emit typeChanged();
}
}
<commit_msg>QmlDesigner.propertyEditor emit in all cases to fix color coding<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 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 "propertyeditorvalue.h"
#include <abstractview.h>
#include <nodeabstractproperty.h>
#include <nodeproperty.h>
#include <model.h>
#include <nodemetainfo.h>
#include <metainfo.h>
#include <propertymetainfo.h>
#include <nodeproperty.h>
#include <qmlobjectnode.h>
//using namespace QmlDesigner;
PropertyEditorValue::PropertyEditorValue(QObject *parent)
: QObject(parent),
m_isInSubState(false),
m_isInModel(false),
m_isBound(false),
m_isValid(false),
m_complexNode(new PropertyEditorNodeWrapper(this))
{
}
QVariant PropertyEditorValue::value() const
{
QVariant returnValue = m_value;
if (modelNode().isValid() && modelNode().metaInfo().isValid() && modelNode().metaInfo().property(name()).isValid())
if (modelNode().metaInfo().property(name()).type() == QLatin1String("QUrl")) {
returnValue = returnValue.toUrl().toString();
}
return returnValue;
}
static bool cleverDoubleCompare(QVariant value1, QVariant value2)
{ //we ignore slight changes on doubles
if ((value1.type() == QVariant::Double) && (value2.type() == QVariant::Double)) {
int a = value1.toDouble() * 100;
int b = value2.toDouble() * 100;
if (qFuzzyCompare((qreal(a) / 100), (qreal(b) / 100))) {
return true;
}
}
return false;
}
void PropertyEditorValue::setValueWithEmit(const QVariant &value)
{
if ( m_value != value) {
QVariant newValue = value;
if (modelNode().isValid() && modelNode().metaInfo().isValid() && modelNode().metaInfo().property(name()).isValid())
if (modelNode().metaInfo().property(name()).type() == QLatin1String("QUrl")) {
newValue = QUrl(newValue.toString());
}
if (cleverDoubleCompare(newValue, m_value))
return;
setValue(newValue);
m_isBound = false;
emit valueChanged(name(), value);
emit isBoundChanged();
}
}
void PropertyEditorValue::setValue(const QVariant &value)
{
if ( m_value != value) {
m_value = value;
}
emit valueChanged(QString(), value);
emit isBoundChanged();
}
QString PropertyEditorValue::expression() const
{
return m_expression;
}
void PropertyEditorValue::setExpressionWithEmit(const QString &expression)
{
if ( m_expression != expression) {
setExpression(expression);
emit expressionChanged(name());
}
}
void PropertyEditorValue::setExpression(const QString &expression)
{
if ( m_expression != expression) {
m_expression = expression;
emit expressionChanged(QString());
}
}
bool PropertyEditorValue::isInSubState() const
{
const QmlDesigner::QmlObjectNode objectNode(modelNode());
return objectNode.isValid() && objectNode.propertyAffectedByCurrentState(name());
}
bool PropertyEditorValue::isBound() const
{
return modelNode().isValid() && modelNode().property(name()).isValid() && modelNode().property(name()).isBindingProperty();
}
bool PropertyEditorValue::isInModel() const
{
qDebug() << name();
qDebug() << (modelNode().isValid() && modelNode().hasProperty(name()));
return modelNode().isValid() && modelNode().hasProperty(name());
}
QString PropertyEditorValue::name() const
{
return m_name;
}
void PropertyEditorValue::setName(const QString &name)
{
m_name = name;
}
bool PropertyEditorValue::isValid() const
{
return m_isValid;
}
void PropertyEditorValue::setIsValid(bool valid)
{
m_isValid = valid;
}
ModelNode PropertyEditorValue::modelNode() const
{
return m_modelNode;
}
void PropertyEditorValue::setModelNode(const ModelNode &modelNode)
{
if (modelNode != m_modelNode) {
m_modelNode = modelNode;
m_complexNode->update();
emit modelNodeChanged();
}
}
PropertyEditorNodeWrapper* PropertyEditorValue::complexNode()
{
return m_complexNode;
}
void PropertyEditorValue::resetValue()
{
if (m_value.isValid()) {
setValue(QVariant());
m_isBound = false;
emit valueChanged(name(), QVariant());
}
}
void PropertyEditorValue::registerDeclarativeTypes()
{
qmlRegisterType<PropertyEditorValue>("Bauhaus",1,0,"PropertyEditorValue");
qmlRegisterType<PropertyEditorNodeWrapper>("Bauhaus",1,0,"PropertyEditorNodeWrapper");
qmlRegisterType<QDeclarativePropertyMap>("Bauhaus",1,0,"QDeclarativePropertyMap");
}
PropertyEditorNodeWrapper::PropertyEditorNodeWrapper(PropertyEditorValue* parent) : m_valuesPropertyMap(this)
{
m_editorValue = parent;
connect(m_editorValue, SIGNAL(modelNodeChanged()), this, SLOT(update()));
}
PropertyEditorNodeWrapper::PropertyEditorNodeWrapper(QObject *parent) : QObject(parent)
{
}
bool PropertyEditorNodeWrapper::exists()
{
if (!(m_editorValue && m_editorValue->modelNode().isValid()))
return false;
return m_modelNode.isValid();
}
QString PropertyEditorNodeWrapper::type()
{
if (!(m_modelNode.isValid()))
return QString("");
return m_modelNode.simplifiedTypeName();
}
ModelNode PropertyEditorNodeWrapper::parentModelNode() const
{
return m_editorValue->modelNode();
}
QString PropertyEditorNodeWrapper::propertyName() const
{
return m_editorValue->name();
}
QDeclarativePropertyMap* PropertyEditorNodeWrapper::properties()
{
return &m_valuesPropertyMap;
}
void PropertyEditorNodeWrapper::add(const QString &type)
{
QString propertyType = type;
if ((m_editorValue && m_editorValue->modelNode().isValid())) {
if (propertyType.isEmpty())
propertyType = m_editorValue->modelNode().metaInfo().property(m_editorValue->name()).type();
while (propertyType.contains('*')) //strip star
propertyType.chop(1);
m_modelNode = m_editorValue->modelNode().view()->createModelNode(propertyType, 4, 6);
m_editorValue->modelNode().nodeAbstractProperty(m_editorValue->name()).reparentHere(m_modelNode);
if (!m_modelNode.isValid()) {
qWarning("PropertyEditorNodeWrapper::add failed");
}
} else {
qWarning("PropertyEditorNodeWrapper::add failed - node invalid");
}
setup();
}
void PropertyEditorNodeWrapper::remove()
{
if ((m_editorValue && m_editorValue->modelNode().isValid())) {
if (QmlDesigner::QmlObjectNode(m_modelNode).isValid())
QmlDesigner::QmlObjectNode(m_modelNode).destroy();
m_editorValue->modelNode().removeProperty(m_editorValue->name());
} else {
qWarning("PropertyEditorNodeWrapper::remove failed - node invalid");
}
m_modelNode = QmlDesigner::ModelNode();
foreach (const QString &propertyName, m_valuesPropertyMap.keys())
m_valuesPropertyMap.clear(propertyName);
foreach (QObject *object, m_valuesPropertyMap.children())
delete object;
emit propertiesChanged();
emit existsChanged();
}
void PropertyEditorNodeWrapper::changeValue(const QString &name)
{
if (name.isNull())
return;
if (m_modelNode.isValid()) {
QmlDesigner::QmlObjectNode fxObjectNode(m_modelNode);
PropertyEditorValue *valueObject = qvariant_cast<PropertyEditorValue *>(m_valuesPropertyMap.value(name));
if (valueObject->value().isValid())
fxObjectNode.setVariantProperty(name, valueObject->value());
else
fxObjectNode.removeVariantProperty(name);
}
}
void PropertyEditorNodeWrapper::setup()
{
Q_ASSERT(m_editorValue);
Q_ASSERT(m_editorValue->modelNode().isValid());
if ((m_editorValue->modelNode().isValid() && m_modelNode.isValid())) {
QmlDesigner::QmlObjectNode fxObjectNode(m_modelNode);
foreach ( const QString &propertyName, m_valuesPropertyMap.keys())
m_valuesPropertyMap.clear(propertyName);
foreach (QObject *object, m_valuesPropertyMap.children())
delete object;
foreach (const QString &propertyName, m_modelNode.metaInfo().properties().keys()) {
PropertyEditorValue *valueObject = new PropertyEditorValue(&m_valuesPropertyMap);
valueObject->setName(propertyName);
valueObject->setValue(fxObjectNode.instanceValue(propertyName));
connect(valueObject, SIGNAL(valueChanged(QString, const QVariant&)), &m_valuesPropertyMap, SIGNAL(valueChanged(QString, const QVariant&)));
m_valuesPropertyMap.insert(propertyName, QVariant::fromValue(valueObject));
}
}
connect(&m_valuesPropertyMap, SIGNAL(valueChanged(const QString &, const QVariant&)), this, SLOT(changeValue(const QString&)));
emit propertiesChanged();
emit existsChanged();
}
void PropertyEditorNodeWrapper::update()
{
if (m_editorValue && m_editorValue->modelNode().isValid()) {
if (m_editorValue->modelNode().hasProperty(m_editorValue->name()) && m_editorValue->modelNode().property(m_editorValue->name()).isNodeProperty()) {
m_modelNode = m_editorValue->modelNode().nodeProperty(m_editorValue->name()).modelNode();
}
setup();
emit existsChanged();
emit typeChanged();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sprite.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2005-11-02 13:03:59 $
*
* 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 INCLUDED_VCLCANVAS_SPRITE_HXX
#define INCLUDED_VCLCANVAS_SPRITE_HXX
#include <canvas/base/sprite.hxx>
class OutputDevice;
namespace vclcanvas
{
/** Specialization of ::canvas::Sprite interface, to also provide
redraw methods.
*/
class Sprite : public ::canvas::Sprite
{
public:
/** Redraw sprite at the stored position.
@param bBufferedUpdate
When true, the redraw does <em>not</em> happen directly on
the front buffer, but within a VDev. Used to speed up
drawing.
*/
virtual void redraw( OutputDevice& rOutDev,
bool bBufferedUpdate ) const = 0;
/** Redraw sprite at the given position.
@param rPos
Output position of the sprite. Overrides the sprite's own
output position.
@param bBufferedUpdate
When true, the redraw does <em>not</em> happen directly on
the front buffer, but within a VDev. Used to speed up
drawing.
*/
virtual void redraw( OutputDevice& rOutDev,
const ::basegfx::B2DPoint& rPos,
bool bBufferedUpdate ) const = 0;
};
}
#endif /* INCLUDED_VCLCANVAS_SPRITE_HXX */
<commit_msg>INTEGRATION: CWS changefileheader (1.7.136); FILE MERGED 2008/03/28 16:35:17 rt 1.7.136.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: sprite.hxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef INCLUDED_VCLCANVAS_SPRITE_HXX
#define INCLUDED_VCLCANVAS_SPRITE_HXX
#include <canvas/base/sprite.hxx>
class OutputDevice;
namespace vclcanvas
{
/** Specialization of ::canvas::Sprite interface, to also provide
redraw methods.
*/
class Sprite : public ::canvas::Sprite
{
public:
/** Redraw sprite at the stored position.
@param bBufferedUpdate
When true, the redraw does <em>not</em> happen directly on
the front buffer, but within a VDev. Used to speed up
drawing.
*/
virtual void redraw( OutputDevice& rOutDev,
bool bBufferedUpdate ) const = 0;
/** Redraw sprite at the given position.
@param rPos
Output position of the sprite. Overrides the sprite's own
output position.
@param bBufferedUpdate
When true, the redraw does <em>not</em> happen directly on
the front buffer, but within a VDev. Used to speed up
drawing.
*/
virtual void redraw( OutputDevice& rOutDev,
const ::basegfx::B2DPoint& rPos,
bool bBufferedUpdate ) const = 0;
};
}
#endif /* INCLUDED_VCLCANVAS_SPRITE_HXX */
<|endoftext|> |
<commit_before>/* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2017, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NUPIC_UTIL_SLIDING_WINDOW_HPP
#define NUPIC_UTIL_SLIDING_WINDOW_HPP
#include <vector>
#include <algorithm>
#include <nupic/types/Types.hpp>
#include <nupic/utils/Log.hpp>
namespace nupic {
namespace util {
template<class T>
class SlidingWindow {
public:
SlidingWindow(UInt maxCapacity);
SlidingWindow(UInt maxCapacity, std::vector<T> initialData);
const UInt maxCapacity;
size_t size() const;
/** append new value to the end of the buffer and handle the
"overflows"-may pop the first element if full.
*/
void append(T newValue);
/** like append, but return the dropped value. isValid indicates
if the return value is valid (not while size()< maxCapacity)
:param T newValue - new value to append to the sliding window
:param bool isValid - a return pass-by-value that indicates validity
of the return T value. for first maxCapacity items it is false,
later always true.
:return T dropped value (past oldest element) if isValid;
if not valid, this field holds the oldest value
(but still contained in the window!)
*/
T append(T newValue, bool& isValid);
/**
* :return unordered content (data ) of this sl. window;
call getLinearizedData() if you need them oredered from
oldest->newest
* This direct access method is fast.
*/
const std::vector<T>& getData() const;
/** linearize method for the internal buffer; this is slower than
the pure getData() but ensures that the data are ordered (oldest at
the beginning, newest at the end of the vector
* This handles case of |5,6;1,2,3,4| => |1,2,3,4,5,6|
* :return new linearized vector
*/
std::vector<T> getLinearizedData() const;
bool operator==(const SlidingWindow& r2) const;
bool operator!=(const SlidingWindow& r2) const;
T& operator[](UInt index);
const T& operator[](UInt index) const;
private:
std::vector<T> buffer_;
UInt idxNext_;
};
}} //end ns
/// IMPLEMENTATION
#include <cmath>
using nupic::util::SlidingWindow;
template<class T>
SlidingWindow<T>::SlidingWindow(nupic::UInt maxCapacity) :
maxCapacity(maxCapacity) {
NTA_CHECK(maxCapacity > 0);
buffer_.reserve(maxCapacity);
idxNext_ = 0;
}
template<class T>
SlidingWindow<T>::SlidingWindow(nupic::UInt maxCapacity, std::vector<T> initialData) :
SlidingWindow(maxCapacity) {
auto sz = std::min(initialData.size(), (size_t)maxCapacity);
buffer_.insert(std::begin(buffer_), std::end(initialData) - sz, std::end(initialData));
idxNext_ = sz % maxCapacity;
}
template<class T>
size_t SlidingWindow<T>::size() const {
NTA_ASSERT(buffer_.size() <= maxCapacity);
return buffer_.size();
}
template<class T>
void SlidingWindow<T>::append(T newValue) {
if(size() < maxCapacity) {
buffer_.emplace_back(newValue);
} else {
buffer_[idxNext_] = newValue;
}
//the assignment must be out of the [] above, so not [idxNext_++%maxCap],
// because we want to store the value %maxCap, not only ++
idxNext_ = ++idxNext_ %maxCapacity;
}
template<class T>
T SlidingWindow<T>::append(T newValue, bool& isValid) {
//handle case of empty buffer (access buff[0]), otherwise return oldest elem
T old = buffer_.empty() ? newValue : buffer_[idxNext_];
//only in this case we drop oldest; this happens always after
//first maxCap steps ; must be checked before append()
isValid = (buffer_.size()==maxCapacity);
append(newValue);
return old;
}
template<class T>
const std::vector<T>& SlidingWindow<T>::getData() const {
return buffer_; //may contain trailing "zeros"
}
template<class T>
std::vector<T> SlidingWindow<T>::getLinearizedData() const {
std::vector<T> lin;
lin.reserve(buffer_.size());
//insert the "older" part at the beginning
lin.insert(std::begin(lin), std::begin(buffer_) + idxNext_, std::end(buffer_));
//append the "newer" part to the end of the constructed vect
lin.insert(std::end(lin), std::begin(buffer_), std::begin(buffer_) + idxNext_);
return lin;
}
template<class T>
bool SlidingWindow<T>::operator==(const SlidingWindow& r2) const {
return ((this->size() == r2.size()) && (this->maxCapacity == r2.maxCapacity) &&
(this->getData()== r2.getData()) );
//FIXME review the ==, on my machine it randomly passes/fails the test!
}
template<class T>
bool SlidingWindow<T>::operator!=(const SlidingWindow& r2) const {
return !operator==(r2);
}
template<class T>
T& SlidingWindow<T>::operator[](nupic::UInt index) {
NTA_ASSERT(index <= size());
return &buffer_[index];
}
template<class T>
const T& SlidingWindow<T>::operator[](nupic::UInt index) const {
return this->operator[](index); //call the overloaded operator[] above
}
#endif //header
<commit_msg>SlidingWindow: fix operator[]<commit_after>/* Numenta Platform for Intelligent Computing (NuPIC)
* Copyright (C) 2017, Numenta, Inc. Unless you have an agreement
* with Numenta, Inc., for a separate license for this software code, the
* following terms and conditions apply:
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero Public License for more details.
*
* You should have received a copy of the GNU Affero Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*
* http://numenta.org/licenses/
* ---------------------------------------------------------------------
*/
#ifndef NUPIC_UTIL_SLIDING_WINDOW_HPP
#define NUPIC_UTIL_SLIDING_WINDOW_HPP
#include <vector>
#include <algorithm>
#include <nupic/types/Types.hpp>
#include <nupic/utils/Log.hpp>
namespace nupic {
namespace util {
template<class T>
class SlidingWindow {
public:
SlidingWindow(UInt maxCapacity);
SlidingWindow(UInt maxCapacity, std::vector<T> initialData);
const UInt maxCapacity;
size_t size() const;
/** append new value to the end of the buffer and handle the
"overflows"-may pop the first element if full.
*/
void append(T newValue);
/** like append, but return the dropped value. isValid indicates
if the return value is valid (not while size()< maxCapacity)
:param T newValue - new value to append to the sliding window
:param bool isValid - a return pass-by-value that indicates validity
of the return T value. for first maxCapacity items it is false,
later always true.
:return T dropped value (past oldest element) if isValid;
if not valid, this field holds the oldest value
(but still contained in the window!)
*/
T append(T newValue, bool& isValid);
/**
* :return unordered content (data ) of this sl. window;
call getLinearizedData() if you need them oredered from
oldest->newest
* This direct access method is fast.
*/
const std::vector<T>& getData() const;
/** linearize method for the internal buffer; this is slower than
the pure getData() but ensures that the data are ordered (oldest at
the beginning, newest at the end of the vector
* This handles case of |5,6;1,2,3,4| => |1,2,3,4,5,6|
* :return new linearized vector
*/
std::vector<T> getLinearizedData() const;
bool operator==(const SlidingWindow& r2) const;
bool operator!=(const SlidingWindow& r2) const;
T& operator[](UInt index);
const T& operator[](UInt index) const;
private:
std::vector<T> buffer_;
UInt idxNext_;
};
}} //end ns
/// IMPLEMENTATION
#include <cmath>
using nupic::util::SlidingWindow;
template<class T>
SlidingWindow<T>::SlidingWindow(nupic::UInt maxCapacity) :
maxCapacity(maxCapacity) {
NTA_CHECK(maxCapacity > 0);
buffer_.reserve(maxCapacity);
idxNext_ = 0;
}
template<class T>
SlidingWindow<T>::SlidingWindow(nupic::UInt maxCapacity, std::vector<T> initialData) :
SlidingWindow(maxCapacity) {
auto sz = std::min(initialData.size(), (size_t)maxCapacity);
buffer_.insert(std::begin(buffer_), std::end(initialData) - sz, std::end(initialData));
idxNext_ = sz % maxCapacity;
}
template<class T>
size_t SlidingWindow<T>::size() const {
NTA_ASSERT(buffer_.size() <= maxCapacity);
return buffer_.size();
}
template<class T>
void SlidingWindow<T>::append(T newValue) {
if(size() < maxCapacity) {
buffer_.emplace_back(newValue);
} else {
buffer_[idxNext_] = newValue;
}
//the assignment must be out of the [] above, so not [idxNext_++%maxCap],
// because we want to store the value %maxCap, not only ++
idxNext_ = ++idxNext_ %maxCapacity;
}
template<class T>
T SlidingWindow<T>::append(T newValue, bool& isValid) {
//handle case of empty buffer (access buff[0]), otherwise return oldest elem
T old = buffer_.empty() ? newValue : buffer_[idxNext_];
//only in this case we drop oldest; this happens always after
//first maxCap steps ; must be checked before append()
isValid = (buffer_.size()==maxCapacity);
append(newValue);
return old;
}
template<class T>
const std::vector<T>& SlidingWindow<T>::getData() const {
return buffer_; //may contain trailing "zeros"
}
template<class T>
std::vector<T> SlidingWindow<T>::getLinearizedData() const {
std::vector<T> lin;
lin.reserve(buffer_.size());
//insert the "older" part at the beginning
lin.insert(std::begin(lin), std::begin(buffer_) + idxNext_, std::end(buffer_));
//append the "newer" part to the end of the constructed vect
lin.insert(std::end(lin), std::begin(buffer_), std::begin(buffer_) + idxNext_);
return lin;
}
template<class T>
bool SlidingWindow<T>::operator==(const SlidingWindow& r2) const {
return ((this->size() == r2.size()) && (this->maxCapacity == r2.maxCapacity) &&
(this->getData()== r2.getData()) );
//FIXME review the ==, on my machine it randomly passes/fails the test!
}
template<class T>
bool SlidingWindow<T>::operator!=(const SlidingWindow& r2) const {
return !operator==(r2);
}
template<class T>
T& SlidingWindow<T>::operator[](nupic::UInt index) {
NTA_ASSERT(index <= size());
//get last updated position, "current"+index(offset)
//avoid calling getLinearizeData() as it involves copy()
nupic::UInt currentIdx = (idxNext_ -1 + maxCapacity + index) % maxCapacity;
return &buffer_[currentIdx];
}
template<class T>
const T& SlidingWindow<T>::operator[](nupic::UInt index) const {
return this->operator[](index); //call the overloaded operator[] above
}
#endif //header
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativevaluespacesubscriber_p.h"
class QDeclarativeValueSpaceSubscriberPrivate
{
public:
QDeclarativeValueSpaceSubscriberPrivate();
~QDeclarativeValueSpaceSubscriberPrivate();
QValueSpaceSubscriber *subscriber;
};
QDeclarativeValueSpaceSubscriberPrivate::QDeclarativeValueSpaceSubscriberPrivate() :
subscriber(0)
{
}
QDeclarativeValueSpaceSubscriberPrivate::~QDeclarativeValueSpaceSubscriberPrivate()
{
if (subscriber)
delete subscriber;
}
/*!
\qmlclass ValueSpaceSubscriber QDeclarativeValueSpaceSubscriber
\brief The QValueSpaceSubscriber class allows applications to read and
subscribe to Value Space paths.
\ingroup qml-publishsubscribe
The ValueSpaceSubscriber element is part of the \bold {QtMobility.publishsubscribe 1.1} module.
Each \l ValueSpaceSubscriber element represents a single value or path in the Value Space. The
path is set using the \i path property.
\code
ValueSpaceSubscriber {
id: nowPlaying
path: "/applications/mediaplayer/now-playing"
}
\endcode
The value is accessed using the \i value property.
\code
Text {
text: nowPlaying.value
}
\endcode
*/
QDeclarativeValueSpaceSubscriber::QDeclarativeValueSpaceSubscriber() :
d(new QDeclarativeValueSpaceSubscriberPrivate)
{
}
QDeclarativeValueSpaceSubscriber::~QDeclarativeValueSpaceSubscriber()
{
delete d;
}
/*!
\qmlproperty string ValueSpaceSubscriber::path
This property holds the base path of the subscriber, and is read/write.
*/
void QDeclarativeValueSpaceSubscriber::setPath(QString path)
{
if (subscriber) {
if (d->subscriber->path() == path)
return;
d->subscriber->setPath(path);
emit pathChanged();
} else {
d->subscriber = new QValueSpaceSubscriber(path);
emit pathChanged();
}
// re-connect the signal
connect(subscriber, SIGNAL(contentsChanged()),
this, SIGNAL(contentsChanged()));
}
QString QDeclarativeValueSpaceSubscriber::path() const
{
if (!d->subscriber)
return QString();
return d->subscriber->path();
}
/*!
\qmlproperty QVariant ValueSpaceSubscriber::value
This property holds the value of the key at the set path in the Value Space.
Read-only.
*/
QVariant QDeclarativeValueSpaceSubscriber::value(const QString &subPath, const QVariant &def) const
{
if (!d->subscriber)
return QVariant();
return d->subscriber->value(subPath, def);
}
/*!
\qmlproperty QStringList ValueSpaceSubscriber::subPaths
This property holds a list of known sub-paths of the currently set path.
*/
QStringList QDeclarativeValueSpaceSubscriber::subPaths() const
{
if (!d->subscriber)
return QStringList();
return d->subscriber->subPaths();
}
/*!
\qmlproperty bool ValueSpaceSubscriber::connected
This property holds whether the subscriber is currently connected to the
backing store of the Value Space.
*/
bool QDeclarativeValueSpaceSubscriber::isConnected() const
{
if (!d->subscriber)
return false;
return d->subscriber->isConnected();
}
<commit_msg>Fixing up new declarative plugin so it actually builds<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdeclarativevaluespacesubscriber_p.h"
class QDeclarativeValueSpaceSubscriberPrivate
{
public:
QDeclarativeValueSpaceSubscriberPrivate();
~QDeclarativeValueSpaceSubscriberPrivate();
QValueSpaceSubscriber *subscriber;
};
QDeclarativeValueSpaceSubscriberPrivate::QDeclarativeValueSpaceSubscriberPrivate() :
subscriber(0)
{
}
QDeclarativeValueSpaceSubscriberPrivate::~QDeclarativeValueSpaceSubscriberPrivate()
{
if (subscriber)
delete subscriber;
}
/*!
\qmlclass ValueSpaceSubscriber QDeclarativeValueSpaceSubscriber
\brief The QValueSpaceSubscriber class allows applications to read and
subscribe to Value Space paths.
\ingroup qml-publishsubscribe
The ValueSpaceSubscriber element is part of the \bold {QtMobility.publishsubscribe 1.1} module.
Each \l ValueSpaceSubscriber element represents a single value or path in the Value Space. The
path is set using the \i path property.
\code
ValueSpaceSubscriber {
id: nowPlaying
path: "/applications/mediaplayer/now-playing"
}
\endcode
The value is accessed using the \i value property.
\code
Text {
text: nowPlaying.value
}
\endcode
*/
QDeclarativeValueSpaceSubscriber::QDeclarativeValueSpaceSubscriber() :
d(new QDeclarativeValueSpaceSubscriberPrivate)
{
}
QDeclarativeValueSpaceSubscriber::~QDeclarativeValueSpaceSubscriber()
{
delete d;
}
/*!
\qmlproperty string ValueSpaceSubscriber::path
This property holds the base path of the subscriber, and is read/write.
*/
void QDeclarativeValueSpaceSubscriber::setPath(QString path)
{
if (d->subscriber) {
if (d->subscriber->path() == path)
return;
d->subscriber->setPath(path);
emit pathChanged();
} else {
d->subscriber = new QValueSpaceSubscriber(path);
emit pathChanged();
}
// re-connect the signal
connect(d->subscriber, SIGNAL(contentsChanged()),
this, SIGNAL(contentsChanged()));
}
QString QDeclarativeValueSpaceSubscriber::path() const
{
if (!d->subscriber)
return QString();
return d->subscriber->path();
}
/*!
\qmlproperty QVariant ValueSpaceSubscriber::value
This property holds the value of the key at the set path in the Value Space.
Read-only.
*/
QVariant QDeclarativeValueSpaceSubscriber::value(const QString &subPath, const QVariant &def) const
{
if (!d->subscriber)
return QVariant();
return d->subscriber->value(subPath, def);
}
/*!
\qmlproperty QStringList ValueSpaceSubscriber::subPaths
This property holds a list of known sub-paths of the currently set path.
*/
QStringList QDeclarativeValueSpaceSubscriber::subPaths() const
{
if (!d->subscriber)
return QStringList();
return d->subscriber->subPaths();
}
/*!
\qmlproperty bool ValueSpaceSubscriber::connected
This property holds whether the subscriber is currently connected to the
backing store of the Value Space.
*/
bool QDeclarativeValueSpaceSubscriber::isConnected() const
{
if (!d->subscriber)
return false;
return d->subscriber->isConnected();
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 Bjorn Fahller <[email protected]>
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef POLL_HPP
#define POLL_HPP
extern "C" void perror(const char*);
#include <cassert>
namespace crpcut {
namespace wrapped {
int close(int fd);
}
}
extern "C"
{
#include <sys/select.h>
}
namespace crpcut {
namespace wrapped {
int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
}
template <size_t N>
struct polldata
{
polldata()
: num_subscribers(0U),
pending_fds(0U)
{
memset(&rset, 0, sizeof(rset));
memset(&wset, 0, sizeof(wset));
memset(&xset, 0, sizeof(xset));
// FD_ZERO(&rset);
// FD_ZERO(&wset);
// FD_ZERO(&xset);
}
struct fdinfo
{
fdinfo(int fd_ = 0, int mode_ = 0, void *ptr_ = 0)
: fd(fd_), mode(mode_), ptr(ptr_)
{
}
int fd;
int mode;
void *ptr;
};
fdinfo access[N];
size_t num_subscribers;
size_t pending_fds;
fd_set rset;
fd_set wset;
fd_set xset;
static const int readbit = 1;
static const int writebit = 2;
static const int hupbit = 4;
};
}
namespace crpcut {
template <typename T, size_t N>
class poll : private polldata<N>
{
public:
struct polltype
{
typedef enum { r = 1, w = 2, rw = 3 } type;
};
class descriptor
{
public:
T* operator->() const { return data; }
T* get() const { return data; }
bool read() const;
bool write() const;
bool hup() const;
bool timeout() const { return mode == 0; }
private:
descriptor(T* t, int m) : data(t), mode(m) {}
T* data;
int mode;
friend class poll<T, N>;
};
poll();
~poll();
void add_fd(int fd, T* data, int flags = polltype::r);
void del_fd(int fd);
descriptor wait(int timeout_ms = -1);
size_t num_fds() const;
};
}
namespace crpcut {
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::read() const
{
return mode & polldata<N>::readbit;
}
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::write() const
{
return mode & polldata<N>::writebit;
}
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::hup() const
{
return mode & polldata<N>::hupbit;
}
template <typename T, size_t N>
inline poll<T, N>::poll()
{
}
template <typename T, size_t N>
inline poll<T, N>::~poll()
{
}
template <typename T, size_t N>
inline void poll<T, N>::add_fd(int fd, T* data, int flags)
{
this->access[this->num_subscribers++] = typename polldata<N>::fdinfo(fd, flags, data);
}
template <typename T, size_t N>
inline void poll<T, N>::del_fd(int fd)
{
for (size_t i = 0; i < this->num_subscribers; ++i)
{
if (this->access[i].fd == fd)
{
this->access[i] = this->access[--this->num_subscribers];
if ( FD_ISSET(fd, &this->xset)
|| FD_ISSET(fd, &this->rset)
|| FD_ISSET(fd, &this->wset))
{
FD_CLR(fd, &this->rset);
FD_CLR(fd, &this->wset);
FD_CLR(fd, &this->xset);
--this->pending_fds;
}
return;
}
}
assert("fd not found" == 0);
}
template <typename T, size_t N>
inline typename poll<T, N>::descriptor poll<T, N>::wait(int timeout_ms)
{
if (this->pending_fds == 0)
{
int maxfd = 0;
for (size_t i = 0; i < this->num_subscribers; ++i)
{
int fd = this->access[i].fd;
if (fd > maxfd) maxfd = fd;
if (this->access[i].mode & polltype::r) FD_SET(fd, &this->rset);
if (this->access[i].mode & polltype::w) FD_SET(fd, &this->wset);
FD_SET(fd, &this->xset);
}
struct timeval tv = { timeout_ms / 1000, (timeout_ms % 1000) * 1000 };
for (;;)
{
int rv = wrapped::select(maxfd + 1,
&this->rset,
&this->wset,
&this->xset,
timeout_ms == -1 ? 0 : &tv);
if (rv == -1 && errno == EINTR) continue;
assert(rv >= 0);
if (rv == 0) return descriptor(0,0); // timeout
this->pending_fds = size_t(rv);
break;
}
}
for (size_t j = 0; j < this->num_subscribers; ++j)
{
int fd = this->access[j].fd;
int mode = 0;
if (FD_ISSET(fd, &this->rset))
{
mode|= polldata<N>::readbit;
FD_CLR(fd, &this->rset);
}
if (FD_ISSET(fd, &this->wset))
{
mode|= polldata<N>::writebit;
FD_CLR(fd, &this->wset);
}
if (FD_ISSET(fd, &this->xset))
{
mode|= polldata<N>::hupbit;
FD_CLR(fd, &this->xset);
}
if (mode)
{
--this->pending_fds;
return descriptor(static_cast<T*>(this->access[j].ptr), mode);
}
}
assert("no matching fd" == 0);
return descriptor(0, 0);
}
template <typename T, size_t N>
inline size_t poll<T, N>::num_fds() const
{
return this->num_subscribers;
}
}
#endif // POLL_HPP
<commit_msg>Went a bit overboard with clang++ cleanup<commit_after>/*
* Copyright 2009-2011 Bjorn Fahller <[email protected]>
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef POLL_HPP
#define POLL_HPP
extern "C" void perror(const char*);
#include <cassert>
namespace crpcut {
namespace wrapped {
int close(int fd);
}
}
extern "C"
{
#include <sys/select.h>
}
namespace crpcut {
namespace wrapped {
int select(int, fd_set *, fd_set *, fd_set *, struct timeval *);
}
template <size_t N>
struct polldata
{
polldata()
: num_subscribers(0U),
pending_fds(0U)
{
FD_ZERO(&rset);
FD_ZERO(&wset);
FD_ZERO(&xset);
}
struct fdinfo
{
fdinfo(int fd_ = 0, int mode_ = 0, void *ptr_ = 0)
: fd(fd_), mode(mode_), ptr(ptr_)
{
}
int fd;
int mode;
void *ptr;
};
fdinfo access[N];
size_t num_subscribers;
size_t pending_fds;
fd_set rset;
fd_set wset;
fd_set xset;
static const int readbit = 1;
static const int writebit = 2;
static const int hupbit = 4;
};
}
namespace crpcut {
template <typename T, size_t N>
class poll : private polldata<N>
{
public:
struct polltype
{
typedef enum { r = 1, w = 2, rw = 3 } type;
};
class descriptor
{
public:
T* operator->() const { return data; }
T* get() const { return data; }
bool read() const;
bool write() const;
bool hup() const;
bool timeout() const { return mode == 0; }
private:
descriptor(T* t, int m) : data(t), mode(m) {}
T* data;
int mode;
friend class poll<T, N>;
};
poll();
~poll();
void add_fd(int fd, T* data, int flags = polltype::r);
void del_fd(int fd);
descriptor wait(int timeout_ms = -1);
size_t num_fds() const;
};
}
namespace crpcut {
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::read() const
{
return mode & polldata<N>::readbit;
}
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::write() const
{
return mode & polldata<N>::writebit;
}
template <typename T, size_t N>
inline bool poll<T, N>::descriptor::hup() const
{
return mode & polldata<N>::hupbit;
}
template <typename T, size_t N>
inline poll<T, N>::poll()
{
}
template <typename T, size_t N>
inline poll<T, N>::~poll()
{
}
template <typename T, size_t N>
inline void poll<T, N>::add_fd(int fd, T* data, int flags)
{
this->access[this->num_subscribers++] = typename polldata<N>::fdinfo(fd, flags, data);
}
template <typename T, size_t N>
inline void poll<T, N>::del_fd(int fd)
{
for (size_t i = 0; i < this->num_subscribers; ++i)
{
if (this->access[i].fd == fd)
{
this->access[i] = this->access[--this->num_subscribers];
if ( FD_ISSET(fd, &this->xset)
|| FD_ISSET(fd, &this->rset)
|| FD_ISSET(fd, &this->wset))
{
FD_CLR(fd, &this->rset);
FD_CLR(fd, &this->wset);
FD_CLR(fd, &this->xset);
--this->pending_fds;
}
return;
}
}
assert("fd not found" == 0);
}
template <typename T, size_t N>
inline typename poll<T, N>::descriptor poll<T, N>::wait(int timeout_ms)
{
if (this->pending_fds == 0)
{
int maxfd = 0;
for (size_t i = 0; i < this->num_subscribers; ++i)
{
int fd = this->access[i].fd;
if (fd > maxfd) maxfd = fd;
if (this->access[i].mode & polltype::r) FD_SET(fd, &this->rset);
if (this->access[i].mode & polltype::w) FD_SET(fd, &this->wset);
FD_SET(fd, &this->xset);
}
struct timeval tv = { timeout_ms / 1000, (timeout_ms % 1000) * 1000 };
for (;;)
{
int rv = wrapped::select(maxfd + 1,
&this->rset,
&this->wset,
&this->xset,
timeout_ms == -1 ? 0 : &tv);
if (rv == -1 && errno == EINTR) continue;
assert(rv >= 0);
if (rv == 0) return descriptor(0,0); // timeout
this->pending_fds = size_t(rv);
break;
}
}
for (size_t j = 0; j < this->num_subscribers; ++j)
{
int fd = this->access[j].fd;
int mode = 0;
if (FD_ISSET(fd, &this->rset))
{
mode|= polldata<N>::readbit;
FD_CLR(fd, &this->rset);
}
if (FD_ISSET(fd, &this->wset))
{
mode|= polldata<N>::writebit;
FD_CLR(fd, &this->wset);
}
if (FD_ISSET(fd, &this->xset))
{
mode|= polldata<N>::hupbit;
FD_CLR(fd, &this->xset);
}
if (mode)
{
--this->pending_fds;
return descriptor(static_cast<T*>(this->access[j].ptr), mode);
}
}
assert("no matching fd" == 0);
return descriptor(0, 0);
}
template <typename T, size_t N>
inline size_t poll<T, N>::num_fds() const
{
return this->num_subscribers;
}
}
#endif // POLL_HPP
<|endoftext|> |
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/c/task/vision/image_classifier_c_api.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils_c.h"
#include "tensorflow_lite_support/c/task/vision/classification_result_c_api.h"
#include "tensorflow_lite_support/c/task/vision/core/frame_buffer_c_api.h"
namespace tflite {
namespace task {
namespace vision {
namespace {
using ::tflite::task::JoinPath;
constexpr char kTestDataDirectory[] =
"tensorflow_lite_support/cc/test/testdata/task/vision/";
// Float model.
constexpr char kMobileNetFloatWithMetadata[] = "mobilenet_v2_1.0_224.tflite";
// Quantized model.
constexpr char kMobileNetQuantizedWithMetadata[] =
"mobilenet_v1_0.25_224_quant.tflite";
// Hello world flowers classifier supporting 5 classes (quantized model).
constexpr char kAutoMLModelWithMetadata[] = "automl_labeler_model.tflite";
ImageData LoadImage(const char* image_name) {
return DecodeImageFromFile(JoinPath("./" /*test src dir*/,
kTestDataDirectory, image_name).data());
}
TEST(ImageClassifierFromFileTest, FailsWithMissingModelPath) {
// ImageClassifierOptions *options = ImageClassifierOptionsCreate();
ImageClassifier *image_classifier = ImageClassifierFromFile("");
ASSERT_EQ(image_classifier, nullptr);
}
TEST(ImageClassifierFromFileTest, SucceedsWithModelPath) {
ImageClassifier *image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data());
EXPECT_NE(image_classifier, nullptr);
ImageClassifierDelete(image_classifier);
}
TEST(ImageClassifierFromOptionsTest, FailsWithMissingModelPath) {
ImageClassifierOptions *options = ImageClassifierOptionsCreate();
ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
ASSERT_EQ(image_classifier, nullptr);
}
TEST(ImageClassifierFromOptionsTest, SucceedsWithModelPath) {
ImageClassifierOptions *options = ImageClassifierOptionsCreate();
const char *model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data();
ImageClassifierOptionsSetModelFilePath(options, model_path);
ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
EXPECT_NE(image_classifier, nullptr);
ImageClassifierDelete(image_classifier);
}
class ImageClassifierClassifyTest : public ::testing::Test {
protected:
void SetUp() override {
image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data());
ASSERT_NE(image_classifier, nullptr);
}
void TearDown() override {
ImageClassifierDelete(image_classifier);
}
ImageClassifier *image_classifier;
};
TEST_F(ImageClassifierClassifyTest, SucceedsWithModelPath) {
struct ImageData image_data = LoadImage("burger-224.png");
struct FrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.plane.buffer = image_data.pixel_data,
.plane.stride.row_stride_bytes = image_data.width * image_data.channels,
.plane.stride.pixel_stride_bytes = image_data.channels,
.format = kRGB};
struct ClassificationResult *classification_result = ImageClassifierClassify(image_classifier, &frame_buffer);
ImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1) << "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr) << "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1) << "Classification Result Classifications Size is NULL";
EXPECT_NE(classification_result->classifications->classes, nullptr) << "Classification Result Classifications Classes is NULL";
ImageClassifierClassificationResultDelete(classification_result);
}
} // namespace
} // namespace vision
} // namespace task
} // namespace tflite
<commit_msg>Image Classifier C API: Updated test<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow_lite_support/cc/port/gmock.h"
#include "tensorflow_lite_support/cc/port/gtest.h"
#include "tensorflow_lite_support/cc/test/test_utils.h"
#include "tensorflow_lite_support/c/task/vision/image_classifier_c_api.h"
#include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils_c.h"
#include "tensorflow_lite_support/c/task/vision/classification_result_c_api.h"
#include "tensorflow_lite_support/c/task/vision/core/frame_buffer_c_api.h"
namespace tflite {
namespace task {
namespace vision {
namespace {
using ::tflite::task::JoinPath;
constexpr char kTestDataDirectory[] =
"tensorflow_lite_support/cc/test/testdata/task/vision/";
// Float model.
constexpr char kMobileNetFloatWithMetadata[] = "mobilenet_v2_1.0_224.tflite";
// Quantized model.
constexpr char kMobileNetQuantizedWithMetadata[] =
"mobilenet_v1_0.25_224_quant.tflite";
// Hello world flowers classifier supporting 5 classes (quantized model).
constexpr char kAutoMLModelWithMetadata[] = "automl_labeler_model.tflite";
ImageData LoadImage(const char* image_name) {
return DecodeImageFromFile(JoinPath("./" /*test src dir*/,
kTestDataDirectory, image_name).data());
}
TEST(ImageClassifierFromFileTest, FailsWithMissingModelPath) {
ImageClassifier *image_classifier = ImageClassifierFromFile("");
ASSERT_EQ(image_classifier, nullptr);
}
TEST(ImageClassifierFromFileTest, SucceedsWithModelPath) {
ImageClassifier *image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data());
EXPECT_NE(image_classifier, nullptr);
ImageClassifierDelete(image_classifier);
}
TEST(ImageClassifierFromOptionsTest, FailsWithMissingModelPath) {
ImageClassifierOptions *options = ImageClassifierOptionsCreate();
ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
ASSERT_EQ(image_classifier, nullptr);
}
TEST(ImageClassifierFromOptionsTest, SucceedsWithModelPath) {
ImageClassifierOptions *options = ImageClassifierOptionsCreate();
const char *model_path = JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data();
ImageClassifierOptionsSetModelFilePath(options, model_path);
ImageClassifier *image_classifier = ImageClassifierFromOptions(options);
EXPECT_NE(image_classifier, nullptr);
ImageClassifierDelete(image_classifier);
}
class ImageClassifierClassifyTest : public ::testing::Test {
protected:
void SetUp() override {
image_classifier = ImageClassifierFromFile(JoinPath("./" /*test src dir*/, kTestDataDirectory,
kMobileNetQuantizedWithMetadata).data());
ASSERT_NE(image_classifier, nullptr);
}
void TearDown() override {
ImageClassifierDelete(image_classifier);
}
ImageClassifier *image_classifier;
};
TEST_F(ImageClassifierClassifyTest, SucceedsWithImageData) {
struct ImageData image_data = LoadImage("burger-224.png");
struct FrameBuffer frame_buffer = {.dimension.width = image_data.width,
.dimension.height = image_data.height,
.plane.buffer = image_data.pixel_data,
.plane.stride.row_stride_bytes = image_data.width * image_data.channels,
.plane.stride.pixel_stride_bytes = image_data.channels,
.format = kRGB};
struct ClassificationResult *classification_result = ImageClassifierClassify(image_classifier, &frame_buffer);
ImageDataFree(&image_data);
ASSERT_NE(classification_result, nullptr) << "Classification Result is NULL";
EXPECT_TRUE(classification_result->size >= 1) << "Classification Result size is 0";
EXPECT_NE(classification_result->classifications, nullptr) << "Classification Result Classifications is NULL";
EXPECT_TRUE(classification_result->classifications->size >= 1) << "Classification Result Classifications Size is NULL";
EXPECT_NE(classification_result->classifications->classes, nullptr) << "Classification Result Classifications Classes is NULL";
ImageClassifierClassificationResultDelete(classification_result);
}
} // namespace
} // namespace vision
} // namespace task
} // namespace tflite
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// Copyright (c) 2016 John D. Haughton
//
// 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 <cstdio>
#include "ConsoleImpl.h"
#include "PLT/KeyCode.h"
static FILE* input_fp = nullptr;
bool ConsoleImpl::openInputFile(const char* filename)
{
input_fp = fopen(filename, "r");
return isInputFileOpen();
}
bool ConsoleImpl::isInputFileOpen() { return input_fp != nullptr; }
void ConsoleImpl::closeInputFile()
{
fclose(input_fp);
input_fp = nullptr;
}
int ConsoleImpl::getInput(unsigned timeout_ms)
{
if(input_fp != nullptr)
{
if(feof(input_fp))
{
closeInputFile();
}
else
{
return fgetc(input_fp);
}
}
curses.timeout(timeout_ms);
int ch = curses.getch();
// Some PLT::KeyCode to ZSCII conversions
switch(ch)
{
case PLT::BACKSPACE: return 0x08;
case PLT::TAB: return 0x09;
case PLT::RETURN: return 0x0A;
case PLT::ESCAPE: return 0x1B;
case 0x7F: return 0x08;
case PLT::UP: return 0x81;
case PLT::DOWN: return 0x82;
case PLT::LEFT: return 0x83;
case PLT::RIGHT: return 0x84;
case PLT::F1: return 0x85;
case PLT::F2: return 0x86;
case PLT::F3: return 0x87;
case PLT::F4: return 0x88;
case PLT::F5: return 0x89;
case PLT::F6: return 0x8A;
case PLT::F7: return 0x8B;
case PLT::F8: return 0x8C;
case PLT::F9: return 0x8D;
case PLT::F10: return 0x8E;
case PLT::F11: return 0x8F;
case PLT::F12: return 0x90;
// Ignore
case PLT::MENU: return 1;
case PLT::SELECT: return 1;
case PLT::HOME: return 1;
case PLT::VOL_UP: return 1;
case PLT::VOL_DOWN: return 1;
// Quit game
case PLT::BACK: return -1;
}
return ch;
}
<commit_msg>Change some key mappings inside the Z engine<commit_after>//------------------------------------------------------------------------------
// Copyright (c) 2016 John D. Haughton
//
// 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 <cstdio>
#include "ConsoleImpl.h"
#include "PLT/KeyCode.h"
static FILE* input_fp = nullptr;
bool ConsoleImpl::openInputFile(const char* filename)
{
input_fp = fopen(filename, "r");
return isInputFileOpen();
}
bool ConsoleImpl::isInputFileOpen() { return input_fp != nullptr; }
void ConsoleImpl::closeInputFile()
{
fclose(input_fp);
input_fp = nullptr;
}
int ConsoleImpl::getInput(unsigned timeout_ms)
{
if(input_fp != nullptr)
{
if(feof(input_fp))
{
closeInputFile();
}
else
{
return fgetc(input_fp);
}
}
curses.timeout(timeout_ms);
int ch = curses.getch();
// Some PLT::KeyCode to ZSCII conversions
switch(ch)
{
case PLT::BACKSPACE: return 0x08;
case PLT::TAB: return 0x09;
case PLT::RETURN: return 0x0A;
case PLT::ESCAPE: return 0x1B;
case 0x7F: return 0x08;
case PLT::UP: return 0x81;
case PLT::DOWN: return 0x82;
case PLT::LEFT: return 0x83;
case PLT::RIGHT: return 0x84;
case PLT::F1: return 0x85;
case PLT::F2: return 0x86;
case PLT::F3: return 0x87;
case PLT::F4: return 0x88;
case PLT::F5: return 0x89;
case PLT::F6: return 0x8A;
case PLT::F7: return 0x8B;
case PLT::F8: return 0x8C;
case PLT::F9: return 0x8D;
case PLT::F10: return 0x8E;
case PLT::F11: return 0x8F;
case PLT::F12: return 0x90;
// Ignore
case PLT::SELECT: return 1;
case PLT::HOME: return 1;
case PLT::END: return 1;
case PLT::PAGE_UP: return 1;
case PLT::PAGE_DOWN: return 1;
case PLT::VOL_UP: return 1;
case PLT::VOL_DOWN: return 1;
// Quit game
case PLT::MENU: return -1;
case PLT::BACK: return -1;
}
return ch;
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include <rapidcheck/gtest.h>
#include SPECIFIC_HEADER
// Running tests
TEST(TEST_NAME, Zero)
{
ASSERT_EQ(0, less_significant(0));
}
TEST(TEST_NAME, PowerOfTwo)
{
ASSERT_EQ(128, less_significant(128));
}
TEST(TEST_NAME, Nine)
{
ASSERT_EQ(1, less_significant(9));
}
RC_GTEST_PROP(TEST_NAME, AnswerIsPowerOfTwo, (unsigned N))
{
auto answer = less_significant(N);
RC_ASSERT((answer & (answer-1)) == decltype(answer)());
}
RC_GTEST_PROP(TEST_NAME, AnswerIsBitOfInput, (unsigned N))
{
auto answer = less_significant(N);
RC_ASSERT((N | answer) == N);
}
RC_GTEST_PROP(TEST_NAME, AnswerIsTheLowestBit, (unsigned N))
{
RC_PRE(N > unsigned());
RC_PRE(N & (N-1)); //not a power of two
auto answer = less_significant(N);
RC_ASSERT((N ^ answer) > answer);
}
RC_GTEST_PROP(TEST_NAME, AnswerIsItselfForPowerOfTwo, ())
{
auto power = *rc::gen::inRange(decltype(sizeof(unsigned))(), 8 * sizeof(unsigned));
unsigned N = 1 << power;
RC_ASSERT(N == less_significant(N));
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
int ret { RUN_ALL_TESTS() };
return ret;
}
<commit_msg>[less-significant-bit][vs] Fix implicit conversion from unsigned to bool<commit_after>#include "gtest/gtest.h"
#include <rapidcheck/gtest.h>
#include SPECIFIC_HEADER
// Running tests
TEST(TEST_NAME, Zero)
{
ASSERT_EQ(0, less_significant(0));
}
TEST(TEST_NAME, PowerOfTwo)
{
ASSERT_EQ(128, less_significant(128));
}
TEST(TEST_NAME, Nine)
{
ASSERT_EQ(1, less_significant(9));
}
RC_GTEST_PROP(TEST_NAME, AnswerIsPowerOfTwo, (unsigned N))
{
auto answer = less_significant(N);
RC_ASSERT((answer & (answer-1)) == decltype(answer)());
}
RC_GTEST_PROP(TEST_NAME, AnswerIsBitOfInput, (unsigned N))
{
auto answer = less_significant(N);
RC_ASSERT((N | answer) == N);
}
RC_GTEST_PROP(TEST_NAME, AnswerIsTheLowestBit, (unsigned N))
{
RC_PRE(N > unsigned());
RC_PRE((N & (N-1)) != unsigned()); //not a power of two
auto answer = less_significant(N);
RC_ASSERT((N ^ answer) > answer);
}
RC_GTEST_PROP(TEST_NAME, AnswerIsItselfForPowerOfTwo, ())
{
auto power = *rc::gen::inRange(decltype(sizeof(unsigned))(), 8 * sizeof(unsigned));
unsigned N = 1 << power;
RC_ASSERT(N == less_significant(N));
}
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
int ret { RUN_ALL_TESTS() };
return ret;
}
<|endoftext|> |
<commit_before><commit_msg>Lower image quality for chromoting to improve encode speed and compression ratio<commit_after><|endoftext|> |
<commit_before><commit_msg>remove unused #define SFX_ITEMTYPE_STATBAR in workwin.cxx<commit_after><|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.