text
stringlengths 54
60.6k
|
---|
<commit_before>// Scintilla source code edit control
/** @file LexMSSQL.cxx
** Lexer for MSSQL.
**/
// By Filip Yaghob <[email protected]>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#define KW_MSSQL_STATEMENTS 0
#define KW_MSSQL_DATA_TYPES 1
#define KW_MSSQL_SYSTEM_TABLES 2
#define KW_MSSQL_GLOBAL_VARIABLES 3
#define KW_MSSQL_FUNCTIONS 4
#define KW_MSSQL_STORED_PROCEDURES 5
#define KW_MSSQL_OPERATORS 6
static bool isMSSQLOperator(char ch) {
if (isascii(ch) && isalnum(ch))
return false;
// '.' left out as it is used to make up numbers
if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
ch == '-' || ch == '+' || ch == '=' || ch == '|' ||
ch == '<' || ch == '>' || ch == '/' ||
ch == '!' || ch == '~' || ch == '(' || ch == ')' ||
ch == ',')
return true;
return false;
}
static char classifyWordSQL(unsigned int start,
unsigned int end,
WordList *keywordlists[],
Accessor &styler,
unsigned int actualState,
unsigned int prevState) {
char s[256];
bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');
WordList &kwStatements = *keywordlists[KW_MSSQL_STATEMENTS];
WordList &kwDataTypes = *keywordlists[KW_MSSQL_DATA_TYPES];
WordList &kwSystemTables = *keywordlists[KW_MSSQL_SYSTEM_TABLES];
WordList &kwGlobalVariables = *keywordlists[KW_MSSQL_GLOBAL_VARIABLES];
WordList &kwFunctions = *keywordlists[KW_MSSQL_FUNCTIONS];
WordList &kwStoredProcedures = *keywordlists[KW_MSSQL_STORED_PROCEDURES];
WordList &kwOperators = *keywordlists[KW_MSSQL_OPERATORS];
for (unsigned int i = 0; i < end - start + 1 && i < 128; i++) {
s[i] = static_cast<char>(tolower(styler[start + i]));
s[i + 1] = '\0';
}
char chAttr = SCE_MSSQL_IDENTIFIER;
if (actualState == SCE_MSSQL_GLOBAL_VARIABLE) {
if (kwGlobalVariables.InList(&s[2]))
chAttr = SCE_MSSQL_GLOBAL_VARIABLE;
} else if (wordIsNumber) {
chAttr = SCE_MSSQL_NUMBER;
} else if (prevState == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
// Look first in datatypes
if (kwDataTypes.InList(s))
chAttr = SCE_MSSQL_DATATYPE;
else if (kwOperators.InList(s))
chAttr = SCE_MSSQL_OPERATOR;
else if (kwStatements.InList(s))
chAttr = SCE_MSSQL_STATEMENT;
else if (kwSystemTables.InList(s))
chAttr = SCE_MSSQL_SYSTABLE;
else if (kwFunctions.InList(s))
chAttr = SCE_MSSQL_FUNCTION;
else if (kwStoredProcedures.InList(s))
chAttr = SCE_MSSQL_STORED_PROCEDURE;
} else {
if (kwOperators.InList(s))
chAttr = SCE_MSSQL_OPERATOR;
else if (kwStatements.InList(s))
chAttr = SCE_MSSQL_STATEMENT;
else if (kwSystemTables.InList(s))
chAttr = SCE_MSSQL_SYSTABLE;
else if (kwFunctions.InList(s))
chAttr = SCE_MSSQL_FUNCTION;
else if (kwStoredProcedures.InList(s))
chAttr = SCE_MSSQL_STORED_PROCEDURE;
else if (kwDataTypes.InList(s))
chAttr = SCE_MSSQL_DATATYPE;
}
styler.ColourTo(end, chAttr);
return chAttr;
}
static void ColouriseMSSQLDoc(unsigned int startPos, int length,
int initStyle, WordList *keywordlists[], Accessor &styler) {
styler.StartAt(startPos);
bool fold = styler.GetPropertyInt("fold") != 0;
int lineCurrent = styler.GetLine(startPos);
int spaceFlags = 0;
int state = initStyle;
int prevState = initStyle;
char chPrev = ' ';
char chNext = styler[startPos];
styler.StartSegment(startPos);
unsigned int lengthDoc = startPos + length;
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
int lev = indentCurrent;
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
// Only non whitespace lines can be headers
int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags);
if (indentCurrent < (indentNext & ~SC_FOLDLEVELWHITEFLAG)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
}
if (fold) {
styler.SetLevel(lineCurrent, lev);
}
}
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
// When the last char isn't part of the state (have to deal with it too)...
if ( (state == SCE_MSSQL_IDENTIFIER) ||
(state == SCE_MSSQL_STORED_PROCEDURE) ||
(state == SCE_MSSQL_DATATYPE) ||
//~ (state == SCE_MSSQL_COLUMN_NAME) ||
(state == SCE_MSSQL_FUNCTION) ||
//~ (state == SCE_MSSQL_GLOBAL_VARIABLE) ||
(state == SCE_MSSQL_VARIABLE)) {
if (!iswordchar(ch)) {
int stateTmp;
if ((state == SCE_MSSQL_VARIABLE) || (state == SCE_MSSQL_COLUMN_NAME)) {
styler.ColourTo(i - 1, state);
stateTmp = state;
} else
stateTmp = classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);
prevState = state;
if (stateTmp == SCE_MSSQL_IDENTIFIER || stateTmp == SCE_MSSQL_VARIABLE)
state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
else
state = SCE_MSSQL_DEFAULT;
}
} else if (state == SCE_MSSQL_LINE_COMMENT) {
if (ch == '\r' || ch == '\n') {
styler.ColourTo(i - 1, state);
prevState = state;
state = SCE_MSSQL_DEFAULT;
}
} else if (state == SCE_MSSQL_GLOBAL_VARIABLE) {
if ((ch != '@') && !iswordchar(ch)) {
classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);
prevState = state;
state = SCE_MSSQL_DEFAULT;
}
}
// If is the default or one of the above succeeded
if (state == SCE_MSSQL_DEFAULT || state == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
if (iswordstart(ch)) {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_IDENTIFIER;
} else if (ch == '/' && chNext == '*') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_COMMENT;
} else if (ch == '-' && chNext == '-') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_LINE_COMMENT;
} else if (ch == '\'') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_STRING;
} else if (ch == '"') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_COLUMN_NAME;
} else if (ch == '[') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_COLUMN_NAME_2;
} else if (isMSSQLOperator(ch)) {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
styler.ColourTo(i, SCE_MSSQL_OPERATOR);
//~ style = SCE_MSSQL_DEFAULT;
prevState = state;
state = SCE_MSSQL_DEFAULT;
} else if (ch == '@') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
if (chNext == '@') {
state = SCE_MSSQL_GLOBAL_VARIABLE;
// i += 2;
} else
state = SCE_MSSQL_VARIABLE;
}
// When the last char is part of the state...
} else if (state == SCE_MSSQL_COMMENT) {
if (ch == '/' && chPrev == '*') {
if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_MSSQL_COMMENT) &&
(styler.GetStartSegment() == startPos)))) {
styler.ColourTo(i, state);
//~ state = SCE_MSSQL_COMMENT;
prevState = state;
state = SCE_MSSQL_DEFAULT;
}
}
} else if (state == SCE_MSSQL_STRING) {
if (ch == '\'') {
if ( chNext == '\'' ) {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
styler.ColourTo(i, state);
prevState = state;
state = SCE_MSSQL_DEFAULT;
//i++;
}
//ch = chNext;
//chNext = styler.SafeGetCharAt(i + 1);
}
} else if (state == SCE_MSSQL_COLUMN_NAME) {
if (ch == '"') {
if (chNext == '"') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
styler.ColourTo(i, state);
prevState = state;
state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
//i++;
}
}
} else if (state == SCE_MSSQL_COLUMN_NAME_2) {
if (ch == ']') {
styler.ColourTo(i, state);
prevState = state;
state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
//i++;
}
}
chPrev = ch;
}
styler.ColourTo(lengthDoc - 1, state);
}
static void FoldMSSQLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool inComment = (styler.StyleAt(startPos-1) == SCE_MSSQL_COMMENT);
char s[10];
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
// Comment folding
if (foldComment) {
if (!inComment && (style == SCE_MSSQL_COMMENT))
levelCurrent++;
else if (inComment && (style != SCE_MSSQL_COMMENT))
levelCurrent--;
inComment = (style == SCE_MSSQL_COMMENT);
}
if (style == SCE_MSSQL_STATEMENT) {
// Folding between begin and end
if (ch == 'b' || ch == 'e') {
for (unsigned int j = 0; j < 5; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if (strcmp(s, "begin") == 0) {
levelCurrent++;
}
if (strcmp(s, "end") == 0) {
levelCurrent--;
}
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const sqlWordListDesc[] = {
"Statements",
"Data Types",
"System tables",
"Global variables",
"Functions",
"System Stored Procedures",
"Operators",
0,
};
LexerModule lmMSSQL(SCLEX_MSSQL, ColouriseMSSQLDoc, "mssql", FoldMSSQLDoc, sqlWordListDesc);
<commit_msg>Added license reference to help the picky.<commit_after>// Scintilla source code edit control
/** @file LexMSSQL.cxx
** Lexer for MSSQL.
**/
// By Filip Yaghob <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdarg.h>
#include "Platform.h"
#include "PropSet.h"
#include "Accessor.h"
#include "KeyWords.h"
#include "Scintilla.h"
#include "SciLexer.h"
#define KW_MSSQL_STATEMENTS 0
#define KW_MSSQL_DATA_TYPES 1
#define KW_MSSQL_SYSTEM_TABLES 2
#define KW_MSSQL_GLOBAL_VARIABLES 3
#define KW_MSSQL_FUNCTIONS 4
#define KW_MSSQL_STORED_PROCEDURES 5
#define KW_MSSQL_OPERATORS 6
static bool isMSSQLOperator(char ch) {
if (isascii(ch) && isalnum(ch))
return false;
// '.' left out as it is used to make up numbers
if (ch == '%' || ch == '^' || ch == '&' || ch == '*' ||
ch == '-' || ch == '+' || ch == '=' || ch == '|' ||
ch == '<' || ch == '>' || ch == '/' ||
ch == '!' || ch == '~' || ch == '(' || ch == ')' ||
ch == ',')
return true;
return false;
}
static char classifyWordSQL(unsigned int start,
unsigned int end,
WordList *keywordlists[],
Accessor &styler,
unsigned int actualState,
unsigned int prevState) {
char s[256];
bool wordIsNumber = isdigit(styler[start]) || (styler[start] == '.');
WordList &kwStatements = *keywordlists[KW_MSSQL_STATEMENTS];
WordList &kwDataTypes = *keywordlists[KW_MSSQL_DATA_TYPES];
WordList &kwSystemTables = *keywordlists[KW_MSSQL_SYSTEM_TABLES];
WordList &kwGlobalVariables = *keywordlists[KW_MSSQL_GLOBAL_VARIABLES];
WordList &kwFunctions = *keywordlists[KW_MSSQL_FUNCTIONS];
WordList &kwStoredProcedures = *keywordlists[KW_MSSQL_STORED_PROCEDURES];
WordList &kwOperators = *keywordlists[KW_MSSQL_OPERATORS];
for (unsigned int i = 0; i < end - start + 1 && i < 128; i++) {
s[i] = static_cast<char>(tolower(styler[start + i]));
s[i + 1] = '\0';
}
char chAttr = SCE_MSSQL_IDENTIFIER;
if (actualState == SCE_MSSQL_GLOBAL_VARIABLE) {
if (kwGlobalVariables.InList(&s[2]))
chAttr = SCE_MSSQL_GLOBAL_VARIABLE;
} else if (wordIsNumber) {
chAttr = SCE_MSSQL_NUMBER;
} else if (prevState == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
// Look first in datatypes
if (kwDataTypes.InList(s))
chAttr = SCE_MSSQL_DATATYPE;
else if (kwOperators.InList(s))
chAttr = SCE_MSSQL_OPERATOR;
else if (kwStatements.InList(s))
chAttr = SCE_MSSQL_STATEMENT;
else if (kwSystemTables.InList(s))
chAttr = SCE_MSSQL_SYSTABLE;
else if (kwFunctions.InList(s))
chAttr = SCE_MSSQL_FUNCTION;
else if (kwStoredProcedures.InList(s))
chAttr = SCE_MSSQL_STORED_PROCEDURE;
} else {
if (kwOperators.InList(s))
chAttr = SCE_MSSQL_OPERATOR;
else if (kwStatements.InList(s))
chAttr = SCE_MSSQL_STATEMENT;
else if (kwSystemTables.InList(s))
chAttr = SCE_MSSQL_SYSTABLE;
else if (kwFunctions.InList(s))
chAttr = SCE_MSSQL_FUNCTION;
else if (kwStoredProcedures.InList(s))
chAttr = SCE_MSSQL_STORED_PROCEDURE;
else if (kwDataTypes.InList(s))
chAttr = SCE_MSSQL_DATATYPE;
}
styler.ColourTo(end, chAttr);
return chAttr;
}
static void ColouriseMSSQLDoc(unsigned int startPos, int length,
int initStyle, WordList *keywordlists[], Accessor &styler) {
styler.StartAt(startPos);
bool fold = styler.GetPropertyInt("fold") != 0;
int lineCurrent = styler.GetLine(startPos);
int spaceFlags = 0;
int state = initStyle;
int prevState = initStyle;
char chPrev = ' ';
char chNext = styler[startPos];
styler.StartSegment(startPos);
unsigned int lengthDoc = startPos + length;
for (unsigned int i = startPos; i < lengthDoc; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
if ((ch == '\r' && chNext != '\n') || (ch == '\n')) {
int indentCurrent = styler.IndentAmount(lineCurrent, &spaceFlags);
int lev = indentCurrent;
if (!(indentCurrent & SC_FOLDLEVELWHITEFLAG)) {
// Only non whitespace lines can be headers
int indentNext = styler.IndentAmount(lineCurrent + 1, &spaceFlags);
if (indentCurrent < (indentNext & ~SC_FOLDLEVELWHITEFLAG)) {
lev |= SC_FOLDLEVELHEADERFLAG;
}
}
if (fold) {
styler.SetLevel(lineCurrent, lev);
}
}
if (styler.IsLeadByte(ch)) {
chNext = styler.SafeGetCharAt(i + 2);
chPrev = ' ';
i += 1;
continue;
}
// When the last char isn't part of the state (have to deal with it too)...
if ( (state == SCE_MSSQL_IDENTIFIER) ||
(state == SCE_MSSQL_STORED_PROCEDURE) ||
(state == SCE_MSSQL_DATATYPE) ||
//~ (state == SCE_MSSQL_COLUMN_NAME) ||
(state == SCE_MSSQL_FUNCTION) ||
//~ (state == SCE_MSSQL_GLOBAL_VARIABLE) ||
(state == SCE_MSSQL_VARIABLE)) {
if (!iswordchar(ch)) {
int stateTmp;
if ((state == SCE_MSSQL_VARIABLE) || (state == SCE_MSSQL_COLUMN_NAME)) {
styler.ColourTo(i - 1, state);
stateTmp = state;
} else
stateTmp = classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);
prevState = state;
if (stateTmp == SCE_MSSQL_IDENTIFIER || stateTmp == SCE_MSSQL_VARIABLE)
state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
else
state = SCE_MSSQL_DEFAULT;
}
} else if (state == SCE_MSSQL_LINE_COMMENT) {
if (ch == '\r' || ch == '\n') {
styler.ColourTo(i - 1, state);
prevState = state;
state = SCE_MSSQL_DEFAULT;
}
} else if (state == SCE_MSSQL_GLOBAL_VARIABLE) {
if ((ch != '@') && !iswordchar(ch)) {
classifyWordSQL(styler.GetStartSegment(), i - 1, keywordlists, styler, state, prevState);
prevState = state;
state = SCE_MSSQL_DEFAULT;
}
}
// If is the default or one of the above succeeded
if (state == SCE_MSSQL_DEFAULT || state == SCE_MSSQL_DEFAULT_PREF_DATATYPE) {
if (iswordstart(ch)) {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_IDENTIFIER;
} else if (ch == '/' && chNext == '*') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_COMMENT;
} else if (ch == '-' && chNext == '-') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_LINE_COMMENT;
} else if (ch == '\'') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_STRING;
} else if (ch == '"') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_COLUMN_NAME;
} else if (ch == '[') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
state = SCE_MSSQL_COLUMN_NAME_2;
} else if (isMSSQLOperator(ch)) {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
styler.ColourTo(i, SCE_MSSQL_OPERATOR);
//~ style = SCE_MSSQL_DEFAULT;
prevState = state;
state = SCE_MSSQL_DEFAULT;
} else if (ch == '@') {
styler.ColourTo(i - 1, SCE_MSSQL_DEFAULT);
prevState = state;
if (chNext == '@') {
state = SCE_MSSQL_GLOBAL_VARIABLE;
// i += 2;
} else
state = SCE_MSSQL_VARIABLE;
}
// When the last char is part of the state...
} else if (state == SCE_MSSQL_COMMENT) {
if (ch == '/' && chPrev == '*') {
if (((i > (styler.GetStartSegment() + 2)) || ((initStyle == SCE_MSSQL_COMMENT) &&
(styler.GetStartSegment() == startPos)))) {
styler.ColourTo(i, state);
//~ state = SCE_MSSQL_COMMENT;
prevState = state;
state = SCE_MSSQL_DEFAULT;
}
}
} else if (state == SCE_MSSQL_STRING) {
if (ch == '\'') {
if ( chNext == '\'' ) {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
styler.ColourTo(i, state);
prevState = state;
state = SCE_MSSQL_DEFAULT;
//i++;
}
//ch = chNext;
//chNext = styler.SafeGetCharAt(i + 1);
}
} else if (state == SCE_MSSQL_COLUMN_NAME) {
if (ch == '"') {
if (chNext == '"') {
i++;
ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
} else {
styler.ColourTo(i, state);
prevState = state;
state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
//i++;
}
}
} else if (state == SCE_MSSQL_COLUMN_NAME_2) {
if (ch == ']') {
styler.ColourTo(i, state);
prevState = state;
state = SCE_MSSQL_DEFAULT_PREF_DATATYPE;
//i++;
}
}
chPrev = ch;
}
styler.ColourTo(lengthDoc - 1, state);
}
static void FoldMSSQLDoc(unsigned int startPos, int length, int, WordList *[], Accessor &styler) {
bool foldComment = styler.GetPropertyInt("fold.comment") != 0;
bool foldCompact = styler.GetPropertyInt("fold.compact", 1) != 0;
unsigned int endPos = startPos + length;
int visibleChars = 0;
int lineCurrent = styler.GetLine(startPos);
int levelPrev = styler.LevelAt(lineCurrent) & SC_FOLDLEVELNUMBERMASK;
int levelCurrent = levelPrev;
char chNext = styler[startPos];
bool inComment = (styler.StyleAt(startPos-1) == SCE_MSSQL_COMMENT);
char s[10];
for (unsigned int i = startPos; i < endPos; i++) {
char ch = chNext;
chNext = styler.SafeGetCharAt(i + 1);
int style = styler.StyleAt(i);
bool atEOL = (ch == '\r' && chNext != '\n') || (ch == '\n');
// Comment folding
if (foldComment) {
if (!inComment && (style == SCE_MSSQL_COMMENT))
levelCurrent++;
else if (inComment && (style != SCE_MSSQL_COMMENT))
levelCurrent--;
inComment = (style == SCE_MSSQL_COMMENT);
}
if (style == SCE_MSSQL_STATEMENT) {
// Folding between begin and end
if (ch == 'b' || ch == 'e') {
for (unsigned int j = 0; j < 5; j++) {
if (!iswordchar(styler[i + j])) {
break;
}
s[j] = styler[i + j];
s[j + 1] = '\0';
}
if (strcmp(s, "begin") == 0) {
levelCurrent++;
}
if (strcmp(s, "end") == 0) {
levelCurrent--;
}
}
}
if (atEOL) {
int lev = levelPrev;
if (visibleChars == 0 && foldCompact)
lev |= SC_FOLDLEVELWHITEFLAG;
if ((levelCurrent > levelPrev) && (visibleChars > 0))
lev |= SC_FOLDLEVELHEADERFLAG;
if (lev != styler.LevelAt(lineCurrent)) {
styler.SetLevel(lineCurrent, lev);
}
lineCurrent++;
levelPrev = levelCurrent;
visibleChars = 0;
}
if (!isspacechar(ch))
visibleChars++;
}
// Fill in the real level of the next line, keeping the current flags as they will be filled in later
int flagsNext = styler.LevelAt(lineCurrent) & ~SC_FOLDLEVELNUMBERMASK;
styler.SetLevel(lineCurrent, levelPrev | flagsNext);
}
static const char * const sqlWordListDesc[] = {
"Statements",
"Data Types",
"System tables",
"Global variables",
"Functions",
"System Stored Procedures",
"Operators",
0,
};
LexerModule lmMSSQL(SCLEX_MSSQL, ColouriseMSSQLDoc, "mssql", FoldMSSQLDoc, sqlWordListDesc);
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS dr48 (1.38.110); FILE MERGED 2006/05/22 16:33:51 dr 1.38.110.2: type correctness for stream related code in Excel filters (sal_Size vs. ULONG vs. sal_uInt32) 2006/05/10 16:59:31 dr 1.38.110.1: #i63105# backport changes from CWS chart2mst3<commit_after><|endoftext|> |
<commit_before>#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/renderer/common/renderable.h"
#include "pixelboost/logic/system/graphics/render/render.h"
using namespace pb;
Renderable::Renderable(Uid entityUid)
: _BoundsDirty(true)
, _Layer(0)
, _Effect(0)
, _EntityUid(entityUid)
, _RenderPass(kRenderPassScene)
, _WorldMatrixDirty(true)
{
}
Renderable::Renderable(Uid entityUid, Effect* effect)
: _BoundsDirty(true)
, _Layer(0)
, _Effect(effect)
, _EntityUid(entityUid)
, _RenderPass(kRenderPassScene)
, _WorldMatrixDirty(true)
{
}
Renderable::~Renderable()
{
}
void Renderable::SetSystem(RenderSystem* system)
{
_System = system;
}
Uid Renderable::GetEntityUid()
{
return _EntityUid;
}
void Renderable::SetRenderPass(RenderPass renderPass)
{
_RenderPass = renderPass;
RefreshSystemBinding();
}
RenderPass Renderable::GetRenderPass()
{
return _RenderPass;
}
void Renderable::SetLayer(int layer)
{
_Layer = layer;
}
int Renderable::GetLayer()
{
return _Layer;
}
void Renderable::DirtyBounds()
{
_BoundsDirty = true;
}
void Renderable::SetBounds(const BoundingSphere& bounds)
{
_Bounds = bounds;
_BoundsDirty = false;
if (_System)
_System->UpdateBounds(this);
}
const BoundingSphere& Renderable::GetBounds()
{
if (_BoundsDirty)
CalculateBounds();
return _Bounds;
}
void Renderable::DirtyWorldMatrix()
{
_WorldMatrixDirty = true;
}
void Renderable::SetWorldMatrix(const glm::mat4x4& matrix)
{
_WorldMatrix = matrix;
_WorldMatrixDirty = false;
}
const glm::mat4x4& Renderable::GetWorldMatrix()
{
if (_WorldMatrixDirty)
CalculateWorldMatrix();
return _WorldMatrix;
}
void Renderable::CalculateMVP(Viewport* viewport, Camera* camera)
{
if (_WorldMatrixDirty)
CalculateWorldMatrix();
_MVPMatrix = camera->ViewProjectionMatrix * _WorldMatrix;
}
const glm::mat4x4& Renderable::GetMVP() const
{
return _MVPMatrix;
}
Effect* Renderable::GetEffect()
{
return _Effect;
}
void Renderable::SetEffect(Effect* effect)
{
_Effect = effect;
}
void Renderable::RefreshSystemBinding()
{
if (_System)
{
RenderSystem* system = _System;
system->RemoveItem(this);
system->AddItem(this);
}
}
<commit_msg>Initialise render system to 0<commit_after>#include "pixelboost/graphics/camera/camera.h"
#include "pixelboost/graphics/camera/viewport.h"
#include "pixelboost/graphics/renderer/common/renderable.h"
#include "pixelboost/logic/system/graphics/render/render.h"
using namespace pb;
Renderable::Renderable(Uid entityUid)
: _BoundsDirty(true)
, _Layer(0)
, _Effect(0)
, _EntityUid(entityUid)
, _RenderPass(kRenderPassScene)
, _System(0)
, _WorldMatrixDirty(true)
{
}
Renderable::Renderable(Uid entityUid, Effect* effect)
: _BoundsDirty(true)
, _Layer(0)
, _Effect(effect)
, _EntityUid(entityUid)
, _RenderPass(kRenderPassScene)
, _System(0)
, _WorldMatrixDirty(true)
{
}
Renderable::~Renderable()
{
}
void Renderable::SetSystem(RenderSystem* system)
{
_System = system;
}
Uid Renderable::GetEntityUid()
{
return _EntityUid;
}
void Renderable::SetRenderPass(RenderPass renderPass)
{
_RenderPass = renderPass;
RefreshSystemBinding();
}
RenderPass Renderable::GetRenderPass()
{
return _RenderPass;
}
void Renderable::SetLayer(int layer)
{
_Layer = layer;
}
int Renderable::GetLayer()
{
return _Layer;
}
void Renderable::DirtyBounds()
{
_BoundsDirty = true;
}
void Renderable::SetBounds(const BoundingSphere& bounds)
{
_Bounds = bounds;
_BoundsDirty = false;
if (_System)
_System->UpdateBounds(this);
}
const BoundingSphere& Renderable::GetBounds()
{
if (_BoundsDirty)
CalculateBounds();
return _Bounds;
}
void Renderable::DirtyWorldMatrix()
{
_WorldMatrixDirty = true;
}
void Renderable::SetWorldMatrix(const glm::mat4x4& matrix)
{
_WorldMatrix = matrix;
_WorldMatrixDirty = false;
}
const glm::mat4x4& Renderable::GetWorldMatrix()
{
if (_WorldMatrixDirty)
CalculateWorldMatrix();
return _WorldMatrix;
}
void Renderable::CalculateMVP(Viewport* viewport, Camera* camera)
{
if (_WorldMatrixDirty)
CalculateWorldMatrix();
_MVPMatrix = camera->ViewProjectionMatrix * _WorldMatrix;
}
const glm::mat4x4& Renderable::GetMVP() const
{
return _MVPMatrix;
}
Effect* Renderable::GetEffect()
{
return _Effect;
}
void Renderable::SetEffect(Effect* effect)
{
_Effect = effect;
}
void Renderable::RefreshSystemBinding()
{
if (_System)
{
RenderSystem* system = _System;
system->RemoveItem(this);
system->AddItem(this);
}
}
<|endoftext|> |
<commit_before>/*
* logger.hpp
*
* Created on: Aug 9, 2012
* Author: philipp
*/
#ifndef __LOGGER_HPP__
#define __LOGGER_HPP__
#include <string>
#if defined(_GLIBCXX_HAS_GTHREADS)
#include <thread>
#define THREAD_GET_ID() std::this_thread::get_id()
#else
#include <boost/thread.hpp>
namespace std {
using boost::mutex;
using boost::recursive_mutex;
using boost::lock_guard;
using boost::condition_variable;
using boost::unique_lock;
using boost::thread;
}
#define THREAD_GET_ID() boost::this_thread::get_id()
#endif
#include <chrono>
#include <boost/format.hpp>
enum mlog_level
{
trace, debug, info, warning, error, fatal
};
namespace mlog
{
template<typename T>
inline std::string level_to_string(T&& level)
{
if(level == mlog_level::trace)
return "trace";
else if(level == mlog_level::debug)
return "debug";
else if(level == mlog_level::info)
return "info";
else if(level == mlog_level::warning)
return "warning";
else if(level == mlog_level::error)
return "error";
else
return "fatal";
}
struct log_metadata
{
//typedef std::chrono::high_resolution_clock clocks;
typedef std::chrono::system_clock clocks;
bool use_time;
bool use_thread_id;
mlog_level level;
short session_id;
std::chrono::time_point<clocks> time;
std::thread::id thread_id;
log_metadata()
:use_time(true),
use_thread_id(false),
level(info),
session_id(0)
{
}
log_metadata(mlog_level&& lvl, short session_id, bool _use_time, bool _use_thread_id);
std::string to_string() const;
std::ostream& output(std::ostream& stream) const;
};
class logger
{
public:
logger();
virtual ~logger();
inline void write(mlog_level&& level, boost::format&& format)
{
write_to_log(log_metadata(std::move(level), m_session, m_use_time, m_use_thread_id), boost::str(format));
}
inline void write(mlog_level&& level, const boost::format& format)
{
write_to_log(log_metadata(std::move(level), m_session, m_use_time, m_use_thread_id), boost::str(format));
}
inline void write(mlog_level&& level, std::string&& log_text)
{
write_to_log(log_metadata(std::move(level), m_session, m_use_time, m_use_thread_id), std::move(log_text));
}
inline void write(mlog_level&& level, const std::string& log_text)
{
write_to_log(log_metadata(std::move(level), m_session, m_use_time, m_use_thread_id), std::string(log_text));
}
//virtual void flush() = 0;
virtual void write_to_log(log_metadata&& metadata, std::string&& log_text) = 0;
template<typename T>
inline void use_thread_id(T&& value)
{
m_use_thread_id = std::forward<T>(value);
}
inline bool use_thread_id() const
{
return m_use_thread_id;
}
template<typename T>
inline void use_time(T&& value)
{
m_use_time = std::forward<T>(value);
}
inline bool use_time() const
{
return m_use_time;
}
private:
short m_session;
bool m_use_time;
bool m_use_thread_id;
};
}
#endif /* LOGGER_HPP_ */
#ifdef MLOG_NO_LIB
#include "impl/logger.hpp"
#endif
<commit_msg>Fixed a bug with clang.<commit_after>/*
* logger.hpp
*
* Created on: Aug 9, 2012
* Author: philipp
*/
#ifndef __LOGGER_HPP__
#define __LOGGER_HPP__
#include <string>
#if defined(_GLIBCXX_HAS_GTHREADS) || defined(__clang__)
#include <thread>
#define THREAD_GET_ID() std::this_thread::get_id()
#else
#include <boost/thread.hpp>
namespace std {
using boost::mutex;
using boost::recursive_mutex;
using boost::lock_guard;
using boost::condition_variable;
using boost::unique_lock;
using boost::thread;
}
#define THREAD_GET_ID() boost::this_thread::get_id()
#endif
#include <chrono>
#include <boost/format.hpp>
enum mlog_level
{
trace, debug, info, warning, error, fatal
};
namespace mlog
{
template<typename T>
inline std::string level_to_string(T&& level)
{
if(level == mlog_level::trace)
return "trace";
else if(level == mlog_level::debug)
return "debug";
else if(level == mlog_level::info)
return "info";
else if(level == mlog_level::warning)
return "warning";
else if(level == mlog_level::error)
return "error";
else
return "fatal";
}
struct log_metadata
{
//typedef std::chrono::high_resolution_clock clocks;
typedef std::chrono::system_clock clocks;
bool use_time;
bool use_thread_id;
mlog_level level;
short session_id;
std::chrono::time_point<clocks> time;
std::thread::id thread_id;
log_metadata()
:use_time(true),
use_thread_id(false),
level(info),
session_id(0)
{
}
log_metadata(mlog_level&& lvl, short session_id, bool _use_time, bool _use_thread_id);
std::string to_string() const;
std::ostream& output(std::ostream& stream) const;
};
class logger
{
public:
logger();
virtual ~logger();
inline void write(mlog_level&& level, boost::format&& format)
{
write_to_log(log_metadata(std::move(level), m_session, m_use_time, m_use_thread_id), boost::str(format));
}
inline void write(mlog_level&& level, const boost::format& format)
{
write_to_log(log_metadata(std::move(level), m_session, m_use_time, m_use_thread_id), boost::str(format));
}
inline void write(mlog_level&& level, std::string&& log_text)
{
write_to_log(log_metadata(std::move(level), m_session, m_use_time, m_use_thread_id), std::move(log_text));
}
inline void write(mlog_level&& level, const std::string& log_text)
{
write_to_log(log_metadata(std::move(level), m_session, m_use_time, m_use_thread_id), std::string(log_text));
}
//virtual void flush() = 0;
virtual void write_to_log(log_metadata&& metadata, std::string&& log_text) = 0;
template<typename T>
inline void use_thread_id(T&& value)
{
m_use_thread_id = std::forward<T>(value);
}
inline bool use_thread_id() const
{
return m_use_thread_id;
}
template<typename T>
inline void use_time(T&& value)
{
m_use_time = std::forward<T>(value);
}
inline bool use_time() const
{
return m_use_time;
}
private:
short m_session;
bool m_use_time;
bool m_use_thread_id;
};
}
#endif /* LOGGER_HPP_ */
#ifdef MLOG_NO_LIB
#include "impl/logger.hpp"
#endif
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
#include "langmem/Tokenizer.hpp"
void
assertTokenStream (std::string src, langmem::_TokenKind* tokens)
{
langmem::Tokenizer tkz;
tkz.reset();
tkz.setInputString(src);
while ((*tokens) != langmem::T_YACC_END)
{
ASSERT_EQ(*tokens, tkz.getNextToken().Kind());
++ tokens;
}
}
TEST(TokenizerTest, MainFunctionSimplest)
{
std::string src = "main (){}";
langmem::_TokenKind tokens[] = {
langmem::T_ID,
langmem::T_OP,
langmem::T_CP,
langmem::T_OPEN_BRACE,
langmem::T_CLOSE_BRACE,
langmem::T_YACC_END};
assertTokenStream(src, tokens);
}
TEST(TokenizerTest, MainFunctionWithParameterAndReturnType)
{
std::string src = "main (argc :int) -> int{}";
langmem::_TokenKind tokens[] = {
langmem::T_ID,
// Parameters
langmem::T_OP,
langmem::T_ID,
langmem::T_COLON,
langmem::T_ID,
langmem::T_CP,
// Return type
langmem::T_RARR,
langmem::T_ID,
// Block
langmem::T_OPEN_BRACE,
langmem::T_CLOSE_BRACE,
langmem::T_YACC_END};
assertTokenStream(src, tokens);
}
TEST(TokenizerTest, CallWithParameters)
{
std::string src = "fn (i :int, j :int) -> int {return i;}";
src += " main(){ var i :int = fn(1, 2); }";
langmem::_TokenKind tokens[] = {
// fn (
langmem::T_ID,
langmem::T_OP,
//i :int,
langmem::T_ID,
langmem::T_COLON,
langmem::T_ID,
langmem::T_COMMA,
//j :int
langmem::T_ID,
langmem::T_COLON,
langmem::T_ID,
// ) -> int
langmem::T_CP,
langmem::T_RARR,
langmem::T_ID,
// { return i; }
langmem::T_OPEN_BRACE,
langmem::T_RETURN,
langmem::T_ID,
langmem::T_SEMICOLON,
langmem::T_CLOSE_BRACE,
// main ()
langmem::T_ID,
langmem::T_OP,
langmem::T_CP,
// { var i :int =
langmem::T_OPEN_BRACE,
langmem::T_VAR,
langmem::T_ID,
langmem::T_COLON,
langmem::T_ID,
langmem::T_EQ,
// fn(1, 2); }
langmem::T_ID,
langmem::T_OP,
langmem::T_LITERAL_NUMBER,
langmem::T_COMMA,
langmem::T_LITERAL_NUMBER,
langmem::T_CP,
langmem::T_SEMICOLON,
langmem::T_CLOSE_BRACE,
langmem::T_YACC_END};
assertTokenStream(src, tokens);
}
<commit_msg>Add tokenizer test : function call<commit_after>#include "gtest/gtest.h"
#include "langmem/Tokenizer.hpp"
void
assertTokenStream (std::string src, langmem::_TokenKind* tokens)
{
langmem::Tokenizer tkz;
tkz.reset();
tkz.setInputString(src);
while ((*tokens) != langmem::T_YACC_END)
{
ASSERT_EQ(*tokens, tkz.getNextToken().Kind());
++ tokens;
}
}
TEST(TokenizerTest, MainFunctionSimplest)
{
std::string src = "main (){}";
langmem::_TokenKind tokens[] = {
langmem::T_ID,
langmem::T_OP,
langmem::T_CP,
langmem::T_OPEN_BRACE,
langmem::T_CLOSE_BRACE,
langmem::T_YACC_END};
assertTokenStream(src, tokens);
}
TEST(TokenizerTest, MainFunctionWithParameterAndReturnType)
{
std::string src = "main (argc :int) -> int{}";
langmem::_TokenKind tokens[] = {
langmem::T_ID,
// Parameters
langmem::T_OP,
langmem::T_ID,
langmem::T_COLON,
langmem::T_ID,
langmem::T_CP,
// Return type
langmem::T_RARR,
langmem::T_ID,
// Block
langmem::T_OPEN_BRACE,
langmem::T_CLOSE_BRACE,
langmem::T_YACC_END};
assertTokenStream(src, tokens);
}
TEST(TokenizerTest, CallWithParameters)
{
std::string src = "fn (i :int, j :int) -> int {return i;}";
src += " main(){ var i :int = fn(1, 2); }";
langmem::_TokenKind tokens[] = {
// fn (
langmem::T_ID,
langmem::T_OP,
//i :int,
langmem::T_ID,
langmem::T_COLON,
langmem::T_ID,
langmem::T_COMMA,
//j :int
langmem::T_ID,
langmem::T_COLON,
langmem::T_ID,
// ) -> int
langmem::T_CP,
langmem::T_RARR,
langmem::T_ID,
// { return i; }
langmem::T_OPEN_BRACE,
langmem::T_RETURN,
langmem::T_ID,
langmem::T_SEMICOLON,
langmem::T_CLOSE_BRACE,
// main ()
langmem::T_ID,
langmem::T_OP,
langmem::T_CP,
// { var i :int =
langmem::T_OPEN_BRACE,
langmem::T_VAR,
langmem::T_ID,
langmem::T_COLON,
langmem::T_ID,
langmem::T_EQ,
// fn(1, 2); }
langmem::T_ID,
langmem::T_OP,
langmem::T_LITERAL_NUMBER,
langmem::T_COMMA,
langmem::T_LITERAL_NUMBER,
langmem::T_CP,
langmem::T_SEMICOLON,
langmem::T_CLOSE_BRACE,
langmem::T_YACC_END};
assertTokenStream(src, tokens);
}
TEST(TokenizerTest, ObjectCall)
{
std::string src = "main () {p.some_func(1);}";
langmem::_TokenKind tokens[] = {
// main () {
langmem::T_ID,
langmem::T_OP,
langmem::T_CP,
langmem::T_OPEN_BRACE,
// p.some_func
langmem::T_ID,
langmem::T_DOT,
langmem::T_ID,
// (1)
langmem::T_OP,
langmem::T_LITERAL_NUMBER,
langmem::T_CP,
// ;}
langmem::T_SEMICOLON,
langmem::T_CLOSE_BRACE,
langmem::T_YACC_END};
assertTokenStream(src, tokens);
}
<|endoftext|> |
<commit_before>#include <SDL.h>
#include <setjmp.h>
#include "MainLoop.h"
#include "Mutex.h"
#include "ReadWriteLock.h"
#include "AuxLib.h"
#include "EventQueue.h"
#include "Options.h"
#include "LieroX.h"
#include "Cache.h"
#include "OLXCommand.h"
#include "InputEvents.h"
#include "TaskManager.h"
#include "Timer.h"
#include "DeprecatedGUI/Menu.h"
#include "SkinnedGUI/CGuiSkin.h"
#include "CServer.h"
#include "IRC.h"
#include "CrashHandler.h"
/*
Notes:
The following things need to be run on the main thread,
because of implementation details on SDL & the underlying OS,
so we cannot do much about it:
- OpenGL stuff
- SDL_Render*
- SDL events
So, this is exactly what we do in the main thread, and not much more.
Check via isMainThread(), whether you are in the main thread.
Then, there is the main game thread, where we run the game logic
itself, and also do much of the software pixel drawing, and
most other things.
We call it the gameloop thread, because the game gameloop runs in it.
Check via isGameloopThread(), whether you are in the gameloop thread.
To be able to do the software drawing in the mainloop thread,
and in parallel do the system screen drawing, we need to have two
main screen surface, which are handled by the VideoPostProcessor.
Then gameloop thread draws to the VideoPostProcessor::videoSurface().
The main thread draws the VideoPostProcessor::m_videoBufferSurface
to the screen.
*/
struct VideoHandler {
SDL_mutex* mutex;
SDL_cond* sign;
int framesInQueue;
bool videoModeReady;
VideoHandler() : mutex(NULL), sign(NULL), framesInQueue(0), videoModeReady(true) {
mutex = SDL_CreateMutex();
sign = SDL_CreateCond();
}
~VideoHandler() {
SDL_DestroyMutex(mutex); mutex = NULL;
SDL_DestroyCond(sign); sign = NULL;
}
// Runs on the main thread.
void frame() {
{
ScopedLock lock(mutex);
if(!videoModeReady) return;
SDL_CondBroadcast(sign);
if(framesInQueue > 0) framesInQueue--;
else return;
VideoPostProcessor::process();
}
VideoPostProcessor::render();
}
// Runs on the main thread.
void setVideoMode() {
bool makeFrame = false;
{
ScopedLock lock(mutex);
SetVideoMode();
videoModeReady = true;
SDL_CondBroadcast(sign);
if(framesInQueue > 0) {
framesInQueue = 0;
makeFrame = true;
VideoPostProcessor::process();
}
}
if(makeFrame)
VideoPostProcessor::render();
}
// This must not be run on the main thread.
void pushFrame() {
assert(!isMainThread());
// wait for current drawing
ScopedLock lock(mutex);
while(framesInQueue > 0)
SDL_CondWait(sign, mutex);
SDL_Event ev;
ev.type = SDL_USEREVENT;
ev.user.code = UE_DoVideoFrame;
if(SDL_PushEvent(&ev) == 0) {
framesInQueue++;
VideoPostProcessor::flipBuffers();
} else
warnings << "failed to push videoframeevent" << endl;
}
void requestSetVideoMode() {
ScopedLock lock(mutex);
SDL_Event ev;
ev.type = SDL_USEREVENT;
ev.user.code = UE_DoSetVideoMode;
if(SDL_PushEvent(&ev) == 0) {
videoModeReady = false;
while(!videoModeReady)
SDL_CondWait(sign, mutex);
}
else
warnings << "failed to push setvideomode event" << endl;
}
};
static VideoHandler videoHandler;
#ifndef WIN32
sigjmp_buf longJumpBuffer;
#endif
static SDL_Event QuitEventThreadEvent() {
SDL_Event ev;
ev.type = SDL_USEREVENT;
ev.user.code = UE_QuitEventThread;
return ev;
}
struct CoutPrint : PrintOutFct {
void print(const std::string& str) const {
printf("%s", str.c_str());
}
};
void startMainLockDetector() {
if(!tLXOptions->bUseMainLockDetector) return;
struct MainLockDetector : Action {
bool wait(Uint32 time) {
if(!tLX) return false;
AbsTime oldTime = tLX->currentTime;
for(Uint32 t = 0; t < time; t += 100) {
if(!tLX) return false;
if(game.state == Game::S_Quit) return false;
if(oldTime != tLX->currentTime) return true;
SDL_Delay(100);
}
return true;
}
Result handle() {
// We should always have tLX!=NULL here as we uninit it after the thread-shutdown now.
while(game.state != Game::S_Quit) {
AbsTime oldTime = tLX->currentTime;
if(!wait(1000)) return true;
if(!tLX) return true;
if(game.state == Game::S_Quit) return true;
if(IsWaitingForEvent()) continue;
// HINT: Comment that out and you'll find a lot of things in OLX which could be improved.
// WARNING: This is the only code here which could lead to very rare crashes.
//if(!cClient || cClient->getStatus() != NET_PLAYING) continue;
// check if the mainthread is hanging
if(oldTime == tLX->currentTime) {
warnings << "possible lock of game thread detected" << endl;
notes << "current game state: " << game.state << endl;
//OlxWriteCoreDump("mainlock");
//RaiseDebugger();
if(!wait(5*1000)) return true;
if(tLX && game.state != Game::S_Quit && oldTime == tLX->currentTime) {
hints << "Still locked after 5 seconds. Current threads:" << endl;
threadPool->dumpState(stdoutCLI());
DumpAllThreadsCallstack(CoutPrint());
hints << "Free system memory: " << (GetFreeSysMemory() / 1024) << " KB" << endl;
hints << "Cache size: " << (cCache.GetCacheSize() / 1024) << " KB" << endl;
}
else continue;
// pause for a while, don't be so hard
if(!wait(25*1000)) return true;
if(tLX && game.state != Game::S_Quit && oldTime == tLX->currentTime) {
warnings << "we still are locked after 30 seconds" << endl;
DumpAllThreadsCallstack(CoutPrint());
if(tLXOptions && tLXOptions->bFullscreen) {
notes << "we are in fullscreen, going to window mode now" << endl;
tLXOptions->bFullscreen = false;
doSetVideoModeInMainThread();
notes << "setting window mode sucessfull" << endl;
}
}
else continue;
// pause for a while, don't be so hard
if(!wait(25*1000)) return true;
if(tLX && game.state != Game::S_Quit && oldTime == tLX->currentTime) {
errors << "we still are locked after 60 seconds" << endl;
DumpAllThreadsCallstack(CoutPrint());
if(!AmIBeingDebugged()) {
errors << "aborting now" << endl;
abort();
}
}
}
}
return true;
}
};
threadPool->start(new MainLockDetector(), "main lock detector", true);
}
struct MainLoopTask : LoopTask {
enum State {
State_Startup,
State_Loop,
State_Quit
};
State state;
MainLoopTask() : state(State_Startup) {}
Result handle_Startup();
Result handle_Loop();
Result handle_Quit();
Result handleFrame();
};
// Runs on the video thread.
// Returns false on quit.
static bool handleSDLEvent(SDL_Event& ev) {
if(ev.type == SDL_USEREVENT) {
switch(ev.user.code) {
case UE_QuitEventThread:
return false;
case UE_DoVideoFrame:
videoHandler.frame();
return true;
case UE_DoSetVideoMode:
videoHandler.setVideoMode();
return true;
case UE_DoActionInMainThread:
((Action*)ev.user.data1)->handle();
delete (Action*)ev.user.data1;
return true;
case UE_NopWakeup:
// do nothing, it's just a wakeup
return true;
}
warnings << "handleSDLEvent: got unknown user event " << (int)ev.user.code << endl;
return true;
}
if( ev.type == SDL_SYSWMEVENT ) {
EvHndl_SysWmEvent_MainThread( &ev );
return true;
}
mainQueue->push(ev);
return true;
}
// Get all SDL events and push them to our event queue.
// We have to do that in the same thread where we inited the video because of SDL.
bool handleSDLEvents(bool wait) {
assert(isMainThread());
SDL_Event ev;
memset( &ev, 0, sizeof(ev) );
if(wait) {
if( SDL_WaitEvent(&ev) ) {
if(!handleSDLEvent(ev))
return false;
}
else {
notes << "error while waiting for next event" << endl;
SDL_Delay(200);
return true;
}
}
while( SDL_PollEvent(&ev) ) {
if(!handleSDLEvent(ev))
return false;
}
return true;
}
void doMainLoop() {
#ifdef SINGLETHREADED
MainLoopTask mainLoop;
while(true) {
// we handle SDL events in doVideoFrameInMainThread
if(NegResult r = mainLoop.handleFrame())
break;
}
#else
ThreadPoolItem* mainLoopThread = threadPool->start(new MainLoopTask(), "main loop", false);
startMainLockDetector();
if(!bDedicated) {
while(true) {
if(!handleSDLEvents(true))
goto quit;
}
}
quit:
threadPool->wait(mainLoopThread, NULL);
mainLoopThread = NULL;
#endif
}
// note: important to have const char* here because std::string is too dynamic, could be screwed up when returning
void SetCrashHandlerReturnPoint(const char* name) {
#ifndef WIN32
if(sigsetjmp(longJumpBuffer, true) != 0) {
hints << "returned from sigsetjmp in " << name << endl;
if(!tLXOptions) {
notes << "we already have tLXOptions uninitialised, exiting now" << endl;
exit(10);
return;
}
if(tLXOptions->bFullscreen) {
notes << "we are in fullscreen, going to window mode now" << endl;
tLXOptions->bFullscreen = false;
doSetVideoModeInMainThread();
notes << "back in window mode" << endl;
}
}
#endif
}
void doVideoFrameInMainThread() {
if(bDedicated) return;
if(isMainThread()) {
VideoPostProcessor::flipBuffers();
VideoPostProcessor::process();
VideoPostProcessor::render();
}
else
videoHandler.pushFrame();
}
void doSetVideoModeInMainThread() {
if(bDedicated) return;
if(isMainThread())
videoHandler.setVideoMode();
else
videoHandler.requestSetVideoMode();
}
void doVppOperation(Action* act) {
{
ScopedLock lock(videoHandler.mutex);
act->handle();
}
delete act;
}
void doActionInMainThread(Action* act) {
if(bDedicated) {
warnings << "doActionInMainThread cannot work correctly in dedicated mode" << endl;
// we will just put it to the main queue instead
mainQueue->push(act);
return;
}
if(isMainThread()) {
act->handle();
delete act;
}
else {
SDL_Event ev;
ev.type = SDL_USEREVENT;
ev.user.code = UE_DoActionInMainThread;
ev.user.data1 = act;
if(SDL_PushEvent(&ev) != 0) {
errors << "failed to push custom action event" << endl;
}
}
}
Result MainLoopTask::handle_Startup() {
gameloopThreadId = getCurrentThreadId();
assert(gameloopThreadId != (ThreadId)-1);
setCurThreadPriority(0.5f);
// NOTE: This code is really old and outdated.
// We might just merge that with the new code.
// Otherwise, it will never work like this because of
// missing stuff, e.g. no game.init call (which does
// also init the old menu, so we cannot simply call it
// like this right now).
if( tLXOptions->bNewSkinnedGUI )
{
// Just for test - it's not real handler yet
SkinnedGUI::cMainSkin->Load("default");
SkinnedGUI::cMainSkin->OpenLayout("test.skn");
while (game.state != Game::S_Quit) {
tLX->fDeltaTime = GetTime() - tLX->currentTime;
tLX->currentTime = GetTime();
ProcessEvents();
SkinnedGUI::cMainSkin->Frame();
}
return "quit";
}
state = State_Loop;
return true;
}
Result MainLoopTask::handle_Loop() {
if(game.state == Game::S_Quit) {
state = State_Quit;
return true;
}
game.frame();
return true;
}
Result MainLoopTask::handle_Quit() {
if(!isMainThread()) {
SDL_Event quitEv = QuitEventThreadEvent();
if(!bDedicated)
while(SDL_PushEvent(&quitEv) < 0) {}
}
gameloopThreadId = (ThreadId)-1;
return "quit";
}
Result MainLoopTask::handleFrame() {
switch(state) {
case State_Startup: return handle_Startup();
case State_Loop: return handle_Loop();
case State_Quit: return handle_Quit();
}
return "invalid state";
}
<commit_msg>more on screen update handling<commit_after>#include <SDL.h>
#include <setjmp.h>
#include "MainLoop.h"
#include "Mutex.h"
#include "ReadWriteLock.h"
#include "AuxLib.h"
#include "EventQueue.h"
#include "Options.h"
#include "LieroX.h"
#include "Cache.h"
#include "OLXCommand.h"
#include "InputEvents.h"
#include "TaskManager.h"
#include "Timer.h"
#include "DeprecatedGUI/Menu.h"
#include "SkinnedGUI/CGuiSkin.h"
#include "CServer.h"
#include "IRC.h"
#include "CrashHandler.h"
/*
Notes:
The following things need to be run on the main thread,
because of implementation details on SDL & the underlying OS,
so we cannot do much about it:
- OpenGL stuff
- SDL_Render*
- SDL events
So, this is exactly what we do in the main thread, and not much more.
Check via isMainThread(), whether you are in the main thread.
Then, there is the main game thread, where we run the game logic
itself, and also do much of the software pixel drawing, and
most other things.
We call it the gameloop thread, because the game gameloop runs in it.
Check via isGameloopThread(), whether you are in the gameloop thread.
To be able to do the software drawing in the mainloop thread,
and in parallel do the system screen drawing, we need to have two
main screen surface, which are handled by the VideoPostProcessor.
Then gameloop thread draws to the VideoPostProcessor::videoSurface().
The main thread draws the VideoPostProcessor::m_videoBufferSurface
to the screen.
*/
struct VideoHandler {
SDL_mutex* mutex;
SDL_cond* sign;
int framesInQueue;
bool videoModeReady;
VideoHandler() : mutex(NULL), sign(NULL), framesInQueue(0), videoModeReady(true) {
mutex = SDL_CreateMutex();
sign = SDL_CreateCond();
}
~VideoHandler() {
SDL_DestroyMutex(mutex); mutex = NULL;
SDL_DestroyCond(sign); sign = NULL;
}
// Runs on the main thread.
void frame() {
{
ScopedLock lock(mutex);
if(!videoModeReady) return;
SDL_CondBroadcast(sign);
if(framesInQueue > 0) framesInQueue--;
else return;
// This must be done while locked because we don't want a flipBuffers meanwhile.
VideoPostProcessor::process();
}
// This can be done unlocked, because we only access it through the main thread.
VideoPostProcessor::render();
}
// Runs on the main thread.
void doSingleDirectFrame() {
assert(isMainThread());
{
ScopedLock lock(mutex);
VideoPostProcessor::flipBuffers();
VideoPostProcessor::process();
}
VideoPostProcessor::render();
}
// Runs on the main thread.
void setVideoMode() {
bool makeFrame = false;
{
ScopedLock lock(mutex);
SetVideoMode();
videoModeReady = true;
SDL_CondBroadcast(sign);
if(framesInQueue > 0) {
framesInQueue = 0;
makeFrame = true;
// This must be done while locked because we don't want a flipBuffers meanwhile.
VideoPostProcessor::process();
}
}
if(makeFrame)
// This can be done unlocked, because we only access it through the main thread.
VideoPostProcessor::render();
}
// This must not be run on the main thread.
void pushFrame() {
assert(!isMainThread());
// wait for current drawing
ScopedLock lock(mutex);
while(framesInQueue > 0)
SDL_CondWait(sign, mutex);
SDL_Event ev;
ev.type = SDL_USEREVENT;
ev.user.code = UE_DoVideoFrame;
if(SDL_PushEvent(&ev) == 0) {
framesInQueue++;
VideoPostProcessor::flipBuffers();
} else
warnings << "failed to push videoframeevent" << endl;
}
void requestSetVideoMode() {
ScopedLock lock(mutex);
SDL_Event ev;
ev.type = SDL_USEREVENT;
ev.user.code = UE_DoSetVideoMode;
if(SDL_PushEvent(&ev) == 0) {
videoModeReady = false;
while(!videoModeReady)
SDL_CondWait(sign, mutex);
}
else
warnings << "failed to push setvideomode event" << endl;
}
};
static VideoHandler videoHandler;
#ifndef WIN32
sigjmp_buf longJumpBuffer;
#endif
static SDL_Event QuitEventThreadEvent() {
SDL_Event ev;
ev.type = SDL_USEREVENT;
ev.user.code = UE_QuitEventThread;
return ev;
}
struct CoutPrint : PrintOutFct {
void print(const std::string& str) const {
printf("%s", str.c_str());
}
};
void startMainLockDetector() {
if(!tLXOptions->bUseMainLockDetector) return;
struct MainLockDetector : Action {
bool wait(Uint32 time) {
if(!tLX) return false;
AbsTime oldTime = tLX->currentTime;
for(Uint32 t = 0; t < time; t += 100) {
if(!tLX) return false;
if(game.state == Game::S_Quit) return false;
if(oldTime != tLX->currentTime) return true;
SDL_Delay(100);
}
return true;
}
Result handle() {
// We should always have tLX!=NULL here as we uninit it after the thread-shutdown now.
while(game.state != Game::S_Quit) {
AbsTime oldTime = tLX->currentTime;
if(!wait(1000)) return true;
if(!tLX) return true;
if(game.state == Game::S_Quit) return true;
if(IsWaitingForEvent()) continue;
// HINT: Comment that out and you'll find a lot of things in OLX which could be improved.
// WARNING: This is the only code here which could lead to very rare crashes.
//if(!cClient || cClient->getStatus() != NET_PLAYING) continue;
// check if the mainthread is hanging
if(oldTime == tLX->currentTime) {
warnings << "possible lock of game thread detected" << endl;
notes << "current game state: " << game.state << endl;
//OlxWriteCoreDump("mainlock");
//RaiseDebugger();
if(!wait(5*1000)) return true;
if(tLX && game.state != Game::S_Quit && oldTime == tLX->currentTime) {
hints << "Still locked after 5 seconds. Current threads:" << endl;
threadPool->dumpState(stdoutCLI());
DumpAllThreadsCallstack(CoutPrint());
hints << "Free system memory: " << (GetFreeSysMemory() / 1024) << " KB" << endl;
hints << "Cache size: " << (cCache.GetCacheSize() / 1024) << " KB" << endl;
}
else continue;
// pause for a while, don't be so hard
if(!wait(25*1000)) return true;
if(tLX && game.state != Game::S_Quit && oldTime == tLX->currentTime) {
warnings << "we still are locked after 30 seconds" << endl;
DumpAllThreadsCallstack(CoutPrint());
if(tLXOptions && tLXOptions->bFullscreen) {
notes << "we are in fullscreen, going to window mode now" << endl;
tLXOptions->bFullscreen = false;
doSetVideoModeInMainThread();
notes << "setting window mode sucessfull" << endl;
}
}
else continue;
// pause for a while, don't be so hard
if(!wait(25*1000)) return true;
if(tLX && game.state != Game::S_Quit && oldTime == tLX->currentTime) {
errors << "we still are locked after 60 seconds" << endl;
DumpAllThreadsCallstack(CoutPrint());
if(!AmIBeingDebugged()) {
errors << "aborting now" << endl;
abort();
}
}
}
}
return true;
}
};
threadPool->start(new MainLockDetector(), "main lock detector", true);
}
struct MainLoopTask : LoopTask {
enum State {
State_Startup,
State_Loop,
State_Quit
};
State state;
MainLoopTask() : state(State_Startup) {}
Result handle_Startup();
Result handle_Loop();
Result handle_Quit();
Result handleFrame();
};
// Runs on the video thread.
// Returns false on quit.
static bool handleSDLEvent(SDL_Event& ev) {
if(ev.type == SDL_USEREVENT) {
switch(ev.user.code) {
case UE_QuitEventThread:
return false;
case UE_DoVideoFrame:
videoHandler.frame();
return true;
case UE_DoSetVideoMode:
videoHandler.setVideoMode();
return true;
case UE_DoActionInMainThread:
((Action*)ev.user.data1)->handle();
delete (Action*)ev.user.data1;
return true;
case UE_NopWakeup:
// do nothing, it's just a wakeup
return true;
}
warnings << "handleSDLEvent: got unknown user event " << (int)ev.user.code << endl;
return true;
}
if( ev.type == SDL_SYSWMEVENT ) {
EvHndl_SysWmEvent_MainThread( &ev );
return true;
}
mainQueue->push(ev);
return true;
}
// Get all SDL events and push them to our event queue.
// We have to do that in the same thread where we inited the video because of SDL.
bool handleSDLEvents(bool wait) {
assert(isMainThread());
SDL_Event ev;
memset( &ev, 0, sizeof(ev) );
if(wait) {
if( SDL_WaitEvent(&ev) ) {
if(!handleSDLEvent(ev))
return false;
}
else {
notes << "error while waiting for next event" << endl;
SDL_Delay(200);
return true;
}
}
while( SDL_PollEvent(&ev) ) {
if(!handleSDLEvent(ev))
return false;
}
return true;
}
void doMainLoop() {
#ifdef SINGLETHREADED
MainLoopTask mainLoop;
while(true) {
// we handle SDL events in doVideoFrameInMainThread
if(NegResult r = mainLoop.handleFrame())
break;
}
#else
ThreadPoolItem* mainLoopThread = threadPool->start(new MainLoopTask(), "main loop", false);
startMainLockDetector();
if(!bDedicated) {
while(true) {
if(!handleSDLEvents(true))
goto quit;
}
}
quit:
threadPool->wait(mainLoopThread, NULL);
mainLoopThread = NULL;
#endif
}
// note: important to have const char* here because std::string is too dynamic, could be screwed up when returning
void SetCrashHandlerReturnPoint(const char* name) {
#ifndef WIN32
if(sigsetjmp(longJumpBuffer, true) != 0) {
hints << "returned from sigsetjmp in " << name << endl;
if(!tLXOptions) {
notes << "we already have tLXOptions uninitialised, exiting now" << endl;
exit(10);
return;
}
if(tLXOptions->bFullscreen) {
notes << "we are in fullscreen, going to window mode now" << endl;
tLXOptions->bFullscreen = false;
doSetVideoModeInMainThread();
notes << "back in window mode" << endl;
}
}
#endif
}
void doVideoFrameInMainThread() {
if(bDedicated) return;
if(isMainThread())
videoHandler.doSingleDirectFrame();
else
videoHandler.pushFrame();
}
void doSetVideoModeInMainThread() {
if(bDedicated) return;
if(isMainThread())
videoHandler.setVideoMode();
else
videoHandler.requestSetVideoMode();
}
void doVppOperation(Action* act) {
{
ScopedLock lock(videoHandler.mutex);
act->handle();
}
delete act;
}
void doActionInMainThread(Action* act) {
if(bDedicated) {
warnings << "doActionInMainThread cannot work correctly in dedicated mode" << endl;
// we will just put it to the main queue instead
mainQueue->push(act);
return;
}
if(isMainThread()) {
act->handle();
delete act;
}
else {
SDL_Event ev;
ev.type = SDL_USEREVENT;
ev.user.code = UE_DoActionInMainThread;
ev.user.data1 = act;
if(SDL_PushEvent(&ev) != 0) {
errors << "failed to push custom action event" << endl;
}
}
}
Result MainLoopTask::handle_Startup() {
gameloopThreadId = getCurrentThreadId();
assert(gameloopThreadId != (ThreadId)-1);
setCurThreadPriority(0.5f);
// NOTE: This code is really old and outdated.
// We might just merge that with the new code.
// Otherwise, it will never work like this because of
// missing stuff, e.g. no game.init call (which does
// also init the old menu, so we cannot simply call it
// like this right now).
if( tLXOptions->bNewSkinnedGUI )
{
// Just for test - it's not real handler yet
SkinnedGUI::cMainSkin->Load("default");
SkinnedGUI::cMainSkin->OpenLayout("test.skn");
while (game.state != Game::S_Quit) {
tLX->fDeltaTime = GetTime() - tLX->currentTime;
tLX->currentTime = GetTime();
ProcessEvents();
SkinnedGUI::cMainSkin->Frame();
}
return "quit";
}
state = State_Loop;
return true;
}
Result MainLoopTask::handle_Loop() {
if(game.state == Game::S_Quit) {
state = State_Quit;
return true;
}
game.frame();
return true;
}
Result MainLoopTask::handle_Quit() {
if(!isMainThread()) {
SDL_Event quitEv = QuitEventThreadEvent();
if(!bDedicated)
while(SDL_PushEvent(&quitEv) < 0) {}
}
gameloopThreadId = (ThreadId)-1;
return "quit";
}
Result MainLoopTask::handleFrame() {
switch(state) {
case State_Startup: return handle_Startup();
case State_Loop: return handle_Loop();
case State_Quit: return handle_Quit();
}
return "invalid state";
}
<|endoftext|> |
<commit_before>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2010-2011 Alessandro Tasora
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
///////////////////////////////////////////////////
//
// ChLcpSimplexSolver.cpp
//
// ***OBSOLETE****
//
// file for CHRONO HYPEROCTANT LCP solver
//
// ------------------------------------------------
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
#include "ChLcpSimplexSolver.h"
#include "core/ChSpmatrix.h"
namespace chrono
{
ChLcpSimplexSolver::ChLcpSimplexSolver()
{
MC = new ChSparseMatrix(30,30); // at least as big as 30x30
X = new ChMatrixDynamic<>(30,1); // at least as big as 30x1
B = new ChMatrixDynamic<>(30,1); // at least as big as 30x1
unilaterals = 0;
truncation_step=0;
}
ChLcpSimplexSolver::~ChLcpSimplexSolver()
{
if (MC) delete MC; MC=0;
if (X) delete X; X=0;
if (B) delete B; B=0;
if (unilaterals) delete[]unilaterals;
}
double ChLcpSimplexSolver::Solve(
ChLcpSystemDescriptor& sysd ///< system description with constraints and variables
)
{
std::vector<ChLcpConstraint*>& mconstraints = sysd.GetConstraintsList();
std::vector<ChLcpVariables*>& mvariables = sysd.GetVariablesList();
double maxviolation = 0.;
// --
// Count active linear constraints..
int n_c=0;
int n_d=0;
for (unsigned int ic = 0; ic< mconstraints.size(); ic++)
{
if (mconstraints[ic]->IsActive())
if (mconstraints[ic]->IsLinear())
if (mconstraints[ic]->IsUnilateral())
n_d++;
else
n_c++;
}
// --
// Count active variables, by scanning through all variable blocks..
int n_q=0;
for (unsigned int iv = 0; iv< mvariables.size(); iv++)
{
if (mvariables[iv]->IsActive())
{
mvariables[iv]->SetOffset(n_q); // also store offsets in state and MC matrix
n_q += mvariables[iv]->Get_ndof();
}
}
if (n_q==0) return 0;
int n_docs = n_c + n_d;
int n_vars = n_q + n_docs;
// --
// Reset and resize (if needed) auxiliary vectors
MC->Reset(n_vars,n_vars); // fast! Reset() method does not realloc if size doesn't change
B->Reset(n_vars,1);
X->Reset(n_vars,1);
if (unilaterals != 0)
{delete[]unilaterals; unilaterals = 0;}
if (n_d > 0)
{
unilaterals = new ChUnilateralData[n_d];
}
// --
// Fills the MC matrix and B vector, to pass to the sparse LCP simplex solver.
// The original problem, stated as
// | M -Cq'|*|q|- | f|= |0| , c>=0, l>=0, l*c=0;
// | Cq 0 | |l| |-b| |c|
// will be used with a small modification as:
// | M Cq'|*| q|- | f|= |0| , c>=0, l>=0, l*c=0;
// | Cq 0 | |-l| |-b| |c|
// so that it uses a symmetric MC matrix (the LDL factorization at each
// pivot is happier:)
// .. fills M submasses and 'f' part of B
int s_q=0;
for (unsigned int iv = 0; iv< mvariables.size(); iv++)
{
if (mvariables[iv]->IsActive())
{
mvariables[iv]->Build_M(*MC, s_q, s_q); // .. fills MC (M part)
B->PasteMatrix(&mvariables[iv]->Get_fb(),s_q, 0); // .. fills B (f part)
s_q += mvariables[iv]->Get_ndof();
}
}
// .. fills M jacobians (only lower part) and 'b' part of B
int s_c=0;
int s_d=0;
for (unsigned int ic = 0; ic< mconstraints.size(); ic++)
{
if (mconstraints[ic]->IsActive())
if (mconstraints[ic]->IsLinear())
if (mconstraints[ic]->IsUnilateral())
{
mconstraints[ic]->Build_Cq (*MC, n_q + n_c + s_d);// .. fills MC (Cq part)
mconstraints[ic]->Build_CqT(*MC, n_q + n_c + s_d);// .. fills MC (Cq' part)
B->SetElement(n_q + n_c + s_d, 0,
-mconstraints[ic]->Get_b_i() ); // .. fills B (c part)
unilaterals[s_d].status = CONSTR_UNILATERAL_OFF;
s_d++;
}
else
{
mconstraints[ic]->Build_Cq (*MC, n_q + s_c);
mconstraints[ic]->Build_CqT(*MC, n_q + s_c);
B->SetElement(n_q + s_c, 0,
-mconstraints[ic]->Get_b_i() );
s_c++;
}
}
// --
// Solve the LCP
MC->SolveLCP(B, X,
n_c, n_d,
truncation_step,
false,
unilaterals);
// --
// Update results into variable-interface objects
s_q=0;
for (unsigned int iv = 0; iv< mvariables.size(); iv++)
{
if (mvariables[iv]->IsActive())
{
mvariables[iv]->Get_qb().PasteClippedMatrix(X,
s_q,0,
mvariables[iv]->Get_ndof(),1,
0,0);
s_q += mvariables[iv]->Get_ndof();
}
}
// --
// Update results into constraint-interface objects
s_c=0;
s_d=0;
for (unsigned int ic = 0; ic< mconstraints.size(); ic++)
{
if (mconstraints[ic]->IsActive())
if (mconstraints[ic]->IsLinear())
if (mconstraints[ic]->IsUnilateral())
{ //(change sign of multipliers!)
mconstraints[ic]->Set_l_i( -X->GetElement(n_q + n_c + s_d , 0));
s_d++;
}
else
{ //(change sign of multipliers!)
mconstraints[ic]->Set_l_i( -X->GetElement(n_q + s_c , 0));
s_c++;
}
}
return maxviolation;
}
} // END_OF_NAMESPACE____
<commit_msg>Added support for stiffness matrices (non-diagonal M) in the direct solver.<commit_after>//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2010-2011 Alessandro Tasora
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
///////////////////////////////////////////////////
//
// ChLcpSimplexSolver.cpp
//
// ***OBSOLETE****
//
// file for CHRONO HYPEROCTANT LCP solver
//
// ------------------------------------------------
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
#include "ChLcpSimplexSolver.h"
#include "core/ChSpmatrix.h"
namespace chrono
{
ChLcpSimplexSolver::ChLcpSimplexSolver()
{
MC = new ChSparseMatrix(30,30); // at least as big as 30x30
X = new ChMatrixDynamic<>(30,1); // at least as big as 30x1
B = new ChMatrixDynamic<>(30,1); // at least as big as 30x1
unilaterals = 0;
truncation_step=0;
}
ChLcpSimplexSolver::~ChLcpSimplexSolver()
{
if (MC) delete MC; MC=0;
if (X) delete X; X=0;
if (B) delete B; B=0;
if (unilaterals) delete[]unilaterals;
}
double ChLcpSimplexSolver::Solve(
ChLcpSystemDescriptor& sysd ///< system description with constraints and variables
)
{
std::vector<ChLcpConstraint*>& mconstraints = sysd.GetConstraintsList();
std::vector<ChLcpVariables*>& mvariables = sysd.GetVariablesList();
std::vector<ChLcpKblock*>& mstiffness = sysd.GetKblocksList();
double maxviolation = 0.;
// --
// Count active linear constraints..
int n_c=0;
int n_d=0;
for (unsigned int ic = 0; ic< mconstraints.size(); ic++)
{
if (mconstraints[ic]->IsActive())
if (mconstraints[ic]->IsLinear())
if (mconstraints[ic]->IsUnilateral())
n_d++;
else
n_c++;
}
// --
// Count active variables, by scanning through all variable blocks..
int n_q=0;
for (unsigned int iv = 0; iv< mvariables.size(); iv++)
{
if (mvariables[iv]->IsActive())
{
mvariables[iv]->SetOffset(n_q); // also store offsets in state and MC matrix
n_q += mvariables[iv]->Get_ndof();
}
}
if (n_q==0) return 0;
int n_docs = n_c + n_d;
int n_vars = n_q + n_docs;
int nv = sysd.CountActiveVariables(); // also sets offsets
int nc = sysd.CountActiveConstraints();
int nx = nv+nc; // total scalar unknowns, in x vector for full KKT system Z*x-d=0
// --
// Reset and resize (if needed) auxiliary vectors
MC->Reset(n_vars,n_vars); // fast! Reset() method does not realloc if size doesn't change
B->Reset(n_vars,1);
X->Reset(n_vars,1);
if (unilaterals != 0)
{delete[]unilaterals; unilaterals = 0;}
if (n_d > 0)
{
unilaterals = new ChUnilateralData[n_d];
}
// --
// Fills the MC matrix and B vector, to pass to the sparse LCP simplex solver.
// The original problem, stated as
// | M -Cq'|*|q|- | f|= |0| , c>=0, l>=0, l*c=0;
// | Cq 0 | |l| |-b| |c|
// will be used with a small modification as:
// | M Cq'|*| q|- | f|= |0| , c>=0, l>=0, l*c=0;
// | Cq 0 | |-l| |-b| |c|
// so that it uses a symmetric MC matrix (the LDL factorization at each
// pivot is happier:)
// .. fills M submasses and 'f' part of B
int s_q=0;
for (unsigned int iv = 0; iv< mvariables.size(); iv++)
{
if (mvariables[iv]->IsActive())
{
mvariables[iv]->Build_M(*MC, s_q, s_q); // .. fills MC (M part)
B->PasteMatrix(&mvariables[iv]->Get_fb(),s_q, 0); // .. fills B (f part)
s_q += mvariables[iv]->Get_ndof();
}
}
// ..if some stiffness / hessian matrix has been added to M ,
// also add it to the sparse M
int s_k=0;
for (unsigned int ik = 0; ik< mstiffness.size(); ik++)
{
mstiffness[ik]->Build_K(*MC, true);
}
// .. fills M jacobians (only lower part) and 'b' part of B
int s_c=0;
int s_d=0;
for (unsigned int ic = 0; ic< mconstraints.size(); ic++)
{
if (mconstraints[ic]->IsActive())
if (mconstraints[ic]->IsLinear())
if (mconstraints[ic]->IsUnilateral())
{
mconstraints[ic]->Build_Cq (*MC, n_q + n_c + s_d);// .. fills MC (Cq part)
mconstraints[ic]->Build_CqT(*MC, n_q + n_c + s_d);// .. fills MC (Cq' part)
B->SetElement(n_q + n_c + s_d, 0,
-mconstraints[ic]->Get_b_i() ); // .. fills B (c part)
unilaterals[s_d].status = CONSTR_UNILATERAL_OFF;
s_d++;
}
else
{
mconstraints[ic]->Build_Cq (*MC, n_q + s_c);
mconstraints[ic]->Build_CqT(*MC, n_q + s_c);
B->SetElement(n_q + s_c, 0,
-mconstraints[ic]->Get_b_i() );
s_c++;
}
}
// --
// Solve the LCP
MC->SolveLCP(B, X,
n_c, n_d,
truncation_step,
false,
unilaterals);
// --
// Update results into variable-interface objects
s_q=0;
for (unsigned int iv = 0; iv< mvariables.size(); iv++)
{
if (mvariables[iv]->IsActive())
{
mvariables[iv]->Get_qb().PasteClippedMatrix(X,
s_q,0,
mvariables[iv]->Get_ndof(),1,
0,0);
s_q += mvariables[iv]->Get_ndof();
}
}
// --
// Update results into constraint-interface objects
s_c=0;
s_d=0;
for (unsigned int ic = 0; ic< mconstraints.size(); ic++)
{
if (mconstraints[ic]->IsActive())
if (mconstraints[ic]->IsLinear())
if (mconstraints[ic]->IsUnilateral())
{ //(change sign of multipliers!)
mconstraints[ic]->Set_l_i( -X->GetElement(n_q + n_c + s_d , 0));
s_d++;
}
else
{ //(change sign of multipliers!)
mconstraints[ic]->Set_l_i( -X->GetElement(n_q + s_c , 0));
s_c++;
}
}
return maxviolation;
}
} // END_OF_NAMESPACE____
<|endoftext|> |
<commit_before>#ifndef NANOCV_DOT_H
#define NANOCV_DOT_H
namespace ncv
{
///
/// \brief general dot-product
///
template
<
typename tscalar,
typename tsize
>
tscalar dot(const tscalar* vec1, const tscalar* vec2, tsize size)
{
tscalar sum = 0;
for (auto i = 0; i < size; i ++)
{
sum += vec1[i] * vec2[i];
}
return sum;
}
///
/// \brief general dot-product (unrolled by 4)
///
template
<
typename tscalar,
typename tsize
>
tscalar dot_unroll4(const tscalar* vec1, const tscalar* vec2, tsize size)
{
const tsize size4 = size & tsize(~3);
tscalar sum = 0;
for (auto i = 0; i < size4; i += 4)
{
sum += vec1[i + 0] * vec2[i + 0] +
vec1[i + 1] * vec2[i + 1] +
vec1[i + 2] * vec2[i + 2] +
vec1[i + 3] * vec2[i + 3];
}
for (auto i = size4; i < size; i ++)
{
sum += vec1[i] * vec2[i];
}
return sum;
}
///
/// \brief general dot-product (unrolled by 8)
///
template
<
typename tscalar,
typename tsize
>
tscalar dot_unroll8(const tscalar* vec1, const tscalar* vec2, tsize size)
{
const tsize size8 = size & tsize(~7);
const tsize size4 = size & tsize(~4);
tscalar sum = 0;
for (auto i = 0; i < size8; i += 8)
{
sum += vec1[i + 0] * vec2[i + 0] +
vec1[i + 1] * vec2[i + 1] +
vec1[i + 2] * vec2[i + 2] +
vec1[i + 3] * vec2[i + 3] +
vec1[i + 4] * vec2[i + 4] +
vec1[i + 5] * vec2[i + 5] +
vec1[i + 6] * vec2[i + 6] +
vec1[i + 7] * vec2[i + 7];
}
for (auto i = size8; i < size4; i += 4)
{
sum += vec1[i + 0] * vec2[i + 0] +
vec1[i + 1] * vec2[i + 1] +
vec1[i + 2] * vec2[i + 2] +
vec1[i + 3] * vec2[i + 3];
}
for (auto i = size4; i < size; i ++)
{
sum += vec1[i] * vec2[i];
}
return sum;
}
///
/// \brief fixed-size dot-product
///
template
<
typename tscalar,
int tsize
>
tscalar dot(const tscalar* vec1, const tscalar* vec2, int)
{
tscalar sum = 0;
for (auto i = 0; i < tsize; i ++)
{
sum += vec1[i] * vec2[i];
}
return sum;
}
}
#endif // NANOCV_DOT_H
<commit_msg>fix dot produc<commit_after>#ifndef NANOCV_DOT_H
#define NANOCV_DOT_H
namespace ncv
{
///
/// \brief general dot-product
///
template
<
typename tscalar,
typename tsize
>
tscalar dot(const tscalar* vec1, const tscalar* vec2, tsize size)
{
tscalar sum = 0;
for (auto i = 0; i < size; i ++)
{
sum += vec1[i] * vec2[i];
}
return sum;
}
///
/// \brief general dot-product (unrolled by 4)
///
template
<
typename tscalar,
typename tsize
>
tscalar dot_unroll4(const tscalar* vec1, const tscalar* vec2, tsize size)
{
const tsize size4 = size & tsize(~3);
tscalar sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0;
for (auto i = 0; i < size4; i += 4)
{
sum0 += vec1[i + 0] * vec2[i + 0];
sum1 += vec1[i + 1] * vec2[i + 1];
sum2 += vec1[i + 2] * vec2[i + 2];
sum3 += vec1[i + 3] * vec2[i + 3];
}
for (auto i = size4; i < size; i ++)
{
sum0 += vec1[i] * vec2[i];
}
return (sum0 + sum1) + (sum2 + sum3);
}
///
/// \brief general dot-product (unrolled by 8)
///
template
<
typename tscalar,
typename tsize
>
tscalar dot_unroll8(const tscalar* vec1, const tscalar* vec2, tsize size)
{
const tsize size8 = size & tsize(~7);
const tsize size4 = size & tsize(~3);
tscalar sum0 = 0, sum1 = 0, sum2 = 0, sum3 = 0, sum4 = 0, sum5 = 0, sum6 = 0, sum7 = 0;
for (auto i = 0; i < size8; i += 8)
{
sum0 += vec1[i + 0] * vec2[i + 0];
sum1 += vec1[i + 1] * vec2[i + 1];
sum2 += vec1[i + 2] * vec2[i + 2];
sum3 += vec1[i + 3] * vec2[i + 3];
sum4 += vec1[i + 4] * vec2[i + 4];
sum5 += vec1[i + 5] * vec2[i + 5];
sum6 += vec1[i + 6] * vec2[i + 6];
sum7 += vec1[i + 7] * vec2[i + 7];
}
for (auto i = size8; i < size4; i += 4)
{
sum0 += vec1[i + 0] * vec2[i + 0];
sum1 += vec1[i + 1] * vec2[i + 1];
sum2 += vec1[i + 2] * vec2[i + 2];
sum3 += vec1[i + 3] * vec2[i + 3];
}
for (auto i = size4; i < size; i ++)
{
sum0 += vec1[i] * vec2[i];
}
return (sum0 + sum1) + (sum2 + sum3) + (sum4 + sum5) + (sum6 + sum7);
}
///
/// \brief fixed-size dot-product
///
template
<
typename tscalar,
int tsize
>
tscalar dot(const tscalar* vec1, const tscalar* vec2, int)
{
tscalar sum = 0;
for (auto i = 0; i < tsize; i ++)
{
sum += vec1[i] * vec2[i];
}
return sum;
}
}
#endif // NANOCV_DOT_H
<|endoftext|> |
<commit_before>#include "Odometry.h"
#include <cstdint>
#include "WProgram.h"
#include "Device.h"
#include "config.h"
namespace tamproxy {
Odometer::Odometer(Encoder& lEncoder, Encoder& rEncoder, Gyro& gyro, float alpha)
: _encL(lEncoder),
_encR(rEncoder),
_gyro(gyro),
_alpha(alpha),
_lastTime(micros()),
_lastMeanEnc(0),
_gyroTot(0) { }
std::vector<uint8_t> Odometer::handleRequest(std::vector<uint8_t> &request)
{
if (request[0] == ODOMETER_READ_CODE) {
if (request.size() != 1) return {REQUEST_LENGTH_INVALID_CODE};
// here be dragons
float vals[] = {_angle, _x, _y};
uint32_t val = *reinterpret_cast<uint32_t*>(&_angle);
return {
static_cast<uint8_t>(val>>24),
static_cast<uint8_t>(val>>16),
static_cast<uint8_t>(val>>8),
static_cast<uint8_t>(val)
};
}
else {
return {REQUEST_BODY_INVALID_CODE};
}
}
void Odometer::update()
{
const float ticksPerRev = 3200.0;
const float wheelDiam = 3.78125;
const float baseWidth = 15.3; //inches
uint32_t lEncVal = _encL.read();
uint32_t rEncVal = _encR.read();
// be careful about overflow here
int32_t diffEnc = lEncVal - rEncVal;
uint32_t meanEnc = rEncVal + diffEnc/2;
bool ok;
float gyroRead = _gyro.read(ok);
if(!ok) return;
_gyroTot += gyroRead*(micros()-_lastTime) / 1e6;
float encAngle = (diffEnc/ticksPerRev)*wheelDiam/(baseWidth / 2);
_angle = _alpha*_gyroTot + (1-_alpha)*encAngle;
float dr = static_cast<int32_t>(meanEnc - _lastMeanEnc)/ticksPerRev*wheelDiam*M_PI;
_x += dr * cos(_angle);
_y += dr * sin(_angle);
_lastTime = micros();
}
}<commit_msg>Add missing update<commit_after>#include "Odometry.h"
#include <cstdint>
#include "WProgram.h"
#include "Device.h"
#include "config.h"
namespace tamproxy {
Odometer::Odometer(Encoder& lEncoder, Encoder& rEncoder, Gyro& gyro, float alpha)
: _encL(lEncoder),
_encR(rEncoder),
_gyro(gyro),
_alpha(alpha),
_lastTime(micros()),
_lastMeanEnc(0),
_gyroTot(0) { }
std::vector<uint8_t> Odometer::handleRequest(std::vector<uint8_t> &request)
{
if (request[0] == ODOMETER_READ_CODE) {
if (request.size() != 1) return {REQUEST_LENGTH_INVALID_CODE};
// here be dragons
float vals[] = {_angle, _x, _y};
uint32_t val = *reinterpret_cast<uint32_t*>(&_angle);
return {
static_cast<uint8_t>(val>>24),
static_cast<uint8_t>(val>>16),
static_cast<uint8_t>(val>>8),
static_cast<uint8_t>(val)
};
}
else {
return {REQUEST_BODY_INVALID_CODE};
}
}
void Odometer::update()
{
const float ticksPerRev = 3200.0;
const float wheelDiam = 3.78125;
const float baseWidth = 15.3; //inches
uint32_t lEncVal = _encL.read();
uint32_t rEncVal = _encR.read();
// be careful about overflow here
int32_t diffEnc = lEncVal - rEncVal;
uint32_t meanEnc = rEncVal + diffEnc/2;
bool ok;
float gyroRead = _gyro.read(ok);
if(!ok) return;
_gyroTot += gyroRead*(micros()-_lastTime) / 1e6;
float encAngle = (diffEnc/ticksPerRev)*wheelDiam/(baseWidth / 2);
_angle = _alpha*_gyroTot + (1-_alpha)*encAngle;
float dr = static_cast<int32_t>(meanEnc - _lastMeanEnc)/ticksPerRev*wheelDiam*M_PI;
_x += dr * cos(_angle);
_y += dr * sin(_angle);
_lastTime = micros();
_lastMeanEnc = meanEnc;
}
}<|endoftext|> |
<commit_before>#include "DirectedGraph.hh"
#include "Edge.hh"
#include "EdgeType.hh"
#include "Vertex.hh"
using namespace std;
template <typename V>
unsigned int DirectedGraph<V>::addEdge(EdgeType type, V distance, unsigned int start, unsigned int end) {
Edge<V> e = Edge<V>(this->edges_nb_, start, end, type, distance);
this->edges_nb_++;
if (start >= this->vertices_nb_ || end >= this->vertices_nb_)
return -1;
adjacency_[start].second.push_back(e.id());
edges_.push_back(e);
return e.id();
}
template <typename V>
unsigned int DirectedGraph<V>::addVertex(string name, pair<double, double> coordinates) {
Vertex v = Vertex(name, coordinates);
adjacency_.push_back(make_pair(v, vector<unsigned int>()));
return ++(this->vertices_nb_);
}
template <typename V>
Edge<V> DirectedGraph<V>::getEdge(unsigned int id) {
// if (id >= this->edges_nb_)
// return;
return edges_[id];
}
template <typename V>
Vertex DirectedGraph<V>::getVertex(unsigned int id) {
// if (id >= adjacency_.size())
// return;
return adjacency_[id].first;
}
template <typename V>
vector<Edge<V>*> DirectedGraph<V>::outgoingEdges(unsigned int id) {
// if (id >= adjacency_.size())
// return;
vector<Edge<V>*> edges(adjacency_[id].second.size());
int j(0);
for (auto i : adjacency_[id].second)
edges[j++] = &edges_[i];
return edges;
}
template <typename V>
vector<Vertex*> DirectedGraph<V>::adjacentVertices(unsigned int id) {
// if (id >= adjacency_.size())
// return;
vector<Vertex*> vertices;
vector<bool> inserted(this->vertices_nb_, false);
for (auto i : adjacency_[id].second) {
Edge<V> edge = edges_[i];
int other_id = edge.getOtherEnd(id);
if (!inserted[other_id]) {
inserted[other_id] = true;
vertices.push_back(&adjacency_[other_id].first);
}
}
return vertices;
}
template <typename V>
DirectedGraph<V>::~DirectedGraph() {
for (auto v : adjacency_)
v.second.clear();
adjacency_.clear();
edges_.clear();
}
// Types of directed graphs that can be instantiated
template class DirectedGraph<double>;
template class DirectedGraph<float>;
template class DirectedGraph<int>;
<commit_msg>Vertices have an id<commit_after>#include "DirectedGraph.hh"
#include "Edge.hh"
#include "EdgeType.hh"
#include "Vertex.hh"
using namespace std;
template <typename V>
unsigned int DirectedGraph<V>::addEdge(EdgeType type, V distance, unsigned int start, unsigned int end) {
Edge<V> e = Edge<V>(this->edges_nb_, start, end, type, distance);
this->edges_nb_++;
if (start >= this->vertices_nb_ || end >= this->vertices_nb_)
return -1;
adjacency_[start].second.push_back(e.id());
edges_.push_back(e);
return e.id();
}
template <typename V>
unsigned int DirectedGraph<V>::addVertex(string name, pair<double, double> coordinates) {
Vertex v = Vertex(this->vertices_nb_, name, coordinates);
this->vertices_nb_++;
adjacency_.push_back(make_pair(v, vector<unsigned int>()));
return v.id();
}
template <typename V>
Edge<V> DirectedGraph<V>::getEdge(unsigned int id) {
// if (id >= this->edges_nb_)
// return;
return edges_[id];
}
template <typename V>
Vertex DirectedGraph<V>::getVertex(unsigned int id) {
// if (id >= adjacency_.size())
// return;
return adjacency_[id].first;
}
template <typename V>
vector<Edge<V>*> DirectedGraph<V>::outgoingEdges(unsigned int id) {
// if (id >= adjacency_.size())
// return;
vector<Edge<V>*> edges(adjacency_[id].second.size());
int j(0);
for (auto i : adjacency_[id].second)
edges[j++] = &edges_[i];
return edges;
}
template <typename V>
vector<Vertex*> DirectedGraph<V>::adjacentVertices(unsigned int id) {
// if (id >= adjacency_.size())
// return;
vector<Vertex*> vertices;
vector<bool> inserted(this->vertices_nb_, false);
for (auto i : adjacency_[id].second) {
Edge<V> edge = edges_[i];
int other_id = edge.getOtherEnd(id);
if (!inserted[other_id]) {
inserted[other_id] = true;
vertices.push_back(&adjacency_[other_id].first);
}
}
return vertices;
}
template <typename V>
DirectedGraph<V>::~DirectedGraph() {
for (auto v : adjacency_)
v.second.clear();
adjacency_.clear();
edges_.clear();
}
// Types of directed graphs that can be instantiated
template class DirectedGraph<double>;
template class DirectedGraph<float>;
template class DirectedGraph<int>;
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file rcd_load.C
/// @brief Run and manage the RCD_LOAD engine
///
// *HWP HWP Owner: Jacob Harvey <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/rcd_load.H>
#include <lib/dimm/rcd_load_ddr4.H>
#include <generic/memory/lib/utils/find.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
///
/// @brief Perform the rcd_load operations - TARGET_TYPE_MCBIST specialization
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCBIST>
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode rcd_load<TARGET_TYPE_MCBIST>( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
// A vector of CCS instructions. We'll ask the targets to fill it, and then we'll execute it
ccs::program<TARGET_TYPE_MCBIST> l_program;
uint8_t l_sim = 0;
// Clear the initial delays. This will force the CCS engine to recompute the delay based on the
// instructions in the CCS instruction vector
l_program.iv_poll.iv_initial_delay = 0;
l_program.iv_poll.iv_initial_sim_delay = 0;
FAPI_TRY(mss::is_simulation(l_sim));
for ( const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target) )
{
for ( const auto& d : mss::find_targets<TARGET_TYPE_DIMM>(p) )
{
// CKE needs to be LOW before running the RCW sequence
// So we use the power down entry command to achieve this
if(!l_sim)
{
l_program.iv_instructions.push_back( ccs::pde_command<TARGET_TYPE_MCBIST>() );
}
FAPI_DBG("rcd load for %s", mss::c_str(d));
FAPI_TRY( perform_rcd_load(d, l_program.iv_instructions),
"Failed perform_rcd_load() for %s", mss::c_str(d) );
}// dimms
// We have to configure the CCS engine to let it know which port these instructions are
// going out (or whether it's broadcast ...) so lets execute the instructions we presently
// have so that we kind of do this by port
FAPI_TRY( ccs::execute(i_target, l_program, p),
"Failed to execute ccs for %s", mss::c_str(p) );
}// ports
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - unknown DIMM case
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to (unused)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
// If we're here, we have a problem. The DIMM kind (type and/or generation) wasn't known
// to our dispatcher. We have a DIMM plugged in we don't know how to deal with.
FAPI_ASSERT(false,
fapi2::MSS_UNKNOWN_DIMM()
.set_DIMM_TYPE(l_type)
.set_DRAM_GEN(l_gen)
.set_DIMM_IN_ERROR(i_target),
"Unable to perform rcd load on %s: unknown type (%d) or generation (%d)",
mss::c_str(i_target), l_type, l_gen);
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - RDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_RDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting rdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst),
"Failed rcd_load_ddr4() for %s", mss::c_str(i_target) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - LRDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_LRDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting lrdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - start the dispatcher
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
return perform_rcd_load_dispatch<FORCE_DISPATCH>(dimm_kind( l_type, l_gen ), i_target, i_inst);
fapi_try_exit:
FAPI_ERR("couldn't get dimm type, dram gen: %s", mss::c_str(i_target));
return fapi2::current_err;
}
} // namespace
<commit_msg>Adds STR entry and exit functions to support NVDIMM<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file rcd_load.C
/// @brief Run and manage the RCD_LOAD engine
///
// *HWP HWP Owner: Jacob Harvey <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/rcd_load.H>
#include <lib/dimm/rcd_load_ddr4.H>
#include <generic/memory/lib/utils/find.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
///
/// @brief Perform the rcd_load operations - TARGET_TYPE_MCA specialization
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCA>
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode rcd_load<TARGET_TYPE_MCA>( const fapi2::Target<TARGET_TYPE_MCA>& i_target )
{
const auto& l_mcbist = mss::find_target<TARGET_TYPE_MCBIST>(i_target);
// A vector of CCS instructions. We'll ask the targets to fill it, and then we'll execute it
ccs::program<TARGET_TYPE_MCBIST> l_program;
uint8_t l_sim = 0;
// Clear the initial delays. This will force the CCS engine to recompute the delay based on the
// instructions in the CCS instruction vector
l_program.iv_poll.iv_initial_delay = 0;
l_program.iv_poll.iv_initial_sim_delay = 0;
FAPI_TRY(mss::is_simulation(l_sim));
for ( const auto& d : mss::find_targets<TARGET_TYPE_DIMM>(i_target) )
{
// CKE needs to be LOW before running the RCW sequence
// So we use the power down entry command to achieve this
if(!l_sim)
{
l_program.iv_instructions.push_back( ccs::pde_command<TARGET_TYPE_MCBIST>() );
}
FAPI_DBG("rcd load for %s", mss::c_str(d));
FAPI_TRY( perform_rcd_load(d, l_program.iv_instructions),
"Failed perform_rcd_load() for %s", mss::c_str(d) );
}// dimms
// We have to configure the CCS engine to let it know which port these instructions are
// going out (or whether it's broadcast ...) so lets execute the instructions we presently
// have so that we kind of do this by port
FAPI_TRY( ccs::execute(l_mcbist, l_program, i_target),
"Failed to execute ccs for %s", mss::c_str(i_target) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - TARGET_TYPE_MCBIST specialization
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCBIST>
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode rcd_load<TARGET_TYPE_MCBIST>( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
for ( const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target) )
{
FAPI_TRY( rcd_load(p) );
}
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - unknown DIMM case
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to (unused)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
// If we're here, we have a problem. The DIMM kind (type and/or generation) wasn't known
// to our dispatcher. We have a DIMM plugged in we don't know how to deal with.
FAPI_ASSERT(false,
fapi2::MSS_UNKNOWN_DIMM()
.set_DIMM_TYPE(l_type)
.set_DRAM_GEN(l_gen)
.set_DIMM_IN_ERROR(i_target),
"Unable to perform rcd load on %s: unknown type (%d) or generation (%d)",
mss::c_str(i_target), l_type, l_gen);
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - RDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_RDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting rdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst),
"Failed rcd_load_ddr4() for %s", mss::c_str(i_target) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - LRDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_LRDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting lrdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - start the dispatcher
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
return perform_rcd_load_dispatch<FORCE_DISPATCH>(dimm_kind( l_type, l_gen ), i_target, i_inst);
fapi_try_exit:
FAPI_ERR("couldn't get dimm type, dram gen: %s", mss::c_str(i_target));
return fapi2::current_err;
}
} // namespace
<|endoftext|> |
<commit_before>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This file is part of libebml.
**
** 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
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
\author Moritz Bunkus <moritz @ bunkus.org>
*/
#include <array>
#include <cassert>
#include "ebml/EbmlUInteger.h"
namespace libebml {
EbmlUInteger::EbmlUInteger()
:EbmlElement(DEFAULT_UINT_SIZE, false)
{}
EbmlUInteger::EbmlUInteger(std::uint64_t aDefaultValue)
:EbmlElement(DEFAULT_UINT_SIZE, true), Value(aDefaultValue), DefaultValue(aDefaultValue)
{
SetDefaultIsSet();
}
void EbmlUInteger::SetDefaultValue(std::uint64_t aValue)
{
assert(!DefaultISset());
DefaultValue = aValue;
SetDefaultIsSet();
}
std::uint64_t EbmlUInteger::DefaultVal() const
{
assert(DefaultISset());
return DefaultValue;
}
EbmlUInteger::operator std::uint8_t() const {return static_cast<std::uint8_t>(Value); }
EbmlUInteger::operator std::uint16_t() const {return static_cast<std::uint16_t>(Value);}
EbmlUInteger::operator std::uint32_t() const {return static_cast<std::uint32_t>(Value);}
EbmlUInteger::operator std::uint64_t() const {return Value;}
std::uint64_t EbmlUInteger::GetValue() const {return Value;}
EbmlUInteger & EbmlUInteger::SetValue(std::uint64_t NewValue) {
return *this = NewValue;
}
/*!
\todo handle exception on errors
*/
filepos_t EbmlUInteger::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
std::array<binary, 8> FinalData; // we don't handle more than 64 bits integers
if (GetSizeLength() > 8)
return 0; // integer bigger coded on more than 64 bits are not supported
std::uint64_t TempValue = Value;
for (unsigned int i=0; i<GetSize();i++) {
FinalData.at(GetSize()-i-1) = TempValue & 0xFF;
TempValue >>= 8;
}
output.writeFully(FinalData.data(),GetSize());
return GetSize();
}
std::uint64_t EbmlUInteger::UpdateSize(bool bWithDefault, bool /* bForceRender */)
{
if (!bWithDefault && IsDefaultValue())
return 0;
if (Value <= 0xFF) {
SetSize_(1);
} else if (Value <= 0xFFFF) {
SetSize_(2);
} else if (Value <= 0xFFFFFF) {
SetSize_(3);
} else if (Value <= 0xFFFFFFFF) {
SetSize_(4);
} else if (Value <= EBML_PRETTYLONGINT(0xFFFFFFFFFF)) {
SetSize_(5);
} else if (Value <= EBML_PRETTYLONGINT(0xFFFFFFFFFFFF)) {
SetSize_(6);
} else if (Value <= EBML_PRETTYLONGINT(0xFFFFFFFFFFFFFF)) {
SetSize_(7);
} else {
SetSize_(8);
}
if (GetDefaultSize() > GetSize()) {
SetSize_(GetDefaultSize());
}
return GetSize();
}
filepos_t EbmlUInteger::ReadData(IOCallback & input, ScopeMode ReadFully)
{
if (ReadFully == SCOPE_NO_DATA)
return GetSize();
if (GetSize() > 8) {
// impossible to read, skip it
input.setFilePointer(GetSize(), seek_current);
return GetSize();
}
std::array<binary, 8> Buffer;
input.readFully(Buffer.data(), GetSize());
Value = 0;
for (unsigned int i=0; i<GetSize(); i++) {
Value <<= 8;
Value |= Buffer.at(i);
}
SetValueIsSet();
return GetSize();
}
bool EbmlUInteger::IsSmallerThan(const EbmlElement *Cmp) const
{
if (EbmlId(*this) == EbmlId(*Cmp))
return this->Value < static_cast<const EbmlUInteger *>(Cmp)->Value;
return false;
}
} // namespace libebml
<commit_msg>replace EBML_PRETTYLONGINT with proper C++ integer literal<commit_after>/****************************************************************************
** libebml : parse EBML files, see http://embl.sourceforge.net/
**
** <file/class description>
**
** Copyright (C) 2002-2010 Steve Lhomme. All rights reserved.
**
** This file is part of libebml.
**
** 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
**
** See http://www.gnu.org/licenses/lgpl-2.1.html for LGPL licensing information.
**
** Contact [email protected] if any conditions of this licensing are
** not clear to you.
**
**********************************************************************/
/*!
\file
\version \$Id$
\author Steve Lhomme <robux4 @ users.sf.net>
\author Moritz Bunkus <moritz @ bunkus.org>
*/
#include <array>
#include <cassert>
#include "ebml/EbmlUInteger.h"
namespace libebml {
EbmlUInteger::EbmlUInteger()
:EbmlElement(DEFAULT_UINT_SIZE, false)
{}
EbmlUInteger::EbmlUInteger(std::uint64_t aDefaultValue)
:EbmlElement(DEFAULT_UINT_SIZE, true), Value(aDefaultValue), DefaultValue(aDefaultValue)
{
SetDefaultIsSet();
}
void EbmlUInteger::SetDefaultValue(std::uint64_t aValue)
{
assert(!DefaultISset());
DefaultValue = aValue;
SetDefaultIsSet();
}
std::uint64_t EbmlUInteger::DefaultVal() const
{
assert(DefaultISset());
return DefaultValue;
}
EbmlUInteger::operator std::uint8_t() const {return static_cast<std::uint8_t>(Value); }
EbmlUInteger::operator std::uint16_t() const {return static_cast<std::uint16_t>(Value);}
EbmlUInteger::operator std::uint32_t() const {return static_cast<std::uint32_t>(Value);}
EbmlUInteger::operator std::uint64_t() const {return Value;}
std::uint64_t EbmlUInteger::GetValue() const {return Value;}
EbmlUInteger & EbmlUInteger::SetValue(std::uint64_t NewValue) {
return *this = NewValue;
}
/*!
\todo handle exception on errors
*/
filepos_t EbmlUInteger::RenderData(IOCallback & output, bool /* bForceRender */, bool /* bWithDefault */)
{
std::array<binary, 8> FinalData; // we don't handle more than 64 bits integers
if (GetSizeLength() > 8)
return 0; // integer bigger coded on more than 64 bits are not supported
std::uint64_t TempValue = Value;
for (unsigned int i=0; i<GetSize();i++) {
FinalData.at(GetSize()-i-1) = TempValue & 0xFF;
TempValue >>= 8;
}
output.writeFully(FinalData.data(),GetSize());
return GetSize();
}
std::uint64_t EbmlUInteger::UpdateSize(bool bWithDefault, bool /* bForceRender */)
{
if (!bWithDefault && IsDefaultValue())
return 0;
if (Value <= 0xFF) {
SetSize_(1);
} else if (Value <= 0xFFFF) {
SetSize_(2);
} else if (Value <= 0xFFFFFF) {
SetSize_(3);
} else if (Value <= 0xFFFFFFFF) {
SetSize_(4);
} else if (Value <= 0xFFFFFFFFFFLL) {
SetSize_(5);
} else if (Value <= 0xFFFFFFFFFFFFLL) {
SetSize_(6);
} else if (Value <= 0xFFFFFFFFFFFFFFLL) {
SetSize_(7);
} else {
SetSize_(8);
}
if (GetDefaultSize() > GetSize()) {
SetSize_(GetDefaultSize());
}
return GetSize();
}
filepos_t EbmlUInteger::ReadData(IOCallback & input, ScopeMode ReadFully)
{
if (ReadFully == SCOPE_NO_DATA)
return GetSize();
if (GetSize() > 8) {
// impossible to read, skip it
input.setFilePointer(GetSize(), seek_current);
return GetSize();
}
std::array<binary, 8> Buffer;
input.readFully(Buffer.data(), GetSize());
Value = 0;
for (unsigned int i=0; i<GetSize(); i++) {
Value <<= 8;
Value |= Buffer.at(i);
}
SetValueIsSet();
return GetSize();
}
bool EbmlUInteger::IsSmallerThan(const EbmlElement *Cmp) const
{
if (EbmlId(*this) == EbmlId(*Cmp))
return this->Value < static_cast<const EbmlUInteger *>(Cmp)->Value;
return false;
}
} // namespace libebml
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file rcd_load.C
/// @brief Run and manage the RCD_LOAD engine
///
// *HWP HWP Owner: Jacob Harvey <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/rcd_load.H>
#include <lib/dimm/rcd_load_ddr4.H>
#include <generic/memory/lib/utils/find.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
///
/// @brief Perform the rcd_load operations - TARGET_TYPE_MCBIST specialization
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCBIST>
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode rcd_load<TARGET_TYPE_MCBIST>( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
// A vector of CCS instructions. We'll ask the targets to fill it, and then we'll execute it
ccs::program<TARGET_TYPE_MCBIST> l_program;
// Clear the initial delays. This will force the CCS engine to recompute the delay based on the
// instructions in the CCS instruction vector
l_program.iv_poll.iv_initial_delay = 0;
l_program.iv_poll.iv_initial_sim_delay = 0;
for ( const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target) )
{
for ( const auto& d : mss::find_targets<TARGET_TYPE_DIMM>(p) )
{
// CKE needs to be LOW before running the RCW sequence
// So we use the power down entry command to achieve this
l_program.iv_instructions.push_back( ccs::pde_command<TARGET_TYPE_MCBIST>() );
FAPI_DBG("rcd load for %s", mss::c_str(d));
FAPI_TRY( perform_rcd_load(d, l_program.iv_instructions),
"Failed perform_rcd_load() for %s", mss::c_str(d) );
}// dimms
// We have to configure the CCS engine to let it know which port these instructions are
// going out (or whether it's broadcast ...) so lets execute the instructions we presently
// have so that we kind of do this by port
FAPI_TRY( ccs::execute(i_target, l_program, p),
"Failed to execute ccs for %s", mss::c_str(p) );
}// ports
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - unknown DIMM case
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to (unused)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
// If we're here, we have a problem. The DIMM kind (type and/or generation) wasn't known
// to our dispatcher. We have a DIMM plugged in we don't know how to deal with.
FAPI_ASSERT(false,
fapi2::MSS_UNKNOWN_DIMM()
.set_DIMM_TYPE(l_type)
.set_DRAM_GEN(l_gen)
.set_DIMM_IN_ERROR(i_target),
"Unable to perform rcd load on %s: unknown type (%d) or generation (%d)",
mss::c_str(i_target), l_type, l_gen);
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - RDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_RDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting rdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst),
"Failed rcd_load_ddr4() for %s", mss::c_str(i_target) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - LRDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_LRDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting lrdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - start the dispatcher
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
return perform_rcd_load_dispatch<FORCE_DISPATCH>(dimm_kind( l_type, l_gen ), i_target, i_inst);
fapi_try_exit:
FAPI_ERR("couldn't get dimm type, dram gen: %s", mss::c_str(i_target));
return fapi2::current_err;
}
} // namespace
<commit_msg>Fix sim problems on awan<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/rcd_load.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file rcd_load.C
/// @brief Run and manage the RCD_LOAD engine
///
// *HWP HWP Owner: Jacob Harvey <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: FSP:HB
#include <fapi2.H>
#include <mss.H>
#include <lib/dimm/rcd_load.H>
#include <lib/dimm/rcd_load_ddr4.H>
#include <generic/memory/lib/utils/find.H>
using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_MCS;
using fapi2::TARGET_TYPE_DIMM;
using fapi2::FAPI2_RC_SUCCESS;
namespace mss
{
///
/// @brief Perform the rcd_load operations - TARGET_TYPE_MCBIST specialization
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_MCBIST>
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode rcd_load<TARGET_TYPE_MCBIST>( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
// A vector of CCS instructions. We'll ask the targets to fill it, and then we'll execute it
ccs::program<TARGET_TYPE_MCBIST> l_program;
uint8_t l_sim = 0;
// Clear the initial delays. This will force the CCS engine to recompute the delay based on the
// instructions in the CCS instruction vector
l_program.iv_poll.iv_initial_delay = 0;
l_program.iv_poll.iv_initial_sim_delay = 0;
FAPI_TRY(mss::is_simulation(l_sim));
for ( const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target) )
{
for ( const auto& d : mss::find_targets<TARGET_TYPE_DIMM>(p) )
{
// CKE needs to be LOW before running the RCW sequence
// So we use the power down entry command to achieve this
if(!l_sim)
{
l_program.iv_instructions.push_back( ccs::pde_command<TARGET_TYPE_MCBIST>() );
}
FAPI_DBG("rcd load for %s", mss::c_str(d));
FAPI_TRY( perform_rcd_load(d, l_program.iv_instructions),
"Failed perform_rcd_load() for %s", mss::c_str(d) );
}// dimms
// We have to configure the CCS engine to let it know which port these instructions are
// going out (or whether it's broadcast ...) so lets execute the instructions we presently
// have so that we kind of do this by port
FAPI_TRY( ccs::execute(i_target, l_program, p),
"Failed to execute ccs for %s", mss::c_str(p) );
}// ports
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - unknown DIMM case
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to (unused)
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<DEFAULT_KIND>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
// If we're here, we have a problem. The DIMM kind (type and/or generation) wasn't known
// to our dispatcher. We have a DIMM plugged in we don't know how to deal with.
FAPI_ASSERT(false,
fapi2::MSS_UNKNOWN_DIMM()
.set_DIMM_TYPE(l_type)
.set_DRAM_GEN(l_gen)
.set_DIMM_IN_ERROR(i_target),
"Unable to perform rcd load on %s: unknown type (%d) or generation (%d)",
mss::c_str(i_target), l_type, l_gen);
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - RDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_RDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting rdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst),
"Failed rcd_load_ddr4() for %s", mss::c_str(i_target) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - LRDIMM DDR4
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<KIND_LRDIMM_DDR4>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
FAPI_DBG("perform rcd_load for %s [expecting lrdimm (ddr4)]", mss::c_str(i_target));
FAPI_TRY( rcd_load_ddr4(i_target, i_inst) );
fapi_try_exit:
return fapi2::current_err;
}
///
/// @brief Perform the rcd_load operations - start the dispatcher
/// @param[in] i_target, a fapi2::Target<TARGET_TYPE_DIMM>
/// @param[in] a vector of CCS instructions we should add to
/// @return FAPI2_RC_SUCCESS if and only if ok
///
template<>
fapi2::ReturnCode perform_rcd_load<FORCE_DISPATCH>( const fapi2::Target<TARGET_TYPE_DIMM>& i_target,
std::vector< ccs::instruction_t<TARGET_TYPE_MCBIST> >& i_inst)
{
uint8_t l_type = 0;
uint8_t l_gen = 0;
FAPI_TRY( mss::eff_dimm_type(i_target, l_type) );
FAPI_TRY( mss::eff_dram_gen(i_target, l_gen) );
return perform_rcd_load_dispatch<FORCE_DISPATCH>(dimm_kind( l_type, l_gen ), i_target, i_inst);
fapi_try_exit:
FAPI_ERR("couldn't get dimm type, dram gen: %s", mss::c_str(i_target));
return fapi2::current_err;
}
} // namespace
<|endoftext|> |
<commit_before>/// Timestamps.
// Stores a monotonic* time value with (theoretical) microseconds resolution. Timestamps can be compared with each other and simple arithmetic is supported.
// Note: Timestamp values are only monotonic as long as the systems's clock is monotonic as well (and not, e.g. set back).
// Note: Timestamps are UTC (Coordinated Universal Time) based.
// @module timestamp
#include "Timestamp.h"
#include "DynamicAny.h"
#include <ctime>
int luaopen_poco_timestamp(lua_State* L)
{
int rv = 0;
if (LuaPoco::loadMetatables(L))
{
struct LuaPoco::UserdataMethod methods[] =
{
{ "new", LuaPoco::TimestampUserdata::Timestamp },
{ "__call", LuaPoco::TimestampUserdata::Timestamp },
{ "fromEpoch", LuaPoco::TimestampUserdata::TimestampFromEpoch },
{ "fromUTC", LuaPoco::TimestampUserdata::TimestampFromUtc },
{ NULL, NULL}
};
lua_createtable(L, 0, 1);
setMetatableFunctions(L, methods);
// lua_pushvalue(L, -1);
// lua_setfield(L, -2, "__index");
lua_pushvalue(L, -1);
lua_setmetatable(L, -2);
rv = 1;
}
else
{
lua_pushnil(L);
lua_pushstring(L, "failed to create required poco metatables");
rv = 2;
}
return rv;
}
namespace LuaPoco
{
const char* POCO_TIMESTAMP_METATABLE_NAME = "Poco.Timestamp.metatable";
TimestampUserdata::TimestampUserdata() :
mTimestamp()
{
}
TimestampUserdata::TimestampUserdata(Poco::Int64 tv) :
mTimestamp(tv)
{
}
TimestampUserdata::TimestampUserdata(const Poco::Timestamp& ts) :
mTimestamp(ts)
{
}
TimestampUserdata::~TimestampUserdata()
{
}
bool TimestampUserdata::copyToState(lua_State* L)
{
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata(mTimestamp);
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
return true;
}
// register metatable for this class
bool TimestampUserdata::registerTimestamp(lua_State* L)
{
struct UserdataMethod methods[] =
{
{ "__gc", metamethod__gc },
{ "__tostring", metamethod__tostring },
{ "__add", metamethod__add },
{ "__sub", metamethod__sub },
{ "__eq", metamethod__eq },
{ "__lt", metamethod__lt },
{ "__le", metamethod__le },
{ "elapsed", elapsed },
{ "epochMicroseconds", epochMicroseconds },
{ "epochTime", epochTime },
{ "isElapsed", isElapsed },
{ "update", update },
{ "utcTime", utcTime },
{ NULL, NULL}
};
setupUserdataMetatable(L, POCO_TIMESTAMP_METATABLE_NAME, methods);
return true;
}
// standalone functions that create a TimestampUserdata
/// Constructs a new timestamp userdata from epoch value.
// @int epoch value used to create timestamp.
// @return userdata or nil. (error)
// @return error message.
// @function fromEpoch
int TimestampUserdata::TimestampFromEpoch(lua_State* L)
{
int rv = 0;
std::time_t val = luaL_checkinteger(L, 1);
try
{
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud))
TimestampUserdata(Poco::Timestamp::fromEpochTime(val));
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
/// Constructs a new timestamp userdata from UTC value.
// @int utc value used to create timestamp.
// @return userdata or nil. (error)
// @return error message.
// @function fromEpoch
int TimestampUserdata::TimestampFromUtc(lua_State* L)
{
int rv = 0;
Poco::Int64 val = 0;
DynamicAnyUserdata* daud = checkPrivateUserdata<DynamicAnyUserdata>(L, 1);
try
{
daud->mDynamicAny.convert(val);
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata(val);
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
// Lua constructor
/// Constructs a new timestamp userdata from current time.
// @return userdata or nil. (error)
// @return error message.
// @function new
int TimestampUserdata::Timestamp(lua_State* L)
{
int rv = 0;
try
{
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata();
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
///
// @type timestamp
int TimestampUserdata::metamethod__tostring(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
lua_pushfstring(L, "Poco.Timestamp (%p)", static_cast<void*>(tsud));
return 1;
}
int TimestampUserdata::metamethod__add(lua_State* L)
{
int rv = 0;
int tsIndex = 1;
int otherIndex = 2;
if (!lua_isuserdata(L, 1) || !lua_isuserdata(L, 2))
{
lua_pushnil(L);
lua_pushfstring(L, "Poco.Timestamp and Poco.DynamicAny required for __add");
return 2;
}
lua_getmetatable(L, 1);
luaL_getmetatable(L, "Poco.Timestamp.metatable");
if (!lua_rawequal(L, -1, -2))
{
tsIndex = 2;
otherIndex = 1;
}
lua_pop(L, 2);
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, tsIndex);
DynamicAnyUserdata* daud = checkPrivateUserdata<DynamicAnyUserdata>(L, otherIndex);
try
{
Poco::Int64 val;
daud->mDynamicAny.convert(val);
Poco::Timestamp newTs;
newTs = tsud->mTimestamp + val;
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata(newTs);
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
int TimestampUserdata::metamethod__sub(lua_State* L)
{
int rv = 0;
int tsIndex = 1;
int otherIndex = 2;
if (!lua_isuserdata(L, 1) || !lua_isuserdata(L, 2))
{
lua_pushnil(L);
lua_pushfstring(L, "Poco.Timestamp and Poco.DynamicAny required for __sub");
return 2;
}
lua_getmetatable(L, 1);
luaL_getmetatable(L, "Poco.Timestamp.metatable");
if (!lua_rawequal(L, -1, -2))
{
tsIndex = 2;
otherIndex = 1;
}
lua_pop(L, 2);
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, tsIndex);
DynamicAnyUserdata* daud = checkPrivateUserdata<DynamicAnyUserdata>(L, otherIndex);
try
{
Poco::Int64 val;
daud->mDynamicAny.convert(val);
Poco::Timestamp newTs;
if (tsIndex == 1)
newTs = tsud->mTimestamp - val;
else
newTs = val - tsud->mTimestamp;
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata(newTs);
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
int TimestampUserdata::metamethod__lt(lua_State* L)
{
TimestampUserdata* tsudLhs = checkPrivateUserdata<TimestampUserdata>(L, 1);
TimestampUserdata* tsudRhs = checkPrivateUserdata<TimestampUserdata>(L, 2);
bool result = tsudLhs->mTimestamp < tsudRhs->mTimestamp;
lua_pushboolean(L, result);
return 1;
}
int TimestampUserdata::metamethod__eq(lua_State* L)
{
TimestampUserdata* tsudRhs = checkPrivateUserdata<TimestampUserdata>(L, 1);
TimestampUserdata* tsudLhs = checkPrivateUserdata<TimestampUserdata>(L, 2);
bool result = tsudLhs->mTimestamp == tsudRhs->mTimestamp;
lua_pushboolean(L, result);
return 1;
}
int TimestampUserdata::metamethod__le(lua_State* L)
{
TimestampUserdata* tsudRhs = checkPrivateUserdata<TimestampUserdata>(L, 1);
TimestampUserdata* tsudLhs = checkPrivateUserdata<TimestampUserdata>(L, 2);
bool result = tsudLhs->mTimestamp <= tsudRhs->mTimestamp;
lua_pushboolean(L, result);
return 1;
}
// userdata methods
/// Get time elapsed since time denoted by timestamp in microseconds.
// The value returned is stored within a dynamicany userdata as an Int64.
// @see dynamicany
// @return dynamicany userdata or nil. (error)
// @return error message.
// @function elapsed
int TimestampUserdata::elapsed(lua_State* L)
{
int rv = 0;
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
Poco::Int64 elapsed = tsud->mTimestamp.elapsed();
try
{
DynamicAnyUserdata* daud = new(lua_newuserdata(L, sizeof *daud)) DynamicAnyUserdata(elapsed);
setupPocoUserdata(L, daud, POCO_DYNAMICANY_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
/// Get the timestamp expressed in microseconds since the Unix epoch, midnight, January 1, 1970.
// The value returned is stored within a dynamicany userdata as an Int64.
// @see dynamicany
// @return dynamicany userdata or nil. (error)
// @return error message.
// @function epochMicroseconds
int TimestampUserdata::epochMicroseconds(lua_State* L)
{
int rv = 0;
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
Poco::Int64 epochMs = tsud->mTimestamp.epochMicroseconds();
try
{
DynamicAnyUserdata* daud = new(lua_newuserdata(L, sizeof *daud)) DynamicAnyUserdata(epochMs);
setupPocoUserdata(L, daud, POCO_DYNAMICANY_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
/// Gets the timestamp expressed in time_t (a Lua number). time_t base time is midnight, January 1, 1970. Resolution is one second.
// The value returned is stored within a dynamicany userdata as an Int64.
// @see dynamicany
// @return dynamicany userdata or nil. (error)
// @return error message.
// @function epochTime
int TimestampUserdata::epochTime(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
// Lua 5.1 and 5.2 represent os.time() values as lua_Numbers.
lua_Number epoch = static_cast<lua_Number>(tsud->mTimestamp.epochTime());
lua_pushnumber(L, epoch);
return 1;
}
/// Returns true if and only if the given interval (in microseconds) has passed since the time denoted by the timestamp.
// @int interval time duration in microseconds to check.
// @return boolean
// @function isElapsed
int TimestampUserdata::isElapsed(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
Poco::Int64 interval = 0;
if (lua_isnumber(L, 2))
interval = luaL_checkinteger(L, 2);
else
{
DynamicAnyUserdata* daud = checkPrivateUserdata<DynamicAnyUserdata>(L, 2);
try
{
daud->mDynamicAny.convert(interval);
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
return lua_error(L);
}
catch (...)
{
pushUnknownException(L);
return lua_error(L);
}
}
int elapsed = tsud->mTimestamp.isElapsed(interval);
lua_pushboolean(L, elapsed);
return 1;
}
/// Gets the resolution in units per second. Since the timestamp has microsecond resolution, the returned value is always 1000000.
// @return number
// @function resolution
int TimestampUserdata::resolution(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
lua_Number res = tsud->mTimestamp.resolution();
lua_pushnumber(L, res);
return 1;
}
int TimestampUserdata::update(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
tsud->mTimestamp.update();
return 0;
}
/// Gets the timestamp expressed in UTC-based time. UTC base time is midnight, October 15, 1582. Resolution is 100 nanoseconds.
// The value returned is stored within a dynamicany userdata as an Int64.
// @see dynamicany
// @return dynamicany userdata or nil. (error)
// @return error message.
// @function utcTime
int TimestampUserdata::utcTime(lua_State* L)
{
int rv = 0;
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
Poco::DynamicAny val = tsud->mTimestamp.utcTime();
try
{
DynamicAnyUserdata* daud = new(lua_newuserdata(L, sizeof *daud)) DynamicAnyUserdata(val);
setupPocoUserdata(L, daud, POCO_DYNAMICANY_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
} // LuaPoco
<commit_msg>fix Timestamp module for poco 1.6<commit_after>/// Timestamps.
// Stores a monotonic* time value with (theoretical) microseconds resolution. Timestamps can be compared with each other and simple arithmetic is supported.
// Note: Timestamp values are only monotonic as long as the systems's clock is monotonic as well (and not, e.g. set back).
// Note: Timestamps are UTC (Coordinated Universal Time) based.
// @module timestamp
#include "Timestamp.h"
#include "DynamicAny.h"
#include <ctime>
int luaopen_poco_timestamp(lua_State* L)
{
int rv = 0;
if (LuaPoco::loadMetatables(L))
{
struct LuaPoco::UserdataMethod methods[] =
{
{ "new", LuaPoco::TimestampUserdata::Timestamp },
{ "__call", LuaPoco::TimestampUserdata::Timestamp },
{ "fromEpoch", LuaPoco::TimestampUserdata::TimestampFromEpoch },
{ "fromUTC", LuaPoco::TimestampUserdata::TimestampFromUtc },
{ NULL, NULL}
};
lua_createtable(L, 0, 1);
setMetatableFunctions(L, methods);
// lua_pushvalue(L, -1);
// lua_setfield(L, -2, "__index");
lua_pushvalue(L, -1);
lua_setmetatable(L, -2);
rv = 1;
}
else
{
lua_pushnil(L);
lua_pushstring(L, "failed to create required poco metatables");
rv = 2;
}
return rv;
}
namespace LuaPoco
{
const char* POCO_TIMESTAMP_METATABLE_NAME = "Poco.Timestamp.metatable";
TimestampUserdata::TimestampUserdata() :
mTimestamp()
{
}
TimestampUserdata::TimestampUserdata(Poco::Int64 tv) :
mTimestamp(tv)
{
}
TimestampUserdata::TimestampUserdata(const Poco::Timestamp& ts) :
mTimestamp(ts)
{
}
TimestampUserdata::~TimestampUserdata()
{
}
bool TimestampUserdata::copyToState(lua_State* L)
{
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata(mTimestamp);
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
return true;
}
// register metatable for this class
bool TimestampUserdata::registerTimestamp(lua_State* L)
{
struct UserdataMethod methods[] =
{
{ "__gc", metamethod__gc },
{ "__tostring", metamethod__tostring },
{ "__add", metamethod__add },
{ "__sub", metamethod__sub },
{ "__eq", metamethod__eq },
{ "__lt", metamethod__lt },
{ "__le", metamethod__le },
{ "elapsed", elapsed },
{ "epochMicroseconds", epochMicroseconds },
{ "epochTime", epochTime },
{ "isElapsed", isElapsed },
{ "update", update },
{ "utcTime", utcTime },
{ NULL, NULL}
};
setupUserdataMetatable(L, POCO_TIMESTAMP_METATABLE_NAME, methods);
return true;
}
// standalone functions that create a TimestampUserdata
/// Constructs a new timestamp userdata from epoch value.
// @int epoch value used to create timestamp.
// @return userdata or nil. (error)
// @return error message.
// @function fromEpoch
int TimestampUserdata::TimestampFromEpoch(lua_State* L)
{
int rv = 0;
std::time_t val = luaL_checkinteger(L, 1);
try
{
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud))
TimestampUserdata(Poco::Timestamp::fromEpochTime(val));
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
/// Constructs a new timestamp userdata from UTC value.
// @int utc value used to create timestamp.
// @return userdata or nil. (error)
// @return error message.
// @function fromEpoch
int TimestampUserdata::TimestampFromUtc(lua_State* L)
{
int rv = 0;
Poco::Int64 val = 0;
DynamicAnyUserdata* daud = checkPrivateUserdata<DynamicAnyUserdata>(L, 1);
try
{
daud->mDynamicAny.convert(val);
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata(val);
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
// Lua constructor
/// Constructs a new timestamp userdata from current time.
// @return userdata or nil. (error)
// @return error message.
// @function new
int TimestampUserdata::Timestamp(lua_State* L)
{
int rv = 0;
try
{
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata();
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
///
// @type timestamp
int TimestampUserdata::metamethod__tostring(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
lua_pushfstring(L, "Poco.Timestamp (%p)", static_cast<void*>(tsud));
return 1;
}
int TimestampUserdata::metamethod__add(lua_State* L)
{
int rv = 0;
int tsIndex = 1;
int otherIndex = 2;
if (!lua_isuserdata(L, 1) || !lua_isuserdata(L, 2))
{
lua_pushnil(L);
lua_pushfstring(L, "Poco.Timestamp and Poco.DynamicAny required for __add");
return 2;
}
lua_getmetatable(L, 1);
luaL_getmetatable(L, "Poco.Timestamp.metatable");
if (!lua_rawequal(L, -1, -2))
{
tsIndex = 2;
otherIndex = 1;
}
lua_pop(L, 2);
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, tsIndex);
DynamicAnyUserdata* daud = checkPrivateUserdata<DynamicAnyUserdata>(L, otherIndex);
try
{
Poco::Int64 val;
daud->mDynamicAny.convert(val);
Poco::Timestamp newTs;
newTs = tsud->mTimestamp + val;
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata(newTs);
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
int TimestampUserdata::metamethod__sub(lua_State* L)
{
int rv = 0;
int tsIndex = 1;
int otherIndex = 2;
if (!lua_isuserdata(L, 1) || !lua_isuserdata(L, 2))
return luaL_error(L, "Poco.Timestamp and Poco.DynamicAny required for __sub");
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, tsIndex);
DynamicAnyUserdata* daud = checkPrivateUserdata<DynamicAnyUserdata>(L, otherIndex);
try
{
Poco::Timestamp::TimeDiff val;
daud->mDynamicAny.convert(val);
Poco::Timestamp newTs;
newTs = tsud->mTimestamp - val;
TimestampUserdata* tsud = new(lua_newuserdata(L, sizeof *tsud)) TimestampUserdata(newTs);
setupPocoUserdata(L, tsud, POCO_TIMESTAMP_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
int TimestampUserdata::metamethod__lt(lua_State* L)
{
TimestampUserdata* tsudLhs = checkPrivateUserdata<TimestampUserdata>(L, 1);
TimestampUserdata* tsudRhs = checkPrivateUserdata<TimestampUserdata>(L, 2);
bool result = tsudLhs->mTimestamp < tsudRhs->mTimestamp;
lua_pushboolean(L, result);
return 1;
}
int TimestampUserdata::metamethod__eq(lua_State* L)
{
TimestampUserdata* tsudRhs = checkPrivateUserdata<TimestampUserdata>(L, 1);
TimestampUserdata* tsudLhs = checkPrivateUserdata<TimestampUserdata>(L, 2);
bool result = tsudLhs->mTimestamp == tsudRhs->mTimestamp;
lua_pushboolean(L, result);
return 1;
}
int TimestampUserdata::metamethod__le(lua_State* L)
{
TimestampUserdata* tsudRhs = checkPrivateUserdata<TimestampUserdata>(L, 1);
TimestampUserdata* tsudLhs = checkPrivateUserdata<TimestampUserdata>(L, 2);
bool result = tsudLhs->mTimestamp <= tsudRhs->mTimestamp;
lua_pushboolean(L, result);
return 1;
}
// userdata methods
/// Get time elapsed since time denoted by timestamp in microseconds.
// The value returned is stored within a dynamicany userdata as an Int64.
// @see dynamicany
// @return dynamicany userdata or nil. (error)
// @return error message.
// @function elapsed
int TimestampUserdata::elapsed(lua_State* L)
{
int rv = 0;
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
Poco::Int64 elapsed = tsud->mTimestamp.elapsed();
try
{
DynamicAnyUserdata* daud = new(lua_newuserdata(L, sizeof *daud)) DynamicAnyUserdata(elapsed);
setupPocoUserdata(L, daud, POCO_DYNAMICANY_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
/// Get the timestamp expressed in microseconds since the Unix epoch, midnight, January 1, 1970.
// The value returned is stored within a dynamicany userdata as an Int64.
// @see dynamicany
// @return dynamicany userdata or nil. (error)
// @return error message.
// @function epochMicroseconds
int TimestampUserdata::epochMicroseconds(lua_State* L)
{
int rv = 0;
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
Poco::Int64 epochMs = tsud->mTimestamp.epochMicroseconds();
try
{
DynamicAnyUserdata* daud = new(lua_newuserdata(L, sizeof *daud)) DynamicAnyUserdata(epochMs);
setupPocoUserdata(L, daud, POCO_DYNAMICANY_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
/// Gets the timestamp expressed in time_t (a Lua number). time_t base time is midnight, January 1, 1970. Resolution is one second.
// The value returned is stored within a dynamicany userdata as an Int64.
// @see dynamicany
// @return dynamicany userdata or nil. (error)
// @return error message.
// @function epochTime
int TimestampUserdata::epochTime(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
// Lua 5.1 and 5.2 represent os.time() values as lua_Numbers.
lua_Number epoch = static_cast<lua_Number>(tsud->mTimestamp.epochTime());
lua_pushnumber(L, epoch);
return 1;
}
/// Returns true if and only if the given interval (in microseconds) has passed since the time denoted by the timestamp.
// @int interval time duration in microseconds to check.
// @return boolean
// @function isElapsed
int TimestampUserdata::isElapsed(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
Poco::Int64 interval = 0;
if (lua_isnumber(L, 2))
interval = luaL_checkinteger(L, 2);
else
{
DynamicAnyUserdata* daud = checkPrivateUserdata<DynamicAnyUserdata>(L, 2);
try
{
daud->mDynamicAny.convert(interval);
}
catch (const Poco::Exception& e)
{
pushPocoException(L, e);
return lua_error(L);
}
catch (...)
{
pushUnknownException(L);
return lua_error(L);
}
}
int elapsed = tsud->mTimestamp.isElapsed(interval);
lua_pushboolean(L, elapsed);
return 1;
}
/// Gets the resolution in units per second. Since the timestamp has microsecond resolution, the returned value is always 1000000.
// @return number
// @function resolution
int TimestampUserdata::resolution(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
lua_Number res = tsud->mTimestamp.resolution();
lua_pushnumber(L, res);
return 1;
}
int TimestampUserdata::update(lua_State* L)
{
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
tsud->mTimestamp.update();
return 0;
}
/// Gets the timestamp expressed in UTC-based time. UTC base time is midnight, October 15, 1582. Resolution is 100 nanoseconds.
// The value returned is stored within a dynamicany userdata as an Int64.
// @see dynamicany
// @return dynamicany userdata or nil. (error)
// @return error message.
// @function utcTime
int TimestampUserdata::utcTime(lua_State* L)
{
int rv = 0;
TimestampUserdata* tsud = checkPrivateUserdata<TimestampUserdata>(L, 1);
Poco::DynamicAny val = tsud->mTimestamp.utcTime();
try
{
DynamicAnyUserdata* daud = new(lua_newuserdata(L, sizeof *daud)) DynamicAnyUserdata(val);
setupPocoUserdata(L, daud, POCO_DYNAMICANY_METATABLE_NAME);
rv = 1;
}
catch (const Poco::Exception& e)
{
rv = pushPocoException(L, e);
}
catch (...)
{
rv = pushUnknownException(L);
}
return rv;
}
} // LuaPoco
<|endoftext|> |
<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/text_input_manager_win32.h"
#include <imm.h>
#include <memory>
namespace flutter {
void TextInputManagerWin32::SetWindowHandle(HWND window_handle) {
window_handle_ = window_handle;
}
void TextInputManagerWin32::CreateImeWindow() {
if (window_handle_ == nullptr) {
return;
}
// Some IMEs ignore calls to ::ImmSetCandidateWindow() and use the position of
// the current system caret instead via ::GetCaretPos(). In order to behave
// as expected with these IMEs, we create a temporary system caret.
if (!ime_active_) {
::CreateCaret(window_handle_, nullptr, 1, 1);
}
ime_active_ = true;
// Set the position of the IME windows.
UpdateImeWindow();
}
void TextInputManagerWin32::DestroyImeWindow() {
if (window_handle_ == nullptr) {
return;
}
// Destroy the system caret created in CreateImeWindow().
if (ime_active_) {
::DestroyCaret();
}
ime_active_ = false;
}
void TextInputManagerWin32::UpdateImeWindow() {
if (window_handle_ == nullptr) {
return;
}
HIMC imm_context = ::ImmGetContext(window_handle_);
if (imm_context) {
MoveImeWindow(imm_context);
::ImmReleaseContext(window_handle_, imm_context);
}
}
void TextInputManagerWin32::UpdateCaretRect(const Rect& rect) {
caret_rect_ = rect;
if (window_handle_ == nullptr) {
return;
}
// TODO(cbracken): wrap these in an RAII container.
HIMC imm_context = ::ImmGetContext(window_handle_);
if (imm_context) {
MoveImeWindow(imm_context);
::ImmReleaseContext(window_handle_, imm_context);
}
}
long TextInputManagerWin32::GetComposingCursorPosition() const {
if (window_handle_ == nullptr) {
return false;
}
HIMC imm_context = ::ImmGetContext(window_handle_);
if (imm_context) {
// Read the cursor position within the composing string.
const int pos =
ImmGetCompositionStringW(imm_context, GCS_CURSORPOS, nullptr, 0);
::ImmReleaseContext(window_handle_, imm_context);
return pos;
}
return -1;
}
std::optional<std::u16string> TextInputManagerWin32::GetComposingString()
const {
return GetString(GCS_COMPSTR);
}
std::optional<std::u16string> TextInputManagerWin32::GetResultString() const {
return GetString(GCS_RESULTSTR);
}
std::optional<std::u16string> TextInputManagerWin32::GetString(int type) const {
if (window_handle_ == nullptr || !ime_active_) {
return std::nullopt;
}
HIMC imm_context = ::ImmGetContext(window_handle_);
if (imm_context) {
// Read the composing string length.
const long compose_bytes =
::ImmGetCompositionString(imm_context, type, nullptr, 0);
const long compose_length = compose_bytes / sizeof(wchar_t);
if (compose_length <= 0) {
::ImmReleaseContext(window_handle_, imm_context);
return std::nullopt;
}
std::u16string text(compose_length, '\0');
::ImmGetCompositionString(imm_context, type, &text[0], compose_bytes);
::ImmReleaseContext(window_handle_, imm_context);
return text;
}
return std::nullopt;
}
void TextInputManagerWin32::MoveImeWindow(HIMC imm_context) {
if (GetFocus() != window_handle_ || !ime_active_) {
return;
}
LONG x = caret_rect_.left();
LONG y = caret_rect_.top();
::SetCaretPos(x, y);
COMPOSITIONFORM cf = {CFS_POINT, {x, y}};
::ImmSetCompositionWindow(imm_context, &cf);
CANDIDATEFORM candidate_form = {0, CFS_CANDIDATEPOS, {x, y}, {0, 0, 0, 0}};
::ImmSetCandidateWindow(imm_context, &candidate_form);
}
} // namespace flutter
<commit_msg>Add RAII wrapper for Win32 IMM context (#24699)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/text_input_manager_win32.h"
#include <imm.h>
#include <cassert>
#include <memory>
namespace flutter {
// RAII wrapper for the Win32 Input Method Manager context.
class ImmContext {
public:
ImmContext(HWND window_handle)
: context_(::ImmGetContext(window_handle)),
window_handle_(window_handle) {
assert(window_handle);
}
~ImmContext() {
if (context_ != nullptr) {
::ImmReleaseContext(window_handle_, context_);
}
}
// Prevent copying.
ImmContext(const ImmContext& other) = delete;
ImmContext& operator=(const ImmContext& other) = delete;
// Returns true if a valid IMM context has been obtained.
bool IsValid() const { return context_ != nullptr; }
// Returns the IMM context.
HIMC get() {
assert(context_);
return context_;
}
private:
HWND window_handle_;
HIMC context_;
};
void TextInputManagerWin32::SetWindowHandle(HWND window_handle) {
window_handle_ = window_handle;
}
void TextInputManagerWin32::CreateImeWindow() {
if (window_handle_ == nullptr) {
return;
}
// Some IMEs ignore calls to ::ImmSetCandidateWindow() and use the position of
// the current system caret instead via ::GetCaretPos(). In order to behave
// as expected with these IMEs, we create a temporary system caret.
if (!ime_active_) {
::CreateCaret(window_handle_, nullptr, 1, 1);
}
ime_active_ = true;
// Set the position of the IME windows.
UpdateImeWindow();
}
void TextInputManagerWin32::DestroyImeWindow() {
if (window_handle_ == nullptr) {
return;
}
// Destroy the system caret created in CreateImeWindow().
if (ime_active_) {
::DestroyCaret();
}
ime_active_ = false;
}
void TextInputManagerWin32::UpdateImeWindow() {
if (window_handle_ == nullptr) {
return;
}
ImmContext imm_context(window_handle_);
if (imm_context.IsValid()) {
MoveImeWindow(imm_context.get());
}
}
void TextInputManagerWin32::UpdateCaretRect(const Rect& rect) {
caret_rect_ = rect;
if (window_handle_ == nullptr) {
return;
}
ImmContext imm_context(window_handle_);
if (imm_context.IsValid()) {
MoveImeWindow(imm_context.get());
}
}
long TextInputManagerWin32::GetComposingCursorPosition() const {
if (window_handle_ == nullptr) {
return false;
}
ImmContext imm_context(window_handle_);
if (imm_context.IsValid()) {
// Read the cursor position within the composing string.
return ImmGetCompositionString(imm_context.get(), GCS_CURSORPOS, nullptr,
0);
}
return -1;
}
std::optional<std::u16string> TextInputManagerWin32::GetComposingString()
const {
return GetString(GCS_COMPSTR);
}
std::optional<std::u16string> TextInputManagerWin32::GetResultString() const {
return GetString(GCS_RESULTSTR);
}
std::optional<std::u16string> TextInputManagerWin32::GetString(int type) const {
if (window_handle_ == nullptr || !ime_active_) {
return std::nullopt;
}
ImmContext imm_context(window_handle_);
if (imm_context.IsValid()) {
// Read the composing string length.
const long compose_bytes =
::ImmGetCompositionString(imm_context.get(), type, nullptr, 0);
const long compose_length = compose_bytes / sizeof(wchar_t);
if (compose_length <= 0) {
return std::nullopt;
}
std::u16string text(compose_length, '\0');
::ImmGetCompositionString(imm_context.get(), type, &text[0], compose_bytes);
return text;
}
return std::nullopt;
}
void TextInputManagerWin32::MoveImeWindow(HIMC imm_context) {
if (GetFocus() != window_handle_ || !ime_active_) {
return;
}
LONG x = caret_rect_.left();
LONG y = caret_rect_.top();
::SetCaretPos(x, y);
COMPOSITIONFORM cf = {CFS_POINT, {x, y}};
::ImmSetCompositionWindow(imm_context, &cf);
CANDIDATEFORM candidate_form = {0, CFS_CANDIDATEPOS, {x, y}, {0, 0, 0, 0}};
::ImmSetCandidateWindow(imm_context, &candidate_form);
}
} // namespace flutter
<|endoftext|> |
<commit_before>// RefCount.hh for FbTk - Fluxbox Toolkit
// Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//
// 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 FBTK_REFCOUNT_HH
#define FBTK_REFCOUNT_HH
namespace FbTk {
/// holds a pointer with reference counting, similar to std:auto_ptr
template <typename Pointer>
class RefCount {
public:
RefCount();
explicit RefCount(Pointer *p);
explicit RefCount(RefCount<Pointer> ©);
explicit RefCount(const RefCount<Pointer> ©);
~RefCount();
RefCount<Pointer> &operator = (const RefCount<Pointer> ©);
RefCount<Pointer> &operator = (Pointer *p);
Pointer *operator * () const { return get(); }
Pointer *operator -> () const { return get(); }
Pointer *get() const { return m_data; }
/// @return number of referenses
unsigned int usedBy() const { return (m_refcount != 0 ? *m_refcount : 0); }
private:
/// increase referense count
void incRefCount();
/// decrease referense count
void decRefCount();
Pointer *m_data; ///< data holder
mutable unsigned int *m_refcount; ///< holds reference counting
};
// implementation
template <typename Pointer>
RefCount<Pointer>::RefCount():m_data(0), m_refcount(new unsigned int(0)) {
}
template <typename Pointer>
RefCount<Pointer>::RefCount(RefCount<Pointer> ©):
m_data(copy.m_data),
m_refcount(copy.m_refcount) {
incRefCount();
}
template <typename Pointer>
RefCount<Pointer>::RefCount(Pointer *p):m_data(p), m_refcount(new unsigned int(0)) {
incRefCount();
}
template <typename Pointer>
RefCount<Pointer>::RefCount(const RefCount<Pointer> ©):
m_data(copy.m_data),
m_refcount(copy.m_refcount) {
incRefCount();
}
template <typename Pointer>
RefCount<Pointer>::~RefCount() {
decRefCount();
}
template <typename Pointer>
RefCount<Pointer> &RefCount<Pointer>::operator = (const RefCount<Pointer> ©) {
decRefCount(); // dec current ref count
m_refcount = copy.m_refcount; // set new ref count
m_data = copy.m_data; // set new data pointer
incRefCount(); // inc new ref count
return *this;
}
template <typename Pointer>
RefCount<Pointer> &RefCount<Pointer>::operator = (Pointer *p) {
decRefCount();
m_data = p;
if (m_refcount == 0)
m_refcount = new unsigned int(0);
incRefCount();
}
template <typename Pointer>
void RefCount<Pointer>::decRefCount() {
if (m_refcount == 0)
return;
if (*m_refcount == 0) { // already zero, then delete refcount
delete m_refcount;
m_refcount = 0;
return;
}
(*m_refcount)--;
if (*m_refcount == 0) { // destroy m_data and m_refcount if nobody else is using this
if (m_data != 0)
delete m_data;
m_data = 0;
delete m_refcount;
m_refcount = 0;
}
}
template <typename Pointer>
void RefCount<Pointer>::incRefCount() {
if (m_refcount == 0)
return;
(*m_refcount)++;
}
}; // end namespace FbTk
#endif // FBTK_REFCOUNT_HH
<commit_msg>fixed minor bug in operator = Pointer<commit_after>// RefCount.hh for FbTk - Fluxbox Toolkit
// Copyright (c) 2002 Henrik Kinnunen (fluxgen at users.sourceforge.net)
//
// 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 FBTK_REFCOUNT_HH
#define FBTK_REFCOUNT_HH
namespace FbTk {
/// holds a pointer with reference counting, similar to std:auto_ptr
template <typename Pointer>
class RefCount {
public:
RefCount();
explicit RefCount(Pointer *p);
explicit RefCount(RefCount<Pointer> ©);
explicit RefCount(const RefCount<Pointer> ©);
~RefCount();
RefCount<Pointer> &operator = (const RefCount<Pointer> ©);
RefCount<Pointer> &operator = (Pointer *p);
Pointer *operator * () const { return get(); }
Pointer *operator -> () const { return get(); }
Pointer *get() const { return m_data; }
/// @return number of referenses
unsigned int usedBy() const { return (m_refcount != 0 ? *m_refcount : 0); }
private:
/// increase referense count
void incRefCount();
/// decrease referense count
void decRefCount();
Pointer *m_data; ///< data holder
mutable unsigned int *m_refcount; ///< holds reference counting
};
// implementation
template <typename Pointer>
RefCount<Pointer>::RefCount():m_data(0), m_refcount(new unsigned int(0)) {
}
template <typename Pointer>
RefCount<Pointer>::RefCount(RefCount<Pointer> ©):
m_data(copy.m_data),
m_refcount(copy.m_refcount) {
incRefCount();
}
template <typename Pointer>
RefCount<Pointer>::RefCount(Pointer *p):m_data(p), m_refcount(new unsigned int(0)) {
incRefCount();
}
template <typename Pointer>
RefCount<Pointer>::RefCount(const RefCount<Pointer> ©):
m_data(copy.m_data),
m_refcount(copy.m_refcount) {
incRefCount();
}
template <typename Pointer>
RefCount<Pointer>::~RefCount() {
decRefCount();
}
template <typename Pointer>
RefCount<Pointer> &RefCount<Pointer>::operator = (const RefCount<Pointer> ©) {
decRefCount(); // dec current ref count
m_refcount = copy.m_refcount; // set new ref count
m_data = copy.m_data; // set new data pointer
incRefCount(); // inc new ref count
return *this;
}
template <typename Pointer>
RefCount<Pointer> &RefCount<Pointer>::operator = (Pointer *p) {
decRefCount();
m_data = p; // set data pointer
m_refcount = new unsigned int(0); // create new counter
incRefCount();
}
template <typename Pointer>
void RefCount<Pointer>::decRefCount() {
if (m_refcount == 0)
return;
if (*m_refcount == 0) { // already zero, then delete refcount
delete m_refcount;
m_refcount = 0;
return;
}
(*m_refcount)--;
if (*m_refcount == 0) { // destroy m_data and m_refcount if nobody else is using this
if (m_data != 0)
delete m_data;
m_data = 0;
delete m_refcount;
m_refcount = 0;
}
}
template <typename Pointer>
void RefCount<Pointer>::incRefCount() {
if (m_refcount == 0)
return;
(*m_refcount)++;
}
}; // end namespace FbTk
#endif // FBTK_REFCOUNT_HH
<|endoftext|> |
<commit_before><commit_msg>Renderer - Enums - BufferUsage / IndexType<commit_after><|endoftext|> |
<commit_before>/*!
* \file shader_source.hpp
* \brief file shader_source.hpp
*
* Adapted from: WRATHGLProgram.hpp of WRATH:
*
* Copyright 2013 by Nomovok Ltd.
* Contact: [email protected]
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/c_array.hpp>
namespace fastuidraw {
namespace glsl {
/*!\addtogroup GLSL
* @{
*/
/*!
* \brief
* A ShaderSource represents the source code
* to a GLSL shader, specifying blocks of source
* code and macros to use.
*/
class ShaderSource
{
public:
/*!
* \brief
* Enumeration to indiciate the source for a shader.
*/
enum source_t
{
/*!
* Shader source code is taken
* from the file whose name
* is the passed string.
*/
from_file,
/*!
* The passed string is the
* shader source code.
*/
from_string,
/*!
* The passed string is label
* for a string of text fetched
* with fastuidraw::fetch_static_resource()
*/
from_resource,
};
/*!
* \brief
* Enumeration to determine if source
* code or a macro
*/
enum add_location_t
{
/*!
* add the source code or macro
* to the back.
*/
push_back,
/*!
* add the source code or macro
* to the front.
*/
push_front
};
/*!
* \brief
* Enumeration to indicate extension
* enable flags.
*/
enum extension_enable_t
{
/*!
* Requires the named GLSL extension,
* i.e. will add <B>"#extension extension_name: require"</B>
* to GLSL source code.
*/
require_extension,
/*!
* Enables the named GLSL extension,
* i.e. will add <B>"#extension extension_name: enable"</B>
* to GLSL source code.
*/
enable_extension,
/*!
* Enables the named GLSL extension,
* but request that the GLSL compiler
* issues warning when the extension
* is used, i.e. will add
* <B>"#extension extension_name: warn"</B>
* to GLSL source code.
*/
warn_extension,
/*!
* Disables the named GLSL extension,
* i.e. will add <B>"#extension extension_name: disable"</B>
* to GLSL source code.
*/
disable_extension
};
/*!
* A MacroSet represents a set of macros.
*/
class MacroSet
{
public:
/*!
* Ctor.
*/
MacroSet(void);
/*!
* Copy ctor.
* \param obj value from which to copy
*/
MacroSet(const MacroSet &obj);
~MacroSet();
/*!
* Assignment operator.
* \param obj value from which to copy
*/
MacroSet&
operator=(const MacroSet &obj);
/*!
* Swap operation
* \param obj object with which to swap
*/
void
swap(MacroSet &obj);
/*!
* Add a macro to this MacroSet.
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
MacroSet&
add_macro(c_string macro_name, c_string macro_value = "");
/*!
* Add a macro to this MacroSet.
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
MacroSet&
add_macro(c_string macro_name, uint32_t macro_value);
/*!
* Add a macro to this MacroSet.
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
MacroSet&
add_macro(c_string macro_name, int32_t macro_value);
/*!
* Add a macro to this MacroSet.
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
MacroSet&
add_macro(c_string macro_name, float macro_value);
private:
friend class ShaderSource;
void *m_d;
};
/*!
* Ctor.
*/
ShaderSource(void);
/*!
* Copy ctor.
* \param obj value from which to copy
*/
ShaderSource(const ShaderSource &obj);
~ShaderSource();
/*!
* Assignment operator.
* \param obj value from which to copy
*/
ShaderSource&
operator=(const ShaderSource &obj);
/*!
* Swap operation
* \param obj object with which to swap
*/
void
swap(ShaderSource &obj);
/*!
* Specifies the version of GLSL to which to
* declare the shader. An empty string indicates
* to not have a "#version" directive in the shader.
* String is -copied-.
*/
ShaderSource&
specify_version(c_string v);
/*!
* Returns the value set by specify_version().
* Returned pointer is only valid until the
* next time that specify_version() is called.
*/
c_string
version(void) const;
/*!
* Add shader source code to this ShaderSource.
* \param str string that is a filename, GLSL source or a resource name
* \param tp interpretation of str, i.e. determines if
* str is a filename, raw GLSL source or a resource
* \param loc location to add source
*/
ShaderSource&
add_source(c_string str, enum source_t tp = from_file,
enum add_location_t loc = push_back);
/*!
* Add the sources from another ShaderSource object.
* \param obj ShaderSource object from which to absorb
*/
ShaderSource&
add_source(const ShaderSource &obj);
/*!
* Add a macro to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code.
* \param macro_name name of macro
* \param macro_value value to which macro is given
* \param loc location to add macro within code
*/
ShaderSource&
add_macro(c_string macro_name, c_string macro_value = "",
enum add_location_t loc = push_back);
/*!
* Add a macro to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code.
* \param macro_name name of macro
* \param macro_value value to which macro is given
* \param loc location to add macro within code
*/
ShaderSource&
add_macro(c_string macro_name, uint32_t macro_value,
enum add_location_t loc = push_back);
/*!
* Add a macro to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code.
* \param macro_name name of macro
* \param macro_value value to which macro is given
* \param loc location to add macro within code
*/
ShaderSource&
add_macro(c_string macro_name, int32_t macro_value,
enum add_location_t loc = push_back);
/*!
* Add a macro to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code.
* \param macro_name name of macro
* \param macro_value value to which macro is given
* \param loc location to add macro within code
*/
ShaderSource&
add_macro(c_string macro_name, float macro_value,
enum add_location_t loc = push_back);
/*!
* Add macros of a MacroSet to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code for each macro in the
* \ref MacroSet.
* \param macros set of macros to add
* \param loc location to add macro within code
*/
ShaderSource&
add_macros(const MacroSet ¯os,
enum add_location_t loc = push_back);
/*!
* Functionally, will insert \#undef macro_name
* in the GLSL source code.
* \param macro_name name of macro
* \param loc location to add macro within code
*/
ShaderSource&
remove_macro(c_string macro_name,
enum add_location_t loc = push_back);
/*!
* Remove macros of a MacroSet to this ShaderSource.
* Functionally, will insert \#undef macro_name
* in the GLSL source code for each macro in the
* \ref MacroSet.
* \param macros set of macros to remove
* \param loc location to add macro within code
*/
ShaderSource&
remove_macros(const MacroSet ¯os,
enum add_location_t loc = push_back);
/*!
* Specifiy an extension and usage.
* \param ext_name name of GL extension
* \param tp usage of extension
*/
ShaderSource&
specify_extension(c_string ext_name,
enum extension_enable_t tp = enable_extension);
/*!
* Add all the extension specifacation from another
* ShaderSource object to this ShaderSource objects.
* Extension already set in this ShaderSource that
* are specified in obj are overwritten to the values
* specified in obj.
* \param obj ShaderSource object from which to take
*/
ShaderSource&
specify_extensions(const ShaderSource &obj);
/*!
* Set to disable adding pre-added FastUIDraw macros
* and functions to GLSL source code. The pre-added
* functions are:
* - uint fastuidraw_mask(uint num_bits) : returns a uint where the last num_bits bits are up
* - uint fastuidraw_extract_bits(uint bit0, uint num_bits, uint src) : extracts a value from the named bits of a uint
* - void fastuidraw_do_nothing(void) : function that has empty body (i.e. does nothing).
*
* The added macros are:
*
* - FASTUIDRAW_MASK(bit0, num_bits) : wrapper over fastuidraw_mask that casts arguments into uint's
* - FASTUIDRAW_EXTRACT_BITS(bit0, num_bits, src) : wrapper over fastuidraw_extract_bits that casts arguments into uint's
*/
ShaderSource&
disable_pre_added_source(void);
/*!
* Returns the GLSL code assembled. The returned string is only
* gauranteed to be valid up until the ShaderSource object
* is modified.
* \param code_only if true only, return the GLSL code without
* the additions of version, extension and
* FastUIDraw convenience functions and macros.
*/
c_string
assembled_code(bool code_only = false) const;
private:
void *m_d;
};
/*! @} */
} //namespace glsl
} //namespace fastuidraw
<commit_msg>fastuidraw/glsl/shader_source: add add_macro_u32() method to force values into uint32_t types to get the u-suffix in GLSL<commit_after>/*!
* \file shader_source.hpp
* \brief file shader_source.hpp
*
* Adapted from: WRATHGLProgram.hpp of WRATH:
*
* Copyright 2013 by Nomovok Ltd.
* Contact: [email protected]
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
#include <fastuidraw/util/util.hpp>
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/c_array.hpp>
namespace fastuidraw {
namespace glsl {
/*!\addtogroup GLSL
* @{
*/
/*!
* \brief
* A ShaderSource represents the source code
* to a GLSL shader, specifying blocks of source
* code and macros to use.
*/
class ShaderSource
{
public:
/*!
* \brief
* Enumeration to indiciate the source for a shader.
*/
enum source_t
{
/*!
* Shader source code is taken
* from the file whose name
* is the passed string.
*/
from_file,
/*!
* The passed string is the
* shader source code.
*/
from_string,
/*!
* The passed string is label
* for a string of text fetched
* with fastuidraw::fetch_static_resource()
*/
from_resource,
};
/*!
* \brief
* Enumeration to determine if source
* code or a macro
*/
enum add_location_t
{
/*!
* add the source code or macro
* to the back.
*/
push_back,
/*!
* add the source code or macro
* to the front.
*/
push_front
};
/*!
* \brief
* Enumeration to indicate extension
* enable flags.
*/
enum extension_enable_t
{
/*!
* Requires the named GLSL extension,
* i.e. will add <B>"#extension extension_name: require"</B>
* to GLSL source code.
*/
require_extension,
/*!
* Enables the named GLSL extension,
* i.e. will add <B>"#extension extension_name: enable"</B>
* to GLSL source code.
*/
enable_extension,
/*!
* Enables the named GLSL extension,
* but request that the GLSL compiler
* issues warning when the extension
* is used, i.e. will add
* <B>"#extension extension_name: warn"</B>
* to GLSL source code.
*/
warn_extension,
/*!
* Disables the named GLSL extension,
* i.e. will add <B>"#extension extension_name: disable"</B>
* to GLSL source code.
*/
disable_extension
};
/*!
* A MacroSet represents a set of macros.
*/
class MacroSet
{
public:
/*!
* Ctor.
*/
MacroSet(void);
/*!
* Copy ctor.
* \param obj value from which to copy
*/
MacroSet(const MacroSet &obj);
~MacroSet();
/*!
* Assignment operator.
* \param obj value from which to copy
*/
MacroSet&
operator=(const MacroSet &obj);
/*!
* Swap operation
* \param obj object with which to swap
*/
void
swap(MacroSet &obj);
/*!
* Add a macro to this MacroSet.
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
MacroSet&
add_macro(c_string macro_name, c_string macro_value = "");
/*!
* Add a macro to this MacroSet.
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
MacroSet&
add_macro(c_string macro_name, uint32_t macro_value);
/*!
* Add a macro to this MacroSet.
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
MacroSet&
add_macro(c_string macro_name, int32_t macro_value);
/*!
* Add a macro to this MacroSet.
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
MacroSet&
add_macro(c_string macro_name, float macro_value);
/*!
* Add a macro to this MacroSet for casted to uint32_t
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
template<typename T>
MacroSet&
add_macro_u32(c_string macro_name, T macro_value)
{
uint32_t v(macro_value);
return add_macro(macro_name, v);
}
private:
friend class ShaderSource;
void *m_d;
};
/*!
* Ctor.
*/
ShaderSource(void);
/*!
* Copy ctor.
* \param obj value from which to copy
*/
ShaderSource(const ShaderSource &obj);
~ShaderSource();
/*!
* Assignment operator.
* \param obj value from which to copy
*/
ShaderSource&
operator=(const ShaderSource &obj);
/*!
* Swap operation
* \param obj object with which to swap
*/
void
swap(ShaderSource &obj);
/*!
* Specifies the version of GLSL to which to
* declare the shader. An empty string indicates
* to not have a "#version" directive in the shader.
* String is -copied-.
*/
ShaderSource&
specify_version(c_string v);
/*!
* Returns the value set by specify_version().
* Returned pointer is only valid until the
* next time that specify_version() is called.
*/
c_string
version(void) const;
/*!
* Add shader source code to this ShaderSource.
* \param str string that is a filename, GLSL source or a resource name
* \param tp interpretation of str, i.e. determines if
* str is a filename, raw GLSL source or a resource
* \param loc location to add source
*/
ShaderSource&
add_source(c_string str, enum source_t tp = from_file,
enum add_location_t loc = push_back);
/*!
* Add the sources from another ShaderSource object.
* \param obj ShaderSource object from which to absorb
*/
ShaderSource&
add_source(const ShaderSource &obj);
/*!
* Add a macro to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code.
* \param macro_name name of macro
* \param macro_value value to which macro is given
* \param loc location to add macro within code
*/
ShaderSource&
add_macro(c_string macro_name, c_string macro_value = "",
enum add_location_t loc = push_back);
/*!
* Add a macro to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code.
* \param macro_name name of macro
* \param macro_value value to which macro is given
* \param loc location to add macro within code
*/
ShaderSource&
add_macro(c_string macro_name, uint32_t macro_value,
enum add_location_t loc = push_back);
/*!
* Add a macro to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code.
* \param macro_name name of macro
* \param macro_value value to which macro is given
* \param loc location to add macro within code
*/
ShaderSource&
add_macro(c_string macro_name, int32_t macro_value,
enum add_location_t loc = push_back);
/*!
* Add a macro to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code.
* \param macro_name name of macro
* \param macro_value value to which macro is given
* \param loc location to add macro within code
*/
ShaderSource&
add_macro(c_string macro_name, float macro_value,
enum add_location_t loc = push_back);
/*!
* Add a macro to this MacroSet for casted to uint32_t
* \param macro_name name of macro
* \param macro_value value to which macro is given
*/
template<typename T>
ShaderSource&
add_macro_u32(c_string macro_name, T macro_value)
{
uint32_t v(macro_value);
return add_macro(macro_name, v);
}
/*!
* Add macros of a MacroSet to this ShaderSource.
* Functionally, will insert \#define macro_name macro_value
* in the GLSL source code for each macro in the
* \ref MacroSet.
* \param macros set of macros to add
* \param loc location to add macro within code
*/
ShaderSource&
add_macros(const MacroSet ¯os,
enum add_location_t loc = push_back);
/*!
* Functionally, will insert \#undef macro_name
* in the GLSL source code.
* \param macro_name name of macro
* \param loc location to add macro within code
*/
ShaderSource&
remove_macro(c_string macro_name,
enum add_location_t loc = push_back);
/*!
* Remove macros of a MacroSet to this ShaderSource.
* Functionally, will insert \#undef macro_name
* in the GLSL source code for each macro in the
* \ref MacroSet.
* \param macros set of macros to remove
* \param loc location to add macro within code
*/
ShaderSource&
remove_macros(const MacroSet ¯os,
enum add_location_t loc = push_back);
/*!
* Specifiy an extension and usage.
* \param ext_name name of GL extension
* \param tp usage of extension
*/
ShaderSource&
specify_extension(c_string ext_name,
enum extension_enable_t tp = enable_extension);
/*!
* Add all the extension specifacation from another
* ShaderSource object to this ShaderSource objects.
* Extension already set in this ShaderSource that
* are specified in obj are overwritten to the values
* specified in obj.
* \param obj ShaderSource object from which to take
*/
ShaderSource&
specify_extensions(const ShaderSource &obj);
/*!
* Set to disable adding pre-added FastUIDraw macros
* and functions to GLSL source code. The pre-added
* functions are:
* - uint fastuidraw_mask(uint num_bits) : returns a uint where the last num_bits bits are up
* - uint fastuidraw_extract_bits(uint bit0, uint num_bits, uint src) : extracts a value from the named bits of a uint
* - void fastuidraw_do_nothing(void) : function that has empty body (i.e. does nothing).
*
* The added macros are:
*
* - FASTUIDRAW_MASK(bit0, num_bits) : wrapper over fastuidraw_mask that casts arguments into uint's
* - FASTUIDRAW_EXTRACT_BITS(bit0, num_bits, src) : wrapper over fastuidraw_extract_bits that casts arguments into uint's
*/
ShaderSource&
disable_pre_added_source(void);
/*!
* Returns the GLSL code assembled. The returned string is only
* gauranteed to be valid up until the ShaderSource object
* is modified.
* \param code_only if true only, return the GLSL code without
* the additions of version, extension and
* FastUIDraw convenience functions and macros.
*/
c_string
assembled_code(bool code_only = false) const;
private:
void *m_d;
};
/*! @} */
} //namespace glsl
} //namespace fastuidraw
<|endoftext|> |
<commit_before>#ifndef __SCRIPT_HH__
#define __SCRIPT_HH__
#include <sstream>
#include <iterator>
#include <iostream>
#include <string>
#include <cstdio>
#include <stdarg.h>
#include <stdint.h>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include "Action/AAction.hh"
#include "PokemonUtils.hh"
#include "../vbam/gba/Globals.h"
#include "Data.hh"
#define VM_FLAGS 0x900
#define VM_VARS 0x100
#define VM_TEMP 0x1F
#define VM_BANKS 0x04
#define VM_BUFF 0x03
#define VM_VAR_OFFSET 0x4000
#define VM_TEMP_OFFSET 0x8000
#define VM_LASTRESULT 0x800D
#define VM_IS_FLAG(x) ((x) < VM_FLAGS)
#define VM_IS_BANK(x) ((x) < VM_BANKS)
#define VM_IS_VAR(x) ((x) >= VM_VAR_OFFSET && (x) < VM_VAR_OFFSET + VM_VARS)
#define VM_IS_TEMP(x) ((x) >= VM_TEMP_OFFSET && (x) < VM_TEMP_OFFSET + VM_TEMP)
class Script
{
private:
struct Range
{
Range(uint32_t x = 0, uint32_t y = 0)
: start(x), end(y) {}
uint32_t start;
uint32_t end;
};
public:
typedef std::vector<uint32_t> Args;
typedef std::vector<std::string> TypeList;
typedef uint32_t(Script::*ParamReader)();
struct Instruction
{
uint32_t offset;
uint8_t *bytecode;
uint8_t length;
uint32_t next;
uint8_t cmd;
std::string str;
Args args;
TypeList types;
uint8_t toVisit; // bit field storing what parts of the branch was visited
Instruction(uint32_t p_off, uint8_t *p_mem)
: offset(p_off), bytecode(p_mem + p_off), length(1), cmd(*bytecode), str(""),
toVisit((cmd == 0x06 || cmd == 0x07) * 3)
{}
bool notVisited(bool result)
{ return (toVisit & (1 << result)); }
void visit(bool result)
{ toVisit &= ~(1 << result); }
void print()
{
printf("%#08x: ", offset);
for (int i = 0; i < 10; i++)
printf(i < length ? "%02x " : " ", bytecode[i]);
printf("%s\n", str.c_str());
}
void setLength(uint8_t len)
{
length = len;
next = (cmd == 0x02 || cmd == 0x03 ? 0 : offset + length);
}
};
struct Command
{
Command(std::initializer_list<std::string> il)
: format(il.size() ? *(il.begin()) : "UNKNOWN"),
args(il.size() > 1 ? *(il.begin() + 1) : ""),
hook(NULL)
{}
Command(const std::string &fmt, const std::string ¶ms = "", void (Script::*func)(Instruction *) = NULL)
: format(fmt), args(params), hook(func)
{}
std::string format;
std::string args;
void (Script::*hook)(Instruction *);
};
enum ScriptType
{
PERSON,
SIGN,
SCRIPT,
STD,
NONE
};
struct Identifier
{
uint8_t bank;
uint8_t map;
uint8_t id;
ScriptType type;
Identifier(uint8_t bank = 0, uint8_t map = 0, uint8_t id = 0, ScriptType type = NONE)
: bank(bank), map(map), id(id), type(type)
{}
bool operator<(const Identifier &o) const
{
if (bank != o.bank)
return (bank < o.bank);
if (map != o.map)
return (map < o.map);
if (id != o.id)
return (id < o.id);
return (type < o.type);
}
};
public:
Script(uint8_t bank = 0, uint8_t map = 0, uint8_t id = 0, ScriptType type = NONE);
~Script();
public:
Script &load(uint32_t ptr);
Script &loadStd(uint8_t n);
void print();
static Script *getStd(uint8_t n) { return (_getScript(0, 0, n, STD)); }
static Script *getPerson(uint8_t bank, uint8_t map, uint8_t id) { return (_getScript(bank, map, id, PERSON)); }
static Script *getPerson(uint8_t id) { return (_getScript(0, 0, id, PERSON)); }
static Script *getSign(uint8_t bank, uint8_t map, uint8_t id) { return (_getScript(bank, map, id, SIGN)); }
static Script *getSign(uint8_t id) { return (_getScript(0, 0, id, SIGN)); }
static Script *getScript(uint8_t bank, uint8_t map, uint8_t id) { return (_getScript(bank, map, id, SCRIPT)); }
static Script *getScript(uint8_t id) { return (_getScript(0, 0, id, SCRIPT)); }
static Script *getGenericScript(uint8_t b, uint8_t m, uint8_t id, ScriptType t) { return (_getScript(b, m, id, t)); }
public:
uint8_t getBank() const { return (_id.bank); }
uint8_t getMap() const { return (_id.map); }
uint8_t getId() const { return (_id.id); }
uint8_t getType() const { return (_id.type); }
public:
std::map<int, Instruction *> &getInstructions() { return (_instructions); }
uint32_t getStartOffset() { return (_offset); }
private:
void _subPrint(uint32_t ptr);
void _reset();
bool _setupNextAddr();
void _getInstruction(Command &cmd);
void _addHook(Instruction *instr);
static Script *_getScript(uint8_t bank, uint8_t map, uint8_t id, ScriptType type);
private:
uint32_t _readByte();
uint32_t _readWord();
uint32_t _readDword();
private:
void _loadpointer(Instruction *instr);
void _bufferstring(Instruction *instr);
void _preparemsg(Instruction *instr);
void _checkattack(Instruction *instr);
void _if(Instruction *instr);
void _branch(Instruction *instr);
private:
Data &_data;
Identifier _id;
uint32_t _offset;
uint32_t _start;
uint8_t *_ptr;
uint32_t _pc;
uint32_t _oldpc;
std::vector<Range> _ranges;
std::queue<uint32_t> _addrs;
std::map<int, Instruction *> _instructions;
static Command _cmds[0xD6];
static std::map<Identifier, Script *> _cache;
static std::map<std::string, ParamReader> _readers;
static std::map<uint8_t, uint8_t> _cmdHooks;
static std::map<uint16_t, std::vector<Script *> > _hookList;
};
#endif
<commit_msg>fix: remove code duplication with optionnal parameters<commit_after>#ifndef __SCRIPT_HH__
#define __SCRIPT_HH__
#include <sstream>
#include <iterator>
#include <iostream>
#include <string>
#include <cstdio>
#include <stdarg.h>
#include <stdint.h>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include "Action/AAction.hh"
#include "PokemonUtils.hh"
#include "../vbam/gba/Globals.h"
#include "Data.hh"
#define VM_FLAGS 0x900
#define VM_VARS 0x100
#define VM_TEMP 0x1F
#define VM_BANKS 0x04
#define VM_BUFF 0x03
#define VM_VAR_OFFSET 0x4000
#define VM_TEMP_OFFSET 0x8000
#define VM_LASTRESULT 0x800D
#define VM_IS_FLAG(x) ((x) < VM_FLAGS)
#define VM_IS_BANK(x) ((x) < VM_BANKS)
#define VM_IS_VAR(x) ((x) >= VM_VAR_OFFSET && (x) < VM_VAR_OFFSET + VM_VARS)
#define VM_IS_TEMP(x) ((x) >= VM_TEMP_OFFSET && (x) < VM_TEMP_OFFSET + VM_TEMP)
class Script
{
private:
struct Range
{
Range(uint32_t x = 0, uint32_t y = 0)
: start(x), end(y) {}
uint32_t start;
uint32_t end;
};
public:
typedef std::vector<uint32_t> Args;
typedef std::vector<std::string> TypeList;
typedef uint32_t(Script::*ParamReader)();
struct Instruction
{
uint32_t offset;
uint8_t *bytecode;
uint8_t length;
uint32_t next;
uint8_t cmd;
std::string str;
Args args;
TypeList types;
uint8_t toVisit; // bit field storing what parts of the branch was visited
Instruction(uint32_t p_off, uint8_t *p_mem)
: offset(p_off), bytecode(p_mem + p_off), length(1), cmd(*bytecode), str(""),
toVisit((cmd == 0x06 || cmd == 0x07) * 3)
{}
bool notVisited(bool result)
{ return (toVisit & (1 << result)); }
void visit(bool result)
{ toVisit &= ~(1 << result); }
void print()
{
printf("%#08x: ", offset);
for (int i = 0; i < 10; i++)
printf(i < length ? "%02x " : " ", bytecode[i]);
printf("%s\n", str.c_str());
}
void setLength(uint8_t len)
{
length = len;
next = (cmd == 0x02 || cmd == 0x03 ? 0 : offset + length);
}
};
struct Command
{
Command(std::initializer_list<std::string> il)
: format(il.size() ? *(il.begin()) : "UNKNOWN"),
args(il.size() > 1 ? *(il.begin() + 1) : ""),
hook(NULL)
{}
Command(const std::string &fmt, const std::string ¶ms = "", void (Script::*func)(Instruction *) = NULL)
: format(fmt), args(params), hook(func)
{}
std::string format;
std::string args;
void (Script::*hook)(Instruction *);
};
enum ScriptType
{
PERSON,
SIGN,
SCRIPT,
STD,
NONE
};
struct Identifier
{
uint8_t bank;
uint8_t map;
uint8_t id;
ScriptType type;
Identifier(uint8_t bank = 0, uint8_t map = 0, uint8_t id = 0, ScriptType type = NONE)
: bank(bank), map(map), id(id), type(type)
{}
bool operator<(const Identifier &o) const
{
if (bank != o.bank)
return (bank < o.bank);
if (map != o.map)
return (map < o.map);
if (id != o.id)
return (id < o.id);
return (type < o.type);
}
};
public:
Script(uint8_t bank = 0, uint8_t map = 0, uint8_t id = 0, ScriptType type = NONE);
~Script();
public:
Script &load(uint32_t ptr);
Script &loadStd(uint8_t n);
void print();
static Script *getStd(uint8_t n) { return (_getScript(0, 0, n, STD)); }
static Script *getPerson(uint8_t id, uint8_t bank = 0, uint8_t map = 0) { return (_getScript(bank, map, id, PERSON)); }
static Script *getSign(uint8_t id, uint8_t bank = 0, uint8_t map = 0) { return (_getScript(bank, map, id, SIGN)); }
static Script *getScript(uint8_t id, uint8_t bank = 0, uint8_t map = 0) { return (_getScript(bank, map, id, SCRIPT)); }
static Script *getGenericScript(uint8_t id, uint8_t b, uint8_t m, ScriptType t) { return (_getScript(b, m, id, t)); }
public:
uint8_t getBank() const { return (_id.bank); }
uint8_t getMap() const { return (_id.map); }
uint8_t getId() const { return (_id.id); }
uint8_t getType() const { return (_id.type); }
public:
std::map<int, Instruction *> &getInstructions() { return (_instructions); }
uint32_t getStartOffset() { return (_offset); }
private:
void _subPrint(uint32_t ptr);
void _reset();
bool _setupNextAddr();
void _getInstruction(Command &cmd);
void _addHook(Instruction *instr);
static Script *_getScript(uint8_t bank, uint8_t map, uint8_t id, ScriptType type);
private:
uint32_t _readByte();
uint32_t _readWord();
uint32_t _readDword();
private:
void _loadpointer(Instruction *instr);
void _bufferstring(Instruction *instr);
void _preparemsg(Instruction *instr);
void _checkattack(Instruction *instr);
void _if(Instruction *instr);
void _branch(Instruction *instr);
private:
Data &_data;
Identifier _id;
uint32_t _offset;
uint32_t _start;
uint8_t *_ptr;
uint32_t _pc;
uint32_t _oldpc;
std::vector<Range> _ranges;
std::queue<uint32_t> _addrs;
std::map<int, Instruction *> _instructions;
static Command _cmds[0xD6];
static std::map<Identifier, Script *> _cache;
static std::map<std::string, ParamReader> _readers;
static std::map<uint8_t, uint8_t> _cmdHooks;
static std::map<uint16_t, std::vector<Script *> > _hookList;
};
#endif
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "FBOCommFabric.h"
#include <mpi.h>
megamol::pbs::MPICommFabric::MPICommFabric(int target_rank, int source_rank)
: my_rank_{0}
, target_rank_{target_rank}
, source_rank_{source_rank}
, recv_count_{1} {
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank_);
}
bool megamol::pbs::MPICommFabric::Connect(std::string const &address) { return true; }
bool megamol::pbs::MPICommFabric::Bind(std::string const &address) { return true; }
bool megamol::pbs::MPICommFabric::Send(std::vector<char> const& buf, send_type const type) {
auto status = MPI_Send(buf.data(), buf.size(), MPI_CHAR, target_rank_, 0, MPI_COMM_WORLD);
return status == MPI_SUCCESS;
}
bool megamol::pbs::MPICommFabric::Recv(std::vector<char> &buf, recv_type const type) {
MPI_Status stat;
buf.resize(recv_count_);
auto status = MPI_Recv(buf.data(), recv_count_, MPI_CHAR, source_rank_, 0, MPI_COMM_WORLD, &stat);
MPI_Get_count(&stat, MPI_CHAR, &recv_count_);
return status == MPI_SUCCESS;
}
bool megamol::pbs::MPICommFabric::Disconnect() { return true; }
megamol::pbs::MPICommFabric::~MPICommFabric() { }
megamol::pbs::ZMQCommFabric::ZMQCommFabric(zmq::socket_type const& type) : ctx_{1}, socket_{ctx_, type} {}
megamol::pbs::ZMQCommFabric::ZMQCommFabric(ZMQCommFabric&& rhs) noexcept
: ctx_{std::move(rhs.ctx_)}, socket_{std::move(rhs.socket_)} {}
megamol::pbs::ZMQCommFabric& megamol::pbs::ZMQCommFabric::operator=(ZMQCommFabric&& rhs) noexcept {
this->ctx_ = std::move(rhs.ctx_);
this->socket_ = std::move(rhs.socket_);
return *this;
}
bool megamol::pbs::ZMQCommFabric::Connect(std::string const& address) {
/*if (!this->socket_.connected()) {
this->address_ = address;
this->socket_.connect(address);
return this->socket_.connected();
}
return true;*/
this->address_ = address;
this->socket_.connect(address);
return this->socket_.connected();
}
bool megamol::pbs::ZMQCommFabric::Bind(std::string const& address) {
this->address_ = address;
try {
this->socket_.bind(address);
} catch (zmq::error_t const& e) {
printf("ZMQ ERROR: %s", e.what());
}
return this->socket_.connected();
}
bool megamol::pbs::ZMQCommFabric::Send(std::vector<char> const& buf, send_type const type) {
return this->socket_.send(buf.begin(), buf.end());
}
bool megamol::pbs::ZMQCommFabric::Recv(std::vector<char>& buf, recv_type const type) {
zmq::message_t msg;
auto const ret = this->socket_.recv(&msg);
if (!ret) return false;
buf.resize(msg.size());
std::copy(static_cast<char*>(msg.data()), static_cast<char*>(msg.data()) + msg.size(), buf.begin());
return true;
}
bool megamol::pbs::ZMQCommFabric::Disconnect() {
if (this->socket_.connected()) {
this->socket_.disconnect(this->address_);
return !this->socket_.connected();
}
return true;
}
megamol::pbs::ZMQCommFabric::~ZMQCommFabric() { this->Disconnect(); }
megamol::pbs::FBOCommFabric::FBOCommFabric(std::unique_ptr<AbstractCommFabric>&& pimpl)
: pimpl_{std::forward<std::unique_ptr<AbstractCommFabric>>(pimpl)} {}
bool megamol::pbs::FBOCommFabric::Connect(std::string const& address) { return this->pimpl_->Connect(address); }
bool megamol::pbs::FBOCommFabric::Bind(std::string const& address) { return this->pimpl_->Bind(address); }
bool megamol::pbs::FBOCommFabric::Send(std::vector<char> const& buf, send_type const type) {
return this->pimpl_->Send(buf, type);
}
bool megamol::pbs::FBOCommFabric::Recv(std::vector<char>& buf, recv_type const type) {
return this->pimpl_->Recv(buf, type);
}
bool megamol::pbs::FBOCommFabric::Disconnect() { return this->pimpl_->Disconnect(); }
<commit_msg>workaround for unconnected zmq sockets when analyzing<commit_after>#include "stdafx.h"
#include "FBOCommFabric.h"
#include <mpi.h>
megamol::pbs::MPICommFabric::MPICommFabric(int target_rank, int source_rank)
: my_rank_{0}
, target_rank_{target_rank}
, source_rank_{source_rank}
, recv_count_{1} {
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank_);
}
bool megamol::pbs::MPICommFabric::Connect(std::string const &address) { return true; }
bool megamol::pbs::MPICommFabric::Bind(std::string const &address) { return true; }
bool megamol::pbs::MPICommFabric::Send(std::vector<char> const& buf, send_type const type) {
auto status = MPI_Send(buf.data(), buf.size(), MPI_CHAR, target_rank_, 0, MPI_COMM_WORLD);
return status == MPI_SUCCESS;
}
bool megamol::pbs::MPICommFabric::Recv(std::vector<char> &buf, recv_type const type) {
MPI_Status stat;
buf.resize(recv_count_);
auto status = MPI_Recv(buf.data(), recv_count_, MPI_CHAR, source_rank_, 0, MPI_COMM_WORLD, &stat);
MPI_Get_count(&stat, MPI_CHAR, &recv_count_);
return status == MPI_SUCCESS;
}
bool megamol::pbs::MPICommFabric::Disconnect() { return true; }
megamol::pbs::MPICommFabric::~MPICommFabric() { }
megamol::pbs::ZMQCommFabric::ZMQCommFabric(zmq::socket_type const& type) : ctx_{1}, socket_{ctx_, type} {}
megamol::pbs::ZMQCommFabric::ZMQCommFabric(ZMQCommFabric&& rhs) noexcept
: ctx_{std::move(rhs.ctx_)}, socket_{std::move(rhs.socket_)} {}
megamol::pbs::ZMQCommFabric& megamol::pbs::ZMQCommFabric::operator=(ZMQCommFabric&& rhs) noexcept {
this->ctx_ = std::move(rhs.ctx_);
this->socket_ = std::move(rhs.socket_);
return *this;
}
bool megamol::pbs::ZMQCommFabric::Connect(std::string const& address) {
/*if (!this->socket_.connected()) {
this->address_ = address;
this->socket_.connect(address);
return this->socket_.connected();
}
return true;*/
this->address_ = address;
this->socket_.connect(address);
return this->socket_.connected();
}
bool megamol::pbs::ZMQCommFabric::Bind(std::string const& address) {
this->address_ = address;
try {
this->socket_.bind(address);
} catch (zmq::error_t const& e) {
printf("ZMQ ERROR: %s", e.what());
}
return this->socket_.connected();
}
bool megamol::pbs::ZMQCommFabric::Send(std::vector<char> const& buf, send_type const type) {
return this->socket_.send(buf.begin(), buf.end());
}
bool megamol::pbs::ZMQCommFabric::Recv(std::vector<char>& buf, recv_type const type) {
zmq::message_t msg;
auto const ret = this->socket_.recv(&msg);
if (!ret) return false;
buf.resize(msg.size());
std::copy(static_cast<char*>(msg.data()), static_cast<char*>(msg.data()) + msg.size(), buf.begin());
return true;
}
bool megamol::pbs::ZMQCommFabric::Disconnect() {
//if (this->socket_.connected()) {
if (!this->address_.empty()) {
this->socket_.disconnect(this->address_);
return !this->socket_.connected();
}
return true;
}
megamol::pbs::ZMQCommFabric::~ZMQCommFabric() { this->Disconnect(); }
megamol::pbs::FBOCommFabric::FBOCommFabric(std::unique_ptr<AbstractCommFabric>&& pimpl)
: pimpl_{std::forward<std::unique_ptr<AbstractCommFabric>>(pimpl)} {}
bool megamol::pbs::FBOCommFabric::Connect(std::string const& address) { return this->pimpl_->Connect(address); }
bool megamol::pbs::FBOCommFabric::Bind(std::string const& address) { return this->pimpl_->Bind(address); }
bool megamol::pbs::FBOCommFabric::Send(std::vector<char> const& buf, send_type const type) {
return this->pimpl_->Send(buf, type);
}
bool megamol::pbs::FBOCommFabric::Recv(std::vector<char>& buf, recv_type const type) {
return this->pimpl_->Recv(buf, type);
}
bool megamol::pbs::FBOCommFabric::Disconnect() { return this->pimpl_->Disconnect(); }
<|endoftext|> |
<commit_before>#include "connection.h"
#include <QDataStream>
#include <QtConcurrent/QtConcurrent>
Connection::Connection(uint32_t id)
:
socket_(0),
shouldConnect_(false),
connected_(),
destination_(),
port_(0),
socketDescriptor_(0),
buffer_(),
sendMutex_(),
running_(false),
started_(false),
ID_(id)
{
qDebug() << "Constructing connection with ID:" << ID_;
}
void Connection::init()
{
QObject::connect(this, &error, this, &printError);
running_ = true;
start();
}
void Connection::establishConnection(QString &destination, uint16_t port)
{
qDebug() << "Establishing connection to" << destination << ":" << port;
destination_ = destination;
port_ = port;
shouldConnect_ = true;
init();
}
void Connection::setExistingConnection(qintptr socketDescriptor)
{
qDebug() << "Setting existing/incoming connection. SocketDesc:" << socketDescriptor;
socketDescriptor_ = socketDescriptor;
init();
}
void Connection::sendPacket(const QString &data)
{
qDebug() << "adding packet for sending";
if(running_)
{
sendMutex_.lock();
buffer_.push(data);
sendMutex_.unlock();
if(started_)
eventDispatcher()->wakeUp();
}
else
{
qWarning() << "Warning: Not sending message, because sender has been shut down.";
}
}
void Connection::receivedMessage()
{
qDebug() << "Socket ready to read:" << ID_;
if(started_)
eventDispatcher()->wakeUp();
}
void Connection::connectLoop()
{
const int connectionTimeout = 5 * 1000; // 5 seconds
qDebug() << "Connecting to address:" << destination_ << "Port:" << port_;
socket_->connectToHost(destination_, port_);
if (!socket_->waitForConnected(connectionTimeout)) {
emit error(socket_->error(), socket_->errorString());
return;
}
connected_ = true;
qDebug() << "Outgoing TCP connection established";
emit connected(ID_);
}
void Connection::run()
{
qDebug() << "Starting connection run loop";
started_ = true;
if(socket_ == 0)
{
socket_ = new QTcpSocket();
QObject::connect(socket_, SIGNAL(bytesWritten(qint64)),
this, SLOT(printBytesWritten(qint64)));
QObject::connect(socket_, SIGNAL(readyRead()),
this, SLOT(receivedMessage()));
}
if(socketDescriptor_ != 0)
{
qDebug() << "Getting socket";
if(!socket_->setSocketDescriptor(socketDescriptor_))
{
qCritical() << "ERROR: Could not get socket descriptor";
}
qDebug() << "Socket connected to our address:" << socket_->localAddress() << ":" << socket_->peerPort()
<< "Peer address:" << socket_->peerAddress() << ":" << socket_->peerPort();
connected_ = true;
}
if(eventDispatcher() == 0)
{
qWarning() << "WARNING: Sorry no event dispatcher for this connection.";
return;
}
while(running_)
{
if(!connected_ && shouldConnect_)
{
connectLoop();
}
if(socket_->bytesToWrite() > 0)
{
qDebug() << "Bytes to write:" << socket_->bytesToWrite() << "in state:" << socket_->state();
}
if(connected_)
{
if(socket_->canReadLine())
{
qDebug() << "Can read line with bytes available:" << socket_->bytesAvailable();
// TODO: maybe not create the data stream everytime.
QDataStream in(socket_);
in.setVersion(QDataStream::Qt_4_0);
QString message;
in >> message;
if(leftOvers_.length() > 0)
{
message = leftOvers_ + message;
}
int headerEndIndex = message.indexOf("\r\n\r\n", 0, Qt::CaseInsensitive) + 4;
int contentLengthIndex = message.indexOf("content-length", 0, Qt::CaseInsensitive);
qDebug() << "header end at:" << headerEndIndex
<< "and content-length at:" << contentLengthIndex;
if(contentLengthIndex != -1 && headerEndIndex != -1)
{
int contentLengthLineEndIndex = message.indexOf("\r\n", contentLengthIndex, Qt::CaseInsensitive);
QString value = message.mid(contentLengthIndex + 16, contentLengthLineEndIndex - (contentLengthIndex + 16));
int valueInt= value.toInt();
qDebug() << "Content-length:" << valueInt;
if(message.length() < headerEndIndex + valueInt)
{
leftOvers_ = message;
}
else
{
leftOvers_ = message.right(message.length() - (headerEndIndex + valueInt));
QString header = message.left(headerEndIndex);
QString content = message.mid(headerEndIndex, valueInt);
qDebug() << "Whole message received.";
qDebug() << "Header:" << header;
qDebug() << "Content:" << content;
qDebug() << "Left overs:" << leftOvers_;
emit messageAvailable(header, content, ID_);
}
}
else
{
qDebug() << "Message was not received fully";
leftOvers_ = message;
}
}
sendMutex_.lock();
while(buffer_.size() > 0 && socket_->state() == QAbstractSocket::ConnectedState)
{
bufferToSocket();
}
sendMutex_.unlock();
}
//qDebug() << "Connection thread waiting:" << ID_;
eventDispatcher()->processEvents(QEventLoop::WaitForMoreEvents);
//qDebug() << "Connection thread woken:" << ID_;
}
while(buffer_.size() > 0 && socket_->state() == QAbstractSocket::ConnectedState)
{
bufferToSocket();
}
eventDispatcher()->processEvents(QEventLoop::AllEvents);
qDebug() << "Disconnecting connection with id:" << ID_;
disconnect();
if(socket_ != 0)
delete socket_;
}
void Connection::bufferToSocket()
{
qDebug() << "Sending packet with buffersize:" << buffer_.size();
QString message = buffer_.front();
buffer_.pop();
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << message;
qint64 sentBytes = socket_->write(block);
qDebug() << "Sent Bytes:" << sentBytes;
}
void Connection::disconnect()
{
running_ = false;
shouldConnect_ = false;
socket_->disconnectFromHost();
if (socket_->state() == QAbstractSocket::UnconnectedState ||
socket_->waitForDisconnected(1000))
{
qDebug() << "Disconnected id:" << ID_;
}
else
{
emit error(socket_->error(), socket_->errorString());
return;
}
connected_ = false;
}
void Connection::printError(int socketError, const QString &message)
{
qWarning() << "ERROR. Socket error" << socketError << "for connection:"
<< ID_ << "Error:" << message;
}
void Connection::printBytesWritten(qint64 bytes)
{
qDebug() << bytes << "bytes written to socket for connection ID:" << ID_;
}
<commit_msg>Added a TODO.<commit_after>#include "connection.h"
#include <QDataStream>
#include <QtConcurrent/QtConcurrent>
Connection::Connection(uint32_t id)
:
socket_(0),
shouldConnect_(false),
connected_(),
destination_(),
port_(0),
socketDescriptor_(0),
buffer_(),
sendMutex_(),
running_(false),
started_(false),
ID_(id)
{
qDebug() << "Constructing connection with ID:" << ID_;
}
void Connection::init()
{
QObject::connect(this, &error, this, &printError);
running_ = true;
start();
}
void Connection::establishConnection(QString &destination, uint16_t port)
{
qDebug() << "Establishing connection to" << destination << ":" << port;
destination_ = destination;
port_ = port;
shouldConnect_ = true;
init();
}
void Connection::setExistingConnection(qintptr socketDescriptor)
{
qDebug() << "Setting existing/incoming connection. SocketDesc:" << socketDescriptor;
socketDescriptor_ = socketDescriptor;
init();
}
void Connection::sendPacket(const QString &data)
{
qDebug() << "adding packet for sending";
if(running_)
{
sendMutex_.lock();
buffer_.push(data);
sendMutex_.unlock();
if(started_)
eventDispatcher()->wakeUp();
}
else
{
qWarning() << "Warning: Not sending message, because sender has been shut down.";
}
}
void Connection::receivedMessage()
{
qDebug() << "Socket ready to read:" << ID_;
if(started_)
eventDispatcher()->wakeUp();
}
void Connection::connectLoop()
{
const int connectionTimeout = 5 * 1000; // 5 seconds
qDebug() << "Connecting to address:" << destination_ << "Port:" << port_;
// TODO Stop trying if connection can't be established.
socket_->connectToHost(destination_, port_);
if (!socket_->waitForConnected(connectionTimeout)) {
emit error(socket_->error(), socket_->errorString());
return;
}
connected_ = true;
qDebug() << "Outgoing TCP connection established";
emit connected(ID_);
}
void Connection::run()
{
qDebug() << "Starting connection run loop";
started_ = true;
if(socket_ == 0)
{
socket_ = new QTcpSocket();
QObject::connect(socket_, SIGNAL(bytesWritten(qint64)),
this, SLOT(printBytesWritten(qint64)));
QObject::connect(socket_, SIGNAL(readyRead()),
this, SLOT(receivedMessage()));
}
if(socketDescriptor_ != 0)
{
qDebug() << "Getting socket";
if(!socket_->setSocketDescriptor(socketDescriptor_))
{
qCritical() << "ERROR: Could not get socket descriptor";
}
qDebug() << "Socket connected to our address:" << socket_->localAddress() << ":" << socket_->peerPort()
<< "Peer address:" << socket_->peerAddress() << ":" << socket_->peerPort();
connected_ = true;
}
if(eventDispatcher() == 0)
{
qWarning() << "WARNING: Sorry no event dispatcher for this connection.";
return;
}
while(running_)
{
if(!connected_ && shouldConnect_)
{
connectLoop();
}
if(socket_->bytesToWrite() > 0)
{
qDebug() << "Bytes to write:" << socket_->bytesToWrite() << "in state:" << socket_->state();
}
if(connected_)
{
if(socket_->canReadLine())
{
qDebug() << "Can read line with bytes available:" << socket_->bytesAvailable();
// TODO: maybe not create the data stream everytime.
QDataStream in(socket_);
in.setVersion(QDataStream::Qt_4_0);
QString message;
in >> message;
if(leftOvers_.length() > 0)
{
message = leftOvers_ + message;
}
int headerEndIndex = message.indexOf("\r\n\r\n", 0, Qt::CaseInsensitive) + 4;
int contentLengthIndex = message.indexOf("content-length", 0, Qt::CaseInsensitive);
qDebug() << "header end at:" << headerEndIndex
<< "and content-length at:" << contentLengthIndex;
if(contentLengthIndex != -1 && headerEndIndex != -1)
{
int contentLengthLineEndIndex = message.indexOf("\r\n", contentLengthIndex, Qt::CaseInsensitive);
QString value = message.mid(contentLengthIndex + 16, contentLengthLineEndIndex - (contentLengthIndex + 16));
int valueInt= value.toInt();
qDebug() << "Content-length:" << valueInt;
if(message.length() < headerEndIndex + valueInt)
{
leftOvers_ = message;
}
else
{
leftOvers_ = message.right(message.length() - (headerEndIndex + valueInt));
QString header = message.left(headerEndIndex);
QString content = message.mid(headerEndIndex, valueInt);
qDebug() << "Whole message received.";
qDebug() << "Header:" << header;
qDebug() << "Content:" << content;
qDebug() << "Left overs:" << leftOvers_;
emit messageAvailable(header, content, ID_);
}
}
else
{
qDebug() << "Message was not received fully";
leftOvers_ = message;
}
}
sendMutex_.lock();
while(buffer_.size() > 0 && socket_->state() == QAbstractSocket::ConnectedState)
{
bufferToSocket();
}
sendMutex_.unlock();
}
//qDebug() << "Connection thread waiting:" << ID_;
eventDispatcher()->processEvents(QEventLoop::WaitForMoreEvents);
//qDebug() << "Connection thread woken:" << ID_;
}
while(buffer_.size() > 0 && socket_->state() == QAbstractSocket::ConnectedState)
{
bufferToSocket();
}
eventDispatcher()->processEvents(QEventLoop::AllEvents);
qDebug() << "Disconnecting connection with id:" << ID_;
disconnect();
if(socket_ != 0)
delete socket_;
}
void Connection::bufferToSocket()
{
qDebug() << "Sending packet with buffersize:" << buffer_.size();
QString message = buffer_.front();
buffer_.pop();
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << message;
qint64 sentBytes = socket_->write(block);
qDebug() << "Sent Bytes:" << sentBytes;
}
void Connection::disconnect()
{
running_ = false;
shouldConnect_ = false;
socket_->disconnectFromHost();
if (socket_->state() == QAbstractSocket::UnconnectedState ||
socket_->waitForDisconnected(1000))
{
qDebug() << "Disconnected id:" << ID_;
}
else
{
emit error(socket_->error(), socket_->errorString());
return;
}
connected_ = false;
}
void Connection::printError(int socketError, const QString &message)
{
qWarning() << "ERROR. Socket error" << socketError << "for connection:"
<< ID_ << "Error:" << message;
}
void Connection::printBytesWritten(qint64 bytes)
{
qDebug() << bytes << "bytes written to socket for connection ID:" << ID_;
}
<|endoftext|> |
<commit_before><commit_msg>Fix class_creator::implicit_ctor.<commit_after><|endoftext|> |
<commit_before><commit_msg>Fixing bug in GRD addClique<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: collator_unicode.cxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: kz $ $Date: 2006-01-31 18:35:58 $
*
* 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 <rtl/ustrbuf.hxx>
#include <collator_unicode.hxx>
#include <com/sun/star/i18n/CollatorOptions.hpp>
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
Collator_Unicode::Collator_Unicode()
{
implementationName = "com.sun.star.i18n.Collator_Unicode";
collator = NULL;
}
Collator_Unicode::~Collator_Unicode()
{
if (collator) delete collator;
}
sal_Int32 SAL_CALL
Collator_Unicode::compareSubstring( const OUString& str1, sal_Int32 off1, sal_Int32 len1,
const OUString& str2, sal_Int32 off2, sal_Int32 len2) throw(RuntimeException)
{
return collator->compare(str1.getStr() + off1, len1, str2.getStr() + off2, len2);
}
sal_Int32 SAL_CALL
Collator_Unicode::compareString( const OUString& str1, const OUString& str2) throw(RuntimeException)
{
return collator->compare(str1.getStr(), str2.getStr());
}
sal_Int32 SAL_CALL
Collator_Unicode::loadCollatorAlgorithm(const OUString& rAlgorithm, const lang::Locale& rLocale, sal_Int32 options)
throw(RuntimeException)
{
if (!collator) {
// load ICU collator
UErrorCode status = U_ZERO_ERROR;
if (OUString::createFromAscii(LOCAL_RULE_LANGS).indexOf(rLocale.Language) >= 0) {
OUStringBuffer aBuf;
#ifdef SAL_DLLPREFIX
aBuf.appendAscii(SAL_DLLPREFIX);
#endif
aBuf.appendAscii( "collator_data" ).appendAscii( SAL_DLLEXTENSION );
oslModule hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT );
if (hModule) {
const sal_uInt8* (*func)() = NULL;
aBuf.appendAscii("get_").append(rLocale.Language).appendAscii("_");
if (rLocale.Language.equalsAscii("zh")) {
OUString func_base = aBuf.makeStringAndClear();
if (OUString::createFromAscii("TW HK MO").indexOf(rLocale.Country) >= 0)
func=(const sal_uInt8* (*)()) osl_getSymbol(hModule,
(func_base + OUString::createFromAscii("TW_") + rAlgorithm).pData);
if (!func)
func=(const sal_uInt8* (*)()) osl_getSymbol(hModule, (func_base + rAlgorithm).pData);
} else {
if (rLocale.Language.equalsAscii("ja")) {
// replace algrithm name to implementation name.
if (rAlgorithm.equalsAscii("phonetic (alphanumeric first)") )
aBuf.appendAscii("phonetic_alphanumeric_first");
else if (rAlgorithm.equalsAscii("phonetic (alphanumeric last)"))
aBuf.appendAscii("phonetic_alphanumeric_last");
else
aBuf.append(rAlgorithm);
} else {
aBuf.append(rAlgorithm);
}
func=(const sal_uInt8* (*)()) osl_getSymbol(hModule, aBuf.makeStringAndClear().pData);
}
if (func) {
const sal_uInt8* ruleImage=func();
collator = new RuleBasedCollator(ruleImage, status);
if (! U_SUCCESS(status))
throw RuntimeException();
}
osl_unloadModule(hModule);
}
}
if (!collator) {
// load ICU collator
/** ICU collators are loaded using a locale only.
ICU uses Variant as collation algorithm name (like de__PHONEBOOK
locale), note the empty territory (Country) designator in this special
case here. The icu::Locale contructor changes the algorithm name to
uppercase itself, so we don't have to bother with that.
*/
icu::Locale icuLocale(
OUStringToOString(rLocale.Language, RTL_TEXTENCODING_ASCII_US).getStr(),
OUStringToOString(rLocale.Country, RTL_TEXTENCODING_ASCII_US).getStr(),
OUStringToOString(rAlgorithm, RTL_TEXTENCODING_ASCII_US).getStr());
collator = (RuleBasedCollator*) icu::Collator::createInstance(icuLocale, status);
if (! U_SUCCESS(status))
throw RuntimeException();
}
}
if (options & CollatorOptions::CollatorOptions_IGNORE_CASE_ACCENT)
collator->setStrength(Collator::PRIMARY);
else if (options & CollatorOptions::CollatorOptions_IGNORE_CASE)
collator->setStrength(Collator::SECONDARY);
else
collator->setStrength(Collator::TERTIARY);
return(0);
}
OUString SAL_CALL
Collator_Unicode::getImplementationName() throw( RuntimeException )
{
return OUString::createFromAscii(implementationName);
}
sal_Bool SAL_CALL
Collator_Unicode::supportsService(const rtl::OUString& rServiceName) throw( RuntimeException )
{
return !rServiceName.compareToAscii(implementationName);
}
Sequence< OUString > SAL_CALL
Collator_Unicode::getSupportedServiceNames() throw( RuntimeException )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii(implementationName);
return aRet;
}
} } } }
<commit_msg>#100000# WNT: sal_uInt8* is not const char* ?<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: collator_unicode.cxx,v $
*
* $Revision: 1.11 $
*
* last change: $Author: vg $ $Date: 2006-04-10 10:02:05 $
*
* 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 <rtl/ustrbuf.hxx>
#include <collator_unicode.hxx>
#include <com/sun/star/i18n/CollatorOptions.hpp>
using namespace ::com::sun::star;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::uno;
using namespace ::rtl;
namespace com { namespace sun { namespace star { namespace i18n {
Collator_Unicode::Collator_Unicode()
{
implementationName = "com.sun.star.i18n.Collator_Unicode";
collator = NULL;
}
Collator_Unicode::~Collator_Unicode()
{
if (collator) delete collator;
}
sal_Int32 SAL_CALL
Collator_Unicode::compareSubstring( const OUString& str1, sal_Int32 off1, sal_Int32 len1,
const OUString& str2, sal_Int32 off2, sal_Int32 len2) throw(RuntimeException)
{
return collator->compare(str1.getStr() + off1, len1, str2.getStr() + off2, len2);
}
sal_Int32 SAL_CALL
Collator_Unicode::compareString( const OUString& str1, const OUString& str2) throw(RuntimeException)
{
return collator->compare(str1.getStr(), str2.getStr());
}
sal_Int32 SAL_CALL
Collator_Unicode::loadCollatorAlgorithm(const OUString& rAlgorithm, const lang::Locale& rLocale, sal_Int32 options)
throw(RuntimeException)
{
if (!collator) {
// load ICU collator
UErrorCode status = U_ZERO_ERROR;
if (OUString::createFromAscii(LOCAL_RULE_LANGS).indexOf(rLocale.Language) >= 0) {
OUStringBuffer aBuf;
#ifdef SAL_DLLPREFIX
aBuf.appendAscii(SAL_DLLPREFIX);
#endif
aBuf.appendAscii( "collator_data" ).appendAscii( SAL_DLLEXTENSION );
oslModule hModule = osl_loadModule( aBuf.makeStringAndClear().pData, SAL_LOADMODULE_DEFAULT );
if (hModule) {
const sal_uInt8* (*func)() = NULL;
aBuf.appendAscii("get_").append(rLocale.Language).appendAscii("_");
if (rLocale.Language.equalsAscii("zh")) {
OUString func_base = aBuf.makeStringAndClear();
if (OUString::createFromAscii("TW HK MO").indexOf(rLocale.Country) >= 0)
func=(const sal_uInt8* (*)()) osl_getSymbol(hModule,
(func_base + OUString::createFromAscii("TW_") + rAlgorithm).pData);
if (!func)
func=(const sal_uInt8* (*)()) osl_getSymbol(hModule, (func_base + rAlgorithm).pData);
} else {
if (rLocale.Language.equalsAscii("ja")) {
// replace algrithm name to implementation name.
if (rAlgorithm.equalsAscii("phonetic (alphanumeric first)") )
aBuf.appendAscii("phonetic_alphanumeric_first");
else if (rAlgorithm.equalsAscii("phonetic (alphanumeric last)"))
aBuf.appendAscii("phonetic_alphanumeric_last");
else
aBuf.append(rAlgorithm);
} else {
aBuf.append(rAlgorithm);
}
func=(const sal_uInt8* (*)()) osl_getSymbol(hModule, aBuf.makeStringAndClear().pData);
}
if (func) {
const sal_uInt8* ruleImage=func();
collator = new RuleBasedCollator(UnicodeString(reinterpret_cast<const char*>(ruleImage)), status);
if (! U_SUCCESS(status))
throw RuntimeException();
}
osl_unloadModule(hModule);
}
}
if (!collator) {
// load ICU collator
/** ICU collators are loaded using a locale only.
ICU uses Variant as collation algorithm name (like de__PHONEBOOK
locale), note the empty territory (Country) designator in this special
case here. The icu::Locale contructor changes the algorithm name to
uppercase itself, so we don't have to bother with that.
*/
icu::Locale icuLocale(
OUStringToOString(rLocale.Language, RTL_TEXTENCODING_ASCII_US).getStr(),
OUStringToOString(rLocale.Country, RTL_TEXTENCODING_ASCII_US).getStr(),
OUStringToOString(rAlgorithm, RTL_TEXTENCODING_ASCII_US).getStr());
collator = (RuleBasedCollator*) icu::Collator::createInstance(icuLocale, status);
if (! U_SUCCESS(status))
throw RuntimeException();
}
}
if (options & CollatorOptions::CollatorOptions_IGNORE_CASE_ACCENT)
collator->setStrength(Collator::PRIMARY);
else if (options & CollatorOptions::CollatorOptions_IGNORE_CASE)
collator->setStrength(Collator::SECONDARY);
else
collator->setStrength(Collator::TERTIARY);
return(0);
}
OUString SAL_CALL
Collator_Unicode::getImplementationName() throw( RuntimeException )
{
return OUString::createFromAscii(implementationName);
}
sal_Bool SAL_CALL
Collator_Unicode::supportsService(const rtl::OUString& rServiceName) throw( RuntimeException )
{
return !rServiceName.compareToAscii(implementationName);
}
Sequence< OUString > SAL_CALL
Collator_Unicode::getSupportedServiceNames() throw( RuntimeException )
{
Sequence< OUString > aRet(1);
aRet[0] = OUString::createFromAscii(implementationName);
return aRet;
}
} } } }
<|endoftext|> |
<commit_before>// Copyright 2017 Netherlands eScience Center and Netherlands Institute for Radio Astronomy (ASTRON)
//
// 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 <ReadData.hpp>
namespace AstroData
{
RingBufferError::RingBufferError(const std::string &message) : message(message) {}
RingBufferError::~RingBufferError() noexcept {}
const char *RingBufferError::what() const noexcept
{
return message.c_str();
}
void readZappedChannels(Observation &observation, const std::string &inputFilename, std::vector<unsigned int> &zappedChannels)
{
unsigned int nrChannels = 0;
std::ifstream input;
input.open(inputFilename);
if (!input)
{
throw FileError("ERROR: impossible to open zapped channels file \"" + inputFilename + "\"");
}
while (!input.eof())
{
unsigned int channel = observation.getNrChannels();
input >> channel;
if (channel < observation.getNrChannels())
{
zappedChannels[channel] = 1;
nrChannels++;
}
}
input.close();
observation.setNrZappedChannels(nrChannels);
}
void readIntegrationSteps(const Observation &observation, const std::string &inputFilename, std::set<unsigned int> &integrationSteps)
{
std::ifstream input;
input.open(inputFilename);
if (!input)
{
throw FileError("ERROR: impossible to open integration steps file \"" + inputFilename + "\"");
}
while (!input.eof())
{
unsigned int step = observation.getNrSamplesPerBatch();
input >> step;
if (step < observation.getNrSamplesPerBatch())
{
integrationSteps.insert(step);
}
}
input.close();
}
std::uint64_t getSIGPROCHeaderSize(const std::string &inputFilename)
{
std::uint64_t headerSize = 0;
std::uint8_t state = 0;
char buffer = '\0';
std::ifstream inputFile;
inputFile.open(inputFilename.c_str(), std::ios::binary);
inputFile.exceptions(std::ifstream::failbit);
if ( !inputFile )
{
throw FileError("ERROR: impossible to open SIGPROC file \"" + inputFilename + "\".");
}
while ( inputFile.get(buffer) )
{
switch ( buffer )
{
case 'H':
state = 1;
break;
case 'E':
if ( (state == 1) || (state == 4) || (state == 7) )
{
state++;
}
else
{
state = 0;
}
break;
case 'A':
if ( state == 2 )
{
state++;
}
else
{
state = 0;
}
break;
case 'D':
if ( (state == 3) || (state == 9) )
{
state++;
}
else
{
state = 0;
}
break;
case 'R':
if ( state == 5 )
{
state++;
}
else
{
state = 0;
}
break;
case '_':
if ( state == 6 )
{
state++;
}
else
{
state = 0;
}
break;
case 'N':
if ( state == 8 )
{
state++;
}
else
{
state = 0;
}
break;
default:
break;
}
headerSize++;
if ( state == 10 )
{
break;
}
}
inputFile.close();
return headerSize;
}
void readSIGPROCHeader(const std::uint64_t headerSize, Observation & observation, const std::string & inputFilename, const unsigned int subbands)
{
std::uint64_t bytesRead = 0;
std::uint8_t state = 0;
std::ifstream inputFile;
// Temporary variables
char buffer = '\0';
char * temp32 = new char [4];
char * temp64 = new char [8];
double tsamp = 0.0;
unsigned int nsamples = 0;
double fch1 = 0.0;
double foff = 0.0;
unsigned int nchans = 0;
inputFile.open(inputFilename.c_str(), std::ios::binary);
inputFile.exceptions(std::ifstream::failbit);
if ( !inputFile )
{
throw FileError("ERROR: impossible to open SIGPROC file \"" + inputFilename + "\".");
}
while ( inputFile.get(buffer) )
{
switch ( buffer )
{
case 't':
if ( state == 0 )
{
state = 1;
}
break;
case 's':
if ( (state == 1) || (state == 5) )
{
state++;
}
else if ( state == 11 )
{
// nsamples : int
inputFile.read(temp32, 4);
nsamples = *(reinterpret_cast<unsigned int *>(temp32));
bytesRead += 4;
state = 0;
}
else if ( state == 20 )
{
// nchans : int
inputFile.read(temp32, 4);
nchans = *(reinterpret_cast<unsigned int *>(temp32));
bytesRead += 4;
state = 0;
}
else
{
state = 0;
}
break;
case 'a':
if ( (state == 2) || (state == 6) || (state == 18) )
{
state++;
}
else
{
state = 0;
}
break;
case 'm':
if ( (state == 3) || (state == 7) )
{
state++;
}
else
{
state = 0;
}
break;
case 'p':
if ( state == 4 )
{
// tsamp : double
inputFile.read(temp64, 8);
tsamp = *(reinterpret_cast<double *>(temp64));
bytesRead += 8;
state = 0;
}
else if ( state == 8 )
{
state++;
}
else
{
state = 0;
}
break;
case 'n':
if ( state == 0 )
{
state = 5;
}
else if ( state == 19 )
{
state++;
}
else
{
state = 0;
}
break;
case 'l':
if ( state == 9 )
{
state++;
}
else
{
state = 0;
}
break;
case 'e':
if ( state == 10 )
{
state++;
}
else
{
state = 0;
}
break;
case 'f':
if ( state == 0 )
{
state = 12;
}
else if ( state == 15 )
{
state++;
}
else if ( state == 16 )
{
// foff : double
inputFile.read(temp64, 8);
foff = *(reinterpret_cast<double *>(temp64));
bytesRead += 8;
state = 0;
}
else
{
state = 0;
}
break;
case 'c':
if ( state == 12 )
{
state++;
}
else if ( state == 5 )
{
state = 17;
}
else
{
state = 0;
}
break;
case 'h':
if ( (state == 13) || (state == 17) )
{
state++;
}
else
{
state = 0;
}
break;
case '1':
if ( state == 14 )
{
// fch1 : double
inputFile.read(temp64, 8);
fch1 = *(reinterpret_cast<double *>(temp64));
bytesRead += 8;
state = 0;
}
else
{
state = 0;
}
break;
case 'o':
if ( state == 12 )
{
state = 15;
}
else
{
state = 0;
}
break;
default:
break;
}
bytesRead++;
if ( bytesRead >= headerSize )
{
break;
}
}
inputFile.close();
observation.setNrSamplesPerBatch(nsamples);
observation.setSamplingTime(tsamp);
observation.setFrequencyRange(subbands, nchans, fch1 + (foff * (nchans - 1)), -foff);
}
#ifdef HAVE_PSRDADA
void readPSRDADAHeader(Observation &observation, dada_hdu_t &ringBuffer)
{
// Staging variables for the header elements
unsigned int uintValue = 0;
float floatValue[2] = {0.0f, 0.0f};
// Header string
uint64_t headerBytes = 0;
char *header = 0;
header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes);
if ((header == 0) || (headerBytes == 0))
{
throw RingBufferError("ERROR: impossible to read the PSRDADA header");
}
ascii_header_get(header, "SAMPLES_PER_BATCH", "%d", &uintValue);
observation.setNrSamplesPerBatch(uintValue);
ascii_header_get(header, "NCHAN", "%d", &uintValue);
ascii_header_get(header, "MIN_FREQUENCY", "%f", &floatValue[0]);
ascii_header_get(header, "CHANNEL_BANDWIDTH", "%f", &floatValue[1]);
observation.setFrequencyRange(observation.getNrSubbands(), uintValue, floatValue[0], floatValue[1]);
ascii_header_get(header, "TSAMP", "%f", &floatValue[0]);
observation.setSamplingTime(floatValue[0]);
if (ipcbuf_mark_cleared(ringBuffer.header_block) < 0)
{
throw RingBufferError("ERROR: impossible to mark the PSRDADA header as cleared");
}
}
#endif // HAVE_PSRDADA
} // namespace AstroData
<commit_msg>Fix to compute the right number of samples per batch.<commit_after>// Copyright 2017 Netherlands eScience Center and Netherlands Institute for Radio Astronomy (ASTRON)
//
// 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 <ReadData.hpp>
namespace AstroData
{
RingBufferError::RingBufferError(const std::string &message) : message(message) {}
RingBufferError::~RingBufferError() noexcept {}
const char *RingBufferError::what() const noexcept
{
return message.c_str();
}
void readZappedChannels(Observation &observation, const std::string &inputFilename, std::vector<unsigned int> &zappedChannels)
{
unsigned int nrChannels = 0;
std::ifstream input;
input.open(inputFilename);
if (!input)
{
throw FileError("ERROR: impossible to open zapped channels file \"" + inputFilename + "\"");
}
while (!input.eof())
{
unsigned int channel = observation.getNrChannels();
input >> channel;
if (channel < observation.getNrChannels())
{
zappedChannels[channel] = 1;
nrChannels++;
}
}
input.close();
observation.setNrZappedChannels(nrChannels);
}
void readIntegrationSteps(const Observation &observation, const std::string &inputFilename, std::set<unsigned int> &integrationSteps)
{
std::ifstream input;
input.open(inputFilename);
if (!input)
{
throw FileError("ERROR: impossible to open integration steps file \"" + inputFilename + "\"");
}
while (!input.eof())
{
unsigned int step = observation.getNrSamplesPerBatch();
input >> step;
if (step < observation.getNrSamplesPerBatch())
{
integrationSteps.insert(step);
}
}
input.close();
}
std::uint64_t getSIGPROCHeaderSize(const std::string &inputFilename)
{
std::uint64_t headerSize = 0;
std::uint8_t state = 0;
char buffer = '\0';
std::ifstream inputFile;
inputFile.open(inputFilename.c_str(), std::ios::binary);
inputFile.exceptions(std::ifstream::failbit);
if ( !inputFile )
{
throw FileError("ERROR: impossible to open SIGPROC file \"" + inputFilename + "\".");
}
while ( inputFile.get(buffer) )
{
switch ( buffer )
{
case 'H':
state = 1;
break;
case 'E':
if ( (state == 1) || (state == 4) || (state == 7) )
{
state++;
}
else
{
state = 0;
}
break;
case 'A':
if ( state == 2 )
{
state++;
}
else
{
state = 0;
}
break;
case 'D':
if ( (state == 3) || (state == 9) )
{
state++;
}
else
{
state = 0;
}
break;
case 'R':
if ( state == 5 )
{
state++;
}
else
{
state = 0;
}
break;
case '_':
if ( state == 6 )
{
state++;
}
else
{
state = 0;
}
break;
case 'N':
if ( state == 8 )
{
state++;
}
else
{
state = 0;
}
break;
default:
break;
}
headerSize++;
if ( state == 10 )
{
break;
}
}
inputFile.close();
return headerSize;
}
void readSIGPROCHeader(const std::uint64_t headerSize, Observation & observation, const std::string & inputFilename, const unsigned int subbands)
{
std::uint64_t bytesRead = 0;
std::uint8_t state = 0;
std::ifstream inputFile;
// Temporary variables
char buffer = '\0';
char * temp32 = new char [4];
char * temp64 = new char [8];
double tsamp = 0.0;
unsigned int nsamples = 0;
double fch1 = 0.0;
double foff = 0.0;
unsigned int nchans = 0;
inputFile.open(inputFilename.c_str(), std::ios::binary);
inputFile.exceptions(std::ifstream::failbit);
if ( !inputFile )
{
throw FileError("ERROR: impossible to open SIGPROC file \"" + inputFilename + "\".");
}
while ( inputFile.get(buffer) )
{
switch ( buffer )
{
case 't':
if ( state == 0 )
{
state = 1;
}
break;
case 's':
if ( (state == 1) || (state == 5) )
{
state++;
}
else if ( state == 11 )
{
// nsamples : int
inputFile.read(temp32, 4);
nsamples = *(reinterpret_cast<unsigned int *>(temp32));
bytesRead += 4;
state = 0;
}
else if ( state == 20 )
{
// nchans : int
inputFile.read(temp32, 4);
nchans = *(reinterpret_cast<unsigned int *>(temp32));
bytesRead += 4;
state = 0;
}
else
{
state = 0;
}
break;
case 'a':
if ( (state == 2) || (state == 6) || (state == 18) )
{
state++;
}
else
{
state = 0;
}
break;
case 'm':
if ( (state == 3) || (state == 7) )
{
state++;
}
else
{
state = 0;
}
break;
case 'p':
if ( state == 4 )
{
// tsamp : double
inputFile.read(temp64, 8);
tsamp = *(reinterpret_cast<double *>(temp64));
bytesRead += 8;
state = 0;
}
else if ( state == 8 )
{
state++;
}
else
{
state = 0;
}
break;
case 'n':
if ( state == 0 )
{
state = 5;
}
else if ( state == 19 )
{
state++;
}
else
{
state = 0;
}
break;
case 'l':
if ( state == 9 )
{
state++;
}
else
{
state = 0;
}
break;
case 'e':
if ( state == 10 )
{
state++;
}
else
{
state = 0;
}
break;
case 'f':
if ( state == 0 )
{
state = 12;
}
else if ( state == 15 )
{
state++;
}
else if ( state == 16 )
{
// foff : double
inputFile.read(temp64, 8);
foff = *(reinterpret_cast<double *>(temp64));
bytesRead += 8;
state = 0;
}
else
{
state = 0;
}
break;
case 'c':
if ( state == 12 )
{
state++;
}
else if ( state == 5 )
{
state = 17;
}
else
{
state = 0;
}
break;
case 'h':
if ( (state == 13) || (state == 17) )
{
state++;
}
else
{
state = 0;
}
break;
case '1':
if ( state == 14 )
{
// fch1 : double
inputFile.read(temp64, 8);
fch1 = *(reinterpret_cast<double *>(temp64));
bytesRead += 8;
state = 0;
}
else
{
state = 0;
}
break;
case 'o':
if ( state == 12 )
{
state = 15;
}
else
{
state = 0;
}
break;
default:
break;
}
bytesRead++;
if ( bytesRead >= headerSize )
{
break;
}
}
inputFile.close();
observation.setNrSamplesPerBatch(nsamples / observation.getNrBatches());
observation.setSamplingTime(tsamp);
observation.setFrequencyRange(subbands, nchans, fch1 + (foff * (nchans - 1)), -foff);
}
#ifdef HAVE_PSRDADA
void readPSRDADAHeader(Observation &observation, dada_hdu_t &ringBuffer)
{
// Staging variables for the header elements
unsigned int uintValue = 0;
float floatValue[2] = {0.0f, 0.0f};
// Header string
uint64_t headerBytes = 0;
char *header = 0;
header = ipcbuf_get_next_read(ringBuffer.header_block, &headerBytes);
if ((header == 0) || (headerBytes == 0))
{
throw RingBufferError("ERROR: impossible to read the PSRDADA header");
}
ascii_header_get(header, "SAMPLES_PER_BATCH", "%d", &uintValue);
observation.setNrSamplesPerBatch(uintValue);
ascii_header_get(header, "NCHAN", "%d", &uintValue);
ascii_header_get(header, "MIN_FREQUENCY", "%f", &floatValue[0]);
ascii_header_get(header, "CHANNEL_BANDWIDTH", "%f", &floatValue[1]);
observation.setFrequencyRange(observation.getNrSubbands(), uintValue, floatValue[0], floatValue[1]);
ascii_header_get(header, "TSAMP", "%f", &floatValue[0]);
observation.setSamplingTime(floatValue[0]);
if (ipcbuf_mark_cleared(ringBuffer.header_block) < 0)
{
throw RingBufferError("ERROR: impossible to mark the PSRDADA header as cleared");
}
}
#endif // HAVE_PSRDADA
} // namespace AstroData
<|endoftext|> |
<commit_before>#include "Resolver.h"
#include "Hash.h"
#include "Requirement.h"
#include <cassert>
#include <exception>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
using namespace Arbiter;
using namespace Resolver;
namespace {
/**
* Filters out versions from the given generator which fail the given
* requirement, saving whatever is left (even if just a terminal event) into
* `promise`.
*/
void satisfyPromiseWithFirstVersionPassingRequirement (std::shared_ptr<Promise<Optional<ArbiterSelectedVersion>>> promise, std::shared_ptr<Generator<ArbiterSelectedVersion>> versions, std::shared_ptr<ArbiterRequirement> requirement)
{
versions->next().add_callback([promise, versions, requirement](const auto &result) {
if (result.hasLeft() || !result.right() || requirement->satisfiedBy(result.right()->_semanticVersion)) {
promise->set_result(result);
} else {
satisfyPromiseWithFirstVersionPassingRequirement(promise, versions, requirement);
}
});
}
/**
* A node in, or being considered for, an acyclic dependency graph.
*/
class DependencyNode final
{
public:
struct Hash final
{
public:
size_t operator() (const DependencyNode &node) const
{
return hashOf(node._project);
}
};
const ArbiterProjectIdentifier _project;
/**
* The version of the dependency that this node represents.
*
* This version is merely "proposed" because it depends on the final
* resolution of the graph, as well as whether any "better" graphs exist.
*/
const ArbiterSelectedVersion _proposedVersion;
DependencyNode (ArbiterProjectIdentifier project, ArbiterSelectedVersion proposedVersion, const ArbiterRequirement &requirement)
: _project(std::move(project))
, _proposedVersion(std::move(proposedVersion))
, _state(std::make_shared<State>())
{
setRequirement(requirement);
}
DependencyNode (const DependencyNode &other) noexcept
: _project(other._project)
, _proposedVersion(other._proposedVersion)
, _state(other._state)
{}
DependencyNode (DependencyNode &&other) noexcept
: _project(other._project)
, _proposedVersion(other._proposedVersion)
, _state(std::move(other._state))
{}
DependencyNode &operator= (const DependencyNode &) = delete;
DependencyNode &operator= (DependencyNode &&) = delete;
bool operator== (const DependencyNode &other) const
{
// For the purposes of node lookup in a graph, this is the only field
// which matters.
return _project == other._project;
}
/**
* The current requirement(s) applied to this dependency.
*
* This specifier may change as the graph is added to, and the requirements
* become more stringent.
*/
const ArbiterRequirement &requirement () const noexcept
{
return *_state->_requirement;
}
void setRequirement (const ArbiterRequirement &requirement)
{
setRequirement(requirement.clone());
}
void setRequirement (std::unique_ptr<ArbiterRequirement> requirement)
{
assert(requirement);
assert(requirement->satisfiedBy(_proposedVersion._semanticVersion));
_state->_requirement = std::move(requirement);
}
std::unordered_set<DependencyNode, Hash> &dependencies () noexcept
{
return _state->_dependencies;
}
const std::unordered_set<DependencyNode, Hash> &dependencies () const noexcept
{
return _state->_dependencies;
}
private:
struct State final
{
public:
std::unique_ptr<ArbiterRequirement> _requirement;
std::unordered_set<DependencyNode, Hash> _dependencies;
};
std::shared_ptr<State> _state;
};
std::ostream &operator<< (std::ostream &os, const DependencyNode &node)
{
return os
<< node._project << " @ " << node._proposedVersion
<< " (restricted to " << node.requirement() << ")";
}
} // namespace
namespace std {
template<>
struct hash<DependencyNode> final
{
public:
size_t operator() (const DependencyNode &node) const
{
return DependencyNode::Hash()(node);
}
};
} // namespace std
namespace {
/**
* Represents an acyclic dependency graph in which each project appears at most
* once.
*
* Dependency graphs can exist in an incomplete state, but will never be
* inconsistent (i.e., include versions that are known to be invalid given the
* current graph).
*/
class DependencyGraph final
{
public:
/**
* A full list of all nodes included in the graph.
*/
std::unordered_set<DependencyNode> _allNodes;
/**
* Maps between nodes in the graph and their immediate dependencies.
*/
std::unordered_map<DependencyNode, std::unordered_set<DependencyNode>> _edges;
/**
* The root nodes of the graph (i.e., those dependencies that are listed by
* the top-level project).
*/
std::unordered_set<DependencyNode> _roots;
bool operator== (const DependencyGraph &other) const
{
return _edges == other._edges && _roots == other._roots;
}
/**
* Attempts to add the given node into the graph, as a dependency of
* `dependent` if specified.
*
* If the given node refers to a project which already exists in the graph,
* this method will attempt to intersect the version requirements of both.
*
* Returns a pointer to the node as actually inserted into the graph (which
* may be different from the node passed in), or `nullptr` if this addition
* would make the graph inconsistent.
*/
DependencyNode *addNode (const DependencyNode &inputNode, const DependencyNode *dependent)
{
auto nodeInsertion = _allNodes.insert(inputNode);
// Unordered collections rightly discourage mutation so hashes don't get
// invalidated, but we've already handled this in the implementation of
// DependencyNode.
DependencyNode &insertedNode = const_cast<DependencyNode &>(*nodeInsertion.first);
// If no insertion was actually performed, we need to unify our input with
// what was already there.
if (!nodeInsertion.second) {
if (auto newRequirement = insertedNode.requirement().intersect(inputNode.requirement())) {
if (!newRequirement->satisfiedBy(insertedNode._proposedVersion._semanticVersion)) {
// This strengthened requirement invalidates the version we've
// proposed in this graph, so the graph would become inconsistent.
return nullptr;
}
insertedNode.setRequirement(std::move(newRequirement));
} else {
// If intersecting the requirements is impossible, the versions
// currently shouldn't be able to match.
//
// Notably, though, Carthage does permit scenarios like this when
// pinned to a branch. Arbiter doesn't support requirements like this
// right now, but may in the future.
assert(inputNode._proposedVersion != insertedNode._proposedVersion);
return nullptr;
}
}
if (dependent) {
_edges[*dependent].insert(insertedNode);
} else {
_roots.insert(insertedNode);
}
return &insertedNode;
}
};
std::ostream &operator<< (std::ostream &os, const DependencyGraph &graph)
{
os << "Roots:";
for (const DependencyNode &root : graph._roots) {
os << "\n\t" << root;
}
os << "\n\nEdges";
for (const auto &pair : graph._edges) {
const DependencyNode &node = pair.first;
os << "\n\t" << node._project << " ->";
const auto &dependencies = pair.second;
for (const DependencyNode &dep : dependencies) {
os << "\n\t\t" << dep;
}
}
return os;
}
} // namespace
ArbiterResolver *ArbiterCreateResolver (ArbiterResolverBehaviors behaviors, const ArbiterDependencyList *dependencyList, ArbiterUserValue context)
{
return new ArbiterResolver(std::move(behaviors), *dependencyList, ArbiterResolver::Context(std::move(context)));
}
const void *ArbiterResolverContext (const ArbiterResolver *resolver)
{
return resolver->_context.data();
}
bool ArbiterResolvedAllDependencies (const ArbiterResolver *resolver)
{
return resolver->resolvedAll();
}
void ArbiterStartResolvingNextDependency (ArbiterResolver *resolver, ArbiterResolverCallbacks callbacks)
{
resolver->resolveNext().add_callback([resolver, callbacks = std::move(callbacks)](const auto &result) {
try {
const ResolvedDependency &dependency = result.rightOrThrowLeft();
callbacks.onSuccess(resolver, &dependency.projectIdentifier, &dependency.selectedVersion);
} catch (const std::exception &ex) {
callbacks.onError(resolver, ex.what());
}
});
}
void ArbiterFreeResolver (ArbiterResolver *resolver)
{
delete resolver;
}
ResolvedDependency ResolvedDependency::takeOwnership (ArbiterDependencyListFetch fetch) noexcept
{
std::unique_ptr<ArbiterProjectIdentifier> project(const_cast<ArbiterProjectIdentifier *>(fetch.project));
std::unique_ptr<ArbiterSelectedVersion> selectedVersion(const_cast<ArbiterSelectedVersion *>(fetch.selectedVersion));
return ResolvedDependency { std::move(*project), std::move(*selectedVersion) };
}
bool ResolvedDependency::operator== (const ResolvedDependency &other) const noexcept
{
return projectIdentifier == other.projectIdentifier && selectedVersion == other.selectedVersion;
}
bool ArbiterResolver::resolvedAll () const noexcept
{
return _remainingDependencies._dependencies.empty();
}
Arbiter::Future<ResolvedDependency> resolveNext ()
{
Arbiter::Promise<ResolvedDependency> promise;
// TODO: Actually resolve
return promise.get_future();
}
Arbiter::Future<ArbiterDependencyList> ArbiterResolver::insertDependencyListFetch (ResolvedDependency dependency)
{
std::lock_guard<std::mutex> lock(_fetchesMutex);
return _dependencyListFetches[std::move(dependency)].get_future();
}
Arbiter::Promise<ArbiterDependencyList> ArbiterResolver::extractDependencyListFetch (const ResolvedDependency &dependency)
{
std::lock_guard<std::mutex> lock(_fetchesMutex);
Arbiter::Promise<ArbiterDependencyList> promise = std::move(_dependencyListFetches.at(dependency));
_dependencyListFetches.erase(dependency);
return promise;
}
Arbiter::Generator<ArbiterSelectedVersion> ArbiterResolver::insertAvailableVersionsFetch (ArbiterProjectIdentifier fetch)
{
std::lock_guard<std::mutex> lock(_fetchesMutex);
return _availableVersionsFetches[std::move(fetch)].getGenerator();
}
Arbiter::Sink<ArbiterSelectedVersion> ArbiterResolver::extractAvailableVersionsFetch (const ArbiterProjectIdentifier &fetch)
{
std::lock_guard<std::mutex> lock(_fetchesMutex);
Arbiter::Sink<ArbiterSelectedVersion> sink = std::move(_availableVersionsFetches.at(fetch));
_availableVersionsFetches.erase(fetch);
return sink;
}
Arbiter::Future<ArbiterDependencyList> ArbiterResolver::fetchDependencyList (ResolvedDependency dependency)
{
// Eventually freed in the C callback function.
auto project = std::make_unique<ArbiterProjectIdentifier>(dependency.projectIdentifier);
auto version = std::make_unique<ArbiterSelectedVersion>(dependency.selectedVersion);
auto future = insertDependencyListFetch(std::move(dependency));
_behaviors.fetchDependencyList(
ArbiterDependencyListFetch { this, project.release(), version.release() },
&dependencyListFetchOnSuccess,
&dependencyListFetchOnError
);
return future;
}
Arbiter::Generator<ArbiterSelectedVersion> ArbiterResolver::fetchAvailableVersions (ArbiterProjectIdentifier project)
{
// Eventually freed in the C callback function.
auto projectCopy = std::make_unique<ArbiterProjectIdentifier>(project);
auto generator = insertAvailableVersionsFetch(std::move(project));
_behaviors.fetchAvailableVersions(
ArbiterAvailableVersionsFetch { this, projectCopy.release() },
&availableVersionsFetchOnNext,
&availableVersionsFetchOnCompleted,
&availableVersionsFetchOnError
);
return generator;
}
Generator<ArbiterSelectedVersion> ArbiterResolver::fetchAvailableVersions (ArbiterProjectIdentifier project, const ArbiterRequirement &requirement)
{
auto allVersions = std::make_shared<Generator<ArbiterSelectedVersion>>(fetchAvailableVersions(project));
std::shared_ptr<ArbiterRequirement> sharedRequirement(requirement.clone());
return Arbiter::Generator<ArbiterSelectedVersion>([allVersions, sharedRequirement] {
auto promise = std::make_shared<Promise<Optional<ArbiterSelectedVersion>>>();
satisfyPromiseWithFirstVersionPassingRequirement(promise, allVersions, sharedRequirement);
return promise->get_future();
});
}
void ArbiterResolver::dependencyListFetchOnSuccess (ArbiterDependencyListFetch cFetch, const ArbiterDependencyList *fetchedList)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
auto dependency = ResolvedDependency::takeOwnership(cFetch);
resolver
.extractDependencyListFetch(dependency)
.set_value(*fetchedList);
}
void ArbiterResolver::dependencyListFetchOnError (ArbiterDependencyListFetch cFetch)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
auto dependency = ResolvedDependency::takeOwnership(cFetch);
resolver
.extractDependencyListFetch(dependency)
// TODO: Better error reporting
.set_exception(std::make_exception_ptr(std::runtime_error("Dependency list fetch failed")));
}
void ArbiterResolver::availableVersionsFetchOnNext (ArbiterAvailableVersionsFetch cFetch, const ArbiterSelectedVersion *nextVersion)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
const auto &project = *cFetch.project;
std::lock_guard<std::mutex> lock(resolver._fetchesMutex);
resolver
._availableVersionsFetches
.at(project)
.onNext(*nextVersion);
}
void ArbiterResolver::availableVersionsFetchOnCompleted (ArbiterAvailableVersionsFetch cFetch)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
std::unique_ptr<ArbiterProjectIdentifier> project(const_cast<ArbiterProjectIdentifier *>(cFetch.project));
resolver
.extractAvailableVersionsFetch(*project)
.onCompleted();
}
void ArbiterResolver::availableVersionsFetchOnError (ArbiterAvailableVersionsFetch cFetch)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
std::unique_ptr<ArbiterProjectIdentifier> project(const_cast<ArbiterProjectIdentifier *>(cFetch.project));
resolver
.extractAvailableVersionsFetch(*project)
// TODO: Better error reporting
.onError(std::make_exception_ptr(std::runtime_error("Available versions fetch failed")));
}
<commit_msg>Add TODO where dependency resolution needs to happen<commit_after>#include "Resolver.h"
#include "Hash.h"
#include "Requirement.h"
#include <cassert>
#include <exception>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
using namespace Arbiter;
using namespace Resolver;
namespace {
/**
* Filters out versions from the given generator which fail the given
* requirement, saving whatever is left (even if just a terminal event) into
* `promise`.
*/
void satisfyPromiseWithFirstVersionPassingRequirement (std::shared_ptr<Promise<Optional<ArbiterSelectedVersion>>> promise, std::shared_ptr<Generator<ArbiterSelectedVersion>> versions, std::shared_ptr<ArbiterRequirement> requirement)
{
versions->next().add_callback([promise, versions, requirement](const auto &result) {
if (result.hasLeft() || !result.right() || requirement->satisfiedBy(result.right()->_semanticVersion)) {
promise->set_result(result);
} else {
satisfyPromiseWithFirstVersionPassingRequirement(promise, versions, requirement);
}
});
}
/**
* A node in, or being considered for, an acyclic dependency graph.
*/
class DependencyNode final
{
public:
struct Hash final
{
public:
size_t operator() (const DependencyNode &node) const
{
return hashOf(node._project);
}
};
const ArbiterProjectIdentifier _project;
/**
* The version of the dependency that this node represents.
*
* This version is merely "proposed" because it depends on the final
* resolution of the graph, as well as whether any "better" graphs exist.
*/
const ArbiterSelectedVersion _proposedVersion;
DependencyNode (ArbiterProjectIdentifier project, ArbiterSelectedVersion proposedVersion, const ArbiterRequirement &requirement)
: _project(std::move(project))
, _proposedVersion(std::move(proposedVersion))
, _state(std::make_shared<State>())
{
setRequirement(requirement);
}
DependencyNode (const DependencyNode &other) noexcept
: _project(other._project)
, _proposedVersion(other._proposedVersion)
, _state(other._state)
{}
DependencyNode (DependencyNode &&other) noexcept
: _project(other._project)
, _proposedVersion(other._proposedVersion)
, _state(std::move(other._state))
{}
DependencyNode &operator= (const DependencyNode &) = delete;
DependencyNode &operator= (DependencyNode &&) = delete;
bool operator== (const DependencyNode &other) const
{
// For the purposes of node lookup in a graph, this is the only field
// which matters.
return _project == other._project;
}
/**
* The current requirement(s) applied to this dependency.
*
* This specifier may change as the graph is added to, and the requirements
* become more stringent.
*/
const ArbiterRequirement &requirement () const noexcept
{
return *_state->_requirement;
}
void setRequirement (const ArbiterRequirement &requirement)
{
setRequirement(requirement.clone());
}
void setRequirement (std::unique_ptr<ArbiterRequirement> requirement)
{
assert(requirement);
assert(requirement->satisfiedBy(_proposedVersion._semanticVersion));
_state->_requirement = std::move(requirement);
}
std::unordered_set<DependencyNode, Hash> &dependencies () noexcept
{
return _state->_dependencies;
}
const std::unordered_set<DependencyNode, Hash> &dependencies () const noexcept
{
return _state->_dependencies;
}
private:
struct State final
{
public:
std::unique_ptr<ArbiterRequirement> _requirement;
std::unordered_set<DependencyNode, Hash> _dependencies;
};
std::shared_ptr<State> _state;
};
std::ostream &operator<< (std::ostream &os, const DependencyNode &node)
{
return os
<< node._project << " @ " << node._proposedVersion
<< " (restricted to " << node.requirement() << ")";
}
} // namespace
namespace std {
template<>
struct hash<DependencyNode> final
{
public:
size_t operator() (const DependencyNode &node) const
{
return DependencyNode::Hash()(node);
}
};
} // namespace std
namespace {
/**
* Represents an acyclic dependency graph in which each project appears at most
* once.
*
* Dependency graphs can exist in an incomplete state, but will never be
* inconsistent (i.e., include versions that are known to be invalid given the
* current graph).
*/
class DependencyGraph final
{
public:
/**
* A full list of all nodes included in the graph.
*/
std::unordered_set<DependencyNode> _allNodes;
/**
* Maps between nodes in the graph and their immediate dependencies.
*/
std::unordered_map<DependencyNode, std::unordered_set<DependencyNode>> _edges;
/**
* The root nodes of the graph (i.e., those dependencies that are listed by
* the top-level project).
*/
std::unordered_set<DependencyNode> _roots;
bool operator== (const DependencyGraph &other) const
{
return _edges == other._edges && _roots == other._roots;
}
/**
* Attempts to add the given node into the graph, as a dependency of
* `dependent` if specified.
*
* If the given node refers to a project which already exists in the graph,
* this method will attempt to intersect the version requirements of both.
*
* Returns a pointer to the node as actually inserted into the graph (which
* may be different from the node passed in), or `nullptr` if this addition
* would make the graph inconsistent.
*/
DependencyNode *addNode (const DependencyNode &inputNode, const DependencyNode *dependent)
{
auto nodeInsertion = _allNodes.insert(inputNode);
// Unordered collections rightly discourage mutation so hashes don't get
// invalidated, but we've already handled this in the implementation of
// DependencyNode.
DependencyNode &insertedNode = const_cast<DependencyNode &>(*nodeInsertion.first);
// If no insertion was actually performed, we need to unify our input with
// what was already there.
if (!nodeInsertion.second) {
if (auto newRequirement = insertedNode.requirement().intersect(inputNode.requirement())) {
if (!newRequirement->satisfiedBy(insertedNode._proposedVersion._semanticVersion)) {
// This strengthened requirement invalidates the version we've
// proposed in this graph, so the graph would become inconsistent.
return nullptr;
}
insertedNode.setRequirement(std::move(newRequirement));
} else {
// If intersecting the requirements is impossible, the versions
// currently shouldn't be able to match.
//
// Notably, though, Carthage does permit scenarios like this when
// pinned to a branch. Arbiter doesn't support requirements like this
// right now, but may in the future.
assert(inputNode._proposedVersion != insertedNode._proposedVersion);
return nullptr;
}
}
if (dependent) {
_edges[*dependent].insert(insertedNode);
} else {
_roots.insert(insertedNode);
}
return &insertedNode;
}
};
std::ostream &operator<< (std::ostream &os, const DependencyGraph &graph)
{
os << "Roots:";
for (const DependencyNode &root : graph._roots) {
os << "\n\t" << root;
}
os << "\n\nEdges";
for (const auto &pair : graph._edges) {
const DependencyNode &node = pair.first;
os << "\n\t" << node._project << " ->";
const auto &dependencies = pair.second;
for (const DependencyNode &dep : dependencies) {
os << "\n\t\t" << dep;
}
}
return os;
}
Generator<DependencyGraph> generateDependencyGraphs (const ArbiterDependencyList &roots) {
// TODO: Recursively generate every possible dependency graph for everything
// in `roots`, then merge them together.
assert(false);
}
} // namespace
ArbiterResolver *ArbiterCreateResolver (ArbiterResolverBehaviors behaviors, const ArbiterDependencyList *dependencyList, ArbiterUserValue context)
{
return new ArbiterResolver(std::move(behaviors), *dependencyList, ArbiterResolver::Context(std::move(context)));
}
const void *ArbiterResolverContext (const ArbiterResolver *resolver)
{
return resolver->_context.data();
}
bool ArbiterResolvedAllDependencies (const ArbiterResolver *resolver)
{
return resolver->resolvedAll();
}
void ArbiterStartResolvingNextDependency (ArbiterResolver *resolver, ArbiterResolverCallbacks callbacks)
{
resolver->resolveNext().add_callback([resolver, callbacks = std::move(callbacks)](const auto &result) {
try {
const ResolvedDependency &dependency = result.rightOrThrowLeft();
callbacks.onSuccess(resolver, &dependency.projectIdentifier, &dependency.selectedVersion);
} catch (const std::exception &ex) {
callbacks.onError(resolver, ex.what());
}
});
}
void ArbiterFreeResolver (ArbiterResolver *resolver)
{
delete resolver;
}
ResolvedDependency ResolvedDependency::takeOwnership (ArbiterDependencyListFetch fetch) noexcept
{
std::unique_ptr<ArbiterProjectIdentifier> project(const_cast<ArbiterProjectIdentifier *>(fetch.project));
std::unique_ptr<ArbiterSelectedVersion> selectedVersion(const_cast<ArbiterSelectedVersion *>(fetch.selectedVersion));
return ResolvedDependency { std::move(*project), std::move(*selectedVersion) };
}
bool ResolvedDependency::operator== (const ResolvedDependency &other) const noexcept
{
return projectIdentifier == other.projectIdentifier && selectedVersion == other.selectedVersion;
}
bool ArbiterResolver::resolvedAll () const noexcept
{
return _remainingDependencies._dependencies.empty();
}
Arbiter::Future<ResolvedDependency> resolveNext ()
{
Arbiter::Promise<ResolvedDependency> promise;
// TODO: Actually resolve
return promise.get_future();
}
Arbiter::Future<ArbiterDependencyList> ArbiterResolver::insertDependencyListFetch (ResolvedDependency dependency)
{
std::lock_guard<std::mutex> lock(_fetchesMutex);
return _dependencyListFetches[std::move(dependency)].get_future();
}
Arbiter::Promise<ArbiterDependencyList> ArbiterResolver::extractDependencyListFetch (const ResolvedDependency &dependency)
{
std::lock_guard<std::mutex> lock(_fetchesMutex);
Arbiter::Promise<ArbiterDependencyList> promise = std::move(_dependencyListFetches.at(dependency));
_dependencyListFetches.erase(dependency);
return promise;
}
Arbiter::Generator<ArbiterSelectedVersion> ArbiterResolver::insertAvailableVersionsFetch (ArbiterProjectIdentifier fetch)
{
std::lock_guard<std::mutex> lock(_fetchesMutex);
return _availableVersionsFetches[std::move(fetch)].getGenerator();
}
Arbiter::Sink<ArbiterSelectedVersion> ArbiterResolver::extractAvailableVersionsFetch (const ArbiterProjectIdentifier &fetch)
{
std::lock_guard<std::mutex> lock(_fetchesMutex);
Arbiter::Sink<ArbiterSelectedVersion> sink = std::move(_availableVersionsFetches.at(fetch));
_availableVersionsFetches.erase(fetch);
return sink;
}
Arbiter::Future<ArbiterDependencyList> ArbiterResolver::fetchDependencyList (ResolvedDependency dependency)
{
// Eventually freed in the C callback function.
auto project = std::make_unique<ArbiterProjectIdentifier>(dependency.projectIdentifier);
auto version = std::make_unique<ArbiterSelectedVersion>(dependency.selectedVersion);
auto future = insertDependencyListFetch(std::move(dependency));
_behaviors.fetchDependencyList(
ArbiterDependencyListFetch { this, project.release(), version.release() },
&dependencyListFetchOnSuccess,
&dependencyListFetchOnError
);
return future;
}
Arbiter::Generator<ArbiterSelectedVersion> ArbiterResolver::fetchAvailableVersions (ArbiterProjectIdentifier project)
{
// Eventually freed in the C callback function.
auto projectCopy = std::make_unique<ArbiterProjectIdentifier>(project);
auto generator = insertAvailableVersionsFetch(std::move(project));
_behaviors.fetchAvailableVersions(
ArbiterAvailableVersionsFetch { this, projectCopy.release() },
&availableVersionsFetchOnNext,
&availableVersionsFetchOnCompleted,
&availableVersionsFetchOnError
);
return generator;
}
Generator<ArbiterSelectedVersion> ArbiterResolver::fetchAvailableVersions (ArbiterProjectIdentifier project, const ArbiterRequirement &requirement)
{
auto allVersions = std::make_shared<Generator<ArbiterSelectedVersion>>(fetchAvailableVersions(project));
std::shared_ptr<ArbiterRequirement> sharedRequirement(requirement.clone());
return Arbiter::Generator<ArbiterSelectedVersion>([allVersions, sharedRequirement] {
auto promise = std::make_shared<Promise<Optional<ArbiterSelectedVersion>>>();
satisfyPromiseWithFirstVersionPassingRequirement(promise, allVersions, sharedRequirement);
return promise->get_future();
});
}
void ArbiterResolver::dependencyListFetchOnSuccess (ArbiterDependencyListFetch cFetch, const ArbiterDependencyList *fetchedList)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
auto dependency = ResolvedDependency::takeOwnership(cFetch);
resolver
.extractDependencyListFetch(dependency)
.set_value(*fetchedList);
}
void ArbiterResolver::dependencyListFetchOnError (ArbiterDependencyListFetch cFetch)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
auto dependency = ResolvedDependency::takeOwnership(cFetch);
resolver
.extractDependencyListFetch(dependency)
// TODO: Better error reporting
.set_exception(std::make_exception_ptr(std::runtime_error("Dependency list fetch failed")));
}
void ArbiterResolver::availableVersionsFetchOnNext (ArbiterAvailableVersionsFetch cFetch, const ArbiterSelectedVersion *nextVersion)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
const auto &project = *cFetch.project;
std::lock_guard<std::mutex> lock(resolver._fetchesMutex);
resolver
._availableVersionsFetches
.at(project)
.onNext(*nextVersion);
}
void ArbiterResolver::availableVersionsFetchOnCompleted (ArbiterAvailableVersionsFetch cFetch)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
std::unique_ptr<ArbiterProjectIdentifier> project(const_cast<ArbiterProjectIdentifier *>(cFetch.project));
resolver
.extractAvailableVersionsFetch(*project)
.onCompleted();
}
void ArbiterResolver::availableVersionsFetchOnError (ArbiterAvailableVersionsFetch cFetch)
{
auto &resolver = *const_cast<ArbiterResolver *>(cFetch.resolver);
std::unique_ptr<ArbiterProjectIdentifier> project(const_cast<ArbiterProjectIdentifier *>(cFetch.project));
resolver
.extractAvailableVersionsFetch(*project)
// TODO: Better error reporting
.onError(std::make_exception_ptr(std::runtime_error("Available versions fetch failed")));
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "AutoCompleteServlet.h"
#include "CTRCounter.h"
#include "fnord-base/Language.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/io/fileutil.h"
using namespace fnord;
namespace cm {
AutoCompleteServlet::AutoCompleteServlet(
RefPtr<fts::Analyzer> analyzer) :
analyzer_(analyzer) {}
void AutoCompleteServlet::addTermInfo(const String& term, const TermInfo& ti) {
if (ti.score < 1000) return;
term_info_.emplace(term, ti);
}
void AutoCompleteServlet::handleHTTPRequest(
http::HTTPRequest* req,
http::HTTPResponse* res) {
URI uri(req->uri());
ResultListType results;
const auto& params = uri.queryParams();
/* arguments */
String lang_str;
if (!URI::getParam(params, "lang", &lang_str)) {
res->addBody("error: missing ?lang=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
String qstr;
if (!URI::getParam(params, "q", &qstr)) {
res->addBody("error: missing ?q=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
Vector<String> terms;
Vector<String> valid_terms;
auto lang = languageFromString(lang_str);
analyzer_->tokenize(lang, qstr, &terms);
if (terms.size() == 0) {
res->addBody("error: invalid ?q=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
for (const auto& t : terms) {
if (term_info_.count(lang_str + "~" + t) > 0) {
valid_terms.emplace_back(t);
}
}
if (terms.size() == 1 || valid_terms.size() == 0) {
suggestSingleTerm(lang, terms, &results);
} else {
suggestMultiTerm(lang, terms, valid_terms, &results);
}
if (results.size() == 0 && qstr.length() > 2) {
suggestFuzzy(lang, terms, &results);
}
#ifndef FNORD_NODEBUG
fnord::logDebug(
"cm.autocompleteserver",
"suggest lang=$0 qstr=$1 terms=$2 valid_terms=$3 results=$4",
lang_str,
qstr,
inspect(terms),
inspect(valid_terms),
results.size());
#endif
/* write response */
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream json(res->getBodyOutputStream());
json.beginObject();
json.addObjectEntry("query");
json.addString(qstr);
json.addComma();
json.addObjectEntry("suggestions");
json.beginArray();
for (int i = 0; i < results.size() && i < 12; ++i) {
if (i > 0) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("text");
json.addString(std::get<0>(results[i]));
json.addComma();
json.addObjectEntry("score");
json.addFloat(std::get<1>(results[i]));
json.addComma();
json.addObjectEntry("url");
json.addString(std::get<2>(results[i]));
json.endObject();
}
json.endArray();
json.endObject();
}
void AutoCompleteServlet::suggestSingleTerm(
Language lang,
Vector<String> terms,
ResultListType* results) {
auto prefix = languageToString(lang) + "~" + terms.back();
terms.pop_back();
String qstr_prefix;
if (terms.size() > 0 ) {
qstr_prefix += StringUtil::join(terms, " ") + " ";
}
Vector<Pair<String, double>> matches;
double best_match = 0;
for (auto iter = term_info_.lower_bound(prefix);
iter != term_info_.end() && StringUtil::beginsWith(iter->first, prefix);
++iter) {
matches.emplace_back(iter->first, iter->second.score);
if (iter->second.score > best_match) {
best_match = iter->second.score;
}
}
std::sort(matches.begin(), matches.end(), [] (
const Pair<String, double>& a,
const Pair<String, double>& b) {
return b.second < a.second;
});
if (matches.size() > 0) {
const auto& best_match_ti = term_info_.find(matches[0].first);
for (const auto& c : best_match_ti->second.top_categories) {
if ((c.second / best_match_ti->second.top_categories[0].second) < 0.2) {
break;
}
auto label = StringUtil::format(
"$0$1 in $2",
qstr_prefix,
matches[0].first,
c.first);
results->emplace_back(label, c.second, "");
}
}
for (int m = 0; m < matches.size(); ++m) {
auto score = matches[m].second;
if ((score / best_match) < 0.1) {
break;
}
results->emplace_back(qstr_prefix + matches[m].first, score, "");
}
if (matches.size() > 1) {
const auto& best_match_ti = term_info_.find(matches[0].first);
for (const auto& r : best_match_ti->second.related_terms) {
auto label = StringUtil::format(
"$0$1 $2",
qstr_prefix,
matches[0].first,
r.first);
results->emplace_back(label, r.second, "");
}
}
}
void AutoCompleteServlet::suggestMultiTerm(
Language lang,
Vector<String> terms,
const Vector<String>& valid_terms,
ResultListType* results) {
auto lang_str = fnord::languageToString(lang);
auto last_term = terms.back();
terms.pop_back();
String qstr_prefix;
if (terms.size() > 0 ) {
qstr_prefix += StringUtil::join(terms, " ") + " ";
}
fnord::iputs("multi term search for: $0, valid: $1", last_term, valid_terms);
HashMap<String, double> matches_h;
double best_match = 0;
for (const auto& vt : valid_terms) {
if (last_term == vt) {
continue;
}
const auto& vtinfo = term_info_.find(lang_str + "~" + vt)->second;
for (const auto& related : vtinfo.related_terms) {
if (!StringUtil::beginsWith(related.first, last_term)) {
continue;
}
matches_h[related.first] += related.second;
if (matches_h[related.first] > best_match) {
best_match = matches_h[related.first];
}
}
}
Vector<Pair<String, double>> matches;
for (const auto& m : matches_h) {
matches.emplace_back(m);
}
std::sort(matches.begin(), matches.end(), [] (
const Pair<String, double>& a,
const Pair<String, double>& b) {
return b.second < a.second;
});
for (int m = 0; m < matches.size(); ++m) {
auto score = matches[m].second;
if ((score / best_match) < 0.1) {
break;
}
results->emplace_back(qstr_prefix + matches[m].first, score, "");
}
matches_h.clear();
matches.clear();
best_match = 0;
for (const auto& vt : valid_terms) {
const auto& vtinfo = term_info_.find(lang_str + "~" + vt)->second;
for (const auto& related : vtinfo.related_terms) {
matches_h[related.first] += related.second;
if (matches_h[related.first] > best_match) {
best_match = matches_h[related.first];
}
}
}
for (const auto& m : matches_h) {
matches.emplace_back(m);
}
std::sort(matches.begin(), matches.end(), [] (
const Pair<String, double>& a,
const Pair<String, double>& b) {
return b.second < a.second;
});
for (int m = 0; m < matches.size(); ++m) {
auto score = matches[m].second;
if ((score / best_match) < 0.1) {
break;
}
results->emplace_back(qstr_prefix + matches[m].first, score, "");
}
}
void AutoCompleteServlet::suggestFuzzy(
Language lang,
Vector<String> terms,
ResultListType* results) {
results->emplace_back("here be dragons: fuzzy suggestion", 1.0, "");
}
}
<commit_msg>remove debug print<commit_after>/**
* Copyright (c) 2015 - The CM Authors <[email protected]>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "AutoCompleteServlet.h"
#include "CTRCounter.h"
#include "fnord-base/Language.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/io/fileutil.h"
using namespace fnord;
namespace cm {
AutoCompleteServlet::AutoCompleteServlet(
RefPtr<fts::Analyzer> analyzer) :
analyzer_(analyzer) {}
void AutoCompleteServlet::addTermInfo(const String& term, const TermInfo& ti) {
if (ti.score < 1000) return;
term_info_.emplace(term, ti);
}
void AutoCompleteServlet::handleHTTPRequest(
http::HTTPRequest* req,
http::HTTPResponse* res) {
URI uri(req->uri());
ResultListType results;
const auto& params = uri.queryParams();
/* arguments */
String lang_str;
if (!URI::getParam(params, "lang", &lang_str)) {
res->addBody("error: missing ?lang=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
String qstr;
if (!URI::getParam(params, "q", &qstr)) {
res->addBody("error: missing ?q=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
Vector<String> terms;
Vector<String> valid_terms;
auto lang = languageFromString(lang_str);
analyzer_->tokenize(lang, qstr, &terms);
if (terms.size() == 0) {
res->addBody("error: invalid ?q=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
for (const auto& t : terms) {
if (term_info_.count(lang_str + "~" + t) > 0) {
valid_terms.emplace_back(t);
}
}
if (terms.size() == 1 || valid_terms.size() == 0) {
suggestSingleTerm(lang, terms, &results);
} else {
suggestMultiTerm(lang, terms, valid_terms, &results);
}
if (results.size() == 0 && qstr.length() > 2) {
suggestFuzzy(lang, terms, &results);
}
#ifndef FNORD_NODEBUG
fnord::logDebug(
"cm.autocompleteserver",
"suggest lang=$0 qstr=$1 terms=$2 valid_terms=$3 results=$4",
lang_str,
qstr,
inspect(terms),
inspect(valid_terms),
results.size());
#endif
/* write response */
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream json(res->getBodyOutputStream());
json.beginObject();
json.addObjectEntry("query");
json.addString(qstr);
json.addComma();
json.addObjectEntry("suggestions");
json.beginArray();
for (int i = 0; i < results.size() && i < 12; ++i) {
if (i > 0) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("text");
json.addString(std::get<0>(results[i]));
json.addComma();
json.addObjectEntry("score");
json.addFloat(std::get<1>(results[i]));
json.addComma();
json.addObjectEntry("url");
json.addString(std::get<2>(results[i]));
json.endObject();
}
json.endArray();
json.endObject();
}
void AutoCompleteServlet::suggestSingleTerm(
Language lang,
Vector<String> terms,
ResultListType* results) {
auto prefix = languageToString(lang) + "~" + terms.back();
terms.pop_back();
String qstr_prefix;
if (terms.size() > 0 ) {
qstr_prefix += StringUtil::join(terms, " ") + " ";
}
Vector<Pair<String, double>> matches;
double best_match = 0;
for (auto iter = term_info_.lower_bound(prefix);
iter != term_info_.end() && StringUtil::beginsWith(iter->first, prefix);
++iter) {
matches.emplace_back(iter->first, iter->second.score);
if (iter->second.score > best_match) {
best_match = iter->second.score;
}
}
std::sort(matches.begin(), matches.end(), [] (
const Pair<String, double>& a,
const Pair<String, double>& b) {
return b.second < a.second;
});
if (matches.size() > 0) {
const auto& best_match_ti = term_info_.find(matches[0].first);
for (const auto& c : best_match_ti->second.top_categories) {
if ((c.second / best_match_ti->second.top_categories[0].second) < 0.2) {
break;
}
auto label = StringUtil::format(
"$0$1 in $2",
qstr_prefix,
matches[0].first,
c.first);
results->emplace_back(label, c.second, "");
}
}
for (int m = 0; m < matches.size(); ++m) {
auto score = matches[m].second;
if ((score / best_match) < 0.1) {
break;
}
results->emplace_back(qstr_prefix + matches[m].first, score, "");
}
if (matches.size() > 1) {
const auto& best_match_ti = term_info_.find(matches[0].first);
for (const auto& r : best_match_ti->second.related_terms) {
auto label = StringUtil::format(
"$0$1 $2",
qstr_prefix,
matches[0].first,
r.first);
results->emplace_back(label, r.second, "");
}
}
}
void AutoCompleteServlet::suggestMultiTerm(
Language lang,
Vector<String> terms,
const Vector<String>& valid_terms,
ResultListType* results) {
auto lang_str = fnord::languageToString(lang);
auto last_term = terms.back();
terms.pop_back();
String qstr_prefix;
if (terms.size() > 0 ) {
qstr_prefix += StringUtil::join(terms, " ") + " ";
}
HashMap<String, double> matches_h;
double best_match = 0;
for (const auto& vt : valid_terms) {
if (last_term == vt) {
continue;
}
const auto& vtinfo = term_info_.find(lang_str + "~" + vt)->second;
for (const auto& related : vtinfo.related_terms) {
if (!StringUtil::beginsWith(related.first, last_term)) {
continue;
}
matches_h[related.first] += related.second;
if (matches_h[related.first] > best_match) {
best_match = matches_h[related.first];
}
}
}
Vector<Pair<String, double>> matches;
for (const auto& m : matches_h) {
matches.emplace_back(m);
}
std::sort(matches.begin(), matches.end(), [] (
const Pair<String, double>& a,
const Pair<String, double>& b) {
return b.second < a.second;
});
for (int m = 0; m < matches.size(); ++m) {
auto score = matches[m].second;
if ((score / best_match) < 0.1) {
break;
}
results->emplace_back(qstr_prefix + matches[m].first, score, "");
}
matches_h.clear();
matches.clear();
best_match = 0;
for (const auto& vt : valid_terms) {
const auto& vtinfo = term_info_.find(lang_str + "~" + vt)->second;
for (const auto& related : vtinfo.related_terms) {
matches_h[related.first] += related.second;
if (matches_h[related.first] > best_match) {
best_match = matches_h[related.first];
}
}
}
for (const auto& m : matches_h) {
matches.emplace_back(m);
}
std::sort(matches.begin(), matches.end(), [] (
const Pair<String, double>& a,
const Pair<String, double>& b) {
return b.second < a.second;
});
for (int m = 0; m < matches.size(); ++m) {
auto score = matches[m].second;
if ((score / best_match) < 0.1) {
break;
}
results->emplace_back(qstr_prefix + matches[m].first, score, "");
}
}
void AutoCompleteServlet::suggestFuzzy(
Language lang,
Vector<String> terms,
ResultListType* results) {
results->emplace_back("here be dragons: fuzzy suggestion", 1.0, "");
}
}
<|endoftext|> |
<commit_before>#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/opengl.hpp>
#include <wayfire/render-manager.hpp>
static const char *vertex_shader =
R"(
#version 100
attribute mediump vec2 position;
attribute highp vec2 uvPosition;
varying highp vec2 uvpos;
void main() {
gl_Position = vec4(position.xy, 0.0, 1.0);
uvpos = uvPosition;
}
)";
static const char *fragment_shader =
R"(
#version 100
varying highp vec2 uvpos;
uniform sampler2D smp;
uniform bool preserve_hue;
void main()
{
if (preserve_hue)
{
mediump float hue = tex.a - min(tex.r, min(tex.g, tex.b)) - max(tex.r, max(tex.g, tex.b));
gl_FragColor = hue + tex;
} else
{
gl_FragColor = vec4(1.0 - tex.r, 1.0 - tex.g, 1.0 - tex.b, 1.0);
}
}
)";
class wayfire_invert_screen : public wf::plugin_interface_t
{
wf::post_hook_t hook;
wf::activator_callback toggle_cb;
wf::option_wrapper_t<bool> preserve_hue{"invert/preserve_hue"};
bool active = false;
OpenGL::program_t program;
public:
void init() override
{
wf::option_wrapper_t<wf::activatorbinding_t> toggle_key{"invert/toggle"};
grab_interface->name = "invert";
grab_interface->capabilities = 0;
hook = [=] (const wf::framebuffer_base_t& source,
const wf::framebuffer_base_t& destination)
{
render(source, destination);
};
toggle_cb = [=] (auto)
{
if (!output->can_activate_plugin(grab_interface))
{
return false;
}
if (active)
{
output->render->rem_post(&hook);
} else
{
output->render->add_post(&hook);
}
active = !active;
return true;
};
OpenGL::render_begin();
program.set_simple(
OpenGL::compile_program(vertex_shader, fragment_shader));
OpenGL::render_end();
output->add_activator(toggle_key, &toggle_cb);
}
void render(const wf::framebuffer_base_t& source,
const wf::framebuffer_base_t& destination)
{
static const float vertexData[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
static const float coordData[] = {
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f
};
OpenGL::render_begin(destination);
program.use(wf::TEXTURE_TYPE_RGBA);
GL_CALL(glBindTexture(GL_TEXTURE_2D, source.tex));
GL_CALL(glActiveTexture(GL_TEXTURE0));
program.attrib_pointer("position", 2, 0, vertexData);
program.attrib_pointer("uvPosition", 2, 0, coordData);
program.uniform1i("preserve_hue", preserve_hue);
GL_CALL(glDisable(GL_BLEND));
GL_CALL(glDrawArrays(GL_TRIANGLE_FAN, 0, 4));
GL_CALL(glEnable(GL_BLEND));
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
program.deactivate();
OpenGL::render_end();
}
void fini() override
{
if (active)
{
output->render->rem_post(&hook);
}
OpenGL::render_begin();
program.free_resources();
OpenGL::render_end();
output->rem_binding(&toggle_cb);
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_invert_screen);
<commit_msg>added missing sample call that was missing in #902 (#914)<commit_after>#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/opengl.hpp>
#include <wayfire/render-manager.hpp>
static const char *vertex_shader =
R"(
#version 100
attribute mediump vec2 position;
attribute highp vec2 uvPosition;
varying highp vec2 uvpos;
void main() {
gl_Position = vec4(position.xy, 0.0, 1.0);
uvpos = uvPosition;
}
)";
static const char *fragment_shader =
R"(
#version 100
varying highp vec2 uvpos;
uniform sampler2D smp;
uniform bool preserve_hue;
void main()
{
mediump vec4 tex = texture2D(smp, uvpos);
if (preserve_hue)
{
mediump float hue = tex.a - min(tex.r, min(tex.g, tex.b)) - max(tex.r, max(tex.g, tex.b));
gl_FragColor = hue + tex;
} else
{
gl_FragColor = vec4(1.0 - tex.r, 1.0 - tex.g, 1.0 - tex.b, 1.0);
}
}
)";
class wayfire_invert_screen : public wf::plugin_interface_t
{
wf::post_hook_t hook;
wf::activator_callback toggle_cb;
wf::option_wrapper_t<bool> preserve_hue{"invert/preserve_hue"};
bool active = false;
OpenGL::program_t program;
public:
void init() override
{
wf::option_wrapper_t<wf::activatorbinding_t> toggle_key{"invert/toggle"};
grab_interface->name = "invert";
grab_interface->capabilities = 0;
hook = [=] (const wf::framebuffer_base_t& source,
const wf::framebuffer_base_t& destination)
{
render(source, destination);
};
toggle_cb = [=] (auto)
{
if (!output->can_activate_plugin(grab_interface))
{
return false;
}
if (active)
{
output->render->rem_post(&hook);
} else
{
output->render->add_post(&hook);
}
active = !active;
return true;
};
OpenGL::render_begin();
program.set_simple(
OpenGL::compile_program(vertex_shader, fragment_shader));
OpenGL::render_end();
output->add_activator(toggle_key, &toggle_cb);
}
void render(const wf::framebuffer_base_t& source,
const wf::framebuffer_base_t& destination)
{
static const float vertexData[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
static const float coordData[] = {
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f
};
OpenGL::render_begin(destination);
program.use(wf::TEXTURE_TYPE_RGBA);
GL_CALL(glBindTexture(GL_TEXTURE_2D, source.tex));
GL_CALL(glActiveTexture(GL_TEXTURE0));
program.attrib_pointer("position", 2, 0, vertexData);
program.attrib_pointer("uvPosition", 2, 0, coordData);
program.uniform1i("preserve_hue", preserve_hue);
GL_CALL(glDisable(GL_BLEND));
GL_CALL(glDrawArrays(GL_TRIANGLE_FAN, 0, 4));
GL_CALL(glEnable(GL_BLEND));
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
program.deactivate();
OpenGL::render_end();
}
void fini() override
{
if (active)
{
output->render->rem_post(&hook);
}
OpenGL::render_begin();
program.free_resources();
OpenGL::render_end();
output->rem_binding(&toggle_cb);
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_invert_screen);
<|endoftext|> |
<commit_before>//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// ----------------------------------------------------------------
// AFRODITE (iThemba Labs)
// ----------------------------------------------------------------
//
// Github repository: https://www.github.com/KevinCWLi/AFRODITE
//
// Main Author: K.C.W. Li
//
// email: [email protected]
//
#include "RunAction.hh"
#include "Analysis.hh"
#include "G4Run.hh"
#include "G4RunManager.hh"
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
RunAction::RunAction()
: G4UserRunAction()
{
// set printing event number per each event
G4RunManager::GetRunManager()->SetPrintProgress(1);
// Create analysis manager
// The choice of analysis technology is done via selectin of a namespace
// in Analysis.hh
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
G4cout << "Using " << analysisManager->GetType() << G4endl;
// Create directories
//analysisManager->SetHistoDirectoryName("histograms");
//analysisManager->SetNtupleDirectoryName("ntuple");
analysisManager->SetVerboseLevel(1);
//analysisManager->SetFirstHistoId(1);
// Book histograms, ntuple
//
// Creating 1D histograms
/*
//// TIARA DETECTORS, Histograms 1-6
analysisManager->CreateH1("CvsE_TIARA1","TIARA 1 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA2","TIARA 2 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA3","TIARA 3 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA4","TIARA 4 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA5","TIARA 5 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA_EA","Entire TIARA Array - Counts versus Energy", 10000, 0., 10000.);
//// PADDLE DETECTORS, Histograms 7-9
analysisManager->CreateH1("CvsE_PADDLE1","PADDLE 1 - Counts versus Energy", 1000, 0., 100.);
analysisManager->CreateH1("CvsE_PADDLE2","PADDLE 2 - Counts versus Energy", 1000, 0., 100.);
analysisManager->CreateH1("CvsE_PADDLE3","PADDLE 3 - Counts versus Energy", 1000, 0., 100.);
//// CLOVER DETECTORS, Histograms 10-19
analysisManager->CreateH1("CvsE_CLOVER1","CLOVER 1 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER2","CLOVER 2 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER3","CLOVER 3 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER4","CLOVER 4 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER5","CLOVER 5 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER6","CLOVER 6 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER7","CLOVER 7 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER8","CLOVER 8 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER9","CLOVER 9 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER_EA","Entire CLOVER Array - Counts versus Energy", 3000, 0., 3000.);
*/
////////////////////////////////////////////////////
// DataTreeSim
////////////////////////////////////////////////////
// Creating ntuple
analysisManager->CreateNtuple("DataTreeSim", "AFRODITE");
////////////////////////////////////////////////////
//// CLOVER Detectors
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[0]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[1]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[2]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[3]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[4]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[5]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[6]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[7]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[8]");
//// Gamma Tracking
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[0]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[1]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[2]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[3]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[4]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[5]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[6]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[7]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[8]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[0]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[1]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[2]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[3]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[4]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[5]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[6]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[7]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[8]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[0]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[1]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[2]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[3]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[4]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[5]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[6]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[7]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[8]");
////////////////////////////////////////////////////
///// PlasticScint Detectors (Neutron Wall)
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[0]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[1]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[2]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[3]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[4]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[5]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[6]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[7]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[8]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[9]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[10]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[11]");
////////////////////////////////////////////////////
//// LEPS Detectors
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[0]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[1]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[2]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[3]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[4]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[5]");
analysisManager->FinishNtuple(0);
////////////////////////////////////////////////////////////
// GeometryAnalysisTree
////////////////////////////////////////////////////////////
// Creating ntuple
analysisManager->CreateNtuple("GeometryAnalysisTree", "K600 Spectrometer - GeometryAnalysis");
//// TIARA Detectors
analysisManager->CreateNtupleIColumn(1, "TIARANo");
analysisManager->CreateNtupleIColumn(1, "TIARA_RowNo");
analysisManager->CreateNtupleIColumn(1, "TIARA_SectorNo");
analysisManager->CreateNtupleDColumn(1, "Theta");
analysisManager->CreateNtupleDColumn(1, "Phi");
analysisManager->FinishNtuple(1);
////////////////////////////////////////////////////////////
// Input Variable Tree
////////////////////////////////////////////////////////////
// Creating ntuple
analysisManager->CreateNtuple("InputVariableTree", "K600 Spectrometer - InputVariable");
//// Initial Particle Angular Distributions
analysisManager->CreateNtupleDColumn(2, "ThetaDist");
analysisManager->CreateNtupleDColumn(2, "PhiDist");
analysisManager->FinishNtuple(2);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
RunAction::~RunAction()
{
delete G4AnalysisManager::Instance();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void RunAction::BeginOfRunAction(const G4Run* /*run*/)
{
//inform the runManager to save random number seed
//G4RunManager::GetRunManager()->SetRandomNumberStore(true);
// Get analysis manager
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
// Open an output file
//
G4String fileName = "K600Output";
analysisManager->OpenFile(fileName);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void RunAction::EndOfRunAction(const G4Run* /*run*/)
{
// print histogram statistics
//
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
if ( analysisManager->GetH1(1) ) {
/*
G4cout << "\n ----> print histograms statistic ";
if(isMaster) {
G4cout << "for the entire run \n" << G4endl;
}
else {
G4cout << "for the local thread \n" << G4endl;
}
G4cout << " EAbs : mean = "
<< G4BestUnit(analysisManager->GetH1(1)->mean(), "Energy")
<< " rms = "
<< G4BestUnit(analysisManager->GetH1(1)->rms(), "Energy") << G4endl;
G4cout << " EGap : mean = "
<< G4BestUnit(analysisManager->GetH1(2)->mean(), "Energy")
<< " rms = "
<< G4BestUnit(analysisManager->GetH1(2)->rms(), "Energy") << G4endl;
G4cout << " LAbs : mean = "
<< G4BestUnit(analysisManager->GetH1(3)->mean(), "Length")
<< " rms = "
<< G4BestUnit(analysisManager->GetH1(3)->rms(), "Length") << G4endl;
G4cout << " LGap : mean = "
<< G4BestUnit(analysisManager->GetH1(4)->mean(), "Length")
<< " rms = "
<< G4BestUnit(analysisManager->GetH1(4)->rms(), "Length") << G4endl;
*/
}
// save histograms & ntuple
//
analysisManager->Write();
analysisManager->CloseFile();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
<commit_msg>Commented out calls for histogram (for statistics) as this results in warnings when no histograms are declared and no histograms are currently needed<commit_after>//
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
// ----------------------------------------------------------------
// AFRODITE (iThemba Labs)
// ----------------------------------------------------------------
//
// Github repository: https://www.github.com/KevinCWLi/AFRODITE
//
// Main Author: K.C.W. Li
//
// email: [email protected]
//
#include "RunAction.hh"
#include "Analysis.hh"
#include "G4Run.hh"
#include "G4RunManager.hh"
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
RunAction::RunAction()
: G4UserRunAction()
{
// set printing event number per each event
G4RunManager::GetRunManager()->SetPrintProgress(1);
// Create analysis manager
// The choice of analysis technology is done via selectin of a namespace
// in Analysis.hh
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
G4cout << "Using " << analysisManager->GetType() << G4endl;
// Create directories
//analysisManager->SetHistoDirectoryName("histograms");
//analysisManager->SetNtupleDirectoryName("ntuple");
analysisManager->SetVerboseLevel(1);
//analysisManager->SetFirstHistoId(1);
// Book histograms, ntuple
//
// Creating 1D histograms
/*
//// TIARA DETECTORS, Histograms 1-6
analysisManager->CreateH1("CvsE_TIARA1","TIARA 1 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA2","TIARA 2 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA3","TIARA 3 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA4","TIARA 4 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA5","TIARA 5 - Counts versus Energy", 10000, 0., 10000.);
analysisManager->CreateH1("CvsE_TIARA_EA","Entire TIARA Array - Counts versus Energy", 10000, 0., 10000.);
//// PADDLE DETECTORS, Histograms 7-9
analysisManager->CreateH1("CvsE_PADDLE1","PADDLE 1 - Counts versus Energy", 1000, 0., 100.);
analysisManager->CreateH1("CvsE_PADDLE2","PADDLE 2 - Counts versus Energy", 1000, 0., 100.);
analysisManager->CreateH1("CvsE_PADDLE3","PADDLE 3 - Counts versus Energy", 1000, 0., 100.);
//// CLOVER DETECTORS, Histograms 10-19
analysisManager->CreateH1("CvsE_CLOVER1","CLOVER 1 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER2","CLOVER 2 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER3","CLOVER 3 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER4","CLOVER 4 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER5","CLOVER 5 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER6","CLOVER 6 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER7","CLOVER 7 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER8","CLOVER 8 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER9","CLOVER 9 - Counts versus Energy", 3000, 0., 3000.);
analysisManager->CreateH1("CvsE_CLOVER_EA","Entire CLOVER Array - Counts versus Energy", 3000, 0., 3000.);
*/
////////////////////////////////////////////////////
// DataTreeSim
////////////////////////////////////////////////////
// Creating ntuple
analysisManager->CreateNtuple("DataTreeSim", "AFRODITE");
////////////////////////////////////////////////////
//// CLOVER Detectors
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[0]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[1]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[2]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[3]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[4]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[5]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[6]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[7]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_Energy[8]");
//// Gamma Tracking
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[0]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[1]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[2]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[3]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[4]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[5]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[6]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[7]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosX[8]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[0]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[1]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[2]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[3]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[4]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[5]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[6]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[7]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosY[8]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[0]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[1]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[2]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[3]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[4]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[5]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[6]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[7]");
analysisManager->CreateNtupleDColumn(0, "CLOVER_PosZ[8]");
////////////////////////////////////////////////////
///// PlasticScint Detectors (Neutron Wall)
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[0]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[1]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[2]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[3]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[4]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[5]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[6]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[7]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[8]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[9]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[10]");
analysisManager->CreateNtupleDColumn(0, "PlasticScint_Energy[11]");
////////////////////////////////////////////////////
//// LEPS Detectors
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[0]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[1]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[2]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[3]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[4]");
analysisManager->CreateNtupleDColumn(0, "LEPS_Energy[5]");
analysisManager->FinishNtuple(0);
////////////////////////////////////////////////////////////
// GeometryAnalysisTree
////////////////////////////////////////////////////////////
// Creating ntuple
analysisManager->CreateNtuple("GeometryAnalysisTree", "K600 Spectrometer - GeometryAnalysis");
//// TIARA Detectors
analysisManager->CreateNtupleIColumn(1, "TIARANo");
analysisManager->CreateNtupleIColumn(1, "TIARA_RowNo");
analysisManager->CreateNtupleIColumn(1, "TIARA_SectorNo");
analysisManager->CreateNtupleDColumn(1, "Theta");
analysisManager->CreateNtupleDColumn(1, "Phi");
analysisManager->FinishNtuple(1);
////////////////////////////////////////////////////////////
// Input Variable Tree
////////////////////////////////////////////////////////////
// Creating ntuple
analysisManager->CreateNtuple("InputVariableTree", "K600 Spectrometer - InputVariable");
//// Initial Particle Angular Distributions
analysisManager->CreateNtupleDColumn(2, "ThetaDist");
analysisManager->CreateNtupleDColumn(2, "PhiDist");
analysisManager->FinishNtuple(2);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
RunAction::~RunAction()
{
delete G4AnalysisManager::Instance();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void RunAction::BeginOfRunAction(const G4Run* /*run*/)
{
//inform the runManager to save random number seed
//G4RunManager::GetRunManager()->SetRandomNumberStore(true);
// Get analysis manager
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
// Open an output file
//
G4String fileName = "K600Output";
analysisManager->OpenFile(fileName);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void RunAction::EndOfRunAction(const G4Run* /*run*/)
{
// print histogram statistics
//
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
/*
// print histogram statistics
//
if( analysisManager->GetH1(1) ){
G4cout << "\n ----> print histograms statistic ";
if(isMaster) {
G4cout << "for the entire run \n" << G4endl;
}
else {
G4cout << "for the local thread \n" << G4endl;
}
G4cout << " EAbs : mean = "
<< G4BestUnit(analysisManager->GetH1(1)->mean(), "Energy")
<< " rms = "
<< G4BestUnit(analysisManager->GetH1(1)->rms(), "Energy") << G4endl;
G4cout << " EGap : mean = "
<< G4BestUnit(analysisManager->GetH1(2)->mean(), "Energy")
<< " rms = "
<< G4BestUnit(analysisManager->GetH1(2)->rms(), "Energy") << G4endl;
G4cout << " LAbs : mean = "
<< G4BestUnit(analysisManager->GetH1(3)->mean(), "Length")
<< " rms = "
<< G4BestUnit(analysisManager->GetH1(3)->rms(), "Length") << G4endl;
G4cout << " LGap : mean = "
<< G4BestUnit(analysisManager->GetH1(4)->mean(), "Length")
<< " rms = "
<< G4BestUnit(analysisManager->GetH1(4)->rms(), "Length") << G4endl;
}
*/
// save histograms & ntuple
//
analysisManager->Write();
analysisManager->CloseFile();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
<|endoftext|> |
<commit_before>#include <plugin.hpp>
#include <output.hpp>
#include <core.hpp>
#include <debug.hpp>
#include <view.hpp>
#include <view-transform.hpp>
#include <render-manager.hpp>
#include <workspace-stream.hpp>
#include <workspace-manager.hpp>
#include <signal-definitions.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <animation.hpp>
#include <cmath>
#include <utility>
#include <animation.hpp>
#include "vswipe-processing.hpp"
class vswipe : public wf::plugin_interface_t
{
private:
struct {
/* When the workspace is set to (-1, -1), means no such workspace */
wf::workspace_stream_t prev, curr, next;
} streams;
enum swipe_direction_t
{
HORIZONTAL = 0,
VERTICAL,
UNKNOWN,
};
struct {
bool swiping = false;
swipe_direction_t direction;
wf_pointf initial_deltas;
double delta_sum = 0.0;
double gap = 0.0;
double delta_prev = 0.0;
double delta_last = 0.0;
int vx = 0;
int vy = 0;
int vw = 0;
int vh = 0;
} state;
wf::render_hook_t renderer;
wf_duration duration;
wf_transition transition;
wf_option animation_duration;
wf_option background_color;
wf_option enable;
wf_option ignore_cancel;
wf_option fingers;
wf_option gap;
wf_option threshold;
wf_option delta_threshold;
wf_option speed_factor;
wf_option speed_cap;
public:
void init(wayfire_config *config)
{
grab_interface->name = "vswipe";
grab_interface->capabilities = wf::CAPABILITY_MANAGE_COMPOSITOR;
grab_interface->callbacks.cancel = [=] () { finalize_and_exit(); };
auto section = config->get_section("vswipe");
animation_duration = section->get_option("duration", "180");
duration = wf_duration(animation_duration);
enable = section->get_option("enable", "1");
ignore_cancel = section->get_option("ignore_cancel", "1");
fingers = section->get_option("fingers", "4");
gap = section->get_option("gap", "32");
threshold = section->get_option("threshold", "0.35");
delta_threshold = section->get_option("delta_threshold", "24");
speed_factor = section->get_option("speed_factor", "256");
speed_cap = section->get_option("speed_cap", "0.05");
wf::get_core().connect_signal("pointer-swipe-begin", &on_swipe_begin);
wf::get_core().connect_signal("pointer-swipe-update", &on_swipe_update);
wf::get_core().connect_signal("pointer-swipe-end", &on_swipe_end);
background_color = section->get_option("background", "0 0 0 1");
renderer = [=] (const wf_framebuffer& buffer) { render(buffer); };
}
/**
* Get the translation matrix for a workspace at the given offset.
* Depends on the swipe direction
*/
glm::mat4 get_translation(double offset)
{
switch (state.direction)
{
case UNKNOWN:
return glm::mat4(1.0);
case HORIZONTAL:
return glm::translate(glm::mat4(1.0),
glm::vec3(offset, 0.0, 0.0));
case VERTICAL:
return glm::translate(glm::mat4(1.0),
glm::vec3(0.0, -offset, 0.0));
}
assert(false); // not reached
}
void render(const wf_framebuffer &fb)
{
if (!duration.running() && !state.swiping)
finalize_and_exit();
if (duration.running())
state.delta_sum = duration.progress(transition);
update_stream(streams.prev);
update_stream(streams.curr);
update_stream(streams.next);
OpenGL::render_begin(fb);
OpenGL::clear(background_color->as_cached_color());
fb.scissor(fb.framebuffer_box_from_geometry_box(fb.geometry));
gl_geometry out_geometry = {
.x1 = -1,
.y1 = 1,
.x2 = 1,
.y2 = -1,
};
auto swipe = get_translation(state.delta_sum * 2);
if (streams.prev.ws.x >= 0)
{
auto prev = get_translation(-2.0 - state.gap * 2.0);
OpenGL::render_transformed_texture(streams.prev.buffer.tex,
out_geometry, {}, fb.transform * prev * swipe);
}
OpenGL::render_transformed_texture(streams.curr.buffer.tex,
out_geometry, {}, fb.transform * swipe);
if (streams.next.ws.x >= 0)
{
auto next = get_translation(2.0 + state.gap * 2.0);
OpenGL::render_transformed_texture(streams.next.buffer.tex,
out_geometry, {}, fb.transform * next * swipe);
}
GL_CALL(glUseProgram(0));
OpenGL::render_end();
}
inline void update_stream(wf::workspace_stream_t& s)
{
if (s.ws.x < 0 || s.ws.y < 0)
return;
if (!s.running)
output->render->workspace_stream_start(s);
else
output->render->workspace_stream_update(s);
}
wf::signal_callback_t on_swipe_begin = [=] (wf::signal_data_t *data)
{
if (!enable->as_cached_int())
return;
if (output->is_plugin_active(grab_interface->name))
return;
auto ev = static_cast<wf::swipe_begin_signal*> (data)->ev;
if (static_cast<int>(ev->fingers) != fingers->as_cached_int())
return;
// Plugins are per output, swipes are global, so we need to handle
// the swipe only when the cursor is on *our* (plugin instance's) output
if (!(output->get_relative_geometry() & output->get_cursor_position()))
return;
wf::get_core().focus_output(output);
if (!output->activate_plugin(grab_interface))
return;
grab_interface->grab();
state.swiping = true;
state.direction = UNKNOWN;
state.initial_deltas = {0.0, 0.0};
state.delta_sum = 0;
state.delta_last = 0;
state.delta_prev = 0;
state.gap = gap->as_cached_double() / output->get_screen_size().width;
// We switch the actual workspace before the finishing animation,
// so the rendering of the animation cannot dynamically query current
// workspace again, so it's stored here
auto grid = output->workspace->get_workspace_grid_size();
auto ws = output->workspace->get_current_workspace();
state.vw = grid.width;
state.vh = grid.height;
state.vx = ws.x;
state.vy = ws.y;
/* Invalid in the beginning, because we want a few swipe events to
* determine whether swipe is horizontal or vertical */
streams.prev.ws = {-1, -1};
streams.next.ws = {-1, -1};
streams.curr.ws = wf_point {ws.x, ws.y};
output->render->set_renderer(renderer);
output->render->damage_whole();
};
void start_swipe(swipe_direction_t direction)
{
assert(direction != UNKNOWN);
state.direction = direction;
auto ws = output->workspace->get_current_workspace();
auto grid = output->workspace->get_workspace_grid_size();
if (direction == HORIZONTAL)
{
if (ws.x > 0)
streams.prev.ws = wf_point{ws.x - 1, ws.y};
if (ws.x < grid.width - 1)
streams.next.ws = wf_point{ws.x + 1, ws.y};
} else //if (direction == VERTICAL)
{
if (ws.y > 0)
streams.prev.ws = wf_point{ws.x, ws.y - 1};
if (ws.y < grid.height - 1)
streams.next.ws = wf_point{ws.x, ws.y + 1};
}
}
wf::signal_callback_t on_swipe_update = [=] (wf::signal_data_t *data)
{
if (!state.swiping)
return;
auto ev = static_cast<wf::swipe_update_signal*> (data)->ev;
if (state.direction == UNKNOWN)
{
auto grid = output->workspace->get_workspace_grid_size();
// XXX: how to determine this??
static constexpr double initial_direction_threshold = 0.05;
state.initial_deltas.x +=
std::abs(ev->dx) / speed_factor->as_double();
state.initial_deltas.y +=
std::abs(ev->dy) / speed_factor->as_double();
bool horizontal =
state.initial_deltas.x > initial_direction_threshold;
bool vertical =
state.initial_deltas.y > initial_direction_threshold;
horizontal &= state.initial_deltas.x > state.initial_deltas.y;
vertical &= state.initial_deltas.y > state.initial_deltas.x;
if (horizontal || grid.height == 1)
{
start_swipe(HORIZONTAL);
}
else if (vertical || grid.width == 1)
{
start_swipe(VERTICAL);
}
if (state.direction == UNKNOWN)
return;
}
const double cap = speed_cap->as_cached_double();
const double fac = speed_factor->as_cached_double();
state.delta_prev = state.delta_last;
if (state.direction == HORIZONTAL)
{
state.delta_sum += vswipe_process_delta(ev->dx, state.delta_sum,
state.vx, state.vw, cap, fac);
state.delta_last = ev->dx;
} else
{
state.delta_sum += vswipe_process_delta(ev->dy, state.delta_sum,
state.vy, state.vh, cap, fac);
state.delta_last = ev->dy;
}
output->render->damage_whole();
};
wf::signal_callback_t on_swipe_end = [=] (wf::signal_data_t *data)
{
if (!state.swiping)
return;
state.swiping = false;
auto ev = static_cast<wf::swipe_end_signal*>(data)->ev;
const double move_threshold =
clamp(threshold->as_cached_double(), 0.0, 1.0);
const double fast_threshold =
clamp(delta_threshold->as_cached_double(), 0.0, 1000.0);
int target_delta = 0;
wf_point target_workspace = {state.vx, state.vy};
if (!ev->cancelled || ignore_cancel->as_int())
{
switch (state.direction)
{
case UNKNOWN:
target_delta = 0;
break;
case HORIZONTAL:
target_delta = vswipe_finish_target(state.delta_sum,
state.vx, state.vw, state.delta_prev + state.delta_last,
move_threshold, fast_threshold);
target_workspace.x -= target_delta;
break;
case VERTICAL:
target_delta = vswipe_finish_target(state.delta_sum,
state.vy, state.vh, state.delta_prev + state.delta_last,
move_threshold, fast_threshold);
target_workspace.y -= target_delta;
break;
}
}
transition = {state.delta_sum, target_delta + state.gap * target_delta};
output->workspace->set_workspace(target_workspace);
output->render->set_redraw_always();
duration.start();
};
void finalize_and_exit()
{
state.swiping = false;
grab_interface->ungrab();
output->deactivate_plugin(grab_interface);
if (streams.prev.running)
output->render->workspace_stream_stop(streams.prev);
output->render->workspace_stream_stop(streams.curr);
if (streams.next.running)
output->render->workspace_stream_stop(streams.next);
output->render->set_renderer(nullptr);
output->render->set_redraw_always(false);
}
void fini()
{
if (state.swiping)
finalize_and_exit();
OpenGL::render_begin();
streams.prev.buffer.release();
streams.curr.buffer.release();
streams.next.buffer.release();
OpenGL::render_end();
}
};
DECLARE_WAYFIRE_PLUGIN(vswipe);
<commit_msg>vswipe: allow disabling vertical or horizontal via options<commit_after>#include <plugin.hpp>
#include <output.hpp>
#include <core.hpp>
#include <debug.hpp>
#include <view.hpp>
#include <view-transform.hpp>
#include <render-manager.hpp>
#include <workspace-stream.hpp>
#include <workspace-manager.hpp>
#include <signal-definitions.hpp>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <animation.hpp>
#include <cmath>
#include <utility>
#include <animation.hpp>
#include "vswipe-processing.hpp"
class vswipe : public wf::plugin_interface_t
{
private:
struct {
/* When the workspace is set to (-1, -1), means no such workspace */
wf::workspace_stream_t prev, curr, next;
} streams;
enum swipe_direction_t
{
HORIZONTAL = 0,
VERTICAL,
UNKNOWN,
};
struct {
bool swiping = false;
swipe_direction_t direction;
wf_pointf initial_deltas;
double delta_sum = 0.0;
double gap = 0.0;
double delta_prev = 0.0;
double delta_last = 0.0;
int vx = 0;
int vy = 0;
int vw = 0;
int vh = 0;
} state;
wf::render_hook_t renderer;
wf_duration duration;
wf_transition transition;
wf_option animation_duration;
wf_option background_color;
wf_option enable_horizontal;
wf_option enable_vertical;
wf_option ignore_cancel;
wf_option fingers;
wf_option gap;
wf_option threshold;
wf_option delta_threshold;
wf_option speed_factor;
wf_option speed_cap;
public:
void init(wayfire_config *config)
{
grab_interface->name = "vswipe";
grab_interface->capabilities = wf::CAPABILITY_MANAGE_COMPOSITOR;
grab_interface->callbacks.cancel = [=] () { finalize_and_exit(); };
auto section = config->get_section("vswipe");
animation_duration = section->get_option("duration", "180");
duration = wf_duration(animation_duration);
enable_horizontal = section->get_option("enable_horizontal", "1");
enable_vertical = section->get_option("enable_vertical", "1");
ignore_cancel = section->get_option("ignore_cancel", "1");
fingers = section->get_option("fingers", "4");
gap = section->get_option("gap", "32");
threshold = section->get_option("threshold", "0.35");
delta_threshold = section->get_option("delta_threshold", "24");
speed_factor = section->get_option("speed_factor", "256");
speed_cap = section->get_option("speed_cap", "0.05");
wf::get_core().connect_signal("pointer-swipe-begin", &on_swipe_begin);
wf::get_core().connect_signal("pointer-swipe-update", &on_swipe_update);
wf::get_core().connect_signal("pointer-swipe-end", &on_swipe_end);
background_color = section->get_option("background", "0 0 0 1");
renderer = [=] (const wf_framebuffer& buffer) { render(buffer); };
}
/**
* Get the translation matrix for a workspace at the given offset.
* Depends on the swipe direction
*/
glm::mat4 get_translation(double offset)
{
switch (state.direction)
{
case UNKNOWN:
return glm::mat4(1.0);
case HORIZONTAL:
return glm::translate(glm::mat4(1.0),
glm::vec3(offset, 0.0, 0.0));
case VERTICAL:
return glm::translate(glm::mat4(1.0),
glm::vec3(0.0, -offset, 0.0));
}
assert(false); // not reached
}
void render(const wf_framebuffer &fb)
{
if (!duration.running() && !state.swiping)
finalize_and_exit();
if (duration.running())
state.delta_sum = duration.progress(transition);
update_stream(streams.prev);
update_stream(streams.curr);
update_stream(streams.next);
OpenGL::render_begin(fb);
OpenGL::clear(background_color->as_cached_color());
fb.scissor(fb.framebuffer_box_from_geometry_box(fb.geometry));
gl_geometry out_geometry = {
.x1 = -1,
.y1 = 1,
.x2 = 1,
.y2 = -1,
};
auto swipe = get_translation(state.delta_sum * 2);
if (streams.prev.ws.x >= 0)
{
auto prev = get_translation(-2.0 - state.gap * 2.0);
OpenGL::render_transformed_texture(streams.prev.buffer.tex,
out_geometry, {}, fb.transform * prev * swipe);
}
OpenGL::render_transformed_texture(streams.curr.buffer.tex,
out_geometry, {}, fb.transform * swipe);
if (streams.next.ws.x >= 0)
{
auto next = get_translation(2.0 + state.gap * 2.0);
OpenGL::render_transformed_texture(streams.next.buffer.tex,
out_geometry, {}, fb.transform * next * swipe);
}
GL_CALL(glUseProgram(0));
OpenGL::render_end();
}
inline void update_stream(wf::workspace_stream_t& s)
{
if (s.ws.x < 0 || s.ws.y < 0)
return;
if (!s.running)
output->render->workspace_stream_start(s);
else
output->render->workspace_stream_update(s);
}
wf::signal_callback_t on_swipe_begin = [=] (wf::signal_data_t *data)
{
if (!enable_horizontal->as_cached_int() && !enable_vertical->as_cached_int())
return;
if (output->is_plugin_active(grab_interface->name))
return;
auto ev = static_cast<wf::swipe_begin_signal*> (data)->ev;
if (static_cast<int>(ev->fingers) != fingers->as_cached_int())
return;
// Plugins are per output, swipes are global, so we need to handle
// the swipe only when the cursor is on *our* (plugin instance's) output
if (!(output->get_relative_geometry() & output->get_cursor_position()))
return;
wf::get_core().focus_output(output);
if (!output->activate_plugin(grab_interface))
return;
grab_interface->grab();
state.swiping = true;
state.direction = UNKNOWN;
state.initial_deltas = {0.0, 0.0};
state.delta_sum = 0;
state.delta_last = 0;
state.delta_prev = 0;
state.gap = gap->as_cached_double() / output->get_screen_size().width;
// We switch the actual workspace before the finishing animation,
// so the rendering of the animation cannot dynamically query current
// workspace again, so it's stored here
auto grid = output->workspace->get_workspace_grid_size();
auto ws = output->workspace->get_current_workspace();
state.vw = grid.width;
state.vh = grid.height;
state.vx = ws.x;
state.vy = ws.y;
/* Invalid in the beginning, because we want a few swipe events to
* determine whether swipe is horizontal or vertical */
streams.prev.ws = {-1, -1};
streams.next.ws = {-1, -1};
streams.curr.ws = wf_point {ws.x, ws.y};
output->render->set_renderer(renderer);
output->render->damage_whole();
};
void start_swipe(swipe_direction_t direction)
{
assert(direction != UNKNOWN);
state.direction = direction;
auto ws = output->workspace->get_current_workspace();
auto grid = output->workspace->get_workspace_grid_size();
if (direction == HORIZONTAL)
{
if (ws.x > 0)
streams.prev.ws = wf_point{ws.x - 1, ws.y};
if (ws.x < grid.width - 1)
streams.next.ws = wf_point{ws.x + 1, ws.y};
} else //if (direction == VERTICAL)
{
if (ws.y > 0)
streams.prev.ws = wf_point{ws.x, ws.y - 1};
if (ws.y < grid.height - 1)
streams.next.ws = wf_point{ws.x, ws.y + 1};
}
}
wf::signal_callback_t on_swipe_update = [=] (wf::signal_data_t *data)
{
if (!state.swiping)
return;
auto ev = static_cast<wf::swipe_update_signal*> (data)->ev;
if (state.direction == UNKNOWN)
{
auto grid = output->workspace->get_workspace_grid_size();
// XXX: how to determine this??
static constexpr double initial_direction_threshold = 0.05;
state.initial_deltas.x +=
std::abs(ev->dx) / speed_factor->as_double();
state.initial_deltas.y +=
std::abs(ev->dy) / speed_factor->as_double();
bool horizontal =
state.initial_deltas.x > initial_direction_threshold;
bool vertical =
state.initial_deltas.y > initial_direction_threshold;
horizontal &= state.initial_deltas.x > state.initial_deltas.y;
vertical &= state.initial_deltas.y > state.initial_deltas.x;
if (horizontal && grid.width > 1 && enable_horizontal->as_cached_int())
{
start_swipe(HORIZONTAL);
}
else if (vertical && grid.height > 1 && enable_vertical->as_cached_int())
{
start_swipe(VERTICAL);
}
if (state.direction == UNKNOWN)
return;
}
const double cap = speed_cap->as_cached_double();
const double fac = speed_factor->as_cached_double();
state.delta_prev = state.delta_last;
if (state.direction == HORIZONTAL)
{
state.delta_sum += vswipe_process_delta(ev->dx, state.delta_sum,
state.vx, state.vw, cap, fac);
state.delta_last = ev->dx;
} else
{
state.delta_sum += vswipe_process_delta(ev->dy, state.delta_sum,
state.vy, state.vh, cap, fac);
state.delta_last = ev->dy;
}
output->render->damage_whole();
};
wf::signal_callback_t on_swipe_end = [=] (wf::signal_data_t *data)
{
if (!state.swiping)
return;
state.swiping = false;
auto ev = static_cast<wf::swipe_end_signal*>(data)->ev;
const double move_threshold =
clamp(threshold->as_cached_double(), 0.0, 1.0);
const double fast_threshold =
clamp(delta_threshold->as_cached_double(), 0.0, 1000.0);
int target_delta = 0;
wf_point target_workspace = {state.vx, state.vy};
if (!ev->cancelled || ignore_cancel->as_int())
{
switch (state.direction)
{
case UNKNOWN:
target_delta = 0;
break;
case HORIZONTAL:
target_delta = vswipe_finish_target(state.delta_sum,
state.vx, state.vw, state.delta_prev + state.delta_last,
move_threshold, fast_threshold);
target_workspace.x -= target_delta;
break;
case VERTICAL:
target_delta = vswipe_finish_target(state.delta_sum,
state.vy, state.vh, state.delta_prev + state.delta_last,
move_threshold, fast_threshold);
target_workspace.y -= target_delta;
break;
}
}
transition = {state.delta_sum, target_delta + state.gap * target_delta};
output->workspace->set_workspace(target_workspace);
output->render->set_redraw_always();
duration.start();
};
void finalize_and_exit()
{
state.swiping = false;
grab_interface->ungrab();
output->deactivate_plugin(grab_interface);
if (streams.prev.running)
output->render->workspace_stream_stop(streams.prev);
output->render->workspace_stream_stop(streams.curr);
if (streams.next.running)
output->render->workspace_stream_stop(streams.next);
output->render->set_renderer(nullptr);
output->render->set_redraw_always(false);
}
void fini()
{
if (state.swiping)
finalize_and_exit();
OpenGL::render_begin();
streams.prev.buffer.release();
streams.curr.buffer.release();
streams.next.buffer.release();
OpenGL::render_end();
}
};
DECLARE_WAYFIRE_PLUGIN(vswipe);
<|endoftext|> |
<commit_before>#include "Genes/Genome.h"
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
#include "Game/Color.h"
#include "Game/Clock.h"
#include "Utility/Random.h"
#include "Utility/String.h"
#include "Utility/Exceptions.h"
#include "Genes/Gene.h"
#include "Genes/Total_Force_Gene.h"
#include "Genes/Freedom_To_Move_Gene.h"
#include "Genes/Pawn_Advancement_Gene.h"
#include "Genes/Passed_Pawn_Gene.h"
#include "Genes/Opponent_Pieces_Targeted_Gene.h"
#include "Genes/Sphere_of_Influence_Gene.h"
#include "Genes/Look_Ahead_Gene.h"
#include "Genes/King_Confinement_Gene.h"
#include "Genes/King_Protection_Gene.h"
#include "Genes/Castling_Possible_Gene.h"
#include "Genes/Piece_Strength_Gene.h"
#include "Genes/Stacked_Pawns_Gene.h"
#include "Genes/Pawn_Islands_Gene.h"
#include "Genes/Checkmate_Material_Gene.h"
#include "Genes/Mutation_Rate_Gene.h"
class Board;
namespace
{
constexpr auto piece_strength_gene_index = size_t(0);
constexpr auto look_ahead_gene_index = size_t(1);
constexpr auto mutation_rate_gene_index = size_t(2);
}
Genome::Genome() noexcept
{
// Regulator genes
genome.emplace_back(std::make_unique<Piece_Strength_Gene>());
assert(genome[piece_strength_gene_index]->name() == "Piece Strength Gene");
genome.emplace_back(std::make_unique<Look_Ahead_Gene>());
assert(genome[look_ahead_gene_index]->name() == "Look Ahead Gene");
genome.emplace_back(std::make_unique<Mutation_Rate_Gene>());
assert(genome[mutation_rate_gene_index]->name() == "Mutation Rate Gene");
// Normal genes
auto psg = static_cast<const Piece_Strength_Gene*>(genome[piece_strength_gene_index].get());
genome.emplace_back(std::make_unique<Total_Force_Gene>(psg));
genome.emplace_back(std::make_unique<Freedom_To_Move_Gene>());
genome.emplace_back(std::make_unique<Pawn_Advancement_Gene>());
genome.emplace_back(std::make_unique<Passed_Pawn_Gene>());
genome.emplace_back(std::make_unique<Opponent_Pieces_Targeted_Gene>(psg));
genome.emplace_back(std::make_unique<Sphere_of_Influence_Gene>());
genome.emplace_back(std::make_unique<King_Confinement_Gene>());
genome.emplace_back(std::make_unique<King_Protection_Gene>());
genome.emplace_back(std::make_unique<Castling_Possible_Gene>());
genome.emplace_back(std::make_unique<Stacked_Pawns_Gene>());
genome.emplace_back(std::make_unique<Pawn_Islands_Gene>());
genome.emplace_back(std::make_unique<Checkmate_Material_Gene>());
renormalize_priorities();
}
Genome::Genome(const Genome& other) noexcept
{
std::transform(other.genome.begin(), other.genome.end(),
std::back_inserter(genome),
[](const auto& gene)
{
return gene->duplicate();
});
reset_piece_strength_gene();
}
void Genome::reset_piece_strength_gene() noexcept
{
auto piece_strength_gene = static_cast<const Piece_Strength_Gene*>(genome[piece_strength_gene_index].get());
for(auto& gene : genome)
{
gene->reset_piece_strength_gene(piece_strength_gene);
}
}
void Genome::renormalize_priorities() noexcept
{
auto norm = std::accumulate(genome.begin(), genome.end(), 0.0,
[](auto sum, const auto& gene)
{
return sum + std::abs(gene->priority());
});
if(norm > 0.0)
{
for(auto& gene : genome)
{
gene->scale_priority(1.0/norm);
}
}
}
Genome& Genome::operator=(const Genome& other) noexcept
{
std::transform(other.genome.begin(), other.genome.end(),
genome.begin(),
[](const auto& gene)
{
return gene->duplicate();
});
reset_piece_strength_gene();
return *this;
}
Genome::Genome(const Genome& A, const Genome& B) noexcept
{
std::transform(A.genome.begin(), A.genome.end(), B.genome.begin(),
std::back_inserter(genome),
[](const auto& gene_a, const auto& gene_b)
{
return (Random::coin_flip() ? gene_a : gene_b)->duplicate();
});
reset_piece_strength_gene();
renormalize_priorities();
}
void Genome::read_from(std::istream& is)
{
std::string line;
while(std::getline(is, line))
{
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
if(line == "END")
{
renormalize_priorities();
return;
}
auto line_split = String::split(line, ":", 1);
if(line_split.size() != 2)
{
throw Genetic_AI_Creation_Error("No colon in parameter line: " + line);
}
if(String::trim_outer_whitespace(line_split[0]) == "Name")
{
auto gene_name = String::remove_extra_whitespace(line_split[1]);
bool gene_found = false;
for(auto& gene : genome)
{
if(gene->name() == gene_name)
{
gene->read_from(is);
gene_found = true;
break;
}
}
if( ! gene_found)
{
throw Genetic_AI_Creation_Error("Unrecognized gene name: " + gene_name + "\nin line: " + line);
}
}
else
{
throw Genetic_AI_Creation_Error("Bad line in genome file (expected Name): " + line);
}
}
throw Genetic_AI_Creation_Error("Reached end of file before END of genome.");
}
double Genome::score_board(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
return std::accumulate(genome.begin(), genome.end(), 0.0,
[&](auto sum, const auto& gene)
{
return sum + gene->evaluate(board, perspective, depth);
});
}
double Genome::evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
return score_board(board, perspective, depth) - score_board(board, opposite(perspective), depth);
}
void Genome::mutate() noexcept
{
// Create copies of genes based on the number of internal components
// that are mutatable
std::vector<Gene*> genes;
for(const auto& gene : genome)
{
genes.insert(genes.end(), gene->mutatable_components(), gene.get());
}
// Pick randomly from the list of copies to make sure genes with
// more components don't lack for mutations.
auto mutation_count = components_to_mutate();
for(auto mutations = 0; mutations < mutation_count; ++mutations)
{
Random::random_element(genes)->mutate();
renormalize_priorities();
}
}
void Genome::print(std::ostream& os) const noexcept
{
for(const auto& gene : genome)
{
gene->print(os);
};
}
Clock::seconds Genome::time_to_examine(const Board& board, const Clock& clock) const noexcept
{
return gene_reference<Look_Ahead_Gene, look_ahead_gene_index>().time_to_examine(board, clock);
}
double Genome::speculation_time_factor() const noexcept
{
return gene_reference<Look_Ahead_Gene, look_ahead_gene_index>().speculation_time_factor();
}
const std::array<double, 6>& Genome::piece_values() const noexcept
{
return gene_reference<Piece_Strength_Gene, piece_strength_gene_index>().piece_values();
}
int Genome::components_to_mutate() const noexcept
{
return gene_reference<Mutation_Rate_Gene, mutation_rate_gene_index>().mutation_count();
}
<commit_msg>Delete extra semicolon<commit_after>#include "Genes/Genome.h"
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
#include "Game/Color.h"
#include "Game/Clock.h"
#include "Utility/Random.h"
#include "Utility/String.h"
#include "Utility/Exceptions.h"
#include "Genes/Gene.h"
#include "Genes/Total_Force_Gene.h"
#include "Genes/Freedom_To_Move_Gene.h"
#include "Genes/Pawn_Advancement_Gene.h"
#include "Genes/Passed_Pawn_Gene.h"
#include "Genes/Opponent_Pieces_Targeted_Gene.h"
#include "Genes/Sphere_of_Influence_Gene.h"
#include "Genes/Look_Ahead_Gene.h"
#include "Genes/King_Confinement_Gene.h"
#include "Genes/King_Protection_Gene.h"
#include "Genes/Castling_Possible_Gene.h"
#include "Genes/Piece_Strength_Gene.h"
#include "Genes/Stacked_Pawns_Gene.h"
#include "Genes/Pawn_Islands_Gene.h"
#include "Genes/Checkmate_Material_Gene.h"
#include "Genes/Mutation_Rate_Gene.h"
class Board;
namespace
{
constexpr auto piece_strength_gene_index = size_t(0);
constexpr auto look_ahead_gene_index = size_t(1);
constexpr auto mutation_rate_gene_index = size_t(2);
}
Genome::Genome() noexcept
{
// Regulator genes
genome.emplace_back(std::make_unique<Piece_Strength_Gene>());
assert(genome[piece_strength_gene_index]->name() == "Piece Strength Gene");
genome.emplace_back(std::make_unique<Look_Ahead_Gene>());
assert(genome[look_ahead_gene_index]->name() == "Look Ahead Gene");
genome.emplace_back(std::make_unique<Mutation_Rate_Gene>());
assert(genome[mutation_rate_gene_index]->name() == "Mutation Rate Gene");
// Normal genes
auto psg = static_cast<const Piece_Strength_Gene*>(genome[piece_strength_gene_index].get());
genome.emplace_back(std::make_unique<Total_Force_Gene>(psg));
genome.emplace_back(std::make_unique<Freedom_To_Move_Gene>());
genome.emplace_back(std::make_unique<Pawn_Advancement_Gene>());
genome.emplace_back(std::make_unique<Passed_Pawn_Gene>());
genome.emplace_back(std::make_unique<Opponent_Pieces_Targeted_Gene>(psg));
genome.emplace_back(std::make_unique<Sphere_of_Influence_Gene>());
genome.emplace_back(std::make_unique<King_Confinement_Gene>());
genome.emplace_back(std::make_unique<King_Protection_Gene>());
genome.emplace_back(std::make_unique<Castling_Possible_Gene>());
genome.emplace_back(std::make_unique<Stacked_Pawns_Gene>());
genome.emplace_back(std::make_unique<Pawn_Islands_Gene>());
genome.emplace_back(std::make_unique<Checkmate_Material_Gene>());
renormalize_priorities();
}
Genome::Genome(const Genome& other) noexcept
{
std::transform(other.genome.begin(), other.genome.end(),
std::back_inserter(genome),
[](const auto& gene)
{
return gene->duplicate();
});
reset_piece_strength_gene();
}
void Genome::reset_piece_strength_gene() noexcept
{
auto piece_strength_gene = static_cast<const Piece_Strength_Gene*>(genome[piece_strength_gene_index].get());
for(auto& gene : genome)
{
gene->reset_piece_strength_gene(piece_strength_gene);
}
}
void Genome::renormalize_priorities() noexcept
{
auto norm = std::accumulate(genome.begin(), genome.end(), 0.0,
[](auto sum, const auto& gene)
{
return sum + std::abs(gene->priority());
});
if(norm > 0.0)
{
for(auto& gene : genome)
{
gene->scale_priority(1.0/norm);
}
}
}
Genome& Genome::operator=(const Genome& other) noexcept
{
std::transform(other.genome.begin(), other.genome.end(),
genome.begin(),
[](const auto& gene)
{
return gene->duplicate();
});
reset_piece_strength_gene();
return *this;
}
Genome::Genome(const Genome& A, const Genome& B) noexcept
{
std::transform(A.genome.begin(), A.genome.end(), B.genome.begin(),
std::back_inserter(genome),
[](const auto& gene_a, const auto& gene_b)
{
return (Random::coin_flip() ? gene_a : gene_b)->duplicate();
});
reset_piece_strength_gene();
renormalize_priorities();
}
void Genome::read_from(std::istream& is)
{
std::string line;
while(std::getline(is, line))
{
line = String::strip_comments(line, "#");
if(line.empty())
{
continue;
}
if(line == "END")
{
renormalize_priorities();
return;
}
auto line_split = String::split(line, ":", 1);
if(line_split.size() != 2)
{
throw Genetic_AI_Creation_Error("No colon in parameter line: " + line);
}
if(String::trim_outer_whitespace(line_split[0]) == "Name")
{
auto gene_name = String::remove_extra_whitespace(line_split[1]);
bool gene_found = false;
for(auto& gene : genome)
{
if(gene->name() == gene_name)
{
gene->read_from(is);
gene_found = true;
break;
}
}
if( ! gene_found)
{
throw Genetic_AI_Creation_Error("Unrecognized gene name: " + gene_name + "\nin line: " + line);
}
}
else
{
throw Genetic_AI_Creation_Error("Bad line in genome file (expected Name): " + line);
}
}
throw Genetic_AI_Creation_Error("Reached end of file before END of genome.");
}
double Genome::score_board(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
return std::accumulate(genome.begin(), genome.end(), 0.0,
[&](auto sum, const auto& gene)
{
return sum + gene->evaluate(board, perspective, depth);
});
}
double Genome::evaluate(const Board& board, Piece_Color perspective, size_t depth) const noexcept
{
return score_board(board, perspective, depth) - score_board(board, opposite(perspective), depth);
}
void Genome::mutate() noexcept
{
// Create copies of genes based on the number of internal components
// that are mutatable
std::vector<Gene*> genes;
for(const auto& gene : genome)
{
genes.insert(genes.end(), gene->mutatable_components(), gene.get());
}
// Pick randomly from the list of copies to make sure genes with
// more components don't lack for mutations.
auto mutation_count = components_to_mutate();
for(auto mutations = 0; mutations < mutation_count; ++mutations)
{
Random::random_element(genes)->mutate();
renormalize_priorities();
}
}
void Genome::print(std::ostream& os) const noexcept
{
for(const auto& gene : genome)
{
gene->print(os);
}
}
Clock::seconds Genome::time_to_examine(const Board& board, const Clock& clock) const noexcept
{
return gene_reference<Look_Ahead_Gene, look_ahead_gene_index>().time_to_examine(board, clock);
}
double Genome::speculation_time_factor() const noexcept
{
return gene_reference<Look_Ahead_Gene, look_ahead_gene_index>().speculation_time_factor();
}
const std::array<double, 6>& Genome::piece_values() const noexcept
{
return gene_reference<Piece_Strength_Gene, piece_strength_gene_index>().piece_values();
}
int Genome::components_to_mutate() const noexcept
{
return gene_reference<Mutation_Rate_Gene, mutation_rate_gene_index>().mutation_count();
}
<|endoftext|> |
<commit_before><commit_msg>fix build failure if pch is on<commit_after><|endoftext|> |
<commit_before>//
// Copyright (c) 2014-2020 CNRS INRIA
//
#ifndef __eigenpy_eigen_from_python_hpp__
#define __eigenpy_eigen_from_python_hpp__
#include "eigenpy/fwd.hpp"
#include "eigenpy/numpy-type.hpp"
#include "eigenpy/eigen-allocator.hpp"
#include "eigenpy/scalar-conversion.hpp"
#include <boost/python/converter/rvalue_from_python_data.hpp>
namespace boost { namespace python { namespace converter {
/// \brief Template specialization of rvalue_from_python_data
template<typename Derived>
struct rvalue_from_python_data<Eigen::MatrixBase<Derived> const & >
: rvalue_from_python_storage<Derived const & >
{
typedef Eigen::MatrixBase<Derived> const & T;
# if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \
&& (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \
&& (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \
&& !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */
// This must always be a POD struct with m_data its first member.
BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0);
# endif
// The usual constructor
rvalue_from_python_data(rvalue_from_python_stage1_data const & _stage1)
{
this->stage1 = _stage1;
}
// This constructor just sets m_convertible -- used by
// implicitly_convertible<> to perform the final step of the
// conversion, where the construct() function is already known.
rvalue_from_python_data(void* convertible)
{
this->stage1.convertible = convertible;
}
// Destroys any object constructed in the storage.
~rvalue_from_python_data()
{
if (this->stage1.convertible == this->storage.bytes)
static_cast<Derived *>((void *)this->storage.bytes)->~Derived();
}
};
/// \brief Template specialization of rvalue_from_python_data
template<typename Derived>
struct rvalue_from_python_data<Eigen::EigenBase<Derived> const & >
: rvalue_from_python_storage<Derived const & >
{
typedef Eigen::EigenBase<Derived> const & T;
# if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \
&& (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \
&& (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \
&& !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */
// This must always be a POD struct with m_data its first member.
BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0);
# endif
// The usual constructor
rvalue_from_python_data(rvalue_from_python_stage1_data const & _stage1)
{
this->stage1 = _stage1;
}
// This constructor just sets m_convertible -- used by
// implicitly_convertible<> to perform the final step of the
// conversion, where the construct() function is already known.
rvalue_from_python_data(void* convertible)
{
this->stage1.convertible = convertible;
}
// Destroys any object constructed in the storage.
~rvalue_from_python_data()
{
if (this->stage1.convertible == this->storage.bytes)
static_cast<Derived *>((void *)this->storage.bytes)->~Derived();
}
};
} } }
namespace eigenpy
{
template<typename MatType>
struct EigenFromPy
{
static bool isScalarConvertible(const int np_type)
{
if(NumpyEquivalentType<typename MatType::Scalar>::type_code == np_type)
return true;
switch(np_type)
{
case NPY_INT:
return FromTypeToType<int,typename MatType::Scalar>::value;
case NPY_LONG:
return FromTypeToType<long,typename MatType::Scalar>::value;
case NPY_FLOAT:
return FromTypeToType<float,typename MatType::Scalar>::value;
case NPY_CFLOAT:
return FromTypeToType<std::complex<float>,typename MatType::Scalar>::value;
case NPY_DOUBLE:
return FromTypeToType<double,typename MatType::Scalar>::value;
case NPY_CDOUBLE:
return FromTypeToType<std::complex<double>,typename MatType::Scalar>::value;
case NPY_LONGDOUBLE:
return FromTypeToType<long double,typename MatType::Scalar>::value;
case NPY_CLONGDOUBLE:
return FromTypeToType<std::complex<long double>,typename MatType::Scalar>::value;
default:
return false;
}
}
/// \brief Determine if pyObj can be converted into a MatType object
static void* convertible(PyArrayObject* pyArray)
{
if(!PyArray_Check(pyArray))
return 0;
if(!isScalarConvertible(EIGENPY_GET_PY_ARRAY_TYPE(pyArray)))
return 0;
if(MatType::IsVectorAtCompileTime)
{
const Eigen::DenseIndex size_at_compile_time
= MatType::IsRowMajor
? MatType::ColsAtCompileTime
: MatType::RowsAtCompileTime;
switch(PyArray_NDIM(pyArray))
{
case 0:
return 0;
case 1:
{
if(size_at_compile_time != Eigen::Dynamic)
{
// check that the sizes at compile time matche
if(PyArray_DIMS(pyArray)[0] == size_at_compile_time)
return pyArray;
else
return 0;
}
else // This is a dynamic MatType
return pyArray;
}
case 2:
{
// Special care of scalar matrix of dimension 1x1.
if(PyArray_DIMS(pyArray)[0] == 1 && PyArray_DIMS(pyArray)[1] == 1)
{
if(size_at_compile_time != Eigen::Dynamic)
{
if(size_at_compile_time == 1)
return pyArray;
else
return 0;
}
else // This is a dynamic MatType
return pyArray;
}
if(PyArray_DIMS(pyArray)[0] > 1 && PyArray_DIMS(pyArray)[1] > 1)
{
#ifndef NDEBUG
std::cerr << "The number of dimension of the object does not correspond to a vector" << std::endl;
#endif
return 0;
}
if(((PyArray_DIMS(pyArray)[0] == 1) && (MatType::ColsAtCompileTime == 1))
|| ((PyArray_DIMS(pyArray)[1] == 1) && (MatType::RowsAtCompileTime == 1)))
{
#ifndef NDEBUG
if(MatType::ColsAtCompileTime == 1)
std::cerr << "The object is not a column vector" << std::endl;
else
std::cerr << "The object is not a row vector" << std::endl;
#endif
return 0;
}
if(size_at_compile_time != Eigen::Dynamic)
{ // This is a fixe size vector
const Eigen::DenseIndex pyArray_size
= PyArray_DIMS(pyArray)[0] > PyArray_DIMS(pyArray)[1]
? PyArray_DIMS(pyArray)[0]
: PyArray_DIMS(pyArray)[1];
if(size_at_compile_time != pyArray_size)
return 0;
}
break;
}
default:
return 0;
}
}
else // this is a matrix
{
if(PyArray_NDIM(pyArray) == 1) // We can always convert a vector into a matrix
{
return pyArray;
}
if(PyArray_NDIM(pyArray) != 2)
{
#ifndef NDEBUG
std::cerr << "The number of dimension of the object is not correct." << std::endl;
#endif
return 0;
}
if(PyArray_NDIM(pyArray) == 2)
{
const int R = (int)PyArray_DIMS(pyArray)[0];
const int C = (int)PyArray_DIMS(pyArray)[1];
if( (MatType::RowsAtCompileTime!=R)
&& (MatType::RowsAtCompileTime!=Eigen::Dynamic) )
return 0;
if( (MatType::ColsAtCompileTime!=C)
&& (MatType::ColsAtCompileTime!=Eigen::Dynamic) )
return 0;
}
}
#ifdef NPY_1_8_API_VERSION
if(!(PyArray_FLAGS(pyArray)))
#else
if(!(PyArray_FLAGS(pyArray) & NPY_ALIGNED))
#endif
{
#ifndef NDEBUG
std::cerr << "NPY non-aligned matrices are not implemented." << std::endl;
#endif
return 0;
}
return pyArray;
}
/// \brief Allocate memory and copy pyObj in the new storage
static void construct(PyObject* pyObj,
bp::converter::rvalue_from_python_stage1_data* memory)
{
PyArrayObject * pyArray = reinterpret_cast<PyArrayObject*>(pyObj);
assert((PyArray_DIMS(pyArray)[0]<INT_MAX) && (PyArray_DIMS(pyArray)[1]<INT_MAX));
void* storage = reinterpret_cast<bp::converter::rvalue_from_python_storage<MatType>*>
(reinterpret_cast<void*>(memory))->storage.bytes;
EigenAllocator<MatType>::allocate(pyArray,storage);
memory->convertible = storage;
}
static void registration()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&EigenFromPy::convertible),
&EigenFromPy::construct,bp::type_id<MatType>());
}
};
template<typename MatType>
struct EigenFromPyConverter
{
static void registration()
{
EigenFromPy<MatType>::registration();
// Add also conversion to Eigen::MatrixBase<MatType>
typedef Eigen::MatrixBase<MatType> MatrixBase;
EigenFromPy<MatrixBase>::registration();
// Add also conversion to Eigen::EigenBase<MatType>
typedef Eigen::EigenBase<MatType> EigenBase;
EigenFromPy<EigenBase>::registration();
}
};
template<typename MatType>
struct EigenFromPy< Eigen::MatrixBase<MatType> > : EigenFromPy<MatType>
{
typedef EigenFromPy<MatType> EigenFromPyDerived;
typedef Eigen::MatrixBase<MatType> Base;
static void registration()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&EigenFromPy::convertible),
&EigenFromPy::construct,bp::type_id<Base>());
}
};
template<typename MatType>
struct EigenFromPy< Eigen::EigenBase<MatType> > : EigenFromPy<MatType>
{
typedef EigenFromPy<MatType> EigenFromPyDerived;
typedef Eigen::EigenBase<MatType> Base;
static void registration()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&EigenFromPy::convertible),
&EigenFromPy::construct,bp::type_id<Base>());
}
};
#if EIGEN_VERSION_AT_LEAST(3,2,0)
// Template specialization for Eigen::Ref
template<typename MatType>
struct EigenFromPyConverter< eigenpy::Ref<MatType> >
{
static void registration()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&EigenFromPy<MatType>::convertible),
&EigenFromPy<MatType>::construct,bp::type_id<MatType>());
}
};
#endif
}
#endif // __eigenpy_eigen_from_python_hpp__
<commit_msg>core: remote std::cerr<commit_after>//
// Copyright (c) 2014-2020 CNRS INRIA
//
#ifndef __eigenpy_eigen_from_python_hpp__
#define __eigenpy_eigen_from_python_hpp__
#include "eigenpy/fwd.hpp"
#include "eigenpy/numpy-type.hpp"
#include "eigenpy/eigen-allocator.hpp"
#include "eigenpy/scalar-conversion.hpp"
#include <boost/python/converter/rvalue_from_python_data.hpp>
namespace boost { namespace python { namespace converter {
/// \brief Template specialization of rvalue_from_python_data
template<typename Derived>
struct rvalue_from_python_data<Eigen::MatrixBase<Derived> const & >
: rvalue_from_python_storage<Derived const & >
{
typedef Eigen::MatrixBase<Derived> const & T;
# if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \
&& (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \
&& (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \
&& !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */
// This must always be a POD struct with m_data its first member.
BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0);
# endif
// The usual constructor
rvalue_from_python_data(rvalue_from_python_stage1_data const & _stage1)
{
this->stage1 = _stage1;
}
// This constructor just sets m_convertible -- used by
// implicitly_convertible<> to perform the final step of the
// conversion, where the construct() function is already known.
rvalue_from_python_data(void* convertible)
{
this->stage1.convertible = convertible;
}
// Destroys any object constructed in the storage.
~rvalue_from_python_data()
{
if (this->stage1.convertible == this->storage.bytes)
static_cast<Derived *>((void *)this->storage.bytes)->~Derived();
}
};
/// \brief Template specialization of rvalue_from_python_data
template<typename Derived>
struct rvalue_from_python_data<Eigen::EigenBase<Derived> const & >
: rvalue_from_python_storage<Derived const & >
{
typedef Eigen::EigenBase<Derived> const & T;
# if (!defined(__MWERKS__) || __MWERKS__ >= 0x3000) \
&& (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 245) \
&& (!defined(__DECCXX_VER) || __DECCXX_VER > 60590014) \
&& !defined(BOOST_PYTHON_SYNOPSIS) /* Synopsis' OpenCXX has trouble parsing this */
// This must always be a POD struct with m_data its first member.
BOOST_STATIC_ASSERT(BOOST_PYTHON_OFFSETOF(rvalue_from_python_storage<T>,stage1) == 0);
# endif
// The usual constructor
rvalue_from_python_data(rvalue_from_python_stage1_data const & _stage1)
{
this->stage1 = _stage1;
}
// This constructor just sets m_convertible -- used by
// implicitly_convertible<> to perform the final step of the
// conversion, where the construct() function is already known.
rvalue_from_python_data(void* convertible)
{
this->stage1.convertible = convertible;
}
// Destroys any object constructed in the storage.
~rvalue_from_python_data()
{
if (this->stage1.convertible == this->storage.bytes)
static_cast<Derived *>((void *)this->storage.bytes)->~Derived();
}
};
} } }
namespace eigenpy
{
template<typename MatType>
struct EigenFromPy
{
static bool isScalarConvertible(const int np_type)
{
if(NumpyEquivalentType<typename MatType::Scalar>::type_code == np_type)
return true;
switch(np_type)
{
case NPY_INT:
return FromTypeToType<int,typename MatType::Scalar>::value;
case NPY_LONG:
return FromTypeToType<long,typename MatType::Scalar>::value;
case NPY_FLOAT:
return FromTypeToType<float,typename MatType::Scalar>::value;
case NPY_CFLOAT:
return FromTypeToType<std::complex<float>,typename MatType::Scalar>::value;
case NPY_DOUBLE:
return FromTypeToType<double,typename MatType::Scalar>::value;
case NPY_CDOUBLE:
return FromTypeToType<std::complex<double>,typename MatType::Scalar>::value;
case NPY_LONGDOUBLE:
return FromTypeToType<long double,typename MatType::Scalar>::value;
case NPY_CLONGDOUBLE:
return FromTypeToType<std::complex<long double>,typename MatType::Scalar>::value;
default:
return false;
}
}
/// \brief Determine if pyObj can be converted into a MatType object
static void* convertible(PyArrayObject* pyArray)
{
if(!PyArray_Check(pyArray))
return 0;
if(!isScalarConvertible(EIGENPY_GET_PY_ARRAY_TYPE(pyArray)))
return 0;
if(MatType::IsVectorAtCompileTime)
{
const Eigen::DenseIndex size_at_compile_time
= MatType::IsRowMajor
? MatType::ColsAtCompileTime
: MatType::RowsAtCompileTime;
switch(PyArray_NDIM(pyArray))
{
case 0:
return 0;
case 1:
{
if(size_at_compile_time != Eigen::Dynamic)
{
// check that the sizes at compile time matche
if(PyArray_DIMS(pyArray)[0] == size_at_compile_time)
return pyArray;
else
return 0;
}
else // This is a dynamic MatType
return pyArray;
}
case 2:
{
// Special care of scalar matrix of dimension 1x1.
if(PyArray_DIMS(pyArray)[0] == 1 && PyArray_DIMS(pyArray)[1] == 1)
{
if(size_at_compile_time != Eigen::Dynamic)
{
if(size_at_compile_time == 1)
return pyArray;
else
return 0;
}
else // This is a dynamic MatType
return pyArray;
}
if(PyArray_DIMS(pyArray)[0] > 1 && PyArray_DIMS(pyArray)[1] > 1)
{
return 0;
}
if(((PyArray_DIMS(pyArray)[0] == 1) && (MatType::ColsAtCompileTime == 1))
|| ((PyArray_DIMS(pyArray)[1] == 1) && (MatType::RowsAtCompileTime == 1)))
{
return 0;
}
if(size_at_compile_time != Eigen::Dynamic)
{ // This is a fixe size vector
const Eigen::DenseIndex pyArray_size
= PyArray_DIMS(pyArray)[0] > PyArray_DIMS(pyArray)[1]
? PyArray_DIMS(pyArray)[0]
: PyArray_DIMS(pyArray)[1];
if(size_at_compile_time != pyArray_size)
return 0;
}
break;
}
default:
return 0;
}
}
else // this is a matrix
{
if(PyArray_NDIM(pyArray) == 1) // We can always convert a vector into a matrix
{
return pyArray;
}
if(PyArray_NDIM(pyArray) != 2)
{
return 0;
}
if(PyArray_NDIM(pyArray) == 2)
{
const int R = (int)PyArray_DIMS(pyArray)[0];
const int C = (int)PyArray_DIMS(pyArray)[1];
if( (MatType::RowsAtCompileTime!=R)
&& (MatType::RowsAtCompileTime!=Eigen::Dynamic) )
return 0;
if( (MatType::ColsAtCompileTime!=C)
&& (MatType::ColsAtCompileTime!=Eigen::Dynamic) )
return 0;
}
}
#ifdef NPY_1_8_API_VERSION
if(!(PyArray_FLAGS(pyArray)))
#else
if(!(PyArray_FLAGS(pyArray) & NPY_ALIGNED))
#endif
{
return 0;
}
return pyArray;
}
/// \brief Allocate memory and copy pyObj in the new storage
static void construct(PyObject* pyObj,
bp::converter::rvalue_from_python_stage1_data* memory)
{
PyArrayObject * pyArray = reinterpret_cast<PyArrayObject*>(pyObj);
assert((PyArray_DIMS(pyArray)[0]<INT_MAX) && (PyArray_DIMS(pyArray)[1]<INT_MAX));
void* storage = reinterpret_cast<bp::converter::rvalue_from_python_storage<MatType>*>
(reinterpret_cast<void*>(memory))->storage.bytes;
EigenAllocator<MatType>::allocate(pyArray,storage);
memory->convertible = storage;
}
static void registration()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&EigenFromPy::convertible),
&EigenFromPy::construct,bp::type_id<MatType>());
}
};
template<typename MatType>
struct EigenFromPyConverter
{
static void registration()
{
EigenFromPy<MatType>::registration();
// Add also conversion to Eigen::MatrixBase<MatType>
typedef Eigen::MatrixBase<MatType> MatrixBase;
EigenFromPy<MatrixBase>::registration();
// Add also conversion to Eigen::EigenBase<MatType>
typedef Eigen::EigenBase<MatType> EigenBase;
EigenFromPy<EigenBase>::registration();
}
};
template<typename MatType>
struct EigenFromPy< Eigen::MatrixBase<MatType> > : EigenFromPy<MatType>
{
typedef EigenFromPy<MatType> EigenFromPyDerived;
typedef Eigen::MatrixBase<MatType> Base;
static void registration()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&EigenFromPy::convertible),
&EigenFromPy::construct,bp::type_id<Base>());
}
};
template<typename MatType>
struct EigenFromPy< Eigen::EigenBase<MatType> > : EigenFromPy<MatType>
{
typedef EigenFromPy<MatType> EigenFromPyDerived;
typedef Eigen::EigenBase<MatType> Base;
static void registration()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&EigenFromPy::convertible),
&EigenFromPy::construct,bp::type_id<Base>());
}
};
#if EIGEN_VERSION_AT_LEAST(3,2,0)
// Template specialization for Eigen::Ref
template<typename MatType>
struct EigenFromPyConverter< eigenpy::Ref<MatType> >
{
static void registration()
{
bp::converter::registry::push_back
(reinterpret_cast<void *(*)(_object *)>(&EigenFromPy<MatType>::convertible),
&EigenFromPy<MatType>::construct,bp::type_id<MatType>());
}
};
#endif
}
#endif // __eigenpy_eigen_from_python_hpp__
<|endoftext|> |
<commit_before>#pragma once
#include <iostream>
#include <type_traits> // for std::is_same<>
#include <functional>
#include <type_traits> // for std::false_type/std::true_type
#include <exception> // for std::is_same<>
namespace mittens
{
//////////////////////////////////////////////////////////////////////////
template <typename FailCodeType_ = int>
class UnHandler
{
public:
typedef FailCodeType_ FailCodeType;
FailCodeType handleException()
{
// Instead of a call to `throw` we will check if the function was called inside a
// catch clause. If so, `std::rethrow_exception(eptr)` is the same as `throw`.
// Otherwise, throw an `std::logic_error` since this is obviously a bug.
if (std::exception_ptr eptr = std::current_exception())
std::rethrow_exception(eptr);
throw std::logic_error("Mittens handler called outside of a catch clause! This is a BUG.");
}
FailCodeType operator()() { return handleException(); }
};
//////////////////////////////////////////////////////////////////////////
// Helper utils
namespace
{
template <bool v> struct Bool2Type { static const bool value = v; }; // anonymous helper function
}
// Helper default no-action type
template <typename ExceptionType = void>
struct DefaultNoAction
{ void operator()(ExceptionType&){} };
template <>
struct DefaultNoAction<void>
{ void operator()(){} };
//////////////////////////////////////////////////////////////////////////
template <typename ExceptionType, typename NestedHandler, typename Callable = DefaultNoAction<ExceptionType> >
class GenericExceptionHandler
{
public:
typedef typename NestedHandler::FailCodeType FailCodeType;
GenericExceptionHandler(FailCodeType failCode, NestedHandler const& nestedHandler, Callable customAction = Callable(), bool supressExceptionsInAction = true):
failCode_(failCode),
nestedHandler(nestedHandler),
customAction_(customAction),
supressExceptionsInAction_(supressExceptionsInAction)
{}
FailCodeType handleException() { return handleException_(Bool2Type<std::is_same<ExceptionType, void>::value>()); }
FailCodeType operator()() { return handleException(); }
private:
//////////////////////////////////////////////////////////////////////////
// What follows is lots of code and compile-time trickery to work-around
// partial support for template specialization in VS2010
FailCodeType handleException_(Bool2Type<false> exceptionTypeNotVoid)
{
// Handle the case of ExceptionType != void
// This means 'e' can and needs to be passed to the custom-action (if the exception is caught)
try
{
return nestedHandler();
}
catch (ExceptionType& e)
{
// If the return type of the custom action is the same as FailCodeType (as opposed to void or even less plausible something else)
// then return the result of custom action as the fail code.
auto shouldReturnActionResult = Bool2Type< std::is_same< FailCodeType, decltype(customAction_(e)) >::value>();
return handleNonVoidExceptionType(shouldReturnActionResult);
e; // prevent unused variable warning. 'e' is used inside the decltype, but nowhere else (except here...)
}
}
FailCodeType handleException_(Bool2Type<true> exceptionTypeIsVoid)
{
// Handle the case of ExceptionType == void: Interpret this as catch-all: '...'
try
{
return nestedHandler();
}
catch (...)
{
// If the return type of the custom action is the same as FailCodeType (as opposed to void or even less plausible something else)
// then return the result of custom action as the fail code.
auto shouldReturnActionResult = Bool2Type< std::is_same< FailCodeType, decltype(customAction_()) >::value>();
return handleVoidExceptionType(shouldReturnActionResult);
}
}
FailCodeType handleVoidExceptionType(Bool2Type<true> shouldReturnFromCustomAction)
{
try { return customAction_(); } catch (...) { if (!supressExceptionsInAction_) throw; } // Run custom action. Force it no-throw by suppressing any exceptions or not.
return failCode_;
}
FailCodeType handleVoidExceptionType(Bool2Type<false> shouldReturnFromCustomAction)
{
try { customAction_(); } catch (...) { if (!supressExceptionsInAction_) throw; } // Run custom action. Force it no-throw by suppressing any exceptions or not.
return failCode_;
}
FailCodeType handleNonVoidExceptionType(Bool2Type<true> shouldReturnFromCustomAction)
{
try
{
try
{ throw; } // rethrow to get 'e' - can't pass it as argument since it may be of type void
catch (ExceptionType& e)
{
// now we have 'e':
try { return customAction_(e); } catch (...) { if (!supressExceptionsInAction_) throw; } // Run custom action. Force it no-throw by suppressing any exceptions or not.
return failCode_;
}
} catch (...) {} // In case from some weird situation the re-thrown exception is not of type ExceptionType
return failCode_;
}
FailCodeType handleNonVoidExceptionType(Bool2Type<false> shouldReturnFromCustomAction)
{
try
{
try
{ throw; } // rethrow to get 'e' - can't pass it as argument since it may be of type void
catch (ExceptionType& e)
{
// now we have 'e':
try { customAction_(e); } catch (...) { if (!supressExceptionsInAction_) throw; } // Run custom action. Force it no-throw by suppressing any exceptions or not.
return failCode_;
}
} catch (...) {} // In case from some weird situation the re-thrown exception is not of type ExceptionType
return failCode_;
}
private:
FailCodeType failCode_;
NestedHandler nestedHandler;
Callable customAction_;
bool supressExceptionsInAction_;
};
template <typename ExceptionType, typename Callable, typename NestedHandler>
inline auto generic_handler(typename NestedHandler::FailCodeType failCode, Callable customAction, NestedHandler const& nestedHandler, bool supressExceptionsInAction = true)
{ return GenericExceptionHandler<ExceptionType, NestedHandler, Callable>(failCode, nestedHandler, customAction, supressExceptionsInAction); }
namespace
{
namespace detail
{
//////////////////////////////////////////////////////////////////////////
// Helper functions for SFINAE overload resolution
template< typename ... Ts >
using void_t = void;
template< typename T, typename = void >
struct hasNestedFailCodeType : std::false_type {};
template< typename T >
struct hasNestedFailCodeType< T, void_t<typename T::FailCodeType> > : std::true_type {};
//////////////////////////////////////////////////////////////////////////
template <typename ExceptionType, typename Callable, typename FailCodeType>
inline auto generic_handler_impl(FailCodeType failCode, Callable customAction, bool supressExceptionsInAction, std::false_type)
{ return generic_handler<ExceptionType>(failCode, customAction, UnHandler<FailCodeType>(), supressExceptionsInAction); }
template <typename ExceptionType, typename NestedHandler, typename FailCodeType>
inline auto generic_handler_impl(FailCodeType failCode, NestedHandler const& nestedHandler, bool supressExceptionsInAction, std::true_type)
{ return generic_handler<ExceptionType>(failCode, DefaultNoAction<ExceptionType>(), nestedHandler, supressExceptionsInAction); }
}
}
template <typename ExceptionType, typename Callable, typename FailCodeType>
inline auto generic_handler(FailCodeType code, Callable func, bool supressExceptionsInAction = true)
{ return detail::generic_handler_impl<ExceptionType>(code, func, supressExceptionsInAction, detail::hasNestedFailCodeType<Callable>{}); }
template <typename ExceptionType, typename FailCodeType>
inline auto generic_handler(FailCodeType failCode)
{ return generic_handler<ExceptionType>(failCode, DefaultNoAction<ExceptionType>(), UnHandler<FailCodeType>()); }
}
<commit_msg>Prevent 'unused variable' warning on all platforms.<commit_after>#pragma once
#include <iostream>
#include <type_traits> // for std::is_same<>
#include <functional>
#include <type_traits> // for std::false_type/std::true_type
#include <exception> // for std::is_same<>
namespace mittens
{
//////////////////////////////////////////////////////////////////////////
template <typename FailCodeType_ = int>
class UnHandler
{
public:
typedef FailCodeType_ FailCodeType;
FailCodeType handleException()
{
// Instead of a call to `throw` we will check if the function was called inside a
// catch clause. If so, `std::rethrow_exception(eptr)` is the same as `throw`.
// Otherwise, throw an `std::logic_error` since this is obviously a bug.
if (std::exception_ptr eptr = std::current_exception())
std::rethrow_exception(eptr);
throw std::logic_error("Mittens handler called outside of a catch clause! This is a BUG.");
}
FailCodeType operator()() { return handleException(); }
};
//////////////////////////////////////////////////////////////////////////
// Helper utils
namespace
{
template <bool v> struct Bool2Type { static const bool value = v; }; // anonymous helper function
}
// Helper default no-action type
template <typename ExceptionType = void>
struct DefaultNoAction
{ void operator()(ExceptionType&){} };
template <>
struct DefaultNoAction<void>
{ void operator()(){} };
//////////////////////////////////////////////////////////////////////////
template <typename ExceptionType, typename NestedHandler, typename Callable = DefaultNoAction<ExceptionType> >
class GenericExceptionHandler
{
public:
typedef typename NestedHandler::FailCodeType FailCodeType;
GenericExceptionHandler(FailCodeType failCode, NestedHandler const& nestedHandler, Callable customAction = Callable(), bool supressExceptionsInAction = true):
failCode_(failCode),
nestedHandler(nestedHandler),
customAction_(customAction),
supressExceptionsInAction_(supressExceptionsInAction)
{}
FailCodeType handleException() { return handleException_(Bool2Type<std::is_same<ExceptionType, void>::value>()); }
FailCodeType operator()() { return handleException(); }
private:
//////////////////////////////////////////////////////////////////////////
// What follows is lots of code and compile-time trickery to work-around
// partial support for template specialization in VS2010
FailCodeType handleException_(Bool2Type<false> exceptionTypeNotVoid)
{
// Handle the case of ExceptionType != void
// This means 'e' can and needs to be passed to the custom-action (if the exception is caught)
try
{
return nestedHandler();
}
catch (ExceptionType& e)
{
// If the return type of the custom action is the same as FailCodeType (as opposed to void or even less plausible something else)
// then return the result of custom action as the fail code.
auto shouldReturnActionResult = Bool2Type< std::is_same< FailCodeType, decltype(customAction_(e)) >::value>();
return handleNonVoidExceptionType(shouldReturnActionResult);
(void)e; // prevent unused variable warning. 'e' is used inside the decltype, but nowhere else (except here...)
}
}
FailCodeType handleException_(Bool2Type<true> exceptionTypeIsVoid)
{
// Handle the case of ExceptionType == void: Interpret this as catch-all: '...'
try
{
return nestedHandler();
}
catch (...)
{
// If the return type of the custom action is the same as FailCodeType (as opposed to void or even less plausible something else)
// then return the result of custom action as the fail code.
auto shouldReturnActionResult = Bool2Type< std::is_same< FailCodeType, decltype(customAction_()) >::value>();
return handleVoidExceptionType(shouldReturnActionResult);
}
}
FailCodeType handleVoidExceptionType(Bool2Type<true> shouldReturnFromCustomAction)
{
try { return customAction_(); } catch (...) { if (!supressExceptionsInAction_) throw; } // Run custom action. Force it no-throw by suppressing any exceptions or not.
return failCode_;
}
FailCodeType handleVoidExceptionType(Bool2Type<false> shouldReturnFromCustomAction)
{
try { customAction_(); } catch (...) { if (!supressExceptionsInAction_) throw; } // Run custom action. Force it no-throw by suppressing any exceptions or not.
return failCode_;
}
FailCodeType handleNonVoidExceptionType(Bool2Type<true> shouldReturnFromCustomAction)
{
try
{
try
{ throw; } // rethrow to get 'e' - can't pass it as argument since it may be of type void
catch (ExceptionType& e)
{
// now we have 'e':
try { return customAction_(e); } catch (...) { if (!supressExceptionsInAction_) throw; } // Run custom action. Force it no-throw by suppressing any exceptions or not.
return failCode_;
}
} catch (...) {} // In case from some weird situation the re-thrown exception is not of type ExceptionType
return failCode_;
}
FailCodeType handleNonVoidExceptionType(Bool2Type<false> shouldReturnFromCustomAction)
{
try
{
try
{ throw; } // rethrow to get 'e' - can't pass it as argument since it may be of type void
catch (ExceptionType& e)
{
// now we have 'e':
try { customAction_(e); } catch (...) { if (!supressExceptionsInAction_) throw; } // Run custom action. Force it no-throw by suppressing any exceptions or not.
return failCode_;
}
} catch (...) {} // In case from some weird situation the re-thrown exception is not of type ExceptionType
return failCode_;
}
private:
FailCodeType failCode_;
NestedHandler nestedHandler;
Callable customAction_;
bool supressExceptionsInAction_;
};
template <typename ExceptionType, typename Callable, typename NestedHandler>
inline auto generic_handler(typename NestedHandler::FailCodeType failCode, Callable customAction, NestedHandler const& nestedHandler, bool supressExceptionsInAction = true)
{ return GenericExceptionHandler<ExceptionType, NestedHandler, Callable>(failCode, nestedHandler, customAction, supressExceptionsInAction); }
namespace
{
namespace detail
{
//////////////////////////////////////////////////////////////////////////
// Helper functions for SFINAE overload resolution
template< typename ... Ts >
using void_t = void;
template< typename T, typename = void >
struct hasNestedFailCodeType : std::false_type {};
template< typename T >
struct hasNestedFailCodeType< T, void_t<typename T::FailCodeType> > : std::true_type {};
//////////////////////////////////////////////////////////////////////////
template <typename ExceptionType, typename Callable, typename FailCodeType>
inline auto generic_handler_impl(FailCodeType failCode, Callable customAction, bool supressExceptionsInAction, std::false_type)
{ return generic_handler<ExceptionType>(failCode, customAction, UnHandler<FailCodeType>(), supressExceptionsInAction); }
template <typename ExceptionType, typename NestedHandler, typename FailCodeType>
inline auto generic_handler_impl(FailCodeType failCode, NestedHandler const& nestedHandler, bool supressExceptionsInAction, std::true_type)
{ return generic_handler<ExceptionType>(failCode, DefaultNoAction<ExceptionType>(), nestedHandler, supressExceptionsInAction); }
}
}
template <typename ExceptionType, typename Callable, typename FailCodeType>
inline auto generic_handler(FailCodeType code, Callable func, bool supressExceptionsInAction = true)
{ return detail::generic_handler_impl<ExceptionType>(code, func, supressExceptionsInAction, detail::hasNestedFailCodeType<Callable>{}); }
template <typename ExceptionType, typename FailCodeType>
inline auto generic_handler(FailCodeType failCode)
{ return generic_handler<ExceptionType>(failCode, DefaultNoAction<ExceptionType>(), UnHandler<FailCodeType>()); }
}
<|endoftext|> |
<commit_before>/* This file is part of the KDE project
*
* Copyright (C) 2005 Christoph Cullmann <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "katesession.h"
#include "katesessionmanager.h"
#include "katedebug.h"
#include <KConfig>
#include <KConfigGroup>
#include <QCollator>
#include <QFile>
#include <QFileInfo>
static const QLatin1String opGroupName("Open Documents");
static const QLatin1String keyCount("Count");
KateSession::KateSession(const QString &file, const QString &name, const bool anonymous, const KConfig *_config)
: m_name(name)
, m_file(file)
, m_anonymous(anonymous)
, m_documents(0)
, m_config(0)
, m_timestamp()
{
Q_ASSERT(!m_file.isEmpty());
if (_config) { // copy data from config instead
m_config = _config->copyTo(m_file);
} else if (!QFile::exists(m_file)) { // given file exists, use it to load some stuff
qCDebug(LOG_KATE) << "Warning, session file not found: " << m_file;
return;
}
m_timestamp = QFileInfo(m_file).lastModified();
// get the document count
m_documents = config()->group(opGroupName).readEntry(keyCount, 0);
}
KateSession::~KateSession()
{
delete m_config;
}
const QString &KateSession::file() const
{
return m_file;
}
void KateSession::setDocuments(const unsigned int number)
{
config()->group(opGroupName).writeEntry(keyCount, number);
m_documents = number;
}
void KateSession::setFile(const QString &filename)
{
if (m_config) {
KConfig *cfg = m_config->copyTo(filename);
delete m_config;
m_config = cfg;
}
m_file = filename;
}
void KateSession::setName(const QString &name)
{
m_name = name;
}
KConfig *KateSession::config()
{
if (m_config) {
return m_config;
}
// reread documents number?
return m_config = new KConfig(m_file, KConfig::SimpleConfig);
}
KateSession::Ptr KateSession::create(const QString &file, const QString &name)
{
return Ptr(new KateSession(file, name, false));
}
KateSession::Ptr KateSession::createFrom(const KateSession::Ptr &session, const QString &file, const QString &name)
{
return Ptr(new KateSession(file, name, false, session->config()));
}
KateSession::Ptr KateSession::createAnonymous(const QString &file)
{
return Ptr(new KateSession(file, QString(), true));
}
KateSession::Ptr KateSession::createAnonymousFrom(const KateSession::Ptr &session, const QString &file)
{
return Ptr(new KateSession(file, QString(), true, session->config()));
}
bool KateSession::compareByName(const KateSession::Ptr &s1, const KateSession::Ptr &s2)
{
return QCollator().compare(s1->name(), s2->name()) == -1;
}
bool KateSession::compareByTimeDesc(const KateSession::Ptr &s1, const KateSession::Ptr &s2)
{
return s1->timestamp() < s2->timestamp();
}
<commit_msg>kate: use correct time order for quick open sessions<commit_after>/* This file is part of the KDE project
*
* Copyright (C) 2005 Christoph Cullmann <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "katesession.h"
#include "katesessionmanager.h"
#include "katedebug.h"
#include <KConfig>
#include <KConfigGroup>
#include <QCollator>
#include <QFile>
#include <QFileInfo>
static const QLatin1String opGroupName("Open Documents");
static const QLatin1String keyCount("Count");
KateSession::KateSession(const QString &file, const QString &name, const bool anonymous, const KConfig *_config)
: m_name(name)
, m_file(file)
, m_anonymous(anonymous)
, m_documents(0)
, m_config(0)
, m_timestamp()
{
Q_ASSERT(!m_file.isEmpty());
if (_config) { // copy data from config instead
m_config = _config->copyTo(m_file);
} else if (!QFile::exists(m_file)) { // given file exists, use it to load some stuff
qCDebug(LOG_KATE) << "Warning, session file not found: " << m_file;
return;
}
m_timestamp = QFileInfo(m_file).lastModified();
// get the document count
m_documents = config()->group(opGroupName).readEntry(keyCount, 0);
}
KateSession::~KateSession()
{
delete m_config;
}
const QString &KateSession::file() const
{
return m_file;
}
void KateSession::setDocuments(const unsigned int number)
{
config()->group(opGroupName).writeEntry(keyCount, number);
m_documents = number;
}
void KateSession::setFile(const QString &filename)
{
if (m_config) {
KConfig *cfg = m_config->copyTo(filename);
delete m_config;
m_config = cfg;
}
m_file = filename;
}
void KateSession::setName(const QString &name)
{
m_name = name;
}
KConfig *KateSession::config()
{
if (m_config) {
return m_config;
}
// reread documents number?
return m_config = new KConfig(m_file, KConfig::SimpleConfig);
}
KateSession::Ptr KateSession::create(const QString &file, const QString &name)
{
return Ptr(new KateSession(file, name, false));
}
KateSession::Ptr KateSession::createFrom(const KateSession::Ptr &session, const QString &file, const QString &name)
{
return Ptr(new KateSession(file, name, false, session->config()));
}
KateSession::Ptr KateSession::createAnonymous(const QString &file)
{
return Ptr(new KateSession(file, QString(), true));
}
KateSession::Ptr KateSession::createAnonymousFrom(const KateSession::Ptr &session, const QString &file)
{
return Ptr(new KateSession(file, QString(), true, session->config()));
}
bool KateSession::compareByName(const KateSession::Ptr &s1, const KateSession::Ptr &s2)
{
return QCollator().compare(s1->name(), s2->name()) == -1;
}
bool KateSession::compareByTimeDesc(const KateSession::Ptr &s1, const KateSession::Ptr &s2)
{
return s1->timestamp() > s2->timestamp();
}
<|endoftext|> |
<commit_before>/**
* Node Native Module for Lib Sodium
*
* @Author Pedro Paixao
* @email paixaop at gmail dot com
* @License MIT
*/
#include "node_sodium.h"
#include "crypto_sign_ed25519.h"
/**
* Register function calls in node binding
*/
void register_crypto_sign(Handle<Object> target) {
// Sign
NEW_METHOD_ALIAS(crypto_sign, crypto_sign_ed25519);
NEW_METHOD_ALIAS(crypto_sign_open, crypto_sign_ed25519_open);
NEW_METHOD_ALIAS(crypto_sign_detached, crypto_sign_ed25519_detached);
NEW_METHOD_ALIAS(crypto_sign_verify_detached, crypto_sign_ed25519_verify_detached);
NEW_METHOD_ALIAS(crypto_sign_keypair, crypto_sign_ed25519_keypair);
NEW_METHOD_ALIAS(crypto_sign_seed_keypair, crypto_sign_ed25519_seed_keypair);
NEW_INT_PROP(crypto_sign_BYTES);
NEW_INT_PROP(crypto_sign_PUBLICKEYBYTES);
NEW_INT_PROP(crypto_sign_SECRETKEYBYTES);
NEW_STRING_PROP(crypto_sign_PRIMITIVE);
}<commit_msg>missing crypto_sign_SEEDBYTES<commit_after>/**
* Node Native Module for Lib Sodium
*
* @Author Pedro Paixao
* @email paixaop at gmail dot com
* @License MIT
*/
#include "node_sodium.h"
#include "crypto_sign_ed25519.h"
/**
* Register function calls in node binding
*/
void register_crypto_sign(Handle<Object> target) {
// Sign
NEW_METHOD_ALIAS(crypto_sign, crypto_sign_ed25519);
NEW_METHOD_ALIAS(crypto_sign_open, crypto_sign_ed25519_open);
NEW_METHOD_ALIAS(crypto_sign_detached, crypto_sign_ed25519_detached);
NEW_METHOD_ALIAS(crypto_sign_verify_detached, crypto_sign_ed25519_verify_detached);
NEW_METHOD_ALIAS(crypto_sign_keypair, crypto_sign_ed25519_keypair);
NEW_METHOD_ALIAS(crypto_sign_seed_keypair, crypto_sign_ed25519_seed_keypair);
NEW_INT_PROP(crypto_sign_SEEDBYTES);
NEW_INT_PROP(crypto_sign_BYTES);
NEW_INT_PROP(crypto_sign_PUBLICKEYBYTES);
NEW_INT_PROP(crypto_sign_SECRETKEYBYTES);
NEW_STRING_PROP(crypto_sign_PRIMITIVE);
}
<|endoftext|> |
<commit_before>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2016 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/exif/exif_IO_EasyExif.hpp"
#include "openMVG/geodesy/geodesy.hpp"
#include "software/SfM/SfMPlyHelper.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include <iostream>
#include <memory>
#include <string>
using namespace openMVG;
using namespace openMVG::exif;
using namespace openMVG::geodesy;
using namespace std;
int main(int argc, char **argv)
{
std::string
sInputDirectory = "",
sOutputPLYFile = "GPS_POSITION.ply";
CmdLine cmd;
cmd.add(make_option('i', sInputDirectory, "input-directory") );
cmd.add(make_option('o', sOutputPLYFile, "output-file") );
try
{
cmd.process(argc, argv);
}
catch(const std::string& s)
{
std::cout
<< "Geodesy demo:\n"
<< " Export as PLY points the parsed image EXIF GPS positions,\n"
<< " -[i|input-directory] Directory that will be parsed.\n"
<< "-- OPTIONAL PARAMETERS --\n"
<< " -[o|output-file] Output PLY file.\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
// Loop: Parse images
// | If valid GPS data information are found, convert them to XYZ & add it to an array
// Export all XYZ parsed data to a PLY file
// Init the EXIF reader
std::unique_ptr<Exif_IO> exifReader(new Exif_IO_EasyExif);
if (!exifReader)
{
std::cerr << "Cannot instantiate the EXIF metadata reader." << std::endl;
return EXIT_FAILURE;
}
std::vector<Vec3> vec_gps_xyz_position;
size_t valid_exif_count = 0;
const std::vector<std::string> vec_image = stlplus::folder_files( sInputDirectory );
for (const std::string & it_string : vec_image)
{
const std::string sImageFilename = stlplus::create_filespec( sInputDirectory, it_string );
// Try to parse EXIF metada
exifReader->open( sImageFilename );
// Check existence of EXIF data
if (!exifReader->doesHaveExifInfo())
continue;
++valid_exif_count;
// Check existence of GPS coordinates
double latitude, longitude, altitude;
if ( exifReader->GPSLatitude( &latitude ) &&
exifReader->GPSLongitude( &longitude ) &&
exifReader->GPSAltitude( &altitude ) )
{
// Add ECEF XYZ position to the GPS position array
vec_gps_xyz_position.push_back( lla_to_ecef( latitude, longitude, altitude ) );
}
}
std::cout << std::endl
<< "Report:\n"
<< " #file listed: " << vec_image.size() << "\n"
<< " #valid exif data: " << valid_exif_count << "\n"
<< " #valid exif gps data: " << vec_gps_xyz_position.size() << std::endl;
if ( vec_gps_xyz_position.empty() )
{
std::cerr << "No valid GPS data found for the image list" << std::endl;
return EXIT_FAILURE;
}
if ( plyHelper::exportToPly( vec_gps_xyz_position, sOutputPLYFile ) )
{
std::cout << sOutputPLYFile << " -> successfully exported on disk." << std::endl;
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
<commit_msg>Display the command line option is the binary is used without arguments.<commit_after>// This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2016 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/exif/exif_IO_EasyExif.hpp"
#include "openMVG/geodesy/geodesy.hpp"
#include "software/SfM/SfMPlyHelper.hpp"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include <iostream>
#include <memory>
#include <string>
using namespace openMVG;
using namespace openMVG::exif;
using namespace openMVG::geodesy;
using namespace std;
int main(int argc, char **argv)
{
std::string
sInputDirectory = "",
sOutputPLYFile = "GPS_POSITION.ply";
CmdLine cmd;
cmd.add(make_option('i', sInputDirectory, "input-directory") );
cmd.add(make_option('o', sOutputPLYFile, "output-file") );
try
{
if (argc == 1) throw std::string("Invalid parameter.");
cmd.process(argc, argv);
}
catch(const std::string& s)
{
std::cout
<< "Geodesy demo:\n"
<< " Export as PLY points the parsed image EXIF GPS positions,\n"
<< " -[i|input-directory] Directory that will be parsed.\n"
<< "-- OPTIONAL PARAMETERS --\n"
<< " -[o|output-file] Output PLY file.\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
// Loop: Parse images
// | If valid GPS data information are found, convert them to XYZ & add it to an array
// Export all XYZ parsed data to a PLY file
// Init the EXIF reader
std::unique_ptr<Exif_IO> exifReader(new Exif_IO_EasyExif);
if (!exifReader)
{
std::cerr << "Cannot instantiate the EXIF metadata reader." << std::endl;
return EXIT_FAILURE;
}
std::vector<Vec3> vec_gps_xyz_position;
size_t valid_exif_count = 0;
const std::vector<std::string> vec_image = stlplus::folder_files( sInputDirectory );
for (const std::string & it_string : vec_image)
{
const std::string sImageFilename = stlplus::create_filespec( sInputDirectory, it_string );
// Try to parse EXIF metada
exifReader->open( sImageFilename );
// Check existence of EXIF data
if (!exifReader->doesHaveExifInfo())
continue;
++valid_exif_count;
// Check existence of GPS coordinates
double latitude, longitude, altitude;
if ( exifReader->GPSLatitude( &latitude ) &&
exifReader->GPSLongitude( &longitude ) &&
exifReader->GPSAltitude( &altitude ) )
{
// Add ECEF XYZ position to the GPS position array
vec_gps_xyz_position.push_back( lla_to_ecef( latitude, longitude, altitude ) );
}
}
std::cout << std::endl
<< "Report:\n"
<< " #file listed: " << vec_image.size() << "\n"
<< " #valid exif data: " << valid_exif_count << "\n"
<< " #valid exif gps data: " << vec_gps_xyz_position.size() << std::endl;
if ( vec_gps_xyz_position.empty() )
{
std::cerr << "No valid GPS data found for the image list" << std::endl;
return EXIT_FAILURE;
}
if ( plyHelper::exportToPly( vec_gps_xyz_position, sOutputPLYFile ) )
{
std::cout << sOutputPLYFile << " -> successfully exported on disk." << std::endl;
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "css_parser.hxx"
#include "css_syntax.hxx"
#include "pool/pool.hxx"
#include "istream/Sink.hxx"
#include "istream/UnusedPtr.hxx"
#include "util/StringUtil.hxx"
#include "util/TrivialArray.hxx"
struct CssParser final : IstreamSink {
template<size_t max>
class StringBuffer : public TrivialArray<char, max> {
public:
using TrivialArray<char, max>::capacity;
using TrivialArray<char, max>::size;
using TrivialArray<char, max>::raw;
using TrivialArray<char, max>::end;
size_t GetRemainingSpace() const {
return capacity() - size();
}
void AppendTruncated(StringView p) {
size_t n = std::min(p.size, GetRemainingSpace());
std::copy_n(p.data, n, end());
this->the_size += n;
}
constexpr operator StringView() const {
return {raw(), size()};
}
gcc_pure
bool Equals(StringView other) const {
return other.Equals(*this);
}
template<size_t n>
bool EqualsLiteral(const char (&value)[n]) const {
return Equals({value, n - 1});
}
};
struct pool *pool;
bool block;
off_t position;
const CssParserHandler *handler;
void *handler_ctx;
/* internal state */
enum class State {
NONE,
BLOCK,
CLASS_NAME,
XML_ID,
DISCARD_QUOTED,
PROPERTY,
POST_PROPERTY,
PRE_VALUE,
VALUE,
PRE_URL,
URL,
/**
* An '@' was found. Feeding characters into "name".
*/
AT,
PRE_IMPORT,
IMPORT,
} state;
char quote;
off_t name_start;
StringBuffer<64> name_buffer;
StringBuffer<64> value_buffer;
off_t url_start;
StringBuffer<1024> url_buffer;
CssParser(struct pool &pool, UnusedIstreamPtr input, bool block,
const CssParserHandler &handler, void *handler_ctx);
void Destroy() {
pool_unref(pool);
}
bool IsDefined() const {
return input.IsDefined();
}
void Read() {
input.Read();
}
void Close() {
input.Close();
}
size_t Feed(const char *start, size_t length);
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override {
assert(input.IsDefined());
const ScopePoolRef ref(*pool TRACE_ARGS);
return Feed((const char *)data, length);
}
void OnEof() noexcept override {
assert(input.IsDefined());
input.Clear();
handler->eof(handler_ctx, position);
Destroy();
}
void OnError(std::exception_ptr ep) noexcept override {
assert(input.IsDefined());
input.Clear();
handler->error(ep, handler_ctx);
Destroy();
}
};
gcc_pure
static bool
at_url_start(const char *p, size_t length)
{
return length >= 4 && memcmp(p + length - 4, "url(", 4) == 0 &&
(/* just url(): */ length == 4 ||
/* url() after another token: */
IsWhitespaceOrNull(p[length - 5]));
}
size_t
CssParser::Feed(const char *start, size_t length)
{
assert(input.IsDefined());
assert(start != nullptr);
assert(length > 0);
const char *buffer = start, *end = start + length, *p;
size_t nbytes;
CssParserValue url;
while (buffer < end) {
switch (state) {
case State::NONE:
do {
switch (*buffer) {
case '{':
/* start of block */
state = State::BLOCK;
if (handler->block != nullptr)
handler->block(handler_ctx);
break;
case '.':
if (handler->class_name != nullptr) {
state = State::CLASS_NAME;
name_start = position + (off_t)(buffer - start) + 1;
name_buffer.clear();
}
break;
case '#':
if (handler->xml_id != nullptr) {
state = State::XML_ID;
name_start = position + (off_t)(buffer - start) + 1;
name_buffer.clear();
}
break;
case '@':
if (handler->import != nullptr) {
state = State::AT;
name_buffer.clear();
}
break;
}
++buffer;
} while (buffer < end && state == State::NONE);
break;
case State::CLASS_NAME:
do {
if (!is_css_nmchar(*buffer)) {
if (!name_buffer.empty()) {
CssParserValue name = {
.start = name_start,
.end = position + (off_t)(buffer - start),
};
name.value = name_buffer;
handler->class_name(&name,handler_ctx);
}
state = State::NONE;
break;
}
if (name_buffer.size() < name_buffer.capacity() - 1)
name_buffer.push_back(*buffer);
++buffer;
} while (buffer < end);
break;
case State::XML_ID:
do {
if (!is_css_nmchar(*buffer)) {
if (!name_buffer.empty()) {
CssParserValue name = {
.start = name_start,
.end = position + (off_t)(buffer - start),
};
name.value = name_buffer;
handler->xml_id(&name, handler_ctx);
}
state = State::NONE;
break;
}
if (name_buffer.size() < name_buffer.capacity() - 1)
name_buffer.push_back(*buffer);
++buffer;
} while (buffer < end);
break;
case State::BLOCK:
do {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
break;
case ':':
/* colon introduces property value */
state = State::PRE_VALUE;
name_buffer.clear();
break;
case '\'':
case '"':
state = State::DISCARD_QUOTED;
quote = *buffer;
break;
default:
if (is_css_ident_start(*buffer) &&
handler->property_keyword != nullptr) {
state = State::PROPERTY;
name_start = position + (off_t)(buffer - start);
name_buffer.clear();
name_buffer.push_back(*buffer);
}
}
++buffer;
} while (buffer < end && state == State::BLOCK);
break;
case State::DISCARD_QUOTED:
p = (const char *)memchr(buffer, quote, end - buffer);
if (p == nullptr) {
nbytes = end - start;
position += (off_t)nbytes;
return nbytes;
}
state = State::BLOCK;
buffer = p + 1;
break;
case State::PROPERTY:
while (buffer < end) {
if (!is_css_ident_char(*buffer)) {
state = State::POST_PROPERTY;
break;
}
if (name_buffer.size() < name_buffer.capacity() - 1)
name_buffer.push_back(*buffer);
++buffer;
}
break;
case State::POST_PROPERTY:
do {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
break;
case ':':
/* colon introduces property value */
state = State::PRE_VALUE;
break;
case '\'':
case '"':
state = State::DISCARD_QUOTED;
quote = *buffer;
break;
}
++buffer;
} while (buffer < end && state == State::BLOCK);
break;
case State::PRE_VALUE:
buffer = StripLeft(buffer, end);
if (buffer < end) {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
++buffer;
break;
case ';':
state = State::BLOCK;
++buffer;
break;
default:
state = State::VALUE;
value_buffer.clear();
}
}
break;
case State::VALUE:
do {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
break;
case ';':
if (!name_buffer.empty()) {
assert(handler->property_keyword != nullptr);
name_buffer.push_back('\0');
handler->property_keyword(name_buffer.raw(),
value_buffer,
name_start,
position + (off_t)(buffer - start) + 1,
handler_ctx);
}
state = State::BLOCK;
break;
case '\'':
case '"':
state = State::DISCARD_QUOTED;
quote = *buffer;
break;
default:
if (value_buffer.size() >= value_buffer.capacity() - 1)
break;
value_buffer.push_back(*buffer);
if (handler->url != nullptr &&
at_url_start(value_buffer.raw(),
value_buffer.size()))
state = State::PRE_URL;
}
++buffer;
} while (buffer < end && state == State::VALUE);
break;
case State::PRE_URL:
buffer = StripLeft(buffer, end);
if (buffer < end) {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
++buffer;
break;
case '\'':
case '"':
state = State::URL;
quote = *buffer++;
url_start = position + (off_t)(buffer - start);
url_buffer.clear();
break;
default:
state = State::BLOCK;
}
}
break;
case State::URL:
p = (const char *)memchr(buffer, quote, end - buffer);
if (p == nullptr) {
nbytes = end - start;
url_buffer.AppendTruncated({buffer, nbytes});
position += (off_t)nbytes;
return nbytes;
}
/* found the end of the URL - copy the rest, and invoke
the handler method "url()" */
nbytes = p - buffer;
url_buffer.AppendTruncated({buffer, nbytes});
buffer = p + 1;
state = State::BLOCK;
url.start = url_start;
url.end = position + (off_t)(p - start);
url.value = url_buffer;
handler->url(&url, handler_ctx);
if (!input.IsDefined())
return 0;
break;
case State::AT:
do {
if (!is_css_nmchar(*buffer)) {
if (name_buffer.EqualsLiteral("import"))
state = State::PRE_IMPORT;
else
state = State::NONE;
break;
}
if (name_buffer.size() < name_buffer.capacity() - 1)
name_buffer.push_back(*buffer);
++buffer;
} while (buffer < end);
break;
case State::PRE_IMPORT:
do {
if (!IsWhitespaceOrNull(*buffer)) {
if (*buffer == '"') {
++buffer;
state = State::IMPORT;
url_start = position + (off_t)(buffer - start);
url_buffer.clear();
} else
state = State::NONE;
break;
}
++buffer;
} while (buffer < end);
break;
case State::IMPORT:
p = (const char *)memchr(buffer, '"', end - buffer);
if (p == nullptr) {
nbytes = end - start;
url_buffer.AppendTruncated({buffer, nbytes});
position += (off_t)nbytes;
return nbytes;
}
/* found the end of the URL - copy the rest, and invoke
the handler method "import()" */
nbytes = p - buffer;
url_buffer.AppendTruncated({buffer, nbytes});
buffer = p + 1;
state = State::NONE;
url.start = url_start;
url.end = position + (off_t)(p - start);
url.value = url_buffer;
handler->import(&url, handler_ctx);
if (!input.IsDefined())
return 0;
break;
}
}
assert(input.IsDefined());
position += length;
return length;
}
/*
* constructor
*
*/
CssParser::CssParser(struct pool &_pool, UnusedIstreamPtr _input, bool _block,
const CssParserHandler &_handler,
void *_handler_ctx)
:IstreamSink(std::move(_input)), pool(&_pool), block(_block),
position(0),
handler(&_handler), handler_ctx(_handler_ctx),
state(block ? State::BLOCK : State::NONE)
{
}
CssParser *
css_parser_new(struct pool &pool, UnusedIstreamPtr input, bool block,
const CssParserHandler &handler, void *handler_ctx)
{
assert(handler.eof != nullptr);
assert(handler.error != nullptr);
pool_ref(&pool);
return NewFromPool<CssParser>(pool, pool, std::move(input), block,
handler, handler_ctx);
}
void
css_parser_close(CssParser *parser)
{
assert(parser != nullptr);
assert(parser->IsDefined());
parser->Close();
parser->Destroy();
}
void
css_parser_read(CssParser *parser)
{
assert(parser != nullptr);
assert(parser->IsDefined());
parser->Read();
}
<commit_msg>css_parser: call destructor<commit_after>/*
* Copyright 2007-2017 Content Management AG
* All rights reserved.
*
* author: Max Kellermann <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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 "css_parser.hxx"
#include "css_syntax.hxx"
#include "pool/pool.hxx"
#include "istream/Sink.hxx"
#include "istream/UnusedPtr.hxx"
#include "util/StringUtil.hxx"
#include "util/TrivialArray.hxx"
struct CssParser final : IstreamSink {
template<size_t max>
class StringBuffer : public TrivialArray<char, max> {
public:
using TrivialArray<char, max>::capacity;
using TrivialArray<char, max>::size;
using TrivialArray<char, max>::raw;
using TrivialArray<char, max>::end;
size_t GetRemainingSpace() const {
return capacity() - size();
}
void AppendTruncated(StringView p) {
size_t n = std::min(p.size, GetRemainingSpace());
std::copy_n(p.data, n, end());
this->the_size += n;
}
constexpr operator StringView() const {
return {raw(), size()};
}
gcc_pure
bool Equals(StringView other) const {
return other.Equals(*this);
}
template<size_t n>
bool EqualsLiteral(const char (&value)[n]) const {
return Equals({value, n - 1});
}
};
struct pool *pool;
bool block;
off_t position;
const CssParserHandler *handler;
void *handler_ctx;
/* internal state */
enum class State {
NONE,
BLOCK,
CLASS_NAME,
XML_ID,
DISCARD_QUOTED,
PROPERTY,
POST_PROPERTY,
PRE_VALUE,
VALUE,
PRE_URL,
URL,
/**
* An '@' was found. Feeding characters into "name".
*/
AT,
PRE_IMPORT,
IMPORT,
} state;
char quote;
off_t name_start;
StringBuffer<64> name_buffer;
StringBuffer<64> value_buffer;
off_t url_start;
StringBuffer<1024> url_buffer;
CssParser(struct pool &pool, UnusedIstreamPtr input, bool block,
const CssParserHandler &handler, void *handler_ctx);
void Destroy() {
pool_unref(pool);
this->~CssParser();
}
bool IsDefined() const {
return input.IsDefined();
}
void Read() {
input.Read();
}
void Close() {
input.Close();
}
size_t Feed(const char *start, size_t length);
/* virtual methods from class IstreamHandler */
size_t OnData(const void *data, size_t length) override {
assert(input.IsDefined());
const ScopePoolRef ref(*pool TRACE_ARGS);
return Feed((const char *)data, length);
}
void OnEof() noexcept override {
assert(input.IsDefined());
input.Clear();
handler->eof(handler_ctx, position);
Destroy();
}
void OnError(std::exception_ptr ep) noexcept override {
assert(input.IsDefined());
input.Clear();
handler->error(ep, handler_ctx);
Destroy();
}
};
gcc_pure
static bool
at_url_start(const char *p, size_t length)
{
return length >= 4 && memcmp(p + length - 4, "url(", 4) == 0 &&
(/* just url(): */ length == 4 ||
/* url() after another token: */
IsWhitespaceOrNull(p[length - 5]));
}
size_t
CssParser::Feed(const char *start, size_t length)
{
assert(input.IsDefined());
assert(start != nullptr);
assert(length > 0);
const char *buffer = start, *end = start + length, *p;
size_t nbytes;
CssParserValue url;
while (buffer < end) {
switch (state) {
case State::NONE:
do {
switch (*buffer) {
case '{':
/* start of block */
state = State::BLOCK;
if (handler->block != nullptr)
handler->block(handler_ctx);
break;
case '.':
if (handler->class_name != nullptr) {
state = State::CLASS_NAME;
name_start = position + (off_t)(buffer - start) + 1;
name_buffer.clear();
}
break;
case '#':
if (handler->xml_id != nullptr) {
state = State::XML_ID;
name_start = position + (off_t)(buffer - start) + 1;
name_buffer.clear();
}
break;
case '@':
if (handler->import != nullptr) {
state = State::AT;
name_buffer.clear();
}
break;
}
++buffer;
} while (buffer < end && state == State::NONE);
break;
case State::CLASS_NAME:
do {
if (!is_css_nmchar(*buffer)) {
if (!name_buffer.empty()) {
CssParserValue name = {
.start = name_start,
.end = position + (off_t)(buffer - start),
};
name.value = name_buffer;
handler->class_name(&name,handler_ctx);
}
state = State::NONE;
break;
}
if (name_buffer.size() < name_buffer.capacity() - 1)
name_buffer.push_back(*buffer);
++buffer;
} while (buffer < end);
break;
case State::XML_ID:
do {
if (!is_css_nmchar(*buffer)) {
if (!name_buffer.empty()) {
CssParserValue name = {
.start = name_start,
.end = position + (off_t)(buffer - start),
};
name.value = name_buffer;
handler->xml_id(&name, handler_ctx);
}
state = State::NONE;
break;
}
if (name_buffer.size() < name_buffer.capacity() - 1)
name_buffer.push_back(*buffer);
++buffer;
} while (buffer < end);
break;
case State::BLOCK:
do {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
break;
case ':':
/* colon introduces property value */
state = State::PRE_VALUE;
name_buffer.clear();
break;
case '\'':
case '"':
state = State::DISCARD_QUOTED;
quote = *buffer;
break;
default:
if (is_css_ident_start(*buffer) &&
handler->property_keyword != nullptr) {
state = State::PROPERTY;
name_start = position + (off_t)(buffer - start);
name_buffer.clear();
name_buffer.push_back(*buffer);
}
}
++buffer;
} while (buffer < end && state == State::BLOCK);
break;
case State::DISCARD_QUOTED:
p = (const char *)memchr(buffer, quote, end - buffer);
if (p == nullptr) {
nbytes = end - start;
position += (off_t)nbytes;
return nbytes;
}
state = State::BLOCK;
buffer = p + 1;
break;
case State::PROPERTY:
while (buffer < end) {
if (!is_css_ident_char(*buffer)) {
state = State::POST_PROPERTY;
break;
}
if (name_buffer.size() < name_buffer.capacity() - 1)
name_buffer.push_back(*buffer);
++buffer;
}
break;
case State::POST_PROPERTY:
do {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
break;
case ':':
/* colon introduces property value */
state = State::PRE_VALUE;
break;
case '\'':
case '"':
state = State::DISCARD_QUOTED;
quote = *buffer;
break;
}
++buffer;
} while (buffer < end && state == State::BLOCK);
break;
case State::PRE_VALUE:
buffer = StripLeft(buffer, end);
if (buffer < end) {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
++buffer;
break;
case ';':
state = State::BLOCK;
++buffer;
break;
default:
state = State::VALUE;
value_buffer.clear();
}
}
break;
case State::VALUE:
do {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
break;
case ';':
if (!name_buffer.empty()) {
assert(handler->property_keyword != nullptr);
name_buffer.push_back('\0');
handler->property_keyword(name_buffer.raw(),
value_buffer,
name_start,
position + (off_t)(buffer - start) + 1,
handler_ctx);
}
state = State::BLOCK;
break;
case '\'':
case '"':
state = State::DISCARD_QUOTED;
quote = *buffer;
break;
default:
if (value_buffer.size() >= value_buffer.capacity() - 1)
break;
value_buffer.push_back(*buffer);
if (handler->url != nullptr &&
at_url_start(value_buffer.raw(),
value_buffer.size()))
state = State::PRE_URL;
}
++buffer;
} while (buffer < end && state == State::VALUE);
break;
case State::PRE_URL:
buffer = StripLeft(buffer, end);
if (buffer < end) {
switch (*buffer) {
case '}':
/* end of block */
if (block)
break;
state = State::NONE;
++buffer;
break;
case '\'':
case '"':
state = State::URL;
quote = *buffer++;
url_start = position + (off_t)(buffer - start);
url_buffer.clear();
break;
default:
state = State::BLOCK;
}
}
break;
case State::URL:
p = (const char *)memchr(buffer, quote, end - buffer);
if (p == nullptr) {
nbytes = end - start;
url_buffer.AppendTruncated({buffer, nbytes});
position += (off_t)nbytes;
return nbytes;
}
/* found the end of the URL - copy the rest, and invoke
the handler method "url()" */
nbytes = p - buffer;
url_buffer.AppendTruncated({buffer, nbytes});
buffer = p + 1;
state = State::BLOCK;
url.start = url_start;
url.end = position + (off_t)(p - start);
url.value = url_buffer;
handler->url(&url, handler_ctx);
if (!input.IsDefined())
return 0;
break;
case State::AT:
do {
if (!is_css_nmchar(*buffer)) {
if (name_buffer.EqualsLiteral("import"))
state = State::PRE_IMPORT;
else
state = State::NONE;
break;
}
if (name_buffer.size() < name_buffer.capacity() - 1)
name_buffer.push_back(*buffer);
++buffer;
} while (buffer < end);
break;
case State::PRE_IMPORT:
do {
if (!IsWhitespaceOrNull(*buffer)) {
if (*buffer == '"') {
++buffer;
state = State::IMPORT;
url_start = position + (off_t)(buffer - start);
url_buffer.clear();
} else
state = State::NONE;
break;
}
++buffer;
} while (buffer < end);
break;
case State::IMPORT:
p = (const char *)memchr(buffer, '"', end - buffer);
if (p == nullptr) {
nbytes = end - start;
url_buffer.AppendTruncated({buffer, nbytes});
position += (off_t)nbytes;
return nbytes;
}
/* found the end of the URL - copy the rest, and invoke
the handler method "import()" */
nbytes = p - buffer;
url_buffer.AppendTruncated({buffer, nbytes});
buffer = p + 1;
state = State::NONE;
url.start = url_start;
url.end = position + (off_t)(p - start);
url.value = url_buffer;
handler->import(&url, handler_ctx);
if (!input.IsDefined())
return 0;
break;
}
}
assert(input.IsDefined());
position += length;
return length;
}
/*
* constructor
*
*/
CssParser::CssParser(struct pool &_pool, UnusedIstreamPtr _input, bool _block,
const CssParserHandler &_handler,
void *_handler_ctx)
:IstreamSink(std::move(_input)), pool(&_pool), block(_block),
position(0),
handler(&_handler), handler_ctx(_handler_ctx),
state(block ? State::BLOCK : State::NONE)
{
}
CssParser *
css_parser_new(struct pool &pool, UnusedIstreamPtr input, bool block,
const CssParserHandler &handler, void *handler_ctx)
{
assert(handler.eof != nullptr);
assert(handler.error != nullptr);
pool_ref(&pool);
return NewFromPool<CssParser>(pool, pool, std::move(input), block,
handler, handler_ctx);
}
void
css_parser_close(CssParser *parser)
{
assert(parser != nullptr);
assert(parser->IsDefined());
parser->Close();
parser->Destroy();
}
void
css_parser_read(CssParser *parser)
{
assert(parser != nullptr);
assert(parser->IsDefined());
parser->Read();
}
<|endoftext|> |
<commit_before>//=============================================================================================================
/**
* @file eegosportsdriver.cpp
* @author Christoph Dinh <[email protected]>;
* Lorenz Esch <[email protected]>;
* Viktor Klueber <[email protected]>;
* Johannes Vorwerk <[email protected]>
* @version dev
* @date February, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Christoph Dinh, Lorenz Esch, Viktor Klueber, Johannes Vorwerk. 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 Contains the implementation of the EEGoSportsDriver class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "eegosportsdriver.h"
#include "eegosportsproducer.h"
#include "eemagine/sdk/wrapper.cc" // Wrapper code to be compiled.
#include "eemagine/sdk/factory.h" // SDK header
#ifndef _WIN32
#include <unistd.h>
#endif
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDebug>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace EEGOSPORTSPLUGIN;
using namespace eemagine::sdk;
using namespace Eigen;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
EEGoSportsDriver::EEGoSportsDriver(EEGoSportsProducer* pEEGoSportsProducer)
: m_pEEGoSportsProducer(pEEGoSportsProducer)
, m_bDllLoaded(true)
, m_bInitDeviceSuccess(false)
, m_bStartRecordingSuccess(false)
, m_uiNumberOfChannels(90)
, m_uiNumberOfEEGChannels(64)
, m_uiSamplingFrequency(512)
, m_uiSamplesPerBlock(100)
, m_bWriteDriverDebugToFile(false)
, m_sOutputFilePath("/resources/mne_scan/plugins/eegosports")
, m_bMeasureImpedances(false)
{
m_bDllLoaded = true;
}
//*************************************************************************************************************
EEGoSportsDriver::~EEGoSportsDriver()
{
}
//*************************************************************************************************************
bool EEGoSportsDriver::initDevice(bool bWriteDriverDebugToFile,
const QString& sOutpuFilePath, bool bMeasureImpedance)
{
m_bMeasureImpedances = bMeasureImpedance;
//Check if the driver DLL was loaded
if(!m_bDllLoaded) {
return false;
}
//Set global variables
m_bWriteDriverDebugToFile = bWriteDriverDebugToFile;
m_sOutputFilePath = sOutpuFilePath;
//Open debug file to write to
if(m_bWriteDriverDebugToFile) {
m_outputFileStream.open("./EEGoSports_Driver_Debug.txt", std::ios::trunc); //ios::trunc deletes old file data
}
try {
// Get device handler
#ifdef _WIN32
factory factoryObj ("eego-SDK.dll"); // Make sure that eego-SDK.dll resides in the working directory
#else
factory factoryObj ("/home/vorwerkj/git/mne-cpp/lib/libeego-SDK.so"); // Make sure that eego-SDK.dll resides in the working directory
#endif
m_pAmplifier = factoryObj.getAmplifier(); // Get an amplifier
//std::cout<<"[EEGoSportsDriver::initDevice] Serial number of connected eegosports device: "<<m_pAmplifier->getSerialNumber()<<std::endl;
QThread::msleep(100);
} catch (std::runtime_error& e) {
qWarning() <<"[EEGoSportsDriver::initDevice] error " << e.what();
return false;
}
std::vector<channel> channellist = m_pAmplifier->getChannelList();
int iEEGChannelCount = 0;
int iBipolarChannelCount = 0;
for(std::vector<channel>::iterator it = channellist.begin(); it != channellist.end(); ++it){
if(it->getType() == 1)
++iEEGChannelCount;
else if(it->getType() == 2)
++iBipolarChannelCount;
}
if(!bMeasureImpedance)
m_uiNumberOfChannels = channellist.size() + 3; //trigger, sample count, and ref not considered here
else
m_uiNumberOfChannels = iEEGChannelCount + 2; //ref and gnd not considered here
m_uiNumberOfEEGChannels = iEEGChannelCount;
m_uiNumberOfBipolarChannels = iBipolarChannelCount;
qDebug() << "[EEGoSportsDriver::initDevice] iChannelcount " << m_uiNumberOfChannels;
qDebug() << "[EEGoSportsDriver::initDevice] iEEGChannelcount " << iEEGChannelCount;
qDebug() << "[EEGoSportsDriver::initDevice] iBipolarChannelCount " << iBipolarChannelCount;
qInfo() << "[EEGoSportsDriver::initDevice] Successfully initialised the device.";
// Set flag for successfull initialisation true
m_bInitDeviceSuccess = true;
return true;
}
//*************************************************************************************************************
bool EEGoSportsDriver::startRecording(int iSamplesPerBlock,
int iSamplingFrequency,
bool bMeasureImpedance)
{
//Set global variables
m_uiSamplesPerBlock = iSamplesPerBlock;
m_uiSamplingFrequency = iSamplingFrequency;
m_bMeasureImpedances = bMeasureImpedance;
try {
//Start the stream
if(bMeasureImpedance) {
m_pDataStream = m_pAmplifier->OpenImpedanceStream();
} else {
//reference_range the range, in volt, for the referential channels. Valid values are: 1, 0.75, 0.15
//bipolar_range the range, in volt, for the bipolar channels. Valid values are: 4, 1.5, 0.7, 0.35
double reference_range = 0.75;
double bipolar_range = 4;
m_pDataStream = m_pAmplifier->OpenEegStream(m_uiSamplingFrequency, reference_range, bipolar_range);
}
QThread::msleep(100);
} catch (std::runtime_error& e) {
qWarning() <<"[EEGoSportsDriver::startRecording]" << e.what();
return false;
}
qInfo() << "[EEGoSportsDriver::startRecording] Successfully started recording";
// Set flag for successfull initialisation true
m_bStartRecordingSuccess = true;
return true;
}
//*************************************************************************************************************
bool EEGoSportsDriver::uninitDevice()
{
//Check if the device was initialised
if(!m_bStartRecordingSuccess) {
qWarning() << "[EEGoSportsDriver::uninitDevice] Recording was not started - therefore can not be stopped";
return false;
}
//Check if the device was initialised
if(!m_bInitDeviceSuccess) {
qWarning() << "[EEGoSportsDriver::uninitDevice] Device was not initialised - therefore can not be uninitialised";
return false;
}
//Check if the driver DLL was loaded
if(!m_bDllLoaded) {
qWarning() << "[EEGoSportsDriver::uninitDevice] Driver DLL was not loaded";
return false;
}
//Close the output stream/file
if(m_outputFileStream.is_open() && m_bWriteDriverDebugToFile) {
m_outputFileStream.close();
m_outputFileStream.clear();
}
delete m_pDataStream;
delete m_pAmplifier;
qInfo() << "[EEGoSportsDriver::uninitDevice] Successfully uninitialised the device";
m_bStartRecordingSuccess = false;
m_bInitDeviceSuccess = false;
return true;
}
//*************************************************************************************************************
bool EEGoSportsDriver::getSampleMatrixValue(Eigen::MatrixXd &sampleMatrix)
{
//Check if device was initialised and connected correctly
if(!m_bInitDeviceSuccess) {
qWarning() << "[EEGoSportsDriver::getSampleMatrixValue] Cannot start to get samples from device because device was not initialised correctly";
return false;
}
if(!m_bStartRecordingSuccess) {
qWarning() << "[EEGoSportsDriver::getSampleMatrixValue] Cannot start to get samples from device because recording was not started";
return false;
}
sampleMatrix = MatrixXd::Zero(m_uiNumberOfChannels, m_uiSamplesPerBlock);
uint iSampleIterator, iReceivedSamples, iChannelCount, i, j;
iSampleIterator = 0;
buffer buf;
VectorXd vec;
//get samples from device until the complete matrix is filled, i.e. the samples per block size is met
while(iSampleIterator < m_uiSamplesPerBlock) {
//Get sample block from device
buf = m_pDataStream->getData();
iReceivedSamples = buf.getSampleCount();
iChannelCount = buf.getChannelCount();
//Write the received samples to an extra buffer, so that they are not getting lost if too many samples were received. These are then written to the next matrix (block)
for(i = 0; i < iReceivedSamples; ++i) {
vec.resize(iChannelCount);
for(j = 0; j < iChannelCount; ++j) {
vec(j) = buf.getSample(j,i);
//std::cout<<vec(j)<<std::endl;
}
m_lSampleBlockBuffer.push_back(vec);
}
//Fill matrix with data from buffer
while(!m_lSampleBlockBuffer.isEmpty()) {
if(iSampleIterator >= m_uiSamplesPerBlock) {
break;
}
sampleMatrix.col(iSampleIterator).head(iChannelCount) = m_lSampleBlockBuffer.takeFirst();
iSampleIterator++;
}
if(m_outputFileStream.is_open() && m_bWriteDriverDebugToFile) {
m_outputFileStream << "buf.getSampleCount(): " << buf.getSampleCount() << std::endl;
m_outputFileStream << "buf.getChannelCount(): " << buf.getChannelCount() << std::endl;
m_outputFileStream << "buf.size(): " << buf.size() << std::endl;
m_outputFileStream << "iSampleIterator: " << iSampleIterator << std::endl;
m_outputFileStream << "m_lSampleBlockBuffer.size(): " << m_lSampleBlockBuffer.size() << std::endl << std::endl;
std::vector<channel> channellist = m_pDataStream->getChannelList();
if(iSampleIterator == 1)
for(std::vector<channel>::iterator it = channellist.begin(); it != channellist.end(); ++it){
m_outputFileStream << "Channeltype " << it->getType() << std::endl;
m_outputFileStream << "Channelindex " << it->getIndex() << std::endl;
}
}
}
return true;
}
//*************************************************************************************************************
uint EEGoSportsDriver::getNumberOfChannels()
{
return m_uiNumberOfChannels;
}
//*************************************************************************************************************
uint EEGoSportsDriver::getNumberOfEEGChannels()
{
return m_uiNumberOfEEGChannels;
}
//*************************************************************************************************************
uint EEGoSportsDriver::getNumberOfBipolarChannels()
{
return m_uiNumberOfBipolarChannels;
}
//*************************************************************************************************************
QList<uint> EEGoSportsDriver::getChannellist()
{
std::vector<channel> channellist = m_pAmplifier->getChannelList();
QList<uint> uichannellist;
for(std::vector<channel>::iterator it = channellist.begin(); it != channellist.end(); ++it)
uichannellist.append(it->getType());
return uichannellist;
}
<commit_msg>eegosports: fixed library path<commit_after>//=============================================================================================================
/**
* @file eegosportsdriver.cpp
* @author Christoph Dinh <[email protected]>;
* Lorenz Esch <[email protected]>;
* Viktor Klueber <[email protected]>;
* Johannes Vorwerk <[email protected]>
* @version dev
* @date February, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Christoph Dinh, Lorenz Esch, Viktor Klueber, Johannes Vorwerk. 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 Contains the implementation of the EEGoSportsDriver class.
*
*/
//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "eegosportsdriver.h"
#include "eegosportsproducer.h"
#include "eemagine/sdk/wrapper.cc" // Wrapper code to be compiled.
#include "eemagine/sdk/factory.h" // SDK header
#ifndef _WIN32
#include <unistd.h>
#endif
//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QDebug>
//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace EEGOSPORTSPLUGIN;
using namespace eemagine::sdk;
using namespace Eigen;
//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
EEGoSportsDriver::EEGoSportsDriver(EEGoSportsProducer* pEEGoSportsProducer)
: m_pEEGoSportsProducer(pEEGoSportsProducer)
, m_bDllLoaded(true)
, m_bInitDeviceSuccess(false)
, m_bStartRecordingSuccess(false)
, m_uiNumberOfChannels(90)
, m_uiNumberOfEEGChannels(64)
, m_uiSamplingFrequency(512)
, m_uiSamplesPerBlock(100)
, m_bWriteDriverDebugToFile(false)
, m_sOutputFilePath("/resources/mne_scan/plugins/eegosports")
, m_bMeasureImpedances(false)
{
m_bDllLoaded = true;
}
//*************************************************************************************************************
EEGoSportsDriver::~EEGoSportsDriver()
{
}
//*************************************************************************************************************
bool EEGoSportsDriver::initDevice(bool bWriteDriverDebugToFile,
const QString& sOutpuFilePath, bool bMeasureImpedance)
{
m_bMeasureImpedances = bMeasureImpedance;
//Check if the driver DLL was loaded
if(!m_bDllLoaded) {
return false;
}
//Set global variables
m_bWriteDriverDebugToFile = bWriteDriverDebugToFile;
m_sOutputFilePath = sOutpuFilePath;
//Open debug file to write to
if(m_bWriteDriverDebugToFile) {
m_outputFileStream.open("./EEGoSports_Driver_Debug.txt", std::ios::trunc); //ios::trunc deletes old file data
}
try {
// Get device handler
#ifdef _WIN32
factory factoryObj ("eego-SDK.dll"); // Make sure that eego-SDK.dll resides in the working directory
#else
factory factoryObj ("libeego-SDK.so"); // Make sure that eego-SDK.dll resides in the working directory
#endif
m_pAmplifier = factoryObj.getAmplifier(); // Get an amplifier
//std::cout<<"[EEGoSportsDriver::initDevice] Serial number of connected eegosports device: "<<m_pAmplifier->getSerialNumber()<<std::endl;
QThread::msleep(100);
} catch (std::runtime_error& e) {
qWarning() <<"[EEGoSportsDriver::initDevice] error " << e.what();
return false;
}
std::vector<channel> channellist = m_pAmplifier->getChannelList();
int iEEGChannelCount = 0;
int iBipolarChannelCount = 0;
for(std::vector<channel>::iterator it = channellist.begin(); it != channellist.end(); ++it){
if(it->getType() == 1)
++iEEGChannelCount;
else if(it->getType() == 2)
++iBipolarChannelCount;
}
if(!bMeasureImpedance)
m_uiNumberOfChannels = channellist.size() + 3; //trigger, sample count, and ref not considered here
else
m_uiNumberOfChannels = iEEGChannelCount + 2; //ref and gnd not considered here
m_uiNumberOfEEGChannels = iEEGChannelCount;
m_uiNumberOfBipolarChannels = iBipolarChannelCount;
qDebug() << "[EEGoSportsDriver::initDevice] iChannelcount " << m_uiNumberOfChannels;
qDebug() << "[EEGoSportsDriver::initDevice] iEEGChannelcount " << iEEGChannelCount;
qDebug() << "[EEGoSportsDriver::initDevice] iBipolarChannelCount " << iBipolarChannelCount;
qInfo() << "[EEGoSportsDriver::initDevice] Successfully initialised the device.";
// Set flag for successfull initialisation true
m_bInitDeviceSuccess = true;
return true;
}
//*************************************************************************************************************
bool EEGoSportsDriver::startRecording(int iSamplesPerBlock,
int iSamplingFrequency,
bool bMeasureImpedance)
{
//Set global variables
m_uiSamplesPerBlock = iSamplesPerBlock;
m_uiSamplingFrequency = iSamplingFrequency;
m_bMeasureImpedances = bMeasureImpedance;
try {
//Start the stream
if(bMeasureImpedance) {
m_pDataStream = m_pAmplifier->OpenImpedanceStream();
} else {
//reference_range the range, in volt, for the referential channels. Valid values are: 1, 0.75, 0.15
//bipolar_range the range, in volt, for the bipolar channels. Valid values are: 4, 1.5, 0.7, 0.35
double reference_range = 0.75;
double bipolar_range = 4;
m_pDataStream = m_pAmplifier->OpenEegStream(m_uiSamplingFrequency, reference_range, bipolar_range);
}
QThread::msleep(100);
} catch (std::runtime_error& e) {
qWarning() <<"[EEGoSportsDriver::startRecording]" << e.what();
return false;
}
qInfo() << "[EEGoSportsDriver::startRecording] Successfully started recording";
// Set flag for successfull initialisation true
m_bStartRecordingSuccess = true;
return true;
}
//*************************************************************************************************************
bool EEGoSportsDriver::uninitDevice()
{
//Check if the device was initialised
if(!m_bStartRecordingSuccess) {
qWarning() << "[EEGoSportsDriver::uninitDevice] Recording was not started - therefore can not be stopped";
return false;
}
//Check if the device was initialised
if(!m_bInitDeviceSuccess) {
qWarning() << "[EEGoSportsDriver::uninitDevice] Device was not initialised - therefore can not be uninitialised";
return false;
}
//Check if the driver DLL was loaded
if(!m_bDllLoaded) {
qWarning() << "[EEGoSportsDriver::uninitDevice] Driver DLL was not loaded";
return false;
}
//Close the output stream/file
if(m_outputFileStream.is_open() && m_bWriteDriverDebugToFile) {
m_outputFileStream.close();
m_outputFileStream.clear();
}
delete m_pDataStream;
delete m_pAmplifier;
qInfo() << "[EEGoSportsDriver::uninitDevice] Successfully uninitialised the device";
m_bStartRecordingSuccess = false;
m_bInitDeviceSuccess = false;
return true;
}
//*************************************************************************************************************
bool EEGoSportsDriver::getSampleMatrixValue(Eigen::MatrixXd &sampleMatrix)
{
//Check if device was initialised and connected correctly
if(!m_bInitDeviceSuccess) {
qWarning() << "[EEGoSportsDriver::getSampleMatrixValue] Cannot start to get samples from device because device was not initialised correctly";
return false;
}
if(!m_bStartRecordingSuccess) {
qWarning() << "[EEGoSportsDriver::getSampleMatrixValue] Cannot start to get samples from device because recording was not started";
return false;
}
sampleMatrix = MatrixXd::Zero(m_uiNumberOfChannels, m_uiSamplesPerBlock);
uint iSampleIterator, iReceivedSamples, iChannelCount, i, j;
iSampleIterator = 0;
buffer buf;
VectorXd vec;
//get samples from device until the complete matrix is filled, i.e. the samples per block size is met
while(iSampleIterator < m_uiSamplesPerBlock) {
//Get sample block from device
buf = m_pDataStream->getData();
iReceivedSamples = buf.getSampleCount();
iChannelCount = buf.getChannelCount();
//Write the received samples to an extra buffer, so that they are not getting lost if too many samples were received. These are then written to the next matrix (block)
for(i = 0; i < iReceivedSamples; ++i) {
vec.resize(iChannelCount);
for(j = 0; j < iChannelCount; ++j) {
vec(j) = buf.getSample(j,i);
//std::cout<<vec(j)<<std::endl;
}
m_lSampleBlockBuffer.push_back(vec);
}
//Fill matrix with data from buffer
while(!m_lSampleBlockBuffer.isEmpty()) {
if(iSampleIterator >= m_uiSamplesPerBlock) {
break;
}
sampleMatrix.col(iSampleIterator).head(iChannelCount) = m_lSampleBlockBuffer.takeFirst();
iSampleIterator++;
}
if(m_outputFileStream.is_open() && m_bWriteDriverDebugToFile) {
m_outputFileStream << "buf.getSampleCount(): " << buf.getSampleCount() << std::endl;
m_outputFileStream << "buf.getChannelCount(): " << buf.getChannelCount() << std::endl;
m_outputFileStream << "buf.size(): " << buf.size() << std::endl;
m_outputFileStream << "iSampleIterator: " << iSampleIterator << std::endl;
m_outputFileStream << "m_lSampleBlockBuffer.size(): " << m_lSampleBlockBuffer.size() << std::endl << std::endl;
std::vector<channel> channellist = m_pDataStream->getChannelList();
if(iSampleIterator == 1)
for(std::vector<channel>::iterator it = channellist.begin(); it != channellist.end(); ++it){
m_outputFileStream << "Channeltype " << it->getType() << std::endl;
m_outputFileStream << "Channelindex " << it->getIndex() << std::endl;
}
}
}
return true;
}
//*************************************************************************************************************
uint EEGoSportsDriver::getNumberOfChannels()
{
return m_uiNumberOfChannels;
}
//*************************************************************************************************************
uint EEGoSportsDriver::getNumberOfEEGChannels()
{
return m_uiNumberOfEEGChannels;
}
//*************************************************************************************************************
uint EEGoSportsDriver::getNumberOfBipolarChannels()
{
return m_uiNumberOfBipolarChannels;
}
//*************************************************************************************************************
QList<uint> EEGoSportsDriver::getChannellist()
{
std::vector<channel> channellist = m_pAmplifier->getChannelList();
QList<uint> uichannellist;
for(std::vector<channel>::iterator it = channellist.begin(); it != channellist.end(); ++it)
uichannellist.append(it->getType());
return uichannellist;
}
<|endoftext|> |
<commit_before><<<<<<< HEAD
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $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 "s60mediaplayercontrol.h"
#include "s60mediaplayersession.h"
#include <QtCore/qdir.h>
#include <QtCore/qurl.h>
#include <QtCore/qdebug.h>
S60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent)
: QMediaPlayerControl(parent),
m_mediaPlayerResolver(mediaPlayerResolver),
m_session(NULL),
m_stream(NULL)
{
}
S60MediaPlayerControl::~S60MediaPlayerControl()
{
}
qint64 S60MediaPlayerControl::position() const
{
if (m_session)
return m_session->position();
return 0;
}
qint64 S60MediaPlayerControl::duration() const
{
if (m_session)
return m_session->duration();
return -1;
}
QMediaPlayer::State S60MediaPlayerControl::state() const
{
if (m_session)
return m_session->state();
return QMediaPlayer::StoppedState;
}
QMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const
{
if (m_session)
return m_session->mediaStatus();
return QMediaPlayer::NoMedia;
}
int S60MediaPlayerControl::bufferStatus() const
{
return -1;
}
int S60MediaPlayerControl::volume() const
{
if (m_session)
return m_session->volume();
return m_mediaSettings.volume();
}
bool S60MediaPlayerControl::isMuted() const
{
if (m_session)
return m_session->isMuted();
return m_mediaSettings.isMuted();
}
bool S60MediaPlayerControl::isSeekable() const
{
if (m_session)
return m_session->isSeekable();
return false;
}
QMediaTimeRange S60MediaPlayerControl::availablePlaybackRanges() const
{
QMediaTimeRange ranges;
if(m_session && q_check_ptr(m_session)->isSeekable())
ranges.addInterval(0, m_session->duration());
return ranges;
}
qreal S60MediaPlayerControl::playbackRate() const
{
if (m_session)
return m_session->playbackRate();
return m_mediaSettings.playbackRate();
}
void S60MediaPlayerControl::setPlaybackRate(qreal rate)
{
if (m_session)
m_session->setPlaybackRate(rate);
m_mediaSettings.setPlaybackRate(rate);
}
void S60MediaPlayerControl::setPosition(qint64 pos)
{
if (m_session)
m_session->setPosition(pos);
}
void S60MediaPlayerControl::play()
{
if (m_session)
m_session->play();
}
void S60MediaPlayerControl::pause()
{
if (m_session)
m_session->pause();
}
void S60MediaPlayerControl::stop()
{
if (m_session)
m_session->stop();
}
void S60MediaPlayerControl::setVolume(int volume)
{
if (m_mediaSettings.volume() != volume && volume >= 0 && volume <= 100) {
m_mediaSettings.setVolume(volume);
if (m_session)
m_session->setVolume(volume);
emit volumeChanged(volume);
}
}
void S60MediaPlayerControl::setMuted(bool muted)
{
if (m_session)
m_session->setMuted(muted);
else if (m_mediaSettings.isMuted() != muted)
emit mutedChanged(muted);
m_mediaSettings.setMuted(muted);
}
QMediaContent S60MediaPlayerControl::media() const
{
return m_currentResource;
}
const QIODevice *S60MediaPlayerControl::mediaStream() const
{
return m_stream;
}
void S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream)
{
Q_UNUSED(stream)
// we don't want to set & load media again when it is already loaded
if (m_session && (m_currentResource == source) && m_session->state() == QMediaPlayer::LoadedMedia) {
return;
}
// store to variable as session is created based on the content type.
m_currentResource = source;
if (m_session) {
m_session->stop();
}
m_session = currentPlayerSession();
QUrl url;
if (m_session && !source.isNull()) {
url = source.canonicalUrl();
if (m_session->isUrl() == false) {
m_session->load(url);
} else {
m_session->loadUrl(url);
}
emit mediaChanged(m_currentResource);
}
else {
emit mediaStatusChanged(QMediaPlayer::InvalidMedia);
}
}
void S60MediaPlayerControl::setVideoOutput(QObject *output)
{
if (!m_session)
m_session = m_mediaPlayerResolver.VideoPlayerSession();
m_session->setVideoRenderer(output);
}
bool S60MediaPlayerControl::isVideoAvailable() const
{
if (m_session)
return m_session->isVideoAvailable();
return false;
}
S60MediaPlayerSession* S60MediaPlayerControl::currentPlayerSession()
{
return m_mediaPlayerResolver.PlayerSession();
}
const S60MediaSettings& S60MediaPlayerControl::mediaControlSettings() const
{
return m_mediaSettings;
}
<commit_msg>Fixed merge issue in s60mediaplayercontrol.cpp.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $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 "s60mediaplayercontrol.h"
#include "s60mediaplayersession.h"
#include <QtCore/qdir.h>
#include <QtCore/qurl.h>
#include <QtCore/qdebug.h>
S60MediaPlayerControl::S60MediaPlayerControl(MS60MediaPlayerResolver& mediaPlayerResolver, QObject *parent)
: QMediaPlayerControl(parent),
m_mediaPlayerResolver(mediaPlayerResolver),
m_session(NULL),
m_stream(NULL)
{
}
S60MediaPlayerControl::~S60MediaPlayerControl()
{
}
qint64 S60MediaPlayerControl::position() const
{
if (m_session)
return m_session->position();
return 0;
}
qint64 S60MediaPlayerControl::duration() const
{
if (m_session)
return m_session->duration();
return -1;
}
QMediaPlayer::State S60MediaPlayerControl::state() const
{
if (m_session)
return m_session->state();
return QMediaPlayer::StoppedState;
}
QMediaPlayer::MediaStatus S60MediaPlayerControl::mediaStatus() const
{
if (m_session)
return m_session->mediaStatus();
return QMediaPlayer::NoMedia;
}
int S60MediaPlayerControl::bufferStatus() const
{
return -1;
}
int S60MediaPlayerControl::volume() const
{
if (m_session)
return m_session->volume();
return m_mediaSettings.volume();
}
bool S60MediaPlayerControl::isMuted() const
{
if (m_session)
return m_session->isMuted();
return m_mediaSettings.isMuted();
}
bool S60MediaPlayerControl::isSeekable() const
{
if (m_session)
return m_session->isSeekable();
return false;
}
QMediaTimeRange S60MediaPlayerControl::availablePlaybackRanges() const
{
QMediaTimeRange ranges;
if(m_session && q_check_ptr(m_session)->isSeekable())
ranges.addInterval(0, m_session->duration());
return ranges;
}
qreal S60MediaPlayerControl::playbackRate() const
{
if (m_session)
return m_session->playbackRate();
return m_mediaSettings.playbackRate();
}
void S60MediaPlayerControl::setPlaybackRate(qreal rate)
{
if (m_session)
m_session->setPlaybackRate(rate);
m_mediaSettings.setPlaybackRate(rate);
}
void S60MediaPlayerControl::setPosition(qint64 pos)
{
if (m_session)
m_session->setPosition(pos);
}
void S60MediaPlayerControl::play()
{
if (m_session)
m_session->play();
}
void S60MediaPlayerControl::pause()
{
if (m_session)
m_session->pause();
}
void S60MediaPlayerControl::stop()
{
if (m_session)
m_session->stop();
}
void S60MediaPlayerControl::setVolume(int volume)
{
if (m_mediaSettings.volume() != volume && volume >= 0 && volume <= 100) {
m_mediaSettings.setVolume(volume);
if (m_session)
m_session->setVolume(volume);
emit volumeChanged(volume);
}
}
void S60MediaPlayerControl::setMuted(bool muted)
{
if (m_session)
m_session->setMuted(muted);
else if (m_mediaSettings.isMuted() != muted)
emit mutedChanged(muted);
m_mediaSettings.setMuted(muted);
}
QMediaContent S60MediaPlayerControl::media() const
{
return m_currentResource;
}
const QIODevice *S60MediaPlayerControl::mediaStream() const
{
return m_stream;
}
void S60MediaPlayerControl::setMedia(const QMediaContent &source, QIODevice *stream)
{
Q_UNUSED(stream)
// we don't want to set & load media again when it is already loaded
if (m_session && (m_currentResource == source) && m_session->state() == QMediaPlayer::LoadedMedia) {
return;
}
// store to variable as session is created based on the content type.
m_currentResource = source;
if (m_session) {
m_session->stop();
}
m_session = currentPlayerSession();
QUrl url;
if (m_session && !source.isNull()) {
url = source.canonicalUrl();
if (m_session->isUrl() == false) {
m_session->load(url);
} else {
m_session->loadUrl(url);
}
emit mediaChanged(m_currentResource);
}
else {
emit mediaStatusChanged(QMediaPlayer::InvalidMedia);
}
}
void S60MediaPlayerControl::setVideoOutput(QObject *output)
{
if (!m_session)
m_session = m_mediaPlayerResolver.VideoPlayerSession();
m_session->setVideoRenderer(output);
}
bool S60MediaPlayerControl::isVideoAvailable() const
{
if (m_session)
return m_session->isVideoAvailable();
return false;
}
S60MediaPlayerSession* S60MediaPlayerControl::currentPlayerSession()
{
return m_mediaPlayerResolver.PlayerSession();
}
const S60MediaSettings& S60MediaPlayerControl::mediaControlSettings() const
{
return m_mediaSettings;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $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 "s60videoplayersession.h"
#include "s60videowidget.h"
#include "s60mediaplayerservice.h"
#include "s60videooverlay.h"
#include <QtCore/qdebug.h>
#include <QtCore/private/qcore_symbian_p.h>
#include <QtGui/qwidget.h>
#include <QApplication>
#include <coecntrl.h>
#include <coemain.h> // For CCoeEnv
#include <w32std.h>
#include <mmf/common/mmfcontrollerframeworkbase.h>
S60VideoPlayerSession::S60VideoPlayerSession(QMediaService *service)
: S60MediaPlayerSession(service)
, m_player(0)
, m_clipRect(0, 0, 0, 0)
, m_windowRect(0, 0, 0, 0)
, m_output(QVideoOutputControl::NoOutput)
, m_windowId(0)
, m_wsSession(0)
, m_screenDevice(0)
, m_window(0)
, m_service(*service)
{
resetNativeHandles();
QT_TRAP_THROWING(m_player = CVideoPlayerUtility::NewL(
*this,
0,
EMdaPriorityPreferenceNone,
*m_wsSession,
*m_screenDevice,
*m_window,
m_windowRect,
m_clipRect));
}
S60VideoPlayerSession::~S60VideoPlayerSession()
{
m_player->Close();
delete m_player;
}
void S60VideoPlayerSession::doLoadL(const TDesC &path)
{
m_player->OpenFileL(path);
}
void S60VideoPlayerSession::doLoadUrlL(const TDesC &path)
{
m_player->OpenUrlL(path);
}
int S60VideoPlayerSession::doGetMediaLoadingProgressL() const
{
int progress = 0;
m_player->GetVideoLoadingProgressL(progress);
return progress;
}
int S60VideoPlayerSession::doGetDurationL() const
{
return m_player->DurationL().Int64() / 1000;
}
void S60VideoPlayerSession::setVideoRenderer(QObject *videoOutput)
{
Q_UNUSED(videoOutput)
QVideoOutputControl *videoControl = qobject_cast<QVideoOutputControl *>(m_service.control(QVideoOutputControl_iid));
//Render changes
if (m_output != videoControl->output()) {
if (m_output == QVideoOutputControl::WidgetOutput) {
S60VideoWidgetControl *widgetControl = qobject_cast<S60VideoWidgetControl *>(m_service.control(QVideoWidgetControl_iid));
disconnect(widgetControl, SIGNAL(widgetUpdated()), this, SLOT(resetVideoDisplay()));
disconnect(this, SIGNAL(stateChanged(QMediaPlayer::State)), widgetControl, SLOT(videoStateChanged(QMediaPlayer::State)));
}
if (videoControl->output() == QVideoOutputControl::WidgetOutput) {
S60VideoWidgetControl *widgetControl = qobject_cast<S60VideoWidgetControl *>(m_service.control(QVideoWidgetControl_iid));
connect(widgetControl, SIGNAL(widgetUpdated()), this, SLOT(resetVideoDisplay()));
connect(this, SIGNAL(stateChanged(QMediaPlayer::State)), widgetControl, SLOT(videoStateChanged(QMediaPlayer::State)));
}
m_output = videoControl->output();
resetVideoDisplay();
}
}
bool S60VideoPlayerSession::resetNativeHandles()
{
QVideoOutputControl* videoControl = qobject_cast<QVideoOutputControl *>(m_service.control(QVideoOutputControl_iid));
WId newId = 0;
TRect newClipRect = TRect(0,0,0,0);
if (videoControl->output() == QVideoOutputControl::WidgetOutput) {
S60VideoWidgetControl* widgetControl = qobject_cast<S60VideoWidgetControl *>(m_service.control(QVideoWidgetControl_iid));
QWidget *videoWidget = widgetControl->videoWidget();
newId = videoWidget->winId();
newClipRect = qt_QRect2TRect(QRect(videoWidget->mapToGlobal(videoWidget->pos()), videoWidget->size()));
} else if (videoControl->output() == QVideoOutputControl::WindowOutput) {
S60VideoOverlay* windowControl = qobject_cast<S60VideoOverlay *>(m_service.control(QVideoWindowControl_iid));
newId = windowControl->winId();
newClipRect = TRect( newId->DrawableWindow()->AbsPosition(), newId->DrawableWindow()->Size());
} else {
if (QApplication::activeWindow())
newId = QApplication::activeWindow()->effectiveWinId();
}
if (newClipRect == m_clipRect && newId == m_windowId)
return false;
if (newId) {
m_windowRect = TRect( newId->DrawableWindow()->AbsPosition(), newId->DrawableWindow()->Size());
m_clipRect = newClipRect;
m_windowId = newId;
CCoeEnv *coeEnv = m_windowId->ControlEnv();
m_wsSession = &(coeEnv->WsSession());
m_screenDevice = coeEnv->ScreenDevice();
m_window = m_windowId->DrawableWindow();
return true;
}
return false;
}
bool S60VideoPlayerSession::isVideoAvailable() const
{
#ifdef PRE_S60_50_PLATFORM
return true; // this is not support in pre 5th platforms
#endif
return m_player->VideoEnabledL();
}
bool S60VideoPlayerSession::isAudioAvailable() const
{
if (m_player)
return m_player->AudioEnabledL();
else
return false;
}
void S60VideoPlayerSession::doPlay()
{
m_player->Play();
}
void S60VideoPlayerSession::doPauseL()
{
m_player->PauseL();
}
void S60VideoPlayerSession::doStop()
{
m_player->Stop();
}
qint64 S60VideoPlayerSession::doGetPositionL() const
{
return m_player->PositionL().Int64() / 1000;
}
void S60VideoPlayerSession::doSetPositionL(qint64 microSeconds)
{
m_player->SetPositionL(TTimeIntervalMicroSeconds(microSeconds));
}
void S60VideoPlayerSession::doSetVolumeL(int volume)
{
m_player->SetVolumeL((volume / 100.0)* m_player->MaxVolume());
}
void S60VideoPlayerSession::MvpuoOpenComplete(TInt aError)
{
setError(aError);
m_player->Prepare();
}
void S60VideoPlayerSession::MvpuoPrepareComplete(TInt aError)
{
setError(aError);
TRAPD(err,
m_player->SetDisplayWindowL(*m_wsSession,
*m_screenDevice,
*m_window,
m_windowRect,
m_clipRect));
setError(err);
initComplete();
}
void S60VideoPlayerSession::MvpuoFrameReady(CFbsBitmap &aFrame, TInt aError)
{
Q_UNUSED(aFrame);
Q_UNUSED(aError);
}
void S60VideoPlayerSession::MvpuoPlayComplete(TInt aError)
{
setError(aError);
playComplete();
}
void S60VideoPlayerSession::MvpuoEvent(const TMMFEvent &aEvent)
{
Q_UNUSED(aEvent);
}
void S60VideoPlayerSession::updateMetaDataEntriesL()
{
metaDataEntries().clear();
int numberOfMetaDataEntries = 0;
numberOfMetaDataEntries = m_player->NumberOfMetaDataEntriesL();
for (int i = 0; i < numberOfMetaDataEntries; i++) {
CMMFMetaDataEntry *entry = NULL;
entry = m_player->MetaDataEntryL(i);
metaDataEntries().insert(QString::fromUtf16(entry->Name().Ptr(), entry->Name().Length()), QString::fromUtf16(entry->Value().Ptr(), entry->Value().Length()));
delete entry;
}
emit metaDataChanged();
}
void S60VideoPlayerSession::resetVideoDisplay()
{
if (resetNativeHandles()) {
TRAPD(err, m_player->SetDisplayWindowL(*m_wsSession,
*m_screenDevice,
*m_window,
m_windowRect,
m_clipRect));
setError(err);
}
}
<commit_msg>Symbian: Fix platform check for isVideoAvailable.<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Mobility Components.
**
** $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 "s60videoplayersession.h"
#include "s60videowidget.h"
#include "s60mediaplayerservice.h"
#include "s60videooverlay.h"
#include <QtCore/qdebug.h>
#include <QtCore/private/qcore_symbian_p.h>
#include <QtGui/qwidget.h>
#include <QApplication>
#include <coecntrl.h>
#include <coemain.h> // For CCoeEnv
#include <w32std.h>
#include <mmf/common/mmfcontrollerframeworkbase.h>
S60VideoPlayerSession::S60VideoPlayerSession(QMediaService *service)
: S60MediaPlayerSession(service)
, m_player(0)
, m_clipRect(0, 0, 0, 0)
, m_windowRect(0, 0, 0, 0)
, m_output(QVideoOutputControl::NoOutput)
, m_windowId(0)
, m_wsSession(0)
, m_screenDevice(0)
, m_window(0)
, m_service(*service)
{
resetNativeHandles();
QT_TRAP_THROWING(m_player = CVideoPlayerUtility::NewL(
*this,
0,
EMdaPriorityPreferenceNone,
*m_wsSession,
*m_screenDevice,
*m_window,
m_windowRect,
m_clipRect));
}
S60VideoPlayerSession::~S60VideoPlayerSession()
{
m_player->Close();
delete m_player;
}
void S60VideoPlayerSession::doLoadL(const TDesC &path)
{
m_player->OpenFileL(path);
}
void S60VideoPlayerSession::doLoadUrlL(const TDesC &path)
{
m_player->OpenUrlL(path);
}
int S60VideoPlayerSession::doGetMediaLoadingProgressL() const
{
int progress = 0;
m_player->GetVideoLoadingProgressL(progress);
return progress;
}
int S60VideoPlayerSession::doGetDurationL() const
{
return m_player->DurationL().Int64() / 1000;
}
void S60VideoPlayerSession::setVideoRenderer(QObject *videoOutput)
{
Q_UNUSED(videoOutput)
QVideoOutputControl *videoControl = qobject_cast<QVideoOutputControl *>(m_service.control(QVideoOutputControl_iid));
//Render changes
if (m_output != videoControl->output()) {
if (m_output == QVideoOutputControl::WidgetOutput) {
S60VideoWidgetControl *widgetControl = qobject_cast<S60VideoWidgetControl *>(m_service.control(QVideoWidgetControl_iid));
disconnect(widgetControl, SIGNAL(widgetUpdated()), this, SLOT(resetVideoDisplay()));
disconnect(this, SIGNAL(stateChanged(QMediaPlayer::State)), widgetControl, SLOT(videoStateChanged(QMediaPlayer::State)));
}
if (videoControl->output() == QVideoOutputControl::WidgetOutput) {
S60VideoWidgetControl *widgetControl = qobject_cast<S60VideoWidgetControl *>(m_service.control(QVideoWidgetControl_iid));
connect(widgetControl, SIGNAL(widgetUpdated()), this, SLOT(resetVideoDisplay()));
connect(this, SIGNAL(stateChanged(QMediaPlayer::State)), widgetControl, SLOT(videoStateChanged(QMediaPlayer::State)));
}
m_output = videoControl->output();
resetVideoDisplay();
}
}
bool S60VideoPlayerSession::resetNativeHandles()
{
QVideoOutputControl* videoControl = qobject_cast<QVideoOutputControl *>(m_service.control(QVideoOutputControl_iid));
WId newId = 0;
TRect newClipRect = TRect(0,0,0,0);
if (videoControl->output() == QVideoOutputControl::WidgetOutput) {
S60VideoWidgetControl* widgetControl = qobject_cast<S60VideoWidgetControl *>(m_service.control(QVideoWidgetControl_iid));
QWidget *videoWidget = widgetControl->videoWidget();
newId = videoWidget->winId();
newClipRect = qt_QRect2TRect(QRect(videoWidget->mapToGlobal(videoWidget->pos()), videoWidget->size()));
} else if (videoControl->output() == QVideoOutputControl::WindowOutput) {
S60VideoOverlay* windowControl = qobject_cast<S60VideoOverlay *>(m_service.control(QVideoWindowControl_iid));
newId = windowControl->winId();
newClipRect = TRect( newId->DrawableWindow()->AbsPosition(), newId->DrawableWindow()->Size());
} else {
if (QApplication::activeWindow())
newId = QApplication::activeWindow()->effectiveWinId();
}
if (newClipRect == m_clipRect && newId == m_windowId)
return false;
if (newId) {
m_windowRect = TRect( newId->DrawableWindow()->AbsPosition(), newId->DrawableWindow()->Size());
m_clipRect = newClipRect;
m_windowId = newId;
CCoeEnv *coeEnv = m_windowId->ControlEnv();
m_wsSession = &(coeEnv->WsSession());
m_screenDevice = coeEnv->ScreenDevice();
m_window = m_windowId->DrawableWindow();
return true;
}
return false;
}
bool S60VideoPlayerSession::isVideoAvailable() const
{
#ifdef PRE_S60_50_PLATFORM
return true; // this is not support in pre 5th platforms
#else
return m_player->VideoEnabledL();
#endif
}
bool S60VideoPlayerSession::isAudioAvailable() const
{
if (m_player)
return m_player->AudioEnabledL();
else
return false;
}
void S60VideoPlayerSession::doPlay()
{
m_player->Play();
}
void S60VideoPlayerSession::doPauseL()
{
m_player->PauseL();
}
void S60VideoPlayerSession::doStop()
{
m_player->Stop();
}
qint64 S60VideoPlayerSession::doGetPositionL() const
{
return m_player->PositionL().Int64() / 1000;
}
void S60VideoPlayerSession::doSetPositionL(qint64 microSeconds)
{
m_player->SetPositionL(TTimeIntervalMicroSeconds(microSeconds));
}
void S60VideoPlayerSession::doSetVolumeL(int volume)
{
m_player->SetVolumeL((volume / 100.0)* m_player->MaxVolume());
}
void S60VideoPlayerSession::MvpuoOpenComplete(TInt aError)
{
setError(aError);
m_player->Prepare();
}
void S60VideoPlayerSession::MvpuoPrepareComplete(TInt aError)
{
setError(aError);
TRAPD(err,
m_player->SetDisplayWindowL(*m_wsSession,
*m_screenDevice,
*m_window,
m_windowRect,
m_clipRect));
setError(err);
initComplete();
}
void S60VideoPlayerSession::MvpuoFrameReady(CFbsBitmap &aFrame, TInt aError)
{
Q_UNUSED(aFrame);
Q_UNUSED(aError);
}
void S60VideoPlayerSession::MvpuoPlayComplete(TInt aError)
{
setError(aError);
playComplete();
}
void S60VideoPlayerSession::MvpuoEvent(const TMMFEvent &aEvent)
{
Q_UNUSED(aEvent);
}
void S60VideoPlayerSession::updateMetaDataEntriesL()
{
metaDataEntries().clear();
int numberOfMetaDataEntries = 0;
numberOfMetaDataEntries = m_player->NumberOfMetaDataEntriesL();
for (int i = 0; i < numberOfMetaDataEntries; i++) {
CMMFMetaDataEntry *entry = NULL;
entry = m_player->MetaDataEntryL(i);
metaDataEntries().insert(QString::fromUtf16(entry->Name().Ptr(), entry->Name().Length()), QString::fromUtf16(entry->Value().Ptr(), entry->Value().Length()));
delete entry;
}
emit metaDataChanged();
}
void S60VideoPlayerSession::resetVideoDisplay()
{
if (resetNativeHandles()) {
TRAPD(err, m_player->SetDisplayWindowL(*m_wsSession,
*m_screenDevice,
*m_window,
m_windowRect,
m_clipRect));
setError(err);
}
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef MARKERS_SYMBOLIZER_HPP
#define MARKERS_SYMBOLIZER_HPP
//mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/color.hpp>
#include <mapnik/stroke.hpp>
#include <mapnik/enumeration.hpp>
namespace mapnik {
// TODO - consider merging with text_symbolizer label_placement_e
enum marker_placement_enum {
MARKER_POINT_PLACEMENT,
MARKER_LINE_PLACEMENT,
marker_placement_enum_MAX
};
DEFINE_ENUM( marker_placement_e, marker_placement_enum );
enum marker_type_enum {
ARROW,
ELLIPSE,
marker_type_enum_MAX
};
DEFINE_ENUM( marker_type_e, marker_type_enum );
struct MAPNIK_DECL markers_symbolizer :
public symbolizer_with_image, public symbolizer_base
{
public:
markers_symbolizer();
markers_symbolizer(path_expression_ptr filename);
markers_symbolizer(markers_symbolizer const& rhs);
void set_allow_overlap(bool overlap);
bool get_allow_overlap() const;
void set_spacing(double spacing);
double get_spacing() const;
void set_max_error(double max_error);
double get_max_error() const;
void set_fill(color fill);
color const& get_fill() const;
void set_width(double width);
double get_width() const;
void set_height(double height);
double get_height() const;
stroke const& get_stroke() const;
void set_stroke(stroke const& stroke);
void set_marker_placement(marker_placement_e marker_p);
marker_placement_e get_marker_placement() const;
void set_marker_type(marker_type_e marker_p);
marker_type_e get_marker_type() const;
private:
bool allow_overlap_;
color fill_;
double spacing_;
double max_error_;
double width_;
double height_;
stroke stroke_;
marker_placement_e marker_p_;
marker_type_e marker_type_;
};
}
#endif // MARKERS_SYMBOLIZER_HPP
<commit_msg>declare dlf ctor explicit<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef MARKERS_SYMBOLIZER_HPP
#define MARKERS_SYMBOLIZER_HPP
//mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/color.hpp>
#include <mapnik/stroke.hpp>
#include <mapnik/enumeration.hpp>
namespace mapnik {
// TODO - consider merging with text_symbolizer label_placement_e
enum marker_placement_enum {
MARKER_POINT_PLACEMENT,
MARKER_LINE_PLACEMENT,
marker_placement_enum_MAX
};
DEFINE_ENUM( marker_placement_e, marker_placement_enum );
enum marker_type_enum {
ARROW,
ELLIPSE,
marker_type_enum_MAX
};
DEFINE_ENUM( marker_type_e, marker_type_enum );
struct MAPNIK_DECL markers_symbolizer :
public symbolizer_with_image, public symbolizer_base
{
public:
explicit markers_symbolizer();
markers_symbolizer(path_expression_ptr filename);
markers_symbolizer(markers_symbolizer const& rhs);
void set_allow_overlap(bool overlap);
bool get_allow_overlap() const;
void set_spacing(double spacing);
double get_spacing() const;
void set_max_error(double max_error);
double get_max_error() const;
void set_fill(color fill);
color const& get_fill() const;
void set_width(double width);
double get_width() const;
void set_height(double height);
double get_height() const;
stroke const& get_stroke() const;
void set_stroke(stroke const& stroke);
void set_marker_placement(marker_placement_e marker_p);
marker_placement_e get_marker_placement() const;
void set_marker_type(marker_type_e marker_p);
marker_type_e get_marker_type() const;
private:
bool allow_overlap_;
color fill_;
double spacing_;
double max_error_;
double width_;
double height_;
stroke stroke_;
marker_placement_e marker_p_;
marker_type_e marker_type_;
};
}
#endif // MARKERS_SYMBOLIZER_HPP
<|endoftext|> |
<commit_before>#ifndef INCLUDED_U5E_CANONICAL_COMPOSITION
#define INCLUDED_U5E_CANONICAL_COMPOSITION
#include <u5e/props/canonical_composition_mapping.hpp>
namespace u5e {
/**
* \brief performs in-place canonical composition.
*
* This will return the iterator in the end position after the
* composition.
*
* \tparam StorageType the storage type where to apply it.
*
* Must support codepoint_begin, codepont_cbegin, codepoint_end,
* codepoint_cend, as well as the member types iterator and
* const_iterator. It is also a requirement that you should be able
* to write to it as you read it, which means that this must only be
* used in utf32 iterators, otherwise the output may race ahead of
* the input.
*
* \param data the object where the canonical composition will be
* performed.
*
* \param count return pointer for how many compositions were performed
*/
template <typename StorageType>
typename StorageType::iterator
inline canonical_composition(StorageType& data, int* count) {
typename StorageType::iterator oi_begin(data.codepoint_begin());
typename StorageType::iterator oi(data.codepoint_begin());
typename StorageType::const_iterator input(data.codepoint_cbegin());
typename StorageType::const_iterator input_end(data.codepoint_cend());
while (input != input_end) {
int a = *(input++);
if (input == input_end) {
// there is no b.
*(oi++) = a;
} else {
// look ahead for the next codepoint
int b = *input;
int c;
if (u5e::props::canonical_composition_mapping::resolve(a, b, &c)) {
*(oi++) = c;
++input;
*count = *count + 1;
} else {
*(oi++) = a;
}
}
}
return oi;
};
}
#endif
<commit_msg>fix bug in canonical composition<commit_after>#ifndef INCLUDED_U5E_CANONICAL_COMPOSITION
#define INCLUDED_U5E_CANONICAL_COMPOSITION
#include <u5e/props/canonical_composition_mapping.hpp>
namespace u5e {
/**
* \brief performs in-place canonical composition.
*
* This will return the iterator in the end position after the
* composition.
*
* \tparam StorageType the storage type where to apply it.
*
* Must support codepoint_begin, codepont_cbegin, codepoint_end,
* codepoint_cend, as well as the member types iterator and
* const_iterator. It is also a requirement that you should be able
* to write to it as you read it, which means that this must only be
* used in utf32 iterators, otherwise the output may race ahead of
* the input.
*
* \param data the object where the canonical composition will be
* performed.
*
* \param count return pointer for how many compositions were performed
*/
template <typename StorageType>
typename StorageType::iterator
inline canonical_composition(StorageType& data, int* count) {
typename StorageType::iterator oi(data.codepoint_begin());
typename StorageType::iterator in = oi;
typename StorageType::iterator end(data.codepoint_end());
int a, b, c;
while (in != end) {
//
// grab the codepoint in the current input iterator
//
a = *in;
if ((in + 1) == end) {
//
// If this is the last codepoint, it can't be composed, so we
// just push it to the output as-is.
//
*(oi++) = a;
in++;
} else {
//
// look ahead for the next codepoint
//
b = *(in + 1);
if (u5e::props::canonical_composition_mapping::resolve(a, b, &c)) {
//
// If this is a composition, we set it as the current input
// iterator after advancing, because it may still be
// composed more.
//
*(++in) = c;
*count = *count + 1;
} else {
//
// If there is no composition, we set it in the output iterator
//
*(oi++) = a;
//
// And finally advance the input iterator.
//
in++;
}
}
}
return oi;
};
}
#endif
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "stringutils.h"
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <limits.h>
namespace Utils {
QTCREATOR_UTILS_EXPORT QString settingsKey(const QString &category)
{
QString rc(category);
const QChar underscore = QLatin1Char('_');
const int size = rc.size();
for (int i = 0; i < size; i++) {
const QChar c = rc.at(i);
if (!c.isLetterOrNumber() && c != underscore)
rc[i] = underscore;
}
return rc;
}
// Figure out length of common start of string ("C:\a", "c:\b" -> "c:\"
static inline int commonPartSize(const QString &s1, const QString &s2)
{
const int size = qMin(s1.size(), s2.size());
for (int i = 0; i < size; i++)
if (s1.at(i) != s2.at(i))
return i;
return size;
}
QTCREATOR_UTILS_EXPORT QString commonPrefix(const QStringList &strings)
{
switch (strings.size()) {
case 0:
return QString();
case 1:
return strings.front();
default:
break;
}
// Figure out common string part: "C:\foo\bar1" "C:\foo\bar2" -> "C:\foo\bar"
int commonLength = INT_MAX;
const int last = strings.size() - 1;
for (int i = 0; i < last; i++)
commonLength = qMin(commonLength, commonPartSize(strings.at(i), strings.at(i + 1)));
if (!commonLength)
return QString();
return strings.at(0).left(commonLength);
}
QTCREATOR_UTILS_EXPORT QString commonPath(const QStringList &files)
{
QString common = commonPrefix(files);
// Find common directory part: "C:\foo\bar" -> "C:\foo"
int lastSeparatorPos = common.lastIndexOf(QLatin1Char('/'));
if (lastSeparatorPos == -1)
lastSeparatorPos = common.lastIndexOf(QLatin1Char('\\'));
if (lastSeparatorPos == -1)
return QString();
if (lastSeparatorPos == -1)
return QString();
#ifdef Q_OS_UNIX
if (lastSeparatorPos == 0) // Unix: "/a", "/b" -> '/'
lastSeparatorPos = 1;
#endif
common.truncate(lastSeparatorPos);
return common;
}
} // namespace Utils
<commit_msg>Text editor: Fix settings groups.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "stringutils.h"
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <limits.h>
namespace Utils {
QTCREATOR_UTILS_EXPORT QString settingsKey(const QString &category)
{
QString rc(category);
const QChar underscore = QLatin1Char('_');
// Remove the sort category "X.Category" -> "Category"
if (rc.size() > 2 && rc.at(0).isLetter() && rc.at(1) == QLatin1Char('.'))
rc.remove(0, 2);
// Replace special characters
const int size = rc.size();
for (int i = 0; i < size; i++) {
const QChar c = rc.at(i);
if (!c.isLetterOrNumber() && c != underscore)
rc[i] = underscore;
}
return rc;
}
// Figure out length of common start of string ("C:\a", "c:\b" -> "c:\"
static inline int commonPartSize(const QString &s1, const QString &s2)
{
const int size = qMin(s1.size(), s2.size());
for (int i = 0; i < size; i++)
if (s1.at(i) != s2.at(i))
return i;
return size;
}
QTCREATOR_UTILS_EXPORT QString commonPrefix(const QStringList &strings)
{
switch (strings.size()) {
case 0:
return QString();
case 1:
return strings.front();
default:
break;
}
// Figure out common string part: "C:\foo\bar1" "C:\foo\bar2" -> "C:\foo\bar"
int commonLength = INT_MAX;
const int last = strings.size() - 1;
for (int i = 0; i < last; i++)
commonLength = qMin(commonLength, commonPartSize(strings.at(i), strings.at(i + 1)));
if (!commonLength)
return QString();
return strings.at(0).left(commonLength);
}
QTCREATOR_UTILS_EXPORT QString commonPath(const QStringList &files)
{
QString common = commonPrefix(files);
// Find common directory part: "C:\foo\bar" -> "C:\foo"
int lastSeparatorPos = common.lastIndexOf(QLatin1Char('/'));
if (lastSeparatorPos == -1)
lastSeparatorPos = common.lastIndexOf(QLatin1Char('\\'));
if (lastSeparatorPos == -1)
return QString();
if (lastSeparatorPos == -1)
return QString();
#ifdef Q_OS_UNIX
if (lastSeparatorPos == 0) // Unix: "/a", "/b" -> '/'
lastSeparatorPos = 1;
#endif
common.truncate(lastSeparatorPos);
return common;
}
} // namespace Utils
<|endoftext|> |
<commit_before>#include "pch.h"
#include "RTHRMain.h"
#include "Common\DirectXHelper.h"
// Loads and initializes application assets when the application is loaded.
RTHRMain::RTHRMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
deviceResources(deviceResources)
{
// Register to be notified if the Device is lost or recreated
deviceResources->RegisterDeviceNotify(this);
// TODO: Replace this with your app's content initialization.
fpsTextRenderer = std::unique_ptr<SampleFpsTextRenderer>(new SampleFpsTextRenderer(deviceResources));
#ifdef _DEBUG
m_console->RestoreDevice(deviceResources->GetD3DDeviceContext(), L"Assets\\Fonts\\consolas.spritefont");
#endif
CreateWindowSizeDependentResources();
#ifdef _DEBUG
m_console->WriteLine(L"Starting Up...");
m_console->WriteLine(L"Making geometry");
#endif
matrices.world = Matrix::Identity;
eyePos = Vector3(2, 2, 0);
matrices.view = Matrix::CreateLookAt(eyePos,
Vector3::Zero,
Vector3::UnitY);
hairObj = make_unique<Hair>(GeometryType::SPHERE, deviceResources, 1.0f, 4, 5);
}
RTHRMain::~RTHRMain()
{
// Deregister device notification
deviceResources->RegisterDeviceNotify(nullptr);
}
// Updates application state when the window size changes (e.g. device orientation change)
void RTHRMain::CreateWindowSizeDependentResources()
{
// TODO: Replace this with the size-dependent initialization of your app's content.
auto size = deviceResources->GetOutputSize();
#ifdef _DEBUG
m_console->SetWindow(SimpleMath::Viewport::ComputeTitleSafeArea(size.Width, size.Height));
#endif
matrices.projection = Matrix::CreatePerspectiveFieldOfView(XM_PI / 4.f, (size.Width/size.Height), FLT_EPSILON, 10.f);
constMatrices = make_unique<ConstantBuffer<MatrixContants>>(deviceResources->GetD3DDevice());
dirtyFlags = EffectDirtyFlags::WorldViewProj;
}
// Updates the application state once per frame.
void RTHRMain::Update()
{
// Update scene objects.
stepTimer.Tick([&]()
{
// If the world view projection matrix is dirty and needs to be cleaned
if (dirtyFlags & EffectDirtyFlags::WorldViewProj)
{
XMMATRIX worldViewProjConstant;
matrices.SetConstants(dirtyFlags, worldViewProjConstant);
MatrixContants update = MatrixContants();
update.eyePosition = eyePos;
update.world = matrices.world;
update.worldViewProj = worldViewProjConstant;
auto size = deviceResources->GetOutputSize();
update.renderTargetSize = Vector2(size.Width, size.Height);
constMatrices->SetData(deviceResources->GetD3DDeviceContext(), update);
}
// TODO: Replace this with your app's content update functions.
fpsTextRenderer->Update(stepTimer);
});
}
// Renders the current frame according to the current application state.
// Returns true if the frame was rendered and is ready to be displayed.
bool RTHRMain::Render()
{
#pragma region RenderInit
// Don't try to render anything before the first Update.
if (stepTimer.GetFrameCount() == 0)
{
return false;
}
auto context = deviceResources->GetD3DDeviceContext();
// Reset the viewport to target the whole screen.
auto viewport = deviceResources->GetScreenViewport();
context->RSSetViewports(1, &viewport);
// Reset render targets to the screen.
ID3D11RenderTargetView *const targets[1] = { deviceResources->GetBackBufferRenderTargetView() };
context->OMSetRenderTargets(1, targets, deviceResources->GetDepthStencilView());
// Clear the back buffer and depth stencil view.
context->ClearRenderTargetView(deviceResources->GetBackBufferRenderTargetView(), Colors::MintCream);
context->ClearDepthStencilView(deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
#pragma endregion
#pragma region Render Calls
// Render the scene objects.
fpsTextRenderer->Render();
#ifdef _DEBUG
m_console->Render();
#endif
hairObj->Draw(&matrices, eyePos, constMatrices->GetBufferAddress(), Colors::RosyBrown);
#pragma endregion
return true;
}
// Notifies renderers that device resources need to be released.
void RTHRMain::OnDeviceLost()
{
hairObj->Reset();
#ifdef _DEBUG
m_console->WriteLine(L"Device Lost");
m_console->ReleaseDevice();
#endif
fpsTextRenderer->ReleaseDeviceDependentResources();
}
// Notifies renderers that device resources may now be recreated.
void RTHRMain::OnDeviceRestored()
{
#ifdef _DEBUG
m_console->RestoreDevice(deviceResources->GetD3DDeviceContext(), L"../../Fonts/consolas.spritefont");
m_console->WriteLine(L"Device Restored");
#endif
fpsTextRenderer->CreateDeviceDependentResources();
hairObj->CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
<commit_msg>Changes to the HairGeometry<commit_after>#include "pch.h"
#include "RTHRMain.h"
#include "Common\DirectXHelper.h"
// Loads and initializes application assets when the application is loaded.
RTHRMain::RTHRMain(const std::shared_ptr<DX::DeviceResources>& deviceResources) :
deviceResources(deviceResources)
{
// Register to be notified if the Device is lost or recreated
deviceResources->RegisterDeviceNotify(this);
// TODO: Replace this with your app's content initialization.
fpsTextRenderer = std::unique_ptr<SampleFpsTextRenderer>(new SampleFpsTextRenderer(deviceResources));
#ifdef _DEBUG
m_console->RestoreDevice(deviceResources->GetD3DDeviceContext(), L"Assets\\Fonts\\consolas.spritefont");
#endif
CreateWindowSizeDependentResources();
#ifdef _DEBUG
m_console->WriteLine(L"Starting Up...");
m_console->WriteLine(L"Making geometry");
#endif
matrices.world = Matrix::Identity;
eyePos = Vector3(0, 0, 3);
matrices.view = Matrix::CreateLookAt(eyePos,
Vector3::Zero,
Vector3::UnitY);
hairObj = make_unique<Hair>(GeometryType::SPHERE, deviceResources, 1.0f, 4, 5);
}
RTHRMain::~RTHRMain()
{
// Deregister device notification
deviceResources->RegisterDeviceNotify(nullptr);
}
// Updates application state when the window size changes (e.g. device orientation change)
void RTHRMain::CreateWindowSizeDependentResources()
{
// TODO: Replace this with the size-dependent initialization of your app's content.
auto size = deviceResources->GetOutputSize();
#ifdef _DEBUG
m_console->SetWindow(SimpleMath::Viewport::ComputeTitleSafeArea(size.Width, size.Height));
#endif
matrices.projection = Matrix::CreatePerspectiveFieldOfView(XM_PI / 4.f, (size.Width/size.Height), FLT_EPSILON, 10.f);
constMatrices = make_unique<ConstantBuffer<MatrixContants>>(deviceResources->GetD3DDevice());
dirtyFlags = EffectDirtyFlags::WorldViewProj;
}
// Updates the application state once per frame.
void RTHRMain::Update()
{
// Update scene objects.
stepTimer.Tick([&]()
{
// If the world view projection matrix is dirty and needs to be cleaned
if (dirtyFlags & EffectDirtyFlags::WorldViewProj)
{
XMMATRIX worldViewProjConstant;
matrices.SetConstants(dirtyFlags, worldViewProjConstant);
MatrixContants update = MatrixContants();
update.eyePosition = eyePos;
update.world = matrices.world;
update.worldViewProj = worldViewProjConstant;
auto size = deviceResources->GetOutputSize();
update.renderTargetSize = Vector2(size.Width, size.Height);
constMatrices->SetData(deviceResources->GetD3DDeviceContext(), update);
}
// TODO: Replace this with your app's content update functions.
fpsTextRenderer->Update(stepTimer);
});
}
// Renders the current frame according to the current application state.
// Returns true if the frame was rendered and is ready to be displayed.
bool RTHRMain::Render()
{
#pragma region RenderInit
// Don't try to render anything before the first Update.
if (stepTimer.GetFrameCount() == 0)
{
return false;
}
auto context = deviceResources->GetD3DDeviceContext();
// Reset the viewport to target the whole screen.
auto viewport = deviceResources->GetScreenViewport();
context->RSSetViewports(1, &viewport);
// Reset render targets to the screen.
ID3D11RenderTargetView *const targets[1] = { deviceResources->GetBackBufferRenderTargetView() };
context->OMSetRenderTargets(1, targets, deviceResources->GetDepthStencilView());
// Clear the back buffer and depth stencil view.
context->ClearRenderTargetView(deviceResources->GetBackBufferRenderTargetView(), Colors::MintCream);
context->ClearDepthStencilView(deviceResources->GetDepthStencilView(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
#pragma endregion
#pragma region Render Calls
// Render the scene objects.
fpsTextRenderer->Render();
#ifdef _DEBUG
m_console->Render();
#endif
hairObj->Draw(&matrices, eyePos, constMatrices->GetBufferAddress(), Colors::RosyBrown);
#pragma endregion
return true;
}
// Notifies renderers that device resources need to be released.
void RTHRMain::OnDeviceLost()
{
hairObj->Reset();
#ifdef _DEBUG
m_console->WriteLine(L"Device Lost");
m_console->ReleaseDevice();
#endif
fpsTextRenderer->ReleaseDeviceDependentResources();
}
// Notifies renderers that device resources may now be recreated.
void RTHRMain::OnDeviceRestored()
{
#ifdef _DEBUG
m_console->RestoreDevice(deviceResources->GetD3DDeviceContext(), L"../../Fonts/consolas.spritefont");
m_console->WriteLine(L"Device Restored");
#endif
fpsTextRenderer->CreateDeviceDependentResources();
hairObj->CreateDeviceDependentResources();
CreateWindowSizeDependentResources();
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMesaActor.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.
=========================================================================*/
// This keeps the New method from being defined in included cxx file.
#define VTK_IMPLEMENT_MESA_CXX
#include "GL/gl_mangle.h"
#include "GL/gl.h"
#include <math.h>
#include "vtkToolkits.h"
#include "vtkMesaActor.h"
#include "vtkRenderWindow.h"
#include "vtkMesaProperty.h"
#include "vtkMesaCamera.h"
#include "vtkMesaLight.h"
#include "vtkCuller.h"
// make sure this file is included before the #define takes place
// so we don't get two vtkMesaActor classes defined.
#include "vtkOpenGLActor.h"
#include "vtkMesaActor.h"
// Make sure vtkMesaActor is a copy of vtkOpenGLActor
// with vtkOpenGLActor replaced with vtkMesaActor
#define vtkOpenGLActor vtkMesaActor
#include "vtkOpenGLActor.cxx"
#undef vtkOpenGLActor
//-------------------------------------------------------------------------
vtkMesaActor* vtkMesaActor::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMesaActor");
if(ret)
{
return (vtkMesaActor*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkMesaActor;
}
vtkProperty* MakeProperty()
{
return vtkMesaProperty::New();
}
<commit_msg>forgot the vtkMesaActor::<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkMesaActor.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.
=========================================================================*/
// This keeps the New method from being defined in included cxx file.
#define VTK_IMPLEMENT_MESA_CXX
#include "GL/gl_mangle.h"
#include "GL/gl.h"
#include <math.h>
#include "vtkToolkits.h"
#include "vtkMesaActor.h"
#include "vtkRenderWindow.h"
#include "vtkMesaProperty.h"
#include "vtkMesaCamera.h"
#include "vtkMesaLight.h"
#include "vtkCuller.h"
// make sure this file is included before the #define takes place
// so we don't get two vtkMesaActor classes defined.
#include "vtkOpenGLActor.h"
#include "vtkMesaActor.h"
// Make sure vtkMesaActor is a copy of vtkOpenGLActor
// with vtkOpenGLActor replaced with vtkMesaActor
#define vtkOpenGLActor vtkMesaActor
#include "vtkOpenGLActor.cxx"
#undef vtkOpenGLActor
//-------------------------------------------------------------------------
vtkMesaActor* vtkMesaActor::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkMesaActor");
if(ret)
{
return (vtkMesaActor*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkMesaActor;
}
vtkProperty* vtkMesaActor::MakeProperty()
{
return vtkMesaProperty::New();
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef POLYGON_PATTERN_SYMBOLIZER_HPP
#define MAPNIK_POLYGON_PATTERN_SYMBOLIZER_HPP
// mapnik
#include <mapnik/symbolizer.hpp>
namespace mapnik
{
struct MAPNIK_DECL polygon_pattern_symbolizer :
public symbolizer_with_image
{
polygon_pattern_symbolizer(path_expression_ptr file);
polygon_pattern_symbolizer(polygon_pattern_symbolizer const& rhs);
};
}
#endif //MAPNIK_POLYGON_PATTERN_SYMBOLIZER_HPP
<commit_msg>fix include guard<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef POLYGON_PATTERN_SYMBOLIZER_HPP
#define POLYGON_PATTERN_SYMBOLIZER_HPP
// mapnik
#include <mapnik/symbolizer.hpp>
namespace mapnik
{
struct MAPNIK_DECL polygon_pattern_symbolizer :
public symbolizer_with_image
{
polygon_pattern_symbolizer(path_expression_ptr file);
polygon_pattern_symbolizer(polygon_pattern_symbolizer const& rhs);
};
}
#endif //POLYGON_PATTERN_SYMBOLIZER_HPP
<|endoftext|> |
<commit_before>/* mockturtle: C++ logic network library
* Copyright (C) 2018 EPFL
*
* 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 refactoring.hpp
\brief Refactoring
\author Mathias Soeken
*/
#pragma once
#include <iostream>
#include "../algorithms/akers_synthesis.hpp"
#include "../algorithms/cut_rewriting.hpp"
#include "../algorithms/simulation.hpp"
#include "../networks/mig.hpp"
#include "../traits.hpp"
#include "../utils/progress_bar.hpp"
#include "../utils/stopwatch.hpp"
#include "../views/cut_view.hpp"
#include "../views/mffc_view.hpp"
#include "../views/topo_view.hpp"
#include <fmt/format.h>
#include <kitty/dynamic_truth_table.hpp>
namespace mockturtle
{
/*! \brief Parameters for refactoring.
*
* The data structure `refactoring_params` holds configurable parameters with
* default arguments for `refactoring`.
*/
struct refactoring_params
{
/*! \brief Maximum number of PIs in MFFCs. */
uint32_t max_pis{6};
/*! \brief Show progress. */
bool progress{false};
/*! \brief Be verbose. */
bool verbose{false};
};
struct refactoring_stats
{
stopwatch<>::duration time_total{0};
stopwatch<>::duration time_mffc{0};
stopwatch<>::duration time_refactoring{0};
stopwatch<>::duration time_simulation{0};
void report() const
{
std::cout << fmt::format( "[i] total time = {:>5.2f} secs\n", to_seconds( time_total ) );
std::cout << fmt::format( "[i] MFFC time = {:>5.2f} secs\n", to_seconds( time_mffc ) );
std::cout << fmt::format( "[i] refactoring time = {:>5.2f} secs\n", to_seconds( time_refactoring ) );
std::cout << fmt::format( "[i] simulation time = {:>5.2f} secs\n", to_seconds( time_simulation ) );
}
};
namespace detail
{
template<class Ntk, class RefactoringFn>
class refactoring_impl
{
public:
refactoring_impl( Ntk& ntk, RefactoringFn&& refactoring_fn, refactoring_params const& ps, refactoring_stats& st )
: ntk( ntk ), refactoring_fn( refactoring_fn ), ps( ps ), st( st )
{
}
void run()
{
const auto size = ntk.size();
progress_bar pbar{ntk.size(), "|{0}| node = {1:>4} cand = {2:>4} est. reduction = {3:>5}", ps.progress};
stopwatch t( st.time_total );
ntk.clear_visited();
ntk.clear_values();
ntk.foreach_node( [&]( auto const& n ) {
ntk.set_value( n, ntk.fanout_size( n ) );
} );
ntk.foreach_gate( [&]( auto const& n, auto i ) {
if ( i >= size )
{
return false;
}
const auto mffc = make_with_stopwatch<mffc_view<Ntk>>( st.time_mffc, ntk, n );
pbar( i, i, _candidates, _estimated_gain );
if ( mffc.num_pos() == 0 || mffc.num_pis() > ps.max_pis || mffc.size() < 4 )
{
return true;
}
std::vector<signal<Ntk>> leaves( mffc.num_pis() );
mffc.foreach_pi( [&]( auto const& n, auto j ) {
leaves[j] = ntk.make_signal( n );
} );
default_simulator<kitty::dynamic_truth_table> sim( mffc.num_pis() );
const auto tt = call_with_stopwatch( st.time_simulation,
[&]() { return simulate<kitty::dynamic_truth_table>( mffc, sim )[0]; } );
const auto new_f = call_with_stopwatch( st.time_refactoring,
[&]() { return refactoring_fn( ntk, tt, leaves.begin(), leaves.end() ); } );
if ( n == ntk.get_node( new_f ) )
{
return true;
}
int32_t gain = detail::recursive_deref( ntk, n );
gain -= detail::recursive_ref( ntk, ntk.get_node( new_f ) );
if ( gain > 0 )
{
++_candidates;
_estimated_gain += gain;
ntk.substitute_node( n, new_f );
ntk.set_value( n, 0 );
ntk.set_value( ntk.get_node( new_f ), ntk.fanout_size( ntk.get_node( new_f ) ) );
}
else
{
detail::recursive_deref( ntk, ntk.get_node( new_f ) );
detail::recursive_ref( ntk, n );
}
return true;
} );
}
private:
Ntk& ntk;
RefactoringFn&& refactoring_fn;
refactoring_params const& ps;
refactoring_stats& st;
uint32_t _candidates{0};
uint32_t _estimated_gain{0};
};
} /* namespace detail */
/*! \brief Boolean refactoring.
*
* This algorithm performs refactoring by collapsing maximal fanout-free cones
* (MFFCs) into truth tables and recreate a new network structure from it.
* The algorithm performs changes directly in the input network and keeps the
* substituted structures dangling in the network. They can be cleaned up using
* the `cleanup_dangling` algorithm.
*
* The refactoring function must be of type `NtkDest::signal(NtkDest&,
* kitty::dynamic_truth_table const&, LeavesIterator, LeavesIterator)` where
* `LeavesIterator` can be dereferenced to a `NtkDest::signal`. The last two
* parameters compose an iterator pair where the distance matches the number of
* variables of the truth table that is passed as second parameter. There are
* some refactoring algorithms in the folder
* `mockturtle/algorithms/node_resyntesis`, since the resynthesis functions
* have the same signature.
*
* **Required network functions:**
* - `get_node`
* - `size`
* - `make_signal`
* - `foreach_gate`
* - `substitute_node`
* - `clear_visited`
* - `clear_values`
* - `fanout_size`
* - `set_value`
* - `foreach_node`
*
* \param ntk Input network (will be changed in-place)
* \param refactoring_fn Refactoring function
* \param ps Refactoring params
*/
template<class Ntk, class RefactoringFn>
void refactoring( Ntk& ntk, RefactoringFn&& refactoring_fn, refactoring_params const& ps = {} )
{
static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" );
static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" );
static_assert( has_size_v<Ntk>, "Ntk does not implement the size method" );
static_assert( has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" );
static_assert( has_foreach_gate_v<Ntk>, "Ntk does not implement the foreach_gate method" );
static_assert( has_substitute_node_v<Ntk>, "Ntk does not implement the substitute_node method" );
static_assert( has_clear_visited_v<Ntk>, "Ntk does not implement the clear_visited method" );
static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the clear_values method" );
static_assert( has_fanout_size_v<Ntk>, "Ntk does not implement the fanout_size method" );
static_assert( has_set_value_v<Ntk>, "Ntk does not implement the set_value method" );
static_assert( has_foreach_node_v<Ntk>, "Ntk does not implement the foreach_node method" );
refactoring_stats st;
detail::refactoring_impl<Ntk, RefactoringFn> p( ntk, refactoring_fn, ps, st );
p.run();
if ( ps.verbose )
{
st.report();
}
}
} /* namespace mockturtle */
<commit_msg>refactoring.<commit_after>/* mockturtle: C++ logic network library
* Copyright (C) 2018 EPFL
*
* 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 refactoring.hpp
\brief Refactoring
\author Mathias Soeken
*/
#pragma once
#include <iostream>
#include "../algorithms/akers_synthesis.hpp"
#include "../algorithms/mffc_utils.hpp"
#include "../algorithms/simulation.hpp"
#include "../networks/mig.hpp"
#include "../traits.hpp"
#include "../utils/progress_bar.hpp"
#include "../utils/stopwatch.hpp"
#include "../views/cut_view.hpp"
#include "../views/mffc_view.hpp"
#include "../views/topo_view.hpp"
#include <fmt/format.h>
#include <kitty/dynamic_truth_table.hpp>
namespace mockturtle
{
/*! \brief Parameters for refactoring.
*
* The data structure `refactoring_params` holds configurable parameters with
* default arguments for `refactoring`.
*/
struct refactoring_params
{
/*! \brief Maximum number of PIs in MFFCs. */
uint32_t max_pis{6};
/*! \brief Show progress. */
bool progress{false};
/*! \brief Be verbose. */
bool verbose{false};
};
struct refactoring_stats
{
stopwatch<>::duration time_total{0};
stopwatch<>::duration time_mffc{0};
stopwatch<>::duration time_refactoring{0};
stopwatch<>::duration time_simulation{0};
void report() const
{
std::cout << fmt::format( "[i] total time = {:>5.2f} secs\n", to_seconds( time_total ) );
std::cout << fmt::format( "[i] MFFC time = {:>5.2f} secs\n", to_seconds( time_mffc ) );
std::cout << fmt::format( "[i] refactoring time = {:>5.2f} secs\n", to_seconds( time_refactoring ) );
std::cout << fmt::format( "[i] simulation time = {:>5.2f} secs\n", to_seconds( time_simulation ) );
}
};
namespace detail
{
template<class Ntk, class RefactoringFn>
class refactoring_impl
{
public:
refactoring_impl( Ntk& ntk, RefactoringFn&& refactoring_fn, refactoring_params const& ps, refactoring_stats& st )
: ntk( ntk ), refactoring_fn( refactoring_fn ), ps( ps ), st( st )
{
}
void run()
{
const auto size = ntk.size();
progress_bar pbar{ntk.size(), "|{0}| node = {1:>4} cand = {2:>4} est. reduction = {3:>5}", ps.progress};
stopwatch t( st.time_total );
ntk.clear_visited();
ntk.clear_values();
ntk.foreach_node( [&]( auto const& n ) {
ntk.set_value( n, ntk.fanout_size( n ) );
} );
ntk.foreach_gate( [&]( auto const& n, auto i ) {
if ( i >= size )
{
return false;
}
const auto mffc = make_with_stopwatch<mffc_view<Ntk>>( st.time_mffc, ntk, n );
pbar( i, i, _candidates, _estimated_gain );
if ( mffc.num_pos() == 0 || mffc.num_pis() > ps.max_pis || mffc.size() < 4 )
{
return true;
}
std::vector<signal<Ntk>> leaves( mffc.num_pis() );
mffc.foreach_pi( [&]( auto const& n, auto j ) {
leaves[j] = ntk.make_signal( n );
} );
default_simulator<kitty::dynamic_truth_table> sim( mffc.num_pis() );
const auto tt = call_with_stopwatch( st.time_simulation,
[&]() { return simulate<kitty::dynamic_truth_table>( mffc, sim )[0]; } );
const auto new_f = call_with_stopwatch( st.time_refactoring,
[&]() { return refactoring_fn( ntk, tt, leaves.begin(), leaves.end() ); } );
if ( n == ntk.get_node( new_f ) )
{
return true;
}
int32_t gain = detail::recursive_deref( ntk, n );
gain -= detail::recursive_ref( ntk, ntk.get_node( new_f ) );
if ( gain > 0 )
{
++_candidates;
_estimated_gain += gain;
ntk.substitute_node( n, new_f );
ntk.set_value( n, 0 );
ntk.set_value( ntk.get_node( new_f ), ntk.fanout_size( ntk.get_node( new_f ) ) );
}
else
{
detail::recursive_deref( ntk, ntk.get_node( new_f ) );
detail::recursive_ref( ntk, n );
}
return true;
} );
}
private:
Ntk& ntk;
RefactoringFn&& refactoring_fn;
refactoring_params const& ps;
refactoring_stats& st;
uint32_t _candidates{0};
uint32_t _estimated_gain{0};
};
} /* namespace detail */
/*! \brief Boolean refactoring.
*
* This algorithm performs refactoring by collapsing maximal fanout-free cones
* (MFFCs) into truth tables and recreate a new network structure from it.
* The algorithm performs changes directly in the input network and keeps the
* substituted structures dangling in the network. They can be cleaned up using
* the `cleanup_dangling` algorithm.
*
* The refactoring function must be of type `NtkDest::signal(NtkDest&,
* kitty::dynamic_truth_table const&, LeavesIterator, LeavesIterator)` where
* `LeavesIterator` can be dereferenced to a `NtkDest::signal`. The last two
* parameters compose an iterator pair where the distance matches the number of
* variables of the truth table that is passed as second parameter. There are
* some refactoring algorithms in the folder
* `mockturtle/algorithms/node_resyntesis`, since the resynthesis functions
* have the same signature.
*
* **Required network functions:**
* - `get_node`
* - `size`
* - `make_signal`
* - `foreach_gate`
* - `substitute_node`
* - `clear_visited`
* - `clear_values`
* - `fanout_size`
* - `set_value`
* - `foreach_node`
*
* \param ntk Input network (will be changed in-place)
* \param refactoring_fn Refactoring function
* \param ps Refactoring params
*/
template<class Ntk, class RefactoringFn>
void refactoring( Ntk& ntk, RefactoringFn&& refactoring_fn, refactoring_params const& ps = {} )
{
static_assert( is_network_type_v<Ntk>, "Ntk is not a network type" );
static_assert( has_get_node_v<Ntk>, "Ntk does not implement the get_node method" );
static_assert( has_size_v<Ntk>, "Ntk does not implement the size method" );
static_assert( has_make_signal_v<Ntk>, "Ntk does not implement the make_signal method" );
static_assert( has_foreach_gate_v<Ntk>, "Ntk does not implement the foreach_gate method" );
static_assert( has_substitute_node_v<Ntk>, "Ntk does not implement the substitute_node method" );
static_assert( has_clear_visited_v<Ntk>, "Ntk does not implement the clear_visited method" );
static_assert( has_clear_values_v<Ntk>, "Ntk does not implement the clear_values method" );
static_assert( has_fanout_size_v<Ntk>, "Ntk does not implement the fanout_size method" );
static_assert( has_set_value_v<Ntk>, "Ntk does not implement the set_value method" );
static_assert( has_foreach_node_v<Ntk>, "Ntk does not implement the foreach_node method" );
refactoring_stats st;
detail::refactoring_impl<Ntk, RefactoringFn> p( ntk, refactoring_fn, ps, st );
p.run();
if ( ps.verbose )
{
st.report();
}
}
} /* namespace mockturtle */
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <cstddef>
#include "../matrix.h"
#include "math.h"
namespace MATH_NAMESPACE
{
//-------------------------------------------------------------------------------------------------
// quaternion members
//
template <typename T>
MATH_FUNC
inline quaternion<T>::quaternion(T const& w, T const& x, T const& y, T const& z)
: w(w)
, x(x)
, y(y)
, z(z)
{
}
template <typename T>
MATH_FUNC
inline quaternion<T>::quaternion(T const& w, vector<3, T> const& v)
: w(w)
, x(v.x)
, y(v.y)
, z(v.z)
{
}
template <typename T>
MATH_FUNC
inline quaternion<T> quaternion<T>::identity()
{
return quaternion<T>(T(1.0), T(0.0), T(0.0), T(0.0));
}
template <typename T>
MATH_FUNC
inline quaternion<T> quaternion<T>::rotation(vector<3, T> const& from, vector<3, T> const& to)
{
vector<3, T> nfrom = normalize(from);
vector<3, T> nto = normalize(to);
return quaternion<T>(dot(nfrom, nto), cross(nfrom, nto));
}
template <typename T>
MATH_FUNC
inline quaternion<T> quaternion<T>::rotation(T const& yaw, T const& pitch, T const& roll)
{
T cy = cos(yaw * T(0.5));
T sy = sin(yaw * T(0.5));
T cp = cos(pitch * T(0.5));
T sp = sin(pitch * T(0.5));
T cr = cos(roll * T(0.5));
T sr = sin(roll * T(0.5));
return quaternion<T>(
cy * cp * cr + sy * sp * sr,
cy * cp * sr - sy * sp * cr,
sy * cp * sr + cy * sp * cr,
sy * cp * cr - cy * sp * sr
);
}
//--------------------------------------------------------------------------------------------------
// Basic arithmetic
//
template <typename T>
MATH_FUNC
inline quaternion<T> operator+(quaternion<T> const& p, quaternion<T> const& q)
{
return quaternion<T>(p.w + q.w, p.x + q.x, p.y + q.y, p.z + q.z);
}
template <typename T>
MATH_FUNC
inline quaternion<T> operator*(quaternion<T> const& p, quaternion<T> const& q)
{
return quaternion<T>(
p.w * q.w - p.x * q.x - p.y * q.y - p.z * q.z,
p.w * q.x + p.x * q.w + p.y * q.z - p.z * q.y,
p.w * q.y - p.x * q.z + p.y * q.w + p.z * q.x,
p.w * q.z + p.x * q.y - p.y * q.x + p.z * q.w
);
}
//--------------------------------------------------------------------------------------------------
// Geometric functions
//
template <typename T>
MATH_FUNC
inline quaternion<T> operator*(quaternion<T> const& p, T const& s)
{
return quaternion<T>(p.w * s, p.x * s, p.y * s, p.z * s);
}
template <typename T>
MATH_FUNC
inline quaternion<T> conjugate(quaternion<T> const& q)
{
return quat(q.w, -q.x, -q.y, -q.z);
}
template <typename T>
MATH_FUNC
inline T dot(quaternion<T> const& p, quaternion<T> const& q)
{
return p.w * q.w + p.x * q.x + p.y * q.y + p.z * q.z;
}
template <typename T>
MATH_FUNC
inline quaternion<T> inverse(quaternion<T> const& q)
{
return conjugate(q) * (T(1.0) / dot(q, q));
}
template <typename T>
MATH_FUNC
inline T length(quaternion<T> const& q)
{
return sqrt(dot(q, q));
}
template <typename T>
MATH_FUNC
inline quaternion<T> normalize(quaternion<T> const& q)
{
return q * (T(1.0) / length(q));
}
template <typename T>
MATH_FUNC
inline quaternion<T> rotation(vector<3, T> const& axis, T const& angle)
{
T s = sin(T(0.5) * angle) / length(axis);
T c = cos(T(0.5) * angle);
return quaternion<T>(c, s * axis[0], s * axis[1], s * axis[2]);
}
template <typename T>
MATH_FUNC
inline matrix<4, 4, T> rotation(quaternion<T> const& q)
{
T xx = q.x * q.x;
T xy = q.x * q.y;
T xz = q.x * q.z;
T xw = q.x * q.w;
T yy = q.y * q.y;
T yz = q.y * q.z;
T yw = q.y * q.w;
T zz = q.z * q.z;
T zw = q.z * q.w;
T ww = q.w * q.w;
matrix<4, 4, T> result;
result(0, 0) = T(2.0) * (ww + xx) - T(1.0);
result(1, 0) = T(2.0) * (xy + zw);
result(2, 0) = T(2.0) * (xz - yw);
result(3, 0) = T(0.0);
result(0, 1) = T(2.0) * (xy - zw);
result(1, 1) = T(2.0) * (ww + yy) - T(1.0);
result(2, 1) = T(2.0) * (yz + xw);
result(3, 1) = T(0.0);
result(0, 2) = T(2.0) * (xz + yw);
result(1, 2) = T(2.0) * (yz - xw);
result(2, 2) = T(2.0) * (ww + zz) - T(1.0);
result(3, 2) = T(0.0);
result(0, 3) = T(0.0);
result(1, 3) = T(0.0);
result(2, 3) = T(0.0);
result(3, 3) = T(1.0);
return result;
}
template <size_t N, size_t M, typename T>
MATH_FUNC
inline quaternion<T> rotation(matrix<N, M, T> const& a)
{
vector<3, T> diag(a(0,0),a(1,1),a(2,2));
T tr = diag.x + diag.y + diag.z + T(1.0);
if (tr > T(1.0))
{
T s = sqrt(tr) * T(2.0);
return quaternion<T>(
T(0.25) * s,
(a(1,2) - a(2,1)) / s,
(a(2,0) - a(0,2)) / s,
(a(0,1) - a(1,0)) / s
);
}
else if (min_index(diag) == 0)
{
T s = sqrt(T(1.0) + diag.x - diag.y - diag.z) * T(2.0);
return quaternion<T>(
(a(1,2) - a(2,1)) / s,
T(0.25) * s,
(a(1,0) - a(0,1)) / s,
(a(2,1) - a(1,2)) / s
);
}
else if (min_index(diag) == 1)
{
T s = sqrt(T(1.0) + diag.y - diag.x - diag.z) *T(2.0);
return quaternion<T>(
(a(2,0) - a(0,2)) / s,
(a(1,0) - a(0,1)) / s,
T(0.25) * s,
(a(2,1) - a(1,2)) / s
);
}
else
{
T s = sqrt(T(1.0) + diag.z - diag.x - diag.y) * T(2.0);
return quaternion<T>(
(a(0,1) - a(1,0)) / s,
(a(2,0) - a(0,2)) / s,
(a(2,1) - a(1,2)) / s,
T(0.25) * s
);
}
}
template <typename T>
MATH_FUNC
inline T rotation_angle(quaternion<T> const& q)
{
return T(2.0) * acos(q.w);
}
template <typename T>
MATH_FUNC
inline vector<3, T> rotation_axis(quaternion<T> const& q)
{
return normalize(vector<3, T>(q.x, q.y, q.z));
}
} // MATH_NAMESPACE
<commit_msg>Revert "Convert rotation matrix to quaternion"<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include "../matrix.h"
#include "math.h"
namespace MATH_NAMESPACE
{
//-------------------------------------------------------------------------------------------------
// quaternion members
//
template <typename T>
MATH_FUNC
inline quaternion<T>::quaternion(T const& w, T const& x, T const& y, T const& z)
: w(w)
, x(x)
, y(y)
, z(z)
{
}
template <typename T>
MATH_FUNC
inline quaternion<T>::quaternion(T const& w, vector<3, T> const& v)
: w(w)
, x(v.x)
, y(v.y)
, z(v.z)
{
}
template <typename T>
MATH_FUNC
inline quaternion<T> quaternion<T>::identity()
{
return quaternion<T>(T(1.0), T(0.0), T(0.0), T(0.0));
}
template <typename T>
MATH_FUNC
inline quaternion<T> quaternion<T>::rotation(vector<3, T> const& from, vector<3, T> const& to)
{
vector<3, T> nfrom = normalize(from);
vector<3, T> nto = normalize(to);
return quaternion<T>(dot(nfrom, nto), cross(nfrom, nto));
}
template <typename T>
MATH_FUNC
inline quaternion<T> quaternion<T>::rotation(T const& yaw, T const& pitch, T const& roll)
{
T cy = cos(yaw * T(0.5));
T sy = sin(yaw * T(0.5));
T cp = cos(pitch * T(0.5));
T sp = sin(pitch * T(0.5));
T cr = cos(roll * T(0.5));
T sr = sin(roll * T(0.5));
return quaternion<T>(
cy * cp * cr + sy * sp * sr,
cy * cp * sr - sy * sp * cr,
sy * cp * sr + cy * sp * cr,
sy * cp * cr - cy * sp * sr
);
}
//--------------------------------------------------------------------------------------------------
// Basic arithmetic
//
template <typename T>
MATH_FUNC
inline quaternion<T> operator+(quaternion<T> const& p, quaternion<T> const& q)
{
return quaternion<T>(p.w + q.w, p.x + q.x, p.y + q.y, p.z + q.z);
}
template <typename T>
MATH_FUNC
inline quaternion<T> operator*(quaternion<T> const& p, quaternion<T> const& q)
{
return quaternion<T>(
p.w * q.w - p.x * q.x - p.y * q.y - p.z * q.z,
p.w * q.x + p.x * q.w + p.y * q.z - p.z * q.y,
p.w * q.y - p.x * q.z + p.y * q.w + p.z * q.x,
p.w * q.z + p.x * q.y - p.y * q.x + p.z * q.w
);
}
//--------------------------------------------------------------------------------------------------
// Geometric functions
//
template <typename T>
MATH_FUNC
inline quaternion<T> operator*(quaternion<T> const& p, T const& s)
{
return quaternion<T>(p.w * s, p.x * s, p.y * s, p.z * s);
}
template <typename T>
MATH_FUNC
inline quaternion<T> conjugate(quaternion<T> const& q)
{
return quat(q.w, -q.x, -q.y, -q.z);
}
template <typename T>
MATH_FUNC
inline T dot(quaternion<T> const& p, quaternion<T> const& q)
{
return p.w * q.w + p.x * q.x + p.y * q.y + p.z * q.z;
}
template <typename T>
MATH_FUNC
inline quaternion<T> inverse(quaternion<T> const& q)
{
return conjugate(q) * (T(1.0) / dot(q, q));
}
template <typename T>
MATH_FUNC
inline T length(quaternion<T> const& q)
{
return sqrt(dot(q, q));
}
template <typename T>
MATH_FUNC
inline quaternion<T> normalize(quaternion<T> const& q)
{
return q * (T(1.0) / length(q));
}
template <typename T>
MATH_FUNC
inline quaternion<T> rotation(vector<3, T> const& axis, T const& angle)
{
T s = sin(T(0.5) * angle) / length(axis);
T c = cos(T(0.5) * angle);
return quaternion<T>(c, s * axis[0], s * axis[1], s * axis[2]);
}
template <typename T>
MATH_FUNC
inline matrix<4, 4, T> rotation(quaternion<T> const& q)
{
T xx = q.x * q.x;
T xy = q.x * q.y;
T xz = q.x * q.z;
T xw = q.x * q.w;
T yy = q.y * q.y;
T yz = q.y * q.z;
T yw = q.y * q.w;
T zz = q.z * q.z;
T zw = q.z * q.w;
T ww = q.w * q.w;
matrix<4, 4, T> result;
result(0, 0) = T(2.0) * (ww + xx) - T(1.0);
result(1, 0) = T(2.0) * (xy + zw);
result(2, 0) = T(2.0) * (xz - yw);
result(3, 0) = T(0.0);
result(0, 1) = T(2.0) * (xy - zw);
result(1, 1) = T(2.0) * (ww + yy) - T(1.0);
result(2, 1) = T(2.0) * (yz + xw);
result(3, 1) = T(0.0);
result(0, 2) = T(2.0) * (xz + yw);
result(1, 2) = T(2.0) * (yz - xw);
result(2, 2) = T(2.0) * (ww + zz) - T(1.0);
result(3, 2) = T(0.0);
result(0, 3) = T(0.0);
result(1, 3) = T(0.0);
result(2, 3) = T(0.0);
result(3, 3) = T(1.0);
return result;
}
template <typename T>
MATH_FUNC
inline T rotation_angle(quaternion<T> const& q)
{
return T(2.0) * acos(q.w);
}
template <typename T>
MATH_FUNC
inline vector<3, T> rotation_axis(quaternion<T> const& q)
{
return normalize(vector<3, T>(q.x, q.y, q.z));
}
} // MATH_NAMESPACE
<|endoftext|> |
<commit_before>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// uncov is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov. If not, see <http://www.gnu.org/licenses/>.
#include "decoration.hpp"
#include <unistd.h>
#include <cstdio>
#include <ostream>
namespace {
class Colors
{
public:
void disable() { isAscii = false; }
const char * bold () { return isAscii ? "\033[1m" : ""; }
const char * inv () { return isAscii ? "\033[7m" : ""; }
const char * def () { return isAscii ? "\033[1m\033[0m" : ""; }
const char * black_fg () { return isAscii ? "\033[30m" : ""; }
const char * red_fg () { return isAscii ? "\033[31m" : ""; }
const char * green_fg () { return isAscii ? "\033[32m" : ""; }
const char * yellow_fg () { return isAscii ? "\033[33m" : ""; }
const char * blue_fg () { return isAscii ? "\033[34m" : ""; }
const char * magenta_fg () { return isAscii ? "\033[35m" : ""; }
const char * cyan_fg () { return isAscii ? "\033[36m" : ""; }
const char * white_fg () { return isAscii ? "\033[37m" : ""; }
const char * black_bg () { return isAscii ? "\033[40m" : ""; }
const char * red_bg () { return isAscii ? "\033[41m" : ""; }
const char * green_bg () { return isAscii ? "\033[42m" : ""; }
const char * yellow_bg () { return isAscii ? "\033[43m" : ""; }
const char * blue_bg () { return isAscii ? "\033[44m" : ""; }
const char * magenta_bg () { return isAscii ? "\033[45m" : ""; }
const char * cyan_bg () { return isAscii ? "\033[46m" : ""; }
const char * white_bg () { return isAscii ? "\033[47m" : ""; }
private:
bool isAscii = isatty(fileno(stdout));
} C;
}
// Shorten type name to fit into 80 columns limit.
using ostr = std::ostream;
using namespace decor;
const Decoration
decor::none,
decor::bold ([](ostr &os) -> ostr & { return os << C.bold(); }),
decor::inv ([](ostr &os) -> ostr & { return os << C.inv(); }),
decor::def ([](ostr &os) -> ostr & { return os << C.def(); }),
decor::black_fg ([](ostr &os) -> ostr & { return os << C.black_fg(); }),
decor::red_fg ([](ostr &os) -> ostr & { return os << C.red_fg(); }),
decor::green_fg ([](ostr &os) -> ostr & { return os << C.green_fg(); }),
decor::yellow_fg ([](ostr &os) -> ostr & { return os << C.yellow_fg(); }),
decor::blue_fg ([](ostr &os) -> ostr & { return os << C.blue_fg(); }),
decor::magenta_fg ([](ostr &os) -> ostr & { return os << C.magenta_fg(); }),
decor::cyan_fg ([](ostr &os) -> ostr & { return os << C.cyan_fg(); }),
decor::white_fg ([](ostr &os) -> ostr & { return os << C.white_fg(); }),
decor::black_bg ([](ostr &os) -> ostr & { return os << C.black_bg(); }),
decor::red_bg ([](ostr &os) -> ostr & { return os << C.red_bg(); }),
decor::green_bg ([](ostr &os) -> ostr & { return os << C.green_bg(); }),
decor::yellow_bg ([](ostr &os) -> ostr & { return os << C.yellow_bg(); }),
decor::blue_bg ([](ostr &os) -> ostr & { return os << C.blue_bg(); }),
decor::magenta_bg ([](ostr &os) -> ostr & { return os << C.magenta_bg(); }),
decor::cyan_bg ([](ostr &os) -> ostr & { return os << C.cyan_bg(); }),
decor::white_bg ([](ostr &os) -> ostr & { return os << C.white_bg(); });
Decoration::Decoration(const Decoration &rhs)
: decorator(rhs.decorator),
lhs(rhs.lhs == nullptr ? nullptr : new Decoration(*rhs.lhs)),
rhs(rhs.rhs == nullptr ? nullptr : new Decoration(*rhs.rhs))
{
}
Decoration::Decoration(decorFunc decorator) : decorator(decorator)
{
}
Decoration::Decoration(const Decoration &lhs, const Decoration &rhs)
: lhs(new Decoration(lhs)),
rhs(new Decoration(rhs))
{
}
std::ostream &
Decoration::decorate(std::ostream &os) const
{
if (decorator != nullptr) {
return os << decorator;
}
if (lhs != nullptr && rhs != nullptr) {
return os << *lhs << *rhs;
}
return os;
}
std::ostream &
ScopedDecoration::decorate(std::ostream &os) const
{
os << decoration;
for (const auto app : apps) {
app(os);
}
os << def;
return os;
}
void
decor::disableDecorations()
{
C.disable();
}
<commit_msg>Preserve field width in decoration unit<commit_after>// Copyright (C) 2016 xaizek <[email protected]>
//
// This file is part of uncov.
//
// uncov is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// uncov is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with uncov. If not, see <http://www.gnu.org/licenses/>.
#include "decoration.hpp"
#include <unistd.h>
#include <cstdio>
#include <ostream>
namespace {
class Colors
{
public:
void disable() { isAscii = false; }
const char * bold () { return isAscii ? "\033[1m" : ""; }
const char * inv () { return isAscii ? "\033[7m" : ""; }
const char * def () { return isAscii ? "\033[1m\033[0m" : ""; }
const char * black_fg () { return isAscii ? "\033[30m" : ""; }
const char * red_fg () { return isAscii ? "\033[31m" : ""; }
const char * green_fg () { return isAscii ? "\033[32m" : ""; }
const char * yellow_fg () { return isAscii ? "\033[33m" : ""; }
const char * blue_fg () { return isAscii ? "\033[34m" : ""; }
const char * magenta_fg () { return isAscii ? "\033[35m" : ""; }
const char * cyan_fg () { return isAscii ? "\033[36m" : ""; }
const char * white_fg () { return isAscii ? "\033[37m" : ""; }
const char * black_bg () { return isAscii ? "\033[40m" : ""; }
const char * red_bg () { return isAscii ? "\033[41m" : ""; }
const char * green_bg () { return isAscii ? "\033[42m" : ""; }
const char * yellow_bg () { return isAscii ? "\033[43m" : ""; }
const char * blue_bg () { return isAscii ? "\033[44m" : ""; }
const char * magenta_bg () { return isAscii ? "\033[45m" : ""; }
const char * cyan_bg () { return isAscii ? "\033[46m" : ""; }
const char * white_bg () { return isAscii ? "\033[47m" : ""; }
private:
bool isAscii = isatty(fileno(stdout));
} C;
}
// Shorten type name to fit into 80 columns limit.
using ostr = std::ostream;
using namespace decor;
const Decoration
decor::none,
decor::bold ([](ostr &os) -> ostr & { return os << C.bold(); }),
decor::inv ([](ostr &os) -> ostr & { return os << C.inv(); }),
decor::def ([](ostr &os) -> ostr & { return os << C.def(); }),
decor::black_fg ([](ostr &os) -> ostr & { return os << C.black_fg(); }),
decor::red_fg ([](ostr &os) -> ostr & { return os << C.red_fg(); }),
decor::green_fg ([](ostr &os) -> ostr & { return os << C.green_fg(); }),
decor::yellow_fg ([](ostr &os) -> ostr & { return os << C.yellow_fg(); }),
decor::blue_fg ([](ostr &os) -> ostr & { return os << C.blue_fg(); }),
decor::magenta_fg ([](ostr &os) -> ostr & { return os << C.magenta_fg(); }),
decor::cyan_fg ([](ostr &os) -> ostr & { return os << C.cyan_fg(); }),
decor::white_fg ([](ostr &os) -> ostr & { return os << C.white_fg(); }),
decor::black_bg ([](ostr &os) -> ostr & { return os << C.black_bg(); }),
decor::red_bg ([](ostr &os) -> ostr & { return os << C.red_bg(); }),
decor::green_bg ([](ostr &os) -> ostr & { return os << C.green_bg(); }),
decor::yellow_bg ([](ostr &os) -> ostr & { return os << C.yellow_bg(); }),
decor::blue_bg ([](ostr &os) -> ostr & { return os << C.blue_bg(); }),
decor::magenta_bg ([](ostr &os) -> ostr & { return os << C.magenta_bg(); }),
decor::cyan_bg ([](ostr &os) -> ostr & { return os << C.cyan_bg(); }),
decor::white_bg ([](ostr &os) -> ostr & { return os << C.white_bg(); });
Decoration::Decoration(const Decoration &rhs)
: decorator(rhs.decorator),
lhs(rhs.lhs == nullptr ? nullptr : new Decoration(*rhs.lhs)),
rhs(rhs.rhs == nullptr ? nullptr : new Decoration(*rhs.rhs))
{
}
Decoration::Decoration(decorFunc decorator) : decorator(decorator)
{
}
Decoration::Decoration(const Decoration &lhs, const Decoration &rhs)
: lhs(new Decoration(lhs)),
rhs(new Decoration(rhs))
{
}
std::ostream &
Decoration::decorate(std::ostream &os) const
{
if (decorator != nullptr) {
const auto width = os.width({});
os << decorator;
static_cast<void>(os.width(width));
return os;
}
if (lhs != nullptr && rhs != nullptr) {
return os << *lhs << *rhs;
}
return os;
}
std::ostream &
ScopedDecoration::decorate(std::ostream &os) const
{
os << decoration;
for (const auto app : apps) {
app(os);
}
os << def;
return os;
}
void
decor::disableDecorations()
{
C.disable();
}
<|endoftext|> |
<commit_before>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
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 "mitkOclResourceServiceImpl_p.h"
OclResourceService::~OclResourceService()
{
}
OclResourceServiceImpl::OclResourceServiceImpl()
: m_ContextCollection(NULL), m_ProgramStorage()
{
}
OclResourceServiceImpl::~OclResourceServiceImpl()
{
// if map non-empty, release all remaining
if( m_ProgramStorage.size() )
{
ProgramMapType::iterator it = m_ProgramStorage.begin();
while(it != m_ProgramStorage.end() )
{
clReleaseProgram( it->second.program );
m_ProgramStorage.erase( it++ );
}
}
if( m_ContextCollection )
delete m_ContextCollection;
}
cl_context OclResourceServiceImpl::GetContext() const
{
if( m_ContextCollection == NULL )
{
m_ContextCollection = new OclContextCollection();
}
else if( !m_ContextCollection->CanProvideContext() )
{
return NULL;
}
return m_ContextCollection->m_Context;
}
cl_command_queue OclResourceServiceImpl::GetCommandQueue() const
{
// check if queue valid
cl_context clQueueContext;
cl_int clErr = clGetCommandQueueInfo( m_ContextCollection->m_CommandQueue, CL_QUEUE_CONTEXT, sizeof(clQueueContext), &clQueueContext, NULL );
if( clErr != CL_SUCCESS || clQueueContext != m_ContextCollection->m_Context )
{
MITK_WARN << "Have no valid command queue. Query returned : " << GetOclErrorAsString( clErr );
return NULL;
}
return m_ContextCollection->m_CommandQueue;
}
cl_device_id OclResourceServiceImpl::GetCurrentDevice() const
{
return m_ContextCollection->m_Devices[0];
}
bool OclResourceServiceImpl::GetIsFormatSupported(cl_image_format *fmt)
{
cl_image_format temp;
temp.image_channel_data_type = fmt->image_channel_data_type;
temp.image_channel_order = fmt->image_channel_order;
return (this->m_ContextCollection->m_ImageFormats->GetNearestSupported(&temp, fmt));
}
void OclResourceServiceImpl::PrintContextInfo() const
{
// context and devices available
if( m_ContextCollection->CanProvideContext() )
{
oclPrintDeviceInfo( m_ContextCollection->m_Devices[0] );
}
}
void OclResourceServiceImpl::InsertProgram(cl_program _program_in, std::string name, bool forceOverride)
{
typedef std::pair < std::string, ProgramData > MapElemPair;
std::pair< ProgramMapType::iterator, bool> retValue;
ProgramData data;
data.counter = 1;
data.program = _program_in;
// program is not stored, insert first instance (count = 1)
m_ProgramStorageMutex.Lock();
retValue = m_ProgramStorage.insert( MapElemPair(name, data) );
m_ProgramStorageMutex.Unlock();
// insertion failed, i.e. a program with same name exists
if( !retValue.second )
{
std::string overrideMsg("");
if( forceOverride )
{
// overwrite old instance
m_ProgramStorage[name].program = _program_in;
overrideMsg +=" The old program was overwritten!";
}
MITK_WARN("OpenCL.ResourceService") << "The program " << name << " already exists." << overrideMsg;
}
}
cl_program OclResourceServiceImpl::GetProgram(const std::string &name)
{
ProgramMapType::iterator it = m_ProgramStorage.find(name);
if( it != m_ProgramStorage.end() )
{
it->second.mutex.Lock();
// first check if the program was deleted
// while waiting on the mutex
if ( it->second.counter == 0 )
mitkThrow() << "Requested OpenCL Program (" << name <<") not found."
<< "(deleted while waiting on the mutex)";
// increase the reference counter
// by one if the program is requestet
it->second.counter += 1;
it->second.mutex.Unlock();
// return the cl_program
return it->second.program;
}
mitkThrow() << "Requested OpenCL Program (" << name <<") not found.";
}
void OclResourceServiceImpl::InvalidateStorage()
{
// do nothing if no context present, there is also no storage
if( !m_ContextCollection->CanProvideContext() )
return;
// query the map
ProgramMapType::iterator it = m_ProgramStorage.begin();
while(it != m_ProgramStorage.end() )
{
// query the program build status
cl_build_status status;
unsigned int query = clGetProgramBuildInfo( it->second.program, m_ContextCollection->m_Devices[0], CL_PROGRAM_BUILD_STATUS, sizeof(cl_int), &status, NULL );
CHECK_OCL_ERR( query )
MITK_DEBUG << "Quering status for " << it->first << std::endl;
// remove program if no succesfull build
// we need to pay attention to the increment of the iterator when erasing current element
if( status != CL_BUILD_SUCCESS )
{
MITK_DEBUG << " +-- Build failed " << std::endl;
m_ProgramStorage.erase( it++ );
}
else
{
++it;
}
}
}
void OclResourceServiceImpl::RemoveProgram(const std::string& name)
{
ProgramMapType::iterator it = m_ProgramStorage.find(name);
cl_int status = 0;
cl_program program = NULL;
if( it != m_ProgramStorage.end() )
{
it->second.mutex.Lock();
// decrease reference by one
it->second.counter -= 1;
it->second.mutex.Unlock();
// remove from the storage
if( it->second.counter == 0 )
{
program = it->second.program;
m_ProgramStorageMutex.Lock();
m_ProgramStorage.erase(it);
m_ProgramStorageMutex.Unlock();
}
// delete the program
if( program )
{
status = clReleaseProgram(program);
CHECK_OCL_ERR( status );
}
}
else
{
MITK_WARN("OpenCL.ResourceService") << "Program name [" <<name <<"] passed for deletion not found.";
}
}
unsigned int OclResourceServiceImpl::GetMaximumImageSize(unsigned int dimension, cl_mem_object_type _imagetype)
{
if( ! m_ContextCollection->CanProvideContext() )
return 0;
unsigned int retValue = 0;
switch(dimension)
{
case 0:
if ( _imagetype == CL_MEM_OBJECT_IMAGE2D)
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof( cl_uint ), &retValue, NULL );
else
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof( cl_uint ), &retValue, NULL );
break;
case 1:
if ( _imagetype == CL_MEM_OBJECT_IMAGE2D)
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof( cl_uint ), &retValue, NULL );
else
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof( cl_uint ), &retValue, NULL );
break;
case 2:
if ( _imagetype == CL_MEM_OBJECT_IMAGE3D)
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof( cl_uint ), &retValue, NULL);
break;
default:
MITK_WARN << "Could not recieve info. Desired dimension or object type does not exist. ";
break;
}
return retValue;
}
<commit_msg>check if there is an opencl context collection and create one to prevent to create a command queue without a context<commit_after>/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
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 "mitkOclResourceServiceImpl_p.h"
OclResourceService::~OclResourceService()
{
}
OclResourceServiceImpl::OclResourceServiceImpl()
: m_ContextCollection(NULL), m_ProgramStorage()
{
}
OclResourceServiceImpl::~OclResourceServiceImpl()
{
// if map non-empty, release all remaining
if( m_ProgramStorage.size() )
{
ProgramMapType::iterator it = m_ProgramStorage.begin();
while(it != m_ProgramStorage.end() )
{
clReleaseProgram( it->second.program );
m_ProgramStorage.erase( it++ );
}
}
if( m_ContextCollection )
delete m_ContextCollection;
}
cl_context OclResourceServiceImpl::GetContext() const
{
if( m_ContextCollection == NULL )
{
m_ContextCollection = new OclContextCollection();
}
else if( !m_ContextCollection->CanProvideContext() )
{
return NULL;
}
return m_ContextCollection->m_Context;
}
cl_command_queue OclResourceServiceImpl::GetCommandQueue() const
{
// check if queue valid
cl_context clQueueContext;
// check if there is a context available
// if not create one
if( ! m_ContextCollection )
{
m_ContextCollection = new OclContextCollection();
}
cl_int clErr = clGetCommandQueueInfo( m_ContextCollection->m_CommandQueue, CL_QUEUE_CONTEXT, sizeof(clQueueContext), &clQueueContext, NULL );
if( clErr != CL_SUCCESS || clQueueContext != m_ContextCollection->m_Context )
{
MITK_WARN << "Have no valid command queue. Query returned : " << GetOclErrorAsString( clErr );
return NULL;
}
return m_ContextCollection->m_CommandQueue;
}
cl_device_id OclResourceServiceImpl::GetCurrentDevice() const
{
return m_ContextCollection->m_Devices[0];
}
bool OclResourceServiceImpl::GetIsFormatSupported(cl_image_format *fmt)
{
cl_image_format temp;
temp.image_channel_data_type = fmt->image_channel_data_type;
temp.image_channel_order = fmt->image_channel_order;
return (this->m_ContextCollection->m_ImageFormats->GetNearestSupported(&temp, fmt));
}
void OclResourceServiceImpl::PrintContextInfo() const
{
// context and devices available
if( m_ContextCollection->CanProvideContext() )
{
oclPrintDeviceInfo( m_ContextCollection->m_Devices[0] );
}
}
void OclResourceServiceImpl::InsertProgram(cl_program _program_in, std::string name, bool forceOverride)
{
typedef std::pair < std::string, ProgramData > MapElemPair;
std::pair< ProgramMapType::iterator, bool> retValue;
ProgramData data;
data.counter = 1;
data.program = _program_in;
// program is not stored, insert first instance (count = 1)
m_ProgramStorageMutex.Lock();
retValue = m_ProgramStorage.insert( MapElemPair(name, data) );
m_ProgramStorageMutex.Unlock();
// insertion failed, i.e. a program with same name exists
if( !retValue.second )
{
std::string overrideMsg("");
if( forceOverride )
{
// overwrite old instance
m_ProgramStorage[name].program = _program_in;
overrideMsg +=" The old program was overwritten!";
}
MITK_WARN("OpenCL.ResourceService") << "The program " << name << " already exists." << overrideMsg;
}
}
cl_program OclResourceServiceImpl::GetProgram(const std::string &name)
{
ProgramMapType::iterator it = m_ProgramStorage.find(name);
if( it != m_ProgramStorage.end() )
{
it->second.mutex.Lock();
// first check if the program was deleted
// while waiting on the mutex
if ( it->second.counter == 0 )
mitkThrow() << "Requested OpenCL Program (" << name <<") not found."
<< "(deleted while waiting on the mutex)";
// increase the reference counter
// by one if the program is requestet
it->second.counter += 1;
it->second.mutex.Unlock();
// return the cl_program
return it->second.program;
}
mitkThrow() << "Requested OpenCL Program (" << name <<") not found.";
}
void OclResourceServiceImpl::InvalidateStorage()
{
// do nothing if no context present, there is also no storage
if( !m_ContextCollection->CanProvideContext() )
return;
// query the map
ProgramMapType::iterator it = m_ProgramStorage.begin();
while(it != m_ProgramStorage.end() )
{
// query the program build status
cl_build_status status;
unsigned int query = clGetProgramBuildInfo( it->second.program, m_ContextCollection->m_Devices[0], CL_PROGRAM_BUILD_STATUS, sizeof(cl_int), &status, NULL );
CHECK_OCL_ERR( query )
MITK_DEBUG << "Quering status for " << it->first << std::endl;
// remove program if no succesfull build
// we need to pay attention to the increment of the iterator when erasing current element
if( status != CL_BUILD_SUCCESS )
{
MITK_DEBUG << " +-- Build failed " << std::endl;
m_ProgramStorage.erase( it++ );
}
else
{
++it;
}
}
}
void OclResourceServiceImpl::RemoveProgram(const std::string& name)
{
ProgramMapType::iterator it = m_ProgramStorage.find(name);
cl_int status = 0;
cl_program program = NULL;
if( it != m_ProgramStorage.end() )
{
it->second.mutex.Lock();
// decrease reference by one
it->second.counter -= 1;
it->second.mutex.Unlock();
// remove from the storage
if( it->second.counter == 0 )
{
program = it->second.program;
m_ProgramStorageMutex.Lock();
m_ProgramStorage.erase(it);
m_ProgramStorageMutex.Unlock();
}
// delete the program
if( program )
{
status = clReleaseProgram(program);
CHECK_OCL_ERR( status );
}
}
else
{
MITK_WARN("OpenCL.ResourceService") << "Program name [" <<name <<"] passed for deletion not found.";
}
}
unsigned int OclResourceServiceImpl::GetMaximumImageSize(unsigned int dimension, cl_mem_object_type _imagetype)
{
if( ! m_ContextCollection->CanProvideContext() )
return 0;
unsigned int retValue = 0;
switch(dimension)
{
case 0:
if ( _imagetype == CL_MEM_OBJECT_IMAGE2D)
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof( cl_uint ), &retValue, NULL );
else
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof( cl_uint ), &retValue, NULL );
break;
case 1:
if ( _imagetype == CL_MEM_OBJECT_IMAGE2D)
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof( cl_uint ), &retValue, NULL );
else
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof( cl_uint ), &retValue, NULL );
break;
case 2:
if ( _imagetype == CL_MEM_OBJECT_IMAGE3D)
clGetDeviceInfo( m_ContextCollection->m_Devices[0], CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof( cl_uint ), &retValue, NULL);
break;
default:
MITK_WARN << "Could not recieve info. Desired dimension or object type does not exist. ";
break;
}
return retValue;
}
<|endoftext|> |
<commit_before>
#include "CCPACSPointListXYZ.h"
namespace tigl
{
void CCPACSPointListXYZ::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string &xpath)
{
generated::CPACSPointListXYZVector::ReadCPACS(tixiHandle, xpath);
// create cached representation from CPACS fields
const std::vector<double>& xs = m_x.AsVector();
const std::vector<double>& ys = m_y.AsVector();
const std::vector<double>& zs = m_z.AsVector();
if (xs.size() != ys.size() || ys.size() != zs.size()) {
throw std::runtime_error("component vectors in CCPACSPointListXYZ must all have the same number of elements");
}
m_vec.clear();
for (std::size_t i = 0; i < xs.size(); i++) {
m_vec.push_back(CTiglPoint(xs[i], ys[i], zs[i]));
}
}
void CCPACSPointListXYZ::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const
{
// write back to CPACS fields
CCPACSPointListXYZ* self = const_cast<CCPACSPointListXYZ*>(this); // TODO: ugly hack, but WriteCPACS() has to be const, fix this
std::vector<double>& xs = self->m_x.AsVector();
std::vector<double>& ys = self->m_y.AsVector();
std::vector<double>& zs = self->m_z.AsVector();
xs.clear();
ys.clear();
zs.clear();
for (std::vector<CTiglPoint>::const_iterator it = m_vec.begin(); it != m_vec.end(); ++it) {
xs.push_back(it->x);
ys.push_back(it->y);
zs.push_back(it->z);
}
generated::CPACSPointListXYZVector::WriteCPACS(tixiHandle, xpath);
}
const std::vector<CTiglPoint>& CCPACSPointListXYZ::AsVector() const
{
return m_vec;
}
std::vector<CTiglPoint>& CCPACSPointListXYZ::AsVector()
{
return m_vec;
}
}
<commit_msg>added missing include<commit_after>#include "CCPACSPointListXYZ.h"
#include <stdexcept>
namespace tigl
{
void CCPACSPointListXYZ::ReadCPACS(const TixiDocumentHandle& tixiHandle, const std::string &xpath)
{
generated::CPACSPointListXYZVector::ReadCPACS(tixiHandle, xpath);
// create cached representation from CPACS fields
const std::vector<double>& xs = m_x.AsVector();
const std::vector<double>& ys = m_y.AsVector();
const std::vector<double>& zs = m_z.AsVector();
if (xs.size() != ys.size() || ys.size() != zs.size()) {
throw std::runtime_error("component vectors in CCPACSPointListXYZ must all have the same number of elements");
}
m_vec.clear();
for (std::size_t i = 0; i < xs.size(); i++) {
m_vec.push_back(CTiglPoint(xs[i], ys[i], zs[i]));
}
}
void CCPACSPointListXYZ::WriteCPACS(const TixiDocumentHandle& tixiHandle, const std::string& xpath) const
{
// write back to CPACS fields
CCPACSPointListXYZ* self = const_cast<CCPACSPointListXYZ*>(this); // TODO: ugly hack, but WriteCPACS() has to be const, fix this
std::vector<double>& xs = self->m_x.AsVector();
std::vector<double>& ys = self->m_y.AsVector();
std::vector<double>& zs = self->m_z.AsVector();
xs.clear();
ys.clear();
zs.clear();
for (std::vector<CTiglPoint>::const_iterator it = m_vec.begin(); it != m_vec.end(); ++it) {
xs.push_back(it->x);
ys.push_back(it->y);
zs.push_back(it->z);
}
generated::CPACSPointListXYZVector::WriteCPACS(tixiHandle, xpath);
}
const std::vector<CTiglPoint>& CCPACSPointListXYZ::AsVector() const
{
return m_vec;
}
std::vector<CTiglPoint>& CCPACSPointListXYZ::AsVector()
{
return m_vec;
}
}
<|endoftext|> |
<commit_before>#ifndef _SWAP_SCHEDULING_
#define _SWAP_SCHEDULING_
#include <vector>
#include "../VoltageTable.hpp"
#include "../nnet/nnetmultitask.hpp"
#include "../TaskHandoff.hpp"
class SwapScheduling {
public:
void buildTaskTable(char *filename);
void buildSolarPowerTrace();
std::vector<double> generateChargeTrace();
int compareTwoTasks(size_t i);
void exhaustiveSwapping();
void genScheduleForEES(std::string ees, std::string dp) const;
private:
std::vector<TaskVoltageTable> realTaskVoltageTable;
std::vector<double> solarPowerTrace;
std::vector<double> taskPowerTrace;
nnetmultitask nnetPredictor;
std::vector<double> taskToPowerTrace(const TaskVoltageTable &tvt) const;
std::vector<double> extractSolarPowerInterval(size_t i) const;
std::vector<double> extractTaskPowerInterval(size_t i, size_t j) const;
double predictTwoTasksEnergyInterval(const vector<double> &solarPowerInterval, size_t i, size_t j);
void addDCDCPower(vector<double> &powerTrace) const;
double predictPowerInterval(const vector<double> &chargeTrace);
};
#endif
<commit_msg>Updates SwapScheduling.hpp<commit_after>#ifndef _SWAP_SCHEDULING_
#define _SWAP_SCHEDULING_
#include <vector>
#include "../VoltageTable.hpp"
#include "../nnet/nnetmultitask.hpp"
#include "../TaskHandoff.hpp"
class SwapScheduling {
public:
void buildTaskTable(char *filename);
void buildSolarPowerTrace();
std::vector<double> generateChargeTrace();
int compareTwoTasks(size_t i);
void exhaustiveSwapping();
void genScheduleForEES(std::string ees, std::string dp) const;
/**
* @return The number of tasks in this task set
*/
int getTaskNumber() const { return realTaskVoltageTable.size(); }
private:
std::vector<TaskVoltageTable> realTaskVoltageTable;
std::vector<double> solarPowerTrace;
std::vector<double> taskPowerTrace;
nnetmultitask nnetPredictor;
std::vector<double> taskToPowerTrace(const TaskVoltageTable &tvt) const;
std::vector<double> extractSolarPowerInterval(size_t i) const;
std::vector<double> extractTaskPowerInterval(size_t i, size_t j) const;
double predictTwoTasksEnergyInterval(const vector<double> &solarPowerInterval, size_t i, size_t j);
void addDCDCPower(vector<double> &powerTrace) const;
double predictPowerInterval(const vector<double> &chargeTrace);
};
#endif
<|endoftext|> |
<commit_before>// StlSolid.cpp
#include "stdafx.h"
#include "StlSolid.h"
#include "../tinyxml/tinyxml.h"
#include <fstream>
using namespace std;
CStlSolid::CStlSolid(const HeeksColor* col):color(*col), m_gl_list(0){
m_title.assign(GetTypeString());
}
CStlSolid::CStlSolid(const wxChar* filepath, const HeeksColor* col):color(*col), m_gl_list(0){
// read the stl file
ifstream ifs(filepath, ios::binary);
if(!ifs)return;
char solid_string[6] = "aaaaa";
ifs.read(solid_string, 5);
if(ifs.eof())return;
if(strcmp(solid_string, "solid"))
{
// try binary file read
// read the header
char header[81];
header[80] = 0;
memcpy(header, solid_string, 5);
ifs.read(&header[5], 75);
unsigned int num_facets = 0;
ifs.read((char*)(&num_facets), 4);
ofstream tof("trilist.txt");
for(unsigned int i = 0; i<num_facets; i++)
{
CStlTri tri;
ifs.read((char*)(tri.n), 12);
ifs.read((char*)(tri.x[0]), 36);
short attr;
ifs.read((char*)(&attr), 2);
m_list.push_back(tri);
char str[1024];
sprintf(str, "%d - %lf %lf %lf %lf %lf %lf %lf %lf %lf\n", i, tri.x[0][0], tri.x[0][1], tri.x[0][2], tri.x[1][0], tri.x[1][1], tri.x[1][2], tri.x[2][0], tri.x[2][1], tri.x[2][2]);
tof<<str;
}
}
else
{
// "solid" already found
char str[1024] = "solid";
ifs.getline(&str[5], 1024);
char title[1024];
if(sscanf(str, "solid %s", title) == 1)
m_title.assign(Ctt(title));
CStlTri t;
char five_chars[6] = "aaaaa";
int vertex = 0;
while(!ifs.eof())
{
ifs.getline(str, 1024);
int i = 0, j = 0;
for(; i<5; i++, j++)
{
if(str[j] == 0)break;
while(str[j] == ' ' || str[j] == '\t')j++;
five_chars[i] = str[j];
}
if(i == 5)
{
if(!strcmp(five_chars, "verte"))
{
sscanf(str, " vertex %f %f %f", &(t.x[vertex][0]), &(t.x[vertex][1]), &(t.x[vertex][2]));
vertex++;
if(vertex > 2)vertex = 2;
}
else if(!strcmp(five_chars, "facet"))
{
sscanf(str, " facet normal %f %f %f", &(t.n[0]), &(t.n[1]), &(t.n[2]));
vertex = 0;
}
else if(!strcmp(five_chars, "endfa"))
{
if(vertex == 2)
{
m_list.push_back(t);
}
}
}
}
}
}
CStlSolid::~CStlSolid(){
KillGLLists();
}
const CStlSolid& CStlSolid::operator=(const CStlSolid& s)
{
// don't copy id
m_box = s.m_box;
m_title = s.m_title;
KillGLLists();
return *this;
}
void CStlSolid::KillGLLists()
{
if (m_gl_list)
{
glDeleteLists(m_gl_list, 1);
m_gl_list = 0;
m_box = CBox();
}
}
void CStlSolid::glCommands(bool select, bool marked, bool no_color){
glEnable(GL_LIGHTING);
if(m_gl_list)
{
glCallList(m_gl_list);
}
else{
m_gl_list = glGenLists(1);
glNewList(m_gl_list, GL_COMPILE_AND_EXECUTE);
// to do , render all the triangles
glBegin(GL_TRIANGLES);
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
glNormal3fv(t.n);
glVertex3fv(t.x[0]);
glVertex3fv(t.x[1]);
glVertex3fv(t.x[2]);
}
glEnd();
glEndList();
}
glDisable(GL_LIGHTING);
}
void CStlSolid::GetBox(CBox &box){
if(!m_box.m_valid)
{
// calculate the box for all the triangles
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
m_box.Insert(t.x[0][0], t.x[0][1], t.x[0][2]);
m_box.Insert(t.x[1][0], t.x[1][1], t.x[1][2]);
m_box.Insert(t.x[2][0], t.x[2][1], t.x[2][2]);
}
}
box.Insert(m_box);
}
bool CStlSolid::ModifyByMatrix(const double* m){
gp_Trsf mat = make_matrix(m);
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
gp_Vec vn(t.n[0], t.n[1], t.n[2]);
vn.Transform(mat);
t.n[0] = (float)vn.X();
t.n[1] = (float)vn.Y();
t.n[2] = (float)vn.Z();
for(int i = 0; i<3; i++){
gp_Pnt vx;
vx = gp_Pnt(t.x[i][0], t.x[i][1], t.x[i][2]);
vx.Transform(mat);
t.x[i][0] = (float)vx.X();
t.x[i][1] = (float)vx.Y();
t.x[i][2] = (float)vx.Z();
}
}
KillGLLists();
return false;
}
HeeksObj *CStlSolid::MakeACopy(void)const{
CStlSolid *new_object = new CStlSolid(*this);
return new_object;
}
void CStlSolid::CopyFrom(const HeeksObj* object)
{
operator=(*((CStlSolid*)object));
}
void CStlSolid::OnEditString(const wxChar* str){
m_title.assign(str);
wxGetApp().WasModified(this);
}
void CStlSolid::GetTriangles(void(*callbackfunc)(const double* x, const double* n), double cusp, bool just_one_average_normal){
double x[9];
double n[9];
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
x[0] = t.x[0][0];
x[1] = t.x[0][1];
x[2] = t.x[0][2];
x[3] = t.x[1][0];
x[4] = t.x[1][1];
x[5] = t.x[1][2];
x[6] = t.x[2][0];
x[7] = t.x[2][1];
x[8] = t.x[2][2];
n[0] = t.n[0];
n[1] = t.n[1];
n[2] = t.n[2];
if(!just_one_average_normal)
{
n[3] = t.n[0];
n[4] = t.n[1];
n[5] = t.n[2];
n[6] = t.n[0];
n[7] = t.n[1];
n[8] = t.n[2];
}
(*callbackfunc)(x, n);
}
}
void CStlSolid::WriteXML(TiXmlElement *root)
{
TiXmlElement * element;
element = new TiXmlElement( "STLSolid" );
root->LinkEndChild( element );
element->SetAttribute("col", color.COLORREF_color());
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
TiXmlElement * child_element;
child_element = new TiXmlElement( "tri" );
element->LinkEndChild( child_element );
child_element->SetDoubleAttribute("nx", t.n[0]);
child_element->SetDoubleAttribute("ny", t.n[1]);
child_element->SetDoubleAttribute("nz", t.n[2]);
child_element->SetDoubleAttribute("p1x", t.x[0][0]);
child_element->SetDoubleAttribute("p1y", t.x[0][1]);
child_element->SetDoubleAttribute("p1z", t.x[0][2]);
child_element->SetDoubleAttribute("p2x", t.x[1][0]);
child_element->SetDoubleAttribute("p2y", t.x[1][1]);
child_element->SetDoubleAttribute("p2z", t.x[1][2]);
child_element->SetDoubleAttribute("p3x", t.x[2][0]);
child_element->SetDoubleAttribute("p3y", t.x[2][1]);
child_element->SetDoubleAttribute("p3z", t.x[2][2]);
}
WriteBaseXML(element);
}
// static member function
HeeksObj* CStlSolid::ReadFromXMLElement(TiXmlElement* pElem)
{
HeeksColor c;
CStlTri t;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "col"){c = HeeksColor(a->IntValue());}
}
CStlSolid* new_object = new CStlSolid(&c);
// loop through all the "tri" objects
for(TiXmlElement* pTriElem = TiXmlHandle(pElem).FirstChildElement().Element(); pTriElem; pTriElem = pTriElem->NextSiblingElement())
{
// get the attributes
for(TiXmlAttribute* a = pTriElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "nx"){t.n[0] = (float)a->DoubleValue();}
else if(name == "ny"){t.n[1] = (float)a->DoubleValue();}
else if(name == "nz"){t.n[2] = (float)a->DoubleValue();}
else if(name == "p1x"){t.x[0][0] = (float)a->DoubleValue();}
else if(name == "p1y"){t.x[0][1] = (float)a->DoubleValue();}
else if(name == "p1z"){t.x[0][2] = (float)a->DoubleValue();}
else if(name == "p2x"){t.x[1][0] = (float)a->DoubleValue();}
else if(name == "p2y"){t.x[1][1] = (float)a->DoubleValue();}
else if(name == "p2z"){t.x[1][2] = (float)a->DoubleValue();}
else if(name == "p3x"){t.x[2][0] = (float)a->DoubleValue();}
else if(name == "p3y"){t.x[2][1] = (float)a->DoubleValue();}
else if(name == "p3z"){t.x[2][2] = (float)a->DoubleValue();}
}
new_object->m_list.push_back(t);
}
new_object->ReadBaseXML(pElem);
return new_object;
}
<commit_msg>oops, I had accidentally left in some code to write a log file<commit_after>// StlSolid.cpp
#include "stdafx.h"
#include "StlSolid.h"
#include "../tinyxml/tinyxml.h"
#include <fstream>
using namespace std;
CStlSolid::CStlSolid(const HeeksColor* col):color(*col), m_gl_list(0){
m_title.assign(GetTypeString());
}
CStlSolid::CStlSolid(const wxChar* filepath, const HeeksColor* col):color(*col), m_gl_list(0){
// read the stl file
ifstream ifs(filepath, ios::binary);
if(!ifs)return;
char solid_string[6] = "aaaaa";
ifs.read(solid_string, 5);
if(ifs.eof())return;
if(strcmp(solid_string, "solid"))
{
// try binary file read
// read the header
char header[81];
header[80] = 0;
memcpy(header, solid_string, 5);
ifs.read(&header[5], 75);
unsigned int num_facets = 0;
ifs.read((char*)(&num_facets), 4);
for(unsigned int i = 0; i<num_facets; i++)
{
CStlTri tri;
ifs.read((char*)(tri.n), 12);
ifs.read((char*)(tri.x[0]), 36);
short attr;
ifs.read((char*)(&attr), 2);
m_list.push_back(tri);
}
}
else
{
// "solid" already found
char str[1024] = "solid";
ifs.getline(&str[5], 1024);
char title[1024];
if(sscanf(str, "solid %s", title) == 1)
m_title.assign(Ctt(title));
CStlTri t;
char five_chars[6] = "aaaaa";
int vertex = 0;
while(!ifs.eof())
{
ifs.getline(str, 1024);
int i = 0, j = 0;
for(; i<5; i++, j++)
{
if(str[j] == 0)break;
while(str[j] == ' ' || str[j] == '\t')j++;
five_chars[i] = str[j];
}
if(i == 5)
{
if(!strcmp(five_chars, "verte"))
{
sscanf(str, " vertex %f %f %f", &(t.x[vertex][0]), &(t.x[vertex][1]), &(t.x[vertex][2]));
vertex++;
if(vertex > 2)vertex = 2;
}
else if(!strcmp(five_chars, "facet"))
{
sscanf(str, " facet normal %f %f %f", &(t.n[0]), &(t.n[1]), &(t.n[2]));
vertex = 0;
}
else if(!strcmp(five_chars, "endfa"))
{
if(vertex == 2)
{
m_list.push_back(t);
}
}
}
}
}
}
CStlSolid::~CStlSolid(){
KillGLLists();
}
const CStlSolid& CStlSolid::operator=(const CStlSolid& s)
{
// don't copy id
m_box = s.m_box;
m_title = s.m_title;
KillGLLists();
return *this;
}
void CStlSolid::KillGLLists()
{
if (m_gl_list)
{
glDeleteLists(m_gl_list, 1);
m_gl_list = 0;
m_box = CBox();
}
}
void CStlSolid::glCommands(bool select, bool marked, bool no_color){
glEnable(GL_LIGHTING);
if(m_gl_list)
{
glCallList(m_gl_list);
}
else{
m_gl_list = glGenLists(1);
glNewList(m_gl_list, GL_COMPILE_AND_EXECUTE);
// to do , render all the triangles
glBegin(GL_TRIANGLES);
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
glNormal3fv(t.n);
glVertex3fv(t.x[0]);
glVertex3fv(t.x[1]);
glVertex3fv(t.x[2]);
}
glEnd();
glEndList();
}
glDisable(GL_LIGHTING);
}
void CStlSolid::GetBox(CBox &box){
if(!m_box.m_valid)
{
// calculate the box for all the triangles
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
m_box.Insert(t.x[0][0], t.x[0][1], t.x[0][2]);
m_box.Insert(t.x[1][0], t.x[1][1], t.x[1][2]);
m_box.Insert(t.x[2][0], t.x[2][1], t.x[2][2]);
}
}
box.Insert(m_box);
}
bool CStlSolid::ModifyByMatrix(const double* m){
gp_Trsf mat = make_matrix(m);
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
gp_Vec vn(t.n[0], t.n[1], t.n[2]);
vn.Transform(mat);
t.n[0] = (float)vn.X();
t.n[1] = (float)vn.Y();
t.n[2] = (float)vn.Z();
for(int i = 0; i<3; i++){
gp_Pnt vx;
vx = gp_Pnt(t.x[i][0], t.x[i][1], t.x[i][2]);
vx.Transform(mat);
t.x[i][0] = (float)vx.X();
t.x[i][1] = (float)vx.Y();
t.x[i][2] = (float)vx.Z();
}
}
KillGLLists();
return false;
}
HeeksObj *CStlSolid::MakeACopy(void)const{
CStlSolid *new_object = new CStlSolid(*this);
return new_object;
}
void CStlSolid::CopyFrom(const HeeksObj* object)
{
operator=(*((CStlSolid*)object));
}
void CStlSolid::OnEditString(const wxChar* str){
m_title.assign(str);
wxGetApp().WasModified(this);
}
void CStlSolid::GetTriangles(void(*callbackfunc)(const double* x, const double* n), double cusp, bool just_one_average_normal){
double x[9];
double n[9];
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
x[0] = t.x[0][0];
x[1] = t.x[0][1];
x[2] = t.x[0][2];
x[3] = t.x[1][0];
x[4] = t.x[1][1];
x[5] = t.x[1][2];
x[6] = t.x[2][0];
x[7] = t.x[2][1];
x[8] = t.x[2][2];
n[0] = t.n[0];
n[1] = t.n[1];
n[2] = t.n[2];
if(!just_one_average_normal)
{
n[3] = t.n[0];
n[4] = t.n[1];
n[5] = t.n[2];
n[6] = t.n[0];
n[7] = t.n[1];
n[8] = t.n[2];
}
(*callbackfunc)(x, n);
}
}
void CStlSolid::WriteXML(TiXmlElement *root)
{
TiXmlElement * element;
element = new TiXmlElement( "STLSolid" );
root->LinkEndChild( element );
element->SetAttribute("col", color.COLORREF_color());
for(std::list<CStlTri>::iterator It = m_list.begin(); It != m_list.end(); It++)
{
CStlTri &t = *It;
TiXmlElement * child_element;
child_element = new TiXmlElement( "tri" );
element->LinkEndChild( child_element );
child_element->SetDoubleAttribute("nx", t.n[0]);
child_element->SetDoubleAttribute("ny", t.n[1]);
child_element->SetDoubleAttribute("nz", t.n[2]);
child_element->SetDoubleAttribute("p1x", t.x[0][0]);
child_element->SetDoubleAttribute("p1y", t.x[0][1]);
child_element->SetDoubleAttribute("p1z", t.x[0][2]);
child_element->SetDoubleAttribute("p2x", t.x[1][0]);
child_element->SetDoubleAttribute("p2y", t.x[1][1]);
child_element->SetDoubleAttribute("p2z", t.x[1][2]);
child_element->SetDoubleAttribute("p3x", t.x[2][0]);
child_element->SetDoubleAttribute("p3y", t.x[2][1]);
child_element->SetDoubleAttribute("p3z", t.x[2][2]);
}
WriteBaseXML(element);
}
// static member function
HeeksObj* CStlSolid::ReadFromXMLElement(TiXmlElement* pElem)
{
HeeksColor c;
CStlTri t;
// get the attributes
for(TiXmlAttribute* a = pElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "col"){c = HeeksColor(a->IntValue());}
}
CStlSolid* new_object = new CStlSolid(&c);
// loop through all the "tri" objects
for(TiXmlElement* pTriElem = TiXmlHandle(pElem).FirstChildElement().Element(); pTriElem; pTriElem = pTriElem->NextSiblingElement())
{
// get the attributes
for(TiXmlAttribute* a = pTriElem->FirstAttribute(); a; a = a->Next())
{
std::string name(a->Name());
if(name == "nx"){t.n[0] = (float)a->DoubleValue();}
else if(name == "ny"){t.n[1] = (float)a->DoubleValue();}
else if(name == "nz"){t.n[2] = (float)a->DoubleValue();}
else if(name == "p1x"){t.x[0][0] = (float)a->DoubleValue();}
else if(name == "p1y"){t.x[0][1] = (float)a->DoubleValue();}
else if(name == "p1z"){t.x[0][2] = (float)a->DoubleValue();}
else if(name == "p2x"){t.x[1][0] = (float)a->DoubleValue();}
else if(name == "p2y"){t.x[1][1] = (float)a->DoubleValue();}
else if(name == "p2z"){t.x[1][2] = (float)a->DoubleValue();}
else if(name == "p3x"){t.x[2][0] = (float)a->DoubleValue();}
else if(name == "p3y"){t.x[2][1] = (float)a->DoubleValue();}
else if(name == "p3z"){t.x[2][2] = (float)a->DoubleValue();}
}
new_object->m_list.push_back(t);
}
new_object->ReadBaseXML(pElem);
return new_object;
}
<|endoftext|> |
<commit_before>/*
Copyright 2008 Larry Gritz and the other authors and contributors.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the software's owners 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.
(This is the Modified BSD License)
*/
#include <vector>
#include <memory>
#include <gif_lib.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/thread.h>
// GIFLIB:
// http://giflib.sourceforge.net/
// Format description:
// http://giflib.sourceforge.net/whatsinagif/index.html
// for older giflib versions
#ifndef GIFLIB_MAJOR
#define GIFLIB_MAJOR 4
#endif
#ifndef DISPOSAL_UNSPECIFIED
#define DISPOSAL_UNSPECIFIED 0
#endif
#ifndef DISPOSE_BACKGROUND
#define DISPOSE_BACKGROUND 2
#endif
OIIO_PLUGIN_NAMESPACE_BEGIN
class GIFInput final : public ImageInput {
public:
GIFInput () { init (); }
virtual ~GIFInput () { close (); }
virtual const char *format_name (void) const override { return "gif"; }
virtual bool open (const std::string &name, ImageSpec &newspec) override;
virtual bool close (void) override;
virtual bool seek_subimage (int subimage, int miplevel) override;
virtual bool read_native_scanline (int subimage, int miplevel,
int y, int z, void *data) override;
virtual int current_subimage (void) const override {
lock_guard lock (m_mutex);
return m_subimage;
}
virtual int current_miplevel (void) const override {
// No mipmap support
return 0;
}
private:
std::string m_filename; ///< Stash the filename
GifFileType *m_gif_file; ///< GIFLIB handle
int m_transparent_color; ///< Transparent color index
int m_subimage; ///< Current subimage index
int m_disposal_method; ///< Disposal method of current subimage.
/// Indicates what to do with canvas
/// before drawing the _next_ subimage.
int m_previous_disposal_method; ///< Disposal method of previous subimage.
/// Indicates what to do with canvas
/// before drawing _current_ subimage.
std::vector<unsigned char> m_canvas; ///< Image canvas in output format, on
/// which subimages are sequentially
/// drawn.
/// Reset everything to initial state
///
void init (void);
/// Read current subimage metadata.
///
bool read_subimage_metadata (ImageSpec &newspec);
/// Read current subimage data (ie. draw it on canvas).
///
bool read_subimage_data (void);
/// Helper: read gif extension.
///
void read_gif_extension (int ext_code, GifByteType *ext, ImageSpec &spec);
/// Decode and return a real scanline index in the interlaced image.
///
int decode_line_number (int line_number, int height);
/// Print error message.
///
void report_last_error (void);
};
// Obligatory material to make this a recognizeable imageio plugin
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT int gif_imageio_version = OIIO_PLUGIN_VERSION;
OIIO_EXPORT ImageInput *gif_input_imageio_create () {
return new GIFInput;
}
OIIO_EXPORT const char *gif_input_extensions[] = { "gif", NULL };
OIIO_EXPORT const char* gif_imageio_library_version () {
#define STRINGIZE2(a) #a
#define STRINGIZE(a) STRINGIZE2(a)
#if defined(GIFLIB_MAJOR) && defined(GIFLIB_MINOR) && defined(GIFLIB_RELEASE)
return "gif_lib " STRINGIZE(GIFLIB_MAJOR) "." STRINGIZE(GIFLIB_MINOR) "." STRINGIZE(GIFLIB_RELEASE);
#else
return "gif_lib unknown version";
#endif
}
OIIO_PLUGIN_EXPORTS_END
void
GIFInput::init (void)
{
m_gif_file = NULL;
}
bool
GIFInput::open (const std::string &name, ImageSpec &newspec)
{
m_filename = name;
m_subimage = -1;
m_canvas.clear ();
bool ok = seek_subimage (0, 0);
newspec = spec();
return ok;
}
inline int
GIFInput::decode_line_number (int line_number, int height)
{
if (1 < height && (height + 1) / 2 <= line_number) // 4th tile 1/2 sized
return 2 * (line_number - (height + 1) / 2) + 1;
if (2 < height && (height + 3) / 4 <= line_number) // 3rd tile 1/4 sized
return 4 * (line_number - (height + 3) / 4) + 2;
if (4 < height && (height + 7) / 8 <= line_number) // 2nd tile 1/8 sized
return 8 * (line_number - (height + 7) / 8) + 4;
// 1st tile 1/8 sized
return line_number * 8;
}
bool
GIFInput::read_native_scanline (int subimage, int miplevel,
int y, int z, void *data)
{
lock_guard lock (m_mutex);
if (! seek_subimage (subimage, miplevel))
return false;
if (y < 0 || y > m_spec.height || ! m_canvas.size())
return false;
memcpy (data, &m_canvas[y * m_spec.width * m_spec.nchannels],
m_spec.width * m_spec.nchannels);
return true;
}
void
GIFInput::read_gif_extension (int ext_code, GifByteType *ext,
ImageSpec &newspec)
{
if (ext_code == GRAPHICS_EXT_FUNC_CODE) {
// read background color index, disposal method and delay time between frames
// http://giflib.sourceforge.net/whatsinagif/bits_and_bytes.html#graphics_control_extension_block
if (ext[1] & 0x01) {
m_transparent_color = (int) ext[4];
}
m_disposal_method = (ext[1] & 0x1c) >> 2;
int delay = (ext[3] << 8) | ext[2];
if (delay) {
int rat[2] = { 100, delay };
newspec.attribute ("FramesPerSecond", TypeRational, &rat);
newspec.attribute ("oiio:Movie", 1);
}
} else if (ext_code == COMMENT_EXT_FUNC_CODE) {
// read comment data
// http://giflib.sourceforge.net/whatsinagif/bits_and_bytes.html#comment_extension_block
std::string comment = std::string ((const char *)&ext[1], int (ext[0]));
newspec.attribute("ImageDescription", comment);
} else if (ext_code == APPLICATION_EXT_FUNC_CODE) {
// read loop count
// http://giflib.sourceforge.net/whatsinagif/bits_and_bytes.html#application_extension_block
if (ext[0] == 3) {
newspec.attribute ("gif:LoopCount", (ext[3] << 8) | ext[2]);
}
}
}
bool
GIFInput::read_subimage_metadata (ImageSpec &newspec)
{
newspec = ImageSpec (TypeDesc::UINT8);
newspec.nchannels = 4;
newspec.default_channel_names ();
newspec.alpha_channel = 4;
newspec.attribute ("oiio:ColorSpace", "sRGB");
m_previous_disposal_method = m_disposal_method;
m_disposal_method = DISPOSAL_UNSPECIFIED;
m_transparent_color = -1;
GifRecordType m_gif_rec_type;
do {
if (DGifGetRecordType (m_gif_file, &m_gif_rec_type) == GIF_ERROR) {
report_last_error ();
return false;
}
switch (m_gif_rec_type) {
case IMAGE_DESC_RECORD_TYPE:
if (DGifGetImageDesc (m_gif_file) == GIF_ERROR) {
report_last_error ();
return false;
}
break;
case EXTENSION_RECORD_TYPE:
int ext_code;
GifByteType *ext;
if (DGifGetExtension(m_gif_file, &ext_code, &ext) == GIF_ERROR)
{
report_last_error ();
return false;
}
read_gif_extension (ext_code, ext, newspec);
while (ext != NULL)
{
if (DGifGetExtensionNext(m_gif_file, &ext) == GIF_ERROR)
{
report_last_error ();
return false;
}
if (ext != NULL) {
read_gif_extension (ext_code, ext, newspec);
}
}
break;
case TERMINATE_RECORD_TYPE:
return false;
break;
default:
break;
}
} while (m_gif_rec_type != IMAGE_DESC_RECORD_TYPE);
newspec.attribute ("gif:Interlacing", m_gif_file->Image.Interlace ? 1 : 0);
return true;
}
bool
GIFInput::read_subimage_data()
{
GifColorType *colormap = NULL;
if (m_gif_file->Image.ColorMap) { // local colormap
colormap = m_gif_file->Image.ColorMap->Colors;
} else if (m_gif_file->SColorMap) { // global colormap
colormap = m_gif_file->SColorMap->Colors;
} else {
error ("Neither local nor global colormap present.");
return false;
}
if (m_subimage == 0 || m_previous_disposal_method == DISPOSE_BACKGROUND) {
// make whole canvas transparent
std::fill (m_canvas.begin(), m_canvas.end(), 0x00);
}
// decode scanline index if image is interlaced
bool interlacing = m_spec.get_int_attribute ("gif:Interlacing") != 0;
// get subimage dimensions and draw it on canvas
int window_height = m_gif_file->Image.Height;
int window_width = m_gif_file->Image.Width;
int window_top = m_gif_file->Image.Top;
int window_left = m_gif_file->Image.Left;
std::unique_ptr<unsigned char[]> fscanline (new unsigned char [window_width]);
for (int wy = 0; wy < window_height; wy++) {
if (DGifGetLine (m_gif_file, &fscanline[0], window_width) == GIF_ERROR) {
report_last_error ();
return false;
}
int y = window_top + (interlacing ?
decode_line_number(wy, window_height) : wy);
if (0 <= y && y < m_spec.height) {
for (int wx = 0; wx < window_width; wx++) {
int x = window_left + wx;
int idx = m_spec.nchannels * (y * m_spec.width + x);
if (0 <= x && x < m_spec.width &&
fscanline[wx] != m_transparent_color) {
m_canvas[idx] = colormap[fscanline[wx]].Red;
m_canvas[idx + 1] = colormap[fscanline[wx]].Green;
m_canvas[idx + 2] = colormap[fscanline[wx]].Blue;
m_canvas[idx + 3] = 0xff;
}
}
}
}
return true;
}
bool
GIFInput::seek_subimage (int subimage, int miplevel)
{
if (subimage < 0 || miplevel != 0)
return false;
if (m_subimage == subimage) {
// We're already pointing to the right subimage
return true;
}
if (m_subimage > subimage) {
// requested subimage is located before the current one
// file needs to be reopened
if (m_gif_file && ! close()) {
return false;
}
}
if (! m_gif_file) {
#if GIFLIB_MAJOR >= 5
int giflib_error;
if (! (m_gif_file = DGifOpenFileName (m_filename.c_str(),
&giflib_error))) {
error (GifErrorString (giflib_error));
return false;
}
#else
if (! (m_gif_file = DGifOpenFileName (m_filename.c_str()))) {
error ("Error trying to open the file.");
return false;
}
#endif
m_subimage = -1;
m_canvas.resize (m_gif_file->SWidth * m_gif_file->SHeight * 4);
}
// skip subimages preceding the requested one
if (m_subimage < subimage) {
for (m_subimage += 1; m_subimage < subimage; m_subimage ++) {
if (! read_subimage_metadata (m_spec) ||
! read_subimage_data ()) {
return false;
}
}
}
// read metadata of current subimage
if (! read_subimage_metadata (m_spec)) {
return false;
}
m_spec.width = m_gif_file->SWidth;
m_spec.height = m_gif_file->SHeight;
m_spec.depth = 1;
m_spec.full_height = m_spec.height;
m_spec.full_width = m_spec.width;
m_spec.full_depth = m_spec.depth;
m_subimage = subimage;
// draw subimage on canvas
if (! read_subimage_data ()) {
return false;
}
return true;
}
static spin_mutex gif_error_mutex;
void
GIFInput::report_last_error (void)
{
// N.B. Only GIFLIB_MAJOR >= 5 looks properly thread-safe, in that the
// error is guaranteed to be specific to this open file. We use a spin
// mutex to prevent a thread clash for older versions, but it still
// appears to be a global call, so we can't be absolutely sure that the
// error was for *this* file. So if you're using giflib prior to
// version 5, beware.
#if GIFLIB_MAJOR >= 5
error ("%s", GifErrorString (m_gif_file->Error));
#elif GIFLIB_MAJOR == 4 && GIFLIB_MINOR >= 2
spin_lock lock (gif_error_mutex);
error ("%s", GifErrorString());
#else
spin_lock lock (gif_error_mutex);
error ("GIF error %d", GifLastError());
#endif
}
inline bool
GIFInput::close (void)
{
if (m_gif_file) {
#if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1)
if (DGifCloseFile (m_gif_file, NULL) == GIF_ERROR) {
#else
if (DGifCloseFile (m_gif_file) == GIF_ERROR) {
#endif
error ("Error trying to close the file.");
return false;
}
m_gif_file = NULL;
}
m_canvas.clear();
return true;
}
OIIO_PLUGIN_NAMESPACE_END
<commit_msg>Fix segfault when reading gif with Comment Extension and no Comment Data (#2001)<commit_after>/*
Copyright 2008 Larry Gritz and the other authors and contributors.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the software's owners 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.
(This is the Modified BSD License)
*/
#include <vector>
#include <memory>
#include <gif_lib.h>
#include <OpenImageIO/imageio.h>
#include <OpenImageIO/thread.h>
// GIFLIB:
// http://giflib.sourceforge.net/
// Format description:
// http://giflib.sourceforge.net/whatsinagif/index.html
// for older giflib versions
#ifndef GIFLIB_MAJOR
#define GIFLIB_MAJOR 4
#endif
#ifndef DISPOSAL_UNSPECIFIED
#define DISPOSAL_UNSPECIFIED 0
#endif
#ifndef DISPOSE_BACKGROUND
#define DISPOSE_BACKGROUND 2
#endif
OIIO_PLUGIN_NAMESPACE_BEGIN
class GIFInput final : public ImageInput {
public:
GIFInput () { init (); }
virtual ~GIFInput () { close (); }
virtual const char *format_name (void) const override { return "gif"; }
virtual bool open (const std::string &name, ImageSpec &newspec) override;
virtual bool close (void) override;
virtual bool seek_subimage (int subimage, int miplevel) override;
virtual bool read_native_scanline (int subimage, int miplevel,
int y, int z, void *data) override;
virtual int current_subimage (void) const override {
lock_guard lock (m_mutex);
return m_subimage;
}
virtual int current_miplevel (void) const override {
// No mipmap support
return 0;
}
private:
std::string m_filename; ///< Stash the filename
GifFileType *m_gif_file; ///< GIFLIB handle
int m_transparent_color; ///< Transparent color index
int m_subimage; ///< Current subimage index
int m_disposal_method; ///< Disposal method of current subimage.
/// Indicates what to do with canvas
/// before drawing the _next_ subimage.
int m_previous_disposal_method; ///< Disposal method of previous subimage.
/// Indicates what to do with canvas
/// before drawing _current_ subimage.
std::vector<unsigned char> m_canvas; ///< Image canvas in output format, on
/// which subimages are sequentially
/// drawn.
/// Reset everything to initial state
///
void init (void);
/// Read current subimage metadata.
///
bool read_subimage_metadata (ImageSpec &newspec);
/// Read current subimage data (ie. draw it on canvas).
///
bool read_subimage_data (void);
/// Helper: read gif extension.
///
void read_gif_extension (int ext_code, GifByteType *ext, ImageSpec &spec);
/// Decode and return a real scanline index in the interlaced image.
///
int decode_line_number (int line_number, int height);
/// Print error message.
///
void report_last_error (void);
};
// Obligatory material to make this a recognizeable imageio plugin
OIIO_PLUGIN_EXPORTS_BEGIN
OIIO_EXPORT int gif_imageio_version = OIIO_PLUGIN_VERSION;
OIIO_EXPORT ImageInput *gif_input_imageio_create () {
return new GIFInput;
}
OIIO_EXPORT const char *gif_input_extensions[] = { "gif", NULL };
OIIO_EXPORT const char* gif_imageio_library_version () {
#define STRINGIZE2(a) #a
#define STRINGIZE(a) STRINGIZE2(a)
#if defined(GIFLIB_MAJOR) && defined(GIFLIB_MINOR) && defined(GIFLIB_RELEASE)
return "gif_lib " STRINGIZE(GIFLIB_MAJOR) "." STRINGIZE(GIFLIB_MINOR) "." STRINGIZE(GIFLIB_RELEASE);
#else
return "gif_lib unknown version";
#endif
}
OIIO_PLUGIN_EXPORTS_END
void
GIFInput::init (void)
{
m_gif_file = NULL;
}
bool
GIFInput::open (const std::string &name, ImageSpec &newspec)
{
m_filename = name;
m_subimage = -1;
m_canvas.clear ();
bool ok = seek_subimage (0, 0);
newspec = spec();
return ok;
}
inline int
GIFInput::decode_line_number (int line_number, int height)
{
if (1 < height && (height + 1) / 2 <= line_number) // 4th tile 1/2 sized
return 2 * (line_number - (height + 1) / 2) + 1;
if (2 < height && (height + 3) / 4 <= line_number) // 3rd tile 1/4 sized
return 4 * (line_number - (height + 3) / 4) + 2;
if (4 < height && (height + 7) / 8 <= line_number) // 2nd tile 1/8 sized
return 8 * (line_number - (height + 7) / 8) + 4;
// 1st tile 1/8 sized
return line_number * 8;
}
bool
GIFInput::read_native_scanline (int subimage, int miplevel,
int y, int z, void *data)
{
lock_guard lock (m_mutex);
if (! seek_subimage (subimage, miplevel))
return false;
if (y < 0 || y > m_spec.height || ! m_canvas.size())
return false;
memcpy (data, &m_canvas[y * m_spec.width * m_spec.nchannels],
m_spec.width * m_spec.nchannels);
return true;
}
void
GIFInput::read_gif_extension (int ext_code, GifByteType *ext,
ImageSpec &newspec)
{
if (ext_code == GRAPHICS_EXT_FUNC_CODE) {
// read background color index, disposal method and delay time between frames
// http://giflib.sourceforge.net/whatsinagif/bits_and_bytes.html#graphics_control_extension_block
if (ext[1] & 0x01) {
m_transparent_color = (int) ext[4];
}
m_disposal_method = (ext[1] & 0x1c) >> 2;
int delay = (ext[3] << 8) | ext[2];
if (delay) {
int rat[2] = { 100, delay };
newspec.attribute ("FramesPerSecond", TypeRational, &rat);
newspec.attribute ("oiio:Movie", 1);
}
} else if (ext_code == COMMENT_EXT_FUNC_CODE) {
// read comment data
// http://giflib.sourceforge.net/whatsinagif/bits_and_bytes.html#comment_extension_block
std::string comment = std::string ((const char *)&ext[1], int (ext[0]));
newspec.attribute("ImageDescription", comment);
} else if (ext_code == APPLICATION_EXT_FUNC_CODE) {
// read loop count
// http://giflib.sourceforge.net/whatsinagif/bits_and_bytes.html#application_extension_block
if (ext[0] == 3) {
newspec.attribute ("gif:LoopCount", (ext[3] << 8) | ext[2]);
}
}
}
bool
GIFInput::read_subimage_metadata (ImageSpec &newspec)
{
newspec = ImageSpec (TypeDesc::UINT8);
newspec.nchannels = 4;
newspec.default_channel_names ();
newspec.alpha_channel = 4;
newspec.attribute ("oiio:ColorSpace", "sRGB");
m_previous_disposal_method = m_disposal_method;
m_disposal_method = DISPOSAL_UNSPECIFIED;
m_transparent_color = -1;
GifRecordType m_gif_rec_type;
do {
if (DGifGetRecordType (m_gif_file, &m_gif_rec_type) == GIF_ERROR) {
report_last_error ();
return false;
}
switch (m_gif_rec_type) {
case IMAGE_DESC_RECORD_TYPE:
if (DGifGetImageDesc (m_gif_file) == GIF_ERROR) {
report_last_error ();
return false;
}
break;
case EXTENSION_RECORD_TYPE:
int ext_code;
GifByteType *ext;
if (DGifGetExtension(m_gif_file, &ext_code, &ext) == GIF_ERROR)
{
report_last_error ();
return false;
}
if (ext != NULL) {
read_gif_extension (ext_code, ext, newspec);
}
while (ext != NULL)
{
if (DGifGetExtensionNext(m_gif_file, &ext) == GIF_ERROR)
{
report_last_error ();
return false;
}
if (ext != NULL) {
read_gif_extension (ext_code, ext, newspec);
}
}
break;
case TERMINATE_RECORD_TYPE:
return false;
break;
default:
break;
}
} while (m_gif_rec_type != IMAGE_DESC_RECORD_TYPE);
newspec.attribute ("gif:Interlacing", m_gif_file->Image.Interlace ? 1 : 0);
return true;
}
bool
GIFInput::read_subimage_data()
{
GifColorType *colormap = NULL;
if (m_gif_file->Image.ColorMap) { // local colormap
colormap = m_gif_file->Image.ColorMap->Colors;
} else if (m_gif_file->SColorMap) { // global colormap
colormap = m_gif_file->SColorMap->Colors;
} else {
error ("Neither local nor global colormap present.");
return false;
}
if (m_subimage == 0 || m_previous_disposal_method == DISPOSE_BACKGROUND) {
// make whole canvas transparent
std::fill (m_canvas.begin(), m_canvas.end(), 0x00);
}
// decode scanline index if image is interlaced
bool interlacing = m_spec.get_int_attribute ("gif:Interlacing") != 0;
// get subimage dimensions and draw it on canvas
int window_height = m_gif_file->Image.Height;
int window_width = m_gif_file->Image.Width;
int window_top = m_gif_file->Image.Top;
int window_left = m_gif_file->Image.Left;
std::unique_ptr<unsigned char[]> fscanline (new unsigned char [window_width]);
for (int wy = 0; wy < window_height; wy++) {
if (DGifGetLine (m_gif_file, &fscanline[0], window_width) == GIF_ERROR) {
report_last_error ();
return false;
}
int y = window_top + (interlacing ?
decode_line_number(wy, window_height) : wy);
if (0 <= y && y < m_spec.height) {
for (int wx = 0; wx < window_width; wx++) {
int x = window_left + wx;
int idx = m_spec.nchannels * (y * m_spec.width + x);
if (0 <= x && x < m_spec.width &&
fscanline[wx] != m_transparent_color) {
m_canvas[idx] = colormap[fscanline[wx]].Red;
m_canvas[idx + 1] = colormap[fscanline[wx]].Green;
m_canvas[idx + 2] = colormap[fscanline[wx]].Blue;
m_canvas[idx + 3] = 0xff;
}
}
}
}
return true;
}
bool
GIFInput::seek_subimage (int subimage, int miplevel)
{
if (subimage < 0 || miplevel != 0)
return false;
if (m_subimage == subimage) {
// We're already pointing to the right subimage
return true;
}
if (m_subimage > subimage) {
// requested subimage is located before the current one
// file needs to be reopened
if (m_gif_file && ! close()) {
return false;
}
}
if (! m_gif_file) {
#if GIFLIB_MAJOR >= 5
int giflib_error;
if (! (m_gif_file = DGifOpenFileName (m_filename.c_str(),
&giflib_error))) {
error (GifErrorString (giflib_error));
return false;
}
#else
if (! (m_gif_file = DGifOpenFileName (m_filename.c_str()))) {
error ("Error trying to open the file.");
return false;
}
#endif
m_subimage = -1;
m_canvas.resize (m_gif_file->SWidth * m_gif_file->SHeight * 4);
}
// skip subimages preceding the requested one
if (m_subimage < subimage) {
for (m_subimage += 1; m_subimage < subimage; m_subimage ++) {
if (! read_subimage_metadata (m_spec) ||
! read_subimage_data ()) {
return false;
}
}
}
// read metadata of current subimage
if (! read_subimage_metadata (m_spec)) {
return false;
}
m_spec.width = m_gif_file->SWidth;
m_spec.height = m_gif_file->SHeight;
m_spec.depth = 1;
m_spec.full_height = m_spec.height;
m_spec.full_width = m_spec.width;
m_spec.full_depth = m_spec.depth;
m_subimage = subimage;
// draw subimage on canvas
if (! read_subimage_data ()) {
return false;
}
return true;
}
static spin_mutex gif_error_mutex;
void
GIFInput::report_last_error (void)
{
// N.B. Only GIFLIB_MAJOR >= 5 looks properly thread-safe, in that the
// error is guaranteed to be specific to this open file. We use a spin
// mutex to prevent a thread clash for older versions, but it still
// appears to be a global call, so we can't be absolutely sure that the
// error was for *this* file. So if you're using giflib prior to
// version 5, beware.
#if GIFLIB_MAJOR >= 5
error ("%s", GifErrorString (m_gif_file->Error));
#elif GIFLIB_MAJOR == 4 && GIFLIB_MINOR >= 2
spin_lock lock (gif_error_mutex);
error ("%s", GifErrorString());
#else
spin_lock lock (gif_error_mutex);
error ("GIF error %d", GifLastError());
#endif
}
inline bool
GIFInput::close (void)
{
if (m_gif_file) {
#if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1)
if (DGifCloseFile (m_gif_file, NULL) == GIF_ERROR) {
#else
if (DGifCloseFile (m_gif_file) == GIF_ERROR) {
#endif
error ("Error trying to close the file.");
return false;
}
m_gif_file = NULL;
}
m_canvas.clear();
return true;
}
OIIO_PLUGIN_NAMESPACE_END
<|endoftext|> |
<commit_before>#ifndef ALPHA_DIRECTRENDERLAYER_HEADER
#define ALPHA_DIRECTRENDERLAYER_HEADER
#include "gl/RenderLayer.hpp"
#include "gl/Physical.hpp"
#include "gl/util.hpp"
#include <GL/gl.h>
#include <vector>
#include <algorithm>
namespace nt {
namespace gl {
/**
* Represents something that can be rendered. Specifically,
* it requires a physical location, as well as a renderer
* that can draw the geometry at that location.
*/
template <typename Scalar, typename Renderer>
struct Renderable
{
Physical<Scalar>* physical;
Renderer* renderer;
Renderable(Physical<Scalar>* const physical, Renderer* const renderer) :
physical(physical),
renderer(renderer)
{}
template <typename U, typename V>
bool operator==(const Renderable<U, V>& other)
{
return physical == other.physical &&
renderer == other.renderer;
}
};
/**
* A layer that contains a list of renderable objects. This is called a
* "direct" render layer because the objects that are rendered directly:
* their physical location is used without modification to translate the
* object in space, and the renderer function is wholly responsible for
* drawing the object. This is in contrast with other layers that do not have
* a one-to-one representation of rendered geometery to objects.
*/
template <typename Scalar, typename Renderer>
class DirectRenderLayer : public RenderLayer
{
public:
typedef Renderable<Scalar, Renderer> RenderableType;
typedef std::vector<RenderableType> RenderableList;
protected:
RenderableList renderables;
public:
void add(Physical<Scalar>* const physical, Renderer* const renderer)
{
renderables.push_back(RenderableType(physical, renderer));
}
void render(const Vector3<double>&) const
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
for (typename RenderableList::const_iterator i = renderables.begin(); i != renderables.end(); ++i) {
const RenderableType& renderable(*i);
glTranslate(renderable.physical->getPosition());
glRotateRadians(renderable.physical->getRotation());
renderable.renderer();
}
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
}
int numRenderables() const
{
return renderables.size();
}
void remove(Physical<Scalar>* const physical, Renderer* const renderer)
{
typename RenderableList::iterator pos =
std::remove(renderables.begin(), renderables.end(),
RenderableType(physical, renderer));
renderables.erase(pos, renderables.end());
}
};
} // namespace gl
} // namespace nt
#endif // ALPHA_DIRECTRENDERLAYER_HEADER
<commit_msg>DirectRenderLayer: Made typedefs and renderable list private<commit_after>#ifndef ALPHA_DIRECTRENDERLAYER_HEADER
#define ALPHA_DIRECTRENDERLAYER_HEADER
#include "gl/RenderLayer.hpp"
#include "gl/Physical.hpp"
#include "gl/util.hpp"
#include <GL/gl.h>
#include <vector>
#include <algorithm>
namespace nt {
namespace gl {
/**
* Represents something that can be rendered. Specifically,
* it requires a physical location, as well as a renderer
* that can draw the geometry at that location.
*/
template <typename Scalar, typename Renderer>
struct Renderable
{
Physical<Scalar>* physical;
Renderer* renderer;
Renderable(Physical<Scalar>* const physical, Renderer* const renderer) :
physical(physical),
renderer(renderer)
{}
template <typename U, typename V>
bool operator==(const Renderable<U, V>& other)
{
return physical == other.physical &&
renderer == other.renderer;
}
};
/**
* A layer that contains a list of renderable objects. This is called a
* "direct" render layer because the objects that are rendered directly:
* their physical location is used without modification to translate the
* object in space, and the renderer function is wholly responsible for
* drawing the object. This is in contrast with other layers that do not have
* a one-to-one representation of rendered geometery to objects.
*/
template <typename Scalar, typename Renderer>
class DirectRenderLayer : public RenderLayer
{
typedef Renderable<Scalar, Renderer> RenderableType;
typedef std::vector<RenderableType> RenderableList;
RenderableList renderables;
public:
void add(Physical<Scalar>* const physical, Renderer* const renderer)
{
renderables.push_back(RenderableType(physical, renderer));
}
void render(const Vector3<double>&) const
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
for (typename RenderableList::const_iterator i = renderables.begin(); i != renderables.end(); ++i) {
const RenderableType& renderable(*i);
glTranslate(renderable.physical->getPosition());
glRotateRadians(renderable.physical->getRotation());
renderable.renderer();
}
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
}
int numRenderables() const
{
return renderables.size();
}
void remove(Physical<Scalar>* const physical, Renderer* const renderer)
{
typename RenderableList::iterator pos =
std::remove(renderables.begin(), renderables.end(),
RenderableType(physical, renderer));
renderables.erase(pos, renderables.end());
}
};
} // namespace gl
} // namespace nt
#endif // ALPHA_DIRECTRENDERLAYER_HEADER
<|endoftext|> |
<commit_before>#include "trace.h"
#include "lib/lambertian.h"
#include "lib/stats.h"
Color trace(const Vec& origin, const Vec& dir,
const Tree& triangles_tree, const std::vector<Light>& lights,
int depth, const Configuration& conf)
{
Stats::instance().num_rays += 1;
if (depth > conf.max_depth) {
return {};
}
auto& light = lights.front();
// intersection
float dist_to_triangle, s, t;
auto triangle_pt = triangles_tree.intersect(
aiRay(origin, dir), dist_to_triangle, s, t);
if (!triangle_pt) {
return conf.bg_color;
}
// light direction
auto p = origin + dist_to_triangle * dir;
auto light_dir = (light.position - p).Normalize();
// interpolate normal
const auto& triangle = *triangle_pt;
auto normal = triangle.interpolate_normal(1.f - s - t, s, t);
// direct light
auto direct_lightning = lambertian(
light_dir, normal, triangle.diffuse, light.color);
// move slightly in direction of normal
auto p2 = p + normal * 0.0001f;
auto color = direct_lightning;
// reflection
if (triangle.reflectivity > 0) {
// compute reflected ray from incident ray
auto reflected_ray_dir = dir - 2.f * (normal * dir) * normal;
// TODO: Multiplication by reflective color is not correct. Replace by
// Fresnel function.
auto reflected_color = triangle.reflective * triangle.diffuse * trace(
p2, reflected_ray_dir,
triangles_tree, lights, depth + 1, conf);
color = (1.f - triangle.reflectivity) * direct_lightning
+ triangle.reflectivity * reflected_color;
}
// shadow
float dist_to_next_triangle;
light_dir = (light.position - p2).Normalize();
float dist_to_light = (light.position - p2).Length();
auto has_shadow = triangles_tree.intersect(
aiRay(p2, light_dir), dist_to_next_triangle, s, t);
if (has_shadow && dist_to_next_triangle < dist_to_light) {
color -= color * conf.shadow_intensity;
}
return color;
}
<commit_msg>Remove diffuse color from mirrored ray.<commit_after>#include "trace.h"
#include "lib/lambertian.h"
#include "lib/stats.h"
Color trace(const Vec& origin, const Vec& dir,
const Tree& triangles_tree, const std::vector<Light>& lights,
int depth, const Configuration& conf)
{
Stats::instance().num_rays += 1;
if (depth > conf.max_depth) {
return {};
}
auto& light = lights.front();
// intersection
float dist_to_triangle, s, t;
auto triangle_pt = triangles_tree.intersect(
aiRay(origin, dir), dist_to_triangle, s, t);
if (!triangle_pt) {
return conf.bg_color;
}
// light direction
auto p = origin + dist_to_triangle * dir;
auto light_dir = (light.position - p).Normalize();
// interpolate normal
const auto& triangle = *triangle_pt;
auto normal = triangle.interpolate_normal(1.f - s - t, s, t);
// direct light
auto direct_lightning = lambertian(
light_dir, normal, triangle.diffuse, light.color);
// move slightly in direction of normal
auto p2 = p + normal * 0.0001f;
auto color = direct_lightning;
// reflection
if (triangle.reflectivity > 0) {
// compute reflected ray from incident ray
auto reflected_ray_dir = dir - 2.f * (normal * dir) * normal;
auto reflected_color = trace(
p2, reflected_ray_dir,
triangles_tree, lights, depth + 1, conf);
color = (1.f - triangle.reflectivity) * direct_lightning
+ triangle.reflectivity * triangle.reflective * reflected_color;
}
// shadow
float dist_to_next_triangle;
light_dir = (light.position - p2).Normalize();
float dist_to_light = (light.position - p2).Length();
auto has_shadow = triangles_tree.intersect(
aiRay(p2, light_dir), dist_to_next_triangle, s, t);
if (has_shadow && dist_to_next_triangle < dist_to_light) {
color -= color * conf.shadow_intensity;
}
return color;
}
<|endoftext|> |
<commit_before>#include "timer.h"
#ifdef _WIN32
#include <windows.h>
#include <winbase.h>
#else
#include <time.h>
#endif
HighResTimer::HighResTimer()
{
ElapsedTime = 0;
running = 0;
}
HighResTimer::~HighResTimer() {}
void HighResTimer::Start()
{
#ifdef _WIN32
__int64 istart;
QueryPerformanceCounter((LARGE_INTEGER*)&istart);
StartTime = (double) istart;
#else
timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
StartTime = (double) tv.tv_sec * 1.0E9 + (double) tv.tv_nsec;
#endif
running = 1;
}
void HighResTimer::ResetStart()
{
ElapsedTime = 0;
Start();
}
void HighResTimer::Stop()
{
if (running == 0) return;
running = 0;
double EndTime = 0;
#ifdef _WIN32
__int64 iend;
QueryPerformanceCounter((LARGE_INTEGER*) &iend);
EndTime = (double) iend;
#else
timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
EndTime = (double) tv.tv_sec * 1.0E9 + (double) tv.tv_nsec;
#endif
ElapsedTime += EndTime - StartTime;
}
void HighResTimer::Reset()
{
ElapsedTime = 0;
StartTime = 0;
running = 0;
}
double HighResTimer::GetElapsedTime()
{
return ElapsedTime / Frequency;
}
double HighResTimer::GetCurrentElapsedTime()
{
if (running == 0) return(GetElapsedTime());
double CurrentTime = 0;
#ifdef _WIN32
__int64 iend;
QueryPerformanceCounter((LARGE_INTEGER*) &iend);
CurrentTime = (double) iend;
#else
timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
CurrentTime = (double) tv.tv_sec * 1.0E9 + (double) tv.tv_nsec;
#endif
return((CurrentTime - StartTime + ElapsedTime) / Frequency);
}
double HighResTimer::GetFrequency()
{
#ifdef _WIN32
__int64 ifreq;
QueryPerformanceFrequency((LARGE_INTEGER*)&ifreq);
return((double) ifreq);
#else
return(1.0E9);
#endif
}
double HighResTimer::Frequency = HighResTimer::GetFrequency();
<commit_msg>fix codestyle<commit_after>#include "timer.h"
#ifdef _WIN32
#include <windows.h>
#include <winbase.h>
#else
#include <time.h>
#endif
HighResTimer::HighResTimer()
{
ElapsedTime = 0;
running = 0;
}
HighResTimer::~HighResTimer() {}
void HighResTimer::Start()
{
#ifdef _WIN32
__int64 istart;
QueryPerformanceCounter((LARGE_INTEGER*) &istart);
StartTime = (double) istart;
#else
timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
StartTime = (double) tv.tv_sec * 1.0e9 + (double) tv.tv_nsec;
#endif
running = 1;
}
void HighResTimer::ResetStart()
{
ElapsedTime = 0;
Start();
}
void HighResTimer::Stop()
{
if (running == 0) return;
running = 0;
double EndTime = 0;
#ifdef _WIN32
__int64 iend;
QueryPerformanceCounter((LARGE_INTEGER*) &iend);
EndTime = (double) iend;
#else
timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
EndTime = (double) tv.tv_sec * 1.0e9 + (double) tv.tv_nsec;
#endif
ElapsedTime += EndTime - StartTime;
}
void HighResTimer::Reset()
{
ElapsedTime = 0;
StartTime = 0;
running = 0;
}
double HighResTimer::GetElapsedTime()
{
return ElapsedTime / Frequency;
}
double HighResTimer::GetCurrentElapsedTime()
{
if (running == 0) return(GetElapsedTime());
double CurrentTime = 0;
#ifdef _WIN32
__int64 iend;
QueryPerformanceCounter((LARGE_INTEGER*) &iend);
CurrentTime = (double) iend;
#else
timespec tv;
clock_gettime(CLOCK_REALTIME, &tv);
CurrentTime = (double) tv.tv_sec * 1.0e9 + (double) tv.tv_nsec;
#endif
return((CurrentTime - StartTime + ElapsedTime) / Frequency);
}
double HighResTimer::GetFrequency()
{
#ifdef _WIN32
__int64 ifreq;
QueryPerformanceFrequency((LARGE_INTEGER*) &ifreq);
return((double) ifreq);
#else
return(1.0e9);
#endif
}
double HighResTimer::Frequency = HighResTimer::GetFrequency();
<|endoftext|> |
<commit_before><commit_msg>pTBins -> binsPt<commit_after><|endoftext|> |
<commit_before>
/***************************************************************************
[email protected] - last modified on 03/04/2013
// modified by [email protected] -- 19-11-2016
// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
// 1) flag to know if running on MC or data
// 2) path where all configs are stored
// ---
// Returns:
// kTRUE --> initialization successful
// kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddTaskLStarPP5TeV_sph
(
Bool_t isMC = kFALSE,
Bool_t isPP = kTRUE,
Int_t trCut = 2011,
TString outNameSuffix = "tofveto3stpc2s",
Int_t customQualityCutsID = AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPrCandidate=AliRsnCutSetDaughterParticle::kTPCTOFpidLstar,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCTOFpidLstar,
Float_t nsigmaP = 2.0,
Float_t nsigmaK = 2.0,
Float_t nsigmatofP = 3.0,
Float_t nsigmatofK = 3.0,
Int_t aodFilterBit = 5,
Bool_t enableMonitor = kTRUE,
Int_t nmix = 10,
Float_t maxDiffVzMix = 1.0,
Float_t maxDiffMultMix = 5.0
)
{
UInt_t triggerMask = AliVEvent::kINT7;
Bool_t rejectPileUp = kTRUE;
Double_t vtxZcut = 10.0;//cm, default cut on vtx z
if(!isPP || isMC) rejectPileUp = kFALSE;
//
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskLStarPP8TeV", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("LStar%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
// task->UseESDTriggerMask(triggerMask); //ESD
task->SelectCollisionCandidates(triggerMask); //AOD
if(isPP){
task->UseMultiplicity("AliMultSelection_V0M");
}else task->UseCentrality("V0M");
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
task->UseMC(isMC);
::Info("AddTaskLStarPP5TeV", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n", nmix, maxDiffVzMix, maxDiffMultMix));
mgr->AddTask(task);
AliRsnCutEventUtils* cutEventUtils= new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
cutEventUtils->SetCheckAcceptedMultSelection();
//
// -- EVENT CUTS (same for all configs) ---------------------------------------------------------
//
// cut on primary vertex:
// - 2nd argument --> |Vz| range
// - 3rd argument --> minimum required number of contributors
// - 4th argument --> tells if TPC stand-alone vertexes must be accepted
AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", 10.0, 0, kFALSE);
if (isPP && (!isMC)) cutVertex->SetCheckPileUp(rejectPileUp); // set the check for pileup
// define and fill cut set for event cut
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(cutVertex);
eventCuts->AddCut(cutEventUtils);
eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
// set cuts in task
task->SetEventCuts(eventCuts);
//
// -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//
//vertex
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 240, -12.0, 12.0);
//multiplicity or centrality
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
if (isPP)
outMult->AddAxis(multID, 100, 0.5, 100.5);
else
outMult->AddAxis(multID, 100, 0.0, 100.0);
TH2F* hvz=new TH2F("hVzVsCent","",100,0.,100., 240,-12.0,12.0);
task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member
TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 100,0.5,100.5);
hmc->GetYaxis()->SetTitle("QUALITY");
task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member
TH2F* hsp=new TH2F("hSpherocityVsCent","",110,0.,110., 100.,0.,1.);
task->SetEventQAHist("spherocitycent",hsp);//plugs this histogram into the fHASpherocityCent data member
//
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(-0.5, 0.5);
// cutY->SetRangeD(-0.9, 0.9);
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
//
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
//
//gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPP5TeV.C");
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigLStarPP5TeV_sph.C");
if (!ConfigLStarPP5TeV(task, isMC, isPP, "", cutsPair, trCut, customQualityCutsID,cutKaCandidate,cutPrCandidate, nsigmaP,nsigmaK,nsigmatofP,nsigmatofK,aodFilterBit,enableMonitor)) return 0x0;
//
// -- CONTAINERS --------------------------------------------------------------------------------
//
TString outputFileName = AliAnalysisManager::GetCommonFileName();
// outputFileName += ":Rsn";
Printf("AddTaskLStarPP5TeV - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<commit_msg>corrected file name<commit_after>
/***************************************************************************
[email protected] - last modified on 03/04/2013
// modified by [email protected] -- 19-11-2016
// General macro to configure the RSN analysis task.
// It calls all configs desired by the user, by means
// of the boolean switches defined in the first lines.
// ---
// Inputs:
// 1) flag to know if running on MC or data
// 2) path where all configs are stored
// ---
// Returns:
// kTRUE --> initialization successful
// kFALSE --> initialization failed (some config gave errors)
//
****************************************************************************/
AliRsnMiniAnalysisTask * AddTaskLStarPP5TeV_sph
(
Bool_t isMC = kFALSE,
Bool_t isPP = kTRUE,
Int_t trCut = 2011,
TString outNameSuffix = "tofveto3stpc2s",
Int_t customQualityCutsID = AliRsnCutSetDaughterParticle::kDisableCustom,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutPrCandidate=AliRsnCutSetDaughterParticle::kTPCTOFpidLstar,
AliRsnCutSetDaughterParticle::ERsnDaughterCutSet cutKaCandidate=AliRsnCutSetDaughterParticle::kTPCTOFpidLstar,
Float_t nsigmaP = 2.0,
Float_t nsigmaK = 2.0,
Float_t nsigmatofP = 3.0,
Float_t nsigmatofK = 3.0,
Int_t aodFilterBit = 5,
Bool_t enableMonitor = kTRUE,
Int_t nmix = 10,
Float_t maxDiffVzMix = 1.0,
Float_t maxDiffMultMix = 5.0
)
{
UInt_t triggerMask = AliVEvent::kINT7;
Bool_t rejectPileUp = kTRUE;
Double_t vtxZcut = 10.0;//cm, default cut on vtx z
if(!isPP || isMC) rejectPileUp = kFALSE;
//
// -- INITIALIZATION ----------------------------------------------------------------------------
// retrieve analysis manager
//
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
::Error("AddTaskLStarPP8TeV", "No analysis manager to connect to.");
return NULL;
}
// create the task and configure
TString taskName = Form("LStar%s%s", (isPP? "pp" : "PbPb"), (isMC ? "MC" : "Data"));
AliRsnMiniAnalysisTask *task = new AliRsnMiniAnalysisTask(taskName.Data(), isMC);
// task->UseESDTriggerMask(triggerMask); //ESD
task->SelectCollisionCandidates(triggerMask); //AOD
if(isPP){
task->UseMultiplicity("AliMultSelection_V0M");
}else task->UseCentrality("V0M");
// set event mixing options
task->UseContinuousMix();
//task->UseBinnedMix();
task->SetNMix(nmix);
task->SetMaxDiffVz(maxDiffVzMix);
task->SetMaxDiffMult(maxDiffMultMix);
task->UseMC(isMC);
::Info("AddTaskLStarPP5TeV", Form("Event mixing configuration: \n events to mix = %i \n max diff. vtxZ = cm %5.3f \n max diff multi = %5.3f \n", nmix, maxDiffVzMix, maxDiffMultMix));
mgr->AddTask(task);
AliRsnCutEventUtils* cutEventUtils= new AliRsnCutEventUtils("cutEventUtils",kTRUE,rejectPileUp);
cutEventUtils->SetCheckAcceptedMultSelection();
//
// -- EVENT CUTS (same for all configs) ---------------------------------------------------------
//
// cut on primary vertex:
// - 2nd argument --> |Vz| range
// - 3rd argument --> minimum required number of contributors
// - 4th argument --> tells if TPC stand-alone vertexes must be accepted
AliRsnCutPrimaryVertex *cutVertex = new AliRsnCutPrimaryVertex("cutVertex", 10.0, 0, kFALSE);
if (isPP && (!isMC)) cutVertex->SetCheckPileUp(rejectPileUp); // set the check for pileup
// define and fill cut set for event cut
AliRsnCutSet *eventCuts = new AliRsnCutSet("eventCuts", AliRsnTarget::kEvent);
eventCuts->AddCut(cutVertex);
eventCuts->AddCut(cutEventUtils);
eventCuts->SetCutScheme(Form("%s&%s",cutEventUtils->GetName(),cutVertex->GetName()));
// set cuts in task
task->SetEventCuts(eventCuts);
//
// -- EVENT-ONLY COMPUTATIONS -------------------------------------------------------------------
//
//vertex
Int_t vtxID = task->CreateValue(AliRsnMiniValue::kVz, kFALSE);
AliRsnMiniOutput *outVtx = task->CreateOutput("eventVtx", "HIST", "EVENT");
outVtx->AddAxis(vtxID, 240, -12.0, 12.0);
//multiplicity or centrality
Int_t multID = task->CreateValue(AliRsnMiniValue::kMult, kFALSE);
AliRsnMiniOutput *outMult = task->CreateOutput("eventMult", "HIST", "EVENT");
if (isPP)
outMult->AddAxis(multID, 100, 0.5, 100.5);
else
outMult->AddAxis(multID, 100, 0.0, 100.0);
TH2F* hvz=new TH2F("hVzVsCent","",100,0.,100., 240,-12.0,12.0);
task->SetEventQAHist("vz",hvz);//plugs this histogram into the fHAEventVz data member
TH2F* hmc=new TH2F("MultiVsCent","", 100,0.,100., 100,0.5,100.5);
hmc->GetYaxis()->SetTitle("QUALITY");
task->SetEventQAHist("multicent",hmc);//plugs this histogram into the fHAEventMultiCent data member
TH2F* hsp=new TH2F("hSpherocityVsCent","",110,0.,110., 100.,0.,1.);
task->SetEventQAHist("spherocitycent",hsp);//plugs this histogram into the fHASpherocityCent data member
//
// -- PAIR CUTS (common to all resonances) ------------------------------------------------------
//
AliRsnCutMiniPair *cutY = new AliRsnCutMiniPair("cutRapidity", AliRsnCutMiniPair::kRapidityRange);
cutY->SetRangeD(-0.5, 0.5);
// cutY->SetRangeD(-0.9, 0.9);
AliRsnCutSet *cutsPair = new AliRsnCutSet("pairCuts", AliRsnTarget::kMother);
cutsPair->AddCut(cutY);
cutsPair->SetCutScheme(cutY->GetName());
//
// -- CONFIG ANALYSIS --------------------------------------------------------------------------
//
//gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigKStarPP5TeV.C");
gROOT->LoadMacro("$ALICE_PHYSICS/PWGLF/RESONANCES/macros/mini/ConfigLStarPP5TeV_sph.C");
if (!ConfigLStarPP5TeV_sph(task, isMC, isPP, "", cutsPair, trCut, customQualityCutsID,cutKaCandidate,cutPrCandidate, nsigmaP,nsigmaK,nsigmatofP,nsigmatofK,aodFilterBit,enableMonitor)) return 0x0;
//
// -- CONTAINERS --------------------------------------------------------------------------------
//
TString outputFileName = AliAnalysisManager::GetCommonFileName();
// outputFileName += ":Rsn";
Printf("AddTaskLStarPP5TeV - Set OutputFileName : \n %s\n", outputFileName.Data() );
AliAnalysisDataContainer *output = mgr->CreateContainer(Form("RsnOut_%s",outNameSuffix.Data()),
TList::Class(),
AliAnalysisManager::kOutputContainer,
outputFileName);
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 1, output);
return task;
}
<|endoftext|> |
<commit_before>//
// Euler's sum of powers conjecture counterexample test without recursion
// Wikipedia: Euler's conjecture was disproven by L. J. Lander and T. R. Parkin
// in 1966 when, through a direct computer search on a CDC 6600, they found
// a counterexample for k = 5. A total of three primitive (that is, in which
// the summands do not all have a common factor) counterexamples are known:
// 27^5 + 84^5 + 110^5 + 133^5 = 144^5 (Lander & Parkin, 1966).
//
#include "stdafx.h"
#include "uint128.h"
// Value define
// uncomment to use unsigned int 64 bits. For N=500: ~440 000 000 its/s ( Max N=7100 )
//#define UINT64USE
// uncomment to use 128bit values by me ( 30% slower than uint64 ). For N=500: ~300 000 000 its/s(N=500) ( Max N=50859008 )
#define UINT128USE
// uncomment to use 128bit values by boost ( 17 times slower than uint64 ). For N=500: ~26 000 000 its/s(N=500) ( Max N=50859008 )
//#define BOOST128USE
// Lib define
// use boost as library or stl
#define BOOSTUSE // stl otherwise
// boost map: 413608 its/ms
// std mpa: 367906 its/ms
// boost map is 10% faster
#ifdef BOOSTUSE
#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <boost/unordered_map.hpp>
#include <boost/chrono.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/container/vector.hpp>
#else // stl
#include <unordered_map>
#include <chrono>
#include <vector>
#endif
#include <iostream>
#include <stdlib.h>
#ifdef BOOSTUSE
typedef boost::chrono::high_resolution_clock high_resolution_clock;
typedef boost::chrono::milliseconds milliseconds;
#else
typedef std::chrono::high_resolution_clock high_resolution_clock;
typedef std::chrono::milliseconds milliseconds;
#endif
// N=1 000 000 - 12600
// number of ^5 powers to check
const int N = 86000; // max number is ~7131 for 64 bit values ( 18446744073709551616 )
// Min N=150 for 27 ^ 5 + 84 ^ 5 + 110 ^ 5 + 133 ^ 5 = 144 ^ 5 (Lander & Parkin, 1966).
// const int N = 86000; // 128 bit variables are required to operate with these values, uncomment define UINT128USE or DECIUSE at start of this file
// Min N=86000 for 55^5 + 3183^5 + 28969^5 + 85282^5 = 85359^5 (Frye, 2004). ( 85359^5 is 4531548087264753520490799 )
#ifdef UINT128USE
typedef uint128 ullong;
#endif
#ifdef BOOST128USE
typedef boost::multiprecision::uint128_t ullong;
#endif
#ifdef UINT64USE
typedef unsigned long long ullong;
#endif
// search type
// MAPUSE = unordered_map
//#define SEARCHMAPUSE
// BITSETVECTOR = bitmask + hash + vector
#define SEARCHBITSETVECTOR
typedef unsigned __int32 uint32;
typedef unsigned __int64 uint64;
ullong powers[N];
#ifdef BOOSTUSE
// Hash function to make int128 work with boost::hash.
std::size_t hash_value(uint128 const &input)
{
boost::hash<unsigned long long> hasher;
return hasher(input.GetHash64());
}
#else
namespace std
{
template <>
struct hash<uint128>
{
std::size_t operator()(const uint128& input) const
{
using std::size_t;
using std::hash;
return hash<unsigned long long>()(input.GetHash64());
}
};
}
#endif
struct CompValue
{
CompValue(ullong f, uint32 n)
{
fivePower = f;
number = n;
}
ullong fivePower;
uint32 number;
};
#ifdef BOOSTUSE
boost::container::vector<uint32> foundItems;
#ifdef SEARCHMAPUSE
boost::unordered_map<ullong, uint32> all;
#endif
#ifdef SEARCHBITSETVECTOR
boost::container::vector<CompValue*> setMap[256 * 256 * 16];
#endif
#else
std::vector<uint32> foundItems;
#ifdef SEARCHMAPUSE
std::unordered_map<ullong, uint32> all;
#endif
#ifdef SEARCHBITSETVECTOR
std::vector<CompValue*> setMap[256 * 256 * 16];
#endif
#endif
#ifdef SEARCHBITSETVECTOR
// buffer size is effective up to N=1000000 (over unordered_map performance)
uint32 bitseta[32768];
inline uint32 findBit(ullong fivePower)
{
#ifdef UINT128USE
//uint32 bitval = fivePower.GetHash16();
uint32 bitval = fivePower.GetHash32() & 0xFFFFF;
#else
uint32 bitval = (((uint32)((fivePower >> 32) ^ fivePower)));
bitval = (((bitval >> 16) ^ bitval) & 0xFFFF);
#endif
uint32 b = 1 << (bitval & 0x1F);
uint32 index = bitval >> 5;
if((bitseta[index] & b) > 0)
{
for (auto itm : setMap[bitval])
{
if (itm->fivePower == fivePower)
{
return itm->number;
}
}
}
return 0;
}
inline void setBit(ullong fivePower, uint32 number)
{
#ifdef UINT128USE
//uint32 bitval = fivePower.GetHash16();
uint32 bitval = fivePower.GetHash32() & 0xFFFFF;
#else
uint32 bitval = (((uint32)((fivePower >> 32) ^ fivePower)));
bitval = (((bitval >> 16) ^ bitval) & 0xFFFF);
#endif
setMap[bitval].push_back(new CompValue(fivePower, number));
uint32 b = 1 << (bitval & 0x1F);
uint32 index = bitval >> 5;
bitseta[index] = bitseta[index] | b;
}
#endif
ullong p5(ullong x)
{
return x * x * x * x * x;
}
milliseconds duration_cast_ms(high_resolution_clock::time_point minus)
{
#ifdef BOOSTUSE
return boost::chrono::duration_cast<milliseconds>(high_resolution_clock::now() - minus);
#else
return std::chrono::duration_cast<milliseconds>(high_resolution_clock::now() - minus);
#endif
}
void clearLine()
{
for (int i = 0; i < 77; ++i)
{
std::cout << " ";
}
}
int _tmain(int argc, _TCHAR* argv[])
{
high_resolution_clock::time_point _start = high_resolution_clock::now();
milliseconds speedTime;
std::cout << "Building table of powers 1 - " << N << "^5\n";
#ifdef SEARCHBITSETVECTOR
memset(bitseta, 0, sizeof(bitseta));
#endif
for (uint32 i = 0; i < N; ++i)
{
powers[i] = p5(i);
#ifdef SEARCHMAPUSE
all[powers[i]] = i;
#endif
#ifdef SEARCHBITSETVECTOR
setBit(powers[i], i);
#endif
}
speedTime = duration_cast_ms( _start );
std::cout << "Table ready. Building time: " << ((double)speedTime.count() / 1000 ) << "s, starting search...\n\n";
uint64 counter = 1, speed = 0, hitsspeed = 0;
uint32 foundTest, foundVal;
ullong sum = 0U, baseSum = 0U;
uint32 ind0 = 0x02;
uint32 ind1 = 0x02;
uint32 ind2 = 0x02;
uint32 ind3 = 0x02;
// base sum without ind0 for performance
baseSum = powers[ind1] + powers[ind2] + powers[ind3];
while (true)
{
sum = baseSum + powers[ind0];
#ifdef SEARCHBITSETVECTOR
foundVal = findBit(sum); // comment when using with map
if (foundVal > 0) // comment when using with map
#endif
{
#ifdef SEARCHMAPUSE
if (all.find(sum) != all.end())
#endif
{
#ifdef SEARCHMAPUSE
//foundItems
//only with map
foundVal = all[sum];
#endif
// clear line
clearLine();
std::cout << "\r";
for (auto ind : foundItems)
{
foundTest = foundVal / ind;
if ((foundTest * ind) == foundVal)
{
// duplicate
foundVal = 0;
break;
}
}
if (foundVal != 0)
{
std::cout << "\n\nOk, found: ";
std::cout << ind3 << "^5 + ";
std::cout << ind2 << "^5 + ";
std::cout << ind1 << "^5 + ";
std::cout << ind0 << "^5 = ";
std::cout << foundVal << "^5 ";
// store to check it later
foundItems.push_back(foundVal);
speedTime = duration_cast_ms(_start);
std::cout << "s: " << (double(speedTime.count()) / 1000) << " s. itr: " << counter << "\n\n";
}
else
{
std::cout << "duplicate";
}
}
}
// displaying some progress
counter++;
if ((counter & 0x3FFFFFF) == 0)
{
clearLine();
std::cout << "\r";
std::cout << ind3 << "^5 ";
std::cout << ind2 << "^5 ";
std::cout << ind1 << "^5 ";
std::cout << ind0 << "^5 ";
speedTime = duration_cast_ms( _start);
speed = counter / (uint64)speedTime.count();
// speed: iterations per millisecond, counter: total iterations
std::cout << "s: " << speed << " i/ms itrs: " << counter << "\r";
}
// displaying some progress
++ind0;
if (ind0 < N)
{
continue;
}
else
{
ind0 = ++ind1;
}
if (ind1 >= N)
{
ind0 = ind1 = ++ind2;
}
if (ind2 >= N)
{
ind0 = ind1 = ind2 = ++ind3;
}
if (ind3 >= N)
{
break;
}
// refresh without ind0
baseSum = powers[ind1] + powers[ind2] + powers[ind3];
}
clearLine();
milliseconds time = duration_cast_ms(_start);
std::cout << "\nDone in: " << ( double(time.count()) / 1000 ) << "s\n" << "Total iterations: " << counter << "\n";
speed = counter / (uint64)time.count();
std::cout << "Speed: " << speed << " itr/ms\n";
//getchar();
#ifdef SEARCHBITSETVECTOR
for (auto itm : setMap)
{
for (auto comp : itm)
{
delete comp;
}
}
#endif
return 0;
}
<commit_msg>buffer customization<commit_after>//
// Euler's sum of powers conjecture counterexample test without recursion
// Wikipedia: Euler's conjecture was disproven by L. J. Lander and T. R. Parkin
// in 1966 when, through a direct computer search on a CDC 6600, they found
// a counterexample for k = 5. A total of three primitive (that is, in which
// the summands do not all have a common factor) counterexamples are known:
// 27^5 + 84^5 + 110^5 + 133^5 = 144^5 (Lander & Parkin, 1966).
//
#include "stdafx.h"
typedef unsigned __int32 uint32;
typedef unsigned __int64 uint64;
#include "uint128.h"
// Value define
// uncomment to use unsigned int 64 bits. For N=500: ~440 000 000 its/s ( Max N=7100 )
//#define UINT64USE
// uncomment to use 128bit values by me ( 30% slower than uint64 ). For N=500: ~300 000 000 its/s(N=500) ( Max N=50859008 )
#define UINT128USE
// uncomment to use 128bit values by boost ( 17 times slower than uint64 ). For N=500: ~26 000 000 its/s(N=500) ( Max N=50859008 )
//#define BOOST128USE
// Lib define
// use boost as library or stl
#define BOOSTUSE // stl otherwise
// boost map: 413608 its/ms
// std mpa: 367906 its/ms
// boost map is 10% faster
// search type
// MAPUSE = unordered_map
//#define SEARCHMAPUSE
// BITSETVECTOR = bitmask + hash + vector
#define SEARCHBITSETVECTOR
// SEARCHBITSETVECTOR size in bytes. Must be power of 2
const uint32 SEARCHBITSETSIZE = 0x20000;
// Do not modify next values
const uint32 SEARCHBITSETSIZEARRAY = SEARCHBITSETSIZE / 4;
const uint32 SEARCHBITSETSIZEMASK = ((SEARCHBITSETSIZE * 8) - 1);
// Total memory consumption
// for SEARCHMAPUSE
// N in unordered_map + N array of values to hold powers
//
// for SEARCHBITSETVECTOR
// ( SEARCHBITSETSIZE * 193) + N array of values to hold powers + N of CompValue
// number of ^5 powers to check
const int N = 500; // max number is ~7131 for 64 bit values ( 18446744073709551616 )
// Min N=150 for 27 ^ 5 + 84 ^ 5 + 110 ^ 5 + 133 ^ 5 = 144 ^ 5 (Lander & Parkin, 1966).
// const int N = 86000; // 128 bit variables are required to operate with these values, uncomment define UINT128USE or DECIUSE at start of this file
// Min N=86000 for 55^5 + 3183^5 + 28969^5 + 85282^5 = 85359^5 (Frye, 2004). ( 85359^5 is 4531548087264753520490799 )
#ifdef BOOSTUSE
#include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */
#include <boost/unordered_map.hpp>
#include <boost/chrono.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/container/vector.hpp>
#else // stl
#include <unordered_map>
#include <chrono>
#include <vector>
#endif
#include <iostream>
#include <stdlib.h>
#ifdef BOOSTUSE
typedef boost::chrono::high_resolution_clock high_resolution_clock;
typedef boost::chrono::milliseconds milliseconds;
#else
typedef std::chrono::high_resolution_clock high_resolution_clock;
typedef std::chrono::milliseconds milliseconds;
#endif
#ifdef UINT128USE
typedef uint128 ullong;
#endif
#ifdef BOOST128USE
typedef boost::multiprecision::uint128_t ullong;
#endif
#ifdef UINT64USE
typedef unsigned long long ullong;
#endif
//####################################
// Array of powers
ullong powers[N];
//
//####################################
#ifdef BOOSTUSE
// Hash function to make int128 work with boost::hash.
std::size_t hash_value(uint128 const &input)
{
boost::hash<unsigned long long> hasher;
return hasher(input.GetHash64());
}
#else
namespace std
{
template <>
struct hash<uint128>
{
std::size_t operator()(const uint128& input) const
{
using std::size_t;
using std::hash;
return hash<unsigned long long>()(input.GetHash64());
}
};
}
#endif
struct CompValue
{
CompValue(ullong f, uint32 n)
{
fivePower = f;
number = n;
}
ullong fivePower;
uint32 number;
};
#ifdef BOOSTUSE
boost::container::vector<uint32> foundItems;
#ifdef SEARCHMAPUSE
boost::unordered_map<ullong, uint32> all;
#endif
#ifdef SEARCHBITSETVECTOR
boost::container::vector<CompValue*> setMap[ SEARCHBITSETSIZE * 8 ];
#endif
#else
std::vector<uint32> foundItems;
#ifdef SEARCHMAPUSE
std::unordered_map<ullong, uint32> all;
#endif
#ifdef SEARCHBITSETVECTOR
std::vector<CompValue*> setMap[ SEARCHBITSETSIZE * 8 ];
#endif
#endif
#ifdef SEARCHBITSETVECTOR
uint32 bitseta[SEARCHBITSETSIZEARRAY];
inline uint32 findBit(ullong fivePower)
{
#ifdef UINT128USE
//uint32 bitval = fivePower.GetHash16();
uint32 bitval = fivePower.GetHash32() & SEARCHBITSETSIZEMASK;
#else
uint32 bitval = (((uint32)((fivePower >> 32) ^ fivePower)));
bitval = (((bitval >> 16) ^ bitval) & SEARCHBITSETSIZEMASK);
#endif
uint32 b = 1 << (bitval & 0x1F);
uint32 index = bitval >> 5;
if((bitseta[index] & b) > 0)
{
for (auto itm : setMap[bitval])
{
if (itm->fivePower == fivePower)
{
return itm->number;
}
}
}
return 0;
}
inline void setBit(ullong fivePower, uint32 number)
{
#ifdef UINT128USE
//uint32 bitval = fivePower.GetHash16();
uint32 bitval = fivePower.GetHash32() & SEARCHBITSETSIZEMASK;
#else
uint32 bitval = (((uint32)((fivePower >> 32) ^ fivePower)));
bitval = (((bitval >> 16) ^ bitval) & SEARCHBITSETSIZEMASK);
#endif
setMap[bitval].push_back(new CompValue(fivePower, number));
uint32 b = 1 << (bitval & 0x1F);
uint32 index = bitval >> 5;
bitseta[index] = bitseta[index] | b;
}
#endif
ullong p5(ullong x)
{
return x * x * x * x * x;
}
milliseconds duration_cast_ms(high_resolution_clock::time_point minus)
{
#ifdef BOOSTUSE
return boost::chrono::duration_cast<milliseconds>(high_resolution_clock::now() - minus);
#else
return std::chrono::duration_cast<milliseconds>(high_resolution_clock::now() - minus);
#endif
}
void clearLine()
{
for (int i = 0; i < 77; ++i)
{
std::cout << " ";
}
std::cout << "\r";
}
int _tmain(int argc, _TCHAR* argv[])
{
high_resolution_clock::time_point _start = high_resolution_clock::now();
milliseconds speedTime;
std::cout << "Building table of powers 1 - " << N << "^5\n";
#ifdef SEARCHBITSETVECTOR
memset(bitseta, 0, sizeof(bitseta));
#endif
for (uint32 i = 0; i < N; ++i)
{
powers[i] = p5(i);
#ifdef SEARCHMAPUSE
all[powers[i]] = i;
#endif
#ifdef SEARCHBITSETVECTOR
setBit(powers[i], i);
#endif
}
speedTime = duration_cast_ms( _start );
std::cout << "Table ready. Building time: " << ((double)speedTime.count() / 1000 ) << "s, starting search...\n\n";
uint64 counter = 1, speed = 0, hitsspeed = 0;
uint32 foundTest, foundVal;
ullong sum = 0U, baseSum = 0U;
uint32 ind0 = 0x02;
uint32 ind1 = 0x02;
uint32 ind2 = 0x02;
uint32 ind3 = 0x02;
// base sum without ind0 for performance
baseSum = powers[ind1] + powers[ind2] + powers[ind3];
while (true)
{
sum = baseSum + powers[ind0];
#ifdef SEARCHBITSETVECTOR
foundVal = findBit(sum); // comment when using with map
if (foundVal > 0) // comment when using with map
#endif
{
#ifdef SEARCHMAPUSE
if (all.find(sum) != all.end())
#endif
{
#ifdef SEARCHMAPUSE
//foundItems
//only with map
foundVal = all[sum];
#endif
// clear line
clearLine();
for (auto ind : foundItems)
{
foundTest = foundVal / ind;
if ((foundTest * ind) == foundVal)
{
// duplicate
foundVal = 0;
break;
}
}
if (foundVal != 0)
{
std::cout << "\n\nOk, found: ";
std::cout << ind3 << "^5 + ";
std::cout << ind2 << "^5 + ";
std::cout << ind1 << "^5 + ";
std::cout << ind0 << "^5 = ";
std::cout << foundVal << "^5 ";
// store to check it later
foundItems.push_back(foundVal);
speedTime = duration_cast_ms(_start);
std::cout << "s: " << (double(speedTime.count()) / 1000) << " s. itr: " << counter << "\n\n";
}
else
{
std::cout << "duplicate";
}
}
}
// displaying some progress
counter++;
if ((counter & 0x3FFFFFF) == 0)
{
clearLine();
std::cout << ind3 << "^5 ";
std::cout << ind2 << "^5 ";
std::cout << ind1 << "^5 ";
std::cout << ind0 << "^5 ";
speedTime = duration_cast_ms( _start);
speed = counter / (uint64)speedTime.count();
// speed: iterations per millisecond, counter: total iterations
std::cout << "s: " << speed << " i/ms itrs: " << counter << "\r";
}
// displaying some progress
++ind0;
if (ind0 < N)
{
continue;
}
else
{
ind0 = ++ind1;
}
if (ind1 >= N)
{
ind0 = ind1 = ++ind2;
}
if (ind2 >= N)
{
ind0 = ind1 = ind2 = ++ind3;
}
if (ind3 >= N)
{
break;
}
// refresh without ind0
baseSum = powers[ind1] + powers[ind2] + powers[ind3];
}
clearLine();
milliseconds time = duration_cast_ms(_start);
std::cout << "\nDone in: " << ( double(time.count()) / 1000 ) << "s\n" << "Total iterations: " << counter << "\n";
speed = counter / (uint64)time.count();
std::cout << "Speed: " << speed << " itr/ms\n";
//getchar();
#ifdef SEARCHBITSETVECTOR
for (auto itm : setMap)
{
for (auto comp : itm)
{
delete comp;
}
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>//#include "blocksOverlap.h"
#include "ChimericDetection.h"
#include "ChimericSegment.h"
int chimericAlignScore (ChimericSegment & seg1, ChimericSegment & seg2)
{
int chimScore=0;
uint chimOverlap = seg2.roS>seg1.roS ? (seg2.roS>seg1.roE ? 0 : seg1.roE-seg2.roS+1) : (seg2.roE<seg1.roS ? 0 : seg2.roE-seg1.roS+1);
bool diffMates=(seg1.roE < seg1.align.readLength[0] && seg2.roS >= seg1.align.readLength[0]) || (seg2.roE < seg1.align.readLength[0] && seg1.roS >= seg1.align.readLength[0]);
//segment lengths && (different mates || small gap between segments)
if (seg1.roE > seg1.P.pCh.segmentMin + seg1.roS + chimOverlap && seg2.roE > seg1.P.pCh.segmentMin + seg2.roS + chimOverlap \
&& ( diffMates || ( (seg1.roE + seg1.P.pCh.segmentReadGapMax + 1) >= seg2.roS && (seg2.roE + seg1.P.pCh.segmentReadGapMax + 1) >= seg1.roS ) ) )
{
chimScore = seg1.align.maxScore + seg2.align.maxScore - (int)chimOverlap; //subtract overlap to avoid double counting
};
return chimScore;
};
/////////////////////////////////////////////////////////////
bool ChimericDetection::chimericDetectionMult(uint nW, uint *readLength) {
chimRecord=false;
// for (uint ii=0;ii<chimAligns.size();ii++) {//deallocate aligns
// if (chimAligns.at(ii).stitchingDone) {//al1,al2 were allocated
// delete chimAligns.at(ii).al1;
// delete chimAligns.at(ii).al2;
// };
// };
for (auto cAit=chimAligns.begin(); cAit<chimAligns.end(); cAit++) {//deallocate aligns
if (cAit->stitchingDone) {//al1,al2 were allocated
delete cAit->al1;
delete cAit->al2;
};
};
chimAligns.clear();
chimScoreBest=0;
int bestNonchimAlignScore = trBest->maxScore;
for (uint iW1=0; iW1<nW; iW1++) {//cycle windows
for (uint iA1=0; iA1<nWinTr[iW1]; iA1++) {//cycle aligns in the window
ChimericSegment seg1(P,*trAll[iW1][iA1]);
if (!seg1.segmentCheck())
continue; //seg1 is bad - skip
for (uint iW2=iW1; iW2<nW; iW2++) {//check all windows for chimeras
for (uint iA2=(iW1!=iW2 ? 0 : iA1+1); iA2<nWinTr[iW2]; iA2++) {//cycle over aligns in the window
//for the same window, start iA2 at iA1+1 to avoid duplicating
ChimericSegment seg2(P,*trAll[iW2][iA2]);
if (!seg2.segmentCheck())
continue; //seg2 is bad - skip
if (seg1.str!=0 && seg2.str!=0 && seg2.str!=seg1.str)
continue; //chimeric segments have to have consistent strands. TODO: make this optional
int chimScore=chimericAlignScore(seg1,seg2);
if (chimScore>0)
{//candidate chimera
ChimericAlign chAl(seg1, seg2, chimScore, outGen, RA);
if (!chAl.chimericCheck())
continue; //check chimeric alignment
if (chimScore>=chimScoreBest-(int)P.pCh.multimapScoreRange)
chimAligns.push_back(chAl);//add this chimeric alignment
if ( chimScore > chimScoreBest && chimScore >= P.pCh.scoreMin && chimScore >= (int)(readLength[0]+readLength[1]) - P.pCh.scoreDropMax ) {
chimAligns.back().chimericStitching(outGen.G, Read1[0]);
if (chimAligns.back().chimScore > chimScoreBest)
chimScoreBest=chimAligns.back().chimScore;
};
};
};//cycle over window2 aligns
};//cycle over window2
};//cycle over window1 aligns
};//cycle over window1
if (chimScoreBest==0)
return chimRecord;
chimN=0;
for (auto cAit=chimAligns.begin(); cAit<chimAligns.end(); cAit++) {//scan all chimeras, find the number within score range
if (cAit->chimScore >= chimScoreBest - (int)P.pCh.multimapScoreRange)
++chimN;
};
if (chimN > 2*P.pCh.multimapNmax) //too many loci (considering 2* more candidates for stitching below)
return chimRecord;
chimN=0;
for (auto cAit=chimAligns.begin(); cAit<chimAligns.end(); cAit++) {//re-scan all chimeras: stitch and re-check the score
if (cAit->chimScore >= chimScoreBest-(int)P.pCh.multimapScoreRange) {
cAit->chimericStitching(outGen.G, Read1[0]);
if (cAit->chimScore >= chimScoreBest - (int)P.pCh.multimapScoreRange)
++chimN;
};
};
if (chimN > P.pCh.multimapNmax) //too many loci
return chimRecord;
for (auto cAit=chimAligns.begin(); cAit<chimAligns.end(); cAit++) {//output chimeras within score range
if (cAit->chimScore >= chimScoreBest-(int)P.pCh.multimapScoreRange)
cAit->chimericJunctionOutput(*ostreamChimJunction, chimN);
};
if (chimN>0)
chimRecord=true;
return chimRecord;
};//END
<commit_msg>comparing chim score to non-chim align score<commit_after>//#include "blocksOverlap.h"
#include "ChimericDetection.h"
#include "ChimericSegment.h"
int chimericAlignScore (ChimericSegment & seg1, ChimericSegment & seg2)
{
int chimScore=0;
uint chimOverlap = seg2.roS>seg1.roS ? (seg2.roS>seg1.roE ? 0 : seg1.roE-seg2.roS+1) : (seg2.roE<seg1.roS ? 0 : seg2.roE-seg1.roS+1);
bool diffMates=(seg1.roE < seg1.align.readLength[0] && seg2.roS >= seg1.align.readLength[0]) || (seg2.roE < seg1.align.readLength[0] && seg1.roS >= seg1.align.readLength[0]);
//segment lengths && (different mates || small gap between segments)
if (seg1.roE > seg1.P.pCh.segmentMin + seg1.roS + chimOverlap && seg2.roE > seg1.P.pCh.segmentMin + seg2.roS + chimOverlap \
&& ( diffMates || ( (seg1.roE + seg1.P.pCh.segmentReadGapMax + 1) >= seg2.roS && (seg2.roE + seg1.P.pCh.segmentReadGapMax + 1) >= seg1.roS ) ) )
{
chimScore = seg1.align.maxScore + seg2.align.maxScore - (int)chimOverlap; //subtract overlap to avoid double counting
};
return chimScore;
};
/////////////////////////////////////////////////////////////
bool ChimericDetection::chimericDetectionMult(uint nW, uint *readLength) {
chimRecord=false;
// for (uint ii=0;ii<chimAligns.size();ii++) {//deallocate aligns
// if (chimAligns.at(ii).stitchingDone) {//al1,al2 were allocated
// delete chimAligns.at(ii).al1;
// delete chimAligns.at(ii).al2;
// };
// };
for (auto cAit=chimAligns.begin(); cAit<chimAligns.end(); cAit++) {//deallocate aligns
if (cAit->stitchingDone) {//al1,al2 were allocated
delete cAit->al1;
delete cAit->al2;
};
};
chimAligns.clear();
chimScoreBest=0;
int bestNonchimAlignScore = RA->trBest->maxScore;
for (uint iW1=0; iW1<nW; iW1++) {//cycle windows
for (uint iA1=0; iA1<nWinTr[iW1]; iA1++) {//cycle aligns in the window
ChimericSegment seg1(P,*trAll[iW1][iA1]);
if (!seg1.segmentCheck())
continue; //seg1 is bad - skip
for (uint iW2=iW1; iW2<nW; iW2++) {//check all windows for chimeras
for (uint iA2=(iW1!=iW2 ? 0 : iA1+1); iA2<nWinTr[iW2]; iA2++) {//cycle over aligns in the window
//for the same window, start iA2 at iA1+1 to avoid duplicating
ChimericSegment seg2(P,*trAll[iW2][iA2]);
if (!seg2.segmentCheck())
continue; //seg2 is bad - skip
if (seg1.str!=0 && seg2.str!=0 && seg2.str!=seg1.str)
continue; //chimeric segments have to have consistent strands. TODO: make this optional
int chimScore=chimericAlignScore(seg1,seg2);
if (chimScore>0)
{//candidate chimera
ChimericAlign chAl(seg1, seg2, chimScore, outGen, RA);
if (!chAl.chimericCheck())
continue; //check chimeric alignment
if (chimScore>=chimScoreBest-(int)P.pCh.multimapScoreRange)
chimAligns.push_back(chAl);//add this chimeric alignment
if ( chimScore > chimScoreBest && chimScore >= P.pCh.scoreMin && chimScore >= (int)(readLength[0]+readLength[1]) - P.pCh.scoreDropMax ) {
chimAligns.back().chimericStitching(outGen.G, Read1[0]);
if (chimAligns.back().chimScore > chimScoreBest)
chimScoreBest=chimAligns.back().chimScore;
};
};
};//cycle over window2 aligns
};//cycle over window2
};//cycle over window1 aligns
};//cycle over window1
if (chimScoreBest==0)
return chimRecord;
chimN=0;
for (auto cAit=chimAligns.begin(); cAit<chimAligns.end(); cAit++) {//scan all chimeras, find the number within score range
if (cAit->chimScore >= chimScoreBest - (int)P.pCh.multimapScoreRange)
++chimN;
};
if (chimN > 2*P.pCh.multimapNmax) //too many loci (considering 2* more candidates for stitching below)
return chimRecord;
chimN=0;
for (auto cAit=chimAligns.begin(); cAit<chimAligns.end(); cAit++) {//re-scan all chimeras: stitch and re-check the score
if (cAit->chimScore >= chimScoreBest-(int)P.pCh.multimapScoreRange) {
cAit->chimericStitching(outGen.G, Read1[0]);
if (cAit->chimScore >= chimScoreBest - (int)P.pCh.multimapScoreRange)
++chimN;
};
};
if (chimN > P.pCh.multimapNmax) //too many loci
return chimRecord;
for (auto cAit=chimAligns.begin(); cAit<chimAligns.end(); cAit++) {//output chimeras within score range
if (cAit->chimScore >= chimScoreBest-(int)P.pCh.multimapScoreRange)
cAit->chimericJunctionOutput(*ostreamChimJunction, chimN);
};
if (chimN>0)
chimRecord=true;
return chimRecord;
};//END
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* BP5Writer.cpp
*
*/
#include "BP5Writer.h"
#include "adios2/common/ADIOSMacros.h"
#include "adios2/core/IO.h"
#include "adios2/helper/adiosFunctions.h" //CheckIndexRange
#include "adios2/toolkit/format/buffer/chunk/ChunkV.h"
#include "adios2/toolkit/format/buffer/malloc/MallocV.h"
#include "adios2/toolkit/transport/file/FileFStream.h"
#include <adios2-perfstubs-interface.h>
#include <ctime>
#include <iostream>
namespace adios2
{
namespace core
{
namespace engine
{
using namespace adios2::format;
void BP5Writer::WriteData_TwoLevelShm(format::BufferV *Data)
{
const aggregator::MPIShmChain *a =
dynamic_cast<aggregator::MPIShmChain *>(m_Aggregator);
format::BufferV::BufferV_iovec DataVec = Data->DataVec();
// new step writing starts at offset m_DataPos on master aggregator
// other aggregators to the same file will need to wait for the position
// to arrive from the rank below
// align to PAGE_SIZE (only valid on master aggregator at this point)
m_DataPos += helper::PaddingToAlignOffset(m_DataPos,
m_Parameters.FileSystemPageSize);
/*
// Each aggregator needs to know the total size they write
// including alignment to page size
// This calculation is valid on aggregators only
std::vector<uint64_t> mySizes = a->m_Comm.GatherValues(Data->Size());
uint64_t myTotalSize = 0;
uint64_t pos = m_DataPos;
for (auto s : mySizes)
{
uint64_t alignment =
helper::PaddingToAlignOffset(pos, m_Parameters.FileSystemPageSize);
myTotalSize += alignment + s;
pos += alignment + s;
}
*/
// Each aggregator needs to know the total size they write
// This calculation is valid on aggregators only
std::vector<uint64_t> mySizes = a->m_Comm.GatherValues(Data->Size());
uint64_t myTotalSize = 0;
for (auto s : mySizes)
{
myTotalSize += s;
}
if (a->m_IsAggregator)
{
// In each aggregator chain, send from master down the line
// these total sizes, so every aggregator knows where to start
if (a->m_AggregatorChainComm.Rank() > 0)
{
a->m_AggregatorChainComm.Recv(
&m_DataPos, 1, a->m_AggregatorChainComm.Rank() - 1, 0,
"AggregatorChain token in BP5Writer::WriteData_TwoLevelShm");
// align to PAGE_SIZE
m_DataPos += helper::PaddingToAlignOffset(
m_DataPos, m_Parameters.FileSystemPageSize);
}
m_StartDataPos = m_DataPos; // metadata needs this info
if (a->m_AggregatorChainComm.Rank() <
a->m_AggregatorChainComm.Size() - 1)
{
uint64_t nextWriterPos = m_DataPos + myTotalSize;
a->m_AggregatorChainComm.Isend(
&nextWriterPos, 1, a->m_AggregatorChainComm.Rank() + 1, 0,
"Chain token in BP5Writer::WriteData");
}
else if (a->m_AggregatorChainComm.Size() > 1)
{
// send back final position from last aggregator in file to master
// aggregator
uint64_t nextWriterPos = m_DataPos + myTotalSize;
a->m_AggregatorChainComm.Isend(
&nextWriterPos, 1, 0, 0, "Chain token in BP5Writer::WriteData");
}
/*std::cout << "Rank " << m_Comm.Rank()
<< " aggregator start writing step " << m_WriterStep
<< " to subfile " << a->m_SubStreamIndex << " at pos "
<< m_DataPos << " totalsize " << myTotalSize << std::endl;*/
// Send token to first non-aggregator to start filling shm
// Also informs next process its starting offset (for correct metadata)
if (a->m_Comm.Size() > 1)
{
uint64_t nextWriterPos = m_DataPos + Data->Size();
a->m_Comm.Isend(&nextWriterPos, 1, a->m_Comm.Rank() + 1, 0,
"Shm token in BP5Writer::WriteData_TwoLevelShm");
}
WriteMyOwnData(DataVec);
/* Write from shm until every non-aggr sent all data */
if (a->m_Comm.Size() > 1)
{
WriteOthersData(myTotalSize - Data->Size());
}
// Master aggregator needs to know where the last writing ended by the
// last aggregator in the chain, so that it can start from the correct
// position at the next output step
if (a->m_AggregatorChainComm.Size() > 1 &&
!a->m_AggregatorChainComm.Rank())
{
a->m_AggregatorChainComm.Recv(
&m_DataPos, 1, a->m_AggregatorChainComm.Size() - 1, 0,
"Chain token in BP5Writer::WriteData");
}
}
else
{
// non-aggregators fill shared buffer in marching order
// they also receive their starting offset this way
a->m_Comm.Recv(&m_StartDataPos, 1, a->m_Comm.Rank() - 1, 0,
"Shm token in BP5Writer::WriteData_TwoLevelShm");
/*std::cout << "Rank " << m_Comm.Rank()
<< " non-aggregator recv token to fill shm = "
<< m_StartDataPos << std::endl;*/
SendDataToAggregator(DataVec, Data->Size());
if (a->m_Comm.Rank() < a->m_Comm.Size() - 1)
{
uint64_t nextWriterPos = m_StartDataPos + Data->Size();
a->m_Comm.Isend(&nextWriterPos, 1, a->m_Comm.Rank() + 1, 0,
"Shm token in BP5Writer::WriteData_TwoLevelShm");
}
}
delete[] DataVec;
}
void BP5Writer::WriteMyOwnData(format::BufferV::BufferV_iovec DataVec)
{
m_StartDataPos = m_DataPos;
int i = 0;
while (DataVec[i].iov_base != NULL)
{
if (i == 0)
{
m_FileDataManager.WriteFileAt((char *)DataVec[i].iov_base,
DataVec[i].iov_len, m_StartDataPos);
}
else
{
m_FileDataManager.WriteFiles((char *)DataVec[i].iov_base,
DataVec[i].iov_len);
}
m_DataPos += DataVec[i].iov_len;
i++;
}
}
void BP5Writer::SendDataToAggregator(format::BufferV::BufferV_iovec DataVec,
const size_t TotalSize)
{
/* Only one process is running this function at once
See shmFillerToken in the caller function
In a loop, copy the local data into the shared memory, alternating
between the two segments.
*/
aggregator::MPIShmChain *a =
dynamic_cast<aggregator::MPIShmChain *>(m_Aggregator);
size_t sent = 0;
int block = 0;
size_t temp_offset = 0;
while (DataVec[block].iov_base != nullptr)
{
// potentially blocking call waiting on Aggregator
aggregator::MPIShmChain::ShmDataBuffer *b = a->LockProducerBuffer();
// b->max_size: how much we can copy
// b->actual_size: how much we actually copy
b->actual_size = 0;
while (true)
{
if (DataVec[block].iov_base == nullptr)
{
break;
}
/* Copy n bytes from the current block, current offset to shm
making sure to use up to shm_size bytes
*/
size_t n = DataVec[block].iov_len - temp_offset;
if (n > (b->max_size - b->actual_size))
{
n = b->max_size - b->actual_size;
}
std::memcpy(&b->buf[b->actual_size],
(const char *)DataVec[block].iov_base + temp_offset, n);
b->actual_size += n;
/* Have we processed the entire block or staying with it? */
if (n + temp_offset < DataVec[block].iov_len)
{
temp_offset += n;
}
else
{
temp_offset = 0;
++block;
}
/* Have we reached the max allowed shm size ?*/
if (b->actual_size >= b->max_size)
{
break;
}
}
sent += b->actual_size;
/*std::cout << "Rank " << m_Comm.Rank()
<< " filled shm, data_size = " << b->actual_size
<< " block = " << block << " temp offset = " << temp_offset
<< " sent = " << sent
<< " buf = " << static_cast<void *>(b->buf) << " = ["
<< (int)b->buf[0] << (int)b->buf[1] << "..."
<< (int)b->buf[b->actual_size - 2]
<< (int)b->buf[b->actual_size - 1] << "]" << std::endl;*/
a->UnlockProducerBuffer();
}
}
void BP5Writer::WriteOthersData(size_t TotalSize)
{
/* Only an Aggregator calls this function */
aggregator::MPIShmChain *a =
dynamic_cast<aggregator::MPIShmChain *>(m_Aggregator);
size_t wrote = 0;
while (wrote < TotalSize)
{
// potentially blocking call waiting on some non-aggr process
aggregator::MPIShmChain::ShmDataBuffer *b = a->LockConsumerBuffer();
/*std::cout << "Rank " << m_Comm.Rank()
<< " write from shm, data_size = " << b->actual_size
<< " total so far = " << wrote
<< " buf = " << static_cast<void *>(b->buf) << " = ["
<< (int)b->buf[0] << (int)b->buf[1] << "..."
<< (int)b->buf[b->actual_size - 2]
<< (int)b->buf[b->actual_size - 1] << "]" << std::endl;*/
// b->actual_size: how much we need to write
m_FileDataManager.WriteFiles(b->buf, b->actual_size);
wrote += b->actual_size;
a->UnlockConsumerBuffer();
}
}
} // end namespace engine
} // end namespace core
} // end namespace adios2
<commit_msg>Fix: Keep track of file offset (m_DataPos) in the aggregator when writing out a non-aggregator's data, otherwise next step will start writing at a low offset overwriting the previous step..<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* BP5Writer.cpp
*
*/
#include "BP5Writer.h"
#include "adios2/common/ADIOSMacros.h"
#include "adios2/core/IO.h"
#include "adios2/helper/adiosFunctions.h" //CheckIndexRange
#include "adios2/toolkit/format/buffer/chunk/ChunkV.h"
#include "adios2/toolkit/format/buffer/malloc/MallocV.h"
#include "adios2/toolkit/transport/file/FileFStream.h"
#include <adios2-perfstubs-interface.h>
#include <ctime>
#include <iomanip>
#include <iostream>
namespace adios2
{
namespace core
{
namespace engine
{
using namespace adios2::format;
void BP5Writer::WriteData_TwoLevelShm(format::BufferV *Data)
{
const aggregator::MPIShmChain *a =
dynamic_cast<aggregator::MPIShmChain *>(m_Aggregator);
format::BufferV::BufferV_iovec DataVec = Data->DataVec();
// new step writing starts at offset m_DataPos on master aggregator
// other aggregators to the same file will need to wait for the position
// to arrive from the rank below
// align to PAGE_SIZE (only valid on master aggregator at this point)
m_DataPos += helper::PaddingToAlignOffset(m_DataPos,
m_Parameters.FileSystemPageSize);
/*
// Each aggregator needs to know the total size they write
// including alignment to page size
// This calculation is valid on aggregators only
std::vector<uint64_t> mySizes = a->m_Comm.GatherValues(Data->Size());
uint64_t myTotalSize = 0;
uint64_t pos = m_DataPos;
for (auto s : mySizes)
{
uint64_t alignment =
helper::PaddingToAlignOffset(pos, m_Parameters.FileSystemPageSize);
myTotalSize += alignment + s;
pos += alignment + s;
}
*/
// Each aggregator needs to know the total size they write
// This calculation is valid on aggregators only
std::vector<uint64_t> mySizes = a->m_Comm.GatherValues(Data->Size());
uint64_t myTotalSize = 0;
for (auto s : mySizes)
{
myTotalSize += s;
}
if (a->m_IsAggregator)
{
// In each aggregator chain, send from master down the line
// these total sizes, so every aggregator knows where to start
if (a->m_AggregatorChainComm.Rank() > 0)
{
a->m_AggregatorChainComm.Recv(
&m_DataPos, 1, a->m_AggregatorChainComm.Rank() - 1, 0,
"AggregatorChain token in BP5Writer::WriteData_TwoLevelShm");
// align to PAGE_SIZE
m_DataPos += helper::PaddingToAlignOffset(
m_DataPos, m_Parameters.FileSystemPageSize);
}
m_StartDataPos = m_DataPos; // metadata needs this info
if (a->m_AggregatorChainComm.Rank() <
a->m_AggregatorChainComm.Size() - 1)
{
uint64_t nextWriterPos = m_DataPos + myTotalSize;
a->m_AggregatorChainComm.Isend(
&nextWriterPos, 1, a->m_AggregatorChainComm.Rank() + 1, 0,
"Chain token in BP5Writer::WriteData");
}
else if (a->m_AggregatorChainComm.Size() > 1)
{
// send back final position from last aggregator in file to master
// aggregator
uint64_t nextWriterPos = m_DataPos + myTotalSize;
a->m_AggregatorChainComm.Isend(
&nextWriterPos, 1, 0, 0, "Chain token in BP5Writer::WriteData");
}
/*std::cout << "Rank " << m_Comm.Rank()
<< " aggregator start writing step " << m_WriterStep
<< " to subfile " << a->m_SubStreamIndex << " at pos "
<< m_DataPos << " totalsize " << myTotalSize << std::endl;*/
// Send token to first non-aggregator to start filling shm
// Also informs next process its starting offset (for correct metadata)
if (a->m_Comm.Size() > 1)
{
uint64_t nextWriterPos = m_DataPos + Data->Size();
a->m_Comm.Isend(&nextWriterPos, 1, a->m_Comm.Rank() + 1, 0,
"Shm token in BP5Writer::WriteData_TwoLevelShm");
}
WriteMyOwnData(DataVec);
/* Write from shm until every non-aggr sent all data */
if (a->m_Comm.Size() > 1)
{
WriteOthersData(myTotalSize - Data->Size());
}
// Master aggregator needs to know where the last writing ended by the
// last aggregator in the chain, so that it can start from the correct
// position at the next output step
if (a->m_AggregatorChainComm.Size() > 1 &&
!a->m_AggregatorChainComm.Rank())
{
a->m_AggregatorChainComm.Recv(
&m_DataPos, 1, a->m_AggregatorChainComm.Size() - 1, 0,
"Chain token in BP5Writer::WriteData");
}
}
else
{
// non-aggregators fill shared buffer in marching order
// they also receive their starting offset this way
a->m_Comm.Recv(&m_StartDataPos, 1, a->m_Comm.Rank() - 1, 0,
"Shm token in BP5Writer::WriteData_TwoLevelShm");
/*std::cout << "Rank " << m_Comm.Rank()
<< " non-aggregator recv token to fill shm = "
<< m_StartDataPos << std::endl;*/
SendDataToAggregator(DataVec, Data->Size());
if (a->m_Comm.Rank() < a->m_Comm.Size() - 1)
{
uint64_t nextWriterPos = m_StartDataPos + Data->Size();
a->m_Comm.Isend(&nextWriterPos, 1, a->m_Comm.Rank() + 1, 0,
"Shm token in BP5Writer::WriteData_TwoLevelShm");
}
}
delete[] DataVec;
}
void BP5Writer::WriteMyOwnData(format::BufferV::BufferV_iovec DataVec)
{
m_StartDataPos = m_DataPos;
int i = 0;
while (DataVec[i].iov_base != NULL)
{
if (i == 0)
{
m_FileDataManager.WriteFileAt((char *)DataVec[i].iov_base,
DataVec[i].iov_len, m_StartDataPos);
}
else
{
m_FileDataManager.WriteFiles((char *)DataVec[i].iov_base,
DataVec[i].iov_len);
}
m_DataPos += DataVec[i].iov_len;
i++;
}
}
/*std::string DoubleBufferToString(const double *b, int n)
{
std::ostringstream out;
out.precision(1);
out << std::fixed << "[";
char s[32];
for (int i = 0; i < n; ++i)
{
snprintf(s, sizeof(s), "%g", b[i]);
out << s;
if (i < n - 1)
{
out << ", ";
}
}
out << "]";
return out.str();
}*/
void BP5Writer::SendDataToAggregator(format::BufferV::BufferV_iovec DataVec,
const size_t TotalSize)
{
/* Only one process is running this function at once
See shmFillerToken in the caller function
In a loop, copy the local data into the shared memory, alternating
between the two segments.
*/
aggregator::MPIShmChain *a =
dynamic_cast<aggregator::MPIShmChain *>(m_Aggregator);
size_t sent = 0;
int block = 0;
size_t temp_offset = 0;
while (DataVec[block].iov_base != nullptr)
{
// potentially blocking call waiting on Aggregator
aggregator::MPIShmChain::ShmDataBuffer *b = a->LockProducerBuffer();
// b->max_size: how much we can copy
// b->actual_size: how much we actually copy
b->actual_size = 0;
while (true)
{
if (DataVec[block].iov_base == nullptr)
{
break;
}
/* Copy n bytes from the current block, current offset to shm
making sure to use up to shm_size bytes
*/
size_t n = DataVec[block].iov_len - temp_offset;
if (n > (b->max_size - b->actual_size))
{
n = b->max_size - b->actual_size;
}
std::memcpy(&b->buf[b->actual_size],
(const char *)DataVec[block].iov_base + temp_offset, n);
b->actual_size += n;
/* Have we processed the entire block or staying with it? */
if (n + temp_offset < DataVec[block].iov_len)
{
temp_offset += n;
}
else
{
temp_offset = 0;
++block;
}
/* Have we reached the max allowed shm size ?*/
if (b->actual_size >= b->max_size)
{
break;
}
}
sent += b->actual_size;
/*if (m_RankMPI >= 42)
{
std::cout << "Rank " << m_Comm.Rank()
<< " filled shm, data_size = " << b->actual_size
<< " block = " << block
<< " temp offset = " << temp_offset << " sent = " << sent
<< " buf = " << static_cast<void *>(b->buf) << " = "
<< DoubleBufferToString((double *)b->buf,
b->actual_size / sizeof(double))
<< std::endl;
}*/
a->UnlockProducerBuffer();
}
}
void BP5Writer::WriteOthersData(size_t TotalSize)
{
/* Only an Aggregator calls this function */
aggregator::MPIShmChain *a =
dynamic_cast<aggregator::MPIShmChain *>(m_Aggregator);
size_t wrote = 0;
while (wrote < TotalSize)
{
// potentially blocking call waiting on some non-aggr process
aggregator::MPIShmChain::ShmDataBuffer *b = a->LockConsumerBuffer();
/*std::cout << "Rank " << m_Comm.Rank()
<< " write from shm, data_size = " << b->actual_size
<< " total so far = " << wrote
<< " buf = " << static_cast<void *>(b->buf) << " = "
<< DoubleBufferToString((double *)b->buf,
b->actual_size / sizeof(double))
<< std::endl;*/
/*<< " buf = " << static_cast<void *>(b->buf) << " = ["
<< (int)b->buf[0] << (int)b->buf[1] << "..."
<< (int)b->buf[b->actual_size - 2]
<< (int)b->buf[b->actual_size - 1] << "]" << std::endl;*/
// b->actual_size: how much we need to write
m_FileDataManager.WriteFiles(b->buf, b->actual_size);
wrote += b->actual_size;
a->UnlockConsumerBuffer();
}
m_DataPos += TotalSize;
}
} // end namespace engine
} // end namespace core
} // end namespace adios2
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/threading/platform_thread.h"
#include "base/logging.h"
#include "base/threading/thread_local.h"
#include "base/threading/thread_restrictions.h"
#include "base/win/windows_version.h"
namespace base {
namespace {
static ThreadLocalPointer<char> current_thread_name;
// The information on how to set the thread name comes from
// a MSDN article: http://msdn2.microsoft.com/en-us/library/xcb2z8hs.aspx
const DWORD kVCThreadNameException = 0x406D1388;
typedef struct tagTHREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
struct ThreadParams {
PlatformThread::Delegate* delegate;
bool joinable;
};
DWORD __stdcall ThreadFunc(void* params) {
ThreadParams* thread_params = static_cast<ThreadParams*>(params);
PlatformThread::Delegate* delegate = thread_params->delegate;
if (!thread_params->joinable)
base::ThreadRestrictions::SetSingletonAllowed(false);
delete thread_params;
delegate->ThreadMain();
return NULL;
}
// CreateThreadInternal() matches PlatformThread::Create(), except that
// |out_thread_handle| may be NULL, in which case a non-joinable thread is
// created.
bool CreateThreadInternal(size_t stack_size,
PlatformThread::Delegate* delegate,
PlatformThreadHandle* out_thread_handle) {
PlatformThreadHandle thread_handle;
unsigned int flags = 0;
if (stack_size > 0 && base::win::GetVersion() >= base::win::VERSION_XP) {
flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
} else {
stack_size = 0;
}
ThreadParams* params = new ThreadParams;
params->delegate = delegate;
params->joinable = out_thread_handle != NULL;
// Using CreateThread here vs _beginthreadex makes thread creation a bit
// faster and doesn't require the loader lock to be available. Our code will
// have to work running on CreateThread() threads anyway, since we run code
// on the Windows thread pool, etc. For some background on the difference:
// http://www.microsoft.com/msj/1099/win32/win321099.aspx
thread_handle = CreateThread(
NULL, stack_size, ThreadFunc, params, flags, NULL);
if (!thread_handle) {
delete params;
return false;
}
if (out_thread_handle)
*out_thread_handle = thread_handle;
else
CloseHandle(thread_handle);
return true;
}
} // namespace
// static
PlatformThreadId PlatformThread::CurrentId() {
return GetCurrentThreadId();
}
// static
void PlatformThread::YieldCurrentThread() {
::Sleep(0);
}
// static
void PlatformThread::Sleep(int duration_ms) {
::Sleep(duration_ms);
}
// static
void PlatformThread::SetName(const char* name) {
current_thread_name.Set(const_cast<char*>(name));
// The debugger needs to be around to catch the name in the exception. If
// there isn't a debugger, we are just needlessly throwing an exception.
if (!::IsDebuggerPresent())
return;
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = CurrentId();
info.dwFlags = 0;
__try {
RaiseException(kVCThreadNameException, 0, sizeof(info)/sizeof(DWORD),
reinterpret_cast<DWORD_PTR*>(&info));
} __except(EXCEPTION_CONTINUE_EXECUTION) {
}
}
// static
const char* PlatformThread::GetName() {
return current_thread_name.Get();
}
// static
bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
PlatformThreadHandle* thread_handle) {
DCHECK(thread_handle);
return CreateThreadInternal(stack_size, delegate, thread_handle);
}
// static
bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
return CreateThreadInternal(stack_size, delegate, NULL);
}
// static
void PlatformThread::Join(PlatformThreadHandle thread_handle) {
DCHECK(thread_handle);
// TODO(willchan): Enable this check once I can get it to work for Windows
// shutdown.
// Joining another thread may block the current thread for a long time, since
// the thread referred to by |thread_handle| may still be running long-lived /
// blocking tasks.
#if 0
base::ThreadRestrictions::AssertIOAllowed();
#endif
// Wait for the thread to exit. It should already have terminated but make
// sure this assumption is valid.
DWORD result = WaitForSingleObject(thread_handle, INFINITE);
DCHECK_EQ(WAIT_OBJECT_0, result);
CloseHandle(thread_handle);
}
// static
void PlatformThread::SetThreadPriority(PlatformThreadHandle, ThreadPriority) {
// TODO(crogers): implement
NOTIMPLEMENTED();
}
} // namespace base
<commit_msg>Added code to verify whether TerminateProcess is hooked before calling it.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/threading/platform_thread.h"
#include "base/debug/alias.h"
#include "base/logging.h"
#include "base/threading/thread_local.h"
#include "base/threading/thread_restrictions.h"
#include "base/win/windows_version.h"
namespace base {
namespace {
static ThreadLocalPointer<char> current_thread_name;
// The information on how to set the thread name comes from
// a MSDN article: http://msdn2.microsoft.com/en-us/library/xcb2z8hs.aspx
const DWORD kVCThreadNameException = 0x406D1388;
typedef struct tagTHREADNAME_INFO {
DWORD dwType; // Must be 0x1000.
LPCSTR szName; // Pointer to name (in user addr space).
DWORD dwThreadID; // Thread ID (-1=caller thread).
DWORD dwFlags; // Reserved for future use, must be zero.
} THREADNAME_INFO;
struct ThreadParams {
PlatformThread::Delegate* delegate;
bool joinable;
};
DWORD __stdcall ThreadFunc(void* params) {
// TODO(apatrick): Remove this ASAP. This ensures that if the
// TerminateProcess entry point has been patched to point into a third party
// DLL, this is visible on the stack and the DLL in question can be
// determined.
typedef BOOL (WINAPI *TerminateProcessPtr)(HANDLE, UINT);
TerminateProcessPtr terminate_process = TerminateProcess;
base::debug::Alias(&terminate_process);
ThreadParams* thread_params = static_cast<ThreadParams*>(params);
PlatformThread::Delegate* delegate = thread_params->delegate;
if (!thread_params->joinable)
base::ThreadRestrictions::SetSingletonAllowed(false);
delete thread_params;
delegate->ThreadMain();
return NULL;
}
// CreateThreadInternal() matches PlatformThread::Create(), except that
// |out_thread_handle| may be NULL, in which case a non-joinable thread is
// created.
bool CreateThreadInternal(size_t stack_size,
PlatformThread::Delegate* delegate,
PlatformThreadHandle* out_thread_handle) {
PlatformThreadHandle thread_handle;
unsigned int flags = 0;
if (stack_size > 0 && base::win::GetVersion() >= base::win::VERSION_XP) {
flags = STACK_SIZE_PARAM_IS_A_RESERVATION;
} else {
stack_size = 0;
}
ThreadParams* params = new ThreadParams;
params->delegate = delegate;
params->joinable = out_thread_handle != NULL;
// Using CreateThread here vs _beginthreadex makes thread creation a bit
// faster and doesn't require the loader lock to be available. Our code will
// have to work running on CreateThread() threads anyway, since we run code
// on the Windows thread pool, etc. For some background on the difference:
// http://www.microsoft.com/msj/1099/win32/win321099.aspx
thread_handle = CreateThread(
NULL, stack_size, ThreadFunc, params, flags, NULL);
if (!thread_handle) {
delete params;
return false;
}
if (out_thread_handle)
*out_thread_handle = thread_handle;
else
CloseHandle(thread_handle);
return true;
}
} // namespace
// static
PlatformThreadId PlatformThread::CurrentId() {
return GetCurrentThreadId();
}
// static
void PlatformThread::YieldCurrentThread() {
::Sleep(0);
}
// static
void PlatformThread::Sleep(int duration_ms) {
::Sleep(duration_ms);
}
// static
void PlatformThread::SetName(const char* name) {
current_thread_name.Set(const_cast<char*>(name));
// The debugger needs to be around to catch the name in the exception. If
// there isn't a debugger, we are just needlessly throwing an exception.
if (!::IsDebuggerPresent())
return;
THREADNAME_INFO info;
info.dwType = 0x1000;
info.szName = name;
info.dwThreadID = CurrentId();
info.dwFlags = 0;
__try {
RaiseException(kVCThreadNameException, 0, sizeof(info)/sizeof(DWORD),
reinterpret_cast<DWORD_PTR*>(&info));
} __except(EXCEPTION_CONTINUE_EXECUTION) {
}
}
// static
const char* PlatformThread::GetName() {
return current_thread_name.Get();
}
// static
bool PlatformThread::Create(size_t stack_size, Delegate* delegate,
PlatformThreadHandle* thread_handle) {
DCHECK(thread_handle);
return CreateThreadInternal(stack_size, delegate, thread_handle);
}
// static
bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) {
return CreateThreadInternal(stack_size, delegate, NULL);
}
// static
void PlatformThread::Join(PlatformThreadHandle thread_handle) {
DCHECK(thread_handle);
// TODO(willchan): Enable this check once I can get it to work for Windows
// shutdown.
// Joining another thread may block the current thread for a long time, since
// the thread referred to by |thread_handle| may still be running long-lived /
// blocking tasks.
#if 0
base::ThreadRestrictions::AssertIOAllowed();
#endif
// Wait for the thread to exit. It should already have terminated but make
// sure this assumption is valid.
DWORD result = WaitForSingleObject(thread_handle, INFINITE);
DCHECK_EQ(WAIT_OBJECT_0, result);
CloseHandle(thread_handle);
}
// static
void PlatformThread::SetThreadPriority(PlatformThreadHandle, ThreadPriority) {
// TODO(crogers): implement
NOTIMPLEMENTED();
}
} // namespace base
<|endoftext|> |
<commit_before>#pragma once
#include <cstdint>
#include "pstream.hh"
#ifdef XV6_KERNEL
#include "cpu.hh"
#endif
// XXX(Austin) With decent per-CPU static variables, we could just use
// a per-CPU variable for each of these stats, plus some static
// constructor magic to build a list of them, and we could avoid this
// nonsense. OTOH, this struct is easy to get into user space.
#define KSTATS_TLB(X) \
/* # of TLB shootdown operations. One shootdown may target multiple \
* cores. */ \
X(uint64_t, tlb_shootdown_count) \
/* Total number of targets of TLB shootdowns. This divided by \
* tlb_shootdowns is the average number of targets per shootdown \
* operation. */ \
X(uint64_t, tlb_shootdown_targets) \
/* Total number of cycles spent in TLB shootdown operations. */ \
X(uint64_t, tlb_shootdown_cycles) \
#define KSTATS_VM(X) \
X(uint64_t, page_fault_count) \
X(uint64_t, page_fault_cycles) \
X(uint64_t, page_alloc_count) \
\
X(uint64_t, mmap_count) \
X(uint64_t, mmap_cycles) \
\
X(uint64_t, munmap_count) \
X(uint64_t, munmap_cycles) \
#define KSTATS_KALLOC(X) \
X(uint64_t, kalloc_page_alloc_count) \
X(uint64_t, kalloc_page_free_count) \
X(uint64_t, kalloc_hot_list_refill_count) \
X(uint64_t, kalloc_hot_list_flush_count) \
X(uint64_t, kalloc_hot_list_steal_count) \
#define KSTATS_ALL(X) \
KSTATS_TLB(X) \
KSTATS_VM(X) \
KSTATS_KALLOC(X) \
struct kstats
{
#define X(type, name) type name;
KSTATS_ALL(X)
#undef X
#ifdef XV6_KERNEL
template<class T>
static void inc(T kstats::* field, T delta = 1)
{
mykstats()->*field += delta;
}
class timer
{
uint64_t kstats::* field;
uint64_t start;
public:
timer(uint64_t kstats::* field) : field(field), start(rdtsc()) { }
~timer()
{
end();
}
void end()
{
if (field)
kstats::inc(field, rdtsc() - start);
field = nullptr;
}
};
#endif
kstats &operator+=(const kstats &o)
{
#define X(type, name) name += o.name;
KSTATS_ALL(X);
#undef X
return *this;
}
kstats operator-(const kstats &b) const
{
kstats res{};
#define X(type, name) res.name = name - b.name;
KSTATS_ALL(X);
#undef X
return res;
}
};
__attribute__((unused))
static void
to_stream(print_stream *s, const kstats &o)
{
#define X(type, name) s->println(o.name, " " #name);
KSTATS_ALL(X);
#undef X
}
<commit_msg>kstats: Add timer::abort method<commit_after>#pragma once
#include <cstdint>
#include "pstream.hh"
#ifdef XV6_KERNEL
#include "cpu.hh"
#endif
// XXX(Austin) With decent per-CPU static variables, we could just use
// a per-CPU variable for each of these stats, plus some static
// constructor magic to build a list of them, and we could avoid this
// nonsense. OTOH, this struct is easy to get into user space.
#define KSTATS_TLB(X) \
/* # of TLB shootdown operations. One shootdown may target multiple \
* cores. */ \
X(uint64_t, tlb_shootdown_count) \
/* Total number of targets of TLB shootdowns. This divided by \
* tlb_shootdowns is the average number of targets per shootdown \
* operation. */ \
X(uint64_t, tlb_shootdown_targets) \
/* Total number of cycles spent in TLB shootdown operations. */ \
X(uint64_t, tlb_shootdown_cycles) \
#define KSTATS_VM(X) \
X(uint64_t, page_fault_count) \
X(uint64_t, page_fault_cycles) \
X(uint64_t, page_alloc_count) \
\
X(uint64_t, mmap_count) \
X(uint64_t, mmap_cycles) \
\
X(uint64_t, munmap_count) \
X(uint64_t, munmap_cycles) \
#define KSTATS_KALLOC(X) \
X(uint64_t, kalloc_page_alloc_count) \
X(uint64_t, kalloc_page_free_count) \
X(uint64_t, kalloc_hot_list_refill_count) \
X(uint64_t, kalloc_hot_list_flush_count) \
X(uint64_t, kalloc_hot_list_steal_count) \
#define KSTATS_ALL(X) \
KSTATS_TLB(X) \
KSTATS_VM(X) \
KSTATS_KALLOC(X) \
struct kstats
{
#define X(type, name) type name;
KSTATS_ALL(X)
#undef X
#ifdef XV6_KERNEL
template<class T>
static void inc(T kstats::* field, T delta = 1)
{
mykstats()->*field += delta;
}
class timer
{
uint64_t kstats::* field;
uint64_t start;
public:
timer(uint64_t kstats::* field) : field(field), start(rdtsc()) { }
~timer()
{
end();
}
void end()
{
if (field)
kstats::inc(field, rdtsc() - start);
field = nullptr;
}
void abort()
{
field = nullptr;
}
};
#endif
kstats &operator+=(const kstats &o)
{
#define X(type, name) name += o.name;
KSTATS_ALL(X);
#undef X
return *this;
}
kstats operator-(const kstats &b) const
{
kstats res{};
#define X(type, name) res.name = name - b.name;
KSTATS_ALL(X);
#undef X
return res;
}
};
__attribute__((unused))
static void
to_stream(print_stream *s, const kstats &o)
{
#define X(type, name) s->println(o.name, " " #name);
KSTATS_ALL(X);
#undef X
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void Nr(int &k) {
int nrOfDigits = 0;
k /= 10;
int tmp = k;
while (tmp) {
++nrOfDigits;
tmp /= 10;
}
switch (nrOfDigits) {
case 2: k = k % 10; break;
case 3: k = k % 100; break;
case 4: k = k % 1000; break;
case 5: k = k % 10000; break;
case 6: k = k % 100000; break;
case 7: k = k % 1000000; break;
case 8: k = k % 10000000; break;
}
}
int main() {
int k = 12438;
Nr(k);
cout << k;
cout << endl;
return 0;
}
<commit_msg>reference.cpp was moved in 2009_99 directory<commit_after><|endoftext|> |
<commit_before>// $Id$
// Author: Constantin Loizides <mailto: [email protected]
#include <stream.h>
#include <libgen.h>
#include "AliL3RootTypes.h"
#include "AliL3Logger.h"
#include "AliL3MemHandler.h"
#include "AliL3AltroMemHandler.h"
#include "AliL3DigitData.h"
#include "AliL3Transform.h"
#include "AliL3Logging.h"
#include "AliL3Logger.h"
/**
Example program how to open and read a raw datafile.
In addition it shows, how to store (and read) the
digits in an Altro like data format.
*/
int main(int argc,char **argv)
{
Int_t slice=0;
Int_t patch=0;
Bool_t altroout=kFALSE;
FILE *afile=0;
AliL3Logger l;
l.Set(AliL3Logger::kAll);
//l.UseStderr();
//l.UseStdout();
//l.UseStream();
if(argc<2)
{
cout<<"Usage: read datafile [slice] [patch] [altrodatfile]"<<endl;
exit(1);
}
if (argc>2) {
slice=atoi(argv[2]);
}
if (argc>3) {
patch=atoi(argv[3]);
}
if (argc>4) {
altroout=kTRUE;
afile=fopen(argv[4],"w");
}
//Loading all specific aliroot version quantities, needed.
Char_t fname[1024];
strcpy(fname,argv[1]);
AliL3Transform::Init(dirname(fname));
strcpy(fname,argv[1]);
//Filehandler object:
AliL3MemHandler file;
//Give slice and patch information (see filename convention)
if((patch>=0)&&(patch<6)) file.Init(slice,patch);
else {
Int_t srows[2]={0,175};
patch=0;
file.Init(slice,patch,srows);
}
//Open the data file:
if(!file.SetBinaryInput(argv[1]))
{
cerr<<"Error opening file "<<argv[1]<<endl;
return -1;
}
//Create an RowData object to access the data
AliL3DigitRowData *digits=0;
UInt_t nrows=0;
//Read the file, and store the data in memory. Return value is a pointer to the data.
digits = file.CompBinary2Memory(nrows);
//Create an ALtroMemHandler object
AliL3AltroMemHandler altromem;
if(altroout) altroout=altromem.SetASCIIOutput(afile);
UShort_t time,charge;
UChar_t pad;
Int_t row=file.GetRowMin()-1,crows=0,lrow=row;
for(UInt_t r=0; r<nrows; r++) //Loop over padrows
{
//Get the data on this padrow:
AliL3DigitData *dataPt = (AliL3DigitData*)digits->fDigitData;
row++;
if(lrow+1==row) crows++;
//Loop over all digits on this padrow:
for(UInt_t ndig=0; ndig<digits->fNDigit; ndig++)
{
lrow=row;
pad = dataPt[ndig].fPad;
time = dataPt[ndig].fTime;
charge = dataPt[ndig].fCharge;
cout << "Padrow " << r << " pad " << (int)pad << " time " <<(int) time << " charge " << (int)charge << endl;
// cout << "Padrow " << row << " pad " << (int)pad << " time " <<(int) time << " charge " << (int)charge << endl;
if(altroout) altromem.Write(row,pad,time,charge);
}
//Move the pointer to the next padrow:
file.UpdateRowPointer(digits);
}
if(afile) {
altromem.WriteFinal();
fclose(afile);
#if 0
//test Altro read
UShort_t rrow=0,rtime=0,rcharge=0;
UChar_t rpad=0;
afile=fopen(argv[4],"r");
altromem.SetASCIIInput(afile);
while(altromem.Read(rrow,rpad,rtime,rcharge)){
cout << "Padrow " << (int)rrow << " pad " << (int)rpad << " time " <<(int)rtime << " charge " << (int)rcharge << endl;
}
fclose(afile);
#endif
#if 0
//test Altro read sequence
UShort_t rrow=0,rtime=0;
UChar_t rpad=0,n=100,i=100;
UShort_t *charges=new UShort_t[100];
afile=fopen(argv[4],"r");
altromem.SetASCIIInput(afile);
while(altromem.ReadSequence(rrow,rpad,rtime,i,&charges)){
cout << "Padrow " << (int)rrow << " pad " << (int)rpad << " time " <<(int)rtime << " charges ";
for(UChar_t ii=0;ii<i;ii++) cout << (int)charges[ii] << " ";
cout << endl;
i=n;
}
fclose(afile);
#endif
}
//cerr << "Rows: " << (file.GetRowMax()-file.GetRowMin()+1) << " Consecutive: " << crows << endl;
return 0;
}
<commit_msg>Rows per patch are locally stored.<commit_after>// $Id$
// Author: Constantin Loizides <mailto: [email protected]
#include <stream.h>
#include <libgen.h>
#include "AliL3RootTypes.h"
#include "AliL3Logger.h"
#include "AliL3MemHandler.h"
#include "AliL3AltroMemHandler.h"
#include "AliL3DigitData.h"
#include "AliL3Transform.h"
#include "AliL3Logging.h"
#include "AliL3Logger.h"
/**
Example program how to open and read a raw datafile.
In addition it shows, how to store (and read) the
digits in an Altro like data format.
*/
int main(int argc,char **argv)
{
Int_t slice=0;
Int_t patch=0;
Bool_t altroout=kFALSE;
FILE *afile=0;
AliL3Logger l;
l.Set(AliL3Logger::kAll);
//l.UseStderr();
//l.UseStdout();
//l.UseStream();
if(argc<2)
{
cout<<"Usage: read datafile [slice] [patch] [altrodatfile]"<<endl;
exit(1);
}
if (argc>2) {
slice=atoi(argv[2]);
}
if (argc>3) {
patch=atoi(argv[3]);
}
if (argc>4) {
altroout=kTRUE;
afile=fopen(argv[4],"w");
}
//Loading all specific aliroot version quantities, needed.
Char_t fname[1024];
strcpy(fname,argv[1]);
AliL3Transform::Init(dirname(fname));
strcpy(fname,argv[1]);
//Filehandler object:
AliL3MemHandler file;
//Give slice and patch information (see filename convention)
if((patch>=0)&&(patch<6)) file.Init(slice,patch);
else {
Int_t srows[2]={0,175};
patch=0;
file.Init(slice,patch,srows);
}
//Open the data file:
if(!file.SetBinaryInput(argv[1]))
{
cerr<<"Error opening file "<<argv[1]<<endl;
return -1;
}
//Create an RowData object to access the data
AliL3DigitRowData *digits=0;
UInt_t nrows=0;
//Read the file, and store the data in memory. Return value is a pointer to the data.
digits = file.CompBinary2Memory(nrows);
//Create an ALtroMemHandler object
AliL3AltroMemHandler altromem;
if(altroout) altroout=altromem.SetASCIIOutput(afile);
UShort_t time,charge;
UChar_t pad;
Int_t row=file.GetRowMin()-1,crows=0,lrow=row;
for(UInt_t r=0; r<nrows; r++) //Loop over padrows
{
//Get the data on this padrow:
AliL3DigitData *dataPt = (AliL3DigitData*)digits->fDigitData;
row++;
if(lrow+1==row) crows++;
//Loop over all digits on this padrow:
for(UInt_t ndig=0; ndig<digits->fNDigit; ndig++)
{
lrow=row;
pad = dataPt[ndig].fPad;
time = dataPt[ndig].fTime;
charge = dataPt[ndig].fCharge;
cout << "Padrow " << r << " pad " << (int)pad << " time " <<(int) time << " charge " << (int)charge << endl;
// cout << "Padrow " << row << " pad " << (int)pad << " time " <<(int) time << " charge " << (int)charge << endl;
if(altroout) altromem.Write(r,pad,time,charge);
}
//Move the pointer to the next padrow:
file.UpdateRowPointer(digits);
}
if(afile) {
altromem.WriteFinal();
fclose(afile);
#if 0
//test Altro read
UShort_t rrow=0,rtime=0,rcharge=0;
UChar_t rpad=0;
afile=fopen(argv[4],"r");
altromem.SetASCIIInput(afile);
while(altromem.Read(rrow,rpad,rtime,rcharge)){
cout << "Padrow " << (int)rrow << " pad " << (int)rpad << " time " <<(int)rtime << " charge " << (int)rcharge << endl;
}
fclose(afile);
#endif
#if 0
//test Altro read sequence
UShort_t rrow=0,rtime=0;
UChar_t rpad=0,n=100,i=100;
UShort_t *charges=new UShort_t[100];
afile=fopen(argv[4],"r");
altromem.SetASCIIInput(afile);
while(altromem.ReadSequence(rrow,rpad,rtime,i,&charges)){
cout << "Padrow " << (int)rrow << " pad " << (int)rpad << " time " <<(int)rtime << " charges ";
for(UChar_t ii=0;ii<i;ii++) cout << (int)charges[ii] << " ";
cout << endl;
i=n;
}
fclose(afile);
#endif
}
//cerr << "Rows: " << (file.GetRowMax()-file.GetRowMin()+1) << " Consecutive: " << crows << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* rkf78.hpp
*
* Created on: Wed Mar 16 2016
* Author: zhengfaxiang
*/
#ifndef RKF78_HPP_
#define RKF78_HPP_
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <string>
#include <stdexcept>
using namespace std;
template<class T, int dim>
class RKF78{
private:
static const T a[13]; // rk78 parameters
static const T b[13][12]; // rk78 parameters
T K[13][dim]; // runge-kutta parameters
T R[dim]; // error
T z[13][dim]; // make calculation of Ks easier
void GetZ(int l, T y[dim]);
void RungeKuttaParams78(T t, T h, T y[dim]);
void GetY(T y[dim]);
public:
long step; // step
T (*f[dim])(T t, T y[dim]); // functions to solve
void rkf78(T& h, T& t, T ynow[dim], T hmin, T TOL);
void solve(T hinit, T hmin, T y0[dim], T TOL, T begin, T end,
const char *filename);
};
template<class T, int dim>
const T RKF78<T, dim>::a[13] = {
0.0, 2.0/27.0, 1.0/9.0, 1.0/6.0, 5.0/12.0, 0.5,
5.0/6.0, 1.0/6.0, 2.0/3.0, 1.0/3.0, 1.0, 0.0, 1.0
};
template<class T, int dim>
const T RKF78<T, dim>::b[13][12] = {
{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{2.0/27.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{1.0/36.0, 1.0/12.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{1.0/24.0, 0.0, 1.0/8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{5.0/12.0, 0.0, -25.0/16.0, 25.0/16.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, },
{1.0/20.0, 0.0, 0.0, 1.0/4.0, 1.0/5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0},
{-25.0/108.0, 0.0, 0.0, 125.0/108.0, -65.0/27.0, 125.0/54.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0},
{31.0/300, 0.0, 0.0, 0.0, 61.0/225.0, -2.0/9.0, 13.0/900.0, 0.0,
0.0, 0.0, 0.0, 0.0},
{2.0, 0.0, 0.0, -53.0/6.0, 704.0/45.0, -107.0/9.0, 67.0/90.0, 3.0,
0.0, 0.0, 0.0, 0.0},
{-91.0/108.0, 0.0, 0.0, 23.0/108.0, -976.0/135.0, 311.0/54.0, -19.0/60.0,
17.0/6.0, -1.0/12.0, 0.0, 0.0, 0.0},
{2383.0/4100, 0.0, 0.0, -341.0/164.0, 4496.0/1025.0, -301.0/82.0,
2133.0/4100.0, 45.0/82.0, 45.0/164.0, 18.0/41.0, 0.0, 0.0},
{3.0/205.0, 0.0, 0.0, 0.0, 0.0, -6.0/41.0, -3.0/205.0, -3.0/41.0,
3.0/41.0, 6.0/41.0, 0.0, 0.0},
{-1777.0/4100.0, 0.0, 0.0, -341.0/164.0, 4496.0/1025.0, -289.0/82.0,
2193.0/4100.0, 51.0/82.0, 33.0/164.0, 12.0/41.0, 0.0, 1.0}
};
template<class T, int dim>
void RKF78<T, dim>::GetZ(int l, T y[dim]) {
T tmp[dim];
for (int i=0; i < dim; i++) {
tmp[i] = 0;
}
if (l != 0) {
for (int i=0; i < dim; i++) {
for (int j=0; j < l; j++) {
tmp[i] += K[j][i] * b[l][j];
}
}
}
for (int i=0; i < dim; i++) {
z[l][i] = y[i] + tmp[i];
}
}
template<class T, int dim>
void RKF78<T, dim>::RungeKuttaParams78(T t, T h, T y[dim]) {
// get runge-kutta parameters
for (int j=0; j < 13; j++) {
GetZ(j, y);
for (int i=0; i < dim; i++) {
K[j][i] = h * (*f[i])(t + h * a[j], z[j]);
}
}
}
template<class T, int dim>
void RKF78<T, dim>::GetY(T y[dim]) {
// get y using runge-kutta parameters
for (int i=0; i < dim; i++) {
y[i] += K[5][i] * 34.0 / 105.0 +
(K[6][i] + K[7][i]) * 9.0 / 35.0 +
(K[8][i] + K[9][i]) * 9.0 / 280.0 +
(K[11][i] + K[12][i]) * 41.0 / 840.0;
}
}
template<class T, int dim>
void RKF78<T, dim>::rkf78(T& h, T& t, T y[dim], T hmin, T TOL) {
// function to apply the runge-kutta-fehlberg method for one step
for (;;) {
RungeKuttaParams78(t, h, y); // get Ks
for (int i=0; i < dim; i++) { // finding errors
R[i] = (fabs(K[0][i] + K[10][i] - K[11][i] - K[12][i])\
* h * 41.0 / 810.0);
}
T MaxErr = *max_element(R, R + dim); // maximium value of array R
// T q=pow(TOL / (MaxErr * 2.0), 1.0 / 7.0);
if (MaxErr < TOL) {
GetY(y); // get Ys
// increase pace if error is too small
if (MaxErr < TOL / 10) {
h *= 2.0;
}
t += h;
break;
}
else {
h /= 2.0;
if (h < hmin){ // error handling
throw invalid_argument("Minimum h exceeded!");
}
}
}
}
template<class T, int dim>
void RKF78<T, dim>::solve(T hinit, T hmin, T y[dim], T TOL, T begin, T end,
const char *filename) {
// function to apply the runge-kutta-fehlberg method
// open a file in write mode.
ofstream outfile;
outfile.open(filename, ios::out);
T t = begin; // begin of t
T h = hinit; // begin of h
step = 0; // step
// output header
cout<<setw(28)<<"t"<<setw(28)<<"h";
outfile<<setw(28)<<"t"<<setw(28)<<"h";
for (int i=0; i < dim; i++) {
// convert number to string
ostringstream convert;
convert << i;
string yi = "y" + convert.str();
cout<<setw(28)<<yi;
outfile<<setw(28)<<yi;
}
cout<<endl;
outfile<<endl;
for (;t <= end;) {
rkf78(h, t, y, hmin, TOL); // calculate one step
step++; // step plus one
// output result
cout<<setiosflags(ios::scientific)
<<setprecision(18)<<setw(28)<<t
<<setw(28)<<h;
outfile<<setiosflags(ios::scientific)
<<setprecision(18)<<setw(28)<<t
<<setw(28)<<h;
for (int i=0; i < dim; i++) {
cout<<setiosflags(ios::scientific)<<setprecision(18)
<<setw(28)<<y[i];
outfile<<setiosflags(ios::scientific)<<setprecision(18)
<<setw(28)<<y[i];
}
cout<<endl;
outfile<<endl;
}
outfile.close(); // close the opened file.
cout<<"Procedure completed!"<<endl; // end
}
#endif /* RKF78_HPP_ */
<commit_msg>update<commit_after>/*
* rkf78.hpp
*
* Created on: Wed Mar 16 2016
* Author: zhengfaxiang
*/
#ifndef RKF78_HPP_
#define RKF78_HPP_
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <string>
#include <stdexcept>
using namespace std;
template<class T, int dim>
class RKF78{
private:
static const T a[13]; // rk78 parameters
static const T b[13][12]; // rk78 parameters
T K[13][dim]; // runge-kutta parameters
T R[dim]; // error
T z[13][dim]; // make calculation of Ks easier
void GetZ(int l, T y[dim]);
void RungeKuttaParams78(T t, T h, T y[dim]);
void GetY(T y[dim]);
public:
long step; // step
T (*f[dim])(T t, T y[dim]); // functions to solve
void rkf78(T& h, T& t, T ynow[dim], T hmin, T TOL);
void solve(T hinit, T hmin, T y0[dim], T TOL, T begin, T end,
const char *filename);
};
template<class T, int dim>
const T RKF78<T, dim>::a[13] = {
0.0, 2.0/27.0, 1.0/9.0, 1.0/6.0, 5.0/12.0, 0.5,
5.0/6.0, 1.0/6.0, 2.0/3.0, 1.0/3.0, 1.0, 0.0, 1.0
};
template<class T, int dim>
const T RKF78<T, dim>::b[13][12] = {
{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{2.0/27.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{1.0/36.0, 1.0/12.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{1.0/24.0, 0.0, 1.0/8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0},
{5.0/12.0, 0.0, -25.0/16.0, 25.0/16.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0, 0.0, },
{1.0/20.0, 0.0, 0.0, 1.0/4.0, 1.0/5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
0.0},
{-25.0/108.0, 0.0, 0.0, 125.0/108.0, -65.0/27.0, 125.0/54.0, 0.0,
0.0, 0.0, 0.0, 0.0, 0.0},
{31.0/300, 0.0, 0.0, 0.0, 61.0/225.0, -2.0/9.0, 13.0/900.0, 0.0,
0.0, 0.0, 0.0, 0.0},
{2.0, 0.0, 0.0, -53.0/6.0, 704.0/45.0, -107.0/9.0, 67.0/90.0, 3.0,
0.0, 0.0, 0.0, 0.0},
{-91.0/108.0, 0.0, 0.0, 23.0/108.0, -976.0/135.0, 311.0/54.0, -19.0/60.0,
17.0/6.0, -1.0/12.0, 0.0, 0.0, 0.0},
{2383.0/4100, 0.0, 0.0, -341.0/164.0, 4496.0/1025.0, -301.0/82.0,
2133.0/4100.0, 45.0/82.0, 45.0/164.0, 18.0/41.0, 0.0, 0.0},
{3.0/205.0, 0.0, 0.0, 0.0, 0.0, -6.0/41.0, -3.0/205.0, -3.0/41.0,
3.0/41.0, 6.0/41.0, 0.0, 0.0},
{-1777.0/4100.0, 0.0, 0.0, -341.0/164.0, 4496.0/1025.0, -289.0/82.0,
2193.0/4100.0, 51.0/82.0, 33.0/164.0, 12.0/41.0, 0.0, 1.0}
};
template<class T, int dim>
void RKF78<T, dim>::GetZ(int l, T y[dim]) {
T tmp[dim];
for (int i=0; i < dim; i++) {
tmp[i] = 0;
}
if (l != 0) {
for (int i=0; i < dim; i++) {
for (int j=0; j < l; j++) {
tmp[i] += K[j][i] * b[l][j];
}
}
}
for (int i=0; i < dim; i++) {
z[l][i] = y[i] + tmp[i];
}
}
template<class T, int dim>
void RKF78<T, dim>::RungeKuttaParams78(T t, T h, T y[dim]) {
// get runge-kutta parameters
for (int j=0; j < 13; j++) {
GetZ(j, y);
for (int i=0; i < dim; i++) {
K[j][i] = h * (*f[i])(t + h * a[j], z[j]);
}
}
}
template<class T, int dim>
void RKF78<T, dim>::GetY(T y[dim]) {
// get y using runge-kutta parameters
for (int i=0; i < dim; i++) {
y[i] += (K[5][i] * 34.0 / 105.0 +
(K[6][i] + K[7][i]) * 9.0 / 35.0 +
(K[8][i] + K[9][i]) * 9.0 / 280.0 +
(K[11][i] + K[12][i]) * 41.0 / 840.0);
}
}
template<class T, int dim>
void RKF78<T, dim>::rkf78(T& h, T& t, T y[dim], T hmin, T TOL) {
// function to apply the runge-kutta-fehlberg method for one step
for (;;) {
RungeKuttaParams78(t, h, y); // get Ks
for (int i=0; i < dim; i++) { // finding errors
R[i] = (fabs(K[0][i] + K[10][i] - K[11][i] - K[12][i])
* h * 41.0 / 810.0);
}
T MaxErr = *max_element(R, R + dim); // maximium value of array R
// T q=pow(TOL / (MaxErr * 2.0), 1.0 / 7.0);
if (MaxErr < TOL) {
GetY(y); // get Ys
// increase pace if error is too small
if (MaxErr < TOL / 10) {
h *= 2.0;
}
t += h;
break;
}
else {
h /= 2.0;
if (h < hmin){ // error handling
throw invalid_argument("Minimum h exceeded!");
}
}
}
}
template<class T, int dim>
void RKF78<T, dim>::solve(T hinit, T hmin, T y[dim], T TOL, T begin, T end,
const char *filename) {
// function to apply the runge-kutta-fehlberg method
// open a file in write mode.
ofstream outfile;
outfile.open(filename, ios::out);
T t = begin; // begin of t
T h = hinit; // begin of h
step = 0; // step
// output header
cout<<setw(28)<<"t"<<setw(28)<<"h";
outfile<<setw(28)<<"t"<<setw(28)<<"h";
for (int i=0; i < dim; i++) {
// convert number to string
ostringstream convert;
convert << i;
string yi = "y" + convert.str();
cout<<setw(28)<<yi;
outfile<<setw(28)<<yi;
}
cout<<endl;
outfile<<endl;
for (;t <= end;) {
rkf78(h, t, y, hmin, TOL); // calculate one step
step++; // step plus one
// output result
cout<<setiosflags(ios::scientific)
<<setprecision(18)<<setw(28)<<t
<<setw(28)<<h;
outfile<<setiosflags(ios::scientific)
<<setprecision(18)<<setw(28)<<t
<<setw(28)<<h;
for (int i=0; i < dim; i++) {
cout<<setiosflags(ios::scientific)<<setprecision(18)
<<setw(28)<<y[i];
outfile<<setiosflags(ios::scientific)<<setprecision(18)
<<setw(28)<<y[i];
}
cout<<endl;
outfile<<endl;
}
outfile.close(); // close the opened file.
cout<<"Procedure completed!"<<endl; // end
}
#endif /* RKF78_HPP_ */
<|endoftext|> |
<commit_before>#include "stack.hpp"
#ifndef STACK_CPP
#define STACK_CPP
template <typename T>
stack<T>::stack() : count_(0), array_size_(1), array_(new T[array_size_])
{}
template <typename T>
size_t stack<T> :: count() const
{
return count_;
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template <typename T>
void stack <T> :: push(const T& b)
{
if(count_==array_size_)
{
array_size_*=2;
T*l=copy_new(array_,count_,array_size_);
delete[] array_;
array_=l;
l=nullptr;
}
array_[count_]=b;
count_++;
}
template <typename T>
stack<T>::stack(const stack&c) : array_size_(c.array_size_),count_(c.count_), array_(copy_new(c.array_, c.count_, c.array_size_ ))
{};
/*template<typename T>
T*stack<T>::copy_new(const T*arr,size_t count,size_t array_size)
{T*l=new T[array_size];
std::copy(arr,arr+count,l);
return;}*/
template <typename T>
stack<T>& stack<T>::operator=(const stack &b)
{
if (this != &b)
{
delete[] array_;
array_size_ = b.array_size_;
count_ = b.count_;
array_ = copy_new(b.array_, count_, array_size_);
}
return *this;
}
template <typename T>
T stack<T>::pop()
{
if (!count_)
{
throw std::logic_error("Stack is empty!");
}
return array_[--count_];
}
template<typename T>
bool stack<T>::operator==(stack const & _s)
{
if ((_s.count_ != count_) || (_s.array_size_ != array_size_)) {
return false;
}
else {
for (size_t i = 0; i < count_; i++) {
if (_s.array_[i] != array_[i]) {
return false;
}
}
}
return true;
}
#endif
<commit_msg>Update stack.cpp<commit_after>#include "stack.hpp"
#ifndef STACK_CPP
#define STACK_CPP
template <typename T>
stack<T>::stack() : count_(0), array_size_(1), array_(new T[array_size_])
{}
template <typename T>
size_t stack<T> :: count() const
{
return count_;
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template <typename T>
void stack <T> :: push(const T& b)
{
if(count_==array_size_)
{
array_size_*=2;
T*l=copy_new(array_,count_,array_size_);
delete[] array_;
array_=l;
l=nullptr;
}
array_[count_]=b;
count_++;
}
template <typename T>
stack<T>::stack(const stack&c) : array_size_(c.array_size_),count_(c.count_), array_(copy_new(c.array_, c.count_, c.array_size_ ))
{};
/*template<typename T>
T*stack<T>::copy_new(const T*arr,size_t count,size_t array_size)
{T*l=new T[array_size];
std::copy(arr,arr+count,l);
return;}*/
template <typename T>
stack<T>& stack<T>::operator=(const stack &b)
{
if (this != &b)
{
delete[] array_;
array_size_ = b.array_size_;
count_ = b.count_;
array_ = copy_new(b.array_, count_, array_size_);
}
return *this;
}
template <typename T>
T stack<T>::pop()
{
if (!count_)
{
throw std::logic_error("Stack is empty!");
}
return array_[--count_];
}
template<typename T>
bool stack<T>::operator==(stack const & _s)
{
if ((_s.count_ != count_) || (_s.array_size_ != array_size_)) {
return false;
}
else {
for (size_t i = 0; i < count_; i++) {
if (_s.array_[i] != array_[i]) {
return false;
}
}
}
return true;
}
#endif
<|endoftext|> |
<commit_before>#include "Stack.hpp"
#include <stdexcept>
#ifndef STACK_CPP
#define STACK_CPP
template <typename T1, typename T2>
void construct(T1 * ptr, T2 const & value)
{
new(ptr) T1(value);
}
template <typename T>
void destroy(T * array) noexcept
{
array->~T();
}
template <typename FwdIter>
void destroy(FwdIter first, FwdIter last) noexcept
{
for (; first != last; ++first)
{
destroy(&*first);
}
}
template <typename T>
T* copy_new(const T * arr, size_t count, size_t array_size)
{
T * stk = new T[array_size];
try
{
std::copy(arr, arr + count, stk);
}
catch (...)
{
delete[] stk;
throw;
}
return stk;
};
template<typename T>
bool stack<T>::empty()const noexcept
{
return (allocator<T>::count_ == 0);
};
template <typename T>
allocator<T>::allocator(size_t size) : array_(static_cast<T *>(size == 0 ? nullptr : operator new(size * sizeof(T)))), array_size_(size), count_(0)
{};
template <typename T>
allocator<T>::~allocator()
{
operator delete(array_);
};
template <typename T>
void allocator<T>::swap(allocator& v)
{
std::swap(array_, v.array_);
std::swap(array_size_, v.array_size_);
std::swap(count_, v.count_);
};
template <typename T>
stack<T>::stack(size_t size) : allocator<T>(size)
{
}
template <typename T>
size_t stack<T>::count() const noexcept
{
return allocator<T>::count_;
}
template <typename T>
size_t stack<T>::pop()
{
if (allocator<T>::count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
destroy(allocator<T>::array_ + allocator<T>::count_);
return --allocator<T>::count_;
}
template <typename T>
const T& stack<T>::top()
{
if (allocator<T>::count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
return allocator<T>::array_[allocator<T>::count_ - 1];
}
template <typename T>
void stack<T>::push(T const &elem)
{
if (allocator<T>::count_ == allocator<T>::array_size_)
{
size_t array_size = allocator<T>::array_size_ * 2 + (allocator<T>::array_size_ == 0);
stack<T> temp(array_size);
while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::array_[temp.count()]);
this->swap(temp);
}
construct(allocator<T>::array_ + allocator<T>::count_, elem);
++allocator<T>::count_;
}
template <typename T>
stack<T>::~stack()
{
destroy(allocator<T>::ptr_, allocator<T>::ptr_ + allocator<T>::count_);
}
template <typename T>
stack<T>::stack(const stack&b)
{
allocator<T>::count_ = b.count_;
allocator<T>::array_size_ = b.array_size_;
allocator<T>::array_ = copy_new(b.array_, b.count_, b.array_size_);
}
template <typename T>
stack<T>& stack<T>::operator=(const stack &b)
{
if (this != &b)
{
T* stk = copy_new(b.array_, b.count_, b.array_size_);
delete[] allocator<T>::array_;
allocator<T>::array_ = stk;
allocator<T>::array_size_ = b.array_size_;
allocator<T>::count_ = b.count_;
}
return *this;
}
template<typename T>
bool stack<T>::operator==(stack const & _s)
{
if ((_s.count_ != allocator<T>::count_) || (_s.array_size_ != allocator<T>::array_size_)) {
return false;
}
else {
for (size_t i = 0; i < allocator<T>::count_; i++) {
if (_s.array_[i] != allocator<T>::array_[i]) {
return false;
}
}
}
return true;
}
#endif
<commit_msg>Update stack.cpp<commit_after>#include "Stack.hpp"
#include <stdexcept>
#ifndef STACK_CPP
#define STACK_CPP
template <typename T1, typename T2>
void construct(T1 * ptr, T2 const & value)
{
new(ptr) T1(value);
}
template <typename T>
void destroy(T * array) noexcept
{
array->~T();
}
template <typename FwdIter>
void destroy(FwdIter first, FwdIter last) noexcept
{
for (; first != last; ++first)
{
destroy(&*first);
}
}
template<typename T>
bool stack<T>::empty()const noexcept
{
return (allocator<T>::count_ == 0);
};
template <typename T>
allocator<T>::allocator(size_t size) : array_(static_cast<T *>(size == 0 ? nullptr : operator new(size * sizeof(T)))), array_size_(size), count_(0)
{};
template <typename T>
allocator<T>::~allocator()
{
operator delete(array_);
};
template <typename T>
void allocator<T>::swap(allocator& v)
{
std::swap(array_, v.array_);
std::swap(array_size_, v.array_size_);
std::swap(count_, v.count_);
};
template <typename T>
stack<T>::stack(size_t size) : allocator<T>(size)
{
}
template <typename T>
size_t stack<T>::count() const noexcept
{
return allocator<T>::count_;
}
template <typename T>
size_t stack<T>::pop()
{
if (allocator<T>::count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
destroy(allocator<T>::array_ + allocator<T>::count_);
return --allocator<T>::count_;
}
template <typename T>
const T& stack<T>::top()
{
if (allocator<T>::count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
return allocator<T>::array_[allocator<T>::count_ - 1];
}
template <typename T>
void stack<T>::push(T const &elem)
{
if (allocator<T>::count_ == allocator<T>::array_size_)
{
size_t array_size = allocator<T>::array_size_ * 2 + (allocator<T>::array_size_ == 0);
stack<T> temp(array_size);
while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::array_[temp.count()]);
this->swap(temp);
}
construct(allocator<T>::array_ + allocator<T>::count_, elem);
++allocator<T>::count_;
}
template <typename T>
stack<T>::~stack()
{
destroy(allocator<T>::ptr_, allocator<T>::ptr_ + allocator<T>::count_);
}
template <typename T>
stack<T>::stack(const stack&b)
{
allocator<T>::count_ = b.count_;
allocator<T>::array_size_ = b.array_size_;
allocator<T>::array_ = copy_new(b.array_, b.count_, b.array_size_);
}
template<typename T>
stack<T>& stack<T>::operator=(const stack& b){
if (this != &b){
stack<T> temp(b);
this->swap(temp);
}
return *this;
}
template<typename T>
bool stack<T>::operator==(stack const & _s)
{
if ((_s.count_ != allocator<T>::count_) || (_s.array_size_ != allocator<T>::array_size_)) {
return false;
}
else {
for (size_t i = 0; i < allocator<T>::count_; i++) {
if (_s.array_[i] != allocator<T>::array_[i]) {
return false;
}
}
}
return true;
}
#endif
<|endoftext|> |
<commit_before>#include "processdepth.h"
ProcessDepth::ProcessDepth()
{
}
bool ProcessDepth::detectHand(Mat depth, vector<int> &bbox,
Point3f ¢er, int &gesture)
{
Mat depth_in_range;
if (getContentInRange(depth, depth_in_range, bbox, 0.45)) {
return analyseGesture(depth_in_range, bbox, center, gesture);
}
else
return false;
}
bool ProcessDepth::getContentInRange(Mat depth, Mat &depth_out, vector<int> &bbox,
float range_max, float range_min)
{
depth_out = Mat(depth.size(), CV_32FC1, Scalar(0.0));
int rmin = 640;
int cmin = 480;
int rmax = 0;
int cmax = 0;
bool is_empty = true;
for (size_t r = 0; r < depth.rows; ++r) {
for (size_t c = 0; c < depth.cols; ++c) {
float val = depth.at<float>(r, c);
if (val > range_min && val < range_max) {
is_empty = false;
depth_out.at<float>(r, c) = val;
if (r < rmin) rmin = r;
if (c < cmin) cmin = c;
if (r > rmax) rmax = r;
if (c > cmax) cmax = c;
}
}
}
// In order xmin, ymin, xmax, ymax
bbox.push_back(cmin);
bbox.push_back(rmin);
bbox.push_back(cmax);
bbox.push_back(rmax);
return !is_empty;
}
bool ProcessDepth::analyseGesture(Mat depth, vector<int> bbox,
Point3f ¢er, int &gesture)
{
Mat depth_b(depth.size(), CV_32FC1, Scalar(0.0));
threshold(depth, depth_b, 0.0, 255.0, THRESH_BINARY);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
// Find contours
Mat depth_u(depth.size(), CV_8UC1, Scalar(0));
depth_b.convertTo(depth_u, CV_8UC1);
findContours(depth_b, contours, hierarchy, CV_RETR_TREE,
CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
// Find the convex hull object for the largest contour
vector<vector<Point> >hull(contours.size());
vector<Point> hull_max;
float rt = 0.0;
Point2f center_t;
for(int i = 0; i < contours.size(); i++ ) {
convexHull(Mat(contours[i]), hull[i], false);
Point2f ct;
float rad;
minEnclosingCircle(hull[i], ct, rad);
if (rad > rt) {
rt = rad;
center_t = ct;
hull_max = hull[i];
}
}
// Check the size of max hull and compare with bbox size
float size_hull = M_PI * pow(rt, 2);
float size_bbox = (bbox[2] - bbox[0])*(bbox[3] - bbox[1]);
float fx = 579.77;
float fy = 584.94;
float cx = 333.77;
float cy = 237.86;
float d = depth.at<float>(int(center_t.y), int(center_t.x));
center.x = (center_t.x - cx) * d / fx;
center.y = (center_t.y - cy) * d / fy;
center.z = d;
if (size_hull/size_bbox < 0.2) {
return false;
}
else if (size_hull/size_bbox > 0.8) {
gesture = 0;
return true;
}
else {
gesture = 5;
return true;
}
}
float ProcessDepth::getDepth(const Mat &depthImage, int x, int y,
bool smoothing, float maxZError,
bool estWithNeighborsIfNull)
{
int u = x;
int v = y;
bool isInMM = depthImage.type() == CV_16UC1; // is in mm?
// Inspired from RGBDFrame::getGaussianMixtureDistribution() method from
// https://github.com/ccny-ros-pkg/rgbdtools/blob/master/src/rgbd_frame.cpp
// Window weights:
// | 1 | 2 | 1 |
// | 2 | 4 | 2 |
// | 1 | 2 | 1 |
int u_start = max(u - 1, 0);
int v_start = max(v - 1, 0);
int u_end = min(u + 1, depthImage.cols - 1);
int v_end = min(v + 1, depthImage.rows - 1);
float depth = 0.0f;
if(isInMM) {
if(depthImage.at<unsigned short>(v, u) > 0 &&
depthImage.at<unsigned short>(v, u) < numeric_limits<unsigned short>::max()) {
depth = float(depthImage.at<unsigned short>(v, u)) * 0.001f;
}
}
else
depth = depthImage.at<float>(v, u);
if((depth == 0.0f || !uIsFinite(depth)) && estWithNeighborsIfNull) {
// all cells no2 must be under the zError to be accepted
float tmp = 0.0f;
int count = 0;
for(int uu = u_start; uu <= u_end; ++uu) {
for(int vv = v_start; vv <= v_end; ++vv) {
if((uu == u && vv != v) || (uu != u && vv == v)) {
float d = 0.0f;
if(isInMM) {
if(depthImage.at<unsigned short>(vv, uu) > 0 &&
depthImage.at<unsigned short>(vv, uu) < numeric_limits<unsigned short>::max()) {
depth = float(depthImage.at<unsigned short>(vv, uu)) * 0.001f;
}
}
else {
d = depthImage.at<float>(vv, uu);
}
if(d != 0.0f && uIsFinite(d)) {
if(tmp == 0.0f) {
tmp = d;
++count;
}
else if(fabs(d - tmp) < maxZError)
{
tmp += d;
++count;
}
}
}
}
}
if(count > 1) {
depth = tmp / float(count);
}
}
if(depth != 0.0f && uIsFinite(depth)) {
if(smoothing) {
float sumWeights = 0.0f;
float sumDepths = 0.0f;
for(int uu = u_start; uu <= u_end; ++uu) {
for(int vv = v_start; vv <= v_end; ++vv) {
if(!(uu == u && vv == v)) {
float d = 0.0f;
if(isInMM) {
if(depthImage.at<unsigned short>(vv,uu) > 0 &&
depthImage.at<unsigned short>(vv,uu) < numeric_limits<unsigned short>::max()) {
depth = float(depthImage.at<unsigned short>(vv,uu))*0.001f;
}
}
else {
d = depthImage.at<float>(vv,uu);
}
// ignore if not valid or depth difference is too high
if(d != 0.0f && uIsFinite(d) && fabs(d - depth) < maxZError)
{
if(uu == u || vv == v)
{
sumWeights += 2.0f;
d *= 2.0f;
}
else {
sumWeights+=1.0f;
}
sumDepths += d;
}
}
}
}
// set window weight to center point
depth *= 4.0f;
sumWeights += 4.0f;
// mean
depth = (depth+sumDepths)/sumWeights;
}
}
else {
depth = 0;
}
return depth;
}
<commit_msg>add hand recognize<commit_after>#include "processdepth.h"
ProcessDepth::ProcessDepth()
{
}
bool ProcessDepth::detectHand(Mat depth, vector<int> &bbox,
Point3f ¢er, int &gesture)
{
Mat depth_in_range;
if (getContentInRange(depth, depth_in_range, bbox, 0.45)) {
return analyseGesture(depth_in_range, bbox, center, gesture);
}
else
return false;
}
bool ProcessDepth::getContentInRange(Mat depth, Mat &depth_out, vector<int> &bbox,
float range_max, float range_min)
{
depth_out = Mat(depth.size(), CV_32FC1, Scalar(0.0));
int rmin = 640;
int cmin = 480;
int rmax = 0;
int cmax = 0;
bool is_empty = true;
for (size_t r = 0; r < depth.rows; ++r) {
for (size_t c = 0; c < depth.cols; ++c) {
float val = depth.at<float>(r, c);
if (val > range_min && val < range_max) {
is_empty = false;
depth_out.at<float>(r, c) = val;
if (r < rmin) rmin = r;
if (c < cmin) cmin = c;
if (r > rmax) rmax = r;
if (c > cmax) cmax = c;
}
}
}
// In order xmin, ymin, xmax, ymax
bbox.push_back(cmin);
bbox.push_back(rmin);
bbox.push_back(cmax);
bbox.push_back(rmax);
return !is_empty;
}
bool ProcessDepth::analyseGesture(Mat depth, vector<int> bbox,
Point3f ¢er, int &gesture)
{
Mat depth_b(depth.size(), CV_32FC1, Scalar(0.0));
threshold(depth, depth_b, 0.0, 255.0, THRESH_BINARY);
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
// Find contours
Mat depth_u(depth.size(), CV_8UC1, Scalar(0));
// FindContours support only 8uC1 and 32sC1 images
depth_b.convertTo(depth_u, CV_8UC1);
findContours(depth_u, contours, hierarchy, CV_RETR_TREE,
CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
// Find the convex hull object for the largest contour
vector<vector<Point> >hull(contours.size());
vector<Point> hull_max;
float rt = 0.0;
Point2f center_t;
for(int i = 0; i < contours.size(); i++ ) {
convexHull(Mat(contours[i]), hull[i], false);
Point2f ct;
float rad;
minEnclosingCircle(hull[i], ct, rad);
if (rad > rt) {
rt = rad;
center_t = ct;
hull_max = hull[i];
}
}
// Check the size of max hull and compare with bbox size
float size_hull = M_PI * pow(rt, 2);
float size_bbox = (bbox[2] - bbox[0])*(bbox[3] - bbox[1]);
float fx = 579.77;
float fy = 584.94;
float cx = 333.77;
float cy = 237.86;
float d = depth.at<float>(int(center_t.y), int(center_t.x));
center.x = (center_t.x - cx) * d / fx;
center.y = (center_t.y - cy) * d / fy;
center.z = d;
if (size_hull/size_bbox < 0.2) {
return false;
}
else if (size_hull/size_bbox > 0.8) {
gesture = 0;
return true;
}
else {
gesture = 5;
return true;
}
}
float ProcessDepth::getDepth(const Mat &depthImage, int x, int y,
bool smoothing, float maxZError,
bool estWithNeighborsIfNull)
{
int u = x;
int v = y;
bool isInMM = depthImage.type() == CV_16UC1; // is in mm?
// Inspired from RGBDFrame::getGaussianMixtureDistribution() method from
// https://github.com/ccny-ros-pkg/rgbdtools/blob/master/src/rgbd_frame.cpp
// Window weights:
// | 1 | 2 | 1 |
// | 2 | 4 | 2 |
// | 1 | 2 | 1 |
int u_start = max(u - 1, 0);
int v_start = max(v - 1, 0);
int u_end = min(u + 1, depthImage.cols - 1);
int v_end = min(v + 1, depthImage.rows - 1);
float depth = 0.0f;
if(isInMM) {
if(depthImage.at<unsigned short>(v, u) > 0 &&
depthImage.at<unsigned short>(v, u) < numeric_limits<unsigned short>::max()) {
depth = float(depthImage.at<unsigned short>(v, u)) * 0.001f;
}
}
else
depth = depthImage.at<float>(v, u);
if((depth == 0.0f || !uIsFinite(depth)) && estWithNeighborsIfNull) {
// all cells no2 must be under the zError to be accepted
float tmp = 0.0f;
int count = 0;
for(int uu = u_start; uu <= u_end; ++uu) {
for(int vv = v_start; vv <= v_end; ++vv) {
if((uu == u && vv != v) || (uu != u && vv == v)) {
float d = 0.0f;
if(isInMM) {
if(depthImage.at<unsigned short>(vv, uu) > 0 &&
depthImage.at<unsigned short>(vv, uu) < numeric_limits<unsigned short>::max()) {
depth = float(depthImage.at<unsigned short>(vv, uu)) * 0.001f;
}
}
else {
d = depthImage.at<float>(vv, uu);
}
if(d != 0.0f && uIsFinite(d)) {
if(tmp == 0.0f) {
tmp = d;
++count;
}
else if(fabs(d - tmp) < maxZError)
{
tmp += d;
++count;
}
}
}
}
}
if(count > 1) {
depth = tmp / float(count);
}
}
if(depth != 0.0f && uIsFinite(depth)) {
if(smoothing) {
float sumWeights = 0.0f;
float sumDepths = 0.0f;
for(int uu = u_start; uu <= u_end; ++uu) {
for(int vv = v_start; vv <= v_end; ++vv) {
if(!(uu == u && vv == v)) {
float d = 0.0f;
if(isInMM) {
if(depthImage.at<unsigned short>(vv,uu) > 0 &&
depthImage.at<unsigned short>(vv,uu) < numeric_limits<unsigned short>::max()) {
depth = float(depthImage.at<unsigned short>(vv,uu))*0.001f;
}
}
else {
d = depthImage.at<float>(vv,uu);
}
// ignore if not valid or depth difference is too high
if(d != 0.0f && uIsFinite(d) && fabs(d - depth) < maxZError)
{
if(uu == u || vv == v)
{
sumWeights += 2.0f;
d *= 2.0f;
}
else {
sumWeights+=1.0f;
}
sumDepths += d;
}
}
}
}
// set window weight to center point
depth *= 4.0f;
sumWeights += 4.0f;
// mean
depth = (depth+sumDepths)/sumWeights;
}
}
else {
depth = 0;
}
return depth;
}
<|endoftext|> |
<commit_before>
#ifndef DUNE_GRID_PART_LOCAL_INDEXBASED_HH
#define DUNE_GRID_PART_LOCAL_INDEXBASED_HH
// system
#include <map>
#include <set>
// dune-common
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
// dune-geometry
#include <dune/geometry/type.hh>
// dune-grid-multiscale
#include <dune/grid/part/interface.hh>
#include <dune/grid/part/iterator/local/indexbased.hh>
#include <dune/grid/part/iterator/intersection/local.hh>
#include <dune/grid/part/iterator/intersection/wrapper.hh>
#include <dune/grid/part/indexset/local.hh>
namespace Dune {
namespace grid {
namespace Part {
namespace Local {
namespace IndexBased {
template< class GlobalGridPartImp >
class Const;
template< class GlobalGridPartImp >
struct ConstTraits
{
typedef Dune::grid::Part::Interface< typename GlobalGridPartImp::Traits > GlobalGridPartType;
typedef Dune::grid::Part::Local::IndexBased::Const< GlobalGridPartImp > GridPartType;
typedef typename GlobalGridPartType::GridType GridType;
typedef typename Dune::grid::Part::IndexSet::Local::IndexBased< GlobalGridPartType > IndexSetType;
template< int codim >
struct Codim
{
template< PartitionIteratorType pitype >
struct Partition
{
typedef typename Dune::grid::Part::Iterator::Local::IndexBased< GlobalGridPartType, codim, pitype > IteratorType;
};
};
static const PartitionIteratorType indexSetPartitionType = GlobalGridPartType::indexSetPartitionType;
static const bool conforming = GlobalGridPartType::conforming;
typedef Dune::grid::Part::Iterator::Intersection::Wrapper::FakeDomainBoundary< GlobalGridPartType > IntersectionIteratorType;
}; // class ConstTraits
/**
* \todo Wrap entity, so that entity.ileaf{begin,end}() returns i{begin,end}(entity)
* \todo Implement boundaryId(intersection) by adding a std::map< intersectionIndex, boundaryId >!
*/
template< class GlobalGridPartImp >
class Const
: public Dune::grid::Part::Interface< Dune::grid::Part::Local::IndexBased::ConstTraits< GlobalGridPartImp > >
{
public:
typedef Const< GlobalGridPartImp > ThisType;
typedef Dune::grid::Part::Local::IndexBased::ConstTraits< GlobalGridPartImp > Traits;
typedef Dune::grid::Part::Interface< Traits > BaseType;
typedef typename Traits::GridType GridType;
typedef typename Traits::GlobalGridPartType GlobalGridPartType;
typedef typename Traits::IndexSetType IndexSetType;
typedef typename Traits::IntersectionIteratorType IntersectionIteratorType ;
typedef typename IntersectionIteratorType::Intersection IntersectionType;
typedef typename GridType::template Codim<0>::Entity EntityType;
typedef typename IndexSetType::IndexType IndexType;
typedef std::map< IndexType, IndexType > IndexMapType;
typedef Dune::GeometryType GeometryType;
//! container type for the indices
typedef std::map< GeometryType, std::map< IndexType, IndexType > > IndexContainerType;
//! container type for the boundary information
typedef std::map< IndexType, std::map< int, int > > BoundaryInfoContainerType;
Const(const Dune::shared_ptr< const GlobalGridPartType > globalGridPart,
const Dune::shared_ptr< const IndexContainerType > indexContainer,
const Dune::shared_ptr< const BoundaryInfoContainerType > boundaryInfoContainer)
: globalGridPart_(globalGridPart),
indexContainer_(indexContainer),
boundaryInfoContainer_(boundaryInfoContainer),
indexSet_(*globalGridPart_, indexContainer_)
{}
const IndexSetType& indexSet() const
{
return indexSet_;
}
const GridType& grid() const
{
return globalGridPart_->grid();
}
const GlobalGridPartType& globalGridPart() const
{
return globalGridPart_;
}
template< int codim >
typename BaseType::template Codim< codim >::IteratorType begin() const
{
return typename BaseType::template Codim< codim >::IteratorType(globalGridPart_, indexContainer_);
}
template< int codim, PartitionIteratorType pitype >
typename Traits::template Codim< codim >::template Partition< pitype >::IteratorType begin() const
{
return typename BaseType::template Codim< codim >::template Partition< pitype >::IteratorType(globalGridPart_, indexContainer_);
}
template< int codim >
typename BaseType::template Codim< codim >::IteratorType end() const
{
return typename BaseType::template Codim< codim >::IteratorType(globalGridPart_, indexContainer_, true);
}
template< int codim, PartitionIteratorType pitype >
typename Traits::template Codim< codim >::template Partition< pitype >::IteratorType end() const
{
return typename BaseType::template Codim< codim >::template Partition< pitype >::IteratorType(globalGridPart_, indexContainer_, true);
}
IntersectionIteratorType ibegin(const EntityType& entity) const
{
const IndexType& globalIndex = globalGridPart_->indexSet().index(entity);
const typename BoundaryInfoContainerType::const_iterator result = boundaryInfoContainer_->find(globalIndex);
// if this is an entity at the boundary
if (result != boundaryInfoContainer_->end()) {
// get the information for this entity
const std::map< int, int >& info = result->second;
// return wrapped iterator
return IntersectionIteratorType(globalGridPart_, entity, info);
} else {
// return iterator which just passes everything thrugh
return IntersectionIteratorType(globalGridPart_, entity);
} // if this is an entity at the boundary
} // IntersectionIteratorType ibegin(const EntityType& entity) const
IntersectionIteratorType iend(const EntityType& entity) const
{
const IndexType& globalIndex = globalGridPart_->indexSet().index(entity);
const typename BoundaryInfoContainerType::const_iterator result = boundaryInfoContainer_->find(globalIndex);
// if this is an entity at the boundary
if (result != boundaryInfoContainer_->end()) {
// get the information for this entity
const std::map< int, int >& info = result->second;
// return wrapped iterator
return IntersectionIteratorType(globalGridPart_, entity, info, true);
} else {
// return iterator which just passes everything thrugh
return IntersectionIteratorType(globalGridPart_, entity, true);
} // if this is an entity at the boundary
}
int boundaryId(const IntersectionType& intersection) const
{
DUNE_THROW(Dune::NotImplemented, "As long as I am not sure what this does or is used for I will not implement this!");
return intersection.boundaryId();
}
int level() const
{
return globalGridPart_->level();
}
template< class DataHandleImp ,class DataType >
void communicate(CommDataHandleIF< DataHandleImp, DataType > & data, InterfaceType iftype, CommunicationDirection dir) const
{
DUNE_THROW(Dune::NotImplemented, "As long as I am not sure what this does or is used for I will not implement this!");
globalGridPart_->communicate(data,iftype,dir);
}
private:
const Dune::shared_ptr< const GlobalGridPartType > globalGridPart_;
const Dune::shared_ptr< const IndexContainerType > indexContainer_;
const Dune::shared_ptr< const BoundaryInfoContainerType > boundaryInfoContainer_;
const IndexSetType indexSet_;
}; // class Const
template< class GlobalGridPartImp >
class ConstCoupling;
template< class GlobalGridPartImp >
struct ConstCouplingTraits
: public ConstTraits< GlobalGridPartImp >
{
typedef Dune::grid::Part::Interface< typename GlobalGridPartImp::Traits > GlobalGridPartType;
typedef Dune::grid::Part::Local::IndexBased::ConstCoupling< GlobalGridPartImp > GridPartType;
//! localized intersection iterator
typedef Dune::grid::Part::Iterator::Intersection::Local< GlobalGridPartType > IntersectionIteratorType;
}; // class ConstCouplingTraits
template< class GlobalGridPartImp >
class ConstCoupling
: public Const< GlobalGridPartImp >
{
public:
typedef ConstCoupling< GlobalGridPartImp > ThisType;
typedef Dune::grid::Part::Local::IndexBased::ConstCouplingTraits< GlobalGridPartImp > Traits;
typedef Const< GlobalGridPartImp > BaseType;
typedef typename Traits::IntersectionIteratorType IntersectionIteratorType;
typedef typename IntersectionIteratorType::Intersection IntersectionType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::GlobalGridPartType GlobalGridPartType;
typedef typename BaseType::IndexType IndexType;
typedef typename BaseType::IndexContainerType IndexContainerType;
typedef typename BaseType::BoundaryInfoContainerType BoundaryInfoContainerType;
typedef BaseType InsideType;
typedef BaseType OutsideType;
//! container type for the intersection information
typedef std::map< IndexType, std::set< int > > IntersectionInfoContainerType;
ConstCoupling(const Dune::shared_ptr< const GlobalGridPartType > globalGridPart,
const Dune::shared_ptr< const IndexContainerType > indexContainer,
const Dune::shared_ptr< const IntersectionInfoContainerType > intersectionContainer,
const Dune::shared_ptr< const InsideType > inside,
const Dune::shared_ptr< const OutsideType > outside)
: BaseType(globalGridPart, indexContainer, Dune::shared_ptr< const BoundaryInfoContainerType >(new BoundaryInfoContainerType())),
intersectionContainer_(intersectionContainer),
inside_(inside),
outside_(outside)
{}
IntersectionIteratorType ibegin(const EntityType& entity) const
{
const IndexType& globalIndex = BaseType::globalGridPart().indexSet().index(entity);
const typename IntersectionInfoContainerType::const_iterator result = intersectionContainer_->find(globalIndex);
assert(result != intersectionContainer_->end());
// get the information for this entity
const std::set< int >& info = result->second;
// return localized iterator
return IntersectionIteratorType(BaseType::globalGridPart(), entity, info);
} // IntersectionIteratorType ibegin(const EntityType& entity) const
IntersectionIteratorType iend(const EntityType& entity) const
{
const IndexType& globalIndex = BaseType::globalGridPart().indexSet().index(entity);
const typename IntersectionInfoContainerType::const_iterator result = intersectionContainer_->find(globalIndex);
assert(result != intersectionContainer_->end());
// get the information for this entity
const std::set< int >& info = result->second;
// return localized iterator
return IntersectionIteratorType(BaseType::globalGridPart(), entity, info, true);
} // IntersectionIteratorType iend(const EntityType& entity) const
Dune::shared_ptr< const InsideType > inside() const
{
return inside_;
}
Dune::shared_ptr< const InsideType > outside() const
{
return outside_;
}
private:
const Dune::shared_ptr< const IntersectionInfoContainerType > intersectionContainer_;
const Dune::shared_ptr< const InsideType > inside_;
const Dune::shared_ptr< const OutsideType > outside_;
}; // class ConstCoupling
} // namespace IndexBased
} // namespace Local
} // namespace Part
} // namespace grid
} // namespace Dune
#endif // DUNE_GRID_PART_LOCAL_INDEXBASED_HH
<commit_msg>[grid.part.local.indexbased] added local boundary grid part<commit_after>
#ifndef DUNE_GRID_PART_LOCAL_INDEXBASED_HH
#define DUNE_GRID_PART_LOCAL_INDEXBASED_HH
// system
#include <map>
#include <set>
// dune-common
#include <dune/common/shared_ptr.hh>
#include <dune/common/exceptions.hh>
// dune-geometry
#include <dune/geometry/type.hh>
// dune-grid-multiscale
#include <dune/grid/part/interface.hh>
#include <dune/grid/part/iterator/local/indexbased.hh>
#include <dune/grid/part/iterator/intersection/local.hh>
#include <dune/grid/part/iterator/intersection/wrapper.hh>
#include <dune/grid/part/indexset/local.hh>
namespace Dune {
namespace grid {
namespace Part {
namespace Local {
namespace IndexBased {
template< class GlobalGridPartImp >
class Const;
template< class GlobalGridPartImp >
struct ConstTraits
{
typedef Dune::grid::Part::Interface< typename GlobalGridPartImp::Traits > GlobalGridPartType;
typedef Dune::grid::Part::Local::IndexBased::Const< GlobalGridPartImp > GridPartType;
typedef typename GlobalGridPartType::GridType GridType;
typedef typename Dune::grid::Part::IndexSet::Local::IndexBased< GlobalGridPartType > IndexSetType;
template< int codim >
struct Codim
{
template< PartitionIteratorType pitype >
struct Partition
{
typedef typename Dune::grid::Part::Iterator::Local::IndexBased< GlobalGridPartType, codim, pitype > IteratorType;
};
};
static const PartitionIteratorType indexSetPartitionType = GlobalGridPartType::indexSetPartitionType;
static const bool conforming = GlobalGridPartType::conforming;
typedef Dune::grid::Part::Iterator::Intersection::Wrapper::FakeDomainBoundary< GlobalGridPartType > IntersectionIteratorType;
}; // class ConstTraits
/**
* \todo Wrap entity, so that entity.ileaf{begin,end}() returns i{begin,end}(entity)
* \todo Implement boundaryId(intersection) by adding a std::map< intersectionIndex, boundaryId >!
*/
template< class GlobalGridPartImp >
class Const
: public Dune::grid::Part::Interface< Dune::grid::Part::Local::IndexBased::ConstTraits< GlobalGridPartImp > >
{
public:
typedef Const< GlobalGridPartImp > ThisType;
typedef Dune::grid::Part::Local::IndexBased::ConstTraits< GlobalGridPartImp > Traits;
typedef Dune::grid::Part::Interface< Traits > BaseType;
typedef typename Traits::GridType GridType;
typedef typename Traits::GlobalGridPartType GlobalGridPartType;
typedef typename Traits::IndexSetType IndexSetType;
typedef typename Traits::IntersectionIteratorType IntersectionIteratorType ;
typedef typename IntersectionIteratorType::Intersection IntersectionType;
typedef typename GridType::template Codim<0>::Entity EntityType;
typedef typename IndexSetType::IndexType IndexType;
typedef std::map< IndexType, IndexType > IndexMapType;
typedef Dune::GeometryType GeometryType;
//! container type for the indices
typedef std::map< GeometryType, std::map< IndexType, IndexType > > IndexContainerType;
//! container type for the boundary information
typedef std::map< IndexType, std::map< int, int > > BoundaryInfoContainerType;
Const(const Dune::shared_ptr< const GlobalGridPartType > globalGridPart,
const Dune::shared_ptr< const IndexContainerType > indexContainer,
const Dune::shared_ptr< const BoundaryInfoContainerType > boundaryInfoContainer)
: globalGridPart_(globalGridPart),
indexContainer_(indexContainer),
boundaryInfoContainer_(boundaryInfoContainer),
indexSet_(*globalGridPart_, indexContainer_)
{}
const IndexSetType& indexSet() const
{
return indexSet_;
}
const GridType& grid() const
{
return globalGridPart_->grid();
}
const GlobalGridPartType& globalGridPart() const
{
return globalGridPart_;
}
template< int codim >
typename BaseType::template Codim< codim >::IteratorType begin() const
{
return typename BaseType::template Codim< codim >::IteratorType(globalGridPart_, indexContainer_);
}
template< int codim, PartitionIteratorType pitype >
typename Traits::template Codim< codim >::template Partition< pitype >::IteratorType begin() const
{
return typename BaseType::template Codim< codim >::template Partition< pitype >::IteratorType(globalGridPart_, indexContainer_);
}
template< int codim >
typename BaseType::template Codim< codim >::IteratorType end() const
{
return typename BaseType::template Codim< codim >::IteratorType(globalGridPart_, indexContainer_, true);
}
template< int codim, PartitionIteratorType pitype >
typename Traits::template Codim< codim >::template Partition< pitype >::IteratorType end() const
{
return typename BaseType::template Codim< codim >::template Partition< pitype >::IteratorType(globalGridPart_, indexContainer_, true);
}
IntersectionIteratorType ibegin(const EntityType& entity) const
{
const IndexType& globalIndex = globalGridPart_->indexSet().index(entity);
const typename BoundaryInfoContainerType::const_iterator result = boundaryInfoContainer_->find(globalIndex);
// if this is an entity at the boundary
if (result != boundaryInfoContainer_->end()) {
// get the information for this entity
const std::map< int, int >& info = result->second;
// return wrapped iterator
return IntersectionIteratorType(globalGridPart_, entity, info);
} else {
// return iterator which just passes everything thrugh
return IntersectionIteratorType(globalGridPart_, entity);
} // if this is an entity at the boundary
} // IntersectionIteratorType ibegin(const EntityType& entity) const
IntersectionIteratorType iend(const EntityType& entity) const
{
const IndexType& globalIndex = globalGridPart_->indexSet().index(entity);
const typename BoundaryInfoContainerType::const_iterator result = boundaryInfoContainer_->find(globalIndex);
// if this is an entity at the boundary
if (result != boundaryInfoContainer_->end()) {
// get the information for this entity
const std::map< int, int >& info = result->second;
// return wrapped iterator
return IntersectionIteratorType(globalGridPart_, entity, info, true);
} else {
// return iterator which just passes everything thrugh
return IntersectionIteratorType(globalGridPart_, entity, true);
} // if this is an entity at the boundary
}
int boundaryId(const IntersectionType& intersection) const
{
DUNE_THROW(Dune::NotImplemented, "As long as I am not sure what this does or is used for I will not implement this!");
return intersection.boundaryId();
}
int level() const
{
return globalGridPart_->level();
}
template< class DataHandleImp ,class DataType >
void communicate(CommDataHandleIF< DataHandleImp, DataType > & data, InterfaceType iftype, CommunicationDirection dir) const
{
DUNE_THROW(Dune::NotImplemented, "As long as I am not sure what this does or is used for I will not implement this!");
globalGridPart_->communicate(data,iftype,dir);
}
private:
const Dune::shared_ptr< const GlobalGridPartType > globalGridPart_;
const Dune::shared_ptr< const IndexContainerType > indexContainer_;
const Dune::shared_ptr< const BoundaryInfoContainerType > boundaryInfoContainer_;
const IndexSetType indexSet_;
}; // class Const
template< class GlobalGridPartImp >
class ConstCoupling;
template< class GlobalGridPartImp >
struct ConstCouplingTraits
: public ConstTraits< GlobalGridPartImp >
{
typedef Dune::grid::Part::Interface< typename GlobalGridPartImp::Traits > GlobalGridPartType;
typedef Dune::grid::Part::Local::IndexBased::ConstCoupling< GlobalGridPartImp > GridPartType;
//! localized intersection iterator
typedef Dune::grid::Part::Iterator::Intersection::Local< GlobalGridPartType > IntersectionIteratorType;
}; // class ConstCouplingTraits
template< class GlobalGridPartImp >
class ConstCoupling
: public Const< GlobalGridPartImp >
{
public:
typedef ConstCoupling< GlobalGridPartImp > ThisType;
typedef Dune::grid::Part::Local::IndexBased::ConstCouplingTraits< GlobalGridPartImp > Traits;
typedef Const< GlobalGridPartImp > BaseType;
typedef typename Traits::IntersectionIteratorType IntersectionIteratorType;
typedef typename IntersectionIteratorType::Intersection IntersectionType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::GlobalGridPartType GlobalGridPartType;
typedef typename BaseType::IndexType IndexType;
typedef typename BaseType::IndexContainerType IndexContainerType;
typedef typename BaseType::BoundaryInfoContainerType BoundaryInfoContainerType;
typedef BaseType InsideType;
typedef BaseType OutsideType;
//! container type for the intersection information
typedef std::map< IndexType, std::set< int > > IntersectionInfoContainerType;
ConstCoupling(const Dune::shared_ptr< const GlobalGridPartType > globalGridPart,
const Dune::shared_ptr< const IndexContainerType > indexContainer,
const Dune::shared_ptr< const IntersectionInfoContainerType > intersectionContainer,
const Dune::shared_ptr< const InsideType > inside,
const Dune::shared_ptr< const OutsideType > outside)
: BaseType(globalGridPart, indexContainer, Dune::shared_ptr< const BoundaryInfoContainerType >(new BoundaryInfoContainerType())),
intersectionContainer_(intersectionContainer),
inside_(inside),
outside_(outside)
{}
IntersectionIteratorType ibegin(const EntityType& entity) const
{
const IndexType& globalIndex = BaseType::globalGridPart().indexSet().index(entity);
const typename IntersectionInfoContainerType::const_iterator result = intersectionContainer_->find(globalIndex);
assert(result != intersectionContainer_->end());
// get the information for this entity
const std::set< int >& info = result->second;
// return localized iterator
return IntersectionIteratorType(BaseType::globalGridPart(), entity, info);
} // IntersectionIteratorType ibegin(const EntityType& entity) const
IntersectionIteratorType iend(const EntityType& entity) const
{
const IndexType& globalIndex = BaseType::globalGridPart().indexSet().index(entity);
const typename IntersectionInfoContainerType::const_iterator result = intersectionContainer_->find(globalIndex);
assert(result != intersectionContainer_->end());
// get the information for this entity
const std::set< int >& info = result->second;
// return localized iterator
return IntersectionIteratorType(BaseType::globalGridPart(), entity, info, true);
} // IntersectionIteratorType iend(const EntityType& entity) const
Dune::shared_ptr< const InsideType > inside() const
{
return inside_;
}
Dune::shared_ptr< const InsideType > outside() const
{
return outside_;
}
private:
const Dune::shared_ptr< const IntersectionInfoContainerType > intersectionContainer_;
const Dune::shared_ptr< const InsideType > inside_;
const Dune::shared_ptr< const OutsideType > outside_;
}; // class ConstCoupling
template< class GlobalGridPartImp >
class ConstBoundary;
template< class GlobalGridPartImp >
struct ConstBoundaryTraits
: public ConstTraits< GlobalGridPartImp >
{
typedef Dune::grid::Part::Interface< typename GlobalGridPartImp::Traits > GlobalGridPartType;
typedef Dune::grid::Part::Local::IndexBased::ConstBoundary< GlobalGridPartImp > GridPartType;
//! localized intersection iterator
typedef Dune::grid::Part::Iterator::Intersection::Local< GlobalGridPartType > IntersectionIteratorType;
}; // class ConstBoundaryTraits
template< class GlobalGridPartImp >
class ConstBoundary
: public Const< GlobalGridPartImp >
{
public:
typedef ConstBoundary< GlobalGridPartImp > ThisType;
typedef Dune::grid::Part::Local::IndexBased::ConstBoundaryTraits< GlobalGridPartImp > Traits;
typedef Const< GlobalGridPartImp > BaseType;
typedef typename Traits::IntersectionIteratorType IntersectionIteratorType;
typedef typename IntersectionIteratorType::Intersection IntersectionType;
typedef typename BaseType::EntityType EntityType;
typedef typename BaseType::GlobalGridPartType GlobalGridPartType;
typedef typename BaseType::IndexType IndexType;
typedef typename BaseType::IndexContainerType IndexContainerType;
typedef typename BaseType::BoundaryInfoContainerType BoundaryInfoContainerType;
typedef BaseType InsideType;
typedef BaseType OutsideType;
//! container type for the intersection information
typedef std::map< IndexType, std::set< int > > IntersectionInfoContainerType;
ConstBoundary(const Dune::shared_ptr< const GlobalGridPartType > globalGridPart,
const Dune::shared_ptr< const IndexContainerType > indexContainer,
const Dune::shared_ptr< const IntersectionInfoContainerType > intersectionContainer,
const Dune::shared_ptr< const InsideType > inside)
: BaseType(globalGridPart, indexContainer, Dune::shared_ptr< const BoundaryInfoContainerType >(new BoundaryInfoContainerType())),
intersectionContainer_(intersectionContainer),
inside_(inside)
{}
IntersectionIteratorType ibegin(const EntityType& entity) const
{
const IndexType& globalIndex = BaseType::globalGridPart().indexSet().index(entity);
const typename IntersectionInfoContainerType::const_iterator result = intersectionContainer_->find(globalIndex);
assert(result != intersectionContainer_->end());
// get the information for this entity
const std::set< int >& info = result->second;
// return localized iterator
return IntersectionIteratorType(BaseType::globalGridPart(), entity, info);
} // IntersectionIteratorType ibegin(const EntityType& entity) const
IntersectionIteratorType iend(const EntityType& entity) const
{
const IndexType& globalIndex = BaseType::globalGridPart().indexSet().index(entity);
const typename IntersectionInfoContainerType::const_iterator result = intersectionContainer_->find(globalIndex);
assert(result != intersectionContainer_->end());
// get the information for this entity
const std::set< int >& info = result->second;
// return localized iterator
return IntersectionIteratorType(BaseType::globalGridPart(), entity, info, true);
} // IntersectionIteratorType iend(const EntityType& entity) const
Dune::shared_ptr< const InsideType > inside() const
{
return inside_;
}
private:
const Dune::shared_ptr< const IntersectionInfoContainerType > intersectionContainer_;
const Dune::shared_ptr< const InsideType > inside_;
}; // class ConstCoupling
} // namespace IndexBased
} // namespace Local
} // namespace Part
} // namespace grid
} // namespace Dune
#endif // DUNE_GRID_PART_LOCAL_INDEXBASED_HH
<|endoftext|> |
<commit_before>#include <tiramisu/tiramisu.h>
#include "benchmarks.h"
using namespace tiramisu;
/**
* Benchmark for BLAS SYRK
* out = alpha * A * A' + beta * C
*
* A : a N by K matrix
* C : a symmetric N by N matrix
* alpha, beta : scalars
* A' is the transpose of A
*/
/**
We will make a tiramisu implementation of this code :
for(int i = 0; i<N; i++){
for(int j = 0; j<=i; j++){
int tmp = 0;
for(k=0; k<K; k++)
tmp += A[i][k] * A[j][k];
RESULT[i][j] = alpha * tmp + beta* C[i][j];
}
}
*/
int main(int argc, char **argv)
{
tiramisu::init();
function syrk("syrk");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
computation SIZES("{SIZES[e]: 0<=e<2}", expr(), false, p_float64, &syrk);
//Constants
constant NN("NN", SIZES(0), p_int32, true, NULL, 0, &syrk);
constant KK("KK", SIZES(1), p_int32, true, NULL, 0, &syrk);
//Iteration variables
var i("i"), j("j"), k("k");
//Inputs
computation A("[NN,KK]->{A[i,k]: 0<=i<NN and 0<=k<KK}", expr(), false, p_float64, &syrk);
computation C("[NN]->{C[i,j]: 0<=i<NN and 0<=j<NN}", expr(), false, p_float64, &syrk);
computation alpha("{alpha[0]}", expr(), false, p_float64, &syrk);
computation beta("{beta[0]}", expr(), false, p_float64, &syrk);
//Computations
computation result_init("[NN]->{result_init[i,j]: 0<=i<NN and 0<=j<=i}", expr(cast(p_float64, 0)), true, p_float64, &syrk);
computation mat_mul("[NN,KK]->{mat_mul[i,j,k]: 0<=i<NN and 0<=j<=i and 0<=k<KK}", expr(), true, p_float64, &syrk);
computation mult_alpha("[NN]->{mult_alpha[i,j]: 0<=i<NN and 0<=j<=i}", expr(), true, p_float64, &syrk);
computation add_beta_C("[NN]->{add_beta_C[i,j]: 0<=i<NN and 0<=j<=i}", expr(), true, p_float64, &syrk);
computation copy_symmetric_part("[NN]->{copy_symmetric_part[i,j]: 0<=i<NN and i<j<NN}", expr(), true, p_float64, &syrk);
mat_mul.set_expression(expr(mat_mul(i, j, k-1) + A(i, k) * A(j, k)));
mult_alpha.set_expression(expr(alpha(0) * mat_mul(i, j, NN-1)));
add_beta_C.set_expression(expr(mult_alpha(i, j) + beta(0) * C(i, j)));
copy_symmetric_part.set_expression(expr(add_beta_C(j, i)));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
copy_symmetric_part.after(add_beta_C, computation::root_dimension);
add_beta_C.after(mult_alpha, i);
mult_alpha.after(mat_mul, i);
mat_mul.after(result_init, i);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
//Input Buffers
buffer buf_SIZES("buf_SIZES", {2}, tiramisu::p_int32, a_input, &syrk);
buffer buf_A("buf_A", {NN,KK}, p_float64, a_input, &syrk);
buffer buf_C("buf_C", {NN,NN}, p_float64, a_input, &syrk);
buffer buf_alpha("buf_alpha", {1}, p_float64, a_input, &syrk);
buffer buf_beta("buf_beta", {1}, p_float64, a_input, &syrk);
//Output Buffers
buffer buf_result("buf_result", {NN, NN}, p_float64, a_output, &syrk);
//Store inputs
SIZES.set_access("{SIZES[e]->buf_SIZES[e]: 0<=e<2}");
A.set_access("{A[i,k]->buf_A[i,k]}");
C.set_access("{C[i,j]->buf_C[i,j]}");
alpha.set_access("{alpha[0]->buf_alpha[0]}");
beta.set_access("{beta[0]->buf_beta[0]}");
//Store computations
result_init.set_access("{result_init[i,j]->buf_result[i,j]}");
mat_mul.set_access("{mat_mul[i,j,k]->buf_result[i,j]}");
mult_alpha.set_access("{mult_alpha[i,j]->buf_result[i,j]}");
add_beta_C.set_access("{add_beta_C[i,j]->buf_result[i,j]}");
add_beta_C.set_access("{add_beta_C[j,i]->buf_result[j,i]}");
copy_symmetric_part.set_access("{copy_symmetric_part[i,j]->buf_result[i,j]}");
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
syrk.set_arguments({&buf_SIZES, &buf_A, &buf_C, &buf_alpha, &buf_beta, &buf_result});
syrk.gen_time_space_domain();
syrk.gen_isl_ast();
syrk.gen_halide_stmt();
syrk.gen_halide_obj("generated_syrk.o");
return 0;
}<commit_msg>Add optimizations to syrk blas function<commit_after>#include <tiramisu/tiramisu.h>
#include "benchmarks.h"
#define UNROLL_FACTOR 32
using namespace tiramisu;
/**
* Benchmark for BLAS SYRK
* out = alpha * A * A' + beta * C
*
* A : a N by K matrix
* C : a symmetric N by N matrix
* alpha, beta : scalars
* A' is the transpose of A
*/
/**
We will make a tiramisu implementation of this code :
for(int i = 0; i<N; i++){
for(int j = 0; j<=i; j++){
int tmp = 0;
for(k=0; k<K; k++)
tmp += A[i][k] * A[j][k];
RESULT[i][j] = alpha * tmp + beta* C[i][j];
}
}
*/
int main(int argc, char **argv)
{
tiramisu::init();
function syrk("syrk");
// -------------------------------------------------------
// Layer I
// -------------------------------------------------------
computation SIZES("{SIZES[e]: 0<=e<2}", expr(), false, p_float64, &syrk);
//Constants
constant NN("NN", SIZES(0), p_int32, true, NULL, 0, &syrk);
constant KK("KK", SIZES(1), p_int32, true, NULL, 0, &syrk);
//Iteration variables
var i("i"), j("j"), k("k");
//Inputs
computation A("[NN,KK]->{A[i,k]: 0<=i<NN and 0<=k<KK}", expr(), false, p_float64, &syrk);
computation C("[NN]->{C[i,j]: 0<=i<NN and 0<=j<NN}", expr(), false, p_float64, &syrk);
computation alpha("{alpha[0]}", expr(), false, p_float64, &syrk);
computation beta("{beta[0]}", expr(), false, p_float64, &syrk);
//Computations
computation result_init("[NN]->{result_init[i,j]: 0<=i<NN and 0<=j<=i}", expr(cast(p_float64, 0)), true, p_float64, &syrk);
computation mat_mul("[NN,KK]->{mat_mul[i,j,k]: 0<=i<NN and 0<=j<=i and 0<=k<KK}", expr(), true, p_float64, &syrk);
computation mult_alpha("[NN]->{mult_alpha[i,j]: 0<=i<NN and 0<=j<=i}", expr(), true, p_float64, &syrk);
computation add_beta_C("[NN]->{add_beta_C[i,j]: 0<=i<NN and 0<=j<=i}", expr(), true, p_float64, &syrk);
computation copy_symmetric_part("[NN]->{copy_symmetric_part[i,j]: 0<=i<NN and i<j<NN}", expr(), true, p_float64, &syrk);
mat_mul.set_expression(expr(mat_mul(i, j, k-1) + A(i, k) * A(j, k)));
mult_alpha.set_expression(expr(alpha(0) * mat_mul(i, j, NN-1)));
add_beta_C.set_expression(expr(mult_alpha(i, j) + beta(0) * C(i, j)));
copy_symmetric_part.set_expression(expr(add_beta_C(j, i)));
// -------------------------------------------------------
// Layer II
// -------------------------------------------------------
copy_symmetric_part.after(add_beta_C, computation::root_dimension);
add_beta_C.after(mult_alpha, i);
mult_alpha.after(mat_mul, i);
mat_mul.after(result_init, i);
#if TIRAMISU_LARGE
mat_mul.unroll(k, UNROLL_FACTOR);
#endif
//Parallelization
mat_mul.parallelize(i);
copy_symmetric_part.parallelize(i);
// -------------------------------------------------------
// Layer III
// -------------------------------------------------------
//Input Buffers
buffer buf_SIZES("buf_SIZES", {2}, tiramisu::p_int32, a_input, &syrk);
buffer buf_A("buf_A", {NN,KK}, p_float64, a_input, &syrk);
buffer buf_C("buf_C", {NN,NN}, p_float64, a_input, &syrk);
buffer buf_alpha("buf_alpha", {1}, p_float64, a_input, &syrk);
buffer buf_beta("buf_beta", {1}, p_float64, a_input, &syrk);
//Output Buffers
buffer buf_result("buf_result", {NN, NN}, p_float64, a_output, &syrk);
//Store inputs
SIZES.set_access("{SIZES[e]->buf_SIZES[e]: 0<=e<2}");
A.set_access("{A[i,k]->buf_A[i,k]}");
C.set_access("{C[i,j]->buf_C[i,j]}");
alpha.set_access("{alpha[0]->buf_alpha[0]}");
beta.set_access("{beta[0]->buf_beta[0]}");
//Store computations
result_init.set_access("{result_init[i,j]->buf_result[i,j]}");
mat_mul.set_access("{mat_mul[i,j,k]->buf_result[i,j]}");
mult_alpha.set_access("{mult_alpha[i,j]->buf_result[i,j]}");
add_beta_C.set_access("{add_beta_C[i,j]->buf_result[i,j]}");
add_beta_C.set_access("{add_beta_C[j,i]->buf_result[j,i]}");
copy_symmetric_part.set_access("{copy_symmetric_part[i,j]->buf_result[i,j]}");
// -------------------------------------------------------
// Code Generation
// -------------------------------------------------------
syrk.set_arguments({&buf_SIZES, &buf_A, &buf_C, &buf_alpha, &buf_beta, &buf_result});
syrk.gen_time_space_domain();
syrk.gen_isl_ast();
syrk.gen_halide_stmt();
syrk.gen_halide_obj("generated_syrk.o");
return 0;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/asyncappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/spi/loggingevent.h>
#include <apr_thread_proc.h>
#include <apr_thread_mutex.h>
#include <apr_thread_cond.h>
#include <log4cxx/helpers/condition.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/helpers/stringhelper.h>
#include <apr_atomic.h>
#include <log4cxx/helpers/optionconverter.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
#if APR_HAS_THREADS
IMPLEMENT_LOG4CXX_OBJECT(AsyncAppender)
AsyncAppender::AsyncAppender()
: AppenderSkeleton(),
buffer(),
bufferMutex(pool),
bufferNotFull(pool),
bufferNotEmpty(pool),
discardMap(),
bufferSize(DEFAULT_BUFFER_SIZE),
appenders(new AppenderAttachableImpl()),
dispatcher(),
locationInfo(false),
blocking(true) {
dispatcher.run(dispatch, this);
}
AsyncAppender::~AsyncAppender()
{
finalize();
}
void AsyncAppender::addAppender(const AppenderPtr& newAppender)
{
synchronized sync(appenders->getMutex());
appenders->addAppender(newAppender);
}
void AsyncAppender::setOption(const LogString& option,
const LogString& value) {
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) {
setLocationInfo(OptionConverter::toBoolean(value, false));
}
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize"))) {
setBufferSize(OptionConverter::toInt(value, DEFAULT_BUFFER_SIZE));
}
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BLOCKING"), LOG4CXX_STR("blocking"))) {
setBlocking(OptionConverter::toBoolean(value, true));
} else {
AppenderSkeleton::setOption(option, value);
}
}
void AsyncAppender::append(const spi::LoggingEventPtr& event, Pool& p) {
//
// if dispatcher has died then
// append subsequent events synchronously
//
if (!dispatcher.isAlive() || bufferSize <= 0) {
synchronized sync(appenders->getMutex());
appenders->appendLoopOnAppenders(event, p);
return;
}
// Set the NDC and thread name for the calling thread as these
// LoggingEvent fields were not set at event creation time.
event->getNDC();
event->getThreadName();
// Get a copy of this thread's MDC.
event->getMDCCopy();
{
synchronized sync(bufferMutex);
while(true) {
int previousSize = buffer.size();
if (previousSize < bufferSize) {
buffer.push_back(event);
if (previousSize == 0) {
bufferNotEmpty.signalAll();
}
break;
}
//
// Following code is only reachable if buffer is full
//
//
// if blocking and thread is not already interrupted
// and not the dispatcher then
// wait for a buffer notification
bool discard = true;
if (blocking
&& !Thread::interrupted()
&& !dispatcher.isCurrentThread()) {
try {
bufferNotFull.await(bufferMutex);
discard = false;
} catch (InterruptedException& e) {
//
// reset interrupt status so
// calling code can see interrupt on
// their next wait or sleep.
Thread::currentThreadInterrupt();
}
}
//
// if blocking is false or thread has been interrupted
// add event to discard map.
//
if (discard) {
LogString loggerName = event->getLoggerName();
DiscardMap::iterator iter = discardMap.find(loggerName);
if (iter == discardMap.end()) {
DiscardSummary summary(event);
discardMap.insert(DiscardMap::value_type(loggerName, summary));
} else {
(*iter).second.add(event);
}
break;
}
}
}
}
void AsyncAppender::close() {
{
synchronized sync(bufferMutex);
closed = true;
bufferNotEmpty.signalAll();
bufferNotFull.signalAll();
}
try {
dispatcher.join();
} catch(InterruptedException& e) {
Thread::currentThreadInterrupt();
LogLog::error(LOG4CXX_STR("Got an InterruptedException while waiting for the dispatcher to finish,"), e);
}
{
synchronized sync(appenders->getMutex());
AppenderList appenderList = appenders->getAllAppenders();
for (AppenderList::iterator iter = appenderList.begin();
iter != appenderList.end();
iter++) {
(*iter)->close();
}
}
}
AppenderList AsyncAppender::getAllAppenders() const
{
synchronized sync(appenders->getMutex());
return appenders->getAllAppenders();
}
AppenderPtr AsyncAppender::getAppender(const LogString& name) const
{
synchronized sync(appenders->getMutex());
return appenders->getAppender(name);
}
bool AsyncAppender::isAttached(const AppenderPtr& appender) const
{
synchronized sync(appenders->getMutex());
return appenders->isAttached(appender);
}
bool AsyncAppender::requiresLayout() const {
return false;
}
void AsyncAppender::removeAllAppenders()
{
synchronized sync(appenders->getMutex());
appenders->removeAllAppenders();
}
void AsyncAppender::removeAppender(const AppenderPtr& appender)
{
synchronized sync(appenders->getMutex());
appenders->removeAppender(appender);
}
void AsyncAppender::removeAppender(const LogString& name)
{
synchronized sync(appenders->getMutex());
appenders->removeAppender(name);
}
bool AsyncAppender::getLocationInfo() const {
return locationInfo;
}
void AsyncAppender::setLocationInfo(bool flag) {
locationInfo = flag;
}
void AsyncAppender::setBufferSize(int size)
{
if (size < 0) {
throw IllegalArgumentException("size argument must be non-negative");
}
synchronized sync(bufferMutex);
bufferSize = (size < 1) ? 1 : size;
bufferNotFull.signalAll();
}
int AsyncAppender::getBufferSize() const
{
return bufferSize;
}
void AsyncAppender::setBlocking(bool value) {
synchronized sync(bufferMutex);
blocking = value;
bufferNotFull.signalAll();
}
bool AsyncAppender::getBlocking() const {
return blocking;
}
AsyncAppender::DiscardSummary::DiscardSummary(const LoggingEventPtr& event) :
maxEvent(event), count(1) {
}
AsyncAppender::DiscardSummary::DiscardSummary(const DiscardSummary& src) :
maxEvent(src.maxEvent), count(src.count) {
}
AsyncAppender::DiscardSummary& AsyncAppender::DiscardSummary::operator=(const DiscardSummary& src) {
maxEvent = src.maxEvent;
count = src.count;
return *this;
}
void AsyncAppender::DiscardSummary::add(const LoggingEventPtr& event) {
if (event->getLevel()->toInt() > maxEvent->getLevel()->toInt()) {
maxEvent = event;
}
count++;
}
LoggingEventPtr AsyncAppender::DiscardSummary::createEvent(Pool& p) {
LogString msg(LOG4CXX_STR("Discarded "));
StringHelper::toString(count, p, msg);
msg.append(LOG4CXX_STR(" messages due to a full event buffer including: "));
msg.append(maxEvent->getMessage());
return new LoggingEvent(
Logger::getLogger(maxEvent->getLoggerName()),
maxEvent->getLevel(),
msg,
LocationInfo::getLocationUnavailable());
}
void* LOG4CXX_THREAD_FUNC AsyncAppender::dispatch(log4cxx_thread_t* /* thread */ , void* data) {
AsyncAppender* pThis = (AsyncAppender*) data;
bool isActive = true;
try {
while (isActive) {
//
// process events after lock on buffer is released.
//
Pool p;
LoggingEventList events;
{
synchronized sync(pThis->bufferMutex);
size_t bufferSize = pThis->buffer.size();
isActive = !pThis->closed;
while((bufferSize == 0) && isActive) {
pThis->bufferNotEmpty.await(pThis->bufferMutex);
bufferSize = pThis->buffer.size();
isActive = !pThis->closed;
}
for(LoggingEventList::iterator eventIter = pThis->buffer.begin();
eventIter != pThis->buffer.end();
eventIter++) {
events.push_back(*eventIter);
}
for(DiscardMap::iterator discardIter = pThis->discardMap.begin();
discardIter != pThis->discardMap.end();
discardIter++) {
events.push_back(discardIter->second.createEvent(p));
}
pThis->buffer.clear();
pThis->discardMap.clear();
pThis->bufferNotFull.signalAll();
}
for (LoggingEventList::iterator iter = events.begin();
iter != events.end();
iter++) {
synchronized sync(pThis->appenders->getMutex());
pThis->appenders->appendLoopOnAppenders(*iter, p);
}
}
} catch(InterruptedException& ex) {
Thread::currentThreadInterrupt();
} catch(...) {
}
return 0;
}
#endif
<commit_msg>LOGCXX-129: Explicit apr_thread_exit elims exception on Thread.join on Windows<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <log4cxx/asyncappender.h>
#include <log4cxx/helpers/loglog.h>
#include <log4cxx/spi/loggingevent.h>
#include <apr_thread_proc.h>
#include <apr_thread_mutex.h>
#include <apr_thread_cond.h>
#include <log4cxx/helpers/condition.h>
#include <log4cxx/helpers/synchronized.h>
#include <log4cxx/helpers/stringhelper.h>
#include <apr_atomic.h>
#include <log4cxx/helpers/optionconverter.h>
using namespace log4cxx;
using namespace log4cxx::helpers;
using namespace log4cxx::spi;
#if APR_HAS_THREADS
IMPLEMENT_LOG4CXX_OBJECT(AsyncAppender)
AsyncAppender::AsyncAppender()
: AppenderSkeleton(),
buffer(),
bufferMutex(pool),
bufferNotFull(pool),
bufferNotEmpty(pool),
discardMap(),
bufferSize(DEFAULT_BUFFER_SIZE),
appenders(new AppenderAttachableImpl()),
dispatcher(),
locationInfo(false),
blocking(true) {
dispatcher.run(dispatch, this);
}
AsyncAppender::~AsyncAppender()
{
finalize();
}
void AsyncAppender::addAppender(const AppenderPtr& newAppender)
{
synchronized sync(appenders->getMutex());
appenders->addAppender(newAppender);
}
void AsyncAppender::setOption(const LogString& option,
const LogString& value) {
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("LOCATIONINFO"), LOG4CXX_STR("locationinfo"))) {
setLocationInfo(OptionConverter::toBoolean(value, false));
}
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BUFFERSIZE"), LOG4CXX_STR("buffersize"))) {
setBufferSize(OptionConverter::toInt(value, DEFAULT_BUFFER_SIZE));
}
if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR("BLOCKING"), LOG4CXX_STR("blocking"))) {
setBlocking(OptionConverter::toBoolean(value, true));
} else {
AppenderSkeleton::setOption(option, value);
}
}
void AsyncAppender::append(const spi::LoggingEventPtr& event, Pool& p) {
//
// if dispatcher has died then
// append subsequent events synchronously
//
if (!dispatcher.isAlive() || bufferSize <= 0) {
synchronized sync(appenders->getMutex());
appenders->appendLoopOnAppenders(event, p);
return;
}
// Set the NDC and thread name for the calling thread as these
// LoggingEvent fields were not set at event creation time.
event->getNDC();
event->getThreadName();
// Get a copy of this thread's MDC.
event->getMDCCopy();
{
synchronized sync(bufferMutex);
while(true) {
int previousSize = buffer.size();
if (previousSize < bufferSize) {
buffer.push_back(event);
if (previousSize == 0) {
bufferNotEmpty.signalAll();
}
break;
}
//
// Following code is only reachable if buffer is full
//
//
// if blocking and thread is not already interrupted
// and not the dispatcher then
// wait for a buffer notification
bool discard = true;
if (blocking
&& !Thread::interrupted()
&& !dispatcher.isCurrentThread()) {
try {
bufferNotFull.await(bufferMutex);
discard = false;
} catch (InterruptedException& e) {
//
// reset interrupt status so
// calling code can see interrupt on
// their next wait or sleep.
Thread::currentThreadInterrupt();
}
}
//
// if blocking is false or thread has been interrupted
// add event to discard map.
//
if (discard) {
LogString loggerName = event->getLoggerName();
DiscardMap::iterator iter = discardMap.find(loggerName);
if (iter == discardMap.end()) {
DiscardSummary summary(event);
discardMap.insert(DiscardMap::value_type(loggerName, summary));
} else {
(*iter).second.add(event);
}
break;
}
}
}
}
void AsyncAppender::close() {
{
synchronized sync(bufferMutex);
closed = true;
bufferNotEmpty.signalAll();
bufferNotFull.signalAll();
}
try {
dispatcher.join();
} catch(InterruptedException& e) {
Thread::currentThreadInterrupt();
LogLog::error(LOG4CXX_STR("Got an InterruptedException while waiting for the dispatcher to finish,"), e);
}
{
synchronized sync(appenders->getMutex());
AppenderList appenderList = appenders->getAllAppenders();
for (AppenderList::iterator iter = appenderList.begin();
iter != appenderList.end();
iter++) {
(*iter)->close();
}
}
}
AppenderList AsyncAppender::getAllAppenders() const
{
synchronized sync(appenders->getMutex());
return appenders->getAllAppenders();
}
AppenderPtr AsyncAppender::getAppender(const LogString& name) const
{
synchronized sync(appenders->getMutex());
return appenders->getAppender(name);
}
bool AsyncAppender::isAttached(const AppenderPtr& appender) const
{
synchronized sync(appenders->getMutex());
return appenders->isAttached(appender);
}
bool AsyncAppender::requiresLayout() const {
return false;
}
void AsyncAppender::removeAllAppenders()
{
synchronized sync(appenders->getMutex());
appenders->removeAllAppenders();
}
void AsyncAppender::removeAppender(const AppenderPtr& appender)
{
synchronized sync(appenders->getMutex());
appenders->removeAppender(appender);
}
void AsyncAppender::removeAppender(const LogString& name)
{
synchronized sync(appenders->getMutex());
appenders->removeAppender(name);
}
bool AsyncAppender::getLocationInfo() const {
return locationInfo;
}
void AsyncAppender::setLocationInfo(bool flag) {
locationInfo = flag;
}
void AsyncAppender::setBufferSize(int size)
{
if (size < 0) {
throw IllegalArgumentException("size argument must be non-negative");
}
synchronized sync(bufferMutex);
bufferSize = (size < 1) ? 1 : size;
bufferNotFull.signalAll();
}
int AsyncAppender::getBufferSize() const
{
return bufferSize;
}
void AsyncAppender::setBlocking(bool value) {
synchronized sync(bufferMutex);
blocking = value;
bufferNotFull.signalAll();
}
bool AsyncAppender::getBlocking() const {
return blocking;
}
AsyncAppender::DiscardSummary::DiscardSummary(const LoggingEventPtr& event) :
maxEvent(event), count(1) {
}
AsyncAppender::DiscardSummary::DiscardSummary(const DiscardSummary& src) :
maxEvent(src.maxEvent), count(src.count) {
}
AsyncAppender::DiscardSummary& AsyncAppender::DiscardSummary::operator=(const DiscardSummary& src) {
maxEvent = src.maxEvent;
count = src.count;
return *this;
}
void AsyncAppender::DiscardSummary::add(const LoggingEventPtr& event) {
if (event->getLevel()->toInt() > maxEvent->getLevel()->toInt()) {
maxEvent = event;
}
count++;
}
LoggingEventPtr AsyncAppender::DiscardSummary::createEvent(Pool& p) {
LogString msg(LOG4CXX_STR("Discarded "));
StringHelper::toString(count, p, msg);
msg.append(LOG4CXX_STR(" messages due to a full event buffer including: "));
msg.append(maxEvent->getMessage());
return new LoggingEvent(
Logger::getLogger(maxEvent->getLoggerName()),
maxEvent->getLevel(),
msg,
LocationInfo::getLocationUnavailable());
}
void* LOG4CXX_THREAD_FUNC AsyncAppender::dispatch(log4cxx_thread_t* thread, void* data) {
AsyncAppender* pThis = (AsyncAppender*) data;
bool isActive = true;
try {
while (isActive) {
//
// process events after lock on buffer is released.
//
Pool p;
LoggingEventList events;
{
synchronized sync(pThis->bufferMutex);
size_t bufferSize = pThis->buffer.size();
isActive = !pThis->closed;
while((bufferSize == 0) && isActive) {
pThis->bufferNotEmpty.await(pThis->bufferMutex);
bufferSize = pThis->buffer.size();
isActive = !pThis->closed;
}
for(LoggingEventList::iterator eventIter = pThis->buffer.begin();
eventIter != pThis->buffer.end();
eventIter++) {
events.push_back(*eventIter);
}
for(DiscardMap::iterator discardIter = pThis->discardMap.begin();
discardIter != pThis->discardMap.end();
discardIter++) {
events.push_back(discardIter->second.createEvent(p));
}
pThis->buffer.clear();
pThis->discardMap.clear();
pThis->bufferNotFull.signalAll();
}
for (LoggingEventList::iterator iter = events.begin();
iter != events.end();
iter++) {
synchronized sync(pThis->appenders->getMutex());
pThis->appenders->appendLoopOnAppenders(*iter, p);
}
}
} catch(InterruptedException& ex) {
Thread::currentThreadInterrupt();
} catch(...) {
}
apr_thread_exit((apr_thread_t*) thread, 0);
return 0;
}
#endif
<|endoftext|> |
<commit_before>//============================================================================
// Name : benchmark_main.cc
// Author : Giovanni Azua ([email protected])
// Since : 25.07.2013
// Description : Main application for benchmarking Eigen with MAGMA and MKL
//============================================================================
#include <assert.h>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/config.hpp>
#include <boost/program_options/environment_iterator.hpp>
#include <boost/program_options/eof_iterator.hpp>
#include <boost/program_options/errors.hpp>
#include <boost/program_options/option.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/version.hpp>
#include <boost/chrono.hpp>
#include <boost/tokenizer.hpp>
#include <Eigen/Dense>
/**
* Define reusable Eigen vector and matrix types.
*/
template<typename T>
struct BenchType {
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> MatrixX;
typedef Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::ColMajor> VectorX;
};
typedef BenchType<double>::MatrixX MatrixXd;
typedef BenchType<double>::VectorX VectorXd;
using namespace std;
using namespace boost::accumulators;
using namespace boost::chrono;
namespace po = boost::program_options;
typedef double (*workload_type)(long);
typedef accumulator_set<double, stats<tag::mean, tag::variance> > bench_accumulator;
static bench_accumulator real_time_acc, gflops_acc;
// reusable vector and matrices
MatrixXd A, B, C, L;
VectorXd a, b, c;
Eigen::ColPivHouseholderQR<MatrixXd> Aqr;
/// Generic benchmarking
/**
* Generic benchmarking, implement the different workload types according to the expected signature.
*/
static void run_benchmark(long N, int warm_ups, int num_runs, workload_type workload) {
// warm up runs
for (int i = 0; i < warm_ups; ++i) {
// invoke workload
(*workload)(N);
fprintf(stderr, ".");
fflush (stderr);
}
// actual measurements
for (int i = 0; i < num_runs; ++i) {
double real_time, cpu_time, gflops;
double flop_count;
system_clock::time_point start;
// benchmark using high-resolution timer
start = system_clock::now();
// invoke workload
flop_count = (*workload)(N);
// use high-resolution timer
duration<double> sec = system_clock::now() - start;
real_time = sec.count();
gflops = flop_count / (1e9 * real_time);
// feed the accumulators
real_time_acc(real_time);
gflops_acc(gflops);
fprintf(stderr, ".");
fflush (stderr);
}
}
EIGEN_DONT_INLINE
static double dgemm(long N) {
C = A * B;
// flops see http://www.netlib.org/lapack/lawnspdf/lawn41.pdf page 120
return 2 * N * N * N;
}
EIGEN_DONT_INLINE
static double dgeqp3(long N) {
Eigen::ColPivHouseholderQR<MatrixXd> qr = A.colPivHouseholderQr();
// flops see http://www.netlib.org/lapack/lawnspdf/lawn41.pdf page 121
return N * N * N - (2 / 3) * N * N * N + N * N + N * N + (14 / 3) * N;
}
EIGEN_DONT_INLINE
static double dgemv(long N) {
C = A * b;
return 2 * N * N - N;
}
EIGEN_DONT_INLINE
static double dtrsm(long N) {
C = Aqr.solve(B);
return N * N * N;
}
EIGEN_DONT_INLINE
static double dpotrf(long N) {
Eigen::LLT<MatrixXd> lltOfA(A);
L = lltOfA.matrixL();
return N * N * N / 3.0 + N * N / 2.0 + N / 6.0;
}
EIGEN_DONT_INLINE
static double dgesvd(long N) {
Eigen::JacobiSVD<MatrixXd> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);
return 22 * N * N * N;
}
int main(int argc, char** argv) {
#if !defined(NDEBUG) || defined(DEBUG)
fprintf(stderr, "Warning: you are running in debug mode - assertions are enabled. \n");
#endif
try {
#if defined(EIGEN_USE_MAGMA_ALL)
MAGMA_INIT();
#endif
// program arguments
string function;
string range;
int warm_ups, num_runs;
po::options_description desc("Benchmark main options");
desc.add_options()("help", "produce help message")
("warm-up-runs", po::value<int>(&warm_ups)->default_value(1), "warm up runs e.g. 1")
("num-runs", po::value<int>(&num_runs)->default_value(10), "number of runs e.g. 10")
("function", po::value < string > (&function)->default_value("dgemm"), "Function to test e.g. dgemm, dgeqp3")
("range", po::value < string > (&range)->default_value("1024:10240:1024"), "N range i.e. start:stop:step");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return EXIT_FAILURE;
} else {
string temp = range;
boost::tokenizer<> tok(temp);
vector<long> range_values;
for (boost::tokenizer<>::iterator current = tok.begin(); current != tok.end();
++current) {
range_values.push_back(boost::lexical_cast<long>(*current));
}
if (range_values.size() != 3) {
throw "Illegal range input: '" + range + "'";
}
workload_type workload;
if (function == "dgemm") {
workload = dgemm;
} else if (function == "dgeqp3") {
workload = dgeqp3;
} else if (function == "dgemv") {
workload = dgemv;
} else if (function == "dtrsm") {
workload = dtrsm;
} else if (function == "dpotrf") {
workload = dpotrf;
} else if (function == "dgesvd") {
workload = dgesvd;
} else {
throw "Sorry, the function '" + function + "' is not yet implemented.";
}
for (long N = range_values[0]; N <= range_values[1]; N += range_values[2]) {
// prepare the input data
A = MatrixXd::Random(N, N);
B = MatrixXd::Random(N, N);
b = VectorXd::Random(N);
// function-specific input data
if (function == "dtrsm") {
Aqr = A.colPivHouseholderQr();
} else if (function == "dpotrf") {
// make sure A is SDP
A = A.adjoint() * A;
}
real_time_acc = bench_accumulator();
gflops_acc = bench_accumulator();
// run the benchmark
run_benchmark(N, warm_ups, num_runs, workload);
fprintf(stdout, "%d\t%e\t%e\n", N, mean(real_time_acc), mean(gflops_acc));
fflush (stdout);
fprintf(stderr, "%d,%e,%e\n", N, mean(real_time_acc), mean(gflops_acc));
fflush (stderr);
}
}
#if defined(EIGEN_USE_MAGMA_ALL)
MAGMA_FINALIZE();
#endif
} catch (std::exception& e) {
cerr << "Exception: " << e.what() << "\n";
return EXIT_FAILURE;
} catch (string& e) {
cerr << "Exception: " << e << "\n";
return EXIT_FAILURE;
} catch (...) {
cerr << "Exception of unknown type!\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<commit_msg>Cosmetics<commit_after>//============================================================================
// Name : benchmark_main.cc
// Author : Giovanni Azua ([email protected])
// Since : 25.07.2013
// Description : Main application for benchmarking Eigen with MAGMA and MKL
//============================================================================
#include <assert.h>
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/program_options/cmdline.hpp>
#include <boost/program_options/config.hpp>
#include <boost/program_options/environment_iterator.hpp>
#include <boost/program_options/eof_iterator.hpp>
#include <boost/program_options/errors.hpp>
#include <boost/program_options/option.hpp>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/positional_options.hpp>
#include <boost/program_options/value_semantic.hpp>
#include <boost/program_options/variables_map.hpp>
#include <boost/program_options/version.hpp>
#include <boost/chrono.hpp>
#include <boost/tokenizer.hpp>
#include <Eigen/Dense>
/**
* Define reusable Eigen vector and matrix types.
*/
template<typename T>
struct BenchType {
typedef Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::ColMajor> MatrixX;
typedef Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::ColMajor> VectorX;
};
typedef BenchType<double>::MatrixX MatrixXd;
typedef BenchType<double>::VectorX VectorXd;
using namespace std;
using namespace boost::accumulators;
using namespace boost::chrono;
namespace po = boost::program_options;
typedef double (*workload_type)(long);
typedef accumulator_set<double, stats<tag::mean, tag::variance> > bench_accumulator;
static bench_accumulator real_time_acc, gflops_acc;
// reusable vector and matrices
MatrixXd A, B, C, L;
VectorXd a, b, c;
Eigen::ColPivHouseholderQR<MatrixXd> Aqr;
/// Generic benchmarking
/**
* Generic benchmarking, implement the different workload types according to the expected signature.
*/
static void run_benchmark(long N, int warm_ups, int num_runs, workload_type workload) {
// warm up runs
for (int i = 0; i < warm_ups; ++i) {
// invoke workload
(*workload)(N);
fprintf(stderr, ".");
fflush (stderr);
}
// actual measurements
for (int i = 0; i < num_runs; ++i) {
double real_time, cpu_time, gflops;
double flop_count;
system_clock::time_point start;
// benchmark using high-resolution timer
start = system_clock::now();
// invoke workload
flop_count = (*workload)(N);
// use high-resolution timer
duration<double> sec = system_clock::now() - start;
real_time = sec.count();
gflops = flop_count / (1e9 * real_time);
// feed the accumulators
real_time_acc(real_time);
gflops_acc(gflops);
fprintf(stderr, ".");
fflush (stderr);
}
}
EIGEN_DONT_INLINE
static double dgemm(long N) {
C = A * B;
// flops see http://www.netlib.org/lapack/lawnspdf/lawn41.pdf page 120
return 2 * N * N * N;
}
EIGEN_DONT_INLINE
static double dgeqp3(long N) {
Eigen::ColPivHouseholderQR<MatrixXd> qr = A.colPivHouseholderQr();
// flops see http://www.netlib.org/lapack/lawnspdf/lawn41.pdf page 121
return N * N * N - (2 / 3) * N * N * N + N * N + N * N + (14 / 3) * N;
}
EIGEN_DONT_INLINE
static double dgemv(long N) {
C = A * b;
return 2 * N * N - N;
}
EIGEN_DONT_INLINE
static double dtrsm(long N) {
C = Aqr.solve(B);
return N * N * N;
}
EIGEN_DONT_INLINE
static double dpotrf(long N) {
Eigen::LLT<MatrixXd> lltOfA(A);
L = lltOfA.matrixL();
return N * N * N / 3.0 + N * N / 2.0 + N / 6.0;
}
EIGEN_DONT_INLINE
static double dgesvd(long N) {
Eigen::JacobiSVD<MatrixXd> svd(A, Eigen::ComputeThinU | Eigen::ComputeThinV);
return 22 * N * N * N;
}
int main(int argc, char** argv) {
#if !defined(NDEBUG) || defined(DEBUG)
fprintf(stderr, "Warning: you are running in debug mode - assertions are enabled. \n");
#endif
try {
#if defined(EIGEN_USE_MAGMA_ALL)
MAGMA_INIT();
#endif
// program arguments
string function;
string range;
int warm_ups, num_runs;
po::options_description desc("Benchmark main options");
desc.add_options()("help", "produce help message")
("warm-up-runs", po::value<int>(&warm_ups)->default_value(1), "warm up runs e.g. 1")
("num-runs", po::value<int>(&num_runs)->default_value(10), "number of runs e.g. 10")
("function", po::value < string > (&function)->default_value("dgemm"), "Function to test e.g. dgemm, dgeqp3")
("range", po::value < string > (&range)->default_value("1024:10240:1024"), "N range i.e. start:stop:step");
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return EXIT_FAILURE;
} else {
string temp = range;
boost::tokenizer<> tok(temp);
vector<long> range_values;
for (boost::tokenizer<>::iterator current = tok.begin(); current != tok.end(); ++current) {
range_values.push_back(boost::lexical_cast<long>(*current));
}
if (range_values.size() != 3) {
throw "Illegal range input: '" + range + "'";
}
workload_type workload;
if (function == "dgemm") {
workload = dgemm;
} else if (function == "dgeqp3") {
workload = dgeqp3;
} else if (function == "dgemv") {
workload = dgemv;
} else if (function == "dtrsm") {
workload = dtrsm;
} else if (function == "dpotrf") {
workload = dpotrf;
} else if (function == "dgesvd") {
workload = dgesvd;
} else {
throw "Sorry, the function '" + function + "' is not yet implemented.";
}
for (long N = range_values[0]; N <= range_values[1]; N += range_values[2]) {
// prepare the input data
A = MatrixXd::Random(N, N);
B = MatrixXd::Random(N, N);
b = VectorXd::Random(N);
// function-specific input data
if (function == "dtrsm") {
Aqr = A.colPivHouseholderQr();
} else if (function == "dpotrf") {
// make sure A is SPD
A = A.adjoint() * A;
}
real_time_acc = bench_accumulator();
gflops_acc = bench_accumulator();
// run the benchmark
run_benchmark(N, warm_ups, num_runs, workload);
fprintf(stdout, "%d\t%e\t%e\n", N, mean(real_time_acc), mean(gflops_acc));
fflush (stdout);
fprintf(stderr, "%d,%e,%e\n", N, mean(real_time_acc), mean(gflops_acc));
fflush (stderr);
}
}
#if defined(EIGEN_USE_MAGMA_ALL)
MAGMA_FINALIZE();
#endif
} catch (std::exception& e) {
cerr << "Exception: " << e.what() << "\n";
return EXIT_FAILURE;
} catch (string& e) {
cerr << "Exception: " << e << "\n";
return EXIT_FAILURE;
} catch (...) {
cerr << "Exception of unknown type!\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// This file is part of BlueSky
//
// BlueSky is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// BlueSky is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with BlueSky; if not, see <http://www.gnu.org/licenses/>.
#include "bs_messaging.h"
#include "bs_object_base.h"
#include "bs_kernel.h"
#include "boost/signal.hpp"
#define SLOT_EXEC_LAYER sync_layer
using namespace std;
using namespace blue_sky;
using namespace Loki;
namespace blue_sky {
//---------------BlueSky Slot implementation--------------------------------------
//Andrey
//off
//struct bs_slot::slot_wrapper
//{
// slot_wrapper(const sp_slot& slot) : slot_(slot)
// {}
//
// void operator()(sp_mobj sender, int signal_code, sp_obj param) const
// {
// kernel& k = give_kernel::Instance();
// slot_.lock()->init(sender, signal_code, param);
// k.add_task(slot_);
// }
//
// bool operator==(const slot_wrapper& rhs) const {
// return (slot_ == rhs.slot_);
// }
//
// bool operator==(const sp_slot& slot) const {
// return (slot_ == slot);
// }
//
// bool operator<(const slot_wrapper& rhs) const {
// return (slot_ < rhs.slot_);
// }
//
// sp_slot slot_;
//};
//
//void bs_slot::init(const sp_mobj& sender, int signal_code, const sp_obj& param)
//{
// sender_ = sender; signal_code_ = signal_code; param_ = param;
//}
//
void bs_slot::dispose() const {
delete this;
}
//new implementation
class slot_holder {
public:
typedef const bs_imessaging* sender_ptr;
slot_holder(const sp_slot& slot, const sender_ptr& sender = NULL)
: slot_(slot), sender_(sender)
{}
bool operator==(const slot_holder& rhs) const {
return (slot_ == rhs.slot_);
}
bool operator==(const sp_slot& slot) const {
return (slot_ == slot);
}
bool operator<(const slot_holder& rhs) const {
return (slot_ < rhs.slot_);
}
void operator()(const sp_mobj& sender, int signal_code, sp_obj param) const {
if((!sender_) || (sender == sender_))
fire_slot(sender, signal_code, param);
}
// children should override this function
virtual void fire_slot(const sp_mobj& sender, int signal_code, const sp_obj& param) const = 0;
// virtual dtor
virtual ~slot_holder() {};
protected:
sp_slot slot_;
// if sender != NULL then only signals from this sender will be triggered
// if we store sp_mobj then object will live forever, because every slot holds smart pointer to sender
// thats why only pure pointer to object is stored
// when sender is deleted, all slot_holders will be destroyed and there will be no dead references
const bs_imessaging* sender_;
//sp_mobj sender_;
};
class async_layer : public slot_holder {
class slot2com : public combase {
public:
slot2com(const sp_slot& slot, const sp_mobj& sender, int signal_code, const sp_obj& param)
: slot_(slot), sender_(sender), sc_(signal_code), param_(param)
{}
sp_com execute() {
slot_->execute(sender_, sc_, param_);
return NULL;
}
void unexecute() {}
bool can_unexecute() const { return false; }
void dispose() const {
//DEBUG
//cout << "dispose() for slot_wrapper " << this << " called" << endl;
delete this;
}
private:
sp_slot slot_;
sp_mobj sender_;
int sc_;
sp_obj param_;
};
public:
typedef slot_holder::sender_ptr sender_ptr;
async_layer(const sp_slot& slot, const sender_ptr& sender = NULL)
: slot_holder(slot, sender)
{}
void fire_slot(const sp_mobj& sender, int signal_code, const sp_obj& param) const {
if(slot_)
give_kernel::Instance().add_task(new slot2com(slot_, sender, signal_code, param));
}
};
class sync_layer : public slot_holder {
public:
typedef slot_holder::sender_ptr sender_ptr;
sync_layer(const sp_slot& slot, const sender_ptr& sender = NULL)
: slot_holder(slot, sender)
{}
void fire_slot(const sp_mobj& sender, int signal_code, const sp_obj& param) const {
if(slot_)
slot_->execute(sender, signal_code, param);
}
};
//bs_signal definition
class bs_signal::signal_impl
{
public:
//send signal command
typedef boost::signal< void (const sp_mobj& sender, int signal_code, const sp_obj& param) > signal_engine;
signal_engine my_signal_;
//sp_mobj sender_;
int signal_code_;
sp_obj param_;
//default ctor
signal_impl() : signal_code_(0) {}
// ctor with sig code initialization
signal_impl(int sig_code)
: signal_code_(sig_code)
{}
// signal_impl(const sp_mobj& sender, int sig_code)
// : signal_code_(sig_code), sender_(sender),
// {}
//non-const function because boost::signals doesn't support mt
void execute(const sp_mobj& sender) {
//if(sender)
my_signal_(sender, signal_code_, param_);
}
void fire(const sp_mobj& sender, const sp_obj& param) {
param_ = param;
execute(sender);
}
// if sender != NULL then slot will be activated only for given sender
bool connect(const sp_slot& slot, const sp_mobj& sender = NULL) {
if(!slot) return false;
//my_signal_.connect(bs_slot::slot_wrapper(slot));
my_signal_.connect(SLOT_EXEC_LAYER(slot, sender));
return true;
}
bool disconnect(const sp_slot& slot) {
if(!slot) return false;
my_signal_.disconnect(SLOT_EXEC_LAYER(slot));
return true;
}
ulong num_slots() const {
return static_cast< ulong >(my_signal_.num_slots());
}
};
//=============================== bs_signal implementation =============================================================
bs_signal::bs_signal(int signal_code)
: pimpl_(new signal_impl(signal_code), mutex(), bs_static_cast())
{}
void bs_signal::init(int signal_code) const {
lpimpl lp(pimpl_);
if(signal_code > 0)
lp->signal_code_ = signal_code;
else
throw bs_kernel_exception ("bs_signal::init", no_error, "Wrong signal code given");
}
//bool bs_signal::sender_binded() const {
// return (pimpl_->sender_.get() != NULL);
//}
void bs_signal::fire(const sp_mobj& sender, const sp_obj& param) const {
//lock during recepients call because boost:signals doesn't support mt
//lpimpl lp(pimpl_);
//lp->param_ = param;
//lp->execute();
pimpl_.lock()->fire(sender, param);
//give_kernel::Instance().add_task(this);
}
bool bs_signal::connect(const sp_slot& slot, const sp_mobj& sender) const {
return pimpl_.lock()->connect(slot, sender);
}
bool bs_signal::disconnect(const sp_slot& slot) const
{
return pimpl_.lock()->disconnect(slot);
}
//sp_com bs_signal::execute()
//{
// pimpl_->execute();
// return NULL;
//}
//
//void bs_signal::unexecute()
//{}
//
//bool bs_signal::can_unexecute() const
//{
// return false;
//}
ulong bs_signal::num_slots() const {
return pimpl_->num_slots();
}
void bs_signal::dispose() const {
delete this;
}
int bs_signal::get_code() const {
return pimpl_->signal_code_;
}
//============================== bs_messaging implementation ===========================================================
//empty ctor
bs_messaging::bs_messaging() {}
//empty dtor
//bs_messaging::~bs_messaging() {}
//ctor that adds all signals in a half-open range
bs_messaging::bs_messaging(const sig_range_t& sig_range) {
add_signal(sig_range);
}
//copy ctor implementation
bs_messaging::bs_messaging(const bs_messaging& mes)
: bs_refcounter(mes), bs_imessaging(), signals_(mes.signals_)
{}
void bs_messaging::swap(bs_messaging& rhs) {
std::swap(signals_, rhs.signals_);
}
//bs_messaging& bs_messaging::operator=(const bs_messaging& lhs) {
// bs_messaging(lhs).swap(*this);
// return *this;
//}
bool bs_messaging::fire_signal(int signal_code, const sp_obj& params) const
{
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig == signals_.end()) return false;
//if(!sig->second->sender_binded())
// sig->second->init(this);
sig->second->fire(this, params);
//kernel &k = give_kernel::Instance();
//sig->second.lock()->set_param(params);
//k.add_task(sig->second);
return true;
}
bool bs_messaging::add_signal(int signal_code)
{
if(signals_.find(signal_code) != signals_.end()) return false;
pair< sp_signal, bool > sig;
sig = BS_KERNEL.reg_signal(BS_GET_TI(*this), signal_code);
signals_[signal_code] = sig.first;
//new bs_signal(signal_code);
return sig.second;
}
ulong bs_messaging::add_signal(const sig_range_t& sr) {
ulong cnt = 0;
for(int i = sr.first; i < sr.second; ++i)
cnt += static_cast< ulong >(add_signal(i));
return cnt;
}
bool bs_messaging::remove_signal(int signal_code)
{
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig != signals_.end())
{
signals_.erase(signal_code);
BS_KERNEL.rem_signal(BS_GET_TI(*this), signal_code);
return true;
}
return false;
}
std::vector< int > bs_messaging::get_signal_list() const
{
std::vector< int > res;
res.reserve(signals_.size());
for (bs_signals_map::const_iterator p = signals_.begin(); p != signals_.end(); ++p)
res.push_back(p->first);
return res;
}
bool bs_messaging::subscribe(int signal_code, const sp_slot& slot) const {
if(!slot) return false;
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig != signals_.end()) {
sig->second->connect(slot, this);
return true;
}
return false;
}
bool bs_messaging::unsubscribe(int signal_code, const smart_ptr< bs_slot, true >& slot) const
{
if(!slot) return false;
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig != signals_.end()) {
sig->second->disconnect(slot);
return true;
}
return false;
}
ulong bs_messaging::num_slots(int signal_code) const {
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig != signals_.end())
return sig->second->num_slots();
else return 0;
}
void bs_messaging::dispose() const {
delete this;
}
} //end of namespace blue_sky
<commit_msg>signals: more efficient & customizable signal implementation<commit_after>// This file is part of BlueSky
//
// BlueSky is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// BlueSky is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with BlueSky; if not, see <http://www.gnu.org/licenses/>.
#include "bs_messaging.h"
#include "bs_object_base.h"
#include "bs_kernel.h"
#include "boost/signal.hpp"
#define SLOT_EXEC_LAYER sync_layer
using namespace std;
using namespace blue_sky;
using namespace Loki;
namespace blue_sky {
void bs_slot::dispose() const {
delete this;
}
/*-----------------------------------------------------------------
* BS signal helpers
*----------------------------------------------------------------*/
// define execution layer -- sync or async
template< class slot_ptr >
class async_layer {
class slot2com : public combase {
public:
slot2com(const slot_ptr& slot, const sp_mobj& sender, int signal_code, const sp_obj& param)
: slot_(slot), sender_(sender), sc_(signal_code), param_(param)
{}
sp_com execute() {
slot_->execute(sender_, sc_, param_);
return NULL;
}
void unexecute() {}
bool can_unexecute() const { return false; }
void dispose() const {
//DEBUG
//cout << "dispose() for slot_wrapper " << this << " called" << endl;
delete this;
}
private:
slot_ptr slot_;
sp_mobj sender_;
int sc_;
sp_obj param_;
};
public:
void fire_slot(
const sp_slot& slot, const sp_mobj& sender, int signal_code, const sp_obj& param
) const {
if(slot)
// execute slot as kernel task
BS_KERNEL.add_task(new slot2com(slot, sender, signal_code, param));
}
};
template< class slot_ptr >
class sync_layer {
public:
void fire_slot(
const slot_ptr& slot, const sp_mobj& sender, int signal_code, const sp_obj& param
) const {
if(slot)
// directly execute slot
slot->execute(sender, signal_code, param);
}
};
// slot holder that uses execution layer to fire slot
template< class slot_ptr = sp_slot, template < class > class exec_layer = SLOT_EXEC_LAYER >
class slot_holder : public exec_layer< slot_ptr > {
public:
typedef const bs_imessaging* sender_ptr;
typedef exec_layer< slot_ptr > base_t;
using base_t::fire_slot;
slot_holder(const slot_ptr& slot, const sender_ptr& sender = NULL)
: slot_(slot), sender_(sender)
{}
bool operator==(const slot_holder& rhs) const {
return (slot_ == rhs.slot_);
}
bool operator==(const slot_ptr& slot) const {
return (slot_ == slot);
}
bool operator<(const slot_holder& rhs) const {
return (slot_ < rhs.slot_);
}
void operator()(const sp_mobj& sender, int signal_code, sp_obj param) const {
if((!sender_) || (sender == sender_))
fire_slot(slot_, sender, signal_code, param);
}
protected:
slot_ptr slot_;
// if sender != NULL then only signals from this sender will be triggered
// if we store sp_mobj then object will live forever, because every slot holds smart pointer to sender
// thats why only pure pointer to object is stored
// when sender is deleted, all slot_holders will be destroyed and there will be no dead references
const bs_imessaging* sender_;
};
/*-----------------------------------------------------------------
* BS signal implementation details
*----------------------------------------------------------------*/
class bs_signal::signal_impl
{
public:
//send signal command
typedef boost::signal< void (const sp_mobj& sender, int signal_code, const sp_obj& param) > signal_engine;
signal_engine my_signal_;
//sp_mobj sender_;
int signal_code_;
sp_obj param_;
//default ctor
signal_impl() : signal_code_(0) {}
// ctor with sig code initialization
signal_impl(int sig_code)
: signal_code_(sig_code)
{}
// signal_impl(const sp_mobj& sender, int sig_code)
// : signal_code_(sig_code), sender_(sender),
// {}
//non-const function because boost::signals doesn't support mt
void execute(const sp_mobj& sender) {
//if(sender)
my_signal_(sender, signal_code_, param_);
}
void fire(const sp_mobj& sender, const sp_obj& param) {
param_ = param;
execute(sender);
}
// if sender != NULL then slot will be activated only for given sender
bool connect(const sp_slot& slot, const sp_mobj& sender = NULL) {
if(!slot) return false;
//my_signal_.connect(bs_slot::slot_wrapper(slot));
my_signal_.connect(slot_holder<>(slot, sender));
return true;
}
bool disconnect(const sp_slot& slot) {
if(!slot) return false;
my_signal_.disconnect(slot_holder<>(slot));
return true;
}
ulong num_slots() const {
return static_cast< ulong >(my_signal_.num_slots());
}
};
//=============================== bs_signal implementation =============================================================
bs_signal::bs_signal(int signal_code)
: pimpl_(new signal_impl(signal_code), mutex(), bs_static_cast())
{}
void bs_signal::init(int signal_code) const {
lpimpl lp(pimpl_);
if(signal_code > 0)
lp->signal_code_ = signal_code;
else
throw bs_kernel_exception ("bs_signal::init", no_error, "Wrong signal code given");
}
void bs_signal::fire(const sp_mobj& sender, const sp_obj& param) const {
//lock during recepients call because boost:signals doesn't support mt
//lpimpl lp(pimpl_);
//lp->param_ = param;
//lp->execute();
pimpl_.lock()->fire(sender, param);
//give_kernel::Instance().add_task(this);
}
bool bs_signal::connect(const sp_slot& slot, const sp_mobj& sender) const {
return pimpl_.lock()->connect(slot, sender);
}
bool bs_signal::disconnect(const sp_slot& slot) const
{
return pimpl_.lock()->disconnect(slot);
}
ulong bs_signal::num_slots() const {
return pimpl_->num_slots();
}
void bs_signal::dispose() const {
delete this;
}
int bs_signal::get_code() const {
return pimpl_->signal_code_;
}
//============================== bs_messaging implementation ===========================================================
//empty ctor
bs_messaging::bs_messaging() {}
//empty dtor
//bs_messaging::~bs_messaging() {}
//ctor that adds all signals in a half-open range
bs_messaging::bs_messaging(const sig_range_t& sig_range) {
add_signal(sig_range);
}
//copy ctor implementation
bs_messaging::bs_messaging(const bs_messaging& mes)
: bs_refcounter(mes), bs_imessaging(), signals_(mes.signals_)
{}
void bs_messaging::swap(bs_messaging& rhs) {
std::swap(signals_, rhs.signals_);
}
//bs_messaging& bs_messaging::operator=(const bs_messaging& lhs) {
// bs_messaging(lhs).swap(*this);
// return *this;
//}
bool bs_messaging::fire_signal(int signal_code, const sp_obj& params) const
{
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig == signals_.end()) return false;
//if(!sig->second->sender_binded())
// sig->second->init(this);
sig->second->fire(this, params);
//kernel &k = give_kernel::Instance();
//sig->second.lock()->set_param(params);
//k.add_task(sig->second);
return true;
}
bool bs_messaging::add_signal(int signal_code)
{
if(signals_.find(signal_code) != signals_.end()) return false;
pair< sp_signal, bool > sig;
sig = BS_KERNEL.reg_signal(BS_GET_TI(*this), signal_code);
signals_[signal_code] = sig.first;
//new bs_signal(signal_code);
return sig.second;
}
ulong bs_messaging::add_signal(const sig_range_t& sr) {
ulong cnt = 0;
for(int i = sr.first; i < sr.second; ++i)
cnt += static_cast< ulong >(add_signal(i));
return cnt;
}
bool bs_messaging::remove_signal(int signal_code)
{
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig != signals_.end())
{
signals_.erase(signal_code);
BS_KERNEL.rem_signal(BS_GET_TI(*this), signal_code);
return true;
}
return false;
}
std::vector< int > bs_messaging::get_signal_list() const
{
std::vector< int > res;
res.reserve(signals_.size());
for (bs_signals_map::const_iterator p = signals_.begin(); p != signals_.end(); ++p)
res.push_back(p->first);
return res;
}
bool bs_messaging::subscribe(int signal_code, const sp_slot& slot) const {
if(!slot) return false;
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig != signals_.end()) {
sig->second->connect(slot, this);
return true;
}
return false;
}
bool bs_messaging::unsubscribe(int signal_code, const smart_ptr< bs_slot, true >& slot) const
{
if(!slot) return false;
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig != signals_.end()) {
sig->second->disconnect(slot);
return true;
}
return false;
}
ulong bs_messaging::num_slots(int signal_code) const {
bs_signals_map::const_iterator sig = signals_.find(signal_code);
if(sig != signals_.end())
return sig->second->num_slots();
else return 0;
}
void bs_messaging::dispose() const {
delete this;
}
} //end of namespace blue_sky
<|endoftext|> |
<commit_before>#include "product_price_trend.h"
#include <common/Utilities.h>
#include <log-manager/PriceHistory.h>
#include <am/range/AmIterator.h>
#include <libcassandra/util_functions.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <algorithm>
using namespace std;
using namespace libcassandra;
using izenelib::util::UString;
namespace sf1r
{
ProductPriceTrend::ProductPriceTrend(
const CassandraStorageConfig& cassandraConfig,
const string& collection_name,
const string& data_dir,
const vector<string>& group_prop_vec,
const vector<uint32_t>& time_int_vec)
: cassandraConfig_(cassandraConfig)
, collection_name_(collection_name)
, data_dir_(data_dir)
, group_prop_vec_(group_prop_vec)
, time_int_vec_(time_int_vec)
, enable_tpc_(!group_prop_vec_.empty() && !time_int_vec_.empty())
{
}
ProductPriceTrend::~ProductPriceTrend()
{
for (TPCStorage::iterator it = tpc_storage_.begin();
it != tpc_storage_.end(); ++it)
{
for (uint32_t i = 0; i < time_int_vec_.size(); i++)
delete it->second[i];
}
}
bool ProductPriceTrend::Init()
{
if (!cassandraConfig_.enable)
return false;
PriceHistory::keyspace_name = cassandraConfig_.keyspace;
PriceHistory::createColumnFamily();
if (!PriceHistory::is_enabled)
return false;
for (vector<string>::const_iterator it = group_prop_vec_.begin();
it != group_prop_vec_.end(); ++it)
{
vector<TPCBTree *>& prop_tpc = tpc_storage_[*it];
for (uint32_t i = 0; i < time_int_vec_.size(); i++)
{
string db_path = data_dir_ + "/" + *it + "." + boost::lexical_cast<string>(time_int_vec_[i]) + ".tpc";
prop_tpc.push_back(new TPCBTree(db_path));
if (!prop_tpc.back()->open())
{
boost::filesystem::remove_all(db_path);
prop_tpc.back()->open();
}
}
}
price_history_buffer_.reserve(10000);
return true;
}
bool ProductPriceTrend::Insert(
const string& docid,
const ProductPrice& price,
time_t timestamp)
{
string key;
ParseDocid_(key, docid);
price_history_buffer_.push_back(PriceHistory(key));
price_history_buffer_.back().insert(timestamp, price);
if (IsBufferFull_())
{
return Flush();
}
return true;
}
bool ProductPriceTrend::Update(
const string& docid,
const ProductPrice& price,
time_t timestamp,
map<string, string>& group_prop_map)
{
string key;
ParseDocid_(key, docid);
price_history_buffer_.push_back(PriceHistory());
price_history_buffer_.back().resetKey(key);
price_history_buffer_.back().insert(timestamp, price);
if (enable_tpc_ && !group_prop_map.empty() && price.value.first > 0)
{
PropItemType& prop_item = prop_map_[key];
prop_item.first = price.value.first;
prop_item.second.swap(group_prop_map);
}
if (IsBufferFull_())
{
return Flush();
}
return true;
}
bool ProductPriceTrend::IsBufferFull_()
{
return price_history_buffer_.size() >= 10000;
}
bool ProductPriceTrend::Flush()
{
bool ret = true;
time_t now = Utilities::createTimeStamp();
if (!prop_map_.empty())
{
for (uint32_t i = 0; i < time_int_vec_.size(); i++)
{
if (!UpdateTPC_(i, now))
ret = false;
}
prop_map_.clear();
}
if (!PriceHistory::updateMultiRow(price_history_buffer_))
ret = false;
price_history_buffer_.clear();
return ret;
}
bool ProductPriceTrend::CronJob()
{
if (!enable_tpc_) return true;
//TODO
return true;
}
bool ProductPriceTrend::UpdateTPC_(uint32_t time_int, time_t timestamp)
{
vector<string> key_list;
Utilities::getKeyList(key_list, prop_map_);
if (timestamp == -1)
timestamp = Utilities::createTimeStamp();
timestamp -= 86400000000LL * time_int_vec_[time_int];
vector<PriceHistory> row_list;
if (!PriceHistory::getMultiSlice(row_list, key_list, serializeLong(timestamp), "", 1))
return false;
map<string, map<string, TPCQueue> > tpc_cache;
for (uint32_t i = 0; i < row_list.size(); i++)
{
const PropItemType& prop_item = prop_map_.find(row_list[i].getDocId())->second;
const pair<time_t, ProductPrice>& price_record = *(row_list[i].getPriceHistory().begin());
const ProductPriceType& old_price = price_record.second.value.first;
float price_cut = old_price == 0 ? 0 : 1 - prop_item.first / old_price;
for (map<string, string>::const_iterator it = prop_item.second.begin();
it != prop_item.second.end(); ++it)
{
TPCQueue& tpc_queue = tpc_cache[it->first][it->second];
if (tpc_queue.empty())
{
tpc_queue.reserve(1001);
tpc_storage_[it->first][time_int]->get(it->second, tpc_queue);
}
tpc_queue.push_back(make_pair(price_cut, string()));
StripDocid_(tpc_queue.back().second, row_list[i].getDocId());
push_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>);
if (tpc_queue.size() > 1000)
{
pop_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>);
tpc_queue.pop_back();
}
}
}
for (map<string, map<string, TPCQueue> >::const_iterator it = tpc_cache.begin();
it != tpc_cache.end(); ++it)
{
TPCBTree* tpc_btree = tpc_storage_[it->first][time_int];
for (map<string, TPCQueue>::const_iterator mit = it->second.begin();
mit != it->second.end(); ++mit)
{
tpc_btree->update(mit->first, mit->second);
}
tpc_btree->flush();
}
return true;
}
bool ProductPriceTrend::GetMultiPriceHistory(
PriceHistoryList& history_list,
const vector<string>& docid_list,
time_t from_tt,
time_t to_tt,
string& error_msg)
{
vector<string> key_list;
ParseDocidList_(key_list, docid_list);
string from_str(from_tt == -1 ? "" : serializeLong(from_tt));
string to_str(to_tt == -1 ? "" : serializeLong(to_tt));
vector<PriceHistory> row_list;
if (!PriceHistory::getMultiSlice(row_list, key_list, from_str, to_str))
{
error_msg = "Failed retrieving price histories from Cassandra";
return false;
}
history_list.reserve(history_list.size() + row_list.size());
for (vector<PriceHistory>::const_iterator it = row_list.begin();
it != row_list.end(); ++it)
{
const PriceHistory::PriceHistoryType& price_history = it->getPriceHistory();
PriceHistoryItem history_item;
history_item.reserve(price_history.size());
for (PriceHistory::PriceHistoryType::const_iterator hit = price_history.begin();
hit != price_history.end(); ++hit)
{
history_item.push_back(make_pair(string(), hit->second.value));
history_item.back().first = boost::posix_time::to_iso_string(
boost::posix_time::from_time_t(hit->first / 1000000 - timezone)
+ boost::posix_time::microseconds(hit->first % 1000000));
}
history_list.push_back(make_pair(string(), PriceHistoryItem()));
StripDocid_(history_list.back().first, it->getDocId());
history_list.back().second.swap(history_item);
}
if (history_list.empty())
{
error_msg = "Have not got any valid docid";
return false;
}
return true;
}
bool ProductPriceTrend::GetMultiPriceRange(
PriceRangeList& range_list,
const vector<string>& docid_list,
time_t from_tt,
time_t to_tt,
string& error_msg)
{
vector<string> key_list;
ParseDocidList_(key_list, docid_list);
string from_str(from_tt == -1 ? "" : serializeLong(from_tt));
string to_str(to_tt == -1 ? "" : serializeLong(to_tt));
vector<PriceHistory> row_list;
if (!PriceHistory::getMultiSlice(row_list, key_list, from_str, to_str))
{
error_msg = "Failed retrieving price histories from Cassandra";
return false;
}
range_list.reserve(range_list.size() + row_list.size());
for (vector<PriceHistory>::const_iterator it = row_list.begin();
it != row_list.end(); ++it)
{
const PriceHistory::PriceHistoryType& price_history = it->getPriceHistory();
ProductPrice range_item;
for (PriceHistory::PriceHistoryType::const_iterator hit = price_history.begin();
hit != price_history.end(); ++hit)
{
range_item += hit->second;
}
range_list.push_back(make_pair(string(), range_item.value));
StripDocid_(range_list.back().first, it->getDocId());
}
if (range_list.empty())
{
error_msg = "Have not got any valid docid";
return false;
}
return true;
}
void ProductPriceTrend::ParseDocid_(string& dest, const string& src) const
{
if (!collection_name_.empty())
{
dest.assign(collection_name_ + "_" + src);
}
else
{
dest.assign(src);
}
}
void ProductPriceTrend::StripDocid_(string& dest, const string& src) const
{
if (!collection_name_.empty() && src.length() > collection_name_.length() + 1)
{
dest.assign(src.substr(collection_name_.length() + 1));
}
else
{
dest.assign(src);
}
}
void ProductPriceTrend::ParseDocidList_(vector<string>& dest, const vector<string>& src) const
{
dest.reserve(dest.size() + src.size());
for (uint32_t i = 0; i < src.size(); i++)
{
if (src[i].empty()) continue;
dest.push_back(string());
ParseDocid_(dest.back(), src[i]);
}
}
void ProductPriceTrend::StripDocidList_(vector<string>& dest, const vector<string>& src) const
{
dest.reserve(dest.size() + src.size());
for (uint32_t i = 0; i < src.size(); i++)
{
if (src[i].empty()) continue;
dest.push_back(string());
StripDocid_(dest.back(), src[i]);
}
}
bool ProductPriceTrend::GetTopPriceCutList(
TPCQueue& tpc_queue,
const string& prop_name,
const string& prop_value,
uint32_t days,
uint32_t count,
string& error_msg)
{
if (!enable_tpc_)
{
error_msg = "Top price-cut list is not enabled for this collection.";
return false;
}
TPCStorage::const_iterator tpc_it = tpc_storage_.find(prop_name);
if (tpc_it == tpc_storage_.end())
{
error_msg = "Don't find data for this property name: " + prop_name;
return false;
}
uint32_t time_int = 0;
while (days > time_int_vec_[time_int++] && time_int < time_int_vec_.size() - 1);
if (!tpc_it->second[time_int]->get(prop_value, tpc_queue))
{
error_msg = "Don't find price-cut record for this property value: " + prop_value;
return false;
}
sort_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator><TPCQueue::value_type>);
if (tpc_queue.size() > count)
tpc_queue.resize(count);
return true;
}
}
<commit_msg>refine heap manipulations<commit_after>#include "product_price_trend.h"
#include <common/Utilities.h>
#include <log-manager/PriceHistory.h>
#include <am/range/AmIterator.h>
#include <libcassandra/util_functions.h>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/filesystem.hpp>
#include <algorithm>
using namespace std;
using namespace libcassandra;
using izenelib::util::UString;
namespace sf1r
{
ProductPriceTrend::ProductPriceTrend(
const CassandraStorageConfig& cassandraConfig,
const string& collection_name,
const string& data_dir,
const vector<string>& group_prop_vec,
const vector<uint32_t>& time_int_vec)
: cassandraConfig_(cassandraConfig)
, collection_name_(collection_name)
, data_dir_(data_dir)
, group_prop_vec_(group_prop_vec)
, time_int_vec_(time_int_vec)
, enable_tpc_(!group_prop_vec_.empty() && !time_int_vec_.empty())
{
}
ProductPriceTrend::~ProductPriceTrend()
{
for (TPCStorage::iterator it = tpc_storage_.begin();
it != tpc_storage_.end(); ++it)
{
for (uint32_t i = 0; i < time_int_vec_.size(); i++)
delete it->second[i];
}
}
bool ProductPriceTrend::Init()
{
if (!cassandraConfig_.enable)
return false;
PriceHistory::keyspace_name = cassandraConfig_.keyspace;
PriceHistory::createColumnFamily();
if (!PriceHistory::is_enabled)
return false;
for (vector<string>::const_iterator it = group_prop_vec_.begin();
it != group_prop_vec_.end(); ++it)
{
vector<TPCBTree *>& prop_tpc = tpc_storage_[*it];
for (uint32_t i = 0; i < time_int_vec_.size(); i++)
{
string db_path = data_dir_ + "/" + *it + "." + boost::lexical_cast<string>(time_int_vec_[i]) + ".tpc";
prop_tpc.push_back(new TPCBTree(db_path));
if (!prop_tpc.back()->open())
{
boost::filesystem::remove_all(db_path);
prop_tpc.back()->open();
}
}
}
price_history_buffer_.reserve(10000);
return true;
}
bool ProductPriceTrend::Insert(
const string& docid,
const ProductPrice& price,
time_t timestamp)
{
string key;
ParseDocid_(key, docid);
price_history_buffer_.push_back(PriceHistory(key));
price_history_buffer_.back().insert(timestamp, price);
if (IsBufferFull_())
{
return Flush();
}
return true;
}
bool ProductPriceTrend::Update(
const string& docid,
const ProductPrice& price,
time_t timestamp,
map<string, string>& group_prop_map)
{
string key;
ParseDocid_(key, docid);
price_history_buffer_.push_back(PriceHistory());
price_history_buffer_.back().resetKey(key);
price_history_buffer_.back().insert(timestamp, price);
if (enable_tpc_ && !group_prop_map.empty() && price.value.first > 0)
{
PropItemType& prop_item = prop_map_[key];
prop_item.first = price.value.first;
prop_item.second.swap(group_prop_map);
}
if (IsBufferFull_())
{
return Flush();
}
return true;
}
bool ProductPriceTrend::IsBufferFull_()
{
return price_history_buffer_.size() >= 10000;
}
bool ProductPriceTrend::Flush()
{
bool ret = true;
time_t now = Utilities::createTimeStamp();
if (!prop_map_.empty())
{
for (uint32_t i = 0; i < time_int_vec_.size(); i++)
{
if (!UpdateTPC_(i, now))
ret = false;
}
prop_map_.clear();
}
if (!PriceHistory::updateMultiRow(price_history_buffer_))
ret = false;
price_history_buffer_.clear();
return ret;
}
bool ProductPriceTrend::CronJob()
{
if (!enable_tpc_) return true;
//TODO
return true;
}
bool ProductPriceTrend::UpdateTPC_(uint32_t time_int, time_t timestamp)
{
vector<string> key_list;
Utilities::getKeyList(key_list, prop_map_);
if (timestamp == -1)
timestamp = Utilities::createTimeStamp();
timestamp -= 86400000000LL * time_int_vec_[time_int];
vector<PriceHistory> row_list;
if (!PriceHistory::getMultiSlice(row_list, key_list, serializeLong(timestamp), "", 1))
return false;
map<string, map<string, TPCQueue> > tpc_cache;
for (uint32_t i = 0; i < row_list.size(); i++)
{
const PropItemType& prop_item = prop_map_.find(row_list[i].getDocId())->second;
const pair<time_t, ProductPrice>& price_record = *(row_list[i].getPriceHistory().begin());
const ProductPriceType& old_price = price_record.second.value.first;
float price_cut = old_price == 0 ? 0 : 1 - prop_item.first / old_price;
for (map<string, string>::const_iterator it = prop_item.second.begin();
it != prop_item.second.end(); ++it)
{
TPCQueue& tpc_queue = tpc_cache[it->first][it->second];
if (tpc_queue.empty())
{
tpc_queue.reserve(1000);
tpc_storage_[it->first][time_int]->get(it->second, tpc_queue);
}
if (tpc_queue.size() < 1000)
{
tpc_queue.push_back(make_pair(price_cut, string()));
StripDocid_(tpc_queue.back().second, row_list[i].getDocId());
push_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>);
}
else if (price_cut > tpc_queue[0].first)
{
pop_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>);
tpc_queue.back().first = price_cut;
StripDocid_(tpc_queue.back().second, row_list[i].getDocId());
push_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator> <TPCQueue::value_type>);
}
}
}
for (map<string, map<string, TPCQueue> >::const_iterator it = tpc_cache.begin();
it != tpc_cache.end(); ++it)
{
TPCBTree* tpc_btree = tpc_storage_[it->first][time_int];
for (map<string, TPCQueue>::const_iterator mit = it->second.begin();
mit != it->second.end(); ++mit)
{
tpc_btree->update(mit->first, mit->second);
}
tpc_btree->flush();
}
return true;
}
bool ProductPriceTrend::GetMultiPriceHistory(
PriceHistoryList& history_list,
const vector<string>& docid_list,
time_t from_tt,
time_t to_tt,
string& error_msg)
{
vector<string> key_list;
ParseDocidList_(key_list, docid_list);
string from_str(from_tt == -1 ? "" : serializeLong(from_tt));
string to_str(to_tt == -1 ? "" : serializeLong(to_tt));
vector<PriceHistory> row_list;
if (!PriceHistory::getMultiSlice(row_list, key_list, from_str, to_str))
{
error_msg = "Failed retrieving price histories from Cassandra";
return false;
}
history_list.reserve(history_list.size() + row_list.size());
for (vector<PriceHistory>::const_iterator it = row_list.begin();
it != row_list.end(); ++it)
{
const PriceHistory::PriceHistoryType& price_history = it->getPriceHistory();
PriceHistoryItem history_item;
history_item.reserve(price_history.size());
for (PriceHistory::PriceHistoryType::const_iterator hit = price_history.begin();
hit != price_history.end(); ++hit)
{
history_item.push_back(make_pair(string(), hit->second.value));
history_item.back().first = boost::posix_time::to_iso_string(
boost::posix_time::from_time_t(hit->first / 1000000 - timezone)
+ boost::posix_time::microseconds(hit->first % 1000000));
}
history_list.push_back(make_pair(string(), PriceHistoryItem()));
StripDocid_(history_list.back().first, it->getDocId());
history_list.back().second.swap(history_item);
}
if (history_list.empty())
{
error_msg = "Have not got any valid docid";
return false;
}
return true;
}
bool ProductPriceTrend::GetMultiPriceRange(
PriceRangeList& range_list,
const vector<string>& docid_list,
time_t from_tt,
time_t to_tt,
string& error_msg)
{
vector<string> key_list;
ParseDocidList_(key_list, docid_list);
string from_str(from_tt == -1 ? "" : serializeLong(from_tt));
string to_str(to_tt == -1 ? "" : serializeLong(to_tt));
vector<PriceHistory> row_list;
if (!PriceHistory::getMultiSlice(row_list, key_list, from_str, to_str))
{
error_msg = "Failed retrieving price histories from Cassandra";
return false;
}
range_list.reserve(range_list.size() + row_list.size());
for (vector<PriceHistory>::const_iterator it = row_list.begin();
it != row_list.end(); ++it)
{
const PriceHistory::PriceHistoryType& price_history = it->getPriceHistory();
ProductPrice range_item;
for (PriceHistory::PriceHistoryType::const_iterator hit = price_history.begin();
hit != price_history.end(); ++hit)
{
range_item += hit->second;
}
range_list.push_back(make_pair(string(), range_item.value));
StripDocid_(range_list.back().first, it->getDocId());
}
if (range_list.empty())
{
error_msg = "Have not got any valid docid";
return false;
}
return true;
}
void ProductPriceTrend::ParseDocid_(string& dest, const string& src) const
{
if (!collection_name_.empty())
{
dest.assign(collection_name_ + "_" + src);
}
else
{
dest.assign(src);
}
}
void ProductPriceTrend::StripDocid_(string& dest, const string& src) const
{
if (!collection_name_.empty() && src.length() > collection_name_.length() + 1)
{
dest.assign(src.substr(collection_name_.length() + 1));
}
else
{
dest.assign(src);
}
}
void ProductPriceTrend::ParseDocidList_(vector<string>& dest, const vector<string>& src) const
{
dest.reserve(dest.size() + src.size());
for (uint32_t i = 0; i < src.size(); i++)
{
if (src[i].empty()) continue;
dest.push_back(string());
ParseDocid_(dest.back(), src[i]);
}
}
void ProductPriceTrend::StripDocidList_(vector<string>& dest, const vector<string>& src) const
{
dest.reserve(dest.size() + src.size());
for (uint32_t i = 0; i < src.size(); i++)
{
if (src[i].empty()) continue;
dest.push_back(string());
StripDocid_(dest.back(), src[i]);
}
}
bool ProductPriceTrend::GetTopPriceCutList(
TPCQueue& tpc_queue,
const string& prop_name,
const string& prop_value,
uint32_t days,
uint32_t count,
string& error_msg)
{
if (!enable_tpc_)
{
error_msg = "Top price-cut list is not enabled for this collection.";
return false;
}
TPCStorage::const_iterator tpc_it = tpc_storage_.find(prop_name);
if (tpc_it == tpc_storage_.end())
{
error_msg = "Don't find data for this property name: " + prop_name;
return false;
}
uint32_t time_int = 0;
while (days > time_int_vec_[time_int++] && time_int < time_int_vec_.size() - 1);
if (!tpc_it->second[time_int]->get(prop_value, tpc_queue))
{
error_msg = "Don't find price-cut record for this property value: " + prop_value;
return false;
}
sort_heap(tpc_queue.begin(), tpc_queue.end(), rel_ops::operator><TPCQueue::value_type>);
if (tpc_queue.size() > count)
tpc_queue.resize(count);
return true;
}
}
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include "vesa_console.hpp"
#include "vesa.hpp"
#include "early_memory.hpp"
namespace {
constexpr const size_t MARGIN = 10;
constexpr const size_t PADDING = 5;
constexpr const size_t LEFT = MARGIN + PADDING;
constexpr const size_t TOP = 40;
// Constants extracted from VESA
size_t _lines;
size_t _columns;
uint32_t _color;
size_t buffer_size;
} //end of anonymous namespace
void vesa_console::init() {
auto& block = *reinterpret_cast<vesa::mode_info_block_t*>(early::vesa_mode_info_address);
_columns = (block.width - (MARGIN + PADDING) * 2) / 8;
_lines = (block.height - TOP - MARGIN - PADDING) / 16;
_color = vesa::make_color(0, 255, 0);
buffer_size = block.height * block.bytes_per_scan_line;
vesa::draw_hline(MARGIN, MARGIN, block.width - 2 * MARGIN, _color);
vesa::draw_hline(MARGIN, 35, block.width - 2 * MARGIN, _color);
vesa::draw_hline(MARGIN, block.height - MARGIN, block.width - 2 * MARGIN, _color);
vesa::draw_vline(MARGIN, MARGIN, block.height - 2 * MARGIN, _color);
vesa::draw_vline(block.width - MARGIN, MARGIN, block.height - 2 * MARGIN, _color);
auto title_left = (block.width - 4 * 8) / 2;
vesa::draw_char(title_left, PADDING + MARGIN, 'T', _color);
vesa::draw_char(title_left + 8, PADDING + MARGIN, 'H', _color);
vesa::draw_char(title_left + 16, PADDING + MARGIN, 'O', _color);
vesa::draw_char(title_left + 24, PADDING + MARGIN, 'R', _color);
}
size_t vesa_console::lines() const {
return _lines;
}
size_t vesa_console::columns() const {
return _columns;
}
void vesa_console::clear() {
vesa::draw_rect(LEFT, TOP, _columns * 8, _lines * 16, vesa::make_color(0, 0, 0));
}
void vesa_console::clear(void* buffer) {
vesa::draw_rect(buffer, LEFT, TOP, _columns * 8, _lines * 16, vesa::make_color(0, 0, 0));
}
void vesa_console::scroll_up() {
vesa::move_lines_up(TOP + 16, LEFT, _columns * 8, (_lines - 1) * 16, 16);
vesa::draw_rect(LEFT, TOP + (_lines - 1) * 16, _columns * 8, 16, vesa::make_color(0, 0, 0));
}
void vesa_console::scroll_up(void* buffer) {
vesa::move_lines_up(buffer, TOP + 16, LEFT, _columns * 8, (_lines - 1) * 16, 16);
vesa::draw_rect(buffer, LEFT, TOP + (_lines - 1) * 16, _columns * 8, 16, vesa::make_color(0, 0, 0));
}
void vesa_console::print_char(size_t line, size_t column, char c) {
vesa::draw_char(LEFT + 8 * column, TOP + 16 * line, c, _color);
}
void vesa_console::print_char(void* buffer, size_t line, size_t column, char c) {
vesa::draw_char(buffer, LEFT + 8 * column, TOP + 16 * line, c, _color);
}
void* vesa_console::save(void* buffer) {
void* buffer32 = static_cast<uint32_t*>(buffer);
if (!buffer32) {
buffer32 = new uint32_t[buffer_size];
}
vesa::save(static_cast<char*>(buffer32));
return buffer32;
}
void vesa_console::restore(void* buffer) {
vesa::redraw(static_cast<char*>(buffer));
}
<commit_msg>Some debugging<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://www.opensource.org/licenses/MIT)
//=======================================================================
#include "vesa_console.hpp"
#include "vesa.hpp"
#include "early_memory.hpp"
#include "logging.hpp"
namespace {
constexpr const size_t MARGIN = 10;
constexpr const size_t PADDING = 5;
constexpr const size_t LEFT = MARGIN + PADDING;
constexpr const size_t TOP = 40;
// Constants extracted from VESA
size_t _lines;
size_t _columns;
uint32_t _color;
size_t buffer_size;
} //end of anonymous namespace
void vesa_console::init() {
logging::logf(logging::log_level::TRACE, "vesa_console: init()\n");
auto& block = *reinterpret_cast<vesa::mode_info_block_t*>(early::vesa_mode_info_address);
_columns = (block.width - (MARGIN + PADDING) * 2) / 8;
_lines = (block.height - TOP - MARGIN - PADDING) / 16;
_color = vesa::make_color(0, 255, 0);
buffer_size = block.height * block.bytes_per_scan_line;
vesa::draw_hline(MARGIN, MARGIN, block.width - 2 * MARGIN, _color);
vesa::draw_hline(MARGIN, 35, block.width - 2 * MARGIN, _color);
vesa::draw_hline(MARGIN, block.height - MARGIN, block.width - 2 * MARGIN, _color);
vesa::draw_vline(MARGIN, MARGIN, block.height - 2 * MARGIN, _color);
vesa::draw_vline(block.width - MARGIN, MARGIN, block.height - 2 * MARGIN, _color);
auto title_left = (block.width - 4 * 8) / 2;
vesa::draw_char(title_left, PADDING + MARGIN, 'T', _color);
vesa::draw_char(title_left + 8, PADDING + MARGIN, 'H', _color);
vesa::draw_char(title_left + 16, PADDING + MARGIN, 'O', _color);
vesa::draw_char(title_left + 24, PADDING + MARGIN, 'R', _color);
logging::logf(logging::log_level::TRACE, "vesa_console: Buffer size: %m\n", buffer_size * sizeof(uint32_t));
}
size_t vesa_console::lines() const {
return _lines;
}
size_t vesa_console::columns() const {
return _columns;
}
void vesa_console::clear() {
vesa::draw_rect(LEFT, TOP, _columns * 8, _lines * 16, vesa::make_color(0, 0, 0));
}
void vesa_console::clear(void* buffer) {
vesa::draw_rect(buffer, LEFT, TOP, _columns * 8, _lines * 16, vesa::make_color(0, 0, 0));
}
void vesa_console::scroll_up() {
vesa::move_lines_up(TOP + 16, LEFT, _columns * 8, (_lines - 1) * 16, 16);
vesa::draw_rect(LEFT, TOP + (_lines - 1) * 16, _columns * 8, 16, vesa::make_color(0, 0, 0));
}
void vesa_console::scroll_up(void* buffer) {
vesa::move_lines_up(buffer, TOP + 16, LEFT, _columns * 8, (_lines - 1) * 16, 16);
vesa::draw_rect(buffer, LEFT, TOP + (_lines - 1) * 16, _columns * 8, 16, vesa::make_color(0, 0, 0));
}
void vesa_console::print_char(size_t line, size_t column, char c) {
vesa::draw_char(LEFT + 8 * column, TOP + 16 * line, c, _color);
}
void vesa_console::print_char(void* buffer, size_t line, size_t column, char c) {
vesa::draw_char(buffer, LEFT + 8 * column, TOP + 16 * line, c, _color);
}
void* vesa_console::save(void* buffer) {
void* buffer32 = static_cast<uint32_t*>(buffer);
if (!buffer32) {
buffer32 = new uint32_t[buffer_size];
}
vesa::save(static_cast<char*>(buffer32));
return buffer32;
}
void vesa_console::restore(void* buffer) {
vesa::redraw(static_cast<char*>(buffer));
}
<|endoftext|> |
<commit_before>#include "Base.h"
#include "Camera.h"
#include "Game.h"
#include "Node.h"
#include "Game.h"
#include "PhysicsController.h"
// Camera dirty bits
#define CAMERA_DIRTY_VIEW 1
#define CAMERA_DIRTY_PROJ 2
#define CAMERA_DIRTY_VIEW_PROJ 4
#define CAMERA_DIRTY_INV_VIEW 8
#define CAMERA_DIRTY_INV_VIEW_PROJ 16
#define CAMERA_DIRTY_BOUNDS 32
#define CAMERA_DIRTY_ALL (CAMERA_DIRTY_VIEW | CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS)
// Other misc camera bits
#define CAMERA_CUSTOM_PROJECTION 64
namespace gameplay
{
Camera::Camera(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
: _type(PERSPECTIVE), _fieldOfView(fieldOfView), _aspectRatio(aspectRatio), _nearPlane(nearPlane), _farPlane(farPlane),
_bits(CAMERA_DIRTY_ALL), _node(NULL), _listeners(NULL)
{
}
Camera::Camera(float zoomX, float zoomY, float aspectRatio, float nearPlane, float farPlane)
: _type(ORTHOGRAPHIC), _aspectRatio(aspectRatio), _nearPlane(nearPlane), _farPlane(farPlane),
_bits(CAMERA_DIRTY_ALL), _node(NULL), _listeners(NULL)
{
// Orthographic camera.
_zoom[0] = zoomX;
_zoom[1] = zoomY;
}
Camera::~Camera()
{
SAFE_DELETE(_listeners);
}
Camera* Camera::createPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
{
return new Camera(fieldOfView, aspectRatio, nearPlane, farPlane);
}
Camera* Camera::createOrthographic(float zoomX, float zoomY, float aspectRatio, float nearPlane, float farPlane)
{
return new Camera(zoomX, zoomY, aspectRatio, nearPlane, farPlane);
}
Camera* Camera::create(Properties* properties)
{
GP_ASSERT(properties);
// Read camera type
std::string typeStr;
if (properties->exists("type"))
typeStr = properties->getString("type");
Camera::Type type;
if (typeStr == "PERSPECTIVE")
{
type = Camera::PERSPECTIVE;
}
else if (typeStr == "ORTHOGRAPHIC")
{
type = Camera::ORTHOGRAPHIC;
}
else
{
GP_ERROR("Invalid 'type' parameter for camera definition.");
return NULL;
}
// Read common parameters
float aspectRatio, nearPlane, farPlane;
if (properties->exists("aspectRatio"))
{
aspectRatio = properties->getFloat("aspectRatio");
}
else
{
// Use default aspect ratio
aspectRatio = (float)Game::getInstance()->getWidth() / Game::getInstance()->getHeight();
}
if (properties->exists("nearPlane"))
nearPlane = properties->getFloat("nearPlane");
else
nearPlane = 0.2f; // use some reasonable default value
if (properties->exists("farPlane"))
farPlane = properties->getFloat("farPlane");
else
farPlane = 100; // use some reasonable default value
Camera* camera = NULL;
switch (type)
{
case Camera::PERSPECTIVE:
// If field of view is not specified, use a default of 60 degrees
camera = createPerspective(
properties->exists("fieldOfView") ? properties->getFloat("fieldOfView") : 60.0f,
aspectRatio, nearPlane, farPlane);
break;
case Camera::ORTHOGRAPHIC:
// If zoomX and zoomY are not specified, use screen width/height
camera = createOrthographic(
properties->exists("zoomX") ? properties->getFloat("zoomX") : Game::getInstance()->getWidth(),
properties->exists("zoomY") ? properties->getFloat("zoomY") : Game::getInstance()->getHeight(),
aspectRatio, nearPlane, farPlane);
break;
}
return camera;
}
Camera::Type Camera::getCameraType() const
{
return _type;
}
float Camera::getFieldOfView() const
{
GP_ASSERT(_type == Camera::PERSPECTIVE);
return _fieldOfView;
}
void Camera::setFieldOfView(float fieldOfView)
{
GP_ASSERT(_type == Camera::PERSPECTIVE);
_fieldOfView = fieldOfView;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getZoomX() const
{
GP_ASSERT(_type == Camera::ORTHOGRAPHIC);
return _zoom[0];
}
void Camera::setZoomX(float zoomX)
{
GP_ASSERT(_type == Camera::ORTHOGRAPHIC);
_zoom[0] = zoomX;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getZoomY() const
{
GP_ASSERT(_type == Camera::ORTHOGRAPHIC);
return _zoom[1];
}
void Camera::setZoomY(float zoomY)
{
GP_ASSERT(_type == Camera::ORTHOGRAPHIC);
_zoom[1] = zoomY;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getAspectRatio() const
{
return _aspectRatio;
}
void Camera::setAspectRatio(float aspectRatio)
{
_aspectRatio = aspectRatio;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getNearPlane() const
{
return _nearPlane;
}
void Camera::setNearPlane(float nearPlane)
{
_nearPlane = nearPlane;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getFarPlane() const
{
return _farPlane;
}
void Camera::setFarPlane(float farPlane)
{
_farPlane = farPlane;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
Node* Camera::getNode() const
{
return _node;
}
void Camera::setNode(Node* node)
{
if (_node != node)
{
if (_node)
{
_node->removeListener(this);
}
// Connect the new node.
_node = node;
if (_node)
{
_node->addListener(this);
}
_bits |= CAMERA_DIRTY_VIEW | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
}
const Matrix& Camera::getViewMatrix() const
{
if (_bits & CAMERA_DIRTY_VIEW)
{
if (_node)
{
// The view matrix is the inverse of our transform matrix.
_node->getWorldMatrix().invert(&_view);
}
else
{
_view.setIdentity();
}
_bits &= ~CAMERA_DIRTY_VIEW;
}
return _view;
}
const Matrix& Camera::getInverseViewMatrix() const
{
if (_bits & CAMERA_DIRTY_INV_VIEW)
{
getViewMatrix().invert(&_inverseView);
_bits &= ~CAMERA_DIRTY_INV_VIEW;
}
return _inverseView;
}
const Matrix& Camera::getProjectionMatrix() const
{
if (!(_bits & CAMERA_CUSTOM_PROJECTION) && (_bits & CAMERA_DIRTY_PROJ))
{
if (_type == PERSPECTIVE)
{
Matrix::createPerspective(_fieldOfView, _aspectRatio, _nearPlane, _farPlane, &_projection);
}
else
{
// Create an ortho projection with the origin at the bottom left of the viewport, +X to the right and +Y up.
Matrix::createOrthographic(_zoom[0], _zoom[1], _nearPlane, _farPlane, &_projection);
}
_bits &= ~CAMERA_DIRTY_PROJ;
}
return _projection;
}
void Camera::setProjectionMatrix(const Matrix& matrix)
{
_projection = matrix;
_bits |= CAMERA_CUSTOM_PROJECTION;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
void Camera::resetProjectionMatrix()
{
if (_bits & CAMERA_CUSTOM_PROJECTION)
{
_bits &= ~CAMERA_CUSTOM_PROJECTION;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
}
const Matrix& Camera::getViewProjectionMatrix() const
{
if (_bits & CAMERA_DIRTY_VIEW_PROJ)
{
Matrix::multiply(getProjectionMatrix(), getViewMatrix(), &_viewProjection);
_bits &= ~CAMERA_DIRTY_VIEW_PROJ;
}
return _viewProjection;
}
const Matrix& Camera::getInverseViewProjectionMatrix() const
{
if (_bits & CAMERA_DIRTY_INV_VIEW_PROJ)
{
getViewProjectionMatrix().invert(&_inverseViewProjection);
_bits &= ~CAMERA_DIRTY_INV_VIEW_PROJ;
}
return _inverseViewProjection;
}
const Frustum& Camera::getFrustum() const
{
if (_bits & CAMERA_DIRTY_BOUNDS)
{
// Update our bounding frustum from our view projection matrix.
_bounds.set(getViewProjectionMatrix());
_bits &= ~CAMERA_DIRTY_BOUNDS;
}
return _bounds;
}
void Camera::project(const Rectangle& viewport, const Vector3& position, float* x, float* y, float* depth) const
{
GP_ASSERT(x);
GP_ASSERT(y);
// Transform the point to clip-space.
Vector4 clipPos;
getViewProjectionMatrix().transformVector(Vector4(position.x, position.y, position.z, 1.0f), &clipPos);
// Compute normalized device coordinates.
GP_ASSERT(clipPos.w != 0.0f);
float ndcX = clipPos.x / clipPos.w;
float ndcY = clipPos.y / clipPos.w;
// Compute screen coordinates by applying our viewport transformation.
*x = viewport.x + (ndcX + 1.0f) * 0.5f * viewport.width;
*y = viewport.y + (1.0f - (ndcY + 1.0f) * 0.5f) * viewport.height;
if (depth)
{
float ndcZ = clipPos.z / clipPos.w;
*depth = (ndcZ + 1.0f) / 2.0f;
}
}
void Camera::project(const Rectangle& viewport, const Vector3& position, Vector2* out) const
{
GP_ASSERT(out);
float x, y;
project(viewport, position, &x, &y);
out->set(x, y);
}
void Camera::project(const Rectangle& viewport, const Vector3& position, Vector3* out) const
{
GP_ASSERT(out);
float x, y, depth;
project(viewport, position, &x, &y, &depth);
out->set(x, y, depth);
}
void Camera::unproject(const Rectangle& viewport, float x, float y, float depth, Vector3* dst) const
{
GP_ASSERT(dst);
// Create our screen space position in NDC.
GP_ASSERT(viewport.width != 0.0f && viewport.height != 0.0f);
Vector4 screen((x - viewport.x) / viewport.width, ((viewport.height - y) - viewport.y) / viewport.height, depth, 1.0f);
// Map to range -1 to 1.
screen.x = screen.x * 2.0f - 1.0f;
screen.y = screen.y * 2.0f - 1.0f;
screen.z = screen.z * 2.0f - 1.0f;
// Transform the screen-space NDC by our inverse view projection matrix.
getInverseViewProjectionMatrix().transformVector(screen, &screen);
// Divide by our W coordinate.
if (screen.w != 0.0f)
{
screen.x /= screen.w;
screen.y /= screen.w;
screen.z /= screen.w;
}
dst->set(screen.x, screen.y, screen.z);
}
void Camera::pickRay(const Rectangle& viewport, float x, float y, Ray* dst) const
{
GP_ASSERT(dst);
// Get the world-space position at the near clip plane.
Vector3 nearPoint;
unproject(viewport, x, y, 0.0f, &nearPoint);
// Get the world-space position at the far clip plane.
Vector3 farPoint;
unproject(viewport, x, y, 1.0f, &farPoint);
// Set the direction of the ray.
Vector3 direction;
Vector3::subtract(farPoint, nearPoint, &direction);
direction.normalize();
dst->set(nearPoint, direction);
}
Camera* Camera::clone(NodeCloneContext& context)
{
Camera* cameraClone = NULL;
if (getCameraType() == PERSPECTIVE)
{
cameraClone = createPerspective(_fieldOfView, _aspectRatio, _nearPlane, _farPlane);
}
else if (getCameraType() == ORTHOGRAPHIC)
{
cameraClone = createOrthographic(getZoomX(), getZoomY(), getAspectRatio(), _nearPlane, _farPlane);
}
GP_ASSERT(cameraClone);
if (Node* node = context.findClonedNode(getNode()))
{
cameraClone->setNode(node);
}
return cameraClone;
}
void Camera::transformChanged(Transform* transform, long cookie)
{
_bits |= CAMERA_DIRTY_VIEW | CAMERA_DIRTY_INV_VIEW | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
void Camera::cameraChanged()
{
if (_listeners == NULL)
return;
for (std::list<Camera::Listener*>::iterator itr = _listeners->begin(); itr != _listeners->end(); ++itr)
{
Camera::Listener* listener = (*itr);
listener->cameraChanged(this);
}
}
void Camera::addListener(Camera::Listener* listener)
{
GP_ASSERT(listener);
if (_listeners == NULL)
_listeners = new std::list<Camera::Listener*>();
_listeners->push_back(listener);
}
void Camera::removeListener(Camera::Listener* listener)
{
GP_ASSERT(listener);
if (_listeners)
{
for (std::list<Camera::Listener*>::iterator itr = _listeners->begin(); itr != _listeners->end(); ++itr)
{
if ((*itr) == listener)
{
_listeners->erase(itr);
break;
}
}
}
}
}
<commit_msg>fixed Camera::unproject to properly work with arbitrary viewports (previously if viewport origin was not at zero the unproject result was incorrectly calculated)<commit_after>#include "Base.h"
#include "Camera.h"
#include "Game.h"
#include "Node.h"
#include "Game.h"
#include "PhysicsController.h"
// Camera dirty bits
#define CAMERA_DIRTY_VIEW 1
#define CAMERA_DIRTY_PROJ 2
#define CAMERA_DIRTY_VIEW_PROJ 4
#define CAMERA_DIRTY_INV_VIEW 8
#define CAMERA_DIRTY_INV_VIEW_PROJ 16
#define CAMERA_DIRTY_BOUNDS 32
#define CAMERA_DIRTY_ALL (CAMERA_DIRTY_VIEW | CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS)
// Other misc camera bits
#define CAMERA_CUSTOM_PROJECTION 64
namespace gameplay
{
Camera::Camera(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
: _type(PERSPECTIVE), _fieldOfView(fieldOfView), _aspectRatio(aspectRatio), _nearPlane(nearPlane), _farPlane(farPlane),
_bits(CAMERA_DIRTY_ALL), _node(NULL), _listeners(NULL)
{
}
Camera::Camera(float zoomX, float zoomY, float aspectRatio, float nearPlane, float farPlane)
: _type(ORTHOGRAPHIC), _aspectRatio(aspectRatio), _nearPlane(nearPlane), _farPlane(farPlane),
_bits(CAMERA_DIRTY_ALL), _node(NULL), _listeners(NULL)
{
// Orthographic camera.
_zoom[0] = zoomX;
_zoom[1] = zoomY;
}
Camera::~Camera()
{
SAFE_DELETE(_listeners);
}
Camera* Camera::createPerspective(float fieldOfView, float aspectRatio, float nearPlane, float farPlane)
{
return new Camera(fieldOfView, aspectRatio, nearPlane, farPlane);
}
Camera* Camera::createOrthographic(float zoomX, float zoomY, float aspectRatio, float nearPlane, float farPlane)
{
return new Camera(zoomX, zoomY, aspectRatio, nearPlane, farPlane);
}
Camera* Camera::create(Properties* properties)
{
GP_ASSERT(properties);
// Read camera type
std::string typeStr;
if (properties->exists("type"))
typeStr = properties->getString("type");
Camera::Type type;
if (typeStr == "PERSPECTIVE")
{
type = Camera::PERSPECTIVE;
}
else if (typeStr == "ORTHOGRAPHIC")
{
type = Camera::ORTHOGRAPHIC;
}
else
{
GP_ERROR("Invalid 'type' parameter for camera definition.");
return NULL;
}
// Read common parameters
float aspectRatio, nearPlane, farPlane;
if (properties->exists("aspectRatio"))
{
aspectRatio = properties->getFloat("aspectRatio");
}
else
{
// Use default aspect ratio
aspectRatio = (float)Game::getInstance()->getWidth() / Game::getInstance()->getHeight();
}
if (properties->exists("nearPlane"))
nearPlane = properties->getFloat("nearPlane");
else
nearPlane = 0.2f; // use some reasonable default value
if (properties->exists("farPlane"))
farPlane = properties->getFloat("farPlane");
else
farPlane = 100; // use some reasonable default value
Camera* camera = NULL;
switch (type)
{
case Camera::PERSPECTIVE:
// If field of view is not specified, use a default of 60 degrees
camera = createPerspective(
properties->exists("fieldOfView") ? properties->getFloat("fieldOfView") : 60.0f,
aspectRatio, nearPlane, farPlane);
break;
case Camera::ORTHOGRAPHIC:
// If zoomX and zoomY are not specified, use screen width/height
camera = createOrthographic(
properties->exists("zoomX") ? properties->getFloat("zoomX") : Game::getInstance()->getWidth(),
properties->exists("zoomY") ? properties->getFloat("zoomY") : Game::getInstance()->getHeight(),
aspectRatio, nearPlane, farPlane);
break;
}
return camera;
}
Camera::Type Camera::getCameraType() const
{
return _type;
}
float Camera::getFieldOfView() const
{
GP_ASSERT(_type == Camera::PERSPECTIVE);
return _fieldOfView;
}
void Camera::setFieldOfView(float fieldOfView)
{
GP_ASSERT(_type == Camera::PERSPECTIVE);
_fieldOfView = fieldOfView;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getZoomX() const
{
GP_ASSERT(_type == Camera::ORTHOGRAPHIC);
return _zoom[0];
}
void Camera::setZoomX(float zoomX)
{
GP_ASSERT(_type == Camera::ORTHOGRAPHIC);
_zoom[0] = zoomX;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getZoomY() const
{
GP_ASSERT(_type == Camera::ORTHOGRAPHIC);
return _zoom[1];
}
void Camera::setZoomY(float zoomY)
{
GP_ASSERT(_type == Camera::ORTHOGRAPHIC);
_zoom[1] = zoomY;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getAspectRatio() const
{
return _aspectRatio;
}
void Camera::setAspectRatio(float aspectRatio)
{
_aspectRatio = aspectRatio;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getNearPlane() const
{
return _nearPlane;
}
void Camera::setNearPlane(float nearPlane)
{
_nearPlane = nearPlane;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
float Camera::getFarPlane() const
{
return _farPlane;
}
void Camera::setFarPlane(float farPlane)
{
_farPlane = farPlane;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
Node* Camera::getNode() const
{
return _node;
}
void Camera::setNode(Node* node)
{
if (_node != node)
{
if (_node)
{
_node->removeListener(this);
}
// Connect the new node.
_node = node;
if (_node)
{
_node->addListener(this);
}
_bits |= CAMERA_DIRTY_VIEW | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
}
const Matrix& Camera::getViewMatrix() const
{
if (_bits & CAMERA_DIRTY_VIEW)
{
if (_node)
{
// The view matrix is the inverse of our transform matrix.
_node->getWorldMatrix().invert(&_view);
}
else
{
_view.setIdentity();
}
_bits &= ~CAMERA_DIRTY_VIEW;
}
return _view;
}
const Matrix& Camera::getInverseViewMatrix() const
{
if (_bits & CAMERA_DIRTY_INV_VIEW)
{
getViewMatrix().invert(&_inverseView);
_bits &= ~CAMERA_DIRTY_INV_VIEW;
}
return _inverseView;
}
const Matrix& Camera::getProjectionMatrix() const
{
if (!(_bits & CAMERA_CUSTOM_PROJECTION) && (_bits & CAMERA_DIRTY_PROJ))
{
if (_type == PERSPECTIVE)
{
Matrix::createPerspective(_fieldOfView, _aspectRatio, _nearPlane, _farPlane, &_projection);
}
else
{
// Create an ortho projection with the origin at the bottom left of the viewport, +X to the right and +Y up.
Matrix::createOrthographic(_zoom[0], _zoom[1], _nearPlane, _farPlane, &_projection);
}
_bits &= ~CAMERA_DIRTY_PROJ;
}
return _projection;
}
void Camera::setProjectionMatrix(const Matrix& matrix)
{
_projection = matrix;
_bits |= CAMERA_CUSTOM_PROJECTION;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
void Camera::resetProjectionMatrix()
{
if (_bits & CAMERA_CUSTOM_PROJECTION)
{
_bits &= ~CAMERA_CUSTOM_PROJECTION;
_bits |= CAMERA_DIRTY_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
}
const Matrix& Camera::getViewProjectionMatrix() const
{
if (_bits & CAMERA_DIRTY_VIEW_PROJ)
{
Matrix::multiply(getProjectionMatrix(), getViewMatrix(), &_viewProjection);
_bits &= ~CAMERA_DIRTY_VIEW_PROJ;
}
return _viewProjection;
}
const Matrix& Camera::getInverseViewProjectionMatrix() const
{
if (_bits & CAMERA_DIRTY_INV_VIEW_PROJ)
{
getViewProjectionMatrix().invert(&_inverseViewProjection);
_bits &= ~CAMERA_DIRTY_INV_VIEW_PROJ;
}
return _inverseViewProjection;
}
const Frustum& Camera::getFrustum() const
{
if (_bits & CAMERA_DIRTY_BOUNDS)
{
// Update our bounding frustum from our view projection matrix.
_bounds.set(getViewProjectionMatrix());
_bits &= ~CAMERA_DIRTY_BOUNDS;
}
return _bounds;
}
void Camera::project(const Rectangle& viewport, const Vector3& position, float* x, float* y, float* depth) const
{
GP_ASSERT(x);
GP_ASSERT(y);
// Transform the point to clip-space.
Vector4 clipPos;
getViewProjectionMatrix().transformVector(Vector4(position.x, position.y, position.z, 1.0f), &clipPos);
// Compute normalized device coordinates.
GP_ASSERT(clipPos.w != 0.0f);
float ndcX = clipPos.x / clipPos.w;
float ndcY = clipPos.y / clipPos.w;
// Compute screen coordinates by applying our viewport transformation.
*x = viewport.x + (ndcX + 1.0f) * 0.5f * viewport.width;
*y = viewport.y + (1.0f - (ndcY + 1.0f) * 0.5f) * viewport.height;
if (depth)
{
float ndcZ = clipPos.z / clipPos.w;
*depth = (ndcZ + 1.0f) / 2.0f;
}
}
void Camera::project(const Rectangle& viewport, const Vector3& position, Vector2* out) const
{
GP_ASSERT(out);
float x, y;
project(viewport, position, &x, &y);
out->set(x, y);
}
void Camera::project(const Rectangle& viewport, const Vector3& position, Vector3* out) const
{
GP_ASSERT(out);
float x, y, depth;
project(viewport, position, &x, &y, &depth);
out->set(x, y, depth);
}
void Camera::unproject(const Rectangle& viewport, float x, float y, float depth, Vector3* dst) const
{
GP_ASSERT(dst);
// Create our screen space position in NDC.
GP_ASSERT(viewport.width != 0.0f && viewport.height != 0.0f);
Vector4 screen((x - viewport.x) / viewport.width, (viewport.y - y + viewport.height) / viewport.height, depth, 1.0f);
// Map to range -1 to 1.
screen.x = screen.x * 2.0f - 1.0f;
screen.y = screen.y * 2.0f - 1.0f;
screen.z = screen.z * 2.0f - 1.0f;
// Transform the screen-space NDC by our inverse view projection matrix.
getInverseViewProjectionMatrix().transformVector(screen, &screen);
// Divide by our W coordinate.
if (screen.w != 0.0f)
{
screen.x /= screen.w;
screen.y /= screen.w;
screen.z /= screen.w;
}
dst->set(screen.x, screen.y, screen.z);
}
void Camera::pickRay(const Rectangle& viewport, float x, float y, Ray* dst) const
{
GP_ASSERT(dst);
// Get the world-space position at the near clip plane.
Vector3 nearPoint;
unproject(viewport, x, y, 0.0f, &nearPoint);
// Get the world-space position at the far clip plane.
Vector3 farPoint;
unproject(viewport, x, y, 1.0f, &farPoint);
// Set the direction of the ray.
Vector3 direction;
Vector3::subtract(farPoint, nearPoint, &direction);
direction.normalize();
dst->set(nearPoint, direction);
}
Camera* Camera::clone(NodeCloneContext& context)
{
Camera* cameraClone = NULL;
if (getCameraType() == PERSPECTIVE)
{
cameraClone = createPerspective(_fieldOfView, _aspectRatio, _nearPlane, _farPlane);
}
else if (getCameraType() == ORTHOGRAPHIC)
{
cameraClone = createOrthographic(getZoomX(), getZoomY(), getAspectRatio(), _nearPlane, _farPlane);
}
GP_ASSERT(cameraClone);
if (Node* node = context.findClonedNode(getNode()))
{
cameraClone->setNode(node);
}
return cameraClone;
}
void Camera::transformChanged(Transform* transform, long cookie)
{
_bits |= CAMERA_DIRTY_VIEW | CAMERA_DIRTY_INV_VIEW | CAMERA_DIRTY_INV_VIEW_PROJ | CAMERA_DIRTY_VIEW_PROJ | CAMERA_DIRTY_BOUNDS;
cameraChanged();
}
void Camera::cameraChanged()
{
if (_listeners == NULL)
return;
for (std::list<Camera::Listener*>::iterator itr = _listeners->begin(); itr != _listeners->end(); ++itr)
{
Camera::Listener* listener = (*itr);
listener->cameraChanged(this);
}
}
void Camera::addListener(Camera::Listener* listener)
{
GP_ASSERT(listener);
if (_listeners == NULL)
_listeners = new std::list<Camera::Listener*>();
_listeners->push_back(listener);
}
void Camera::removeListener(Camera::Listener* listener)
{
GP_ASSERT(listener);
if (_listeners)
{
for (std::list<Camera::Listener*>::iterator itr = _listeners->begin(); itr != _listeners->end(); ++itr)
{
if ((*itr) == listener)
{
_listeners->erase(itr);
break;
}
}
}
}
}
<|endoftext|> |
<commit_before>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
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.
*/
#ifndef RESEMBLA_ELIMINATOR_HPP
#define RESEMBLA_ELIMINATOR_HPP
#include <string>
#include <vector>
#include <map>
#include "string_util.hpp"
namespace resembla {
template<typename string_type, typename bitvector_type = uint64_t>
struct Eliminator
{
using size_type = typename string_type::size_type;
using symbol_type = typename string_type::value_type;
using distance_type = int;
Eliminator(string_type const& pattern = string_type())
{
init(pattern);
}
void init(string_type const& pattern)
{
this->pattern = pattern;
if(pattern.empty()){
return;
}
pattern_length = pattern.size();
block_size = ((pattern_length - 1) >> bitOffset<bitvector_type>()) + 1;
rest_bits = pattern_length - (block_size - 1) * bitWidth<bitvector_type>();
sink = bitvector_type{1} << (rest_bits - 1);
constructPM();
zeroes.resize(block_size, 0);
work.resize(block_size);
VP0 = 0;
for(size_type i = 0; i < rest_bits; ++i){
VP0 |= bitvector_type{1} << i;
}
}
void operator()(std::vector<string_type>& candidates, size_type k, bool keep_tie = true)
{
using index_distance = std::pair<size_type, distance_type>;
// calculate scores
std::vector<index_distance> work(candidates.size());
for(size_type i = 0; i < work.size(); ++i){
work[i].first = i;
work[i].second = -distance(candidates[i]);
}
if(keep_tie){
// sort partially to obtain top-k elements
std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),
[](const index_distance& a, const index_distance& b) -> bool{
return a.second > b.second;
});
}
else{
std::sort(std::begin(work), std::end(work),
[](const index_distance& a, const index_distance& b) -> bool{
return a.second > b.second;
});
// expand k so that work[l] < work[k] for all l > k
while(k < work.size() - 1 && work[k] == work[k + 1]){
++k;
}
}
// ensure that work[i].first < work[j].first if i < j < k
std::sort(std::begin(work), std::begin(work) + k,
[](const index_distance& a, const index_distance& b) -> bool{
return a.first < b.first;
});
#ifdef DEBUG
std::cerr << "narrow " << work.size() << " strings" << std::endl;
for(size_type i = 0; i < k; ++i){
std::cerr << cast_string<std::string>(candidates[work[i].first]) << ": " << work[i].second << std::endl;
}
#endif
// sort original list
for(size_type i = 0; i < k; ++i){
std::swap(candidates[i], candidates[work[i].first]);
}
candidates.erase(std::begin(candidates) + k, std::end(candidates));
}
protected:
string_type pattern;
size_type pattern_length;
symbol_type c_min, c_max;
size_type block_size;
size_type rest_bits;
bitvector_type sink;
std::vector<std::pair<symbol_type, std::vector<bitvector_type>>> PM;
std::vector<bitvector_type> zeroes;
struct WorkData
{
bitvector_type D0;
bitvector_type HP;
bitvector_type HN;
bitvector_type VP;
bitvector_type VN;
void reset()
{
D0 = HP = HN = VN = 0;
VP = ~(bitvector_type{0});
}
};
std::vector<WorkData> work;
bitvector_type VP0;
template<typename Integer> static constexpr int bitWidth()
{
return 8 * sizeof(Integer);
}
static constexpr int bitOffset(int w)
{
return w < 2 ? 0 : (bitOffset(w >> 1) + 1);
}
template<typename Integer> static constexpr int bitOffset()
{
return bitOffset(bitWidth<Integer>());
}
template<typename key_type, typename value_type>
const value_type& findValue(const std::vector<std::pair<key_type, value_type>>& data,
const key_type c, const value_type& default_value) const
{
if(c < c_min || c_max < c){
return default_value;
}
else if(c == c_min){
return PM.front().second;
}
else if(c == c_max){
return PM.back().second;
}
size_type l = 1, r = data.size() - 1;
while(r - l > 8){
auto i = (l + r) / 2;
if(data[i].first < c){
l = i + 1;
}
else if(data[i].first > c){
r = i;
}
else{
return data[i].second;
}
}
for(size_type i = l; i < r; ++i){
if(data[i].first == c){
return data[i].second;
}
}
return default_value;
}
void constructPM()
{
std::map<symbol_type, std::vector<bitvector_type>> PM_work;
for(size_type i = 0; i < block_size - 1; ++i){
for(size_type j = 0; j < bitWidth<bitvector_type>(); ++j){
if(PM_work[pattern[i * bitWidth<bitvector_type>() + j]].empty()){
PM_work[pattern[i * bitWidth<bitvector_type>() + j]].resize(block_size, 0);
}
PM_work[pattern[i * bitWidth<bitvector_type>() + j]][i] |= bitvector_type{1} << j;
}
}
for(size_type i = 0; i < rest_bits; ++i){
if(PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].empty()){
PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].resize(block_size, 0);
}
PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].back() |= bitvector_type{1} << i;
}
PM.resize(PM_work.size());
std::copy(PM_work.begin(), PM_work.end(), PM.begin());
c_min = PM.front().first;
c_max = PM.back().first;
}
distance_type distance_sp(string_type const &text)
{
auto& w = work.front();
w.reset();
w.VP = VP0;
distance_type D = pattern_length;
for(auto c: text){
auto X = findValue(PM, c, zeroes).front() | w.VN;
w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;
w.HP = w.VN | ~(w.VP | w.D0);
w.HN = w.VP & w.D0;
X = (w.HP << 1) | 1;
w.VP = (w.HN << 1) | ~(X | w.D0);
w.VN = X & w.D0;
if(w.HP & sink){
++D;
}
else if(w.HN & sink){
--D;
}
}
return D;
}
distance_type distance_lp(string_type const &text)
{
constexpr bitvector_type msb = bitvector_type{1} << (bitWidth<bitvector_type>() - 1);
for(auto& w: work){
w.reset();
}
work.back().VP = VP0;
distance_type D = pattern_length;
for(auto c: text){
const auto& PMc = findValue(PM, c, zeroes);
for(size_type r = 0; r < block_size; ++r){
auto& w = work[r];
auto X = PMc[r];
if(r > 0 && (work[r - 1].HN & msb)){
X |= 1;
}
w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;
w.HP = w.VN | ~(w.VP | w.D0);
w.HN = w.VP & w.D0;
X = w.HP << 1;
if(r == 0 || work[r - 1].HP & msb){
X |= 1;
}
w.VP = (w.HN << 1) | ~(X | w.D0);
if(r > 0 && (work[r - 1].HN & msb)){
w.VP |= 1;
}
w.VN = X & w.D0;
}
if(work.back().HP & sink){
++D;
}
else if(work.back().HN & sink){
--D;
}
}
return D;
}
distance_type distance(string_type const &text)
{
if(text.empty()){
return pattern_length;
}
else if(pattern_length == 0){
return text.size();
}
if(block_size == 1){
return distance_sp(text);
}
else{
return distance_lp(text);
}
}
};
}
#endif
<commit_msg>add include headers<commit_after>/*
Resembla: Word-based Japanese similar sentence search library
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
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.
*/
#ifndef RESEMBLA_ELIMINATOR_HPP
#define RESEMBLA_ELIMINATOR_HPP
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <iostream>
#include "string_util.hpp"
namespace resembla {
template<typename string_type, typename bitvector_type = uint64_t>
struct Eliminator
{
using size_type = typename string_type::size_type;
using symbol_type = typename string_type::value_type;
using distance_type = int;
Eliminator(string_type const& pattern = string_type())
{
init(pattern);
}
void init(string_type const& pattern)
{
this->pattern = pattern;
if(pattern.empty()){
return;
}
pattern_length = pattern.size();
block_size = ((pattern_length - 1) >> bitOffset<bitvector_type>()) + 1;
rest_bits = pattern_length - (block_size - 1) * bitWidth<bitvector_type>();
sink = bitvector_type{1} << (rest_bits - 1);
constructPM();
zeroes.resize(block_size, 0);
work.resize(block_size);
VP0 = 0;
for(size_type i = 0; i < rest_bits; ++i){
VP0 |= bitvector_type{1} << i;
}
}
void operator()(std::vector<string_type>& candidates, size_type k, bool keep_tie = true)
{
using index_distance = std::pair<size_type, distance_type>;
// calculate scores
std::vector<index_distance> work(candidates.size());
for(size_type i = 0; i < work.size(); ++i){
work[i].first = i;
work[i].second = -distance(candidates[i]);
}
if(keep_tie){
// sort partially to obtain top-k elements
std::nth_element(std::begin(work), std::begin(work) + k, std::end(work),
[](const index_distance& a, const index_distance& b) -> bool{
return a.second > b.second;
});
}
else{
std::sort(std::begin(work), std::end(work),
[](const index_distance& a, const index_distance& b) -> bool{
return a.second > b.second;
});
// expand k so that work[l] < work[k] for all l > k
while(k < work.size() - 1 && work[k] == work[k + 1]){
++k;
}
}
// ensure that work[i].first < work[j].first if i < j < k
std::sort(std::begin(work), std::begin(work) + k,
[](const index_distance& a, const index_distance& b) -> bool{
return a.first < b.first;
});
#ifdef DEBUG
std::cerr << "narrow " << work.size() << " strings" << std::endl;
for(size_type i = 0; i < k; ++i){
std::cerr << cast_string<std::string>(candidates[work[i].first]) << ": " << work[i].second << std::endl;
}
#endif
// sort original list
for(size_type i = 0; i < k; ++i){
std::swap(candidates[i], candidates[work[i].first]);
}
candidates.erase(std::begin(candidates) + k, std::end(candidates));
}
protected:
string_type pattern;
size_type pattern_length;
symbol_type c_min, c_max;
size_type block_size;
size_type rest_bits;
bitvector_type sink;
std::vector<std::pair<symbol_type, std::vector<bitvector_type>>> PM;
std::vector<bitvector_type> zeroes;
struct WorkData
{
bitvector_type D0;
bitvector_type HP;
bitvector_type HN;
bitvector_type VP;
bitvector_type VN;
void reset()
{
D0 = HP = HN = VN = 0;
VP = ~(bitvector_type{0});
}
};
std::vector<WorkData> work;
bitvector_type VP0;
template<typename Integer> static constexpr int bitWidth()
{
return 8 * sizeof(Integer);
}
static constexpr int bitOffset(int w)
{
return w < 2 ? 0 : (bitOffset(w >> 1) + 1);
}
template<typename Integer> static constexpr int bitOffset()
{
return bitOffset(bitWidth<Integer>());
}
template<typename key_type, typename value_type>
const value_type& findValue(const std::vector<std::pair<key_type, value_type>>& data,
const key_type c, const value_type& default_value) const
{
if(c < c_min || c_max < c){
return default_value;
}
else if(c == c_min){
return PM.front().second;
}
else if(c == c_max){
return PM.back().second;
}
size_type l = 1, r = data.size() - 1;
while(r - l > 8){
auto i = (l + r) / 2;
if(data[i].first < c){
l = i + 1;
}
else if(data[i].first > c){
r = i;
}
else{
return data[i].second;
}
}
for(size_type i = l; i < r; ++i){
if(data[i].first == c){
return data[i].second;
}
}
return default_value;
}
void constructPM()
{
std::map<symbol_type, std::vector<bitvector_type>> PM_work;
for(size_type i = 0; i < block_size - 1; ++i){
for(size_type j = 0; j < bitWidth<bitvector_type>(); ++j){
if(PM_work[pattern[i * bitWidth<bitvector_type>() + j]].empty()){
PM_work[pattern[i * bitWidth<bitvector_type>() + j]].resize(block_size, 0);
}
PM_work[pattern[i * bitWidth<bitvector_type>() + j]][i] |= bitvector_type{1} << j;
}
}
for(size_type i = 0; i < rest_bits; ++i){
if(PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].empty()){
PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].resize(block_size, 0);
}
PM_work[pattern[(block_size - 1) * bitWidth<bitvector_type>() + i]].back() |= bitvector_type{1} << i;
}
PM.resize(PM_work.size());
std::copy(PM_work.begin(), PM_work.end(), PM.begin());
c_min = PM.front().first;
c_max = PM.back().first;
}
distance_type distance_sp(string_type const &text)
{
auto& w = work.front();
w.reset();
w.VP = VP0;
distance_type D = pattern_length;
for(auto c: text){
auto X = findValue(PM, c, zeroes).front() | w.VN;
w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X;
w.HP = w.VN | ~(w.VP | w.D0);
w.HN = w.VP & w.D0;
X = (w.HP << 1) | 1;
w.VP = (w.HN << 1) | ~(X | w.D0);
w.VN = X & w.D0;
if(w.HP & sink){
++D;
}
else if(w.HN & sink){
--D;
}
}
return D;
}
distance_type distance_lp(string_type const &text)
{
constexpr bitvector_type msb = bitvector_type{1} << (bitWidth<bitvector_type>() - 1);
for(auto& w: work){
w.reset();
}
work.back().VP = VP0;
distance_type D = pattern_length;
for(auto c: text){
const auto& PMc = findValue(PM, c, zeroes);
for(size_type r = 0; r < block_size; ++r){
auto& w = work[r];
auto X = PMc[r];
if(r > 0 && (work[r - 1].HN & msb)){
X |= 1;
}
w.D0 = ((w.VP + (X & w.VP)) ^ w.VP) | X | w.VN;
w.HP = w.VN | ~(w.VP | w.D0);
w.HN = w.VP & w.D0;
X = w.HP << 1;
if(r == 0 || work[r - 1].HP & msb){
X |= 1;
}
w.VP = (w.HN << 1) | ~(X | w.D0);
if(r > 0 && (work[r - 1].HN & msb)){
w.VP |= 1;
}
w.VN = X & w.D0;
}
if(work.back().HP & sink){
++D;
}
else if(work.back().HN & sink){
--D;
}
}
return D;
}
distance_type distance(string_type const &text)
{
if(text.empty()){
return pattern_length;
}
else if(pattern_length == 0){
return text.size();
}
if(block_size == 1){
return distance_sp(text);
}
else{
return distance_lp(text);
}
}
};
}
#endif
<|endoftext|> |
<commit_before>/*
* libeinit++.c++
* einit
*
* Created by Magnus Deininger on 01/08/2007.
* Copyright 2006, 2007 Magnus Deininger. All rights reserved.
*
*/
/*
Copyright (c) 2007, Magnus Deininger
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 project nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <einit/einit++.h>
#include <map>
using std::pair;
/* our primary einit class */
Einit::Einit() {
this->listening = false;
this->servicesRaw = NULL;
this->modulesRaw = NULL;
this->modesRaw = NULL;
einit_connect();
}
Einit::~Einit() {
einit_disconnect();
}
void Einit::listen (enum einit_event_subsystems type, void (* handler)(struct einit_remote_event *)) {
if (!this->listening) {
einit_receive_events();
this->listening = true;
}
einit_remote_event_listen (type, handler);
}
void Einit::ignore (enum einit_event_subsystems type, void (* handler)(struct einit_remote_event *)) {
einit_remote_event_ignore (type, handler);
}
EinitService *Einit::getService (string s) {
map<string, EinitService *>::iterator it = this->services.find (s);
if (it != this->services.end()) {
return it->second;
} else {
if (!this->servicesRaw) {
this->servicesRaw = einit_get_all_services();
} if (!this->servicesRaw)
return NULL;
struct stree *res = streefind (this->servicesRaw, s.c_str(), tree_find_first);
if (res) {
struct einit_service *s = (struct einit_service *)res->value;
EinitService *r = new EinitService (this, s);
return r;
} else {
return NULL;
}
}
}
EinitModule *Einit::getModule (string s) {
map<string, EinitModule *>::iterator it = this->modules.find (s);
if (it != this->modules.end()) {
return it->second;
} else {
if (!this->modulesRaw) {
this->modulesRaw = einit_get_all_modules();
} if (!this->modulesRaw)
return NULL;
struct stree *res = streefind (this->modulesRaw, s.c_str(), tree_find_first);
if (res) {
struct einit_module *s = (struct einit_module *)res->value;
EinitModule *r = new EinitModule (this, s);
return r;
} else {
return NULL;
}
}
}
EinitMode *Einit::getMode (string s) {
map<string, EinitMode *>::iterator it = this->modes.find (s);
if (it != this->modes.end()) {
return it->second;
} else {
if (!this->modesRaw) {
this->modesRaw = einit_get_all_modes();
} if (!this->modesRaw)
return NULL;
struct stree *res = streefind (this->modesRaw, s.c_str(), tree_find_first);
if (res) {
struct einit_mode_summary *s = (struct einit_mode_summary *)res->value;
EinitMode *r = new EinitMode (this, s);
return r;
} else {
return NULL;
}
}
}
map<string, EinitModule *> Einit::getAllModules() {
if (!this->modulesRaw) {
this->modulesRaw = einit_get_all_modules();
}
struct stree *cur = this->modulesRaw;
while (cur) {
this->getModule(cur->key);
cur = streenext (cur);
}
return this->modules;
}
map<string, EinitService *> Einit::getAllServices() {
if (!this->servicesRaw) {
this->servicesRaw = einit_get_all_services();
}
struct stree *cur = this->servicesRaw;
while (cur) {
this->getService(cur->key);
cur = streenext (cur);
}
return this->services;
}
map<string, EinitMode *> Einit::getAllModes() {
if (!this->modesRaw) {
this->modesRaw = einit_get_all_modes();
}
struct stree *cur = this->modesRaw;
while (cur) {
this->getMode(cur->key);
cur = streenext (cur);
}
return this->modes;
}
bool Einit::powerDown() {
einit_power_down();
return true;
}
bool Einit::powerReset() {
einit_power_reset();
return true;
}
void Einit::update() {
if (this->servicesRaw) {
struct stree *services = einit_get_all_services();
struct stree *cur = services;
while (cur) {
map<string, EinitService *>::iterator it = this->services.find ((string)cur->key);
if (it != this->services.end()) {
it->second->update ((struct einit_service *)cur->value);
}
cur = streenext (cur);
}
servicestree_free (this->servicesRaw);
this->servicesRaw = services;
}
if (this->modulesRaw) {
struct stree *modules = einit_get_all_modules();
struct stree *cur = modules;
while (cur) {
map<string, EinitModule *>::iterator it = this->modules.find ((string)cur->key);
if (it != this->modules.end()) {
it->second->update ((struct einit_module *)cur->value);
}
cur = streenext (cur);
}
modulestree_free (this->modulesRaw);
this->modulesRaw = modules;
}
if (this->modesRaw) {
struct stree *modes = einit_get_all_modes();
struct stree *cur = modes;
while (cur) {
map<string, EinitMode *>::iterator it = this->modes.find ((string)cur->key);
if (it != this->modes.end()) {
it->second->update ((struct einit_mode_summary *)cur->value);
}
cur = streenext (cur);
}
modestree_free (this->modesRaw);
this->modesRaw = modes;
}
}
/* generic offspring */
EinitOffspring::EinitOffspring (Einit *e) {
this->main = e;
}
EinitOffspring::~EinitOffspring () {
}
/* services */
EinitService::EinitService (Einit *e, struct einit_service *t) : EinitOffspring (e) {
this->update (t);
}
EinitService::~EinitService () {
}
bool EinitService::enable() {
einit_service_enable (this->id.c_str());
return true;
}
bool EinitService::disable() {
einit_service_disable (this->id.c_str());
return true;
}
bool EinitService::call(string s) {
einit_service_call (this->id.c_str(), s.c_str());
return true;
}
vector<string> EinitService::getCommonFunctions() {
vector<string> rv;
return rv;
}
vector<string> EinitService::getAllFunctions() {
vector<string> rv;
return rv;
}
bool EinitService::update(struct einit_service *s) {
this->id = s->name;
this->provided = (s->status & service_provided) ? true : false;
if (s->group && s->group->seq && s->group->services) {
uint32_t i = 0;
this->groupType = s->group->seq;
for (; s->group->services[i]; i++) {
EinitService *sp = this->main->getService (s->group->services[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->group.find (s->group->services[i]);
if (it != this->group.end()) {
this->group.erase (it);
}
this->group.insert(pair<string, EinitService *>(s->group->services[i], sp));
}
}
}
if (s->modules) {
struct stree *cur = s->modules;
while (cur) {
EinitModule *sp = this->main->getModule (cur->key);
if (sp) {
map<string, EinitModule *>::iterator it = this->modules.find (cur->key);
if (it != this->modules.end()) {
this->modules.erase (it);
}
this->modules.insert(pair<string, EinitModule *>(cur->key, sp));
}
cur = streenext (cur);
}
}
if (s->used_in_mode) {
uint32_t i = 0;
for (; s->used_in_mode[i]; i++) {
EinitMode *sp = this->main->getMode (s->used_in_mode[i]);
if (sp) {
map<string, EinitMode *>::iterator it = this->modes.find (s->used_in_mode[i]);
if (it != this->modes.end()) {
this->modes.erase (it);
}
this->modes.insert(pair<string, EinitMode *>(s->used_in_mode[i], sp));
}
}
}
return true;
}
/* modules */
EinitModule::EinitModule (Einit *e, struct einit_module *t) : EinitOffspring (e) {
this->update (t);
}
EinitModule::~EinitModule () {
}
bool EinitModule::enable() {
einit_module_id_enable (this->id.c_str());
return true;
}
bool EinitModule::disable() {
einit_module_id_disable (this->id.c_str());
return true;
}
bool EinitModule::call(string s) {
einit_module_id_call (this->id.c_str(), s.c_str());
return true;
}
bool EinitModule::update(struct einit_module *s) {
this->id = s->id;
this->name = s->name ? s->name : "unknown";
this->enabled = (s->status & status_enabled) ? true : false;
this->idle = (s->status == status_idle) ? true : false;
this->error = (s->status & status_failed) ? true : false;
if (s->requires) {
uint32_t i = 0;
for (; s->requires[i]; i++) {
EinitService *sp = this->main->getService (s->requires[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->requires.find (s->requires[i]);
if (it != this->requires.end()) {
this->requires.erase (it);
}
this->requires.insert(pair<string, EinitService *>(s->requires[i], sp));
}
}
}
if (s->provides) {
uint32_t i = 0;
for (; s->provides[i]; i++) {
EinitService *sp = this->main->getService (s->provides[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->provides.find (s->provides[i]);
if (it != this->provides.end()) {
this->provides.erase (it);
}
this->provides.insert(pair<string, EinitService *>(s->provides[i], sp));
}
}
}
this->after = s->after ? (char **)setdup ((const void **)s->after, SET_TYPE_STRING) : NULL;
this->before = s->before ? (char **)setdup ((const void **)s->before, SET_TYPE_STRING) : NULL;
this->functions = s->functions ? (char **)setdup ((const void **)s->functions, SET_TYPE_STRING) : NULL;
return true;
}
/* modes */
EinitMode::EinitMode (Einit *e, struct einit_mode_summary *t) : EinitOffspring (e) {
this->update (t);
}
EinitMode::~EinitMode () {
}
bool EinitMode::switchTo() {
einit_switch_mode (this->id.c_str());
return true;
}
bool EinitMode::update(struct einit_mode_summary *s) {
this->id = s->id;
if (s->services) {
uint32_t i = 0;
for (; s->services[i]; i++) {
EinitService *sp = this->main->getService (s->services[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->services.find (s->services[i]);
if (it != this->services.end()) {
this->services.erase (it);
}
this->services.insert(pair<string, EinitService *>(s->services[i], sp));
}
}
}
if (s->critical) {
uint32_t i = 0;
for (; s->critical[i]; i++) {
EinitService *sp = this->main->getService (s->critical[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->critical.find (s->critical[i]);
if (it != this->critical.end()) {
this->critical.erase (it);
}
this->critical.insert(pair<string, EinitService *>(s->critical[i], sp));
}
}
}
if (s->disable) {
uint32_t i = 0;
for (; s->disable[i]; i++) {
EinitService *sp = this->main->getService (s->disable[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->disable.find (s->disable[i]);
if (it != this->disable.end()) {
this->disable.erase (it);
}
this->disable.insert(pair<string, EinitService *>(s->disable[i], sp));
}
}
}
if (s->base) {
uint32_t i = 0;
for (; s->base[i]; i++) {
EinitMode *sp = this->main->getMode (s->base[i]);
if (sp) {
map<string, EinitMode *>::iterator it = this->base.find (s->base[i]);
if (it != this->base.end()) {
this->base.erase (it);
}
this->base.insert(pair<string, EinitMode *>(s->base[i], sp));
}
}
}
return true;
}
<commit_msg>getAllFunctions() should work... getCommonFunctions() not yet, but that shouldn't be too tragic<commit_after>/*
* libeinit++.c++
* einit
*
* Created by Magnus Deininger on 01/08/2007.
* Copyright 2006, 2007 Magnus Deininger. All rights reserved.
*
*/
/*
Copyright (c) 2007, Magnus Deininger
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 project nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <einit/einit++.h>
#include <map>
using std::pair;
/* our primary einit class */
Einit::Einit() {
this->listening = false;
this->servicesRaw = NULL;
this->modulesRaw = NULL;
this->modesRaw = NULL;
einit_connect();
}
Einit::~Einit() {
einit_disconnect();
}
void Einit::listen (enum einit_event_subsystems type, void (* handler)(struct einit_remote_event *)) {
if (!this->listening) {
einit_receive_events();
this->listening = true;
}
einit_remote_event_listen (type, handler);
}
void Einit::ignore (enum einit_event_subsystems type, void (* handler)(struct einit_remote_event *)) {
einit_remote_event_ignore (type, handler);
}
EinitService *Einit::getService (string s) {
map<string, EinitService *>::iterator it = this->services.find (s);
if (it != this->services.end()) {
return it->second;
} else {
if (!this->servicesRaw) {
this->servicesRaw = einit_get_all_services();
} if (!this->servicesRaw)
return NULL;
struct stree *res = streefind (this->servicesRaw, s.c_str(), tree_find_first);
if (res) {
struct einit_service *s = (struct einit_service *)res->value;
EinitService *r = new EinitService (this, s);
return r;
} else {
return NULL;
}
}
}
EinitModule *Einit::getModule (string s) {
map<string, EinitModule *>::iterator it = this->modules.find (s);
if (it != this->modules.end()) {
return it->second;
} else {
if (!this->modulesRaw) {
this->modulesRaw = einit_get_all_modules();
} if (!this->modulesRaw)
return NULL;
struct stree *res = streefind (this->modulesRaw, s.c_str(), tree_find_first);
if (res) {
struct einit_module *s = (struct einit_module *)res->value;
EinitModule *r = new EinitModule (this, s);
return r;
} else {
return NULL;
}
}
}
EinitMode *Einit::getMode (string s) {
map<string, EinitMode *>::iterator it = this->modes.find (s);
if (it != this->modes.end()) {
return it->second;
} else {
if (!this->modesRaw) {
this->modesRaw = einit_get_all_modes();
} if (!this->modesRaw)
return NULL;
struct stree *res = streefind (this->modesRaw, s.c_str(), tree_find_first);
if (res) {
struct einit_mode_summary *s = (struct einit_mode_summary *)res->value;
EinitMode *r = new EinitMode (this, s);
return r;
} else {
return NULL;
}
}
}
map<string, EinitModule *> Einit::getAllModules() {
if (!this->modulesRaw) {
this->modulesRaw = einit_get_all_modules();
}
struct stree *cur = this->modulesRaw;
while (cur) {
this->getModule(cur->key);
cur = streenext (cur);
}
return this->modules;
}
map<string, EinitService *> Einit::getAllServices() {
if (!this->servicesRaw) {
this->servicesRaw = einit_get_all_services();
}
struct stree *cur = this->servicesRaw;
while (cur) {
this->getService(cur->key);
cur = streenext (cur);
}
return this->services;
}
map<string, EinitMode *> Einit::getAllModes() {
if (!this->modesRaw) {
this->modesRaw = einit_get_all_modes();
}
struct stree *cur = this->modesRaw;
while (cur) {
this->getMode(cur->key);
cur = streenext (cur);
}
return this->modes;
}
bool Einit::powerDown() {
einit_power_down();
return true;
}
bool Einit::powerReset() {
einit_power_reset();
return true;
}
void Einit::update() {
if (this->servicesRaw) {
struct stree *services = einit_get_all_services();
struct stree *cur = services;
while (cur) {
map<string, EinitService *>::iterator it = this->services.find ((string)cur->key);
if (it != this->services.end()) {
it->second->update ((struct einit_service *)cur->value);
}
cur = streenext (cur);
}
servicestree_free (this->servicesRaw);
this->servicesRaw = services;
}
if (this->modulesRaw) {
struct stree *modules = einit_get_all_modules();
struct stree *cur = modules;
while (cur) {
map<string, EinitModule *>::iterator it = this->modules.find ((string)cur->key);
if (it != this->modules.end()) {
it->second->update ((struct einit_module *)cur->value);
}
cur = streenext (cur);
}
modulestree_free (this->modulesRaw);
this->modulesRaw = modules;
}
if (this->modesRaw) {
struct stree *modes = einit_get_all_modes();
struct stree *cur = modes;
while (cur) {
map<string, EinitMode *>::iterator it = this->modes.find ((string)cur->key);
if (it != this->modes.end()) {
it->second->update ((struct einit_mode_summary *)cur->value);
}
cur = streenext (cur);
}
modestree_free (this->modesRaw);
this->modesRaw = modes;
}
}
/* generic offspring */
EinitOffspring::EinitOffspring (Einit *e) {
this->main = e;
}
EinitOffspring::~EinitOffspring () {
}
/* services */
EinitService::EinitService (Einit *e, struct einit_service *t) : EinitOffspring (e) {
this->update (t);
}
EinitService::~EinitService () {
}
bool EinitService::enable() {
einit_service_enable (this->id.c_str());
return true;
}
bool EinitService::disable() {
einit_service_disable (this->id.c_str());
return true;
}
bool EinitService::call(string s) {
einit_service_call (this->id.c_str(), s.c_str());
return true;
}
vector<string> EinitService::getCommonFunctions() {
vector<string> rv = this->getAllFunctions();
return rv;
}
vector<string> EinitService::getAllFunctions() {
vector<string> rv;
map<string,EinitModule *>::iterator it;
for ( it=this->modules.begin() ; it != this->modules.end(); it++ ) {
if (it->second->functions) {
uint32_t i = 0;
for ( ; it->second->functions[i]; i++ ) {
bool have = false;
string toadd = it->second->functions[i];
for (i=0; i<rv.size(); i++) if (rv.at(i) == toadd) have = true;
if (!have) {
rv.push_back (toadd);
}
}
}
}
return rv;
}
bool EinitService::update(struct einit_service *s) {
this->id = s->name;
this->provided = (s->status & service_provided) ? true : false;
if (s->group && s->group->seq && s->group->services) {
uint32_t i = 0;
this->groupType = s->group->seq;
for (; s->group->services[i]; i++) {
EinitService *sp = this->main->getService (s->group->services[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->group.find (s->group->services[i]);
if (it != this->group.end()) {
this->group.erase (it);
}
this->group.insert(pair<string, EinitService *>(s->group->services[i], sp));
}
}
}
if (s->modules) {
struct stree *cur = s->modules;
while (cur) {
EinitModule *sp = this->main->getModule (cur->key);
if (sp) {
map<string, EinitModule *>::iterator it = this->modules.find (cur->key);
if (it != this->modules.end()) {
this->modules.erase (it);
}
this->modules.insert(pair<string, EinitModule *>(cur->key, sp));
}
cur = streenext (cur);
}
}
if (s->used_in_mode) {
uint32_t i = 0;
for (; s->used_in_mode[i]; i++) {
EinitMode *sp = this->main->getMode (s->used_in_mode[i]);
if (sp) {
map<string, EinitMode *>::iterator it = this->modes.find (s->used_in_mode[i]);
if (it != this->modes.end()) {
this->modes.erase (it);
}
this->modes.insert(pair<string, EinitMode *>(s->used_in_mode[i], sp));
}
}
}
return true;
}
/* modules */
EinitModule::EinitModule (Einit *e, struct einit_module *t) : EinitOffspring (e) {
this->update (t);
}
EinitModule::~EinitModule () {
}
bool EinitModule::enable() {
einit_module_id_enable (this->id.c_str());
return true;
}
bool EinitModule::disable() {
einit_module_id_disable (this->id.c_str());
return true;
}
bool EinitModule::call(string s) {
einit_module_id_call (this->id.c_str(), s.c_str());
return true;
}
bool EinitModule::update(struct einit_module *s) {
this->id = s->id;
this->name = s->name ? s->name : "unknown";
this->enabled = (s->status & status_enabled) ? true : false;
this->idle = (s->status == status_idle) ? true : false;
this->error = (s->status & status_failed) ? true : false;
if (s->requires) {
uint32_t i = 0;
for (; s->requires[i]; i++) {
EinitService *sp = this->main->getService (s->requires[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->requires.find (s->requires[i]);
if (it != this->requires.end()) {
this->requires.erase (it);
}
this->requires.insert(pair<string, EinitService *>(s->requires[i], sp));
}
}
}
if (s->provides) {
uint32_t i = 0;
for (; s->provides[i]; i++) {
EinitService *sp = this->main->getService (s->provides[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->provides.find (s->provides[i]);
if (it != this->provides.end()) {
this->provides.erase (it);
}
this->provides.insert(pair<string, EinitService *>(s->provides[i], sp));
}
}
}
this->after = s->after ? (char **)setdup ((const void **)s->after, SET_TYPE_STRING) : NULL;
this->before = s->before ? (char **)setdup ((const void **)s->before, SET_TYPE_STRING) : NULL;
this->functions = s->functions ? (char **)setdup ((const void **)s->functions, SET_TYPE_STRING) : NULL;
return true;
}
/* modes */
EinitMode::EinitMode (Einit *e, struct einit_mode_summary *t) : EinitOffspring (e) {
this->update (t);
}
EinitMode::~EinitMode () {
}
bool EinitMode::switchTo() {
einit_switch_mode (this->id.c_str());
return true;
}
bool EinitMode::update(struct einit_mode_summary *s) {
this->id = s->id;
if (s->services) {
uint32_t i = 0;
for (; s->services[i]; i++) {
EinitService *sp = this->main->getService (s->services[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->services.find (s->services[i]);
if (it != this->services.end()) {
this->services.erase (it);
}
this->services.insert(pair<string, EinitService *>(s->services[i], sp));
}
}
}
if (s->critical) {
uint32_t i = 0;
for (; s->critical[i]; i++) {
EinitService *sp = this->main->getService (s->critical[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->critical.find (s->critical[i]);
if (it != this->critical.end()) {
this->critical.erase (it);
}
this->critical.insert(pair<string, EinitService *>(s->critical[i], sp));
}
}
}
if (s->disable) {
uint32_t i = 0;
for (; s->disable[i]; i++) {
EinitService *sp = this->main->getService (s->disable[i]);
if (sp) {
map<string, EinitService *>::iterator it = this->disable.find (s->disable[i]);
if (it != this->disable.end()) {
this->disable.erase (it);
}
this->disable.insert(pair<string, EinitService *>(s->disable[i], sp));
}
}
}
if (s->base) {
uint32_t i = 0;
for (; s->base[i]; i++) {
EinitMode *sp = this->main->getMode (s->base[i]);
if (sp) {
map<string, EinitMode *>::iterator it = this->base.find (s->base[i]);
if (it != this->base.end()) {
this->base.erase (it);
}
this->base.insert(pair<string, EinitMode *>(s->base[i], sp));
}
}
}
return true;
}
<|endoftext|> |
<commit_before>// @(#)root/proofx:$Id$
// Author: Gerardo Ganis Apr 2008
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TProofMgrLite //
// //
// Basic functionality implementtaion in the case of Lite sessions //
// //
//////////////////////////////////////////////////////////////////////////
#include <errno.h>
#ifdef WIN32
#include <io.h>
#endif
#include "TProofMgrLite.h"
#include "Riostream.h"
#include "TEnv.h"
#include "TError.h"
#include "TObjString.h"
#include "TProofLite.h"
#include "TProofLog.h"
#include "TROOT.h"
#include "TRegexp.h"
#include "TSortedList.h"
ClassImp(TProofMgrLite)
//______________________________________________________________________________
TProofMgrLite::TProofMgrLite(const char *url, Int_t dbg, const char *alias)
: TProofMgr(url, dbg, alias)
{
// Create a PROOF manager for the Lite environment.
// Set the correct servert type
fServType = kProofLite;
}
//______________________________________________________________________________
TProof *TProofMgrLite::CreateSession(const char *cfg,
const char *, Int_t loglevel)
{
// Create a new session
Int_t nwrk = TProofLite::GetNumberOfWorkers(fUrl.GetOptions());
if (nwrk == 0) return (TProof *)0;
// Check if we have already a running session
if (gProof && gProof->IsValid() && gProof->IsLite()) {
if (nwrk > 0 && gProof->GetParallel() != nwrk) {
delete gProof;
gProof = 0;
} else {
// We have already a running session
return gProof;
}
}
// Create the instance
TString u = (strlen(fUrl.GetOptions()) > 0) ? Form("lite/?%s", fUrl.GetOptions())
: "lite";
TProof *p = new TProofLite(u, cfg, 0, loglevel, 0, this);
if (p && p->IsValid()) {
// Save record about this session
Int_t ns = 1;
if (fSessions) {
// To avoid ambiguities in case of removal of some elements
if (fSessions->Last())
ns = ((TProofDesc *)(fSessions->Last()))->GetLocalId() + 1;
} else {
// Create the list
fSessions = new TList;
}
// Create the description class
Int_t st = (p->IsIdle()) ? TProofDesc::kIdle : TProofDesc::kRunning ;
TProofDesc *d =
new TProofDesc(p->GetName(), p->GetTitle(), p->GetUrl(),
ns, p->GetSessionID(), st, p);
fSessions->Add(d);
} else {
// Session creation failed
Error("CreateSession", "creating PROOF session");
SafeDelete(p);
}
// We are done
return p;
}
//_____________________________________________________________________________
TProofLog *TProofMgrLite::GetSessionLogs(Int_t isess,
const char *stag, const char *pattern)
{
// Get logs or log tails from last session associated with this manager
// instance.
// The arguments allow to specify a session different from the last one:
// isess specifies a position relative to the last one, i.e. 1
// for the next to last session; the absolute value is taken
// so -1 and 1 are equivalent.
// stag specifies the unique tag of the wanted session
// The special value stag = "NR" allows to just initialize the TProofLog
// object w/o retrieving the files; this may be useful when the number
// of workers is large and only a subset of logs is required.
// If 'stag' is specified 'isess' is ignored (unless stag = "NR").
// If 'pattern' is specified only the lines containing it are retrieved
// (remote grep functionality); to filter out a pattern 'pat' use
// pattern = "-v pat".
// Returns a TProofLog object (to be deleted by the caller) on success,
// 0 if something wrong happened.
TProofLog *pl = 0;
// The absolute value of isess counts
isess = (isess < 0) ? -isess : isess;
// Special option in stag
bool retrieve = 1;
TString tag(stag);
if (tag == "NR") {
retrieve = 0;
tag = "";
}
// The working dir
TString sandbox(gSystem->WorkingDirectory());
sandbox.ReplaceAll(gSystem->HomeDirectory(),"");
sandbox.ReplaceAll("/","-");
sandbox.Replace(0,1,"/",1);
if (strlen(gEnv->GetValue("Proof.Sandbox", "")) > 0) {
sandbox.Insert(0, gEnv->GetValue("Proof.Sandbox", ""));
} else {
TString sb;
sb.Form("~/%s", kPROOF_WorkDir);
sandbox.Insert(0, sb.Data());
}
gSystem->ExpandPathName(sandbox);
TString sessiondir;
if (tag.Length() > 0) {
sessiondir.Form("%s/session-%s", sandbox.Data(), tag.Data());
if (gSystem->AccessPathName(sessiondir, kReadPermission)) {
Error("GetSessionLogs", "information for session '%s' not available", tag.Data());
return (TProofLog *)0;
}
} else {
// Get the list of available dirs
TSortedList *olddirs = new TSortedList(kFALSE);
void *dirp = gSystem->OpenDirectory(sandbox);
if (dirp) {
const char *e = 0;
while ((e = gSystem->GetDirEntry(dirp))) {
if (!strncmp(e, "session-", 8)) {
TString d(e);
Int_t i = d.Last('-');
if (i != kNPOS) d.Remove(i);
i = d.Last('-');
if (i != kNPOS) d.Remove(0,i+1);
TString path = Form("%s/%s", sandbox.Data(), e);
olddirs->Add(new TNamed(d, path));
}
}
gSystem->FreeDirectory(dirp);
}
// Check isess
if (isess > olddirs->GetSize() - 1) {
Warning("GetSessionLogs",
"session index out of range (%d): take oldest available session", isess);
isess = olddirs->GetSize() - 1;
}
// Locate the session dir
TNamed *n = (TNamed *) olddirs->First();
while (isess-- > 0) {
olddirs->Remove(n);
delete n;
n = (TNamed *) olddirs->First();
}
sessiondir = n->GetTitle();
tag = gSystem->BaseName(sessiondir);
tag.ReplaceAll("session-", "");
// Cleanup
olddirs->SetOwner();
delete olddirs;
}
Info("GetSessionLogs", "analysing session dir %s", sessiondir.Data());
// Create the instance now
pl = new TProofLog(tag, "", this);
void *dirp = gSystem->OpenDirectory(sessiondir);
if (dirp) {
TSortedList *logs = new TSortedList;
const char *e = 0;
while ((e = gSystem->GetDirEntry(dirp))) {
TString fn(e);
if (fn.EndsWith(".log") && fn.CountChar('-') > 0) {
TString ord, url;
if (fn.BeginsWith("session-")) {
ord = "-1";
} else if (fn.BeginsWith("worker-")) {
ord = fn;
ord.ReplaceAll("worker-", "");
Int_t id = ord.First('-');
if (id != kNPOS) {
ord.Remove(id);
} else if (ord.Contains(".valgrind")) {
// Add to the list (special tag for valgrind outputs)
ord.ReplaceAll(".valgrind.log","-valgrind");
} else {
// Not a good path
ord = "";
}
if (!ord.IsNull()) ord.ReplaceAll("0.", "");
}
if (!ord.IsNull()) {
url = Form("%s/%s", sessiondir.Data(), e);
// Add to the list
logs->Add(new TNamed(ord, url));
// Notify
if (gDebug > 1)
Info("GetSessionLogs", "ord: %s, url: %s", ord.Data(), url.Data());
}
}
}
gSystem->FreeDirectory(dirp);
TIter nxl(logs);
TNamed *n = 0;
while ((n = (TNamed *) nxl())) {
TString ord = Form("0.%s", n->GetName());
if (ord == "0.-1") ord = "0";
// Add to the list
pl->Add(ord, n->GetTitle());
}
// Cleanup
logs->SetOwner();
delete logs;
}
// Retrieve the default part
if (pl && retrieve) {
if (pattern && strlen(pattern) > 0)
pl->Retrieve("*", TProofLog::kGrep, 0, pattern);
else
pl->Retrieve();
}
// Done
return pl;
}
//______________________________________________________________________________
TObjString *TProofMgrLite::ReadBuffer(const char *fin, Long64_t ofs, Int_t len)
{
// Read 'len' bytes from offset 'ofs' of the local file 'fin'.
// Returns a TObjString with the content or 0, in case of failure
if (!fin || strlen(fin) <= 0) {
Error("ReadBuffer", "undefined path!");
return (TObjString *)0;
}
// Open the file
TString fn = TUrl(fin).GetFile();
Int_t fd = open(fn.Data(), O_RDONLY);
if (fd < 0) {
Error("ReadBuffer", "problems opening file %s", fn.Data());
return (TObjString *)0;
}
// Total size
off_t start = 0, end = lseek(fd, (off_t) 0, SEEK_END);
// Set the offset
if (ofs > 0 && ofs < end) {
start = lseek(fd, (off_t) ofs, SEEK_SET);
} else {
start = lseek(fd, (off_t) 0, SEEK_SET);
}
if (len > (end - start + 1) || len <= 0)
len = end - start + 1;
TString outbuf;
const Int_t kMAXBUF = 32768;
char buf[kMAXBUF];
Int_t left = len;
Int_t wanted = (left > kMAXBUF - 1) ? kMAXBUF - 1 : left;
do {
while ((len = read(fd, buf, wanted)) < 0 && TSystem::GetErrno() == EINTR)
TSystem::ResetErrno();
if (len < 0) {
Error("ReadBuffer", "error reading file %s", fn.Data());
close(fd);
return (TObjString *)0;
} else if (len > 0) {
if (len == wanted)
buf[len-1] = '\n';
buf[len] = '\0';
outbuf += buf;
}
// Update counters
left -= len;
wanted = (left > kMAXBUF - 1) ? kMAXBUF - 1 : left;
} while (len > 0 && left > 0);
// Done
return new TObjString(outbuf.Data());
}
//______________________________________________________________________________
TObjString *TProofMgrLite::ReadBuffer(const char *fin, const char *pattern)
{
// Read lines containing 'pattern' in 'file'.
// Returns a TObjString with the content or 0, in case of failure
// If no pattern, read everything
if (!pattern || strlen(pattern) <= 0)
return (TObjString *)0;
if (!fin || strlen(fin) <= 0) {
Error("ReadBuffer", "undefined path!");
return (TObjString *)0;
}
TString fn = TUrl(fin).GetFile();
TString pat(pattern);
// Check if "-v"
Bool_t excl = kFALSE;
if (pat.Contains("-v ")) {
pat.ReplaceAll("-v ", "");
excl = kTRUE;
}
pat = pat.Strip(TString::kLeading, ' ');
pat = pat.Strip(TString::kTrailing, ' ');
pat = pat.Strip(TString::kLeading, '\"');
pat = pat.Strip(TString::kTrailing, '\"');
// Use a regular expression
TRegexp re(pat);
// Open file with file info
ifstream in;
in.open(fn.Data());
TString outbuf;
// Read the input list of files and add them to the chain
TString line;
while(in.good()) {
// Read next line
line.ReadLine(in);
// Keep only lines with pattern
if ((excl && line.Index(re) != kNPOS) ||
(!excl && line.Index(re) == kNPOS)) continue;
// Remove trailing '\n', if any
if (!line.EndsWith("\n")) line.Append('\n');
// Add to output
outbuf += line;
}
in.close();
// Done
return new TObjString(outbuf.Data());
}
<commit_msg><commit_after>// @(#)root/proofx:$Id$
// Author: Gerardo Ganis Apr 2008
/*************************************************************************
* Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TProofMgrLite //
// //
// Basic functionality implementtaion in the case of Lite sessions //
// //
//////////////////////////////////////////////////////////////////////////
#include <errno.h>
#ifdef WIN32
#include <io.h>
#endif
#include "TProofMgrLite.h"
#include "Riostream.h"
#include "TEnv.h"
#include "TError.h"
#include "TObjString.h"
#include "TProofLite.h"
#include "TProofLog.h"
#include "TROOT.h"
#include "TRegexp.h"
#include "TSortedList.h"
ClassImp(TProofMgrLite)
//______________________________________________________________________________
TProofMgrLite::TProofMgrLite(const char *url, Int_t dbg, const char *alias)
: TProofMgr(url, dbg, alias)
{
// Create a PROOF manager for the Lite environment.
// Set the correct servert type
fServType = kProofLite;
}
//______________________________________________________________________________
TProof *TProofMgrLite::CreateSession(const char *cfg,
const char *, Int_t loglevel)
{
// Create a new session
Int_t nwrk = TProofLite::GetNumberOfWorkers(fUrl.GetOptions());
if (nwrk == 0) return (TProof *)0;
// Check if we have already a running session
if (gProof && gProof->IsValid() && gProof->IsLite()) {
if (nwrk > 0 && gProof->GetParallel() != nwrk) {
delete gProof;
gProof = 0;
} else {
// We have already a running session
return gProof;
}
}
// Create the instance
TString u = (strlen(fUrl.GetOptions()) > 0) ? Form("lite/?%s", fUrl.GetOptions())
: "lite";
TProof *p = new TProofLite(u, cfg, 0, loglevel, 0, this);
if (p && p->IsValid()) {
// Save record about this session
Int_t ns = 1;
if (fSessions) {
// To avoid ambiguities in case of removal of some elements
if (fSessions->Last())
ns = ((TProofDesc *)(fSessions->Last()))->GetLocalId() + 1;
} else {
// Create the list
fSessions = new TList;
}
// Create the description class
Int_t st = (p->IsIdle()) ? TProofDesc::kIdle : TProofDesc::kRunning ;
TProofDesc *d =
new TProofDesc(p->GetName(), p->GetTitle(), p->GetUrl(),
ns, p->GetSessionID(), st, p);
fSessions->Add(d);
} else {
// Session creation failed
Error("CreateSession", "creating PROOF session");
SafeDelete(p);
}
// We are done
return p;
}
//_____________________________________________________________________________
TProofLog *TProofMgrLite::GetSessionLogs(Int_t isess,
const char *stag, const char *pattern)
{
// Get logs or log tails from last session associated with this manager
// instance.
// The arguments allow to specify a session different from the last one:
// isess specifies a position relative to the last one, i.e. 1
// for the next to last session; the absolute value is taken
// so -1 and 1 are equivalent.
// stag specifies the unique tag of the wanted session
// The special value stag = "NR" allows to just initialize the TProofLog
// object w/o retrieving the files; this may be useful when the number
// of workers is large and only a subset of logs is required.
// If 'stag' is specified 'isess' is ignored (unless stag = "NR").
// If 'pattern' is specified only the lines containing it are retrieved
// (remote grep functionality); to filter out a pattern 'pat' use
// pattern = "-v pat".
// Returns a TProofLog object (to be deleted by the caller) on success,
// 0 if something wrong happened.
TProofLog *pl = 0;
// The absolute value of isess counts
isess = (isess < 0) ? -isess : isess;
// Special option in stag
bool retrieve = 1;
TString tag(stag);
if (tag == "NR") {
retrieve = 0;
tag = "";
}
// The working dir
TString sandbox(gSystem->WorkingDirectory());
sandbox.ReplaceAll(gSystem->HomeDirectory(),"");
sandbox.ReplaceAll("/","-");
sandbox.Replace(0,1,"/",1);
if (strlen(gEnv->GetValue("ProofLite.Sandbox", "")) > 0) {
sandbox.Insert(0, gEnv->GetValue("ProofLite.Sandbox", ""));
} else if (strlen(gEnv->GetValue("Proof.Sandbox", "")) > 0) {
sandbox.Insert(0, gEnv->GetValue("Proof.Sandbox", ""));
} else {
TString sb;
sb.Form("~/%s", kPROOF_WorkDir);
sandbox.Insert(0, sb.Data());
}
gSystem->ExpandPathName(sandbox);
TString sessiondir;
if (tag.Length() > 0) {
sessiondir.Form("%s/session-%s", sandbox.Data(), tag.Data());
if (gSystem->AccessPathName(sessiondir, kReadPermission)) {
Error("GetSessionLogs", "information for session '%s' not available", tag.Data());
return (TProofLog *)0;
}
} else {
// Get the list of available dirs
TSortedList *olddirs = new TSortedList(kFALSE);
void *dirp = gSystem->OpenDirectory(sandbox);
if (dirp) {
const char *e = 0;
while ((e = gSystem->GetDirEntry(dirp))) {
if (!strncmp(e, "session-", 8)) {
TString d(e);
Int_t i = d.Last('-');
if (i != kNPOS) d.Remove(i);
i = d.Last('-');
if (i != kNPOS) d.Remove(0,i+1);
TString path = Form("%s/%s", sandbox.Data(), e);
olddirs->Add(new TNamed(d, path));
}
}
gSystem->FreeDirectory(dirp);
}
// Check isess
if (isess > olddirs->GetSize() - 1) {
Warning("GetSessionLogs",
"session index out of range (%d): take oldest available session", isess);
isess = olddirs->GetSize() - 1;
}
// Locate the session dir
Int_t isx = isess;
TNamed *n = (TNamed *) olddirs->First();
while (isx-- > 0) {
olddirs->Remove(n);
delete n;
n = (TNamed *) olddirs->First();
}
if (!n) {
Error("GetSessionLogs", "cannot locate session dir for index '%d' under '%s':"
" cannot continue!", isess, sandbox.Data());
return (TProofLog *)0;
}
sessiondir = n->GetTitle();
tag = gSystem->BaseName(sessiondir);
tag.ReplaceAll("session-", "");
// Cleanup
olddirs->SetOwner();
delete olddirs;
}
Info("GetSessionLogs", "analysing session dir %s", sessiondir.Data());
// Create the instance now
pl = new TProofLog(tag, "", this);
void *dirp = gSystem->OpenDirectory(sessiondir);
if (dirp) {
TSortedList *logs = new TSortedList;
const char *e = 0;
while ((e = gSystem->GetDirEntry(dirp))) {
TString fn(e);
if (fn.EndsWith(".log") && fn.CountChar('-') > 0) {
TString ord, url;
if (fn.BeginsWith("session-")) {
ord = "-1";
} else if (fn.BeginsWith("worker-")) {
ord = fn;
ord.ReplaceAll("worker-", "");
Int_t id = ord.First('-');
if (id != kNPOS) {
ord.Remove(id);
} else if (ord.Contains(".valgrind")) {
// Add to the list (special tag for valgrind outputs)
ord.ReplaceAll(".valgrind.log","-valgrind");
} else {
// Not a good path
ord = "";
}
if (!ord.IsNull()) ord.ReplaceAll("0.", "");
}
if (!ord.IsNull()) {
url = Form("%s/%s", sessiondir.Data(), e);
// Add to the list
logs->Add(new TNamed(ord, url));
// Notify
if (gDebug > 1)
Info("GetSessionLogs", "ord: %s, url: %s", ord.Data(), url.Data());
}
}
}
gSystem->FreeDirectory(dirp);
TIter nxl(logs);
TNamed *n = 0;
while ((n = (TNamed *) nxl())) {
TString ord = Form("0.%s", n->GetName());
if (ord == "0.-1") ord = "0";
// Add to the list
pl->Add(ord, n->GetTitle());
}
// Cleanup
logs->SetOwner();
delete logs;
}
// Retrieve the default part
if (pl && retrieve) {
if (pattern && strlen(pattern) > 0)
pl->Retrieve("*", TProofLog::kGrep, 0, pattern);
else
pl->Retrieve();
}
// Done
return pl;
}
//______________________________________________________________________________
TObjString *TProofMgrLite::ReadBuffer(const char *fin, Long64_t ofs, Int_t len)
{
// Read 'len' bytes from offset 'ofs' of the local file 'fin'.
// Returns a TObjString with the content or 0, in case of failure
if (!fin || strlen(fin) <= 0) {
Error("ReadBuffer", "undefined path!");
return (TObjString *)0;
}
// Open the file
TString fn = TUrl(fin).GetFile();
Int_t fd = open(fn.Data(), O_RDONLY);
if (fd < 0) {
Error("ReadBuffer", "problems opening file %s", fn.Data());
return (TObjString *)0;
}
// Total size
off_t start = 0, end = lseek(fd, (off_t) 0, SEEK_END);
// Set the offset
if (ofs > 0 && ofs < end) {
start = lseek(fd, (off_t) ofs, SEEK_SET);
} else {
start = lseek(fd, (off_t) 0, SEEK_SET);
}
if (len > (end - start + 1) || len <= 0)
len = end - start + 1;
TString outbuf;
const Int_t kMAXBUF = 32768;
char buf[kMAXBUF];
Int_t left = len;
Int_t wanted = (left > kMAXBUF - 1) ? kMAXBUF - 1 : left;
do {
while ((len = read(fd, buf, wanted)) < 0 && TSystem::GetErrno() == EINTR)
TSystem::ResetErrno();
if (len < 0) {
Error("ReadBuffer", "error reading file %s", fn.Data());
close(fd);
return (TObjString *)0;
} else if (len > 0) {
if (len == wanted)
buf[len-1] = '\n';
buf[len] = '\0';
outbuf += buf;
}
// Update counters
left -= len;
wanted = (left > kMAXBUF - 1) ? kMAXBUF - 1 : left;
} while (len > 0 && left > 0);
// Done
return new TObjString(outbuf.Data());
}
//______________________________________________________________________________
TObjString *TProofMgrLite::ReadBuffer(const char *fin, const char *pattern)
{
// Read lines containing 'pattern' in 'file'.
// Returns a TObjString with the content or 0, in case of failure
// If no pattern, read everything
if (!pattern || strlen(pattern) <= 0)
return (TObjString *)0;
if (!fin || strlen(fin) <= 0) {
Error("ReadBuffer", "undefined path!");
return (TObjString *)0;
}
TString fn = TUrl(fin).GetFile();
TString pat(pattern);
// Check if "-v"
Bool_t excl = kFALSE;
if (pat.Contains("-v ")) {
pat.ReplaceAll("-v ", "");
excl = kTRUE;
}
pat = pat.Strip(TString::kLeading, ' ');
pat = pat.Strip(TString::kTrailing, ' ');
pat = pat.Strip(TString::kLeading, '\"');
pat = pat.Strip(TString::kTrailing, '\"');
// Use a regular expression
TRegexp re(pat);
// Open file with file info
ifstream in;
in.open(fn.Data());
TString outbuf;
// Read the input list of files and add them to the chain
TString line;
while(in.good()) {
// Read next line
line.ReadLine(in);
// Keep only lines with pattern
if ((excl && line.Index(re) != kNPOS) ||
(!excl && line.Index(re) == kNPOS)) continue;
// Remove trailing '\n', if any
if (!line.EndsWith("\n")) line.Append('\n');
// Add to output
outbuf += line;
}
in.close();
// Done
return new TObjString(outbuf.Data());
}
<|endoftext|> |
<commit_before>
///////////////////////////////////////////////////////////////////////////////
//
// +-----------------------------------------------------------+
// | Grok : A Naive JavaScript Interpreter |
// +-----------------------------------------------------------+
//
// Copyright 2015 Pushpinder Singh
//
// 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.
//
//
// \file: main.cc
// \description: definition of main
// \author: Pushpinder Singh
//
///////////////////////////////////////////////////////////////////////////////
#include "parser/parser.h"
#include <iostream>
#include <memory>
#include <string>
int main(int argc, char *argv[]) {
std::string in;
bool result = false;
std::cout << ">> ";
std::getline(std::cin, in);
auto lex = std::make_unique<Lexer>(in);
grok::parser::GrokParser parser{ std::move(lex) };
result = parser.ParseExpression();
if (result) {
std::cout << parser;
} else {
std::cout << "Errors occurred" << std::endl;
}
return 0;
}
<commit_msg>Updated main.cc<commit_after>#include "parser/parser.h"
#include "vm/context.h"
#include "vm/printer.h"
#include "vm/codegen.h"
#include "vm/instruction-list.h"
#include <iostream>
#include <memory>
#include <string>
int main(int argc, char *argv[]) {
std::string in;
bool result = false;
using namespace grok::vm;
using namespace grok::parser;
InitializeVMContext();
std::cout << ">> ";
std::getline(std::cin, in);
auto lex = std::make_unique<Lexer>(in);
grok::parser::GrokParser parser{ std::move(lex) };
result = parser.ParseExpression();
std::cout << std::string(75, '=') << std::endl;
if (!result) {
std::cout << "Errors occurred" << std::endl;
return -1;
}
auto AST = parser.ParsedAST();
CodeGenerator CG;
CG.Generate(AST.get());
auto IR = CG.GetIR();
Printer P{ std::cout };
P.Print(IR);
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "componentsplugin.h"
#include "tabviewindexmodel.h"
#include "addtabdesigneraction.h"
#include "entertabdesigneraction.h"
#include <viewmanager.h>
#include <qmldesignerplugin.h>
#include <QtPlugin>
namespace QmlDesigner {
ComponentsPlugin::ComponentsPlugin()
{
TabViewIndexModel::registerDeclarativeType();
DesignerActionManager *actionManager = &QmlDesignerPlugin::instance()->viewManager().designerActionManager();
}
QString ComponentsPlugin::pluginName() const
{
return ("ComponentsPlugin");
}
QString ComponentsPlugin::metaInfo() const
{
return QString(":/componentsplugin/components.metainfo");
}
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN(QmlDesigner::ComponentsPlugin)
#endif
<commit_msg>QmlDesigner: Remove unused variable<commit_after>/****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "componentsplugin.h"
#include "tabviewindexmodel.h"
#include "addtabdesigneraction.h"
#include "entertabdesigneraction.h"
#include <viewmanager.h>
#include <qmldesignerplugin.h>
#include <QtPlugin>
namespace QmlDesigner {
ComponentsPlugin::ComponentsPlugin()
{
TabViewIndexModel::registerDeclarativeType();
}
QString ComponentsPlugin::pluginName() const
{
return ("ComponentsPlugin");
}
QString ComponentsPlugin::metaInfo() const
{
return QString(":/componentsplugin/components.metainfo");
}
}
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN(QmlDesigner::ComponentsPlugin)
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlprmap.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: obo $ $Date: 2006-09-17 11:00:40 $
*
* 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_xmloff.hxx"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_PROPERTYHANDLERBASE_HXX
#include "xmlprhdl.hxx"
#endif
#ifndef _XMLOFF_PROPERTYHANDLER_BASICTYPES_HXX
#include "xmlbahdl.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include "xmlprmap.hxx"
#endif
#ifndef _XMLOFF_XMLTYPES_HXX
#include "xmltypes.hxx"
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include "xmltoken.hxx"
#endif
using namespace ::std;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using ::xmloff::token::GetXMLToken;
XMLPropertySetMapperEntry_Impl::XMLPropertySetMapperEntry_Impl(
const XMLPropertyMapEntry& rMapEntry,
const UniReference< XMLPropertyHandlerFactory >& rFactory ) :
sXMLAttributeName( GetXMLToken(rMapEntry.meXMLName) ),
sAPIPropertyName( OUString(rMapEntry.msApiName, rMapEntry.nApiNameLength,
RTL_TEXTENCODING_ASCII_US ) ),
nXMLNameSpace( rMapEntry.mnNameSpace ),
nType( rMapEntry.mnType ),
nContextId( rMapEntry.mnContextId ),
pHdl( rFactory->GetPropertyHandler( rMapEntry.mnType & MID_FLAG_MASK ) )
{
}
XMLPropertySetMapperEntry_Impl::XMLPropertySetMapperEntry_Impl(
const XMLPropertySetMapperEntry_Impl& rEntry ) :
sXMLAttributeName( rEntry.sXMLAttributeName),
sAPIPropertyName( rEntry.sAPIPropertyName),
nXMLNameSpace( rEntry.nXMLNameSpace),
nType( rEntry.nType),
nContextId( rEntry.nContextId),
pHdl( rEntry.pHdl)
{
DBG_ASSERT( pHdl, "Unknown XML property type handler!" );
}
///////////////////////////////////////////////////////////////////////////
//
// Ctor
//
XMLPropertySetMapper::XMLPropertySetMapper(
const XMLPropertyMapEntry* pEntries,
const UniReference< XMLPropertyHandlerFactory >& rFactory )
{
aHdlFactories.push_back( rFactory );
if( pEntries )
{
const XMLPropertyMapEntry* pIter = pEntries;
// count entries
while( pIter->msApiName )
{
XMLPropertySetMapperEntry_Impl aEntry( *pIter, rFactory );
aMapEntries.push_back( aEntry );
pIter++;
}
}
}
XMLPropertySetMapper::~XMLPropertySetMapper()
{
}
void XMLPropertySetMapper::AddMapperEntry(
const UniReference < XMLPropertySetMapper >& rMapper )
{
for( vector < UniReference < XMLPropertyHandlerFactory > >::iterator
aFIter = rMapper->aHdlFactories.begin();
aFIter != rMapper->aHdlFactories.end();
aFIter++ )
{
aHdlFactories.push_back( *aFIter );
}
for( vector < XMLPropertySetMapperEntry_Impl >::iterator
aEIter = rMapper->aMapEntries.begin();
aEIter != rMapper->aMapEntries.end();
aEIter++ )
{
aMapEntries.push_back( *aEIter );
}
}
///////////////////////////////////////////////////////////////////////////
//
// Export a Property
//
sal_Bool XMLPropertySetMapper::exportXML(
OUString& rStrExpValue,
const XMLPropertyState& rProperty,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
const XMLPropertyHandler* pHdl = GetPropertyHandler( rProperty.mnIndex );
DBG_ASSERT( pHdl, "Unknown XML Type!" );
if( pHdl )
bRet = pHdl->exportXML( rStrExpValue, rProperty.maValue,
rUnitConverter );
return bRet;
}
///////////////////////////////////////////////////////////////////////////
//
// Import a Property
//
sal_Bool XMLPropertySetMapper::importXML(
const OUString& rStrImpValue,
XMLPropertyState& rProperty,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
const XMLPropertyHandler* pHdl = GetPropertyHandler( rProperty.mnIndex );
if( pHdl )
bRet = pHdl->importXML( rStrImpValue, rProperty.maValue,
rUnitConverter );
return bRet;
}
///////////////////////////////////////////////////////////////////////////
//
// Search for the given name and the namespace in the list and return
// the index of the entry
// If there is no matching entry the method returns -1
//
const sal_Int32 XMLPropertySetMapper::GetEntryIndex(
sal_uInt16 nNamespace,
const OUString& rStrName,
sal_uInt32 nPropType,
sal_Int32 nStartAt /* = -1 */ ) const
{
sal_Int32 nEntries = GetEntryCount();
sal_Int32 nIndex= nStartAt == - 1? 0 : nStartAt+1;
do
{
const XMLPropertySetMapperEntry_Impl& rEntry = aMapEntries[nIndex];
if( (!nPropType || nPropType == rEntry.GetPropType()) &&
rEntry.nXMLNameSpace == nNamespace &&
rStrName == rEntry.sXMLAttributeName )
return nIndex;
else
nIndex++;
} while( nIndex<nEntries );
return -1;
}
/** searches for an entry that matches the given api name, namespace and local name or -1 if nothing found */
sal_Int32 XMLPropertySetMapper::FindEntryIndex(
const sal_Char* sApiName,
sal_uInt16 nNameSpace,
const OUString& sXMLName ) const
{
sal_Int32 nIndex = 0;
sal_Int32 nEntries = GetEntryCount();
do
{
const XMLPropertySetMapperEntry_Impl& rEntry = aMapEntries[nIndex];
if( rEntry.nXMLNameSpace == nNameSpace &&
rEntry.sXMLAttributeName.equals( sXMLName ) &&
0 == rEntry.sAPIPropertyName.compareToAscii( sApiName ) )
return nIndex;
else
nIndex++;
} while( nIndex < nEntries );
return -1;
}
sal_Int32 XMLPropertySetMapper::FindEntryIndex( const sal_Int16 nContextId ) const
{
sal_Int32 nIndex = 0;
sal_Int32 nEntries = GetEntryCount();
do
{
const XMLPropertySetMapperEntry_Impl& rEntry = aMapEntries[nIndex];
if( rEntry.nContextId == nContextId )
return nIndex;
else
nIndex++;
} while( nIndex < nEntries );
return -1;
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.8.124); FILE MERGED 2007/06/04 13:23:33 vg 1.8.124.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xmlprmap.cxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: hr $ $Date: 2007-06-27 15:49:00 $
*
* 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_xmloff.hxx"
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _XMLOFF_PROPERTYHANDLERBASE_HXX
#include <xmloff/xmlprhdl.hxx>
#endif
#ifndef _XMLOFF_PROPERTYHANDLER_BASICTYPES_HXX
#include "xmlbahdl.hxx"
#endif
#ifndef _XMLOFF_PROPERTYSETMAPPER_HXX
#include <xmloff/xmlprmap.hxx>
#endif
#ifndef _XMLOFF_XMLTYPES_HXX
#include <xmloff/xmltypes.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_
#include <com/sun/star/beans/XPropertyState.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_ANY_HXX_
#include <com/sun/star/uno/Any.hxx>
#endif
#ifndef _XMLOFF_XMLTOKEN_HXX
#include <xmloff/xmltoken.hxx>
#endif
using namespace ::std;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using ::xmloff::token::GetXMLToken;
XMLPropertySetMapperEntry_Impl::XMLPropertySetMapperEntry_Impl(
const XMLPropertyMapEntry& rMapEntry,
const UniReference< XMLPropertyHandlerFactory >& rFactory ) :
sXMLAttributeName( GetXMLToken(rMapEntry.meXMLName) ),
sAPIPropertyName( OUString(rMapEntry.msApiName, rMapEntry.nApiNameLength,
RTL_TEXTENCODING_ASCII_US ) ),
nXMLNameSpace( rMapEntry.mnNameSpace ),
nType( rMapEntry.mnType ),
nContextId( rMapEntry.mnContextId ),
pHdl( rFactory->GetPropertyHandler( rMapEntry.mnType & MID_FLAG_MASK ) )
{
}
XMLPropertySetMapperEntry_Impl::XMLPropertySetMapperEntry_Impl(
const XMLPropertySetMapperEntry_Impl& rEntry ) :
sXMLAttributeName( rEntry.sXMLAttributeName),
sAPIPropertyName( rEntry.sAPIPropertyName),
nXMLNameSpace( rEntry.nXMLNameSpace),
nType( rEntry.nType),
nContextId( rEntry.nContextId),
pHdl( rEntry.pHdl)
{
DBG_ASSERT( pHdl, "Unknown XML property type handler!" );
}
///////////////////////////////////////////////////////////////////////////
//
// Ctor
//
XMLPropertySetMapper::XMLPropertySetMapper(
const XMLPropertyMapEntry* pEntries,
const UniReference< XMLPropertyHandlerFactory >& rFactory )
{
aHdlFactories.push_back( rFactory );
if( pEntries )
{
const XMLPropertyMapEntry* pIter = pEntries;
// count entries
while( pIter->msApiName )
{
XMLPropertySetMapperEntry_Impl aEntry( *pIter, rFactory );
aMapEntries.push_back( aEntry );
pIter++;
}
}
}
XMLPropertySetMapper::~XMLPropertySetMapper()
{
}
void XMLPropertySetMapper::AddMapperEntry(
const UniReference < XMLPropertySetMapper >& rMapper )
{
for( vector < UniReference < XMLPropertyHandlerFactory > >::iterator
aFIter = rMapper->aHdlFactories.begin();
aFIter != rMapper->aHdlFactories.end();
aFIter++ )
{
aHdlFactories.push_back( *aFIter );
}
for( vector < XMLPropertySetMapperEntry_Impl >::iterator
aEIter = rMapper->aMapEntries.begin();
aEIter != rMapper->aMapEntries.end();
aEIter++ )
{
aMapEntries.push_back( *aEIter );
}
}
///////////////////////////////////////////////////////////////////////////
//
// Export a Property
//
sal_Bool XMLPropertySetMapper::exportXML(
OUString& rStrExpValue,
const XMLPropertyState& rProperty,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
const XMLPropertyHandler* pHdl = GetPropertyHandler( rProperty.mnIndex );
DBG_ASSERT( pHdl, "Unknown XML Type!" );
if( pHdl )
bRet = pHdl->exportXML( rStrExpValue, rProperty.maValue,
rUnitConverter );
return bRet;
}
///////////////////////////////////////////////////////////////////////////
//
// Import a Property
//
sal_Bool XMLPropertySetMapper::importXML(
const OUString& rStrImpValue,
XMLPropertyState& rProperty,
const SvXMLUnitConverter& rUnitConverter ) const
{
sal_Bool bRet = sal_False;
const XMLPropertyHandler* pHdl = GetPropertyHandler( rProperty.mnIndex );
if( pHdl )
bRet = pHdl->importXML( rStrImpValue, rProperty.maValue,
rUnitConverter );
return bRet;
}
///////////////////////////////////////////////////////////////////////////
//
// Search for the given name and the namespace in the list and return
// the index of the entry
// If there is no matching entry the method returns -1
//
const sal_Int32 XMLPropertySetMapper::GetEntryIndex(
sal_uInt16 nNamespace,
const OUString& rStrName,
sal_uInt32 nPropType,
sal_Int32 nStartAt /* = -1 */ ) const
{
sal_Int32 nEntries = GetEntryCount();
sal_Int32 nIndex= nStartAt == - 1? 0 : nStartAt+1;
do
{
const XMLPropertySetMapperEntry_Impl& rEntry = aMapEntries[nIndex];
if( (!nPropType || nPropType == rEntry.GetPropType()) &&
rEntry.nXMLNameSpace == nNamespace &&
rStrName == rEntry.sXMLAttributeName )
return nIndex;
else
nIndex++;
} while( nIndex<nEntries );
return -1;
}
/** searches for an entry that matches the given api name, namespace and local name or -1 if nothing found */
sal_Int32 XMLPropertySetMapper::FindEntryIndex(
const sal_Char* sApiName,
sal_uInt16 nNameSpace,
const OUString& sXMLName ) const
{
sal_Int32 nIndex = 0;
sal_Int32 nEntries = GetEntryCount();
do
{
const XMLPropertySetMapperEntry_Impl& rEntry = aMapEntries[nIndex];
if( rEntry.nXMLNameSpace == nNameSpace &&
rEntry.sXMLAttributeName.equals( sXMLName ) &&
0 == rEntry.sAPIPropertyName.compareToAscii( sApiName ) )
return nIndex;
else
nIndex++;
} while( nIndex < nEntries );
return -1;
}
sal_Int32 XMLPropertySetMapper::FindEntryIndex( const sal_Int16 nContextId ) const
{
sal_Int32 nIndex = 0;
sal_Int32 nEntries = GetEntryCount();
do
{
const XMLPropertySetMapperEntry_Impl& rEntry = aMapEntries[nIndex];
if( rEntry.nContextId == nContextId )
return nIndex;
else
nIndex++;
} while( nIndex < nEntries );
return -1;
}
<|endoftext|> |
<commit_before>#pragma once
#ifndef TETRA_SQLITE_SQLITE
#define TETRA_SQLITE_SQLITE
#include "sqlite3.h"
#include <vector>
#include <stdexcept>
#include <memory>
#include <cstdint>
namespace tetra
{
namespace sqlite
{
template <class T>
struct ScopeExit
{
inline ScopeExit( T fun ) : fun{fun} {};
~ScopeExit() { fun(); };
private:
T fun;
};
template <class T>
ScopeExit<T> atExit( T fun )
{
return ScopeExit<T>( fun );
};
struct Blob
{
Blob() = default;
Blob( const void* ptr, std::size_t len );
const void* m_dataPtr_{nullptr};
std::size_t m_dataLength_{0};
};
struct SQLiteError : public std::runtime_error
{
SQLiteError( const std::string& str );
};
struct StatementFinalizer
{
void operator()( sqlite3_stmt* stmt );
};
/**
* A simple and light wrapper around some of sqlite3's functionality.
**/
class SQLite
{
public:
using SafeStmt = std::unique_ptr<sqlite3_stmt, StatementFinalizer>;
public:
SQLite( const std::string& dbFilename );
~SQLite();
bool tableExists( const std::string& tableName );
void dropTable( const std::string& tableName );
void dropTables( const std::vector<std::string>& tableNames );
/**
* Prepares the given statement for execution, this allows faster
* satement processing as the statement only needs to be parsed
*once.
**/
SafeStmt prepareStatement( const std::string& stmt );
/**
* Executes the given functor on the statement until there are no
*more
* rows left in the result.
**/
template <typename Functor>
void stepUntilDone( sqlite3_stmt* stmt, Functor fctn );
template <typename Functor>
void stepUntilDone( const std::string& query, Functor fctn );
/**
* Executes the given sql statement a single time and resets its
*virtual
* machine, does not process the results. Throws an SQLiteError if
* the statement is not done after being stepped once.
**/
void executeSQL( const std::string& stmt );
void executeSQL( sqlite3_stmt* stmt );
/**
* Executes the sql statetment and then executes the functor before
* resetting the statements's virtual machine.
**/
template <typename Functor>
void executeSQL( sqlite3_stmt* stmt, Functor fctn );
/**
* Typesafe means of binding a value into a prepared sql statetment.
* The first parameter after the statement corresponds to the first
* value to be bound, the second corresponds to the second, etc...
**/
template <class... Params>
void bindSQL( sqlite3_stmt* stmt, Params... params );
static void throwIfNotDone( int result );
private:
sqlite3* m_context_{nullptr};
private:
void bindSQL_Impl( sqlite3_stmt* stmt, int index, int p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, std::string p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, const char* p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, double p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, float p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, std::int64_t p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, Blob p );
template <class Param, class... Params>
void bindSQL_Impl( sqlite3_stmt* stmt, int index, Param p,
Params... params );
}; /* class SQLite */
}
} /* namespace tetra::sqlite */
#include "sqlite_impl.hpp"
#endif
<commit_msg>fixed the include of the sqlite.h header<commit_after>#pragma once
#ifndef TETRA_SQLITE_SQLITE
#define TETRA_SQLITE_SQLITE
#include <sqlite3.h>
#include <vector>
#include <stdexcept>
#include <memory>
#include <cstdint>
namespace tetra
{
namespace sqlite
{
template <class T>
struct ScopeExit
{
inline ScopeExit( T fun ) : fun{fun} {};
~ScopeExit() { fun(); };
private:
T fun;
};
template <class T>
ScopeExit<T> atExit( T fun )
{
return ScopeExit<T>( fun );
};
struct Blob
{
Blob() = default;
Blob( const void* ptr, std::size_t len );
const void* m_dataPtr_{nullptr};
std::size_t m_dataLength_{0};
};
struct SQLiteError : public std::runtime_error
{
SQLiteError( const std::string& str );
};
struct StatementFinalizer
{
void operator()( sqlite3_stmt* stmt );
};
/**
* A simple and light wrapper around some of sqlite3's functionality.
**/
class SQLite
{
public:
using SafeStmt = std::unique_ptr<sqlite3_stmt, StatementFinalizer>;
public:
SQLite( const std::string& dbFilename );
~SQLite();
bool tableExists( const std::string& tableName );
void dropTable( const std::string& tableName );
void dropTables( const std::vector<std::string>& tableNames );
/**
* Prepares the given statement for execution, this allows faster
* satement processing as the statement only needs to be parsed
*once.
**/
SafeStmt prepareStatement( const std::string& stmt );
/**
* Executes the given functor on the statement until there are no
*more
* rows left in the result.
**/
template <typename Functor>
void stepUntilDone( sqlite3_stmt* stmt, Functor fctn );
template <typename Functor>
void stepUntilDone( const std::string& query, Functor fctn );
/**
* Executes the given sql statement a single time and resets its
*virtual
* machine, does not process the results. Throws an SQLiteError if
* the statement is not done after being stepped once.
**/
void executeSQL( const std::string& stmt );
void executeSQL( sqlite3_stmt* stmt );
/**
* Executes the sql statetment and then executes the functor before
* resetting the statements's virtual machine.
**/
template <typename Functor>
void executeSQL( sqlite3_stmt* stmt, Functor fctn );
/**
* Typesafe means of binding a value into a prepared sql statetment.
* The first parameter after the statement corresponds to the first
* value to be bound, the second corresponds to the second, etc...
**/
template <class... Params>
void bindSQL( sqlite3_stmt* stmt, Params... params );
static void throwIfNotDone( int result );
private:
sqlite3* m_context_{nullptr};
private:
void bindSQL_Impl( sqlite3_stmt* stmt, int index, int p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, std::string p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, const char* p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, double p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, float p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, std::int64_t p );
void bindSQL_Impl( sqlite3_stmt* stmt, int index, Blob p );
template <class Param, class... Params>
void bindSQL_Impl( sqlite3_stmt* stmt, int index, Param p,
Params... params );
}; /* class SQLite */
}
} /* namespace tetra::sqlite */
#include "sqlite_impl.hpp"
#endif
<|endoftext|> |
<commit_before>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
#include "test.h"
int num_entries;
bool flush_may_occur;
int expected_flushed_key;
bool check_flush;
static void
flush (CACHEFILE f __attribute__((__unused__)),
int UU(fd),
CACHEKEY k __attribute__((__unused__)),
void *v __attribute__((__unused__)),
void** UU(dd),
void *e __attribute__((__unused__)),
PAIR_ATTR s __attribute__((__unused__)),
PAIR_ATTR* new_size __attribute__((__unused__)),
bool w __attribute__((__unused__)),
bool keep __attribute__((__unused__)),
bool c __attribute__((__unused__)),
bool UU(is_clone)
) {
/* Do nothing */
if (check_flush && !keep) {
if (verbose) { printf("FLUSH: %d write_me %d\n", (int)k.b, w); }
assert(flush_may_occur);
assert(!w);
assert(expected_flushed_key == (int)k.b);
expected_flushed_key--;
}
}
static int
fetch (CACHEFILE f __attribute__((__unused__)),
PAIR UU(p),
int UU(fd),
CACHEKEY k __attribute__((__unused__)),
uint32_t fullhash __attribute__((__unused__)),
void **value __attribute__((__unused__)),
void** UU(dd),
PAIR_ATTR *sizep __attribute__((__unused__)),
int *dirtyp,
void *extraargs __attribute__((__unused__))
) {
*dirtyp = 0;
*value = NULL;
*sizep = make_pair_attr(1);
return 0;
}
static void
cachetable_test (void) {
const int test_limit = 4;
num_entries = 0;
int r;
CACHETABLE ct;
toku_cachetable_create(&ct, test_limit, ZERO_LSN, NULL_LOGGER);
char fname1[] = __SRCFILE__ "test1.dat";
unlink(fname1);
CACHEFILE f1;
r = toku_cachetable_openf(&f1, ct, fname1, O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO); assert(r == 0);
void* v1;
void* v2;
long s1, s2;
flush_may_occur = false;
check_flush = true;
CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL);
wc.flush_callback = flush;
for (int i = 0; i < 100000; i++) {
r = toku_cachetable_get_and_pin(f1, make_blocknum(1), 1, &v1, &s1, wc, fetch, def_pf_req_callback, def_pf_callback, true, NULL);
r = toku_test_cachetable_unpin(f1, make_blocknum(1), 1, CACHETABLE_CLEAN, make_pair_attr(1));
}
for (int i = 0; i < 8; i++) {
r = toku_cachetable_get_and_pin(f1, make_blocknum(2), 2, &v2, &s2, wc, fetch, def_pf_req_callback, def_pf_callback, true, NULL);
r = toku_test_cachetable_unpin(f1, make_blocknum(2), 2, CACHETABLE_CLEAN, make_pair_attr(1));
}
for (int i = 0; i < 4; i++) {
r = toku_cachetable_get_and_pin(f1, make_blocknum(3), 3, &v2, &s2, wc, fetch, def_pf_req_callback, def_pf_callback, true, NULL);
r = toku_test_cachetable_unpin(f1, make_blocknum(3), 3, CACHETABLE_CLEAN, make_pair_attr(1));
}
for (int i = 0; i < 2; i++) {
r = toku_cachetable_get_and_pin(f1, make_blocknum(4), 4, &v2, &s2, wc, fetch, def_pf_req_callback, def_pf_callback, true, NULL);
r = toku_test_cachetable_unpin(f1, make_blocknum(4), 4, CACHETABLE_CLEAN, make_pair_attr(1));
}
flush_may_occur = true;
expected_flushed_key = 4;
toku_cachetable_put(f1, make_blocknum(5), 5, NULL, make_pair_attr(4), wc, put_callback_nop);
ct->ev.signal_eviction_thread();
usleep(1*1024*1024);
flush_may_occur = true;
expected_flushed_key = 5;
r = toku_test_cachetable_unpin(f1, make_blocknum(5), 5, CACHETABLE_CLEAN, make_pair_attr(4));
ct->ev.signal_eviction_thread();
usleep(1*1024*1024);
check_flush = false;
toku_cachefile_close(&f1, false, ZERO_LSN);
toku_cachetable_close(&ct);
}
int
test_main(int argc, const char *argv[]) {
default_parse_args(argc, argv);
cachetable_test();
return 0;
}
<commit_msg>refs #5798 update cachetable-clock-eviction to reflect new probabilistic eviction strategy<commit_after>/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
#ident "Copyright (c) 2007-2012 Tokutek Inc. All rights reserved."
#include "test.h"
int num_entries;
bool flush_may_occur;
int expected_flushed_key;
bool check_flush;
static void
flush (CACHEFILE f __attribute__((__unused__)),
int UU(fd),
CACHEKEY k __attribute__((__unused__)),
void *v __attribute__((__unused__)),
void** UU(dd),
void *e __attribute__((__unused__)),
PAIR_ATTR s __attribute__((__unused__)),
PAIR_ATTR* new_size __attribute__((__unused__)),
bool w __attribute__((__unused__)),
bool keep __attribute__((__unused__)),
bool c __attribute__((__unused__)),
bool UU(is_clone)
) {
/* Do nothing */
if (check_flush && !keep) {
if (verbose) { printf("FLUSH: %d write_me %d expected %d\n", (int)k.b, w, expected_flushed_key); }
assert(flush_may_occur);
assert(!w);
assert(expected_flushed_key == (int)k.b);
expected_flushed_key--;
}
}
static int
fetch (CACHEFILE f __attribute__((__unused__)),
PAIR UU(p),
int UU(fd),
CACHEKEY k __attribute__((__unused__)),
uint32_t fullhash __attribute__((__unused__)),
void **value __attribute__((__unused__)),
void** UU(dd),
PAIR_ATTR *sizep __attribute__((__unused__)),
int *dirtyp,
void *extraargs __attribute__((__unused__))
) {
*dirtyp = 0;
*value = NULL;
*sizep = make_pair_attr(1);
return 0;
}
static void
cachetable_test (void) {
const int test_limit = 4;
num_entries = 0;
int r;
CACHETABLE ct;
toku_cachetable_create(&ct, test_limit, ZERO_LSN, NULL_LOGGER);
char fname1[] = __SRCFILE__ "test1.dat";
unlink(fname1);
CACHEFILE f1;
r = toku_cachetable_openf(&f1, ct, fname1, O_RDWR|O_CREAT, S_IRWXU|S_IRWXG|S_IRWXO); assert(r == 0);
void* v1;
void* v2;
long s1, s2;
flush_may_occur = false;
check_flush = true;
CACHETABLE_WRITE_CALLBACK wc = def_write_callback(NULL);
wc.flush_callback = flush;
for (int i = 0; i < 100000; i++) {
r = toku_cachetable_get_and_pin(f1, make_blocknum(1), 1, &v1, &s1, wc, fetch, def_pf_req_callback, def_pf_callback, true, NULL);
r = toku_test_cachetable_unpin(f1, make_blocknum(1), 1, CACHETABLE_CLEAN, make_pair_attr(1));
}
for (int i = 0; i < 8; i++) {
r = toku_cachetable_get_and_pin(f1, make_blocknum(2), 2, &v2, &s2, wc, fetch, def_pf_req_callback, def_pf_callback, true, NULL);
r = toku_test_cachetable_unpin(f1, make_blocknum(2), 2, CACHETABLE_CLEAN, make_pair_attr(1));
}
for (int i = 0; i < 4; i++) {
r = toku_cachetable_get_and_pin(f1, make_blocknum(3), 3, &v2, &s2, wc, fetch, def_pf_req_callback, def_pf_callback, true, NULL);
r = toku_test_cachetable_unpin(f1, make_blocknum(3), 3, CACHETABLE_CLEAN, make_pair_attr(1));
}
for (int i = 0; i < 2; i++) {
r = toku_cachetable_get_and_pin(f1, make_blocknum(4), 4, &v2, &s2, wc, fetch, def_pf_req_callback, def_pf_callback, true, NULL);
r = toku_test_cachetable_unpin(f1, make_blocknum(4), 4, CACHETABLE_CLEAN, make_pair_attr(1));
}
flush_may_occur = true;
expected_flushed_key = 4;
toku_cachetable_put(f1, make_blocknum(5), 5, NULL, make_pair_attr(1), wc, put_callback_nop);
ct->ev.signal_eviction_thread();
usleep(1*1024*1024);
flush_may_occur = true;
r = toku_test_cachetable_unpin(f1, make_blocknum(5), 5, CACHETABLE_CLEAN, make_pair_attr(2));
ct->ev.signal_eviction_thread();
usleep(1*1024*1024);
check_flush = false;
toku_cachefile_close(&f1, false, ZERO_LSN);
toku_cachetable_close(&ct);
}
int
test_main(int argc, const char *argv[]) {
default_parse_args(argc, argv);
cachetable_test();
return 0;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "boost_std_shared_shim.hpp" // FIXME - do we need it?
// The functions in this file produce deprecation warnings.
// But as shield symbolizer doesn't fully support more than one
// placement from python yet these functions are actually the
// correct ones.
#define NO_DEPRECATION_WARNINGS
// boost
#include <boost/python.hpp>
#include <boost/variant.hpp>
#include <boost/python/suite/indexing/map_indexing_suite.hpp>
// mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/symbolizer_hash.hpp>
#include <mapnik/symbolizer_utils.hpp>
#include <mapnik/symbolizer_keys.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/path_expression.hpp>
#include "mapnik_enumeration.hpp"
#include "mapnik_svg.hpp"
#include <mapnik/graphics.hpp>
#include <mapnik/expression_node.hpp>
#include <mapnik/value_error.hpp>
#include <mapnik/marker_cache.hpp> // for known_svg_prefix_
// stl
#include <sstream>
using mapnik::symbolizer;
using mapnik::point_symbolizer;
using mapnik::line_symbolizer;
using mapnik::line_pattern_symbolizer;
using mapnik::polygon_symbolizer;
using mapnik::polygon_pattern_symbolizer;
using mapnik::raster_symbolizer;
using mapnik::shield_symbolizer;
using mapnik::text_symbolizer;
using mapnik::building_symbolizer;
using mapnik::markers_symbolizer;
using mapnik::symbolizer_base;
using mapnik::color;
using mapnik::path_processor_type;
using mapnik::path_expression_ptr;
using mapnik::guess_type;
using mapnik::expression_ptr;
using mapnik::parse_path;
namespace {
using namespace boost::python;
void __setitem__(mapnik::symbolizer_base & sym, std::string const& name, mapnik::symbolizer_base::value_type const& val)
{
//std::cerr << "__setitem__ " << typeid(val).name() << std::endl;
put(sym, mapnik::get_key(name), val);
}
struct extract_python_object : public boost::static_visitor<boost::python::object>
{
typedef boost::python::object result_type;
template <typename T>
auto operator() (T const& val) const -> result_type
{
return result_type(val); // wrap into python object
}
};
boost::python::object __getitem__(mapnik::symbolizer_base const& sym, std::string const& name)
{
typedef symbolizer_base::cont_type::const_iterator const_iterator;
mapnik::keys key = mapnik::get_key(name);
const_iterator itr = sym.properties.find(key);
if (itr != sym.properties.end())
{
return boost::apply_visitor(extract_python_object(), itr->second);
}
//mapnik::property_meta_type const& meta = mapnik::get_meta(key);
//return boost::apply_visitor(extract_python_object(), std::get<1>(meta));
return boost::python::object();
}
struct symbolizer_to_json : public boost::static_visitor<std::string>
{
typedef std::string result_type;
template <typename T>
auto operator() (T const& sym) const -> result_type
{
std::stringstream ss;
ss << "{\"type\":\"" << mapnik::symbolizer_traits<T>::name() << "\",";
ss << "\"properties\":{";
bool first = true;
for (auto const& prop : sym.properties)
{
auto const& meta = mapnik::get_meta(prop.first);
if (first) first = false;
else ss << ",";
ss << "\"" << std::get<0>(meta) << "\":";
ss << boost::apply_visitor(mapnik::symbolizer_property_value_string<mapnik::property_meta_type>(meta),prop.second);
}
ss << "}}";
return ss.str();
}
};
std::string __str__(mapnik::symbolizer const& sym)
{
return boost::apply_visitor(symbolizer_to_json(), sym);
}
std::string get_symbolizer_type(symbolizer const& sym)
{
return mapnik::symbolizer_name(sym); // FIXME - do we need this ?
}
const point_symbolizer& point_(symbolizer const& sym )
{
return boost::get<point_symbolizer>(sym);
}
const line_symbolizer& line_( const symbolizer& sym )
{
return boost::get<line_symbolizer>(sym);
}
const polygon_symbolizer& polygon_( const symbolizer& sym )
{
return boost::get<polygon_symbolizer>(sym);
}
const raster_symbolizer& raster_( const symbolizer& sym )
{
return boost::get<raster_symbolizer>(sym);
}
const text_symbolizer& text_( const symbolizer& sym )
{
return boost::get<text_symbolizer>(sym);
}
const shield_symbolizer& shield_( const symbolizer& sym )
{
return boost::get<shield_symbolizer>(sym);
}
const line_pattern_symbolizer& line_pattern_( const symbolizer& sym )
{
return boost::get<line_pattern_symbolizer>(sym);
}
const polygon_pattern_symbolizer& polygon_pattern_( const symbolizer& sym )
{
return boost::get<polygon_pattern_symbolizer>(sym);
}
const building_symbolizer& building_( const symbolizer& sym )
{
return boost::get<building_symbolizer>(sym);
}
const markers_symbolizer& markers_( const symbolizer& sym )
{
return boost::get<markers_symbolizer>(sym);
}
struct symbolizer_hash_visitor : public boost::static_visitor<std::size_t>
{
template <typename T>
std::size_t operator() (T const& sym) const
{
return mapnik::symbolizer_hash::value(sym);
}
};
std::size_t hash_impl(symbolizer const& sym)
{
return boost::apply_visitor(symbolizer_hash_visitor(), sym);
}
}
void export_symbolizer()
{
using namespace boost::python;
implicitly_convertible<mapnik::enumeration_wrapper, mapnik::symbolizer_base::value_type>();
implicitly_convertible<std::string, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::color, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::expression_ptr, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::value_integer, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::value_double, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::value_bool, mapnik::symbolizer_base::value_type>();
enum_<mapnik::keys>("keys")
.value("gamma", mapnik::keys::gamma)
.value("gamma_method",mapnik::keys::gamma_method)
;
class_<symbolizer>("Symbolizer",no_init)
.def("type",get_symbolizer_type)
.def("__hash__",hash_impl)
.def("point",point_,
return_value_policy<copy_const_reference>())
.def("line",line_,
return_value_policy<copy_const_reference>())
.def("line_pattern",line_pattern_,
return_value_policy<copy_const_reference>())
.def("polygon",polygon_,
return_value_policy<copy_const_reference>())
.def("polygon_pattern",polygon_pattern_,
return_value_policy<copy_const_reference>())
.def("raster",raster_,
return_value_policy<copy_const_reference>())
.def("shield",shield_,
return_value_policy<copy_const_reference>())
.def("text",text_,
return_value_policy<copy_const_reference>())
.def("building",building_,
return_value_policy<copy_const_reference>())
.def("markers",markers_,
return_value_policy<copy_const_reference>())
;
class_<symbolizer_base>("SymbolizerBase",no_init)
.def("__setitem__",&__setitem__)
.def("__setattr__",&__setitem__)
.def("__getitem__",&__getitem__)
.def("__getattr__",&__getitem__)
.def("__str__", &__str__)
;
}
void export_shield_symbolizer()
{
using namespace boost::python;
class_< shield_symbolizer, bases<text_symbolizer> >("ShieldSymbolizer",
init<>("Default ctor"))
;
}
void export_polygon_symbolizer()
{
using namespace boost::python;
class_<polygon_symbolizer, bases<symbolizer_base> >("PolygonSymbolizer",
init<>("Default ctor"))
;
}
void export_polygon_pattern_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::pattern_alignment_e>("pattern_alignment")
.value("LOCAL",mapnik::LOCAL_ALIGNMENT)
.value("GLOBAL",mapnik::GLOBAL_ALIGNMENT)
;
class_<polygon_pattern_symbolizer>("PolygonPatternSymbolizer",
init<>("Default ctor"))
;
}
void export_raster_symbolizer()
{
using namespace boost::python;
class_<raster_symbolizer, bases<symbolizer_base> >("RasterSymbolizer",
init<>("Default ctor"))
;
}
void export_point_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::point_placement_e>("point_placement")
.value("CENTROID",mapnik::CENTROID_POINT_PLACEMENT)
.value("INTERIOR",mapnik::INTERIOR_POINT_PLACEMENT)
;
class_<point_symbolizer, bases<symbolizer_base> >("PointSymbolizer",
init<>("Default Point Symbolizer - 4x4 black square"))
;
}
void export_markers_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::marker_placement_e>("marker_placement")
.value("POINT_PLACEMENT",mapnik::MARKER_POINT_PLACEMENT)
.value("INTERIOR_PLACEMENT",mapnik::MARKER_INTERIOR_PLACEMENT)
.value("LINE_PLACEMENT",mapnik::MARKER_LINE_PLACEMENT)
;
mapnik::enumeration_<mapnik::marker_multi_policy_e>("marker_multi_policy")
.value("EACH",mapnik::MARKER_EACH_MULTI)
.value("WHOLE",mapnik::MARKER_WHOLE_MULTI)
.value("LARGEST",mapnik::MARKER_LARGEST_MULTI)
;
class_<markers_symbolizer, bases<symbolizer_base> >("MarkersSymbolizer",
init<>("Default Markers Symbolizer - circle"))
;
}
void export_line_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::line_rasterizer_e>("line_rasterizer")
.value("FULL",mapnik::RASTERIZER_FULL)
.value("FAST",mapnik::RASTERIZER_FAST)
;
class_<line_symbolizer, bases<symbolizer_base> >("LineSymbolizer",
init<>("Default LineSymbolizer - 1px solid black"))
;
}
void export_line_pattern_symbolizer()
{
using namespace boost::python;
class_<line_pattern_symbolizer, bases<symbolizer_base> >("LinePatternSymbolizer",
init<> ("Default LinePatternSymbolizer"))
;
}
void export_debug_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::debug_symbolizer_mode_e>("debug_symbolizer_mode")
.value("COLLISION",mapnik::DEBUG_SYM_MODE_COLLISION)
.value("VERTEX",mapnik::DEBUG_SYM_MODE_VERTEX)
;
class_<mapnik::debug_symbolizer, bases<symbolizer_base> >("DebugSymbolizer",
init<>("Default debug Symbolizer"))
;
}
void export_building_symbolizer()
{
using namespace boost::python;
class_<building_symbolizer, bases<symbolizer_base> >("BuildingSymbolizer",
init<>("Default BuildingSymbolizer"))
;
}
<commit_msg>NumericWrapper helper class to pass correct numeric type value_bool, value_integer, value_double to symbolizer property (there must be a better way ;)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2013 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
#include "boost_std_shared_shim.hpp" // FIXME - do we need it?
// The functions in this file produce deprecation warnings.
// But as shield symbolizer doesn't fully support more than one
// placement from python yet these functions are actually the
// correct ones.
#define NO_DEPRECATION_WARNINGS
// boost
#include <boost/python.hpp>
#include <boost/variant.hpp>
#include <boost/python/suite/indexing/map_indexing_suite.hpp>
// mapnik
#include <mapnik/symbolizer.hpp>
#include <mapnik/symbolizer_hash.hpp>
#include <mapnik/symbolizer_utils.hpp>
#include <mapnik/symbolizer_keys.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/parse_path.hpp>
#include <mapnik/path_expression.hpp>
#include "mapnik_enumeration.hpp"
#include "mapnik_svg.hpp"
#include <mapnik/graphics.hpp>
#include <mapnik/expression_node.hpp>
#include <mapnik/value_error.hpp>
#include <mapnik/marker_cache.hpp> // for known_svg_prefix_
// stl
#include <sstream>
using mapnik::symbolizer;
using mapnik::point_symbolizer;
using mapnik::line_symbolizer;
using mapnik::line_pattern_symbolizer;
using mapnik::polygon_symbolizer;
using mapnik::polygon_pattern_symbolizer;
using mapnik::raster_symbolizer;
using mapnik::shield_symbolizer;
using mapnik::text_symbolizer;
using mapnik::building_symbolizer;
using mapnik::markers_symbolizer;
using mapnik::symbolizer_base;
using mapnik::color;
using mapnik::path_processor_type;
using mapnik::path_expression_ptr;
using mapnik::guess_type;
using mapnik::expression_ptr;
using mapnik::parse_path;
namespace {
using namespace boost::python;
void __setitem__(mapnik::symbolizer_base & sym, std::string const& name, mapnik::symbolizer_base::value_type const& val)
{
put(sym, mapnik::get_key(name), val);
}
std::shared_ptr<mapnik::symbolizer_base::value_type> numeric_wrapper(const object& arg)
{
std::shared_ptr<mapnik::symbolizer_base::value_type> result;
if (PyBool_Check(arg.ptr()))
{
mapnik::value_bool val = extract<mapnik::value_bool>(arg);
result.reset(new mapnik::symbolizer_base::value_type(val));
}
else if (PyFloat_Check(arg.ptr()))
{
mapnik::value_double val = extract<mapnik::value_double>(arg);
result.reset(new mapnik::symbolizer_base::value_type(val));
}
else
{
mapnik::value_integer val = extract<mapnik::value_integer>(arg);
result.reset(new mapnik::symbolizer_base::value_type(val));
}
return result;
}
struct extract_python_object : public boost::static_visitor<boost::python::object>
{
typedef boost::python::object result_type;
template <typename T>
auto operator() (T const& val) const -> result_type
{
return result_type(val); // wrap into python object
}
};
boost::python::object __getitem__(mapnik::symbolizer_base const& sym, std::string const& name)
{
typedef symbolizer_base::cont_type::const_iterator const_iterator;
mapnik::keys key = mapnik::get_key(name);
const_iterator itr = sym.properties.find(key);
if (itr != sym.properties.end())
{
return boost::apply_visitor(extract_python_object(), itr->second);
}
//mapnik::property_meta_type const& meta = mapnik::get_meta(key);
//return boost::apply_visitor(extract_python_object(), std::get<1>(meta));
return boost::python::object();
}
struct symbolizer_to_json : public boost::static_visitor<std::string>
{
typedef std::string result_type;
template <typename T>
auto operator() (T const& sym) const -> result_type
{
std::stringstream ss;
ss << "{\"type\":\"" << mapnik::symbolizer_traits<T>::name() << "\",";
ss << "\"properties\":{";
bool first = true;
for (auto const& prop : sym.properties)
{
auto const& meta = mapnik::get_meta(prop.first);
if (first) first = false;
else ss << ",";
ss << "\"" << std::get<0>(meta) << "\":";
ss << boost::apply_visitor(mapnik::symbolizer_property_value_string<mapnik::property_meta_type>(meta),prop.second);
}
ss << "}}";
return ss.str();
}
};
std::string __str__(mapnik::symbolizer const& sym)
{
return boost::apply_visitor(symbolizer_to_json(), sym);
}
std::string get_symbolizer_type(symbolizer const& sym)
{
return mapnik::symbolizer_name(sym); // FIXME - do we need this ?
}
const point_symbolizer& point_(symbolizer const& sym )
{
return boost::get<point_symbolizer>(sym);
}
const line_symbolizer& line_( const symbolizer& sym )
{
return boost::get<line_symbolizer>(sym);
}
const polygon_symbolizer& polygon_( const symbolizer& sym )
{
return boost::get<polygon_symbolizer>(sym);
}
const raster_symbolizer& raster_( const symbolizer& sym )
{
return boost::get<raster_symbolizer>(sym);
}
const text_symbolizer& text_( const symbolizer& sym )
{
return boost::get<text_symbolizer>(sym);
}
const shield_symbolizer& shield_( const symbolizer& sym )
{
return boost::get<shield_symbolizer>(sym);
}
const line_pattern_symbolizer& line_pattern_( const symbolizer& sym )
{
return boost::get<line_pattern_symbolizer>(sym);
}
const polygon_pattern_symbolizer& polygon_pattern_( const symbolizer& sym )
{
return boost::get<polygon_pattern_symbolizer>(sym);
}
const building_symbolizer& building_( const symbolizer& sym )
{
return boost::get<building_symbolizer>(sym);
}
const markers_symbolizer& markers_( const symbolizer& sym )
{
return boost::get<markers_symbolizer>(sym);
}
struct symbolizer_hash_visitor : public boost::static_visitor<std::size_t>
{
template <typename T>
std::size_t operator() (T const& sym) const
{
return mapnik::symbolizer_hash::value(sym);
}
};
std::size_t hash_impl(symbolizer const& sym)
{
return boost::apply_visitor(symbolizer_hash_visitor(), sym);
}
}
void export_symbolizer()
{
using namespace boost::python;
//implicitly_convertible<mapnik::value_bool, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::value_integer, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::value_double, mapnik::symbolizer_base::value_type>();
implicitly_convertible<std::string, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::color, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::expression_ptr, mapnik::symbolizer_base::value_type>();
implicitly_convertible<mapnik::enumeration_wrapper, mapnik::symbolizer_base::value_type>();
enum_<mapnik::keys>("keys")
.value("gamma", mapnik::keys::gamma)
.value("gamma_method",mapnik::keys::gamma_method)
;
class_<symbolizer>("Symbolizer",no_init)
.def("type",get_symbolizer_type)
.def("__hash__",hash_impl)
.def("point",point_,
return_value_policy<copy_const_reference>())
.def("line",line_,
return_value_policy<copy_const_reference>())
.def("line_pattern",line_pattern_,
return_value_policy<copy_const_reference>())
.def("polygon",polygon_,
return_value_policy<copy_const_reference>())
.def("polygon_pattern",polygon_pattern_,
return_value_policy<copy_const_reference>())
.def("raster",raster_,
return_value_policy<copy_const_reference>())
.def("shield",shield_,
return_value_policy<copy_const_reference>())
.def("text",text_,
return_value_policy<copy_const_reference>())
.def("building",building_,
return_value_policy<copy_const_reference>())
.def("markers",markers_,
return_value_policy<copy_const_reference>())
;
class_<symbolizer_base::value_type>("NumericWrapper")
.def("__init__", make_constructor(numeric_wrapper))
;
class_<symbolizer_base>("SymbolizerBase",no_init)
.def("__setitem__",&__setitem__)
.def("__setattr__",&__setitem__)
.def("__getitem__",&__getitem__)
.def("__getattr__",&__getitem__)
.def("__str__", &__str__)
;
}
void export_shield_symbolizer()
{
using namespace boost::python;
class_< shield_symbolizer, bases<text_symbolizer> >("ShieldSymbolizer",
init<>("Default ctor"))
;
}
void export_polygon_symbolizer()
{
using namespace boost::python;
class_<polygon_symbolizer, bases<symbolizer_base> >("PolygonSymbolizer",
init<>("Default ctor"))
;
}
void export_polygon_pattern_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::pattern_alignment_e>("pattern_alignment")
.value("LOCAL",mapnik::LOCAL_ALIGNMENT)
.value("GLOBAL",mapnik::GLOBAL_ALIGNMENT)
;
class_<polygon_pattern_symbolizer>("PolygonPatternSymbolizer",
init<>("Default ctor"))
;
}
void export_raster_symbolizer()
{
using namespace boost::python;
class_<raster_symbolizer, bases<symbolizer_base> >("RasterSymbolizer",
init<>("Default ctor"))
;
}
void export_point_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::point_placement_e>("point_placement")
.value("CENTROID",mapnik::CENTROID_POINT_PLACEMENT)
.value("INTERIOR",mapnik::INTERIOR_POINT_PLACEMENT)
;
class_<point_symbolizer, bases<symbolizer_base> >("PointSymbolizer",
init<>("Default Point Symbolizer - 4x4 black square"))
;
}
void export_markers_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::marker_placement_e>("marker_placement")
.value("POINT_PLACEMENT",mapnik::MARKER_POINT_PLACEMENT)
.value("INTERIOR_PLACEMENT",mapnik::MARKER_INTERIOR_PLACEMENT)
.value("LINE_PLACEMENT",mapnik::MARKER_LINE_PLACEMENT)
;
mapnik::enumeration_<mapnik::marker_multi_policy_e>("marker_multi_policy")
.value("EACH",mapnik::MARKER_EACH_MULTI)
.value("WHOLE",mapnik::MARKER_WHOLE_MULTI)
.value("LARGEST",mapnik::MARKER_LARGEST_MULTI)
;
class_<markers_symbolizer, bases<symbolizer_base> >("MarkersSymbolizer",
init<>("Default Markers Symbolizer - circle"))
;
}
void export_line_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::line_rasterizer_e>("line_rasterizer")
.value("FULL",mapnik::RASTERIZER_FULL)
.value("FAST",mapnik::RASTERIZER_FAST)
;
class_<line_symbolizer, bases<symbolizer_base> >("LineSymbolizer",
init<>("Default LineSymbolizer - 1px solid black"))
;
}
void export_line_pattern_symbolizer()
{
using namespace boost::python;
class_<line_pattern_symbolizer, bases<symbolizer_base> >("LinePatternSymbolizer",
init<> ("Default LinePatternSymbolizer"))
;
}
void export_debug_symbolizer()
{
using namespace boost::python;
mapnik::enumeration_<mapnik::debug_symbolizer_mode_e>("debug_symbolizer_mode")
.value("COLLISION",mapnik::DEBUG_SYM_MODE_COLLISION)
.value("VERTEX",mapnik::DEBUG_SYM_MODE_VERTEX)
;
class_<mapnik::debug_symbolizer, bases<symbolizer_base> >("DebugSymbolizer",
init<>("Default debug Symbolizer"))
;
}
void export_building_symbolizer()
{
using namespace boost::python;
class_<building_symbolizer, bases<symbolizer_base> >("BuildingSymbolizer",
init<>("Default BuildingSymbolizer"))
;
}
<|endoftext|> |
<commit_before>#include "filesystem.h"
FileSystem::FileSystem() {
this->mRoot = new Dnode();
this->mWalker = Walker(this->mRoot, nullptr, "/");
}
FileSystem::~FileSystem() {
delete this->mRoot;
}
int FileSystem::createFolder(std::string folderName) {
dynamic_cast<Dnode*>(mWalker.getLookingAt())->addNode(new Dnode(mWalker.getCwd(), 4, folderName, mWalker.getLookingAt()));
return 1; // implement proper return value
}
int FileSystem::printContents(std::string fileName) {
bool hit = false;
std::vector<Bnode*> files = dynamic_cast<Dnode*>(this->mWalker.getLookingAt())->getFiles();
for (unsigned int i = 0; i < files.size() && !hit; i++) {
if (dynamic_cast<Fnode*>(files.at(i)) && files.at(i)->getName() == fileName) {
hit = true;
std::cout << dynamic_cast<Fnode*>(files.at(i))->getData() << std::endl;
}
}
if (!hit) {
std::cout << "No such file" << std::endl;
}
return 1; // implement proper return value
}
int FileSystem::printCurrentWorkingDirectory() {
std::cout << mWalker.getCwd() << std::endl;
return 1; // implement proper return value
}
int FileSystem::removeFile(std::string fileName) {
bool hit = false;
std::vector<Bnode*> files = dynamic_cast<Dnode*>(this->mWalker.getLookingAt())->getFiles();
for (unsigned int i = 0; i < files.size(); i++) {
if (files.at(i)->getName() == fileName) {
if(dynamic_cast<Fnode*>(files.at(i)))
{
hit = true;
dynamic_cast<Dnode*>(this->mWalker.getLookingAt())->removeNode(i);
}
}
}
if (!hit) {
std::cout << "No such file." << std::endl;
}
return 1; // implement proper return value
}
std::string FileSystem::listDir(std::string dir) {
// TODO: MAKE WALKER STAND ON "PARAMETER DIR" BEFORE GETTING FILE-VECTOR.
std::vector<Bnode*> files = dynamic_cast<Dnode*>(this->mWalker.getLookingAt())->getFiles();
std::string listDirs = "";
for (unsigned int i = 0; i < files.size(); i++) {
listDirs += files.at(i)->getName() + '\n';
}
return listDirs;
}
int FileSystem::createFile(std::string fileName)
{
dynamic_cast<Dnode*>(mWalker.getLookingAt())->addNode(new Fnode("TESTING TESTING", mWalker.getCwd(), 4, fileName, mWalker.getLookingAt()));
return 1; // Fix proper return-value.
}
int FileSystem::createImage() {
/*std::string loggedInUser = getlogin();
std::string path = "/home/" + loggedInUser + "/labb4_filesystem_image";
std::cout << loggedInUser << std::endl; // print logged in user
//std::ofstream fsImage(path, std::ios::out | std::ofstream::binary);
//std::copy(mRoot->getFiles().begin(), mRoot->getFiles().end(), std::ostreambuf_iterator<char>(fsImage));
std::ofstream fsImage(path);
std::ostream_iterator<std::string> output_iterator(fsImage, "\n");
std::copy(mRoot->getFiles().begin, mRoot->getFiles().end(), output_iterator);*/
return 1; // fix proper return value
}
int FileSystem::goToFolder(std::string dir)
{
Bnode* cdNode = findDir(dir);
if (cdNode == nullptr)
{
std::cout <<"cd: " + dir + ": Not a directory" + '\n';
}
else
{
mWalker.setLookingAt(cdNode);
mWalker.setPrev(cdNode->getDotDot());
}
return 1; // Fix proper return-value
}
Bnode* FileSystem::findDir(std::string dir)
{
std::string theDir = "";
std::vector<std::string> dirs = std::vector<std::string>();
for(unsigned int i = 0; i < dir.size(); i++)
{
if (dir[i] == '/' || i == dir.size()-1)
{
if(i == dir.size()-1)
{
theDir += dir[i];
}
dirs.push_back(theDir);
theDir = "";
}
else
theDir += dir[i];
}
/*
for(unsigned int i = 0; i < dirs.size(); i++)
{
std::string yolo = dirs[i];
std::cout << yolo + '\n';
} //FOR DEBUGGING ONLY
*/
return traverseTree(dirs, 0, mWalker.getLookingAt());
}
Bnode* FileSystem::traverseTree(std::vector<std::string> dir, int size, Bnode* theNode)
{
Bnode* returnNode = theNode;
// std::cout << "Size of dir.size(): " << dir.size() << std::endl << "Size of size: " << size << std::endl;
if(size == dir.size())
{
// std::cout << "REACHED BASE"; // DEBUGG ONLY
return returnNode;
}
else
{
if (dir[size] == "..")
{
if (theNode->getDotDot() != nullptr)
{
//std::cout << "Going back one dir" + '\n'; FOR DEBUGGING ONLY
returnNode = theNode->getDotDot();
}
}
else
{
//std::cout << dir[size] << std::endl; # FOR DEBUGGING ONLY
std::vector<Bnode*> files = dynamic_cast<Dnode*>(returnNode)->getFiles();
for(unsigned int i = 0; i < files.size(); i++)
{
if (dynamic_cast<Dnode*>(files.at(i)))
{
if(dir[size] == files.at(i)->getName())
{
//std::cout << " CHANGING DIRECTORY " + dir[size] + '\n'; //FOR DEBUGGING ONLY
returnNode = files.at(i);
break;
}
else if (i == files.size()-1)
{
size = dir.size()-1;
returnNode = nullptr;
}
}
}
}
//std::cout << "Returning: " << size+1 << std::endl << "dir.size():" << dir.size() << std::endl; // FOR DEBUGGING ONLY
return traverseTree(dir, size+1, returnNode);
}
}
<commit_msg>minor fixes<commit_after>#include "filesystem.h"
FileSystem::FileSystem() {
this->mRoot = new Dnode();
this->mWalker = Walker(this->mRoot, nullptr, "/");
this->mRoot->setPath("/");
}
FileSystem::~FileSystem() {
delete this->mRoot;
}
int FileSystem::createFolder(std::string folderName) {
dynamic_cast<Dnode*>(mWalker.getLookingAt())->addNode(new Dnode(mWalker.getLookingAt()->getPath() +
folderName + "/", 4, folderName, mWalker.getLookingAt()));
return 1; // implement proper return value
}
int FileSystem::printContents(std::string fileName) {
bool hit = false;
std::vector<Bnode*> files = dynamic_cast<Dnode*>(this->mWalker.getLookingAt())->getFiles();
for (unsigned int i = 0; i < files.size() && !hit; i++) {
if (dynamic_cast<Fnode*>(files.at(i)) && files.at(i)->getName() == fileName) {
hit = true;
std::cout << dynamic_cast<Fnode*>(files.at(i))->getData() << std::endl;
}
}
if (!hit) {
std::cout << "No such file" << std::endl;
}
return 1; // implement proper return value
}
int FileSystem::printCurrentWorkingDirectory() {
std::cout << mWalker.getLookingAt()->getPath() << std::endl;
return 1; // implement proper return value
}
int FileSystem::removeFile(std::string fileName) {
bool hit = false;
std::vector<Bnode*> files = dynamic_cast<Dnode*>(this->mWalker.getLookingAt())->getFiles();
for (unsigned int i = 0; i < files.size(); i++) {
if (files.at(i)->getName() == fileName) {
if(dynamic_cast<Fnode*>(files.at(i)))
{
hit = true;
dynamic_cast<Dnode*>(this->mWalker.getLookingAt())->removeNode(i);
}
}
}
if (!hit) {
std::cout << "No such file." << std::endl;
}
return 1; // implement proper return value
}
std::string FileSystem::listDir(std::string dir) {
// TODO: MAKE WALKER STAND ON "PARAMETER DIR" BEFORE GETTING FILE-VECTOR.
std::vector<Bnode*> files = dynamic_cast<Dnode*>(this->mWalker.getLookingAt())->getFiles();
std::string listDirs = "";
for (unsigned int i = 0; i < files.size(); i++) {
listDirs += files.at(i)->getName() + '\n';
}
return listDirs;
}
int FileSystem::createFile(std::string fileName)
{
dynamic_cast<Dnode*>(mWalker.getLookingAt())->addNode(new Fnode("TESTING TESTING", mWalker.getCwd(), 4, fileName, mWalker.getLookingAt()));
return 1; // Fix proper return-value.
}
int FileSystem::createImage() {
/*std::string loggedInUser = getlogin();
std::string path = "/home/" + loggedInUser + "/labb4_filesystem_image";
std::cout << loggedInUser << std::endl; // print logged in user
//std::ofstream fsImage(path, std::ios::out | std::ofstream::binary);
//std::copy(mRoot->getFiles().begin(), mRoot->getFiles().end(), std::ostreambuf_iterator<char>(fsImage));
std::ofstream fsImage(path);
std::ostream_iterator<std::string> output_iterator(fsImage, "\n");
std::copy(mRoot->getFiles().begin, mRoot->getFiles().end(), output_iterator);*/
return 1; // fix proper return value
}
int FileSystem::goToFolder(std::string dir)
{
Bnode* cdNode = findDir(dir);
if (cdNode == nullptr)
{
std::cout <<"cd: " + dir + ": Not a directory" + '\n';
}
else
{
mWalker.setLookingAt(cdNode);
mWalker.setPrev(cdNode->getDotDot());
}
return 1; // Fix proper return-value
}
Bnode* FileSystem::findDir(std::string dir)
{
std::string theDir = "";
std::vector<std::string> dirs = std::vector<std::string>();
for(unsigned int i = 0; i < dir.size(); i++)
{
if (dir[i] == '/' || i == dir.size()-1)
{
if(i == dir.size()-1)
{
theDir += dir[i];
}
dirs.push_back(theDir);
theDir = "";
}
else
theDir += dir[i];
}
/*
for(unsigned int i = 0; i < dirs.size(); i++)
{
std::string yolo = dirs[i];
std::cout << yolo + '\n';
} //FOR DEBUGGING ONLY
*/
return traverseTree(dirs, 0, mWalker.getLookingAt());
}
Bnode* FileSystem::traverseTree(std::vector<std::string> dir, int size, Bnode* theNode)
{
Bnode* returnNode = theNode;
// std::cout << "Size of dir.size(): " << dir.size() << std::endl << "Size of size: " << size << std::endl;
if(size == dir.size())
{
// std::cout << "REACHED BASE"; // DEBUGG ONLY
return returnNode;
}
else
{
if (dir[size] == "..")
{
if (theNode->getDotDot() != nullptr)
{
//std::cout << "Going back one dir" + '\n'; FOR DEBUGGING ONLY
returnNode = theNode->getDotDot();
}
}
else
{
//std::cout << dir[size] << std::endl; # FOR DEBUGGING ONLY
std::vector<Bnode*> files = dynamic_cast<Dnode*>(returnNode)->getFiles();
for(unsigned int i = 0; i < files.size(); i++)
{
if (dynamic_cast<Dnode*>(files.at(i)))
{
if(dir[size] == files.at(i)->getName())
{
//std::cout << " CHANGING DIRECTORY " + dir[size] + '\n'; //FOR DEBUGGING ONLY
returnNode = files.at(i);
break;
}
else if (i == files.size()-1)
{
size = dir.size()-1;
returnNode = nullptr;
}
}
}
}
//std::cout << "Returning: " << size+1 << std::endl << "dir.size():" << dir.size() << std::endl; // FOR DEBUGGING ONLY
return traverseTree(dir, size+1, returnNode);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************/
/* material_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "material_editor_plugin.h"
#include "editor/editor_scale.h"
#include "scene/gui/viewport_container.h"
#include "scene/resources/particles_material.h"
void MaterialEditor::_notification(int p_what) {
if (p_what == NOTIFICATION_READY) {
//get_scene()->connect("node_removed",this,"_node_removed");
if (first_enter) {
//it's in propertyeditor so.. could be moved around
light_1_switch->set_normal_texture(get_icon("MaterialPreviewLight1", "EditorIcons"));
light_1_switch->set_pressed_texture(get_icon("MaterialPreviewLight1Off", "EditorIcons"));
light_2_switch->set_normal_texture(get_icon("MaterialPreviewLight2", "EditorIcons"));
light_2_switch->set_pressed_texture(get_icon("MaterialPreviewLight2Off", "EditorIcons"));
sphere_switch->set_normal_texture(get_icon("MaterialPreviewSphereOff", "EditorIcons"));
sphere_switch->set_pressed_texture(get_icon("MaterialPreviewSphere", "EditorIcons"));
box_switch->set_normal_texture(get_icon("MaterialPreviewCubeOff", "EditorIcons"));
box_switch->set_pressed_texture(get_icon("MaterialPreviewCube", "EditorIcons"));
first_enter = false;
}
}
if (p_what == NOTIFICATION_DRAW) {
Ref<Texture> checkerboard = get_icon("Checkerboard", "EditorIcons");
Size2 size = get_size();
draw_texture_rect(checkerboard, Rect2(Point2(), size), true);
}
}
void MaterialEditor::edit(Ref<Material> p_material, const Ref<Environment> &p_env) {
material = p_material;
camera->set_environment(p_env);
if (!material.is_null()) {
sphere_instance->set_material_override(material);
box_instance->set_material_override(material);
} else {
hide();
}
}
void MaterialEditor::_button_pressed(Node *p_button) {
if (p_button == light_1_switch) {
light1->set_visible(!light_1_switch->is_pressed());
}
if (p_button == light_2_switch) {
light2->set_visible(!light_2_switch->is_pressed());
}
if (p_button == box_switch) {
box_instance->show();
sphere_instance->hide();
box_switch->set_pressed(true);
sphere_switch->set_pressed(false);
EditorSettings::get_singleton()->set_project_metadata("inspector_options", "material_preview_on_sphere", false);
}
if (p_button == sphere_switch) {
box_instance->hide();
sphere_instance->show();
box_switch->set_pressed(false);
sphere_switch->set_pressed(true);
EditorSettings::get_singleton()->set_project_metadata("inspector_options", "material_preview_on_sphere", true);
}
}
void MaterialEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_button_pressed"), &MaterialEditor::_button_pressed);
}
MaterialEditor::MaterialEditor() {
vc = memnew(ViewportContainer);
vc->set_stretch(true);
add_child(vc);
vc->set_anchors_and_margins_preset(PRESET_WIDE);
viewport = memnew(Viewport);
Ref<World> world;
world.instance();
viewport->set_world(world); //use own world
vc->add_child(viewport);
viewport->set_disable_input(true);
viewport->set_transparent_background(true);
viewport->set_msaa(Viewport::MSAA_4X);
camera = memnew(Camera);
camera->set_transform(Transform(Basis(), Vector3(0, 0, 3)));
camera->set_perspective(45, 0.1, 10);
camera->make_current();
viewport->add_child(camera);
light1 = memnew(DirectionalLight);
light1->set_transform(Transform().looking_at(Vector3(-1, -1, -1), Vector3(0, 1, 0)));
viewport->add_child(light1);
light2 = memnew(DirectionalLight);
light2->set_transform(Transform().looking_at(Vector3(0, 1, 0), Vector3(0, 0, 1)));
light2->set_color(Color(0.7, 0.7, 0.7));
viewport->add_child(light2);
sphere_instance = memnew(MeshInstance);
viewport->add_child(sphere_instance);
box_instance = memnew(MeshInstance);
viewport->add_child(box_instance);
Transform box_xform;
box_xform.basis.rotate(Vector3(1, 0, 0), Math::deg2rad(25.0));
box_xform.basis = box_xform.basis * Basis().rotated(Vector3(0, 1, 0), Math::deg2rad(-25.0));
box_xform.basis.scale(Vector3(0.8, 0.8, 0.8));
box_xform.origin.y = 0.2;
box_instance->set_transform(box_xform);
sphere_mesh.instance();
sphere_instance->set_mesh(sphere_mesh);
box_mesh.instance();
box_instance->set_mesh(box_mesh);
set_custom_minimum_size(Size2(1, 150) * EDSCALE);
HBoxContainer *hb = memnew(HBoxContainer);
add_child(hb);
hb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 2);
VBoxContainer *vb_shape = memnew(VBoxContainer);
hb->add_child(vb_shape);
sphere_switch = memnew(TextureButton);
sphere_switch->set_toggle_mode(true);
sphere_switch->set_pressed(true);
vb_shape->add_child(sphere_switch);
sphere_switch->connect("pressed", this, "_button_pressed", varray(sphere_switch));
box_switch = memnew(TextureButton);
box_switch->set_toggle_mode(true);
box_switch->set_pressed(false);
vb_shape->add_child(box_switch);
box_switch->connect("pressed", this, "_button_pressed", varray(box_switch));
hb->add_spacer();
VBoxContainer *vb_light = memnew(VBoxContainer);
hb->add_child(vb_light);
light_1_switch = memnew(TextureButton);
light_1_switch->set_toggle_mode(true);
vb_light->add_child(light_1_switch);
light_1_switch->connect("pressed", this, "_button_pressed", varray(light_1_switch));
light_2_switch = memnew(TextureButton);
light_2_switch->set_toggle_mode(true);
vb_light->add_child(light_2_switch);
light_2_switch->connect("pressed", this, "_button_pressed", varray(light_2_switch));
first_enter = true;
if (EditorSettings::get_singleton()->get_project_metadata("inspector_options", "material_preview_on_sphere", true)) {
box_instance->hide();
} else {
box_instance->show();
sphere_instance->hide();
box_switch->set_pressed(true);
sphere_switch->set_pressed(false);
}
}
///////////////////////
bool EditorInspectorPluginMaterial::can_handle(Object *p_object) {
Material *material = Object::cast_to<Material>(p_object);
if (!material) {
return false;
}
return material->get_shader_mode() == Shader::MODE_SPATIAL;
}
void EditorInspectorPluginMaterial::parse_begin(Object *p_object) {
Material *material = Object::cast_to<Material>(p_object);
if (!material) {
return;
}
Ref<Material> m(material);
MaterialEditor *editor = memnew(MaterialEditor);
editor->edit(m, env);
add_custom_control(editor);
}
EditorInspectorPluginMaterial::EditorInspectorPluginMaterial() {
env.instance();
Ref<ProceduralSky> proc_sky = memnew(ProceduralSky(true));
env->set_sky(proc_sky);
env->set_background(Environment::BG_COLOR_SKY);
}
MaterialEditorPlugin::MaterialEditorPlugin(EditorNode *p_node) {
Ref<EditorInspectorPluginMaterial> plugin;
plugin.instance();
add_inspector_plugin(plugin);
}
String SpatialMaterialConversionPlugin::converts_to() const {
return "ShaderMaterial";
}
bool SpatialMaterialConversionPlugin::handles(const Ref<Resource> &p_resource) const {
Ref<SpatialMaterial> mat = p_resource;
return mat.is_valid();
}
Ref<Resource> SpatialMaterialConversionPlugin::convert(const Ref<Resource> &p_resource) const {
Ref<SpatialMaterial> mat = p_resource;
ERR_FAIL_COND_V(!mat.is_valid(), Ref<Resource>());
Ref<ShaderMaterial> smat;
smat.instance();
Ref<Shader> shader;
shader.instance();
String code = VS::get_singleton()->shader_get_code(mat->get_shader_rid());
shader->set_code(code);
smat->set_shader(shader);
List<PropertyInfo> params;
VS::get_singleton()->shader_get_param_list(mat->get_shader_rid(), ¶ms);
for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) {
// Texture parameter has to be treated specially since SpatialMaterial saved it
// as RID but ShaderMaterial needs Texture itself
Ref<Texture> texture = mat->get_texture_by_name(E->get().name);
if (texture.is_valid()) {
smat->set_shader_param(E->get().name, texture);
} else {
Variant value = VS::get_singleton()->material_get_param(mat->get_rid(), E->get().name);
smat->set_shader_param(E->get().name, value);
}
}
smat->set_render_priority(mat->get_render_priority());
return smat;
}
String ParticlesMaterialConversionPlugin::converts_to() const {
return "ShaderMaterial";
}
bool ParticlesMaterialConversionPlugin::handles(const Ref<Resource> &p_resource) const {
Ref<ParticlesMaterial> mat = p_resource;
return mat.is_valid();
}
Ref<Resource> ParticlesMaterialConversionPlugin::convert(const Ref<Resource> &p_resource) const {
Ref<ParticlesMaterial> mat = p_resource;
ERR_FAIL_COND_V(!mat.is_valid(), Ref<Resource>());
Ref<ShaderMaterial> smat;
smat.instance();
Ref<Shader> shader;
shader.instance();
String code = VS::get_singleton()->shader_get_code(mat->get_shader_rid());
shader->set_code(code);
smat->set_shader(shader);
List<PropertyInfo> params;
VS::get_singleton()->shader_get_param_list(mat->get_shader_rid(), ¶ms);
for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) {
Variant value = VS::get_singleton()->material_get_param(mat->get_rid(), E->get().name);
smat->set_shader_param(E->get().name, value);
}
smat->set_render_priority(mat->get_render_priority());
return smat;
}
String CanvasItemMaterialConversionPlugin::converts_to() const {
return "ShaderMaterial";
}
bool CanvasItemMaterialConversionPlugin::handles(const Ref<Resource> &p_resource) const {
Ref<CanvasItemMaterial> mat = p_resource;
return mat.is_valid();
}
Ref<Resource> CanvasItemMaterialConversionPlugin::convert(const Ref<Resource> &p_resource) const {
Ref<CanvasItemMaterial> mat = p_resource;
ERR_FAIL_COND_V(!mat.is_valid(), Ref<Resource>());
Ref<ShaderMaterial> smat;
smat.instance();
Ref<Shader> shader;
shader.instance();
String code = VS::get_singleton()->shader_get_code(mat->get_shader_rid());
shader->set_code(code);
smat->set_shader(shader);
List<PropertyInfo> params;
VS::get_singleton()->shader_get_param_list(mat->get_shader_rid(), ¶ms);
for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) {
Variant value = VS::get_singleton()->material_get_param(mat->get_rid(), E->get().name);
smat->set_shader_param(E->get().name, value);
}
smat->set_render_priority(mat->get_render_priority());
return smat;
}
<commit_msg>Conversion now includes "Local to scene" flag and name<commit_after>/*************************************************************************/
/* material_editor_plugin.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* 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 "material_editor_plugin.h"
#include "editor/editor_scale.h"
#include "scene/gui/viewport_container.h"
#include "scene/resources/particles_material.h"
void MaterialEditor::_notification(int p_what) {
if (p_what == NOTIFICATION_READY) {
//get_scene()->connect("node_removed",this,"_node_removed");
if (first_enter) {
//it's in propertyeditor so.. could be moved around
light_1_switch->set_normal_texture(get_icon("MaterialPreviewLight1", "EditorIcons"));
light_1_switch->set_pressed_texture(get_icon("MaterialPreviewLight1Off", "EditorIcons"));
light_2_switch->set_normal_texture(get_icon("MaterialPreviewLight2", "EditorIcons"));
light_2_switch->set_pressed_texture(get_icon("MaterialPreviewLight2Off", "EditorIcons"));
sphere_switch->set_normal_texture(get_icon("MaterialPreviewSphereOff", "EditorIcons"));
sphere_switch->set_pressed_texture(get_icon("MaterialPreviewSphere", "EditorIcons"));
box_switch->set_normal_texture(get_icon("MaterialPreviewCubeOff", "EditorIcons"));
box_switch->set_pressed_texture(get_icon("MaterialPreviewCube", "EditorIcons"));
first_enter = false;
}
}
if (p_what == NOTIFICATION_DRAW) {
Ref<Texture> checkerboard = get_icon("Checkerboard", "EditorIcons");
Size2 size = get_size();
draw_texture_rect(checkerboard, Rect2(Point2(), size), true);
}
}
void MaterialEditor::edit(Ref<Material> p_material, const Ref<Environment> &p_env) {
material = p_material;
camera->set_environment(p_env);
if (!material.is_null()) {
sphere_instance->set_material_override(material);
box_instance->set_material_override(material);
} else {
hide();
}
}
void MaterialEditor::_button_pressed(Node *p_button) {
if (p_button == light_1_switch) {
light1->set_visible(!light_1_switch->is_pressed());
}
if (p_button == light_2_switch) {
light2->set_visible(!light_2_switch->is_pressed());
}
if (p_button == box_switch) {
box_instance->show();
sphere_instance->hide();
box_switch->set_pressed(true);
sphere_switch->set_pressed(false);
EditorSettings::get_singleton()->set_project_metadata("inspector_options", "material_preview_on_sphere", false);
}
if (p_button == sphere_switch) {
box_instance->hide();
sphere_instance->show();
box_switch->set_pressed(false);
sphere_switch->set_pressed(true);
EditorSettings::get_singleton()->set_project_metadata("inspector_options", "material_preview_on_sphere", true);
}
}
void MaterialEditor::_bind_methods() {
ClassDB::bind_method(D_METHOD("_button_pressed"), &MaterialEditor::_button_pressed);
}
MaterialEditor::MaterialEditor() {
vc = memnew(ViewportContainer);
vc->set_stretch(true);
add_child(vc);
vc->set_anchors_and_margins_preset(PRESET_WIDE);
viewport = memnew(Viewport);
Ref<World> world;
world.instance();
viewport->set_world(world); //use own world
vc->add_child(viewport);
viewport->set_disable_input(true);
viewport->set_transparent_background(true);
viewport->set_msaa(Viewport::MSAA_4X);
camera = memnew(Camera);
camera->set_transform(Transform(Basis(), Vector3(0, 0, 3)));
camera->set_perspective(45, 0.1, 10);
camera->make_current();
viewport->add_child(camera);
light1 = memnew(DirectionalLight);
light1->set_transform(Transform().looking_at(Vector3(-1, -1, -1), Vector3(0, 1, 0)));
viewport->add_child(light1);
light2 = memnew(DirectionalLight);
light2->set_transform(Transform().looking_at(Vector3(0, 1, 0), Vector3(0, 0, 1)));
light2->set_color(Color(0.7, 0.7, 0.7));
viewport->add_child(light2);
sphere_instance = memnew(MeshInstance);
viewport->add_child(sphere_instance);
box_instance = memnew(MeshInstance);
viewport->add_child(box_instance);
Transform box_xform;
box_xform.basis.rotate(Vector3(1, 0, 0), Math::deg2rad(25.0));
box_xform.basis = box_xform.basis * Basis().rotated(Vector3(0, 1, 0), Math::deg2rad(-25.0));
box_xform.basis.scale(Vector3(0.8, 0.8, 0.8));
box_xform.origin.y = 0.2;
box_instance->set_transform(box_xform);
sphere_mesh.instance();
sphere_instance->set_mesh(sphere_mesh);
box_mesh.instance();
box_instance->set_mesh(box_mesh);
set_custom_minimum_size(Size2(1, 150) * EDSCALE);
HBoxContainer *hb = memnew(HBoxContainer);
add_child(hb);
hb->set_anchors_and_margins_preset(Control::PRESET_WIDE, Control::PRESET_MODE_MINSIZE, 2);
VBoxContainer *vb_shape = memnew(VBoxContainer);
hb->add_child(vb_shape);
sphere_switch = memnew(TextureButton);
sphere_switch->set_toggle_mode(true);
sphere_switch->set_pressed(true);
vb_shape->add_child(sphere_switch);
sphere_switch->connect("pressed", this, "_button_pressed", varray(sphere_switch));
box_switch = memnew(TextureButton);
box_switch->set_toggle_mode(true);
box_switch->set_pressed(false);
vb_shape->add_child(box_switch);
box_switch->connect("pressed", this, "_button_pressed", varray(box_switch));
hb->add_spacer();
VBoxContainer *vb_light = memnew(VBoxContainer);
hb->add_child(vb_light);
light_1_switch = memnew(TextureButton);
light_1_switch->set_toggle_mode(true);
vb_light->add_child(light_1_switch);
light_1_switch->connect("pressed", this, "_button_pressed", varray(light_1_switch));
light_2_switch = memnew(TextureButton);
light_2_switch->set_toggle_mode(true);
vb_light->add_child(light_2_switch);
light_2_switch->connect("pressed", this, "_button_pressed", varray(light_2_switch));
first_enter = true;
if (EditorSettings::get_singleton()->get_project_metadata("inspector_options", "material_preview_on_sphere", true)) {
box_instance->hide();
} else {
box_instance->show();
sphere_instance->hide();
box_switch->set_pressed(true);
sphere_switch->set_pressed(false);
}
}
///////////////////////
bool EditorInspectorPluginMaterial::can_handle(Object *p_object) {
Material *material = Object::cast_to<Material>(p_object);
if (!material) {
return false;
}
return material->get_shader_mode() == Shader::MODE_SPATIAL;
}
void EditorInspectorPluginMaterial::parse_begin(Object *p_object) {
Material *material = Object::cast_to<Material>(p_object);
if (!material) {
return;
}
Ref<Material> m(material);
MaterialEditor *editor = memnew(MaterialEditor);
editor->edit(m, env);
add_custom_control(editor);
}
EditorInspectorPluginMaterial::EditorInspectorPluginMaterial() {
env.instance();
Ref<ProceduralSky> proc_sky = memnew(ProceduralSky(true));
env->set_sky(proc_sky);
env->set_background(Environment::BG_COLOR_SKY);
}
MaterialEditorPlugin::MaterialEditorPlugin(EditorNode *p_node) {
Ref<EditorInspectorPluginMaterial> plugin;
plugin.instance();
add_inspector_plugin(plugin);
}
String SpatialMaterialConversionPlugin::converts_to() const {
return "ShaderMaterial";
}
bool SpatialMaterialConversionPlugin::handles(const Ref<Resource> &p_resource) const {
Ref<SpatialMaterial> mat = p_resource;
return mat.is_valid();
}
Ref<Resource> SpatialMaterialConversionPlugin::convert(const Ref<Resource> &p_resource) const {
Ref<SpatialMaterial> mat = p_resource;
ERR_FAIL_COND_V(!mat.is_valid(), Ref<Resource>());
Ref<ShaderMaterial> smat;
smat.instance();
Ref<Shader> shader;
shader.instance();
String code = VS::get_singleton()->shader_get_code(mat->get_shader_rid());
shader->set_code(code);
smat->set_shader(shader);
List<PropertyInfo> params;
VS::get_singleton()->shader_get_param_list(mat->get_shader_rid(), ¶ms);
for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) {
// Texture parameter has to be treated specially since SpatialMaterial saved it
// as RID but ShaderMaterial needs Texture itself
Ref<Texture> texture = mat->get_texture_by_name(E->get().name);
if (texture.is_valid()) {
smat->set_shader_param(E->get().name, texture);
} else {
Variant value = VS::get_singleton()->material_get_param(mat->get_rid(), E->get().name);
smat->set_shader_param(E->get().name, value);
}
}
smat->set_render_priority(mat->get_render_priority());
smat->set_local_to_scene(mat->is_local_to_scene());
smat->set_name(mat->get_name());
return smat;
}
String ParticlesMaterialConversionPlugin::converts_to() const {
return "ShaderMaterial";
}
bool ParticlesMaterialConversionPlugin::handles(const Ref<Resource> &p_resource) const {
Ref<ParticlesMaterial> mat = p_resource;
return mat.is_valid();
}
Ref<Resource> ParticlesMaterialConversionPlugin::convert(const Ref<Resource> &p_resource) const {
Ref<ParticlesMaterial> mat = p_resource;
ERR_FAIL_COND_V(!mat.is_valid(), Ref<Resource>());
Ref<ShaderMaterial> smat;
smat.instance();
Ref<Shader> shader;
shader.instance();
String code = VS::get_singleton()->shader_get_code(mat->get_shader_rid());
shader->set_code(code);
smat->set_shader(shader);
List<PropertyInfo> params;
VS::get_singleton()->shader_get_param_list(mat->get_shader_rid(), ¶ms);
for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) {
Variant value = VS::get_singleton()->material_get_param(mat->get_rid(), E->get().name);
smat->set_shader_param(E->get().name, value);
}
smat->set_render_priority(mat->get_render_priority());
smat->set_local_to_scene(mat->is_local_to_scene());
smat->set_name(mat->get_name());
return smat;
}
String CanvasItemMaterialConversionPlugin::converts_to() const {
return "ShaderMaterial";
}
bool CanvasItemMaterialConversionPlugin::handles(const Ref<Resource> &p_resource) const {
Ref<CanvasItemMaterial> mat = p_resource;
return mat.is_valid();
}
Ref<Resource> CanvasItemMaterialConversionPlugin::convert(const Ref<Resource> &p_resource) const {
Ref<CanvasItemMaterial> mat = p_resource;
ERR_FAIL_COND_V(!mat.is_valid(), Ref<Resource>());
Ref<ShaderMaterial> smat;
smat.instance();
Ref<Shader> shader;
shader.instance();
String code = VS::get_singleton()->shader_get_code(mat->get_shader_rid());
shader->set_code(code);
smat->set_shader(shader);
List<PropertyInfo> params;
VS::get_singleton()->shader_get_param_list(mat->get_shader_rid(), ¶ms);
for (List<PropertyInfo>::Element *E = params.front(); E; E = E->next()) {
Variant value = VS::get_singleton()->material_get_param(mat->get_rid(), E->get().name);
smat->set_shader_param(E->get().name, value);
}
smat->set_render_priority(mat->get_render_priority());
smat->set_local_to_scene(mat->is_local_to_scene());
smat->set_name(mat->get_name());
return smat;
}
<|endoftext|> |
<commit_before><commit_msg>Fix miscalculation of debug vertex buffer size<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: Style.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: obo $ $Date: 2006-09-17 13:14:39 $
*
* 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_chart2.hxx"
#include "Style.hxx"
#include "macros.hxx"
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XNAMECONTAINER_HPP_
#include <com/sun/star/container/XNameContainer.hpp>
#endif
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::rtl::OUString;
using ::osl::MutexGuard;
// necessary for MS compiler
using ::comphelper::OPropertyContainer;
using ::chart::impl::Style_Base;
namespace
{
static const ::rtl::OUString lcl_aImplName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.chart.Style" ));
} // anonymous namespace
namespace chart
{
Style::Style( const Reference< container::XNameContainer > & xStyleFamiliyToAddTo ) :
OPropertyContainer( GetBroadcastHelper()),
Style_Base( GetMutex()),
m_xStyleFamily( xStyleFamiliyToAddTo ),
m_aName( C2U( "Default" ) ),
m_bUserDefined( sal_False )
{
OSL_ENSURE( m_xStyleFamily.is(), "No StyleFamily to add style to" );
}
Style::~Style()
{}
sal_Bool SAL_CALL Style::isUserDefined()
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
return m_bUserDefined;
// \--
}
sal_Bool SAL_CALL Style::isInUse()
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
// aBoundLC is a member of cppuhelper::OPropertySetHelper
// it is assumed that a style is in use whenever some component is
// registered here as listener
return ( aBoundLC.getContainedTypes().getLength() > 0 );
// \--
}
OUString SAL_CALL Style::getParentStyle()
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
return m_aParentStyleName;
// \--
}
void SAL_CALL Style::setParentStyle( const OUString& aParentStyle )
throw (container::NoSuchElementException,
RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
m_aParentStyleName = aParentStyle;
// \--
}
OUString SAL_CALL Style::getName()
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
return m_aName;
// \--
}
void SAL_CALL Style::setName( const OUString& aName )
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
OSL_ASSERT( m_xStyleFamily.is());
if( m_xStyleFamily.is() )
{
// remove old name
if( m_aName.getLength() > 0 )
{
Reference< container::XNameAccess > xAccess( m_xStyleFamily, uno::UNO_QUERY );
OSL_ASSERT( xAccess.is());
if( xAccess->hasByName( m_aName ))
m_xStyleFamily->removeByName( m_aName );
}
// change name
m_aName = aName;
// add new name
m_xStyleFamily->insertByName( m_aName, uno::makeAny( this ));
}
// \--
}
IMPLEMENT_FORWARD_XINTERFACE2( Style, Style_Base, OPropertyContainer )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( Style, Style_Base, OPropertyContainer )
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( Style, lcl_aImplName )
uno::Sequence< OUString > Style::getSupportedServiceNames_Static()
{
uno::Sequence< OUString > aServices( 1 );
aServices[ 0 ] = C2U( "com.sun.star.style.Style" );
return aServices;
}
} // namespace chart
<commit_msg>INTEGRATION: CWS changefileheader (1.3.170); FILE MERGED 2008/04/01 10:50:33 thb 1.3.170.2: #i85898# Stripping all external header guards 2008/03/28 16:44:09 rt 1.3.170.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: Style.cxx,v $
* $Revision: 1.4 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_chart2.hxx"
#include "Style.hxx"
#include "macros.hxx"
#include <com/sun/star/beans/PropertyAttribute.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
using namespace ::com::sun::star;
using ::com::sun::star::uno::Reference;
using ::com::sun::star::uno::RuntimeException;
using ::rtl::OUString;
using ::osl::MutexGuard;
// necessary for MS compiler
using ::comphelper::OPropertyContainer;
using ::chart::impl::Style_Base;
namespace
{
static const ::rtl::OUString lcl_aImplName(
RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.chart.Style" ));
} // anonymous namespace
namespace chart
{
Style::Style( const Reference< container::XNameContainer > & xStyleFamiliyToAddTo ) :
OPropertyContainer( GetBroadcastHelper()),
Style_Base( GetMutex()),
m_xStyleFamily( xStyleFamiliyToAddTo ),
m_aName( C2U( "Default" ) ),
m_bUserDefined( sal_False )
{
OSL_ENSURE( m_xStyleFamily.is(), "No StyleFamily to add style to" );
}
Style::~Style()
{}
sal_Bool SAL_CALL Style::isUserDefined()
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
return m_bUserDefined;
// \--
}
sal_Bool SAL_CALL Style::isInUse()
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
// aBoundLC is a member of cppuhelper::OPropertySetHelper
// it is assumed that a style is in use whenever some component is
// registered here as listener
return ( aBoundLC.getContainedTypes().getLength() > 0 );
// \--
}
OUString SAL_CALL Style::getParentStyle()
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
return m_aParentStyleName;
// \--
}
void SAL_CALL Style::setParentStyle( const OUString& aParentStyle )
throw (container::NoSuchElementException,
RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
m_aParentStyleName = aParentStyle;
// \--
}
OUString SAL_CALL Style::getName()
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
return m_aName;
// \--
}
void SAL_CALL Style::setName( const OUString& aName )
throw (RuntimeException)
{
// /--
MutexGuard aGuard( GetMutex() );
OSL_ASSERT( m_xStyleFamily.is());
if( m_xStyleFamily.is() )
{
// remove old name
if( m_aName.getLength() > 0 )
{
Reference< container::XNameAccess > xAccess( m_xStyleFamily, uno::UNO_QUERY );
OSL_ASSERT( xAccess.is());
if( xAccess->hasByName( m_aName ))
m_xStyleFamily->removeByName( m_aName );
}
// change name
m_aName = aName;
// add new name
m_xStyleFamily->insertByName( m_aName, uno::makeAny( this ));
}
// \--
}
IMPLEMENT_FORWARD_XINTERFACE2( Style, Style_Base, OPropertyContainer )
IMPLEMENT_FORWARD_XTYPEPROVIDER2( Style, Style_Base, OPropertyContainer )
// implement XServiceInfo methods basing upon getSupportedServiceNames_Static
APPHELPER_XSERVICEINFO_IMPL( Style, lcl_aImplName )
uno::Sequence< OUString > Style::getSupportedServiceNames_Static()
{
uno::Sequence< OUString > aServices( 1 );
aServices[ 0 ] = C2U( "com.sun.star.style.Style" );
return aServices;
}
} // namespace chart
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdlib>
#include <cstring>
#include <ctime>
#include "../Configuration/Common.h"
#include "../Debug/Assertions.h"
#include "DateTime.h"
#include "Timezone.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
bool Time::IsDaylightSavingsTime ()
{
static bool sCalledOnce_ = false;
if (not sCalledOnce_) {
tzset ();
sCalledOnce_ = true;
}
return !!daylight;
}
bool Time::IsDaylightSavingsTime (const DateTime& d)
{
struct tm asTM = d.As<struct tm> ();
asTM.tm_isdst = -1; // force calc of correct daylight savings time flag
// THINK this is true - not totally clear - docs on mktime () don't specify unambiguously that this should work...
// So far it seems too however, --LGP 2011-10-15
time_t result = mktime (&asTM);
return asTM.tm_isdst >= 1;
}
time_t Time::GetLocaltimeToGMTOffset (bool applyDST)
{
#if 0
// WRONG - but COULD use this API - but not sure needed
#if qPlatform_Windows
TIME_ZONE_INFORMATION tzInfo;
memset (&tzInfo, 0, sizeof (tzInfo));
(void)::GetTimeZoneInformation (&tzInfo);
int unsignedBias = abs (tzInfo.Bias);
int hrs = unsignedBias / 60;
int mins = unsignedBias - hrs * 60;
tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0? L"-": L"+"), hrs, mins);
#endif
#endif
/*
* COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the
* timezone global var???
*/
struct tm tm;
memset (&tm, 0, sizeof(tm));
tm.tm_year = 70;
tm.tm_mon = 0; // Jan
tm.tm_mday = 1;
tm.tm_isdst = applyDST;
time_t result = mktime (&tm);
return result;
}
<commit_msg>Silence some msvc compiler warnings<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#include "../StroikaPreComp.h"
#include <cstdlib>
#include <cstring>
#include <ctime>
#include "../Configuration/Common.h"
#include "../Debug/Assertions.h"
#include "DateTime.h"
#include "Timezone.h"
using namespace Stroika;
using namespace Stroika::Foundation;
using namespace Stroika::Foundation::Time;
bool Time::IsDaylightSavingsTime ()
{
static bool sCalledOnce_ = false;
if (not sCalledOnce_) {
#pragma warning (push)
#pragma warning (4 : 4996) // MSVC warns tzset() unsafe, but I think the way I use it will be safe
tzset ();
#pragma warning (pop)
sCalledOnce_ = true;
}
#pragma warning (push)
#pragma warning (4 : 4996) // Not great use - but SB OK - I think - at least for now -- LGP 2011-11-02
return !!daylight;
#pragma warning (pop)
}
bool Time::IsDaylightSavingsTime (const DateTime& d)
{
struct tm asTM = d.As<struct tm> ();
asTM.tm_isdst = -1; // force calc of correct daylight savings time flag
// THINK this is true - not totally clear - docs on mktime () don't specify unambiguously that this should work...
// So far it seems too however, --LGP 2011-10-15
time_t result = mktime (&asTM);
return asTM.tm_isdst >= 1;
}
time_t Time::GetLocaltimeToGMTOffset (bool applyDST)
{
#if 0
// WRONG - but COULD use this API - but not sure needed
#if qPlatform_Windows
TIME_ZONE_INFORMATION tzInfo;
memset (&tzInfo, 0, sizeof (tzInfo));
(void)::GetTimeZoneInformation (&tzInfo);
int unsignedBias = abs (tzInfo.Bias);
int hrs = unsignedBias / 60;
int mins = unsignedBias - hrs * 60;
tzBiasString = ::Format (L"%s%.2d:%.2d", (tzInfo.Bias >= 0? L"-": L"+"), hrs, mins);
#endif
#endif
/*
* COULD this be cached? It SHOULD be - but what about when the timezone changes? there maybe a better way to compute this using the
* timezone global var???
*/
struct tm tm;
memset (&tm, 0, sizeof(tm));
tm.tm_year = 70;
tm.tm_mon = 0; // Jan
tm.tm_mday = 1;
tm.tm_isdst = applyDST;
time_t result = mktime (&tm);
return result;
}
<|endoftext|> |
<commit_before>// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
#ifdef HAVE_CONFIG_H
# include <oce-config.h>
#endif
#ifndef WNT
#include <Standard_NullObject.hxx>
#include <Standard_ConstructionError.hxx>
#include <OSD_Host.ixx>
#include <OSD_WhoAmI.hxx>
const OSD_WhoAmI Iam = OSD_WHost;
#include <errno.h>
#ifdef HAVE_SYS_UTSNAME_H
# include <sys/utsname.h> // For 'uname'
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h> // This is for 'gethostbyname'
#endif
#include <stdio.h>
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#if defined(__osf__) || defined(DECOSF1)
#include <sys/types.h>
#include <sys/sysinfo.h> // For 'getsysinfo'
#include <sys/socket.h> // To get ethernet address
#include <sys/ioctl.h>
#include <net/if.h>
extern "C" {
int gethostname(char* address, int len);
}
#endif
#ifdef HAVE_SYSENT_H
# include <sysent.h> // for 'gethostname'
#endif
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_SYS_UNISTD_H
# include <sys/unistd.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_SYSTEMINFO_H
# include <sys/systeminfo.h>
#endif
extern "C" {int sysinfo(int, char *, long);}
// =========================================================================
OSD_Host::OSD_Host(){}
// =========================================================================
TCollection_AsciiString OSD_Host::SystemVersion(){
struct utsname info;
TCollection_AsciiString result;
#ifdef HAVE_SYS_SYSTEMINFO_H
char buf[100];
#endif
uname (&info);
result = info.sysname;
result += " ";
result += info.release;
#ifdef HAVE_SYS_SYSTEMINFO_H
result += " ";
sysinfo(SI_ARCHITECTURE,buf,99);
result += buf;
result += " ";
sysinfo(SI_HW_PROVIDER,buf,99);
result += buf;
#endif
return(result);
}
// =========================================================================
OSD_SysType OSD_Host::SystemId()const{
struct utsname info;
uname (&info);
if (!strcmp(info.sysname,"SunOS")) return (OSD_UnixBSD);
if (!strcmp(info.sysname,"ULTRIX")) return (OSD_UnixBSD);
if (!strcmp(info.sysname,"FreeBSD")) return (OSD_UnixBSD);
if (!strncmp(info.sysname,"Linux",5)) return (OSD_LinuxREDHAT);
if (!strncmp(info.sysname,"IRIX", 4)) return (OSD_UnixSystemV);
if (!strncmp(info.sysname,"OSF", 3)) return (OSD_OSF);
if (!strcmp(info.sysname,"AIX")) return (OSD_Aix);
if (!strcmp(info.sysname,"UNIX_System_V")) return (OSD_UnixSystemV);
if (!strcmp(info.sysname,"VMS_POSIX")) return (OSD_VMS);
if (!strcmp(info.sysname,"Darwin")) return (OSD_MacOs);
return (OSD_Unknown);
}
// =========================================================================
TCollection_AsciiString OSD_Host::HostName(){
TCollection_AsciiString result;
char value[65];
int status;
status = gethostname(value, 64);
if (status == -1) myError.SetValue(errno, Iam, "Host Name");
result = value;
return(result);
}
// =========================================================================
Standard_Integer OSD_Host::AvailableMemory(){
Standard_Integer result;
#if defined(__osf__) || defined(DECOSF1)
char buffer[16];
//// result = getsysinfo(GSI_PHYSMEM,buffer, 16,0,NULL);
if (result != -1)
result *= 1024;
#else
result = 0;
//@@ A faire
#endif
return (result);
}
// =========================================================================
TCollection_AsciiString OSD_Host::InternetAddress(){
struct hostent internet_address;
int a,b,c,d;
char buffer[16];
TCollection_AsciiString result,host;
host = HostName();
memcpy(&internet_address,
gethostbyname(host.ToCString()),
sizeof(struct hostent));
// Gets each bytes into integers
a = (unsigned char)internet_address.h_addr_list[0][0];
b = (unsigned char)internet_address.h_addr_list[0][1];
c = (unsigned char)internet_address.h_addr_list[0][2];
d = (unsigned char)internet_address.h_addr_list[0][3];
sprintf(buffer,"%d.%d.%d.%d",a,b,c,d);
result = buffer;
return(result);
}
// =========================================================================
OSD_OEMType OSD_Host::MachineType(){
struct utsname info;
uname (&info);
if (!strcmp(info.sysname,"SunOS")) return (OSD_SUN);
if (!strcmp(info.sysname,"ULTRIX")) return (OSD_DEC);
if (!strncmp(info.sysname,"IRIX",4)) return (OSD_SGI);
if (!strcmp(info.sysname,"HP-UX")) return (OSD_HP);
if (!strcmp(info.sysname,"UNIX_System_V")) return (OSD_NEC);
if (!strcmp(info.sysname,"VMS_POSIX")) return (OSD_VAX);
if (!strncmp(info.sysname,"OSF",3)) return (OSD_DEC);
if (!strncmp(info.sysname,"Linux",5)) return (OSD_LIN);
if (!strcmp(info.sysname,"FreeBSD")) return (OSD_LIN);
if (!strncmp(info.sysname,"AIX",3)) return (OSD_AIX);
if (!strcmp(info.sysname,"Darwin")) return (OSD_MAC);
return (OSD_Unavailable);
}
void OSD_Host::Reset(){
myError.Reset();
}
Standard_Boolean OSD_Host::Failed()const{
return( myError.Failed());
}
void OSD_Host::Perror() {
myError.Perror();
}
Standard_Integer OSD_Host::Error()const{
return( myError.Error());
}
#else
//------------------------------------------------------------------------
//------------------- WNT Sources of OSD_Host ---------------------------
//------------------------------------------------------------------------
#define STRICT
#include <windows.h>
#include <OSD_Host.hxx>
#ifdef _MSC_VER
#pragma comment( lib, "WSOCK32.LIB" )
#endif
void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
static BOOL fInit = FALSE;
static TCollection_AsciiString hostName;
static TCollection_AsciiString version;
static TCollection_AsciiString interAddr;
static Standard_Integer memSize;
OSD_Host :: OSD_Host () {
DWORD nSize;
Standard_Character szHostName[ MAX_COMPUTERNAME_LENGTH + 1 ];
char* hostAddr = NULL;
MEMORYSTATUS ms = {};
WSADATA wd;
PHOSTENT phe;
IN_ADDR inAddr;
OSVERSIONINFO osVerInfo;
if ( !fInit ) {
nSize = MAX_COMPUTERNAME_LENGTH + 1;
osVerInfo.dwOSVersionInfoSize = sizeof ( OSVERSIONINFO );
ZeroMemory ( szHostName, sizeof ( Standard_Character ) * (MAX_COMPUTERNAME_LENGTH + 1) );
if ( !GetVersionEx ( &osVerInfo ) ) {
_osd_wnt_set_error ( myError, OSD_WHost );
} else if ( !GetComputerName ( szHostName, &nSize ) ) {
_osd_wnt_set_error ( myError, OSD_WHost );
} else {
ms.dwLength = sizeof ( MEMORYSTATUS );
GlobalMemoryStatus ( &ms );
} // end else
if ( !Failed () ) {
memSize = (Standard_Integer) ms.dwAvailPageFile;
if ( WSAStartup ( MAKEWORD( 1, 1 ), &wd ) ) {
_osd_wnt_set_error ( myError, OSD_WHost );
} else if ( ( phe = gethostbyname ( szHostName ) ) == NULL ) {
_osd_wnt_set_error ( myError, OSD_WHost );
} else {
CopyMemory ( &inAddr, *phe -> h_addr_list, sizeof ( IN_ADDR ) );
hostAddr = inet_ntoa ( inAddr );
} // end else
} // end if
if ( !Failed () ) {
hostName = szHostName;
interAddr = Standard_CString ( hostAddr );
wsprintf (
osVerInfo.szCSDVersion, TEXT( "Windows NT Version %d.%d" ),
osVerInfo.dwMajorVersion, osVerInfo.dwMinorVersion
);
version = osVerInfo.szCSDVersion;
fInit = TRUE;
} // end if
} // end if
if ( fInit )
myName = hostName;
} // end constructor
TCollection_AsciiString OSD_Host :: SystemVersion () {
return version;
} // end OSD_Host :: SystemVersion
OSD_SysType OSD_Host :: SystemId () const {
return OSD_WindowsNT;
} // end OSD_Host :: SystemId
TCollection_AsciiString OSD_Host :: HostName () {
return hostName;
} // end OSD_Host :: HostName
Standard_Integer OSD_Host :: AvailableMemory () {
return memSize;
} // end OSD_Host :: AvailableMemory
TCollection_AsciiString OSD_Host :: InternetAddress () {
return interAddr;
} // end OSD_Host :: InternetAddress
OSD_OEMType OSD_Host :: MachineType () {
return OSD_PC;
} // end OSD_Host :: MachineTYpe
Standard_Boolean OSD_Host :: Failed () const {
return myError.Failed ();
} // end OSD_Host :: Failed
void OSD_Host :: Reset () {
myError.Reset ();
} // end OSD_Host :: Reset
void OSD_Host :: Perror () {
myError.Perror ();
} // end OSD_Host :: Perror
Standard_Integer OSD_Host :: Error () const {
return myError.Error ();
} //end OSD_Host :: Error
#endif
<commit_msg>Add __BORLANDC__ check for pragma comment<commit_after>// Copyright (c) 1998-1999 Matra Datavision
// Copyright (c) 1999-2012 OPEN CASCADE SAS
//
// The content of this file is subject to the Open CASCADE Technology Public
// License Version 6.5 (the "License"). You may not use the content of this file
// except in compliance with the License. Please obtain a copy of the License
// at http://www.opencascade.org and read it completely before using this file.
//
// The Initial Developer of the Original Code is Open CASCADE S.A.S., having its
// main offices at: 1, place des Freres Montgolfier, 78280 Guyancourt, France.
//
// The Original Code and all software distributed under the License is
// distributed on an "AS IS" basis, without warranty of any kind, and the
// Initial Developer hereby disclaims all such warranties, including without
// limitation, any warranties of merchantability, fitness for a particular
// purpose or non-infringement. Please see the License for the specific terms
// and conditions governing the rights and limitations under the License.
#ifdef HAVE_CONFIG_H
# include <oce-config.h>
#endif
#ifndef WNT
#include <Standard_NullObject.hxx>
#include <Standard_ConstructionError.hxx>
#include <OSD_Host.ixx>
#include <OSD_WhoAmI.hxx>
const OSD_WhoAmI Iam = OSD_WHost;
#include <errno.h>
#ifdef HAVE_SYS_UTSNAME_H
# include <sys/utsname.h> // For 'uname'
#endif
#ifdef HAVE_NETDB_H
# include <netdb.h> // This is for 'gethostbyname'
#endif
#include <stdio.h>
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#if defined(__osf__) || defined(DECOSF1)
#include <sys/types.h>
#include <sys/sysinfo.h> // For 'getsysinfo'
#include <sys/socket.h> // To get ethernet address
#include <sys/ioctl.h>
#include <net/if.h>
extern "C" {
int gethostname(char* address, int len);
}
#endif
#ifdef HAVE_SYSENT_H
# include <sysent.h> // for 'gethostname'
#endif
#ifdef HAVE_SYS_SOCKET_H
# include <sys/socket.h>
#endif
#ifdef HAVE_SYS_UNISTD_H
# include <sys/unistd.h>
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_SYSTEMINFO_H
# include <sys/systeminfo.h>
#endif
extern "C" {int sysinfo(int, char *, long);}
// =========================================================================
OSD_Host::OSD_Host(){}
// =========================================================================
TCollection_AsciiString OSD_Host::SystemVersion(){
struct utsname info;
TCollection_AsciiString result;
#ifdef HAVE_SYS_SYSTEMINFO_H
char buf[100];
#endif
uname (&info);
result = info.sysname;
result += " ";
result += info.release;
#ifdef HAVE_SYS_SYSTEMINFO_H
result += " ";
sysinfo(SI_ARCHITECTURE,buf,99);
result += buf;
result += " ";
sysinfo(SI_HW_PROVIDER,buf,99);
result += buf;
#endif
return(result);
}
// =========================================================================
OSD_SysType OSD_Host::SystemId()const{
struct utsname info;
uname (&info);
if (!strcmp(info.sysname,"SunOS")) return (OSD_UnixBSD);
if (!strcmp(info.sysname,"ULTRIX")) return (OSD_UnixBSD);
if (!strcmp(info.sysname,"FreeBSD")) return (OSD_UnixBSD);
if (!strncmp(info.sysname,"Linux",5)) return (OSD_LinuxREDHAT);
if (!strncmp(info.sysname,"IRIX", 4)) return (OSD_UnixSystemV);
if (!strncmp(info.sysname,"OSF", 3)) return (OSD_OSF);
if (!strcmp(info.sysname,"AIX")) return (OSD_Aix);
if (!strcmp(info.sysname,"UNIX_System_V")) return (OSD_UnixSystemV);
if (!strcmp(info.sysname,"VMS_POSIX")) return (OSD_VMS);
if (!strcmp(info.sysname,"Darwin")) return (OSD_MacOs);
return (OSD_Unknown);
}
// =========================================================================
TCollection_AsciiString OSD_Host::HostName(){
TCollection_AsciiString result;
char value[65];
int status;
status = gethostname(value, 64);
if (status == -1) myError.SetValue(errno, Iam, "Host Name");
result = value;
return(result);
}
// =========================================================================
Standard_Integer OSD_Host::AvailableMemory(){
Standard_Integer result;
#if defined(__osf__) || defined(DECOSF1)
char buffer[16];
//// result = getsysinfo(GSI_PHYSMEM,buffer, 16,0,NULL);
if (result != -1)
result *= 1024;
#else
result = 0;
//@@ A faire
#endif
return (result);
}
// =========================================================================
TCollection_AsciiString OSD_Host::InternetAddress(){
struct hostent internet_address;
int a,b,c,d;
char buffer[16];
TCollection_AsciiString result,host;
host = HostName();
memcpy(&internet_address,
gethostbyname(host.ToCString()),
sizeof(struct hostent));
// Gets each bytes into integers
a = (unsigned char)internet_address.h_addr_list[0][0];
b = (unsigned char)internet_address.h_addr_list[0][1];
c = (unsigned char)internet_address.h_addr_list[0][2];
d = (unsigned char)internet_address.h_addr_list[0][3];
sprintf(buffer,"%d.%d.%d.%d",a,b,c,d);
result = buffer;
return(result);
}
// =========================================================================
OSD_OEMType OSD_Host::MachineType(){
struct utsname info;
uname (&info);
if (!strcmp(info.sysname,"SunOS")) return (OSD_SUN);
if (!strcmp(info.sysname,"ULTRIX")) return (OSD_DEC);
if (!strncmp(info.sysname,"IRIX",4)) return (OSD_SGI);
if (!strcmp(info.sysname,"HP-UX")) return (OSD_HP);
if (!strcmp(info.sysname,"UNIX_System_V")) return (OSD_NEC);
if (!strcmp(info.sysname,"VMS_POSIX")) return (OSD_VAX);
if (!strncmp(info.sysname,"OSF",3)) return (OSD_DEC);
if (!strncmp(info.sysname,"Linux",5)) return (OSD_LIN);
if (!strcmp(info.sysname,"FreeBSD")) return (OSD_LIN);
if (!strncmp(info.sysname,"AIX",3)) return (OSD_AIX);
if (!strcmp(info.sysname,"Darwin")) return (OSD_MAC);
return (OSD_Unavailable);
}
void OSD_Host::Reset(){
myError.Reset();
}
Standard_Boolean OSD_Host::Failed()const{
return( myError.Failed());
}
void OSD_Host::Perror() {
myError.Perror();
}
Standard_Integer OSD_Host::Error()const{
return( myError.Error());
}
#else
//------------------------------------------------------------------------
//------------------- WNT Sources of OSD_Host ---------------------------
//------------------------------------------------------------------------
#define STRICT
#include <windows.h>
#include <OSD_Host.hxx>
#if defined(_MSC_VER) || defined(__BORLANDC__)
#pragma comment( lib, "WSOCK32.LIB" )
#endif
void _osd_wnt_set_error ( OSD_Error&, OSD_WhoAmI, ... );
static BOOL fInit = FALSE;
static TCollection_AsciiString hostName;
static TCollection_AsciiString version;
static TCollection_AsciiString interAddr;
static Standard_Integer memSize;
OSD_Host :: OSD_Host () {
DWORD nSize;
Standard_Character szHostName[ MAX_COMPUTERNAME_LENGTH + 1 ];
char* hostAddr = NULL;
MEMORYSTATUS ms = {};
WSADATA wd;
PHOSTENT phe;
IN_ADDR inAddr;
OSVERSIONINFO osVerInfo;
if ( !fInit ) {
nSize = MAX_COMPUTERNAME_LENGTH + 1;
osVerInfo.dwOSVersionInfoSize = sizeof ( OSVERSIONINFO );
ZeroMemory ( szHostName, sizeof ( Standard_Character ) * (MAX_COMPUTERNAME_LENGTH + 1) );
if ( !GetVersionEx ( &osVerInfo ) ) {
_osd_wnt_set_error ( myError, OSD_WHost );
} else if ( !GetComputerName ( szHostName, &nSize ) ) {
_osd_wnt_set_error ( myError, OSD_WHost );
} else {
ms.dwLength = sizeof ( MEMORYSTATUS );
GlobalMemoryStatus ( &ms );
} // end else
if ( !Failed () ) {
memSize = (Standard_Integer) ms.dwAvailPageFile;
if ( WSAStartup ( MAKEWORD( 1, 1 ), &wd ) ) {
_osd_wnt_set_error ( myError, OSD_WHost );
} else if ( ( phe = gethostbyname ( szHostName ) ) == NULL ) {
_osd_wnt_set_error ( myError, OSD_WHost );
} else {
CopyMemory ( &inAddr, *phe -> h_addr_list, sizeof ( IN_ADDR ) );
hostAddr = inet_ntoa ( inAddr );
} // end else
} // end if
if ( !Failed () ) {
hostName = szHostName;
interAddr = Standard_CString ( hostAddr );
wsprintf (
osVerInfo.szCSDVersion, TEXT( "Windows NT Version %d.%d" ),
osVerInfo.dwMajorVersion, osVerInfo.dwMinorVersion
);
version = osVerInfo.szCSDVersion;
fInit = TRUE;
} // end if
} // end if
if ( fInit )
myName = hostName;
} // end constructor
TCollection_AsciiString OSD_Host :: SystemVersion () {
return version;
} // end OSD_Host :: SystemVersion
OSD_SysType OSD_Host :: SystemId () const {
return OSD_WindowsNT;
} // end OSD_Host :: SystemId
TCollection_AsciiString OSD_Host :: HostName () {
return hostName;
} // end OSD_Host :: HostName
Standard_Integer OSD_Host :: AvailableMemory () {
return memSize;
} // end OSD_Host :: AvailableMemory
TCollection_AsciiString OSD_Host :: InternetAddress () {
return interAddr;
} // end OSD_Host :: InternetAddress
OSD_OEMType OSD_Host :: MachineType () {
return OSD_PC;
} // end OSD_Host :: MachineTYpe
Standard_Boolean OSD_Host :: Failed () const {
return myError.Failed ();
} // end OSD_Host :: Failed
void OSD_Host :: Reset () {
myError.Reset ();
} // end OSD_Host :: Reset
void OSD_Host :: Perror () {
myError.Perror ();
} // end OSD_Host :: Perror
Standard_Integer OSD_Host :: Error () const {
return myError.Error ();
} //end OSD_Host :: Error
#endif
<|endoftext|> |
<commit_before>/* Authors: Don Sanders <[email protected]>
Copyright (C) 2000 Don Sanders <[email protected]>
Includes KMLittleProgressDlg which is based on KIOLittleProgressDlg
by Matt Koss <[email protected]>
License GPL
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmbroadcaststatus.h"
#include "kmbroadcaststatus.moc"
#include "ssllabel.h"
using KMail::SSLLabel;
#include "progressmanager.h"
using KMail::ProgressItem;
using KMail::ProgressManager;
#include <kprogress.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <klocale.h>
#include <qlayout.h>
#include <qwidgetstack.h>
#include <qdatetime.h>
#include <kmkernel.h> // for the progress dialog
#include "kmmainwidget.h"
//-----------------------------------------------------------------------------
KMBroadcastStatus* KMBroadcastStatus::instance_ = 0;
KMBroadcastStatus* KMBroadcastStatus::instance()
{
if (!instance_)
instance_ = new KMBroadcastStatus();
return instance_;
}
KMBroadcastStatus::KMBroadcastStatus()
{
reset();
}
void KMBroadcastStatus::setUsingSSL( bool isUsing )
{
emit signalUsingSSL( isUsing );
}
void KMBroadcastStatus::setStatusMsg( const QString& message )
{
emit statusMsg( message );
}
void KMBroadcastStatus::setStatusMsgWithTimestamp( const QString& message )
{
KLocale* locale = KGlobal::locale();
setStatusMsg( i18n( "%1 is a time, %2 is a status message", "[%1] %2" )
.arg( locale->formatTime( QTime::currentTime(),
true /* with seconds */ ) )
.arg( message ) );
}
void KMBroadcastStatus::setStatusMsgTransmissionCompleted( int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission complete. %n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission complete. %n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 );
else
statusMsg = i18n( "Transmission complete. %n message in %1 KB.",
"Transmission complete. %n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 );
}
else
statusMsg = i18n( "Transmission complete. %n new message.",
"Transmission complete. %n new messages.",
numMessages );
}
else
statusMsg = i18n( "Transmission complete. No new messages." );
setStatusMsgWithTimestamp( statusMsg );
}
void KMBroadcastStatus::setStatusMsgTransmissionCompleted( const QString& account,
int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission for account %3 complete. "
"%n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission for account %3 complete. "
"%n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 )
.arg( account );
else
statusMsg = i18n( "Transmission for account %2 complete. "
"%n message in %1 KB.",
"Transmission for account %2 complete. "
"%n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. "
"%n new message.",
"Transmission for account %1 complete. "
"%n new messages.",
numMessages )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. No new messages.")
.arg( account );
setStatusMsgWithTimestamp( statusMsg );
}
void KMBroadcastStatus::setStatusProgressEnable( const QString &id,
bool enable )
{
bool wasEmpty = ids.isEmpty();
if (enable) ids.insert(id, 0);
else ids.remove(id);
if (!wasEmpty && !ids.isEmpty())
setStatusProgressPercent("", 0);
else
emit statusProgressEnable( !ids.isEmpty() );
}
void KMBroadcastStatus::setStatusProgressPercent( const QString &id,
unsigned long percent )
{
if (!id.isEmpty() && ids.contains(id)) ids.insert(id, percent);
unsigned long sum = 0, count = 0;
for (QMap<QString,unsigned long>::iterator it = ids.begin();
it != ids.end(); it++)
{
sum += *it;
count++;
}
emit statusProgressPercent( count ? (sum / count) : sum );
}
void KMBroadcastStatus::reset()
{
abortRequested_ = false;
if (ids.isEmpty())
emit resetRequested();
}
bool KMBroadcastStatus::abortRequested()
{
return abortRequested_;
}
void KMBroadcastStatus::setAbortRequested()
{
abortRequested_ = true;
}
void KMBroadcastStatus::requestAbort()
{
abortRequested_ = true;
emit signalAbortRequested();
}
//-----------------------------------------------------------------------------
KMLittleProgressDlg::KMLittleProgressDlg( KMMainWidget* mainWidget, QWidget* parent, bool button )
: QFrame( parent ), m_mainWidget( mainWidget ), mCurrentItem( 0 )
{
m_bShowButton = button;
int w = fontMetrics().width( " 999.9 kB/s 00:00:01 " ) + 8;
box = new QHBoxLayout( this, 0, 0 );
m_pButton = new QPushButton( this );
m_pButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,
QSizePolicy::Minimum ) );
m_pButton->setPixmap( SmallIcon( "up" ) );
box->addWidget( m_pButton );
stack = new QWidgetStack( this );
stack->setMaximumHeight( fontMetrics().height() );
box->addWidget( stack );
m_sslLabel = new SSLLabel( this );
box->addWidget( m_sslLabel );
QToolTip::add( m_pButton, i18n("Open detailed progress dialog") );
m_pProgressBar = new KProgress( this );
m_pProgressBar->setLineWidth( 1 );
m_pProgressBar->setFrameStyle( QFrame::Box );
m_pProgressBar->installEventFilter( this );
m_pProgressBar->setMinimumWidth( w );
stack->addWidget( m_pProgressBar, 1 );
m_pLabel = new QLabel( "", this );
m_pLabel->setAlignment( AlignHCenter | AlignVCenter );
m_pLabel->installEventFilter( this );
m_pLabel->setMinimumWidth( w );
stack->addWidget( m_pLabel, 2 );
m_pButton->setMaximumHeight( fontMetrics().height() );
setMinimumWidth( minimumSizeHint().width() );
mode = None;
setMode();
connect( m_pButton, SIGNAL( clicked() ),
mainWidget, SLOT( slotToggleProgressDialog() ) );
connect ( ProgressManager::instance(), SIGNAL( progressItemAdded( ProgressItem * ) ),
this, SLOT( slotProgressItemAdded( ProgressItem * ) ) );
connect ( ProgressManager::instance(), SIGNAL( progressItemCompleted( ProgressItem * ) ),
this, SLOT( slotProgressItemCompleted( ProgressItem * ) ) );
}
void KMLittleProgressDlg::slotProgressItemAdded( ProgressItem *item )
{
slotEnable(true);
if ( item->parent() ) return; // we are only interested in top level items
if ( mCurrentItem ) {
disconnect ( mCurrentItem, SIGNAL( progressItemProgress( ProgressItem *, unsigned int ) ),
this, SLOT( slotProgressItemProgress( ProgressItem *, unsigned int ) ) );
}
mCurrentItem = item;
connect ( mCurrentItem, SIGNAL( progressItemProgress( ProgressItem *, unsigned int ) ),
this, SLOT( slotProgressItemProgress( ProgressItem *, unsigned int ) ) );
}
void KMLittleProgressDlg::slotProgressItemCompleted( ProgressItem *item )
{
if ( mCurrentItem && mCurrentItem == item ) {
slotClean();
mCurrentItem = 0;
}
}
void KMLittleProgressDlg::slotProgressItemProgress( ProgressItem *item, unsigned int value )
{
Q_ASSERT( item == mCurrentItem); // the only one we should be connected to
m_pProgressBar->setValue( value );
}
void KMLittleProgressDlg::slotEnable( bool enabled )
{
if (enabled) {
if (mode == Progress) // it's already enabled
return;
m_pButton->setDown( false );
mode = Progress;
kdDebug(5006) << "enable progress" << endl;
}
else {
if (mode == None)
return;
mode = None;
}
setMode();
}
void KMLittleProgressDlg::slotSetSSL( bool ssl )
{
m_sslLabel->setEncrypted( ssl );
}
void KMLittleProgressDlg::setMode() {
switch ( mode ) {
case None:
if ( m_bShowButton ) {
m_pButton->hide();
}
m_sslLabel->setState( SSLLabel::Done );
// show the empty label in order to make the status bar look better
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Clean:
if ( m_bShowButton ) {
m_pButton->hide();
}
m_sslLabel->setState( SSLLabel::Clean );
// show the empty label in order to make the status bar look better
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Label:
if ( m_bShowButton ) {
m_pButton->show();
}
m_sslLabel->setState( m_sslLabel->lastState() );
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Progress:
if (stack->isVisible()) {
stack->show();
stack->raiseWidget( m_pProgressBar );
if ( m_bShowButton ) {
m_pButton->show();
}
m_sslLabel->setState( m_sslLabel->lastState() );
}
break;
}
}
void KMLittleProgressDlg::slotJustPercent( unsigned long _percent )
{
m_pProgressBar->setValue( _percent );
}
void KMLittleProgressDlg::slotClean()
{
m_pProgressBar->setValue( 0 );
m_pLabel->clear();
mode = Clean;
setMode();
}
bool KMLittleProgressDlg::eventFilter( QObject *, QEvent *ev )
{
if ( ev->type() == QEvent::MouseButtonPress ) {
QMouseEvent *e = (QMouseEvent*)ev;
if ( e->button() == LeftButton && mode != Clean ) { // toggle view on left mouse button
// Hide the progress bar when the detailed one is showing
if ( mode == Label ) {
mode = Progress;
} else if ( mode == Progress ) {
mode = Label;
}
setMode();
// Consensus seems to be that we should show/hide the fancy dialog when the user
// clicks anywhere in the small one.
m_mainWidget->slotToggleProgressDialog();
return true;
}
}
return false;
}
<commit_msg>Progress or Label means active already.<commit_after>/* Authors: Don Sanders <[email protected]>
Copyright (C) 2000 Don Sanders <[email protected]>
Includes KMLittleProgressDlg which is based on KIOLittleProgressDlg
by Matt Koss <[email protected]>
License GPL
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmbroadcaststatus.h"
#include "kmbroadcaststatus.moc"
#include "ssllabel.h"
using KMail::SSLLabel;
#include "progressmanager.h"
using KMail::ProgressItem;
using KMail::ProgressManager;
#include <kprogress.h>
#include <kiconloader.h>
#include <kdebug.h>
#include <qlabel.h>
#include <qpushbutton.h>
#include <qtooltip.h>
#include <klocale.h>
#include <qlayout.h>
#include <qwidgetstack.h>
#include <qdatetime.h>
#include <kmkernel.h> // for the progress dialog
#include "kmmainwidget.h"
//-----------------------------------------------------------------------------
KMBroadcastStatus* KMBroadcastStatus::instance_ = 0;
KMBroadcastStatus* KMBroadcastStatus::instance()
{
if (!instance_)
instance_ = new KMBroadcastStatus();
return instance_;
}
KMBroadcastStatus::KMBroadcastStatus()
{
reset();
}
void KMBroadcastStatus::setUsingSSL( bool isUsing )
{
emit signalUsingSSL( isUsing );
}
void KMBroadcastStatus::setStatusMsg( const QString& message )
{
emit statusMsg( message );
}
void KMBroadcastStatus::setStatusMsgWithTimestamp( const QString& message )
{
KLocale* locale = KGlobal::locale();
setStatusMsg( i18n( "%1 is a time, %2 is a status message", "[%1] %2" )
.arg( locale->formatTime( QTime::currentTime(),
true /* with seconds */ ) )
.arg( message ) );
}
void KMBroadcastStatus::setStatusMsgTransmissionCompleted( int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission complete. %n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission complete. %n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 );
else
statusMsg = i18n( "Transmission complete. %n message in %1 KB.",
"Transmission complete. %n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 );
}
else
statusMsg = i18n( "Transmission complete. %n new message.",
"Transmission complete. %n new messages.",
numMessages );
}
else
statusMsg = i18n( "Transmission complete. No new messages." );
setStatusMsgWithTimestamp( statusMsg );
}
void KMBroadcastStatus::setStatusMsgTransmissionCompleted( const QString& account,
int numMessages,
int numBytes,
int numBytesRead,
int numBytesToRead,
bool mLeaveOnServer )
{
QString statusMsg;
if( numMessages > 0 ) {
if( numBytes != -1 ) {
if( ( numBytesToRead != numBytes ) && mLeaveOnServer )
statusMsg = i18n( "Transmission for account %3 complete. "
"%n new message in %1 KB "
"(%2 KB remaining on the server).",
"Transmission for account %3 complete. "
"%n new messages in %1 KB "
"(%2 KB remaining on the server).",
numMessages )
.arg( numBytesRead / 1024 )
.arg( numBytes / 1024 )
.arg( account );
else
statusMsg = i18n( "Transmission for account %2 complete. "
"%n message in %1 KB.",
"Transmission for account %2 complete. "
"%n messages in %1 KB.",
numMessages )
.arg( numBytesRead / 1024 )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. "
"%n new message.",
"Transmission for account %1 complete. "
"%n new messages.",
numMessages )
.arg( account );
}
else
statusMsg = i18n( "Transmission for account %1 complete. No new messages.")
.arg( account );
setStatusMsgWithTimestamp( statusMsg );
}
void KMBroadcastStatus::setStatusProgressEnable( const QString &id,
bool enable )
{
bool wasEmpty = ids.isEmpty();
if (enable) ids.insert(id, 0);
else ids.remove(id);
if (!wasEmpty && !ids.isEmpty())
setStatusProgressPercent("", 0);
else
emit statusProgressEnable( !ids.isEmpty() );
}
void KMBroadcastStatus::setStatusProgressPercent( const QString &id,
unsigned long percent )
{
if (!id.isEmpty() && ids.contains(id)) ids.insert(id, percent);
unsigned long sum = 0, count = 0;
for (QMap<QString,unsigned long>::iterator it = ids.begin();
it != ids.end(); it++)
{
sum += *it;
count++;
}
emit statusProgressPercent( count ? (sum / count) : sum );
}
void KMBroadcastStatus::reset()
{
abortRequested_ = false;
if (ids.isEmpty())
emit resetRequested();
}
bool KMBroadcastStatus::abortRequested()
{
return abortRequested_;
}
void KMBroadcastStatus::setAbortRequested()
{
abortRequested_ = true;
}
void KMBroadcastStatus::requestAbort()
{
abortRequested_ = true;
emit signalAbortRequested();
}
//-----------------------------------------------------------------------------
KMLittleProgressDlg::KMLittleProgressDlg( KMMainWidget* mainWidget, QWidget* parent, bool button )
: QFrame( parent ), m_mainWidget( mainWidget ), mCurrentItem( 0 )
{
m_bShowButton = button;
int w = fontMetrics().width( " 999.9 kB/s 00:00:01 " ) + 8;
box = new QHBoxLayout( this, 0, 0 );
m_pButton = new QPushButton( this );
m_pButton->setSizePolicy( QSizePolicy( QSizePolicy::Minimum,
QSizePolicy::Minimum ) );
m_pButton->setPixmap( SmallIcon( "up" ) );
box->addWidget( m_pButton );
stack = new QWidgetStack( this );
stack->setMaximumHeight( fontMetrics().height() );
box->addWidget( stack );
m_sslLabel = new SSLLabel( this );
box->addWidget( m_sslLabel );
QToolTip::add( m_pButton, i18n("Open detailed progress dialog") );
m_pProgressBar = new KProgress( this );
m_pProgressBar->setLineWidth( 1 );
m_pProgressBar->setFrameStyle( QFrame::Box );
m_pProgressBar->installEventFilter( this );
m_pProgressBar->setMinimumWidth( w );
stack->addWidget( m_pProgressBar, 1 );
m_pLabel = new QLabel( "", this );
m_pLabel->setAlignment( AlignHCenter | AlignVCenter );
m_pLabel->installEventFilter( this );
m_pLabel->setMinimumWidth( w );
stack->addWidget( m_pLabel, 2 );
m_pButton->setMaximumHeight( fontMetrics().height() );
setMinimumWidth( minimumSizeHint().width() );
mode = None;
setMode();
connect( m_pButton, SIGNAL( clicked() ),
mainWidget, SLOT( slotToggleProgressDialog() ) );
connect ( ProgressManager::instance(), SIGNAL( progressItemAdded( ProgressItem * ) ),
this, SLOT( slotProgressItemAdded( ProgressItem * ) ) );
connect ( ProgressManager::instance(), SIGNAL( progressItemCompleted( ProgressItem * ) ),
this, SLOT( slotProgressItemCompleted( ProgressItem * ) ) );
}
void KMLittleProgressDlg::slotProgressItemAdded( ProgressItem *item )
{
slotEnable(true);
if ( item->parent() ) return; // we are only interested in top level items
if ( mCurrentItem ) {
disconnect ( mCurrentItem, SIGNAL( progressItemProgress( ProgressItem *, unsigned int ) ),
this, SLOT( slotProgressItemProgress( ProgressItem *, unsigned int ) ) );
}
mCurrentItem = item;
connect ( mCurrentItem, SIGNAL( progressItemProgress( ProgressItem *, unsigned int ) ),
this, SLOT( slotProgressItemProgress( ProgressItem *, unsigned int ) ) );
}
void KMLittleProgressDlg::slotProgressItemCompleted( ProgressItem *item )
{
if ( mCurrentItem && mCurrentItem == item ) {
slotClean();
mCurrentItem = 0;
}
}
void KMLittleProgressDlg::slotProgressItemProgress( ProgressItem *item, unsigned int value )
{
Q_ASSERT( item == mCurrentItem); // the only one we should be connected to
m_pProgressBar->setValue( value );
}
void KMLittleProgressDlg::slotEnable( bool enabled )
{
if (enabled) {
if (mode == Progress || mode == Label ) // it's already enabled
return;
m_pButton->setDown( false );
mode = Progress;
kdDebug(5006) << "enable progress" << endl;
}
else {
if (mode == None)
return;
mode = None;
}
setMode();
}
void KMLittleProgressDlg::slotSetSSL( bool ssl )
{
m_sslLabel->setEncrypted( ssl );
}
void KMLittleProgressDlg::setMode() {
switch ( mode ) {
case None:
if ( m_bShowButton ) {
m_pButton->hide();
}
m_sslLabel->setState( SSLLabel::Done );
// show the empty label in order to make the status bar look better
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Clean:
if ( m_bShowButton ) {
m_pButton->hide();
}
m_sslLabel->setState( SSLLabel::Clean );
// show the empty label in order to make the status bar look better
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Label:
if ( m_bShowButton ) {
m_pButton->show();
}
m_sslLabel->setState( m_sslLabel->lastState() );
stack->show();
stack->raiseWidget( m_pLabel );
break;
case Progress:
if (stack->isVisible()) {
stack->show();
stack->raiseWidget( m_pProgressBar );
if ( m_bShowButton ) {
m_pButton->show();
}
m_sslLabel->setState( m_sslLabel->lastState() );
}
break;
}
}
void KMLittleProgressDlg::slotJustPercent( unsigned long _percent )
{
m_pProgressBar->setValue( _percent );
}
void KMLittleProgressDlg::slotClean()
{
m_pProgressBar->setValue( 0 );
m_pLabel->clear();
mode = Clean;
setMode();
}
bool KMLittleProgressDlg::eventFilter( QObject *, QEvent *ev )
{
if ( ev->type() == QEvent::MouseButtonPress ) {
QMouseEvent *e = (QMouseEvent*)ev;
if ( e->button() == LeftButton && mode != Clean ) { // toggle view on left mouse button
// Hide the progress bar when the detailed one is showing
if ( mode == Label ) {
mode = Progress;
} else if ( mode == Progress ) {
mode = Label;
}
setMode();
// Consensus seems to be that we should show/hide the fancy dialog when the user
// clicks anywhere in the small one.
m_mainWidget->slotToggleProgressDialog();
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>/*
* shaperenderer.cpp
*
* Created on: Mar 11, 2013
* @author schurade
*/
#include "shaperenderer.h"
#include "glfunctions.h"
#include "../../data/mesh/tesselation.h"
#include <QDebug>
#include <QtOpenGL/QGLShaderProgram>
ShapeRenderer::ShapeRenderer() :
vboIds( new GLuint[ 5 ] )
{
}
ShapeRenderer::~ShapeRenderer()
{
glDeleteBuffers( 5, vboIds );
delete[] vboIds;
}
void ShapeRenderer::init()
{
glGenBuffers( 5, vboIds );
initBox();
initSphere();
}
void ShapeRenderer::initBox()
{
GLushort indices[] = {
3, 2, 1, 0, //bottom
0, 1, 5, 4, // front
1, 2, 6, 5, // right
2, 3, 7, 6, // back
3, 0, 4, 7, // left
4, 5, 6, 7 // top
};
// Transfer index data to VBO 0
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, 24 * sizeof(GLushort), indices, GL_STATIC_DRAW );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
GLushort lineIndices[] = {
0, 1, 1, 2, 2, 3, 3, 0,
4, 5, 5, 6, 6, 7, 7, 4,
0, 4, 1, 5, 2, 6, 3, 7
};
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 4 ] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, 24 * sizeof(GLushort), lineIndices, GL_STATIC_DRAW );
float x1 = -1.0f;
float y1 = -1.0f;
float z1 = -1.0f;
float x2 = 1.0f;
float y2 = 1.0f;
float z2 = 1.0f;
float vertices[] =
{
x1, y1, z1,
x2, y1, z1,
x2, y2, z1,
x1, y2, z1,
x1, y1, z2,
x2, y1, z2,
x2, y2, z2,
x1, y2, z2
};
// Transfer vertex data to VBO 1
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
glBufferData( GL_ARRAY_BUFFER, 24 * sizeof(float), &vertices, GL_STATIC_DRAW );
}
void ShapeRenderer::initSphere()
{
int lod = 3;
const Matrix* vertices = tess::vertices( lod );
const int* faces = tess::faces( lod );
int numVerts = tess::n_vertices( lod );
int numTris = tess::n_faces( lod );
std::vector<float>verts;
verts.reserve( numVerts * 3 );
std::vector<int>indexes;
indexes.reserve( numTris * 3 );
for ( int i = 0; i < numVerts; ++i )
{
verts.push_back( (*vertices)( i+1, 1 ) );
verts.push_back( (*vertices)( i+1, 2 ) );
verts.push_back( (*vertices)( i+1, 3 ) );
}
for ( int i = 0; i < numTris; ++i )
{
indexes.push_back( faces[i*3] );
indexes.push_back( faces[i*3+1] );
indexes.push_back( faces[i*3+2] );
}
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 2 ] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, indexes.size() * sizeof(GLuint), &indexes[0], GL_STATIC_DRAW );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 3 ] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), &verts[0], GL_STATIC_DRAW );
}
void ShapeRenderer::drawBox( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix,
float x, float y, float z, float dx, float dy, float dz,
QColor color, int pickID, int width, int height, int renderMode )
{
float alpha = color.alphaF();
switch ( renderMode )
{
case 0:
break;
case 1:
{
if ( alpha < 1.0 ) // obviously not opaque
{
return;
}
break;
}
default:
{
if ( alpha == 1.0 ) // not transparent
{
return;
}
break;
}
}
QGLShaderProgram* program = GLFunctions::getShader( "shape" );
// Tell OpenGL which VBOs to use
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
program->bind();
// Offset for position
intptr_t offset = 0;
// Tell OpenGL programmable pipeline how to locate vertex position data
int vertexLocation = program->attributeLocation( "a_position" );
program->enableAttributeArray( vertexLocation );
glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, (const void *) offset );
// Set modelview-projection matrix
program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
float pAlpha = 1.0;
float blue = (float)(( pickID ) & 0xFF) / 255.f;
float green = (float)(( pickID >> 8 ) & 0xFF) / 255.f;
float red = (float)(( pickID >> 16 ) & 0xFF) / 255.f;
program->setUniformValue( "u_pickColor", red, green , blue, pAlpha );
program->setUniformValue( "u_color", color.redF(), color.greenF(), color.blueF(), color.alphaF() );
program->setUniformValue( "u_alpha", (float)color.alphaF() );
program->setUniformValue( "u_renderMode", renderMode );
program->setUniformValue( "u_canvasSize", width, height );
program->setUniformValue( "u_lighting", false );
program->setUniformValue( "D0", 9 );
program->setUniformValue( "D1", 10 );
program->setUniformValue( "D2", 11 );
program->setUniformValue( "P0", 12 );
program->setUniformValue( "u_x", x );
program->setUniformValue( "u_y", y );
program->setUniformValue( "u_z", z );
program->setUniformValue( "u_dx", dx / 2 );
program->setUniformValue( "u_dy", dy / 2 );
program->setUniformValue( "u_dz", dz / 2 );
glEnable(GL_CULL_FACE);
glCullFace( GL_BACK );
glFrontFace( GL_CCW );
// Draw cube geometry using indices from VBO 0
glDrawElements( GL_QUADS, 24, GL_UNSIGNED_SHORT, 0 );
glDisable(GL_CULL_FACE);
program->setUniformValue( "u_color", color.redF(), color.greenF(), color.blueF(), color.alphaF() );
program->setUniformValue( "u_alpha", 1.0f );
program->setUniformValue( "u_renderMode", renderMode );
program->setUniformValue( "u_canvasSize", width, height );
program->setUniformValue( "u_lighting", false );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 4 ] );
glDrawElements( GL_LINES, 24, GL_UNSIGNED_SHORT, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
void ShapeRenderer::drawSphere( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix,
float x, float y, float z, float dx, float dy, float dz,
QColor color, int pickID, int width, int height, int renderMode )
{
float alpha = color.alphaF();
if ( renderMode == 1 ) // we are drawing opaque objects
{
if ( alpha < 1.0 )
{
// obviously not opaque
return;
}
}
else // we are drawing tranparent objects
{
if ( !(alpha < 1.0 ) || alpha == 0.0 )
{
// not transparent
return;
}
}
QGLShaderProgram* program = GLFunctions::getShader( "shape" );
program->bind();
// Set modelview-projection matrix
program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 2 ] );
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] );
// Offset for position
intptr_t offset = 0;
// Tell OpenGL programmable pipeline how to locate vertex position data
int vertexLocation = program->attributeLocation( "a_position" );
program->enableAttributeArray( vertexLocation );
glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, (const void *) offset );
program->setUniformValue( "u_x", x );
program->setUniformValue( "u_y", y );
program->setUniformValue( "u_z", z );
program->setUniformValue( "u_dx", dx / 2 );
program->setUniformValue( "u_dy", dy / 2 );
program->setUniformValue( "u_dz", dz / 2 );
float pAlpha = 1.0;
float blue = (float)(( pickID ) & 0xFF) / 255.f;
float green = (float)(( pickID >> 8 ) & 0xFF) / 255.f;
float red = (float)(( pickID >> 16 ) & 0xFF) / 255.f;
//qDebug() << " input" << red << green << blue << alpha ;
program->setUniformValue( "u_pickColor", red, green , blue, pAlpha );
program->setUniformValue( "u_color", color.redF(), color.greenF(), color.blueF(), color.alphaF() );
program->setUniformValue( "u_alpha", (float)color.alphaF() );
program->setUniformValue( "u_renderMode", renderMode );
program->setUniformValue( "u_canvasSize", width, height );
program->setUniformValue( "u_lighting", true );
program->setUniformValue( "D0", 9 );
program->setUniformValue( "D1", 10 );
program->setUniformValue( "D2", 11 );
program->setUniformValue( "P0", 12 );
glEnable(GL_CULL_FACE);
glCullFace( GL_BACK );
glFrontFace( GL_CCW );
glDrawElements( GL_TRIANGLES, tess::n_faces( 3 ) * 3, GL_UNSIGNED_INT, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glDisable(GL_CULL_FACE);
}
<commit_msg>set uniforms for light parameters for rois<commit_after>/*
* shaperenderer.cpp
*
* Created on: Mar 11, 2013
* @author schurade
*/
#include "shaperenderer.h"
#include "glfunctions.h"
#include "../../data/models.h"
#include "../../data/mesh/tesselation.h"
#include <QDebug>
#include <QtOpenGL/QGLShaderProgram>
ShapeRenderer::ShapeRenderer() :
vboIds( new GLuint[ 5 ] )
{
}
ShapeRenderer::~ShapeRenderer()
{
glDeleteBuffers( 5, vboIds );
delete[] vboIds;
}
void ShapeRenderer::init()
{
glGenBuffers( 5, vboIds );
initBox();
initSphere();
}
void ShapeRenderer::initBox()
{
GLushort indices[] = {
3, 2, 1, 0, //bottom
0, 1, 5, 4, // front
1, 2, 6, 5, // right
2, 3, 7, 6, // back
3, 0, 4, 7, // left
4, 5, 6, 7 // top
};
// Transfer index data to VBO 0
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, 24 * sizeof(GLushort), indices, GL_STATIC_DRAW );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
GLushort lineIndices[] = {
0, 1, 1, 2, 2, 3, 3, 0,
4, 5, 5, 6, 6, 7, 7, 4,
0, 4, 1, 5, 2, 6, 3, 7
};
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 4 ] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, 24 * sizeof(GLushort), lineIndices, GL_STATIC_DRAW );
float x1 = -1.0f;
float y1 = -1.0f;
float z1 = -1.0f;
float x2 = 1.0f;
float y2 = 1.0f;
float z2 = 1.0f;
float vertices[] =
{
x1, y1, z1,
x2, y1, z1,
x2, y2, z1,
x1, y2, z1,
x1, y1, z2,
x2, y1, z2,
x2, y2, z2,
x1, y2, z2
};
// Transfer vertex data to VBO 1
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
glBufferData( GL_ARRAY_BUFFER, 24 * sizeof(float), &vertices, GL_STATIC_DRAW );
}
void ShapeRenderer::initSphere()
{
int lod = 3;
const Matrix* vertices = tess::vertices( lod );
const int* faces = tess::faces( lod );
int numVerts = tess::n_vertices( lod );
int numTris = tess::n_faces( lod );
std::vector<float>verts;
verts.reserve( numVerts * 3 );
std::vector<int>indexes;
indexes.reserve( numTris * 3 );
for ( int i = 0; i < numVerts; ++i )
{
verts.push_back( (*vertices)( i+1, 1 ) );
verts.push_back( (*vertices)( i+1, 2 ) );
verts.push_back( (*vertices)( i+1, 3 ) );
}
for ( int i = 0; i < numTris; ++i )
{
indexes.push_back( faces[i*3] );
indexes.push_back( faces[i*3+1] );
indexes.push_back( faces[i*3+2] );
}
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 2 ] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, indexes.size() * sizeof(GLuint), &indexes[0], GL_STATIC_DRAW );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 3 ] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, verts.size() * sizeof(GLfloat), &verts[0], GL_STATIC_DRAW );
}
void ShapeRenderer::drawBox( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix,
float x, float y, float z, float dx, float dy, float dz,
QColor color, int pickID, int width, int height, int renderMode )
{
float alpha = color.alphaF();
switch ( renderMode )
{
case 0:
break;
case 1:
{
if ( alpha < 1.0 ) // obviously not opaque
{
return;
}
break;
}
default:
{
if ( alpha == 1.0 ) // not transparent
{
return;
}
break;
}
}
QGLShaderProgram* program = GLFunctions::getShader( "shape" );
// Tell OpenGL which VBOs to use
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 0 ] );
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 1 ] );
program->bind();
// Offset for position
intptr_t offset = 0;
// Tell OpenGL programmable pipeline how to locate vertex position data
int vertexLocation = program->attributeLocation( "a_position" );
program->enableAttributeArray( vertexLocation );
glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, (const void *) offset );
// Set modelview-projection matrix
program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
float pAlpha = 1.0;
float blue = (float)(( pickID ) & 0xFF) / 255.f;
float green = (float)(( pickID >> 8 ) & 0xFF) / 255.f;
float red = (float)(( pickID >> 16 ) & 0xFF) / 255.f;
program->setUniformValue( "u_pickColor", red, green , blue, pAlpha );
program->setUniformValue( "u_color", color.redF(), color.greenF(), color.blueF(), color.alphaF() );
program->setUniformValue( "u_alpha", (float)color.alphaF() );
program->setUniformValue( "u_renderMode", renderMode );
program->setUniformValue( "u_canvasSize", width, height );
program->setUniformValue( "u_lighting", false );
program->setUniformValue( "D0", 9 );
program->setUniformValue( "D1", 10 );
program->setUniformValue( "D2", 11 );
program->setUniformValue( "P0", 12 );
program->setUniformValue( "u_x", x );
program->setUniformValue( "u_y", y );
program->setUniformValue( "u_z", z );
program->setUniformValue( "u_dx", dx / 2 );
program->setUniformValue( "u_dy", dy / 2 );
program->setUniformValue( "u_dz", dz / 2 );
glEnable(GL_CULL_FACE);
glCullFace( GL_BACK );
glFrontFace( GL_CCW );
// Draw cube geometry using indices from VBO 0
glDrawElements( GL_QUADS, 24, GL_UNSIGNED_SHORT, 0 );
glDisable(GL_CULL_FACE);
program->setUniformValue( "u_color", color.redF(), color.greenF(), color.blueF(), color.alphaF() );
program->setUniformValue( "u_alpha", 1.0f );
program->setUniformValue( "u_renderMode", renderMode );
program->setUniformValue( "u_canvasSize", width, height );
program->setUniformValue( "u_lighting", false );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 4 ] );
glDrawElements( GL_LINES, 24, GL_UNSIGNED_SHORT, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
}
void ShapeRenderer::drawSphere( QMatrix4x4 p_matrix, QMatrix4x4 mv_matrix,
float x, float y, float z, float dx, float dy, float dz,
QColor color, int pickID, int width, int height, int renderMode )
{
float alpha = color.alphaF();
if ( renderMode == 1 ) // we are drawing opaque objects
{
if ( alpha < 1.0 )
{
// obviously not opaque
return;
}
}
else // we are drawing tranparent objects
{
if ( !(alpha < 1.0 ) || alpha == 0.0 )
{
// not transparent
return;
}
}
QGLShaderProgram* program = GLFunctions::getShader( "shape" );
program->bind();
// Set modelview-projection matrix
program->setUniformValue( "mvp_matrix", p_matrix * mv_matrix );
program->setUniformValue( "mv_matrixInvert", mv_matrix.inverted() );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, vboIds[ 2 ] );
glBindBuffer( GL_ARRAY_BUFFER, vboIds[ 3 ] );
// Offset for position
intptr_t offset = 0;
// Tell OpenGL programmable pipeline how to locate vertex position data
int vertexLocation = program->attributeLocation( "a_position" );
program->enableAttributeArray( vertexLocation );
glVertexAttribPointer( vertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(float)*3, (const void *) offset );
program->setUniformValue( "u_x", x );
program->setUniformValue( "u_y", y );
program->setUniformValue( "u_z", z );
program->setUniformValue( "u_dx", dx / 2 );
program->setUniformValue( "u_dy", dy / 2 );
program->setUniformValue( "u_dz", dz / 2 );
float pAlpha = 1.0;
float blue = (float)(( pickID ) & 0xFF) / 255.f;
float green = (float)(( pickID >> 8 ) & 0xFF) / 255.f;
float red = (float)(( pickID >> 16 ) & 0xFF) / 255.f;
//qDebug() << " input" << red << green << blue << alpha ;
program->setUniformValue( "u_pickColor", red, green , blue, pAlpha );
program->setUniformValue( "u_color", color.redF(), color.greenF(), color.blueF(), color.alphaF() );
program->setUniformValue( "u_alpha", (float)color.alphaF() );
program->setUniformValue( "u_renderMode", renderMode );
program->setUniformValue( "u_canvasSize", width, height );
program->setUniformValue( "u_lighting", true );
program->setUniformValue( "u_lighting", Models::getGlobal( Fn::Property::G_LIGHT_SWITCH ).toBool() );
program->setUniformValue( "u_lightAmbient", Models::getGlobal( Fn::Property::G_LIGHT_AMBIENT ).toFloat() );
program->setUniformValue( "u_lightDiffuse", Models::getGlobal( Fn::Property::G_LIGHT_DIFFUSE ).toFloat() );
program->setUniformValue( "u_materialAmbient", 1.0f );
program->setUniformValue( "u_materialDiffuse", 1.0f );
program->setUniformValue( "u_materialSpecular", 1.0f );
program->setUniformValue( "u_materialShininess", 1.0f );
program->setUniformValue( "D0", 9 );
program->setUniformValue( "D1", 10 );
program->setUniformValue( "D2", 11 );
program->setUniformValue( "P0", 12 );
glEnable(GL_CULL_FACE);
glCullFace( GL_BACK );
glFrontFace( GL_CCW );
glDrawElements( GL_TRIANGLES, tess::n_faces( 3 ) * 3, GL_UNSIGNED_INT, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glDisable(GL_CULL_FACE);
}
<|endoftext|> |
<commit_before>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief %Object commands.
@ingroup cmd_object
*/
#pragma once
#include <Hord/config.hpp>
#include <Hord/String.hpp>
#include <Hord/Data/Defs.hpp>
#include <Hord/Data/ValueRef.hpp>
#include <Hord/Data/Table.hpp>
#include <Hord/Object/Defs.hpp>
#include <Hord/Cmd/Defs.hpp>
#include <Hord/Cmd/Unit.hpp>
namespace Hord {
namespace Cmd {
namespace Object {
// Forward declarations
class SetSlug;
class SetParent;
class SetMetaField;
class RenameMetaField;
class RemoveMetaField;
/**
@addtogroup cmd_object
@{
*/
/**
Base object command properties.
*/
struct Base {
friend class SetSlug;
friend class SetParent;
friend class SetMetaField;
friend class RenameMetaField;
friend class RemoveMetaField;
protected:
Hord::Object::ID m_id;
public:
/** @name Properties */ /// @{
/**
Get object ID.
*/
Hord::Object::ID
get_object_id() const noexcept {
return m_id;
}
/// @}
};
/**
Set slug command.
*/
class SetSlug final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<SetSlug>
{
HORD_CMD_IMPL_BOILERPLATE(
SetSlug,
"Cmd::Object::SetSlug"
);
public:
/** @name Operations */ /// @{
/**
Set slug.
@param object Object to modify.
@param new_slug New slug.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
String new_slug
) noexcept;
/// @}
};
/**
Set parent command.
*/
class SetParent final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<SetParent>
{
HORD_CMD_IMPL_BOILERPLATE(
SetParent,
"Cmd::Object::SetParent"
);
public:
/** @name Operations */ /// @{
/**
Set parent.
@param object Object to modify.
@param new_parent New parent.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
Hord::Object::ID const new_parent
) noexcept;
/// @}
};
/**
Set MetaField value command.
*/
class SetMetaField final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<SetMetaField>
{
HORD_CMD_IMPL_BOILERPLATE(
SetMetaField,
"Cmd::Object::SetMetaField"
);
private:
bool m_created{false};
public:
/** @name Properties */ /// @{
/**
Get whether a new field was created.
*/
bool created() const noexcept {
return m_created;
}
/// @}
/** @name Operations */ /// @{
/**
Set field value by index.
@param object Object to modify.
@param index Index of field.
@param new_value New value for field.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
unsigned const index,
Data::ValueRef const& new_value
) noexcept;
/**
Set field value by name.
@param object Object to modify.
@param name Name of field.
@param new_value New value for field.
@param create Whether to create the field if it does not exist.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
String const& name,
Data::ValueRef const& new_value,
bool const create = true
) noexcept;
/// @}
};
/**
Rename MetaField command.
*/
class RenameMetaField final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<RenameMetaField>
{
HORD_CMD_IMPL_BOILERPLATE(
RenameMetaField,
"Cmd::Object::RenameMetaField"
);
private:
Cmd::Result
set_name(
Hord::Object::Unit& object,
Hord::Data::Table::Iterator& it,
String const& new_name
);
public:
/** @name Operations */ /// @{
/**
Rename field by index.
@param object Object to modify.
@param index Index of field.
@param new_name New name.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
unsigned const index,
String const& new_name
) noexcept;
/**
Rename field by name.
@param object Object to modify.
@param old_name Name of field.
@param new_name New name.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
String const& old_name,
String const& new_name
) noexcept;
/// @}
};
/**
Rename MetaField command.
*/
class RemoveMetaField final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<RemoveMetaField>
{
HORD_CMD_IMPL_BOILERPLATE(
RemoveMetaField,
"Cmd::Object::RemoveMetaField"
);
public:
/** @name Operations */ /// @{
/**
Remove field by index.
@param object Object to modify.
@param index Index of field.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
unsigned const index
) noexcept;
/**
Remove field by name.
@param object Object to modify.
@param name Name of field.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
String const& name
) noexcept;
/// @}
};
/** @} */ // end of doc-group cmd_object
} // namespace Object
/** @cond INTERNAL */
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::SetSlug);
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::SetParent);
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::SetMetaField);
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::RenameMetaField);
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::RemoveMetaField);
/** @endcond */ // INTERNAL
} // namespace Cmd
} // namespace Hord
<commit_msg>Cmd::Object::Base: explicitly initialize m_id to ID_NULL.<commit_after>/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file
@brief %Object commands.
@ingroup cmd_object
*/
#pragma once
#include <Hord/config.hpp>
#include <Hord/String.hpp>
#include <Hord/Data/Defs.hpp>
#include <Hord/Data/ValueRef.hpp>
#include <Hord/Data/Table.hpp>
#include <Hord/Object/Defs.hpp>
#include <Hord/Cmd/Defs.hpp>
#include <Hord/Cmd/Unit.hpp>
namespace Hord {
namespace Cmd {
namespace Object {
// Forward declarations
struct Base;
class SetSlug;
class SetParent;
class SetMetaField;
class RenameMetaField;
class RemoveMetaField;
/**
@addtogroup cmd_object
@{
*/
/**
Base object command properties.
*/
struct Base {
friend class SetSlug;
friend class SetParent;
friend class SetMetaField;
friend class RenameMetaField;
friend class RemoveMetaField;
protected:
Hord::Object::ID m_id{Hord::Object::ID_NULL};
public:
/** @name Properties */ /// @{
/**
Get object ID.
*/
Hord::Object::ID
get_object_id() const noexcept {
return m_id;
}
/// @}
};
/**
Set slug command.
*/
class SetSlug final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<SetSlug>
{
HORD_CMD_IMPL_BOILERPLATE(
SetSlug,
"Cmd::Object::SetSlug"
);
public:
/** @name Operations */ /// @{
/**
Set slug.
@param object Object to modify.
@param new_slug New slug.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
String new_slug
) noexcept;
/// @}
};
/**
Set parent command.
*/
class SetParent final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<SetParent>
{
HORD_CMD_IMPL_BOILERPLATE(
SetParent,
"Cmd::Object::SetParent"
);
public:
/** @name Operations */ /// @{
/**
Set parent.
@param object Object to modify.
@param new_parent New parent.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
Hord::Object::ID const new_parent
) noexcept;
/// @}
};
/**
Set MetaField value command.
*/
class SetMetaField final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<SetMetaField>
{
HORD_CMD_IMPL_BOILERPLATE(
SetMetaField,
"Cmd::Object::SetMetaField"
);
private:
bool m_created{false};
public:
/** @name Properties */ /// @{
/**
Get whether a new field was created.
*/
bool created() const noexcept {
return m_created;
}
/// @}
/** @name Operations */ /// @{
/**
Set field value by index.
@param object Object to modify.
@param index Index of field.
@param new_value New value for field.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
unsigned const index,
Data::ValueRef const& new_value
) noexcept;
/**
Set field value by name.
@param object Object to modify.
@param name Name of field.
@param new_value New value for field.
@param create Whether to create the field if it does not exist.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
String const& name,
Data::ValueRef const& new_value,
bool const create = true
) noexcept;
/// @}
};
/**
Rename MetaField command.
*/
class RenameMetaField final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<RenameMetaField>
{
HORD_CMD_IMPL_BOILERPLATE(
RenameMetaField,
"Cmd::Object::RenameMetaField"
);
private:
Cmd::Result
set_name(
Hord::Object::Unit& object,
Hord::Data::Table::Iterator& it,
String const& new_name
);
public:
/** @name Operations */ /// @{
/**
Rename field by index.
@param object Object to modify.
@param index Index of field.
@param new_name New name.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
unsigned const index,
String const& new_name
) noexcept;
/**
Rename field by name.
@param object Object to modify.
@param old_name Name of field.
@param new_name New name.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
String const& old_name,
String const& new_name
) noexcept;
/// @}
};
/**
Rename MetaField command.
*/
class RemoveMetaField final
: public Hord::Cmd::Object::Base
, public Cmd::Unit<RemoveMetaField>
{
HORD_CMD_IMPL_BOILERPLATE(
RemoveMetaField,
"Cmd::Object::RemoveMetaField"
);
public:
/** @name Operations */ /// @{
/**
Remove field by index.
@param object Object to modify.
@param index Index of field.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
unsigned const index
) noexcept;
/**
Remove field by name.
@param object Object to modify.
@param name Name of field.
*/
exec_result_type
operator()(
Hord::Object::Unit& object,
String const& name
) noexcept;
/// @}
};
/** @} */ // end of doc-group cmd_object
} // namespace Object
/** @cond INTERNAL */
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::SetSlug);
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::SetParent);
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::SetMetaField);
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::RenameMetaField);
HORD_CMD_IMPL_ENSURE_TRAITS(Cmd::Object::RemoveMetaField);
/** @endcond */ // INTERNAL
} // namespace Cmd
} // namespace Hord
<|endoftext|> |
<commit_before>/*
* This file is part of Poedit (http://www.poedit.net)
*
* Copyright (C) 1999-2005 Vaclav Slavik
*
* 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 <wx/filename.h>
#include <wx/log.h>
#include <wx/panel.h>
#include <wx/stattext.h>
#include <wx/choice.h>
#include <wx/config.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/listctrl.h>
#include <wx/fontenum.h>
#include <wx/stc/stc.h>
#include "fileviewer.h"
#include "utility.h"
FileViewer::FileViewer(wxWindow *parent,
const wxString& basePath,
const wxArrayString& references,
size_t startAt)
: wxFrame(parent, -1, _("Source file")),
m_references(references)
{
m_basePath = basePath;
SetName(_T("fileviewer"));
wxPanel *panel = new wxPanel(this, -1);
wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
panel->SetSizer(sizer);
wxSizer *barsizer = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(barsizer, wxSizerFlags().Expand().Border());
barsizer->Add(new wxStaticText(panel, wxID_ANY,
_("Source file occurrence:")),
wxSizerFlags().Center().Border(wxRIGHT));
wxChoice *choice = new wxChoice(panel, wxID_ANY);
barsizer->Add(choice, wxSizerFlags(1).Center());
for (size_t i = 0; i < references.Count(); i++)
choice->Append(references[i]);
choice->SetSelection(startAt);
m_text = new wxStyledTextCtrl(panel, wxID_ANY,
wxDefaultPosition, wxDefaultSize,
wxBORDER_THEME);
SetupTextCtrl();
sizer->Add(m_text, 1, wxEXPAND);
RestoreWindowState(this, wxSize(600, 400));
wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
topsizer->Add(panel, wxSizerFlags(1).Expand());
SetSizer(topsizer);
Layout();
ShowReference(m_references[startAt]);
}
FileViewer::~FileViewer()
{
SaveWindowState(this);
}
void FileViewer::SetupTextCtrl()
{
wxStyledTextCtrl& t = *m_text;
wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
#ifdef __WXGTK__
font.SetFaceName(_T("monospace"));
#else
static const wxChar *s_monospaced_fonts[] = {
#ifdef __WXMSW__
_T("Consolas"),
_T("Lucida Console"),
#endif
#ifdef __WXOSX__
_T("Menlo"),
_T("Monaco"),
#endif
NULL
};
for ( const wxChar **f = s_monospaced_fonts; *f; ++f )
{
if ( wxFontEnumerator::IsValidFacename(*f) )
{
font.SetFaceName(*f);
break;
}
}
#endif
// style used:
wxString fontspec = wxString::Format(_T("face:%s,size:%d"),
font.GetFaceName().c_str(),
font.GetPointSize());
const wxString STRING = fontspec + _T(",bold,fore:#882d21");
const wxString COMMENT = fontspec + _T(",fore:#487e18");
const wxString KEYWORD = fontspec + _T(",fore:#2f00f9");
const wxString LINENUMBERS = fontspec + _T(",fore:#5d8bab");
// current line marker
t.MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, wxColour(255,255,0));
// set fonts
t.StyleSetSpec(wxSTC_STYLE_DEFAULT, fontspec);
t.StyleSetSpec(wxSTC_STYLE_LINENUMBER, LINENUMBERS);
// line numbers margin size:
t.SetMarginType(0, wxSTC_MARGIN_NUMBER);
t.SetMarginWidth(0,
t.TextWidth(wxSTC_STYLE_LINENUMBER, _T("9999 ")));
t.SetMarginWidth(1, 0);
t.SetMarginWidth(2, 3);
// set syntax highlighting styling
t.StyleSetSpec(wxSTC_C_STRING, STRING);
t.StyleSetSpec(wxSTC_C_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_C_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_P_STRING, STRING);
t.StyleSetSpec(wxSTC_P_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_P_COMMENTBLOCK, COMMENT);
t.StyleSetSpec(wxSTC_LUA_STRING, STRING);
t.StyleSetSpec(wxSTC_LUA_LITERALSTRING, STRING);
t.StyleSetSpec(wxSTC_LUA_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_LUA_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_HPHP_HSTRING, STRING);
t.StyleSetSpec(wxSTC_HPHP_SIMPLESTRING, STRING);
t.StyleSetSpec(wxSTC_HPHP_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_HPHP_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_TCL_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_TCL_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_TCL_BLOCK_COMMENT, COMMENT);
#if wxCHECK_VERSION(2,9,0)
t.StyleSetSpec(wxSTC_PAS_STRING, STRING);
t.StyleSetSpec(wxSTC_PAS_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_PAS_COMMENT2, COMMENT);
t.StyleSetSpec(wxSTC_PAS_COMMENTLINE, COMMENT);
#endif
}
int FileViewer::GetLexer(const wxString& ext)
{
struct LexerInfo
{
const char *ext;
int lexer;
};
static const LexerInfo s_lexer[] = {
{ "c", wxSTC_LEX_CPP },
{ "cpp", wxSTC_LEX_CPP },
{ "cc", wxSTC_LEX_CPP },
{ "cxx", wxSTC_LEX_CPP },
{ "h", wxSTC_LEX_CPP },
{ "hxx", wxSTC_LEX_CPP },
{ "hpp", wxSTC_LEX_CPP },
{ "py", wxSTC_LEX_PYTHON },
{ "htm", wxSTC_LEX_HTML },
{ "html", wxSTC_LEX_HTML },
{ "php", wxSTC_LEX_PHPSCRIPT },
{ "xml", wxSTC_LEX_XML },
{ "pas", wxSTC_LEX_PASCAL },
{ NULL, -1 }
};
wxString e = ext.Lower();
for ( const LexerInfo *i = s_lexer; i->ext; ++i )
{
if ( e == wxString::FromAscii(i->ext) )
return i->lexer;
}
return wxSTC_LEX_NULL;
}
void FileViewer::ShowReference(const wxString& ref)
{
wxPathFormat pathfmt = ref.Contains(_T('\\')) ? wxPATH_WIN : wxPATH_UNIX;
wxFileName filename(ref.BeforeLast(_T(':')), pathfmt);
filename.MakeAbsolute(m_basePath);
if ( !filename.IsFileReadable() )
{
wxLogError(_("Error opening file %s!"), filename.GetFullPath().c_str());
return;
}
m_current = ref;
// support GNOME's xml2po's extension to references in the form of
// filename:line(xml_node):
wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('('));
long linenum;
if (!linenumStr.ToLong(&linenum))
linenum = 0;
m_text->SetReadOnly(false);
m_text->LoadFile(filename.GetFullPath());
m_text->SetLexer(GetLexer(filename.GetExt()));
m_text->SetReadOnly(true);
m_text->MarkerDeleteAll(1);
m_text->MarkerAdd(linenum - 1, 1);
// Center the highlighted line:
int lineHeight = m_text->TextHeight(linenum);
int linesInWnd = m_text->GetSize().y / lineHeight;
m_text->ScrollToLine(wxMax(0, linenum - linesInWnd/2));
}
BEGIN_EVENT_TABLE(FileViewer, wxFrame)
EVT_CHOICE(wxID_ANY, FileViewer::OnChoice)
END_EVENT_TABLE()
void FileViewer::OnChoice(wxCommandEvent &event)
{
ShowReference(m_references[event.GetSelection()]);
}
<commit_msg>Fix missing text in sources viewer.<commit_after>/*
* This file is part of Poedit (http://www.poedit.net)
*
* Copyright (C) 1999-2005 Vaclav Slavik
*
* 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 <wx/filename.h>
#include <wx/log.h>
#include <wx/panel.h>
#include <wx/stattext.h>
#include <wx/choice.h>
#include <wx/config.h>
#include <wx/sizer.h>
#include <wx/settings.h>
#include <wx/listctrl.h>
#include <wx/fontenum.h>
#include <wx/stc/stc.h>
#include "fileviewer.h"
#include "utility.h"
FileViewer::FileViewer(wxWindow *parent,
const wxString& basePath,
const wxArrayString& references,
size_t startAt)
: wxFrame(parent, -1, _("Source file")),
m_references(references)
{
m_basePath = basePath;
SetName(_T("fileviewer"));
wxPanel *panel = new wxPanel(this, -1);
wxSizer *sizer = new wxBoxSizer(wxVERTICAL);
panel->SetSizer(sizer);
wxSizer *barsizer = new wxBoxSizer(wxHORIZONTAL);
sizer->Add(barsizer, wxSizerFlags().Expand().Border());
barsizer->Add(new wxStaticText(panel, wxID_ANY,
_("Source file occurrence:")),
wxSizerFlags().Center().Border(wxRIGHT));
wxChoice *choice = new wxChoice(panel, wxID_ANY);
barsizer->Add(choice, wxSizerFlags(1).Center());
for (size_t i = 0; i < references.Count(); i++)
choice->Append(references[i]);
choice->SetSelection(startAt);
m_text = new wxStyledTextCtrl(panel, wxID_ANY,
wxDefaultPosition, wxDefaultSize,
wxBORDER_THEME);
SetupTextCtrl();
sizer->Add(m_text, 1, wxEXPAND);
RestoreWindowState(this, wxSize(600, 400));
wxSizer *topsizer = new wxBoxSizer(wxVERTICAL);
topsizer->Add(panel, wxSizerFlags(1).Expand());
SetSizer(topsizer);
Layout();
ShowReference(m_references[startAt]);
}
FileViewer::~FileViewer()
{
SaveWindowState(this);
}
void FileViewer::SetupTextCtrl()
{
wxStyledTextCtrl& t = *m_text;
wxFont font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
#ifdef __WXGTK__
font.SetFaceName(_T("monospace"));
#else
static const wxChar *s_monospaced_fonts[] = {
#ifdef __WXMSW__
_T("Consolas"),
_T("Lucida Console"),
#endif
#ifdef __WXOSX__
_T("Menlo"),
_T("Monaco"),
#endif
NULL
};
for ( const wxChar **f = s_monospaced_fonts; *f; ++f )
{
if ( wxFontEnumerator::IsValidFacename(*f) )
{
font.SetFaceName(*f);
break;
}
}
#endif
// style used:
wxString fontspec = wxString::Format(_T("face:%s,size:%d"),
font.GetFaceName().c_str(),
font.GetPointSize());
const wxString DEFAULT = fontspec + _T(",fore:black,back:white");
const wxString STRING = fontspec + _T(",bold,fore:#882d21");
const wxString COMMENT = fontspec + _T(",fore:#487e18");
const wxString KEYWORD = fontspec + _T(",fore:#2f00f9");
const wxString LINENUMBERS = fontspec + _T(",fore:#5d8bab");
// current line marker
t.MarkerDefine(1, wxSTC_MARK_BACKGROUND, wxNullColour, wxColour(255,255,0));
// set fonts
t.StyleSetSpec(wxSTC_STYLE_DEFAULT, DEFAULT);
t.StyleSetSpec(wxSTC_STYLE_LINENUMBER, LINENUMBERS);
// line numbers margin size:
t.SetMarginType(0, wxSTC_MARGIN_NUMBER);
t.SetMarginWidth(0,
t.TextWidth(wxSTC_STYLE_LINENUMBER, _T("9999 ")));
t.SetMarginWidth(1, 0);
t.SetMarginWidth(2, 3);
// set syntax highlighting styling
t.StyleSetSpec(wxSTC_C_STRING, STRING);
t.StyleSetSpec(wxSTC_C_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_C_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_P_STRING, STRING);
t.StyleSetSpec(wxSTC_P_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_P_COMMENTBLOCK, COMMENT);
t.StyleSetSpec(wxSTC_LUA_STRING, STRING);
t.StyleSetSpec(wxSTC_LUA_LITERALSTRING, STRING);
t.StyleSetSpec(wxSTC_LUA_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_LUA_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_HPHP_HSTRING, STRING);
t.StyleSetSpec(wxSTC_HPHP_SIMPLESTRING, STRING);
t.StyleSetSpec(wxSTC_HPHP_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_HPHP_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_TCL_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_TCL_COMMENTLINE, COMMENT);
t.StyleSetSpec(wxSTC_TCL_BLOCK_COMMENT, COMMENT);
#if wxCHECK_VERSION(2,9,0)
t.StyleSetSpec(wxSTC_PAS_STRING, STRING);
t.StyleSetSpec(wxSTC_PAS_COMMENT, COMMENT);
t.StyleSetSpec(wxSTC_PAS_COMMENT2, COMMENT);
t.StyleSetSpec(wxSTC_PAS_COMMENTLINE, COMMENT);
#endif
}
int FileViewer::GetLexer(const wxString& ext)
{
struct LexerInfo
{
const char *ext;
int lexer;
};
static const LexerInfo s_lexer[] = {
{ "c", wxSTC_LEX_CPP },
{ "cpp", wxSTC_LEX_CPP },
{ "cc", wxSTC_LEX_CPP },
{ "cxx", wxSTC_LEX_CPP },
{ "h", wxSTC_LEX_CPP },
{ "hxx", wxSTC_LEX_CPP },
{ "hpp", wxSTC_LEX_CPP },
{ "py", wxSTC_LEX_PYTHON },
{ "htm", wxSTC_LEX_HTML },
{ "html", wxSTC_LEX_HTML },
{ "php", wxSTC_LEX_PHPSCRIPT },
{ "xml", wxSTC_LEX_XML },
{ "pas", wxSTC_LEX_PASCAL },
{ NULL, -1 }
};
wxString e = ext.Lower();
for ( const LexerInfo *i = s_lexer; i->ext; ++i )
{
if ( e == wxString::FromAscii(i->ext) )
return i->lexer;
}
return wxSTC_LEX_NULL;
}
void FileViewer::ShowReference(const wxString& ref)
{
wxPathFormat pathfmt = ref.Contains(_T('\\')) ? wxPATH_WIN : wxPATH_UNIX;
wxFileName filename(ref.BeforeLast(_T(':')), pathfmt);
filename.MakeAbsolute(m_basePath);
if ( !filename.IsFileReadable() )
{
wxLogError(_("Error opening file %s!"), filename.GetFullPath().c_str());
return;
}
m_current = ref;
// support GNOME's xml2po's extension to references in the form of
// filename:line(xml_node):
wxString linenumStr = ref.AfterLast(_T(':')).BeforeFirst(_T('('));
long linenum;
if (!linenumStr.ToLong(&linenum))
linenum = 0;
m_text->SetReadOnly(false);
m_text->LoadFile(filename.GetFullPath());
m_text->SetReadOnly(true);
m_text->MarkerDeleteAll(1);
m_text->MarkerAdd(linenum - 1, 1);
// Center the highlighted line:
int lineHeight = m_text->TextHeight(linenum);
int linesInWnd = m_text->GetSize().y / lineHeight;
m_text->ScrollToLine(wxMax(0, linenum - linesInWnd/2));
}
BEGIN_EVENT_TABLE(FileViewer, wxFrame)
EVT_CHOICE(wxID_ANY, FileViewer::OnChoice)
END_EVENT_TABLE()
void FileViewer::OnChoice(wxCommandEvent &event)
{
ShowReference(m_references[event.GetSelection()]);
}
<|endoftext|> |
<commit_before>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
#include <common/version.h>
#include <test/TestBase.h>
class VersionTest : public TestBase {};
TEST_F(VersionTest, Constructor) {
ASSERT_TRUE(EFU_VERSION_NUM(0,0,1) > EFU_VERSION_NUM(0,0,0));
ASSERT_TRUE(EFU_VERSION_NUM(0,1,0) > EFU_VERSION_NUM(0,0,1));
ASSERT_TRUE(EFU_VERSION_NUM(1,0,0) > EFU_VERSION_NUM(0,1,0));
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<commit_msg>include corrected after file rename<commit_after>/** Copyright (C) 2016, 2017 European Spallation Source ERIC */
#include <common/Version.h>
#include <test/TestBase.h>
class VersionTest : public TestBase {};
TEST_F(VersionTest, Constructor) {
ASSERT_TRUE(EFU_VERSION_NUM(0,0,1) > EFU_VERSION_NUM(0,0,0));
ASSERT_TRUE(EFU_VERSION_NUM(0,1,0) > EFU_VERSION_NUM(0,0,1));
ASSERT_TRUE(EFU_VERSION_NUM(1,0,0) > EFU_VERSION_NUM(0,1,0));
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
<|endoftext|> |
<commit_before>/*
This file is part of KOrganizer.
Copyright (c) 1998 Barry D Benowitz
Copyright (c) 2001 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <unistd.h>
#include <stdio.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kurl.h>
#include <kapplication.h>
#include <dcopclient.h>
#include <kprocess.h>
#include <libkcal/event.h>
#include <libkcal/todo.h>
#include "version.h"
#include "koprefs.h"
#include "komailclient.h"
KOMailClient::KOMailClient()
{
}
KOMailClient::~KOMailClient()
{
}
bool KOMailClient::mailAttendees(IncidenceBase *incidence,const QString &attachment)
{
QPtrList<Attendee> attendees = incidence->attendees();
if (attendees.count() == 0) return false;
QString to;
for(uint i=0; i<attendees.count();++i) {
to += attendees.at(i)->email();
if (i != attendees.count()-1) to += ", ";
}
QString from = KOPrefs::instance()->email();
QString subject;
if(incidence->type()!="FreeBusy") {
Incidence *inc = static_cast<Incidence *>(incidence);
subject = inc->summary();
} else {
subject = "Free Busy Object";
}
QString body = createBody(incidence);
bool bcc = KOPrefs::instance()->mBcc;
return send(from,to,subject,body,bcc,attachment);
}
bool KOMailClient::mailOrganizer(IncidenceBase *incidence,const QString &attachment)
{
QString to = incidence->organizer();
QString from = KOPrefs::instance()->email();
QString subject;
if(incidence->type()!="FreeBusy") {
Incidence *inc = static_cast<Incidence *>(incidence);
subject = inc->summary();
} else {
subject = "Free Busy Message";
}
QString body = createBody(incidence);
bool bcc = KOPrefs::instance()->mBcc;
return send(from,to,subject,body,bcc,attachment);
}
bool KOMailClient::mailTo(IncidenceBase *incidence,const QString &recipients,
const QString &attachment)
{
QString from = KOPrefs::instance()->email();
QString subject;
if(incidence->type()!="FreeBusy") {
Incidence *inc = static_cast<Incidence *>(incidence);
subject = inc->summary();
} else {
subject = "Free Busy Message";
}
QString body = createBody(incidence);
bool bcc = KOPrefs::instance()->mBcc;
kdDebug () << "KOMailClient::mailTo " << recipients << endl;
return send(from,recipients,subject,body,bcc,attachment);
}
bool KOMailClient::send(const QString &from,const QString &to,
const QString &subject,const QString &body,bool bcc,
const QString &attachment)
{
kdDebug() << "KOMailClient::sendMail():\nFrom: " << from << "\nTo: " << to
<< "\nSubject: " << subject << "\nBody: \n" << body
<< "\nAttachment:\n" << attachment << endl;
if (KOPrefs::instance()->mMailClient == KOPrefs::MailClientSendmail) {
bool needHeaders = true;
QString command = KStandardDirs::findExe(QString::fromLatin1("sendmail"),
QString::fromLatin1("/sbin:/usr/sbin:/usr/lib"));
if (!command.isNull()) command += QString::fromLatin1(" -oi -t");
else {
command = KStandardDirs::findExe(QString::fromLatin1("mail"));
if (command.isNull()) return false; // give up
command.append(QString::fromLatin1(" -s "));
command.append(KProcess::quote(subject));
if (bcc) {
command.append(QString::fromLatin1(" -b "));
command.append(KProcess::quote(from));
}
command.append(" ");
command.append(KProcess::quote(to));
needHeaders = false;
}
FILE * fd = popen(command.local8Bit(),"w");
if (!fd)
{
kdError() << "Unable to open a pipe to " << command << endl;
return false;
}
QString textComplete;
if (needHeaders)
{
textComplete += QString::fromLatin1("From: ") + from + '\n';
textComplete += QString::fromLatin1("To: ") + to + '\n';
if (bcc) textComplete += QString::fromLatin1("Bcc: ") + from + '\n';
textComplete += QString::fromLatin1("Subject: ") + subject + '\n';
textComplete += QString::fromLatin1("X-Mailer: KOrganizer") + korgVersion + '\n';
}
textComplete += '\n'; // end of headers
textComplete += body;
textComplete += '\n';
textComplete += attachment;
fwrite(textComplete.local8Bit(),textComplete.length(),1,fd);
pclose(fd);
} else {
if (!kapp->dcopClient()->isApplicationRegistered("kmail")) {
if (KApplication::startServiceByDesktopName("kmail")) {
KMessageBox::error(0,i18n("No running instance of KMail found."));
return false;
}
}
if (attachment.isEmpty()) {
if (!kMailOpenComposer(to,"",from,subject,body,0,KURL())) return false;
} else {
QString meth;
int idx = attachment.find("METHOD");
if (idx>=0) {
idx = attachment.find(':',idx)+1;
meth = attachment.mid(idx,attachment.find('\n',idx)-idx);
meth = meth.lower();
} else {
meth = "publish";
}
if (!kMailOpenComposer(to,"",from,subject,body,0,"cal.ics","7bit",
attachment.utf8(),"text","calendar","method",meth,
"attachment")) return false;
}
}
return true;
}
int KOMailClient::kMailOpenComposer(const QString& arg0,const QString& arg1,
const QString& arg2,const QString& arg3,const QString& arg4,int arg5,
const KURL& arg6)
{
int result = 0;
QByteArray data, replyData;
QCString replyType;
QDataStream arg( data, IO_WriteOnly );
arg << arg0;
arg << arg1;
arg << arg2;
arg << arg3;
arg << arg4;
arg << arg5;
arg << arg6;
if (kapp->dcopClient()->call("kmail","KMailIface","openComposer(QString,QString,QString,QString,QString,int,KURL)", data, replyType, replyData ) ) {
if ( replyType == "int" ) {
QDataStream _reply_stream( replyData, IO_ReadOnly );
_reply_stream >> result;
} else {
kdDebug() << "kMailOpenComposer() call failed." << endl;
}
} else {
kdDebug() << "kMailOpenComposer() call failed." << endl;
}
return result;
}
int KOMailClient::kMailOpenComposer( const QString& arg0, const QString& arg1,
const QString& arg2, const QString& arg3,
const QString& arg4, int arg5, const QString& arg6,
const QCString& arg7, const QCString& arg8,
const QCString& arg9, const QCString& arg10,
const QCString& arg11, const QString& arg12,
const QCString& arg13 )
{
int result = 0;
QByteArray data, replyData;
QCString replyType;
QDataStream arg( data, IO_WriteOnly );
arg << arg0;
arg << arg1;
arg << arg2;
arg << arg3;
arg << arg4;
arg << arg5;
arg << arg6;
arg << arg7;
arg << arg8;
arg << arg9;
arg << arg10;
arg << arg11;
arg << arg12;
arg << arg13;
if ( kapp->dcopClient()->call("kmail","KMailIface","openComposer(QString,QString,QString,QString,QString,int,QString,QCString,QCString,QCString,QCString,QCString,QString,QCString)", data, replyType, replyData ) ) {
if ( replyType == "int" ) {
QDataStream _reply_stream( replyData, IO_ReadOnly );
_reply_stream >> result;
} else {
kdDebug() << "kMailOpenComposer() call failed." << endl;
}
} else {
kdDebug() << "kMailOpenComposer() call failed." << endl;
}
return result;
}
QString KOMailClient::createBody(IncidenceBase *incidence)
{
QString CR = ("\n");
QString body;
// mailbody for Event
if (incidence->type()=="Event") {
Event *selectedEvent = static_cast<Event *>(incidence);
QString recurrence[]= {i18n("no recurrence", "None"),i18n("Daily"),i18n("Weekly"),i18n("Monthly Same Day"),
i18n("Monthly Same Position"),i18n("Yearly"),i18n("Yearly")};
if (selectedEvent->organizer() != "") {
body += i18n("Organizer: %1").arg(selectedEvent->organizer());
body += CR;
}
body += i18n("Summary: %1").arg(selectedEvent->summary());
if (!selectedEvent->location().isEmpty()) {
body += CR;
body += i18n("Location: %1").arg(selectedEvent->location());
}
if (!selectedEvent->doesFloat()) {
body += CR;
body += i18n("Start Date: %1").arg(selectedEvent->dtStartDateStr());
body += CR;
body += i18n("Start Time: %1").arg(selectedEvent->dtStartTimeStr());
body += CR;
if (selectedEvent->recurrence()->doesRecur()) {
body += i18n("Recurs: %1")
.arg(recurrence[selectedEvent->recurrence()->frequency()]);
body += CR;
if (selectedEvent->recurrence()->duration() > 0 ) {
body += i18n ("Repeats %1 times")
.arg(QString::number(selectedEvent->recurrence()->duration()));
body += CR;
} else {
if (selectedEvent->recurrence()->duration() != -1) {
body += i18n("End Date: %1")
.arg(selectedEvent->recurrence()->endDateStr());
body += CR;
} else {
body += i18n("Repeats forever");
body += CR;
}
}
}
body += i18n("End Time: %1").arg(selectedEvent->dtEndTimeStr());
body += CR;
QString details = selectedEvent->description();
if (!details.isEmpty()) {
body += i18n("Details:");
body += CR;
body += details;
}
}
}
// mailbody for Todo
if (incidence->type()=="Todo") {
Todo *selectedEvent = static_cast<Todo *>(incidence);
if (selectedEvent->organizer() != "") {
body += i18n("Organizer: %1").arg(selectedEvent->organizer());
body += CR;
}
body += i18n("Summary: %1").arg(selectedEvent->summary());
if (!selectedEvent->location().isEmpty()) {
body += CR;
body += i18n("Location: %1").arg(selectedEvent->location());
}
if (!selectedEvent->hasStartDate()) {
body += CR;
body += i18n("Start Date: %1").arg(selectedEvent->dtStartDateStr());
body += CR;
if (!selectedEvent->doesFloat()) {
body += i18n("Start Time: %1").arg(selectedEvent->dtStartTimeStr());
body += CR;
}
}
if (!selectedEvent->hasDueDate()) {
body += CR;
body += i18n("Due Date: %1").arg(selectedEvent->dtDueDateStr());
body += CR;
if (!selectedEvent->doesFloat()) {
body += i18n("Due Time: %1").arg(selectedEvent->dtDueTimeStr());
body += CR;
}
}
body += CR;
QString details = selectedEvent->description();
if (!details.isEmpty()) {
body += i18n("Details:");
body += CR;
body += details;
}
}
// mailbody for FreeBusy
if(incidence->type()=="FreeBusy") {
body = i18n("This is a Free Busy Object");
}
// mailbody for Journal
if(incidence->type()=="Journal") {
Incidence *inc = static_cast<Incidence *>(incidence);
body = inc->summary();
body += CR;
body += inc->description();
}
return body;
}
<commit_msg>Removed a comparison to ""<commit_after>/*
This file is part of KOrganizer.
Copyright (c) 1998 Barry D Benowitz
Copyright (c) 2001 Cornelius Schumacher <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
As a special exception, permission is given to link this program
with any edition of Qt, and distribute the resulting executable,
without including the source code for Qt in the source distribution.
*/
#include <unistd.h>
#include <stdio.h>
#include <klocale.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <kmessagebox.h>
#include <kurl.h>
#include <kapplication.h>
#include <dcopclient.h>
#include <kprocess.h>
#include <libkcal/event.h>
#include <libkcal/todo.h>
#include "version.h"
#include "koprefs.h"
#include "komailclient.h"
KOMailClient::KOMailClient()
{
}
KOMailClient::~KOMailClient()
{
}
bool KOMailClient::mailAttendees(IncidenceBase *incidence,const QString &attachment)
{
QPtrList<Attendee> attendees = incidence->attendees();
if (attendees.count() == 0) return false;
QString to;
for(uint i=0; i<attendees.count();++i) {
to += attendees.at(i)->email();
if (i != attendees.count()-1) to += ", ";
}
QString from = KOPrefs::instance()->email();
QString subject;
if(incidence->type()!="FreeBusy") {
Incidence *inc = static_cast<Incidence *>(incidence);
subject = inc->summary();
} else {
subject = "Free Busy Object";
}
QString body = createBody(incidence);
bool bcc = KOPrefs::instance()->mBcc;
return send(from,to,subject,body,bcc,attachment);
}
bool KOMailClient::mailOrganizer(IncidenceBase *incidence,const QString &attachment)
{
QString to = incidence->organizer();
QString from = KOPrefs::instance()->email();
QString subject;
if(incidence->type()!="FreeBusy") {
Incidence *inc = static_cast<Incidence *>(incidence);
subject = inc->summary();
} else {
subject = "Free Busy Message";
}
QString body = createBody(incidence);
bool bcc = KOPrefs::instance()->mBcc;
return send(from,to,subject,body,bcc,attachment);
}
bool KOMailClient::mailTo(IncidenceBase *incidence,const QString &recipients,
const QString &attachment)
{
QString from = KOPrefs::instance()->email();
QString subject;
if(incidence->type()!="FreeBusy") {
Incidence *inc = static_cast<Incidence *>(incidence);
subject = inc->summary();
} else {
subject = "Free Busy Message";
}
QString body = createBody(incidence);
bool bcc = KOPrefs::instance()->mBcc;
kdDebug () << "KOMailClient::mailTo " << recipients << endl;
return send(from,recipients,subject,body,bcc,attachment);
}
bool KOMailClient::send(const QString &from,const QString &to,
const QString &subject,const QString &body,bool bcc,
const QString &attachment)
{
kdDebug() << "KOMailClient::sendMail():\nFrom: " << from << "\nTo: " << to
<< "\nSubject: " << subject << "\nBody: \n" << body
<< "\nAttachment:\n" << attachment << endl;
if (KOPrefs::instance()->mMailClient == KOPrefs::MailClientSendmail) {
bool needHeaders = true;
QString command = KStandardDirs::findExe(QString::fromLatin1("sendmail"),
QString::fromLatin1("/sbin:/usr/sbin:/usr/lib"));
if (!command.isNull()) command += QString::fromLatin1(" -oi -t");
else {
command = KStandardDirs::findExe(QString::fromLatin1("mail"));
if (command.isNull()) return false; // give up
command.append(QString::fromLatin1(" -s "));
command.append(KProcess::quote(subject));
if (bcc) {
command.append(QString::fromLatin1(" -b "));
command.append(KProcess::quote(from));
}
command.append(" ");
command.append(KProcess::quote(to));
needHeaders = false;
}
FILE * fd = popen(command.local8Bit(),"w");
if (!fd)
{
kdError() << "Unable to open a pipe to " << command << endl;
return false;
}
QString textComplete;
if (needHeaders)
{
textComplete += QString::fromLatin1("From: ") + from + '\n';
textComplete += QString::fromLatin1("To: ") + to + '\n';
if (bcc) textComplete += QString::fromLatin1("Bcc: ") + from + '\n';
textComplete += QString::fromLatin1("Subject: ") + subject + '\n';
textComplete += QString::fromLatin1("X-Mailer: KOrganizer") + korgVersion + '\n';
}
textComplete += '\n'; // end of headers
textComplete += body;
textComplete += '\n';
textComplete += attachment;
fwrite(textComplete.local8Bit(),textComplete.length(),1,fd);
pclose(fd);
} else {
if (!kapp->dcopClient()->isApplicationRegistered("kmail")) {
if (KApplication::startServiceByDesktopName("kmail")) {
KMessageBox::error(0,i18n("No running instance of KMail found."));
return false;
}
}
if (attachment.isEmpty()) {
if (!kMailOpenComposer(to,"",from,subject,body,0,KURL())) return false;
} else {
QString meth;
int idx = attachment.find("METHOD");
if (idx>=0) {
idx = attachment.find(':',idx)+1;
meth = attachment.mid(idx,attachment.find('\n',idx)-idx);
meth = meth.lower();
} else {
meth = "publish";
}
if (!kMailOpenComposer(to,"",from,subject,body,0,"cal.ics","7bit",
attachment.utf8(),"text","calendar","method",meth,
"attachment")) return false;
}
}
return true;
}
int KOMailClient::kMailOpenComposer(const QString& arg0,const QString& arg1,
const QString& arg2,const QString& arg3,const QString& arg4,int arg5,
const KURL& arg6)
{
int result = 0;
QByteArray data, replyData;
QCString replyType;
QDataStream arg( data, IO_WriteOnly );
arg << arg0;
arg << arg1;
arg << arg2;
arg << arg3;
arg << arg4;
arg << arg5;
arg << arg6;
if (kapp->dcopClient()->call("kmail","KMailIface","openComposer(QString,QString,QString,QString,QString,int,KURL)", data, replyType, replyData ) ) {
if ( replyType == "int" ) {
QDataStream _reply_stream( replyData, IO_ReadOnly );
_reply_stream >> result;
} else {
kdDebug() << "kMailOpenComposer() call failed." << endl;
}
} else {
kdDebug() << "kMailOpenComposer() call failed." << endl;
}
return result;
}
int KOMailClient::kMailOpenComposer( const QString& arg0, const QString& arg1,
const QString& arg2, const QString& arg3,
const QString& arg4, int arg5, const QString& arg6,
const QCString& arg7, const QCString& arg8,
const QCString& arg9, const QCString& arg10,
const QCString& arg11, const QString& arg12,
const QCString& arg13 )
{
int result = 0;
QByteArray data, replyData;
QCString replyType;
QDataStream arg( data, IO_WriteOnly );
arg << arg0;
arg << arg1;
arg << arg2;
arg << arg3;
arg << arg4;
arg << arg5;
arg << arg6;
arg << arg7;
arg << arg8;
arg << arg9;
arg << arg10;
arg << arg11;
arg << arg12;
arg << arg13;
if ( kapp->dcopClient()->call("kmail","KMailIface","openComposer(QString,QString,QString,QString,QString,int,QString,QCString,QCString,QCString,QCString,QCString,QString,QCString)", data, replyType, replyData ) ) {
if ( replyType == "int" ) {
QDataStream _reply_stream( replyData, IO_ReadOnly );
_reply_stream >> result;
} else {
kdDebug() << "kMailOpenComposer() call failed." << endl;
}
} else {
kdDebug() << "kMailOpenComposer() call failed." << endl;
}
return result;
}
QString KOMailClient::createBody(IncidenceBase *incidence)
{
QString CR = ("\n");
QString body;
// mailbody for Event
if (incidence->type()=="Event") {
Event *selectedEvent = static_cast<Event *>(incidence);
QString recurrence[]= {i18n("no recurrence", "None"),i18n("Daily"),i18n("Weekly"),i18n("Monthly Same Day"),
i18n("Monthly Same Position"),i18n("Yearly"),i18n("Yearly")};
if (!selectedEvent->organizer().isEmpty()) {
body += i18n("Organizer: %1").arg(selectedEvent->organizer());
body += CR;
}
body += i18n("Summary: %1").arg(selectedEvent->summary());
if (!selectedEvent->location().isEmpty()) {
body += CR;
body += i18n("Location: %1").arg(selectedEvent->location());
}
if (!selectedEvent->doesFloat()) {
body += CR;
body += i18n("Start Date: %1").arg(selectedEvent->dtStartDateStr());
body += CR;
body += i18n("Start Time: %1").arg(selectedEvent->dtStartTimeStr());
body += CR;
if (selectedEvent->recurrence()->doesRecur()) {
body += i18n("Recurs: %1")
.arg(recurrence[selectedEvent->recurrence()->frequency()]);
body += CR;
if (selectedEvent->recurrence()->duration() > 0 ) {
body += i18n ("Repeats %1 times")
.arg(QString::number(selectedEvent->recurrence()->duration()));
body += CR;
} else {
if (selectedEvent->recurrence()->duration() != -1) {
body += i18n("End Date: %1")
.arg(selectedEvent->recurrence()->endDateStr());
body += CR;
} else {
body += i18n("Repeats forever");
body += CR;
}
}
}
body += i18n("End Time: %1").arg(selectedEvent->dtEndTimeStr());
body += CR;
QString details = selectedEvent->description();
if (!details.isEmpty()) {
body += i18n("Details:");
body += CR;
body += details;
}
}
}
// mailbody for Todo
if (incidence->type()=="Todo") {
Todo *selectedEvent = static_cast<Todo *>(incidence);
if (!selectedEvent->organizer().isEmpty()) {
body += i18n("Organizer: %1").arg(selectedEvent->organizer());
body += CR;
}
body += i18n("Summary: %1").arg(selectedEvent->summary());
if (!selectedEvent->location().isEmpty()) {
body += CR;
body += i18n("Location: %1").arg(selectedEvent->location());
}
if (!selectedEvent->hasStartDate()) {
body += CR;
body += i18n("Start Date: %1").arg(selectedEvent->dtStartDateStr());
body += CR;
if (!selectedEvent->doesFloat()) {
body += i18n("Start Time: %1").arg(selectedEvent->dtStartTimeStr());
body += CR;
}
}
if (!selectedEvent->hasDueDate()) {
body += CR;
body += i18n("Due Date: %1").arg(selectedEvent->dtDueDateStr());
body += CR;
if (!selectedEvent->doesFloat()) {
body += i18n("Due Time: %1").arg(selectedEvent->dtDueTimeStr());
body += CR;
}
}
body += CR;
QString details = selectedEvent->description();
if (!details.isEmpty()) {
body += i18n("Details:");
body += CR;
body += details;
}
}
// mailbody for FreeBusy
if(incidence->type()=="FreeBusy") {
body = i18n("This is a Free Busy Object");
}
// mailbody for Journal
if(incidence->type()=="Journal") {
Incidence *inc = static_cast<Incidence *>(incidence);
body = inc->summary();
body += CR;
body += inc->description();
}
return body;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.